text
stringlengths
1
2.05k
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\n", "\n", "\n", " " " "\n", "
class MyModel(nn.Module):\n", " def __init__(self):\n", " super(MyModel, self).__init__()\n", "\n", " self.conv1 = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=5, stride=2)\n", " self.conv2 = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=5, stride=2)\n", "\n", " self.relu = nn.ReLU()\n", "\n", " self.d1 = nn.Linear(48, 48)\n", " self.d2 = nn.Linear(48, 10)\n", "\n", " def forward(self, x):\n", " " x = self.conv1(x)\n", " x = self.relu(x)\n", " x = self.conv2(x)\n", " x = self.relu(x)\n", "\n", " " x = x.flatten(start_dim = 1)\n", "\n", " " x = self.d1(x)\n", " x = self.relu(x)\n", "\n", " " logits = self.d2(x)\n", "\n", " return logits\n", "\n", "\n", "circuit = MyModel()\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", "shape = [1, 28, 28]\n", " "x = 0.1*torch.rand(1,*shape, requires_grad=True)\n", "\n", " "circuit.eval()\n", "\n", " "torch.onnx.export(circuit, " x, " model_path, " 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(data_path, 'w' ))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d5e374a2", "metadata": {}, "outputs": [], "source": [ "py_run_args = ezkl.PyRunArgs()\n", "py_run_args.input_visibility = \"private\"\n", "py_run_args.output_visibility = \"public\"\n", "py_run_args.param_visibility = \"fixed\" "\n", "res = ezkl.gen_settings(m
odel_path, settings_path, py_run_args=py_run_args)\n", "\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 = (torch.rand(20, *shape, requires_grad=True).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", "ezkl.calibrate_settings(cal_path, model_path, settings_path, \"resources\")" ] }, { "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": 9, "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.15" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "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. \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.neural_network
import MLPClassifier\n", "from hummingbird.ml
import convert\n", "
import torch\n", "
import ezkl\n", "
import os\n", "\n", "\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 = MLPClassifier()\n", "clr.fit(X_train, y_train)\n", "\n", "circuit = convert(clr, \"torch\", X_test[:1]).model\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", " " "\n", " "shape = X_train.shape[1:]\n", "x = torch.rand(1, *shape, requires_grad=True)\n", "torch_out = circuit(x)\n", " "torch.onnx.export(circuit, " " 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).detach().numpy()).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 = (torch.rand(20, *shape, requires_grad=True).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", "ezkl.calibrate_settings(cal_path, model_path, settings_path, \"resources\")" ] }, { "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.15" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "cell_type": "markdown", "id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67", "metadata": { "id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67" }, "source": [ " "\n", "Here we create a demo of a solvency calculation in the manner of [summa-solvency](https: "\n", "In this setup:\n", "- the commitments to users, respective balances, and total balance are known are publicly known to the prover and verifier. \n", "- We leave the outputs of the model as public as well (known to the verifier and prover). \n", "\n", "The circuit calculates the total sum of the balances, and checks that it is less than the total balance which is precommited to." ] }, { "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", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"pytest\"])\n", "\n", " "except:\n", " pass\n", "\n", " " " " " "\n", "\n", " "\n", " "from torch
import nn\n", "
import ezkl\n", "
import os\n", "
import json\n", "
import torch\n", "\n", "
class Circuit(nn.Module):\n", " def __init__(self):\n", " super(Circuit, self).__init__()\n", "\n", " def forward(self, users, balances, total):\n", " nil = torch.nn.Parameter(torch.tensor([0.0]))\n", " " balances = torch.sum(balances, dim=1) + nil * users\n", " " return (balances[:,0] <= total)\n", "\n", "\n", "circuit = Circuit()\n", "\n", " "\n" ] }, { "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": "markdown", "id": "1c21e56e", "metadata": {}, "source": [ "We create dummy data here for the sake of demonstration. In a real world scenario, the data would be provided by the users, and the commitments would be made by some trusted party.\n", "\n", "The users are generated as hashes of the integers 0 to 9. The balances are generated as integers between 0 and 10. \n", "\n", "The total balance is the sum of the balances." ] }, { "cell_type": "code", "execution_count": null, "id": "dfd6c7e7", "metadata": {}, "outputs": [], "source": [ "\n", "\n", "user_preimages = [0.0, 1.0, 2.0, 3.0, 4.0, 9.0]\n", "balances = torch.tensor([0, 2, 3, 4, 5, 10])\n", "balances = balances.reshape(1, 6)\n", "\n", "\n", " "users =
[]\n", "\n", " "for e in user_preimages:\n", " " users.append(ezkl.poseidon_hash([ezkl.float_to_felt(e, 0)])[0])\n", "\n", "users_t = torch.tensor(user_preimages)\n", "users_t = users_t.reshape(1, 6)\n", "\n", "total = torch.tensor([25])\n", "total = total.reshape(1, 1)\n", "\n", " "circuit.eval()\n", "\n", " "torch.onnx.export(circuit, " (users_t,balances,total), " model_path, " export_params=True, " opset_version=17, " do_constant_folding=False, " input_names = ['input'], " output_names = ['output'], " dynamic_axes={'input' : {0 : 'batch_size'}, " 'output' : {0 : 'batch_size'}})\n", "\n", "\n", " \n", "data_array_x = users\n", "data_array_y = ((balances).detach().numpy()).reshape([-1]).tolist()\n", "data_array_z = ((total).detach().numpy()).reshape([-1]).tolist()\n", "\n", "data = dict(input_data = [data_array_x, data_array_y, data_array_z])\n", "\n", "\n", " "json.dump( data, open(data_path, 'w' ))\n" ] }, { "cell_type": "markdown", "id": "22d3d8df", "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 5 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", "- `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`: \"public\"\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, "id": "d5e374a2", "metadata": { "id": "d5e374a2" }, "outputs": [], "source": [ "run_args = ezkl.PyRunArgs()\n", " "run_args.input_visibility = \"polycommit\"\n", " "run_args.param_visibility = \"fixed\"\n", " "run_args.output_visibility = \"public\"\n", "run_args.variables = [(\"batch_size\", 1)]\n", " "run_args.scale_rebase_multiplier = 1000\n",
" "run_args.logrows = 11\n", "run_args.lookup_range = (-1000,1000)\n", "run_args.input_scale = 0\n", "run_args.param_scale = 0\n", "\n", "\n", " "res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\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": { "colab": { "base_uri": "https: }, "id": "8b74dcee", "outputId": "f7b9198c-2b3d-48bb-c67e-8478333cedb5" }, "outputs": [], "source": [ " "res = ezkl.get_srs( settings_path)" ] }, { "cell_type": "markdown", "id": "f7c98c96", "metadata": {}, "source": [ "We'll generate two proofs, one with the correct total balance, and one with an incorrect total balance.\n", "\n", " "\n", "The data file above has a total balance of above the user total balance. We'll generate a proof with this total balance." ] }, { "cell_type": "code", "execution_count": null, "id": "93e90079", "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)" ] }, { "cell_type": "code", "execution_count": null, "id": "efa0ac91", "m
etadata": {}, "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, vk_path)\n", "assert os.path.isfile(witness_path)\n", "\n", " " "witness = json.load(open(witness_path, \"r\"))\n", "witness[\"outputs\"][0] = [ezkl.float_to_felt(1.0, 0)]\n", "json.dump(witness, open(witness_path, \"w\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "90973daf", "metadata": {}, "outputs": [], "source": [ "proof_path = os.path.join('proof.json')\n", " "res = ezkl.prove(\n", " witness_path,\n", " compiled_model_path,\n", " pk_path,\n", " proof_path,\n", " \n", " \"single\",\n", " )\n", "\n", "assert os.path.isfile(proof_path)\n", "\n", "print(res)\n" ] }, { "cell_type": "markdown", "id": "ef79b4ee", "metadata": {}, "source": [ "- now we swap the commitments of the proof as a way to demonstrate that the proof is valid given some public inputs \n", "- this is just for testing purposes and would
require fetching public commits from the blockchain or some other source\n", "- see https: ] }, { "cell_type": "code", "execution_count": null, "id": "8bb46735", "metadata": {}, "outputs": [], "source": [ "\n", "\n", "res = ezkl.swap_proof_commitments(proof_path, witness_path)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "59f3b1e9", "metadata": {}, "outputs": [], "source": [ " "res = ezkl.verify(\n", " proof_path,\n", " settings_path,\n", " vk_path,\n", " \n", " )\n", "assert res == True" ] }, { "cell_type": "markdown", "id": "77dec3dd", "metadata": {}, "source": [ " "\n", "We'll generate a proof with a total balance of 10. This is below the user total balance." ] }, { "cell_type": "code", "execution_count": null, "id": "FQfGdcUNpvuK", "metadata": { "id": "FQfGdcUNpvuK" }, "outputs": [], "source": [ " "
import random\n", "\n", "data_path_truthy = os.path.join('input.json')\n", "data = json.load(open(data_path, 'r' ))\n", "data['input_data'][2] = [10]\n", "\n", "data_path_faulty = os.path.join('input_faulty.json')\n", " "json.dump( data, open(data_path_faulty, 'w' ))\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b1c561a8", "metadata": { "id": "b1c561a8" }, "outputs": [], "source": [ " "\n", "res = ezkl.gen_witness(data_path_faulty, compiled_model_path, witness_path, vk_path)\n", "assert os.path.isfile(witness_path)\n", "\n", " " "witness = json.load(open(witness_path, \"r\"))\n", "witness[\"outputs\"][0] = [ezkl.float_to_felt(1.0, 0)]\n", "json.dump(witness, open(witness_path, \"w\"))\n" ] }, { "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": "4edaca46", "metadata": {}, "outputs": [], "source": [ "res = ezkl.swap_proof_commitments(proof_path, witness_path)\n" ] }, { "cell_type": "markdown", "id": "638d776f", "metadata": {}, "source": [ "Now we test that verification fails" ] }, { "cell_type": "code", "execution_count": null, "id": "4nqEx7-qpci
Q", "metadata": { "id": "4nqEx7-qpciQ" }, "outputs": [], "source": [ "
import pytest\n", "\n", "def test_verification():\n", " with pytest.raises(RuntimeError, match='Failed to run verify: The constraint system is not satisfied'):\n", " ezkl.verify(\n", " proof_path,\n", " settings_path,\n", " vk_path,\n", " \n", " )\n", "\n", " "test_verification()" ] } ], "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 }
{ "cells": [ { "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.\n", "This notebook showcases how to do so using the `hummingbird-ml` python package !\n", "\n", "We're going to combine a few models to create a stacked regression model.\n", "1. Linear Ridge Regression\n", "2. Support Vector Regression\n", "3. Random Forest Regression as a meta-estimator\n", "\n", "We then use hummingbird to convert the model to Torch and ONNX formats.\n", "\n", "\n", "\n", "We then use ezkl to run zk-proofs.\n", "\n", "The generated onnx should look like this:\n", "\n", "![Alt text](image.png)" ] }, { "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", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"scikit-learn==1.3.1\"])\n", "\n", " "except:\n", " pass\n", "\n", "
import os\n", "
import torch\n", "
import ezkl\n", "
import json\n", "from hummingbird.ml
import convert\n", "\n", "\n", " "\n", " "
import numpy as np\n", "from sklearn.linear_model
import RidgeCV\n", "from sklearn.svm
import LinearSVR\n", "from sklearn.ensemble
import RandomForestRegressor\n", "from sklearn.ensemble
import StackingRegressor\n", "\n", "estimators = [\n", " ('lr', RidgeCV()),\n", " ('svr', LinearSVR(dual=\"auto\", random_state=42))\n", "]\n", "\n", "X = np.array([[1, 1], [1, 2], [2, 2], [2, 3], [3, 3], [4, 4], [6, 8]])\n", " "y = np.dot(X, np.array([1, 2])) + 3\n", "\n", "reg = StackingRegressor(\n", " estimators=estimators,\n", " final_estimator=RandomForestRegressor(n_estimators=2,\n", " random_state=42)\n", ")\n", "reg.fit(X, y)\n", "reg.score(X, y)\n", "\n", "circuit = convert(reg, \"torch\", X[:1]).model\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "8b0a6f4b", "metadata": {}, "outputs": [], "source": [ "print(circuit)" ] }, { "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": {}, "ou
tputs": [], "source": [ "\n", "\n", " " "\n", " "shape = X.shape[1:]\n", "x = torch.rand(1, *shape, requires_grad=True)\n", "torch_out = circuit(x)\n", " "torch.onnx.export(circuit, " " 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).detach().numpy()).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", "\n", "res = ezkl.calibrate_settings(data_path, model_path, settings_path, \"resources\")\n", "assert res == True" ] }, {
"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cal_path = os.path.join(\"calibration.json\")\n", "\n", "data_array = (torch.rand(20, *shape, requires_grad=True).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", "ezkl.calibrate_settings(cal_path, model_path, settings_path, \"resources\")" ] }, { "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.15" } }, "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.svm
import SVC\n", "
import sk2torch\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", "ys = np.array([False] * 256 + [True] * 256)\n", "\n", " "sk_model = SVC(probability=True)\n", "sk_model.fit(xs, ys)\n", "model = sk2torch.wrap(sk_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": "7f0ca328", "metadata": {}, "outputs": [], "source": [ "
import matplotlib.pyplot as plt\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", "\n", " "outputs = model.predict_proba(grid_xs)[:, 1]\n", "(input_grads,) = torch.autograd.grad(outputs.sum(), (grid_xs,))\n", "\n", "\n", " "plt.quiver(\n", " grid_xs[:, 0].detach().numpy(),\n", " grid_xs[:, 1].detach().numpy(),\n", " input_grads[:, 0].detach().numpy(),\n", " input_grads[:, 1].detach().numpy(),\n", ")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "82db373a", "metadata": {}, "outputs": [], "source": [ "\n", "\n", " " "\n", " "shape = xs.shape[1:]\n", "x = grid_xs[0:1]\n", "torch_out = model.predict(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", "ezkl.calibrate_settings(cal_path, model_path, settings_path, \"resources\")" ] }, { "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": 10, "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", "e
xecution_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\")" ] }, { "cell_type": "markdown", "id": "760580d4", "metadata": {}, "source": [ " ] }, { "cell_type": "code", "execution_count": null, "id": "481824fe", "metadata": {}, "outputs": [], "source": [ " "\n", " "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.svm
import LinearSVC\n", "
import sk2torch\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", "ys = np.array([False] * 256 + [True] * 256)\n", "\n", " "sk_model = LinearSVC()\n", "sk_model.fit(xs, ys)\n", "model = sk2torch.wrap(sk_model)\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "7d1d47fe", "metadata": {}, "outputs": [], "source": [ "\n", "\n", " " "\n", " "shape = xs.shape[1:]\n", "x = grid_xs[0:1]\n", "torch_out = model.predict(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": "7c00b3f6", "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": "69536185", "metadata": {}, "outputs": [], "source": [ "!RUST_LOG=trace\n", " "res = ezkl.gen_settings(model_path, settings_path)\n", "assert res == True\n", "\n", "res = ezkl.calibrate_settings(data_path, model_path, settings_path, \"resources\")\n", "assert res == True" ] } ], "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": [ { "cell_type": "markdown", "metadata": {}, "source": [ " "\n", "This is another approach of verifying games but using an anomaly detection approach instead of classification.\n", "\n", "Make sure to use a GPU otherwise you'll take a super long time to train" ] }, { "cell_type": "code", "execution_count": 1, "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", "!RUST_LOG=trace" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " "\n", "The game states are in the form of\n", "```json\n", "[\n", " {\n", " \"history\": [\n", " [null, null, null, null, null, null, null, null, null],\n", " [\"X\", null, null, null, null, null, null, null, null],\n", " ...\n", " ],\n", " \"outcome\": \"X\"\n", " }\n", "]\n", "```\n", "\n", "To create the game states for tic tac toe, do a recursive a tree search of possible gameplay." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "
import json\n", "\n", "def check_winner(board):\n", " winning_combinations = [\n", " [0, 1, 2], [3, 4, 5], [6, 7, 8], " [0, 3, 6], [1, 4, 7], [2, 5, 8], " [0, 4, 8], [2, 4, 6] " ]\n", " for combo in winning_combinations:\n", " if board[combo[0]] == board[combo[1]] == board[combo[2]] and board[combo[0]] is not None:\n", " return board[combo[0]]\n", " return None\n", "\n", "def generate_games(board, player):\n", " winner = check_winner(board)\n", " if winner or None not in board:\n", " " return [{\n", " \"history\": [list(board)],\n", " \"outcome\": winner if winner else \"Draw\"\n", " }]\n", "\n", " games = []\n", " for i in range(9):\n", " if board[i] is None:\n", " new_board = board.copy()\n", " new_board[i] = player\n", " next_player = 'O' if player == 'X' else 'X'\n", " next_games = generate_games(new_board, next_player)\n", " for game in next_games:\n", " game[\"history\"].insert(0, list(board))\n", " games.extend(next_games)\n", "\n", " return games\n", "\n", "initial_board = [None for _ in range(9)]\n", "games = generate_games(initial_board, 'X')\n", "\n", "with open(\"tic_tac_toe_games.json\", \"w\") as file:\n", " file.write(\"[\\n\") " for i, game in enumer
ate(games):\n", " json.dump(game, file, separators=(',', ': '))\n", " if i != len(games) - 1: " file.write(\",\\n\")\n", " else:\n", " file.write(\"\\n\")\n", " file.write(\"]\\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's make a list of illegal game play by running through the legal games and making bad games." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "with open(\"tic_tac_toe_games_bad.json\", \"w\") as file:\n", " file.write(\"[\\n\")\n", " for i, game in enumerate(games):\n", " " game_history = game['history']\n", " new_game_history = []\n", " for moves in game_history:\n", " new_moves = []\n", " for move in moves:\n", " if move is None:\n", " new_moves.append('X')\n", " elif move == 'X':\n", " new_moves.append('O')\n", " else:\n", " new_moves.append(None)\n", " new_game_history.append(new_moves)\n", " game['history'] = new_game_history\n", "\n", " json.dump(game, file, separators=(',', ': '))\n", "\n", " if i != len(games) - 1: " file.write(\",\\n\")\n", " else:\n", " file.write(\"\\n\")\n", " file.write(\"]
\\n\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " "\n", "1. We use an autoencoder to verify the execution. An autoencoder is essentially a fan-in, fan-out architecture. It can be used for generative tasks, but in this case we use it as an anomaly detection approach.\n", "\n", "2. The autoencoder helps us extract out the latent distribution of normal tic tac toe games. If there's a weird tic tac toe game, we can then reject it if the distribution is not within some threshold we want. We can quantify this distribution via the mean absolute error between the data point and the reconstructed data." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "
import torch\n", "
import torch.nn as nn\n", "from torch.utils.data
import DataLoader, IterableDataset, random_split\n", "