text
stringlengths
1
2.05k
{ "cells": [ { "cell_type": "markdown", "id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67", "metadata": { "id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67" }, "source": [ "\n", " "\n", "We show how to use EZKL to prove that we know matrices $A$ and its generalized inverse $B$. Since these are large we deal with the KZG commitments, with $a$ the polycommit of $A$, $b$ the polycommit of $B$, and $ABA = A$.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "95613ee9", "metadata": { "id": "95613ee9" }, "outputs": [], "source": [ " "try:\n", " "
import google.colab\n", "
import subprocess\n", "
import sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ezkl\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n", "\n", " "except:\n", " pass\n", "\n", "\n", " "\n", " "from torch
import nn\n", "
import ezkl\n", "
import os\n", "
import json\n", "
import torch" ] }, { "cell_type": "code", "execution_count": null, "id": "9LgqGF56Qcdz", "metadata": { "id": "9LgqGF56Qcdz" }, "outputs": [], "source": [ "
class GeneralizedInverseProof(nn.Module):\n", " def __init__(self):\n", " super(GeneralizedInverseProof, self).__init__()\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self,A,B):\n", " " return torch.sum(torch.abs(A@B@A - A)) < 0.1\n", "\n", "circuit = GeneralizedInverseProof()" ] }, { "cell_type": "code", "execution_count": null, "id": "YRQLvvsXVs9s", "metadata": { "id": "YRQLvvsXVs9s" }, "outputs": [], "source": [ "gip_run_args = ezkl.PyRunArgs()\n", "gip_run_args.input_visibility = \"polycommit\" "gip_run_args.output_visibility = \"fixed\" "gip_run_args.param_visibility = \"fixed\" ] }, { "cell_type": "code", "execution_count": null, "id": "b37637c4", "metadata": { "id": "b37637c4" }, "outputs": [], "source": [ "model_path = os.path.join('network.onnx')\n", "compiled_model_path = os.path.join('network.compiled')\n", "pk_path = os.path.join('test.pk')\n", "vk_path = os.path.join('test.vk')\n", "settings_path = os.path.join('settings.json')\n", "\n", "witness_path = os.path.join('witness.json')\n", "data_path = os.path.join('input.json')" ] }, { "cell_type": "code", "execution_count": null, "id": "82db373a", "metadata": { "id": "82db373a" }, "outputs": [], "source": [ " "shape = [10, 10]\n", "\n", "A = 0.1*torch.rand(1,*shape, requires_grad=True)\n", "B = A.inverse()\n", "\n", " "circuit.eval()\n", "\n", " "torch.onnx.export(circuit, " (A,B), " model_path, " export_params=True,
" opset_version=10, " do_constant_folding=True, " input_names = ['input1', 'input2'], " output_names = ['output'], " dynamic_axes={'input1' : {0 : 'batch_size'},\n", " 'input2' : {0 : 'batch_size'},\n", " 'output' : {0 : 'batch_size'}})\n", "\n", "d0 = ((A).detach().numpy()).reshape([-1]).tolist()\n", "d1 = ((B).detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(\n", " input_data=[d0, d1],\n", ")\n", "\n", " "json.dump( data, open(data_path, 'w' ))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "HOLcdGx4eQ9n", "metadata": { "colab": { "base_uri": "https: }, "id": "HOLcdGx4eQ9n", "outputId": "cd0a4f10-251e-492e-9f05-d8af0d79c86a" }, "outputs": [], "source": [ "circuit.forward(A,B)" ] }, { "cell_type": "code", "execution_count": null, "id": "d5e374a2", "metadata": { "colab": { "background_save": true, "base_uri": "https: }, "id": "d5e374a2", "outputId": "11ae5963-02d4-4939-9c98-d126071a9ba0" }, "outputs": [], "source": [ "\n", "res = ezkl.gen_settings(model_path, settings_path, py_run_args=gip_run_args)\n", "\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cal_path = os.path.join(\"calibration.json\")\n", "\n", "data_array = (0.1*torch.rand(20,*shape).detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array])\n", "\n", "
"json.dump(data, open(cal_path, 'w'))\n", "\n", "\n", "res = ezkl.calibrate_settings(data_path, model_path, settings_path, \"resources\")\n", "assert res == True\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3aa4f090", "metadata": { "id": "3aa4f090" }, "outputs": [], "source": [ "res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "id": "8b74dcee", "metadata": { "id": "8b74dcee" }, "outputs": [], "source": [ " "res = ezkl.get_srs( settings_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "18c8b7c7", "metadata": { "id": "18c8b7c7" }, "outputs": [], "source": [ " "\n", "res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\n", "assert os.path.isfile(witness_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "b1c561a8", "metadata": { "id": "b1c561a8" }, "outputs": [], "source": [ "\n", " " "res = ezkl.setup(\n", " compiled_model_path,\n", " vk_path,\n", " pk_path,\n", " \n", " witness_path = witness_path,\n", " )\n", "\n", "assert res == True\n", "assert os.path.isfile(vk_path)\n", "assert os.path.isfile(pk_path)\n", "assert os.path.isfile(settings_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "c384cbc8", "metadata": { "id": "c384cbc8" }, "outputs": [], "source": [ " "\n", "\n", "proof_path = os.path.join('test.pf')\n", "\n",
"res = ezkl.prove(\n", " witness_path,\n", " compiled_model_path,\n", " pk_path,\n", " proof_path,\n", " \n", " \"single\",\n", " )\n", "\n", "print(res)\n", "assert os.path.isfile(proof_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "76f00d41", "metadata": { "id": "76f00d41" }, "outputs": [], "source": [ " "\n", "res = ezkl.verify(\n", " proof_path,\n", " settings_path,\n", " vk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "print(\"verified\")" ] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.15" } }, "nbformat": 4, "nbformat_minor": 5 }
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lvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4Kk67BXQAAJDZJREFUeAHtnQuwVVUZxxfKS+QlIKJg8pSXKJQ8VbxqqKBjJmlaUxra5KTWZPhoSoXR1DR10lIZHUsrRZMJy8hSlLhAoJiIFSqKegUUBHkICEgZ/2X7uO/hnHP3Pufsc/ZZ67dmzr377L3W2uv7ffv+73rvZqNGjfrYECAAAQh4SGAvD23GZAhAAAKWAALIgwABCHhLAAH01vUYDgEIIIA8AxCAgLcEEEBvXY/hEIAAAsgzAAEIeEsAAfTW9RgOAQgggDwDEICAtwQQQG9dj+EQgAACyDMAAQh4SwAB9Nb1GA4BCCCAPAMQgIC3BBBAb12P4RCAAALIMwABCHhLAAH01vUYDgEIIIA8AxCAgLcEEEBvXY/hEIAAAsgzAAEIeEsAAfTW9RgOAQgggDwDEICAtwQQQG9dj+EQgAACyDMAAQh4SwAB9Nb1GA4BCCCAPAMQgIC3BBBAb12P4RCAAALIMwABCHhLAAH01vUYDgEIIIA8AxCAgLcEEEBvXY/hEIAAAs
gzAAEIeEsAAfTW9RgOAQgggDwDEICAtwQQQG9dj+EQgAACyDMAAQh4SwAB9Nb1GA4BCCCAPAMQgIC3BBBAb12P4RCAAALIMwABCHhLAAH01vUYDgEIIIA8AxCAgLcEEEBvXY/hEIAAAsgzAAEIeEsAAfTW9RgOAQgggDwDEICAtwQQQG9dj+EQgAACyDMAAQh4SwAB9Nb1GA4BCCCAPAMQgIC3BBBAb12P4RCAAALIMwABCHhLAAH01vUYDgEIIIA8AxCAgLcEEEBvXY/hEIAAAsgzAAEIeEsAAfTW9RgOAQgggDwDEICAtwQQQG9dj+EQgAACyDMAAQh4SwAB9Nb1GA4BCCCAPAMQgIC3BBBAb12P4RCAAALIMwABCHhLoLm3lmN4LAIffvih0ee } }, "cell_type": "markdown", "id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67", "metadata": {}, "source": [ " "\n", "\n", "Sklearn based models are slightly finicky to get into a suitable onnx format. By default most tree based models will export into something that looks like this: \n", "\n", "\n", "![image.png](attachment:image.png)\n", "\n", "\n", "Processing such nodes can be difficult and error prone. It would be much better if the operations of the tree were represented as a proper graph, possibly ... like this: \n", "\n", "\n", "![image-2.png](attachment:image-2.png)\n", "\n", "\n", "This notebook showcases how to do that using the `hummingbird-ml` python package ! " ] }, { "cell_type": "code", "execution_count": null, "id": "95613ee9", "metadata": {}, "outputs": [], "source": [ " "try:\n", " "
import google.colab\n", "
import subprocess\n", "
import sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ezkl\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"hummingbird-ml\"])\n", "\n", " "except:\n", " pass\n", "\n", "\n", " "\n", " "
import json\n", "
import numpy as np\n", "from sklearn.datasets
import load_iris\n", "from sklearn.model_selection
import train_test_split\n", "from sklearn.ensemble
import GradientBoostingClassifier as Gbc\n", "
import torch\n", "
import ezkl\n", "
import os\n", "from torch
import nn\n", "from hummingbird.ml
import convert\n", "\n", "\n", "NUM_CLASSES = 3\n", "\n", "iris = load_iris()\n", "X, y = iris.data, iris.target\n", "X = X.astype(np.float32)\n", "X_train, X_test, y_train, y_test = train_test_split(X, y)\n", "clr = Gbc()\n", "clr.fit(X_train, y_train)\n", "\n", "\n", "\n", "torch_gbt = convert(clr, \"torch\", X_test[:1])\n", " "diffs = []\n", "\n", "for i in range(len(X_test)):\n", " torch_pred = torch_gbt.predict(torch.tensor(X_test[i].reshape(1, -1)))\n", " sk_pred = clr.predict(X_test[i].reshape(1, -1))\n", " diffs.append(torch_pred != sk_pred[0])\n", "\n", "print(\"num diff: \", sum(diffs))\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b37637c4", "metadata": {}, "outputs": [], "source": [ "model_path = os.path.join('network.onnx')\n", "compiled_model_path = os.path.join('network.compiled')\n", "pk_path = os.path.join('test.pk')\n", "vk_path = os.path.join('test.vk')\n", "settings_path = os.path.join('settings.json')\n", "\n", "witness_path = os.path.join('witness.json')\n", "data_path = os.path.join('input.json')" ] }, { "cell_type": "code", "execution_count": null, "id": "82db373a", "metadata": {}, "outputs": [], "source": [ " "\n", "\n", "\n", " "shape = X_train.shape[1:]\n",
"x = torch.rand(1, *shape, requires_grad=False)\n", "torch_out = torch_gbt.predict(x)\n", " "torch.onnx.export(torch_gbt.model, " " x,\n", " " \"network.onnx\",\n", " export_params=True, " opset_version=18, " input_names=['input'], " output_names=['output'], " dynamic_axes={'input': {0: 'batch_size'}, " 'output': {0: 'batch_size'}})\n", "\n", "d = ((x).detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_shapes=[shape],\n", " input_data=[d],\n", " output_data=[o.reshape([-1]).tolist() for o in torch_out])\n", "\n", " "json.dump(data, open(\"input.json\", 'w'))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d5e374a2", "metadata": {}, "outputs": [], "source": [ "run_args = ezkl.PyRunArgs()\n", "run_args.variables = [(\"batch_size\", 1)]\n", "\n", " "res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\n", "assert res == True\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cal_path = os.path.join(\"calibration.json\")\n", "\n", "data_array = (torch.rand(20,*shape).
detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array])\n", "\n", " "json.dump(data, open(cal_path, 'w'))\n", "\n", "\n", "res = ezkl.calibrate_settings(data_path, model_path, settings_path, \"resources\")\n", "assert res == True\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3aa4f090", "metadata": {}, "outputs": [], "source": [ "res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "id": "8b74dcee", "metadata": {}, "outputs": [], "source": [ " "res = ezkl.get_srs( settings_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "18c8b7c7", "metadata": {}, "outputs": [], "source": [ " "\n", "res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\n", "assert os.path.isfile(witness_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "b1c561a8", "metadata": {}, "outputs": [], "source": [ "\n", " " " " "\n", "\n", "\n", "res = ezkl.setup(\n", " compiled_model_path,\n", " vk_path,\n", " pk_path,\n", " \n", " )\n",
"\n", "assert res == True\n", "assert os.path.isfile(vk_path)\n", "assert os.path.isfile(pk_path)\n", "assert os.path.isfile(settings_path)" ] }, { "cell_type": "code", "execution_count": 10, "id": "c384cbc8", "metadata": {}, "outputs": [], "source": [ " "\n", "\n", "proof_path = os.path.join('test.pf')\n", "\n", "res = ezkl.prove(\n", " witness_path,\n", " compiled_model_path,\n", " pk_path,\n", " proof_path,\n", " \n", " \"single\",\n", " )\n", "\n", "print(res)\n", "assert os.path.isfile(proof_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "76f00d41", "metadata": {}, "outputs": [], "source": [ " "\n", "res = ezkl.verify(\n", " proof_path,\n", " settings_path,\n", " vk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "print(\"verified\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python",
"pygments_lexer": "ipython3", "version": "3.9.15" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ " "\n", "Here's an example leveraging EZKL whereby the inputs to the model, and the model params themselves, are hashed inside a circuit.\n", "\n", "In this setup:\n", "- the hashes are publicly known to the prover and verifier\n", "- the hashes serve as \"public inputs\" (a.k.a instances) to the circuit\n", "\n", "We leave the outputs of the model as public as well (known to the verifier and prover). \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "First we
import the necessary dependencies and set up logging to be as informative as possible. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " "try:\n", " "
import google.colab\n", "
import subprocess\n", "
import sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ezkl\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n", "\n", " "except:\n", " pass\n", "\n", "from torch
import nn\n", "
import ezkl\n", "
import os\n", "
import json\n", "
import logging\n", "\n", " "FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\n", "logging.basicConfig(format=FORMAT)\n", "logging.getLogger().setLevel(logging.INFO)\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Now we define our model. It is a humble model with but a conv layer and a $ReLU$ non-linearity, but it is a model nonetheless" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "
import torch\n", " " " "\n", "
class MyModel(nn.Module):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", "\n", " self.conv1 = nn.Conv2d(in_channels=3, out_channels=1, kernel_size=5, stride=4)\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x):\n", " x = self.conv1(x)\n", " x = self.relu(x)\n", "\n", " return x\n", "\n", "\n", "circuit = MyModel()\n", "\n", " "\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "We omit training for purposes of this demonstration. We've marked where training would happen in the cell above. \n", "Now we export the model to onnx and create a corresponding (randomly generated) input file.\n", "\n", "You can replace the random `x` with real data if you so wish. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "shape = [3, 8, 8]\n", "x = torch.rand(1,*shape, requires_grad=True)\n", "\n", " "circuit.eval()\n", "\n", " "torch.onnx.export(circuit, " x, " \"network.onnx\", " export_params=True, " opset_version=10, " do_constant_folding=True,
" input_names = ['input'], " output_names = ['output'], " dynamic_axes={'input' : {0 : 'batch_size'}, " 'output' : {0 : 'batch_size'}})\n", "\n", "data_array = ((x).detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array])\n", "\n", " "json.dump( data, open(\"input.json\", 'w' ))\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "This is where the magic happens. We define our `PyRunArgs` objects which contains the visibility parameters for out model. \n", "- `input_visibility` defines the visibility of the model inputs\n", "- `param_visibility` defines the visibility of the model weights and constants and parameters \n", "- `output_visibility` defines the visibility of the model outputs\n", "\n", "There are currently 6 visibility settings:\n", "- `public`: known to both the verifier and prover (a subtle nuance is that this may not be the case for model parameters but until we have more rigorous theoretical results we don't want to make strong claims as to this). \n", "- `private`: known only to the prover\n", "- `fixed`: known to the prover and verifier (as a commit), but not modifiable by the prover.\n", "- `hashed`: the hash pre-image is known to the prover, the prover and verifier know the hash. The prover proves that the they know the pre-image to the hash. \n", "- `encrypted`: the non-encrypted element and the secret key used for decryption are known to the prover. The prover and the verifier know the encrypt
ed element, the public key used to encrypt, and the hash of the decryption hey. The prover proves that they know the pre-image of the hashed decryption key and that this key can in fact decrypt the encrypted message.\n", "- `polycommit`: unblinded advice column which generates a kzg commitment. This doesn't appear in the instances of the circuit and must instead be inserted directly within the proof bytes. \n", "\n", "\n", "Here we create the following setup:\n", "- `input_visibility`: \"hashed\"\n", "- `param_visibility`: \"hashed\"\n", "- `output_visibility`: public\n", "\n", "We encourage you to play around with other setups :) \n", "\n", "Shoutouts: \n", "\n", "- [summa-solvency](https: "- [timeofey](https: ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "
import ezkl\n", "\n", "model_path = os.path.join('network.onnx')\n", "compiled_model_path = os.path.join('network.compiled')\n", "pk_path = os.path.join('test.pk')\n", "vk_path = os.path.join('test.vk')\n", "settings_path = os.path.join('settings.json')\n", "\n", "data_path = os.path.join('input.json')\n", "\n", "run_args = ezkl.PyRunArgs()\n", "run_args.input_visibility = \"hashed\"\n", "run_args.param_visibility = \"hashed\"\n", "run_args.output_visibility = \"public\"\n", "run_args.variables = [(\"batch_size\", 1)]\n", "\n", "\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https: "\n", "You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we create a dummy calibration dataset for demonstration purposes. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!RUST_LOG=trace\n", " "res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "
"cal_data = {\n", " \"input_data\": [torch.cat((x, torch.rand(10, *[3, 8, 8]))).flatten().tolist()],\n", "}\n", "\n", "cal_path = os.path.join('val_data.json')\n", " "with open(cal_path, \"w\") as f:\n", " json.dump(cal_data, f)\n", "\n", "res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \"resources\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n", "assert res == True" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "As we use Halo2 with KZG-commitments we need an SRS string from (preferably) a multi-party trusted setup ceremony. For an overview of the procedures for such a ceremony check out [this page](https: "\n", "These SRS were generated with [this](https: ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "res = ezkl.get_srs( settings_path)\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "We now need to generate the (partial) circuit witness. These are the model outputs (and any hashes) that are generated when feeding the previously generated `input.json` through the circuit / model. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [
"!export RUST_BACKTRACE=1\n", "\n", "witness_path = \"witness.json\"\n", "\n", "res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "As a sanity check you can \"mock prove\" (i.e check that all the constraints of the circuit match without generate a full proof). " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "\n", "res = ezkl.mock(witness_path, compiled_model_path)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Here we setup verifying and proving keys for the circuit. As the name suggests the proving key is needed for ... proving and the verifying key is needed for ... verifying. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " " " " "res = ezkl.setup(\n", " compiled_model_path,\n", " vk_path,\n", " pk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "assert os.path.isfile(vk_path)\n", "assert os.path.isfile(pk_path)\n", "assert os.path.isfile(settings_path)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "
Now we generate a full proof. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " "\n", "proof_path = os.path.join('test.pf')\n", "\n", "res = ezkl.prove(\n", " witness_path,\n", " compiled_model_path,\n", " pk_path,\n", " proof_path,\n", " \n", " \"single\",\n", " )\n", "\n", "print(res)\n", "assert os.path.isfile(proof_path)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "And verify it as a sanity check. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " "\n", "res = ezkl.verify(\n", " proof_path,\n", " settings_path,\n", " vk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "print(\"verified\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "We can now create an EVM / `.sol` verifier that can be deployed on chain to verify submitted proofs using a view function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "abi_path = 'test.abi'\n",
"sol_code_path = 'test.sol'\n", "\n", "res = ezkl.create_evm_verifier(\n", " vk_path,\n", " \n", " settings_path,\n", " sol_code_path,\n", " abi_path,\n", " )\n", "assert res == True\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " " " "
import json\n", "\n", "address_path = os.path.join(\"address.json\")\n", "\n", "res = ezkl.deploy_evm(\n", " address_path,\n", " sol_code_path,\n", " 'http: ")\n", "\n", "assert res == True\n", "\n", "with open(address_path, 'r') as file:\n", " addr = file.read().rstrip()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " " "\n", "res = ezkl.verify_evm(\n", " addr,\n", " proof_path,\n", " \"http: ")\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "ezkl", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": null, "id": "a27b0cd9", "metadata": {}, "outputs": [], "source": [ " "try:\n", " "
import google.colab\n", "
import subprocess\n", "
import sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ezkl\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"tf2onnx\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n", "\n", " "except:\n", " pass\n", "\n", " "
import ezkl\n", "
import os\n", "
import json\n", "from keras.models
import Sequential\n", "from keras.layers
import Dense, Dropout, Activation, Flatten\n", "from keras.layers
import Convolution2D, MaxPooling2D\n", "
import logging\n", "\n", " " " " ] }, { "cell_type": "code", "execution_count": null, "id": "95613ee9", "metadata": {}, "outputs": [], "source": [ "\n", "\n", " " " "\n", "model = Sequential()\n", "model.add(Convolution2D(2, (3,3), activation='relu', input_shape=(28,28,1)))\n", "model.add(Convolution2D(2, (3,3), activation='relu'))\n", "model.add(MaxPooling2D(pool_size=(2,2)))\n", "model.add(Dropout(0.25))\n", "model.add(Flatten())\n", "model.add(Dense(128, activation='relu'))\n", "model.add(Dropout(0.5))\n", "model.add(Dense(10, activation='softmax'))\n", "model.output_names=['output']\n", "\n", "\n", " "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b37637c4", "metadata": {}, "outputs": [], "source": [ "model_path = os.path.join('network.onnx')\n", "compiled_model_path = os.path.join('network.compiled')\n", "pk_path = os.path.join('test.pk')\n", "vk_path = os.path.join('test.vk')\n", "settings_path = os.path.join('settings.json')\n", "\n", "witness_path = os.path.join('witness.json')\n", "data_path = os.path.join('input.json')" ] }, { "cell_type": "code", "execution_count": null, "id": "82db373a", "metadata": {}, "outputs": [], "source": [ "\n",
"
import numpy as np\n", "
import tf2onnx\n", "
import tensorflow as tf\n", "\n", "\n", "shape = [1, 28, 28]\n", " "x = 0.1*np.random.rand(1,*shape)\n", "\n", "spec = tf.TensorSpec([1, 28, 28, 1], tf.float32, name='input_0')\n", "\n", "\n", "tf2onnx.convert.from_keras(model, input_signature=[spec], inputs_as_nchw=['input_0'], opset=12, output_path=model_path)\n", "\n", "data_array = x.reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array])\n", "\n", " "json.dump( data, open(data_path, 'w' ))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d5e374a2", "metadata": {}, "outputs": [], "source": [ "!RUST_LOG=trace\n", "\n", " "res = ezkl.gen_settings(model_path, settings_path)\n", "assert res == True\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cal_path = os.path.join(\"calibration.json\")\n", "\n", "data_array = (0.1*np.random.rand(20,*shape)).reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array])\n", "\n", " "json.dump(data, open(cal_path, 'w'))\n", "\n", "\n", "res = ezkl.calibrate_settings(data_path, model_path, settings_path, \"resources\")\n", "assert res == True\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b6e051d5", "metadata": {},
"outputs": [], "source": [ "res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "id": "8b74dcee", "metadata": {}, "outputs": [], "source": [ " "res = ezkl.get_srs(settings_path = settings_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "18c8b7c7", "metadata": {}, "outputs": [], "source": [ " "witness_path = \"witness.json\"\n", "\n", "res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\n", "assert os.path.isfile(witness_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "b1c561a8", "metadata": {}, "outputs": [], "source": [ "\n", " " " " "\n", "res = ezkl.setup(\n", " compiled_model_path,\n", " vk_path,\n", " pk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "assert os.path.isfile(vk_path)\n", "assert os.path.isfile(pk_path)\n", "assert os.path.isfile(settings_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "c384cbc8", "metadata": {}, "outputs": [], "source": [ " "\n", "\n", "proof_path = os.path.join('test.pf')\n",
"\n", "res = ezkl.prove(\n", " witness_path,\n", " compiled_model_path,\n", " pk_path,\n", " proof_path,\n", " \n", " \"single\",\n", " )\n", "\n", "print(res)\n", "assert os.path.isfile(proof_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "76f00d41", "metadata": {}, "outputs": [], "source": [ " "res = ezkl.verify(\n", " proof_path,\n", " settings_path,\n", " vk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "print(\"verified\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67", "metadata": {}, "source": [ " "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "95613ee9", "metadata": {}, "outputs": [], "source": [ " "try:\n", " "
import google.colab\n", "
import subprocess\n", "
import sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ezkl\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"sk2torch\"])\n", "\n", " "except:\n", " pass\n", "\n", "\n", " "\n", " "
import json\n", "
import numpy as np\n", "from sklearn.cluster
import KMeans\n", "from hummingbird.ml
import convert\n", "
import torch\n", "
import ezkl\n", "
import os\n", "\n", "\n", " " "xs = np.concatenate(\n", " [\n", " np.random.random(size=(256, 2)) + [1, 0],\n", " np.random.random(size=(256, 2)) + [-1, 0],\n", " ],\n", " axis=0,\n", ")\n", "\n", " "sk_model = KMeans()\n", "sk_model.fit(xs)\n", "model = convert(sk_model, backend=\"pytorch\").model\n", "\n", "\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b37637c4", "metadata": {}, "outputs": [], "source": [ "model_path = os.path.join('network.onnx')\n", "compiled_model_path = os.path.join('network.compiled')\n", "pk_path = os.path.join('test.pk')\n", "vk_path = os.path.join('test.vk')\n", "settings_path = os.path.join('settings.json')\n", "\n", "witness_path = os.path.join('witness.json')\n", "data_path = os.path.join('input.json')" ] }, { "cell_type": "code", "execution_count": null, "id": "82db373a", "metadata": {}, "outputs": [], "source": [ "\n", "\n", " " " "spaced = np.linspace(-2, 2, num=25)\n", "grid_xs = torch.tensor([[x, y] for x in spaced for y in spaced], requires_grad=True)\n", "\n", " "shape = xs.shape[1:]\n", "x = grid_xs[0:1]\n", "torch_out = model(x)\n", " "torch.onnx
.export(model, " " x,\n", " " \"network.onnx\",\n", " export_params=True, " opset_version=10, " do_constant_folding=True, " input_names=['input'], " output_names=['output'], " dynamic_axes={'input': {0: 'batch_size'}, " 'output': {0: 'batch_size'}})\n", "\n", "d = ((x).detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_shapes=[shape],\n", " input_data=[d],\n", " output_data=[o.reshape([-1]).tolist() for o in torch_out])\n", "\n", " "json.dump(data, open(\"input.json\", 'w'))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d5e374a2", "metadata": {}, "outputs": [], "source": [ "!RUST_LOG=trace\n", " "res = ezkl.gen_settings(model_path, settings_path)\n", "assert res == True\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cal_path = os.path.join(\"calibration.json\")\n", "\n", "data_array = (grid_xs[0:20].detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array])\n", "\n", " "json.dump(data, open(cal_path, 'w'))\n", "\n",
"\n", "res = ezkl.calibrate_settings(data_path, model_path, settings_path, \"resources\")\n", "assert res == True\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3aa4f090", "metadata": {}, "outputs": [], "source": [ "res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "id": "8b74dcee", "metadata": {}, "outputs": [], "source": [ " "res = ezkl.get_srs( settings_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "18c8b7c7", "metadata": {}, "outputs": [], "source": [ " "\n", "res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\n", "assert os.path.isfile(witness_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "b1c561a8", "metadata": {}, "outputs": [], "source": [ "\n", " " " " "\n", "\n", "\n", "res = ezkl.setup(\n", " compiled_model_path,\n", " vk_path,\n", " pk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "assert os.path.isfile(vk_path)\n", "assert os.path.isfile(pk_path)\n", "assert os.path.isfile(settings_path)" ] }, { "
cell_type": "code", "execution_count": null, "id": "c384cbc8", "metadata": {}, "outputs": [], "source": [ " "\n", "\n", "proof_path = os.path.join('test.pf')\n", "\n", "res = ezkl.prove(\n", " witness_path,\n", " compiled_model_path,\n", " pk_path,\n", " proof_path,\n", " \n", " \"single\",\n", " )\n", "\n", "print(res)\n", "assert os.path.isfile(proof_path)" ] }, { "cell_type": "code", "execution_count": null, "id": "76f00d41", "metadata": {}, "outputs": [], "source": [ " "\n", "res = ezkl.verify(\n", " proof_path,\n", " settings_path,\n", " vk_path,\n", " \n", " )\n", "\n", "assert res == True\n", "print(\"verified\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ " "\n", "Here's an example leveraging EZKL whereby the inputs to the model, and the model params themselves, are committed to using kzg-commitments inside a circuit.\n", "\n", "In this setup:\n", "- the commitments are publicly known to the prover and verifier\n", "\n", "\n", "We leave the outputs of the model as public as well (known to the verifier and prover). \n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "First we
import the necessary dependencies and set up logging to be as informative as possible. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ " "try:\n", " "
import google.colab\n", "
import subprocess\n", "
import sys\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"ezkl\"])\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n", "\n", " "except:\n", " pass\n", "\n", "from torch
import nn\n", "
import ezkl\n", "
import os\n", "
import json\n", "
import logging\n", "\n", " "FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\n", "logging.basicConfig(format=FORMAT)\n", "logging.getLogger().setLevel(logging.INFO)\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Now we define our model. It is a humble model with but a conv layer and a $ReLU$ non-linearity, but it is a model nonetheless" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "
import torch\n", " " " "\n", "
class MyModel(nn.Module):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", "\n", " self.conv1 = nn.Conv2d(in_channels=3, out_channels=1, kernel_size=5, stride=4)\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x):\n", " x = self.conv1(x)\n", " x = self.relu(x)\n", "\n", " return x\n", "\n", "\n", "circuit = MyModel()\n", "\n", " "\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "We omit training for purposes of this demonstration. We've marked where training would happen in the cell above. \n", "Now we export the model to onnx and create a corresponding (randomly generated) input file.\n", "\n", "You can replace the random `x` with real data if you so wish. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = torch.rand(1,*[3, 8, 8], requires_grad=True)\n", "\n", " "circuit.eval()\n", "\n", " "torch.onnx.export(circuit, " x, " \"network.onnx\", " export_params=True, " opset_version=10, " do_constant_folding=True, " input_names = ['input'],
" output_names = ['output'], " dynamic_axes={'input' : {0 : 'batch_size'}, " 'output' : {0 : 'batch_size'}})\n", "\n", "data_array = ((x).detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array])\n", "\n", " "json.dump( data, open(\"input.json\", 'w' ))\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "This is where the magic happens. We define our `PyRunArgs` objects which contains the visibility parameters for out model. \n", "- `input_visibility` defines the visibility of the model inputs\n", "- `param_visibility` defines the visibility of the model weights and constants and parameters \n", "- `output_visibility` defines the visibility of the model outputs\n", "\n", "There are currently 6 visibility settings:\n", "- `public`: known to both the verifier and prover (a subtle nuance is that this may not be the case for model parameters but until we have more rigorous theoretical results we don't want to make strong claims as to this). \n", "- `private`: known only to the prover\n", "- `fixed`: known to the prover and verifier (as a commit), but not modifiable by the prover.\n", "- `hashed`: the hash pre-image is known to the prover, the prover and verifier know the hash. The prover proves that the they know the pre-image to the hash. \n", "- `encrypted`: the non-encrypted element and the secret key used for decryption are known to the prover. The prover and the verifier know the encrypted element, the public key used to encrypt, and the hash
of the decryption hey. The prover proves that they know the pre-image of the hashed decryption key and that this key can in fact decrypt the encrypted message.\n", "- `polycommit`: unblinded advice column which generates a kzg commitment. This doesn't appear in the instances of the circuit and must instead be modified directly within the proof bytes. \n", "\n", "Here we create the following setup:\n", "- `input_visibility`: \"polycommit\"\n", "- `param_visibility`: \"polycommit\"\n", "- `output_visibility`: public\n", "\n", "We encourage you to play around with other setups :) \n", "\n", "Shoutouts: \n", "\n", "- [summa-solvency](https: "- [timeofey](https: ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "
import ezkl\n", "\n", "model_path = os.path.join('network.onnx')\n", "compiled_model_path = os.path.join('network.compiled')\n", "pk_path = os.path.join('test.pk')\n", "vk_path = os.path.join('test.vk')\n", "settings_path = os.path.join('settings.json')\n", "\n", "data_path = os.path.join('input.json')\n", "\n", "run_args = ezkl.PyRunArgs()\n", "run_args.input_visibility = \"polycommit\"\n", "run_args.param_visibility = \"polycommit\"\n", "run_args.output_visibility = \"public\"\n", "run_args.variables = [(\"batch_size\", 1)]\n", "\n", "\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Now we generate a settings file. This file basically instantiates a bunch of parameters that determine their circuit shape, size etc... Because of the way we represent nonlinearities in the circuit (using Halo2's [lookup tables](https: "\n", "You can pass a dataset for calibration that will be representative of real inputs you might find if and when you deploy the prover. Here we create a dummy calibration dataset for demonstration purposes. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!RUST_LOG=trace\n", " "res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\n", "assert res == True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "