file_path
stringlengths
7
180
content
stringlengths
0
811k
repo
stringclasses
11 values
examples/onnx/1l_relu/gen.py
from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.layer = nn.ReLU() def forward(self, x): return self.layer(x) circuit = MyModel() export(circuit, input_shape = [3])
https://github.com/zkonduit/ezkl
examples/onnx/1l_reshape/gen.py
import torch from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): x = x.reshape([-1, 6]) return x circuit = MyModel() export(circuit, input_shape=[1, 3, 2])
https://github.com/zkonduit/ezkl
examples/onnx/1l_sigmoid/gen.py
from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.layer = nn.Sigmoid() def forward(self, x): return self.layer(x) circuit = MyModel() export(circuit, input_shape = [3])
https://github.com/zkonduit/ezkl
examples/onnx/1l_slice/gen.py
import torch from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): return x[:,1:2] circuit = MyModel() export(circuit, input_shape=[3, 2])
https://github.com/zkonduit/ezkl
examples/onnx/1l_softmax/gen.py
import torch from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.layer = nn.Softmax(dim=1) def forward(self, x): return self.layer(x) circuit = MyModel() export(circuit, input_shape=[3])
https://github.com/zkonduit/ezkl
examples/onnx/1l_sqrt/gen.py
import torch from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): return torch.sqrt(x) circuit = MyModel() export(circuit, input_shape = [3])
https://github.com/zkonduit/ezkl
examples/onnx/1l_tiny_div/gen.py
from torch import nn import torch import json class Circuit(nn.Module): def __init__(self, inplace=False): super(Circuit, self).__init__() def forward(self, x): return x/ 10000 circuit = Circuit() x = torch.empty(1, 8).random_(0, 2) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/1l_topk/gen.py
from torch import nn import torch import json class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): topk_largest = torch.topk(x, 4) topk_smallest = torch.topk(x, 4, largest=False) print(topk_largest) print(topk_smallest) return topk_largest.values + topk_smallest.values circuit = MyModel() x = torch.randint(10, (1, 6)) y = circuit(x) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=14, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in y] ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/1l_upsample/gen.py
import io import numpy as np from torch import nn import torch.onnx import torch.nn as nn import torch.nn.init as init import json class Circuit(nn.Module): def __init__(self, inplace=False): super(Circuit, self).__init__() self.upsample = nn.Upsample(scale_factor=2, mode='nearest') def forward(self, x): y = self.upsample(x) return y def main(): torch_model = Circuit() # Input to the model shape = [3, 5, 5] x = 0.1*torch.rand(1,*shape, requires_grad=True) torch_out = torch_model(x) # Export the model torch.onnx.export(torch_model, # model being run (x), # model input (or a tuple for multiple inputs) "network.onnx", # where to save the model (can be a file or file-like object) export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names = ['input'], # the model's input names output_names = ['output'], # the model's output names dynamic_axes={'input' : {0 : 'batch_size'}, # variable length axes 'output' : {0 : 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes = [shape], input_data = [d], output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w')) if __name__ == "__main__": main()
https://github.com/zkonduit/ezkl
examples/onnx/1l_var/gen.py
from torch import nn from ezkl import export import torch class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): return [torch.var(x, unbiased=False, dim=[1,2])] circuit = MyModel() export(circuit, input_shape = [1,3,3])
https://github.com/zkonduit/ezkl
examples/onnx/1l_where/gen.py
from torch import nn import torch import json class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): return [torch.where(x >= 0.0, 3.0, 5.0)] circuit = MyModel() x = torch.randint(1, (1, 64)) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/2l_relu_fc/gen.py
from torch import nn import torch.nn.init as init from ezkl import export class Model(nn.Module): def __init__(self, inplace=False): super(Model, self).__init__() self.aff1 = nn.Linear(3,1) self.relu = nn.ReLU() self._initialize_weights() def forward(self, x): x = self.aff1(x) x = self.relu(x) return (x) def _initialize_weights(self): init.orthogonal_(self.aff1.weight) circuit = Model() export(circuit, input_shape = [3])
https://github.com/zkonduit/ezkl
examples/onnx/2l_sigmoid_small/gen.py
from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() self.fc = nn.Linear(3, 2) def forward(self, x): x = self.sigmoid(x) x = self.sigmoid(x) return x circuit = MyModel() export(circuit, input_shape = [1])
https://github.com/zkonduit/ezkl
examples/onnx/3l_relu_conv_fc/gen.py
from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.conv1 = nn.Conv2d(1,4, kernel_size=5, stride=2) self.conv2 = nn.Conv2d(4,4, kernel_size=5, stride=2) self.relu = nn.ReLU() self.fc = nn.Linear(4*4*4, 10) def forward(self, x): x = x.view(-1,1,28,28) x = self.relu(self.conv1(x)) x = self.relu(self.conv2(x)) x = x.view(-1,4*4*4) x = self.fc(x) return x circuit = MyModel() export(circuit, input_shape = [1,28,28])
https://github.com/zkonduit/ezkl
examples/onnx/4l_relu_conv_fc/gen.py
from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=5, stride=2) self.conv2 = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=5, stride=2) self.relu = nn.ReLU() self.d1 = nn.Linear(48, 48) self.d2 = nn.Linear(48, 10) def forward(self, x): # 32x1x28x28 => 32x32x26x26 x = self.conv1(x) x = self.relu(x) x = self.conv2(x) x = self.relu(x) # flatten => 32 x (32*26*26) x = x.flatten(start_dim = 1) # x = x.flatten() # 32 x (32*26*26) => 32x128 x = self.d1(x) x = self.relu(x) # logits => 32x10 logits = self.d2(x) return logits circuit = MyModel() export(circuit, input_shape = [1,28,28])
https://github.com/zkonduit/ezkl
examples/onnx/arange/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self): return torch.arange(0, 10, 2) circuit = MyModel() torch.onnx.export(circuit, (), "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=15, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization output_names=['output'], # the model's output names ) data = dict( input_data=[[]], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/bitshift/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, w, x, y, z): return x << 2, y >> 3, z << 1, w >> 4 circuit = MyModel() # random integers between 0 and 100 x = torch.empty(1, 3).uniform_(0, 100).to(torch.int32) y = torch.empty(1, 3).uniform_(0, 100).to(torch.int32) z = torch.empty(1, 3).uniform_(0, 100).to(torch.int32) w = torch.empty(1, 3).uniform_(0, 100).to(torch.int32) torch.onnx.export(circuit, (w, x, y, z), "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=16, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input', 'input1', 'input2', 'input3'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'input1': {0: 'batch_size'}, 'input2': {0: 'batch_size'}, 'input3': {0: 'batch_size'}, 'output': {0: 'batch_size'}, 'output1': {0: 'batch_size'}, 'output2': {0: 'batch_size'}, 'output3': {0: 'batch_size'}}) d = ((w).detach().numpy()).reshape([-1]).tolist() d1 = ((x).detach().numpy()).reshape([-1]).tolist() d2 = ((y).detach().numpy()).reshape([-1]).tolist() d3 = ((z).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d, d1, d2, d3], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/bitwise_ops/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, w, x, y, z): # bitwise and and_xy = torch.bitwise_and(x, y) # bitwise or or_yz = torch.bitwise_or(y, z) # bitwise not not_wyz = torch.bitwise_not(or_yz) return not_wyz circuit = MyModel() a = torch.empty(1, 3).uniform_(0, 1) w = torch.bernoulli(a).to(torch.bool) x = torch.bernoulli(a).to(torch.bool) y = torch.bernoulli(a).to(torch.bool) z = torch.bernoulli(a).to(torch.bool) torch.onnx.export(circuit, (w, x, y, z), "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=16, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input', 'input1', 'input2', 'input3'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'input1': {0: 'batch_size'}, 'input2': {0: 'batch_size'}, 'input3': {0: 'batch_size'}, 'output': {0: 'batch_size'}}) d = ((w).detach().numpy()).reshape([-1]).tolist() d1 = ((x).detach().numpy()).reshape([-1]).tolist() d2 = ((y).detach().numpy()).reshape([-1]).tolist() d3 = ((z).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d, d1, d2, d3], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/blackman_window/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): # bitwise and bmw = torch.blackman_window(8) + x return bmw circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=16, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/boolean/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, w, x, y, z): return [((x & y)) == (x & (y | (z ^ w)))] circuit = MyModel() a = torch.empty(1, 3).uniform_(0, 1) w = torch.bernoulli(a).to(torch.bool) x = torch.bernoulli(a).to(torch.bool) y = torch.bernoulli(a).to(torch.bool) z = torch.bernoulli(a).to(torch.bool) torch.onnx.export(circuit, (w, x, y, z), "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=15, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input', 'input1', 'input2', 'input3'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'input1': {0: 'batch_size'}, 'input2': {0: 'batch_size'}, 'input3': {0: 'batch_size'}, 'output': {0: 'batch_size'}}) d = ((w).detach().numpy()).reshape([-1]).tolist() d1 = ((x).detach().numpy()).reshape([-1]).tolist() d2 = ((y).detach().numpy()).reshape([-1]).tolist() d3 = ((z).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d, d1, d2, d3], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/boolean_identity/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): return [x] circuit = MyModel() a = torch.empty(1, 3).uniform_(0, 1) x = torch.bernoulli(a).to(torch.bool) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=15, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/celu/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.CELU()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/clip/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = torch.clamp(x, min=0.4, max=0.8) return m circuit = MyModel() x = torch.empty(1, 2, 2, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/decision_tree/gen.py
# Train a model. import json import onnxruntime as rt from skl2onnx import to_onnx import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier as De import sk2torch import torch iris = load_iris() X, y = iris.data, iris.target X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = De() clr.fit(X_train, y_train) torch_model = sk2torch.wrap(clr) # Convert into ONNX format. # export to onnx format # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=True) torch_out = torch_model(x) # Export the model torch.onnx.export(torch_model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/doodles/gen.py
from torch import nn from ezkl import export class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): return x circuit = MyModel() export(circuit, input_shape=[1, 64, 64])
https://github.com/zkonduit/ezkl
examples/onnx/eye/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = x @ torch.eye(8) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/gather_elements/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, w, x): return torch.gather(w, 1, x) circuit = MyModel() w = torch.rand(1, 15, 18) x = torch.randint(0, 15, (1, 15, 2)) torch.onnx.export(circuit, (w, x), "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=15, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input', 'input1'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'input1': {0: 'batch_size'}, 'output': {0: 'batch_size'}}) d = ((w).detach().numpy()).reshape([-1]).tolist() d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d, d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/gather_nd/gen.py
from torch import nn import json import numpy as np import tf2onnx import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras.models import Model # gather_nd in tf then export to onnx x = in1 = Input((15, 18,)) w = in2 = Input((15, 1), dtype=tf.int32) x = tf.gather_nd(x, w, batch_dims=1) tm = Model((in1, in2), x ) tm.summary() tm.compile(optimizer='adam', loss='mse') shape = [1, 15, 18] index_shape = [1, 15, 1] # After training, export to onnx (network.onnx) and create a data file (input.json) x = 0.1*np.random.rand(1,*shape) # w = random int tensor w = np.random.randint(0, 10, index_shape) spec = tf.TensorSpec(shape, tf.float32, name='input_0') index_spec = tf.TensorSpec(index_shape, tf.int32, name='input_1') model_path = "network.onnx" tf2onnx.convert.from_keras(tm, input_signature=[spec, index_spec], inputs_as_nchw=['input_0', 'input_1'], opset=12, output_path=model_path) d = x.reshape([-1]).tolist() d1 = w.reshape([-1]).tolist() data = dict( input_data=[d, d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/gradient_boosted_trees/gen.py
# make sure you have the dependencies required here already installed import json import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingClassifier as Gbc import sk2torch import torch import ezkl import os from torch import nn NUM_CLASSES = 3 iris = load_iris() X, y = iris.data, iris.target X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = Gbc(n_estimators=10) clr.fit(X_train, y_train) trees = [] for bundle in clr.estimators_: tree_bundle = [] for tree in bundle: tree_bundle.append(sk2torch.wrap(tree)) trees.append(tree_bundle) class GradientBoostedTrees(nn.Module): def __init__(self, trees): super(GradientBoostedTrees, self).__init__() bundle_modules = [] for bundle in trees: module = nn.ModuleList(bundle) bundle_modules.append(module) self.trees = nn.ModuleList(bundle_modules) self.num_classifiers = torch.tensor( [len(self.trees) for _ in range(NUM_CLASSES)]) def forward(self, x): # first bundle local_pred = self.trees[0][0](x) local_pred = local_pred.reshape(-1, 1) for tree in self.trees[0][1:]: tree_out = tree(x) tree_out = tree_out.reshape(-1, 1) local_pred = torch.cat((local_pred, tree_out), 1) local_pred = local_pred.reshape(-1, NUM_CLASSES) out = local_pred for bundle in self.trees[1:]: local_pred = bundle[0](x) local_pred = local_pred.reshape(-1, 1) for tree in bundle[1:]: tree_out = tree(x) tree_out = tree_out.reshape(-1, 1) local_pred = torch.cat((local_pred, tree_out), 1) # local_pred = local_pred.reshape(x.shape[0], 3) local_pred = local_pred.reshape(-1, NUM_CLASSES) out = out + local_pred output = out / self.num_classifiers return out.reshape(-1, NUM_CLASSES) torch_rf = GradientBoostedTrees(trees) # assert predictions from torch are = to sklearn for i in range(len(X_test)): torch_pred = torch_rf(torch.tensor(X_test[i].reshape(1, -1))) sk_pred = clr.predict(X_test[i].reshape(1, -1)) print(torch_pred, sk_pred[0]) assert torch_pred.argmax() == sk_pred[0] torch_rf.eval() # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=False) torch_out = torch_rf(x) # Export the model torch.onnx.export(torch_rf, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/gru/gen.py
import random import math import numpy as np import torch from torch import nn import torch.nn.functional as F import json model = nn.GRU(3, 3) # Input dim is 3, output dim is 3 x = torch.randn(1, 3) # make a sequence of length 5 print(x) # Flips the neural net into inference mode model.eval() model.to('cpu') # Export the model torch.onnx.export(model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) data_array = ((x).detach().numpy()).reshape([-1]).tolist() data_json = dict(input_data=[data_array]) print(data_json) # Serialize data into file: json.dump(data_json, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/hard_max/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = torch.argmax(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/hard_sigmoid/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.Hardsigmoid()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/hard_swish/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.Hardswish()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/hummingbird_decision_tree/gen.py
# Train a model. import json import onnxruntime as rt from skl2onnx import to_onnx import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier as De from hummingbird.ml import convert import torch iris = load_iris() X, y = iris.data, iris.target X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = De() clr.fit(X_train, y_train) torch_model = convert(clr, "pytorch").model # Convert into ONNX format. # export to onnx format # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=True) torch_out = torch_model(x) # Export the model torch.onnx.export(torch_model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/layernorm/gen.py
import torch import torch.nn as nn import json # A single model that only does layernorm class LayerNorm(nn.Module): def __init__(self, hidden_size): super().__init__() self.ln = nn.LayerNorm(hidden_size) def forward(self, x): return self.ln(x) x = torch.randn(1, 10, 10) model = LayerNorm(10) out = model(x) torch.onnx.export(model, x, "network.onnx", export_params=True, do_constant_folding=True, input_names = ['input'],output_names = ['output'],dynamic_axes={'input' : {0 : 'batch_size'},'output' : {0 : 'batch_size'}}) data_array = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_data = [data_array], output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in out]) json.dump( data, open( "input.json", 'w' ) )
https://github.com/zkonduit/ezkl
examples/onnx/less/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, w, x): return torch.less(w, x) circuit = MyModel() w = torch.rand(1, 4) x = torch.rand(1, 4) torch.onnx.export(circuit, (w, x), "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=15, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input', 'input1'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'input1': {0: 'batch_size'}, 'output': {0: 'batch_size'}}) d = ((w).detach().numpy()).reshape([-1]).tolist() d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d, d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/lightgbm/gen.py
# make sure you have the dependencies required here already installed import json import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from lightgbm import LGBMClassifier as Gbc import torch import ezkl import os from torch import nn import xgboost as xgb from hummingbird.ml import convert NUM_CLASSES = 3 iris = load_iris() X, y = iris.data, iris.target X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = Gbc(n_estimators=12) clr.fit(X_train, y_train) # convert to torch torch_gbt = convert(clr, 'torch', X_test[:1]) print(torch_gbt) # assert predictions from torch are = to sklearn diffs = [] for i in range(len(X_test)): torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1))) sk_pred = clr.predict(X_test[i].reshape(1, -1)) diffs.append(torch_pred != sk_pred[0]) print("num diff: ", sum(diffs)) # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=False) torch_out = torch_gbt.predict(x) # Export the model torch.onnx.export(torch_gbt.model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[(o).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/linear_regression/gen.py
import os import torch import ezkl import json from hummingbird.ml import convert # here we create and (potentially train a model) # make sure you have the dependencies required here already installed import numpy as np from sklearn.linear_model import LinearRegression X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) # y = 1 * x_0 + 2 * x_1 + 3 y = np.dot(X, np.array([1, 2])) + 3 reg = LinearRegression().fit(X, y) reg.score(X, y) circuit = convert(reg, "torch", X[:1]).model # export to onnx format # !!!!!!!!!!!!!!!!! This will flash a warning but it is fine !!!!!!!!!!!!!!!!!!!!! # Input to the model shape = X.shape[1:] x = torch.rand(1, *shape, requires_grad=True) torch_out = circuit(x) # Export the model torch.onnx.export(circuit, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/log_softmax/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.LogSoftmax()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/logsumexp/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = torch.logsumexp(x, dim=1) return m circuit = MyModel() x = torch.empty(1, 2, 2, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/lstm/gen.py
import random import math import numpy as np import torch from torch import nn import torch.nn.functional as F import json model = nn.LSTM(3, 3) # Input dim is 3, output dim is 3 x = torch.randn(1, 3) # make a sequence of length 5 print(x) # Flips the neural net into inference mode model.eval() model.to('cpu') # Export the model torch.onnx.export(model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) data_array = ((x).detach().numpy()).reshape([-1]).tolist() data_json = dict(input_data=[data_array]) print(data_json) # Serialize data into file: json.dump(data_json, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/ltsf/gen.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import json class moving_avg(nn.Module): """ Moving average block to highlight the trend of time series """ def __init__(self, kernel_size, stride): super(moving_avg, self).__init__() self.kernel_size = kernel_size self.avg = nn.AvgPool1d(kernel_size=kernel_size, stride=stride, padding=0) def forward(self, x): # padding on the both ends of time series front = x[:, 0:1, :].repeat(1, (self.kernel_size - 1) // 2, 1) end = x[:, -1:, :].repeat(1, (self.kernel_size - 1) // 2, 1) x = torch.cat([front, x, end], dim=1) x = self.avg(x.permute(0, 2, 1)) x = x.permute(0, 2, 1) return x class series_decomp(nn.Module): """ Series decomposition block """ def __init__(self, kernel_size): super(series_decomp, self).__init__() self.moving_avg = moving_avg(kernel_size, stride=1) def forward(self, x): moving_mean = self.moving_avg(x) res = x - moving_mean return res, moving_mean class Model(nn.Module): """ Decomposition-Linear """ def __init__(self, configs): super(Model, self).__init__() self.seq_len = configs['seq_len'] self.pred_len = configs['pred_len'] # Decompsition Kernel Size kernel_size = 25 self.decompsition = series_decomp(kernel_size) self.individual = configs['individual'] self.channels = configs['enc_in'] if self.individual: self.Linear_Seasonal = nn.ModuleList() self.Linear_Trend = nn.ModuleList() for i in range(self.channels): self.Linear_Seasonal.append(nn.Linear(self.seq_len,self.pred_len)) self.Linear_Trend.append(nn.Linear(self.seq_len,self.pred_len)) # Use this two lines if you want to visualize the weights # self.Linear_Seasonal[i].weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) # self.Linear_Trend[i].weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) else: self.Linear_Seasonal = nn.Linear(self.seq_len,self.pred_len) self.Linear_Trend = nn.Linear(self.seq_len,self.pred_len) # Use this two lines if you want to visualize the weights # self.Linear_Seasonal.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) # self.Linear_Trend.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) def forward(self, x): # x: [Batch, Input length, Channel] seasonal_init, trend_init = self.decompsition(x) seasonal_init, trend_init = seasonal_init.permute(0,2,1), trend_init.permute(0,2,1) if self.individual: seasonal_output = torch.zeros([seasonal_init.size(0),seasonal_init.size(1),self.pred_len],dtype=seasonal_init.dtype).to(seasonal_init.device) trend_output = torch.zeros([trend_init.size(0),trend_init.size(1),self.pred_len],dtype=trend_init.dtype).to(trend_init.device) for i in range(self.channels): seasonal_output[:,i,:] = self.Linear_Seasonal[i](seasonal_init[:,i,:]) trend_output[:,i,:] = self.Linear_Trend[i](trend_init[:,i,:]) else: seasonal_output = self.Linear_Seasonal(seasonal_init) trend_output = self.Linear_Trend(trend_init) x = seasonal_output + trend_output return x.permute(0,2,1) # to [Batch, Output length, Channel] configs = { 'seq_len': 96, 'pred_len': 1, 'individual': True, 'enc_in': 1, } circuit = Model(configs) x = torch.empty(1, 96, 1).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/max/gen.py
from torch import nn from ezkl import export import torch class Model(nn.Module): def __init__(self): super(Model, self).__init__() def forward(self, x): return [torch.max(x)] circuit = Model() export(circuit, input_shape=[3, 2, 2])
https://github.com/zkonduit/ezkl
examples/onnx/min/gen.py
from torch import nn from ezkl import export import torch class Model(nn.Module): def __init__(self): super(Model, self).__init__() def forward(self, x): return [torch.min(x)] circuit = Model() export(circuit, input_shape=[3, 2, 2])
https://github.com/zkonduit/ezkl
examples/onnx/mish/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.Mish()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/multihead_attention/gen.py
# 1. We define a simple transformer model with MultiHeadAttention layers import ezkl import json import torch import torch.nn as nn import torch.nn.functional as F class ScaledDotProductAttention(nn.Module): def __init__(self, d_model, dropout=0.1): super().__init__() self.temperature = d_model ** 0.5 self.dropout = nn.Dropout(dropout) def forward(self, q, k, v): attn = torch.matmul(q / self.temperature, k.transpose(2, 3)) attn = F.softmax(attn, dim=-1) attn = self.dropout(attn) output = torch.matmul(attn, v) return output, attn class MultiHeadAttention(nn.Module): def __init__(self, n_heads, d_model, dropout=0.1): super().__init__() self.n_heads = n_heads self.d_model = d_model self.d_k = d_model // n_heads self.w_qs = nn.Linear(d_model, d_model) self.w_ks = nn.Linear(d_model, d_model) self.w_vs = nn.Linear(d_model, d_model) self.fc = nn.Linear(d_model, d_model) self.attention = ScaledDotProductAttention(d_model) self.dropout = nn.Dropout(dropout) self.layer_norm = nn.LayerNorm(d_model) def forward(self, q, k, v): n_batches = q.size(0) q = self.w_qs(q).view(n_batches, -1, self.n_heads, self.d_k).transpose(1, 2) k = self.w_ks(k).view(n_batches, -1, self.n_heads, self.d_k).transpose(1, 2) v = self.w_vs(v).view(n_batches, -1, self.n_heads, self.d_k).transpose(1, 2) q, attn = self.attention(q, k, v) q = q.transpose(1, 2).contiguous().view(n_batches, -1, self.d_model) q = self.dropout(self.fc(q)) return self.layer_norm(q) class SimpleTransformer(nn.Module): def __init__(self, nlayer, d_model=512, n_heads=8): super().__init__() self.layers = nn.ModuleList( [MultiHeadAttention(n_heads, d_model) for _ in range(nlayer)]) # self.layers = nn.ModuleList([MultiHeadAttention(n_heads, d_model)]) self.fc = nn.Linear(d_model, 1) def forward(self, x): # assuming x is of shape [batch_size, sequence_length, d_model] for layer in self.layers: x = layer(x, x, x) x = x.mean(dim=1) # taking mean over the sequence length x = self.fc(x) return x # 2. We export it model = SimpleTransformer(2, d_model=128) input_shape = [1, 16, 128] x = 0.1*torch.rand(1, *input_shape, requires_grad=True) # Export the model torch.onnx.export(model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) data_array = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_data=[data_array]) json.dump(data, open("input.json", 'w')) # 3. We do our ezkl work # ezkl.gen_settings("network.onnx", "settings.json") # !RUST_LOG = full # res = ezkl.calibrate_settings( # "input.json", "network.onnx", "settings.json", "resources")
https://github.com/zkonduit/ezkl
examples/onnx/nanoGPT/gen.py
""" Reference: https://github.com/karpathy/nanoGPT """ import json import math from dataclasses import dataclass import torch import torch.nn as nn from torch.nn import functional as F import sys import os SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) def new_gelu(x): """ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415 """ return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x))) class LayerNorm(nn.Module): """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """ def __init__(self, ndim, bias): super().__init__() self.weight = nn.Parameter(torch.ones(ndim)) self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None def forward(self, input): return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5) class CausalSelfAttention(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads, but in a batch self.c_attn = nn.Linear( config.n_embd, 3 * config.n_embd, bias=config.bias) # output projection self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias) # regularization self.attn_dropout = nn.Dropout(config.dropout) self.resid_dropout = nn.Dropout(config.dropout) self.n_head = config.n_head self.n_embd = config.n_embd self.dropout = config.dropout # causal mask to ensure that attention is only applied to the left in the input sequence self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)) .view(1, 1, config.block_size, config.block_size)) def forward(self, x): B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd) # calculate query, key, values for all heads in batch and move head forward to be the batch dim q, k, v = self.c_attn(x).split(self.n_embd, dim=2) k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) # manual implementation of attention # q shape:(B, nh, T, hs), k transpose shape (B, nh, hs, T) -> (B, nh, T, T) att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float(-10)) att = F.softmax(att, dim=-1) att = self.attn_dropout(att) y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs) # re-assemble all head outputs side by side y = y.transpose(1, 2).contiguous().view(B, T, C) y = self.resid_dropout(self.c_proj(y)) return y class MLP(nn.Module): def __init__(self, config): super().__init__() self.c_fc = nn.Linear( config.n_embd, 4 * config.n_embd, bias=config.bias) self.c_proj = nn.Linear( 4 * config.n_embd, config.n_embd, bias=config.bias) self.dropout = nn.Dropout(config.dropout) def forward(self, x): x = self.c_fc(x) x = new_gelu(x) x = self.c_proj(x) x = self.dropout(x) return x class Block(nn.Module): def __init__(self, config): super().__init__() self.ln_1 = LayerNorm(config.n_embd, bias=config.bias) self.attn = CausalSelfAttention(config) self.ln_2 = LayerNorm(config.n_embd, bias=config.bias) self.mlp = MLP(config) def forward(self, x): x = x + self.attn(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x @dataclass class GPTConfig: block_size: int = 1024 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency vocab_size: int = 50304 n_layer: int = 12 n_head: int = 12 n_embd: int = 768 dropout: float = 0.0 # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster bias: bool = True class GPT(nn.Module): def __init__(self, config): super().__init__() assert config.vocab_size is not None assert config.block_size is not None self.config = config self.transformer = nn.ModuleDict(dict( wte=nn.Embedding(config.vocab_size, config.n_embd), wpe=nn.Embedding(config.block_size, config.n_embd), drop=nn.Dropout(config.dropout), h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]), ln_f=LayerNorm(config.n_embd, bias=config.bias), )) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) # weight-tying # https://paperswithcode.com/method/weight-tying self.transformer.wte.weight = self.lm_head.weight self.block = Block(config) # init all weights self.apply(self._init_weights) # apply special scaled init to the residual projections, per GPT-2 paper for pn, p in self.named_parameters(): if pn.endswith('c_proj.weight'): torch.nn.init.normal_( p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer)) # report number of parameters print("number of parameters: %.2fM" % (self.get_num_params()/1e6,)) def get_num_params(self, non_embedding=True): """ Return the number of parameters in the model. For non-embedding count (default), the position embeddings get subtracted. The token embeddings would too, except due to the parameter sharing these params are actually used as weights in the final layer, so we include them. """ n_params = sum(p.numel() for p in self.parameters()) if non_embedding: n_params -= self.transformer.wpe.weight.numel() return n_params def _init_weights(self, module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: torch.nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) def forward(self, idx, targets=None): device = idx.device b, t = idx.size() assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}" pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0) # shape (1, t) # # # forward the GPT model itself # token embeddings of shape (b, t, n_embd), idx -> token_emb idx = self.transformer.wte(idx) # position embeddings of shape (1, t, n_embd) pos_emb = self.transformer.wpe(pos) idx = self.transformer.drop(idx + pos_emb) for block in self.transformer.h: idx = block(idx) idx = self.transformer.ln_f(idx) idx = self.lm_head(idx) return idx gptconf = GPTConfig(block_size=64, vocab_size=65, n_layer=4, n_head=4, n_embd=64, dropout=0.0, bias=False) model = GPT(gptconf) model.get_num_params() shape = [1, 64] x = torch.randint(65, (1, 64)) torch_out = model(x) torch.onnx.export(model, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/oh_decision_tree/gen.py
# Train a model. import json import onnxruntime as rt from skl2onnx import to_onnx import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier as De import sk2torch import torch iris = load_iris() X, y = iris.data, iris.target X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = De() clr.fit(X_train, y_train) torch_model = sk2torch.wrap(clr) # Convert into ONNX format. # export to onnx format # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=True) torch_out = torch_model(x) # Export the model torch.onnx.export(torch_model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/quantize_dequantize/gen.py
import json import torch import torch.nn as nn import torch.optim as optim from torch.ao.quantization import QuantStub, DeQuantStub # define NN architecture class PredictLiquidationsV0(nn.Module): def __init__(self): super().__init__() self.quant = QuantStub() self.layer_1 = nn.Linear(in_features=41, out_features=1) self.dequant = DeQuantStub() def forward(self, x): x = self.quant(x) x = self.layer_1(x) x = self.dequant(x) return x # instantiate the model model_0 = PredictLiquidationsV0() # for QAT # model_0.qconfig = torch.ao.quantization.get_default_qat_qconfig('fbgemm') torch.ao.quantization.prepare_qat(model_0, inplace=True) # convert to a QAT model quantized_model_0 = torch.ao.quantization.convert( model_0.eval(), inplace=False) # evaluate quantized_model_0 # ... x = torch.randn((1, 41), requires_grad=True) # export as onnx quantized_model_0.eval() torch.onnx.export(quantized_model_0, torch.randn((1, 41), requires_grad=True), 'network.onnx', input_names=['input'], output_names=['output'], dynamic_axes={'input': {0: 'batch_size'}, 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_data=[d],) # save to input.json json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/random_forest/gen.py
# make sure you have the dependencies required here already installed import json import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier as Rf import sk2torch import torch import ezkl import os from torch import nn iris = load_iris() X, y = iris.data, iris.target X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = Rf() clr.fit(X_train, y_train) trees = [] for tree in clr.estimators_: trees.append(sk2torch.wrap(tree)) print(trees) class RandomForest(nn.Module): def __init__(self, trees): super(RandomForest, self).__init__() self.trees = nn.ModuleList(trees) def forward(self, x): out = self.trees[0](x) for tree in self.trees[1:]: out += tree(x) return out / len(self.trees) torch_rf = RandomForest(trees) # assert predictions from torch are = to sklearn for i in range(len(X_test)): torch_pred = torch_rf(torch.tensor(X_test[i].reshape(1, -1))) sk_pred = clr.predict(X_test[i].reshape(1, -1)) print(torch_pred, sk_pred[0]) assert torch_pred[0].round() == sk_pred[0] torch_rf.eval() # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=False) torch_out = torch_rf(x) # Export the model torch.onnx.export(torch_rf, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/reducel1/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = torch.norm(x, p=1, dim=1) return m circuit = MyModel() x = torch.empty(1, 2, 2, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/reducel2/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = torch.norm(x, p=2, dim=1) return m circuit = MyModel() x = torch.empty(1, 2, 2, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/remainder/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): return x % 0.5 circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/rnn/gen.py
import random import math import numpy as np import torch from torch import nn import torch.nn.functional as F import json model = nn.RNN(3, 3) # Input dim is 3, output dim is 3 x = torch.randn(1, 3) # make a sequence of length 5 print(x) # Flips the neural net into inference mode model.eval() model.to('cpu') # Export the model torch.onnx.export(model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) data_array = ((x).detach().numpy()).reshape([-1]).tolist() data_json = dict(input_data=[data_array]) print(data_json) # Serialize data into file: json.dump(data_json, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/rounding_ops/gen.py
import io import numpy as np from torch import nn import torch.onnx import torch import torch.nn as nn import torch.nn.init as init import json class Circuit(nn.Module): def __init__(self): super(Circuit, self).__init__() def forward(self, w, x, y): return torch.round(w), torch.floor(x), torch.ceil(y) def main(): torch_model = Circuit() # Input to the model shape = [3, 2, 3] w = 0.1*torch.rand(1, *shape, requires_grad=True) x = 0.1*torch.rand(1, *shape, requires_grad=True) y = 0.1*torch.rand(1, *shape, requires_grad=True) torch_out = torch_model(w, x, y) # Export the model torch.onnx.export(torch_model, # model being run # model input (or a tuple for multiple inputs) (w, x, y), # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=16, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['w', 'x', 'y'], # the model's input names # the model's output names output_names=['output_w', 'output_x', 'output_y'], dynamic_axes={'x': {0: 'batch_size'}, # variable length axes 'y': {0: 'batch_size'}, 'w': {0: 'batch_size'}, 'output_w': {0: 'batch_size'}, 'output_x': {0: 'batch_size'}, 'output_y': {0: 'batch_size'} }) dw = ((w).detach().numpy()).reshape([-1]).tolist() dx = ((x).detach().numpy()).reshape([-1]).tolist() dy = ((y).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape, shape, shape, shape], input_data=[dw, dx, dy], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w')) if __name__ == "__main__": main()
https://github.com/zkonduit/ezkl
examples/onnx/scatter_elements/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, w, x, src): # scatter_elements return w.scatter(2, x, src) circuit = MyModel() w = torch.rand(1, 15, 18) src = torch.rand(1, 15, 2) x = torch.randint(0, 15, (1, 15, 2)) torch.onnx.export(circuit, (w, x, src), "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=15, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization # the model's input names input_names=['input', 'input1', 'input2'], output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'input1': {0: 'batch_size'}, 'input2': {0: 'batch_size'}, 'output': {0: 'batch_size'}}) d = ((w).detach().numpy()).reshape([-1]).tolist() d1 = ((x).detach().numpy()).reshape([-1]).tolist() d2 = ((src).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d, d1, d2], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/scatter_nd/gen.py
import torch import torch.nn as nn import sys import json sys.path.append("..") class Model(nn.Module): """ Just one Linear layer """ def __init__(self, configs): super(Model, self).__init__() self.seq_len = configs.seq_len self.pred_len = configs.pred_len # Use this line if you want to visualize the weights # self.Linear.weight = nn.Parameter((1/self.seq_len)*torch.ones([self.pred_len,self.seq_len])) self.channels = configs.enc_in self.individual = configs.individual if self.individual: self.Linear = nn.ModuleList() for i in range(self.channels): self.Linear.append(nn.Linear(self.seq_len,self.pred_len)) else: self.Linear = nn.Linear(self.seq_len, self.pred_len) def forward(self, x): # x: [Batch, Input length, Channel] if self.individual: output = torch.zeros([x.size(0),self.pred_len,x.size(2)],dtype=x.dtype).to(x.device) for i in range(self.channels): output[:,:,i] = self.Linear[i](x[:,:,i]) x = output else: x = self.Linear(x.permute(0,2,1)).permute(0,2,1) return x # [Batch, Output length, Channel] class Configs: def __init__(self, seq_len, pred_len, enc_in=321, individual=True): self.seq_len = seq_len self.pred_len = pred_len self.enc_in = enc_in self.individual = individual model = 'Linear' seq_len = 10 pred_len = 4 enc_in = 3 configs = Configs(seq_len, pred_len, enc_in, True) circuit = Model(configs) x = torch.randn(1, seq_len, pred_len) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=15, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization # the model's input names input_names=['input'], output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/self_attention/gen.py
""" Reference: https://github.com/karpathy/nanoGPT :) """ import torch import json from torch import nn import math from dataclasses import dataclass from torch.nn import functional as F @dataclass class GPTConfig: block_size: int = 1024 vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency n_layer: int = 12 n_head: int = 12 n_embd: int = 768 dropout: float = 0.0 bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster def new_gelu(x): """ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415 """ return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * x * x * x))) class CausalSelfAttention(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 # key, query, value projections for all heads, but in a batch self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias) # output projection self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias) # regularization self.attn_dropout = nn.Dropout(config.dropout) self.resid_dropout = nn.Dropout(config.dropout) self.n_head = config.n_head self.n_embd = config.n_embd self.dropout = config.dropout # causal mask to ensure that attention is only applied to the left in the input sequence self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)) .view(1, 1, config.block_size, config.block_size)) def forward(self, x): B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd) # calculate query, key, values for all heads in batch and move head forward to be the batch dim q, k, v = self.c_attn(x).split(self.n_embd, dim=2) k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs) # manual implementation of attention att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1))) #q shape:(B, nh, T, hs), k transpose shape (B, nh, hs, T) -> (B, nh, T, T) att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float(-10)) att = F.softmax(att, dim=-1) att = self.attn_dropout(att) y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs) y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side y = self.resid_dropout(self.c_proj(y)) return y class MLP(nn.Module): def __init__(self, config): super().__init__() self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd) self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd) self.dropout = nn.Dropout(config.dropout) def forward(self, x): x = self.c_fc(x) x = new_gelu(x) x = self.c_proj(x) x = self.dropout(x) return x class Block(nn.Module): def __init__(self, config): super().__init__() self.ln_1 = nn.LayerNorm(config.n_embd) self.attention = CausalSelfAttention(config) self.ln_2 = nn.LayerNorm(config.n_embd) self.mlp = MLP(config) def forward(self, x): x = x + self.attention(self.ln_1(x)) x = x + self.mlp(self.ln_2(x)) return x shape = [1, 64, 64] x = torch.ones(1, 64, 64) config = GPTConfig(block_size = 64, vocab_size = 65, n_layer = 4, n_head = 4, n_embd = 64,dropout = 0.0, bias = False) model = Block(config) torch_out = model(x) torch.onnx.export(model, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names = ['input'], # the model's input names output_names = ['output'], # the model's output names dynamic_axes={'input' : {0 : 'batch_size'}, # variable length axes 'output' : {0 : 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes = [shape], input_data = [d], output_data = [((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump( data, open( "input.json", 'w' ) )
https://github.com/zkonduit/ezkl
examples/onnx/selu/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.SELU()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/softplus/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.Softplus()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/softsign/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = nn.Softsign()(x) return m circuit = MyModel() x = torch.empty(1, 8).uniform_(0, 1) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/trig/gen.py
import io import numpy as np from torch import nn import torch.onnx import torch import torch.nn as nn import torch.nn.init as init import json class Circuit(nn.Module): def __init__(self): super(Circuit, self).__init__() self.softplus = nn.Softplus() def forward(self, x): x = self.softplus(x) x = torch.cos(x) x = torch.sin(x) x = torch.tan(x) x = torch.acos(x) x = torch.asin(x) x = torch.atan(x) # x = torch.cosh(x) # x = torch.sinh(x) x = torch.tanh(x) # x = torch.acosh(x) # x = torch.asinh(x) # x = torch.atanh(x) return (-x).abs().sign() def main(): torch_model = Circuit() # Input to the model shape = [3, 2, 3] x = 0.1*torch.rand(1, *shape, requires_grad=True) torch_out = torch_model(x) # Export the model torch.onnx.export(torch_model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape, shape, shape], input_data=[d], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w')) if __name__ == "__main__": main()
https://github.com/zkonduit/ezkl
examples/onnx/tril/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = torch.triu(x) return m circuit = MyModel() x = torch.empty(1, 3, 3).uniform_(0, 5) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/triu/gen.py
from torch import nn import torch import json import numpy as np class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() def forward(self, x): m = torch.tril(x) return m circuit = MyModel() x = torch.empty(1, 3, 3).uniform_(0, 5) out = circuit(x) print(out) torch.onnx.export(circuit, x, "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=17, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d1 = ((x).detach().numpy()).reshape([-1]).tolist() data = dict( input_data=[d1], ) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/tutorial/gen.py
import io import numpy as np from torch import nn import torch.onnx import torch.nn as nn import torch.nn.init as init import json class Circuit(nn.Module): def __init__(self, inplace=False): super(Circuit, self).__init__() self.relu = nn.ReLU() self.sigmoid = nn.Sigmoid() self.conv = nn.Conv2d(3, 3, (2, 2), 1, 2) self._initialize_weights() def forward(self, x, y, z): x = self.sigmoid(self.conv(y@x**2 + (x) - (self.relu(z)))) + 2 return (x, self.relu(z) / 3) def _initialize_weights(self): init.orthogonal_(self.conv.weight) def main(): torch_model = Circuit() # Input to the model shape = [3, 2, 2] x = 0.1*torch.rand(1, *shape, requires_grad=True) y = 0.1*torch.rand(1, *shape, requires_grad=True) z = 0.1*torch.rand(1, *shape, requires_grad=True) torch_out = torch_model(x, y, z) # Export the model torch.onnx.export(torch_model, # model being run # model input (or a tuple for multiple inputs) (x, y, z), # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() dy = ((y).detach().numpy()).reshape([-1]).tolist() dz = ((z).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape, shape, shape], input_data=[d, dy, dz], output_data=[((o).detach().numpy()).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w')) if __name__ == "__main__": main()
https://github.com/zkonduit/ezkl
examples/onnx/xgboost/gen.py
# make sure you have the dependencies required here already installed import json import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from xgboost import XGBClassifier as Gbc import torch import ezkl import os from torch import nn import xgboost as xgb from hummingbird.ml import convert NUM_CLASSES = 3 iris = load_iris() X, y = iris.data, iris.target X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = Gbc(n_estimators=12) clr.fit(X_train, y_train) # convert to torch torch_gbt = convert(clr, 'torch') print(torch_gbt) # assert predictions from torch are = to sklearn diffs = [] for i in range(len(X_test)): torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1))) sk_pred = clr.predict(X_test[i].reshape(1, -1)) diffs.append(torch_pred != sk_pred[0]) print("num diff: ", sum(diffs)) # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=False) torch_out = torch_gbt.predict(x) # Export the model torch.onnx.export(torch_gbt.model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) d = ((x).detach().numpy()).reshape([-1]).tolist() data = dict(input_shapes=[shape], input_data=[d], output_data=[(o).reshape([-1]).tolist() for o in torch_out]) # Serialize data into file: json.dump(data, open("input.json", 'w'))
https://github.com/zkonduit/ezkl
examples/onnx/xgboost_reg/gen.py
# make sure you have the dependencies required here already installed import json import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from xgboost import XGBRegressor as Gbc import torch import ezkl import os from torch import nn import xgboost as xgb from hummingbird.ml import convert NUM_CLASSES = 3 X, y = np.random.rand(1000, 4), np.random.rand(1000, 1) X = X.astype(np.float32) X_train, X_test, y_train, y_test = train_test_split(X, y) clr = Gbc(n_estimators=12) clr.fit(X_train, y_train) # convert to torch torch_gbt = convert(clr, 'torch') print(torch_gbt) # assert predictions from torch are = to sklearn diffs = [] # Input to the model shape = X_train.shape[1:] x = torch.rand(1, *shape, requires_grad=False) torch_out = torch_gbt.predict(x) # Export the model torch.onnx.export(torch_gbt.model, # model being run # model input (or a tuple for multiple inputs) x, # where to save the model (can be a file or file-like object) "network.onnx", export_params=True, # store the trained parameter weights inside the model file opset_version=11, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}})
https://github.com/zkonduit/ezkl
jest.config.js
module.exports = { preset: 'ts-jest', testEnvironment: 'node', };
https://github.com/zkonduit/ezkl
src/bin/ezkl.rs
// ignore file if compiling for wasm #[cfg(not(target_arch = "wasm32"))] use clap::Parser; #[cfg(not(target_arch = "wasm32"))] use colored_json::ToColoredJson; #[cfg(not(target_arch = "wasm32"))] use ezkl::commands::Cli; #[cfg(not(target_arch = "wasm32"))] use ezkl::execute::run; #[cfg(not(target_arch = "wasm32"))] use ezkl::logger::init_logger; #[cfg(not(target_arch = "wasm32"))] use log::{debug, error, info}; #[cfg(not(any(target_arch = "wasm32", feature = "no-banner")))] use rand::prelude::SliceRandom; #[cfg(not(target_arch = "wasm32"))] #[cfg(feature = "icicle")] use std::env; #[cfg(not(target_arch = "wasm32"))] use std::error::Error; #[tokio::main(flavor = "current_thread")] #[cfg(not(target_arch = "wasm32"))] pub async fn main() -> Result<(), Box<dyn Error>> { let args = Cli::parse(); init_logger(); #[cfg(not(any(target_arch = "wasm32", feature = "no-banner")))] banner(); #[cfg(feature = "icicle")] if env::var("ENABLE_ICICLE_GPU").is_ok() { info!("Running with ICICLE GPU"); } else { info!("Running with CPU"); } debug!("command: \n {}", &args.as_json()?.to_colored_json_auto()?); let res = run(args.command).await; match &res { Ok(_) => info!("succeeded"), Err(e) => error!("failed: {}", e), }; res.map(|_| ()) } #[cfg(target_arch = "wasm32")] pub fn main() {} #[cfg(not(any(target_arch = "wasm32", feature = "no-banner")))] fn banner() { let ell: Vec<&str> = vec![ "for Neural Networks", "Linear Algebra", "for Layers", "for the Laconic", "Learning", "for Liberty", "for the Lyrical", ]; info!( "{}", format!( " ███████╗███████╗██╗ ██╗██╗ ██╔════╝╚══███╔╝██║ ██╔╝██║ █████╗ ███╔╝ █████╔╝ ██║ ██╔══╝ ███╔╝ ██╔═██╗ ██║ ███████╗███████╗██║ ██╗███████╗ ╚══════╝╚══════╝╚═╝ ╚═╝╚══════╝ ----------------------------------------------------------- Easy Zero Knowledge {}. ----------------------------------------------------------- ", ell.choose(&mut rand::thread_rng()).unwrap() ) ); }
https://github.com/zkonduit/ezkl
src/circuit/mod.rs
/// pub mod modules; /// pub mod table; /// pub mod utils; /// pub mod ops; pub use ops::chip::*; pub use ops::*; /// Tests #[cfg(test)] mod tests;
https://github.com/zkonduit/ezkl
src/circuit/modules/mod.rs
/// pub mod poseidon; /// pub mod polycommit; /// pub mod planner; use halo2_proofs::{ circuit::Layouter, plonk::{ConstraintSystem, Error}, }; use halo2curves::ff::PrimeField; pub use planner::*; use crate::tensor::{TensorType, ValTensor}; use super::region::ConstantsMap; /// Module trait used to extend ezkl functionality pub trait Module<F: PrimeField + TensorType + PartialOrd> { /// Config type Config; /// The return type after an input assignment type InputAssignments; /// The inputs used in the run function type RunInputs; /// The params used in configure type Params; /// construct new module from config fn new(config: Self::Config) -> Self; /// Configure fn configure(meta: &mut ConstraintSystem<F>, params: Self::Params) -> Self::Config; /// Name fn name(&self) -> &'static str; /// Run the operation the module represents fn run(input: Self::RunInputs) -> Result<Vec<Vec<F>>, Box<dyn std::error::Error>>; /// Layout inputs fn layout_inputs( &self, layouter: &mut impl Layouter<F>, input: &[ValTensor<F>], constants: &mut ConstantsMap<F>, ) -> Result<Self::InputAssignments, Error>; /// Layout fn layout( &self, layouter: &mut impl Layouter<F>, input: &[ValTensor<F>], row_offset: usize, constants: &mut ConstantsMap<F>, ) -> Result<ValTensor<F>, Error>; /// Number of instance values the module uses every time it is applied fn instance_increment_input(&self) -> Vec<usize>; /// Number of rows used by the module fn num_rows(input_len: usize) -> usize; }
https://github.com/zkonduit/ezkl
src/circuit/modules/planner.rs
use std::cmp; use std::collections::HashMap; use std::fmt; use std::marker::PhantomData; use halo2curves::ff::Field; use halo2_proofs::{ circuit::{ layouter::{RegionColumn, RegionLayouter, RegionShape, SyncDeps, TableLayouter}, Cell, Layouter, Region, RegionIndex, RegionStart, Table, Value, }, plonk::{ Advice, Any, Assigned, Assignment, Challenge, Circuit, Column, Error, Fixed, FloorPlanner, Instance, Selector, TableColumn, }, }; use log::{debug, trace}; /// A simple [`FloorPlanner`] that performs minimal optimizations. #[derive(Debug)] pub struct ModulePlanner; impl FloorPlanner for ModulePlanner { fn synthesize<F: Field, CS: Assignment<F> + SyncDeps, C: Circuit<F>>( cs: &mut CS, circuit: &C, config: C::Config, constants: Vec<Column<Fixed>>, ) -> Result<(), Error> { let layouter = ModuleLayouter::new(cs, constants)?; circuit.synthesize(config, layouter) } } /// pub type ModuleIdx = usize; /// pub type RegionIdx = usize; /// A [`Layouter`] for a circuit with multiple modules. pub struct ModuleLayouter<'a, F: Field, CS: Assignment<F> + 'a> { cs: &'a mut CS, constants: Vec<Column<Fixed>>, /// Stores the starting row for each region. regions: HashMap<ModuleIdx, HashMap<RegionIdx, RegionStart>>, /// Stores the starting row for each region. region_idx: HashMap<RegionIdx, ModuleIdx>, /// Stores the first empty row for each column. columns: HashMap<(ModuleIdx, RegionColumn), usize>, /// Stores the table fixed columns. table_columns: Vec<TableColumn>, _marker: PhantomData<F>, /// current module current_module: usize, /// num_constants total_constants: usize, } impl<'a, F: Field, CS: Assignment<F> + 'a> fmt::Debug for ModuleLayouter<'a, F, CS> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ModuleLayouter") .field("regions", &self.regions) .field("columns", &self.columns) .field("total_constants", &self.total_constants) .finish() } } impl<'a, F: Field, CS: Assignment<F>> ModuleLayouter<'a, F, CS> { /// Creates a new module layouter. pub fn new(cs: &'a mut CS, constants: Vec<Column<Fixed>>) -> Result<Self, Error> { let ret = ModuleLayouter { cs, constants, regions: HashMap::default(), columns: HashMap::default(), region_idx: HashMap::default(), table_columns: vec![], current_module: 0, total_constants: 0, _marker: PhantomData, }; Ok(ret) } /// fn get_constant_col_cartesian_coord( &self, linear_coord: usize, col_size: usize, ) -> (usize, usize) { let x = linear_coord / col_size; let y = linear_coord % col_size; (x, y) } } impl<'a, F: Field, CS: Assignment<F> + 'a + SyncDeps> Layouter<F> for ModuleLayouter<'a, F, CS> { type Root = Self; fn assign_region<A, AR, N, NR>(&mut self, name: N, mut assignment: A) -> Result<AR, Error> where A: FnMut(Region<'_, F>) -> Result<AR, Error>, N: Fn() -> NR, NR: Into<String>, { // if the name contains the required substring we increment the current module idx if Into::<String>::into(name()).contains("_enter_module_") { let name = Into::<String>::into(name()); let index = match name.split("_enter_module_").last() { Some(v) => v, None => { log::error!("Invalid module name"); return Err(Error::Synthesis); } }; let index = index.parse::<usize>().map_err(|_| { log::error!("Invalid module name"); Error::Synthesis })?; if !self.regions.contains_key(&index) { debug!("spawning module {}", index) }; self.current_module = index; } let region_index = self.region_idx.len(); self.region_idx.insert(region_index, self.current_module); // Get shape of the region. let mut shape = RegionShape::new(region_index.into()); { let region: &mut dyn RegionLayouter<F> = &mut shape; assignment(region.into())?; } // Modules are stacked horizontally across new columns -- THIS ASSUMES THE MODULES HAVE NON OVERLAPPING COLUMNS. let region_start = match self.regions.get_mut(&self.current_module) { Some(v) => { let mut region_start = 0; for column in shape.columns().iter() { region_start = cmp::max( region_start, self.columns .get(&(self.current_module, *column)) .cloned() .unwrap_or(0), ); } v.insert(region_index, region_start.into()); region_start } None => { let map = HashMap::from([(region_index, 0.into())]); self.regions.insert(self.current_module, map); 0 } }; // Update column usage information. for column in shape.columns() { self.columns.insert( (self.current_module, *column), region_start + shape.row_count(), ); } // Assign region cells. self.cs.enter_region(name); let mut region = ModuleLayouterRegion::new(self, region_index.into()); let result = { let region: &mut dyn RegionLayouter<F> = &mut region; assignment(region.into()) }?; let constants_to_assign = region.constants; self.cs.exit_region(); // Assign constants. For the simple floor planner, we assign constants in order in // the first `constants` column. if self.constants.is_empty() { if !constants_to_assign.is_empty() { return Err(Error::NotEnoughColumnsForConstants); } } else { for (constant, advice) in constants_to_assign { // read path from OS env let (constant_column, y) = crate::graph::GLOBAL_SETTINGS.with(|settings| { match settings.borrow().as_ref() { Some(settings) => { let col_size = settings.available_col_size(); let (x, y) = self .get_constant_col_cartesian_coord(self.total_constants, col_size); (self.constants[x], y) } None => (self.constants[0], self.total_constants), } }); self.cs.assign_fixed( || format!("Constant({:?})", constant.evaluate()), constant_column, y, || Value::known(constant), )?; let region_module = self.region_idx[&advice.region_index]; self.cs.copy( constant_column.into(), y, advice.column, *self.regions[&region_module][&advice.region_index] + advice.row_offset, )?; self.total_constants += 1; } } trace!("region {} assigned", region_index); trace!("total_constants: {:?}", self.total_constants); let max_row_index = self .columns .iter() .filter(|((module, _), _)| *module == self.current_module) .map(|(_, row)| *row) .max() .unwrap_or(0); trace!("max_row_index: {:?}", max_row_index); Ok(result) } fn assign_table<A, N, NR>(&mut self, name: N, mut assignment: A) -> Result<(), Error> where A: FnMut(Table<'_, F>) -> Result<(), Error>, N: Fn() -> NR, NR: Into<String>, { // Maintenance hazard: there is near-duplicate code in `v1::AssignmentPass::assign_table`. // Assign table cells. self.cs.enter_region(name); let mut table = halo2_proofs::circuit::SimpleTableLayouter::new(self.cs, &self.table_columns); { let table: &mut dyn TableLayouter<F> = &mut table; assignment(table.into()) }?; let default_and_assigned = table.default_and_assigned; self.cs.exit_region(); // Check that all table columns have the same length `first_unused`, // and all cells up to that length are assigned. let first_unused = { match default_and_assigned .values() .map(|(_, assigned)| { if assigned.iter().all(|b| *b) { Some(assigned.len()) } else { None } }) .reduce(|acc, item| match (acc, item) { (Some(a), Some(b)) if a == b => Some(a), _ => None, }) { Some(Some(len)) => len, _ => return Err(Error::Synthesis), // TODO better error } }; // Record these columns so that we can prevent them from being used again. for column in default_and_assigned.keys() { self.table_columns.push(*column); } for (col, (default_val, _)) in default_and_assigned { // default_val must be Some because we must have assigned // at least one cell in each column, and in that case we checked // that all cells up to first_unused were assigned. let default_val = default_val.ok_or(Error::Synthesis)?; self.cs .fill_from_row(col.inner(), first_unused, default_val)?; } Ok(()) } fn constrain_instance( &mut self, cell: Cell, instance: Column<Instance>, row: usize, ) -> Result<(), Error> { let module_idx = self.region_idx[&cell.region_index]; self.cs.copy( cell.column, *self.regions[&module_idx][&cell.region_index] + cell.row_offset, instance.into(), row, ) } fn get_challenge(&self, challenge: Challenge) -> Value<F> { self.cs.get_challenge(challenge) } fn get_root(&mut self) -> &mut Self::Root { self } fn push_namespace<NR, N>(&mut self, name_fn: N) where NR: Into<String>, N: FnOnce() -> NR, { self.cs.push_namespace(name_fn) } fn pop_namespace(&mut self, gadget_name: Option<String>) { self.cs.pop_namespace(gadget_name) } } struct ModuleLayouterRegion<'r, 'a, F: Field, CS: Assignment<F> + 'a> { layouter: &'r mut ModuleLayouter<'a, F, CS>, region_index: RegionIndex, /// Stores the constants to be assigned, and the cells to which they are copied. constants: Vec<(Assigned<F>, Cell)>, } impl<'r, 'a, F: Field, CS: Assignment<F> + 'a> fmt::Debug for ModuleLayouterRegion<'r, 'a, F, CS> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ModuleLayouterRegion") .field("layouter", &self.layouter) .field("region_index", &self.region_index) .finish() } } impl<'r, 'a, F: Field, CS: Assignment<F> + 'a> ModuleLayouterRegion<'r, 'a, F, CS> { fn new(layouter: &'r mut ModuleLayouter<'a, F, CS>, region_index: RegionIndex) -> Self { ModuleLayouterRegion { layouter, region_index, constants: vec![], } } } impl<'r, 'a, F: Field, CS: Assignment<F> + 'a + SyncDeps> RegionLayouter<F> for ModuleLayouterRegion<'r, 'a, F, CS> { fn instance_value( &mut self, instance: Column<Instance>, row: usize, ) -> Result<Value<F>, Error> { self.layouter.cs.query_instance(instance, row) } fn enable_selector<'v>( &'v mut self, annotation: &'v (dyn Fn() -> String + 'v), selector: &Selector, offset: usize, ) -> Result<(), Error> { let module_idx = self.layouter.region_idx[&self.region_index]; self.layouter.cs.enable_selector( annotation, selector, *self.layouter.regions[&module_idx][&self.region_index] + offset, ) } fn name_column<'v>( &'v mut self, annotation: &'v (dyn Fn() -> String + 'v), column: Column<Any>, ) { self.layouter.cs.annotate_column(annotation, column); } fn assign_advice<'v>( &'v mut self, annotation: &'v (dyn Fn() -> String + 'v), column: Column<Advice>, offset: usize, to: &'v mut (dyn FnMut() -> Value<Assigned<F>> + 'v), ) -> Result<Cell, Error> { let module_idx = self.layouter.region_idx[&self.region_index]; self.layouter.cs.assign_advice( annotation, column, *self.layouter.regions[&module_idx][&self.region_index] + offset, to, )?; Ok(Cell { region_index: self.region_index, row_offset: offset, column: column.into(), }) } fn assign_advice_from_constant<'v>( &'v mut self, annotation: &'v (dyn Fn() -> String + 'v), column: Column<Advice>, offset: usize, constant: Assigned<F>, ) -> Result<Cell, Error> { let advice = self.assign_advice(annotation, column, offset, &mut || Value::known(constant))?; self.constrain_constant(advice, constant)?; Ok(advice) } fn assign_advice_from_instance<'v>( &mut self, annotation: &'v (dyn Fn() -> String + 'v), instance: Column<Instance>, row: usize, advice: Column<Advice>, offset: usize, ) -> Result<(Cell, Value<F>), Error> { let value = self.layouter.cs.query_instance(instance, row)?; let cell = self.assign_advice(annotation, advice, offset, &mut || value.to_field())?; let module_idx = self.layouter.region_idx[&cell.region_index]; self.layouter.cs.copy( cell.column, *self.layouter.regions[&module_idx][&cell.region_index] + cell.row_offset, instance.into(), row, )?; Ok((cell, value)) } fn assign_fixed<'v>( &'v mut self, annotation: &'v (dyn Fn() -> String + 'v), column: Column<Fixed>, offset: usize, to: &'v mut (dyn FnMut() -> Value<Assigned<F>> + 'v), ) -> Result<Cell, Error> { let module_idx = self.layouter.region_idx[&self.region_index]; self.layouter.cs.assign_fixed( annotation, column, *self.layouter.regions[&module_idx][&self.region_index] + offset, to, )?; Ok(Cell { region_index: self.region_index, row_offset: offset, column: column.into(), }) } fn constrain_constant(&mut self, cell: Cell, constant: Assigned<F>) -> Result<(), Error> { self.constants.push((constant, cell)); Ok(()) } fn constrain_equal(&mut self, left: Cell, right: Cell) -> Result<(), Error> { let left_module = self.layouter.region_idx[&left.region_index]; let right_module = self.layouter.region_idx[&right.region_index]; self.layouter.cs.copy( left.column, *self.layouter.regions[&left_module][&left.region_index] + left.row_offset, right.column, *self.layouter.regions[&right_module][&right.region_index] + right.row_offset, )?; Ok(()) } } #[cfg(test)] mod tests { use halo2curves::pasta::vesta; use super::ModulePlanner; use halo2_proofs::{ dev::MockProver, plonk::{Advice, Circuit, Column, Error}, }; #[test] fn not_enough_columns_for_constants() { struct MyCircuit {} impl Circuit<vesta::Scalar> for MyCircuit { type Config = Column<Advice>; type FloorPlanner = ModulePlanner; type Params = (); fn without_witnesses(&self) -> Self { MyCircuit {} } fn configure( meta: &mut halo2_proofs::plonk::ConstraintSystem<vesta::Scalar>, ) -> Self::Config { meta.advice_column() } fn synthesize( &self, config: Self::Config, mut layouter: impl halo2_proofs::circuit::Layouter<vesta::Scalar>, ) -> Result<(), halo2_proofs::plonk::Error> { layouter.assign_region( || "assign constant", |mut region| { region.assign_advice_from_constant( || "one", config, 0, vesta::Scalar::one(), ) }, )?; Ok(()) } } let circuit = MyCircuit {}; assert!(matches!( MockProver::run(3, &circuit, vec![]).unwrap_err(), Error::NotEnoughColumnsForConstants, )); } }
https://github.com/zkonduit/ezkl
src/circuit/modules/polycommit.rs
/* An easy-to-use implementation of the Poseidon Hash in the form of a Halo2 Chip. While the Poseidon Hash function is already implemented in halo2_gadgets, there is no wrapper chip that makes it easy to use in other circuits. Thanks to https://github.com/summa-dev/summa-solvency/blob/master/src/chips/poseidon/hash.rs for the inspiration (and also helping us understand how to use this). */ use std::collections::HashMap; // This chip adds a set of advice columns to the gadget Chip to store the inputs of the hash use halo2_proofs::halo2curves::bn256::Fr as Fp; use halo2_proofs::poly::commitment::{Blind, CommitmentScheme, Params}; use halo2_proofs::{circuit::*, plonk::*}; use halo2curves::bn256::G1Affine; use halo2curves::group::prime::PrimeCurveAffine; use halo2curves::group::Curve; use halo2curves::CurveAffine; use crate::circuit::region::ConstantsMap; use crate::tensor::{Tensor, ValTensor, ValType, VarTensor}; use super::Module; /// The number of instance columns used by the PolyCommit hash function pub const NUM_INSTANCE_COLUMNS: usize = 0; /// The number of advice columns used by the PolyCommit hash function pub const NUM_INNER_COLS: usize = 1; #[derive(Debug, Clone)] /// Configuration for the PolyCommit chip pub struct PolyCommitConfig { /// pub inputs: VarTensor, } type InputAssignments = (); /// #[derive(Debug)] pub struct PolyCommitChip { config: PolyCommitConfig, } impl PolyCommitChip { /// Commit to the message using the KZG commitment scheme pub fn commit<Scheme: CommitmentScheme<Scalar = Fp, Curve = G1Affine>>( message: Vec<Scheme::Scalar>, num_unusable_rows: u32, params: &Scheme::ParamsProver, ) -> Vec<G1Affine> { let k = params.k(); let domain = halo2_proofs::poly::EvaluationDomain::new(2, k); let n = 2_u64.pow(k) - num_unusable_rows as u64; let num_poly = (message.len() / n as usize) + 1; let mut poly = vec![domain.empty_lagrange(); num_poly]; (0..num_unusable_rows).for_each(|i| { for p in &mut poly { p[(n + i as u64) as usize] = Blind::default().0; } }); for (i, m) in message.iter().enumerate() { let x = i / (n as usize); let y = i % (n as usize); poly[x][y] = *m; } let mut advice_commitments_projective = vec![]; for a in poly { advice_commitments_projective.push(params.commit_lagrange(&a, Blind::default())) } let mut advice_commitments = vec![G1Affine::identity(); advice_commitments_projective.len()]; <G1Affine as CurveAffine>::CurveExt::batch_normalize( &advice_commitments_projective, &mut advice_commitments, ); advice_commitments } } impl Module<Fp> for PolyCommitChip { type Config = PolyCommitConfig; type InputAssignments = InputAssignments; type RunInputs = Vec<Fp>; type Params = (usize, usize); fn name(&self) -> &'static str { "PolyCommit" } fn instance_increment_input(&self) -> Vec<usize> { vec![0] } /// Constructs a new PoseidonChip fn new(config: Self::Config) -> Self { Self { config } } /// Configuration of the PoseidonChip fn configure(meta: &mut ConstraintSystem<Fp>, params: Self::Params) -> Self::Config { let inputs = VarTensor::new_unblinded_advice(meta, params.0, NUM_INNER_COLS, params.1); Self::Config { inputs } } fn layout_inputs( &self, _: &mut impl Layouter<Fp>, _: &[ValTensor<Fp>], _: &mut ConstantsMap<Fp>, ) -> Result<Self::InputAssignments, Error> { Ok(()) } /// L is the number of inputs to the hash function /// Takes the cells containing the input values of the hash function and return the cell containing the hash output /// It uses the pow5_chip to compute the hash fn layout( &self, layouter: &mut impl Layouter<Fp>, input: &[ValTensor<Fp>], _: usize, constants: &mut ConstantsMap<Fp>, ) -> Result<ValTensor<Fp>, Error> { assert_eq!(input.len(), 1); let local_constants = constants.clone(); layouter.assign_region( || "PolyCommit", |mut region| { let mut local_inner_constants = local_constants.clone(); let res = self.config.inputs.assign( &mut region, 0, &input[0], &mut local_inner_constants, )?; *constants = local_inner_constants; Ok(res) }, ) } /// fn run(message: Vec<Fp>) -> Result<Vec<Vec<Fp>>, Box<dyn std::error::Error>> { Ok(vec![message]) } fn num_rows(_: usize) -> usize { 0 } } #[allow(unused)] mod tests { use crate::circuit::modules::ModulePlanner; use super::*; use std::marker::PhantomData; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, plonk::{Circuit, ConstraintSystem}, }; use halo2curves::ff::Field; const K: usize = 8; const R: usize = 2048; struct HashCircuit { message: ValTensor<Fp>, } impl Circuit<Fp> for HashCircuit { type Config = PolyCommitConfig; type FloorPlanner = ModulePlanner; type Params = (); fn without_witnesses(&self) -> Self { let empty_val: Vec<ValType<Fp>> = vec![Value::<Fp>::unknown().into(); R]; let message: Tensor<ValType<Fp>> = empty_val.into_iter().into(); Self { message: message.into(), } } fn configure(meta: &mut ConstraintSystem<Fp>) -> Self::Config { let params = (K, R); PolyCommitChip::configure(meta, params) } fn synthesize( &self, config: Self::Config, mut layouter: impl Layouter<Fp>, ) -> Result<(), Error> { let polycommit_chip = PolyCommitChip::new(config); polycommit_chip.layout( &mut layouter, &[self.message.clone()], 0, &mut HashMap::new(), ); Ok(()) } } #[test] #[ignore] fn polycommit_chip_for_a_range_of_input_sizes() { let rng = rand::rngs::OsRng; #[cfg(not(target_arch = "wasm32"))] env_logger::init(); { let i = 32; // print a bunch of new lines println!( "i is {} -------------------------------------------------", i ); let message: Vec<Fp> = (0..i).map(|_| Fp::random(rng)).collect::<Vec<_>>(); let mut message: Tensor<ValType<Fp>> = message.into_iter().map(|m| Value::known(m).into()).into(); let circuit = HashCircuit { message: message.into(), }; let prover = halo2_proofs::dev::MockProver::run(K as u32, &circuit, vec![]).unwrap(); assert_eq!(prover.verify(), Ok(())) } } #[test] #[ignore] fn polycommit_chip_much_longer_input() { #[cfg(not(target_arch = "wasm32"))] env_logger::init(); let rng = rand::rngs::OsRng; let mut message: Vec<Fp> = (0..2048).map(|_| Fp::random(rng)).collect::<Vec<_>>(); let mut message: Tensor<ValType<Fp>> = message.into_iter().map(|m| Value::known(m).into()).into(); let circuit = HashCircuit { message: message.into(), }; let prover = halo2_proofs::dev::MockProver::run(K as u32, &circuit, vec![]).unwrap(); assert_eq!(prover.verify(), Ok(())) } }
https://github.com/zkonduit/ezkl
src/circuit/modules/poseidon.rs
/* An easy-to-use implementation of the Poseidon Hash in the form of a Halo2 Chip. While the Poseidon Hash function is already implemented in halo2_gadgets, there is no wrapper chip that makes it easy to use in other circuits. Thanks to https://github.com/summa-dev/summa-solvency/blob/master/src/chips/poseidon/hash.rs for the inspiration (and also helping us understand how to use this). */ pub mod poseidon_params; pub mod spec; // This chip adds a set of advice columns to the gadget Chip to store the inputs of the hash use halo2_gadgets::poseidon::{primitives::*, Hash, Pow5Chip, Pow5Config}; use halo2_proofs::arithmetic::Field; use halo2_proofs::halo2curves::bn256::Fr as Fp; use halo2_proofs::{circuit::*, plonk::*}; // use maybe_rayon::prelude::{IndexedParallelIterator, IntoParallelRefIterator}; use maybe_rayon::prelude::ParallelIterator; use maybe_rayon::slice::ParallelSlice; use std::marker::PhantomData; use crate::circuit::region::ConstantsMap; use crate::tensor::{Tensor, ValTensor, ValType}; use super::Module; /// The number of instance columns used by the Poseidon hash function pub const NUM_INSTANCE_COLUMNS: usize = 1; #[derive(Debug, Clone)] /// WIDTH, RATE and L are const generics for the struct, which represent the width, rate, and number of inputs for the Poseidon hash function, respectively. /// This means they are values that are known at compile time and can be used to specialize the implementation of the struct. /// The actual chip provided by halo2_gadgets is added to the parent Chip. pub struct PoseidonConfig<const WIDTH: usize, const RATE: usize> { /// pub hash_inputs: Vec<Column<Advice>>, /// pub instance: Option<Column<Instance>>, /// pub pow5_config: Pow5Config<Fp, WIDTH, RATE>, } type InputAssignments = (Vec<AssignedCell<Fp, Fp>>, AssignedCell<Fp, Fp>); /// PoseidonChip is a wrapper around the Pow5Chip that adds a set of advice columns to the gadget Chip to store the inputs of the hash #[derive(Debug, Clone)] pub struct PoseidonChip< S: Spec<Fp, WIDTH, RATE> + Sync, const WIDTH: usize, const RATE: usize, const L: usize, > { config: PoseidonConfig<WIDTH, RATE>, _marker: PhantomData<S>, } impl<S: Spec<Fp, WIDTH, RATE> + Sync, const WIDTH: usize, const RATE: usize, const L: usize> PoseidonChip<S, WIDTH, RATE, L> { /// Creates a new PoseidonChip pub fn configure_with_cols( meta: &mut ConstraintSystem<Fp>, partial_sbox: Column<Advice>, rc_a: [Column<Fixed>; WIDTH], rc_b: [Column<Fixed>; WIDTH], hash_inputs: Vec<Column<Advice>>, instance: Option<Column<Instance>>, ) -> PoseidonConfig<WIDTH, RATE> { let pow5_config = Pow5Chip::configure::<S>( meta, hash_inputs.clone().try_into().unwrap(), partial_sbox, rc_a, rc_b, ); PoseidonConfig { pow5_config, instance, hash_inputs, } } } impl<S: Spec<Fp, WIDTH, RATE> + Sync, const WIDTH: usize, const RATE: usize, const L: usize> PoseidonChip<S, WIDTH, RATE, L> { /// Configuration of the PoseidonChip pub fn configure_with_optional_instance( meta: &mut ConstraintSystem<Fp>, instance: Option<Column<Instance>>, ) -> PoseidonConfig<WIDTH, RATE> { // instantiate the required columns let hash_inputs = (0..WIDTH).map(|_| meta.advice_column()).collect::<Vec<_>>(); for input in &hash_inputs { meta.enable_equality(*input); } let partial_sbox = meta.advice_column(); let rc_a = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>(); let rc_b = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>(); for input in hash_inputs.iter().take(WIDTH) { meta.enable_equality(*input); } meta.enable_constant(rc_b[0]); Self::configure_with_cols( meta, partial_sbox, rc_a.try_into().unwrap(), rc_b.try_into().unwrap(), hash_inputs, instance, ) } } impl<S: Spec<Fp, WIDTH, RATE> + Sync, const WIDTH: usize, const RATE: usize, const L: usize> Module<Fp> for PoseidonChip<S, WIDTH, RATE, L> { type Config = PoseidonConfig<WIDTH, RATE>; type InputAssignments = InputAssignments; type RunInputs = Vec<Fp>; type Params = (); fn name(&self) -> &'static str { "Poseidon" } fn instance_increment_input(&self) -> Vec<usize> { vec![1] } /// Constructs a new PoseidonChip fn new(config: Self::Config) -> Self { Self { config, _marker: PhantomData, } } /// Configuration of the PoseidonChip fn configure(meta: &mut ConstraintSystem<Fp>, _: Self::Params) -> Self::Config { // instantiate the required columns let hash_inputs = (0..WIDTH).map(|_| meta.advice_column()).collect::<Vec<_>>(); for input in &hash_inputs { meta.enable_equality(*input); } let partial_sbox = meta.advice_column(); let rc_a = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>(); let rc_b = (0..WIDTH).map(|_| meta.fixed_column()).collect::<Vec<_>>(); for input in hash_inputs.iter().take(WIDTH) { meta.enable_equality(*input); } meta.enable_constant(rc_b[0]); let instance = meta.instance_column(); meta.enable_equality(instance); Self::configure_with_cols( meta, partial_sbox, rc_a.try_into().unwrap(), rc_b.try_into().unwrap(), hash_inputs, Some(instance), ) } fn layout_inputs( &self, layouter: &mut impl Layouter<Fp>, message: &[ValTensor<Fp>], constants: &mut ConstantsMap<Fp>, ) -> Result<Self::InputAssignments, Error> { assert_eq!(message.len(), 1); let message = message[0].clone(); let start_time = instant::Instant::now(); let local_constants = constants.clone(); let res = layouter.assign_region( || "load message", |mut region| { let assigned_message: Result<Vec<AssignedCell<Fp, Fp>>, Error> = match &message { ValTensor::Value { inner: v, .. } => v .iter() .enumerate() .map(|(i, value)| { let x = i % WIDTH; let y = i / WIDTH; match value { ValType::Value(v) => region.assign_advice( || format!("load message_{}", i), self.config.hash_inputs[x], y, || *v, ), ValType::PrevAssigned(v) | ValType::AssignedConstant(v, ..) => { Ok(v.clone()) } ValType::Constant(f) => { if local_constants.contains_key(f) { Ok(constants.get(f).unwrap().assigned_cell().ok_or({ log::error!("constant not previously assigned"); Error::Synthesis })?) } else { let res = region.assign_advice_from_constant( || format!("load message_{}", i), self.config.hash_inputs[x], y, *f, )?; constants .insert(*f, ValType::AssignedConstant(res.clone(), *f)); Ok(res) } } e => { log::error!( "wrong input type {:?}, must be previously assigned", e ); Err(Error::Synthesis) } } }) .collect(), ValTensor::Instance { dims, inner: col, idx, initial_offset, .. } => { // this should never ever fail let num_elems = dims[*idx].iter().product::<usize>(); (0..num_elems) .map(|i| { let x = i % WIDTH; let y = i / WIDTH; region.assign_advice_from_instance( || "pub input anchor", *col, initial_offset + i, self.config.hash_inputs[x], y, ) }) .collect() } }; let offset = message.len() / WIDTH + 1; let zero_val = region .assign_advice_from_constant( || "", self.config.hash_inputs[0], offset, Fp::ZERO, ) .unwrap(); Ok((assigned_message?, zero_val)) }, ); log::trace!( "input (N={:?}) layout took: {:?}", message.len(), start_time.elapsed() ); res } /// L is the number of inputs to the hash function /// Takes the cells containing the input values of the hash function and return the cell containing the hash output /// It uses the pow5_chip to compute the hash fn layout( &self, layouter: &mut impl Layouter<Fp>, input: &[ValTensor<Fp>], row_offset: usize, constants: &mut ConstantsMap<Fp>, ) -> Result<ValTensor<Fp>, Error> { let (mut input_cells, zero_val) = self.layout_inputs(layouter, input, constants)?; // extract the values from the input cells let mut assigned_input: Tensor<ValType<Fp>> = input_cells.iter().map(|e| ValType::from(e.clone())).into(); let len = assigned_input.len(); let start_time = instant::Instant::now(); let mut one_iter = false; // do the Tree dance baby while input_cells.len() > 1 || !one_iter { let hashes: Result<Vec<AssignedCell<Fp, Fp>>, Error> = input_cells .chunks(L) .enumerate() .map(|(i, block)| { let _start_time = instant::Instant::now(); let mut block = block.to_vec(); let remainder = block.len() % L; if remainder != 0 { block.extend(vec![zero_val.clone(); L - remainder]); } let pow5_chip = Pow5Chip::construct(self.config.pow5_config.clone()); // initialize the hasher let hasher = Hash::<_, _, S, ConstantLength<L>, WIDTH, RATE>::init( pow5_chip, layouter.namespace(|| "block_hasher"), )?; let hash = hasher.hash( layouter.namespace(|| "hash"), block.to_vec().try_into().map_err(|_| Error::Synthesis)?, ); if i == 0 { log::trace!("block (L={:?}) took: {:?}", L, _start_time.elapsed()); } hash }) .collect(); log::trace!("hashes (N={:?}) took: {:?}", len, start_time.elapsed()); one_iter = true; input_cells = hashes?; } let duration = start_time.elapsed(); log::trace!("layout (N={:?}) took: {:?}", len, duration); let result = Tensor::from(input_cells.iter().map(|e| ValType::from(e.clone()))); let output = match result[0].clone() { ValType::PrevAssigned(v) => v, _ => { log::error!("wrong input type, must be previously assigned"); return Err(Error::Synthesis); } }; if let Some(instance) = self.config.instance { layouter.assign_region( || "constrain output", |mut region| { let expected_var = region.assign_advice_from_instance( || "pub input anchor", instance, row_offset, self.config.hash_inputs[0], 0, )?; region.constrain_equal(output.cell(), expected_var.cell()) }, )?; assigned_input.reshape(input[0].dims()).map_err(|e| { log::error!("reshape failed: {:?}", e); Error::Synthesis })?; Ok(assigned_input.into()) } else { Ok(result.into()) } } /// fn run(message: Vec<Fp>) -> Result<Vec<Vec<Fp>>, Box<dyn std::error::Error>> { let mut hash_inputs = message; let len = hash_inputs.len(); let start_time = instant::Instant::now(); let mut one_iter = false; // do the Tree dance baby while hash_inputs.len() > 1 || !one_iter { let hashes: Vec<Fp> = hash_inputs .par_chunks(L) .map(|block| { let mut block = block.to_vec(); let remainder = block.len() % L; if remainder != 0 { block.extend(vec![Fp::ZERO; L - remainder].iter()); } let message = block.try_into().map_err(|_| Error::Synthesis)?; Ok(halo2_gadgets::poseidon::primitives::Hash::< _, S, ConstantLength<L>, { WIDTH }, { RATE }, >::init() .hash(message)) }) .collect::<Result<Vec<_>, Error>>()?; one_iter = true; hash_inputs = hashes; } let duration = start_time.elapsed(); log::trace!("run (N={:?}) took: {:?}", len, duration); Ok(vec![hash_inputs]) } fn num_rows(mut input_len: usize) -> usize { // this was determined by running the circuit and looking at the number of constraints // in the test called hash_for_a_range_of_input_sizes, then regressing in python to find the slope let fixed_cost: usize = 41 * L; let mut num_rows = 0; loop { // the number of times the input_len is divisible by L let num_chunks = input_len / L + 1; num_rows += num_chunks * fixed_cost; if num_chunks == 1 { break; } input_len = num_chunks; } num_rows } } #[allow(unused)] mod tests { use crate::circuit::modules::ModulePlanner; use super::{ spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH}, *, }; use std::{collections::HashMap, marker::PhantomData}; use halo2_gadgets::poseidon::primitives::Spec; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, plonk::{Circuit, ConstraintSystem}, }; use halo2curves::ff::Field; const WIDTH: usize = POSEIDON_WIDTH; const RATE: usize = POSEIDON_RATE; const R: usize = 240; struct HashCircuit<S: Spec<Fp, WIDTH, RATE>, const L: usize> { message: ValTensor<Fp>, _spec: PhantomData<S>, } impl<S: Spec<Fp, WIDTH, RATE>, const L: usize> Circuit<Fp> for HashCircuit<S, L> { type Config = PoseidonConfig<WIDTH, RATE>; type FloorPlanner = ModulePlanner; type Params = (); fn without_witnesses(&self) -> Self { let empty_val: Vec<ValType<Fp>> = vec![Value::<Fp>::unknown().into()]; let message: Tensor<ValType<Fp>> = empty_val.into_iter().into(); Self { message: message.into(), _spec: PhantomData, } } fn configure(meta: &mut ConstraintSystem<Fp>) -> PoseidonConfig<WIDTH, RATE> { PoseidonChip::<PoseidonSpec, WIDTH, RATE, L>::configure(meta, ()) } fn synthesize( &self, config: PoseidonConfig<WIDTH, RATE>, mut layouter: impl Layouter<Fp>, ) -> Result<(), Error> { let chip: PoseidonChip<PoseidonSpec, WIDTH, RATE, L> = PoseidonChip::new(config); chip.layout( &mut layouter, &[self.message.clone()], 0, &mut HashMap::new(), )?; Ok(()) } } #[test] fn poseidon_hash() { let rng = rand::rngs::OsRng; let message = [Fp::random(rng), Fp::random(rng)]; let output = PoseidonChip::<PoseidonSpec, WIDTH, RATE, 2>::run(message.to_vec()).unwrap(); let mut message: Tensor<ValType<Fp>> = message.into_iter().map(|m| Value::known(m).into()).into(); let k = 9; let circuit = HashCircuit::<PoseidonSpec, 2> { message: message.into(), _spec: PhantomData, }; let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap(); assert_eq!(prover.verify(), Ok(())) } #[test] fn poseidon_hash_longer_input() { let rng = rand::rngs::OsRng; let message = [Fp::random(rng), Fp::random(rng), Fp::random(rng)]; let output = PoseidonChip::<PoseidonSpec, WIDTH, RATE, 3>::run(message.to_vec()).unwrap(); let mut message: Tensor<ValType<Fp>> = message.into_iter().map(|m| Value::known(m).into()).into(); let k = 9; let circuit = HashCircuit::<PoseidonSpec, 3> { message: message.into(), _spec: PhantomData, }; let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap(); assert_eq!(prover.verify(), Ok(())) } #[test] #[ignore] fn hash_for_a_range_of_input_sizes() { let rng = rand::rngs::OsRng; #[cfg(not(target_arch = "wasm32"))] env_logger::init(); { let i = 32; // print a bunch of new lines println!( "i is {} -------------------------------------------------", i ); let message: Vec<Fp> = (0..i).map(|_| Fp::random(rng)).collect::<Vec<_>>(); let output = PoseidonChip::<PoseidonSpec, WIDTH, RATE, 32>::run(message.clone()).unwrap(); let mut message: Tensor<ValType<Fp>> = message.into_iter().map(|m| Value::known(m).into()).into(); let k = 17; let circuit = HashCircuit::<PoseidonSpec, 32> { message: message.into(), _spec: PhantomData, }; let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap(); assert_eq!(prover.verify(), Ok(())) } } #[test] #[ignore] fn poseidon_hash_much_longer_input() { let rng = rand::rngs::OsRng; let mut message: Vec<Fp> = (0..2048).map(|_| Fp::random(rng)).collect::<Vec<_>>(); let output = PoseidonChip::<PoseidonSpec, WIDTH, RATE, 25>::run(message.clone()).unwrap(); let mut message: Tensor<ValType<Fp>> = message.into_iter().map(|m| Value::known(m).into()).into(); let k = 17; let circuit = HashCircuit::<PoseidonSpec, 25> { message: message.into(), _spec: PhantomData, }; let prover = halo2_proofs::dev::MockProver::run(k, &circuit, output).unwrap(); assert_eq!(prover.verify(), Ok(())) } }
https://github.com/zkonduit/ezkl
src/circuit/modules/poseidon/poseidon_params.rs
//! This file was generated by running generate_params.py //! Number of round constants: 340 //! Round constants for GF(p): //! Parameters for using rate 4 Poseidon with the BN256 field. //! The parameters can be reproduced by running the following Sage script from //! [this repository](https://github.com/daira/pasta-hadeshash): //! //! ```text //! $ sage generate_parameters_grain.sage 1 0 254 5 8 60 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 --rust //! ``` //! //! where 1 means "prime field", 0 means "non-negative sbox", 254 is the bitsize //! of the field, 5 is the Poseidon width (rate + 1), 8 is the number of full //! rounds, 60 is the number of partial rounds. //! More info here => <https://hackmd.io/@letargicus/SJOvx48Nn> use halo2_proofs::halo2curves::bn256::Fr as Fp; pub(crate) const ROUND_CONSTANTS: [[Fp; 2]; 64] = [ [ Fp::from_raw([ 0x6c7d_c0db_d0ab_d7a7, 0xa71a_a177_534c_dd1b, 0xfe1f_aaba_294c_ba38, 0x09c4_6e9e_c68e_9bd4, ]), Fp::from_raw([ 0x3c1d_83ff_a604_cb81, 0xc514_2b3a_e405_b834, 0x2a97_ed93_7f31_35cf, 0x0c03_5653_0896_eec4, ]), ], [ Fp::from_raw([ 0x317e_a977_cc15_4a30, 0xa00e_a5aa_bd62_68bd, 0x142e_5118_2bb5_4cf4, 0x1e28_a1d9_3569_8ad1, ]), Fp::from_raw([ 0x4cf9_e2b1_2b91_251f, 0x0e57_57c3_e008_db96, 0x0809_65db_30e2_98e4, 0x27af_2d83_1a9d_2748, ]), ], [ Fp::from_raw([ 0x79aa_f435_45b7_4e03, 0x4129_1462_f214_cd08, 0x3a6a_3cfe_16ae_175a, 0x1e6f_11ce_60fc_8f51, ]), Fp::from_raw([ 0xf719_2062_68d1_42d3, 0x0446_2ed1_4c36_13d8, 0x8541_819c_b681_f0be, 0x2a67_384d_3bbd_5e43, ]), ], [ Fp::from_raw([ 0x3640_8f5d_5c9f_45d0, 0xb985_e381_f025_1889, 0x1609_f8e1_2fbf_ecf0, 0x0b66_fdf3_5609_3a61, ]), Fp::from_raw([ 0xdaa6_852d_bdb0_9e21, 0x0b26_c83c_c5ce_beed, 0x830c_6109_3c2a_de37, 0x012e_e3ec_1e78_d470, ]), ], [ Fp::from_raw([ 0x2d10_8e7b_445b_b1b9, 0x6cd1_c431_b099_b6bb, 0xfd88_f67f_8175_e3fd, 0x0252_ba5f_6760_bfbd, ]), Fp::from_raw([ 0xef5a_eaad_7ca9_32f1, 0x5439_1a89_35ff_71d6, 0x6c6b_ec3c_ef54_2963, 0x1794_74cc_eca5_ff67, ]), ], [ Fp::from_raw([ 0x7e1a_2589_bbed_2b91, 0x9c1f_974a_2649_69b3, 0x9228_ff4a_503f_d4ed, 0x2c24_2613_79a5_1bfa, ]), Fp::from_raw([ 0x53e6_6c05_5180_1b05, 0xc2f6_3f50_01fc_0fc5, 0xac2f_288b_d069_5b43, 0x1cc1_d7b6_2692_e63e, ]), ], [ Fp::from_raw([ 0x5d9e_ff5f_d9c9_1b56, 0x0078_4dbf_17fb_acd0, 0xb2ed_55f8_5297_9e96, 0x2550_5930_1aad_a98b, ]), Fp::from_raw([ 0xb11c_29ce_7e59_efd9, 0xaea2_4234_970a_8193, 0x79e1_f5c0_eccd_32b3, 0x2843_7be3_ac1c_b2e4, ]), ], [ Fp::from_raw([ 0x3387_62c3_7f5f_2043, 0x1854_8da8_fb4f_78d4, 0x1ca4_fa6b_5376_6eb1, 0x2821_6a44_2f2e_1f71, ]), Fp::from_raw([ 0x131f_2377_3234_82c9, 0xeee1_efce_0309_4581, 0x1f39_f4e7_056d_d03f, 0x2c1f_47cd_17fa_5adf, ]), ], [ Fp::from_raw([ 0x646b_8566_a621_afc9, 0xd9da_fca2_7663_8a63, 0x8632_bcc9_356c_eb7d, 0x07ab_ad02_b7a5_ebc4, ]), Fp::from_raw([ 0x37da_0c4d_15f9_6c3c, 0x9429_f908_80a6_9cd1, 0x275b_33ff_aab5_1dfe, 0x0230_2646_01ff_df29, ]), ], [ Fp::from_raw([ 0x717e_5d66_899a_a0a9, 0xa864_4145_57ee_289e, 0xa0f1_6865_6497_ca40, 0x1bc9_7305_4e51_d905, ]), Fp::from_raw([ 0x2a6b_2228_8f0a_67fc, 0xd249_aff5_c2d8_421f, 0x206c_3157_e863_41ed, 0x2e1c_22f9_6443_5008, ]), ], [ Fp::from_raw([ 0xa704_52bc_2bba_86b8, 0x9e8e_a159_8e46_c9f7, 0x121c_1d5f_461b_bc50, 0x1224_f38d_f67c_5378, ]), Fp::from_raw([ 0x69d2_9891_86cd_e20e, 0xd7bf_e8cd_9dfe_da19, 0x9280_b4bd_9ed0_068f, 0x02e4_e69d_8ba5_9e51, ]), ], [ Fp::from_raw([ 0x6d47_e973_5d98_018e, 0x4f19_ee36_4e65_3f07, 0x7f5d_f81f_c04f_f3ee, 0x1f1e_ccc3_4aab_a013, ]), Fp::from_raw([ 0xeacb_8a4d_4284_f582, 0x1424_4480_32cd_1819, 0x7426_6c30_39a9_a731, 0x1672_ad3d_709a_3539, ]), ], [ Fp::from_raw([ 0x1d2e_d602_df8c_8fc7, 0xcda6_961f_284d_2499, 0x56f4_4af5_192b_4ae9, 0x283e_3fdc_2c6e_420c, ]), Fp::from_raw([ 0x614f_bd69_ff39_4bcc, 0x6837_51f8_fdff_59d6, 0xd0db_0957_170f_a013, 0x1c2a_3d12_0c55_0ecf, ]), ], [ Fp::from_raw([ 0x96cb_6b81_7765_3fbd, 0x143a_9a43_773e_a6f2, 0xf789_7a73_2345_6efe, 0x216f_8487_7aac_6172, ]), Fp::from_raw([ 0x11a1_f515_52f9_4788, 0xceaa_47ea_61ca_59a4, 0x64ba_7e8e_3e28_d12b, 0x2c0d_272b_ecf2_a757, ]), ], [ Fp::from_raw([ 0xcb4a_6c3d_8954_6f43, 0x170a_5480_abe0_508f, 0x484e_e7a7_4c45_4e9f, 0x16e3_4299_865c_0e28, ]), Fp::from_raw([ 0x48cd_9397_5548_8fc5, 0x7720_4776_5802_290f, 0x375a_232a_6fb9_cc71, 0x175c_eba5_99e9_6f5b, ]), ], [ Fp::from_raw([ 0xd8c5_ffbb_44a1_ee32, 0x6aa4_10bf_bc35_4f54, 0xfead_9e17_58b0_2806, 0x0c75_9444_0dc4_8c16, ]), Fp::from_raw([ 0x9247_9882_d919_fd8d, 0x760e_2001_3ccf_912c, 0xc466_db7d_7eb6_fd8f, 0x1a3c_29bc_39f2_1bb5, ]), ], [ Fp::from_raw([ 0x95c8_eeab_cd22_e68f, 0x0855_d349_074f_5a66, 0xc098_6ea0_49b2_5340, 0x0ccf_dd90_6f34_26e5, ]), Fp::from_raw([ 0xe0e6_99b6_7dd9_e796, 0x66a7_a8a3_fd06_5b3c, 0x2bdb_475c_e6c9_4118, 0x14f6_bc81_d9f1_86f6, ]), ], [ Fp::from_raw([ 0x88ed_eb73_86b9_7052, 0xcc09_9810_c9c4_95c8, 0x9702_ca70_b2f6_c5aa, 0x0962_b827_89fb_3d12, ]), Fp::from_raw([ 0xafef_0c8f_6a31_a86d, 0x1328_4ab0_1ef0_2575, 0xbf20_c79d_e251_27bc, 0x1a88_0af7_074d_18b3, ]), ], [ Fp::from_raw([ 0x4c30_12bb_7ae9_311b, 0x20af_2924_fc20_ff3f, 0xcd5e_77f0_211c_154b, 0x10cb_a184_19a6_a332, ]), Fp::from_raw([ 0x756a_2849_f302_f10d, 0xfa27_b731_9cae_3406, 0xbdc7_6ba6_3a9e_aca8, 0x057e_62a9_a8f8_9b3e, ]), ], [ Fp::from_raw([ 0xafa0_413b_4428_0cee, 0xb961_303b_bf65_cff5, 0xd44a_df53_84b4_988c, 0x287c_971d_e91d_c0ab, ]), Fp::from_raw([ 0x6f7f_7960_e306_891d, 0x1e56_2bc4_6d4a_ba4e, 0xb3bc_a9da_0cca_908f, 0x21df_3388_af16_87bb, ]), ], [ Fp::from_raw([ 0x3eff_8b56_0e16_82b3, 0x789d_f8f7_0b49_8fd8, 0x3e25_cc97_4d09_34cd, 0x1be5_c887_d25b_ce70, ]), Fp::from_raw([ 0x48d5_9c27_06a0_d5c1, 0xd2cb_5d42_fda5_acea, 0x6811_7175_cea2_cd0d, 0x268d_a36f_76e5_68fb, ]), ], [ Fp::from_raw([ 0xbd06_460c_c26a_5ed6, 0xc5d8_bb74_135e_bd05, 0xc609_beaf_5510_ecec, 0x0e17_ab09_1f6e_ae50, ]), Fp::from_raw([ 0x040f_5caa_1f62_af40, 0x91ef_62d8_cf83_d270, 0x7aee_535a_b074_a430, 0x04d7_27e7_28ff_a0a6, ]), ], [ Fp::from_raw([ 0x2b15_417d_7e39_ca6e, 0x3370_2ac1_0f1b_fd86, 0x81b5_4976_2bc0_22ed, 0x0ddb_d7bf_9c29_3415, ]), Fp::from_raw([ 0x8a29_c49c_8789_654b, 0x34f5_b0d1_d3af_9b58, 0x7681_62e8_2989_c6c2, 0x2790_eb33_5162_1752, ]), ], [ Fp::from_raw([ 0x84b7_6420_6142_f9e9, 0x395f_3d9a_b8b2_fd09, 0x4471_9501_93d8_a570, 0x1e45_7c60_1a63_b73e, ]), Fp::from_raw([ 0xc4c6_86fc_46e0_91b0, 0xfa90_ecd0_c43f_f91f, 0x638d_6ab2_bbe7_135f, 0x21ae_6430_1dca_9625, ]), ], [ Fp::from_raw([ 0x5858_534e_ed8d_350b, 0x854b_e9e3_432e_0955, 0x4da2_9316_6f49_4928, 0x0379_f63c_8ce3_468d, ]), Fp::from_raw([ 0x8c9f_58a3_24c3_5049, 0xca0e_4921_a466_86ac, 0x6a74_4a08_0809_e054, 0x002d_5642_0359_d026, ]), ], [ Fp::from_raw([ 0x0fc2_c5af_9635_15a6, 0xda8d_6245_9e21_f409, 0x1d68_b3cd_32e1_0bbe, 0x1231_58e5_965b_5d9b, ]), Fp::from_raw([ 0x60c8_0eb4_9cad_9ec1, 0x0fbb_2b6f_5283_6d4e, 0x661d_14bb_f6cb_e042, 0x0be2_9fc4_0847_a941, ]), ], [ Fp::from_raw([ 0x2338_02f2_4fdf_4c1a, 0x36db_9d85_9cad_5f9a, 0x5771_6142_015a_453c, 0x1ac9_6991_dec2_bb05, ]), Fp::from_raw([ 0x51ca_3355_bcb0_627e, 0x5e12_c9fa_97f1_8a92, 0x5f49_64fc_61d2_3b3e, 0x1596_443f_763d_bcc2, ]), ], [ Fp::from_raw([ 0xd6d0_49ea_e3ba_3212, 0xf185_7d9f_17e7_15ae, 0x6b28_61d4_ec3a_eae0, 0x12e0_bcd3_654b_dfa7, ]), Fp::from_raw([ 0x04e6_c76c_7cf9_64ba, 0xceab_ac7f_3715_4b19, 0x9ea7_3d4a_f9af_2a50, 0x0fc9_2b4f_1bbe_a82b, ]), ], [ Fp::from_raw([ 0x9c7e_9652_3387_2762, 0xb14f_7c77_2223_6f4f, 0xd6f2_e592_a801_3f40, 0x1f9c_0b16_1044_6442, ]), Fp::from_raw([ 0x8d15_9f64_3dbb_f4d3, 0x050d_914d_a38b_4c05, 0xf8cd_e061_57a7_82f4, 0x0ebd_7424_4ae7_2675, ]), ], [ Fp::from_raw([ 0x7a83_9839_dccf_c6d1, 0x3b06_71e9_7346_ee39, 0x69a9_fafd_4ab9_51c0, 0x2cb7_f0ed_39e1_6e9f, ]), Fp::from_raw([ 0x90c7_2bca_7352_d9bf, 0xce76_1d05_14ce_5266, 0x5605_443e_e41b_ab20, 0x1a9d_6e2e_cff0_22cc, ]), ], [ Fp::from_raw([ 0x87da_182d_648e_c72f, 0xd0c1_3326_a9a7_ba30, 0x5ea8_3c3b_c44a_9331, 0x2a11_5439_607f_335a, ]), Fp::from_raw([ 0x9535_c115_c5a4_c060, 0xe738_b563_05cd_44f2, 0x15b8_fa7a_ee3e_3410, 0x23f9_b652_9b5d_040d, ]), ], [ Fp::from_raw([ 0x260e_b939_f0e6_e8a7, 0xa3ce_97c1_6d58_b68b, 0x249a_c6ba_484b_b9c3, 0x0587_2c16_db0f_72a2, ]), Fp::from_raw([ 0x2b62_4a7c_dedd_f6a7, 0x0219_b615_1d55_b5c5, 0xca20_fb80_1180_75f4, 0x1300_bdee_08bb_7824, ]), ], [ Fp::from_raw([ 0x072e_4e7b_7d52_b376, 0x8d7a_d299_16d9_8cb1, 0xe638_1786_3a8f_6c28, 0x19b9_b63d_2f10_8e17, ]), Fp::from_raw([ 0x24a2_0128_481b_4f7f, 0x13d1_c887_26b5_ec42, 0xb5bd_a237_6685_22f6, 0x015b_ee13_57e3_c015, ]), ], [ Fp::from_raw([ 0xea92_c785_b128_ffd1, 0xfe1e_1ce4_bab2_18cb, 0x1b97_07a4_f161_5e4e, 0x2953_736e_94bb_6b9f, ]), Fp::from_raw([ 0x4ce7_266e_d660_8dfc, 0x851b_98d3_72b4_5f54, 0x862f_8061_80c0_385f, 0x0b06_9353_ba09_1618, ]), ], [ Fp::from_raw([ 0x4f58_8ac9_7d81_f429, 0x55ae_b7eb_9306_b64e, 0x15e4_e0bc_fb93_817e, 0x304f_74d4_61cc_c131, ]), Fp::from_raw([ 0xb8ee_5415_cde9_13fc, 0xaad2_a164_a461_7a4c, 0xe8a3_3f5e_77df_e4f5, 0x15bb_f146_ce9b_ca09, ]), ], [ Fp::from_raw([ 0xa9ff_2385_9572_c8c6, 0x9b8f_4b85_0405_c10c, 0x4490_1031_4879_64ed, 0x0ab4_dfe0_c274_2cde, ]), Fp::from_raw([ 0x251d_e39f_9639_779a, 0xef5e_edfe_a546_dea9, 0x97f4_5f76_49a1_9675, 0x0e32_db32_0a04_4e31, ]), ], [ Fp::from_raw([ 0xa307_8efa_516d_a016, 0x6797_733a_8277_4896, 0xb276_35a7_8b68_88e6, 0x0a17_56aa_1f37_8ca4, ]), Fp::from_raw([ 0x4254_d6a2_a25d_93ef, 0x95e6_1d32_8f85_efa9, 0x47fd_1717_7f95_2ef8, 0x044c_4a33_b10f_6934, ]), ], [ Fp::from_raw([ 0xd37b_07b5_466c_4b8b, 0xfe08_79d7_9a49_6891, 0xbe65_5b53_7f66_f700, 0x2ed3_611b_725b_8a70, ]), Fp::from_raw([ 0xd833_9ea7_1208_58aa, 0xadfd_eb9c_fdd3_47b5, 0xc8ec_c3d7_22aa_2e0e, 0x1f9b_a4e8_bab7_ce42, ]), ], [ Fp::from_raw([ 0xb740_56f8_65c5_d3da, 0xa38e_82ac_4502_066d, 0x8f7e_e907_a84e_518a, 0x1b23_3043_052e_8c28, ]), Fp::from_raw([ 0xca2f_97b0_2087_5954, 0x9020_53bf_c0f1_4db0, 0x7403_1ab7_2bd5_5b4c, 0x2431_e1cc_164b_b8d0, ]), ], [ Fp::from_raw([ 0xa791_f273_9658_01fd, 0xa13e_3220_9758_3319, 0x30cd_6953_a0a7_db45, 0x082f_934c_91f5_aac3, ]), Fp::from_raw([ 0x9ad6_bb93_0c48_997c, 0xc772_45e2_ae7c_be99, 0xa34b_e074_3155_42a3, 0x2b9a_0a22_3e75_38b0, ]), ], [ Fp::from_raw([ 0xb0b5_89cc_7021_4e7d, 0x8164_163e_75a8_a00e, 0xceb8_5483_b887_a9be, 0x0e1c_d91e_dd2c_fa2c, ]), Fp::from_raw([ 0x88d3_2460_1ceb_e2f9, 0x9977_4f19_854d_00f5, 0xc951_f614_77e3_6989, 0x2e1e_ac0f_2bfd_fd63, ]), ], [ Fp::from_raw([ 0x23d7_4811_5b50_0b83, 0x7345_784d_8efd_b33c, 0x0c76_158e_769d_6d15, 0x0cbf_a95f_37fb_7406, ]), Fp::from_raw([ 0x980c_232d_fa4a_4f84, 0x76d9_91e3_a775_13d9, 0xd65a_d49d_8a61_e9a6, 0x08f0_5b3b_e923_ed44, ]), ], [ Fp::from_raw([ 0x25a2_dd51_0c04_7ef6, 0xe728_4925_dc07_58a3, 0x52bf_8e21_984d_0443, 0x2271_9e2a_070b_cd08, ]), Fp::from_raw([ 0xf41f_62b2_f268_30c0, 0x7bdb_f036_1199_82c0, 0xc060_f7fc_c3a1_ab4c, 0x041f_596a_9ee1_cb2b, ]), ], [ Fp::from_raw([ 0x19fc_dd09_86b1_0f89, 0x021b_e1c2_d0dc_464a, 0x8762_8eb0_6f6b_1d4c, 0x233f_d35d_e1be_520a, ]), Fp::from_raw([ 0xefcb_453c_61c9_c267, 0xd31e_078a_a1b4_707e, 0x4325_e0a4_23eb_c810, 0x0524_b46d_1aa8_7a5e, ]), ], [ Fp::from_raw([ 0xcc44_8623_7c51_5211, 0x4227_bb95_4b0f_3199, 0xce47_fcac_894b_8582, 0x2c34_f424_c81e_5716, ]), Fp::from_raw([ 0xf330_1032_7de4_915e, 0x2dd2_025b_5457_cc97, 0x207e_ffc2_b554_1fb7, 0x0b5f_2a4b_6338_7819, ]), ], [ Fp::from_raw([ 0xaefa_c41f_e05c_659f, 0xc174_35d2_f57a_f6ce, 0xc5b7_2fe4_39d2_cfd6, 0x2220_7856_082c_cc54, ]), Fp::from_raw([ 0x2785_4048_ce2c_8171, 0xcdfb_2101_94ca_f79f, 0x4e24_159b_7f89_50b5, 0x24d5_7a8b_f5da_63fe, ]), ], [ Fp::from_raw([ 0x7391_9bb2_3b79_396e, 0x374a_d709_7bb0_1a85, 0x3b37_1d75_bd69_3f98, 0x0afa_b181_fdd5_e058, ]), Fp::from_raw([ 0xf162_90d6_2b11_28ee, 0x76c0_0571_94c1_6c0b, 0x998a_52ef_ac7c_bd56, 0x2dba_9b10_8f20_8772, ]), ], [ Fp::from_raw([ 0x5aff_13e6_bce4_20b3, 0xcbb8_3de0_bd59_2b25, 0x56f8_81c7_88f5_3f83, 0x2634_9b66_edb8_b16f, ]), Fp::from_raw([ 0x2352_88a3_e6f1_37db, 0xd81a_56d2_8ecc_193b, 0x685e_95f9_2339_753a, 0x25af_7ce0_e5e1_0357, ]), ], [ Fp::from_raw([ 0x1f7c_0187_fe35_011f, 0x70ee_d7aa_e88b_2bff, 0xc094_d6a5_5edd_68b9, 0x25b4_ce7b_d229_4390, ]), Fp::from_raw([ 0x8cb9_d54c_1e02_b631, 0xde9c_ef28_ebdf_30b1, 0x387e_53f1_908a_88e5, 0x22c5_43f1_0f6c_89ec, ]), ], [ Fp::from_raw([ 0xdf66_8e74_882f_87a9, 0x425e_906a_919d_7a34, 0x4fc7_908a_9f19_1e1e, 0x0236_f93e_7789_c472, ]), Fp::from_raw([ 0x9cb4_97af_980c_4b52, 0x652b_dae1_14eb_0165, 0x0e7d_27e3_7d05_da99, 0x2935_0b40_1166_ca01, ]), ], [ Fp::from_raw([ 0xee12_6091_6652_363f, 0x65ed_b75d_844e_bb89, 0x6bd3_1bba_b547_f75a, 0x0eed_787d_6582_0d3f, ]), Fp::from_raw([ 0x1906_f656_f4de_6fad, 0xfdcd_0e99_bd94_297d, 0x036a_753f_520b_3291, 0x07cc_1170_f13b_46f2, ]), ], [ Fp::from_raw([ 0x2059_4356_89e8_acea, 0x9087_86d7_f9f5_d10c, 0xf49b_cf61_3a3d_30b1, 0x22b9_3923_3b1d_7205, ]), Fp::from_raw([ 0xadd6_50ac_e60a_e5a6, 0x740f_083a_5aa8_5438, 0x8aad_1dc8_bc33_e870, 0x0145_1762_a0aa_b81c, ]), ], [ Fp::from_raw([ 0xe704_fec0_892f_ce89, 0xe32e_aa61_dec7_da57, 0x61fa_bf10_25d4_6d1f, 0x2350_6bb5_d872_7d44, ]), Fp::from_raw([ 0x7f8b_d689_0735_5522, 0x2a37_0953_1e1e_fea9, 0xbac0_6ae3_f71b_dd09, 0x2e48_4c44_e838_aea0, ]), ], [ Fp::from_raw([ 0x4541_8da2_6835_b54c, 0xaf4a_5945_45ce_dc25, 0x379e_78c5_0bd2_e42b, 0x0f4b_c7d0_7eba_fd64, ]), Fp::from_raw([ 0xe620_996d_50d8_e74e, 0x5158_2388_725d_f460, 0xfa76_6378_62fa_aee8, 0x1f4d_3c8f_6583_e9e5, ]), ], [ Fp::from_raw([ 0x53eb_9bcb_48fe_7389, 0xfae0_2abc_7b68_1d91, 0x2660_d07b_e0e4_a988, 0x0935_14e0_c707_11f8, ]), Fp::from_raw([ 0x4a58_e0a3_47e1_53d8, 0x43ee_83ec_e472_28f2, 0x4669_9a2b_5f3b_c036, 0x1ada_b0c8_e2b3_bad3, ]), ], [ Fp::from_raw([ 0x1a22_dbef_9e80_dad2, 0x378c_1b94_b807_2bac, 0xd147_09eb_b474_641a, 0x1672_b172_6057_d99d, ]), Fp::from_raw([ 0x30d4_7b23_9b47_9c14, 0xc5d8_e2fa_e0ac_c4ee, 0x8f44_f53f_dcab_468c, 0x1dfd_53d4_576a_f2e3, ]), ], [ Fp::from_raw([ 0xbc7f_2077_5320_5c60, 0xe6d7_7d64_0f6f_c3de, 0xa70a_3626_3a37_e17f, 0x0c68_88a1_0b75_b0f3, ]), Fp::from_raw([ 0x8509_1ecc_a9d1_e508, 0x611a_61e0_0ee6_848b, 0x92b3_4a7e_77d1_2fe8, 0x1add_b933_a65b_e770, ]), ], [ Fp::from_raw([ 0x7935_628e_299d_1791, 0xf638_ff54_25f0_afff, 0x5c10_ae18_d1de_933c, 0x00d7_540d_cd26_8a84, ]), Fp::from_raw([ 0xd316_939d_20b8_2c0e, 0x26fe_dde4_acd9_9db1, 0x01b2_827a_5664_ca9c, 0x140c_0e42_687e_9ead, ]), ], [ Fp::from_raw([ 0xc091_e2ae_5656_5984, 0xc20a_0f9b_24f8_c5ed, 0x91ba_89b8_d13d_1806, 0x2f0c_3a11_5d43_17d1, ]), Fp::from_raw([ 0xd8c5_38a1_dc95_8c61, 0x08a0_cff6_70b2_2b82, 0x3006_ed22_0cf9_c810, 0x0c4e_e778_ff7c_1455, ]), ], [ Fp::from_raw([ 0x27c3_d748_5de7_4c69, 0x9424_ed26_c0ac_c662, 0x3693_f004_40cc_c360, 0x1704_f276_6d46_f82c, ]), Fp::from_raw([ 0x39b6_6fe9_009c_3cfa, 0xf076_9c9f_8544_e402, 0xa7a0_2c1b_51d2_44ab, 0x2f2d_19cc_3ea5_d78e, ]), ], [ Fp::from_raw([ 0xd6c7_66a8_06fc_6629, 0xdd7e_e6cb_9cfe_d9c7, 0x5053_f112_e2a8_e8dc, 0x1ae0_3853_b75f_caba, ]), Fp::from_raw([ 0x4e41_a86d_daf0_56d5, 0x3556_921b_2d6f_014e, 0x51d1_31d0_fa61_aa5f, 0x0971_aabf_7952_41df, ]), ], [ Fp::from_raw([ 0x5f5c_29f7_bfe2_f646, 0xda62_4f83_80df_1c87, 0x91d4_cf6b_6e0d_e73e, 0x1408_c316_e601_4e1a, ]), Fp::from_raw([ 0x4169_1f39_822e_f5bd, 0x6c89_f1f7_73ef_2853, 0x248a_be42_b543_093b, 0x1667_f3fe_2edb_e850, ]), ], [ Fp::from_raw([ 0x424c_6957_6500_fe37, 0x5b81_7184_09e5_c133, 0xa48b_0a03_557c_df91, 0x13bf_7c5d_0d2c_4376, ]), Fp::from_raw([ 0x19bc_0ba7_43a6_2c2c, 0x024b_9534_7856_b797, 0x3016_adf3_d353_3c24, 0x0762_0a6d_fb0b_6cec, ]), ], [ Fp::from_raw([ 0x1675_de3e_1982_b4d0, 0x75d2_959e_2f32_2b73, 0x36a8_ca08_bdbd_d8b0, 0x1574_c7ef_0c43_545f, ]), Fp::from_raw([ 0xc06e_03a7_ff83_78f0, 0x5bd4_1845_71c2_54fd, 0xfd56_7970_a717_ceec, 0x269e_4b5b_7a2e_b21a, ]), ], ]; // n: 254 // t: 5 // N: 1270 // Result Algorithm 1: // [True, 0] // Result Algorithm 2: // [True, None] // Result Algorithm 3: // [True, None] // Prime number: 0x0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 // MDS matrix: pub(crate) const MDS: [[Fp; 2]; 2] = [ [ Fp::from_raw([ 0xbcec_a70b_d2af_7ad5, 0xaf07_f38a_f8c9_52a7, 0xec10_3453_51a2_3a3a, 0x066f_6f85_d6f6_8a85, ]), Fp::from_raw([ 0x0546_2b9f_8125_b1e8, 0x20a7_c02b_bd8b_ea73, 0x7782_e150_9b1d_0fdb, 0x2b9d_4b41_10c9_ae99, ]), ], [ Fp::from_raw([ 0xf573_f431_221f_8ff9, 0xb6c0_9d55_7013_fff1, 0x2bf6_7a44_93cc_262f, 0x0cc5_7cdb_b085_07d6, ]), Fp::from_raw([ 0x21bc_d147_9432_03c8, 0xade8_57e8_6eb5_c3a1, 0xa31a_6ed6_9724_e1ad, 0x1274_e649_a32e_d355, ]), ], ]; // Inverse MDS matrix: pub(crate) const MDS_INV: [[Fp; 2]; 2] = [ [ Fp::from_raw([ 0x8dbe_bd0f_a8c5_3e66, 0x0554_569d_9b29_d1ea, 0x7081_9ab1_c784_6f21, 0x13ab_ec39_0ada_7f43, ]), Fp::from_raw([ 0xaaf6_185b_1a1e_60fe, 0xbd52_1ead_5dfe_0345, 0x4c98_62a1_d97d_1510, 0x1eb9_e1dc_19a3_3a62, ]), ], [ Fp::from_raw([ 0x763f_7875_036b_cb02, 0x8ce5_1690_30a2_ad69, 0x601a_bc49_fdad_4f03, 0x0fc1_c939_4db8_9bb2, ]), Fp::from_raw([ 0x8abc_ed6b_d147_c8be, 0x2b7e_ac34_3459_61bc, 0x9502_054e_dc03_e7b2, 0x16a9_e98c_493a_902b, ]), ], ];
https://github.com/zkonduit/ezkl
src/circuit/modules/poseidon/spec.rs
//! This file was generated by running generate_params.py //! Specification for rate 5 Poseidon using the BN256 curve. //! Patterned after [halo2_gadgets::poseidon::primitives::P128Pow5T3] use halo2_gadgets::poseidon::primitives::*; use halo2_proofs::arithmetic::Field; use halo2_proofs::halo2curves::bn256::Fr as Fp; use super::poseidon_params; /// The specification for the Poseidon hash function. #[derive(Debug, Clone, Copy)] pub struct PoseidonSpec; /// Basically the number of columns allocated within the poseidon chip pub const POSEIDON_WIDTH: usize = 2; /// The number of full SBox rounds pub const POSEIDON_RATE: usize = 1; pub(crate) type Mds<Fp, const T: usize> = [[Fp; T]; T]; impl Spec<Fp, POSEIDON_WIDTH, POSEIDON_RATE> for PoseidonSpec { fn full_rounds() -> usize { 8 } fn partial_rounds() -> usize { 56 } fn sbox(val: Fp) -> Fp { val.pow_vartime([5]) } fn secure_mds() -> usize { unimplemented!() } fn constants() -> ( Vec<[Fp; POSEIDON_WIDTH]>, Mds<Fp, POSEIDON_WIDTH>, Mds<Fp, POSEIDON_WIDTH>, ) { ( poseidon_params::ROUND_CONSTANTS[..].to_vec(), poseidon_params::MDS, poseidon_params::MDS_INV, ) } }
https://github.com/zkonduit/ezkl
src/circuit/ops/base.rs
use crate::tensor::TensorType; use std::{ fmt, ops::{Add, Mul, Neg, Sub}, }; #[allow(missing_docs)] /// An enum representing the operations that can be used to express more complex operations via accumulation #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum BaseOp { Dot, DotInit, CumProdInit, CumProd, Add, Mult, Sub, SumInit, Sum, IsBoolean, } /// Matches a [BaseOp] to an operation over inputs impl BaseOp { /// forward func pub fn nonaccum_f< T: TensorType + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Neg<Output = T>, >( &self, inputs: (T, T), ) -> T { let (a, b) = inputs; match &self { BaseOp::Add => a + b, BaseOp::Sub => a - b, BaseOp::Mult => a * b, BaseOp::IsBoolean => b, _ => panic!("nonaccum_f called on accumulating operation"), } } /// forward func pub fn accum_f< T: TensorType + Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Neg<Output = T>, >( &self, prev_output: T, a: Vec<T>, b: Vec<T>, ) -> T { let zero = T::zero().unwrap(); let one = T::one().unwrap(); match &self { BaseOp::DotInit => a.into_iter().zip(b).fold(zero, |acc, (a, b)| acc + a * b), BaseOp::Dot => prev_output + a.into_iter().zip(b).fold(zero, |acc, (a, b)| acc + a * b), BaseOp::CumProdInit => b.into_iter().fold(one, |acc, b| acc * b), BaseOp::CumProd => prev_output * b.into_iter().fold(one, |acc, b| acc * b), BaseOp::SumInit => b.into_iter().fold(zero, |acc, b| acc + b), BaseOp::Sum => prev_output + b.into_iter().fold(zero, |acc, b| acc + b), _ => panic!("accum_f called on non-accumulating operation"), } } /// display func pub fn as_str(&self) -> &'static str { match self { BaseOp::Dot => "DOT", BaseOp::DotInit => "DOTINIT", BaseOp::CumProdInit => "CUMPRODINIT", BaseOp::CumProd => "CUMPROD", BaseOp::Add => "ADD", BaseOp::Sub => "SUB", BaseOp::Mult => "MULT", BaseOp::Sum => "SUM", BaseOp::SumInit => "SUMINIT", BaseOp::IsBoolean => "ISBOOLEAN", } } /// Returns the range of the query offset for this operation. pub fn query_offset_rng(&self) -> (i32, usize) { match self { BaseOp::DotInit => (0, 1), BaseOp::Dot => (-1, 2), BaseOp::CumProd => (-1, 2), BaseOp::CumProdInit => (0, 1), BaseOp::Add => (0, 1), BaseOp::Sub => (0, 1), BaseOp::Mult => (0, 1), BaseOp::Sum => (-1, 2), BaseOp::SumInit => (0, 1), BaseOp::IsBoolean => (0, 1), } } /// Returns the number of inputs for this operation. pub fn num_inputs(&self) -> usize { match self { BaseOp::DotInit => 2, BaseOp::Dot => 2, BaseOp::CumProdInit => 1, BaseOp::CumProd => 1, BaseOp::Add => 2, BaseOp::Sub => 2, BaseOp::Mult => 2, BaseOp::Sum => 1, BaseOp::SumInit => 1, BaseOp::IsBoolean => 0, } } /// Returns the number of outputs for this operation. pub fn constraint_idx(&self) -> usize { match self { BaseOp::DotInit => 0, BaseOp::Dot => 1, BaseOp::Add => 0, BaseOp::Sub => 0, BaseOp::Mult => 0, BaseOp::Sum => 1, BaseOp::SumInit => 0, BaseOp::CumProd => 1, BaseOp::CumProdInit => 0, BaseOp::IsBoolean => 0, } } } impl fmt::Display for BaseOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } }
https://github.com/zkonduit/ezkl
src/circuit/ops/chip.rs
use std::str::FromStr; use thiserror::Error; use halo2_proofs::{ circuit::Layouter, plonk::{ConstraintSystem, Constraints, Expression, Selector}, poly::Rotation, }; use log::debug; #[cfg(feature = "python-bindings")] use pyo3::{ conversion::{FromPyObject, PyTryFrom}, exceptions::PyValueError, prelude::*, types::PyString, }; use serde::{Deserialize, Serialize}; use tosubcommand::ToFlags; use crate::{ circuit::{ ops::base::BaseOp, table::{Range, RangeCheck, Table}, utils, }, tensor::{Tensor, TensorType, ValTensor, VarTensor}, }; use std::{collections::BTreeMap, error::Error, marker::PhantomData}; use super::{lookup::LookupOp, region::RegionCtx, Op}; use halo2curves::ff::{Field, PrimeField}; /// circuit related errors. #[derive(Debug, Error)] pub enum CircuitError { /// Shape mismatch in circuit construction #[error("dimension mismatch in circuit construction for op: {0}")] DimMismatch(String), /// Error when instantiating lookup tables #[error("failed to instantiate lookup tables")] LookupInstantiation, /// A lookup table was was already assigned #[error("attempting to initialize an already instantiated lookup table")] TableAlreadyAssigned, /// This operation is unsupported #[error("unsupported operation in graph")] UnsupportedOp, /// #[error("invalid einsum expression")] InvalidEinsum, } #[allow(missing_docs)] /// An enum representing activating the sanity checks we can perform on the accumulated arguments #[derive( Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default, Copy, )] pub enum CheckMode { #[default] SAFE, UNSAFE, } impl std::fmt::Display for CheckMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { CheckMode::SAFE => write!(f, "safe"), CheckMode::UNSAFE => write!(f, "unsafe"), } } } impl ToFlags for CheckMode { /// Convert the struct to a subcommand string fn to_flags(&self) -> Vec<String> { vec![format!("{}", self)] } } impl From<String> for CheckMode { fn from(value: String) -> Self { match value.to_lowercase().as_str() { "safe" => CheckMode::SAFE, "unsafe" => CheckMode::UNSAFE, _ => { log::error!("Invalid value for CheckMode"); log::warn!("defaulting to SAFE"); CheckMode::SAFE } } } } #[allow(missing_docs)] /// An enum representing the tolerance we can accept for the accumulated arguments, either absolute or percentage #[derive(Clone, Default, Debug, PartialEq, PartialOrd, Serialize, Deserialize, Copy)] pub struct Tolerance { pub val: f32, pub scale: utils::F32, } impl std::fmt::Display for Tolerance { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:.2}", self.val) } } impl ToFlags for Tolerance { /// Convert the struct to a subcommand string fn to_flags(&self) -> Vec<String> { vec![format!("{}", self)] } } impl FromStr for Tolerance { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { if let Ok(val) = s.parse::<f32>() { Ok(Tolerance { val, scale: utils::F32(1.0), }) } else { Err( "Invalid tolerance value provided. It should expressed as a percentage (f32)." .to_string(), ) } } } impl From<f32> for Tolerance { fn from(value: f32) -> Self { Tolerance { val: value, scale: utils::F32(1.0), } } } #[cfg(feature = "python-bindings")] /// Converts CheckMode into a PyObject (Required for CheckMode to be compatible with Python) impl IntoPy<PyObject> for CheckMode { fn into_py(self, py: Python) -> PyObject { match self { CheckMode::SAFE => "safe".to_object(py), CheckMode::UNSAFE => "unsafe".to_object(py), } } } #[cfg(feature = "python-bindings")] /// Obtains CheckMode from PyObject (Required for CheckMode to be compatible with Python) impl<'source> FromPyObject<'source> for CheckMode { fn extract(ob: &'source PyAny) -> PyResult<Self> { let trystr = <PyString as PyTryFrom>::try_from(ob)?; let strval = trystr.to_string(); match strval.to_lowercase().as_str() { "safe" => Ok(CheckMode::SAFE), "unsafe" => Ok(CheckMode::UNSAFE), _ => Err(PyValueError::new_err("Invalid value for CheckMode")), } } } #[cfg(feature = "python-bindings")] /// Converts Tolerance into a PyObject (Required for Tolerance to be compatible with Python) impl IntoPy<PyObject> for Tolerance { fn into_py(self, py: Python) -> PyObject { (self.val, self.scale.0).to_object(py) } } #[cfg(feature = "python-bindings")] /// Obtains Tolerance from PyObject (Required for Tolerance to be compatible with Python) impl<'source> FromPyObject<'source> for Tolerance { fn extract(ob: &'source PyAny) -> PyResult<Self> { if let Ok((val, scale)) = ob.extract::<(f32, f32)>() { Ok(Tolerance { val, scale: utils::F32(scale), }) } else { Err(PyValueError::new_err("Invalid tolerance value provided. ")) } } } /// A struct representing the selectors for the dynamic lookup tables #[derive(Clone, Debug, Default)] pub struct DynamicLookups { /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops. pub lookup_selectors: BTreeMap<(usize, usize), Selector>, /// Selectors for the dynamic lookup tables pub table_selectors: Vec<Selector>, /// Inputs: pub inputs: Vec<VarTensor>, /// tables pub tables: Vec<VarTensor>, } impl DynamicLookups { /// Returns a new [DynamicLookups] with no inputs, no selectors, and no tables. pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self { let dummy_var = VarTensor::dummy(col_size, num_inner_cols); let single_col_dummy_var = VarTensor::dummy(col_size, 1); Self { lookup_selectors: BTreeMap::new(), table_selectors: vec![], inputs: vec![dummy_var.clone(), dummy_var.clone(), dummy_var.clone()], tables: vec![ single_col_dummy_var.clone(), single_col_dummy_var.clone(), single_col_dummy_var.clone(), ], } } } /// A struct representing the selectors for the dynamic lookup tables #[derive(Clone, Debug, Default)] pub struct Shuffles { /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops. pub input_selectors: BTreeMap<(usize, usize), Selector>, /// Selectors for the dynamic lookup tables pub reference_selectors: Vec<Selector>, /// Inputs: pub inputs: Vec<VarTensor>, /// tables pub references: Vec<VarTensor>, } impl Shuffles { /// Returns a new [DynamicLookups] with no inputs, no selectors, and no tables. pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self { let dummy_var = VarTensor::dummy(col_size, num_inner_cols); let single_col_dummy_var = VarTensor::dummy(col_size, 1); Self { input_selectors: BTreeMap::new(), reference_selectors: vec![], inputs: vec![dummy_var.clone(), dummy_var.clone()], references: vec![single_col_dummy_var.clone(), single_col_dummy_var.clone()], } } } /// A struct representing the selectors for the static lookup tables #[derive(Clone, Debug, Default)] pub struct StaticLookups<F: PrimeField + TensorType + PartialOrd> { /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops. pub selectors: BTreeMap<(LookupOp, usize, usize), Selector>, /// Selectors for the dynamic lookup tables pub tables: BTreeMap<LookupOp, Table<F>>, /// pub index: VarTensor, /// pub output: VarTensor, /// pub input: VarTensor, } impl<F: PrimeField + TensorType + PartialOrd> StaticLookups<F> { /// Returns a new [StaticLookups] with no inputs, no selectors, and no tables. pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self { let dummy_var = VarTensor::dummy(col_size, num_inner_cols); Self { selectors: BTreeMap::new(), tables: BTreeMap::new(), index: dummy_var.clone(), output: dummy_var.clone(), input: dummy_var, } } } /// A struct representing the selectors for custom gates #[derive(Clone, Debug, Default)] pub struct CustomGates { /// the inputs to the accumulated operations. pub inputs: Vec<VarTensor>, /// the (currently singular) output of the accumulated operations. pub output: VarTensor, /// selector pub selectors: BTreeMap<(BaseOp, usize, usize), Selector>, } impl CustomGates { /// Returns a new [CustomGates] with no inputs, no selectors, and no tables. pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self { let dummy_var = VarTensor::dummy(col_size, num_inner_cols); Self { inputs: vec![dummy_var.clone(), dummy_var.clone()], output: dummy_var, selectors: BTreeMap::new(), } } } /// A struct representing the selectors for the range checks #[derive(Clone, Debug, Default)] pub struct RangeChecks<F: PrimeField + TensorType + PartialOrd> { /// [Selector]s generated when configuring the layer. We use a [BTreeMap] as we expect to configure many dynamic lookup ops. pub selectors: BTreeMap<(Range, usize, usize), Selector>, /// Selectors for the dynamic lookup tables pub ranges: BTreeMap<Range, RangeCheck<F>>, /// pub index: VarTensor, /// pub input: VarTensor, } impl<F: PrimeField + TensorType + PartialOrd> RangeChecks<F> { /// Returns a new [RangeChecks] with no inputs, no selectors, and no tables. pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self { let dummy_var = VarTensor::dummy(col_size, num_inner_cols); Self { selectors: BTreeMap::new(), ranges: BTreeMap::new(), index: dummy_var.clone(), input: dummy_var, } } } /// Configuration for an accumulated arg. #[derive(Clone, Debug, Default)] pub struct BaseConfig<F: PrimeField + TensorType + PartialOrd> { /// Custom gates pub custom_gates: CustomGates, /// StaticLookups pub static_lookups: StaticLookups<F>, /// [Selector]s for the dynamic lookup tables pub dynamic_lookups: DynamicLookups, /// [Selector]s for the range checks pub range_checks: RangeChecks<F>, /// [Selector]s for the shuffles pub shuffles: Shuffles, /// Activate sanity checks pub check_mode: CheckMode, _marker: PhantomData<F>, } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> BaseConfig<F> { /// Returns a new [BaseConfig] with no inputs, no selectors, and no tables. pub fn dummy(col_size: usize, num_inner_cols: usize) -> Self { Self { custom_gates: CustomGates::dummy(col_size, num_inner_cols), static_lookups: StaticLookups::dummy(col_size, num_inner_cols), dynamic_lookups: DynamicLookups::dummy(col_size, num_inner_cols), shuffles: Shuffles::dummy(col_size, num_inner_cols), range_checks: RangeChecks::dummy(col_size, num_inner_cols), check_mode: CheckMode::SAFE, _marker: PhantomData, } } /// Configures [BaseOp]s for a given [ConstraintSystem]. /// # Arguments /// * `meta` - The [ConstraintSystem] to configure the operations in. /// * `inputs` - The explicit inputs to the operations. /// * `output` - The variable representing the (currently singular) output of the operations. /// * `check_mode` - The variable representing the (currently singular) output of the operations. pub fn configure( meta: &mut ConstraintSystem<F>, inputs: &[VarTensor; 2], output: &VarTensor, check_mode: CheckMode, ) -> Self { // setup a selector per base op let mut nonaccum_selectors = BTreeMap::new(); let mut accum_selectors = BTreeMap::new(); if inputs[0].num_cols() != inputs[1].num_cols() { log::warn!("input shapes do not match"); } if inputs[0].num_cols() != output.num_cols() { log::warn!("input and output shapes do not match"); } for i in 0..output.num_blocks() { for j in 0..output.num_inner_cols() { nonaccum_selectors.insert((BaseOp::Add, i, j), meta.selector()); nonaccum_selectors.insert((BaseOp::Sub, i, j), meta.selector()); nonaccum_selectors.insert((BaseOp::Mult, i, j), meta.selector()); nonaccum_selectors.insert((BaseOp::IsBoolean, i, j), meta.selector()); } } for i in 0..output.num_blocks() { accum_selectors.insert((BaseOp::DotInit, i, 0), meta.selector()); accum_selectors.insert((BaseOp::Dot, i, 0), meta.selector()); accum_selectors.insert((BaseOp::CumProd, i, 0), meta.selector()); accum_selectors.insert((BaseOp::CumProdInit, i, 0), meta.selector()); accum_selectors.insert((BaseOp::Sum, i, 0), meta.selector()); accum_selectors.insert((BaseOp::SumInit, i, 0), meta.selector()); } for ((base_op, block_idx, inner_col_idx), selector) in nonaccum_selectors.iter() { meta.create_gate(base_op.as_str(), |meta| { let selector = meta.query_selector(*selector); let zero = Expression::<F>::Constant(F::ZERO); let mut qis = vec![zero; 2]; for (i, q_i) in qis .iter_mut() .enumerate() .take(2) .skip(2 - base_op.num_inputs()) { *q_i = inputs[i] .query_rng(meta, *block_idx, *inner_col_idx, 0, 1) .expect("non accum: input query failed")[0] .clone() } // Get output expressions for each input channel let (rotation_offset, rng) = base_op.query_offset_rng(); let constraints = match base_op { BaseOp::IsBoolean => { let expected_output: Tensor<Expression<F>> = output .query_rng(meta, *block_idx, *inner_col_idx, 0, 1) .expect("non accum: output query failed"); let output = expected_output[base_op.constraint_idx()].clone(); vec![(output.clone()) * (output.clone() - Expression::Constant(F::from(1)))] } _ => { let expected_output: Tensor<Expression<F>> = output .query_rng(meta, *block_idx, *inner_col_idx, rotation_offset, rng) .expect("non accum: output query failed"); let res = base_op.nonaccum_f((qis[0].clone(), qis[1].clone())); vec![expected_output[base_op.constraint_idx()].clone() - res] } }; Constraints::with_selector(selector, constraints) }); } for ((base_op, block_idx, _), selector) in accum_selectors.iter() { meta.create_gate(base_op.as_str(), |meta| { let selector = meta.query_selector(*selector); let mut qis = vec![vec![]; 2]; for (i, q_i) in qis .iter_mut() .enumerate() .take(2) .skip(2 - base_op.num_inputs()) { *q_i = inputs[i] .query_whole_block(meta, *block_idx, 0, 1) .expect("accum: input query failed") .into_iter() .collect() } // Get output expressions for each input channel let (rotation_offset, rng) = base_op.query_offset_rng(); let expected_output: Tensor<Expression<F>> = output .query_rng(meta, *block_idx, 0, rotation_offset, rng) .expect("accum: output query failed"); let res = base_op.accum_f(expected_output[0].clone(), qis[0].clone(), qis[1].clone()); let constraints = vec![expected_output[base_op.constraint_idx()].clone() - res]; Constraints::with_selector(selector, constraints) }); } // selectors is the merger of nonaccum and accum selectors let selectors = nonaccum_selectors .into_iter() .chain(accum_selectors) .collect(); Self { custom_gates: CustomGates { inputs: inputs.to_vec(), output: output.clone(), selectors, }, static_lookups: StaticLookups::default(), dynamic_lookups: DynamicLookups::default(), shuffles: Shuffles::default(), range_checks: RangeChecks::default(), check_mode, _marker: PhantomData, } } /// Configures and creates lookup selectors #[allow(clippy::too_many_arguments)] pub fn configure_lookup( &mut self, cs: &mut ConstraintSystem<F>, input: &VarTensor, output: &VarTensor, index: &VarTensor, lookup_range: Range, logrows: usize, nl: &LookupOp, ) -> Result<(), Box<dyn Error>> where F: Field, { if !index.is_advice() { return Err("wrong input type for lookup index".into()); } if !input.is_advice() { return Err("wrong input type for lookup input".into()); } if !output.is_advice() { return Err("wrong input type for lookup output".into()); } // we borrow mutably twice so we need to do this dance let table = if !self.static_lookups.tables.contains_key(nl) { // as all tables have the same input we see if there's another table who's input we can reuse let table = if let Some(table) = self.static_lookups.tables.values().next() { Table::<F>::configure( cs, lookup_range, logrows, nl, Some(table.table_inputs.clone()), ) } else { Table::<F>::configure(cs, lookup_range, logrows, nl, None) }; self.static_lookups.tables.insert(nl.clone(), table.clone()); table } else { return Ok(()); }; for x in 0..input.num_blocks() { for y in 0..input.num_inner_cols() { let len = table.selector_constructor.degree; let multi_col_selector = cs.complex_selector(); for ((col_idx, input_col), output_col) in table .table_inputs .iter() .enumerate() .zip(table.table_outputs.iter()) { cs.lookup("", |cs| { let mut res = vec![]; let sel = cs.query_selector(multi_col_selector); let synthetic_sel = match len { 1 => Expression::Constant(F::from(1)), _ => match index { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[x][y], Rotation(0)) } _ => unreachable!(), }, }; let input_query = match &input { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[x][y], Rotation(0)) } _ => unreachable!(), }; let output_query = match &output { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[x][y], Rotation(0)) } _ => unreachable!(), }; // we index from 1 to avoid the zero element creating soundness issues // this is 0 if the index is the same as the column index (starting from 1) let col_expr = sel.clone() * table .selector_constructor .get_expr_at_idx(col_idx, synthetic_sel); let multiplier = table.selector_constructor.get_selector_val_at_idx(col_idx); let not_expr = Expression::Constant(multiplier) - col_expr.clone(); let (default_x, default_y) = table.get_first_element(col_idx); log::trace!("---------------- col {:?} ------------------", col_idx,); log::trace!("expr: {:?}", col_expr,); log::trace!("multiplier: {:?}", multiplier); log::trace!("not_expr: {:?}", not_expr); log::trace!("default x: {:?}", default_x); log::trace!("default y: {:?}", default_y); res.extend([ ( col_expr.clone() * input_query.clone() + not_expr.clone() * Expression::Constant(default_x), *input_col, ), ( col_expr.clone() * output_query.clone() + not_expr.clone() * Expression::Constant(default_y), *output_col, ), ]); res }); } self.static_lookups .selectors .insert((nl.clone(), x, y), multi_col_selector); } } // if we haven't previously initialized the input/output, do so now if let VarTensor::Empty = self.static_lookups.input { debug!("assigning lookup input"); self.static_lookups.input = input.clone(); } if let VarTensor::Empty = self.static_lookups.output { debug!("assigning lookup output"); self.static_lookups.output = output.clone(); } if let VarTensor::Empty = self.static_lookups.index { debug!("assigning lookup index"); self.static_lookups.index = index.clone(); } Ok(()) } /// Configures and creates lookup selectors #[allow(clippy::too_many_arguments)] pub fn configure_dynamic_lookup( &mut self, cs: &mut ConstraintSystem<F>, lookups: &[VarTensor; 3], tables: &[VarTensor; 3], ) -> Result<(), Box<dyn Error>> where F: Field, { for l in lookups.iter() { if !l.is_advice() { return Err("wrong input type for dynamic lookup".into()); } } for t in tables.iter() { if !t.is_advice() || t.num_blocks() > 1 || t.num_inner_cols() > 1 { return Err("wrong table type for dynamic lookup".into()); } } let one = Expression::Constant(F::ONE); let s_ltable = cs.complex_selector(); for x in 0..lookups[0].num_blocks() { for y in 0..lookups[0].num_inner_cols() { let s_lookup = cs.complex_selector(); cs.lookup_any("lookup", |cs| { let s_lookupq = cs.query_selector(s_lookup); let mut expression = vec![]; let s_ltableq = cs.query_selector(s_ltable); let mut lookup_queries = vec![one.clone()]; for lookup in lookups { lookup_queries.push(match lookup { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[x][y], Rotation(0)) } _ => unreachable!(), }); } let mut table_queries = vec![one.clone()]; for table in tables { table_queries.push(match table { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[0][0], Rotation(0)) } _ => unreachable!(), }); } let lhs = lookup_queries.into_iter().map(|c| c * s_lookupq.clone()); let rhs = table_queries.into_iter().map(|c| c * s_ltableq.clone()); expression.extend(lhs.zip(rhs)); expression }); self.dynamic_lookups .lookup_selectors .entry((x, y)) .or_insert(s_lookup); } } self.dynamic_lookups.table_selectors.push(s_ltable); // if we haven't previously initialized the input/output, do so now if self.dynamic_lookups.tables.is_empty() { debug!("assigning dynamic lookup table"); self.dynamic_lookups.tables = tables.to_vec(); } if self.dynamic_lookups.inputs.is_empty() { debug!("assigning dynamic lookup input"); self.dynamic_lookups.inputs = lookups.to_vec(); } Ok(()) } /// Configures and creates lookup selectors #[allow(clippy::too_many_arguments)] pub fn configure_shuffles( &mut self, cs: &mut ConstraintSystem<F>, inputs: &[VarTensor; 2], references: &[VarTensor; 2], ) -> Result<(), Box<dyn Error>> where F: Field, { for l in inputs.iter() { if !l.is_advice() { return Err("wrong input type for dynamic lookup".into()); } } for t in references.iter() { if !t.is_advice() || t.num_blocks() > 1 || t.num_inner_cols() > 1 { return Err("wrong table type for dynamic lookup".into()); } } let one = Expression::Constant(F::ONE); let s_reference = cs.complex_selector(); for x in 0..inputs[0].num_blocks() { for y in 0..inputs[0].num_inner_cols() { let s_input = cs.complex_selector(); cs.lookup_any("lookup", |cs| { let s_inputq = cs.query_selector(s_input); let mut expression = vec![]; let s_referenceq = cs.query_selector(s_reference); let mut input_queries = vec![one.clone()]; for input in inputs { input_queries.push(match input { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[x][y], Rotation(0)) } _ => unreachable!(), }); } let mut ref_queries = vec![one.clone()]; for reference in references { ref_queries.push(match reference { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[0][0], Rotation(0)) } _ => unreachable!(), }); } let lhs = input_queries.into_iter().map(|c| c * s_inputq.clone()); let rhs = ref_queries.into_iter().map(|c| c * s_referenceq.clone()); expression.extend(lhs.zip(rhs)); expression }); self.shuffles .input_selectors .entry((x, y)) .or_insert(s_input); } } self.shuffles.reference_selectors.push(s_reference); // if we haven't previously initialized the input/output, do so now if self.shuffles.references.is_empty() { debug!("assigning shuffles reference"); self.shuffles.references = references.to_vec(); } if self.shuffles.inputs.is_empty() { debug!("assigning shuffles input"); self.shuffles.inputs = inputs.to_vec(); } Ok(()) } /// Configures and creates lookup selectors #[allow(clippy::too_many_arguments)] pub fn configure_range_check( &mut self, cs: &mut ConstraintSystem<F>, input: &VarTensor, index: &VarTensor, range: Range, logrows: usize, ) -> Result<(), Box<dyn Error>> where F: Field, { if !input.is_advice() { return Err("wrong input type for lookup input".into()); } // we borrow mutably twice so we need to do this dance let range_check = if let std::collections::btree_map::Entry::Vacant(e) = self.range_checks.ranges.entry(range) { // as all tables have the same input we see if there's another table who's input we can reuse let range_check = RangeCheck::<F>::configure(cs, range, logrows); e.insert(range_check.clone()); range_check } else { return Ok(()); }; for x in 0..input.num_blocks() { for y in 0..input.num_inner_cols() { let len = range_check.selector_constructor.degree; let multi_col_selector = cs.complex_selector(); for (col_idx, input_col) in range_check.inputs.iter().enumerate() { cs.lookup("", |cs| { let mut res = vec![]; let sel = cs.query_selector(multi_col_selector); let synthetic_sel = match len { 1 => Expression::Constant(F::from(1)), _ => match index { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[x][y], Rotation(0)) } _ => unreachable!(), }, }; let input_query = match &input { VarTensor::Advice { inner: advices, .. } => { cs.query_advice(advices[x][y], Rotation(0)) } _ => unreachable!(), }; let default_x = range_check.get_first_element(col_idx); let col_expr = sel.clone() * range_check .selector_constructor .get_expr_at_idx(col_idx, synthetic_sel); let multiplier = range_check .selector_constructor .get_selector_val_at_idx(col_idx); let not_expr = Expression::Constant(multiplier) - col_expr.clone(); res.extend([( col_expr.clone() * input_query.clone() + not_expr.clone() * Expression::Constant(default_x), *input_col, )]); log::trace!("---------------- col {:?} ------------------", col_idx,); log::trace!("expr: {:?}", col_expr,); log::trace!("multiplier: {:?}", multiplier); log::trace!("not_expr: {:?}", not_expr); log::trace!("default x: {:?}", default_x); res }); } self.range_checks .selectors .insert((range, x, y), multi_col_selector); } } // if we haven't previously initialized the input/output, do so now if let VarTensor::Empty = self.range_checks.input { debug!("assigning range check input"); self.range_checks.input = input.clone(); } if let VarTensor::Empty = self.range_checks.index { debug!("assigning range check index"); self.range_checks.index = index.clone(); } Ok(()) } /// layout_tables must be called before layout. pub fn layout_tables(&mut self, layouter: &mut impl Layouter<F>) -> Result<(), Box<dyn Error>> { for (i, table) in self.static_lookups.tables.values_mut().enumerate() { if !table.is_assigned { debug!( "laying out table for {}", crate::circuit::ops::Op::<F>::as_string(&table.nonlinearity) ); if i == 0 { table.layout(layouter, false)?; } else { table.layout(layouter, true)?; } } } Ok(()) } /// layout_range_checks must be called before layout. pub fn layout_range_checks( &mut self, layouter: &mut impl Layouter<F>, ) -> Result<(), Box<dyn Error>> { for range_check in self.range_checks.ranges.values_mut() { if !range_check.is_assigned { debug!("laying out range check for {:?}", range_check.range); range_check.layout(layouter)?; } } Ok(()) } /// Assigns variables to the regions created when calling `configure`. /// # Arguments /// * `values` - The explicit values to the operations. /// * `layouter` - A Halo2 Layouter. /// * `op` - The operation being represented. pub fn layout( &mut self, region: &mut RegionCtx<F>, values: &[ValTensor<F>], op: Box<dyn Op<F>>, ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> { op.layout(self, region, values) } }
https://github.com/zkonduit/ezkl
src/circuit/ops/hybrid.rs
use super::*; use crate::{ circuit::{layouts, utils, Tolerance}, fieldutils::i128_to_felt, graph::multiplier_to_scale, tensor::{self, Tensor, TensorType, ValTensor}, }; use halo2curves::ff::PrimeField; use serde::{Deserialize, Serialize}; // import run args from model #[allow(missing_docs)] /// An enum representing the operations that consist of both lookups and arithmetic operations. #[derive(Clone, Debug, Serialize, Deserialize)] pub enum HybridOp { Recip { input_scale: utils::F32, output_scale: utils::F32, use_range_check_for_int: bool, }, Div { denom: utils::F32, use_range_check_for_int: bool, }, ReduceMax { axes: Vec<usize>, }, ReduceArgMax { dim: usize, }, SumPool { padding: Vec<(usize, usize)>, stride: Vec<usize>, kernel_shape: Vec<usize>, normalized: bool, }, MaxPool { padding: Vec<(usize, usize)>, stride: Vec<usize>, pool_dims: Vec<usize>, }, ReduceMin { axes: Vec<usize>, }, ReduceArgMin { dim: usize, }, Softmax { input_scale: utils::F32, output_scale: utils::F32, axes: Vec<usize>, }, RangeCheck(Tolerance), Greater, GreaterEqual, Less, LessEqual, Equals, Gather { dim: usize, constant_idx: Option<Tensor<usize>>, }, TopK { dim: usize, k: usize, largest: bool, }, OneHot { dim: usize, num_classes: usize, }, } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for HybridOp { /// fn requires_homogenous_input_scales(&self) -> Vec<usize> { match self { HybridOp::Greater | HybridOp::Less | HybridOp::Equals => vec![0, 1], HybridOp::GreaterEqual | HybridOp::LessEqual => vec![0, 1], _ => vec![], } } /// Returns a reference to the Any trait. fn as_any(&self) -> &dyn Any { self } fn as_string(&self) -> String { match self { HybridOp::Recip { input_scale, output_scale, use_range_check_for_int, } => format!( "RECIP (input_scale={}, output_scale={}, use_range_check_for_int={})", input_scale, output_scale, use_range_check_for_int ), HybridOp::Div { denom, use_range_check_for_int, } => format!( "DIV (denom={}, use_range_check_for_int={})", denom, use_range_check_for_int ), HybridOp::SumPool { padding, stride, kernel_shape, normalized, } => format!( "SUMPOOL (padding={:?}, stride={:?}, kernel_shape={:?}, normalized={})", padding, stride, kernel_shape, normalized ), HybridOp::ReduceMax { axes } => format!("REDUCEMAX (axes={:?})", axes), HybridOp::ReduceArgMax { dim } => format!("REDUCEARGMAX (dim={})", dim), HybridOp::MaxPool { padding, stride, pool_dims, } => format!( "MaxPool (padding={:?}, stride={:?}, pool_dims={:?})", padding, stride, pool_dims ), HybridOp::ReduceMin { axes } => format!("REDUCEMIN (axes={:?})", axes), HybridOp::ReduceArgMin { dim } => format!("REDUCEARGMIN (dim={})", dim), HybridOp::Softmax { input_scale, output_scale, axes, } => { format!( "SOFTMAX (input_scale={}, output_scale={}, axes={:?})", input_scale, output_scale, axes ) } HybridOp::RangeCheck(p) => format!("RANGECHECK (tol={:?})", p), HybridOp::Greater => "GREATER".into(), HybridOp::GreaterEqual => "GREATEREQUAL".into(), HybridOp::Less => "LESS".into(), HybridOp::LessEqual => "LESSEQUAL".into(), HybridOp::Equals => "EQUALS".into(), HybridOp::Gather { dim, .. } => format!("GATHER (dim={})", dim), HybridOp::TopK { k, dim, largest } => { format!("TOPK (k={}, dim={}, largest={})", k, dim, largest) } HybridOp::OneHot { dim, num_classes } => { format!("ONEHOT (dim={}, num_classes={})", dim, num_classes) } } } fn layout( &self, config: &mut crate::circuit::BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], ) -> Result<Option<ValTensor<F>>, Box<dyn std::error::Error>> { Ok(Some(match self { HybridOp::SumPool { padding, stride, kernel_shape, normalized, } => layouts::sumpool( config, region, values[..].try_into()?, padding, stride, kernel_shape, *normalized, )?, HybridOp::Recip { input_scale, output_scale, use_range_check_for_int, } => { if input_scale.0.fract() == 0.0 && output_scale.0.fract() == 0.0 && *use_range_check_for_int { layouts::recip( config, region, values[..].try_into()?, i128_to_felt(input_scale.0 as i128), i128_to_felt(output_scale.0 as i128), )? } else { layouts::nonlinearity( config, region, values.try_into()?, &LookupOp::Recip { input_scale: *input_scale, output_scale: *output_scale, }, )? } } HybridOp::Div { denom, use_range_check_for_int, .. } => { if denom.0.fract() == 0.0 && *use_range_check_for_int { layouts::loop_div( config, region, values[..].try_into()?, i128_to_felt(denom.0 as i128), )? } else { layouts::nonlinearity( config, region, values.try_into()?, &LookupOp::Div { denom: *denom }, )? } } HybridOp::Gather { dim, constant_idx } => { if let Some(idx) = constant_idx { tensor::ops::gather(values[0].get_inner_tensor()?, idx, *dim)?.into() } else { layouts::gather(config, region, values[..].try_into()?, *dim)? } } HybridOp::MaxPool { padding, stride, pool_dims, } => layouts::max_pool( config, region, values[..].try_into()?, padding, stride, pool_dims, )?, HybridOp::ReduceMax { axes } => { layouts::max_axes(config, region, values[..].try_into()?, axes)? } HybridOp::ReduceArgMax { dim } => { layouts::argmax_axes(config, region, values[..].try_into()?, *dim)? } HybridOp::ReduceMin { axes } => { layouts::min_axes(config, region, values[..].try_into()?, axes)? } HybridOp::ReduceArgMin { dim } => { layouts::argmin_axes(config, region, values[..].try_into()?, *dim)? } HybridOp::Softmax { input_scale, output_scale, axes, } => layouts::softmax_axes( config, region, values[..].try_into()?, *input_scale, *output_scale, axes, )?, HybridOp::RangeCheck(tol) => layouts::range_check_percent( config, region, values[..].try_into()?, tol.scale, tol.val, )?, HybridOp::Greater => layouts::greater(config, region, values[..].try_into()?)?, HybridOp::GreaterEqual => { layouts::greater_equal(config, region, values[..].try_into()?)? } HybridOp::Less => layouts::less(config, region, values[..].try_into()?)?, HybridOp::LessEqual => layouts::less_equal(config, region, values[..].try_into()?)?, HybridOp::Equals => layouts::equals(config, region, values[..].try_into()?)?, HybridOp::TopK { dim, k, largest } => { layouts::topk_axes(config, region, values[..].try_into()?, *k, *dim, *largest)? } HybridOp::OneHot { dim, num_classes } => { layouts::one_hot_axis(config, region, values[..].try_into()?, *num_classes, *dim)? } })) } fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { let scale = match self { HybridOp::Greater { .. } | HybridOp::GreaterEqual { .. } | HybridOp::Less { .. } | HybridOp::LessEqual { .. } | HybridOp::ReduceArgMax { .. } | HybridOp::OneHot { .. } | HybridOp::ReduceArgMin { .. } => 0, HybridOp::Softmax { output_scale, .. } | HybridOp::Recip { output_scale, .. } => { multiplier_to_scale(output_scale.0 as f64) } _ => in_scales[0], }; Ok(scale) } fn clone_dyn(&self) -> Box<dyn Op<F>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } }
https://github.com/zkonduit/ezkl
src/circuit/ops/layouts.rs
use std::{ collections::{HashMap, HashSet}, error::Error, ops::Range, }; use halo2_proofs::circuit::Value; use halo2curves::ff::PrimeField; use itertools::Itertools; use log::{error, trace}; use maybe_rayon::{ iter::IntoParallelRefIterator, prelude::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}, slice::ParallelSliceMut, }; use self::tensor::{create_constant_tensor, create_zero_tensor}; use super::{ chip::{BaseConfig, CircuitError}, region::RegionCtx, }; use crate::{ circuit::{ops::base::BaseOp, utils}, fieldutils::{felt_to_i128, i128_to_felt}, tensor::{ create_unit_tensor, get_broadcasted_shape, ops::{accumulated, add, mult, sub}, Tensor, TensorError, ValType, }, }; use super::*; use crate::circuit::ops::lookup::LookupOp; /// Same as div but splits the division into N parts pub(crate) fn loop_div<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, value: &[ValTensor<F>; 1], divisor: F, ) -> Result<ValTensor<F>, Box<dyn Error>> { if divisor == F::ONE { return Ok(value[0].clone()); } // if integer val is divisible by 2, we can use a faster method and div > F::S let mut divisor = divisor; let mut num_parts = 1; while felt_to_i128(divisor) % 2 == 0 && felt_to_i128(divisor) > (2_i128.pow(F::S - 4)) { divisor = i128_to_felt(felt_to_i128(divisor) / 2); num_parts += 1; } let output = div(config, region, value, divisor)?; if num_parts == 1 { return Ok(output); } let divisor_int = 2_i128.pow(num_parts - 1); let divisor_felt = i128_to_felt(divisor_int); if divisor_int <= 2_i128.pow(F::S - 3) { div(config, region, &[output], divisor_felt) } else { // keep splitting the divisor until it satisfies the condition loop_div(config, region, &[output], divisor_felt) } } /// Div accumulated layout pub(crate) fn div<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, value: &[ValTensor<F>; 1], div: F, ) -> Result<ValTensor<F>, Box<dyn Error>> { if div == F::ONE { return Ok(value[0].clone()); } let input = value[0].clone(); let input_dims = input.dims(); let range_check_bracket = felt_to_i128(div) / 2; let divisor = create_constant_tensor(div, 1); let divisor = region.assign(&config.custom_gates.inputs[1], &divisor)?; region.increment(divisor.len()); let is_assigned = !input.any_unknowns()? && !divisor.any_unknowns()?; let mut claimed_output: ValTensor<F> = if is_assigned { let input_evals = input.get_int_evals()?; tensor::ops::nonlinearities::const_div(&input_evals.clone(), felt_to_i128(div) as f64) .par_iter() .map(|x| Value::known(i128_to_felt(*x))) .collect::<Tensor<Value<F>>>() .into() } else { Tensor::new( Some(&vec![Value::<F>::unknown(); input.len()]), &[input.len()], )? .into() }; claimed_output.reshape(input_dims)?; region.assign(&config.custom_gates.output, &claimed_output)?; region.increment(claimed_output.len()); let product = pairwise( config, region, &[claimed_output.clone(), divisor.clone()], BaseOp::Mult, )?; let diff_with_input = pairwise( config, region, &[product.clone(), input.clone()], BaseOp::Sub, )?; range_check( config, region, &[diff_with_input], &(-range_check_bracket, range_check_bracket), )?; Ok(claimed_output) } /// recip accumulated layout pub(crate) fn recip<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, value: &[ValTensor<F>; 1], input_scale: F, output_scale: F, ) -> Result<ValTensor<F>, Box<dyn Error>> { let input = value[0].clone(); let input_dims = input.dims(); let integer_input_scale = felt_to_i128(input_scale); let integer_output_scale = felt_to_i128(output_scale); // range_check_bracket is min of input_scale * output_scale and 2^F::S - 3 let range_check_len = std::cmp::min(integer_output_scale, 2_i128.pow(F::S - 4)); let input_scale_ratio = if range_check_len > 0 { i128_to_felt(integer_input_scale * integer_output_scale / range_check_len) } else { F::ONE }; let range_check_bracket = range_check_len / 2; let is_assigned = !input.any_unknowns()?; let mut claimed_output: ValTensor<F> = if is_assigned { let input_evals = input.get_int_evals()?; tensor::ops::nonlinearities::recip( &input_evals, felt_to_i128(input_scale) as f64, felt_to_i128(output_scale) as f64, ) .par_iter() .map(|x| Value::known(i128_to_felt(*x))) .collect::<Tensor<Value<F>>>() .into() } else { Tensor::new( Some(&vec![Value::<F>::unknown(); input.len()]), &[input.len()], )? .into() }; claimed_output.reshape(input_dims)?; let claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?; region.increment(claimed_output.len()); // this is now of scale 2 * scale let product = pairwise( config, region, &[claimed_output.clone(), input.clone()], BaseOp::Mult, )?; // divide by input_scale let rebased_div = loop_div(config, region, &[product], input_scale_ratio)?; let zero_inverse_val = tensor::ops::nonlinearities::zero_recip(felt_to_i128(output_scale) as f64)[0]; let zero_inverse = create_constant_tensor(i128_to_felt(zero_inverse_val), 1); let equal_zero_mask = equals_zero(config, region, &[input.clone()])?; let equal_inverse_mask = equals(config, region, &[claimed_output.clone(), zero_inverse])?; // assert the two masks are equal enforce_equality( config, region, &[equal_zero_mask.clone(), equal_inverse_mask], )?; let unit_scale = create_constant_tensor(i128_to_felt(range_check_len), 1); let unit_mask = pairwise(config, region, &[equal_zero_mask, unit_scale], BaseOp::Mult)?; // now add the unit mask to the rebased_div let rebased_offset_div = pairwise(config, region, &[rebased_div, unit_mask], BaseOp::Add)?; // at most the error should be in the original unit scale's range range_check( config, region, &[rebased_offset_div], &(range_check_bracket, 3 * range_check_bracket), )?; Ok(claimed_output) } /// Dot product of two tensors. /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::einsum; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// use ezkl::circuit::layouts::dot; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]), /// &[1, 3, 3], /// ).unwrap()); /// let y = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 5, 10, -4, 2, -1, 2, 0, 1]), /// &[1, 3, 3], /// ).unwrap()); /// assert_eq!(dot::<Fp>(&dummy_config, &mut dummy_region, &[x, y]).unwrap().get_int_evals().unwrap()[0], 86); /// ``` pub fn dot<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { region.flush()?; // time this entire function run let global_start = instant::Instant::now(); let mut values = values.clone(); // this section has been optimized to death, don't mess with it let mut removal_indices = values[0].get_const_zero_indices()?; let second_zero_indices = values[1].get_const_zero_indices()?; removal_indices.extend(second_zero_indices); removal_indices.par_sort_unstable(); removal_indices.dedup(); // is already sorted values[0].remove_indices(&mut removal_indices, true)?; values[1].remove_indices(&mut removal_indices, true)?; let elapsed = global_start.elapsed(); trace!("filtering const zero indices took: {:?}", elapsed); if values[0].len() != values[1].len() { return Err(Box::new(TensorError::DimMismatch("dot".to_string()))); } // if empty return a const if values[0].is_empty() && values[1].is_empty() { return Ok(create_zero_tensor(1)); } let start = instant::Instant::now(); let mut inputs = vec![]; let block_width = config.custom_gates.output.num_inner_cols(); let mut assigned_len = 0; for (i, input) in values.iter_mut().enumerate() { input.pad_to_zero_rem(block_width, ValType::Constant(F::ZERO))?; let inp = { let (res, len) = region.assign_with_duplication( &config.custom_gates.inputs[i], input, &config.check_mode, false, )?; assigned_len = len; res.get_inner()? }; inputs.push(inp); } let elapsed = start.elapsed(); trace!("assigning inputs took: {:?}", elapsed); // Now we can assign the dot product // time this step let start = instant::Instant::now(); let accumulated_dot = accumulated::dot(&[inputs[0].clone(), inputs[1].clone()], block_width)?; let elapsed = start.elapsed(); trace!("calculating accumulated dot took: {:?}", elapsed); let start = instant::Instant::now(); let (output, output_assigned_len) = region.assign_with_duplication( &config.custom_gates.output, &accumulated_dot.into(), &config.check_mode, true, )?; let elapsed = start.elapsed(); trace!("assigning output took: {:?}", elapsed); // enable the selectors if !region.is_dummy() { (0..output_assigned_len) .map(|i| { let (x, _, z) = config .custom_gates .output .cartesian_coord(region.linear_coord() + i * block_width); // hop over duplicates at start of column if z == 0 && i > 0 { return Ok(()); } let selector = if i == 0 { config.custom_gates.selectors.get(&(BaseOp::DotInit, x, 0)) } else { config.custom_gates.selectors.get(&(BaseOp::Dot, x, 0)) }; region.enable(selector, z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } let last_elem = output.get_slice(&[output.len() - 1..output.len()])?; region.increment(assigned_len); // last element is the result let elapsed = global_start.elapsed(); trace!("dot layout took: {:?}, row {}", elapsed, region.row()); trace!("----------------------------"); Ok(last_elem) } /// Computes the einstein sum of a set of tensors. /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::einsum; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// // matmul case /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 1, 2, 1, 1, 1]), /// &[2, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 3, 2, 1, 1, 1]), /// &[3, 2], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "ij,jk->ik").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[8, 9, 5, 5]), &[2, 2]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// // element wise multiplication /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5]), /// &[3, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 1, 2, 3, 1, 2, 3]), /// &[3, 3], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "ij,ij->ij").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1, 4, 9, 2, 6, 12, 3, 8, 15]), &[3, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// /// // dot product of A with the transpose of B. /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5]), /// &[3, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 1, 2, 3, 1, 2, 3]), /// &[3, 3], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "ik,jk->ij").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[14, 14, 14, 20, 20, 20, 26, 26, 26]), &[3, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// // dot product /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5]), /// &[3, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 1, 2, 3, 1, 2, 3]), /// &[3, 3], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "ik,ik->i").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[14, 20, 26]), &[3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// /// // dot product /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3]), /// &[3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3]), /// &[3], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "i,i->").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[14]), &[1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// /// // wut ? /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]), /// &[3, 3, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[4, 5, 7, 8]), /// &[2, 2], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "anm,bm->ba").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[68, 80, 95, 113, 134, 158]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// // wutttttt ? /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]), /// &[3, 3, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[4, 5, 7, 8]), /// &[2, 2], /// ).unwrap()); /// let z = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[4, 5, 7, 8, 9, 9]), /// &[2, 3], /// ).unwrap()); /// /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[z, x, k], "bn,anm,bm->ba").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[390, 414, 534, 994, 1153, 1384]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// /// // contraction with a single common axis /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]), /// &[3, 3, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[4, 5, 7, 8]), /// &[2, 2], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "abc,cd->").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[648]), &[1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// // contraction with no common axes (outer product) /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 2, 3, 4, 3, 4, 5, 1, 2, 3, 2, 3, 4, 3, 4, 5]), /// &[3, 3, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[4, 5, 7, 8]), /// &[2, 2], /// ).unwrap()); /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "abc,ed->").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1296]), &[1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// // trivial axes mapping /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[4, 5, 7, 8]), /// &[2, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[4, 5]), /// &[2], /// ).unwrap()); /// /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x.clone(), k.clone()], "mk,k->m").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[41, 68]), &[2]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x, k], "mk,k->mn").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[41, 68]), &[2, 1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[0, 0, 0, 3]), /// &[1, 4], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[213, 227, 74, 77]), /// &[4], /// ).unwrap()); /// /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x.clone(), k.clone()], "mk,k->ma").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[231]), &[1, 1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// // subtle difference /// let result = einsum::<Fp>(&dummy_config, &mut dummy_region, &[x.clone(), k.clone()], "mk,n->ma").unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1773]), &[1, 1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// ``` /// pub fn einsum<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, inputs: &[ValTensor<F>], equation: &str, ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut equation = equation.split("->"); let inputs_eq = equation.next().ok_or(CircuitError::InvalidEinsum)?; let output_eq = equation.next().ok_or(CircuitError::InvalidEinsum)?; let inputs_eq = inputs_eq.split(',').collect::<Vec<_>>(); // Check that the number of inputs matches the number of inputs in the equation if inputs.len() != inputs_eq.len() { return Err(Box::new(TensorError::DimMismatch("einsum".to_string()))); } let mut indices_to_size = HashMap::new(); for (i, input) in inputs.iter().enumerate() { for j in 0..inputs_eq[i].len() { let c = inputs_eq[i] .chars() .nth(j) .ok_or(CircuitError::InvalidEinsum)?; if let std::collections::hash_map::Entry::Vacant(e) = indices_to_size.entry(c) { e.insert(input.dims()[j]); } else if indices_to_size[&c] != input.dims()[j] { return Err(Box::new(TensorError::DimMismatch("einsum".to_string()))); } } } // maps unrepresented indices in the output to a trivial 1 for c in output_eq.chars() { indices_to_size.entry(c).or_insert(1); } // Compute the output tensor shape let mut output_shape: Vec<usize> = output_eq .chars() .map(|c| { indices_to_size .get(&c) .ok_or(CircuitError::InvalidEinsum) .copied() }) .collect::<Result<Vec<_>, _>>()?; if output_shape.is_empty() { output_shape.push(1); } // Create a new output tensor with the computed shape let mut output: Tensor<ValType<F>> = Tensor::new(None, &output_shape)?; let mut seen = HashSet::new(); let mut common_indices_to_inputs = vec![]; for input in inputs_eq.iter().take(inputs.len()) { for c in input.chars() { if !seen.contains(&c) { seen.insert(c); } else { common_indices_to_inputs.push(c); } } } let non_common_indices = indices_to_size .keys() .filter(|&x| !common_indices_to_inputs.contains(x)) .collect::<Vec<_>>(); let non_common_coord_size = non_common_indices .iter() .map(|d| { // If the current index is in the output equation, then the slice should be the current coordinate if output_eq.contains(**d) { Ok(1) // Otherwise, the slice should be the entire dimension of the input tensor } else { indices_to_size .get(d) .ok_or(CircuitError::InvalidEinsum) .copied() } }) .collect::<Result<Vec<_>, _>>()? .iter() .product::<usize>(); let cartesian_coord = output_shape .iter() .map(|d| 0..*d) .multi_cartesian_product() .collect::<Vec<_>>(); // Get the indices common across input tensors let mut common_coord = common_indices_to_inputs .iter() .map(|d| { // If the current index is in the output equation, then the slice should be the current coordinate if output_eq.contains(*d) { Ok(0..1) // Otherwise, the slice should be the entire dimension of the input tensor } else { Ok(0..*indices_to_size.get(d).ok_or(CircuitError::InvalidEinsum)?) } }) .collect::<Result<Vec<Range<_>>, Box<dyn Error>>>()? .into_iter() .multi_cartesian_product() .collect::<Vec<_>>(); // If there are no common indices, then we need to add an empty slice to force one iteration of the loop if common_coord.is_empty() { common_coord.push(vec![]); } let inner_loop_function = |i: usize, region: &mut RegionCtx<'_, F>| { let coord = cartesian_coord[i].clone(); // Compute the slice of each input tensor given the current coordinate of the output tensor let inputs = (0..inputs.len()) .map(|idx| { let mut slice = vec![]; for (i, c) in inputs_eq[idx].chars().enumerate() { // If the current index is in the output equation, then the slice should be the current coordinate if let Some(idx) = output_eq.find(c) { slice.push(coord[idx]..coord[idx] + 1); // Otherwise, the slice should be the entire dimension of the input tensor } else { slice.push(0..inputs[idx].dims()[i]); } } // Get the slice of the input tensor inputs[idx].get_slice(&slice) }) .collect::<Result<Vec<_>, _>>()?; // in this case its just a dot product :) if non_common_coord_size == 1 && inputs.len() == 2 { Ok(dot( config, region, inputs[..].try_into().map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis })?, )? .get_inner_tensor()?[0] .clone()) } else { let mut prod_res = None; // Compute the cartesian product of all common indices for common_dim in &common_coord { let inputs = (0..inputs.len()) .map(|idx| { let mut slice = vec![]; // Iterate over all indices in the input equation for (i, c) in inputs_eq[idx].chars().enumerate() { // If the current index is common to multiple inputs, then the slice should be the current coordinate if let Some(j) = common_indices_to_inputs.iter().position(|&r| r == c) { slice.push(common_dim[j]..common_dim[j] + 1); } else { slice.push(0..inputs[idx].dims()[i]); } } // Get the slice of the input tensor inputs[idx].get_slice(&slice).map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis }) }) .collect::<Result<Vec<_>, _>>()?; let mut input_pairs = vec![]; for input in inputs { input_pairs.push(input.get_inner_tensor()?.clone().into_iter()); } let input_pairs = input_pairs .into_iter() .multi_cartesian_product() .collect::<Vec<_>>(); // Compute the product of all input tensors for pair in input_pairs { let product_across_pair = prod(config, region, &[pair.into()])?; if let Some(product) = prod_res { prod_res = Some( pairwise(config, region, &[product, product_across_pair], BaseOp::Add) .map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis })?, ); } else { prod_res = Some(product_across_pair); } } } Ok::<_, region::RegionError>( prod_res .ok_or(Into::<region::RegionError>::into("missing prod"))? .get_inner_tensor()?[0] .clone(), ) } }; region.flush()?; region.apply_in_loop(&mut output, inner_loop_function)?; let output: ValTensor<F> = output.into(); Ok(output) } fn _sort_ascending<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut input = values[0].clone(); input.flatten(); let is_assigned = !input.any_unknowns()?; let sorted = if is_assigned { let mut int_evals = input.get_int_evals()?; int_evals.par_sort_unstable_by(|a, b| a.cmp(b)); int_evals .par_iter() .map(|x| Value::known(i128_to_felt(*x))) .collect::<Tensor<Value<F>>>() } else { Tensor::new( Some(&vec![Value::<F>::unknown(); input.len()]), &[input.len()], )? }; let assigned_sort = region.assign(&config.custom_gates.inputs[0], &sorted.into())?; region.increment(assigned_sort.len()); let window_a = assigned_sort.get_slice(&[0..assigned_sort.len() - 1])?; let window_b = assigned_sort.get_slice(&[1..assigned_sort.len()])?; let is_greater = greater_equal(config, region, &[window_b.clone(), window_a.clone()])?; let unit = create_unit_tensor(is_greater.len()); enforce_equality(config, region, &[unit, is_greater])?; // assert that this is a permutation/shuffle shuffles(config, region, &[assigned_sort.clone()], &[input.clone()])?; Ok(assigned_sort) } /// Returns top K values. fn _select_topk<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], k: usize, largest: bool, ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut sorted = _sort_ascending(config, region, values)?; if largest { sorted.reverse()?; } sorted.get_slice(&[0..k]) } /// Returns top K values. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::topk_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2,3], /// ).unwrap()); /// let result = topk_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], 2, 1, true).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[15, 2, 1, 1]), /// &[2,2], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn topk_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], k: usize, dim: usize, largest: bool, ) -> Result<ValTensor<F>, Box<dyn Error>> { let topk_at_k = move |config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1]| -> Result<ValTensor<F>, Box<dyn Error>> { _select_topk(config, region, values, k, largest) }; let output: ValTensor<F> = multi_dim_axes_op(config, region, values, &[dim], topk_at_k)?; Ok(output) } fn select<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { let start = instant::Instant::now(); let (mut input, index) = (values[0].clone(), values[1].clone()); input.flatten(); // these will be assigned as constants let dim_indices: ValTensor<F> = Tensor::from((0..input.len() as u64).map(|x| ValType::Constant(F::from(x)))).into(); let is_assigned = !input.any_unknowns()? && !index.any_unknowns()?; let output: ValTensor<F> = if is_assigned && region.witness_gen() { let felt_evals = input.get_felt_evals()?; index .get_int_evals()? .par_iter() .map(|x| Value::known(felt_evals.get(&[*x as usize]))) .collect::<Tensor<Value<F>>>() } else { Tensor::new( Some(&vec![Value::<F>::unknown(); index.len()]), &[index.len()], )? } .into(); let (_, assigned_output) = dynamic_lookup(config, region, &[index, output], &[dim_indices, input])?; let end = start.elapsed(); trace!("select took: {:?}", end); Ok(assigned_output) } fn one_hot<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], num_classes: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { // assert values is flat assert_eq!(values[0].dims().len(), 1); // assert its a single elelemnt assert_eq!(values[0].len(), 1); let input = values[0].clone(); let is_assigned = !input.any_unknowns()?; let output: ValTensor<F> = if is_assigned { let int_evals = input.get_int_evals()?; let res = tensor::ops::one_hot(&int_evals, num_classes, 1)?; res.par_iter() .map(|x| Value::known(i128_to_felt(*x))) .collect::<Tensor<_>>() } else { Tensor::new( Some(&vec![Value::<F>::unknown(); num_classes]), &[num_classes], )? } .into(); let assigned_input = region.assign(&config.custom_gates.inputs[0], &input)?; // now assert all elems are 0 or 1 let assigned_output = boolean_identity(config, region, &[output.clone()], true)?; region.increment(std::cmp::max(assigned_output.len(), assigned_input.len())); let sum = sum(config, region, &[assigned_output.clone()])?; // assert sum is 1 let unit = create_unit_tensor(1); enforce_equality(config, region, &[unit.clone(), sum])?; let gathered = gather( config, region, &[assigned_output.clone(), assigned_input.clone()], 0, )?; enforce_equality(config, region, &[unit, gathered])?; Ok(assigned_output) } /// Dynamic lookup pub(crate) fn dynamic_lookup<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, lookups: &[ValTensor<F>; 2], tables: &[ValTensor<F>; 2], ) -> Result<(ValTensor<F>, ValTensor<F>), Box<dyn Error>> { let start = instant::Instant::now(); // if not all lookups same length err if lookups[0].len() != lookups[1].len() { return Err("lookups must be same length".into()); } // if not all inputs same length err if tables[0].len() != tables[1].len() { return Err("tables must be same length".into()); } let dynamic_lookup_index = region.dynamic_lookup_index(); let (lookup_0, lookup_1) = (lookups[0].clone(), lookups[1].clone()); let (table_0, table_1) = (tables[0].clone(), tables[1].clone()); let table_0 = region.assign_dynamic_lookup(&config.dynamic_lookups.tables[0], &table_0)?; let _table_1 = region.assign_dynamic_lookup(&config.dynamic_lookups.tables[1], &table_1)?; let table_len = table_0.len(); trace!("assigning tables took: {:?}", start.elapsed()); // now create a vartensor of constants for the dynamic lookup index let table_index = create_constant_tensor(F::from(dynamic_lookup_index as u64), table_len); let _table_index = region.assign_dynamic_lookup(&config.dynamic_lookups.tables[2], &table_index)?; trace!("assigning table index took: {:?}", start.elapsed()); let lookup_0 = region.assign(&config.dynamic_lookups.inputs[0], &lookup_0)?; let lookup_1 = region.assign(&config.dynamic_lookups.inputs[1], &lookup_1)?; let lookup_len = lookup_0.len(); trace!("assigning lookups took: {:?}", start.elapsed()); // now set the lookup index let lookup_index = create_constant_tensor(F::from(dynamic_lookup_index as u64), lookup_len); let _lookup_index = region.assign(&config.dynamic_lookups.inputs[2], &lookup_index)?; trace!("assigning lookup index took: {:?}", start.elapsed()); if !region.is_dummy() { (0..table_len) .map(|i| { let table_selector = config.dynamic_lookups.table_selectors[0]; let (_, _, z) = config.dynamic_lookups.tables[0] .cartesian_coord(region.combined_dynamic_shuffle_coord() + i); region.enable(Some(&table_selector), z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } if !region.is_dummy() { // Enable the selectors (0..lookup_len) .map(|i| { let (x, y, z) = config.dynamic_lookups.inputs[0].cartesian_coord(region.linear_coord() + i); let lookup_selector = config .dynamic_lookups .lookup_selectors .get(&(x, y)) .ok_or("missing selectors")?; region.enable(Some(lookup_selector), z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } region.increment_dynamic_lookup_col_coord(table_len); region.increment_dynamic_lookup_index(1); region.increment(lookup_len); let end = start.elapsed(); trace!("dynamic lookup took: {:?}", end); Ok((lookup_0, lookup_1)) } /// Shuffle arg pub(crate) fn shuffles<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, input: &[ValTensor<F>; 1], reference: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { let shuffle_index = region.shuffle_index(); let (input, reference) = (input[0].clone(), reference[0].clone()); // assert input and reference are same length if input.len() != reference.len() { return Err("input and reference must be same length".into()); } let reference = region.assign_shuffle(&config.shuffles.references[0], &reference)?; let reference_len = reference.len(); // now create a vartensor of constants for the shuffle index let index = create_constant_tensor(F::from(shuffle_index as u64), reference_len); let index = region.assign_shuffle(&config.shuffles.references[1], &index)?; let input = region.assign(&config.shuffles.inputs[0], &input)?; region.assign(&config.shuffles.inputs[1], &index)?; if !region.is_dummy() { (0..reference_len) .map(|i| { let ref_selector = config.shuffles.reference_selectors[0]; let (_, _, z) = config.shuffles.references[0] .cartesian_coord(region.combined_dynamic_shuffle_coord() + i); region.enable(Some(&ref_selector), z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } if !region.is_dummy() { // Enable the selectors (0..reference_len) .map(|i| { let (x, y, z) = config.custom_gates.inputs[0].cartesian_coord(region.linear_coord() + i); let input_selector = config .shuffles .input_selectors .get(&(x, y)) .ok_or("missing selectors")?; region.enable(Some(input_selector), z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } region.increment_shuffle_col_coord(reference_len); region.increment_shuffle_index(1); region.increment(reference_len); Ok(input) } /// One hot accumulated layout pub(crate) fn one_hot_axis<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], num_classes: usize, dim: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { let input = values[0].clone(); let input_inner = input.get_inner_tensor()?; let mut output_dims = values[0].dims().to_vec(); output_dims.insert(dim, num_classes); let mut op_tensors: Tensor<ValTensor<F>> = Tensor::new(None, input_inner.dims())?; let inner_loop_function = |i: usize, region: &mut RegionCtx<'_, F>| -> Result<ValTensor<F>, _> { let inp = input_inner[i].clone(); let tensor = Tensor::new(Some(&[inp.clone()]), &[1])?; Ok(one_hot(config, region, &[tensor.into()], num_classes)?) }; region.apply_in_loop(&mut op_tensors, inner_loop_function)?; // Allocate memory for the output tensor let cartesian_coord = output_dims .iter() .map(|x| 0..*x) .multi_cartesian_product() .collect::<Vec<_>>(); let mut output = Tensor::<ValType<F>>::new(None, &output_dims)?; output = output.par_enum_map(|i, _| { let coord = cartesian_coord[i].clone(); let mut op_idx = coord.clone(); let coord_at_dims = vec![coord[dim]]; op_idx.remove(dim); let op_tensor = op_tensors.get(&op_idx); let op_tensor = op_tensor.get_inner_tensor()?; let one_hot_val = op_tensor.get(&coord_at_dims).clone(); Ok::<_, region::RegionError>(one_hot_val) })?; Ok(output.into()) } /// Gather accumulated layout pub(crate) fn gather<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], dim: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { let (input, mut index_clone) = (values[0].clone(), values[1].clone()); index_clone.flatten(); if index_clone.is_singleton() { index_clone.reshape(&[1])?; } // Calculate the output tensor size let input_dims = input.dims(); let mut output_size = input_dims.to_vec(); output_size[dim] = index_clone.dims()[0]; let linear_index = linearize_element_index(config, region, &[index_clone], input_dims, dim, true)?; let mut output = select(config, region, &[input, linear_index])?; output.reshape(&output_size)?; Ok(output) } /// Gather accumulated layout pub(crate) fn gather_elements<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], dim: usize, ) -> Result<(ValTensor<F>, ValTensor<F>), Box<dyn Error>> { let (input, index) = (values[0].clone(), values[1].clone()); assert_eq!(input.dims().len(), index.dims().len()); // Calculate the output tensor size let output_size = index.dims().to_vec(); let linear_index = linearize_element_index(config, region, &[index], input.dims(), dim, false)?; let mut output = select(config, region, &[input, linear_index.clone()])?; output.reshape(&output_size)?; Ok((output, linear_index)) } /// Gather accumulated layout pub(crate) fn gather_nd<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], batch_dims: usize, ) -> Result<(ValTensor<F>, ValTensor<F>), Box<dyn Error>> { let (input, index) = (values[0].clone(), values[1].clone()); 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 index_dims.last() > Some(&(input_dims.len() - batch_dims)) { return Err(TensorError::DimMismatch("gather_nd".to_string()).into()); } 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 }; let linear_index = linearize_nd_index(config, region, &[index], input.dims(), batch_dims)?; let mut output = select(config, region, &[input, linear_index.clone()])?; output.reshape(&output_size)?; Ok((output, linear_index)) } /// Takes a tensor representing a multi-dimensional index and returns a tensor representing the linearized index. /// The linearized index is the index of the element in the flattened tensor. /// FOr instance if the dims is [3,5,2], the linearized index of [2] at dim 1 is 2*5 + 3 = 13 pub(crate) fn linearize_element_index<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], dims: &[usize], dim: usize, is_flat_index: bool, ) -> Result<ValTensor<F>, Box<dyn Error>> { let start_time = instant::Instant::now(); let index = values[0].clone(); if !is_flat_index { assert_eq!(index.dims().len(), dims.len()); // if the index is already flat, return it if index.dims().len() == 1 { return Ok(index); } } let dim_multiplier: Tensor<usize> = Tensor::new(None, &[dims.len()])?; let dim_multiplier: Tensor<F> = dim_multiplier.par_enum_map(|i, _| { let mut res = 1; for dim in dims.iter().skip(i + 1) { res *= dim; } Ok::<_, region::RegionError>(F::from(res as u64)) })?; let iteration_dims = if is_flat_index { let mut dims = dims.to_vec(); dims[dim] = index.len(); dims } else { index.dims().to_vec() }; let cartesian_coord = iteration_dims .iter() .map(|x| 0..*x) .multi_cartesian_product() .collect::<Vec<_>>(); let val_dim_multiplier: ValTensor<F> = dim_multiplier .get_slice(&[dim..dim + 1])? .map(|x| ValType::Constant(x)) .into(); let mut output = Tensor::new(None, &[cartesian_coord.len()])?; let inner_loop_function = |i: usize, region: &mut RegionCtx<'_, F>| { let coord = cartesian_coord[i].clone(); let slice: Vec<Range<usize>> = if is_flat_index { coord[dim..dim + 1].iter().map(|x| *x..*x + 1).collect() } else { coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>() }; let index_val = index.get_slice(&slice)?; let mut const_offset = F::ZERO; for i in 0..dims.len() { if i != dim { const_offset += F::from(coord[i] as u64) * dim_multiplier[i]; } } let const_offset = create_constant_tensor(const_offset, 1); let res = pairwise( config, region, &[index_val, val_dim_multiplier.clone()], BaseOp::Mult, )?; let res = pairwise(config, region, &[res, const_offset], BaseOp::Add)?; Ok(res.get_inner_tensor()?[0].clone()) }; region.apply_in_loop(&mut output, inner_loop_function)?; let elapsed = start_time.elapsed(); trace!("linearize_element_index took: {:?}", elapsed); Ok(output.into()) } /// Takes a tensor representing a nd index and returns a tensor representing the linearized index. /// The linearized index is the index of the element in the flattened tensor. /// Given data tensor of rank r >= 1, indices tensor of rank q >= 1, and batch_dims integer b, this operator gathers slices of data into an output tensor of rank q + r - indices_shape[-1] - 1 - b. /// indices is an q-dimensional integer tensor, best thought of as a (q-1)-dimensional tensor of index-tuples into data, where each element defines a slice of data /// batch_dims (denoted as b) is an integer indicating the number of batch dimensions, i.e the leading b number of dimensions of data tensor and indices are representing the batches, and the gather starts from the b+1 dimension. /// Some salient points about the inputs’ rank and shape: /// r >= 1 and q >= 1 are to be honored. There is no dependency condition to be met between ranks r and q /// The first b dimensions of the shape of indices tensor and data tensor must be equal. /// b < min(q, r) is to be honored. /// The indices_shape[-1] should have a value between 1 (inclusive) and rank r-b (inclusive) /// All values in indices are expected to be within bounds [-s, s-1] along axis of size s (i.e.) -data_shape[i] <= indices[...,i] <= data_shape[i] - 1. It is an error if any of the index values are out of bounds. // The output is computed as follows: /// The output tensor is obtained by mapping each index-tuple in the indices tensor to the corresponding slice of the input data. /// If indices_shape[-1] > r-b => error condition /// 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 (Example 1 below) /// 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 (Examples 2, 3, 4 and 5 below) pub(crate) fn linearize_nd_index<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], dims: &[usize], batch_dims: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { let index = values[0].clone(); let index_dims = index.dims().to_vec(); let last_dim = index.dims().last().unwrap(); let input_rank = dims[batch_dims..].len(); let dim_multiplier: Tensor<usize> = Tensor::new(None, &[dims.len()])?; let dim_multiplier: Tensor<F> = dim_multiplier.par_enum_map(|i, _| { let mut res = 1; for dim in dims.iter().skip(i + 1) { res *= dim; } Ok::<_, region::RegionError>(F::from(res as u64)) })?; let iteration_dims = index.dims()[0..batch_dims].to_vec(); let mut batch_cartesian_coord = iteration_dims .iter() .map(|x| 0..*x) .multi_cartesian_product() .collect::<Vec<_>>(); if batch_cartesian_coord.is_empty() { batch_cartesian_coord.push(vec![]); } let index_dim_multiplier: ValTensor<F> = dim_multiplier .get_slice(&[batch_dims..dims.len()])? .map(|x| ValType::Constant(x)) .into(); let mut outer_results = vec![]; for coord in batch_cartesian_coord { let slice: Vec<Range<usize>> = coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>(); let mut index_slice = index.get_slice(&slice)?; index_slice.reshape(&index_dims[batch_dims..])?; // expand the index to the full dims by iterating over the rest of the dims and inserting constants // eg in the case // batch_dims = 0 // data = [[[0,1],[2,3]],[[4,5],[6,7]]] # data_shape = [2, 2, 2] // indices = [[0,1],[1,0]] # indices_shape = [2, 2] // output = [[2,3],[4,5]] # output_shape = [2, 2] // the index should be expanded to the shape [2,2,3]: [[0,1,0],[0,1,1],[1,0,0],[1,0,1]] 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 indices = if last_dim < &input_rank { inner_cartesian_coord .iter() .map(|x| { let slice = x.iter().map(|x| *x..*x + 1).collect::<Vec<_>>(); let index = index_slice.get_slice(&slice)?; // map over cartesian coord of rest of dims and insert constants let grid = (*last_dim..input_rank) .map(|x| 0..dims[x]) .multi_cartesian_product(); Ok(grid .map(|x| { let index = index.clone(); let constant_valtensor: ValTensor<F> = Tensor::from( x.into_iter().map(|x| ValType::Constant(F::from(x as u64))), ) .into(); index.concat(constant_valtensor) }) .collect::<Result<Vec<_>, TensorError>>()?) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()? .into_iter() .flatten() .collect::<Vec<_>>() } else { inner_cartesian_coord .iter() .map(|x| { let slice = x.iter().map(|x| *x..*x + 1).collect::<Vec<_>>(); index_slice.get_slice(&slice) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()? }; let mut const_offset = F::ZERO; for i in 0..batch_dims { const_offset += F::from(coord[i] as u64) * dim_multiplier[i]; } let const_offset = create_constant_tensor(const_offset, 1); let mut results = vec![]; for index_val in indices { let mut index_val = index_val.clone(); index_val.flatten(); let res = pairwise( config, region, &[index_val.clone(), index_dim_multiplier.clone()], BaseOp::Mult, )?; let res = res.concat(const_offset.clone())?; let res = sum(config, region, &[res])?; results.push(res.get_inner_tensor()?.clone()); // assert than res is less than the product of the dims if region.witness_gen() { assert!( res.get_int_evals()? .iter() .all(|x| *x < dims.iter().product::<usize>() as i128), "res is greater than the product of the dims {} (coord={}, index_dim_multiplier={}, res={})", dims.iter().product::<usize>(), index_val.show(), index_dim_multiplier.show(), res.show() ); } } let result_tensor = Tensor::from(results.into_iter()); outer_results.push(result_tensor.combine()?); } let output = Tensor::from(outer_results.into_iter()); let output = output.combine()?; Ok(output.into()) } pub(crate) fn get_missing_set_elements< F: PrimeField + TensorType + PartialOrd + std::hash::Hash, >( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ordered: bool, ) -> Result<ValTensor<F>, Box<dyn Error>> { let (mut input, fullset) = (values[0].clone(), values[1].clone()); let set_len = fullset.len(); input.flatten(); let is_assigned = !input.any_unknowns()? && !fullset.any_unknowns()?; let mut claimed_output: ValTensor<F> = if is_assigned { let input_evals = input.get_int_evals()?; let mut fullset_evals = fullset.get_int_evals()?.into_iter().collect::<Vec<_>>(); // get the difference between the two vectors for eval in input_evals.iter() { // delete first occurence of that value if let Some(pos) = fullset_evals.iter().position(|x| x == eval) { fullset_evals.remove(pos); } } // if fullset + input is the same length, then input is a subset of fullset, else randomly delete elements, this is a patch for // the fact that we can't have a tensor of unknowns when using constant during gen-settings if fullset_evals.len() != set_len - input.len() { fullset_evals.truncate(set_len - input.len()); } fullset_evals .par_iter() .map(|x| Value::known(i128_to_felt(*x))) .collect::<Tensor<Value<F>>>() .into() } else { let dim = fullset.len() - input.len(); Tensor::new(Some(&vec![Value::<F>::unknown(); dim]), &[dim])?.into() }; // assign the claimed output claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?; // input and claimed output should be the shuffles of fullset // concatentate input and claimed output let input_and_claimed_output = input.concat(claimed_output.clone())?; // assert that this is a permutation/shuffle shuffles( config, region, &[input_and_claimed_output.clone()], &[fullset.clone()], )?; if ordered { // assert that the claimed output is sorted claimed_output = _sort_ascending(config, region, &[claimed_output])?; } Ok(claimed_output) } /// Gather accumulated layout pub(crate) fn scatter_elements<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 3], dim: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { let (input, mut index, src) = (values[0].clone(), values[1].clone(), values[2].clone()); assert_eq!(input.dims().len(), index.dims().len()); if !index.all_prev_assigned() { index = region.assign(&config.custom_gates.inputs[1], &index)?; region.increment(index.len()); } let is_assigned = !input.any_unknowns()? && !index.any_unknowns()? && !src.any_unknowns()?; let claimed_output: ValTensor<F> = if is_assigned && region.witness_gen() { let input_inner = input.get_int_evals()?; let index_inner = index.get_int_evals()?.map(|x| x as usize); let src_inner = src.get_int_evals()?; let res = tensor::ops::scatter(&input_inner, &index_inner, &src_inner, dim)?; res.par_iter() .map(|x| Value::known(i128_to_felt(*x))) .collect::<Tensor<Value<F>>>() .into() } else { Tensor::new( Some(&vec![Value::<F>::unknown(); input.len()]), &[input.len()], )? .into() }; // assign the claimed output let mut claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?; region.increment(claimed_output.len()); claimed_output.reshape(input.dims())?; // scatter elements is the inverse of gather elements let (gather_src, linear_index) = gather_elements( config, region, &[claimed_output.clone(), index.clone()], dim, )?; // assert this is equal to the src enforce_equality(config, region, &[gather_src, src])?; let full_index_set: ValTensor<F> = Tensor::from((0..input.len() as u64).map(|x| ValType::Constant(F::from(x)))).into(); let input_indices = get_missing_set_elements( config, region, &[linear_index, full_index_set.clone()], true, )?; claimed_output.flatten(); let (gather_input, _) = gather_elements( config, region, &[claimed_output.clone(), input_indices.clone()], 0, )?; // assert this is a subset of the input dynamic_lookup( config, region, &[input_indices, gather_input], &[full_index_set, input.clone()], )?; claimed_output.reshape(input.dims())?; Ok(claimed_output) } /// Scatter Nd pub(crate) fn scatter_nd<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 3], ) -> Result<ValTensor<F>, Box<dyn Error>> { let (input, mut index, src) = (values[0].clone(), values[1].clone(), values[2].clone()); if !index.all_prev_assigned() { index = region.assign(&config.custom_gates.inputs[1], &index)?; region.increment(index.len()); } let is_assigned = !input.any_unknowns()? && !index.any_unknowns()? && !src.any_unknowns()?; let claimed_output: ValTensor<F> = if is_assigned && region.witness_gen() { let input_inner = input.get_int_evals()?; let index_inner = index.get_int_evals()?.map(|x| x as usize); let src_inner = src.get_int_evals()?; let res = tensor::ops::scatter_nd(&input_inner, &index_inner, &src_inner)?; res.par_iter() .map(|x| Value::known(i128_to_felt(*x))) .collect::<Tensor<Value<F>>>() .into() } else { Tensor::new( Some(&vec![Value::<F>::unknown(); input.len()]), &[input.len()], )? .into() }; // assign the claimed output let mut claimed_output = region.assign(&config.custom_gates.output, &claimed_output)?; region.increment(claimed_output.len()); claimed_output.reshape(input.dims())?; // scatter elements is the inverse of gather elements let (gather_src, linear_index) = gather_nd(config, region, &[claimed_output.clone(), index.clone()], 0)?; // assert this is equal to the src enforce_equality(config, region, &[gather_src, src])?; let full_index_set: ValTensor<F> = Tensor::from((0..input.len() as u64).map(|x| ValType::Constant(F::from(x)))).into(); let input_indices = get_missing_set_elements( config, region, &[linear_index, full_index_set.clone()], true, )?; // now that it is flattened we can gather over elements on dim 0 claimed_output.flatten(); let (gather_input, _) = gather_elements( config, region, &[claimed_output.clone(), input_indices.clone()], 0, )?; // assert this is a subset of the input dynamic_lookup( config, region, &[input_indices, gather_input], &[full_index_set, input.clone()], )?; claimed_output.reshape(input.dims())?; Ok(claimed_output) } /// Sums a tensor. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::sum; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = sum::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap(); /// let expected = 21; /// assert_eq!(result.get_int_evals().unwrap()[0], expected); /// ``` pub fn sum<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { region.flush()?; // time this entire function run let global_start = instant::Instant::now(); let mut values = values.clone(); // this section has been optimized to death, don't mess with it let mut removal_indices = values[0].get_const_zero_indices()?; removal_indices.par_sort_unstable(); removal_indices.dedup(); // is already sorted values[0].remove_indices(&mut removal_indices, true)?; let elapsed = global_start.elapsed(); trace!("filtering const zero indices took: {:?}", elapsed); // if empty return a const if values[0].is_empty() { return Ok(create_zero_tensor(1)); } let block_width = config.custom_gates.output.num_inner_cols(); let assigned_len: usize; let input = { let mut input = values[0].clone(); input.pad_to_zero_rem(block_width, ValType::Constant(F::ZERO))?; let (res, len) = region.assign_with_duplication( &config.custom_gates.inputs[1], &input, &config.check_mode, false, )?; assigned_len = len; res.get_inner()? }; // Now we can assign the dot product let accumulated_sum = accumulated::sum(&input, block_width)?; let (output, output_assigned_len) = region.assign_with_duplication( &config.custom_gates.output, &accumulated_sum.into(), &config.check_mode, true, )?; // enable the selectors if !region.is_dummy() { for i in 0..output_assigned_len { let (x, _, z) = config .custom_gates .output .cartesian_coord(region.linear_coord() + i * block_width); // skip over duplicates at start of column if z == 0 && i > 0 { continue; } let selector = if i == 0 { config.custom_gates.selectors.get(&(BaseOp::SumInit, x, 0)) } else { config.custom_gates.selectors.get(&(BaseOp::Sum, x, 0)) }; region.enable(selector, z)?; } } let last_elem = output.get_slice(&[output.len() - 1..output.len()])?; region.increment(assigned_len); // last element is the result Ok(last_elem) } /// Takes prod of tensor's elements. /// # Arguments /// /// * `a` - Tensor /// * `b` - Single value /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::prod; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = prod::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap(); /// let expected = 0; /// assert_eq!(result.get_int_evals().unwrap()[0], expected); /// ``` pub fn prod<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { region.flush()?; // time this entire function run let global_start = instant::Instant::now(); // this section has been optimized to death, don't mess with it let removal_indices = values[0].get_const_zero_indices()?; let elapsed = global_start.elapsed(); trace!("finding const zero indices took: {:?}", elapsed); // if empty return a const if !removal_indices.is_empty() { return Ok(create_zero_tensor(1)); } let block_width = config.custom_gates.output.num_inner_cols(); let assigned_len: usize; let input = { let mut input = values[0].clone(); input.pad_to_zero_rem(block_width, ValType::Constant(F::ONE))?; let (res, len) = region.assign_with_duplication( &config.custom_gates.inputs[1], &input, &config.check_mode, false, )?; assigned_len = len; res.get_inner()? }; // Now we can assign the dot product let accumulated_prod = accumulated::prod(&input, block_width)?; let (output, output_assigned_len) = region.assign_with_duplication( &config.custom_gates.output, &accumulated_prod.into(), &config.check_mode, true, )?; // enable the selectors if !region.is_dummy() { (0..output_assigned_len) .map(|i| { let (x, _, z) = config .custom_gates .output .cartesian_coord(region.linear_coord() + i * block_width); // skip over duplicates at start of column if z == 0 && i > 0 { return Ok(()); } let selector = if i == 0 { config .custom_gates .selectors .get(&(BaseOp::CumProdInit, x, 0)) } else { config.custom_gates.selectors.get(&(BaseOp::CumProd, x, 0)) }; region.enable(selector, z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } let last_elem = output.get_slice(&[output.len() - 1..output.len()])?; region.increment(assigned_len); // last element is the result Ok(last_elem) } /// Axes wise op wrapper fn axes_wise_op<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axes: &[usize], // generic layout op op: impl Fn( &BaseConfig<F>, &mut RegionCtx<F>, &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> + Send + Sync, ) -> Result<ValTensor<F>, Box<dyn Error>> { // calculate value of output let a = &values[0]; if axes.is_empty() { return Ok(a.clone()); } let mut new_dims = vec![]; for i in 0..a.dims().len() { if !axes.contains(&i) { new_dims.push(a.dims()[i]); } else { new_dims.push(1); } } let mut res = Tensor::new(None, &new_dims)?; let cartesian_coord = new_dims .iter() .map(|x| 0..*x) .multi_cartesian_product() .collect::<Vec<_>>(); let inner_loop_function = |i: usize, region: &mut RegionCtx<'_, F>| { let coord = cartesian_coord[i].clone(); let mut prod_dims = vec![]; for (i, c) in coord.iter().enumerate() { if axes.contains(&i) { prod_dims.push(0..a.dims()[i]); } else { prod_dims.push(*c..*c + 1); } } let values = a.get_slice(&prod_dims)?; let op = op(config, region, &[values])?; Ok(op.get_inner_tensor()?[0].clone()) }; region.apply_in_loop(&mut res, inner_loop_function)?; Ok(res.into()) } /// Takes product of a tensor along specific axes. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::prod_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = prod_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[60, 0]), /// &[2, 1], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn prod_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axes: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { // calculate value of output axes_wise_op(config, region, values, axes, prod) } /// Sums a tensor along specific axes. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::sum_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = sum_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[19, 2]), /// &[2, 1], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn sum_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axes: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { // calculate value of output axes_wise_op(config, region, values, axes, sum) } /// Argmax of a tensor along specific axes. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::argmax_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = argmax_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], 1).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[1, 0]), /// &[2, 1], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn argmax_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], dim: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { // these will be assigned as constants let argmax = move |config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1]| -> Result<ValTensor<F>, Box<dyn Error>> { argmax(config, region, values) }; // calculate value of output axes_wise_op(config, region, values, &[dim], argmax) } /// Max of a tensor along specific axes. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::max_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = max_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[15, 1]), /// &[2, 1], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn max_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axes: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { // calculate value of output axes_wise_op(config, region, values, axes, max) } /// Argmin of a tensor along specific axes. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::argmin_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = argmin_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], 1).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[0, 2]), /// &[2, 1], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn argmin_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], dim: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { // calculate value of output let argmin = move |config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1]| -> Result<ValTensor<F>, Box<dyn Error>> { argmin(config, region, values) }; axes_wise_op(config, region, values, &[dim], argmin) } /// Mins a tensor along specific axes. /// # Arguments /// /// * `a` - Tensor /// * `b` - Single value /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::min_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = min_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[2, 0]), /// &[2, 1], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn min_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axes: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { // calculate value of output axes_wise_op(config, region, values, axes, min) } /// Pairwise (elementwise) op layout pub(crate) fn pairwise<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], op: BaseOp, ) -> Result<ValTensor<F>, Box<dyn Error>> { // time to calculate the value of the output let global_start = instant::Instant::now(); let (mut lhs, mut rhs) = (values[0].clone(), values[1].clone()); let broadcasted_shape = get_broadcasted_shape(lhs.dims(), rhs.dims())?; lhs.expand(&broadcasted_shape)?; rhs.expand(&broadcasted_shape)?; // original values let orig_lhs = lhs.clone(); let orig_rhs = rhs.clone(); // get indices of zeros let first_zero_indices = lhs.get_const_zero_indices()?; let second_zero_indices = rhs.get_const_zero_indices()?; let mut removal_indices = match op { BaseOp::Add | BaseOp::Mult => { let mut removal_indices = first_zero_indices.clone(); removal_indices.extend(second_zero_indices.clone()); removal_indices } BaseOp::Sub => second_zero_indices.clone(), _ => return Err(Box::new(CircuitError::UnsupportedOp)), }; removal_indices.dedup(); let removal_indices: HashSet<&usize> = HashSet::from_iter(removal_indices.iter()); let removal_indices_ptr = &removal_indices; if lhs.len() != rhs.len() { return Err(Box::new(CircuitError::DimMismatch(format!( "pairwise {} layout", op.as_str() )))); } let mut inputs = vec![]; for (i, input) in [lhs.clone(), rhs.clone()].iter().enumerate() { let inp = { let res = region.assign_with_omissions( &config.custom_gates.inputs[i], input, removal_indices_ptr, )?; res.get_inner()? }; inputs.push(inp); } // Now we can assign the dot product // time the calc let start = instant::Instant::now(); let op_result = match op { BaseOp::Add => add(&inputs), BaseOp::Sub => sub(&inputs), BaseOp::Mult => mult(&inputs), _ => return Err(Box::new(CircuitError::UnsupportedOp)), } .map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis })?; let elapsed = start.elapsed(); let assigned_len = inputs[0].len() - removal_indices.len(); let mut output = region.assign_with_omissions( &config.custom_gates.output, &op_result.into(), removal_indices_ptr, )?; trace!("pairwise {} calc took {:?}", op.as_str(), elapsed); // Enable the selectors if !region.is_dummy() { (0..assigned_len) .map(|i| { let (x, y, z) = config.custom_gates.inputs[0].cartesian_coord(region.linear_coord() + i); let selector = config.custom_gates.selectors.get(&(op.clone(), x, y)); region.enable(selector, z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } region.increment(assigned_len); let a_tensor = orig_lhs.get_inner_tensor()?; let b_tensor = orig_rhs.get_inner_tensor()?; let first_zero_indices: HashSet<&usize> = HashSet::from_iter(first_zero_indices.iter()); let second_zero_indices: HashSet<&usize> = HashSet::from_iter(second_zero_indices.iter()); trace!("setting up indices took {:?}", start.elapsed()); // infill the zero indices with the correct values from values[0] or values[1] if !removal_indices_ptr.is_empty() { output .get_inner_tensor_mut()? .par_enum_map_mut_filtered(removal_indices_ptr, |i| { let val = match op { BaseOp::Add => { let a_is_null = first_zero_indices.contains(&i); let b_is_null = second_zero_indices.contains(&i); if a_is_null && b_is_null { ValType::Constant(F::ZERO) } else if a_is_null { b_tensor[i].clone() } else { a_tensor[i].clone() } } BaseOp::Sub => { let a_is_null = first_zero_indices.contains(&i); // by default b is null in this case for sub if a_is_null { ValType::Constant(F::ZERO) } else { a_tensor[i].clone() } } BaseOp::Mult => ValType::Constant(F::ZERO), // can safely panic as the prior check ensures this is not called _ => unreachable!(), }; Ok::<_, TensorError>(val) })?; } output.reshape(&broadcasted_shape)?; let end = global_start.elapsed(); trace!( "pairwise {} layout took {:?}, row: {}", op.as_str(), end, region.row() ); Ok(output) } /// Mean of squares axes /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::mean_of_squares_axes; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 15, 2, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = mean_of_squares_axes::<Fp>(&dummy_config, &mut dummy_region, &[x], &[1]).unwrap(); /// let expected = Tensor::<i128>::new( /// Some(&[78, 1]), /// &[2, 1], /// ).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn mean_of_squares_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axes: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let squared = pow(config, region, values, 2)?; let sum_squared = sum_axes(config, region, &[squared], axes)?; let dividand: usize = values[0].len() / sum_squared.len(); let mean_squared = div(config, region, &[sum_squared], F::from(dividand as u64))?; Ok(mean_squared) } /// expand the tensor to the given shape pub(crate) fn expand<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], shape: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut assigned_input = region.assign(&config.custom_gates.inputs[0], &values[0])?; assigned_input.expand(shape)?; region.increment(assigned_input.len()); Ok(assigned_input) } /// Greater than operation. /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::greater; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 12, 6, 4, 5, 6]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 4, 5, 6]), /// &[2, 3], /// ).unwrap()); /// let result = greater::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[0, 1, 1, 0, 0, 0]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn greater<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { let (mut lhs, mut rhs) = (values[0].clone(), values[1].clone()); let broadcasted_shape = get_broadcasted_shape(lhs.dims(), rhs.dims())?; lhs.expand(&broadcasted_shape)?; rhs.expand(&broadcasted_shape)?; let diff = pairwise(config, region, &[lhs, rhs], BaseOp::Sub)?; nonlinearity( config, region, &[diff], &LookupOp::GreaterThan { a: utils::F32(0.) }, ) } /// Greater equals than operation. /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::greater_equal; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 12, 6, 4, 3, 2]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 4, 5, 4]), /// &[2, 3], /// ).unwrap()); /// let result = greater_equal::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 1, 0, 0]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn greater_equal<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { let (mut lhs, mut rhs) = (values[0].clone(), values[1].clone()); let broadcasted_shape = get_broadcasted_shape(lhs.dims(), rhs.dims())?; lhs.expand(&broadcasted_shape)?; rhs.expand(&broadcasted_shape)?; let diff = pairwise(config, region, &[lhs, rhs], BaseOp::Sub)?; nonlinearity( config, region, &[diff], &LookupOp::GreaterThanEqual { a: utils::F32(0.) }, ) } /// Less than to operation. /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::less; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 5, 4, 5, 1]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 4, 5, 6]), /// &[2, 3], /// ).unwrap()); /// let result = less::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 0, 0, 1]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` /// pub fn less<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { // just flip the order and use greater greater(config, region, &[values[1].clone(), values[0].clone()]) } /// Less equals than operation. /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::less_equal; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 5, 4, 5, 1]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 4, 5, 6]), /// &[2, 3], /// ).unwrap()); /// let result = less_equal::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1, 1, 0, 1, 1, 1]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` /// pub fn less_equal<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { // just flip the order and use greater greater_equal(config, region, &[values[1].clone(), values[0].clone()]) } /// Elementwise applies and to two tensors /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::and; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 1, 1, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 1, 0, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = and::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1, 0, 1, 0, 1, 0]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn and<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { let a = boolean_identity(config, region, &[values[0].clone()], true)?; let b = boolean_identity(config, region, &[values[1].clone()], true)?; let res = pairwise(config, region, &[a, b], BaseOp::Mult)?; Ok(res) } /// Elementwise applies or to two tensors . /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::or; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 1, 1, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 1, 0, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = or::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1, 1, 1, 1, 1, 0]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn or<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { let a = values[0].clone(); let b = values[1].clone(); let b = boolean_identity(config, region, &[b], true)?; let iff_values = &[a.clone(), a, b]; let res = iff(config, region, iff_values)?; Ok(res) } /// Elementwise applies equals to two tensors . /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::equals; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 1, 1, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 1, 0, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = equals::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1, 0, 1, 0, 1, 1]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn equals<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { let diff = pairwise(config, region, values, BaseOp::Sub)?; equals_zero(config, region, &[diff]) } /// Equality boolean operation pub(crate) fn equals_zero<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { let values = values[0].clone(); let values_inverse = values.inverse()?; let product_values_and_invert = pairwise( config, region, &[values.clone(), values_inverse], BaseOp::Mult, )?; // constant of 1 let ones = create_unit_tensor(1); // subtract let output = pairwise( config, region, &[ones, product_values_and_invert], BaseOp::Sub, )?; // take the product of diff and output let prod_check = pairwise(config, region, &[values, output.clone()], BaseOp::Mult)?; let zero_tensor = create_zero_tensor(prod_check.len()); enforce_equality(config, region, &[prod_check, zero_tensor])?; Ok(output) } /// Elementwise applies xor to two tensors /// # Arguments /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::xor; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 1, 1, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 1, 0, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = xor::<Fp>(&dummy_config, &mut dummy_region, &[a,b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[0, 1, 0, 1, 0, 0]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` /// pub fn xor<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { let lhs = values[0].clone(); let rhs = values[1].clone(); let lhs_not = not(config, region, &[lhs.clone()])?; let rhs_not = not(config, region, &[rhs.clone()])?; let lhs_and_rhs_not = and(config, region, &[lhs, rhs_not.clone()])?; let lhs_not_and_rhs = and(config, region, &[rhs, lhs_not])?; // we can safely use add and not OR here because we know that lhs_and_rhs_not and lhs_not_and_rhs are =1 at different incices let res: ValTensor<F> = pairwise( config, region, &[lhs_and_rhs_not, lhs_not_and_rhs], BaseOp::Add, )?; Ok(res) } /// Elementwise applies not to a tensor . /// # Arguments /// * `a` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::not; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 1, 1, 1, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let result = not::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[0, 0, 0, 0, 0, 1]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn not<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { let mask = values[0].clone(); let unit = create_unit_tensor(1); let nil = create_zero_tensor(1); let res = iff(config, region, &[mask, nil, unit])?; Ok(res) } /// IFF operation. /// # Arguments /// * `mask` - Tensor of 0s and 1s /// * `a` - Tensor /// * `b` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::iff; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let mask = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 1, 0, 1, 0]), /// &[2, 3], /// ).unwrap()); /// let a = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 2, 3, 4, 5, 6]), /// &[2, 3], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[7, 8, 9, 10, 11, 12]), /// &[2, 3], /// ).unwrap()); /// let result = iff::<Fp>(&dummy_config, &mut dummy_region, &[mask, a, b]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[1, 8, 3, 10, 5, 12]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn iff<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 3], ) -> Result<ValTensor<F>, Box<dyn Error>> { // if mask > 0 then output a else output b let (mask, a, b) = (&values[0], &values[1], &values[2]); let unit = create_unit_tensor(1); // make sure mask is boolean let assigned_mask = boolean_identity(config, region, &[mask.clone()], true)?; let one_minus_mask = pairwise(config, region, &[unit, assigned_mask.clone()], BaseOp::Sub)?; let masked_a = pairwise(config, region, &[a.clone(), assigned_mask], BaseOp::Mult)?; let masked_b = pairwise(config, region, &[b.clone(), one_minus_mask], BaseOp::Mult)?; let res = pairwise(config, region, &[masked_a, masked_b], BaseOp::Add)?; Ok(res) } /// Negates a tensor. /// # Arguments /// /// * `a` - Tensor /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::neg; /// /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 1, 2, 1, 1, 1]), /// &[2, 3], /// ).unwrap()); /// let result = neg::<Fp>(&dummy_config, &mut dummy_region, &[x]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[-2, -1, -2, -1, -1, -1]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn neg<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { let nil = create_zero_tensor(1); pairwise(config, region, &[nil, values[0].clone()], BaseOp::Sub) } /// Applies sum pooling over ND tensor of shape B x C x D1 x D2 x ... x DN. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::sumpool; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]), /// &[1, 1, 3, 3], /// ).unwrap()); /// let pooled = sumpool::<Fp>(&dummy_config, &mut dummy_region, &[x.clone()], &vec![(0, 0); 2], &vec![1;2], &vec![2, 2], false).unwrap(); /// let expected: Tensor<i128> = Tensor::<i128>::new(Some(&[11, 8, 8, 10]), &[1, 1, 2, 2]).unwrap(); /// assert_eq!(pooled.get_int_evals().unwrap(), expected); /// /// // This time with normalization /// let pooled = sumpool::<Fp>(&dummy_config, &mut dummy_region, &[x], &vec![(0, 0); 2], &vec![1;2], &vec![2, 2], true).unwrap(); /// let expected: Tensor<i128> = Tensor::<i128>::new(Some(&[3, 2, 2, 3]), &[1, 1, 2, 2]).unwrap(); /// assert_eq!(pooled.get_int_evals().unwrap(), expected); /// ``` pub fn sumpool<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], padding: &[(usize, usize)], stride: &[usize], kernel_shape: &[usize], normalized: bool, ) -> Result<ValTensor<F>, Box<dyn Error>> { let batch_size = values[0].dims()[0]; let image_channels = values[0].dims()[1]; let kernel_len = kernel_shape.iter().product(); let mut kernel = create_unit_tensor(kernel_len); let mut kernel_dims = vec![1, 1]; kernel_dims.extend(kernel_shape); kernel.reshape(&kernel_dims)?; let kernel = region.assign(&config.custom_gates.inputs[1], &kernel)?; region.increment(kernel.len()); let cartesian_coord = [(0..batch_size), (0..image_channels)] .iter() .cloned() .multi_cartesian_product() .collect::<Vec<_>>(); let mut res = vec![]; cartesian_coord .iter() .map(|coord| { let (b, i) = (coord[0], coord[1]); let input = values[0].get_slice(&[b..b + 1, i..i + 1])?; let output = conv(config, region, &[input, kernel.clone()], padding, stride)?; res.push(output); Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; let shape = &res[0].dims()[2..]; let mut last_elem = res[1..] .iter() .try_fold(res[0].clone(), |acc, elem| acc.concat(elem.clone()))?; last_elem.reshape(&[&[batch_size, image_channels], shape].concat())?; if normalized { last_elem = loop_div(config, region, &[last_elem], F::from(kernel_len as u64))?; } Ok(last_elem) } /// Applies max pooling over a ND tensor of shape B x C x D1 x D2 x ... x DN. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::max_pool; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]), /// &[1, 1, 3, 3], /// ).unwrap()); /// let pooled = max_pool::<Fp>(&dummy_config, &mut dummy_region, &[x], &vec![(0, 0); 2], &vec![1;2], &vec![2;2]).unwrap(); /// let expected: Tensor<i128> = Tensor::<i128>::new(Some(&[5, 4, 4, 6]), &[1, 1, 2, 2]).unwrap(); /// assert_eq!(pooled.get_int_evals().unwrap(), expected); /// /// ``` pub fn max_pool<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], padding: &[(usize, usize)], stride: &[usize], pool_dims: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let image = values[0].clone(); let image_dims = image.dims(); let (batch, input_channels) = (image_dims[0], image_dims[1]); let mut padded_image = image.clone(); padded_image.pad(padding.to_vec(), 2)?; let slides = image_dims[2..] .iter() .enumerate() .map(|(i, d)| { let d = padding[i].0 + d + padding[i].1; d.checked_sub(pool_dims[i]) .ok_or_else(|| TensorError::Overflow("conv".to_string()))? .checked_div(stride[i]) .ok_or_else(|| TensorError::Overflow("conv".to_string()))? .checked_add(1) .ok_or_else(|| TensorError::Overflow("conv".to_string())) }) .collect::<Result<Vec<_>, TensorError>>()?; let mut output_dims = vec![batch, input_channels]; output_dims.extend(slides); let mut output: Tensor<ValType<F>> = Tensor::new(None, &output_dims)?; let cartesian_coord = output_dims .iter() .map(|x| 0..*x) .multi_cartesian_product() .collect::<Vec<_>>(); output .iter_mut() .enumerate() .map(|(flat_index, o)| { let coord = &cartesian_coord[flat_index]; let (b, i) = (coord[0], coord[1]); let mut slice = vec![b..b + 1, i..i + 1]; slice.extend( coord[2..] .iter() .zip(stride.iter()) .zip(pool_dims.iter()) .map(|((c, s), k)| { let start = c * s; let end = start + k; start..end }), ); let slice = padded_image.get_slice(&slice)?; let max_w = max(config, region, &[slice])?; *o = max_w.get_inner_tensor()?[0].clone(); Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; let res: ValTensor<F> = output.into(); Ok(res) } /// Performs a deconvolution on the given input tensor. /// # Examples /// ``` // // expected ouputs are taken from pytorch torch.nn.functional.conv_transpose2d /// /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::deconv; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// use ezkl::tensor::ValTensor; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let c = ValTensor::from_i128_tensor(Tensor::<i128>::new(Some(&[6, 0, 12, 4, 0, 8, 0, 0, 3, 0, 0, 2]), &[1, 2, 2, 3]).unwrap()); /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, c], &vec![(1, 1); 2], &vec![1;2], &vec![2;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[0, 32, 0, 32, 0, 6, 0, 12, 0, 4, 0, 8, 0, 4, 0, 8, 0, 0, 0, 3, 0, 0, 0, 2]), &[1, 2, 3, 4]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[3, 1, 1, 5]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(0, 0); 2], &vec![0;2], &vec![1;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[6, 14, 4, 2, 17, 21, 0, 1, 5]), &[1, 1, 3, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[3, 1, 1, 5]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(1, 1); 2], &vec![0;2], &vec![1;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[17]), &[1, 1, 1, 1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[3, 1, 1, 5]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(1, 1); 2], &vec![0;2], &vec![2; 2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[10, 4, 0, 3]), &[1, 1, 2, 2]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[3, 1, 1, 5]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(0, 0); 2], &vec![0;2], &vec![2; 2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[6, 2, 12, 4, 2, 10, 4, 20, 0, 0, 3, 1, 0, 0, 1, 5]), &[1, 1, 4, 4]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[3, 2]), /// &[1, 1, 2, 1], /// ).unwrap()); /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(1, 1); 2], &vec![0;2], &vec![2; 2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[0, 0]), &[1, 1, 2, 1]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[3, 2]), /// &[1, 1, 2, 1], /// ).unwrap()); /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k], &vec![(0, 0); 2], &vec![0;2], &vec![2; 2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[6, 0, 12, 4, 0, 8, 0, 0, 3, 0, 0, 2]), &[1, 1, 4, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// /// let c = ValTensor::from_i128_tensor(Tensor::<i128>::new(Some(&[6, 0, 12, 4, 0, 8, 0, 0, 3, 0, 0, 2]), &[1, 2, 2, 3]).unwrap()); /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 4, 0, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, c], &vec![(1, 1); 2], &vec![0;2], &vec![2;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[0, 32, 0, 0, 6, 0, 0, 4, 0, 0, 0, 0]), &[1, 2, 2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[3, 8, 0, 8, 4, 9, 8, 1, 8]), /// &[1, 1, 3, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 0, 4, 6]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1]), /// &[1], /// ).unwrap()); /// let result = deconv::<Fp>(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(1, 1); 2], &vec![0;2], &vec![1;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[55, 58, 66, 69]), &[1, 1, 2, 2]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// ``` pub fn deconv< F: PrimeField + TensorType + PartialOrd + std::hash::Hash + std::marker::Send + std::marker::Sync, >( config: &BaseConfig<F>, region: &mut RegionCtx<F>, inputs: &[ValTensor<F>], padding: &[(usize, usize)], output_padding: &[usize], stride: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let has_bias = inputs.len() == 3; let (image, kernel) = (&inputs[0], &inputs[1]); if stride.iter().any(|&s| s == 0) { return Err(Box::new(TensorError::DimMismatch( "non-positive stride is not supported for deconv".to_string(), ))); } let null_val = ValType::Constant(F::ZERO); let mut expanded_image = image.clone(); for (i, s) in stride.iter().enumerate() { expanded_image.intercalate_values(null_val.clone(), *s, 2 + i)?; } expanded_image.pad( kernel.dims()[2..] .iter() .map(|d| (d - 1, d - 1)) .collect::<Vec<_>>(), 2, )?; // pad to the kernel size // flip order let channel_coord = (0..kernel.dims()[0]) .cartesian_product(0..kernel.dims()[1]) .collect::<Vec<_>>(); let slice_coord = expanded_image .dims() .iter() .enumerate() .map(|(i, d)| { if i >= 2 { padding[i - 2].0..d - padding[i - 2].1 + output_padding[i - 2] } else { 0..*d } }) .collect::<Vec<_>>(); let sliced_expanded_image = expanded_image.get_slice(&slice_coord)?; let mut inverted_kernels = vec![]; for (i, j) in channel_coord { let channel = kernel.get_slice(&[i..i + 1, j..j + 1])?; let mut channel = Tensor::from(channel.get_inner_tensor()?.clone().into_iter().rev()); channel.reshape(&kernel.dims()[2..])?; inverted_kernels.push(channel); } let mut deconv_kernel = Tensor::new(Some(&inverted_kernels), &[inverted_kernels.len()])?.combine()?; deconv_kernel.reshape(kernel.dims())?; // tensorflow formatting patch if kernel.dims()[0] == sliced_expanded_image.dims()[1] { let mut dims = deconv_kernel.dims().to_vec(); dims.swap(0, 1); deconv_kernel.reshape(&dims)?; } let conv_input = if has_bias { vec![ sliced_expanded_image, deconv_kernel.clone().into(), inputs[2].clone(), ] } else { vec![sliced_expanded_image, deconv_kernel.clone().into()] }; let conv_dim = kernel.dims()[2..].len(); let output = conv( config, region, &conv_input, &vec![(0, 0); conv_dim], &vec![1; conv_dim], )?; Ok(output) } /// Applies convolution over a ND tensor of shape C x H x D1...DN (and adds a bias). /// ``` /// // expected ouputs are taken from pytorch torch.nn.functional.conv2d /// /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::conv; /// use ezkl::tensor::val::ValTensor; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6]), /// &[1, 1, 3, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 1, 1, 1]), /// &[1, 1, 2, 2], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[0]), /// &[1], /// ).unwrap()); /// let result = conv::<Fp>(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(0, 0); 2], &vec![1;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[31, 16, 8, 26]), &[1, 1, 2, 2]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// // Now test single channel /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6, 5, 2, 3, 0, 4, -1, 3, 1, 6]), /// &[1, 2, 3, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 1, 1, 1, 5, 2, 1, 1]), /// &[2, 1, 2, 2], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 1]), /// &[2], /// ).unwrap()); /// /// let result = conv::<Fp>(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(0, 0); 2], &vec![1;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[32, 17, 9, 27, 34, 20, 13, 26]), &[1, 2, 2, 2]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// /// // Now test multi channel /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 2, 3, 0, 4, -1, 3, 1, 6, 5, 2, 3, 0, 4, -1, 3, 1, 6]), /// &[1, 2, 3, 3], /// ).unwrap()); /// let k = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[5, 1, 1, 1, 5, 2, 1, 1, 5, 3, 1, 1, 5, 4, 1, 1, 5, 1, 1, 1, 5, 2, 1, 1, 5, 3, 1, 1, 5, 4, 1, 1]), /// &[4, 2, 2, 2], /// ).unwrap()); /// let b = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[1, 1, 1, 1]), /// &[4], /// ).unwrap()); /// /// let result =conv(&dummy_config, &mut dummy_region, &[x, k, b], &vec![(0, 0); 2], &vec![1;2]).unwrap(); /// let expected = Tensor::<i128>::new(Some(&[65, 36, 21, 52, 73, 48, 37, 48, 65, 36, 21, 52, 73, 48, 37, 48]), &[1, 4, 2, 2]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` /// pub fn conv< F: PrimeField + TensorType + PartialOrd + std::hash::Hash + std::marker::Send + std::marker::Sync, >( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], padding: &[(usize, usize)], stride: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let has_bias = values.len() == 3; let (mut image, mut kernel) = (values[0].clone(), values[1].clone()); if stride.iter().any(|&s| s == 0) { return Err(Box::new(TensorError::DimMismatch( "non-positive stride is not supported for conv".to_string(), ))); } // we specifically want to use the same kernel and image for all the convolutions and need to enforce this by assigning them // 1. assign the kernel let mut assigned_len = vec![]; if !kernel.all_prev_assigned() { kernel = region.assign(&config.custom_gates.inputs[0], &kernel)?; assigned_len.push(kernel.len()); } // 2. assign the image if !image.all_prev_assigned() { image = region.assign(&config.custom_gates.inputs[1], &image)?; assigned_len.push(image.len()); } if !assigned_len.is_empty() { // safe to unwrap since we've just checked it has at least one element region.increment(*assigned_len.iter().max().unwrap()); } let image_dims = image.dims(); let kernel_dims = kernel.dims(); let mut padded_image = image.clone(); padded_image.pad(padding.to_vec(), 2)?; let batch_size = image_dims[0]; let input_channels = image_dims[1]; let output_channels = kernel_dims[0]; log::debug!( "batch_size: {}, output_channels: {}, input_channels: {}", batch_size, output_channels, input_channels ); let slides = image_dims[2..] .iter() .enumerate() .map(|(i, d)| { let d = padding[i].0 + d + padding[i].1; d.checked_sub(kernel_dims[i + 2]) .ok_or_else(|| TensorError::Overflow("conv".to_string()))? .checked_div(stride[i]) .ok_or_else(|| TensorError::Overflow("conv".to_string()))? .checked_add(1) .ok_or_else(|| TensorError::Overflow("conv".to_string())) }) .collect::<Result<Vec<_>, TensorError>>()?; log::debug!("slides: {:?}", slides); let num_groups = input_channels / kernel_dims[1]; let input_channels_per_group = input_channels / num_groups; let output_channels_per_group = output_channels / num_groups; log::debug!( "num_groups: {}, input_channels_per_group: {}, output_channels_per_group: {}", num_groups, input_channels_per_group, output_channels_per_group ); if output_channels_per_group == 0 { return Err(Box::new(TensorError::DimMismatch(format!( "Given groups={}, expected kernel to be at least {} at dimension 0 but got {} instead", num_groups, num_groups, output_channels_per_group )))); } let num_outputs = batch_size * num_groups * output_channels_per_group * slides.iter().product::<usize>(); log::debug!("num_outputs: {}", num_outputs); let mut output: Tensor<ValType<F>> = Tensor::new(None, &[num_outputs])?; let mut iterations = vec![0..batch_size, 0..num_groups, 0..output_channels_per_group]; for slide in slides.iter() { iterations.push(0..*slide); } let cartesian_coord = iterations .iter() .cloned() .multi_cartesian_product() .collect::<Vec<_>>(); let inner_loop_function = |idx: usize, region: &mut RegionCtx<F>| { let cartesian_coord_per_group = &cartesian_coord[idx]; let (batch, group, i) = ( cartesian_coord_per_group[0], cartesian_coord_per_group[1], cartesian_coord_per_group[2], ); let start_channel = group * input_channels_per_group; let end_channel = start_channel + input_channels_per_group; let mut slices = vec![batch..batch + 1, start_channel..end_channel]; for (i, stride) in stride.iter().enumerate() { let coord = cartesian_coord_per_group[3 + i] * stride; let kernel_dim = kernel_dims[2 + i]; slices.push(coord..(coord + kernel_dim)); } let mut local_image = padded_image.get_slice(&slices)?; local_image.flatten(); let start_kernel_index = group * output_channels_per_group + i; let end_kernel_index = start_kernel_index + 1; let mut local_kernel = kernel.get_slice(&[start_kernel_index..end_kernel_index])?; local_kernel.flatten(); // this is dot product notation in einsum format let mut res = einsum(config, region, &[local_image, local_kernel], "i,i->")?; if has_bias { let bias_index = if values[2].len() > 1 { start_kernel_index } else { 0 }; let bias = values[2].get_single_elem(bias_index)?; res = pairwise(config, region, &[res, bias], BaseOp::Add)?; } region.flush()?; Ok(res.get_inner_tensor()?[0].clone()) }; region.flush()?; region.apply_in_loop(&mut output, inner_loop_function)?; let reshape_output = |output: &mut Tensor<ValType<F>>| -> Result<(), TensorError> { // remove dummy batch dimension if we added one let mut dims = vec![batch_size, output_channels]; dims.extend(slides.iter().cloned()); output.reshape(&dims)?; Ok(()) }; // remove dummy batch dimension if we added one reshape_output(&mut output)?; let output: ValTensor<_> = output.into(); Ok(output) } /// Power accumulated layout pub(crate) fn pow<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], exponent: u32, ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut t = values[0].clone(); for _ in 1..exponent { t = pairwise(config, region, &[t, values[0].clone()], BaseOp::Mult)?; } Ok(t) } /// Rescaled op accumulated layout pub(crate) fn rescale<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], scales: &[(usize, u128)], ) -> Result<Vec<ValTensor<F>>, Box<dyn Error>> { let mut rescaled_inputs = vec![]; for (i, ri) in values.iter().enumerate() { if scales[i].1 == 1 { rescaled_inputs.push(ri.clone()); continue; } let multiplier = create_constant_tensor(F::from(scales[i].1 as u64), 1); let scaled_input = pairwise(config, region, &[ri.clone(), multiplier], BaseOp::Mult)?; rescaled_inputs.push(scaled_input); } Ok(rescaled_inputs) } /// Dummy (no contraints) reshape layout pub(crate) fn reshape<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( values: &[ValTensor<F>; 1], new_dims: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut t = values[0].clone(); t.reshape(new_dims)?; Ok(t) } /// Dummy (no contraints) move_axis layout pub(crate) fn move_axis<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( values: &[ValTensor<F>; 1], source: usize, destination: usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut t = values[0].clone(); t.move_axis(source, destination)?; Ok(t) } /// resize layout pub(crate) fn resize<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], scales: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut output = region.assign(&config.custom_gates.output, &values[0])?; region.increment(output.len()); output.resize(scales)?; Ok(output) } /// Slice layout pub(crate) fn slice<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axis: &usize, start: &usize, end: &usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { // assigns the instance to the advice. let mut output = values[0].clone(); let is_assigned = output.all_prev_assigned(); if !is_assigned { output = region.assign(&config.custom_gates.output, &values[0])?; region.increment(output.len()); } output.slice(axis, start, end)?; Ok(output) } /// Trilu layout pub(crate) fn trilu<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], k: &i32, upper: &bool, ) -> Result<ValTensor<F>, Box<dyn Error>> { // assigns the instance to the advice. let mut output = values[0].clone(); let is_assigned = output.all_prev_assigned(); if !is_assigned { output = region.assign(&config.custom_gates.inputs[0], &values[0])?; } let res = tensor::ops::trilu(output.get_inner_tensor()?, *k, *upper)?; let output = region.assign(&config.custom_gates.output, &res.into())?; region.increment(output.len()); Ok(output) } /// Concat layout pub(crate) fn concat<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( values: &[ValTensor<F>], axis: &usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { let collected_inner: Result<Vec<&Tensor<_>>, _> = values.iter().map(|e| e.get_inner_tensor()).collect(); let collected_inner = collected_inner?; Ok(tensor::ops::concat(&collected_inner, *axis)?.into()) } /// Identity constraint. Usually used to constrain an instance column to an advice so the returned cells / values can be operated upon. pub(crate) fn identity<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut output = values[0].clone(); if !output.all_prev_assigned() { output = region.assign(&config.custom_gates.output, &values[0])?; region.increment(output.len()); } Ok(output) } /// Boolean identity constraint. Usually used to constrain an instance column to an advice so the returned cells / values can be operated upon. pub(crate) fn boolean_identity<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], assign: bool, ) -> Result<ValTensor<F>, Box<dyn Error>> { let output = if assign || !values[0].get_const_indices()?.is_empty() { // get zero constants indices let output = region.assign(&config.custom_gates.output, &values[0])?; region.increment(output.len()); output } else { values[0].clone() }; // Enable the selectors if !region.is_dummy() { (0..output.len()) .map(|j| { let index = region.linear_coord() - j - 1; let (x, y, z) = config.custom_gates.output.cartesian_coord(index); let selector = config .custom_gates .selectors .get(&(BaseOp::IsBoolean, x, y)); region.enable(selector, z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } Ok(output) } /// Downsample layout pub(crate) fn downsample<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axis: &usize, stride: &usize, modulo: &usize, ) -> Result<ValTensor<F>, Box<dyn Error>> { let input = region.assign(&config.custom_gates.inputs[0], &values[0])?; let processed_output = tensor::ops::downsample(input.get_inner_tensor()?, *axis, *stride, *modulo)?; let output = region.assign(&config.custom_gates.output, &processed_output.into())?; region.increment(std::cmp::max(input.len(), output.len())); Ok(output) } /// layout for enforcing two sets of cells to be equal pub(crate) fn enforce_equality<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], ) -> Result<ValTensor<F>, Box<dyn Error>> { // assert of same len if values[0].len() != values[1].len() { return Err(Box::new(TensorError::DimMismatch( "enforce_equality".to_string(), ))); } // assigns the instance to the advice. let input = region.assign(&config.custom_gates.inputs[1], &values[0])?; let output = region.assign(&config.custom_gates.output, &values[1])?; if !region.is_dummy() { region.constrain_equal(&input, &output)?; } region.increment(output.len()); Ok(output) } /// layout for range check. pub(crate) fn range_check<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], range: &crate::circuit::table::Range, ) -> Result<ValTensor<F>, Box<dyn Error>> { region.add_used_range_check(*range)?; // time the entire operation let timer = instant::Instant::now(); let x = values[0].clone(); let w = region.assign(&config.range_checks.input, &x)?; let assigned_len = x.len(); let is_dummy = region.is_dummy(); let table_index: ValTensor<F> = w .get_inner_tensor()? .par_enum_map(|_, e| { Ok::<ValType<F>, TensorError>(if let Some(f) = e.get_felt_eval() { let col_idx = if !is_dummy { let table = config .range_checks .ranges .get(range) .ok_or(TensorError::TableLookupError)?; table.get_col_index(f) } else { F::ZERO }; Value::known(col_idx).into() } else { Value::<F>::unknown().into() }) })? .into(); region.assign(&config.range_checks.index, &table_index)?; if !is_dummy { (0..assigned_len) .map(|i| { let (x, y, z) = config .range_checks .input .cartesian_coord(region.linear_coord() + i); let selector = config.range_checks.selectors.get(&(*range, x, y)); region.enable(selector, z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } let is_assigned = !w.any_unknowns()?; if is_assigned && region.witness_gen() { // assert is within range let int_values = w.get_int_evals()?; for v in int_values.iter() { if v < &range.0 || v > &range.1 { log::error!("Value ({:?}) out of range: {:?}", v, range); return Err(Box::new(TensorError::TableLookupError)); } } } region.increment(assigned_len); let elapsed = timer.elapsed(); trace!( "range check {:?} layout took {:?}, row: {:?}", range, elapsed, region.row() ); Ok(w) } /// layout for nonlinearity check. pub(crate) fn nonlinearity<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], nl: &LookupOp, ) -> Result<ValTensor<F>, Box<dyn Error>> { region.add_used_lookup(nl.clone(), values)?; // time the entire operation let timer = instant::Instant::now(); let x = values[0].clone(); let removal_indices = values[0].get_const_indices()?; let removal_indices: HashSet<&usize> = HashSet::from_iter(removal_indices.iter()); let removal_indices_ptr = &removal_indices; let w = region.assign_with_omissions(&config.static_lookups.input, &x, removal_indices_ptr)?; let output = w.get_inner_tensor()?.par_enum_map(|i, e| { Ok::<_, TensorError>(if let Some(f) = e.get_felt_eval() { if !removal_indices.contains(&i) { Value::known(nl.f(&[Tensor::from(vec![f].into_iter())])?.output[0]).into() } else { ValType::Constant(nl.f(&[Tensor::from(vec![f].into_iter())])?.output[0]) } } else { Value::<F>::unknown().into() }) })?; let assigned_len = x.len() - removal_indices.len(); let mut output = region.assign_with_omissions( &config.static_lookups.output, &output.into(), removal_indices_ptr, )?; let is_dummy = region.is_dummy(); let table_index: ValTensor<F> = w .get_inner_tensor()? .par_enum_map(|i, e| { Ok::<_, TensorError>(if let Some(f) = e.get_felt_eval() { let col_idx = if !is_dummy { let table = config .static_lookups .tables .get(nl) .ok_or(TensorError::TableLookupError)?; table.get_col_index(f) } else { F::ZERO }; if !removal_indices.contains(&i) { Value::known(col_idx).into() } else { ValType::Constant(col_idx) } } else { Value::<F>::unknown().into() }) })? .into(); region.assign_with_omissions( &config.static_lookups.index, &table_index, removal_indices_ptr, )?; if !is_dummy { (0..assigned_len) .map(|i| { let (x, y, z) = config .static_lookups .input .cartesian_coord(region.linear_coord() + i); let selector = config.static_lookups.selectors.get(&(nl.clone(), x, y)); region.enable(selector, z)?; Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; } region.increment(assigned_len); output.reshape(x.dims())?; let elapsed = timer.elapsed(); trace!( "nonlinearity {} layout took {:?}, row: {:?}", <LookupOp as Op<F>>::as_string(nl), elapsed, region.row() ); // constrain the calculated output to a column Ok(output) } /// Argmax pub(crate) fn argmax<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { // this is safe because we later constrain it let argmax = values[0] .get_int_evals()? .into_par_iter() .enumerate() // we value the first index in the case of a tie .max_by_key(|(idx, value)| (*value, -(*idx as i64))) .map(|(idx, _)| idx as i128); let argmax_val: ValTensor<F> = match argmax { None => Tensor::new(Some(&[Value::<F>::unknown()]), &[1])?.into(), Some(i) => Tensor::new(Some(&[Value::known(i128_to_felt::<F>(i))]), &[1])?.into(), }; let assigned_argmax: ValTensor<F> = region.assign(&config.custom_gates.inputs[1], &argmax_val)?; region.increment(assigned_argmax.len()); let claimed_val = select( config, region, &[values[0].clone(), assigned_argmax.clone()], )?; let max_val = max(config, region, &[values[0].clone()])?; enforce_equality(config, region, &[claimed_val, max_val])?; Ok(assigned_argmax) } /// Argmin pub(crate) fn argmin<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { // this is safe because we later constrain it let argmin = values[0] .get_int_evals()? .into_par_iter() .enumerate() // we value the first index in the case of a tie .min_by_key(|(idx, value)| (*value, (*idx as i64))) .map(|(idx, _)| idx as i128); let argmin_val: ValTensor<F> = match argmin { None => Tensor::new(Some(&[Value::<F>::unknown()]), &[1])?.into(), Some(i) => Tensor::new(Some(&[Value::known(i128_to_felt::<F>(i))]), &[1])?.into(), }; let assigned_argmin: ValTensor<F> = region.assign(&config.custom_gates.inputs[1], &argmin_val)?; region.increment(assigned_argmin.len()); // these will be assigned as constants let claimed_val = select( config, region, &[values[0].clone(), assigned_argmin.clone()], )?; let min_val = min(config, region, &[values[0].clone()])?; enforce_equality(config, region, &[claimed_val, min_val])?; Ok(assigned_argmin) } /// max layout pub(crate) fn max<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { let input_len = values[0].len(); _sort_ascending(config, region, values)?.get_slice(&[input_len - 1..input_len]) } /// min layout pub(crate) fn min<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> { _sort_ascending(config, region, values)?.get_slice(&[0..1]) } fn multi_dim_axes_op<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], axes: &[usize], op: impl Fn( &BaseConfig<F>, &mut RegionCtx<F>, &[ValTensor<F>; 1], ) -> Result<ValTensor<F>, Box<dyn Error>> + Send + Sync, ) -> Result<ValTensor<F>, Box<dyn Error>> { let mut input = values[0].clone(); if !input.all_prev_assigned() { input = region.assign(&config.custom_gates.inputs[0], &input)?; region.increment(input.len()); } if input.dims().len() == 1 { return op(config, region, &[input]); } // Calculate the output tensor size let input_dims = input.dims(); let mut sorted_axes = axes.to_vec(); // descending order sorted_axes.sort_by(|x, y| y.cmp(x)); let mut output_size_without_dim = input_dims.to_vec(); for dim in &sorted_axes { output_size_without_dim.remove(*dim); } let mut op_tensors = Tensor::<ValTensor<F>>::new(None, &output_size_without_dim)?; // Allocate memory for the output tensor let cartesian_coord = output_size_without_dim .iter() .map(|x| 0..*x) .multi_cartesian_product() .collect::<Vec<_>>(); let inner_loop_function = |i: usize, region: &mut RegionCtx<F>| { let coord = cartesian_coord[i].clone(); let mut slice = coord.iter().map(|x| *x..*x + 1).collect::<Vec<_>>(); for dim in &sorted_axes { slice.insert(*dim, 0..input_dims[*dim]); } let mut sliced_input = input.get_slice(&slice)?; sliced_input.flatten(); Ok(op(config, region, &[sliced_input])?) }; region.apply_in_loop(&mut op_tensors, inner_loop_function)?; // assert all op_tensors have the same dims let sample_op_output_size = op_tensors[0].dims(); // now deduce the output size from the dims of the output tensors let mut output_size = input_dims.to_vec(); for dim in axes.iter().enumerate() { output_size[*dim.1] = sample_op_output_size[dim.0]; } // Allocate memory for the output tensor let cartesian_coord = output_size .iter() .map(|x| 0..*x) .multi_cartesian_product() .collect::<Vec<_>>(); let mut output = Tensor::<ValType<F>>::new(None, &output_size)?; output = output.par_enum_map(|i, _| { let coord = cartesian_coord[i].clone(); let mut op_idx = coord.clone(); let mut coord_at_dims = vec![]; for dim in &sorted_axes { op_idx.remove(*dim); } for dim in axes { coord_at_dims.push(coord[*dim]); } let topk_elem = op_tensors .get(&op_idx) .get_inner_tensor()? .get(&coord_at_dims) .clone(); Ok::<_, region::RegionError>(topk_elem) })?; Ok(output.into()) } /// softmax layout pub(crate) fn softmax_axes<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], input_scale: utils::F32, output_scale: utils::F32, axes: &[usize], ) -> Result<ValTensor<F>, Box<dyn Error>> { let soft_max_at_scale = move |config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1]| -> Result<ValTensor<F>, Box<dyn Error>> { softmax(config, region, values, input_scale, output_scale) }; let output = multi_dim_axes_op(config, region, values, axes, soft_max_at_scale)?; Ok(output) } /// percent func pub(crate) fn percent<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], input_scale: utils::F32, output_scale: utils::F32, ) -> Result<ValTensor<F>, Box<dyn Error>> { let is_assigned = values[0].all_prev_assigned(); let mut input = values[0].clone(); if !is_assigned { input = region.assign(&config.custom_gates.inputs[0], &values[0])?; region.increment(input.len()); }; // sum of exps let denom = sum(config, region, &[input.clone()])?; let input_felt_scale = F::from(input_scale.0 as u64); let output_felt_scale = F::from(output_scale.0 as u64); let inv_denom = recip( config, region, &[denom], input_felt_scale, output_felt_scale, )?; // product of num * (1 / denom) = 2*output_scale let percent = pairwise(config, region, &[input, inv_denom], BaseOp::Mult)?; // rebase the percent to 2x the scale loop_div(config, region, &[percent], input_felt_scale) } /// Applies softmax /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::softmax; /// use ezkl::tensor::val::ValTensor; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[2, 2, 3, 2, 2, 0]), /// &[2, 3], /// ).unwrap()); /// let result = softmax::<Fp>(&dummy_config, &mut dummy_region, &[x], 128.0.into(), (128.0 * 128.0).into()).unwrap(); /// // doubles the scale of the input /// let expected = Tensor::<i128>::new(Some(&[2734, 2734, 2756, 2734, 2734, 2691]), &[2, 3]).unwrap(); /// assert_eq!(result.get_int_evals().unwrap(), expected); /// ``` pub fn softmax<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 1], input_scale: utils::F32, output_scale: utils::F32, ) -> Result<ValTensor<F>, Box<dyn Error>> { // get the max then subtract it let max_val = max(config, region, values)?; // rebase the input to 0 let sub = pairwise(config, region, &[values[0].clone(), max_val], BaseOp::Sub)?; // elementwise exponential let ex = nonlinearity( config, region, &[sub], &LookupOp::Exp { scale: input_scale }, )?; percent(config, region, &[ex.clone()], input_scale, output_scale) } /// Checks that the percent error between the expected public output and the actual output value /// is within the percent error expressed by the `tol` input, where `tol == 1.0` means the percent /// error tolerance is 1 percent. /// # Examples /// ``` /// use ezkl::tensor::Tensor; /// use ezkl::circuit::ops::layouts::range_check_percent; /// use ezkl::tensor::val::ValTensor; /// use halo2curves::bn256::Fr as Fp; /// use ezkl::circuit::region::RegionCtx; /// use ezkl::circuit::BaseConfig; /// /// let dummy_config = BaseConfig::dummy(12, 2); /// let mut dummy_region = RegionCtx::new_dummy(0,2,true); /// /// let x = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[100, 200, 300, 400, 500, 600]), /// &[2, 3], /// ).unwrap()); /// let y = ValTensor::from_i128_tensor(Tensor::<i128>::new( /// Some(&[101, 201, 302, 403, 503, 603]), /// &[2, 3], /// ).unwrap()); /// let result = range_check_percent::<Fp>(&dummy_config, &mut dummy_region, &[x, y], 1024.0.into(), 1.0).unwrap(); /// ``` pub fn range_check_percent<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( config: &BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>; 2], scale: utils::F32, tol: f32, ) -> Result<ValTensor<F>, Box<dyn Error>> { if tol == 0.0 { // regular equality constraint return enforce_equality(config, region, values); } let mut values = [values[0].clone(), values[1].clone()]; values[0] = region.assign(&config.custom_gates.inputs[0], &values[0])?; values[1] = region.assign(&config.custom_gates.inputs[1], &values[1])?; let total_assigned_0 = values[0].len(); let total_assigned_1 = values[1].len(); let total_assigned = std::cmp::max(total_assigned_0, total_assigned_1); region.increment(total_assigned); // Calculate the difference between the expected output and actual output let diff = pairwise(config, region, &values, BaseOp::Sub)?; // integer scale let int_scale = scale.0 as i128; // felt scale let felt_scale = i128_to_felt(int_scale); // range check len capped at 2^(S-3) and make it divisible 2 let range_check_bracket = std::cmp::min( utils::F32(scale.0), utils::F32(2_f32.powf((F::S - 5) as f32)), ) .0; let range_check_bracket_int = range_check_bracket as i128; // input scale ratio we multiply by tol such that in the new scale range_check_len represents tol percent let input_scale_ratio = ((scale.0.powf(2.0) / range_check_bracket) * tol) as i128 / 2 * 2; let recip = recip( config, region, &[values[0].clone()], felt_scale, felt_scale * F::from(100), )?; log::debug!("recip: {}", recip.show()); // Multiply the difference by the recip let product = pairwise(config, region, &[diff, recip], BaseOp::Mult)?; log::debug!("product: {}", product.show()); let rebased_product = loop_div(config, region, &[product], i128_to_felt(input_scale_ratio))?; log::debug!("rebased_product: {}", rebased_product.show()); // check that it is within the tolerance range range_check( config, region, &[rebased_product], &(-range_check_bracket_int, range_check_bracket_int), ) }
https://github.com/zkonduit/ezkl
src/circuit/ops/lookup.rs
use super::*; use serde::{Deserialize, Serialize}; use std::error::Error; use crate::{ circuit::{layouts, table::Range, utils}, fieldutils::{felt_to_i128, i128_to_felt}, graph::multiplier_to_scale, tensor::{self, Tensor, TensorError, TensorType}, }; use super::Op; use halo2curves::ff::PrimeField; #[allow(missing_docs)] /// An enum representing the operations that can be used to express more complex operations via accumulation #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Deserialize, Serialize)] pub enum LookupOp { Abs, Div { denom: utils::F32, }, Cast { scale: utils::F32, }, ReLU, Max { scale: utils::F32, a: utils::F32, }, Min { scale: utils::F32, a: utils::F32, }, Ceil { scale: utils::F32, }, Floor { scale: utils::F32, }, Round { scale: utils::F32, }, RoundHalfToEven { scale: utils::F32, }, Sqrt { scale: utils::F32, }, Rsqrt { scale: utils::F32, }, Recip { input_scale: utils::F32, output_scale: utils::F32, }, LeakyReLU { slope: utils::F32, }, Sigmoid { scale: utils::F32, }, Ln { scale: utils::F32, }, Exp { scale: utils::F32, }, Cos { scale: utils::F32, }, ACos { scale: utils::F32, }, Cosh { scale: utils::F32, }, ACosh { scale: utils::F32, }, Sin { scale: utils::F32, }, ASin { scale: utils::F32, }, Sinh { scale: utils::F32, }, ASinh { scale: utils::F32, }, Tan { scale: utils::F32, }, ATan { scale: utils::F32, }, Tanh { scale: utils::F32, }, ATanh { scale: utils::F32, }, Erf { scale: utils::F32, }, GreaterThan { a: utils::F32, }, LessThan { a: utils::F32, }, GreaterThanEqual { a: utils::F32, }, LessThanEqual { a: utils::F32, }, Sign, KroneckerDelta, Pow { scale: utils::F32, a: utils::F32, }, HardSwish { scale: utils::F32, }, } impl LookupOp { /// Returns the range of values that can be represented by the table pub fn bit_range(max_len: usize) -> Range { let range = (max_len - 1) as f64 / 2_f64; let range = range as i128; (-range, range) } /// Matches a [Op] to an operation in the `tensor::ops` module. pub(crate) fn f<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>( &self, x: &[Tensor<F>], ) -> Result<ForwardResult<F>, TensorError> { let x = x[0].clone().map(|x| felt_to_i128(x)); let res = match &self { LookupOp::Abs => Ok(tensor::ops::abs(&x)?), LookupOp::Ceil { scale } => Ok(tensor::ops::nonlinearities::ceil(&x, scale.into())), LookupOp::Floor { scale } => Ok(tensor::ops::nonlinearities::floor(&x, scale.into())), LookupOp::Round { scale } => Ok(tensor::ops::nonlinearities::round(&x, scale.into())), LookupOp::RoundHalfToEven { scale } => Ok( tensor::ops::nonlinearities::round_half_to_even(&x, scale.into()), ), LookupOp::Pow { scale, a } => Ok(tensor::ops::nonlinearities::pow( &x, scale.0.into(), a.0.into(), )), LookupOp::KroneckerDelta => Ok(tensor::ops::nonlinearities::kronecker_delta(&x)), LookupOp::Max { scale, a } => Ok(tensor::ops::nonlinearities::max( &x, scale.0.into(), a.0.into(), )), LookupOp::Min { scale, a } => Ok(tensor::ops::nonlinearities::min( &x, scale.0.into(), a.0.into(), )), LookupOp::Sign => Ok(tensor::ops::nonlinearities::sign(&x)), LookupOp::LessThan { a } => Ok(tensor::ops::nonlinearities::less_than( &x, f32::from(*a).into(), )), LookupOp::LessThanEqual { a } => Ok(tensor::ops::nonlinearities::less_than_equal( &x, f32::from(*a).into(), )), LookupOp::GreaterThan { a } => Ok(tensor::ops::nonlinearities::greater_than( &x, f32::from(*a).into(), )), LookupOp::GreaterThanEqual { a } => Ok( tensor::ops::nonlinearities::greater_than_equal(&x, f32::from(*a).into()), ), LookupOp::Div { denom } => Ok(tensor::ops::nonlinearities::const_div( &x, f32::from(*denom).into(), )), LookupOp::Cast { scale } => Ok(tensor::ops::nonlinearities::const_div( &x, f32::from(*scale).into(), )), LookupOp::Recip { input_scale, output_scale, } => Ok(tensor::ops::nonlinearities::recip( &x, input_scale.into(), output_scale.into(), )), LookupOp::ReLU => Ok(tensor::ops::nonlinearities::leakyrelu(&x, 0_f64)), LookupOp::LeakyReLU { slope: a } => { Ok(tensor::ops::nonlinearities::leakyrelu(&x, a.0.into())) } LookupOp::Sigmoid { scale } => { Ok(tensor::ops::nonlinearities::sigmoid(&x, scale.into())) } LookupOp::Sqrt { scale } => Ok(tensor::ops::nonlinearities::sqrt(&x, scale.into())), LookupOp::Rsqrt { scale } => Ok(tensor::ops::nonlinearities::rsqrt(&x, scale.into())), LookupOp::Erf { scale } => Ok(tensor::ops::nonlinearities::erffunc(&x, scale.into())), LookupOp::Exp { scale } => Ok(tensor::ops::nonlinearities::exp(&x, scale.into())), LookupOp::Ln { scale } => Ok(tensor::ops::nonlinearities::ln(&x, scale.into())), LookupOp::Cos { scale } => Ok(tensor::ops::nonlinearities::cos(&x, scale.into())), LookupOp::ACos { scale } => Ok(tensor::ops::nonlinearities::acos(&x, scale.into())), LookupOp::Cosh { scale } => Ok(tensor::ops::nonlinearities::cosh(&x, scale.into())), LookupOp::ACosh { scale } => Ok(tensor::ops::nonlinearities::acosh(&x, scale.into())), LookupOp::Sin { scale } => Ok(tensor::ops::nonlinearities::sin(&x, scale.into())), LookupOp::ASin { scale } => Ok(tensor::ops::nonlinearities::asin(&x, scale.into())), LookupOp::Sinh { scale } => Ok(tensor::ops::nonlinearities::sinh(&x, scale.into())), LookupOp::ASinh { scale } => Ok(tensor::ops::nonlinearities::asinh(&x, scale.into())), LookupOp::Tan { scale } => Ok(tensor::ops::nonlinearities::tan(&x, scale.into())), LookupOp::ATan { scale } => Ok(tensor::ops::nonlinearities::atan(&x, scale.into())), LookupOp::ATanh { scale } => Ok(tensor::ops::nonlinearities::atanh(&x, scale.into())), LookupOp::Tanh { scale } => Ok(tensor::ops::nonlinearities::tanh(&x, scale.into())), LookupOp::HardSwish { scale } => { Ok(tensor::ops::nonlinearities::hardswish(&x, scale.into())) } }?; let output = res.map(|x| i128_to_felt(x)); Ok(ForwardResult { output }) } } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for LookupOp { /// Returns a reference to the Any trait. fn as_any(&self) -> &dyn Any { self } /// Returns the name of the operation fn as_string(&self) -> String { match self { LookupOp::Abs => "ABS".into(), LookupOp::Ceil { scale } => format!("CEIL(scale={})", scale), LookupOp::Floor { scale } => format!("FLOOR(scale={})", scale), LookupOp::Round { scale } => format!("ROUND(scale={})", scale), LookupOp::RoundHalfToEven { scale } => format!("ROUND_HALF_TO_EVEN(scale={})", scale), LookupOp::Pow { a, scale } => format!("POW(scale={}, exponent={})", scale, a), LookupOp::KroneckerDelta => "K_DELTA".into(), LookupOp::Max { scale, a } => format!("MAX(scale={}, a={})", scale, a), LookupOp::Min { scale, a } => format!("MIN(scale={}, a={})", scale, a), LookupOp::Sign => "SIGN".into(), LookupOp::GreaterThan { a } => format!("GREATER_THAN(a={})", a), LookupOp::GreaterThanEqual { a } => format!("GREATER_THAN_EQUAL(a={})", a), LookupOp::LessThan { a } => format!("LESS_THAN(a={})", a), LookupOp::LessThanEqual { a } => format!("LESS_THAN_EQUAL(a={})", a), LookupOp::Recip { input_scale, output_scale, } => format!( "RECIP(input_scale={}, output_scale={})", input_scale, output_scale ), LookupOp::Div { denom, .. } => format!("DIV(denom={})", denom), LookupOp::Cast { scale } => format!("CAST(scale={})", scale), LookupOp::Ln { scale } => format!("LN(scale={})", scale), LookupOp::ReLU => "RELU".to_string(), LookupOp::LeakyReLU { slope: a } => format!("L_RELU(slope={})", a), LookupOp::Sigmoid { scale } => format!("SIGMOID(scale={})", scale), LookupOp::Sqrt { scale } => format!("SQRT(scale={})", scale), LookupOp::Erf { scale } => format!("ERF(scale={})", scale), LookupOp::Rsqrt { scale } => format!("RSQRT(scale={})", scale), LookupOp::Exp { scale } => format!("EXP(scale={})", scale), LookupOp::Tan { scale } => format!("TAN(scale={})", scale), LookupOp::ATan { scale } => format!("ATAN(scale={})", scale), LookupOp::Tanh { scale } => format!("TANH(scale={})", scale), LookupOp::ATanh { scale } => format!("ATANH(scale={})", scale), LookupOp::Cos { scale } => format!("COS(scale={})", scale), LookupOp::ACos { scale } => format!("ACOS(scale={})", scale), LookupOp::Cosh { scale } => format!("COSH(scale={})", scale), LookupOp::ACosh { scale } => format!("ACOSH(scale={})", scale), LookupOp::Sin { scale } => format!("SIN(scale={})", scale), LookupOp::ASin { scale } => format!("ASIN(scale={})", scale), LookupOp::Sinh { scale } => format!("SINH(scale={})", scale), LookupOp::ASinh { scale } => format!("ASINH(scale={})", scale), LookupOp::HardSwish { scale } => format!("HARDSWISH(scale={})", scale), } } fn layout( &self, config: &mut crate::circuit::BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> { Ok(Some(layouts::nonlinearity( config, region, values[..].try_into()?, self, )?)) } /// Returns the scale of the output of the operation. fn out_scale(&self, inputs_scale: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { let scale = match self { LookupOp::Cast { scale } => { let in_scale = inputs_scale[0]; in_scale + multiplier_to_scale(1. / scale.0 as f64) } LookupOp::Recip { output_scale, .. } => multiplier_to_scale(output_scale.into()), LookupOp::Sign | LookupOp::GreaterThan { .. } | LookupOp::LessThan { .. } | LookupOp::GreaterThanEqual { .. } | LookupOp::LessThanEqual { .. } | LookupOp::KroneckerDelta => 0, _ => inputs_scale[0], }; Ok(scale) } fn clone_dyn(&self) -> Box<dyn Op<F>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } }
https://github.com/zkonduit/ezkl
src/circuit/ops/mod.rs
use std::{any::Any, error::Error}; use serde::{Deserialize, Serialize}; use crate::{ graph::quantize_tensor, tensor::{self, Tensor, TensorType, ValTensor}, }; use halo2curves::ff::PrimeField; use self::{lookup::LookupOp, region::RegionCtx}; /// pub mod base; /// pub mod chip; /// pub mod hybrid; /// Layouts for specific functions (composed of base ops) pub mod layouts; /// pub mod lookup; /// pub mod poly; /// pub mod region; /// A struct representing the result of a forward pass. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct ForwardResult<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> { pub(crate) output: Tensor<F>, } /// A trait representing operations that can be represented as constraints in a circuit. pub trait Op<F: PrimeField + TensorType + PartialOrd + std::hash::Hash>: std::fmt::Debug + Send + Sync + Any { /// Returns a string representation of the operation. fn as_string(&self) -> String; /// Layouts the operation in a circuit. fn layout( &self, config: &mut crate::circuit::BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], ) -> Result<Option<ValTensor<F>>, Box<dyn Error>>; /// Returns the scale of the output of the operation. fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>>; /// Do any of the inputs to this op require homogenous input scales? fn requires_homogenous_input_scales(&self) -> Vec<usize> { vec![] } /// Returns true if the operation is an input. fn is_input(&self) -> bool { false } /// Returns true if the operation is a constant. fn is_constant(&self) -> bool { false } /// Boxes and clones fn clone_dyn(&self) -> Box<dyn Op<F>>; /// Returns a reference to the Any trait. fn as_any(&self) -> &dyn Any; } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Clone for Box<dyn Op<F>> { fn clone(&self) -> Self { self.clone_dyn() } } /// #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub enum InputType { /// Bool, /// F16, /// F32, /// F64, /// Int, /// TDim, } impl InputType { /// pub fn is_integer(&self) -> bool { matches!(self, InputType::Int | InputType::TDim | InputType::Bool) } /// pub fn roundtrip<T: num::ToPrimitive + num::FromPrimitive + Clone>(&self, input: &mut T) { match self { InputType::Bool => { let boolean_input = input.clone().to_i64().unwrap(); assert!(boolean_input == 0 || boolean_input == 1); *input = T::from_i64(boolean_input).unwrap(); } InputType::F16 => { // TODO: implement f16 let f32_input = input.clone().to_f32().unwrap(); *input = T::from_f32(f32_input).unwrap(); } InputType::F32 => { let f32_input = input.clone().to_f32().unwrap(); *input = T::from_f32(f32_input).unwrap(); } InputType::F64 => { let f64_input = input.clone().to_f64().unwrap(); *input = T::from_f64(f64_input).unwrap(); } InputType::Int | InputType::TDim => { let int_input = input.clone().to_i128().unwrap(); *input = T::from_i128(int_input).unwrap(); } } } } /// #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct Input { /// pub scale: crate::Scale, /// pub datum_type: InputType, } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for Input { fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { Ok(self.scale) } fn as_any(&self) -> &dyn Any { self } fn as_string(&self) -> String { "Input".into() } fn layout( &self, config: &mut crate::circuit::BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> { let value = values[0].clone(); if !value.all_prev_assigned() { match self.datum_type { InputType::Bool => { log::debug!("constraining input to be boolean"); Ok(Some(super::layouts::boolean_identity( config, region, values[..].try_into()?, true, )?)) } _ => Ok(Some(super::layouts::identity( config, region, values[..].try_into()?, )?)), } } else { Ok(Some(value)) } } fn is_input(&self) -> bool { true } fn clone_dyn(&self) -> Box<dyn Op<F>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } } /// An unknown operation. #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct Unknown; impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Op<F> for Unknown { fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { Ok(0) } fn as_any(&self) -> &dyn Any { self } fn as_string(&self) -> String { "Unknown".into() } fn layout( &self, _: &mut crate::circuit::BaseConfig<F>, _: &mut RegionCtx<F>, _: &[ValTensor<F>], ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> { Err(Box::new(super::CircuitError::UnsupportedOp)) } fn clone_dyn(&self) -> Box<dyn Op<F>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } } /// #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Constant<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> { /// pub quantized_values: Tensor<F>, /// pub raw_values: Tensor<f32>, /// #[serde(skip)] pub pre_assigned_val: Option<ValTensor<F>>, } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Constant<F> { /// pub fn new(quantized_values: Tensor<F>, raw_values: Tensor<f32>) -> Self { Self { quantized_values, raw_values, pre_assigned_val: None, } } /// Rebase the scale of the constant pub fn rebase_scale(&mut self, new_scale: crate::Scale) -> Result<(), Box<dyn Error>> { let visibility = self.quantized_values.visibility().unwrap(); self.quantized_values = quantize_tensor(self.raw_values.clone(), new_scale, &visibility)?; Ok(()) } /// Empty raw value pub fn empty_raw_value(&mut self) { self.raw_values = Tensor::new(None, &[0]).unwrap(); } /// pub fn pre_assign(&mut self, val: ValTensor<F>) { self.pre_assigned_val = Some(val) } } impl< F: PrimeField + TensorType + PartialOrd + std::hash::Hash + Serialize + for<'de> Deserialize<'de>, > Op<F> for Constant<F> { fn as_any(&self) -> &dyn Any { self } fn as_string(&self) -> String { format!("CONST (scale={})", self.quantized_values.scale().unwrap()) } fn layout( &self, config: &mut crate::circuit::BaseConfig<F>, region: &mut RegionCtx<F>, _: &[ValTensor<F>], ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> { let value = if let Some(value) = &self.pre_assigned_val { value.clone() } else { self.quantized_values.clone().try_into()? }; // we gotta constrain it once if its used multiple times Ok(Some(layouts::identity(config, region, &[value])?)) } fn clone_dyn(&self) -> Box<dyn Op<F>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { Ok(self.quantized_values.scale().unwrap()) } fn is_constant(&self) -> bool { true } }
https://github.com/zkonduit/ezkl
src/circuit/ops/poly.rs
use crate::{ circuit::layouts, tensor::{self, Tensor, TensorError}, }; use super::{base::BaseOp, *}; #[allow(missing_docs)] /// An enum representing the operations that can be expressed as arithmetic (non lookup) operations. #[derive(Clone, Debug, Serialize, Deserialize)] pub enum PolyOp { GatherElements { dim: usize, constant_idx: Option<Tensor<usize>>, }, GatherND { batch_dims: usize, indices: Option<Tensor<usize>>, }, ScatterElements { dim: usize, constant_idx: Option<Tensor<usize>>, }, ScatterND { constant_idx: Option<Tensor<usize>>, }, MultiBroadcastTo { shape: Vec<usize>, }, Einsum { equation: String, }, Conv { padding: Vec<(usize, usize)>, stride: Vec<usize>, }, Downsample { axis: usize, stride: usize, modulo: usize, }, DeConv { padding: Vec<(usize, usize)>, output_padding: Vec<usize>, stride: Vec<usize>, }, Add, Sub, Neg, Mult, Identity { out_scale: Option<crate::Scale>, }, Reshape(Vec<usize>), MoveAxis { source: usize, destination: usize, }, Flatten(Vec<usize>), Pad(Vec<(usize, usize)>), Sum { axes: Vec<usize>, }, MeanOfSquares { axes: Vec<usize>, }, Prod { axes: Vec<usize>, len_prod: usize, }, Pow(u32), Concat { axis: usize, }, Slice { axis: usize, start: usize, end: usize, }, Iff, Resize { scale_factor: Vec<usize>, }, Not, And, Or, Xor, Trilu { upper: bool, k: i32, }, } impl< F: PrimeField + TensorType + PartialOrd + std::hash::Hash + Serialize + for<'de> Deserialize<'de>, > Op<F> for PolyOp { /// Returns a reference to the Any trait. fn as_any(&self) -> &dyn Any { self } fn as_string(&self) -> String { match &self { PolyOp::GatherElements { dim, constant_idx } => format!( "GATHERELEMENTS (dim={}, constant_idx{})", dim, constant_idx.is_some() ), PolyOp::GatherND { batch_dims, indices, } => format!( "GATHERND (batch_dims={}, constant_idx{})", batch_dims, indices.is_some() ), PolyOp::MeanOfSquares { axes } => format!("MEANOFSQUARES (axes={:?})", axes), PolyOp::ScatterElements { dim, constant_idx } => format!( "SCATTERELEMENTS (dim={}, constant_idx{})", dim, constant_idx.is_some() ), PolyOp::ScatterND { constant_idx } => { format!("SCATTERND (constant_idx={})", constant_idx.is_some()) } PolyOp::MultiBroadcastTo { shape } => format!("MULTIBROADCASTTO (shape={:?})", shape), PolyOp::MoveAxis { .. } => "MOVEAXIS".into(), PolyOp::Downsample { .. } => "DOWNSAMPLE".into(), PolyOp::Resize { .. } => "RESIZE".into(), PolyOp::Iff => "IFF".into(), PolyOp::Einsum { equation, .. } => format!("EINSUM {}", equation), PolyOp::Identity { out_scale } => { format!("IDENTITY (out_scale={:?})", out_scale) } PolyOp::Reshape(shape) => format!("RESHAPE (shape={:?})", shape), PolyOp::Flatten(_) => "FLATTEN".into(), PolyOp::Pad(pads) => format!("PAD (pads={:?})", pads), PolyOp::Add => "ADD".into(), PolyOp::Mult => "MULT".into(), PolyOp::Sub => "SUB".into(), PolyOp::Sum { axes } => format!("SUM (axes={:?})", axes), PolyOp::Prod { .. } => "PROD".into(), PolyOp::Pow(_) => "POW".into(), PolyOp::Conv { stride, padding } => { format!("CONV (stride={:?}, padding={:?})", stride, padding) } PolyOp::DeConv { stride, padding, output_padding, } => { format!( "DECONV (stride={:?}, padding={:?}, output_padding={:?})", stride, padding, output_padding ) } PolyOp::Concat { axis } => format!("CONCAT (axis={})", axis), PolyOp::Slice { axis, start, end } => { format!("SLICE (axis={}, start={}, end={})", axis, start, end) } PolyOp::Neg => "NEG".into(), PolyOp::Not => "NOT".into(), PolyOp::And => "AND".into(), PolyOp::Or => "OR".into(), PolyOp::Xor => "XOR".into(), PolyOp::Trilu { upper, k } => format!("TRILU (upper={}, k={})", upper, k), } } fn layout( &self, config: &mut crate::circuit::BaseConfig<F>, region: &mut RegionCtx<F>, values: &[ValTensor<F>], ) -> Result<Option<ValTensor<F>>, Box<dyn Error>> { Ok(Some(match self { PolyOp::MultiBroadcastTo { shape } => { layouts::expand(config, region, values[..].try_into()?, shape)? } PolyOp::MeanOfSquares { axes } => { layouts::mean_of_squares_axes(config, region, values[..].try_into()?, axes)? } PolyOp::Xor => layouts::xor(config, region, values[..].try_into()?)?, PolyOp::Or => layouts::or(config, region, values[..].try_into()?)?, PolyOp::And => layouts::and(config, region, values[..].try_into()?)?, PolyOp::Not => layouts::not(config, region, values[..].try_into()?)?, PolyOp::MoveAxis { source, destination, } => layouts::move_axis(values[..].try_into()?, *source, *destination)?, PolyOp::Downsample { axis, stride, modulo, } => layouts::downsample(config, region, values[..].try_into()?, axis, stride, modulo)?, PolyOp::Resize { scale_factor } => { layouts::resize(config, region, values[..].try_into()?, scale_factor)? } PolyOp::Neg => layouts::neg(config, region, values[..].try_into()?)?, PolyOp::Iff => layouts::iff(config, region, values[..].try_into()?)?, PolyOp::Einsum { equation } => layouts::einsum(config, region, values, equation)?, PolyOp::Sum { axes } => { layouts::sum_axes(config, region, values[..].try_into()?, axes)? } PolyOp::Prod { axes, .. } => { layouts::prod_axes(config, region, values[..].try_into()?, axes)? } PolyOp::Conv { padding, stride } => { layouts::conv(config, region, values[..].try_into()?, padding, stride)? } PolyOp::GatherElements { dim, constant_idx } => { if let Some(idx) = constant_idx { tensor::ops::gather_elements(values[0].get_inner_tensor()?, idx, *dim)?.into() } else { layouts::gather_elements(config, region, values[..].try_into()?, *dim)?.0 } } PolyOp::GatherND { batch_dims, indices, } => { if let Some(idx) = indices { tensor::ops::gather_nd(values[0].get_inner_tensor()?, idx, *batch_dims)?.into() } else { layouts::gather_nd(config, region, values[..].try_into()?, *batch_dims)?.0 } } PolyOp::ScatterElements { dim, constant_idx } => { if let Some(idx) = constant_idx { tensor::ops::scatter( values[0].get_inner_tensor()?, idx, values[1].get_inner_tensor()?, *dim, )? .into() } else { layouts::scatter_elements(config, region, values[..].try_into()?, *dim)? } } PolyOp::ScatterND { constant_idx } => { if let Some(idx) = constant_idx { tensor::ops::scatter_nd( values[0].get_inner_tensor()?, idx, values[1].get_inner_tensor()?, )? .into() } else { layouts::scatter_nd(config, region, values[..].try_into()?)? } } PolyOp::DeConv { padding, output_padding, stride, } => layouts::deconv( config, region, values[..].try_into()?, padding, output_padding, stride, )?, PolyOp::Add => layouts::pairwise(config, region, values[..].try_into()?, BaseOp::Add)?, PolyOp::Sub => layouts::pairwise(config, region, values[..].try_into()?, BaseOp::Sub)?, PolyOp::Mult => { layouts::pairwise(config, region, values[..].try_into()?, BaseOp::Mult)? } PolyOp::Identity { .. } => layouts::identity(config, region, values[..].try_into()?)?, PolyOp::Reshape(d) | PolyOp::Flatten(d) => layouts::reshape(values[..].try_into()?, d)?, PolyOp::Pad(p) => { if values.len() != 1 { return Err(Box::new(TensorError::DimError( "Pad operation requires a single input".to_string(), ))); } let mut input = values[0].clone(); input.pad(p.clone(), 0)?; input } PolyOp::Pow(exp) => layouts::pow(config, region, values[..].try_into()?, *exp)?, PolyOp::Concat { axis } => layouts::concat(values[..].try_into()?, axis)?, PolyOp::Slice { axis, start, end } => { layouts::slice(config, region, values[..].try_into()?, axis, start, end)? } PolyOp::Trilu { upper, k } => { layouts::trilu(config, region, values[..].try_into()?, k, upper)? } })) } fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { let scale = match self { PolyOp::MeanOfSquares { .. } => 2 * in_scales[0], PolyOp::Xor | PolyOp::Or | PolyOp::And | PolyOp::Not => 0, PolyOp::Iff => in_scales[1], PolyOp::Einsum { .. } => { let mut scale = in_scales[0]; for s in in_scales.iter().skip(1) { scale += *s; } scale } PolyOp::Prod { len_prod, .. } => in_scales[0] * (*len_prod as crate::Scale), PolyOp::Sum { .. } => in_scales[0], PolyOp::Conv { .. } => { let input_scale = in_scales[0]; let kernel_scale = in_scales[1]; let output_scale = input_scale + kernel_scale; if in_scales.len() == 3 { let bias_scale = in_scales[2]; assert_eq!(output_scale, bias_scale); } output_scale } PolyOp::DeConv { .. } => { let input_scale = in_scales[0]; let kernel_scale = in_scales[1]; let output_scale = input_scale + kernel_scale; if in_scales.len() == 3 { let bias_scale = in_scales[2]; assert_eq!(output_scale, bias_scale); } output_scale } PolyOp::Add => { let scale_a = in_scales[0]; let scale_b = in_scales[1]; assert_eq!(scale_a, scale_b); scale_a } PolyOp::Sub => in_scales[0], PolyOp::Mult => { let mut scale = in_scales[0]; scale += in_scales[1]; scale } PolyOp::Reshape(_) | PolyOp::Flatten(_) => in_scales[0], PolyOp::Pow(pow) => in_scales[0] * (*pow as crate::Scale), PolyOp::Identity { out_scale } => out_scale.unwrap_or(in_scales[0]), _ => in_scales[0], }; Ok(scale) } fn requires_homogenous_input_scales(&self) -> Vec<usize> { if matches!(self, PolyOp::Add { .. } | PolyOp::Sub) { vec![0, 1] } else if matches!(self, PolyOp::Iff) { vec![1, 2] } else if matches!(self, PolyOp::Concat { .. }) { (0..100).collect() } else if matches!(self, PolyOp::ScatterElements { .. }) | matches!(self, PolyOp::ScatterND { .. }) { vec![0, 2] } else { vec![] } } fn clone_dyn(&self) -> Box<dyn Op<F>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } }
https://github.com/zkonduit/ezkl
src/circuit/ops/region.rs
use crate::{ circuit::table::Range, tensor::{Tensor, TensorError, TensorType, ValTensor, ValType, VarTensor}, }; #[cfg(not(target_arch = "wasm32"))] use colored::Colorize; use halo2_proofs::{ circuit::Region, plonk::{Error, Selector}, }; use halo2curves::ff::PrimeField; use portable_atomic::AtomicI128 as AtomicInt; use std::{ cell::RefCell, collections::{HashMap, HashSet}, sync::{ atomic::{AtomicUsize, Ordering}, Arc, Mutex, }, }; use super::lookup::LookupOp; /// Constants map pub type ConstantsMap<F> = HashMap<F, ValType<F>>; /// Dynamic lookup index #[derive(Clone, Debug, Default)] pub struct DynamicLookupIndex { index: usize, col_coord: usize, } impl DynamicLookupIndex { /// Create a new dynamic lookup index pub fn new(index: usize, col_coord: usize) -> DynamicLookupIndex { DynamicLookupIndex { index, col_coord } } /// Get the lookup index pub fn index(&self) -> usize { self.index } /// Get the column coord pub fn col_coord(&self) -> usize { self.col_coord } /// update with another dynamic lookup index pub fn update(&mut self, other: &DynamicLookupIndex) { self.index += other.index; self.col_coord += other.col_coord; } } /// Dynamic lookup index #[derive(Clone, Debug, Default)] pub struct ShuffleIndex { index: usize, col_coord: usize, } impl ShuffleIndex { /// Create a new dynamic lookup index pub fn new(index: usize, col_coord: usize) -> ShuffleIndex { ShuffleIndex { index, col_coord } } /// Get the lookup index pub fn index(&self) -> usize { self.index } /// Get the column coord pub fn col_coord(&self) -> usize { self.col_coord } /// update with another shuffle index pub fn update(&mut self, other: &ShuffleIndex) { self.index += other.index; self.col_coord += other.col_coord; } } /// Region error #[derive(Debug, thiserror::Error)] pub enum RegionError { /// wrap other regions #[error("Wrapped region: {0}")] Wrapped(String), } impl From<String> for RegionError { fn from(e: String) -> Self { Self::Wrapped(e) } } impl From<&str> for RegionError { fn from(e: &str) -> Self { Self::Wrapped(e.to_string()) } } impl From<TensorError> for RegionError { fn from(e: TensorError) -> Self { Self::Wrapped(format!("{:?}", e)) } } impl From<Error> for RegionError { fn from(e: Error) -> Self { Self::Wrapped(format!("{:?}", e)) } } impl From<Box<dyn std::error::Error>> for RegionError { fn from(e: Box<dyn std::error::Error>) -> Self { Self::Wrapped(format!("{:?}", e)) } } #[derive(Debug)] /// A context for a region pub struct RegionCtx<'a, F: PrimeField + TensorType + PartialOrd + std::hash::Hash> { region: Option<RefCell<Region<'a, F>>>, row: usize, linear_coord: usize, num_inner_cols: usize, dynamic_lookup_index: DynamicLookupIndex, shuffle_index: ShuffleIndex, used_lookups: HashSet<LookupOp>, used_range_checks: HashSet<Range>, max_lookup_inputs: i128, min_lookup_inputs: i128, max_range_size: i128, witness_gen: bool, assigned_constants: ConstantsMap<F>, } impl<'a, F: PrimeField + TensorType + PartialOrd + std::hash::Hash> RegionCtx<'a, F> { #[cfg(not(target_arch = "wasm32"))] /// pub fn debug_report(&self) { log::debug!( "(rows={}, coord={}, constants={}, max_lookup_inputs={}, min_lookup_inputs={}, max_range_size={}, dynamic_lookup_col_coord={}, shuffle_col_coord={})", self.row().to_string().blue(), self.linear_coord().to_string().yellow(), self.total_constants().to_string().red(), self.max_lookup_inputs().to_string().green(), self.min_lookup_inputs().to_string().green(), self.max_range_size().to_string().green(), self.dynamic_lookup_col_coord().to_string().green(), self.shuffle_col_coord().to_string().green()); } /// pub fn assigned_constants(&self) -> &ConstantsMap<F> { &self.assigned_constants } /// pub fn update_constants(&mut self, constants: ConstantsMap<F>) { self.assigned_constants.extend(constants); } /// pub fn increment_dynamic_lookup_index(&mut self, n: usize) { self.dynamic_lookup_index.index += n; } /// pub fn increment_dynamic_lookup_col_coord(&mut self, n: usize) { self.dynamic_lookup_index.col_coord += n; } /// pub fn increment_shuffle_index(&mut self, n: usize) { self.shuffle_index.index += n; } /// pub fn increment_shuffle_col_coord(&mut self, n: usize) { self.shuffle_index.col_coord += n; } /// pub fn witness_gen(&self) -> bool { self.witness_gen } /// Create a new region context pub fn new(region: Region<'a, F>, row: usize, num_inner_cols: usize) -> RegionCtx<'a, F> { let region = Some(RefCell::new(region)); let linear_coord = row * num_inner_cols; RegionCtx { region, num_inner_cols, row, linear_coord, dynamic_lookup_index: DynamicLookupIndex::default(), shuffle_index: ShuffleIndex::default(), used_lookups: HashSet::new(), used_range_checks: HashSet::new(), max_lookup_inputs: 0, min_lookup_inputs: 0, max_range_size: 0, witness_gen: true, assigned_constants: HashMap::new(), } } /// Create a new region context pub fn new_with_constants( region: Region<'a, F>, row: usize, num_inner_cols: usize, constants: ConstantsMap<F>, ) -> RegionCtx<'a, F> { let mut new_self = Self::new(region, row, num_inner_cols); new_self.assigned_constants = constants; new_self } /// Create a new region context from a wrapped region pub fn from_wrapped_region( region: Option<RefCell<Region<'a, F>>>, row: usize, num_inner_cols: usize, dynamic_lookup_index: DynamicLookupIndex, shuffle_index: ShuffleIndex, ) -> RegionCtx<'a, F> { let linear_coord = row * num_inner_cols; RegionCtx { region, num_inner_cols, linear_coord, row, dynamic_lookup_index, shuffle_index, used_lookups: HashSet::new(), used_range_checks: HashSet::new(), max_lookup_inputs: 0, min_lookup_inputs: 0, max_range_size: 0, witness_gen: false, assigned_constants: HashMap::new(), } } /// Create a new region context pub fn new_dummy(row: usize, num_inner_cols: usize, witness_gen: bool) -> RegionCtx<'a, F> { let region = None; let linear_coord = row * num_inner_cols; RegionCtx { region, num_inner_cols, linear_coord, row, dynamic_lookup_index: DynamicLookupIndex::default(), shuffle_index: ShuffleIndex::default(), used_lookups: HashSet::new(), used_range_checks: HashSet::new(), max_lookup_inputs: 0, min_lookup_inputs: 0, max_range_size: 0, witness_gen, assigned_constants: HashMap::new(), } } /// Create a new region context pub fn new_dummy_with_linear_coord( row: usize, linear_coord: usize, num_inner_cols: usize, witness_gen: bool, ) -> RegionCtx<'a, F> { let region = None; RegionCtx { region, num_inner_cols, linear_coord, row, dynamic_lookup_index: DynamicLookupIndex::default(), shuffle_index: ShuffleIndex::default(), used_lookups: HashSet::new(), used_range_checks: HashSet::new(), max_lookup_inputs: 0, min_lookup_inputs: 0, max_range_size: 0, witness_gen, assigned_constants: HashMap::new(), } } /// Apply a function in a loop to the region pub fn apply_in_loop<T: TensorType + Send + Sync>( &mut self, output: &mut Tensor<T>, inner_loop_function: impl Fn(usize, &mut RegionCtx<'a, F>) -> Result<T, RegionError> + Send + Sync, ) -> Result<(), RegionError> { if self.is_dummy() { self.dummy_loop(output, inner_loop_function)?; } else { self.real_loop(output, inner_loop_function)?; } Ok(()) } /// Run a loop pub fn real_loop<T: TensorType + Send + Sync>( &mut self, output: &mut Tensor<T>, inner_loop_function: impl Fn(usize, &mut RegionCtx<'a, F>) -> Result<T, RegionError>, ) -> Result<(), RegionError> { output .iter_mut() .enumerate() .map(|(i, o)| { *o = inner_loop_function(i, self)?; Ok(()) }) .collect::<Result<Vec<_>, RegionError>>()?; Ok(()) } /// Create a new region context per loop iteration /// hacky but it works pub fn dummy_loop<T: TensorType + Send + Sync>( &mut self, output: &mut Tensor<T>, inner_loop_function: impl Fn(usize, &mut RegionCtx<'a, F>) -> Result<T, RegionError> + Send + Sync, ) -> Result<(), RegionError> { let row = AtomicUsize::new(self.row()); let linear_coord = AtomicUsize::new(self.linear_coord()); let max_lookup_inputs = AtomicInt::new(self.max_lookup_inputs()); let min_lookup_inputs = AtomicInt::new(self.min_lookup_inputs()); let lookups = Arc::new(Mutex::new(self.used_lookups.clone())); let range_checks = Arc::new(Mutex::new(self.used_range_checks.clone())); let dynamic_lookup_index = Arc::new(Mutex::new(self.dynamic_lookup_index.clone())); let shuffle_index = Arc::new(Mutex::new(self.shuffle_index.clone())); let constants = Arc::new(Mutex::new(self.assigned_constants.clone())); *output = output .par_enum_map(|idx, _| { // we kick off the loop with the current offset let starting_offset = row.load(Ordering::SeqCst); let starting_linear_coord = linear_coord.load(Ordering::SeqCst); // get inner value of the locked lookups // we need to make sure that the region is not shared between threads let mut local_reg = Self::new_dummy_with_linear_coord( starting_offset, starting_linear_coord, self.num_inner_cols, self.witness_gen, ); let res = inner_loop_function(idx, &mut local_reg); // we update the offset and constants row.fetch_add(local_reg.row() - starting_offset, Ordering::SeqCst); linear_coord.fetch_add( local_reg.linear_coord() - starting_linear_coord, Ordering::SeqCst, ); max_lookup_inputs.fetch_max(local_reg.max_lookup_inputs(), Ordering::SeqCst); min_lookup_inputs.fetch_min(local_reg.min_lookup_inputs(), Ordering::SeqCst); // update the lookups let mut lookups = lookups.lock().unwrap(); lookups.extend(local_reg.used_lookups()); // update the range checks let mut range_checks = range_checks.lock().unwrap(); range_checks.extend(local_reg.used_range_checks()); // update the dynamic lookup index let mut dynamic_lookup_index = dynamic_lookup_index.lock().unwrap(); dynamic_lookup_index.update(&local_reg.dynamic_lookup_index); // update the shuffle index let mut shuffle_index = shuffle_index.lock().unwrap(); shuffle_index.update(&local_reg.shuffle_index); // update the constants let mut constants = constants.lock().unwrap(); constants.extend(local_reg.assigned_constants); res }) .map_err(|e| RegionError::from(format!("dummy_loop: {:?}", e)))?; self.linear_coord = linear_coord.into_inner(); #[allow(trivial_numeric_casts)] { self.max_lookup_inputs = max_lookup_inputs.into_inner(); self.min_lookup_inputs = min_lookup_inputs.into_inner(); } self.row = row.into_inner(); self.used_lookups = Arc::try_unwrap(lookups) .map_err(|e| RegionError::from(format!("dummy_loop: failed to get lookups: {:?}", e)))? .into_inner() .map_err(|e| { RegionError::from(format!("dummy_loop: failed to get lookups: {:?}", e)) })?; self.used_range_checks = Arc::try_unwrap(range_checks) .map_err(|e| { RegionError::from(format!("dummy_loop: failed to get range checks: {:?}", e)) })? .into_inner() .map_err(|e| { RegionError::from(format!("dummy_loop: failed to get range checks: {:?}", e)) })?; self.dynamic_lookup_index = Arc::try_unwrap(dynamic_lookup_index) .map_err(|e| { RegionError::from(format!( "dummy_loop: failed to get dynamic lookup index: {:?}", e )) })? .into_inner() .map_err(|e| { RegionError::from(format!( "dummy_loop: failed to get dynamic lookup index: {:?}", e )) })?; self.shuffle_index = Arc::try_unwrap(shuffle_index) .map_err(|e| { RegionError::from(format!("dummy_loop: failed to get shuffle index: {:?}", e)) })? .into_inner() .map_err(|e| { RegionError::from(format!("dummy_loop: failed to get shuffle index: {:?}", e)) })?; self.assigned_constants = Arc::try_unwrap(constants) .map_err(|e| { RegionError::from(format!("dummy_loop: failed to get constants: {:?}", e)) })? .into_inner() .map_err(|e| { RegionError::from(format!("dummy_loop: failed to get constants: {:?}", e)) })?; Ok(()) } /// Update the max and min from inputs pub fn update_max_min_lookup_inputs( &mut self, inputs: &[ValTensor<F>], ) -> Result<(), Box<dyn std::error::Error>> { let (mut min, mut max) = (0, 0); for i in inputs { max = max.max(i.get_int_evals()?.into_iter().max().unwrap_or_default()); min = min.min(i.get_int_evals()?.into_iter().min().unwrap_or_default()); } self.max_lookup_inputs = self.max_lookup_inputs.max(max); self.min_lookup_inputs = self.min_lookup_inputs.min(min); Ok(()) } /// Update the max and min from inputs pub fn update_max_min_lookup_range( &mut self, range: Range, ) -> Result<(), Box<dyn std::error::Error>> { if range.0 > range.1 { return Err(format!("update_max_min_lookup_range: invalid range {:?}", range).into()); } let range_size = (range.1 - range.0).abs(); self.max_range_size = self.max_range_size.max(range_size); Ok(()) } /// Check if the region is dummy pub fn is_dummy(&self) -> bool { self.region.is_none() } /// add used lookup pub fn add_used_lookup( &mut self, lookup: LookupOp, inputs: &[ValTensor<F>], ) -> Result<(), Box<dyn std::error::Error>> { self.used_lookups.insert(lookup); self.update_max_min_lookup_inputs(inputs) } /// add used range check pub fn add_used_range_check(&mut self, range: Range) -> Result<(), Box<dyn std::error::Error>> { self.used_range_checks.insert(range); self.update_max_min_lookup_range(range) } /// Get the offset pub fn row(&self) -> usize { self.row } /// Linear coordinate pub fn linear_coord(&self) -> usize { self.linear_coord } /// Get the total number of constants pub fn total_constants(&self) -> usize { self.assigned_constants.len() } /// Get the dynamic lookup index pub fn dynamic_lookup_index(&self) -> usize { self.dynamic_lookup_index.index } /// Get the dynamic lookup column coordinate pub fn dynamic_lookup_col_coord(&self) -> usize { self.dynamic_lookup_index.col_coord } /// Get the shuffle index pub fn shuffle_index(&self) -> usize { self.shuffle_index.index } /// Get the shuffle column coordinate pub fn shuffle_col_coord(&self) -> usize { self.shuffle_index.col_coord } /// get used lookups pub fn used_lookups(&self) -> HashSet<LookupOp> { self.used_lookups.clone() } /// get used range checks pub fn used_range_checks(&self) -> HashSet<Range> { self.used_range_checks.clone() } /// max lookup inputs pub fn max_lookup_inputs(&self) -> i128 { self.max_lookup_inputs } /// min lookup inputs pub fn min_lookup_inputs(&self) -> i128 { self.min_lookup_inputs } /// max range check pub fn max_range_size(&self) -> i128 { self.max_range_size } /// Assign a valtensor to a vartensor pub fn assign( &mut self, var: &VarTensor, values: &ValTensor<F>, ) -> Result<ValTensor<F>, Error> { if let Some(region) = &self.region { var.assign( &mut region.borrow_mut(), self.linear_coord, values, &mut self.assigned_constants, ) } else { if !values.is_instance() { let values_map = values.create_constants_map_iterator(); self.assigned_constants.extend(values_map); } Ok(values.clone()) } } /// pub fn combined_dynamic_shuffle_coord(&self) -> usize { self.dynamic_lookup_col_coord() + self.shuffle_col_coord() } /// Assign a valtensor to a vartensor pub fn assign_dynamic_lookup( &mut self, var: &VarTensor, values: &ValTensor<F>, ) -> Result<ValTensor<F>, Error> { if let Some(region) = &self.region { var.assign( &mut region.borrow_mut(), self.combined_dynamic_shuffle_coord(), values, &mut self.assigned_constants, ) } else { if !values.is_instance() { let values_map = values.create_constants_map_iterator(); self.assigned_constants.extend(values_map); } Ok(values.clone()) } } /// Assign a valtensor to a vartensor pub fn assign_shuffle( &mut self, var: &VarTensor, values: &ValTensor<F>, ) -> Result<ValTensor<F>, Error> { self.assign_dynamic_lookup(var, values) } /// Assign a valtensor to a vartensor pub fn assign_with_omissions( &mut self, var: &VarTensor, values: &ValTensor<F>, ommissions: &HashSet<&usize>, ) -> Result<ValTensor<F>, Error> { if let Some(region) = &self.region { var.assign_with_omissions( &mut region.borrow_mut(), self.linear_coord, values, ommissions, &mut self.assigned_constants, ) } else { let inner_tensor = values.get_inner_tensor().unwrap(); let mut values_map = values.create_constants_map(); for o in ommissions { if let ValType::Constant(value) = inner_tensor.get_flat_index(**o) { values_map.remove(&value); } } self.assigned_constants.extend(values_map); Ok(values.clone()) } } /// Assign a valtensor to a vartensor with duplication pub fn assign_with_duplication( &mut self, var: &VarTensor, values: &ValTensor<F>, check_mode: &crate::circuit::CheckMode, single_inner_col: bool, ) -> Result<(ValTensor<F>, usize), Error> { if let Some(region) = &self.region { // duplicates every nth element to adjust for column overflow let (res, len) = var.assign_with_duplication( &mut region.borrow_mut(), self.row, self.linear_coord, values, check_mode, single_inner_col, &mut self.assigned_constants, )?; Ok((res, len)) } else { let (_, len) = var.dummy_assign_with_duplication( self.row, self.linear_coord, values, single_inner_col, &mut self.assigned_constants, )?; Ok((values.clone(), len)) } } /// Enable a selector pub fn enable(&mut self, selector: Option<&Selector>, offset: usize) -> Result<(), Error> { match &self.region { Some(region) => selector.unwrap().enable(&mut region.borrow_mut(), offset), None => Ok(()), } } /// constrain equal pub fn constrain_equal(&mut self, a: &ValTensor<F>, b: &ValTensor<F>) -> Result<(), Error> { if let Some(region) = &self.region { let a = a.get_inner_tensor().unwrap(); let b = b.get_inner_tensor().unwrap(); assert_eq!(a.len(), b.len()); a.iter().zip(b.iter()).try_for_each(|(a, b)| { let a = a.get_prev_assigned(); let b = b.get_prev_assigned(); // if they're both assigned, we can constrain them if let (Some(a), Some(b)) = (&a, &b) { region.borrow_mut().constrain_equal(a.cell(), b.cell()) } else if a.is_some() || b.is_some() { log::error!( "constrain_equal: one of the tensors is assigned and the other is not" ); return Err(Error::Synthesis); } else { Ok(()) } }) } else { Ok(()) } } /// Increment the offset by 1 pub fn next(&mut self) { self.linear_coord += 1; if self.linear_coord % self.num_inner_cols == 0 { self.row += 1; } } /// Increment the offset pub fn increment(&mut self, n: usize) { for _ in 0..n { self.next() } } /// flush row to the next row pub fn flush(&mut self) -> Result<(), Box<dyn std::error::Error>> { // increment by the difference between the current linear coord and the next row let remainder = self.linear_coord % self.num_inner_cols; if remainder != 0 { let diff = self.num_inner_cols - remainder; self.increment(diff); } if self.linear_coord % self.num_inner_cols != 0 { return Err("flush: linear coord is not aligned with the next row".into()); } Ok(()) } }
https://github.com/zkonduit/ezkl
src/circuit/table.rs
use std::{error::Error, marker::PhantomData}; use halo2curves::ff::PrimeField; use halo2_proofs::{ circuit::{Layouter, Value}, plonk::{ConstraintSystem, Expression, TableColumn}, }; use log::{debug, warn}; use maybe_rayon::prelude::{IntoParallelIterator, ParallelIterator}; use crate::{ circuit::CircuitError, fieldutils::i128_to_felt, tensor::{Tensor, TensorType}, }; use crate::circuit::lookup::LookupOp; /// The range of the lookup table. pub type Range = (i128, i128); /// The safety factor for the range of the lookup table. pub const RANGE_MULTIPLIER: i128 = 2; /// The safety factor offset for the number of rows in the lookup table. pub const RESERVED_BLINDING_ROWS_PAD: usize = 3; #[derive(Debug, Clone)] /// pub struct SelectorConstructor<F: PrimeField> { /// pub degree: usize, /// _marker: PhantomData<F>, } impl<F: PrimeField> SelectorConstructor<F> { /// pub fn new(degree: usize) -> Self { Self { degree, _marker: PhantomData, } } /// pub fn get_expr_at_idx(&self, i: usize, expr: Expression<F>) -> Expression<F> { let indices = 0..self.degree; indices .into_par_iter() .filter(|x| *x != i) .map(|i| { if i == 0 { expr.clone() } else { (Expression::Constant(F::from(i as u64))) - expr.clone() } }) .reduce(|| Expression::Constant(F::from(1_u64)), |acc, x| acc * x) } /// pub fn get_selector_val_at_idx(&self, i: usize) -> F { let indices = 0..self.degree; indices .into_par_iter() .filter(|x| *x != i) .map(|x| { if x == 0 { F::from(i as u64) } else { F::from(x as u64) - F::from(i as u64) } }) .product() } } /// Halo2 lookup table for element wise non-linearities. #[derive(Clone, Debug)] pub struct Table<F: PrimeField> { /// Non-linearity to be used in table. pub nonlinearity: LookupOp, /// Input to table. pub table_inputs: Vec<TableColumn>, /// col size pub col_size: usize, /// Output of table pub table_outputs: Vec<TableColumn>, /// selector cn pub selector_constructor: SelectorConstructor<F>, /// Flags if table has been previously assigned to. pub is_assigned: bool, /// Number of bits used in lookup table. pub range: Range, _marker: PhantomData<F>, } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Table<F> { /// get column index given input pub fn get_col_index(&self, input: F) -> F { // range is split up into chunks of size col_size, find the chunk that input is in let chunk = (crate::fieldutils::felt_to_i128(input) - self.range.0).abs() / (self.col_size as i128); i128_to_felt(chunk) } /// get first_element of column pub fn get_first_element(&self, chunk: usize) -> (F, F) { let chunk = chunk as i128; // we index from 1 to prevent soundness issues let first_element = i128_to_felt(chunk * (self.col_size as i128) + self.range.0); let op_f = self .nonlinearity .f(&[Tensor::from(vec![first_element].into_iter())]) .unwrap(); (first_element, op_f.output[0]) } /// pub fn cal_col_size(logrows: usize, reserved_blinding_rows: usize) -> usize { 2usize.pow(logrows as u32) - reserved_blinding_rows } /// pub fn cal_bit_range(bits: usize, reserved_blinding_rows: usize) -> usize { 2usize.pow(bits as u32) - reserved_blinding_rows } } /// pub fn num_cols_required(range_len: i128, col_size: usize) -> usize { // number of cols needed to store the range (range_len / (col_size as i128)) as usize + 1 } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> Table<F> { /// Configures the table. pub fn configure( cs: &mut ConstraintSystem<F>, range: Range, logrows: usize, nonlinearity: &LookupOp, preexisting_inputs: Option<Vec<TableColumn>>, ) -> Table<F> { let factors = cs.blinding_factors() + RESERVED_BLINDING_ROWS_PAD; let col_size = Self::cal_col_size(logrows, factors); // number of cols needed to store the range let num_cols = num_cols_required((range.1 - range.0).abs(), col_size); debug!("table range: {:?}", range); let table_inputs = preexisting_inputs.unwrap_or_else(|| { let mut cols = vec![]; for _ in 0..num_cols { cols.push(cs.lookup_table_column()); } cols }); let num_cols = table_inputs.len(); if num_cols > 1 { warn!("Using {} columns for non-linearity table.", num_cols); } let table_outputs = table_inputs .iter() .map(|_| cs.lookup_table_column()) .collect::<Vec<_>>(); Table { nonlinearity: nonlinearity.clone(), table_inputs, table_outputs, is_assigned: false, selector_constructor: SelectorConstructor::new(num_cols), col_size, range, _marker: PhantomData, } } /// Take a linear coordinate and output the (column, row) position in the storage block. pub fn cartesian_coord(&self, linear_coord: usize) -> (usize, usize) { let x = linear_coord / self.col_size; let y = linear_coord % self.col_size; (x, y) } /// Assigns values to the constraints generated when calling `configure`. pub fn layout( &mut self, layouter: &mut impl Layouter<F>, preassigned_input: bool, ) -> Result<(), Box<dyn Error>> { if self.is_assigned { return Err(Box::new(CircuitError::TableAlreadyAssigned)); } let smallest = self.range.0; let largest = self.range.1; let inputs: Tensor<F> = Tensor::from(smallest..=largest).map(|x| i128_to_felt(x)); let evals = self.nonlinearity.f(&[inputs.clone()])?; let chunked_inputs = inputs.chunks(self.col_size); self.is_assigned = true; let col_multipliers: Vec<F> = (0..chunked_inputs.len()) .map(|x| self.selector_constructor.get_selector_val_at_idx(x)) .collect(); let _ = chunked_inputs .enumerate() .map(|(chunk_idx, inputs)| { layouter.assign_table( || "nl table", |mut table| { let _ = inputs .iter() .enumerate() .map(|(mut row_offset, input)| { let col_multiplier = col_multipliers[chunk_idx]; row_offset += chunk_idx * self.col_size; let (x, y) = self.cartesian_coord(row_offset); if !preassigned_input { table.assign_cell( || format!("nl_i_col row {}", row_offset), self.table_inputs[x], y, || Value::known(*input * col_multiplier), )?; } let output = evals.output[row_offset]; table.assign_cell( || format!("nl_o_col row {}", row_offset), self.table_outputs[x], y, || Value::known(output * col_multiplier), )?; Ok(()) }) .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?; Ok(()) }, ) }) .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?; Ok(()) } } /// Halo2 range check column #[derive(Clone, Debug)] pub struct RangeCheck<F: PrimeField> { /// Input to table. pub inputs: Vec<TableColumn>, /// col size pub col_size: usize, /// selector cn pub selector_constructor: SelectorConstructor<F>, /// Flags if table has been previously assigned to. pub is_assigned: bool, /// Number of bits used in lookup table. pub range: Range, _marker: PhantomData<F>, } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> RangeCheck<F> { /// get first_element of column pub fn get_first_element(&self, chunk: usize) -> F { let chunk = chunk as i128; // we index from 1 to prevent soundness issues i128_to_felt(chunk * (self.col_size as i128) + self.range.0) } /// pub fn cal_col_size(logrows: usize, reserved_blinding_rows: usize) -> usize { 2usize.pow(logrows as u32) - reserved_blinding_rows } /// pub fn cal_bit_range(bits: usize, reserved_blinding_rows: usize) -> usize { 2usize.pow(bits as u32) - reserved_blinding_rows } /// get column index given input pub fn get_col_index(&self, input: F) -> F { // range is split up into chunks of size col_size, find the chunk that input is in let chunk = (crate::fieldutils::felt_to_i128(input) - self.range.0).abs() / (self.col_size as i128); i128_to_felt(chunk) } } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> RangeCheck<F> { /// Configures the table. pub fn configure(cs: &mut ConstraintSystem<F>, range: Range, logrows: usize) -> RangeCheck<F> { log::debug!("range check range: {:?}", range); let factors = cs.blinding_factors() + RESERVED_BLINDING_ROWS_PAD; let col_size = Self::cal_col_size(logrows, factors); // number of cols needed to store the range let num_cols = num_cols_required((range.1 - range.0).abs(), col_size); let inputs = { let mut cols = vec![]; for _ in 0..num_cols { cols.push(cs.lookup_table_column()); } cols }; let num_cols = inputs.len(); if num_cols > 1 { warn!("Using {} columns for range-check.", num_cols); } RangeCheck { inputs, col_size, is_assigned: false, selector_constructor: SelectorConstructor::new(num_cols), range, _marker: PhantomData, } } /// Take a linear coordinate and output the (column, row) position in the storage block. pub fn cartesian_coord(&self, linear_coord: usize) -> (usize, usize) { let x = linear_coord / self.col_size; let y = linear_coord % self.col_size; (x, y) } /// Assigns values to the constraints generated when calling `configure`. pub fn layout(&mut self, layouter: &mut impl Layouter<F>) -> Result<(), Box<dyn Error>> { if self.is_assigned { return Err(Box::new(CircuitError::TableAlreadyAssigned)); } let smallest = self.range.0; let largest = self.range.1; let inputs: Tensor<F> = Tensor::from(smallest..=largest).map(|x| i128_to_felt(x)); let chunked_inputs = inputs.chunks(self.col_size); self.is_assigned = true; let col_multipliers: Vec<F> = (0..chunked_inputs.len()) .map(|x| self.selector_constructor.get_selector_val_at_idx(x)) .collect(); let _ = chunked_inputs .enumerate() .map(|(chunk_idx, inputs)| { layouter.assign_table( || "range check table", |mut table| { let _ = inputs .iter() .enumerate() .map(|(mut row_offset, input)| { let col_multiplier = col_multipliers[chunk_idx]; row_offset += chunk_idx * self.col_size; let (x, y) = self.cartesian_coord(row_offset); table.assign_cell( || format!("rc_i_col row {}", row_offset), self.inputs[x], y, || Value::known(*input * col_multiplier), )?; Ok(()) }) .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?; Ok(()) }, ) }) .collect::<Result<Vec<()>, halo2_proofs::plonk::Error>>()?; Ok(()) } }
https://github.com/zkonduit/ezkl
src/circuit/tests.rs
use crate::circuit::ops::poly::PolyOp; use crate::circuit::*; use crate::tensor::{Tensor, TensorType, ValTensor, VarTensor}; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, dev::MockProver, plonk::{Circuit, ConstraintSystem, Error}, }; use halo2curves::bn256::Fr as F; use halo2curves::ff::{Field, PrimeField}; use ops::lookup::LookupOp; use ops::region::RegionCtx; use rand::rngs::OsRng; use std::marker::PhantomData; #[derive(Default)] struct TestParams; #[cfg(test)] mod matmul { use super::*; const K: usize = 9; const LEN: usize = 3; #[derive(Clone)] struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MatmulCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN * LEN); let b = VarTensor::new_advice(cs, K, 1, LEN * LEN); let output = VarTensor::new_advice(cs, K, 1, LEN * LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "ij,jk->ik".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn matmulcircuit() { // parameters let mut a = Tensor::from((0..(LEN + 1) * LEN).map(|i| Value::known(F::from((i + 1) as u64)))); a.reshape(&[LEN, LEN + 1]).unwrap(); let mut w = Tensor::from((0..LEN + 1).map(|i| Value::known(F::from((i + 1) as u64)))); w.reshape(&[LEN + 1, 1]).unwrap(); let circuit = MatmulCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(w)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod matmul_col_overflow_double_col { use super::*; const K: usize = 5; const LEN: usize = 6; const NUM_INNER_COLS: usize = 2; #[derive(Clone)] struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MatmulCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN); let b = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN); let output = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, NUM_INNER_COLS); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "ij,jk->ik".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn matmulcircuit() { // parameters let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64)))); a.reshape(&[LEN, LEN]).unwrap(); let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64)))); w.reshape(&[LEN, 1]).unwrap(); let circuit = MatmulCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(w)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod matmul_col_overflow { use super::*; const K: usize = 5; const LEN: usize = 6; #[derive(Clone)] struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MatmulCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "ij,jk->ik".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn matmulcircuit() { // parameters let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64)))); a.reshape(&[LEN, LEN]).unwrap(); let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64)))); w.reshape(&[LEN, 1]).unwrap(); let circuit = MatmulCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(w)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] mod matmul_col_ultra_overflow_double_col { use halo2_proofs::poly::kzg::{ commitment::KZGCommitmentScheme, multiopen::{ProverSHPLONK, VerifierSHPLONK}, strategy::SingleStrategy, }; use snark_verifier::system::halo2::transcript::evm::EvmTranscript; use super::*; const K: usize = 4; const LEN: usize = 20; const NUM_INNER_COLS: usize = 2; #[derive(Clone)] struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MatmulCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN); let b = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN); let output = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN * LEN * LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, NUM_INNER_COLS); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "ij,jk->ik".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] #[ignore] fn matmulcircuit() { // get some logs fam crate::logger::init_logger(); // parameters let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64)))); a.reshape(&[LEN, LEN]).unwrap(); let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64)))); w.reshape(&[LEN, 1]).unwrap(); let circuit = MatmulCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(w)], _marker: PhantomData, }; let params = crate::pfsys::srs::gen_srs::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>, >(K as u32); let pk = crate::pfsys::create_keys::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>, MatmulCircuit<F>, >(&circuit, &params, true) .unwrap(); let prover = crate::pfsys::create_proof_circuit::< KZGCommitmentScheme<_>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, SingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit.clone(), vec![], &params, &pk, // use safe mode to verify that the proof is correct CheckMode::SAFE, crate::Commitments::KZG, crate::pfsys::TranscriptType::EVM, None, None, ); assert!(prover.is_ok()); } } #[cfg(test)] #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] mod matmul_col_ultra_overflow { use halo2_proofs::poly::kzg::{ commitment::KZGCommitmentScheme, multiopen::{ProverSHPLONK, VerifierSHPLONK}, strategy::SingleStrategy, }; use snark_verifier::system::halo2::transcript::evm::EvmTranscript; use super::*; const K: usize = 4; const LEN: usize = 20; #[derive(Clone)] struct MatmulCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MatmulCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "ij,jk->ik".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] #[ignore] fn matmulcircuit() { // get some logs fam crate::logger::init_logger(); // parameters let mut a = Tensor::from((0..LEN * LEN).map(|i| Value::known(F::from((i + 1) as u64)))); a.reshape(&[LEN, LEN]).unwrap(); let mut w = Tensor::from((0..LEN).map(|i| Value::known(F::from((i + 1) as u64)))); w.reshape(&[LEN, 1]).unwrap(); let circuit = MatmulCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(w)], _marker: PhantomData, }; let params = crate::pfsys::srs::gen_srs::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>, >(K as u32); let pk = crate::pfsys::create_keys::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>, MatmulCircuit<F>, >(&circuit, &params, true) .unwrap(); let prover = crate::pfsys::create_proof_circuit::< KZGCommitmentScheme<_>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, SingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit.clone(), vec![], &params, &pk, // use safe mode to verify that the proof is correct CheckMode::SAFE, crate::Commitments::KZG, crate::pfsys::TranscriptType::EVM, None, None, ); assert!(prover.is_ok()); } } #[cfg(test)] mod dot { use ops::poly::PolyOp; use super::*; const K: usize = 4; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "i,i->".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn dotcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod dot_col_overflow_triple_col { use super::*; const K: usize = 4; const LEN: usize = 50; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { // used for constants in the padding let _fixed = cs.fixed_column(); cs.enable_constant(_fixed); let a = VarTensor::new_advice(cs, K, 3, LEN); let b = VarTensor::new_advice(cs, K, 3, LEN); let output = VarTensor::new_advice(cs, K, 3, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 3); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "i,i->".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn dotcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod dot_col_overflow { use super::*; const K: usize = 4; const LEN: usize = 50; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "i,i->".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn dotcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod sum { use super::*; const K: usize = 4; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 1], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Sum { axes: vec![0] }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn sumcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod sum_col_overflow_double_col { use super::*; const K: usize = 4; const LEN: usize = 20; const NUM_INNER_COLS: usize = 2; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 1], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN); let b = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN); let output = VarTensor::new_advice(cs, K, NUM_INNER_COLS, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, NUM_INNER_COLS); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Sum { axes: vec![0] }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn sumcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod sum_col_overflow { use super::*; const K: usize = 4; const LEN: usize = 20; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 1], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Sum { axes: vec![0] }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn sumcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod composition { use super::*; const K: usize = 9; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { // lots of stacked dot products layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); let _ = config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "i,i->".to_string(), }), ) .unwrap(); let _ = config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "i,i->".to_string(), }), ) .unwrap(); config .layout( &mut region, &self.inputs.clone(), Box::new(PolyOp::Einsum { equation: "i,i->".to_string(), }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn dotcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod conv { use super::*; const K: usize = 22; const LEN: usize = 100; #[derive(Clone)] struct ConvCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: Vec<ValTensor<F>>, _marker: PhantomData<F>, } impl Circuit<F> for ConvCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, (LEN + 1) * LEN); let b = VarTensor::new_advice(cs, K, 1, (LEN + 1) * LEN); let output = VarTensor::new_advice(cs, K, 1, (LEN + 1) * LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &self.inputs, Box::new(PolyOp::Conv { padding: vec![(1, 1); 2], stride: vec![2; 2], }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn convcircuit() { // parameters let kernel_height = 2; let kernel_width = 3; let image_height = 5; let image_width = 7; let in_channels = 3; let out_channels = 2; let mut image = Tensor::from((0..in_channels * image_height * image_width).map(|_| F::random(OsRng))); image .reshape(&[1, in_channels, image_height, image_width]) .unwrap(); image.set_visibility(&crate::graph::Visibility::Private); let image = ValTensor::try_from(image).unwrap(); let mut kernels = Tensor::from( (0..{ out_channels * in_channels * kernel_height * kernel_width }) .map(|_| F::random(OsRng)), ); kernels .reshape(&[out_channels, in_channels, kernel_height, kernel_width]) .unwrap(); kernels.set_visibility(&crate::graph::Visibility::Private); let kernels = ValTensor::try_from(kernels).unwrap(); let mut bias = Tensor::from((0..{ out_channels }).map(|_| F::random(OsRng))); bias.set_visibility(&crate::graph::Visibility::Private); let bias = ValTensor::try_from(bias).unwrap(); let circuit = ConvCircuit::<F> { inputs: [image, kernels, bias].to_vec(), _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } #[test] fn convcircuitnobias() { // parameters let kernel_height = 2; let kernel_width = 2; let image_height = 4; let image_width = 5; let in_channels = 3; let out_channels = 2; let mut image = Tensor::from((0..in_channels * image_height * image_width).map(|i| F::from(i as u64))); image .reshape(&[1, in_channels, image_height, image_width]) .unwrap(); image.set_visibility(&crate::graph::Visibility::Private); let mut kernels = Tensor::from( (0..{ out_channels * in_channels * kernel_height * kernel_width }) .map(|i| F::from(i as u64)), ); kernels .reshape(&[out_channels, in_channels, kernel_height, kernel_width]) .unwrap(); kernels.set_visibility(&crate::graph::Visibility::Private); let image = ValTensor::try_from(image).unwrap(); let kernels = ValTensor::try_from(kernels).unwrap(); let circuit = ConvCircuit::<F> { inputs: [image, kernels].to_vec(), _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] mod conv_col_ultra_overflow { use halo2_proofs::poly::{ kzg::strategy::SingleStrategy, kzg::{ commitment::KZGCommitmentScheme, multiopen::{ProverSHPLONK, VerifierSHPLONK}, }, }; use snark_verifier::system::halo2::transcript::evm::EvmTranscript; use super::*; const K: usize = 4; const LEN: usize = 28; #[derive(Clone)] struct ConvCircuit<F: PrimeField + TensorType + PartialOrd> { image: ValTensor<F>, kernel: ValTensor<F>, _marker: PhantomData<F>, } impl Circuit<F> for ConvCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout( &mut region, &[self.image.clone(), self.kernel.clone()], Box::new(PolyOp::Conv { padding: vec![(1, 1); 2], stride: vec![2; 2], }), ) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] #[ignore] fn conv_circuit() { // parameters let kernel_height = 2; let kernel_width = 2; let image_height = LEN; let image_width = LEN; let in_channels = 3; let out_channels = 2; // get some logs fam crate::logger::init_logger(); let mut image = Tensor::from((0..in_channels * image_height * image_width).map(|i| F::from(i as u64))); image .reshape(&[1, in_channels, image_height, image_width]) .unwrap(); image.set_visibility(&crate::graph::Visibility::Private); let mut kernels = Tensor::from( (0..{ out_channels * in_channels * kernel_height * kernel_width }) .map(|i| F::from(i as u64)), ); kernels .reshape(&[out_channels, in_channels, kernel_height, kernel_width]) .unwrap(); kernels.set_visibility(&crate::graph::Visibility::Private); let circuit = ConvCircuit::<F> { image: ValTensor::try_from(image).unwrap(), kernel: ValTensor::try_from(kernels).unwrap(), _marker: PhantomData, }; let params = crate::pfsys::srs::gen_srs::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>, >(K as u32); let pk = crate::pfsys::create_keys::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>, ConvCircuit<F>, >(&circuit, &params, true) .unwrap(); let prover = crate::pfsys::create_proof_circuit::< KZGCommitmentScheme<_>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, SingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit.clone(), vec![], &params, &pk, // use safe mode to verify that the proof is correct CheckMode::SAFE, crate::Commitments::KZG, crate::pfsys::TranscriptType::EVM, None, None, ); assert!(prover.is_ok()); } } #[cfg(test)] // not wasm 32 unknown #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] mod conv_relu_col_ultra_overflow { use halo2_proofs::poly::kzg::{ commitment::KZGCommitmentScheme, multiopen::{ProverSHPLONK, VerifierSHPLONK}, strategy::SingleStrategy, }; use snark_verifier::system::halo2::transcript::evm::EvmTranscript; use super::*; const K: usize = 4; const LEN: usize = 28; #[derive(Clone)] struct ConvCircuit<F: PrimeField + TensorType + PartialOrd> { image: ValTensor<F>, kernel: ValTensor<F>, _marker: PhantomData<F>, } impl Circuit<F> for ConvCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let b = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let output = VarTensor::new_advice(cs, K, 1, LEN * LEN * LEN); let mut base_config = Self::Config::configure(cs, &[a.clone(), b.clone()], &output, CheckMode::SAFE); // sets up a new relu table base_config .configure_lookup(cs, &b, &output, &a, (-3, 3), K, &LookupOp::ReLU) .unwrap(); base_config.clone() } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { config.layout_tables(&mut layouter).unwrap(); layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); let output = config .layout( &mut region, &[self.image.clone(), self.kernel.clone()], Box::new(PolyOp::Conv { padding: vec![(1, 1); 2], stride: vec![2; 2], }), ) .map_err(|_| Error::Synthesis); let _output = config .layout( &mut region, &[output.unwrap().unwrap()], Box::new(LookupOp::ReLU), ) .unwrap(); Ok(()) }, ) .unwrap(); Ok(()) } } #[test] #[ignore] fn conv_relu_circuit() { // parameters let kernel_height = 2; let kernel_width = 2; let image_height = LEN; let image_width = LEN; let in_channels = 3; let out_channels = 2; // get some logs fam crate::logger::init_logger(); let mut image = Tensor::from((0..in_channels * image_height * image_width).map(|_| F::from(0))); image .reshape(&[1, in_channels, image_height, image_width]) .unwrap(); image.set_visibility(&crate::graph::Visibility::Private); let mut kernels = Tensor::from( (0..{ out_channels * in_channels * kernel_height * kernel_width }).map(|_| F::from(0)), ); kernels .reshape(&[out_channels, in_channels, kernel_height, kernel_width]) .unwrap(); kernels.set_visibility(&crate::graph::Visibility::Private); let circuit = ConvCircuit::<F> { image: ValTensor::try_from(image).unwrap(), kernel: ValTensor::try_from(kernels).unwrap(), _marker: PhantomData, }; let params = crate::pfsys::srs::gen_srs::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>, >(K as u32); let pk = crate::pfsys::create_keys::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>, ConvCircuit<F>, >(&circuit, &params, true) .unwrap(); let prover = crate::pfsys::create_proof_circuit::< KZGCommitmentScheme<_>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, SingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit.clone(), vec![], &params, &pk, CheckMode::SAFE, crate::Commitments::KZG, crate::pfsys::TranscriptType::EVM, // use safe mode to verify that the proof is correct None, None, ); assert!(prover.is_ok()); } } #[cfg(test)] mod add_w_shape_casting { use super::*; const K: usize = 4; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Add)) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn addcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..1).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod add { use super::*; const K: usize = 4; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Add)) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn addcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod dynamic_lookup { use super::*; const K: usize = 6; const LEN: usize = 4; const NUM_LOOP: usize = 5; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { tables: [[ValTensor<F>; 2]; NUM_LOOP], lookups: [[ValTensor<F>; 2]; NUM_LOOP], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 2, LEN); let b = VarTensor::new_advice(cs, K, 2, LEN); let c: VarTensor = VarTensor::new_advice(cs, K, 2, LEN); let d = VarTensor::new_advice(cs, K, 1, LEN); let e = VarTensor::new_advice(cs, K, 1, LEN); let f: VarTensor = VarTensor::new_advice(cs, K, 1, LEN); let _constant = VarTensor::constant_cols(cs, K, LEN * NUM_LOOP, false); let mut config = Self::Config::configure(cs, &[a.clone(), b.clone()], &c, CheckMode::SAFE); config .configure_dynamic_lookup( cs, &[a.clone(), b.clone(), c.clone()], &[d.clone(), e.clone(), f.clone()], ) .unwrap(); config } fn synthesize( &self, config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); for i in 0..NUM_LOOP { layouts::dynamic_lookup( &config, &mut region, &self.lookups[i], &self.tables[i], ) .map_err(|_| Error::Synthesis)?; } assert_eq!( region.dynamic_lookup_col_coord(), NUM_LOOP * self.tables[0][0].len() ); assert_eq!(region.dynamic_lookup_index(), NUM_LOOP); Ok(()) }, ) .unwrap(); Ok(()) } } #[test] fn dynamiclookupcircuit() { // parameters let tables = (0..NUM_LOOP) .map(|loop_idx| { [ ValTensor::from(Tensor::from( (0..LEN).map(|i| Value::known(F::from((i * loop_idx) as u64 + 1))), )), ValTensor::from(Tensor::from( (0..LEN).map(|i| Value::known(F::from((loop_idx * i * i) as u64 + 1))), )), ] }) .collect::<Vec<_>>(); let lookups = (0..NUM_LOOP) .map(|loop_idx| { [ ValTensor::from(Tensor::from( (0..3).map(|i| Value::known(F::from((i * loop_idx) as u64 + 1))), )), ValTensor::from(Tensor::from( (0..3).map(|i| Value::known(F::from((loop_idx * i * i) as u64 + 1))), )), ] }) .collect::<Vec<_>>(); let circuit = MyCircuit::<F> { tables: tables.clone().try_into().unwrap(), lookups: lookups.try_into().unwrap(), _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); let lookups = (0..NUM_LOOP) .map(|loop_idx| { let prev_idx = if loop_idx == 0 { NUM_LOOP - 1 } else { loop_idx - 1 }; [ ValTensor::from(Tensor::from( (0..3).map(|i| Value::known(F::from((i * prev_idx) as u64 + 1))), )), ValTensor::from(Tensor::from( (0..3).map(|i| Value::known(F::from((prev_idx * i * i) as u64 + 1))), )), ] }) .collect::<Vec<_>>(); let circuit = MyCircuit::<F> { tables: tables.try_into().unwrap(), lookups: lookups.try_into().unwrap(), _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); assert!(prover.verify().is_err()); } } #[cfg(test)] mod shuffle { use super::*; const K: usize = 6; const LEN: usize = 4; const NUM_LOOP: usize = 5; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [[ValTensor<F>; 1]; NUM_LOOP], references: [[ValTensor<F>; 1]; NUM_LOOP], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 2, LEN); let b = VarTensor::new_advice(cs, K, 2, LEN); let c: VarTensor = VarTensor::new_advice(cs, K, 2, LEN); let d = VarTensor::new_advice(cs, K, 1, LEN); let e = VarTensor::new_advice(cs, K, 1, LEN); let _constant = VarTensor::constant_cols(cs, K, LEN * NUM_LOOP, false); let mut config = Self::Config::configure(cs, &[a.clone(), b.clone()], &c, CheckMode::SAFE); config .configure_shuffles(cs, &[a.clone(), b.clone()], &[d.clone(), e.clone()]) .unwrap(); config } fn synthesize( &self, config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); for i in 0..NUM_LOOP { layouts::shuffles( &config, &mut region, &self.inputs[i], &self.references[i], ) .map_err(|_| Error::Synthesis)?; } assert_eq!( region.shuffle_col_coord(), NUM_LOOP * self.references[0][0].len() ); assert_eq!(region.shuffle_index(), NUM_LOOP); Ok(()) }, ) .unwrap(); Ok(()) } } #[test] fn shufflecircuit() { // parameters let references = (0..NUM_LOOP) .map(|loop_idx| { [ValTensor::from(Tensor::from((0..LEN).map(|i| { Value::known(F::from((i * loop_idx) as u64 + 1)) })))] }) .collect::<Vec<_>>(); let inputs = (0..NUM_LOOP) .map(|loop_idx| { [ValTensor::from(Tensor::from((0..LEN).rev().map(|i| { Value::known(F::from((i * loop_idx) as u64 + 1)) })))] }) .collect::<Vec<_>>(); let circuit = MyCircuit::<F> { references: references.clone().try_into().unwrap(), inputs: inputs.try_into().unwrap(), _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); let inputs = (0..NUM_LOOP) .map(|loop_idx| { let prev_idx = if loop_idx == 0 { NUM_LOOP - 1 } else { loop_idx - 1 }; [ValTensor::from(Tensor::from((0..LEN).rev().map(|i| { Value::known(F::from((i * prev_idx) as u64 + 1)) })))] }) .collect::<Vec<_>>(); let circuit = MyCircuit::<F> { references: references.try_into().unwrap(), inputs: inputs.try_into().unwrap(), _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); assert!(prover.verify().is_err()); } } #[cfg(test)] mod add_with_overflow { use super::*; const K: usize = 4; const LEN: usize = 50; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Add)) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn addcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod add_with_overflow_and_poseidon { use std::collections::HashMap; use halo2curves::bn256::Fr; use crate::circuit::modules::{ poseidon::{ spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH}, PoseidonChip, PoseidonConfig, }, Module, ModulePlanner, }; use super::*; const K: usize = 15; const LEN: usize = 50; const WIDTH: usize = POSEIDON_WIDTH; const RATE: usize = POSEIDON_RATE; #[derive(Debug, Clone)] struct MyCircuitConfig { base: BaseConfig<Fr>, poseidon: PoseidonConfig<WIDTH, RATE>, } #[derive(Clone)] struct MyCircuit { inputs: [ValTensor<Fr>; 2], } impl Circuit<Fr> for MyCircuit { type Config = MyCircuitConfig; type FloorPlanner = ModulePlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<Fr>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); let base = BaseConfig::configure(cs, &[a, b], &output, CheckMode::SAFE); VarTensor::constant_cols(cs, K, 2, false); let poseidon = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::configure(cs, ()); MyCircuitConfig { base, poseidon } } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<Fr>, ) -> Result<(), Error> { let poseidon_chip: PoseidonChip<PoseidonSpec, WIDTH, RATE, WIDTH> = PoseidonChip::new(config.poseidon.clone()); let assigned_inputs_a = poseidon_chip.layout(&mut layouter, &self.inputs[0..1], 0, &mut HashMap::new())?; let assigned_inputs_b = poseidon_chip.layout(&mut layouter, &self.inputs[1..2], 1, &mut HashMap::new())?; layouter.assign_region(|| "_new_module", |_| Ok(()))?; let inputs = vec![assigned_inputs_a, assigned_inputs_b]; layouter.assign_region( || "model", |region| { let mut region = RegionCtx::new(region, 0, 1); config .base .layout(&mut region, &inputs, Box::new(PolyOp::Add)) .map_err(|_| Error::Synthesis) }, )?; Ok(()) } } #[test] fn addcircuit() { let a = (0..LEN) .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1)) .collect::<Vec<_>>(); let b = (0..LEN) .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1)) .collect::<Vec<_>>(); let commitment_a = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(a.clone()).unwrap()[0][0]; let commitment_b = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(b.clone()).unwrap()[0][0]; // parameters let a = Tensor::from(a.into_iter().map(Value::known)); let b = Tensor::from(b.into_iter().map(Value::known)); let circuit = MyCircuit { inputs: [ValTensor::from(a), ValTensor::from(b)], }; let prover = MockProver::run(K as u32, &circuit, vec![vec![commitment_a, commitment_b]]).unwrap(); prover.assert_satisfied(); } #[test] fn addcircuit_bad_hashes() { let a = (0..LEN) .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1)) .collect::<Vec<_>>(); let b = (0..LEN) .map(|i| halo2curves::bn256::Fr::from(i as u64 + 1)) .collect::<Vec<_>>(); let commitment_a = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(a.clone()) .unwrap()[0][0] + Fr::one(); let commitment_b = PoseidonChip::<PoseidonSpec, WIDTH, RATE, WIDTH>::run(b.clone()) .unwrap()[0][0] + Fr::one(); // parameters let a = Tensor::from(a.into_iter().map(Value::known)); let b = Tensor::from(b.into_iter().map(Value::known)); let circuit = MyCircuit { inputs: [ValTensor::from(a), ValTensor::from(b)], }; let prover = MockProver::run(K as u32, &circuit, vec![vec![commitment_a, commitment_b]]).unwrap(); assert!(prover.verify().is_err()); } } #[cfg(test)] mod sub { use super::*; const K: usize = 4; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Sub)) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn subcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod mult { use super::*; const K: usize = 4; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Mult)) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn multcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let b = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod pow { use super::*; const K: usize = 8; const LEN: usize = 4; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 1], _marker: PhantomData<F>, } impl Circuit<F> for MyCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); Self::Config::configure(cs, &[a, b], &output, CheckMode::SAFE) } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &self.inputs.clone(), Box::new(PolyOp::Pow(5))) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn powcircuit() { // parameters let a = Tensor::from((0..LEN).map(|i| Value::known(F::from(i as u64 + 1)))); let circuit = MyCircuit::<F> { inputs: [ValTensor::from(a)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod matmul_relu { use super::*; const K: usize = 18; const LEN: usize = 32; use crate::circuit::lookup::LookupOp; #[derive(Clone)] struct MyCircuit<F: PrimeField + TensorType + PartialOrd> { inputs: [ValTensor<F>; 2], _marker: PhantomData<F>, } // A columnar ReLu MLP #[derive(Clone)] struct MyConfig<F: PrimeField + TensorType + PartialOrd> { base_config: BaseConfig<F>, } impl Circuit<F> for MyCircuit<F> { type Config = MyConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let a = VarTensor::new_advice(cs, K, 1, LEN); let b = VarTensor::new_advice(cs, K, 1, LEN); let output = VarTensor::new_advice(cs, K, 1, LEN); let mut base_config = BaseConfig::configure(cs, &[a.clone(), b.clone()], &output, CheckMode::SAFE); // sets up a new relu table base_config .configure_lookup(cs, &b, &output, &a, (-32768, 32768), K, &LookupOp::ReLU) .unwrap(); MyConfig { base_config } } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, ) -> Result<(), Error> { config.base_config.layout_tables(&mut layouter).unwrap(); layouter.assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); let op = PolyOp::Einsum { equation: "ij,jk->ik".to_string(), }; let output = config .base_config .layout(&mut region, &self.inputs, Box::new(op)) .unwrap(); let _output = config .base_config .layout(&mut region, &[output.unwrap()], Box::new(LookupOp::ReLU)) .unwrap(); Ok(()) }, )?; Ok(()) } } #[test] fn matmulrelucircuit() { // parameters let mut a = Tensor::from((0..LEN * LEN).map(|_| Value::known(F::from(1)))); a.reshape(&[LEN, LEN]).unwrap(); // parameters let mut b = Tensor::from((0..LEN).map(|_| Value::known(F::from(1)))); b.reshape(&[LEN, 1]).unwrap(); let circuit = MyCircuit { inputs: [ValTensor::from(a), ValTensor::from(b)], _marker: PhantomData, }; let prover = MockProver::run(K as u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] mod relu { use super::*; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, dev::MockProver, plonk::{Circuit, ConstraintSystem, Error}, }; #[derive(Clone)] struct ReLUCircuit<F: PrimeField + TensorType + PartialOrd> { pub input: ValTensor<F>, } impl Circuit<F> for ReLUCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let advices = (0..3) .map(|_| VarTensor::new_advice(cs, 4, 1, 3)) .collect::<Vec<_>>(); let nl = LookupOp::ReLU; let mut config = BaseConfig::default(); config .configure_lookup(cs, &advices[0], &advices[1], &advices[2], (-6, 6), 4, &nl) .unwrap(); config } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, // layouter is our 'write buffer' for the circuit ) -> Result<(), Error> { config.layout_tables(&mut layouter).unwrap(); layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &[self.input.clone()], Box::new(LookupOp::ReLU)) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] fn relucircuit() { let input: Tensor<Value<F>> = Tensor::new(Some(&[Value::<F>::known(F::from(1_u64)); 4]), &[4]).unwrap(); let circuit = ReLUCircuit::<F> { input: ValTensor::from(input), }; let prover = MockProver::run(4_u32, &circuit, vec![]).unwrap(); prover.assert_satisfied(); } } #[cfg(test)] #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] mod lookup_ultra_overflow { use super::*; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, plonk::{Circuit, ConstraintSystem, Error}, poly::kzg::{ commitment::KZGCommitmentScheme, multiopen::{ProverSHPLONK, VerifierSHPLONK}, strategy::SingleStrategy, }, }; use snark_verifier::system::halo2::transcript::evm::EvmTranscript; #[derive(Clone)] struct ReLUCircuit<F: PrimeField + TensorType + PartialOrd> { pub input: ValTensor<F>, } impl Circuit<F> for ReLUCircuit<F> { type Config = BaseConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = TestParams; fn without_witnesses(&self) -> Self { self.clone() } fn configure(cs: &mut ConstraintSystem<F>) -> Self::Config { let advices = (0..3) .map(|_| VarTensor::new_advice(cs, 4, 1, 3)) .collect::<Vec<_>>(); let nl = LookupOp::ReLU; let mut config = BaseConfig::default(); config .configure_lookup( cs, &advices[0], &advices[1], &advices[2], (-1024, 1024), 4, &nl, ) .unwrap(); config } fn synthesize( &self, mut config: Self::Config, mut layouter: impl Layouter<F>, // layouter is our 'write buffer' for the circuit ) -> Result<(), Error> { config.layout_tables(&mut layouter).unwrap(); layouter .assign_region( || "", |region| { let mut region = RegionCtx::new(region, 0, 1); config .layout(&mut region, &[self.input.clone()], Box::new(LookupOp::ReLU)) .map_err(|_| Error::Synthesis) }, ) .unwrap(); Ok(()) } } #[test] #[ignore] fn relucircuit() { // get some logs fam crate::logger::init_logger(); // parameters let a = Tensor::from((0..4).map(|i| Value::known(F::from(i + 1)))); let circuit = ReLUCircuit::<F> { input: ValTensor::from(a), }; let params = crate::pfsys::srs::gen_srs::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<_>, >(4_u32); let pk = crate::pfsys::create_keys::< halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme<halo2curves::bn256::Bn256>, ReLUCircuit<F>, >(&circuit, &params, true) .unwrap(); let prover = crate::pfsys::create_proof_circuit::< KZGCommitmentScheme<_>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, SingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit.clone(), vec![], &params, &pk, // use safe mode to verify that the proof is correct CheckMode::SAFE, crate::Commitments::KZG, crate::pfsys::TranscriptType::EVM, None, None, ); assert!(prover.is_ok()); } }
https://github.com/zkonduit/ezkl
src/circuit/utils.rs
use serde::{Deserialize, Serialize}; // -------------------------------------------------------------------------------------------- // // Float Utils to enable the usage of f32s as the keys of HashMaps // This section is taken from the `eq_float` crate verbatim -- but we also implement deserialization methods // // use std::cmp::Ordering; use std::fmt; use std::hash::{Hash, Hasher}; #[derive(Debug, Default, Clone, Copy)] /// f32 wrapper pub struct F32(pub f32); impl<'de> Deserialize<'de> for F32 { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let float = f32::deserialize(deserializer)?; Ok(F32(float)) } } impl Serialize for F32 { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { f32::serialize(&self.0, serializer) } } /// This works like `PartialEq` on `f32`, except that `NAN == NAN` is true. impl PartialEq for F32 { fn eq(&self, other: &Self) -> bool { if self.0.is_nan() && other.0.is_nan() { true } else { self.0 == other.0 } } } impl Eq for F32 {} /// This works like `PartialOrd` on `f32`, except that `NAN` sorts below all other floats /// (and is equal to another NAN). This always returns a `Some`. impl PartialOrd for F32 { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } /// This works like `PartialOrd` on `f32`, except that `NAN` sorts below all other floats /// (and is equal to another NAN). impl Ord for F32 { fn cmp(&self, other: &Self) -> Ordering { self.0.partial_cmp(&other.0).unwrap_or_else(|| { if self.0.is_nan() && !other.0.is_nan() { Ordering::Less } else if !self.0.is_nan() && other.0.is_nan() { Ordering::Greater } else { Ordering::Equal } }) } } impl Hash for F32 { fn hash<H: Hasher>(&self, state: &mut H) { if self.0.is_nan() { 0x7fc00000u32.hash(state); // a particular bit representation for NAN } else if self.0 == 0.0 { // catches both positive and negative zero 0u32.hash(state); } else { self.0.to_bits().hash(state); } } } impl From<F32> for f32 { fn from(f: F32) -> Self { f.0 } } impl From<f32> for F32 { fn from(f: f32) -> Self { F32(f) } } impl From<f64> for F32 { fn from(f: f64) -> Self { F32(f as f32) } } impl From<usize> for F32 { fn from(f: usize) -> Self { F32(f as f32) } } impl From<F32> for f64 { fn from(f: F32) -> Self { f.0 as f64 } } impl From<&F32> for f64 { fn from(f: &F32) -> Self { f.0 as f64 } } impl fmt::Display for F32 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } #[cfg(test)] mod tests { use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use super::F32; fn calculate_hash<T: Hash>(t: &T) -> u64 { let mut s = DefaultHasher::new(); t.hash(&mut s); s.finish() } #[test] fn f32_eq() { assert!(F32(std::f32::NAN) == F32(std::f32::NAN)); assert!(F32(std::f32::NAN) != F32(5.0)); assert!(F32(5.0) != F32(std::f32::NAN)); assert!(F32(0.0) == F32(-0.0)); } #[test] fn f32_cmp() { assert!(F32(std::f32::NAN) == F32(std::f32::NAN)); assert!(F32(std::f32::NAN) < F32(5.0)); assert!(F32(5.0) > F32(std::f32::NAN)); assert!(F32(0.0) == F32(-0.0)); } #[test] fn f32_hash() { assert!(calculate_hash(&F32(0.0)) == calculate_hash(&F32(-0.0))); assert!(calculate_hash(&F32(std::f32::NAN)) == calculate_hash(&F32(-std::f32::NAN))); } }
https://github.com/zkonduit/ezkl
src/commands.rs
use clap::{Parser, Subcommand}; #[cfg(not(target_arch = "wasm32"))] use ethers::types::H160; #[cfg(feature = "python-bindings")] use pyo3::{ conversion::{FromPyObject, PyTryFrom}, exceptions::PyValueError, prelude::*, types::PyString, }; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use std::{error::Error, str::FromStr}; use tosubcommand::{ToFlags, ToSubcommand}; use crate::{pfsys::ProofType, Commitments, RunArgs}; use crate::circuit::CheckMode; #[cfg(not(target_arch = "wasm32"))] use crate::graph::TestDataSource; use crate::pfsys::TranscriptType; /// The default path to the .json data file pub const DEFAULT_DATA: &str = "input.json"; /// The default path to the .onnx model file pub const DEFAULT_MODEL: &str = "network.onnx"; /// The default path to the compiled model file pub const DEFAULT_COMPILED_CIRCUIT: &str = "model.compiled"; /// The default path to the .json witness file pub const DEFAULT_WITNESS: &str = "witness.json"; /// The default path to the circuit settings file pub const DEFAULT_SETTINGS: &str = "settings.json"; /// The default path to the proving key file pub const DEFAULT_PK: &str = "pk.key"; /// The default path to the verification key file pub const DEFAULT_VK: &str = "vk.key"; /// The default path to the proving key file for aggregated proofs pub const DEFAULT_PK_AGGREGATED: &str = "pk_aggr.key"; /// The default path to the verification key file for aggregated proofs pub const DEFAULT_VK_AGGREGATED: &str = "vk_aggr.key"; /// The default path to the proof file pub const DEFAULT_PROOF: &str = "proof.json"; /// The default path to the proof file for aggregated proofs pub const DEFAULT_PROOF_AGGREGATED: &str = "proof_aggr.json"; /// Default for whether to split proofs pub const DEFAULT_SPLIT: &str = "false"; /// Default verifier abi pub const DEFAULT_VERIFIER_ABI: &str = "verifier_abi.json"; /// Default verifier abi for aggregated proofs pub const DEFAULT_VERIFIER_AGGREGATED_ABI: &str = "verifier_aggr_abi.json"; /// Default verifier abi for data attestation pub const DEFAULT_VERIFIER_DA_ABI: &str = "verifier_da_abi.json"; /// Default solidity code pub const DEFAULT_SOL_CODE: &str = "evm_deploy.sol"; /// Default solidity code for aggregated proofs pub const DEFAULT_SOL_CODE_AGGREGATED: &str = "evm_deploy_aggr.sol"; /// Default solidity code for data attestation pub const DEFAULT_SOL_CODE_DA: &str = "evm_deploy_da.sol"; /// Default contract address pub const DEFAULT_CONTRACT_ADDRESS: &str = "contract.address"; /// Default contract address for data attestation pub const DEFAULT_CONTRACT_ADDRESS_DA: &str = "contract_da.address"; /// Default contract address for vk pub const DEFAULT_CONTRACT_ADDRESS_VK: &str = "contract_vk.address"; /// Default check mode pub const DEFAULT_CHECKMODE: &str = "safe"; /// Default calibration target pub const DEFAULT_CALIBRATION_TARGET: &str = "resources"; /// Default logrows for aggregated proofs pub const DEFAULT_AGGREGATED_LOGROWS: &str = "23"; /// Default optimizer runs pub const DEFAULT_OPTIMIZER_RUNS: &str = "1"; /// Default fuzz runs pub const DEFAULT_FUZZ_RUNS: &str = "10"; /// Default calibration file pub const DEFAULT_CALIBRATION_FILE: &str = "calibration.json"; /// Default lookup safety margin pub const DEFAULT_LOOKUP_SAFETY_MARGIN: &str = "2"; /// Default Compress selectors pub const DEFAULT_DISABLE_SELECTOR_COMPRESSION: &str = "false"; /// Default render vk seperately pub const DEFAULT_RENDER_VK_SEPERATELY: &str = "false"; /// Default VK sol path pub const DEFAULT_VK_SOL: &str = "vk.sol"; /// Default VK abi path pub const DEFAULT_VK_ABI: &str = "vk.abi"; /// Default scale rebase multipliers for calibration pub const DEFAULT_SCALE_REBASE_MULTIPLIERS: &str = "1,2,10"; /// Default use reduced srs for verification pub const DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION: &str = "false"; /// Default only check for range check rebase pub const DEFAULT_ONLY_RANGE_CHECK_REBASE: &str = "false"; /// Default commitment pub const DEFAULT_COMMITMENT: &str = "kzg"; #[cfg(feature = "python-bindings")] /// Converts TranscriptType into a PyObject (Required for TranscriptType to be compatible with Python) impl IntoPy<PyObject> for TranscriptType { fn into_py(self, py: Python) -> PyObject { match self { TranscriptType::Poseidon => "poseidon".to_object(py), TranscriptType::EVM => "evm".to_object(py), } } } #[cfg(feature = "python-bindings")] /// Obtains TranscriptType from PyObject (Required for TranscriptType to be compatible with Python) impl<'source> FromPyObject<'source> for TranscriptType { fn extract(ob: &'source PyAny) -> PyResult<Self> { let trystr = <PyString as PyTryFrom>::try_from(ob)?; let strval = trystr.to_string(); match strval.to_lowercase().as_str() { "poseidon" => Ok(TranscriptType::Poseidon), "evm" => Ok(TranscriptType::EVM), _ => Err(PyValueError::new_err("Invalid value for TranscriptType")), } } } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, PartialOrd)] /// Determines what the calibration pass should optimize for pub enum CalibrationTarget { /// Optimizes for reducing cpu and memory usage Resources { /// Whether to allow for column overflow. This can reduce memory usage (eg. for a browser environment), but may result in a verifier that doesn't fit on the blockchain. col_overflow: bool, }, /// Optimizes for numerical accuracy given the fixed point representation Accuracy, } impl Default for CalibrationTarget { fn default() -> Self { CalibrationTarget::Resources { col_overflow: false, } } } impl std::fmt::Display for CalibrationTarget { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { CalibrationTarget::Resources { col_overflow: true } => { "resources/col-overflow".to_string() } CalibrationTarget::Resources { col_overflow: false, } => "resources".to_string(), CalibrationTarget::Accuracy => "accuracy".to_string(), } ) } } impl ToFlags for CalibrationTarget { fn to_flags(&self) -> Vec<String> { vec![format!("{}", self)] } } impl From<&str> for CalibrationTarget { fn from(s: &str) -> Self { match s { "resources" => CalibrationTarget::Resources { col_overflow: false, }, "resources/col-overflow" => CalibrationTarget::Resources { col_overflow: true }, "accuracy" => CalibrationTarget::Accuracy, _ => { log::error!("Invalid value for CalibrationTarget"); log::warn!("Defaulting to resources"); CalibrationTarget::default() } } } } #[cfg(not(target_arch = "wasm32"))] #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, PartialOrd)] /// wrapper for H160 to make it easy to parse into flag vals pub struct H160Flag { inner: H160, } #[cfg(not(target_arch = "wasm32"))] impl From<H160Flag> for H160 { fn from(val: H160Flag) -> H160 { val.inner } } #[cfg(not(target_arch = "wasm32"))] impl ToFlags for H160Flag { fn to_flags(&self) -> Vec<String> { vec![format!("{:#x}", self.inner)] } } #[cfg(not(target_arch = "wasm32"))] impl From<&str> for H160Flag { fn from(s: &str) -> Self { Self { inner: H160::from_str(s).unwrap(), } } } #[cfg(feature = "python-bindings")] /// Converts CalibrationTarget into a PyObject (Required for CalibrationTarget to be compatible with Python) impl IntoPy<PyObject> for CalibrationTarget { fn into_py(self, py: Python) -> PyObject { match self { CalibrationTarget::Resources { col_overflow: true } => { "resources/col-overflow".to_object(py) } CalibrationTarget::Resources { col_overflow: false, } => "resources".to_object(py), CalibrationTarget::Accuracy => "accuracy".to_object(py), } } } #[cfg(feature = "python-bindings")] /// Obtains CalibrationTarget from PyObject (Required for CalibrationTarget to be compatible with Python) impl<'source> FromPyObject<'source> for CalibrationTarget { fn extract(ob: &'source PyAny) -> PyResult<Self> { let trystr = <PyString as PyTryFrom>::try_from(ob)?; let strval = trystr.to_string(); match strval.to_lowercase().as_str() { "resources" => Ok(CalibrationTarget::Resources { col_overflow: false, }), "resources/col-overflow" => Ok(CalibrationTarget::Resources { col_overflow: true }), "accuracy" => Ok(CalibrationTarget::Accuracy), _ => Err(PyValueError::new_err("Invalid value for CalibrationTarget")), } } } // not wasm use lazy_static::lazy_static; // if CARGO VERSION is 0.0.0 replace with "source - no compatibility guaranteed" lazy_static! { /// The version of the ezkl library pub static ref VERSION: &'static str = if env!("CARGO_PKG_VERSION") == "0.0.0" { "source - no compatibility guaranteed" } else { env!("CARGO_PKG_VERSION") }; } #[allow(missing_docs)] #[derive(Parser, Debug, Clone, Deserialize, Serialize)] #[command(author, about, long_about = None)] #[clap(version = *VERSION)] pub struct Cli { #[command(subcommand)] #[allow(missing_docs)] pub command: Commands, } impl Cli { /// Export the ezkl configuration as json pub fn as_json(&self) -> Result<String, Box<dyn Error>> { let serialized = match serde_json::to_string(&self) { Ok(s) => s, Err(e) => { return Err(Box::new(e)); } }; Ok(serialized) } /// Parse an ezkl configuration from a json pub fn from_json(arg_json: &str) -> Result<Self, serde_json::Error> { serde_json::from_str(arg_json) } } #[allow(missing_docs)] #[derive(Debug, Subcommand, Clone, Deserialize, Serialize, PartialEq, PartialOrd, ToSubcommand)] pub enum Commands { #[cfg(feature = "empty-cmd")] /// Creates an empty buffer Empty, /// Loads model and prints model table Table { /// The path to the .onnx model file #[arg(short = 'M', long, default_value = DEFAULT_MODEL)] model: PathBuf, /// proving arguments #[clap(flatten)] args: RunArgs, }, /// Generates the witness from an input file. GenWitness { /// The path to the .json data file #[arg(short = 'D', long, default_value = DEFAULT_DATA)] data: PathBuf, /// The path to the compiled model file (generated using the compile-circuit command) #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)] compiled_circuit: PathBuf, /// Path to output the witness .json file #[arg(short = 'O', long, default_value = DEFAULT_WITNESS)] output: PathBuf, /// Path to the verification key file (optional - solely used to generate kzg commits) #[arg(short = 'V', long)] vk_path: Option<PathBuf>, /// Path to the srs file (optional - solely used to generate kzg commits) #[arg(short = 'P', long)] srs_path: Option<PathBuf>, }, /// Produces the proving hyperparameters, from run-args GenSettings { /// The path to the .onnx model file #[arg(short = 'M', long, default_value = DEFAULT_MODEL)] model: PathBuf, /// The path to generate the circuit settings .json file to #[arg(short = 'O', long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, /// proving arguments #[clap(flatten)] args: RunArgs, }, /// Calibrates the proving scale, lookup bits and logrows from a circuit settings file. #[cfg(not(target_arch = "wasm32"))] CalibrateSettings { /// The path to the .json calibration data file. #[arg(short = 'D', long, default_value = DEFAULT_CALIBRATION_FILE)] data: PathBuf, /// The path to the .onnx model file #[arg(short = 'M', long, default_value = DEFAULT_MODEL)] model: PathBuf, /// The path to load circuit settings .json file AND overwrite (generated using the gen-settings command). #[arg(short = 'O', long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, #[arg(long = "target", default_value = DEFAULT_CALIBRATION_TARGET)] /// Target for calibration. Set to "resources" to optimize for computational resource. Otherwise, set to "accuracy" to optimize for accuracy. target: CalibrationTarget, /// 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 #[arg(long, default_value = DEFAULT_LOOKUP_SAFETY_MARGIN)] lookup_safety_margin: i128, /// Optional scales to specifically try for calibration. Example, --scales 0,4 #[arg(long, value_delimiter = ',', allow_hyphen_values = true)] scales: Option<Vec<crate::Scale>>, /// Optional scale rebase multipliers to specifically try for calibration. This is the multiplier at which we divide to return to the input scale. Example, --scale-rebase-multipliers 0,4 #[arg( long, value_delimiter = ',', allow_hyphen_values = true, default_value = DEFAULT_SCALE_REBASE_MULTIPLIERS )] scale_rebase_multiplier: Vec<u32>, /// max logrows to use for calibration, 26 is the max public SRS size #[arg(long)] max_logrows: Option<u32>, // whether to only range check rebases (instead of trying both range check and lookup) #[arg(long, default_value = DEFAULT_ONLY_RANGE_CHECK_REBASE)] only_range_check_rebase: bool, }, /// Generates a dummy SRS #[command(name = "gen-srs", arg_required_else_help = true)] GenSrs { /// The path to output the generated SRS #[arg(long)] srs_path: PathBuf, /// number of logrows to use for srs #[arg(long)] logrows: usize, /// commitment used #[arg(long, default_value = DEFAULT_COMMITMENT)] commitment: Commitments, }, #[cfg(not(target_arch = "wasm32"))] /// Gets an SRS from a circuit settings file. #[command(name = "get-srs")] GetSrs { /// The path to output the desired srs file, if set to None will save to $EZKL_REPO_PATH/srs #[arg(long)] srs_path: Option<PathBuf>, /// Path to the circuit settings .json file to read in logrows from. Overriden by logrows if specified. #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)] settings_path: Option<PathBuf>, /// Number of logrows to use for srs. Overrides settings_path if specified. #[arg(long, default_value = None)] logrows: Option<u32>, /// Commitment used #[arg(long, default_value = None)] commitment: Option<Commitments>, }, /// Loads model and input and runs mock prover (for testing) Mock { /// The path to the .json witness file (generated using the gen-witness command) #[arg(short = 'W', long, default_value = DEFAULT_WITNESS)] witness: PathBuf, /// The path to the compiled model file (generated using the compile-circuit command) #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)] model: PathBuf, }, /// Mock aggregate proofs MockAggregate { /// The path to the snarks to aggregate over (generated using the prove command with the --proof-type=for-aggr flag) #[arg(long, default_value = DEFAULT_PROOF, value_delimiter = ',', allow_hyphen_values = true)] aggregation_snarks: Vec<PathBuf>, /// logrows used for aggregation circuit #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)] logrows: u32, /// whether the accumulated are segments of a larger proof #[arg(long, default_value = DEFAULT_SPLIT)] split_proofs: bool, }, /// setup aggregation circuit :) SetupAggregate { /// The path to samples of snarks that will be aggregated over (generated using the prove command with the --proof-type=for-aggr flag) #[arg(long, default_value = DEFAULT_PROOF, value_delimiter = ',', allow_hyphen_values = true)] sample_snarks: Vec<PathBuf>, /// The path to save the desired verification key file to #[arg(long, default_value = DEFAULT_VK_AGGREGATED)] vk_path: PathBuf, /// The path to save the proving key to #[arg(long, default_value = DEFAULT_PK_AGGREGATED)] pk_path: PathBuf, /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, /// logrows used for aggregation circuit #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)] logrows: u32, /// whether the accumulated are segments of a larger proof #[arg(long, default_value = DEFAULT_SPLIT)] split_proofs: bool, /// compress selectors #[arg(long, default_value = DEFAULT_DISABLE_SELECTOR_COMPRESSION)] disable_selector_compression: bool, /// commitment used #[arg(long, default_value = DEFAULT_COMMITMENT)] commitment: Option<Commitments>, }, /// Aggregates proofs :) Aggregate { /// The path to the snarks to aggregate over (generated using the prove command with the --proof-type=for-aggr flag) #[arg(long, default_value = DEFAULT_PROOF, value_delimiter = ',', allow_hyphen_values = true)] aggregation_snarks: Vec<PathBuf>, /// The path to load the desired proving key file (generated using the setup-aggregate command) #[arg(long, default_value = DEFAULT_PK_AGGREGATED)] pk_path: PathBuf, /// The path to output the proof file to #[arg(long, default_value = DEFAULT_PROOF_AGGREGATED)] proof_path: PathBuf, /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, #[arg( long, require_equals = true, num_args = 0..=1, default_value_t = TranscriptType::default(), value_enum )] transcript: TranscriptType, /// logrows used for aggregation circuit #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)] logrows: u32, /// run sanity checks during calculations (safe or unsafe) #[arg(long, default_value = DEFAULT_CHECKMODE)] check_mode: CheckMode, /// whether the accumulated proofs are segments of a larger circuit #[arg(long, default_value = DEFAULT_SPLIT)] split_proofs: bool, /// commitment used #[arg(long, default_value = DEFAULT_COMMITMENT)] commitment: Option<Commitments>, }, /// Compiles a circuit from onnx to a simplified graph (einsum + other ops) and parameters as sets of field elements CompileCircuit { /// The path to the .onnx model file #[arg(short = 'M', long, default_value = DEFAULT_MODEL)] model: PathBuf, /// The path to the compiled model file (generated using the compile-circuit command) #[arg(long, default_value = DEFAULT_COMPILED_CIRCUIT)] compiled_circuit: PathBuf, /// The path to load circuit settings .json file from (generated using the gen-settings command) #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, }, /// Creates pk and vk Setup { /// The path to the compiled model file (generated using the compile-circuit command) #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)] compiled_circuit: PathBuf, /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, /// The path to output the verification key file to #[arg(long, default_value = DEFAULT_VK)] vk_path: PathBuf, /// The path to output the proving key file to #[arg(long, default_value = DEFAULT_PK)] pk_path: PathBuf, /// The graph witness (optional - used to override fixed values in the circuit) #[arg(short = 'W', long)] witness: Option<PathBuf>, /// compress selectors #[arg(long, default_value = DEFAULT_DISABLE_SELECTOR_COMPRESSION)] disable_selector_compression: bool, }, #[cfg(not(target_arch = "wasm32"))] /// Deploys a test contact that the data attester reads from and creates a data attestation formatted input.json file that contains call data information #[command(arg_required_else_help = true)] SetupTestEvmData { /// 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) #[arg(short = 'D', long)] data: PathBuf, /// The path to the compiled model file (generated using the compile-circuit command) #[arg(short = 'M', long)] compiled_circuit: PathBuf, /// 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) #[arg(short = 'T', long)] test_data: PathBuf, /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state #[arg(short = 'U', long)] rpc_url: Option<String>, /// where the input data come from #[arg(long, default_value = "on-chain")] input_source: TestDataSource, /// where the output data come from #[arg(long, default_value = "on-chain")] output_source: TestDataSource, }, #[cfg(not(target_arch = "wasm32"))] /// The Data Attestation Verifier contract stores the account calls to fetch data to feed into ezkl. This call data can be updated by an admin account. This tests that admin account is able to update this call data. #[command(arg_required_else_help = true)] TestUpdateAccountCalls { /// The path to the verifier contract's address #[arg(long)] addr: H160Flag, /// The path to the .json data file. #[arg(short = 'D', long)] data: PathBuf, /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state #[arg(short = 'U', long)] rpc_url: Option<String>, }, #[cfg(not(target_arch = "wasm32"))] /// Swaps the positions in the transcript that correspond to commitments SwapProofCommitments { /// The path to the proof file #[arg(short = 'P', long, default_value = DEFAULT_PROOF)] proof_path: PathBuf, /// The path to the witness file #[arg(short = 'W', long, default_value = DEFAULT_WITNESS)] witness_path: PathBuf, }, #[cfg(not(target_arch = "wasm32"))] /// Loads model, data, and creates proof Prove { /// The path to the .json witness file (generated using the gen-witness command) #[arg(short = 'W', long, default_value = DEFAULT_WITNESS)] witness: PathBuf, /// The path to the compiled model file (generated using the compile-circuit command) #[arg(short = 'M', long, default_value = DEFAULT_COMPILED_CIRCUIT)] compiled_circuit: PathBuf, /// The path to load the desired proving key file (generated using the setup command) #[arg(long, default_value = DEFAULT_PK)] pk_path: PathBuf, /// The path to output the proof file to #[arg(long, default_value = DEFAULT_PROOF)] proof_path: PathBuf, /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, #[arg( long, require_equals = true, num_args = 0..=1, default_value_t = ProofType::Single, value_enum )] proof_type: ProofType, /// run sanity checks during calculations (safe or unsafe) #[arg(long, default_value = DEFAULT_CHECKMODE)] check_mode: CheckMode, }, #[cfg(not(target_arch = "wasm32"))] /// Creates an Evm verifier for a single proof #[command(name = "create-evm-verifier")] CreateEvmVerifier { /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, /// The path to load circuit settings .json file from (generated using the gen-settings command) #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, /// The path to load the desired verification key file #[arg(long, default_value = DEFAULT_VK)] vk_path: PathBuf, /// The path to output the Solidity code #[arg(long, default_value = DEFAULT_SOL_CODE)] sol_code_path: PathBuf, /// The path to output the Solidity verifier ABI #[arg(long, default_value = DEFAULT_VERIFIER_ABI)] abi_path: PathBuf, /// 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. #[arg(long, default_value = DEFAULT_RENDER_VK_SEPERATELY)] render_vk_seperately: bool, }, #[cfg(not(target_arch = "wasm32"))] /// Creates an Evm verifier for a single proof #[command(name = "create-evm-vk")] CreateEvmVK { /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, /// The path to load circuit settings .json file from (generated using the gen-settings command) #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, /// The path to load the desired verification key file #[arg(long, default_value = DEFAULT_VK)] vk_path: PathBuf, /// The path to output the Solidity code #[arg(long, default_value = DEFAULT_VK_SOL)] sol_code_path: PathBuf, /// The path to output the Solidity verifier ABI #[arg(long, default_value = DEFAULT_VK_ABI)] abi_path: PathBuf, }, #[cfg(not(target_arch = "wasm32"))] /// Creates an Evm verifier that attests to on-chain inputs for a single proof #[command(name = "create-evm-da")] CreateEvmDataAttestation { /// The path to load circuit settings .json file from (generated using the gen-settings command) #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, /// The path to output the Solidity code #[arg(long, default_value = DEFAULT_SOL_CODE_DA)] sol_code_path: PathBuf, /// The path to output the Solidity verifier ABI #[arg(long, default_value = DEFAULT_VERIFIER_DA_ABI)] abi_path: PathBuf, /// 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. #[arg(short = 'D', long, default_value = DEFAULT_DATA)] data: PathBuf, }, #[cfg(not(target_arch = "wasm32"))] /// Creates an Evm verifier for an aggregate proof #[command(name = "create-evm-verifier-aggr")] CreateEvmVerifierAggr { /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, /// The path to load the desired verification key file #[arg(long, default_value = DEFAULT_VK_AGGREGATED)] vk_path: PathBuf, /// The path to the Solidity code #[arg(long, default_value = DEFAULT_SOL_CODE_AGGREGATED)] sol_code_path: PathBuf, /// The path to output the Solidity verifier ABI #[arg(long, default_value = DEFAULT_VERIFIER_AGGREGATED_ABI)] abi_path: PathBuf, // aggregated circuit settings paths, used to calculate the number of instances in the aggregate proof #[arg(long, default_value = DEFAULT_SETTINGS, value_delimiter = ',', allow_hyphen_values = true)] aggregation_settings: Vec<PathBuf>, // logrows used for aggregation circuit #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)] logrows: u32, /// 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. #[arg(long, default_value = DEFAULT_RENDER_VK_SEPERATELY)] render_vk_seperately: bool, }, /// Verifies a proof, returning accept or reject Verify { /// The path to load circuit settings .json file from (generated using the gen-settings command) #[arg(short = 'S', long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, /// The path to the proof file (generated using the prove command) #[arg(long, default_value = DEFAULT_PROOF)] proof_path: PathBuf, /// The path to the verification key file (generated using the setup command) #[arg(long, default_value = DEFAULT_VK)] vk_path: PathBuf, /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, /// Reduce 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) #[arg(long, default_value = DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION)] reduced_srs: bool, }, /// Verifies an aggregate proof, returning accept or reject VerifyAggr { /// The path to the proof file (generated using the prove command) #[arg(long, default_value = DEFAULT_PROOF_AGGREGATED)] proof_path: PathBuf, /// The path to the verification key file (generated using the setup-aggregate command) #[arg(long, default_value = DEFAULT_VK_AGGREGATED)] vk_path: PathBuf, /// reduced srs #[arg(long, default_value = DEFAULT_USE_REDUCED_SRS_FOR_VERIFICATION)] reduced_srs: bool, /// The path to SRS, if None will use $EZKL_REPO_PATH/srs/kzg{logrows}.srs #[arg(long)] srs_path: Option<PathBuf>, /// logrows used for aggregation circuit #[arg(long, default_value = DEFAULT_AGGREGATED_LOGROWS)] logrows: u32, /// commitment #[arg(long, default_value = DEFAULT_COMMITMENT)] commitment: Option<Commitments>, }, #[cfg(not(target_arch = "wasm32"))] /// Deploys an evm verifier that is generated by ezkl DeployEvmVerifier { /// The path to the Solidity code (generated using the create-evm-verifier command) #[arg(long, default_value = DEFAULT_SOL_CODE)] sol_code_path: PathBuf, /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state #[arg(short = 'U', long)] rpc_url: Option<String>, #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS)] /// The path to output the contract address addr_path: PathBuf, /// The optimizer runs to set on the verifier. Lower values optimize for deployment cost, while higher values optimize for gas cost. #[arg(long, default_value = DEFAULT_OPTIMIZER_RUNS)] optimizer_runs: usize, /// Private secp256K1 key in hex format, 64 chars, no 0x prefix, of the account signing transactions. If None the private key will be generated by Anvil #[arg(short = 'P', long)] private_key: Option<String>, }, #[cfg(not(target_arch = "wasm32"))] /// Deploys an evm verifier that is generated by ezkl DeployEvmVK { /// The path to the Solidity code (generated using the create-evm-verifier command) #[arg(long, default_value = DEFAULT_VK_SOL)] sol_code_path: PathBuf, /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state #[arg(short = 'U', long)] rpc_url: Option<String>, #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS_VK)] /// The path to output the contract address addr_path: PathBuf, /// The optimizer runs to set on the verifier. Lower values optimize for deployment cost, while higher values optimize for gas cost. #[arg(long, default_value = DEFAULT_OPTIMIZER_RUNS)] optimizer_runs: usize, /// Private secp256K1 key in hex format, 64 chars, no 0x prefix, of the account signing transactions. If None the private key will be generated by Anvil #[arg(short = 'P', long)] private_key: Option<String>, }, #[cfg(not(target_arch = "wasm32"))] /// Deploys an evm verifier that allows for data attestation #[command(name = "deploy-evm-da")] DeployEvmDataAttestation { /// 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) #[arg(short = 'D', long, default_value = DEFAULT_DATA)] data: PathBuf, /// The path to load circuit settings .json file from (generated using the gen-settings command) #[arg(long, default_value = DEFAULT_SETTINGS)] settings_path: PathBuf, /// The path to the Solidity code #[arg(long, default_value = DEFAULT_SOL_CODE_DA)] sol_code_path: PathBuf, /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state #[arg(short = 'U', long)] rpc_url: Option<String>, #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS_DA)] /// The path to output the contract address addr_path: PathBuf, /// The optimizer runs to set on the verifier. (Lower values optimize for deployment, while higher values optimize for execution) #[arg(long, default_value = DEFAULT_OPTIMIZER_RUNS)] optimizer_runs: usize, /// Private secp256K1 key in hex format, 64 chars, no 0x prefix, of the account signing transactions. If None the private key will be generated by Anvil #[arg(short = 'P', long)] private_key: Option<String>, }, #[cfg(not(target_arch = "wasm32"))] /// Verifies a proof using a local Evm executor, returning accept or reject #[command(name = "verify-evm")] VerifyEvm { /// The path to the proof file (generated using the prove command) #[arg(long, default_value = DEFAULT_PROOF)] proof_path: PathBuf, /// The path to verifier contract's address #[arg(long, default_value = DEFAULT_CONTRACT_ADDRESS)] addr_verifier: H160Flag, /// RPC URL for an Ethereum node, if None will use Anvil but WON'T persist state #[arg(short = 'U', long)] rpc_url: Option<String>, /// does the verifier use data attestation ? #[arg(long)] addr_da: Option<H160Flag>, // is the vk rendered seperately, if so specify an address #[arg(long)] addr_vk: Option<H160Flag>, }, }
https://github.com/zkonduit/ezkl
src/eth.rs
use crate::graph::input::{CallsToAccount, FileSourceInner, GraphData}; use crate::graph::modules::POSEIDON_INSTANCES; use crate::graph::DataSource; #[cfg(not(target_arch = "wasm32"))] use crate::graph::GraphSettings; use crate::pfsys::evm::EvmVerificationError; use crate::pfsys::Snark; use ethers::abi::Contract; use ethers::contract::abigen; use ethers::contract::ContractFactory; use ethers::core::k256::ecdsa::SigningKey; use ethers::middleware::SignerMiddleware; use ethers::prelude::ContractInstance; #[cfg(target_arch = "wasm32")] use ethers::prelude::Wallet; use ethers::providers::Middleware; use ethers::providers::{Http, Provider}; use ethers::signers::Signer; use ethers::solc::{CompilerInput, Solc}; use ethers::types::transaction::eip2718::TypedTransaction; use ethers::types::TransactionRequest; use ethers::types::H160; use ethers::types::U256; use ethers::types::{Bytes, I256}; #[cfg(not(target_arch = "wasm32"))] use ethers::{ prelude::{LocalWallet, Wallet}, utils::{Anvil, AnvilInstance}, }; use halo2_solidity_verifier::encode_calldata; use halo2curves::bn256::{Fr, G1Affine}; use halo2curves::group::ff::PrimeField; use log::{debug, info, warn}; use std::error::Error; use std::path::PathBuf; #[cfg(not(target_arch = "wasm32"))] use std::time::Duration; use std::{convert::TryFrom, sync::Arc}; /// A local ethers-rs based client pub type EthersClient = Arc<SignerMiddleware<Provider<Http>, Wallet<SigningKey>>>; // Generate contract bindings OUTSIDE the functions so they are part of library abigen!(TestReads, "./abis/TestReads.json"); abigen!(DataAttestation, "./abis/DataAttestation.json"); abigen!(QuantizeData, "./abis/QuantizeData.json"); const TESTREADS_SOL: &str = include_str!("../contracts/TestReads.sol"); const QUANTIZE_DATA_SOL: &str = include_str!("../contracts/QuantizeData.sol"); const ATTESTDATA_SOL: &str = include_str!("../contracts/AttestData.sol"); const LOADINSTANCES_SOL: &str = include_str!("../contracts/LoadInstances.sol"); /// Return an instance of Anvil and a client for the given RPC URL. If none is provided, a local client is used. #[cfg(not(target_arch = "wasm32"))] pub async fn setup_eth_backend( rpc_url: Option<&str>, private_key: Option<&str>, ) -> Result<(AnvilInstance, EthersClient), Box<dyn Error>> { // Launch anvil let anvil = Anvil::new() .args(["--code-size-limit=41943040", "--disable-block-gas-limit"]) .spawn(); let endpoint: String; if let Some(rpc_url) = rpc_url { endpoint = rpc_url.to_string(); } else { endpoint = anvil.endpoint(); }; // Connect to the network let provider = Provider::<Http>::try_from(endpoint)?.interval(Duration::from_millis(10u64)); let chain_id = provider.get_chainid().await?.as_u64(); info!("using chain {}", chain_id); // Instantiate the wallet let wallet: LocalWallet; if let Some(private_key) = private_key { debug!("using private key {}", private_key); // Sanity checks for private_key let private_key_format_error = "Private key must be in hex format, 64 chars, without 0x prefix"; if private_key.len() != 64 { return Err(private_key_format_error.into()); } let private_key_buffer = hex::decode(private_key)?; let signing_key = SigningKey::from_slice(&private_key_buffer)?; wallet = LocalWallet::from(signing_key); } else { wallet = anvil.keys()[0].clone().into(); } // Instantiate the client with the signer let client = Arc::new(SignerMiddleware::new( provider, wallet.with_chain_id(chain_id), )); Ok((anvil, client)) } /// pub async fn deploy_contract_via_solidity( sol_code_path: PathBuf, rpc_url: Option<&str>, runs: usize, private_key: Option<&str>, contract_name: &str, ) -> Result<ethers::types::Address, Box<dyn Error>> { // anvil instance must be alive at least until the factory completes the deploy let (anvil, client) = setup_eth_backend(rpc_url, private_key).await?; let (abi, bytecode, runtime_bytecode) = get_contract_artifacts(sol_code_path, contract_name, runs)?; let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?; let contract = factory.deploy(())?.send().await?; let addr = contract.address(); drop(anvil); Ok(addr) } /// pub async fn deploy_da_verifier_via_solidity( settings_path: PathBuf, input: PathBuf, sol_code_path: PathBuf, rpc_url: Option<&str>, runs: usize, private_key: Option<&str>, ) -> Result<ethers::types::Address, Box<dyn Error>> { let (anvil, client) = setup_eth_backend(rpc_url, private_key).await?; let input = GraphData::from_path(input)?; let settings = GraphSettings::load(&settings_path)?; let mut scales: Vec<u32> = vec![]; // The data that will be stored in the test contracts that will eventually be read from. let mut calls_to_accounts = vec![]; let mut instance_shapes = vec![]; let mut model_instance_offset = 0; if settings.run_args.input_visibility.is_hashed() { instance_shapes.push(POSEIDON_INSTANCES) } else if settings.run_args.input_visibility.is_public() { for idx in 0..settings.model_input_scales.len() { let shape = &settings.model_instance_shapes[idx]; instance_shapes.push(shape.iter().product::<usize>()); model_instance_offset += 1; } } if settings.run_args.param_visibility.is_hashed() { return Err(Box::new(EvmVerificationError::InvalidVisibility)); } if settings.run_args.output_visibility.is_hashed() { instance_shapes.push(POSEIDON_INSTANCES) } else if settings.run_args.output_visibility.is_public() { for idx in model_instance_offset..model_instance_offset + settings.model_output_scales.len() { let shape = &settings.model_instance_shapes[idx]; instance_shapes.push(shape.iter().product::<usize>()); } } let mut instance_idx = 0; let mut contract_instance_offset = 0; if let DataSource::OnChain(source) = input.input_data { if settings.run_args.input_visibility.is_hashed_public() { // set scales 1.0 scales.extend(vec![0; instance_shapes[instance_idx]]); instance_idx += 1; } else { let input_scales = settings.model_input_scales; // give each input a scale for scale in input_scales { scales.extend(vec![scale as u32; instance_shapes[instance_idx]]); instance_idx += 1; } } for call in source.calls { calls_to_accounts.push(call); } } else if let DataSource::File(source) = input.input_data { if settings.run_args.input_visibility.is_public() { instance_idx += source.len(); for s in source { contract_instance_offset += s.len(); } } } if let Some(DataSource::OnChain(source)) = input.output_data { if settings.run_args.output_visibility.is_hashed_public() { // set scales 1.0 scales.extend(vec![0; instance_shapes[instance_idx]]); } else { let input_scales = settings.model_output_scales; // give each output a scale for scale in input_scales { scales.extend(vec![scale as u32; instance_shapes[instance_idx]]); instance_idx += 1; } } for call in source.calls { calls_to_accounts.push(call); } } let (contract_addresses, call_data, decimals) = if !calls_to_accounts.is_empty() { parse_calls_to_accounts(calls_to_accounts)? } else { return Err("Data source for either input_data or output_data must be OnChain".into()); }; let (abi, bytecode, runtime_bytecode) = get_contract_artifacts(sol_code_path, "DataAttestation", runs)?; let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?; info!("call_data: {:#?}", call_data); info!("contract_addresses: {:#?}", contract_addresses); info!("decimals: {:#?}", decimals); let contract = factory .deploy(( contract_addresses, call_data, decimals, scales, contract_instance_offset as u32, client.address(), ))? .send() .await?; drop(anvil); Ok(contract.address()) } type ParsedCallsToAccount = (Vec<H160>, Vec<Vec<Bytes>>, Vec<Vec<U256>>); fn parse_calls_to_accounts( calls_to_accounts: Vec<CallsToAccount>, ) -> Result<ParsedCallsToAccount, Box<dyn Error>> { let mut contract_addresses = vec![]; let mut call_data = vec![]; let mut decimals: Vec<Vec<U256>> = vec![]; for (i, val) in calls_to_accounts.iter().enumerate() { let contract_address_bytes = hex::decode(val.address.clone())?; let contract_address = H160::from_slice(&contract_address_bytes); contract_addresses.push(contract_address); call_data.push(vec![]); decimals.push(vec![]); for (call, decimal) in &val.call_data { let call_data_bytes = hex::decode(call)?; call_data[i].push(ethers::types::Bytes::from(call_data_bytes)); decimals[i].push(ethers::types::U256::from_dec_str(&decimal.to_string())?); } } Ok((contract_addresses, call_data, decimals)) } pub async fn update_account_calls( addr: H160, input: PathBuf, rpc_url: Option<&str>, ) -> Result<(), Box<dyn Error>> { let input = GraphData::from_path(input)?; // The data that will be stored in the test contracts that will eventually be read from. let mut calls_to_accounts = vec![]; if let DataSource::OnChain(source) = input.input_data { for call in source.calls { calls_to_accounts.push(call); } } if let Some(DataSource::OnChain(source)) = input.output_data { for call in source.calls { calls_to_accounts.push(call); } } let (contract_addresses, call_data, decimals) = if !calls_to_accounts.is_empty() { parse_calls_to_accounts(calls_to_accounts)? } else { return Err("Data source for either input_data or output_data must be OnChain".into()); }; let (anvil, client) = setup_eth_backend(rpc_url, None).await?; let contract = DataAttestation::new(addr, client.clone()); contract .update_account_calls( contract_addresses.clone(), call_data.clone(), decimals.clone(), ) .send() .await?; // Instantiate a different wallet let wallet: LocalWallet = anvil.keys()[1].clone().into(); let client = Arc::new(client.with_signer(wallet.with_chain_id(anvil.chain_id()))); // update contract signer with non admin account let contract = DataAttestation::new(addr, client.clone()); // call to update_account_calls should fail if (contract .update_account_calls(contract_addresses, call_data, decimals) .send() .await) .is_err() { info!("update_account_calls failed as expected"); } else { return Err("update_account_calls should have failed".into()); } Ok(()) } /// Verify a proof using a Solidity verifier contract #[cfg(not(target_arch = "wasm32"))] pub async fn verify_proof_via_solidity( proof: Snark<Fr, G1Affine>, addr: ethers::types::Address, addr_vk: Option<H160>, rpc_url: Option<&str>, ) -> Result<bool, Box<dyn Error>> { let flattened_instances = proof.instances.into_iter().flatten(); let encoded = encode_calldata( addr_vk.as_ref().map(|x| x.0), &proof.proof, &flattened_instances.collect::<Vec<_>>(), ); info!("encoded: {:#?}", hex::encode(&encoded)); let (anvil, client) = setup_eth_backend(rpc_url, None).await?; let tx: TypedTransaction = TransactionRequest::default() .to(addr) .from(client.address()) .data(encoded) .into(); debug!("transaction {:#?}", tx); let result = client.call(&tx, None).await; if result.is_err() { return Err(Box::new(EvmVerificationError::SolidityExecution)); } let result = result?; info!("result: {:#?}", result.to_vec()); // decode return bytes value into uint8 let result = result.to_vec().last().ok_or("no contract output")? == &1u8; if !result { return Err(Box::new(EvmVerificationError::InvalidProof)); } let gas = client.estimate_gas(&tx, None).await?; info!("estimated verify gas cost: {:#?}", gas); // if gas is greater than 30 million warn the user that the gas cost is above ethereum's 30 million block gas limit if gas > 30_000_000.into() { warn!( "Gas cost of verify transaction is greater than 30 million block gas limit. It will fail on mainnet." ); } else if gas > 15_000_000.into() { warn!( "Gas cost of verify transaction is greater than 15 million, the target block size for ethereum" ); } drop(anvil); Ok(true) } fn count_decimal_places(num: f32) -> usize { // Convert the number to a string let s = num.to_string(); // Find the decimal point match s.find('.') { Some(index) => { // Count the number of characters after the decimal point s[index + 1..].len() } None => 0, } } /// pub async fn setup_test_contract<M: 'static + Middleware>( client: Arc<M>, data: &[Vec<FileSourceInner>], ) -> Result<(ContractInstance<Arc<M>, M>, Vec<u8>), Box<dyn Error>> { // save the abi to a tmp file let mut sol_path = std::env::temp_dir(); sol_path.push("testreads.sol"); std::fs::write(&sol_path, TESTREADS_SOL)?; // Compile the contract let (abi, bytecode, runtime_bytecode) = get_contract_artifacts(sol_path, "TestReads", 0)?; let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?; let mut decimals = vec![]; let mut scaled_by_decimals_data = vec![]; for input in &data[0] { if input.is_float() { let input = input.to_float() as f32; let decimal_places = count_decimal_places(input) as u8; let scaled_by_decimals = input * f32::powf(10., decimal_places.into()); scaled_by_decimals_data.push(I256::from(scaled_by_decimals as i128)); decimals.push(decimal_places); } else if input.is_field() { let input = input.to_field(0); let hex_str_fr = format!("{:?}", input); scaled_by_decimals_data.push(I256::from_raw(U256::from_str_radix(&hex_str_fr, 16)?)); decimals.push(0); } } let contract = factory.deploy(scaled_by_decimals_data)?.send().await?; Ok((contract, decimals)) } /// Verify a proof using a Solidity DataAttestation contract. /// Used for testing purposes. #[cfg(not(target_arch = "wasm32"))] pub async fn verify_proof_with_data_attestation( proof: Snark<Fr, G1Affine>, addr_verifier: ethers::types::Address, addr_da: ethers::types::Address, addr_vk: Option<H160>, rpc_url: Option<&str>, ) -> Result<bool, Box<dyn Error>> { use ethers::abi::{Function, Param, ParamType, StateMutability, Token}; let mut public_inputs: Vec<U256> = vec![]; let flattened_instances = proof.instances.into_iter().flatten(); for val in flattened_instances.clone() { let bytes = val.to_repr(); let u = U256::from_little_endian(bytes.as_slice()); public_inputs.push(u); } let encoded_verifier = encode_calldata( addr_vk.as_ref().map(|x| x.0), &proof.proof, &flattened_instances.collect::<Vec<_>>(), ); info!("encoded: {:#?}", hex::encode(&encoded_verifier)); info!("public_inputs: {:#?}", public_inputs); info!( "proof: {:#?}", ethers::types::Bytes::from(proof.proof.to_vec()) ); #[allow(deprecated)] let func = Function { name: "verifyWithDataAttestation".to_owned(), inputs: vec![ Param { name: "verifier".to_owned(), kind: ParamType::Address, internal_type: None, }, Param { name: "encoded".to_owned(), kind: ParamType::Bytes, internal_type: None, }, ], outputs: vec![Param { name: "success".to_owned(), kind: ParamType::Bool, internal_type: None, }], constant: None, state_mutability: StateMutability::View, }; let encoded = func.encode_input(&[ Token::Address(addr_verifier), Token::Bytes(encoded_verifier), ])?; info!("encoded: {:#?}", hex::encode(&encoded)); let (anvil, client) = setup_eth_backend(rpc_url, None).await?; let tx: TypedTransaction = TransactionRequest::default() .to(addr_da) .from(client.address()) .data(encoded) .into(); debug!("transaction {:#?}", tx); info!( "estimated verify gas cost: {:#?}", client.estimate_gas(&tx, None).await? ); let result = client.call(&tx, None).await; if result.is_err() { return Err(Box::new(EvmVerificationError::SolidityExecution)); } let result = result?; info!("result: {:#?}", result); // decode return bytes value into uint8 let result = result.to_vec().last().ok_or("no contract output")? == &1u8; if !result { return Err(Box::new(EvmVerificationError::InvalidProof)); } drop(anvil); Ok(true) } /// get_provider returns a JSON RPC HTTP Provider pub fn get_provider(rpc_url: &str) -> Result<Provider<Http>, Box<dyn Error>> { let provider = Provider::<Http>::try_from(rpc_url)?; debug!("{:#?}", provider); Ok(provider) } /// Tests on-chain data storage by deploying a contract that stores the network input and or output /// data in its storage. It does this by converting the floating point values to integers and storing the /// the number of decimals of the floating point value on chain. pub async fn test_on_chain_data<M: 'static + Middleware>( client: Arc<M>, data: &[Vec<FileSourceInner>], ) -> Result<Vec<CallsToAccount>, Box<dyn Error>> { let (contract, decimals) = setup_test_contract(client.clone(), data).await?; let contract = TestReads::new(contract.address(), client.clone()); // Get the encoded call data for each input let mut calldata = vec![]; for (i, _) in data.iter().flatten().enumerate() { let function = contract.method::<_, I256>("arr", i as u32)?; let call = function.calldata().ok_or("could not get calldata")?; // Push (call, decimals) to the calldata vector. calldata.push((hex::encode(call), decimals[i])); } // Instantiate a new CallsToAccount struct let calls_to_account = CallsToAccount { call_data: calldata, address: hex::encode(contract.address().as_bytes()), }; info!("calls_to_account: {:#?}", calls_to_account); Ok(vec![calls_to_account]) } /// Reads on-chain inputs, returning the raw encoded data returned from making all the calls in on_chain_input_data #[cfg(not(target_arch = "wasm32"))] pub async fn read_on_chain_inputs<M: 'static + Middleware>( client: Arc<M>, address: H160, data: &Vec<CallsToAccount>, ) -> Result<(Vec<Bytes>, Vec<u8>), Box<dyn Error>> { // Iterate over all on-chain inputs let mut fetched_inputs = vec![]; let mut decimals = vec![]; for on_chain_data in data { // Construct the address let contract_address_bytes = hex::decode(on_chain_data.address.clone())?; let contract_address = H160::from_slice(&contract_address_bytes); for (call_data, decimal) in &on_chain_data.call_data { let call_data_bytes = hex::decode(call_data.clone())?; let tx: TypedTransaction = TransactionRequest::default() .to(contract_address) .from(address) .data(call_data_bytes) .into(); debug!("transaction {:#?}", tx); let result = client.call(&tx, None).await?; debug!("return data {:#?}", result); fetched_inputs.push(result); decimals.push(*decimal); } } Ok((fetched_inputs, decimals)) } /// #[cfg(not(target_arch = "wasm32"))] pub async fn evm_quantize<M: 'static + Middleware>( client: Arc<M>, scales: Vec<crate::Scale>, data: &(Vec<ethers::types::Bytes>, Vec<u8>), ) -> Result<Vec<Fr>, Box<dyn Error>> { // save the sol to a tmp file let mut sol_path = std::env::temp_dir(); sol_path.push("quantizedata.sol"); std::fs::write(&sol_path, QUANTIZE_DATA_SOL)?; let (abi, bytecode, runtime_bytecode) = get_contract_artifacts(sol_path, "QuantizeData", 0)?; let factory = get_sol_contract_factory(abi, bytecode, runtime_bytecode, client.clone())?; let contract = factory.deploy(())?.send().await?; let contract = QuantizeData::new(contract.address(), client.clone()); let fetched_inputs = data.0.clone(); let decimals = data.1.clone(); let fetched_inputs = fetched_inputs .iter() .map(|x| Result::<_, std::convert::Infallible>::Ok(ethers::types::Bytes::from(x.to_vec()))) .collect::<Result<Vec<Bytes>, _>>()?; let decimals = decimals .iter() .map(|x| U256::from_dec_str(&x.to_string())) .collect::<Result<Vec<U256>, _>>()?; let scales = scales .iter() .map(|x| U256::from_dec_str(&x.to_string())) .collect::<Result<Vec<U256>, _>>()?; info!("scales: {:#?}", scales); info!("decimals: {:#?}", decimals); info!("fetched_inputs: {:#?}", fetched_inputs); let results = contract .quantize_data(fetched_inputs, decimals, scales) .call() .await?; let felts = contract.to_field_element(results.clone()).call().await?; info!("evm quantization contract results: {:#?}", felts,); let results = felts .iter() .map(|x| PrimeField::from_str_vartime(&x.to_string()).unwrap()) .collect::<Vec<Fr>>(); info!("evm quantization results: {:#?}", results,); Ok(results.to_vec()) } /// Generates the contract factory for a solidity verifier, optionally compiling the code with optimizer runs set on the Solc compiler. fn get_sol_contract_factory<M: 'static + Middleware>( abi: Contract, bytecode: Bytes, runtime_bytecode: Bytes, client: Arc<M>, ) -> Result<ContractFactory<M>, Box<dyn Error>> { const MAX_RUNTIME_BYTECODE_SIZE: usize = 24577; let size = runtime_bytecode.len(); debug!("runtime bytecode size: {:#?}", size); if size > MAX_RUNTIME_BYTECODE_SIZE { // `_runtime_bytecode` exceeds the limit warn!( "Solidity runtime bytecode size is: {:#?}, which exceeds 24577 bytes spurious dragon limit. Contract will fail to deploy on any chain with EIP 140 enabled", size ); } Ok(ContractFactory::new(abi, bytecode, client)) } /// Compiles a solidity verifier contract and returns the abi, bytecode, and runtime bytecode #[cfg(not(target_arch = "wasm32"))] pub fn get_contract_artifacts( sol_code_path: PathBuf, contract_name: &str, runs: usize, ) -> Result<(Contract, Bytes, Bytes), Box<dyn Error>> { if !sol_code_path.exists() { return Err("sol_code_path does not exist".into()); } // Create the compiler input, enabling the optimizer and setting the optimzer runs. let input: CompilerInput = if runs > 0 { let mut i = CompilerInput::new(sol_code_path)?[0] .clone() .optimizer(runs); i.settings.optimizer.enable(); i } else { CompilerInput::new(sol_code_path)?[0].clone() }; let compiled = Solc::default().compile(&input)?; let (abi, bytecode, runtime_bytecode) = match compiled.find(contract_name) { Some(c) => c.into_parts_or_default(), None => { return Err("could not find contract".into()); } }; Ok((abi, bytecode, runtime_bytecode)) } /// Sets the constants stored in the da verifier pub fn fix_da_sol( input_data: Option<Vec<CallsToAccount>>, output_data: Option<Vec<CallsToAccount>>, ) -> Result<String, Box<dyn Error>> { let mut accounts_len = 0; let mut contract = ATTESTDATA_SOL.to_string(); let load_instances = LOADINSTANCES_SOL.to_string(); // replace the import statement with the load_instances contract, not including the // `SPDX-License-Identifier: MIT pragma solidity ^0.8.20;` at the top of the file contract = contract.replace( "import './LoadInstances.sol';", &load_instances[load_instances .find("contract") .ok_or("could not get load-instances contract")?..], ); // fill in the quantization params and total calls // as constants to the contract to save on gas if let Some(input_data) = input_data { let input_calls: usize = input_data.iter().map(|v| v.call_data.len()).sum(); accounts_len = input_data.len(); contract = contract.replace( "uint256 constant INPUT_CALLS = 0;", &format!("uint256 constant INPUT_CALLS = {};", input_calls), ); } if let Some(output_data) = output_data { let output_calls: usize = output_data.iter().map(|v| v.call_data.len()).sum(); accounts_len += output_data.len(); contract = contract.replace( "uint256 constant OUTPUT_CALLS = 0;", &format!("uint256 constant OUTPUT_CALLS = {};", output_calls), ); } contract = contract.replace("AccountCall[]", &format!("AccountCall[{}]", accounts_len)); Ok(contract) }
https://github.com/zkonduit/ezkl
src/execute.rs
use crate::circuit::CheckMode; #[cfg(not(target_arch = "wasm32"))] use crate::commands::CalibrationTarget; use crate::commands::Commands; #[cfg(not(target_arch = "wasm32"))] use crate::commands::H160Flag; #[cfg(not(target_arch = "wasm32"))] use crate::eth::{deploy_contract_via_solidity, deploy_da_verifier_via_solidity}; #[cfg(not(target_arch = "wasm32"))] #[allow(unused_imports)] use crate::eth::{fix_da_sol, get_contract_artifacts, verify_proof_via_solidity}; use crate::graph::input::GraphData; use crate::graph::{GraphCircuit, GraphSettings, GraphWitness, Model}; #[cfg(not(target_arch = "wasm32"))] use crate::graph::{TestDataSource, TestSources}; use crate::pfsys::evm::aggregation_kzg::{AggregationCircuit, PoseidonTranscript}; #[cfg(not(target_arch = "wasm32"))] use crate::pfsys::{ create_keys, load_pk, load_vk, save_params, save_pk, Snark, StrategyType, TranscriptType, }; use crate::pfsys::{ create_proof_circuit, swap_proof_commitments_polycommit, verify_proof_circuit, ProofSplitCommit, }; use crate::pfsys::{save_vk, srs::*}; use crate::tensor::TensorError; use crate::{Commitments, RunArgs}; #[cfg(not(target_arch = "wasm32"))] use colored::Colorize; #[cfg(unix)] use gag::Gag; use halo2_proofs::dev::VerifyFailure; use halo2_proofs::plonk::{self, Circuit}; use halo2_proofs::poly::commitment::{CommitmentScheme, Params}; use halo2_proofs::poly::commitment::{ParamsProver, Verifier}; use halo2_proofs::poly::ipa::commitment::{IPACommitmentScheme, ParamsIPA}; use halo2_proofs::poly::ipa::multiopen::{ProverIPA, VerifierIPA}; use halo2_proofs::poly::ipa::strategy::AccumulatorStrategy as IPAAccumulatorStrategy; use halo2_proofs::poly::ipa::strategy::SingleStrategy as IPASingleStrategy; use halo2_proofs::poly::kzg::commitment::KZGCommitmentScheme; use halo2_proofs::poly::kzg::multiopen::{ProverSHPLONK, VerifierSHPLONK}; use halo2_proofs::poly::kzg::strategy::AccumulatorStrategy as KZGAccumulatorStrategy; use halo2_proofs::poly::kzg::{ commitment::ParamsKZG, strategy::SingleStrategy as KZGSingleStrategy, }; use halo2_proofs::poly::VerificationStrategy; use halo2_proofs::transcript::{EncodedChallenge, TranscriptReadBuffer}; #[cfg(not(target_arch = "wasm32"))] use halo2_solidity_verifier; use halo2curves::bn256::{Bn256, Fr, G1Affine}; use halo2curves::ff::{FromUniformBytes, WithSmallOrderMulGroup}; use halo2curves::serde::SerdeObject; #[cfg(not(target_arch = "wasm32"))] use indicatif::{ProgressBar, ProgressStyle}; use instant::Instant; #[cfg(not(target_arch = "wasm32"))] use itertools::Itertools; #[cfg(not(target_arch = "wasm32"))] use log::debug; use log::{info, trace, warn}; use serde::de::DeserializeOwned; use serde::Serialize; use snark_verifier::loader::native::NativeLoader; use snark_verifier::system::halo2::compile; use snark_verifier::system::halo2::transcript::evm::EvmTranscript; use snark_verifier::system::halo2::Config; use std::error::Error; use std::fs::File; #[cfg(not(target_arch = "wasm32"))] use std::io::{Cursor, Write}; use std::path::Path; use std::path::PathBuf; #[cfg(not(target_arch = "wasm32"))] use std::process::Command; #[cfg(not(target_arch = "wasm32"))] use std::sync::OnceLock; #[cfg(not(target_arch = "wasm32"))] use crate::EZKL_BUF_CAPACITY; #[cfg(not(target_arch = "wasm32"))] use std::io::BufWriter; use std::time::Duration; use tabled::Tabled; use thiserror::Error; #[cfg(not(target_arch = "wasm32"))] static _SOLC_REQUIREMENT: OnceLock<bool> = OnceLock::new(); #[cfg(not(target_arch = "wasm32"))] fn check_solc_requirement() { info!("checking solc installation.."); _SOLC_REQUIREMENT.get_or_init(|| match Command::new("solc").arg("--version").output() { Ok(output) => { debug!("solc output: {:#?}", output); debug!("solc output success: {:#?}", output.status.success()); if !output.status.success() { log::error!( "`solc` check failed: {}", String::from_utf8_lossy(&output.stderr) ); return false; } debug!("solc check passed, proceeding"); true } Err(_) => { log::error!("`solc` check failed: solc not found"); false } }); } use lazy_static::lazy_static; lazy_static! { #[derive(Debug)] /// The path to the ezkl related data. pub static ref EZKL_REPO_PATH: String = std::env::var("EZKL_REPO_PATH").unwrap_or_else(|_| // $HOME/.ezkl/ format!("{}/.ezkl", std::env::var("HOME").unwrap()) ); /// The path to the ezkl related data (SRS) pub static ref EZKL_SRS_REPO_PATH: String = format!("{}/srs", *EZKL_REPO_PATH); } /// A wrapper for tensor related errors. #[derive(Debug, Error)] pub enum ExecutionError { /// Shape mismatch in a operation #[error("verification failed")] VerifyError(Vec<VerifyFailure>), } lazy_static::lazy_static! { // read from env EZKL_WORKING_DIR var or default to current dir static ref WORKING_DIR: PathBuf = { let wd = std::env::var("EZKL_WORKING_DIR").unwrap_or_else(|_| ".".to_string()); PathBuf::from(wd) }; } /// Run an ezkl command with given args pub async fn run(command: Commands) -> Result<String, Box<dyn Error>> { // set working dir std::env::set_current_dir(WORKING_DIR.as_path())?; match command { #[cfg(feature = "empty-cmd")] Commands::Empty => Ok(String::new()), Commands::GenSrs { srs_path, logrows, commitment, } => gen_srs_cmd(srs_path, logrows as u32, commitment), #[cfg(not(target_arch = "wasm32"))] Commands::GetSrs { srs_path, settings_path, logrows, commitment, } => get_srs_cmd(srs_path, settings_path, logrows, commitment).await, Commands::Table { model, args } => table(model, args), Commands::GenSettings { model, settings_path, args, } => gen_circuit_settings(model, settings_path, args), #[cfg(not(target_arch = "wasm32"))] Commands::CalibrateSettings { model, settings_path, data, target, lookup_safety_margin, scales, scale_rebase_multiplier, max_logrows, only_range_check_rebase, } => calibrate( model, data, settings_path, target, lookup_safety_margin, scales, scale_rebase_multiplier, only_range_check_rebase, max_logrows, ) .map(|e| serde_json::to_string(&e).unwrap()), Commands::GenWitness { data, compiled_circuit, output, vk_path, srs_path, } => gen_witness(compiled_circuit, data, Some(output), vk_path, srs_path) .map(|e| serde_json::to_string(&e).unwrap()), Commands::Mock { model, witness } => mock(model, witness), #[cfg(not(target_arch = "wasm32"))] Commands::CreateEvmVerifier { vk_path, srs_path, settings_path, sol_code_path, abi_path, render_vk_seperately, } => create_evm_verifier( vk_path, srs_path, settings_path, sol_code_path, abi_path, render_vk_seperately, ), Commands::CreateEvmVK { vk_path, srs_path, settings_path, sol_code_path, abi_path, } => create_evm_vk(vk_path, srs_path, settings_path, sol_code_path, abi_path), #[cfg(not(target_arch = "wasm32"))] Commands::CreateEvmDataAttestation { settings_path, sol_code_path, abi_path, data, } => create_evm_data_attestation(settings_path, sol_code_path, abi_path, data), #[cfg(not(target_arch = "wasm32"))] Commands::CreateEvmVerifierAggr { vk_path, srs_path, sol_code_path, abi_path, aggregation_settings, logrows, render_vk_seperately, } => create_evm_aggregate_verifier( vk_path, srs_path, sol_code_path, abi_path, aggregation_settings, logrows, render_vk_seperately, ), Commands::CompileCircuit { model, compiled_circuit, settings_path, } => compile_circuit(model, compiled_circuit, settings_path), Commands::Setup { compiled_circuit, srs_path, vk_path, pk_path, witness, disable_selector_compression, } => setup( compiled_circuit, srs_path, vk_path, pk_path, witness, disable_selector_compression, ), #[cfg(not(target_arch = "wasm32"))] Commands::SetupTestEvmData { data, compiled_circuit, test_data, rpc_url, input_source, output_source, } => { setup_test_evm_witness( data, compiled_circuit, test_data, rpc_url, input_source, output_source, ) .await } #[cfg(not(target_arch = "wasm32"))] Commands::TestUpdateAccountCalls { addr, data, rpc_url, } => test_update_account_calls(addr, data, rpc_url).await, #[cfg(not(target_arch = "wasm32"))] Commands::SwapProofCommitments { proof_path, witness_path, } => swap_proof_commitments_cmd(proof_path, witness_path) .map(|e| serde_json::to_string(&e).unwrap()), #[cfg(not(target_arch = "wasm32"))] Commands::Prove { witness, compiled_circuit, pk_path, proof_path, srs_path, proof_type, check_mode, } => prove( witness, compiled_circuit, pk_path, Some(proof_path), srs_path, proof_type, check_mode, ) .map(|e| serde_json::to_string(&e).unwrap()), Commands::MockAggregate { aggregation_snarks, logrows, split_proofs, } => mock_aggregate(aggregation_snarks, logrows, split_proofs), Commands::SetupAggregate { sample_snarks, vk_path, pk_path, srs_path, logrows, split_proofs, disable_selector_compression, commitment, } => setup_aggregate( sample_snarks, vk_path, pk_path, srs_path, logrows, split_proofs, disable_selector_compression, commitment.into(), ), Commands::Aggregate { proof_path, aggregation_snarks, pk_path, srs_path, transcript, logrows, check_mode, split_proofs, commitment, } => aggregate( proof_path, aggregation_snarks, pk_path, srs_path, transcript, logrows, check_mode, split_proofs, commitment.into(), ) .map(|e| serde_json::to_string(&e).unwrap()), Commands::Verify { proof_path, settings_path, vk_path, srs_path, reduced_srs, } => verify(proof_path, settings_path, vk_path, srs_path, reduced_srs) .map(|e| serde_json::to_string(&e).unwrap()), Commands::VerifyAggr { proof_path, vk_path, srs_path, reduced_srs, logrows, commitment, } => verify_aggr( proof_path, vk_path, srs_path, logrows, reduced_srs, commitment.into(), ) .map(|e| serde_json::to_string(&e).unwrap()), #[cfg(not(target_arch = "wasm32"))] Commands::DeployEvmVerifier { sol_code_path, rpc_url, addr_path, optimizer_runs, private_key, } => { deploy_evm( sol_code_path, rpc_url, addr_path, optimizer_runs, private_key, "Halo2Verifier", ) .await } #[cfg(not(target_arch = "wasm32"))] Commands::DeployEvmVK { sol_code_path, rpc_url, addr_path, optimizer_runs, private_key, } => { deploy_evm( sol_code_path, rpc_url, addr_path, optimizer_runs, private_key, "Halo2VerifyingKey", ) .await } #[cfg(not(target_arch = "wasm32"))] Commands::DeployEvmDataAttestation { data, settings_path, sol_code_path, rpc_url, addr_path, optimizer_runs, private_key, } => { deploy_da_evm( data, settings_path, sol_code_path, rpc_url, addr_path, optimizer_runs, private_key, ) .await } #[cfg(not(target_arch = "wasm32"))] Commands::VerifyEvm { proof_path, addr_verifier, rpc_url, addr_da, addr_vk, } => verify_evm(proof_path, addr_verifier, rpc_url, addr_da, addr_vk).await, } } /// Get the srs path pub fn get_srs_path(logrows: u32, srs_path: Option<PathBuf>, commitment: Commitments) -> PathBuf { if let Some(srs_path) = srs_path { srs_path } else { if !Path::new(&*EZKL_SRS_REPO_PATH).exists() { std::fs::create_dir_all(&*EZKL_SRS_REPO_PATH).unwrap(); } match commitment { Commitments::KZG => Path::new(&*EZKL_SRS_REPO_PATH).join(format!("kzg{}.srs", logrows)), Commitments::IPA => Path::new(&*EZKL_SRS_REPO_PATH).join(format!("ipa{}.srs", logrows)), } } } fn srs_exists_check(logrows: u32, srs_path: Option<PathBuf>, commitment: Commitments) -> bool { Path::new(&get_srs_path(logrows, srs_path, commitment)).exists() } pub(crate) fn gen_srs_cmd( srs_path: PathBuf, logrows: u32, commitment: Commitments, ) -> Result<String, Box<dyn Error>> { match commitment { Commitments::KZG => { let params = gen_srs::<KZGCommitmentScheme<Bn256>>(logrows); save_params::<KZGCommitmentScheme<Bn256>>(&srs_path, &params)?; } Commitments::IPA => { let params = gen_srs::<IPACommitmentScheme<G1Affine>>(logrows); save_params::<IPACommitmentScheme<G1Affine>>(&srs_path, &params)?; } } Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] async fn fetch_srs(uri: &str) -> Result<Vec<u8>, Box<dyn Error>> { let pb = { let pb = init_spinner(); pb.set_message("Downloading SRS (this may take a while) ..."); pb }; let client = reqwest::Client::new(); // wasm doesn't require it to be mutable #[allow(unused_mut)] let mut resp = client.get(uri).body(vec![]).send().await?; let mut buf = vec![]; while let Some(chunk) = resp.chunk().await? { buf.extend(chunk.to_vec()); } pb.finish_with_message("SRS downloaded."); Ok(std::mem::take(&mut buf)) } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn get_file_hash(path: &PathBuf) -> Result<String, Box<dyn Error>> { use std::io::Read; let file = std::fs::File::open(path)?; let mut reader = std::io::BufReader::new(file); let mut buffer = vec![]; let bytes_read = reader.read_to_end(&mut buffer)?; info!( "read {} bytes from file (vector of len = {})", bytes_read, buffer.len() ); let hash = sha256::digest(buffer); info!("file hash: {}", hash); Ok(hash) } #[cfg(not(target_arch = "wasm32"))] fn check_srs_hash( logrows: u32, srs_path: Option<PathBuf>, commitment: Commitments, ) -> Result<String, Box<dyn Error>> { let path = get_srs_path(logrows, srs_path, commitment); let hash = get_file_hash(&path)?; let predefined_hash = match crate::srs_sha::PUBLIC_SRS_SHA256_HASHES.get(&logrows) { Some(h) => h, None => return Err(format!("SRS (k={}) hash not found in public set", logrows).into()), }; if hash != *predefined_hash { // delete file warn!("removing SRS file at {}", path.display()); std::fs::remove_file(path)?; return Err( "SRS hash does not match the expected hash. Remote SRS may have been tampered with." .into(), ); } Ok(hash) } #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn get_srs_cmd( srs_path: Option<PathBuf>, settings_path: Option<PathBuf>, logrows: Option<u32>, commitment: Option<Commitments>, ) -> Result<String, Box<dyn Error>> { // logrows overrides settings let err_string = "You will need to provide a valid settings file to use the settings option. You should run gen-settings to generate a settings file (and calibrate-settings to pick optimal logrows)."; let k = if let Some(k) = logrows { k } else if let Some(settings_p) = &settings_path { if settings_p.exists() { let settings = GraphSettings::load(settings_p)?; settings.run_args.logrows } else { return Err(err_string.into()); } } else { return Err(err_string.into()); }; let commitment = if let Some(c) = commitment { c } else if let Some(settings_p) = settings_path { if settings_p.exists() { let settings = GraphSettings::load(&settings_p)?; settings.run_args.commitment.into() } else { return Err(err_string.into()); } } else { return Err(err_string.into()); }; if !srs_exists_check(k, srs_path.clone(), commitment) { if matches!(commitment, Commitments::KZG) { info!("SRS does not exist, downloading..."); let srs_uri = format!("{}{}", PUBLIC_SRS_URL, k); let mut reader = Cursor::new(fetch_srs(&srs_uri).await?); // check the SRS #[cfg(not(target_arch = "wasm32"))] let pb = init_spinner(); #[cfg(not(target_arch = "wasm32"))] pb.set_message("Validating SRS (this may take a while) ..."); let params = ParamsKZG::<Bn256>::read(&mut reader)?; #[cfg(not(target_arch = "wasm32"))] pb.finish_with_message("SRS validated."); info!("Saving SRS to disk..."); let mut file = std::fs::File::create(get_srs_path(k, srs_path.clone(), commitment))?; let mut buffer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, &mut file); params.write(&mut buffer)?; info!("Saved SRS to disk."); info!("SRS downloaded"); } else { let path = get_srs_path(k, srs_path.clone(), commitment); gen_srs_cmd(path, k, commitment)?; } } else { info!("SRS already exists at that path"); }; // check the hash if matches!(commitment, Commitments::KZG) { check_srs_hash(k, srs_path.clone(), commitment)?; } Ok(String::new()) } pub(crate) fn table(model: PathBuf, run_args: RunArgs) -> Result<String, Box<dyn Error>> { let model = Model::from_run_args(&run_args, &model)?; info!("\n {}", model.table_nodes()); Ok(String::new()) } pub(crate) fn gen_witness( compiled_circuit_path: PathBuf, data: PathBuf, output: Option<PathBuf>, vk_path: Option<PathBuf>, srs_path: Option<PathBuf>, ) -> Result<GraphWitness, Box<dyn Error>> { // these aren't real values so the sanity checks are mostly meaningless let mut circuit = GraphCircuit::load(compiled_circuit_path)?; let data = GraphData::from_path(data)?; let settings = circuit.settings().clone(); let vk = if let Some(vk) = vk_path { Some(load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>( vk, settings.clone(), )?) } else { None }; #[cfg(not(target_arch = "wasm32"))] let mut input = circuit.load_graph_input(&data)?; #[cfg(target_arch = "wasm32")] let mut input = circuit.load_graph_input(&data)?; // if any of the settings have kzg visibility then we need to load the srs let commitment: Commitments = settings.run_args.commitment.into(); let start_time = Instant::now(); let witness = if settings.module_requires_polycommit() { if get_srs_path(settings.run_args.logrows, srs_path.clone(), commitment).exists() { match Commitments::from(settings.run_args.commitment) { Commitments::KZG => { let srs: ParamsKZG<Bn256> = load_params_prover::<KZGCommitmentScheme<Bn256>>( srs_path.clone(), settings.run_args.logrows, commitment, )?; circuit.forward::<KZGCommitmentScheme<_>>( &mut input, vk.as_ref(), Some(&srs), true, )? } Commitments::IPA => { let srs: ParamsIPA<G1Affine> = load_params_prover::<IPACommitmentScheme<G1Affine>>( srs_path.clone(), settings.run_args.logrows, commitment, )?; circuit.forward::<IPACommitmentScheme<_>>( &mut input, vk.as_ref(), Some(&srs), true, )? } } } else { warn!("SRS for poly commit does not exist (will be ignored)"); circuit.forward::<KZGCommitmentScheme<Bn256>>(&mut input, vk.as_ref(), None, true)? } } else { circuit.forward::<KZGCommitmentScheme<Bn256>>(&mut input, vk.as_ref(), None, true)? }; // print each variable tuple (symbol, value) as symbol=value trace!( "witness generation {:?} took {:?}", circuit .settings() .run_args .variables .iter() .map(|v| { format!("{}={}", v.0, v.1) }) .collect::<Vec<_>>(), start_time.elapsed() ); if let Some(output_path) = output { witness.save(output_path)?; } // print the witness in debug debug!("witness: \n {}", witness.as_json()?.to_colored_json_auto()?); Ok(witness) } /// Generate a circuit settings file pub(crate) fn gen_circuit_settings( model_path: PathBuf, params_output: PathBuf, run_args: RunArgs, ) -> Result<String, Box<dyn Error>> { let circuit = GraphCircuit::from_run_args(&run_args, &model_path)?; let params = circuit.settings(); params.save(&params_output)?; Ok(String::new()) } // not for wasm targets #[cfg(not(target_arch = "wasm32"))] pub(crate) fn init_spinner() -> ProgressBar { let pb = indicatif::ProgressBar::new_spinner(); pb.set_draw_target(indicatif::ProgressDrawTarget::stdout()); pb.enable_steady_tick(Duration::from_millis(200)); pb.set_style( ProgressStyle::with_template("[{elapsed_precise}] {spinner:.blue} {msg}") .unwrap() .tick_strings(&[ "------ - ✨ ", "------ - ⏳ ", "------ - 🌎 ", "------ - 🔎 ", "------ - 🥹 ", "------ - 🫠 ", "------ - 👾 ", ]), ); pb } // not for wasm targets #[cfg(not(target_arch = "wasm32"))] pub(crate) fn init_bar(len: u64) -> ProgressBar { let pb = ProgressBar::new(len); pb.set_draw_target(indicatif::ProgressDrawTarget::stdout()); pb.enable_steady_tick(Duration::from_millis(200)); let sty = ProgressStyle::with_template( "[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}", ) .unwrap() .progress_chars("##-"); pb.set_style(sty); pb } #[cfg(not(target_arch = "wasm32"))] use colored_json::ToColoredJson; #[derive(Debug, Clone, Tabled)] /// Accuracy tearsheet pub struct AccuracyResults { mean_error: f32, median_error: f32, max_error: f32, min_error: f32, mean_abs_error: f32, median_abs_error: f32, max_abs_error: f32, min_abs_error: f32, mean_squared_error: f32, mean_percent_error: f32, mean_abs_percent_error: f32, } impl AccuracyResults { /// Create a new accuracy results struct pub fn new( mut original_preds: Vec<crate::tensor::Tensor<f32>>, mut calibrated_preds: Vec<crate::tensor::Tensor<f32>>, ) -> Result<Self, Box<dyn Error>> { let mut errors = vec![]; let mut abs_errors = vec![]; let mut squared_errors = vec![]; let mut percentage_errors = vec![]; let mut abs_percentage_errors = vec![]; for (original, calibrated) in original_preds.iter_mut().zip(calibrated_preds.iter_mut()) { original.flatten(); calibrated.flatten(); let error = (original.clone() - calibrated.clone())?; let abs_error = error.map(|x| x.abs()); let squared_error = error.map(|x| x.powi(2)); let percentage_error = error.enum_map(|i, x| { // if everything is 0 then we can't divide by 0 so we just return 0 let res = if original[i] == 0.0 && x == 0.0 { 0.0 } else { x / original[i] }; Ok::<f32, TensorError>(res) })?; let abs_percentage_error = percentage_error.map(|x| x.abs()); errors.extend(error); abs_errors.extend(abs_error); squared_errors.extend(squared_error); percentage_errors.extend(percentage_error); abs_percentage_errors.extend(abs_percentage_error); } let mean_percent_error = percentage_errors.iter().sum::<f32>() / percentage_errors.len() as f32; let mean_abs_percent_error = abs_percentage_errors.iter().sum::<f32>() / abs_percentage_errors.len() as f32; let mean_error = errors.iter().sum::<f32>() / errors.len() as f32; let median_error = errors[errors.len() / 2]; let max_error = *errors .iter() .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let min_error = *errors .iter() .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let mean_abs_error = abs_errors.iter().sum::<f32>() / abs_errors.len() as f32; let median_abs_error = abs_errors[abs_errors.len() / 2]; let max_abs_error = *abs_errors .iter() .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let min_abs_error = *abs_errors .iter() .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)) .unwrap(); let mean_squared_error = squared_errors.iter().sum::<f32>() / squared_errors.len() as f32; Ok(Self { mean_error, median_error, max_error, min_error, mean_abs_error, median_abs_error, max_abs_error, min_abs_error, mean_squared_error, mean_percent_error, mean_abs_percent_error, }) } } /// Calibrate the circuit parameters to a given a dataset #[cfg(not(target_arch = "wasm32"))] #[allow(trivial_casts)] #[allow(clippy::too_many_arguments)] pub(crate) fn calibrate( model_path: PathBuf, data: PathBuf, settings_path: PathBuf, target: CalibrationTarget, lookup_safety_margin: i128, scales: Option<Vec<crate::Scale>>, scale_rebase_multiplier: Vec<u32>, only_range_check_rebase: bool, max_logrows: Option<u32>, ) -> Result<GraphSettings, Box<dyn Error>> { use log::error; use std::collections::HashMap; use tabled::Table; let data = GraphData::from_path(data)?; // load the pre-generated settings let settings = GraphSettings::load(&settings_path)?; // now retrieve the run args // we load the model to get the input and output shapes let model = Model::from_run_args(&settings.run_args, &model_path)?; let chunks = data.split_into_batches(model.graph.input_shapes()?)?; info!("num calibration batches: {}", chunks.len()); debug!("running onnx predictions..."); let original_predictions = Model::run_onnx_predictions( &settings.run_args, &model_path, &chunks, model.graph.input_shapes()?, )?; let range = if let Some(scales) = scales { scales } else { (11..14).collect::<Vec<crate::Scale>>() }; let div_rebasing = if only_range_check_rebase { vec![false] } else { vec![true, false] }; let mut found_params: Vec<GraphSettings> = vec![]; // 2 x 2 grid let range_grid = range .iter() .cartesian_product(range.iter()) .map(|(a, b)| (*a, *b)) .collect::<Vec<(crate::Scale, crate::Scale)>>(); // remove all entries where input_scale > param_scale let mut range_grid = range_grid .into_iter() .filter(|(a, b)| a <= b) .collect::<Vec<(crate::Scale, crate::Scale)>>(); // if all integers let all_scale_0 = model .graph .get_input_types()? .iter() .all(|t| t.is_integer()); if all_scale_0 { // set all a values to 0 then dedup range_grid = range_grid .iter() .map(|(_, b)| (0, *b)) .sorted() .dedup() .collect::<Vec<(crate::Scale, crate::Scale)>>(); } let range_grid = range_grid .iter() .cartesian_product(scale_rebase_multiplier.iter()) .map(|(a, b)| (*a, *b)) .collect::<Vec<((crate::Scale, crate::Scale), u32)>>(); let range_grid = range_grid .iter() .cartesian_product(div_rebasing.iter()) .map(|(a, b)| (*a, *b)) .collect::<Vec<(((crate::Scale, crate::Scale), u32), bool)>>(); let mut forward_pass_res = HashMap::new(); let pb = init_bar(range_grid.len() as u64); pb.set_message("calibrating..."); let mut num_failed = 0; let mut num_passed = 0; for (((input_scale, param_scale), scale_rebase_multiplier), div_rebasing) in range_grid { pb.set_message(format!( "i-scale: {}, p-scale: {}, rebase-(x): {}, div-rebase: {}, fail: {}, pass: {}", input_scale.to_string().blue(), param_scale.to_string().blue(), scale_rebase_multiplier.to_string().blue(), div_rebasing.to_string().yellow(), num_failed.to_string().red(), num_passed.to_string().green() )); let key = ( input_scale, param_scale, scale_rebase_multiplier, div_rebasing, ); forward_pass_res.insert(key, vec![]); let local_run_args = RunArgs { input_scale, param_scale, scale_rebase_multiplier, div_rebasing, ..settings.run_args.clone() }; // if unix get a gag #[cfg(unix)] let _r = match Gag::stdout() { Ok(g) => Some(g), _ => None, }; #[cfg(unix)] let _g = match Gag::stderr() { Ok(g) => Some(g), _ => None, }; let mut circuit = match GraphCircuit::from_run_args(&local_run_args, &model_path) { Ok(c) => c, Err(e) => { error!("circuit creation from run args failed: {:?}", e); pb.inc(1); num_failed += 1; continue; } }; let forward_res = chunks .iter() .map(|chunk| { let chunk = chunk.clone(); let data = circuit .load_graph_from_file_exclusively(&chunk) .map_err(|e| format!("failed to load circuit inputs: {}", e))?; let forward_res = circuit .forward::<KZGCommitmentScheme<Bn256>>(&mut data.clone(), None, None, true) .map_err(|e| format!("failed to forward: {}", e))?; // push result to the hashmap forward_pass_res .get_mut(&key) .ok_or("key not found")? .push(forward_res); Ok(()) as Result<(), String> }) .collect::<Result<Vec<()>, String>>(); match forward_res { Ok(_) => (), // typically errors will be due to the circuit overflowing the i128 limit Err(e) => { error!("forward pass failed: {:?}", e); pb.inc(1); num_failed += 1; continue; } } // drop the gag #[cfg(unix)] drop(_r); #[cfg(unix)] drop(_g); let result = forward_pass_res.get(&key).ok_or("key not found")?; let min_lookup_range = result .iter() .map(|x| x.min_lookup_inputs) .min() .unwrap_or(0); let max_lookup_range = result .iter() .map(|x| x.max_lookup_inputs) .max() .unwrap_or(0); let max_range_size = result.iter().map(|x| x.max_range_size).max().unwrap_or(0); let res = circuit.calc_min_logrows( (min_lookup_range, max_lookup_range), max_range_size, max_logrows, lookup_safety_margin, ); if res.is_ok() { let new_settings = circuit.settings().clone(); let found_run_args = RunArgs { input_scale: new_settings.run_args.input_scale, param_scale: new_settings.run_args.param_scale, div_rebasing: new_settings.run_args.div_rebasing, lookup_range: new_settings.run_args.lookup_range, logrows: new_settings.run_args.logrows, scale_rebase_multiplier: new_settings.run_args.scale_rebase_multiplier, ..settings.run_args.clone() }; let found_settings = GraphSettings { run_args: found_run_args, required_lookups: new_settings.required_lookups, required_range_checks: new_settings.required_range_checks, model_output_scales: new_settings.model_output_scales, model_input_scales: new_settings.model_input_scales, num_rows: new_settings.num_rows, total_assignments: new_settings.total_assignments, total_const_size: new_settings.total_const_size, ..settings.clone() }; found_params.push(found_settings.clone()); debug!( "found settings: \n {}", found_settings.as_json()?.to_colored_json_auto()? ); num_passed += 1; } else { error!("calibration failed {}", res.err().unwrap()); num_failed += 1; } pb.inc(1); } pb.finish_with_message("Calibration Done."); if found_params.is_empty() { return Err("calibration failed, could not find any suitable parameters given the calibration dataset".into()); } debug!("Found {} sets of parameters", found_params.len()); // now find the best params according to the target let mut best_params = match target { CalibrationTarget::Resources { .. } => { let mut param_iterator = found_params.iter().sorted_by_key(|p| p.run_args.logrows); let min_logrows = param_iterator .next() .ok_or("no params found")? .run_args .logrows; // pick the ones that have the minimum logrows but also the largest scale: // this is the best tradeoff between resource usage and accuracy found_params .iter() .filter(|p| p.run_args.logrows == min_logrows) .max_by_key(|p| { ( p.run_args.input_scale, p.run_args.param_scale, // we want the largest rebase multiplier as it means we can use less constraints p.run_args.scale_rebase_multiplier, ) }) .ok_or("no params found")? .clone() } CalibrationTarget::Accuracy => { let param_iterator = found_params.iter().sorted_by_key(|p| { ( p.run_args.input_scale, p.run_args.param_scale, // we want the largest rebase multiplier as it means we can use less constraints p.run_args.scale_rebase_multiplier, ) }); let last = param_iterator.last().ok_or("no params found")?; let max_scale = ( last.run_args.input_scale, last.run_args.param_scale, last.run_args.scale_rebase_multiplier, ); // pick the ones that have the max scale but also the smallest logrows: // this is the best tradeoff between resource usage and accuracy found_params .iter() .filter(|p| { ( p.run_args.input_scale, p.run_args.param_scale, p.run_args.scale_rebase_multiplier, ) == max_scale }) .min_by_key(|p| p.run_args.logrows) .ok_or("no params found")? .clone() } }; let outputs = forward_pass_res .get(&( best_params.run_args.input_scale, best_params.run_args.param_scale, best_params.run_args.scale_rebase_multiplier, best_params.run_args.div_rebasing, )) .ok_or("no params found")? .iter() .map(|x| x.get_float_outputs(&best_params.model_output_scales)) .collect::<Vec<_>>(); let accuracy_res = AccuracyResults::new( original_predictions.into_iter().flatten().collect(), outputs.into_iter().flatten().collect(), )?; let tear_sheet_table = Table::new(vec![accuracy_res]); warn!( "\n\n <------------- Numerical Fidelity Report (input_scale: {}, param_scale: {}, scale_input_multiplier: {}) ------------->\n\n{}\n\n", best_params.run_args.input_scale, best_params.run_args.param_scale, best_params.run_args.scale_rebase_multiplier, tear_sheet_table.to_string().as_str() ); if matches!(target, CalibrationTarget::Resources { col_overflow: true }) { let lookup_log_rows = best_params.lookup_log_rows_with_blinding(); let module_log_row = best_params.module_constraint_logrows_with_blinding(); let instance_logrows = best_params.log2_total_instances_with_blinding(); let dynamic_lookup_logrows = best_params.dynamic_lookup_and_shuffle_logrows_with_blinding(); let mut reduction = std::cmp::max(lookup_log_rows, module_log_row); reduction = std::cmp::max(reduction, instance_logrows); reduction = std::cmp::max(reduction, dynamic_lookup_logrows); reduction = std::cmp::max(reduction, crate::graph::MIN_LOGROWS); info!( "logrows > bits, shrinking logrows: {} -> {}", best_params.run_args.logrows, reduction ); best_params.run_args.logrows = reduction; } best_params.save(&settings_path)?; debug!("Saved parameters."); Ok(best_params) } pub(crate) fn mock( compiled_circuit_path: PathBuf, data_path: PathBuf, ) -> Result<String, Box<dyn Error>> { // mock should catch any issues by default so we set it to safe let mut circuit = GraphCircuit::load(compiled_circuit_path)?; let data = GraphWitness::from_path(data_path)?; circuit.load_graph_witness(&data)?; let public_inputs = circuit.prepare_public_inputs(&data)?; info!("Mock proof"); let prover = halo2_proofs::dev::MockProver::run( circuit.settings().run_args.logrows, &circuit, vec![public_inputs], ) .map_err(Box::<dyn Error>::from)?; prover .verify() .map_err(|e| Box::<dyn Error>::from(ExecutionError::VerifyError(e)))?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn create_evm_verifier( vk_path: PathBuf, srs_path: Option<PathBuf>, settings_path: PathBuf, sol_code_path: PathBuf, abi_path: PathBuf, render_vk_seperately: bool, ) -> Result<String, Box<dyn Error>> { check_solc_requirement(); let settings = GraphSettings::load(&settings_path)?; let commitment: Commitments = settings.run_args.commitment.into(); let params = load_params_verifier::<KZGCommitmentScheme<Bn256>>( srs_path, settings.run_args.logrows, commitment, )?; let num_instance = settings.total_instances(); let num_instance: usize = num_instance.iter().sum::<usize>(); let vk = load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(vk_path, settings)?; trace!("params computed"); let generator = halo2_solidity_verifier::SolidityGenerator::new( &params, &vk, halo2_solidity_verifier::BatchOpenScheme::Bdfg21, num_instance, ); let verifier_solidity = if render_vk_seperately { generator.render_separately()?.0 // ignore the rendered vk for now and generate it in create_evm_vk } else { generator.render()? }; File::create(sol_code_path.clone())?.write_all(verifier_solidity.as_bytes())?; // fetch abi of the contract let (abi, _, _) = get_contract_artifacts(sol_code_path, "Halo2Verifier", 0)?; // save abi to file serde_json::to_writer(std::fs::File::create(abi_path)?, &abi)?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn create_evm_vk( vk_path: PathBuf, srs_path: Option<PathBuf>, settings_path: PathBuf, sol_code_path: PathBuf, abi_path: PathBuf, ) -> Result<String, Box<dyn Error>> { check_solc_requirement(); let settings = GraphSettings::load(&settings_path)?; let commitment: Commitments = settings.run_args.commitment.into(); let params = load_params_verifier::<KZGCommitmentScheme<Bn256>>( srs_path, settings.run_args.logrows, commitment, )?; let num_instance = settings.total_instances(); let num_instance: usize = num_instance.iter().sum::<usize>(); let vk = load_vk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(vk_path, settings)?; trace!("params computed"); let generator = halo2_solidity_verifier::SolidityGenerator::new( &params, &vk, halo2_solidity_verifier::BatchOpenScheme::Bdfg21, num_instance, ); let vk_solidity = generator.render_separately()?.1; File::create(sol_code_path.clone())?.write_all(vk_solidity.as_bytes())?; // fetch abi of the contract let (abi, _, _) = get_contract_artifacts(sol_code_path, "Halo2VerifyingKey", 0)?; // save abi to file serde_json::to_writer(std::fs::File::create(abi_path)?, &abi)?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn create_evm_data_attestation( settings_path: PathBuf, _sol_code_path: PathBuf, _abi_path: PathBuf, _input: PathBuf, ) -> Result<String, Box<dyn Error>> { #[allow(unused_imports)] use crate::graph::{DataSource, VarVisibility}; check_solc_requirement(); let settings = GraphSettings::load(&settings_path)?; let visibility = VarVisibility::from_args(&settings.run_args)?; trace!("params computed"); let data = GraphData::from_path(_input)?; let output_data = if let Some(DataSource::OnChain(source)) = data.output_data { if visibility.output.is_private() { return Err("private output data on chain is not supported on chain".into()); } let mut on_chain_output_data = vec![]; for call in source.calls { on_chain_output_data.push(call); } Some(on_chain_output_data) } else { None }; let input_data = if let DataSource::OnChain(source) = data.input_data { if visibility.input.is_private() { return Err("private input data on chain is not supported on chain".into()); } let mut on_chain_input_data = vec![]; for call in source.calls { on_chain_input_data.push(call); } Some(on_chain_input_data) } else { None }; if input_data.is_some() || output_data.is_some() { let output = fix_da_sol(input_data, output_data)?; let mut f = File::create(_sol_code_path.clone())?; let _ = f.write(output.as_bytes()); // fetch abi of the contract let (abi, _, _) = get_contract_artifacts(_sol_code_path, "DataAttestation", 0)?; // save abi to file serde_json::to_writer(std::fs::File::create(_abi_path)?, &abi)?; } else { return Err( "Neither input or output data source is on-chain. Atleast one must be on chain.".into(), ); } Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn deploy_da_evm( data: PathBuf, settings_path: PathBuf, sol_code_path: PathBuf, rpc_url: Option<String>, addr_path: PathBuf, runs: usize, private_key: Option<String>, ) -> Result<String, Box<dyn Error>> { check_solc_requirement(); let contract_address = deploy_da_verifier_via_solidity( settings_path, data, sol_code_path, rpc_url.as_deref(), runs, private_key.as_deref(), ) .await?; info!("Contract deployed at: {}", contract_address); let mut f = File::create(addr_path)?; write!(f, "{:#?}", contract_address)?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn deploy_evm( sol_code_path: PathBuf, rpc_url: Option<String>, addr_path: PathBuf, runs: usize, private_key: Option<String>, contract_name: &str, ) -> Result<String, Box<dyn Error>> { check_solc_requirement(); let contract_address = deploy_contract_via_solidity( sol_code_path, rpc_url.as_deref(), runs, private_key.as_deref(), contract_name, ) .await?; info!("Contract deployed at: {:#?}", contract_address); let mut f = File::create(addr_path)?; write!(f, "{:#?}", contract_address)?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn verify_evm( proof_path: PathBuf, addr_verifier: H160Flag, rpc_url: Option<String>, addr_da: Option<H160Flag>, addr_vk: Option<H160Flag>, ) -> Result<String, Box<dyn Error>> { use crate::eth::verify_proof_with_data_attestation; check_solc_requirement(); let proof = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?; let result = if let Some(addr_da) = addr_da { verify_proof_with_data_attestation( proof.clone(), addr_verifier.into(), addr_da.into(), addr_vk.map(|s| s.into()), rpc_url.as_deref(), ) .await? } else { verify_proof_via_solidity( proof.clone(), addr_verifier.into(), addr_vk.map(|s| s.into()), rpc_url.as_deref(), ) .await? }; info!("Solidity verification result: {}", result); if !result { return Err("Solidity verification failed".into()); } Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) fn create_evm_aggregate_verifier( vk_path: PathBuf, srs_path: Option<PathBuf>, sol_code_path: PathBuf, abi_path: PathBuf, circuit_settings: Vec<PathBuf>, logrows: u32, render_vk_seperately: bool, ) -> Result<String, Box<dyn Error>> { check_solc_requirement(); let srs_path = get_srs_path(logrows, srs_path, Commitments::KZG); let params: ParamsKZG<Bn256> = load_srs_verifier::<KZGCommitmentScheme<Bn256>>(srs_path)?; let mut settings: Vec<GraphSettings> = vec![]; for path in circuit_settings.iter() { let s = GraphSettings::load(path)?; settings.push(s); } let num_instance: usize = settings .iter() .map(|s| s.total_instances().iter().sum::<usize>()) .sum(); let num_instance = AggregationCircuit::num_instance(num_instance); assert_eq!(num_instance.len(), 1); let num_instance = num_instance[0]; let agg_vk = load_vk::<KZGCommitmentScheme<Bn256>, AggregationCircuit>(vk_path, ())?; let mut generator = halo2_solidity_verifier::SolidityGenerator::new( &params, &agg_vk, halo2_solidity_verifier::BatchOpenScheme::Bdfg21, num_instance, ); let acc_encoding = halo2_solidity_verifier::AccumulatorEncoding::new( 0, AggregationCircuit::num_limbs(), AggregationCircuit::num_bits(), ); generator = generator.set_acc_encoding(Some(acc_encoding)); let verifier_solidity = if render_vk_seperately { generator.render_separately()?.0 // ignore the rendered vk for now and generate it in create_evm_vk } else { generator.render()? }; File::create(sol_code_path.clone())?.write_all(verifier_solidity.as_bytes())?; // fetch abi of the contract let (abi, _, _) = get_contract_artifacts(sol_code_path, "Halo2Verifier", 0)?; // save abi to file serde_json::to_writer(std::fs::File::create(abi_path)?, &abi)?; Ok(String::new()) } pub(crate) fn compile_circuit( model_path: PathBuf, compiled_circuit: PathBuf, settings_path: PathBuf, ) -> Result<String, Box<dyn Error>> { let settings = GraphSettings::load(&settings_path)?; let circuit = GraphCircuit::from_settings(&settings, &model_path, CheckMode::UNSAFE)?; circuit.save(compiled_circuit)?; Ok(String::new()) } pub(crate) fn setup( compiled_circuit: PathBuf, srs_path: Option<PathBuf>, vk_path: PathBuf, pk_path: PathBuf, witness: Option<PathBuf>, disable_selector_compression: bool, ) -> Result<String, Box<dyn Error>> { // these aren't real values so the sanity checks are mostly meaningless let mut circuit = GraphCircuit::load(compiled_circuit)?; if let Some(witness) = witness { let data = GraphWitness::from_path(witness)?; circuit.load_graph_witness(&data)?; } let logrows = circuit.settings().run_args.logrows; let commitment: Commitments = circuit.settings().run_args.commitment.into(); let pk = match commitment { Commitments::KZG => { let params = load_params_prover::<KZGCommitmentScheme<Bn256>>( srs_path, logrows, Commitments::KZG, )?; create_keys::<KZGCommitmentScheme<Bn256>, GraphCircuit>( &circuit, &params, disable_selector_compression, )? } Commitments::IPA => { let params = load_params_prover::<IPACommitmentScheme<G1Affine>>( srs_path, logrows, Commitments::IPA, )?; create_keys::<IPACommitmentScheme<G1Affine>, GraphCircuit>( &circuit, &params, disable_selector_compression, )? } }; save_vk::<G1Affine>(&vk_path, pk.get_vk())?; save_pk::<G1Affine>(&pk_path, &pk)?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn setup_test_evm_witness( data_path: PathBuf, compiled_circuit_path: PathBuf, test_data: PathBuf, rpc_url: Option<String>, input_source: TestDataSource, output_source: TestDataSource, ) -> Result<String, Box<dyn Error>> { use crate::graph::TestOnChainData; info!("run this command in background to keep the instance running for testing"); let mut data = GraphData::from_path(data_path)?; let mut circuit = GraphCircuit::load(compiled_circuit_path)?; // if both input and output are from files fail if matches!(input_source, TestDataSource::File) && matches!(output_source, TestDataSource::File) { return Err("Both input and output cannot be from files".into()); } let test_on_chain_data = TestOnChainData { data: test_data.clone(), rpc: rpc_url, data_sources: TestSources { input: input_source, output: output_source, }, }; circuit .populate_on_chain_test_data(&mut data, test_on_chain_data) .await?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] use crate::pfsys::ProofType; #[cfg(not(target_arch = "wasm32"))] pub(crate) async fn test_update_account_calls( addr: H160Flag, data: PathBuf, rpc_url: Option<String>, ) -> Result<String, Box<dyn Error>> { use crate::eth::update_account_calls; check_solc_requirement(); update_account_calls(addr.into(), data, rpc_url.as_deref()).await?; Ok(String::new()) } #[cfg(not(target_arch = "wasm32"))] #[allow(clippy::too_many_arguments)] pub(crate) fn prove( data_path: PathBuf, compiled_circuit_path: PathBuf, pk_path: PathBuf, proof_path: Option<PathBuf>, srs_path: Option<PathBuf>, proof_type: ProofType, check_mode: CheckMode, ) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> { let data = GraphWitness::from_path(data_path)?; let mut circuit = GraphCircuit::load(compiled_circuit_path)?; circuit.load_graph_witness(&data)?; let pretty_public_inputs = circuit.pretty_public_inputs(&data)?; let public_inputs = circuit.prepare_public_inputs(&data)?; let circuit_settings = circuit.settings().clone(); let strategy: StrategyType = proof_type.into(); let transcript: TranscriptType = proof_type.into(); let proof_split_commits: Option<ProofSplitCommit> = data.into(); let commitment = circuit_settings.run_args.commitment.into(); let logrows = circuit_settings.run_args.logrows; // creates and verifies the proof let mut snark = match commitment { Commitments::KZG => { let pk = load_pk::<KZGCommitmentScheme<Bn256>, GraphCircuit>(pk_path, circuit.params())?; let params = load_params_prover::<KZGCommitmentScheme<Bn256>>( srs_path, logrows, Commitments::KZG, )?; match strategy { StrategyType::Single => create_proof_circuit::< KZGCommitmentScheme<Bn256>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, KZGSingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, proof_split_commits, None, ), StrategyType::Accum => { let protocol = Some(compile( &params, pk.get_vk(), Config::kzg().with_num_instance(vec![public_inputs.len()]), )); create_proof_circuit::< KZGCommitmentScheme<Bn256>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, KZGAccumulatorStrategy<_>, _, PoseidonTranscript<NativeLoader, _>, PoseidonTranscript<NativeLoader, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, proof_split_commits, protocol, ) } } } Commitments::IPA => { let pk = load_pk::<IPACommitmentScheme<G1Affine>, GraphCircuit>(pk_path, circuit.params())?; let params = load_params_prover::<IPACommitmentScheme<G1Affine>>( srs_path, circuit_settings.run_args.logrows, Commitments::IPA, )?; match strategy { StrategyType::Single => create_proof_circuit::< IPACommitmentScheme<G1Affine>, _, ProverIPA<_>, VerifierIPA<_>, IPASingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, proof_split_commits, None, ), StrategyType::Accum => { let protocol = Some(compile( &params, pk.get_vk(), Config::ipa().with_num_instance(vec![public_inputs.len()]), )); create_proof_circuit::< IPACommitmentScheme<G1Affine>, _, ProverIPA<_>, VerifierIPA<_>, IPAAccumulatorStrategy<_>, _, PoseidonTranscript<NativeLoader, _>, PoseidonTranscript<NativeLoader, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, proof_split_commits, protocol, ) } } } }?; snark.pretty_public_inputs = pretty_public_inputs; if let Some(proof_path) = proof_path { snark.save(&proof_path)?; } Ok(snark) } pub(crate) fn swap_proof_commitments_cmd( proof_path: PathBuf, witness: PathBuf, ) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> { let snark = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?; let witness = GraphWitness::from_path(witness)?; let commitments = witness.get_polycommitments(); if commitments.is_empty() { log::warn!("no commitments found in witness"); } let snark_new = swap_proof_commitments_polycommit(&snark, &commitments)?; if snark_new.proof != *snark.proof { log::warn!("swap proof has created a different proof"); } snark_new.save(&proof_path)?; Ok(snark_new) } pub(crate) fn mock_aggregate( aggregation_snarks: Vec<PathBuf>, logrows: u32, split_proofs: bool, ) -> Result<String, Box<dyn Error>> { let mut snarks = vec![]; for proof_path in aggregation_snarks.iter() { match Snark::load::<KZGCommitmentScheme<Bn256>>(proof_path) { Ok(snark) => { snarks.push(snark); } Err(_) => { return Err( "invalid sample commitment type for aggregation, must be KZG" .to_string() .into(), ); } } } // proof aggregation #[cfg(not(target_arch = "wasm32"))] let pb = { let pb = init_spinner(); pb.set_message("Aggregating (may take a while)..."); pb }; let circuit = AggregationCircuit::new(&G1Affine::generator().into(), snarks, split_proofs)?; let prover = halo2_proofs::dev::MockProver::run(logrows, &circuit, vec![circuit.instances()]) .map_err(Box::<dyn Error>::from)?; prover .verify() .map_err(|e| Box::<dyn Error>::from(ExecutionError::VerifyError(e)))?; #[cfg(not(target_arch = "wasm32"))] pb.finish_with_message("Done."); Ok(String::new()) } pub(crate) fn setup_aggregate( sample_snarks: Vec<PathBuf>, vk_path: PathBuf, pk_path: PathBuf, srs_path: Option<PathBuf>, logrows: u32, split_proofs: bool, disable_selector_compression: bool, commitment: Commitments, ) -> Result<String, Box<dyn Error>> { let mut snarks = vec![]; for proof_path in sample_snarks.iter() { match Snark::load::<KZGCommitmentScheme<Bn256>>(proof_path) { Ok(snark) => { snarks.push(snark); } Err(_) => { return Err( "invalid sample commitment type for aggregation, must be KZG" .to_string() .into(), ); } } } let circuit = AggregationCircuit::new(&G1Affine::generator().into(), snarks, split_proofs)?; let pk = match commitment { Commitments::KZG => { let params = load_params_prover::<KZGCommitmentScheme<Bn256>>( srs_path, logrows, Commitments::KZG, )?; create_keys::<KZGCommitmentScheme<Bn256>, AggregationCircuit>( &circuit, &params, disable_selector_compression, )? } Commitments::IPA => { let params = load_params_prover::<IPACommitmentScheme<G1Affine>>( srs_path, logrows, Commitments::IPA, )?; create_keys::<IPACommitmentScheme<G1Affine>, AggregationCircuit>( &circuit, &params, disable_selector_compression, )? } }; save_vk::<G1Affine>(&vk_path, pk.get_vk())?; save_pk::<G1Affine>(&pk_path, &pk)?; Ok(String::new()) } #[allow(clippy::too_many_arguments)] pub(crate) fn aggregate( proof_path: PathBuf, aggregation_snarks: Vec<PathBuf>, pk_path: PathBuf, srs_path: Option<PathBuf>, transcript: TranscriptType, logrows: u32, check_mode: CheckMode, split_proofs: bool, commitment: Commitments, ) -> Result<Snark<Fr, G1Affine>, Box<dyn Error>> { let mut snarks = vec![]; for proof_path in aggregation_snarks.iter() { match Snark::load::<KZGCommitmentScheme<Bn256>>(proof_path) { Ok(snark) => { snarks.push(snark); } Err(_) => { return Err( "invalid sample commitment type for aggregation, must be KZG" .to_string() .into(), ); } } } // proof aggregation #[cfg(not(target_arch = "wasm32"))] let pb = { let pb = init_spinner(); pb.set_message("Aggregating (may take a while)..."); pb }; let now = Instant::now(); let snark = match commitment { Commitments::KZG => { let pk = load_pk::<KZGCommitmentScheme<Bn256>, AggregationCircuit>(pk_path, ())?; let params: ParamsKZG<Bn256> = load_params_prover::<KZGCommitmentScheme<_>>( srs_path.clone(), logrows, Commitments::KZG, )?; let circuit = AggregationCircuit::new( &ParamsProver::<G1Affine>::get_g(&params)[0].into(), snarks, split_proofs, )?; let public_inputs = circuit.instances(); match transcript { TranscriptType::EVM => create_proof_circuit::< KZGCommitmentScheme<Bn256>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, KZGSingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, None, None, ), TranscriptType::Poseidon => { let protocol = Some(compile( &params, pk.get_vk(), Config::kzg().with_num_instance(vec![public_inputs.len()]), )); create_proof_circuit::< KZGCommitmentScheme<Bn256>, _, ProverSHPLONK<_>, VerifierSHPLONK<_>, KZGAccumulatorStrategy<_>, _, PoseidonTranscript<NativeLoader, _>, PoseidonTranscript<NativeLoader, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, None, protocol, ) } } } Commitments::IPA => { let pk = load_pk::<IPACommitmentScheme<_>, AggregationCircuit>(pk_path, ())?; let params: ParamsIPA<_> = load_params_prover::<IPACommitmentScheme<_>>( srs_path.clone(), logrows, Commitments::IPA, )?; let circuit = AggregationCircuit::new( &ParamsProver::<G1Affine>::get_g(&params)[0].into(), snarks, split_proofs, )?; let public_inputs = circuit.instances(); match transcript { TranscriptType::EVM => create_proof_circuit::< IPACommitmentScheme<G1Affine>, _, ProverIPA<_>, VerifierIPA<_>, IPASingleStrategy<_>, _, EvmTranscript<_, _, _, _>, EvmTranscript<_, _, _, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, None, None, ), TranscriptType::Poseidon => { let protocol = Some(compile( &params, pk.get_vk(), Config::ipa().with_num_instance(vec![public_inputs.len()]), )); create_proof_circuit::< IPACommitmentScheme<G1Affine>, _, ProverIPA<_>, VerifierIPA<_>, IPAAccumulatorStrategy<_>, _, PoseidonTranscript<NativeLoader, _>, PoseidonTranscript<NativeLoader, _>, >( circuit, vec![public_inputs], &params, &pk, check_mode, commitment, transcript, None, protocol, ) } } } }?; // the K used for the aggregation circuit let elapsed = now.elapsed(); info!( "Aggregation proof took {}.{}", elapsed.as_secs(), elapsed.subsec_millis() ); snark.save(&proof_path)?; #[cfg(not(target_arch = "wasm32"))] pb.finish_with_message("Done."); Ok(snark) } pub(crate) fn verify( proof_path: PathBuf, settings_path: PathBuf, vk_path: PathBuf, srs_path: Option<PathBuf>, reduced_srs: bool, ) -> Result<bool, Box<dyn Error>> { let circuit_settings = GraphSettings::load(&settings_path)?; let logrows = circuit_settings.run_args.logrows; let commitment = circuit_settings.run_args.commitment.into(); match commitment { Commitments::KZG => { let proof = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?; let params: ParamsKZG<Bn256> = if reduced_srs { // only need G_0 for the verification with shplonk load_params_verifier::<KZGCommitmentScheme<Bn256>>(srs_path, 1, Commitments::KZG)? } else { load_params_verifier::<KZGCommitmentScheme<Bn256>>( srs_path, logrows, Commitments::KZG, )? }; match proof.transcript_type { TranscriptType::EVM => { verify_commitment::< KZGCommitmentScheme<Bn256>, VerifierSHPLONK<'_, Bn256>, _, KZGSingleStrategy<_>, EvmTranscript<G1Affine, _, _, _>, GraphCircuit, _, >(proof_path, circuit_settings, vk_path, &params, logrows) } TranscriptType::Poseidon => { verify_commitment::< KZGCommitmentScheme<Bn256>, VerifierSHPLONK<'_, Bn256>, _, KZGSingleStrategy<_>, PoseidonTranscript<NativeLoader, _>, GraphCircuit, _, >(proof_path, circuit_settings, vk_path, &params, logrows) } } } Commitments::IPA => { let proof = Snark::load::<IPACommitmentScheme<G1Affine>>(&proof_path)?; let params: ParamsIPA<_> = load_params_verifier::<IPACommitmentScheme<G1Affine>>( srs_path, logrows, Commitments::IPA, )?; match proof.transcript_type { TranscriptType::EVM => { verify_commitment::< IPACommitmentScheme<G1Affine>, VerifierIPA<_>, _, IPASingleStrategy<_>, EvmTranscript<G1Affine, _, _, _>, GraphCircuit, _, >(proof_path, circuit_settings, vk_path, &params, logrows) } TranscriptType::Poseidon => { verify_commitment::< IPACommitmentScheme<G1Affine>, VerifierIPA<_>, _, IPASingleStrategy<_>, PoseidonTranscript<NativeLoader, _>, GraphCircuit, _, >(proof_path, circuit_settings, vk_path, &params, logrows) } } } } } fn verify_commitment< 'a, Scheme: CommitmentScheme, V: Verifier<'a, Scheme>, E: EncodedChallenge<Scheme::Curve>, Strategy: VerificationStrategy<'a, Scheme, V>, TR: TranscriptReadBuffer<Cursor<Vec<u8>>, Scheme::Curve, E>, C: Circuit<<Scheme as CommitmentScheme>::Scalar, Params = Params>, Params, >( proof_path: PathBuf, settings: Params, vk_path: PathBuf, params: &'a Scheme::ParamsVerifier, logrows: u32, ) -> Result<bool, Box<dyn Error>> where Scheme::Scalar: FromUniformBytes<64> + SerdeObject + Serialize + DeserializeOwned + WithSmallOrderMulGroup<3>, Scheme::Curve: SerdeObject + Serialize + DeserializeOwned, Scheme::ParamsVerifier: 'a, { let proof = Snark::load::<Scheme>(&proof_path)?; let strategy = Strategy::new(params); let vk = load_vk::<Scheme, C>(vk_path, settings)?; let now = Instant::now(); let result = verify_proof_circuit::<V, _, _, _, TR>(&proof, params, &vk, strategy, 1 << logrows); let elapsed = now.elapsed(); info!( "verify took {}.{}", elapsed.as_secs(), elapsed.subsec_millis() ); info!("verified: {}", result.is_ok()); result.map_err(|e: plonk::Error| e.into()).map(|_| true) } pub(crate) fn verify_aggr( proof_path: PathBuf, vk_path: PathBuf, srs_path: Option<PathBuf>, logrows: u32, reduced_srs: bool, commitment: Commitments, ) -> Result<bool, Box<dyn Error>> { match commitment { Commitments::KZG => { let proof = Snark::load::<KZGCommitmentScheme<Bn256>>(&proof_path)?; let params: ParamsKZG<Bn256> = if reduced_srs { // only need G_0 for the verification with shplonk load_params_verifier::<KZGCommitmentScheme<Bn256>>(srs_path, 1, Commitments::KZG)? } else { load_params_verifier::<KZGCommitmentScheme<Bn256>>( srs_path, logrows, Commitments::KZG, )? }; match proof.transcript_type { TranscriptType::EVM => verify_commitment::< KZGCommitmentScheme<Bn256>, VerifierSHPLONK<'_, Bn256>, _, KZGSingleStrategy<_>, EvmTranscript<_, _, _, _>, AggregationCircuit, _, >(proof_path, (), vk_path, &params, logrows), TranscriptType::Poseidon => { verify_commitment::< KZGCommitmentScheme<Bn256>, VerifierSHPLONK<'_, Bn256>, _, KZGAccumulatorStrategy<_>, PoseidonTranscript<NativeLoader, _>, AggregationCircuit, _, >(proof_path, (), vk_path, &params, logrows) } } } Commitments::IPA => { let proof = Snark::load::<IPACommitmentScheme<G1Affine>>(&proof_path)?; let params: ParamsIPA<_> = load_params_verifier::<IPACommitmentScheme<G1Affine>>( srs_path, logrows, Commitments::IPA, )?; match proof.transcript_type { TranscriptType::EVM => verify_commitment::< IPACommitmentScheme<G1Affine>, VerifierIPA<_>, _, IPASingleStrategy<_>, EvmTranscript<_, _, _, _>, AggregationCircuit, _, >(proof_path, (), vk_path, &params, logrows), TranscriptType::Poseidon => { verify_commitment::< IPACommitmentScheme<G1Affine>, VerifierIPA<_>, _, IPAAccumulatorStrategy<_>, PoseidonTranscript<NativeLoader, _>, AggregationCircuit, _, >(proof_path, (), vk_path, &params, logrows) } } } } } /// helper function for load_params pub(crate) fn load_params_verifier<Scheme: CommitmentScheme>( srs_path: Option<PathBuf>, logrows: u32, commitment: Commitments, ) -> Result<Scheme::ParamsVerifier, Box<dyn Error>> { let srs_path = get_srs_path(logrows, srs_path, commitment); let mut params = load_srs_verifier::<Scheme>(srs_path)?; info!("downsizing params to {} logrows", logrows); if logrows < params.k() { params.downsize(logrows); } Ok(params) } /// helper function for load_params pub(crate) fn load_params_prover<Scheme: CommitmentScheme>( srs_path: Option<PathBuf>, logrows: u32, commitment: Commitments, ) -> Result<Scheme::ParamsProver, Box<dyn Error>> { let srs_path = get_srs_path(logrows, srs_path, commitment); let mut params = load_srs_prover::<Scheme>(srs_path)?; info!("downsizing params to {} logrows", logrows); if logrows < params.k() { params.downsize(logrows); } Ok(params) }
https://github.com/zkonduit/ezkl
src/fieldutils.rs
use halo2_proofs::arithmetic::Field; /// Utilities for converting from Halo2 PrimeField types to integers (and vice-versa). use halo2curves::ff::PrimeField; /// Converts an i32 to a PrimeField element. pub fn i32_to_felt<F: PrimeField>(x: i32) -> F { if x >= 0 { F::from(x as u64) } else { -F::from(x.unsigned_abs() as u64) } } /// Converts an i128 to a PrimeField element. pub fn i128_to_felt<F: PrimeField>(x: i128) -> F { if x >= 0 { F::from_u128(x as u128) } else { -F::from_u128((-x) as u128) } } /// Converts a PrimeField element to an i32. pub fn felt_to_i32<F: PrimeField + PartialOrd + Field>(x: F) -> i32 { if x > F::from(i32::MAX as u64) { let rep = (-x).to_repr(); let negtmp: &[u8] = rep.as_ref(); let lower_32 = u32::from_le_bytes(negtmp[..4].try_into().unwrap()); -(lower_32 as i32) } else { let rep = (x).to_repr(); let tmp: &[u8] = rep.as_ref(); let lower_32 = u32::from_le_bytes(tmp[..4].try_into().unwrap()); lower_32 as i32 } } /// Converts a PrimeField element to an f64. pub fn felt_to_f64<F: PrimeField + PartialOrd + Field>(x: F) -> f64 { if x > F::from_u128(i128::MAX as u128) { let rep = (-x).to_repr(); let negtmp: &[u8] = rep.as_ref(); let lower_128: u128 = u128::from_le_bytes(negtmp[..16].try_into().unwrap()); -(lower_128 as f64) } else { let rep = (x).to_repr(); let tmp: &[u8] = rep.as_ref(); let lower_128: u128 = u128::from_le_bytes(tmp[..16].try_into().unwrap()); lower_128 as f64 } } /// Converts a PrimeField element to an i128. pub fn felt_to_i128<F: PrimeField + PartialOrd + Field>(x: F) -> i128 { if x > F::from_u128(i128::MAX as u128) { let rep = (-x).to_repr(); let negtmp: &[u8] = rep.as_ref(); let lower_128: u128 = u128::from_le_bytes(negtmp[..16].try_into().unwrap()); -(lower_128 as i128) } else { let rep = (x).to_repr(); let tmp: &[u8] = rep.as_ref(); let lower_128: u128 = u128::from_le_bytes(tmp[..16].try_into().unwrap()); lower_128 as i128 } } #[cfg(test)] mod test { use super::*; use halo2curves::pasta::Fp as F; #[test] fn test_conv() { let res: F = i32_to_felt(-15i32); assert_eq!(res, -F::from(15)); let res: F = i32_to_felt(2_i32.pow(17)); assert_eq!(res, F::from(131072)); let res: F = i128_to_felt(-15i128); assert_eq!(res, -F::from(15)); let res: F = i128_to_felt(2_i128.pow(17)); assert_eq!(res, F::from(131072)); } #[test] fn felttoi32() { for x in -(2i32.pow(16))..(2i32.pow(16)) { let fieldx: F = i32_to_felt::<F>(x); let xf: i32 = felt_to_i32::<F>(fieldx); assert_eq!(x, xf); } } #[test] fn felttoi128() { for x in -(2i128.pow(20))..(2i128.pow(20)) { let fieldx: F = i128_to_felt::<F>(x); let xf: i128 = felt_to_i128::<F>(fieldx); assert_eq!(x, xf); } } }
https://github.com/zkonduit/ezkl
src/graph/input.rs
use super::quantize_float; use super::GraphError; use crate::circuit::InputType; use crate::fieldutils::i128_to_felt; #[cfg(not(target_arch = "wasm32"))] use crate::tensor::Tensor; use crate::EZKL_BUF_CAPACITY; use halo2curves::bn256::Fr as Fp; #[cfg(not(target_arch = "wasm32"))] use postgres::{Client, NoTls}; #[cfg(feature = "python-bindings")] use pyo3::prelude::*; #[cfg(feature = "python-bindings")] use pyo3::types::PyDict; #[cfg(feature = "python-bindings")] use pyo3::ToPyObject; use serde::ser::SerializeStruct; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::io::BufReader; use std::io::BufWriter; use std::io::Read; use std::panic::UnwindSafe; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::tract_core::{ tract_data::{prelude::Tensor as TractTensor, TVec}, value::TValue, }; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::tract_hir::tract_num_traits::ToPrimitive; type Decimals = u8; type Call = String; type RPCUrl = String; /// #[derive(Clone, Debug, PartialOrd, PartialEq)] pub enum FileSourceInner { /// Inner elements of float inputs coming from a file Float(f64), /// Inner elements of bool inputs coming from a file Bool(bool), /// Inner elements of inputs coming from a witness Field(Fp), } impl FileSourceInner { /// pub fn is_float(&self) -> bool { matches!(self, FileSourceInner::Float(_)) } /// pub fn is_bool(&self) -> bool { matches!(self, FileSourceInner::Bool(_)) } /// pub fn is_field(&self) -> bool { matches!(self, FileSourceInner::Field(_)) } } impl Serialize for FileSourceInner { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { FileSourceInner::Field(data) => data.serialize(serializer), FileSourceInner::Bool(data) => data.serialize(serializer), FileSourceInner::Float(data) => data.serialize(serializer), } } } // !!! ALWAYS USE JSON SERIALIZATION FOR GRAPH INPUT // UNTAGGED ENUMS WONT WORK :( as highlighted here: impl<'de> Deserialize<'de> for FileSourceInner { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let this_json: Box<serde_json::value::RawValue> = Deserialize::deserialize(deserializer)?; let bool_try: Result<bool, _> = serde_json::from_str(this_json.get()); if let Ok(t) = bool_try { return Ok(FileSourceInner::Bool(t)); } let float_try: Result<f64, _> = serde_json::from_str(this_json.get()); if let Ok(t) = float_try { return Ok(FileSourceInner::Float(t)); } let field_try: Result<Fp, _> = serde_json::from_str(this_json.get()); if let Ok(t) = field_try { return Ok(FileSourceInner::Field(t)); } Err(serde::de::Error::custom( "failed to deserialize FileSourceInner", )) } } /// Elements of inputs coming from a file pub type FileSource = Vec<Vec<FileSourceInner>>; impl FileSourceInner { /// Create a new FileSourceInner pub fn new_float(f: f64) -> Self { FileSourceInner::Float(f) } /// Create a new FileSourceInner pub fn new_field(f: Fp) -> Self { FileSourceInner::Field(f) } /// Create a new FileSourceInner pub fn new_bool(f: bool) -> Self { FileSourceInner::Bool(f) } /// pub fn as_type(&mut self, input_type: &InputType) { match self { FileSourceInner::Float(f) => input_type.roundtrip(f), FileSourceInner::Bool(_) => assert!(matches!(input_type, InputType::Bool)), FileSourceInner::Field(_) => {} } } /// Convert to a field element pub fn to_field(&self, scale: crate::Scale) -> Fp { match self { FileSourceInner::Float(f) => i128_to_felt(quantize_float(f, 0.0, scale).unwrap()), FileSourceInner::Bool(f) => { if *f { Fp::one() } else { Fp::zero() } } FileSourceInner::Field(f) => *f, } } /// Convert to a float pub fn to_float(&self) -> f64 { match self { FileSourceInner::Float(f) => *f, FileSourceInner::Bool(f) => { if *f { 1.0 } else { 0.0 } } FileSourceInner::Field(f) => crate::fieldutils::felt_to_i128(*f) as f64, } } } /// Inner elements of inputs/outputs coming from on-chain #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialOrd, PartialEq)] pub struct OnChainSource { /// Vector of calls to accounts pub calls: Vec<CallsToAccount>, /// RPC url pub rpc: RPCUrl, } impl OnChainSource { /// Create a new OnChainSource pub fn new(calls: Vec<CallsToAccount>, rpc: RPCUrl) -> Self { OnChainSource { calls, rpc } } } #[cfg(not(target_arch = "wasm32"))] /// Inner elements of inputs/outputs coming from postgres DB #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialOrd, PartialEq)] pub struct PostgresSource { /// postgres host pub host: RPCUrl, /// user to connect to postgres pub user: String, /// password to connect to postgres pub password: String, /// query to execute pub query: String, /// dbname pub dbname: String, /// port pub port: String, } #[cfg(not(target_arch = "wasm32"))] impl PostgresSource { /// Create a new PostgresSource pub fn new( host: RPCUrl, port: String, user: String, query: String, dbname: String, password: String, ) -> Self { PostgresSource { host, user, password, query, dbname, port, } } /// Fetch data from postgres pub fn fetch(&self) -> Result<Vec<Vec<pg_bigdecimal::PgNumeric>>, Box<dyn std::error::Error>> { // clone to move into thread let user = self.user.clone(); let host = self.host.clone(); let query = self.query.clone(); let dbname = self.dbname.clone(); let port = self.port.clone(); let password = self.password.clone(); let config = if password.is_empty() { format!( "host={} user={} dbname={} port={}", host, user, dbname, port ) } else { format!( "host={} user={} dbname={} port={} password={}", host, user, dbname, port, password ) }; let mut client = Client::connect(&config, NoTls)?; let mut res: Vec<pg_bigdecimal::PgNumeric> = Vec::new(); // extract rows from query for row in client.query(&query, &[])? { // extract features from row for i in 0..row.len() { res.push(row.get(i)); } } Ok(vec![res]) } /// Fetch data from postgres and format it as a FileSource pub fn fetch_and_format_as_file( &self, ) -> Result<Vec<Vec<FileSourceInner>>, Box<dyn std::error::Error>> { Ok(self .fetch()? .iter() .map(|d| { d.iter() .map(|d| { FileSourceInner::Float( d.n.as_ref() .unwrap() .to_f64() .ok_or("could not convert decimal to f64") .unwrap(), ) }) .collect() }) .collect()) } } impl OnChainSource { #[cfg(not(target_arch = "wasm32"))] /// Create dummy local on-chain data to test the OnChain data source pub async fn test_from_file_data( data: &FileSource, scales: Vec<crate::Scale>, mut shapes: Vec<Vec<usize>>, rpc: Option<&str>, ) -> Result<(Vec<Tensor<Fp>>, Self), Box<dyn std::error::Error>> { use crate::eth::{evm_quantize, read_on_chain_inputs, test_on_chain_data}; use log::debug; // Set up local anvil instance for reading on-chain data let (anvil, client) = crate::eth::setup_eth_backend(rpc, None).await?; let address = client.address(); let mut scales = scales; // set scales to 1 where data is a field element for (idx, i) in data.iter().enumerate() { if i.iter().all(|e| e.is_field()) { scales[idx] = 0; shapes[idx] = vec![i.len()]; } } let calls_to_accounts = test_on_chain_data(client.clone(), data).await?; debug!("Calls to accounts: {:?}", calls_to_accounts); let inputs = read_on_chain_inputs(client.clone(), address, &calls_to_accounts).await?; debug!("Inputs: {:?}", inputs); let mut quantized_evm_inputs = vec![]; let mut prev = 0; for (idx, i) in data.iter().enumerate() { quantized_evm_inputs.extend( evm_quantize( client.clone(), vec![scales[idx]; i.len()], &( inputs.0[prev..i.len()].to_vec(), inputs.1[prev..i.len()].to_vec(), ), ) .await?, ); prev += i.len(); } // on-chain data has already been quantized at this point. Just need to reshape it and push into tensor vector let mut inputs: Vec<Tensor<Fp>> = vec![]; for (input, shape) in [quantized_evm_inputs].iter().zip(shapes) { let mut t: Tensor<Fp> = input.iter().cloned().collect(); t.reshape(&shape)?; inputs.push(t); } let used_rpc = rpc.unwrap_or(&anvil.endpoint()).to_string(); // Fill the input_data field of the GraphData struct Ok(( inputs, OnChainSource::new(calls_to_accounts.clone(), used_rpc), )) } } /// Defines the view only calls to accounts to fetch the on-chain input data. /// This data will be included as part of the first elements in the publicInputs /// for the sol evm verifier and will be verifyWithDataAttestation.sol #[derive(Clone, Debug, Deserialize, Serialize, Default, PartialOrd, PartialEq)] pub struct CallsToAccount { /// A vector of tuples, where index 0 of tuples /// are the byte strings representing the ABI encoded function calls to /// read the data from the address. This call must return a single /// elementary type (<https://docs.soliditylang.org/en/v0.8.20/abi-spec.html#types>). /// The second index of the tuple is the number of decimals for f32 conversion. /// We don't support dynamic types currently. pub call_data: Vec<(Call, Decimals)>, /// Address of the contract to read the data from. pub address: String, } /// Enum that defines source of the inputs/outputs to the EZKL model #[derive(Clone, Debug, Serialize, PartialOrd, PartialEq)] #[serde(untagged)] pub enum DataSource { /// .json File data source. File(FileSource), /// On-chain data source. The first element is the calls to the account, and the second is the RPC url. OnChain(OnChainSource), /// Postgres DB #[cfg(not(target_arch = "wasm32"))] DB(PostgresSource), } impl Default for DataSource { fn default() -> Self { DataSource::File(vec![vec![]]) } } impl From<FileSource> for DataSource { fn from(data: FileSource) -> Self { DataSource::File(data) } } impl From<Vec<Vec<Fp>>> for DataSource { fn from(data: Vec<Vec<Fp>>) -> Self { DataSource::File( data.iter() .map(|e| e.iter().map(|e| FileSourceInner::Field(*e)).collect()) .collect(), ) } } impl From<Vec<Vec<f64>>> for DataSource { fn from(data: Vec<Vec<f64>>) -> Self { DataSource::File( data.iter() .map(|e| e.iter().map(|e| FileSourceInner::Float(*e)).collect()) .collect(), ) } } impl From<OnChainSource> for DataSource { fn from(data: OnChainSource) -> Self { DataSource::OnChain(data) } } // !!! ALWAYS USE JSON SERIALIZATION FOR GRAPH INPUT // UNTAGGED ENUMS WONT WORK :( as highlighted here: impl<'de> Deserialize<'de> for DataSource { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let this_json: Box<serde_json::value::RawValue> = Deserialize::deserialize(deserializer)?; let first_try: Result<FileSource, _> = serde_json::from_str(this_json.get()); if let Ok(t) = first_try { return Ok(DataSource::File(t)); } let second_try: Result<OnChainSource, _> = serde_json::from_str(this_json.get()); if let Ok(t) = second_try { return Ok(DataSource::OnChain(t)); } #[cfg(not(target_arch = "wasm32"))] { let third_try: Result<PostgresSource, _> = serde_json::from_str(this_json.get()); if let Ok(t) = third_try { return Ok(DataSource::DB(t)); } } Err(serde::de::Error::custom("failed to deserialize DataSource")) } } /// Input to graph as a datasource /// Always use JSON serialization for GraphData. Seriously. #[derive(Clone, Debug, Deserialize, Default, PartialEq)] pub struct GraphData { /// Inputs to the model / computational graph (can be empty vectors if inputs are coming from on-chain). pub input_data: DataSource, /// Outputs of the model / computational graph (can be empty vectors if outputs are coming from on-chain). pub output_data: Option<DataSource>, } impl UnwindSafe for GraphData {} impl GraphData { // not wasm #[cfg(not(target_arch = "wasm32"))] /// Convert the input data to tract data pub fn to_tract_data( &self, shapes: &[Vec<usize>], datum_types: &[tract_onnx::prelude::DatumType], ) -> Result<TVec<TValue>, Box<dyn std::error::Error>> { let mut inputs = TVec::new(); match &self.input_data { DataSource::File(data) => { for (i, input) in data.iter().enumerate() { if !input.is_empty() { let dt = datum_types[i]; let input = input.iter().map(|e| e.to_float()).collect::<Vec<f64>>(); let tt = TractTensor::from_shape(&shapes[i], &input)?; let tt = tt.cast_to_dt(dt)?; inputs.push(tt.into_owned().into()); } } } _ => { return Err(Box::new(GraphError::InvalidDims( 0, "non file data cannot be split into batches".to_string(), ))) } } Ok(inputs) } /// pub fn new(input_data: DataSource) -> Self { GraphData { input_data, output_data: None, } } /// Load the model input from a file pub fn from_path(path: std::path::PathBuf) -> Result<Self, Box<dyn std::error::Error>> { let reader = std::fs::File::open(path)?; let mut reader = BufReader::with_capacity(*EZKL_BUF_CAPACITY, reader); let mut buf = String::new(); reader.read_to_string(&mut buf)?; let graph_input = serde_json::from_str(&buf)?; Ok(graph_input) } /// Save the model input to a file pub fn save(&self, path: std::path::PathBuf) -> Result<(), Box<dyn std::error::Error>> { // buf writer let writer = BufWriter::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::create(path)?); serde_json::to_writer(writer, self)?; Ok(()) } /// pub fn split_into_batches( &self, input_shapes: Vec<Vec<usize>>, ) -> Result<Vec<Self>, Box<dyn std::error::Error>> { // split input data into batches let mut batched_inputs = vec![]; let iterable = match self { GraphData { input_data: DataSource::File(data), output_data: _, } => data.clone(), GraphData { input_data: DataSource::OnChain(_), output_data: _, } => { return Err(Box::new(GraphError::InvalidDims( 0, "on-chain data cannot be split into batches".to_string(), ))) } #[cfg(not(target_arch = "wasm32"))] GraphData { input_data: DataSource::DB(data), output_data: _, } => data.fetch_and_format_as_file()?, }; for (i, shape) in input_shapes.iter().enumerate() { // ensure the input is evenly divisible by batch_size let input_size = shape.clone().iter().product::<usize>(); let input = &iterable[i]; if input.len() % input_size != 0 { return Err(Box::new(GraphError::InvalidDims( 0, "calibration data length must be evenly divisible by the original input_size" .to_string(), ))); } let mut batches = vec![]; for batch in input.chunks(input_size) { batches.push(batch.to_vec()); } batched_inputs.push(batches); } // now merge all the batches for each input into a vector of batches // first assert each input has the same number of batches let num_batches = if batched_inputs.is_empty() { 0 } else { let num_batches = batched_inputs[0].len(); for input in batched_inputs.iter() { assert_eq!(input.len(), num_batches); } num_batches }; // now merge the batches let mut input_batches = vec![]; for i in 0..num_batches { let mut batch = vec![]; for input in batched_inputs.iter() { batch.push(input[i].clone()); } input_batches.push(DataSource::File(batch)); } if input_batches.is_empty() { input_batches.push(DataSource::File(vec![vec![]])); } // create a new GraphWitness for each batch let batches = input_batches .into_iter() .map(GraphData::new) .collect::<Vec<GraphData>>(); Ok(batches) } } #[cfg(feature = "python-bindings")] impl ToPyObject for CallsToAccount { fn to_object(&self, py: Python) -> PyObject { let dict = PyDict::new(py); dict.set_item("account", &self.address).unwrap(); dict.set_item("call_data", &self.call_data).unwrap(); dict.to_object(py) } } #[cfg(feature = "python-bindings")] impl ToPyObject for DataSource { fn to_object(&self, py: Python) -> PyObject { match self { DataSource::File(data) => data.to_object(py), DataSource::OnChain(source) => { let dict = PyDict::new(py); dict.set_item("rpc_url", &source.rpc).unwrap(); dict.set_item("calls_to_accounts", &source.calls).unwrap(); dict.to_object(py) } DataSource::DB(source) => { let dict = PyDict::new(py); dict.set_item("host", &source.host).unwrap(); dict.set_item("user", &source.user).unwrap(); dict.set_item("query", &source.query).unwrap(); dict.to_object(py) } } } } #[cfg(feature = "python-bindings")] use crate::pfsys::field_to_string; #[cfg(feature = "python-bindings")] impl ToPyObject for FileSourceInner { fn to_object(&self, py: Python) -> PyObject { match self { FileSourceInner::Field(data) => field_to_string(data).to_object(py), FileSourceInner::Bool(data) => data.to_object(py), FileSourceInner::Float(data) => data.to_object(py), } } } impl Serialize for GraphData { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut state = serializer.serialize_struct("GraphData", 4)?; state.serialize_field("input_data", &self.input_data)?; state.serialize_field("output_data", &self.output_data)?; state.end() } } #[cfg(test)] mod tests { use super::*; #[test] // this is for backwards compatibility with the old format fn test_data_source_serialization_round_trip() { let source = DataSource::from(vec![vec![0.053_262_424, 0.074_970_566, 0.052_355_476]]); let serialized = serde_json::to_string(&source).unwrap(); const JSON: &str = r#"[[0.053262424,0.074970566,0.052355476]]"#; assert_eq!(serialized, JSON); let expect = serde_json::from_str::<DataSource>(JSON) .map_err(|e| e.to_string()) .unwrap(); assert_eq!(expect, source); } #[test] // this is for backwards compatibility with the old format fn test_graph_input_serialization_round_trip() { let file = GraphData::new(DataSource::from(vec![vec![ 0.05326242372393608, 0.07497056573629379, 0.05235547572374344, ]])); let serialized = serde_json::to_string(&file).unwrap(); const JSON: &str = r#"{"input_data":[[0.05326242372393608,0.07497056573629379,0.05235547572374344]],"output_data":null}"#; assert_eq!(serialized, JSON); let graph_input3 = serde_json::from_str::<GraphData>(JSON) .map_err(|e| e.to_string()) .unwrap(); assert_eq!(graph_input3, file); } // test for the compatibility with the serialized elements from the mclbn256 library #[test] fn test_python_compat() { let source = Fp::from_raw([18445520602771460712, 838677322461845011, 3079992810, 0]); let original_addr = "0x000000000000000000000000b794f5ea0ba39494ce839613fffba74279579268"; assert_eq!(format!("{:?}", source), original_addr); } }
https://github.com/zkonduit/ezkl
src/graph/mod.rs
/// Representations of a computational graph's inputs. pub mod input; /// Crate for defining a computational graph and building a ZK-circuit from it. pub mod model; /// Representations of a computational graph's modules. pub mod modules; /// Inner elements of a computational graph that represent a single operation / constraints. pub mod node; /// Helper functions pub mod utilities; /// Representations of a computational graph's variables. pub mod vars; #[cfg(not(target_arch = "wasm32"))] use colored_json::ToColoredJson; #[cfg(unix)] use gag::Gag; use halo2_proofs::plonk::VerifyingKey; use halo2_proofs::poly::commitment::CommitmentScheme; pub use input::DataSource; use itertools::Itertools; use tosubcommand::ToFlags; #[cfg(not(target_arch = "wasm32"))] use self::input::OnChainSource; use self::input::{FileSource, GraphData}; use self::modules::{GraphModules, ModuleConfigs, ModuleForwardResult, ModuleSizes}; use crate::circuit::lookup::LookupOp; use crate::circuit::modules::ModulePlanner; use crate::circuit::region::ConstantsMap; use crate::circuit::table::{num_cols_required, Range, Table, RESERVED_BLINDING_ROWS_PAD}; use crate::circuit::{CheckMode, InputType}; use crate::fieldutils::felt_to_f64; use crate::pfsys::PrettyElements; use crate::tensor::{Tensor, ValTensor}; use crate::{RunArgs, EZKL_BUF_CAPACITY}; use halo2_proofs::{ circuit::Layouter, plonk::{Circuit, ConstraintSystem, Error as PlonkError}, }; use halo2curves::bn256::{self, Fr as Fp, G1Affine}; use halo2curves::ff::{Field, PrimeField}; #[cfg(not(target_arch = "wasm32"))] use lazy_static::lazy_static; use log::{debug, error, trace, warn}; use maybe_rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; pub use model::*; pub use node::*; #[cfg(feature = "python-bindings")] use pyo3::prelude::*; #[cfg(feature = "python-bindings")] use pyo3::types::PyDict; #[cfg(feature = "python-bindings")] use pyo3::ToPyObject; use serde::{Deserialize, Serialize}; use std::ops::Deref; use thiserror::Error; pub use utilities::*; pub use vars::*; #[cfg(feature = "python-bindings")] use crate::pfsys::field_to_string; /// The safety factor for the range of the lookup table. pub const RANGE_MULTIPLIER: i128 = 2; /// The maximum number of columns in a lookup table. pub const MAX_NUM_LOOKUP_COLS: usize = 12; /// Max representation of a lookup table input pub const MAX_LOOKUP_ABS: i128 = (MAX_NUM_LOOKUP_COLS as i128) * 2_i128.pow(MAX_PUBLIC_SRS); #[cfg(not(target_arch = "wasm32"))] lazy_static! { /// Max circuit area pub static ref EZKL_MAX_CIRCUIT_AREA: Option<usize> = if let Ok(max_circuit_area) = std::env::var("EZKL_MAX_CIRCUIT_AREA") { Some(max_circuit_area.parse().unwrap_or(0)) } else { None }; } #[cfg(target_arch = "wasm32")] const EZKL_MAX_CIRCUIT_AREA: Option<usize> = None; /// circuit related errors. #[derive(Debug, Error)] pub enum GraphError { /// The wrong inputs were passed to a lookup node #[error("invalid inputs for a lookup node")] InvalidLookupInputs, /// Shape mismatch in circuit construction #[error("invalid dimensions used for node {0} ({1})")] InvalidDims(usize, String), /// Wrong method was called to configure an op #[error("wrong method was called to configure node {0} ({1})")] WrongMethod(usize, String), /// A requested node is missing in the graph #[error("a requested node is missing in the graph: {0}")] MissingNode(usize), /// The wrong method was called on an operation #[error("an unsupported method was called on node {0} ({1})")] OpMismatch(usize, String), /// This operation is unsupported #[error("unsupported operation in graph")] UnsupportedOp, /// This operation is unsupported #[error("unsupported datatype in graph")] UnsupportedDataType, /// A node has missing parameters #[error("a node is missing required params: {0}")] MissingParams(String), /// A node has missing parameters #[error("a node is has misformed params: {0}")] MisformedParams(String), /// Error in the configuration of the visibility of variables #[error("there should be at least one set of public variables")] Visibility, /// Ezkl only supports divisions by constants #[error("ezkl currently only supports division by constants")] NonConstantDiv, /// Ezkl only supports constant powers #[error("ezkl currently only supports constant exponents")] NonConstantPower, /// Error when attempting to rescale an operation #[error("failed to rescale inputs for {0}")] RescalingError(String), /// Error when attempting to load a model #[error("failed to load")] ModelLoad, /// Packing exponent is too large #[error("largest packing exponent exceeds max. try reducing the scale")] PackingExponent, /// Invalid Input Types #[error("invalid input types")] InvalidInputTypes, /// Missing results #[error("missing results")] MissingResults, } /// pub const ASSUMED_BLINDING_FACTORS: usize = 5; /// The minimum number of rows in the grid pub const MIN_LOGROWS: u32 = 6; /// 26 pub const MAX_PUBLIC_SRS: u32 = bn256::Fr::S - 2; /// pub const RESERVED_BLINDING_ROWS: usize = ASSUMED_BLINDING_FACTORS + RESERVED_BLINDING_ROWS_PAD; use std::cell::RefCell; thread_local!( /// This is a global variable that holds the settings for the graph /// This is used to pass settings to the layouter and other parts of the circuit without needing to heavily modify the Halo2 API in a new fork pub static GLOBAL_SETTINGS: RefCell<Option<GraphSettings>> = const { RefCell::new(None) } ); /// Result from a forward pass #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct GraphWitness { /// The inputs of the forward pass pub inputs: Vec<Vec<Fp>>, /// The prettified outputs of the forward pass, we use a String to maximize compatibility with Python and JS clients pub pretty_elements: Option<PrettyElements>, /// The output of the forward pass pub outputs: Vec<Vec<Fp>>, /// Any hashes of inputs generated during the forward pass pub processed_inputs: Option<ModuleForwardResult>, /// Any hashes of params generated during the forward pass pub processed_params: Option<ModuleForwardResult>, /// Any hashes of outputs generated during the forward pass pub processed_outputs: Option<ModuleForwardResult>, /// max lookup input pub max_lookup_inputs: i128, /// max lookup input pub min_lookup_inputs: i128, /// max range check size pub max_range_size: i128, } impl GraphWitness { /// pub fn get_float_outputs(&self, scales: &[crate::Scale]) -> Vec<Tensor<f32>> { self.outputs .iter() .enumerate() .map(|(i, x)| { x.iter() .map(|y| (felt_to_f64(*y) / scale_to_multiplier(scales[i])) as f32) .collect::<Tensor<f32>>() }) .collect() } /// pub fn new(inputs: Vec<Vec<Fp>>, outputs: Vec<Vec<Fp>>) -> Self { GraphWitness { inputs, outputs, pretty_elements: None, processed_inputs: None, processed_params: None, processed_outputs: None, max_lookup_inputs: 0, min_lookup_inputs: 0, max_range_size: 0, } } /// Generate the rescaled elements for the witness pub fn generate_rescaled_elements( &mut self, input_scales: Vec<crate::Scale>, output_scales: Vec<crate::Scale>, visibility: VarVisibility, ) { let mut pretty_elements = PrettyElements { rescaled_inputs: self .inputs .iter() .enumerate() .map(|(i, t)| { let scale = input_scales[i]; t.iter() .map(|x| dequantize(*x, scale, 0.).to_string()) .collect() }) .collect(), inputs: self .inputs .iter() .map(|t| t.iter().map(|x| format!("{:?}", x)).collect()) .collect(), rescaled_outputs: self .outputs .iter() .enumerate() .map(|(i, t)| { let scale = output_scales[i]; t.iter() .map(|x| dequantize(*x, scale, 0.).to_string()) .collect() }) .collect(), outputs: self .outputs .iter() .map(|t| t.iter().map(|x| format!("{:?}", x)).collect()) .collect(), ..Default::default() }; if let Some(processed_inputs) = self.processed_inputs.clone() { pretty_elements.processed_inputs = processed_inputs .get_result(visibility.input) .iter() // gets printed as hex string .map(|x| x.iter().map(|y| format!("{:?}", y)).collect()) .collect(); } if let Some(processed_params) = self.processed_params.clone() { pretty_elements.processed_params = processed_params .get_result(visibility.params) .iter() // gets printed as hex string .map(|x| x.iter().map(|y| format!("{:?}", y)).collect()) .collect(); } if let Some(processed_outputs) = self.processed_outputs.clone() { pretty_elements.processed_outputs = processed_outputs .get_result(visibility.output) .iter() // gets printed as hex string .map(|x| x.iter().map(|y| format!("{:?}", y)).collect()) .collect(); } self.pretty_elements = Some(pretty_elements); } /// pub fn get_polycommitments(&self) -> Vec<G1Affine> { let mut commitments = vec![]; if let Some(processed_inputs) = &self.processed_inputs { if let Some(commits) = &processed_inputs.polycommit { commitments.extend(commits.iter().flatten()); } } if let Some(processed_params) = &self.processed_params { if let Some(commits) = &processed_params.polycommit { commitments.extend(commits.iter().flatten()); } } if let Some(processed_outputs) = &self.processed_outputs { if let Some(commits) = &processed_outputs.polycommit { commitments.extend(commits.iter().flatten()); } } commitments } /// Export the ezkl witness as json pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> { let serialized = match serde_json::to_string(&self) { Ok(s) => s, Err(e) => { return Err(Box::new(e)); } }; Ok(serialized) } /// Load the model input from a file pub fn from_path(path: std::path::PathBuf) -> Result<Self, Box<dyn std::error::Error>> { let file = std::fs::File::open(path.clone()) .map_err(|_| format!("failed to load {}", path.display()))?; let reader = std::io::BufReader::with_capacity(*EZKL_BUF_CAPACITY, file); serde_json::from_reader(reader).map_err(|e| e.into()) } /// Save the model input to a file pub fn save(&self, path: std::path::PathBuf) -> Result<(), Box<dyn std::error::Error>> { // use buf writer let writer = std::io::BufWriter::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::create(path)?); serde_json::to_writer(writer, &self).map_err(|e| e.into()) } /// pub fn get_input_tensor(&self) -> Vec<Tensor<Fp>> { self.inputs .clone() .into_iter() .map(|i| Tensor::from(i.into_iter())) .collect::<Vec<Tensor<Fp>>>() } /// pub fn get_output_tensor(&self) -> Vec<Tensor<Fp>> { self.outputs .clone() .into_iter() .map(|i| Tensor::from(i.into_iter())) .collect::<Vec<Tensor<Fp>>>() } } #[cfg(feature = "python-bindings")] impl ToPyObject for GraphWitness { fn to_object(&self, py: Python) -> PyObject { // Create a Python dictionary let dict = PyDict::new(py); let dict_inputs = PyDict::new(py); let dict_params = PyDict::new(py); let dict_outputs = PyDict::new(py); let inputs: Vec<Vec<String>> = self .inputs .iter() .map(|x| x.iter().map(field_to_string).collect()) .collect(); let outputs: Vec<Vec<String>> = self .outputs .iter() .map(|x| x.iter().map(field_to_string).collect()) .collect(); dict.set_item("inputs", inputs).unwrap(); dict.set_item("outputs", outputs).unwrap(); dict.set_item("max_lookup_inputs", self.max_lookup_inputs) .unwrap(); dict.set_item("min_lookup_inputs", self.min_lookup_inputs) .unwrap(); dict.set_item("max_range_size", self.max_range_size) .unwrap(); if let Some(processed_inputs) = &self.processed_inputs { //poseidon_hash if let Some(processed_inputs_poseidon_hash) = &processed_inputs.poseidon_hash { insert_poseidon_hash_pydict(dict_inputs, processed_inputs_poseidon_hash).unwrap(); } if let Some(processed_inputs_polycommit) = &processed_inputs.polycommit { insert_polycommit_pydict(dict_inputs, processed_inputs_polycommit).unwrap(); } dict.set_item("processed_inputs", dict_inputs).unwrap(); } if let Some(processed_params) = &self.processed_params { if let Some(processed_params_poseidon_hash) = &processed_params.poseidon_hash { insert_poseidon_hash_pydict(dict_params, processed_params_poseidon_hash).unwrap(); } if let Some(processed_params_polycommit) = &processed_params.polycommit { insert_polycommit_pydict(dict_inputs, processed_params_polycommit).unwrap(); } dict.set_item("processed_params", dict_params).unwrap(); } if let Some(processed_outputs) = &self.processed_outputs { if let Some(processed_outputs_poseidon_hash) = &processed_outputs.poseidon_hash { insert_poseidon_hash_pydict(dict_outputs, processed_outputs_poseidon_hash).unwrap(); } if let Some(processed_outputs_polycommit) = &processed_outputs.polycommit { insert_polycommit_pydict(dict_inputs, processed_outputs_polycommit).unwrap(); } dict.set_item("processed_outputs", dict_outputs).unwrap(); } dict.to_object(py) } } #[cfg(feature = "python-bindings")] fn insert_poseidon_hash_pydict(pydict: &PyDict, poseidon_hash: &Vec<Fp>) -> Result<(), PyErr> { let poseidon_hash: Vec<String> = poseidon_hash.iter().map(field_to_string).collect(); pydict.set_item("poseidon_hash", poseidon_hash)?; Ok(()) } #[cfg(feature = "python-bindings")] fn insert_polycommit_pydict(pydict: &PyDict, commits: &Vec<Vec<G1Affine>>) -> Result<(), PyErr> { use crate::python::PyG1Affine; let poseidon_hash: Vec<Vec<PyG1Affine>> = commits .iter() .map(|c| c.iter().map(|x| PyG1Affine::from(*x)).collect()) .collect(); pydict.set_item("polycommit", poseidon_hash)?; Ok(()) } /// model parameters #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct GraphSettings { /// run args pub run_args: RunArgs, /// the potential number of rows used by the circuit pub num_rows: usize, /// total linear coordinate of assignments pub total_assignments: usize, /// total const size pub total_const_size: usize, /// total dynamic column size pub total_dynamic_col_size: usize, /// number of dynamic lookups pub num_dynamic_lookups: usize, /// number of shuffles pub num_shuffles: usize, /// total shuffle column size pub total_shuffle_col_size: usize, /// the shape of public inputs to the model (in order of appearance) pub model_instance_shapes: Vec<Vec<usize>>, /// model output scales pub model_output_scales: Vec<crate::Scale>, /// model input scales pub model_input_scales: Vec<crate::Scale>, /// the of instance cells used by modules pub module_sizes: ModuleSizes, /// required_lookups pub required_lookups: Vec<LookupOp>, /// required range_checks pub required_range_checks: Vec<Range>, /// check mode pub check_mode: CheckMode, /// ezkl version used pub version: String, /// num blinding factors pub num_blinding_factors: Option<usize>, /// unix time timestamp pub timestamp: Option<u128>, } impl GraphSettings { /// Calc the number of rows required for lookup tables pub fn lookup_log_rows(&self) -> u32 { ((self.run_args.lookup_range.1 - self.run_args.lookup_range.0) as f32) .log2() .ceil() as u32 } /// Calc the number of rows required for lookup tables pub fn lookup_log_rows_with_blinding(&self) -> u32 { ((self.run_args.lookup_range.1 - self.run_args.lookup_range.0) as f32 + RESERVED_BLINDING_ROWS as f32) .log2() .ceil() as u32 } fn model_constraint_logrows_with_blinding(&self) -> u32 { (self.num_rows as f64 + RESERVED_BLINDING_ROWS as f64) .log2() .ceil() as u32 } fn dynamic_lookup_and_shuffle_logrows(&self) -> u32 { (self.total_dynamic_col_size as f64 + self.total_shuffle_col_size as f64) .log2() .ceil() as u32 } /// calculate the number of rows required for the dynamic lookup and shuffle pub fn dynamic_lookup_and_shuffle_logrows_with_blinding(&self) -> u32 { (self.total_dynamic_col_size as f64 + self.total_shuffle_col_size as f64 + RESERVED_BLINDING_ROWS as f64) .log2() .ceil() as u32 } fn dynamic_lookup_and_shuffle_col_size(&self) -> usize { self.total_dynamic_col_size + self.total_shuffle_col_size } /// calculate the number of rows required for the module constraints pub fn module_constraint_logrows(&self) -> u32 { (self.module_sizes.max_constraints() as f64).log2().ceil() as u32 } /// calculate the number of rows required for the module constraints pub fn module_constraint_logrows_with_blinding(&self) -> u32 { (self.module_sizes.max_constraints() as f64 + RESERVED_BLINDING_ROWS as f64) .log2() .ceil() as u32 } fn constants_logrows(&self) -> u32 { (self.total_const_size as f64 / self.run_args.num_inner_cols as f64) .log2() .ceil() as u32 } /// calculate the total number of instances pub fn total_instances(&self) -> Vec<usize> { let mut instances: Vec<usize> = self .model_instance_shapes .iter() .map(|x| x.iter().product()) .collect(); instances.extend(self.module_sizes.num_instances()); instances } /// calculate the log2 of the total number of instances pub fn log2_total_instances(&self) -> u32 { let sum = self.total_instances().iter().sum::<usize>(); // max between 1 and the log2 of the sums std::cmp::max((sum as f64).log2().ceil() as u32, 1) } /// calculate the log2 of the total number of instances pub fn log2_total_instances_with_blinding(&self) -> u32 { let sum = self.total_instances().iter().sum::<usize>() + RESERVED_BLINDING_ROWS; // max between 1 and the log2 of the sums std::cmp::max((sum as f64).log2().ceil() as u32, 1) } /// save params to file pub fn save(&self, path: &std::path::PathBuf) -> Result<(), std::io::Error> { // buf writer let writer = std::io::BufWriter::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::create(path)?); serde_json::to_writer(writer, &self).map_err(|e| { error!("failed to save settings file at {}", e); std::io::Error::new(std::io::ErrorKind::Other, e) }) } /// load params from file pub fn load(path: &std::path::PathBuf) -> Result<Self, std::io::Error> { // buf reader let reader = std::io::BufReader::with_capacity(*EZKL_BUF_CAPACITY, std::fs::File::open(path)?); serde_json::from_reader(reader).map_err(|e| { error!("failed to load settings file at {}", e); std::io::Error::new(std::io::ErrorKind::Other, e) }) } /// Export the ezkl configuration as json pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> { let serialized = match serde_json::to_string(&self) { Ok(s) => s, Err(e) => { return Err(Box::new(e)); } }; Ok(serialized) } /// Parse an ezkl configuration from a json pub fn from_json(arg_json: &str) -> Result<Self, serde_json::Error> { serde_json::from_str(arg_json) } fn set_num_blinding_factors(&mut self, num_blinding_factors: usize) { self.num_blinding_factors = Some(num_blinding_factors); } /// pub fn available_col_size(&self) -> usize { let base = 2u32; if let Some(num_blinding_factors) = self.num_blinding_factors { base.pow(self.run_args.logrows) as usize - num_blinding_factors - 1 } else { log::error!("num_blinding_factors not set"); log::warn!("using default available_col_size"); base.pow(self.run_args.logrows) as usize - ASSUMED_BLINDING_FACTORS - 1 } } /// pub fn uses_modules(&self) -> bool { !self.module_sizes.max_constraints() > 0 } /// if any visibility is encrypted or hashed pub fn module_requires_fixed(&self) -> bool { self.run_args.input_visibility.is_hashed() || self.run_args.output_visibility.is_hashed() || self.run_args.param_visibility.is_hashed() } /// requires dynamic lookup pub fn requires_dynamic_lookup(&self) -> bool { self.num_dynamic_lookups > 0 } /// requires dynamic shuffle pub fn requires_shuffle(&self) -> bool { self.num_shuffles > 0 } /// any kzg visibility pub fn module_requires_polycommit(&self) -> bool { self.run_args.input_visibility.is_polycommit() || self.run_args.output_visibility.is_polycommit() || self.run_args.param_visibility.is_polycommit() } } /// Configuration for a computational graph / model loaded from a `.onnx` file. #[derive(Clone, Debug)] pub struct GraphConfig { model_config: ModelConfig, module_configs: ModuleConfigs, circuit_size: CircuitSize, } /// Defines the circuit for a computational graph / model loaded from a `.onnx` file. #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct CoreCircuit { /// The model / graph of computations. pub model: Model, /// The settings of the model. pub settings: GraphSettings, } /// Defines the circuit for a computational graph / model loaded from a `.onnx` file. #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct GraphCircuit { /// Core circuit pub core: CoreCircuit, /// The witness data for the model. pub graph_witness: GraphWitness, } impl GraphCircuit { /// Settings for the graph pub fn settings(&self) -> &GraphSettings { &self.core.settings } /// Settings for the graph (mutable) pub fn settings_mut(&mut self) -> &mut GraphSettings { &mut self.core.settings } /// The model pub fn model(&self) -> &Model { &self.core.model } /// pub fn save(&self, path: std::path::PathBuf) -> Result<(), Box<dyn std::error::Error>> { let f = std::fs::File::create(path)?; let writer = std::io::BufWriter::with_capacity(*EZKL_BUF_CAPACITY, f); bincode::serialize_into(writer, &self)?; Ok(()) } /// pub fn load(path: std::path::PathBuf) -> Result<Self, Box<dyn std::error::Error>> { // read bytes from file let f = std::fs::File::open(path)?; let reader = std::io::BufReader::with_capacity(*EZKL_BUF_CAPACITY, f); let result: GraphCircuit = bincode::deserialize_from(reader)?; Ok(result) } } #[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, PartialOrd)] /// The data source for a test pub enum TestDataSource { /// The data is loaded from a file File, /// The data is loaded from the chain #[default] OnChain, } impl std::fmt::Display for TestDataSource { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { TestDataSource::File => write!(f, "file"), TestDataSource::OnChain => write!(f, "on-chain"), } } } impl ToFlags for TestDataSource {} impl From<String> for TestDataSource { fn from(value: String) -> Self { match value.to_lowercase().as_str() { "file" => TestDataSource::File, "on-chain" => TestDataSource::OnChain, _ => { error!("invalid data source: {}", value); warn!("using default data source: on-chain"); TestDataSource::default() } } } } #[derive(Clone, Debug, Default)] /// pub struct TestSources { /// pub input: TestDataSource, /// pub output: TestDataSource, } /// #[derive(Clone, Debug, Default)] pub struct TestOnChainData { /// The path to the test witness pub data: std::path::PathBuf, /// rpc endpoint pub rpc: Option<String>, /// pub data_sources: TestSources, } impl GraphCircuit { /// pub fn new( model: Model, run_args: &RunArgs, ) -> Result<GraphCircuit, Box<dyn std::error::Error>> { // // placeholder dummy inputs - must call prepare_public_inputs to load data afterwards let mut inputs: Vec<Vec<Fp>> = vec![]; for shape in model.graph.input_shapes()? { let t: Vec<Fp> = vec![Fp::zero(); shape.iter().product::<usize>()]; inputs.push(t); } // dummy module settings, must load from GraphData after let mut settings = model.gen_params(run_args, run_args.check_mode)?; let mut num_params = 0; if !model.const_shapes().is_empty() { for shape in model.const_shapes() { num_params += shape.iter().product::<usize>(); } } let sizes = GraphModules::num_constraints_and_instances( model.graph.input_shapes()?, vec![vec![num_params]], model.graph.output_shapes()?, VarVisibility::from_args(run_args)?, ); // number of instances used by modules settings.module_sizes = sizes.clone(); // as they occupy independent rows settings.num_rows = std::cmp::max(settings.num_rows, sizes.max_constraints()); let core = CoreCircuit { model, settings: settings.clone(), }; Ok(GraphCircuit { core, graph_witness: GraphWitness::new(inputs, vec![]), }) } /// pub fn new_from_settings( model: Model, mut settings: GraphSettings, check_mode: CheckMode, ) -> Result<GraphCircuit, Box<dyn std::error::Error>> { // placeholder dummy inputs - must call prepare_public_inputs to load data afterwards let mut inputs: Vec<Vec<Fp>> = vec![]; for shape in model.graph.input_shapes()? { let t: Vec<Fp> = vec![Fp::zero(); shape.iter().product::<usize>()]; inputs.push(t); } // dummy module settings, must load from GraphData after settings.check_mode = check_mode; let core = CoreCircuit { model, settings: settings.clone(), }; Ok(GraphCircuit { core, graph_witness: GraphWitness::new(inputs, vec![]), }) } /// load inputs and outputs for the model pub fn load_graph_witness( &mut self, data: &GraphWitness, ) -> Result<(), Box<dyn std::error::Error>> { self.graph_witness = data.clone(); // load the module settings Ok(()) } /// Prepare the public inputs for the circuit. pub fn prepare_public_inputs( &self, data: &GraphWitness, ) -> Result<Vec<Fp>, Box<dyn std::error::Error>> { // the ordering here is important, we want the inputs to come before the outputs // as they are configured in that order as Column<Instances> let mut public_inputs: Vec<Fp> = vec![]; if self.settings().run_args.input_visibility.is_public() { public_inputs.extend(self.graph_witness.inputs.clone().into_iter().flatten()) } else if let Some(processed_inputs) = &data.processed_inputs { public_inputs.extend(processed_inputs.get_instances().into_iter().flatten()); } if let Some(processed_params) = &data.processed_params { public_inputs.extend(processed_params.get_instances().into_iter().flatten()); } if self.settings().run_args.output_visibility.is_public() { public_inputs.extend(self.graph_witness.outputs.clone().into_iter().flatten()); } else if let Some(processed_outputs) = &data.processed_outputs { public_inputs.extend(processed_outputs.get_instances().into_iter().flatten()); } if public_inputs.len() < 11 { debug!("public inputs: {:?}", public_inputs); } else { debug!("public inputs: {:?} ...", &public_inputs[0..10]); } Ok(public_inputs) } /// get rescaled public inputs as floating points for the circuit. pub fn pretty_public_inputs( &self, data: &GraphWitness, ) -> Result<Option<PrettyElements>, Box<dyn std::error::Error>> { // dequantize the supplied data using the provided scale. // the ordering here is important, we want the inputs to come before the outputs // as they are configured in that order as Column<Instances> if data.pretty_elements.is_none() { warn!("no rescaled elements found in witness data"); return Ok(None); } let mut public_inputs = PrettyElements::default(); let elements = data.pretty_elements.as_ref().unwrap(); if self.settings().run_args.input_visibility.is_public() { public_inputs.rescaled_inputs = elements.rescaled_inputs.clone(); public_inputs.inputs = elements.inputs.clone(); } else if data.processed_inputs.is_some() { public_inputs.processed_inputs = elements.processed_inputs.clone(); } if data.processed_params.is_some() { public_inputs.processed_params = elements.processed_params.clone(); } if self.settings().run_args.output_visibility.is_public() { public_inputs.rescaled_outputs = elements.rescaled_outputs.clone(); public_inputs.outputs = elements.outputs.clone(); } else if data.processed_outputs.is_some() { public_inputs.processed_outputs = elements.processed_outputs.clone(); } #[cfg(not(target_arch = "wasm32"))] debug!( "rescaled and processed public inputs: {}", serde_json::to_string(&public_inputs)?.to_colored_json_auto()? ); Ok(Some(public_inputs)) } /// #[cfg(target_arch = "wasm32")] pub fn load_graph_input( &mut self, data: &GraphData, ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { let shapes = self.model().graph.input_shapes()?; let scales = self.model().graph.get_input_scales(); let input_types = self.model().graph.get_input_types()?; self.process_data_source(&data.input_data, shapes, scales, input_types) } /// pub fn load_graph_from_file_exclusively( &mut self, data: &GraphData, ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { let shapes = self.model().graph.input_shapes()?; let scales = self.model().graph.get_input_scales(); let input_types = self.model().graph.get_input_types()?; debug!("input scales: {:?}", scales); match &data.input_data { DataSource::File(file_data) => { self.load_file_data(file_data, &shapes, scales, input_types) } _ => Err("Cannot use non-file data source as input for this method.".into()), } } /// #[cfg(not(target_arch = "wasm32"))] pub fn load_graph_input( &mut self, data: &GraphData, ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { let shapes = self.model().graph.input_shapes()?; let scales = self.model().graph.get_input_scales(); let input_types = self.model().graph.get_input_types()?; debug!("input scales: {:?}", scales); self.process_data_source(&data.input_data, shapes, scales, input_types) } #[cfg(target_arch = "wasm32")] /// Process the data source for the model fn process_data_source( &mut self, data: &DataSource, shapes: Vec<Vec<usize>>, scales: Vec<crate::Scale>, input_types: Vec<InputType>, ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { match &data { DataSource::File(file_data) => { self.load_file_data(file_data, &shapes, scales, input_types) } DataSource::OnChain(_) => { Err("Cannot use on-chain data source as input for this method.".into()) } } } #[cfg(not(target_arch = "wasm32"))] /// Process the data source for the model fn process_data_source( &mut self, data: &DataSource, shapes: Vec<Vec<usize>>, scales: Vec<crate::Scale>, input_types: Vec<InputType>, ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { match &data { DataSource::OnChain(source) => { let mut per_item_scale = vec![]; for (i, shape) in shapes.iter().enumerate() { per_item_scale.extend(vec![scales[i]; shape.iter().product::<usize>()]); } // start runtime and fetch data let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() .build()?; runtime.block_on(async { self.load_on_chain_data(source.clone(), &shapes, per_item_scale) .await }) } DataSource::File(file_data) => { self.load_file_data(file_data, &shapes, scales, input_types) } DataSource::DB(pg) => { let data = pg.fetch_and_format_as_file()?; self.load_file_data(&data, &shapes, scales, input_types) } } } /// Prepare on chain test data #[cfg(not(target_arch = "wasm32"))] pub async fn load_on_chain_data( &mut self, source: OnChainSource, shapes: &Vec<Vec<usize>>, scales: Vec<crate::Scale>, ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { use crate::eth::{evm_quantize, read_on_chain_inputs, setup_eth_backend}; let (_, client) = setup_eth_backend(Some(&source.rpc), None).await?; let inputs = read_on_chain_inputs(client.clone(), client.address(), &source.calls).await?; // quantize the supplied data using the provided scale + QuantizeData.sol let quantized_evm_inputs = evm_quantize(client, scales, &inputs).await?; // on-chain data has already been quantized at this point. Just need to reshape it and push into tensor vector let mut inputs: Vec<Tensor<Fp>> = vec![]; for (input, shape) in [quantized_evm_inputs].iter().zip(shapes) { let mut t: Tensor<Fp> = input.iter().cloned().collect(); t.reshape(shape)?; inputs.push(t); } Ok(inputs) } /// pub fn load_file_data( &mut self, file_data: &FileSource, shapes: &Vec<Vec<usize>>, scales: Vec<crate::Scale>, input_types: Vec<InputType>, ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { // quantize the supplied data using the provided scale. let mut data: Vec<Tensor<Fp>> = vec![]; for (((d, shape), scale), input_type) in file_data .iter() .zip(shapes) .zip(scales) .zip(input_types.iter()) { let t: Vec<Fp> = d .par_iter() .map(|x| { let mut x = x.clone(); x.as_type(input_type); x.to_field(scale) }) .collect(); let mut t: Tensor<Fp> = t.into_iter().into(); t.reshape(shape)?; data.push(t); } Ok(data) } /// pub fn load_witness_file_data( &mut self, file_data: &[Vec<Fp>], shapes: &[Vec<usize>], ) -> Result<Vec<Tensor<Fp>>, Box<dyn std::error::Error>> { // quantize the supplied data using the provided scale. let mut data: Vec<Tensor<Fp>> = vec![]; for (d, shape) in file_data.iter().zip(shapes) { let mut t: Tensor<Fp> = d.clone().into_iter().into(); t.reshape(shape)?; data.push(t); } Ok(data) } fn calc_safe_lookup_range(min_max_lookup: Range, lookup_safety_margin: i128) -> Range { ( lookup_safety_margin * min_max_lookup.0, lookup_safety_margin * min_max_lookup.1, ) } fn calc_num_cols(range_len: i128, max_logrows: u32) -> usize { let max_col_size = Table::<Fp>::cal_col_size(max_logrows as usize, RESERVED_BLINDING_ROWS); num_cols_required(range_len, max_col_size) } fn table_size_logrows( &self, safe_lookup_range: Range, max_range_size: i128, ) -> Result<u32, Box<dyn std::error::Error>> { // pick the range with the largest absolute size safe_lookup_range or max_range_size let safe_range = std::cmp::max( (safe_lookup_range.1 - safe_lookup_range.0).abs(), max_range_size, ); let min_bits = (safe_range as f64 + RESERVED_BLINDING_ROWS as f64 + 1.) .log2() .ceil() as u32; Ok(min_bits) } /// calculate the minimum logrows required for the circuit pub fn calc_min_logrows( &mut self, min_max_lookup: Range, max_range_size: i128, max_logrows: Option<u32>, lookup_safety_margin: i128, ) -> Result<(), Box<dyn std::error::Error>> { // load the max logrows let max_logrows = max_logrows.unwrap_or(MAX_PUBLIC_SRS); let max_logrows = std::cmp::min(max_logrows, MAX_PUBLIC_SRS); let mut max_logrows = std::cmp::max(max_logrows, MIN_LOGROWS); let mut min_logrows = MIN_LOGROWS; let safe_lookup_range = Self::calc_safe_lookup_range(min_max_lookup, lookup_safety_margin); // check if has overflowed max lookup input if (min_max_lookup.1 - min_max_lookup.0).abs() > MAX_LOOKUP_ABS / lookup_safety_margin { let err_string = format!("max lookup input {:?} is too large", min_max_lookup); return Err(err_string.into()); } if max_range_size.abs() > MAX_LOOKUP_ABS { let err_string = format!("max range check size {:?} is too large", max_range_size); return Err(err_string.into()); } // These are hard lower limits, we can't overflow instances or modules constraints let instance_logrows = self.settings().log2_total_instances(); let module_constraint_logrows = self.settings().module_constraint_logrows(); let dynamic_lookup_logrows = self.settings().dynamic_lookup_and_shuffle_logrows(); min_logrows = std::cmp::max( min_logrows, // max of the instance logrows and the module constraint logrows and the dynamic lookup logrows is the lower limit *[ instance_logrows, module_constraint_logrows, dynamic_lookup_logrows, ] .iter() .max() .unwrap(), ); // These are upper limits, going above these is wasteful, but they are not hard limits let model_constraint_logrows = self.settings().model_constraint_logrows_with_blinding(); let min_bits = self.table_size_logrows(safe_lookup_range, max_range_size)?; let constants_logrows = self.settings().constants_logrows(); max_logrows = std::cmp::min( max_logrows, // max of the model constraint logrows, min_bits, and the constants logrows is the upper limit *[model_constraint_logrows, min_bits, constants_logrows] .iter() .max() .unwrap(), ); // we now have a min and max logrows max_logrows = std::cmp::max(min_logrows, max_logrows); // degrade the max logrows until the extended k is small enough while min_logrows < max_logrows && !self.extended_k_is_small_enough(max_logrows, safe_lookup_range, max_range_size) { max_logrows -= 1; } if !self.extended_k_is_small_enough(max_logrows, safe_lookup_range, max_range_size) { let err_string = format!( "extended k is too large to accommodate the quotient polynomial with logrows {}", max_logrows ); debug!("{}", err_string); return Err(err_string.into()); } let logrows = max_logrows; let model = self.model().clone(); let settings_mut = self.settings_mut(); settings_mut.run_args.lookup_range = safe_lookup_range; settings_mut.run_args.logrows = logrows; *settings_mut = GraphCircuit::new(model, &settings_mut.run_args)? .settings() .clone(); debug!( "setting lookup_range to: {:?}, setting logrows to: {}", self.settings().run_args.lookup_range, self.settings().run_args.logrows ); Ok(()) } fn extended_k_is_small_enough( &self, k: u32, safe_lookup_range: Range, max_range_size: i128, ) -> bool { // if num cols is too large then the extended k is too large if Self::calc_num_cols(safe_lookup_range.1 - safe_lookup_range.0, k) > MAX_NUM_LOOKUP_COLS || Self::calc_num_cols(max_range_size, k) > MAX_NUM_LOOKUP_COLS { return false; } let mut settings = self.settings().clone(); settings.run_args.lookup_range = safe_lookup_range; settings.run_args.logrows = k; settings.required_range_checks = vec![(0, max_range_size)]; let mut cs = ConstraintSystem::default(); // if unix get a gag #[cfg(unix)] let _r = match Gag::stdout() { Ok(g) => Some(g), _ => None, }; #[cfg(unix)] let _g = match Gag::stderr() { Ok(g) => Some(g), _ => None, }; Self::configure_with_params(&mut cs, settings); // drop the gag #[cfg(unix)] drop(_r); #[cfg(unix)] drop(_g); #[cfg(feature = "mv-lookup")] let cs = cs.chunk_lookups(); // quotient_poly_degree * params.n - 1 is the degree of the quotient polynomial let max_degree = cs.degree(); let quotient_poly_degree = (max_degree - 1) as u64; // n = 2^k let n = 1u64 << k; let mut extended_k = k; while (1 << extended_k) < (n * quotient_poly_degree) { extended_k += 1; if extended_k > bn256::Fr::S { return false; } } true } /// Runs the forward pass of the model / graph of computations and any associated hashing. pub fn forward<Scheme: CommitmentScheme<Scalar = Fp, Curve = G1Affine>>( &self, inputs: &mut [Tensor<Fp>], vk: Option<&VerifyingKey<G1Affine>>, srs: Option<&Scheme::ParamsProver>, witness_gen: bool, ) -> Result<GraphWitness, Box<dyn std::error::Error>> { let original_inputs = inputs.to_vec(); let visibility = VarVisibility::from_args(&self.settings().run_args)?; let mut processed_inputs = None; let mut processed_params = None; let mut processed_outputs = None; if visibility.input.requires_processing() { let module_outlets = visibility.input.overwrites_inputs(); if !module_outlets.is_empty() { let mut module_inputs = vec![]; for outlet in &module_outlets { module_inputs.push(inputs[*outlet].clone()); } let res = GraphModules::forward::<Scheme>(&module_inputs, &visibility.input, vk, srs)?; processed_inputs = Some(res.clone()); let module_results = res.get_result(visibility.input.clone()); for (i, outlet) in module_outlets.iter().enumerate() { inputs[*outlet] = Tensor::from(module_results[i].clone().into_iter()); } } else { processed_inputs = Some(GraphModules::forward::<Scheme>( inputs, &visibility.input, vk, srs, )?); } } if visibility.params.requires_processing() { let params = self.model().get_all_params(); if !params.is_empty() { let flattened_params = Tensor::new(Some(&params), &[params.len()])?.combine()?; processed_params = Some(GraphModules::forward::<Scheme>( &[flattened_params], &visibility.params, vk, srs, )?); } } let mut model_results = self.model() .forward(inputs, &self.settings().run_args, witness_gen)?; if visibility.output.requires_processing() { let module_outlets = visibility.output.overwrites_inputs(); if !module_outlets.is_empty() { let mut module_inputs = vec![]; for outlet in &module_outlets { module_inputs.push(model_results.outputs[*outlet].clone()); } let res = GraphModules::forward::<Scheme>(&module_inputs, &visibility.output, vk, srs)?; processed_outputs = Some(res.clone()); let module_results = res.get_result(visibility.output.clone()); for (i, outlet) in module_outlets.iter().enumerate() { model_results.outputs[*outlet] = Tensor::from(module_results[i].clone().into_iter()); } } else { processed_outputs = Some(GraphModules::forward::<Scheme>( &model_results.outputs, &visibility.output, vk, srs, )?); } } let mut witness = GraphWitness { inputs: original_inputs .iter() .map(|t| t.deref().to_vec()) .collect_vec(), pretty_elements: None, outputs: model_results .outputs .iter() .map(|t| t.deref().to_vec()) .collect_vec(), processed_inputs, processed_params, processed_outputs, max_lookup_inputs: model_results.max_lookup_inputs, min_lookup_inputs: model_results.min_lookup_inputs, max_range_size: model_results.max_range_size, }; witness.generate_rescaled_elements( self.model().graph.get_input_scales(), self.model().graph.get_output_scales()?, visibility, ); #[cfg(not(target_arch = "wasm32"))] log::trace!( "witness: \n {}", &witness.as_json()?.to_colored_json_auto()? ); Ok(witness) } /// Create a new circuit from a set of input data and [RunArgs]. #[cfg(not(target_arch = "wasm32"))] pub fn from_run_args( run_args: &RunArgs, model_path: &std::path::Path, ) -> Result<Self, Box<dyn std::error::Error>> { let model = Model::from_run_args(run_args, model_path)?; Self::new(model, run_args) } /// Create a new circuit from a set of input data and [GraphSettings]. #[cfg(not(target_arch = "wasm32"))] pub fn from_settings( params: &GraphSettings, model_path: &std::path::Path, check_mode: CheckMode, ) -> Result<Self, Box<dyn std::error::Error>> { params.run_args.validate()?; let model = Model::from_run_args(&params.run_args, model_path)?; Self::new_from_settings(model, params.clone(), check_mode) } /// #[cfg(not(target_arch = "wasm32"))] pub async fn populate_on_chain_test_data( &mut self, data: &mut GraphData, test_on_chain_data: TestOnChainData, ) -> Result<(), Box<dyn std::error::Error>> { // Set up local anvil instance for reading on-chain data let input_scales = self.model().graph.get_input_scales(); let output_scales = self.model().graph.get_output_scales()?; let input_shapes = self.model().graph.input_shapes()?; let output_shapes = self.model().graph.output_shapes()?; if matches!( test_on_chain_data.data_sources.input, TestDataSource::OnChain ) { // if not public then fail if self.settings().run_args.input_visibility.is_private() { return Err("Cannot use on-chain data source as private data".into()); } let input_data = match &data.input_data { DataSource::File(input_data) => input_data, _ => { return Err("Cannot use non file source as input for on-chain test. Manually populate on-chain data from file source instead" .into()) } }; // Get the flatten length of input_data // if the input source is a field then set scale to 0 let datam: (Vec<Tensor<Fp>>, OnChainSource) = OnChainSource::test_from_file_data( input_data, input_scales, input_shapes, test_on_chain_data.rpc.as_deref(), ) .await?; data.input_data = datam.1.into(); } if matches!( test_on_chain_data.data_sources.output, TestDataSource::OnChain ) { // if not public then fail if self.settings().run_args.output_visibility.is_private() { return Err("Cannot use on-chain data source as private data".into()); } let output_data = match &data.output_data { Some(DataSource::File(output_data)) => output_data, Some(DataSource::OnChain(_)) => { return Err( "Cannot use on-chain data source as output for on-chain test. Will manually populate on-chain data from file source instead" .into(), ) } _ => return Err("No output data found".into()), }; let datum: (Vec<Tensor<Fp>>, OnChainSource) = OnChainSource::test_from_file_data( output_data, output_scales, output_shapes, test_on_chain_data.rpc.as_deref(), ) .await?; data.output_data = Some(datum.1.into()); } // Save the updated GraphData struct to the data_path data.save(test_on_chain_data.data)?; Ok(()) } } #[derive(Clone, Debug, Default, Serialize, Deserialize)] /// The configuration for the graph circuit pub struct CircuitSize { num_instances: usize, num_advice_columns: usize, num_fixed: usize, num_challenges: usize, num_selectors: usize, logrows: u32, } impl CircuitSize { /// pub fn from_cs<F: Field>(cs: &ConstraintSystem<F>, logrows: u32) -> Self { CircuitSize { num_instances: cs.num_instance_columns(), num_advice_columns: cs.num_advice_columns(), num_fixed: cs.num_fixed_columns(), num_challenges: cs.num_challenges(), num_selectors: cs.num_selectors(), logrows, } } #[cfg(not(target_arch = "wasm32"))] /// Export the ezkl configuration as json pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> { let serialized = match serde_json::to_string(&self) { Ok(s) => s, Err(e) => { return Err(Box::new(e)); } }; Ok(serialized) } /// number of columns pub fn num_columns(&self) -> usize { self.num_instances + self.num_advice_columns + self.num_fixed } /// area of the circuit pub fn area(&self) -> usize { self.num_columns() * (1 << self.logrows) } /// area less than max pub fn area_less_than_max(&self) -> bool { if EZKL_MAX_CIRCUIT_AREA.is_some() { self.area() < EZKL_MAX_CIRCUIT_AREA.unwrap() } else { true } } } impl Circuit<Fp> for GraphCircuit { type Config = GraphConfig; type FloorPlanner = ModulePlanner; type Params = GraphSettings; fn without_witnesses(&self) -> Self { self.clone() } fn params(&self) -> Self::Params { // safe to clone because the model is Arc'd self.settings().clone() } fn configure_with_params(cs: &mut ConstraintSystem<Fp>, params: Self::Params) -> Self::Config { let mut params = params.clone(); params.set_num_blinding_factors(cs.blinding_factors()); GLOBAL_SETTINGS.with(|settings| { *settings.borrow_mut() = Some(params.clone()); }); let visibility = match VarVisibility::from_args(&params.run_args) { Ok(v) => v, Err(e) => { log::error!("failed to create visibility: {:?}", e); log::warn!("using default visibility"); VarVisibility::default() } }; let mut module_configs = ModuleConfigs::from_visibility( cs, params.module_sizes.clone(), params.run_args.logrows as usize, ); let mut vars = ModelVars::new(cs, &params); module_configs.configure_complex_modules(cs, visibility, params.module_sizes.clone()); vars.instantiate_instance( cs, params.model_instance_shapes.clone(), params.run_args.input_scale, module_configs.instance, ); let base = Model::configure(cs, &vars, &params).unwrap(); let model_config = ModelConfig { base, vars }; debug!( "degree: {}, log2_ceil of degrees: {:?}", cs.degree(), (cs.degree() as f32).log2().ceil() ); let circuit_size = CircuitSize::from_cs(cs, params.run_args.logrows); #[cfg(not(target_arch = "wasm32"))] debug!( "circuit size: \n {}", circuit_size .as_json() .unwrap() .to_colored_json_auto() .unwrap() ); GraphConfig { model_config, module_configs, circuit_size, } } fn configure(_: &mut ConstraintSystem<Fp>) -> Self::Config { unimplemented!("you should call configure_with_params instead") } fn synthesize( &self, config: Self::Config, mut layouter: impl Layouter<Fp>, ) -> Result<(), PlonkError> { // check if the circuit area is less than the max if !config.circuit_size.area_less_than_max() { error!( "circuit area {} is larger than the max allowed area {}", config.circuit_size.area(), EZKL_MAX_CIRCUIT_AREA.unwrap() ); return Err(PlonkError::Synthesis); } trace!("Setting input in synthesize"); let input_vis = &self.settings().run_args.input_visibility; let output_vis = &self.settings().run_args.output_visibility; let mut graph_modules = GraphModules::new(); let mut constants = ConstantsMap::new(); let mut config = config.clone(); let mut inputs = self .graph_witness .get_input_tensor() .iter_mut() .map(|i| { i.set_visibility(input_vis); ValTensor::try_from(i.clone()).map_err(|e| { log::error!("failed to convert input to valtensor: {:?}", e); PlonkError::Synthesis }) }) .collect::<Result<Vec<ValTensor<Fp>>, PlonkError>>()?; let outputs = self .graph_witness .get_output_tensor() .iter_mut() .map(|i| { i.set_visibility(output_vis); ValTensor::try_from(i.clone()).map_err(|e| { log::error!("failed to convert output to valtensor: {:?}", e); PlonkError::Synthesis }) }) .collect::<Result<Vec<ValTensor<Fp>>, PlonkError>>()?; let mut instance_offset = 0; trace!("running input module layout"); let input_visibility = &self.settings().run_args.input_visibility; let outlets = input_visibility.overwrites_inputs(); if !outlets.is_empty() { let mut input_outlets = vec![]; for outlet in &outlets { input_outlets.push(inputs[*outlet].clone()); } graph_modules.layout( &mut layouter, &mut config.module_configs, &mut input_outlets, input_visibility, &mut instance_offset, &mut constants, )?; // replace inputs with the outlets for (i, outlet) in outlets.iter().enumerate() { inputs[*outlet] = input_outlets[i].clone(); } } else { graph_modules.layout( &mut layouter, &mut config.module_configs, &mut inputs, input_visibility, &mut instance_offset, &mut constants, )?; } // now we need to assign the flattened params to the model let mut model = self.model().clone(); let param_visibility = &self.settings().run_args.param_visibility; trace!("running params module layout"); if !self.model().get_all_params().is_empty() && param_visibility.requires_processing() { // now we need to flatten the params let consts = self.model().get_all_params(); let mut flattened_params = { let mut t = Tensor::new(Some(&consts), &[consts.len()]) .map_err(|_| { log::error!("failed to flatten params"); PlonkError::Synthesis })? .combine() .map_err(|_| { log::error!("failed to combine params"); PlonkError::Synthesis })?; t.set_visibility(param_visibility); vec![t.try_into().map_err(|_| { log::error!("failed to convert params to valtensor"); PlonkError::Synthesis })?] }; // now do stuff to the model params graph_modules.layout( &mut layouter, &mut config.module_configs, &mut flattened_params, param_visibility, &mut instance_offset, &mut constants, )?; let shapes = self.model().const_shapes(); trace!("replacing processed consts"); let split_params = split_valtensor(&flattened_params[0], shapes).map_err(|_| { log::error!("failed to split params"); PlonkError::Synthesis })?; // now the flattened_params have been assigned to and we-assign them to the model consts such that they are constrained to be equal model.replace_consts(&split_params); } // create a new module for the model (space 2) layouter.assign_region(|| "_enter_module_2", |_| Ok(()))?; trace!("laying out model"); let mut vars = config.model_config.vars.clone(); vars.set_initial_instance_offset(instance_offset); let mut outputs = model .layout( config.model_config.clone(), &mut layouter, &self.settings().run_args, &inputs, &mut vars, &outputs, &mut constants, ) .map_err(|e| { log::error!("{}", e); PlonkError::Synthesis })?; trace!("running output module layout"); let output_visibility = &self.settings().run_args.output_visibility; let outlets = output_visibility.overwrites_inputs(); instance_offset += vars.get_instance_len(); if !outlets.is_empty() { let mut output_outlets = vec![]; for outlet in &outlets { output_outlets.push(outputs[*outlet].clone()); } // this will re-enter module 0 graph_modules.layout( &mut layouter, &mut config.module_configs, &mut output_outlets, &self.settings().run_args.output_visibility, &mut instance_offset, &mut constants, )?; // replace outputs with the outlets for (i, outlet) in outlets.iter().enumerate() { outputs[*outlet] = output_outlets[i].clone(); } } else { graph_modules.layout( &mut layouter, &mut config.module_configs, &mut outputs, &self.settings().run_args.output_visibility, &mut instance_offset, &mut constants, )?; } Ok(()) } }
https://github.com/zkonduit/ezkl
src/graph/model.rs
use super::extract_const_quantized_values; use super::node::*; use super::scale_to_multiplier; use super::vars::*; use super::GraphError; use super::GraphSettings; use crate::circuit::hybrid::HybridOp; use crate::circuit::region::ConstantsMap; use crate::circuit::region::RegionCtx; use crate::circuit::table::Range; use crate::circuit::Input; use crate::circuit::InputType; use crate::circuit::Unknown; use crate::tensor::ValType; use crate::{ circuit::{lookup::LookupOp, BaseConfig as PolyConfig, CheckMode, Op}, tensor::{Tensor, ValTensor}, RunArgs, }; use halo2curves::bn256::Fr as Fp; #[cfg(not(target_arch = "wasm32"))] use super::input::GraphData; #[cfg(not(target_arch = "wasm32"))] use colored::Colorize; use halo2_proofs::{ circuit::{Layouter, Value}, plonk::ConstraintSystem, }; use halo2curves::ff::Field; use itertools::Itertools; use log::error; use log::{debug, info, trace}; use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; #[cfg(not(target_arch = "wasm32"))] use std::collections::HashMap; use std::collections::HashSet; use std::error::Error; use std::fs; use std::io::Read; use std::path::PathBuf; #[cfg(not(target_arch = "wasm32"))] use tabled::Table; #[cfg(not(target_arch = "wasm32"))] use tract_onnx; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::prelude::{ Framework, Graph, InferenceFact, InferenceModelExt, SymbolValues, TypedFact, TypedOp, }; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::tract_core::internal::DatumType; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::tract_hir::ops::scan::Scan; use unzip_n::unzip_n; unzip_n!(pub 3); #[cfg(not(target_arch = "wasm32"))] type TractResult = (Graph<TypedFact, Box<dyn TypedOp>>, SymbolValues); /// The result of a forward pass. #[derive(Clone, Debug)] pub struct ForwardResult { /// The outputs of the forward pass. pub outputs: Vec<Tensor<Fp>>, /// The maximum value of any input to a lookup operation. pub max_lookup_inputs: i128, /// The minimum value of any input to a lookup operation. pub min_lookup_inputs: i128, /// The max range check size pub max_range_size: i128, } impl From<DummyPassRes> for ForwardResult { fn from(res: DummyPassRes) -> Self { Self { outputs: res.outputs, max_lookup_inputs: res.max_lookup_inputs, min_lookup_inputs: res.min_lookup_inputs, max_range_size: res.max_range_size, } } } /// A circuit configuration for the entirety of a model loaded from an Onnx file. #[derive(Clone, Debug)] pub struct ModelConfig { /// The base configuration for the circuit pub base: PolyConfig<Fp>, /// A wrapper for holding all columns that will be assigned to by the model pub vars: ModelVars<Fp>, } /// Representation of execution graph pub type NodeGraph = BTreeMap<usize, NodeType>; /// A struct for loading from an Onnx file and converting a computational graph to a circuit. #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct DummyPassRes { /// number of rows use pub num_rows: usize, /// num dynamic lookups pub num_dynamic_lookups: usize, /// dynamic lookup col size pub dynamic_lookup_col_coord: usize, /// num shuffles pub num_shuffles: usize, /// shuffle pub shuffle_col_coord: usize, /// linear coordinate pub linear_coord: usize, /// total const size pub total_const_size: usize, /// lookup ops pub lookup_ops: HashSet<LookupOp>, /// range checks pub range_checks: HashSet<Range>, /// max lookup inputs pub max_lookup_inputs: i128, /// min lookup inputs pub min_lookup_inputs: i128, /// min range check pub max_range_size: i128, /// outputs pub outputs: Vec<Tensor<Fp>>, } /// A struct for loading from an Onnx file and converting a computational graph to a circuit. #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] pub struct Model { /// input indices pub graph: ParsedNodes, /// Defines which inputs to the model are public and private (params, inputs, outputs) using [VarVisibility]. pub visibility: VarVisibility, } /// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub enum OutputMapping { /// Single { /// outlet: usize, /// is_state: bool, }, /// Stacked { /// outlet: usize, /// axis: usize, /// is_state: bool, }, } impl OutputMapping { /// pub fn is_state(&self) -> bool { match self { OutputMapping::Single { is_state, .. } => *is_state, OutputMapping::Stacked { is_state, .. } => *is_state, } } /// pub fn outlet(&self) -> usize { match self { OutputMapping::Single { outlet, .. } => *outlet, OutputMapping::Stacked { outlet, .. } => *outlet, } } } /// #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub enum InputMapping { /// Full, /// State, /// Stacked { /// axis: usize, /// chunk: usize, }, } fn number_of_iterations(mappings: &[InputMapping], dims: Vec<&[usize]>) -> usize { let mut number_of_iterations = dims.iter() .zip(mappings) .filter_map(|(dims, mapping)| match mapping { InputMapping::Stacked { axis, chunk } => Some( // number of iterations given the dim size along the axis // and the chunk size (dims[*axis] + chunk - 1) / chunk, ), _ => None, }); // assert all collected number of iterations are equal assert!(number_of_iterations.clone().all_equal()); number_of_iterations.next().unwrap_or(1) } fn input_state_idx(input_mappings: &[InputMapping]) -> Vec<usize> { input_mappings .iter() .enumerate() .filter(|(_, r)| matches!(r, InputMapping::State)) .map(|(index, _)| index) .collect::<Vec<_>>() } fn output_state_idx(output_mappings: &[Vec<OutputMapping>]) -> Vec<usize> { output_mappings .iter() .flatten() .filter_map(|x| if x.is_state() { Some(x.outlet()) } else { None }) .collect::<Vec<_>>() } /// Enables model as subnode of other models #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub enum NodeType { /// A node in the model Node(Node), /// A submodel SubGraph { /// The subgraph model: Model, /// The subgraph's inputs inputs: Vec<Outlet>, /// the subgraph's idx within the parent graph idx: usize, /// output mappings output_mappings: Vec<Vec<OutputMapping>>, /// input mappings input_mappings: Vec<InputMapping>, /// out_dims: Vec<Vec<usize>>, /// out_scales: Vec<crate::Scale>, }, } impl NodeType { /// pub fn is_lookup(&self) -> bool { match self { NodeType::Node(n) => n.opkind.is_lookup(), NodeType::SubGraph { .. } => false, } } /// pub fn num_uses(&self) -> usize { match self { NodeType::Node(n) => n.num_uses, NodeType::SubGraph { .. } => 0, } } /// Returns the indices of the node's inputs. pub fn inputs(&self) -> Vec<Outlet> { match self { NodeType::Node(n) => n.inputs.clone(), NodeType::SubGraph { inputs, .. } => inputs.clone(), } } /// Returns the dimensions of the node's output. pub fn out_dims(&self) -> Vec<Vec<usize>> { match self { NodeType::Node(n) => vec![n.out_dims.clone()], NodeType::SubGraph { out_dims, .. } => out_dims.clone(), } } /// Returns the scales of the node's output. pub fn out_scales(&self) -> Vec<crate::Scale> { match self { NodeType::Node(n) => vec![n.out_scale], NodeType::SubGraph { out_scales, .. } => out_scales.clone(), } } /// Returns a string representation of the operation. pub fn as_str(&self) -> String { match self { NodeType::Node(n) => n.opkind.as_string(), NodeType::SubGraph { .. } => "SUBGRAPH".into(), } } /// Returns true if the operation is a rebase pub fn is_rebase(&self) -> bool { match self { NodeType::Node(n) => matches!(n.opkind, SupportedOp::RebaseScale { .. }), NodeType::SubGraph { .. } => false, } } /// Returns true if the operation is an input. pub fn is_input(&self) -> bool { match self { NodeType::Node(n) => n.opkind.is_input(), NodeType::SubGraph { .. } => false, } } /// Returns true if the operation is a const. pub fn is_constant(&self) -> bool { match self { NodeType::Node(n) => n.opkind.is_constant(), NodeType::SubGraph { .. } => false, } } /// Returns the node's unique identifier. pub fn idx(&self) -> usize { match self { NodeType::Node(n) => n.idx, NodeType::SubGraph { idx, .. } => *idx, } } /// decrement const num times used pub fn decrement_use(&mut self) { match self { NodeType::Node(n) => n.num_uses -= 1, NodeType::SubGraph { .. } => log::warn!("Cannot decrement const of subgraph"), } } /// bunp scale of node pub fn bump_scale(&mut self, scale: crate::Scale) { match self { NodeType::Node(n) => n.out_scale = scale, NodeType::SubGraph { .. } => log::warn!("Cannot bump scale of subgraph"), } } /// Replace the operation kind of the node. pub fn replace_opkind(&mut self, opkind: SupportedOp) { match self { NodeType::Node(n) => n.opkind = opkind, NodeType::SubGraph { .. } => log::warn!("Cannot replace opkind of subgraph"), } } /// Returns the operation kind of the node (if any). pub fn opkind(&self) -> SupportedOp { match self { NodeType::Node(n) => n.opkind.clone(), NodeType::SubGraph { .. } => SupportedOp::Unknown(Unknown), } } } #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] /// A set of EZKL nodes that represent a computational graph. pub struct ParsedNodes { /// The nodes in the graph. pub nodes: BTreeMap<usize, NodeType>, inputs: Vec<usize>, outputs: Vec<Outlet>, } impl ParsedNodes { /// Returns the number of the computational graph's inputs pub fn num_inputs(&self) -> usize { let input_nodes = self.inputs.iter(); input_nodes.len() } /// Input types pub fn get_input_types(&self) -> Result<Vec<InputType>, GraphError> { self.inputs .iter() .map(|o| { match self .nodes .get(o) .ok_or(GraphError::MissingNode(*o))? .opkind() { SupportedOp::Input(Input { datum_type, .. }) => Ok(datum_type.clone()), _ => Err(GraphError::InvalidInputTypes), } }) .collect::<Result<Vec<_>, _>>() } /// Returns shapes of the computational graph's inputs pub fn input_shapes(&self) -> Result<Vec<Vec<usize>>, Box<dyn Error>> { let mut inputs = vec![]; for input in self.inputs.iter() { let node = self .nodes .get(input) .ok_or(GraphError::MissingNode(*input))?; let input_dims = node.out_dims(); let input_dim = input_dims.first().ok_or(GraphError::MissingNode(*input))?; inputs.push(input_dim.clone()); } Ok(inputs) } /// Returns the number of the computational graph's outputs pub fn num_outputs(&self) -> usize { let output_nodes = self.outputs.iter(); output_nodes.len() } /// Returns shapes of the computational graph's outputs pub fn output_shapes(&self) -> Result<Vec<Vec<usize>>, GraphError> { let mut outputs = vec![]; for output in self.outputs.iter() { let (idx, outlet) = output; let node = self.nodes.get(idx).ok_or(GraphError::MissingNode(*idx))?; let out_dims = node.out_dims(); let out_dim = out_dims .get(*outlet) .ok_or(GraphError::MissingNode(*outlet))?; outputs.push(out_dim.clone()); } Ok(outputs) } /// Returns the fixed point scale of the computational graph's inputs pub fn get_input_scales(&self) -> Vec<crate::Scale> { let input_nodes = self.inputs.iter(); input_nodes .flat_map(|idx| { self.nodes .get(idx) .ok_or(GraphError::MissingNode(*idx)) .map(|n| n.out_scales()) .unwrap_or_default() }) .collect() } /// Returns the fixed point scale of the computational graph's outputs pub fn get_output_scales(&self) -> Result<Vec<crate::Scale>, GraphError> { let output_nodes = self.outputs.iter(); output_nodes .map(|(idx, outlet)| { Ok(self .nodes .get(idx) .ok_or(GraphError::MissingNode(*idx))? .out_scales()[*outlet]) }) .collect::<Result<Vec<_>, GraphError>>() } } impl Model { /// Creates a `Model` from a specified path to an Onnx file. /// # Arguments /// * `reader` - A reader for an Onnx file. /// * `run_args` - [RunArgs] #[cfg(not(target_arch = "wasm32"))] pub fn new(reader: &mut dyn std::io::Read, run_args: &RunArgs) -> Result<Self, Box<dyn Error>> { let visibility = VarVisibility::from_args(run_args)?; let graph = Self::load_onnx_model(reader, run_args, &visibility)?; let om = Model { graph, visibility }; debug!("\n {}", om.table_nodes()); Ok(om) } /// pub fn save(&self, path: PathBuf) -> Result<(), Box<dyn Error>> { let f = std::fs::File::create(path)?; let writer = std::io::BufWriter::new(f); bincode::serialize_into(writer, &self)?; Ok(()) } /// pub fn load(path: PathBuf) -> Result<Self, Box<dyn Error>> { // read bytes from file let mut f = std::fs::File::open(&path)?; let metadata = fs::metadata(&path)?; let mut buffer = vec![0; metadata.len() as usize]; f.read_exact(&mut buffer)?; let result = bincode::deserialize(&buffer)?; Ok(result) } /// Generate model parameters for the circuit pub fn gen_params( &self, run_args: &RunArgs, check_mode: CheckMode, ) -> Result<GraphSettings, Box<dyn Error>> { let instance_shapes = self.instance_shapes()?; #[cfg(not(target_arch = "wasm32"))] debug!( "{} {} {}", "model has".blue(), instance_shapes.len().to_string().blue(), "instances".blue() ); let inputs: Vec<ValTensor<Fp>> = self .graph .input_shapes()? .iter() .map(|shape| { let len = shape.iter().product(); let mut t: ValTensor<Fp> = (0..len) .map(|_| { if !self.visibility.input.is_fixed() { ValType::Value(Value::<Fp>::unknown()) } else { ValType::Constant(Fp::random(&mut rand::thread_rng())) } }) .collect::<Vec<_>>() .into(); t.reshape(shape)?; Ok(t) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; let res = self.dummy_layout(run_args, &inputs, false)?; // if we're using percentage tolerance, we need to add the necessary range check ops for it. Ok(GraphSettings { run_args: run_args.clone(), model_instance_shapes: instance_shapes, module_sizes: crate::graph::modules::ModuleSizes::default(), num_rows: res.num_rows, total_assignments: res.linear_coord, required_lookups: res.lookup_ops.into_iter().collect(), required_range_checks: res.range_checks.into_iter().collect(), model_output_scales: self.graph.get_output_scales()?, model_input_scales: self.graph.get_input_scales(), num_dynamic_lookups: res.num_dynamic_lookups, total_dynamic_col_size: res.dynamic_lookup_col_coord, num_shuffles: res.num_shuffles, total_shuffle_col_size: res.shuffle_col_coord, total_const_size: res.total_const_size, check_mode, version: env!("CARGO_PKG_VERSION").to_string(), num_blinding_factors: None, // unix time timestamp #[cfg(not(target_arch = "wasm32"))] timestamp: Some( instant::SystemTime::now() .duration_since(instant::SystemTime::UNIX_EPOCH)? .as_millis(), ), #[cfg(target_arch = "wasm32")] timestamp: None, }) } /// Runs a forward pass on sample data ! /// # Arguments /// * `reader` - A reader for an Onnx file. /// * `model_inputs` - A vector of [Tensor]s to use as inputs to the model. /// * `run_args` - [RunArgs] pub fn forward( &self, model_inputs: &[Tensor<Fp>], run_args: &RunArgs, witness_gen: bool, ) -> Result<ForwardResult, Box<dyn Error>> { let valtensor_inputs: Vec<ValTensor<Fp>> = model_inputs .iter() .map(|x| x.map(|elem| ValType::Value(Value::known(elem))).into()) .collect(); let res = self.dummy_layout(run_args, &valtensor_inputs, witness_gen)?; Ok(res.into()) } /// Loads an Onnx model from a specified path. /// # Arguments /// * `reader` - A reader for an Onnx file. /// * `scale` - The scale to use for quantization. /// * `public_params` - Whether to make the params public. #[cfg(not(target_arch = "wasm32"))] fn load_onnx_using_tract( reader: &mut dyn std::io::Read, run_args: &RunArgs, ) -> Result<TractResult, Box<dyn Error>> { use tract_onnx::{ tract_core::internal::IntoArcTensor, tract_hir::internal::GenericFactoid, }; let mut model = tract_onnx::onnx().model_for_read(reader).map_err(|e| { error!("Error loading model: {}", e); GraphError::ModelLoad })?; let variables: std::collections::HashMap<String, usize> = std::collections::HashMap::from_iter(run_args.variables.clone()); for (i, id) in model.clone().inputs.iter().enumerate() { let input = model.node_mut(id.node); let mut fact: InferenceFact = input.outputs[0].fact.clone(); for (i, x) in fact.clone().shape.dims().enumerate() { if matches!(x, GenericFactoid::Any) { let batch_size = match variables.get("batch_size") { Some(x) => x, None => return Err("Unknown dimension batch_size in model inputs, set batch_size in variables".into()), }; fact.shape .set_dim(i, tract_onnx::prelude::TDim::Val(*batch_size as i64)); } } model.set_input_fact(i, fact)?; } for (i, _) in model.clone().outputs.iter().enumerate() { model.set_output_fact(i, InferenceFact::default())?; } let mut symbol_values = SymbolValues::default(); for (symbol, value) in run_args.variables.iter() { let symbol = model.symbol_table.sym(symbol); symbol_values = symbol_values.with(&symbol, *value as i64); debug!("set {} to {}", symbol, value); } // Note: do not optimize the model, as the layout will depend on underlying hardware let mut typed_model = model .into_typed()? .concretize_dims(&symbol_values)? .into_decluttered()?; // concretize constants for node in typed_model.eval_order()? { let node = typed_model.node_mut(node); if let Some(op) = node.op_as_mut::<tract_onnx::tract_core::ops::konst::Const>() { if op.0.datum_type() == DatumType::TDim { // get inner value to Arc<Tensor> let mut constant = op.0.as_ref().clone(); // Generally a shape or hyperparam constant .as_slice_mut::<tract_onnx::prelude::TDim>()? .iter_mut() .for_each(|x| *x = x.eval(&symbol_values)); op.0 = constant.into_arc_tensor(); } } } Ok((typed_model, symbol_values)) } /// Loads an Onnx model from a specified path. /// # Arguments /// * `reader` - A reader for an Onnx file. /// * `scale` - The scale to use for quantization. /// * `public_params` - Whether to make the params public. #[cfg(not(target_arch = "wasm32"))] fn load_onnx_model( reader: &mut dyn std::io::Read, run_args: &RunArgs, visibility: &VarVisibility, ) -> Result<ParsedNodes, Box<dyn Error>> { let start_time = instant::Instant::now(); let (model, symbol_values) = Self::load_onnx_using_tract(reader, run_args)?; let scales = VarScales::from_args(run_args)?; let nodes = Self::nodes_from_graph( &model, run_args, &scales, visibility, &symbol_values, None, None, )?; debug!("\n {}", model); let parsed_nodes = ParsedNodes { nodes, inputs: model.inputs.iter().map(|o| o.node).collect(), outputs: model.outputs.iter().map(|o| (o.node, o.slot)).collect(), }; let duration = start_time.elapsed(); trace!("model loading took: {:?}", duration); Ok(parsed_nodes) } /// Formats nodes (including subgraphs) into tables ! #[cfg(not(target_arch = "wasm32"))] pub fn table_nodes(&self) -> String { let mut node_accumulator = vec![]; let mut string = String::new(); for (idx, node) in &self.graph.nodes { match node { NodeType::Node(n) => { node_accumulator.push(n); } NodeType::SubGraph { model, inputs, .. } => { let mut table = Table::new(node_accumulator.iter()); table.with(tabled::settings::Style::modern()); table.with(tabled::settings::Shadow::new(1)); table.with( tabled::settings::style::BorderColor::default() .top(tabled::settings::Color::BG_YELLOW), ); string = format!("{} \n\n MAIN GRAPH \n\n{}", string, table); node_accumulator = vec![]; string = format!( "{}\n\n SUBGRAPH AT IDX {} WITH INPUTS {:?}\n{}", string, idx, inputs, model.table_nodes(), ); } } } let mut table = Table::new(node_accumulator.iter()); table.with(tabled::settings::Style::modern()); format!("{} \n{}", string, table) } /// Creates ezkl nodes from a tract graph /// # Arguments /// * `graph` - A tract graph. /// * `run_args` - [RunArgs] /// * `visibility` - Which inputs to the model are public and private (params, inputs, outputs) using [VarVisibility]. /// * `input_scales` - The scales of the model's inputs. #[cfg(not(target_arch = "wasm32"))] pub fn nodes_from_graph( graph: &Graph<TypedFact, Box<dyn TypedOp>>, run_args: &RunArgs, scales: &VarScales, visibility: &VarVisibility, symbol_values: &SymbolValues, override_input_scales: Option<Vec<crate::Scale>>, override_output_scales: Option<HashMap<usize, crate::Scale>>, ) -> Result<BTreeMap<usize, NodeType>, Box<dyn Error>> { use crate::graph::node_output_shapes; let mut nodes = BTreeMap::<usize, NodeType>::new(); let mut input_idx = 0; for (i, n) in graph.nodes.iter().enumerate() { // Extract the slope layer hyperparams match n.op().downcast_ref::<Scan>() { Some(b) => { let model = b.body.clone(); let input_scales = n .inputs .iter() .map(|i| { Ok(nodes .get(&i.node) .ok_or(GraphError::MissingNode(i.node))? .out_scales()[0]) }) .collect::<Result<Vec<_>, GraphError>>()?; let mut input_mappings = vec![]; for mapping in &b.input_mapping { match mapping { tract_onnx::tract_hir::ops::scan::InputMapping::Scan(info) => { input_mappings.push(InputMapping::Stacked { axis: info.axis, chunk: info.chunk as usize, }); } tract_onnx::tract_hir::ops::scan::InputMapping::State => { input_mappings.push(InputMapping::State); } tract_onnx::tract_hir::ops::scan::InputMapping::Full => { input_mappings.push(InputMapping::Full); } } } let input_state_idx = input_state_idx(&input_mappings); let mut output_mappings = vec![]; for (i, mapping) in b.output_mapping.iter().enumerate() { let mut mappings = vec![]; if let Some(outlet) = mapping.last_value_slot { mappings.push(OutputMapping::Single { outlet, is_state: mapping.state, }); } else if mapping.state { mappings.push(OutputMapping::Single { outlet: i, is_state: mapping.state, }); } if let Some(last) = mapping.scan { mappings.push(OutputMapping::Stacked { outlet: last.0, axis: last.1.axis, is_state: false, }); } output_mappings.push(mappings); } let output_state_idx = output_state_idx(&output_mappings); let mut output_scale_override = HashMap::new(); // if input_state_idx and output_state_idx have mismatched scales we need to rebase the scale of the output node for (input_idx, output_idx) in input_state_idx.iter().zip(output_state_idx) { let input_scale = input_scales[*input_idx]; // output mappings is a vec of vec. we need to find the outer index of the output node we want to rebase. let mut traversed_len = 0; for (outer_idx, mappings) in output_mappings.iter().enumerate() { let mapping_len = mappings.len(); if traversed_len + mapping_len > output_idx { let output_node_idx = b.body.outputs[outer_idx].node; output_scale_override.insert(output_node_idx, input_scale); } traversed_len += mapping_len; } } let subgraph_nodes = Self::nodes_from_graph( &model, run_args, scales, visibility, symbol_values, Some(input_scales.clone()), Some(output_scale_override), )?; let subgraph = ParsedNodes { nodes: subgraph_nodes, inputs: model.inputs.iter().map(|o| o.node).collect(), outputs: model.outputs.iter().map(|o| (o.node, o.slot)).collect(), }; let om = Model { graph: subgraph, visibility: visibility.clone(), }; let out_dims = node_output_shapes(n, symbol_values)?; let mut output_scales = BTreeMap::new(); for (i, _mapping) in b.output_mapping.iter().enumerate() { for mapping in b.output_mapping.iter() { if let Some(outlet) = mapping.last_value_slot { output_scales.insert(outlet, om.graph.get_output_scales()?[i]); } if let Some(last) = mapping.scan { output_scales.insert(last.0, om.graph.get_output_scales()?[i]); } } } let out_scales = output_scales.into_values().collect_vec(); nodes.insert( i, NodeType::SubGraph { model: om, inputs: n.inputs.iter().map(|i| (i.node, i.slot)).collect_vec(), idx: i, output_mappings, input_mappings, out_dims, out_scales, }, ); } None => { let mut n = Node::new( n.clone(), &mut nodes, scales, &run_args.param_visibility, i, symbol_values, run_args.div_rebasing, run_args.rebase_frac_zero_constants, )?; if let Some(ref scales) = override_input_scales { if let Some(inp) = n.opkind.get_input() { let scale = scales[input_idx]; n.opkind = SupportedOp::Input(Input { scale, datum_type: inp.datum_type, }); input_idx += 1; n.out_scale = scale; } } if let Some(ref scales) = override_output_scales { if scales.contains_key(&i) { let scale_diff = n.out_scale - scales[&i]; n.opkind = if scale_diff > 0 { RebaseScale::rebase( n.opkind, scales[&i], n.out_scale, 1, run_args.div_rebasing, ) } else { RebaseScale::rebase_up( n.opkind, scales[&i], n.out_scale, run_args.div_rebasing, ) }; n.out_scale = scales[&i]; } } nodes.insert(i, NodeType::Node(n)); } } } Self::remove_unused_nodes(&mut nodes); Ok(nodes) } #[cfg(not(target_arch = "wasm32"))] /// Removes all nodes that are consts with 0 uses fn remove_unused_nodes(nodes: &mut BTreeMap<usize, NodeType>) { // remove all nodes that are consts with 0 uses now nodes.retain(|_, n| match n { NodeType::Node(n) => match &mut n.opkind { SupportedOp::Constant(c) => { c.empty_raw_value(); n.num_uses > 0 } _ => n.num_uses > 0, }, NodeType::SubGraph { model, .. } => { Self::remove_unused_nodes(&mut model.graph.nodes); true } }); } #[cfg(not(target_arch = "wasm32"))] /// Run tract onnx model on sample data ! pub fn run_onnx_predictions( run_args: &RunArgs, model_path: &std::path::Path, data_chunks: &[GraphData], input_shapes: Vec<Vec<usize>>, ) -> Result<Vec<Vec<Tensor<f32>>>, Box<dyn Error>> { use tract_onnx::tract_core::internal::IntoArcTensor; let (model, _) = Model::load_onnx_using_tract( &mut std::fs::File::open(model_path) .map_err(|_| format!("failed to load {}", model_path.display()))?, run_args, )?; let datum_types: Vec<DatumType> = model .input_outlets()? .iter() .map(|o| model.node(o.node).outputs[o.slot].fact.datum_type) .collect(); let runnable_model = model.into_runnable()?; let mut outputs = vec![]; for chunk in data_chunks { let result = runnable_model.run(chunk.to_tract_data(&input_shapes, &datum_types)?)?; outputs.push( result .into_iter() .map(|t| { crate::graph::utilities::extract_tensor_value(t.into_arc_tensor()).unwrap() }) .collect(), ); } Ok(outputs) } /// Creates a `Model` from parsed run_args /// # Arguments /// * `params` - A [GraphSettings] struct holding parsed CLI arguments. #[cfg(not(target_arch = "wasm32"))] pub fn from_run_args( run_args: &RunArgs, model: &std::path::Path, ) -> Result<Self, Box<dyn Error>> { Model::new( &mut std::fs::File::open(model) .map_err(|_| format!("failed to load {}", model.display()))?, run_args, ) } /// Configures a model for the circuit /// # Arguments /// * `meta` - The constraint system. /// * `vars` - The variables for the circuit. /// * `settings` - [GraphSettings] pub fn configure( meta: &mut ConstraintSystem<Fp>, vars: &ModelVars<Fp>, settings: &GraphSettings, ) -> Result<PolyConfig<Fp>, Box<dyn Error>> { debug!("configuring model"); let lookup_range = settings.run_args.lookup_range; let logrows = settings.run_args.logrows as usize; let required_lookups = settings.required_lookups.clone(); let required_range_checks = settings.required_range_checks.clone(); let mut base_gate = PolyConfig::configure( meta, vars.advices[0..2].try_into()?, &vars.advices[2], settings.check_mode, ); // set scale for HybridOp::RangeCheck and call self.conf_lookup on that op for percentage tolerance case let input = &vars.advices[0]; let output = &vars.advices[2]; let index = &vars.advices[1]; for op in required_lookups { base_gate.configure_lookup(meta, input, output, index, lookup_range, logrows, &op)?; } for range in required_range_checks { base_gate.configure_range_check(meta, input, index, range, logrows)?; } if settings.requires_dynamic_lookup() { base_gate.configure_dynamic_lookup( meta, vars.advices[0..3].try_into()?, vars.advices[3..6].try_into()?, )?; } if settings.requires_shuffle() { base_gate.configure_shuffles( meta, vars.advices[0..2].try_into()?, vars.advices[3..5].try_into()?, )?; } Ok(base_gate) } /// Assigns values to the regions created when calling `configure`. /// # Arguments /// * `config` - [ModelConfig] holding all node configs. /// * `layouter` - Halo2 Layouter. /// * `inputs` - The values to feed into the circuit. /// * `vars` - The variables for the circuit. /// * `witnessed_outputs` - The values to compare against. /// * `constants` - The constants for the circuit. pub fn layout( &self, mut config: ModelConfig, layouter: &mut impl Layouter<Fp>, run_args: &RunArgs, inputs: &[ValTensor<Fp>], vars: &mut ModelVars<Fp>, witnessed_outputs: &[ValTensor<Fp>], constants: &mut ConstantsMap<Fp>, ) -> Result<Vec<ValTensor<Fp>>, Box<dyn Error>> { info!("model layout..."); let start_time = instant::Instant::now(); let mut results = BTreeMap::<usize, Vec<ValTensor<Fp>>>::new(); let input_shapes = self.graph.input_shapes()?; for (i, input_idx) in self.graph.inputs.iter().enumerate() { if self.visibility.input.is_public() { let instance = vars.instance.as_ref().ok_or("no instance")?.clone(); results.insert(*input_idx, vec![instance]); vars.increment_instance_idx(); } else { let mut input = inputs[i].clone(); input.reshape(&input_shapes[i])?; results.insert(*input_idx, vec![input]); } } let instance_idx = vars.get_instance_idx(); config.base.layout_tables(layouter)?; config.base.layout_range_checks(layouter)?; let original_constants = constants.clone(); let outputs = layouter.assign_region( || "model", |region| { let mut thread_safe_region = RegionCtx::new_with_constants(region, 0, run_args.num_inner_cols, original_constants.clone()); // we need to do this as this loop is called multiple times vars.set_instance_idx(instance_idx); let outputs = self .layout_nodes(&mut config, &mut thread_safe_region, &mut results) .map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis })?; if run_args.output_visibility.is_public() || run_args.output_visibility.is_fixed() { let output_scales = self.graph.get_output_scales().map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis })?; let res = outputs .iter() .enumerate() .map(|(i, output)| { let mut tolerance = run_args.tolerance; tolerance.scale = scale_to_multiplier(output_scales[i]).into(); let comparators = if run_args.output_visibility == Visibility::Public { let res = vars.instance.as_ref().ok_or("no instance")?.clone(); vars.increment_instance_idx(); res } else { // if witnessed_outputs is of len less than i error if witnessed_outputs.len() <= i { return Err("you provided insufficient witness values to generate a fixed output".into()); } witnessed_outputs[i].clone() }; config.base.layout( &mut thread_safe_region, &[output.clone(), comparators], Box::new(HybridOp::RangeCheck(tolerance)), ) }) .collect::<Result<Vec<_>,_>>(); res.map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis })?; } // Then number of columns in the circuits #[cfg(not(target_arch = "wasm32"))] thread_safe_region.debug_report(); *constants = thread_safe_region.assigned_constants().clone(); Ok(outputs) }, )?; let duration = start_time.elapsed(); trace!("model layout took: {:?}", duration); Ok(outputs) } fn layout_nodes( &self, config: &mut ModelConfig, region: &mut RegionCtx<Fp>, results: &mut BTreeMap<usize, Vec<ValTensor<Fp>>>, ) -> Result<Vec<ValTensor<Fp>>, Box<dyn Error>> { // index over results to get original inputs let orig_inputs: BTreeMap<usize, _> = results .clone() .into_iter() .filter(|(idx, _)| self.graph.inputs.contains(idx)) .collect(); for (idx, node) in self.graph.nodes.iter() { debug!("laying out {}: {}", idx, node.as_str(),); // Then number of columns in the circuits #[cfg(not(target_arch = "wasm32"))] region.debug_report(); debug!("input indices: {:?}", node.inputs()); debug!("output scales: {:?}", node.out_scales()); debug!( "input scales: {:?}", node.inputs() .iter() .map(|(idx, outlet)| self.graph.nodes[idx].out_scales()[*outlet]) .collect_vec() ); let mut values: Vec<ValTensor<Fp>> = if !node.is_input() { node.inputs() .iter() .map(|(idx, outlet)| { Ok(results.get(idx).ok_or(GraphError::MissingResults)?[*outlet].clone()) }) .collect::<Result<Vec<_>, GraphError>>()? } else { // we re-assign inputs, always from the 0 outlet vec![results.get(idx).ok_or(GraphError::MissingResults)?[0].clone()] }; debug!("output dims: {:?}", node.out_dims()); debug!( "input dims {:?}", values.iter().map(|v| v.dims()).collect_vec() ); match &node { NodeType::Node(n) => { let res = if node.is_constant() && node.num_uses() == 1 { log::debug!("node {} is a constant with 1 use", n.idx); let mut node = n.clone(); let c = node.opkind.get_mutable_constant().ok_or("no constant")?; Some(c.quantized_values.clone().try_into()?) } else { config .base .layout(region, &values, n.opkind.clone_dyn()) .map_err(|e| { error!("{}", e); halo2_proofs::plonk::Error::Synthesis })? }; if let Some(mut vt) = res { vt.reshape(&node.out_dims()[0])?; // we get the max as for fused nodes this corresponds to the node output results.insert(*idx, vec![vt.clone()]); //only use with mock prover debug!("------------ output node {:?}: {:?}", idx, vt.show()); } } NodeType::SubGraph { model, inputs, output_mappings, input_mappings, .. } => { let original_values = values.clone(); let input_mappings = input_mappings.clone(); let input_dims = values.iter().map(|inp| inp.dims()); let num_iter = number_of_iterations(&input_mappings, input_dims.collect()); debug!( "{} iteration(s) in a subgraph with inputs {:?}, sources {:?}, and outputs {:?}", num_iter, inputs, model.graph.inputs, model.graph.outputs ); let mut full_results: Vec<ValTensor<Fp>> = vec![]; for i in 0..num_iter { debug!(" -------------- subgraph iteration: {}", i); // replace the Stacked input with the current chunk iter for ((mapping, inp), og_inp) in input_mappings.iter().zip(&mut values).zip(&original_values) { if let InputMapping::Stacked { axis, chunk } = mapping { let start = i * chunk; let end = (i + 1) * chunk; let mut sliced_input = og_inp.clone(); sliced_input.slice(axis, &start, &end)?; *inp = sliced_input; } } let mut subgraph_results = BTreeMap::from_iter( model .graph .inputs .clone() .into_iter() .zip(values.clone().into_iter().map(|v| vec![v])), ); let res = model.layout_nodes(config, region, &mut subgraph_results)?; let mut outlets = BTreeMap::new(); let mut stacked_outlets = BTreeMap::new(); for (mappings, outlet_res) in output_mappings.iter().zip(res) { for mapping in mappings { match mapping { OutputMapping::Single { outlet, .. } => { outlets.insert(outlet, outlet_res.clone()); } OutputMapping::Stacked { outlet, axis, .. } => { if !full_results.is_empty() { let stacked_res = full_results[*outlet] .clone() .concat_axis(outlet_res.clone(), axis)?; stacked_outlets.insert(outlet, stacked_res); } outlets.insert(outlet, outlet_res.clone()); } } } } // now extend with stacked elements let mut pre_stacked_outlets = outlets.clone(); pre_stacked_outlets.extend(stacked_outlets); let outlets = outlets.into_values().collect_vec(); full_results = pre_stacked_outlets.into_values().collect_vec(); let output_states = output_state_idx(output_mappings); let input_states = input_state_idx(&input_mappings); assert_eq!( input_states.len(), output_states.len(), "input and output states must be the same length, got {:?} and {:?}", input_mappings, output_mappings ); for (input_idx, output_idx) in input_states.iter().zip(output_states) { assert_eq!( values[*input_idx].dims(), outlets[output_idx].dims(), "input and output dims must be the same, got {:?} and {:?}", values[*input_idx].dims(), outlets[output_idx].dims() ); values[*input_idx] = outlets[output_idx].clone(); } } //only use with mock prover trace!( "------------ output subgraph node {:?}: {:?}", idx, full_results.iter().map(|x| x.show()).collect_vec() ); results.insert(*idx, full_results); } } } // we do this so we can support multiple passes of the same model and have deterministic results (Non-assigned inputs etc... etc...) results.extend(orig_inputs); let output_nodes = self.graph.outputs.iter(); debug!( "model outputs are nodes: {:?}", output_nodes.clone().collect_vec() ); let outputs = output_nodes .map(|(idx, outlet)| { Ok(results.get(idx).ok_or(GraphError::MissingResults)?[*outlet].clone()) }) .collect::<Result<Vec<_>, GraphError>>()?; Ok(outputs) } /// Assigns dummy values to the regions created when calling `configure`. /// # Arguments /// * `input_shapes` - The shapes of the inputs to the model. pub fn dummy_layout( &self, run_args: &RunArgs, inputs: &[ValTensor<Fp>], witness_gen: bool, ) -> Result<DummyPassRes, Box<dyn Error>> { debug!("calculating num of constraints using dummy model layout..."); let start_time = instant::Instant::now(); let mut results = BTreeMap::<usize, Vec<ValTensor<Fp>>>::new(); for (i, input_idx) in self.graph.inputs.iter().enumerate() { results.insert(*input_idx, vec![inputs[i].clone()]); } let mut dummy_config = PolyConfig::dummy(run_args.logrows as usize, run_args.num_inner_cols); let mut model_config = ModelConfig { base: dummy_config.clone(), vars: ModelVars::new_dummy(), }; let mut region = RegionCtx::new_dummy(0, run_args.num_inner_cols, witness_gen); let outputs = self.layout_nodes(&mut model_config, &mut region, &mut results)?; if self.visibility.output.is_public() || self.visibility.output.is_fixed() { let output_scales = self.graph.get_output_scales()?; let res = outputs .iter() .enumerate() .map(|(i, output)| { let mut comparator: ValTensor<Fp> = (0..output.len()) .map(|_| { if !self.visibility.output.is_fixed() { ValType::Value(Value::<Fp>::unknown()) } else { ValType::Constant(Fp::random(&mut rand::thread_rng())) } }) .collect::<Vec<_>>() .into(); comparator.reshape(output.dims())?; let mut tolerance = run_args.tolerance; tolerance.scale = scale_to_multiplier(output_scales[i]).into(); dummy_config.layout( &mut region, &[output.clone(), comparator], Box::new(HybridOp::RangeCheck(tolerance)), ) }) .collect::<Result<Vec<_>, _>>(); res?; } else if !self.visibility.output.is_private() { for output in &outputs { region.update_constants(output.create_constants_map()); } } let duration = start_time.elapsed(); trace!("dummy model layout took: {:?}", duration); // Then number of columns in the circuits #[cfg(not(target_arch = "wasm32"))] region.debug_report(); let outputs = outputs .iter() .map(|x| { x.get_felt_evals() .unwrap_or(Tensor::new(Some(&[Fp::ZERO]), &[1]).unwrap()) }) .collect(); let res = DummyPassRes { num_rows: region.row(), linear_coord: region.linear_coord(), total_const_size: region.total_constants(), lookup_ops: region.used_lookups(), range_checks: region.used_range_checks(), max_lookup_inputs: region.max_lookup_inputs(), min_lookup_inputs: region.min_lookup_inputs(), max_range_size: region.max_range_size(), num_dynamic_lookups: region.dynamic_lookup_index(), dynamic_lookup_col_coord: region.dynamic_lookup_col_coord(), num_shuffles: region.shuffle_index(), shuffle_col_coord: region.shuffle_col_coord(), outputs, }; Ok(res) } /// Retrieves all constants from the model. pub fn get_all_params(&self) -> Vec<Tensor<Fp>> { let mut params = vec![]; for node in self.graph.nodes.values() { match node { NodeType::Node(_) => { if let Some(constant) = extract_const_quantized_values(node.opkind()) { params.push(constant); } } NodeType::SubGraph { model, .. } => { params.extend(model.get_all_params()); } } } params } /// Shapes of the computational graph's constants pub fn const_shapes(&self) -> Vec<Vec<usize>> { let mut const_shapes = vec![]; for node in self.graph.nodes.values() { match node { NodeType::Node(_) => { if let Some(constant) = extract_const_quantized_values(node.opkind()) { const_shapes.push(constant.dims().to_vec()); }; } NodeType::SubGraph { model, .. } => { const_shapes.extend(model.const_shapes()); } } } const_shapes } /// Replaces all constants in the model with the provided values (in order of indexing), returns the number of consts pub fn replace_consts(&mut self, consts: &[ValTensor<Fp>]) -> usize { let mut const_idx = 0; for node in self.graph.nodes.values_mut() { match node { NodeType::Node(n) => { if let SupportedOp::Constant(c) = &n.opkind { let mut op = crate::circuit::Constant::new( c.quantized_values.clone(), c.raw_values.clone(), ); op.pre_assign(consts[const_idx].clone()); n.opkind = SupportedOp::Constant(op); const_idx += 1; } } NodeType::SubGraph { model, .. } => { let total_consts = model.replace_consts(&consts[const_idx..]); const_idx += total_consts; } } } const_idx } /// Shapes of the computational graph's public inputs (if any) pub fn instance_shapes(&self) -> Result<Vec<Vec<usize>>, Box<dyn Error>> { let mut instance_shapes = vec![]; if self.visibility.input.is_public() { instance_shapes.extend(self.graph.input_shapes()?); } if self.visibility.output.is_public() { instance_shapes.extend(self.graph.output_shapes()?); } Ok(instance_shapes) } }
https://github.com/zkonduit/ezkl
src/graph/modules.rs
use crate::circuit::modules::polycommit::{PolyCommitChip, PolyCommitConfig}; use crate::circuit::modules::poseidon::spec::{PoseidonSpec, POSEIDON_RATE, POSEIDON_WIDTH}; use crate::circuit::modules::poseidon::{PoseidonChip, PoseidonConfig}; use crate::circuit::modules::Module; use crate::circuit::region::ConstantsMap; use crate::tensor::{Tensor, ValTensor}; use halo2_proofs::circuit::Layouter; use halo2_proofs::plonk::{Column, ConstraintSystem, Error, Instance, VerifyingKey}; use halo2_proofs::poly::commitment::CommitmentScheme; use halo2curves::bn256::{Fr as Fp, G1Affine}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use super::{VarVisibility, Visibility}; /// poseidon len to hash in tree pub const POSEIDON_LEN_GRAPH: usize = 32; /// Poseidon number of instancess pub const POSEIDON_INSTANCES: usize = 1; /// Poseidon module type pub type ModulePoseidon = PoseidonChip<PoseidonSpec, POSEIDON_WIDTH, POSEIDON_RATE, POSEIDON_LEN_GRAPH>; /// Poseidon module config pub type ModulePoseidonConfig = PoseidonConfig<POSEIDON_WIDTH, POSEIDON_RATE>; /// #[derive(Clone, Debug, Default)] pub struct ModuleConfigs { /// PolyCommit polycommit: Vec<PolyCommitConfig>, /// Poseidon poseidon: Option<ModulePoseidonConfig>, /// Instance pub instance: Option<Column<Instance>>, } impl ModuleConfigs { /// Create new module configs from visibility of each variable pub fn from_visibility( cs: &mut ConstraintSystem<Fp>, module_size: ModuleSizes, logrows: usize, ) -> Self { let mut config = Self::default(); for size in module_size.polycommit { config .polycommit .push(PolyCommitChip::configure(cs, (logrows, size))); } config } /// Configure the modules pub fn configure_complex_modules( &mut self, cs: &mut ConstraintSystem<Fp>, visibility: VarVisibility, module_size: ModuleSizes, ) { if (visibility.input.is_hashed() || visibility.output.is_hashed() || visibility.params.is_hashed()) && module_size.poseidon.1[0] > 0 { if visibility.input.is_hashed_public() || visibility.output.is_hashed_public() || visibility.params.is_hashed_public() { if let Some(inst) = self.instance { self.poseidon = Some(ModulePoseidon::configure_with_optional_instance( cs, Some(inst), )); } else { let poseidon = ModulePoseidon::configure(cs, ()); self.instance = poseidon.instance; self.poseidon = Some(poseidon); } } else if visibility.input.is_hashed_private() || visibility.output.is_hashed_private() || visibility.params.is_hashed_private() { self.poseidon = Some(ModulePoseidon::configure_with_optional_instance(cs, None)); } }; } } /// Result from a forward pass #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct ModuleForwardResult { /// The inputs of the forward pass for poseidon pub poseidon_hash: Option<Vec<Fp>>, /// The outputs of the forward pass for PolyCommit pub polycommit: Option<Vec<Vec<G1Affine>>>, } impl ModuleForwardResult { /// Get the result pub fn get_result(&self, vis: Visibility) -> Vec<Vec<Fp>> { if vis.is_hashed() { self.poseidon_hash .clone() .unwrap() .into_iter() .map(|x| vec![x]) .collect() } else { vec![] } } /// get instances pub fn get_instances(&self) -> Vec<Vec<Fp>> { if let Some(poseidon) = &self.poseidon_hash { poseidon.iter().map(|x| vec![*x]).collect() } else { vec![] } } } #[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)] /// pub struct ModuleSizes { polycommit: Vec<usize>, poseidon: (usize, Vec<usize>), } impl ModuleSizes { /// Create new module sizes pub fn new() -> Self { ModuleSizes { polycommit: vec![], poseidon: ( 0, vec![0; crate::circuit::modules::poseidon::NUM_INSTANCE_COLUMNS], ), } } /// Get the number of constraints pub fn max_constraints(&self) -> usize { self.poseidon.0 } /// Get the number of instances pub fn num_instances(&self) -> Vec<usize> { // concat self.poseidon.1.clone() } } /// Graph modules that can process inputs, params and outputs beyond the basic operations #[derive(Clone, Debug, Default, Serialize, Deserialize)] pub struct GraphModules { polycommit_idx: usize, } impl GraphModules { /// pub fn new() -> GraphModules { GraphModules { polycommit_idx: 0 } } /// pub fn reset_index(&mut self) { self.polycommit_idx = 0; } } impl GraphModules { fn num_constraint_given_shapes( visibility: Visibility, shapes: Vec<Vec<usize>>, sizes: &mut ModuleSizes, ) { for shape in shapes { let total_len = shape.iter().product::<usize>(); if total_len > 0 { if visibility.is_polycommit() { // 1 constraint for each polycommit commitment sizes.polycommit.push(total_len); } else if visibility.is_hashed() { sizes.poseidon.0 += ModulePoseidon::num_rows(total_len); // 1 constraints for hash sizes.poseidon.1[0] += 1; } } } } /// Get the number of constraints and instances for the module pub fn num_constraints_and_instances( input_shapes: Vec<Vec<usize>>, params_shapes: Vec<Vec<usize>>, output_shapes: Vec<Vec<usize>>, visibility: VarVisibility, ) -> ModuleSizes { let mut module_sizes = ModuleSizes::new(); Self::num_constraint_given_shapes(visibility.input, input_shapes, &mut module_sizes); Self::num_constraint_given_shapes(visibility.params, params_shapes, &mut module_sizes); Self::num_constraint_given_shapes(visibility.output, output_shapes, &mut module_sizes); module_sizes } /// Layout the module fn layout_module( module: &impl Module<Fp>, layouter: &mut impl Layouter<Fp>, x: &mut Vec<ValTensor<Fp>>, instance_offset: &mut usize, constants: &mut ConstantsMap<Fp>, ) -> Result<(), Error> { // reserve module 0 for ... modules // hash the input and replace the constrained cells in the input let cloned_x = (*x).clone(); x[0] = module .layout(layouter, &cloned_x, instance_offset.to_owned(), constants) .unwrap(); for inc in module.instance_increment_input().iter() { // increment the instance offset to make way for future module layouts *instance_offset += inc; } Ok(()) } /// Layout the module pub fn layout( &mut self, layouter: &mut impl Layouter<Fp>, configs: &mut ModuleConfigs, values: &mut [ValTensor<Fp>], element_visibility: &Visibility, instance_offset: &mut usize, constants: &mut ConstantsMap<Fp>, ) -> Result<(), Error> { if element_visibility.is_polycommit() && !values.is_empty() { // concat values and sk to get the inputs let mut inputs = values.iter_mut().map(|x| vec![x.clone()]).collect_vec(); // layout the module inputs.iter_mut().for_each(|x| { // create the module let chip = PolyCommitChip::new(configs.polycommit[self.polycommit_idx].clone()); // reserve module 2 onwards for polycommit modules let module_offset = 3 + self.polycommit_idx; layouter .assign_region(|| format!("_enter_module_{}", module_offset), |_| Ok(())) .unwrap(); Self::layout_module(&chip, layouter, x, instance_offset, constants).unwrap(); // increment the current index self.polycommit_idx += 1; }); // replace the inputs with the outputs values.iter_mut().enumerate().for_each(|(i, x)| { x.clone_from(&inputs[i][0]); }); } // If the module is hashed, then we need to hash the inputs if element_visibility.is_hashed() && !values.is_empty() { if let Some(config) = &mut configs.poseidon { // reserve module 0 for poseidon modules layouter.assign_region(|| "_enter_module_0", |_| Ok(()))?; // create the module let chip = ModulePoseidon::new(config.clone()); // concat values and sk to get the inputs let mut inputs = values.iter_mut().map(|x| vec![x.clone()]).collect_vec(); // layout the module inputs.iter_mut().for_each(|x| { Self::layout_module(&chip, layouter, x, instance_offset, constants).unwrap(); }); // replace the inputs with the outputs values.iter_mut().enumerate().for_each(|(i, x)| { x.clone_from(&inputs[i][0]); }); } else { log::error!("Poseidon config not initialized"); return Err(Error::Synthesis); } // If the module is encrypted, then we need to encrypt the inputs } Ok(()) } /// Run forward pass pub fn forward<Scheme: CommitmentScheme<Scalar = Fp, Curve = G1Affine>>( inputs: &[Tensor<Scheme::Scalar>], element_visibility: &Visibility, vk: Option<&VerifyingKey<G1Affine>>, srs: Option<&Scheme::ParamsProver>, ) -> Result<ModuleForwardResult, Box<dyn std::error::Error>> { let mut poseidon_hash = None; let mut polycommit = None; if element_visibility.is_hashed() { let field_elements = inputs.iter().fold(vec![], |mut acc, x| { let res = ModulePoseidon::run(x.to_vec()).unwrap()[0].clone(); acc.extend(res); acc }); poseidon_hash = Some(field_elements); } if element_visibility.is_polycommit() { if let Some(vk) = vk { if let Some(srs) = srs { let commitments = inputs.iter().fold(vec![], |mut acc, x| { let res = PolyCommitChip::commit::<Scheme>( x.to_vec(), (vk.cs().blinding_factors() + 1) as u32, srs, ); acc.push(res); acc }); polycommit = Some(commitments); } else { log::warn!("no srs provided for polycommit. processed value will be none"); } } else { log::debug!( "no verifying key provided for polycommit. processed value will be none" ); } } Ok(ModuleForwardResult { poseidon_hash, polycommit, }) } }
https://github.com/zkonduit/ezkl
src/graph/node.rs
use super::scale_to_multiplier; #[cfg(not(target_arch = "wasm32"))] use super::utilities::node_output_shapes; #[cfg(not(target_arch = "wasm32"))] use super::VarScales; #[cfg(not(target_arch = "wasm32"))] use super::Visibility; use crate::circuit::hybrid::HybridOp; use crate::circuit::lookup::LookupOp; use crate::circuit::poly::PolyOp; use crate::circuit::Constant; use crate::circuit::Input; use crate::circuit::Op; use crate::circuit::Unknown; #[cfg(not(target_arch = "wasm32"))] use crate::graph::new_op_from_onnx; use crate::tensor::TensorError; use halo2curves::bn256::Fr as Fp; #[cfg(not(target_arch = "wasm32"))] use log::trace; use serde::Deserialize; use serde::Serialize; #[cfg(not(target_arch = "wasm32"))] use std::collections::BTreeMap; use std::error::Error; #[cfg(not(target_arch = "wasm32"))] use std::fmt; #[cfg(not(target_arch = "wasm32"))] use tabled::Tabled; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::{ self, prelude::{Node as OnnxNode, SymbolValues, TypedFact, TypedOp}, }; #[cfg(not(target_arch = "wasm32"))] fn display_vector<T: fmt::Debug>(v: &Vec<T>) -> String { if !v.is_empty() { format!("{:?}", v) } else { String::new() } } #[cfg(not(target_arch = "wasm32"))] fn display_opkind(v: &SupportedOp) -> String { v.as_string() } /// A wrapper for an operation that has been rescaled. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Rescaled { /// The operation that has to be rescaled. pub inner: Box<SupportedOp>, /// The scale of the operation's inputs. pub scale: Vec<(usize, u128)>, } impl Op<Fp> for Rescaled { fn as_any(&self) -> &dyn std::any::Any { self } fn as_string(&self) -> String { format!("RESCALED INPUT ({})", self.inner.as_string()) } fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { let in_scales = in_scales .into_iter() .zip(self.scale.iter()) .map(|(a, b)| a + crate::graph::multiplier_to_scale(b.1 as f64)) .collect(); Op::<Fp>::out_scale(&*self.inner, in_scales) } fn layout( &self, config: &mut crate::circuit::BaseConfig<Fp>, region: &mut crate::circuit::region::RegionCtx<Fp>, values: &[crate::tensor::ValTensor<Fp>], ) -> Result<Option<crate::tensor::ValTensor<Fp>>, Box<dyn Error>> { if self.scale.len() != values.len() { return Err(Box::new(TensorError::DimMismatch( "rescaled inputs".to_string(), ))); } let res = &crate::circuit::layouts::rescale(config, region, values[..].try_into()?, &self.scale)? [..]; self.inner.layout(config, region, res) } fn clone_dyn(&self) -> Box<dyn Op<Fp>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } } /// A wrapper for an operation that has been rescaled. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RebaseScale { /// The operation that has to be rescaled. pub inner: Box<SupportedOp>, /// rebase op pub rebase_op: HybridOp, /// scale being rebased to pub target_scale: i32, /// The original scale of the operation's inputs. pub original_scale: i32, /// multiplier pub multiplier: f64, } impl RebaseScale { /// pub fn rebase( inner: SupportedOp, global_scale: crate::Scale, op_out_scale: crate::Scale, scale_rebase_multiplier: u32, div_rebasing: bool, ) -> SupportedOp { if (op_out_scale > (global_scale * scale_rebase_multiplier as i32)) && !inner.is_constant() && !inner.is_input() { let multiplier = scale_to_multiplier(op_out_scale - global_scale * scale_rebase_multiplier as i32); if let Some(op) = inner.get_rebased() { let multiplier = op.multiplier * multiplier; SupportedOp::RebaseScale(RebaseScale { inner: op.inner.clone(), target_scale: op.target_scale, multiplier, rebase_op: HybridOp::Div { denom: crate::circuit::utils::F32((multiplier) as f32), use_range_check_for_int: !div_rebasing, }, original_scale: op.original_scale, }) } else { SupportedOp::RebaseScale(RebaseScale { inner: Box::new(inner), target_scale: global_scale * scale_rebase_multiplier as i32, multiplier, rebase_op: HybridOp::Div { denom: crate::circuit::utils::F32(multiplier as f32), use_range_check_for_int: !div_rebasing, }, original_scale: op_out_scale, }) } } else { inner } } /// pub fn rebase_up( inner: SupportedOp, target_scale: crate::Scale, op_out_scale: crate::Scale, div_rebasing: bool, ) -> SupportedOp { if (op_out_scale < (target_scale)) && !inner.is_constant() && !inner.is_input() { let multiplier = scale_to_multiplier(op_out_scale - target_scale); if let Some(op) = inner.get_rebased() { let multiplier = op.multiplier * multiplier; SupportedOp::RebaseScale(RebaseScale { inner: op.inner.clone(), target_scale: op.target_scale, multiplier, original_scale: op.original_scale, rebase_op: HybridOp::Div { denom: crate::circuit::utils::F32((multiplier) as f32), use_range_check_for_int: !div_rebasing, }, }) } else { SupportedOp::RebaseScale(RebaseScale { inner: Box::new(inner), target_scale, multiplier, original_scale: op_out_scale, rebase_op: HybridOp::Div { denom: crate::circuit::utils::F32(multiplier as f32), use_range_check_for_int: !div_rebasing, }, }) } } else { inner } } } impl Op<Fp> for RebaseScale { fn as_any(&self) -> &dyn std::any::Any { self } fn as_string(&self) -> String { format!( "REBASED (div={:?}, rebasing_op={}) ({})", self.multiplier, <HybridOp as Op<Fp>>::as_string(&self.rebase_op), self.inner.as_string() ) } fn out_scale(&self, _: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { Ok(self.target_scale) } fn layout( &self, config: &mut crate::circuit::BaseConfig<Fp>, region: &mut crate::circuit::region::RegionCtx<Fp>, values: &[crate::tensor::ValTensor<Fp>], ) -> Result<Option<crate::tensor::ValTensor<Fp>>, Box<dyn Error>> { let original_res = self .inner .layout(config, region, values)? .ok_or("no inner layout")?; self.rebase_op.layout(config, region, &[original_res]) } fn clone_dyn(&self) -> Box<dyn Op<Fp>> { Box::new(self.clone()) // Forward to the derive(Clone) impl } } /// A single operation in a [crate::graph::Model]. #[derive(Clone, Debug, Serialize, Deserialize)] pub enum SupportedOp { /// A linear operation. Linear(PolyOp), /// A nonlinear operation. Nonlinear(LookupOp), /// A hybrid operation. Hybrid(HybridOp), /// Input(Input), /// Constant(Constant<Fp>), /// Unknown(Unknown), /// Rescaled(Rescaled), /// RebaseScale(RebaseScale), } impl SupportedOp { /// pub fn is_lookup(&self) -> bool { match self { SupportedOp::Nonlinear(_) => true, SupportedOp::RebaseScale(op) => op.inner.is_lookup(), _ => false, } } /// pub fn get_input(&self) -> Option<Input> { match self { SupportedOp::Input(op) => Some(op.clone()), _ => None, } } /// pub fn get_rebased(&self) -> Option<&RebaseScale> { match self { SupportedOp::RebaseScale(op) => Some(op), _ => None, } } /// pub fn get_lookup(&self) -> Option<&LookupOp> { match self { SupportedOp::Nonlinear(op) => Some(op), _ => None, } } /// pub fn get_constant(&self) -> Option<&Constant<Fp>> { match self { SupportedOp::Constant(op) => Some(op), _ => None, } } /// pub fn get_mutable_constant(&mut self) -> Option<&mut Constant<Fp>> { match self { SupportedOp::Constant(op) => Some(op), _ => None, } } #[cfg(not(target_arch = "wasm32"))] fn homogenous_rescale( &self, in_scales: Vec<crate::Scale>, ) -> Result<Box<dyn Op<Fp>>, Box<dyn Error>> { let inputs_to_scale = self.requires_homogenous_input_scales(); // creates a rescaled op if the inputs are not homogenous let op = self.clone_dyn(); super::homogenize_input_scales(op, in_scales, inputs_to_scale) } /// Since each associated value of `SupportedOp` implements `Op`, let's define a helper method to retrieve it. fn as_op(&self) -> &dyn Op<Fp> { match self { SupportedOp::Linear(op) => op, SupportedOp::Nonlinear(op) => op, SupportedOp::Hybrid(op) => op, SupportedOp::Input(op) => op, SupportedOp::Constant(op) => op, SupportedOp::Unknown(op) => op, SupportedOp::Rescaled(op) => op, SupportedOp::RebaseScale(op) => op, } } } impl From<Box<dyn Op<Fp>>> for SupportedOp { fn from(value: Box<dyn Op<Fp>>) -> Self { if let Some(op) = value.as_any().downcast_ref::<PolyOp>() { return SupportedOp::Linear(op.clone()); }; if let Some(op) = value.as_any().downcast_ref::<LookupOp>() { return SupportedOp::Nonlinear(op.clone()); }; if let Some(op) = value.as_any().downcast_ref::<HybridOp>() { return SupportedOp::Hybrid(op.clone()); }; if let Some(op) = value.as_any().downcast_ref::<Input>() { return SupportedOp::Input(op.clone()); }; if let Some(op) = value.as_any().downcast_ref::<Constant<Fp>>() { return SupportedOp::Constant(op.clone()); }; if let Some(op) = value.as_any().downcast_ref::<Unknown>() { return SupportedOp::Unknown(op.clone()); }; if let Some(op) = value.as_any().downcast_ref::<Rescaled>() { return SupportedOp::Rescaled(op.clone()); }; if let Some(op) = value.as_any().downcast_ref::<RebaseScale>() { return SupportedOp::RebaseScale(op.clone()); }; log::error!("Unsupported op type"); log::warn!("defaulting to Unknown"); SupportedOp::Unknown(Unknown {}) } } impl Op<Fp> for SupportedOp { fn layout( &self, config: &mut crate::circuit::BaseConfig<Fp>, region: &mut crate::circuit::region::RegionCtx<Fp>, values: &[crate::tensor::ValTensor<Fp>], ) -> Result<Option<crate::tensor::ValTensor<Fp>>, Box<dyn Error>> { self.as_op().layout(config, region, values) } fn is_input(&self) -> bool { self.as_op().is_input() } fn is_constant(&self) -> bool { self.as_op().is_constant() } fn requires_homogenous_input_scales(&self) -> Vec<usize> { self.as_op().requires_homogenous_input_scales() } fn clone_dyn(&self) -> Box<dyn Op<Fp>> { self.as_op().clone_dyn() } fn as_string(&self) -> String { self.as_op().as_string() } fn as_any(&self) -> &dyn std::any::Any { self } fn out_scale(&self, in_scales: Vec<crate::Scale>) -> Result<crate::Scale, Box<dyn Error>> { self.as_op().out_scale(in_scales) } } /// A node's input is a tensor from another node's output. pub type Outlet = (usize, usize); /// A single operation in a [crate::graph::Model]. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Node { /// [Op] i.e what operation this node represents. pub opkind: SupportedOp, /// The denominator in the fixed point representation for the node's output. Tensors of differing scales should not be combined. pub out_scale: i32, // Usually there is a simple in and out shape of the node as an operator. For example, an Affine node has three input_shapes (one for the input, weight, and bias), // but in_dim is [in], out_dim is [out] /// The indices of the node's inputs. pub inputs: Vec<Outlet>, /// Dimensions of output. pub out_dims: Vec<usize>, /// The node's unique identifier. pub idx: usize, /// The node's num of uses pub num_uses: usize, } #[cfg(not(target_arch = "wasm32"))] impl Tabled for Node { const LENGTH: usize = 6; fn headers() -> Vec<std::borrow::Cow<'static, str>> { let mut headers = Vec::with_capacity(Self::LENGTH); for i in ["idx", "opkind", "out_scale", "inputs", "out_dims"] { headers.push(std::borrow::Cow::Borrowed(i)); } headers } fn fields(&self) -> Vec<std::borrow::Cow<'_, str>> { let mut fields = Vec::with_capacity(Self::LENGTH); fields.push(std::borrow::Cow::Owned(self.idx.to_string())); fields.push(std::borrow::Cow::Owned(display_opkind(&self.opkind))); fields.push(std::borrow::Cow::Owned(self.out_scale.to_string())); fields.push(std::borrow::Cow::Owned(display_vector(&self.inputs))); fields.push(std::borrow::Cow::Owned(display_vector(&self.out_dims))); fields } } impl PartialEq for Node { fn eq(&self, other: &Node) -> bool { (self.out_scale == other.out_scale) && (self.inputs == other.inputs) && (self.out_dims == other.out_dims) && (self.idx == other.idx) && (self.opkind.as_string() == other.opkind.as_string()) } } impl Node { /// Converts a tract [OnnxNode] into an ezkl [Node]. /// # Arguments: /// * `node` - [OnnxNode] /// * `other_nodes` - [BTreeMap] of other previously initialized [Node]s in the computational graph. /// * `public_params` - flag if parameters of model are public /// * `idx` - The node's unique identifier. #[cfg(not(target_arch = "wasm32"))] #[allow(clippy::too_many_arguments)] pub fn new( node: OnnxNode<TypedFact, Box<dyn TypedOp>>, other_nodes: &mut BTreeMap<usize, super::NodeType>, scales: &VarScales, param_visibility: &Visibility, idx: usize, symbol_values: &SymbolValues, div_rebasing: bool, rebase_frac_zero_constants: bool, ) -> Result<Self, Box<dyn Error>> { trace!("Create {:?}", node); trace!("Create op {:?}", node.op); let num_uses = std::cmp::max( node.outputs .iter() .map(|outlet| outlet.successors.len()) .sum::<usize>(), // cmp to 1 for outputs 1, ); // load the node inputs let mut inputs = vec![]; // we can only take the inputs as mutable once -- so we need to collect them first let mut input_ids = node .inputs .iter() .map(|i| (i.node, i.slot)) .collect::<Vec<_>>(); input_ids .iter() .map(|(i, _)| { inputs.push(other_nodes.get(i).ok_or("input not found")?.clone()); Ok(()) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; let (mut opkind, deleted_indices) = new_op_from_onnx( idx, scales, param_visibility, node.clone(), &mut inputs, symbol_values, rebase_frac_zero_constants, )?; // parses the op name // we can only take the inputs as mutable once -- so we need to collect them first other_nodes.extend( inputs .iter() .map(|i| (i.idx(), i.clone())) .collect::<BTreeMap<_, _>>(), ); input_ids.iter_mut().enumerate().for_each(|(i, (idx, _))| { if deleted_indices.contains(&i) { // this input is not used *idx = usize::MAX; } }); // remove the inputs that are not used input_ids.retain(|(idx, _)| *idx != usize::MAX); // rescale the inputs if necessary to get consistent fixed points let mut in_scales: Vec<crate::Scale> = input_ids .iter() .map(|(idx, outlet)| { let idx = inputs .iter() .position(|x| *idx == x.idx()) .ok_or("input not found")?; Ok(inputs[idx].out_scales()[*outlet]) }) .collect::<Result<Vec<_>, Box<dyn Error>>>()?; let homogenous_inputs = opkind.requires_homogenous_input_scales(); // autoamtically increases a constant's scale if it is only used once and for input in homogenous_inputs .into_iter() .filter(|i| !deleted_indices.contains(i)) { if inputs.len() > input { let input_node = other_nodes .get_mut(&inputs[input].idx()) .ok_or("input not found")?; let input_opkind = &mut input_node.opkind(); if let Some(constant) = input_opkind.get_mutable_constant() { rescale_const_with_single_use( constant, in_scales.clone(), param_visibility, input_node.num_uses(), )?; input_node.replace_opkind(constant.clone_dyn().into()); let out_scale = input_opkind.out_scale(vec![])?; input_node.bump_scale(out_scale); in_scales[input] = out_scale; } } } opkind = opkind.homogenous_rescale(in_scales.clone())?.into(); let mut out_scale = opkind.out_scale(in_scales.clone())?; // rescale the inputs if necessary to get consistent fixed points, we select the largest scale (highest precision) let global_scale = scales.get_max(); opkind = RebaseScale::rebase( opkind, global_scale, out_scale, scales.rebase_multiplier, div_rebasing, ); out_scale = opkind.out_scale(in_scales)?; // get the output shape let out_dims = node_output_shapes(&node, symbol_values)?; // nodes vs subgraphs always have a single output let mut out_dims = out_dims[0].clone(); if out_dims.is_empty() { out_dims = vec![1]; } Ok(Node { idx, opkind, inputs: input_ids, out_dims, out_scale, num_uses, }) } } #[cfg(not(target_arch = "wasm32"))] fn rescale_const_with_single_use( constant: &mut Constant<Fp>, in_scales: Vec<crate::Scale>, param_visibility: &Visibility, num_uses: usize, ) -> Result<(), Box<dyn Error>> { if num_uses == 1 { let current_scale = constant.out_scale(vec![])?; let scale_max = in_scales.iter().max().ok_or("no scales")?; if scale_max > &current_scale { let raw_values = constant.raw_values.clone(); constant.quantized_values = super::quantize_tensor(raw_values, *scale_max, param_visibility)?; } } Ok(()) }
https://github.com/zkonduit/ezkl
src/graph/utilities.rs
#[cfg(not(target_arch = "wasm32"))] use super::GraphError; #[cfg(not(target_arch = "wasm32"))] use super::VarScales; use super::{Rescaled, SupportedOp, Visibility}; #[cfg(not(target_arch = "wasm32"))] use crate::circuit::hybrid::HybridOp; #[cfg(not(target_arch = "wasm32"))] use crate::circuit::lookup::LookupOp; #[cfg(not(target_arch = "wasm32"))] use crate::circuit::poly::PolyOp; use crate::circuit::Op; use crate::tensor::{Tensor, TensorError, TensorType}; use halo2curves::bn256::Fr as Fp; use halo2curves::ff::PrimeField; use itertools::Itertools; #[cfg(not(target_arch = "wasm32"))] use log::{debug, warn}; use std::error::Error; #[cfg(not(target_arch = "wasm32"))] use std::sync::Arc; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::prelude::{DatumType, Node as OnnxNode, TypedFact, TypedOp}; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::tract_core::ops::{ array::{ Gather, GatherElements, GatherNd, MultiBroadcastTo, OneHot, ScatterElements, ScatterNd, Slice, Topk, }, change_axes::AxisOp, cnn::{Conv, Deconv}, einsum::EinSum, element_wise::ElementWiseOp, nn::{LeakyRelu, Reduce, Softmax}, Downsample, }; #[cfg(not(target_arch = "wasm32"))] use tract_onnx::tract_hir::{ internal::DimLike, ops::array::{Pad, PadMode, TypedConcat}, ops::cnn::PoolSpec, ops::konst::Const, ops::nn::DataFormat, tract_core::ops::cast::Cast, tract_core::ops::cnn::{conv::KernelFormat, MaxPool, PaddingSpec, SumPool}, }; /// Quantizes an iterable of f32s to a [Tensor] of i32s using a fixed point representation. /// Arguments /// /// * `vec` - the vector to quantize. /// * `dims` - the dimensionality of the resulting [Tensor]. /// * `shift` - offset used in the fixed point representation. /// * `scale` - `2^scale` used in the fixed point representation. pub fn quantize_float(elem: &f64, shift: f64, scale: crate::Scale) -> Result<i128, TensorError> { let mult = scale_to_multiplier(scale); let max_value = ((i128::MAX as f64 - shift) / mult).round(); // the maximum value that can be represented w/o sig bit truncation if *elem > max_value { return Err(TensorError::SigBitTruncationError); } // we parallelize the quantization process as it seems to be quite slow at times let scaled = (mult * *elem + shift).round() as i128; Ok(scaled) } /// Dequantizes a field element to a f64 using a fixed point representation. /// Arguments /// * `felt` - the field element to dequantize. /// * `scale` - `2^scale` used in the fixed point representation. /// * `shift` - offset used in the fixed point representation. pub fn dequantize(felt: Fp, scale: crate::Scale, shift: f64) -> f64 { let int_rep = crate::fieldutils::felt_to_i128(felt); let multiplier = scale_to_multiplier(scale); int_rep as f64 / multiplier - shift } /// Converts a scale (log base 2) to a fixed point multiplier. pub fn scale_to_multiplier(scale: crate::Scale) -> f64 { f64::powf(2., scale as f64) } /// Converts a scale (log base 2) to a fixed point multiplier. pub fn multiplier_to_scale(mult: f64) -> crate::Scale { mult.log2().round() as crate::Scale } /// Gets the shape of a onnx node's outlets. #[cfg(not(target_arch = "wasm32"))] pub fn node_output_shapes( node: &OnnxNode<TypedFact, Box<dyn TypedOp>>, symbol_values: &SymbolValues, ) -> Result<Vec<Vec<usize>>, Box<dyn std::error::Error>> { let mut shapes = Vec::new(); let outputs = node.outputs.to_vec(); for output in outputs { let shape = output.fact.shape; let shape = shape.eval_to_usize(symbol_values)?; let mv = shape.to_vec(); shapes.push(mv) } Ok(shapes) } #[cfg(not(target_arch = "wasm32"))] use tract_onnx::prelude::SymbolValues; #[cfg(not(target_arch = "wasm32"))] /// Extracts the raw values from a tensor. pub fn extract_tensor_value( input: Arc<tract_onnx::prelude::Tensor>, ) -> Result<Tensor<f32>, Box<dyn std::error::Error>> { use maybe_rayon::prelude::{IntoParallelRefIterator, ParallelIterator}; let dt = input.datum_type(); let dims = input.shape().to_vec(); let mut const_value: Tensor<f32>; if dims.is_empty() && input.len() == 0 { const_value = Tensor::<f32>::new(None, &dims)?; return Ok(const_value); } match dt { DatumType::F16 => { let vec = input.as_slice::<tract_onnx::prelude::f16>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| (*x).into()).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::F32 => { let vec = input.as_slice::<f32>()?.to_vec(); const_value = Tensor::<f32>::new(Some(&vec), &dims)?; } DatumType::F64 => { let vec = input.as_slice::<f64>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::I64 => { // Generally a shape or hyperparam let vec = input.as_slice::<i64>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::I32 => { // Generally a shape or hyperparam let vec = input.as_slice::<i32>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::I16 => { // Generally a shape or hyperparam let vec = input.as_slice::<i16>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::I8 => { // Generally a shape or hyperparam let vec = input.as_slice::<i8>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::U8 => { // Generally a shape or hyperparam let vec = input.as_slice::<u8>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::U16 => { // Generally a shape or hyperparam let vec = input.as_slice::<u16>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::U32 => { // Generally a shape or hyperparam let vec = input.as_slice::<u32>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::U64 => { // Generally a shape or hyperparam let vec = input.as_slice::<u64>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::Bool => { // Generally a shape or hyperparam let vec = input.as_slice::<bool>()?.to_vec(); let cast: Vec<f32> = vec.par_iter().map(|x| *x as usize as f32).collect(); const_value = Tensor::<f32>::new(Some(&cast), &dims)?; } DatumType::TDim => { // Generally a shape or hyperparam let vec = input.as_slice::<tract_onnx::prelude::TDim>()?.to_vec(); let cast: Result<Vec<f32>, &str> = vec .par_iter() .map(|x| match x.to_i64() { Ok(v) => Ok(v as f32), Err(_) => match x.to_i64() { Ok(v) => Ok(v as f32), Err(_) => Err("could not evaluate tdim"), }, }) .collect(); const_value = Tensor::<f32>::new(Some(&cast?), &dims)?; } _ => return Err("unsupported data type".into()), } const_value.reshape(&dims)?; Ok(const_value) } #[cfg(not(target_arch = "wasm32"))] fn load_op<C: tract_onnx::prelude::Op + Clone>( op: &dyn tract_onnx::prelude::Op, idx: usize, name: String, ) -> Result<C, Box<dyn std::error::Error>> { // Extract the slope layer hyperparams let op: &C = match op.downcast_ref::<C>() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, name))); } }; Ok(op.clone()) } /// Matches an onnx node to a [crate::circuit::Op]. /// Arguments /// * `idx` - the index of the node in the graph. /// * `scale` - the global (circuit) scale. /// * `param_visibility` - [Visibility] of the node. /// * `node` - the [OnnxNode] to be matched. /// * `inputs` - the node's inputs. #[cfg(not(target_arch = "wasm32"))] pub fn new_op_from_onnx( idx: usize, scales: &VarScales, param_visibility: &Visibility, node: OnnxNode<TypedFact, Box<dyn TypedOp>>, inputs: &mut [super::NodeType], symbol_values: &SymbolValues, rebase_frac_zero_constants: bool, ) -> Result<(SupportedOp, Vec<usize>), Box<dyn std::error::Error>> { use tract_onnx::tract_core::ops::array::Trilu; use crate::circuit::InputType; let input_scales = inputs .iter() .flat_map(|x| x.out_scales()) .collect::<Vec<_>>(); let mut replace_const = |scale: crate::Scale, index: usize, default_op: SupportedOp| -> Result<SupportedOp, Box<dyn std::error::Error>> { let mut constant = inputs[index].opkind(); let constant = constant.get_mutable_constant(); if let Some(c) = constant { inputs[index].bump_scale(scale); c.rebase_scale(scale)?; inputs[index].replace_opkind(SupportedOp::Constant(c.clone())); Ok(SupportedOp::Linear(PolyOp::Identity { out_scale: Some(scale), })) } else { Ok(default_op) } }; debug!("Loading node: {:?}", node); let mut deleted_indices = vec![]; let node = match node.op().name().as_ref() { "ShiftLeft" => { // load shift amount if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); let raw_values = &c.raw_values; if raw_values.len() != 1 { return Err(Box::new(GraphError::InvalidDims( idx, "shift left".to_string(), ))); } SupportedOp::Linear(PolyOp::Identity { out_scale: Some(input_scales[0] - raw_values[0] as i32), }) } else { return Err(Box::new(GraphError::OpMismatch( idx, "ShiftLeft".to_string(), ))); } } "ShiftRight" => { // load shift amount if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); let raw_values = &c.raw_values; if raw_values.len() != 1 { return Err(Box::new(GraphError::InvalidDims( idx, "shift right".to_string(), ))); } SupportedOp::Linear(PolyOp::Identity { out_scale: Some(input_scales[0] + raw_values[0] as i32), }) } else { return Err(Box::new(GraphError::OpMismatch( idx, "ShiftRight".to_string(), ))); } } "MultiBroadcastTo" => { let op = load_op::<MultiBroadcastTo>(node.op(), idx, node.op().name().to_string())?; let shape = op.shape.clone(); let shape = shape .iter() .map(|x| x.to_usize()) .collect::<Result<Vec<_>, _>>()?; SupportedOp::Linear(PolyOp::MultiBroadcastTo { shape }) } "Range" => { let mut input_ops = vec![]; for (i, input) in inputs.iter_mut().enumerate() { if !input.opkind().is_constant() { return Err("Range only supports constant inputs in a zk circuit".into()); } else { input.decrement_use(); deleted_indices.push(i); input_ops.push(input.opkind().clone()); } } assert_eq!(input_ops.len(), 3, "Range requires 3 inputs"); let input_ops = input_ops .iter() .map(|x| x.get_constant().ok_or("Range requires constant inputs")) .collect::<Result<Vec<_>, _>>()?; let start = input_ops[0].raw_values.map(|x| x as usize)[0]; let end = input_ops[1].raw_values.map(|x| x as usize)[0]; let delta = input_ops[2].raw_values.map(|x| x as usize)[0]; let range = (start..end).step_by(delta).collect::<Vec<_>>(); let raw_value = range.iter().map(|x| *x as f32).collect::<Tensor<_>>(); // Quantize the raw value (integers) let quantized_value = quantize_tensor(raw_value.clone(), 0, &Visibility::Fixed)?; let c = crate::circuit::ops::Constant::new(quantized_value, raw_value); // Create a constant op SupportedOp::Constant(c) } "Trilu" => { let op = load_op::<Trilu>(node.op(), idx, node.op().name().to_string())?; let upper = op.upper; // assert second input is a constant let diagonal = if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); let raw_values = &c.raw_values; if raw_values.len() != 1 { return Err(Box::new(GraphError::InvalidDims(idx, "trilu".to_string()))); } raw_values[0] as i32 } else { return Err("we only support constant inputs for trilu diagonal".into()); }; SupportedOp::Linear(PolyOp::Trilu { upper, k: diagonal }) } "Gather" => { if inputs.len() != 2 { return Err(Box::new(GraphError::InvalidDims(idx, "gather".to_string()))); }; let op = load_op::<Gather>(node.op(), idx, node.op().name().to_string())?; let axis = op.axis; let mut op = SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::Gather { dim: axis, constant_idx: None, }); // if param_visibility.is_public() { if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(inputs.len() - 1); op = SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::Gather { dim: axis, constant_idx: Some(c.raw_values.map(|x| { if x == -1.0 { inputs[0].out_dims()[0][axis] - 1 } else { x as usize } })), }); } // } if inputs[1].opkind().is_input() { inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input { scale: 0, datum_type: InputType::TDim, })); inputs[1].bump_scale(0); } op // Extract the max value } "Topk" => { let op = load_op::<Topk>(node.op(), idx, node.op().name().to_string())?; let axis = op.axis; // if param_visibility.is_public() { let k = if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(inputs.len() - 1); c.raw_values.map(|x| x as usize)[0] } else { op.fallback_k.to_i64()? as usize }; SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::TopK { dim: axis, k, largest: op.largest, }) } "Onehot" => { let op = load_op::<OneHot>(node.op(), idx, node.op().name().to_string())?; let axis = op.axis; let num_classes = op.dim; SupportedOp::Hybrid(crate::circuit::ops::hybrid::HybridOp::OneHot { dim: axis, num_classes, }) } "ScatterElements" => { if inputs.len() != 3 { return Err(Box::new(GraphError::InvalidDims( idx, "scatter elements".to_string(), ))); }; let op = load_op::<ScatterElements>(node.op(), idx, node.op().name().to_string())?; let axis = op.axis; let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterElements { dim: axis, constant_idx: None, }); // if param_visibility.is_public() { if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterElements { dim: axis, constant_idx: Some(c.raw_values.map(|x| x as usize)), }) } // } if inputs[1].opkind().is_input() { inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input { scale: 0, datum_type: InputType::TDim, })); inputs[1].bump_scale(0); } op // Extract the max value } "ScatterNd" => { if inputs.len() != 3 { return Err(Box::new(GraphError::InvalidDims( idx, "scatter nd".to_string(), ))); }; // just verify it deserializes correctly let _op = load_op::<ScatterNd>(node.op(), idx, node.op().name().to_string())?; let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterND { constant_idx: None, }); // if param_visibility.is_public() { if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::ScatterND { constant_idx: Some(c.raw_values.map(|x| x as usize)), }) } // } if inputs[1].opkind().is_input() { inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input { scale: 0, datum_type: InputType::TDim, })); inputs[1].bump_scale(0); } op } "GatherNd" => { if inputs.len() != 2 { return Err(Box::new(GraphError::InvalidDims( idx, "gather nd".to_string(), ))); }; let op = load_op::<GatherNd>(node.op(), idx, node.op().name().to_string())?; let batch_dims = op.batch_dims; let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherND { batch_dims, indices: None, }); // if param_visibility.is_public() { if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherND { batch_dims, indices: Some(c.raw_values.map(|x| x as usize)), }) } // } if inputs[1].opkind().is_input() { inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input { scale: 0, datum_type: InputType::TDim, })); inputs[1].bump_scale(0); } op } "GatherElements" => { if inputs.len() != 2 { return Err(Box::new(GraphError::InvalidDims( idx, "gather elements".to_string(), ))); }; let op = load_op::<GatherElements>(node.op(), idx, node.op().name().to_string())?; let axis = op.axis; let mut op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherElements { dim: axis, constant_idx: None, }); // if param_visibility.is_public() { if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); op = SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::GatherElements { dim: axis, constant_idx: Some(c.raw_values.map(|x| x as usize)), }) } // } if inputs[1].opkind().is_input() { inputs[1].replace_opkind(SupportedOp::Input(crate::circuit::ops::Input { scale: 0, datum_type: InputType::TDim, })); inputs[1].bump_scale(0); } op // Extract the max value } "MoveAxis" => { let op = load_op::<AxisOp>(node.op(), idx, node.op().name().to_string())?; match op { AxisOp::Move(from, to) => { let source = from.to_usize()?; let destination = to.to_usize()?; SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::MoveAxis { source, destination, }) } _ => { return Err(Box::new(GraphError::OpMismatch( idx, "MoveAxis".to_string(), ))) } } } "Concat" | "InferenceConcat" => { let op = load_op::<TypedConcat>(node.op(), idx, node.op().name().to_string())?; let axis = op.axis; SupportedOp::Linear(crate::circuit::ops::poly::PolyOp::Concat { axis }) } "Slice" => { let slice = load_op::<Slice>(node.op(), idx, node.op().name().to_string())?; let axis = slice.axis; let start = slice.start.to_usize()?; let end = slice.end.to_usize()?; SupportedOp::Linear(PolyOp::Slice { axis, start, end }) } "Const" => { let op: Const = load_op::<Const>(node.op(), idx, node.op().name().to_string())?; let dt = op.0.datum_type(); // Raw values are always f32 let raw_value = extract_tensor_value(op.0)?; // If bool or a tensor dimension then don't scale let mut constant_scale = match dt { DatumType::Bool | DatumType::TDim | DatumType::I64 | DatumType::I32 | DatumType::I16 | DatumType::I8 | DatumType::U8 | DatumType::U16 | DatumType::U32 | DatumType::U64 => 0, DatumType::F16 | DatumType::F32 | DatumType::F64 => scales.params, _ => return Err(Box::new(GraphError::UnsupportedDataType)), }; // if all raw_values are round then set scale to 0 let all_round = raw_value.iter().all(|x| (x).fract() == 0.0); if all_round && rebase_frac_zero_constants { constant_scale = 0; } // Quantize the raw value let quantized_value = quantize_tensor(raw_value.clone(), constant_scale, param_visibility)?; let c = crate::circuit::ops::Constant::new(quantized_value, raw_value); // Create a constant op SupportedOp::Constant(c) } "Reduce<ArgMax(false)>" => { if inputs.len() != 1 { return Err(Box::new(GraphError::InvalidDims(idx, "argmax".to_string()))); }; let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?; let axes: Vec<usize> = op.axes.into_iter().collect(); assert_eq!(axes.len(), 1, "only support argmax over one axis"); SupportedOp::Hybrid(HybridOp::ReduceArgMax { dim: axes[0] }) } "Reduce<ArgMin(false)>" => { if inputs.len() != 1 { return Err(Box::new(GraphError::InvalidDims(idx, "argmin".to_string()))); }; let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?; let axes: Vec<usize> = op.axes.into_iter().collect(); assert_eq!(axes.len(), 1, "only support argmin over one axis"); SupportedOp::Hybrid(HybridOp::ReduceArgMin { dim: axes[0] }) } "Reduce<Min>" => { if inputs.len() != 1 { return Err(Box::new(GraphError::InvalidDims(idx, "min".to_string()))); }; let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?; let axes = op.axes.into_iter().collect(); SupportedOp::Hybrid(HybridOp::ReduceMin { axes }) } "Reduce<Max>" => { if inputs.len() != 1 { return Err(Box::new(GraphError::InvalidDims(idx, "max".to_string()))); }; let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?; let axes = op.axes.into_iter().collect(); SupportedOp::Hybrid(HybridOp::ReduceMax { axes }) } "Reduce<Prod>" => { if inputs.len() != 1 { return Err(Box::new(GraphError::InvalidDims(idx, "prod".to_string()))); }; let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?; let axes: Vec<usize> = op.axes.into_iter().collect(); // length of prod along axes let len_prod = inputs[0].out_dims()[0] .iter() .enumerate() .filter(|(i, _)| axes.contains(i)) .map(|(_, v)| v) .product::<usize>(); SupportedOp::Linear(PolyOp::Prod { axes, len_prod }) } "Reduce<Sum>" => { if inputs.len() != 1 { return Err(Box::new(GraphError::InvalidDims(idx, "sum".to_string()))); }; let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?; let axes = op.axes.into_iter().collect(); SupportedOp::Linear(PolyOp::Sum { axes }) } "Reduce<MeanOfSquares>" => { if inputs.len() != 1 { return Err(Box::new(GraphError::InvalidDims( idx, "mean of squares".to_string(), ))); }; let op = load_op::<Reduce>(node.op(), idx, node.op().name().to_string())?; let axes = op.axes.into_iter().collect(); SupportedOp::Linear(PolyOp::MeanOfSquares { axes }) } "Max" => { // Extract the max value // first find the input that is a constant // and then extract the value let const_inputs = inputs .iter() .enumerate() .filter(|(_, n)| n.is_constant()) .map(|(i, _)| i) .collect::<Vec<_>>(); if const_inputs.len() != 1 { return Err(Box::new(GraphError::OpMismatch(idx, "Max".to_string()))); } let const_idx = const_inputs[0]; let boxed_op = inputs[const_idx].opkind(); let unit = if let Some(c) = extract_const_raw_values(boxed_op) { if c.len() == 1 { c[0] } else { return Err(Box::new(GraphError::InvalidDims(idx, "max".to_string()))); } } else { return Err(Box::new(GraphError::OpMismatch(idx, "Max".to_string()))); }; if inputs.len() == 2 { if let Some(node) = inputs.get_mut(const_idx) { node.decrement_use(); deleted_indices.push(const_idx); } if unit == 0. { SupportedOp::Nonlinear(LookupOp::ReLU) } else { // get the non-constant index let non_const_idx = if const_idx == 0 { 1 } else { 0 }; SupportedOp::Nonlinear(LookupOp::Max { scale: scale_to_multiplier(inputs[non_const_idx].out_scales()[0]).into(), a: crate::circuit::utils::F32(unit), }) } } else { return Err(Box::new(GraphError::InvalidDims(idx, "max".to_string()))); } } "Min" => { // Extract the min value // first find the input that is a constant // and then extract the value let const_inputs = inputs .iter() .enumerate() .filter(|(_, n)| n.is_constant()) .map(|(i, _)| i) .collect::<Vec<_>>(); if const_inputs.len() != 1 { return Err(Box::new(GraphError::OpMismatch(idx, "Min".to_string()))); } let const_idx = const_inputs[0]; let boxed_op = inputs[const_idx].opkind(); let unit = if let Some(c) = extract_const_raw_values(boxed_op) { if c.len() == 1 { c[0] } else { return Err(Box::new(GraphError::InvalidDims(idx, "min".to_string()))); } } else { return Err(Box::new(GraphError::OpMismatch(idx, "Min".to_string()))); }; if inputs.len() == 2 { if let Some(node) = inputs.get_mut(const_idx) { node.decrement_use(); deleted_indices.push(const_idx); } // get the non-constant index let non_const_idx = if const_idx == 0 { 1 } else { 0 }; SupportedOp::Nonlinear(LookupOp::Min { scale: scale_to_multiplier(inputs[non_const_idx].out_scales()[0]).into(), a: crate::circuit::utils::F32(unit), }) } else { return Err(Box::new(GraphError::InvalidDims(idx, "min".to_string()))); } } "Recip" => { let in_scale = inputs[0].out_scales()[0]; let max_scale = std::cmp::max(scales.get_max(), in_scale); // If the input scale is larger than the params scale SupportedOp::Hybrid(HybridOp::Recip { input_scale: (scale_to_multiplier(in_scale) as f32).into(), output_scale: (scale_to_multiplier(max_scale) as f32).into(), use_range_check_for_int: true, }) } "LeakyRelu" => { // Extract the slope layer hyperparams let leaky_op = load_op::<ElementWiseOp>(node.op(), idx, node.op().name().to_string())?; let leaky_op: &LeakyRelu = match leaky_op.0.downcast_ref::<LeakyRelu>() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch( idx, "leaky relu".to_string(), ))); } }; SupportedOp::Nonlinear(LookupOp::LeakyReLU { slope: crate::circuit::utils::F32(leaky_op.alpha), }) } "Scan" => { return Err("scan should never be analyzed explicitly".into()); } "QuantizeLinearU8" | "DequantizeLinearF32" => { SupportedOp::Linear(PolyOp::Identity { out_scale: None }) } "Abs" => SupportedOp::Nonlinear(LookupOp::Abs), "Neg" => SupportedOp::Linear(PolyOp::Neg), "HardSwish" => SupportedOp::Nonlinear(LookupOp::HardSwish { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Sigmoid" => SupportedOp::Nonlinear(LookupOp::Sigmoid { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Sqrt" => SupportedOp::Nonlinear(LookupOp::Sqrt { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Rsqrt" => SupportedOp::Nonlinear(LookupOp::Rsqrt { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Exp" => SupportedOp::Nonlinear(LookupOp::Exp { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Ln" => SupportedOp::Nonlinear(LookupOp::Ln { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Sin" => SupportedOp::Nonlinear(LookupOp::Sin { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Cos" => SupportedOp::Nonlinear(LookupOp::Cos { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Tan" => SupportedOp::Nonlinear(LookupOp::Tan { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Asin" => SupportedOp::Nonlinear(LookupOp::ASin { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Acos" => SupportedOp::Nonlinear(LookupOp::ACos { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Atan" => SupportedOp::Nonlinear(LookupOp::ATan { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Sinh" => SupportedOp::Nonlinear(LookupOp::Sinh { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Cosh" => SupportedOp::Nonlinear(LookupOp::Cosh { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Tanh" => SupportedOp::Nonlinear(LookupOp::Tanh { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Asinh" => SupportedOp::Nonlinear(LookupOp::ASinh { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Acosh" => SupportedOp::Nonlinear(LookupOp::ACosh { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Atanh" => SupportedOp::Nonlinear(LookupOp::ATanh { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Erf" => SupportedOp::Nonlinear(LookupOp::Erf { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Source" => { let (scale, datum_type) = match node.outputs[0].fact.datum_type { DatumType::Bool => (0, InputType::Bool), DatumType::TDim => (0, InputType::TDim), DatumType::I64 | DatumType::I32 | DatumType::I16 | DatumType::I8 | DatumType::U8 | DatumType::U16 | DatumType::U32 | DatumType::U64 => (0, InputType::Int), DatumType::F16 => (scales.input, InputType::F16), DatumType::F32 => (scales.input, InputType::F32), DatumType::F64 => (scales.input, InputType::F64), _ => return Err(Box::new(GraphError::UnsupportedDataType)), }; SupportedOp::Input(crate::circuit::ops::Input { scale, datum_type }) } "Cast" => { let op = load_op::<Cast>(node.op(), idx, node.op().name().to_string())?; let dt = op.to; assert_eq!(input_scales.len(), 1); match dt { DatumType::Bool | DatumType::TDim | DatumType::I64 | DatumType::I32 | DatumType::I16 | DatumType::I8 | DatumType::U8 | DatumType::U16 | DatumType::U32 | DatumType::U64 => { if input_scales[0] != 0 { replace_const( 0, 0, SupportedOp::Nonlinear(LookupOp::Cast { scale: crate::circuit::utils::F32(scale_to_multiplier( input_scales[0], ) as f32), }), )? } else { SupportedOp::Linear(PolyOp::Identity { out_scale: None }) } } DatumType::F16 | DatumType::F32 | DatumType::F64 => { SupportedOp::Linear(PolyOp::Identity { out_scale: None }) } _ => return Err(Box::new(GraphError::UnsupportedDataType)), } } "Add" => SupportedOp::Linear(PolyOp::Add), "Sub" => SupportedOp::Linear(PolyOp::Sub), "Mul" => { let mut op = SupportedOp::Linear(PolyOp::Mult); let const_idx = inputs .iter() .enumerate() .filter(|(_, n)| n.is_constant()) .map(|(i, _)| i) .collect::<Vec<_>>(); if const_idx.len() > 1 { return Err(Box::new(GraphError::InvalidDims(idx, "mul".to_string()))); } if const_idx.len() == 1 { let const_idx = const_idx[0]; if let Some(c) = inputs[const_idx].opkind().get_mutable_constant() { if c.raw_values.len() == 1 && c.raw_values[0] < 1. { // if not divisible by 2 then we need to add a range check let raw_values = 1.0 / c.raw_values[0]; if raw_values.log2().fract() == 0.0 { inputs[const_idx].decrement_use(); deleted_indices.push(const_idx); op = SupportedOp::Linear(PolyOp::Identity { out_scale: Some(input_scales[0] + raw_values.log2() as i32), }); } } } } op } "Iff" => SupportedOp::Linear(PolyOp::Iff), "Less" => { if inputs.len() == 2 { SupportedOp::Hybrid(HybridOp::Less) } else { return Err(Box::new(GraphError::InvalidDims(idx, "less".to_string()))); } } "LessEqual" => { if inputs.len() == 2 { SupportedOp::Hybrid(HybridOp::LessEqual) } else { return Err(Box::new(GraphError::InvalidDims( idx, "less equal".to_string(), ))); } } "Greater" => { // Extract the slope layer hyperparams if inputs.len() == 2 { SupportedOp::Hybrid(HybridOp::Greater) } else { return Err(Box::new(GraphError::InvalidDims( idx, "greater".to_string(), ))); } } "GreaterEqual" => { // Extract the slope layer hyperparams if inputs.len() == 2 { SupportedOp::Hybrid(HybridOp::GreaterEqual) } else { return Err(Box::new(GraphError::InvalidDims( idx, "greater equal".to_string(), ))); } } "EinSum" => { // Extract the slope layer hyperparams let op: &EinSum = match node.op().downcast_ref::<EinSum>() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, "einsum".to_string()))); } }; let axes = &op.axes; SupportedOp::Linear(PolyOp::Einsum { equation: axes.to_string(), }) } "Softmax" => { // Extract the slope layer hyperparams let softmax_op: &Softmax = match node.op().downcast_ref::<Softmax>() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, "softmax".to_string()))); } }; let in_scale = inputs[0].out_scales()[0]; let max_scale = std::cmp::max(scales.get_max(), in_scale); SupportedOp::Hybrid(HybridOp::Softmax { input_scale: scale_to_multiplier(in_scale).into(), output_scale: scale_to_multiplier(max_scale).into(), axes: softmax_op.axes.to_vec(), }) } "MaxPool" => { // Extract the padding and stride layer hyperparams let op = Box::new(node.op()); let sumpool_node: &MaxPool = match op.downcast_ref() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, "Maxpool".to_string()))); } }; let pool_spec: &PoolSpec = &sumpool_node.pool_spec; // only support pytorch type formatting for now if pool_spec.data_format != DataFormat::NCHW { return Err(Box::new(GraphError::MissingParams( "data in wrong format".to_string(), ))); } let stride = pool_spec .strides .clone() .ok_or(GraphError::MissingParams("stride".to_string()))?; let padding = match &pool_spec.padding { PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => { b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect() } _ => { return Err(Box::new(GraphError::MissingParams("padding".to_string()))); } }; let kernel_shape = &pool_spec.kernel_shape; SupportedOp::Hybrid(HybridOp::MaxPool { padding, stride: stride.to_vec(), pool_dims: kernel_shape.to_vec(), }) } "Ceil" => SupportedOp::Nonlinear(LookupOp::Ceil { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Floor" => SupportedOp::Nonlinear(LookupOp::Floor { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Round" => SupportedOp::Nonlinear(LookupOp::Round { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "RoundHalfToEven" => SupportedOp::Nonlinear(LookupOp::RoundHalfToEven { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), }), "Sign" => SupportedOp::Nonlinear(LookupOp::Sign), "Pow" => { // Extract the slope layer hyperparams from a const // if param_visibility.is_public() { if let Some(c) = inputs[1].opkind().get_mutable_constant() { inputs[1].decrement_use(); deleted_indices.push(1); if c.raw_values.len() > 1 { unimplemented!("only support scalar pow") } SupportedOp::Nonlinear(LookupOp::Pow { scale: scale_to_multiplier(inputs[0].out_scales()[0]).into(), a: crate::circuit::utils::F32(c.raw_values[0]), }) } else { unimplemented!("only support constant pow for now") } } "Cube" => SupportedOp::Linear(PolyOp::Pow(3)), "Square" => SupportedOp::Linear(PolyOp::Pow(2)), "Conv" => { let conv_node: &Conv = match node.op().downcast_ref::<Conv>() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, "conv".to_string()))); } }; if let Some(dilations) = &conv_node.pool_spec.dilations { if dilations.iter().any(|x| *x != 1) { return Err(Box::new(GraphError::MisformedParams( "non unit dilations not supported".to_string(), ))); } } if ((conv_node.pool_spec.data_format != DataFormat::NCHW) && (conv_node.pool_spec.data_format != DataFormat::CHW)) || (conv_node.kernel_fmt != KernelFormat::OIHW) { return Err(Box::new(GraphError::MisformedParams( "data or kernel in wrong format".to_string(), ))); } let stride = match conv_node.pool_spec.strides.clone() { Some(s) => s.to_vec(), None => { return Err(Box::new(GraphError::MissingParams("strides".to_string()))); } }; let padding = match &conv_node.pool_spec.padding { PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => { b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect() } _ => { return Err(Box::new(GraphError::MissingParams("padding".to_string()))); } }; // if bias exists then rescale it to the input + kernel scale if input_scales.len() == 3 { let bias_scale = input_scales[2]; let input_scale = input_scales[0]; let kernel_scale = input_scales[1]; let output_scale = input_scale + kernel_scale; if bias_scale != output_scale { replace_const( output_scale, 2, SupportedOp::Unknown(crate::circuit::Unknown), )?; } } SupportedOp::Linear(PolyOp::Conv { padding, stride }) } "Not" => SupportedOp::Linear(PolyOp::Not), "And" => SupportedOp::Linear(PolyOp::And), "Or" => SupportedOp::Linear(PolyOp::Or), "Xor" => SupportedOp::Linear(PolyOp::Xor), "Equals" => SupportedOp::Hybrid(HybridOp::Equals), "Deconv" => { let deconv_node: &Deconv = match node.op().downcast_ref::<Deconv>() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, "deconv".to_string()))); } }; if let Some(dilations) = &deconv_node.pool_spec.dilations { if dilations.iter().any(|x| *x != 1) { return Err(Box::new(GraphError::MisformedParams( "non unit dilations not supported".to_string(), ))); } } if (deconv_node.pool_spec.data_format != DataFormat::NCHW) || (deconv_node.kernel_format != KernelFormat::OIHW) { return Err(Box::new(GraphError::MisformedParams( "data or kernel in wrong format".to_string(), ))); } let stride = match deconv_node.pool_spec.strides.clone() { Some(s) => s.to_vec(), None => { return Err(Box::new(GraphError::MissingParams("strides".to_string()))); } }; let padding = match &deconv_node.pool_spec.padding { PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => { b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect() } _ => { return Err(Box::new(GraphError::MissingParams("padding".to_string()))); } }; // if bias exists then rescale it to the input + kernel scale if input_scales.len() == 3 { let bias_scale = input_scales[2]; let input_scale = input_scales[0]; let kernel_scale = input_scales[1]; let output_scale = input_scale + kernel_scale; if bias_scale != output_scale { replace_const( output_scale, 2, SupportedOp::Unknown(crate::circuit::Unknown), )?; } } SupportedOp::Linear(PolyOp::DeConv { padding, output_padding: deconv_node.adjustments.to_vec(), stride, }) } "Downsample" => { let downsample_node: Downsample = match node.op().downcast_ref::<Downsample>() { Some(b) => b.clone(), None => { return Err(Box::new(GraphError::OpMismatch( idx, "downsample".to_string(), ))); } }; SupportedOp::Linear(PolyOp::Downsample { axis: downsample_node.axis, stride: downsample_node.stride as usize, modulo: downsample_node.modulo, }) } "Resize" => { // this is a bit hacky, but we need to extract the resize node somehow // and this is the only way I can think of // see https://github.com/sonos/tract/issues/324 let resize_node = format!("{:?}", node); if !resize_node.contains("interpolator: Nearest") && !resize_node.contains("nearest: Floor") { unimplemented!("Only nearest neighbor interpolation is supported") } // check if optional scale factor is present if inputs.len() != 2 && inputs.len() != 3 { return Err(Box::new(GraphError::OpMismatch(idx, "Resize".to_string()))); } let scale_factor_node = // find optional_scales_input in the string and extract the value inside the Some if resize_node.contains("optional_scales_input: None") { None } else { Some(resize_node .split("optional_scales_input: ") .collect::<Vec<_>>()[1] .split("Some(") .collect::<Vec<_>>()[1] .split(')') .collect::<Vec<_>>()[0] .parse::<usize>()?) }; let scale_factor = if let Some(scale_factor_node) = scale_factor_node { let boxed_op = inputs[scale_factor_node].opkind(); if let Some(c) = extract_const_raw_values(boxed_op) { c.map(|x| x as usize).into_iter().collect::<Vec<usize>>() } else { return Err(Box::new(GraphError::OpMismatch(idx, "Resize".to_string()))); } } else { // default vec![1] }; for i in 1..inputs.len() { // remove the resize node from the inputs if let Some(node) = inputs.get_mut(i) { node.decrement_use(); deleted_indices.push(i); } } SupportedOp::Linear(PolyOp::Resize { scale_factor }) } "SumPool" => { // Extract the padding and stride layer hyperparams let op = Box::new(node.op()); let sumpool_node: &SumPool = match op.downcast_ref() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, "sumpool".to_string()))); } }; let pool_spec: &PoolSpec = &sumpool_node.pool_spec; // only support pytorch type formatting for now if pool_spec.data_format != DataFormat::NCHW { return Err(Box::new(GraphError::MissingParams( "data in wrong format".to_string(), ))); } let stride = pool_spec .strides .clone() .ok_or(GraphError::MissingParams("stride".to_string()))?; let padding = match &pool_spec.padding { PaddingSpec::Explicit(b, a) | PaddingSpec::ExplicitOnnxPool(b, a, _) => { b.iter().zip(a.iter()).map(|(b, a)| (*b, *a)).collect() } _ => { return Err(Box::new(GraphError::MissingParams("padding".to_string()))); } }; SupportedOp::Hybrid(HybridOp::SumPool { padding, stride: stride.to_vec(), kernel_shape: pool_spec.kernel_shape.to_vec(), normalized: sumpool_node.normalize, }) } // "GlobalAvgPool" => SupportedOp::Linear(PolyOp::SumPool { // padding: [(0, 0); 2], // stride: (1, 1), // kernel_shape: (inputs[0].out_dims()[0][1], inputs[0].out_dims()[0][2]), // }), "Pad" => { let pad_node: &Pad = match node.op().downcast_ref::<Pad>() { Some(b) => b, None => { return Err(Box::new(GraphError::OpMismatch(idx, "pad".to_string()))); } }; // we only support constant 0 padding if pad_node.mode != PadMode::Constant(tract_onnx::prelude::Arc::new( tract_onnx::prelude::Tensor::zero::<f32>(&[])?, )) { return Err(Box::new(GraphError::MisformedParams( "pad mode or pad type".to_string(), ))); } SupportedOp::Linear(PolyOp::Pad(pad_node.pads.to_vec())) } "RmAxis" | "Reshape" | "AddAxis" => { // Extract the slope layer hyperparams let shapes = node_output_shapes(&node, symbol_values)?; let mut output_shape = shapes[0].clone(); if output_shape.is_empty() { output_shape = vec![1]; } SupportedOp::Linear(PolyOp::Reshape(output_shape)) } "Flatten" => { let new_dims: Vec<usize> = vec![inputs[0].out_dims()[0].iter().product::<usize>()]; SupportedOp::Linear(PolyOp::Flatten(new_dims)) } c => { warn!("Unknown op: {}", c); SupportedOp::Unknown(crate::circuit::ops::Unknown) } }; Ok((node, deleted_indices)) } /// Extracts the raw values from a [crate::circuit::ops::Constant] op. pub fn extract_const_raw_values(op: SupportedOp) -> Option<Tensor<f32>> { match op { SupportedOp::Constant(crate::circuit::ops::Constant { raw_values, .. }) => Some(raw_values), _ => None, } } /// Extracts the quantized values from a [crate::circuit::ops::Constant] op. pub fn extract_const_quantized_values(op: SupportedOp) -> Option<Tensor<Fp>> { match op { SupportedOp::Constant(crate::circuit::ops::Constant { quantized_values, .. }) => Some(quantized_values), _ => None, } } /// Converts a tensor to a [ValTensor] with a given scale. pub fn quantize_tensor<F: PrimeField + TensorType + PartialOrd>( const_value: Tensor<f32>, scale: crate::Scale, visibility: &Visibility, ) -> Result<Tensor<F>, Box<dyn std::error::Error>> { let mut value: Tensor<F> = const_value.par_enum_map(|_, x| { Ok::<_, TensorError>(crate::fieldutils::i128_to_felt::<F>(quantize_float( &(x).into(), 0.0, scale, )?)) })?; value.set_scale(scale); value.set_visibility(visibility); Ok(value) } use crate::tensor::ValTensor; /// Split a [ValTensor] into a vector of [ValTensor]s. pub(crate) fn split_valtensor( values: &ValTensor<Fp>, shapes: Vec<Vec<usize>>, ) -> Result<Vec<ValTensor<Fp>>, Box<dyn std::error::Error>> { let mut tensors: Vec<ValTensor<Fp>> = Vec::new(); let mut start = 0; for shape in shapes { let end = start + shape.iter().product::<usize>(); let mut tensor = values.get_slice(&[start..end])?; tensor.reshape(&shape)?; tensors.push(tensor); start = end; } Ok(tensors) } /// pub fn homogenize_input_scales( op: Box<dyn Op<Fp>>, input_scales: Vec<crate::Scale>, inputs_to_scale: Vec<usize>, ) -> Result<Box<dyn Op<Fp>>, Box<dyn Error>> { let relevant_input_scales = input_scales .clone() .into_iter() .enumerate() .filter(|(idx, _)| inputs_to_scale.contains(idx)) .map(|(_, scale)| scale) .collect_vec(); if inputs_to_scale.is_empty() { return Ok(op); } // else if all inputs_scales at inputs_to_scale are the same, we don't need to do anything if relevant_input_scales.windows(2).all(|w| w[0] == w[1]) { return Ok(op); } let mut multipliers: Vec<u128> = vec![1; input_scales.len()]; let max_scale = input_scales.iter().max().ok_or("no max scale")?; let _ = input_scales .iter() .enumerate() .map(|(idx, input_scale)| { if !inputs_to_scale.contains(&idx) { return; } let scale_diff = max_scale - input_scale; if scale_diff > 0 { let mult = crate::graph::scale_to_multiplier(scale_diff); multipliers[idx] = mult as u128; } }) .collect_vec(); // only rescale if need to if multipliers.iter().any(|&x| x > 1) { Ok(Box::new(Rescaled { inner: Box::new(op.into()), scale: (0..input_scales.len()).zip(multipliers).collect_vec(), })) } else { Ok(op) } } #[cfg(test)] pub mod tests { use super::*; #[test] fn test_flatten_valtensors() { let tensor1: Tensor<Fp> = (0..10).map(|x| x.into()).into(); let tensor2: Tensor<Fp> = (10..20).map(|x| x.into()).into(); let tensor3: Tensor<Fp> = (20..30).map(|x| x.into()).into(); let mut tensor = Tensor::new(Some(&[tensor1, tensor2, tensor3]), &[3]) .unwrap() .combine() .unwrap(); tensor.set_visibility(&Visibility::Public); let flattened: ValTensor<Fp> = tensor.try_into().unwrap(); assert_eq!(flattened.len(), 30); let split = split_valtensor(&flattened, vec![vec![2, 5], vec![10], vec![5, 2]]).unwrap(); assert_eq!(split.len(), 3); assert_eq!(split[0].len(), 10); assert_eq!(split[0].dims(), vec![2, 5]); assert_eq!(split[1].len(), 10); assert_eq!(split[1].dims(), vec![10]); assert_eq!(split[2].dims(), vec![5, 2]); assert_eq!(split[2].len(), 10); } }
https://github.com/zkonduit/ezkl
src/graph/vars.rs
use std::error::Error; use std::fmt::Display; use crate::tensor::TensorType; use crate::tensor::{ValTensor, VarTensor}; use crate::RunArgs; use halo2_proofs::plonk::{Column, ConstraintSystem, Instance}; use halo2curves::ff::PrimeField; use itertools::Itertools; use log::debug; #[cfg(feature = "python-bindings")] use pyo3::{ exceptions::PyValueError, types::PyString, FromPyObject, IntoPy, PyAny, PyObject, PyResult, PyTryFrom, Python, ToPyObject, }; use serde::{Deserialize, Serialize}; use tosubcommand::ToFlags; use super::*; /// Label enum to track whether model input, model parameters, and model output are public, private, or hashed #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Default)] pub enum Visibility { /// Mark an item as private to the prover (not in the proof submitted for verification) #[default] Private, /// Mark an item as public (sent in the proof submitted for verification) Public, /// Mark an item as publicly committed to (hash sent in the proof submitted for verification) Hashed { /// Whether the hash is used as an instance (sent in the proof submitted for verification) /// if false the hash is used as an advice (not in the proof submitted for verification) and is then sent to the computational graph /// if true the hash is used as an instance (sent in the proof submitted for verification) the *inputs* to the hashing function are then sent to the computational graph hash_is_public: bool, /// outlets: Vec<usize>, }, /// Mark an item as publicly committed to (KZG commitment sent in the proof submitted for verification) KZGCommit, /// assigned as a constant in the circuit Fixed, } impl Display for Visibility { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Visibility::KZGCommit => write!(f, "polycommit"), Visibility::Private => write!(f, "private"), Visibility::Public => write!(f, "public"), Visibility::Fixed => write!(f, "fixed"), Visibility::Hashed { hash_is_public, outlets, } => { if *hash_is_public { write!(f, "hashed/public") } else { write!(f, "hashed/private/{}", outlets.iter().join(",")) } } } } } impl ToFlags for Visibility { fn to_flags(&self) -> Vec<String> { vec![format!("{}", self)] } } impl<'a> From<&'a str> for Visibility { fn from(s: &'a str) -> Self { if s.contains("hashed/private") { // split on last occurence of '/' let (_, outlets) = s.split_at(s.rfind('/').unwrap()); let outlets = outlets .trim_start_matches('/') .split(',') .map(|s| s.parse::<usize>().unwrap()) .collect_vec(); return Visibility::Hashed { hash_is_public: false, outlets, }; } match s { "private" => Visibility::Private, "public" => Visibility::Public, "polycommit" => Visibility::KZGCommit, "fixed" => Visibility::Fixed, "hashed" | "hashed/public" => Visibility::Hashed { hash_is_public: true, outlets: vec![], }, _ => { log::error!("Invalid value for Visibility: {}", s); log::warn!("Defaulting to private"); Visibility::Private } } } } #[cfg(feature = "python-bindings")] /// Converts Visibility into a PyObject (Required for Visibility to be compatible with Python) impl IntoPy<PyObject> for Visibility { fn into_py(self, py: Python) -> PyObject { match self { Visibility::Private => "private".to_object(py), Visibility::Public => "public".to_object(py), Visibility::Fixed => "fixed".to_object(py), Visibility::KZGCommit => "polycommit".to_object(py), Visibility::Hashed { hash_is_public, outlets, } => { if hash_is_public { "hashed/public".to_object(py) } else { let outlets = outlets .iter() .map(|o| o.to_string()) .collect_vec() .join(","); format!("hashed/private/{}", outlets).to_object(py) } } } } } #[cfg(feature = "python-bindings")] /// Obtains Visibility from PyObject (Required for Visibility to be compatible with Python) impl<'source> FromPyObject<'source> for Visibility { fn extract(ob: &'source PyAny) -> PyResult<Self> { let trystr = <PyString as PyTryFrom>::try_from(ob)?; let strval = trystr.to_string(); let strval = strval.as_str(); if strval.contains("hashed/private") { // split on last occurence of '/' let (_, outlets) = strval.split_at(strval.rfind('/').unwrap()); let outlets = outlets .trim_start_matches('/') .split(',') .map(|s| s.parse::<usize>().unwrap()) .collect_vec(); return Ok(Visibility::Hashed { hash_is_public: false, outlets, }); } match strval.to_lowercase().as_str() { "private" => Ok(Visibility::Private), "public" => Ok(Visibility::Public), "polycommit" => Ok(Visibility::KZGCommit), "hashed" => Ok(Visibility::Hashed { hash_is_public: true, outlets: vec![], }), "hashed/public" => Ok(Visibility::Hashed { hash_is_public: true, outlets: vec![], }), "fixed" => Ok(Visibility::Fixed), _ => Err(PyValueError::new_err("Invalid value for Visibility")), } } } impl Visibility { #[allow(missing_docs)] pub fn is_fixed(&self) -> bool { matches!(&self, Visibility::Fixed) } #[allow(missing_docs)] pub fn is_private(&self) -> bool { matches!(&self, Visibility::Private) || self.is_hashed_private() } #[allow(missing_docs)] pub fn is_public(&self) -> bool { matches!(&self, Visibility::Public) } #[allow(missing_docs)] pub fn is_hashed(&self) -> bool { matches!(&self, Visibility::Hashed { .. }) } #[allow(missing_docs)] pub fn is_polycommit(&self) -> bool { matches!(&self, Visibility::KZGCommit) } #[allow(missing_docs)] pub fn is_hashed_public(&self) -> bool { if let Visibility::Hashed { hash_is_public: true, .. } = self { return true; } false } #[allow(missing_docs)] pub fn is_hashed_private(&self) -> bool { if let Visibility::Hashed { hash_is_public: false, .. } = self { return true; } false } #[allow(missing_docs)] pub fn requires_processing(&self) -> bool { matches!(&self, Visibility::Hashed { .. }) | matches!(&self, Visibility::KZGCommit) } #[allow(missing_docs)] pub fn overwrites_inputs(&self) -> Vec<usize> { if let Visibility::Hashed { outlets, .. } = self { return outlets.clone(); } vec![] } } /// Represents the scale of the model input, model parameters. #[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, PartialOrd)] pub struct VarScales { /// pub input: crate::Scale, /// pub params: crate::Scale, /// pub rebase_multiplier: u32, } impl std::fmt::Display for VarScales { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "(inputs: {}, params: {})", self.input, self.params) } } impl VarScales { /// pub fn get_max(&self) -> crate::Scale { std::cmp::max(self.input, self.params) } /// pub fn get_min(&self) -> crate::Scale { std::cmp::min(self.input, self.params) } /// Place in [VarScales] struct. pub fn from_args(args: &RunArgs) -> Result<Self, Box<dyn Error>> { Ok(Self { input: args.input_scale, params: args.param_scale, rebase_multiplier: args.scale_rebase_multiplier, }) } } /// Represents whether the model input, model parameters, and model output are Public or Private to the prover. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, PartialOrd)] pub struct VarVisibility { /// Input to the model or computational graph pub input: Visibility, /// Parameters, such as weights and biases, in the model pub params: Visibility, /// Output of the model or computational graph pub output: Visibility, } impl std::fmt::Display for VarVisibility { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!( f, "(inputs: {}, params: {}, outputs: {})", self.input, self.params, self.output ) } } impl Default for VarVisibility { fn default() -> Self { Self { input: Visibility::Private, params: Visibility::Private, output: Visibility::Public, } } } impl VarVisibility { /// Read from cli args whether the model input, model parameters, and model output are Public or Private to the prover. /// Place in [VarVisibility] struct. pub fn from_args(args: &RunArgs) -> Result<Self, Box<dyn Error>> { let input_vis = &args.input_visibility; let params_vis = &args.param_visibility; let output_vis = &args.output_visibility; if params_vis.is_public() { return Err( "public visibility for params is deprecated, please use `fixed` instead".into(), ); } if !output_vis.is_public() & !params_vis.is_public() & !input_vis.is_public() & !output_vis.is_fixed() & !params_vis.is_fixed() & !input_vis.is_fixed() & !output_vis.is_hashed() & !params_vis.is_hashed() & !input_vis.is_hashed() & !output_vis.is_polycommit() & !params_vis.is_polycommit() & !input_vis.is_polycommit() { return Err(Box::new(GraphError::Visibility)); } Ok(Self { input: input_vis.clone(), params: params_vis.clone(), output: output_vis.clone(), }) } } /// A wrapper for holding all columns that will be assigned to by a model. #[derive(Clone, Debug)] pub struct ModelVars<F: PrimeField + TensorType + PartialOrd> { #[allow(missing_docs)] pub advices: Vec<VarTensor>, #[allow(missing_docs)] pub instance: Option<ValTensor<F>>, } impl<F: PrimeField + TensorType + PartialOrd + std::hash::Hash> ModelVars<F> { /// Get instance col pub fn get_instance_col(&self) -> Option<&Column<Instance>> { if let Some(instance) = &self.instance { match instance { ValTensor::Instance { inner, .. } => Some(inner), _ => None, } } else { None } } /// Set the initial instance offset pub fn set_initial_instance_offset(&mut self, offset: usize) { if let Some(instance) = &mut self.instance { instance.set_initial_instance_offset(offset); } } /// Get the total instance len pub fn get_instance_len(&self) -> usize { if let Some(instance) = &self.instance { instance.get_total_instance_len() } else { 0 } } /// Increment the instance offset pub fn increment_instance_idx(&mut self) { if let Some(instance) = &mut self.instance { instance.increment_idx(); } } /// Reset the instance offset pub fn set_instance_idx(&mut self, val: usize) { if let Some(instance) = &mut self.instance { instance.set_idx(val); } } /// Get the instance offset pub fn get_instance_idx(&self) -> usize { if let Some(instance) = &self.instance { instance.get_idx() } else { 0 } } /// pub fn instantiate_instance( &mut self, cs: &mut ConstraintSystem<F>, instance_dims: Vec<Vec<usize>>, instance_scale: crate::Scale, existing_instance: Option<Column<Instance>>, ) { debug!("model uses {:?} instance dims", instance_dims); self.instance = if let Some(existing_instance) = existing_instance { debug!("using existing instance"); Some(ValTensor::new_instance_from_col( instance_dims, instance_scale, existing_instance, )) } else { Some(ValTensor::new_instance(cs, instance_dims, instance_scale)) }; } /// Allocate all columns that will be assigned to by a model. pub fn new(cs: &mut ConstraintSystem<F>, params: &GraphSettings) -> Self { debug!("number of blinding factors: {}", cs.blinding_factors()); let logrows = params.run_args.logrows as usize; let var_len = params.total_assignments; let num_inner_cols = params.run_args.num_inner_cols; let num_constants = params.total_const_size; let module_requires_fixed = params.module_requires_fixed(); let requires_dynamic_lookup = params.requires_dynamic_lookup(); let requires_shuffle = params.requires_shuffle(); let dynamic_lookup_and_shuffle_size = params.dynamic_lookup_and_shuffle_col_size(); let mut advices = (0..3) .map(|_| VarTensor::new_advice(cs, logrows, num_inner_cols, var_len)) .collect_vec(); if requires_dynamic_lookup || requires_shuffle { let num_cols = if requires_dynamic_lookup { 3 } else { 2 }; for _ in 0..num_cols { let dynamic_lookup = VarTensor::new_advice(cs, logrows, 1, dynamic_lookup_and_shuffle_size); if dynamic_lookup.num_blocks() > 1 { panic!("dynamic lookup or shuffle should only have one block"); }; advices.push(dynamic_lookup); } } debug!( "model uses {} advice blocks (size={})", advices.iter().map(|v| v.num_blocks()).sum::<usize>(), num_inner_cols ); let num_const_cols = VarTensor::constant_cols(cs, logrows, num_constants, module_requires_fixed); debug!("model uses {} fixed columns", num_const_cols); ModelVars { advices, instance: None, } } /// Allocate all columns that will be assigned to by a model. pub fn new_dummy() -> Self { ModelVars { advices: vec![], instance: None, } } }
https://github.com/zkonduit/ezkl
src/lib.rs
#![deny( bad_style, dead_code, improper_ctypes, non_shorthand_field_patterns, no_mangle_generic_items, overflowing_literals, path_statements, patterns_in_fns_without_body, unconditional_recursion, unused, unused_allocation, unused_comparisons, unused_parens, while_true, missing_docs, trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, missing_debug_implementations, unsafe_code )] // we allow this for our dynamic range based indexing scheme #![allow(clippy::single_range_in_vec_init)] //! A library for turning computational graphs, such as neural networks, into ZK-circuits. //! use std::str::FromStr; use circuit::{table::Range, CheckMode, Tolerance}; use clap::Args; use graph::Visibility; use halo2_proofs::poly::{ ipa::commitment::IPACommitmentScheme, kzg::commitment::KZGCommitmentScheme, }; use halo2curves::bn256::{Bn256, G1Affine}; use serde::{Deserialize, Serialize}; use tosubcommand::ToFlags; /// Methods for configuring tensor operations and assigning values to them in a Halo2 circuit. pub mod circuit; /// CLI commands. #[cfg(not(target_arch = "wasm32"))] pub mod commands; #[cfg(not(target_arch = "wasm32"))] // abigen doesn't generate docs for this module #[allow(missing_docs)] /// Utility functions for contracts pub mod eth; /// Command execution /// #[cfg(not(target_arch = "wasm32"))] pub mod execute; /// Utilities for converting from Halo2 Field types to integers (and vice-versa). pub mod fieldutils; /// Methods for loading onnx format models and automatically laying them out in /// a Halo2 circuit. #[cfg(feature = "onnx")] pub mod graph; /// beautiful logging #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] pub mod logger; /// Tools for proofs and verification used by cli pub mod pfsys; /// Python bindings #[cfg(feature = "python-bindings")] pub mod python; /// srs sha hashes #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))] pub mod srs_sha; /// An implementation of multi-dimensional tensors. pub mod tensor; /// wasm prover and verifier #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] pub mod wasm; #[cfg(not(target_arch = "wasm32"))] use lazy_static::lazy_static; /// The denominator in the fixed point representation used when quantizing inputs pub type Scale = i32; #[cfg(not(target_arch = "wasm32"))] // Buf writer capacity lazy_static! { /// The capacity of the buffer used for writing to disk pub static ref EZKL_BUF_CAPACITY: usize = std::env::var("EZKL_BUF_CAPACITY") .unwrap_or("8000".to_string()) .parse() .unwrap(); /// The serialization format for the keys pub static ref EZKL_KEY_FORMAT: String = std::env::var("EZKL_KEY_FORMAT") .unwrap_or("raw-bytes".to_string()); } #[cfg(target_arch = "wasm32")] const EZKL_KEY_FORMAT: &str = "raw-bytes"; #[cfg(target_arch = "wasm32")] const EZKL_BUF_CAPACITY: &usize = &8000; #[derive( Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default, Copy, )] /// Commitment scheme pub enum Commitments { #[default] /// KZG KZG, /// IPA IPA, } impl From<Option<Commitments>> for Commitments { fn from(value: Option<Commitments>) -> Self { value.unwrap_or(Commitments::KZG) } } impl FromStr for Commitments { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_lowercase().as_str() { "kzg" => Ok(Commitments::KZG), "ipa" => Ok(Commitments::IPA), _ => Err("Invalid value for Commitments".to_string()), } } } impl From<KZGCommitmentScheme<Bn256>> for Commitments { fn from(_value: KZGCommitmentScheme<Bn256>) -> Self { Commitments::KZG } } impl From<IPACommitmentScheme<G1Affine>> for Commitments { fn from(_value: IPACommitmentScheme<G1Affine>) -> Self { Commitments::IPA } } impl std::fmt::Display for Commitments { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Commitments::KZG => write!(f, "kzg"), Commitments::IPA => write!(f, "ipa"), } } } impl ToFlags for Commitments { /// Convert the struct to a subcommand string fn to_flags(&self) -> Vec<String> { vec![format!("{}", self)] } } impl From<String> for Commitments { fn from(value: String) -> Self { match value.to_lowercase().as_str() { "kzg" => Commitments::KZG, "ipa" => Commitments::IPA, _ => { log::error!("Invalid value for Commitments"); log::warn!("defaulting to KZG"); Commitments::KZG } } } } /// Parameters specific to a proving run #[derive(Debug, Args, Deserialize, Serialize, Clone, PartialEq, PartialOrd, ToFlags)] pub struct RunArgs { /// The tolerance for error on model outputs #[arg(short = 'T', long, default_value = "0")] pub tolerance: Tolerance, /// The denominator in the fixed point representation used when quantizing inputs #[arg(short = 'S', long, default_value = "7", allow_hyphen_values = true)] pub input_scale: Scale, /// The denominator in the fixed point representation used when quantizing parameters #[arg(long, default_value = "7", allow_hyphen_values = true)] pub param_scale: Scale, /// 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) #[arg(long, default_value = "1")] pub scale_rebase_multiplier: u32, /// The min and max elements in the lookup table input column #[arg(short = 'B', long, value_parser = parse_key_val::<i128, i128>, default_value = "-32768->32768")] pub lookup_range: Range, /// The log_2 number of rows #[arg(short = 'K', long, default_value = "17")] pub logrows: u32, /// The log_2 number of rows #[arg(short = 'N', long, default_value = "2")] pub num_inner_cols: usize, /// Hand-written parser for graph variables, eg. batch_size=1 #[arg(short = 'V', long, value_parser = parse_key_val::<String, usize>, default_value = "batch_size->1", value_delimiter = ',')] pub variables: Vec<(String, usize)>, /// Flags whether inputs are public, private, hashed, fixed, kzgcommit #[arg(long, default_value = "private")] pub input_visibility: Visibility, /// Flags whether outputs are public, private, fixed, hashed, kzgcommit #[arg(long, default_value = "public")] pub output_visibility: Visibility, /// Flags whether params are fixed, private, hashed, kzgcommit #[arg(long, default_value = "private")] pub param_visibility: Visibility, #[arg(long, default_value = "false")] /// Rebase the scale using lookup table for division instead of using a range check pub div_rebasing: bool, /// Should constants with 0.0 fraction be rebased to scale 0 #[arg(long, default_value = "false")] pub rebase_frac_zero_constants: bool, /// check mode (safe, unsafe, etc) #[arg(long, default_value = "unsafe")] pub check_mode: CheckMode, /// commitment scheme #[arg(long, default_value = "kzg")] pub commitment: Option<Commitments>, } impl Default for RunArgs { fn default() -> Self { Self { tolerance: Tolerance::default(), input_scale: 7, param_scale: 7, scale_rebase_multiplier: 1, lookup_range: (-32768, 32768), logrows: 17, num_inner_cols: 2, variables: vec![("batch_size".to_string(), 1)], input_visibility: Visibility::Private, output_visibility: Visibility::Public, param_visibility: Visibility::Private, div_rebasing: false, rebase_frac_zero_constants: false, check_mode: CheckMode::UNSAFE, commitment: None, } } } impl RunArgs { /// pub fn validate(&self) -> Result<(), Box<dyn std::error::Error>> { if self.param_visibility == Visibility::Public { return Err( "params cannot be public instances, you are probably trying to use `fixed` or `kzgcommit`" .into(), ); } if self.scale_rebase_multiplier < 1 { return Err("scale_rebase_multiplier must be >= 1".into()); } if self.lookup_range.0 > self.lookup_range.1 { return Err("lookup_range min is greater than max".into()); } if self.logrows < 1 { return Err("logrows must be >= 1".into()); } if self.num_inner_cols < 1 { return Err("num_inner_cols must be >= 1".into()); } if self.tolerance.val > 0.0 && self.output_visibility != Visibility::Public { return Err("tolerance > 0.0 requires output_visibility to be public".into()); } Ok(()) } /// Export the ezkl configuration as json pub fn as_json(&self) -> Result<String, Box<dyn std::error::Error>> { let serialized = match serde_json::to_string(&self) { Ok(s) => s, Err(e) => { return Err(Box::new(e)); } }; Ok(serialized) } /// Parse an ezkl configuration from a json pub fn from_json(arg_json: &str) -> Result<Self, serde_json::Error> { serde_json::from_str(arg_json) } } /// Parse a single key-value pair fn parse_key_val<T, U>( s: &str, ) -> Result<(T, U), Box<dyn std::error::Error + Send + Sync + 'static>> where T: std::str::FromStr + std::fmt::Debug, T::Err: std::error::Error + Send + Sync + 'static, U: std::str::FromStr + std::fmt::Debug, U::Err: std::error::Error + Send + Sync + 'static, { let pos = s .find("->") .ok_or_else(|| format!("invalid x->y: no `->` found in `{s}`"))?; let a = s[..pos].parse()?; let b = s[pos + 2..].parse()?; Ok((a, b)) }
https://github.com/zkonduit/ezkl
src/logger.rs
use colored::*; use env_logger::Builder; use log::{Level, LevelFilter, Record}; use std::env; use std::fmt::Formatter; use std::io::Write; /// sets the log level color #[allow(dead_code)] pub fn level_color(level: &log::Level, msg: &str) -> String { match level { Level::Error => msg.red(), Level::Warn => msg.yellow(), Level::Info => msg.blue(), Level::Debug => msg.green(), Level::Trace => msg.magenta(), } .bold() .to_string() } /// sets the log level text color pub fn level_text_color(level: &log::Level, msg: &str) -> String { match level { Level::Error => msg.red(), Level::Warn => msg.yellow(), Level::Info => msg.white(), Level::Debug => msg.white(), Level::Trace => msg.white(), } .bold() .to_string() } /// sets the log level token fn level_token(level: &Level) -> &str { match *level { Level::Error => "E", Level::Warn => "W", Level::Info => "*", Level::Debug => "D", Level::Trace => "T", } } /// sets the log level prefix token fn prefix_token(level: &Level) -> String { format!( "{}{}{}", "[".blue().bold(), level_color(level, level_token(level)), "]".blue().bold() ) } /// formats the log pub fn format(buf: &mut Formatter, record: &Record<'_>) -> Result<(), std::fmt::Error> { let sep = format!("\n{} ", " | ".white().bold()); let level = record.level(); writeln!( buf, "{} {}", prefix_token(&level), level_color(&level, record.args().as_str().unwrap()).replace('\n', &sep), ) } /// initializes the logger pub fn init_logger() { let mut builder = Builder::new(); builder.format(move |buf, record| { writeln!( buf, "{} [{}, {}] - {}", prefix_token(&record.level()), // pretty print UTC time chrono::Utc::now() .format("%Y-%m-%d %H:%M:%S") .to_string() .bright_magenta(), record.metadata().target(), level_text_color(&record.level(), &format!("{}", record.args())) .replace('\n', &format!("\n{} ", " | ".white().bold())) ) }); builder.target(env_logger::Target::Stdout); builder.filter(None, LevelFilter::Info); if env::var("RUST_LOG").is_ok() { builder.parse_filters(&env::var("RUST_LOG").unwrap()); } builder.init(); }
https://github.com/zkonduit/ezkl