text
stringlengths 1
2.05k
|
---|
import torch.optim as optim\n",
" |
import json\n",
" |
import torch.nn.functional as F\n",
"\n",
" |
class TicTacToeNet(nn.Module):\n",
" def __init__(self):\n",
" super(TicTacToeNet, self).__init__()\n",
" self.return_x = True\n",
" self.dense = nn.Linear(11 * 9 * 3, 50)\n",
" self.dense1 = nn.Linear(50, 20)\n",
" self.dense2 = nn.Linear(20, 10)\n",
" self.dense3 = nn.Linear(10, 20)\n",
" self.dense4 = nn.Linear(20, 50)\n",
" self.dense5 = nn.Linear(50, 11 * 9 * 3)\n",
"\n",
" def forward(self, x):\n",
"
" original_x = x.clone()\n",
"\n",
"
" x = F.relu(self.dense(x))\n",
" x = F.relu(self.dense1(x))\n",
" x = F.relu(self.dense2(x))\n",
" x = F.relu(self.dense3(x))\n",
" x = F.relu(self.dense4(x))\n",
" x = self.dense5(x)
"\n",
"
" l1_loss = torch.mean(torch.abs(x - original_x))\n",
"\n",
" if self.return_x:\n",
" return x, l1_loss\n",
" else:\n",
" return l1_loss"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"We want to load good games and bad games for the classification later."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
" |
class JsonDataset(IterableDataset):\n",
" def __init__(self, file):\n",
" self.file_good = file\n",
" self.length = self.compute_length(self.file_good)\n",
" self.data = self.load_data(self.file_good)\n",
"\n",
" def __iter__(self):\n",
" for i in range(len(self.data)):\n",
" yield self.data[i]\n",
"\n",
" def parse_json_object(self, line):\n",
" try:\n",
" return json.loads(line)\n",
" except json.JSONDecodeError:\n",
" return None\n",
"\n",
" def encode_board(self, board):\n",
" encoding = []\n",
" for cell in board:\n",
" if cell == 'X':\n",
" encoding.extend([1,0,0])\n",
" elif cell == 'O':\n",
" encoding.extend([0,1,0])\n",
" else:\n",
" encoding.extend([0,0,1])\n",
"\n",
" return encoding\n",
"\n",
"\n",
" def encode_outcome(self, outcome):\n",
" if outcome == 'X':\n",
" return [1,0,0]\n",
" elif outcome == 'O':\n",
" return [0,1,0]\n",
" else:\n",
" return [0,0,1]\n",
"\n",
" def compute_length(self, file_good):\n",
" count = 0\n",
" with open(file_good, 'r') as f:\n",
"
" next(f)\n",
" for line in f:\n",
" if line.strip() not i |
n [\",\", \"]\"]:\n",
" count += 1\n",
"\n",
" return count\n",
"\n",
" def __len__(self):\n",
" return self.length\n",
"\n",
" def __getitem__(self, idx):\n",
" padded_history, sample_outcome = self.data[idx]\n",
"\n",
" return torch.tensor(padded_history, dtype=torch.float), torch.tensor(sample_outcome, dtype=torch.float)\n",
"\n",
" def process_file(self, file, is_good):\n",
" data = []\n",
" with open(file, 'r') as f:\n",
" next(f)\n",
" for line in f:\n",
"
" if line.endswith(\",\\n\"):\n",
" line = line[:-2]\n",
" sample = self.parse_json_object(line)\n",
" if sample is not None:\n",
" max_length = 10
" history = sample['history']\n",
"\n",
" if len(history) == max_length:\n",
" padded_history = history\n",
" else:\n",
" padded_history = history + [[None] * 9 for _ in range(max_length - len(history))]\n",
"\n",
" padded_history = [self.encode_board(x) for x in padded_history]\n",
" sample_outcome = self.encode_outcome(sample['outcome'])\n",
" sample_outcome.extend([0,0,1] * 8)\n",
" padded_history.append(sample_outcome)\n",
"\n",
" if is_good:\n", |
"
" data.append((padded_history, [1, 0]))\n",
" else:\n",
"
" data.append((padded_history, [0, 1]))\n",
"\n",
" return data\n",
"\n",
"\n",
" def load_data(self, file_good):\n",
" data_good = self.process_file(file_good, True)\n",
"
"
"\n",
" return data_good\n",
"\n",
"def collate_fn(batch):\n",
" histories, outcomes = zip(*batch)\n",
"\n",
"
" histories_tensor = torch.tensor(histories, dtype=torch.float32)\n",
" outcomes_tensor = torch.tensor(outcomes, dtype=torch.int64)\n",
"\n",
" return histories_tensor, outcomes_tensor\n",
"\n",
"dataset = JsonDataset('tic_tac_toe_games.json')\n",
"\n",
"total_size = len(dataset)\n",
"train_size = int(0.8 * total_size)\n",
"test_size = total_size - train_size\n",
"\n",
"train_dataset, test_dataset = random_split(dataset, [train_size, test_size])\n",
"\n",
"\n",
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"Note that during training we want to neural network to try to recreate its inputs. To do this we compare the L1Loss or Mean Absolute Error between the prediction and the input |
."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
"model = TicTacToeNet().to(device)\n",
"criterion = nn.L1Loss()\n",
"optimizer = optim.Adam(model.parameters(), lr=0.001)\n",
"\n",
"
"MAX_EPOCH = 1\n",
"\n",
"for epoch in range(MAX_EPOCH):\n",
" model.train()\n",
"\n",
" for history, valid in train_loader:\n",
"\n",
" history = history.to(device)\n",
" optimizer.zero_grad()\n",
" history = history.view(history.size(0), -1)\n",
" prediction, _ = model(history)\n",
" loss = criterion(prediction, history)\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
"
"\n",
"
" model.eval()\n",
"\n",
"\n",
" with torch.no_grad():\n",
" total_count = 0\n",
" total_loss = 0\n",
" for history, valid in test_loader:\n",
" history = history.to(device)\n",
" history = history.view(history.size(0), -1)\n",
"\n",
" valid = valid.to(device)\n",
" prediction, _ = model(history)\n",
" loss = criterion(prediction, history)\n",
"\n",
" total_loss += loss\n",
"\n",
" total_count += 1\n",
"\n", |
"
"\n",
"\n",
" avg_loss = total_loss / total_count\n",
" print(f\"Epoch {epoch + 1}/{MAX_EPOCH} - Loss: {avg_loss:.2f}\")\n",
" print(history[-1])\n",
" print(prediction[-1])\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"We plot the range of possible losses for normal data.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"model.eval()\n",
"model.return_x = False\n",
"\n",
"\n",
"loss_list = []\n",
"\n",
"for history, valid in test_loader:\n",
" history = history.to(device)\n",
" history = history.view(history.size(0), -1)\n",
" loss = model(history)\n",
" loss_list.append(loss.cpu().detach().numpy())\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
" |
import matplotlib.pyplot as plt\n",
"\n",
"plt.hist(loss_list, bins=50)\n",
"plt.xlabel(\"Normal loss\")\n",
"plt.ylabel(\"No of examples\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"Likewise, we plot the ranges of losses for bad data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"bad_dataset = JsonDataset('tic_tac_toe_games_bad.json')\n",
"\n",
"bad_total_size = len(bad_dataset)\n",
"bad_train_size = int(0.8 * bad_total_size)\n",
"bad_test_size = bad_total_size - bad_train_size\n",
"\n",
"bad_train_dataset, bad_test_dataset = random_split(bad_dataset, [bad_train_size, bad_test_size])\n",
"\n",
"bad_train_loader = DataLoader(bad_train_dataset, batch_size=32, shuffle=True)\n",
"bad_test_loader = DataLoader(bad_test_dataset, batch_size=32, shuffle=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"bad_loss_list = []\n",
"\n",
"for history, valid in bad_test_loader:\n",
" history = history.to(device)\n",
" history = history.view(history.size(0), -1)\n",
" loss = model(history)\n",
" bad_loss_list.append(loss.cpu().detach().numpy())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": |
[
" |
import matplotlib.pyplot as plt\n",
"\n",
"\n",
"plt.hist(bad_loss_list, bins=50)\n",
"plt.xlabel(\"Normal loss\")\n",
"plt.ylabel(\"No of examples\")\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** By visual inspection we can see that if the loss is greater than `~0.200` the data is likely anomalous (this value will probably change depending on the runs). There seems to be no overlap in loss between good gameplay and bad gameplay.\n",
"\n",
"We could alternatively set the threshold to 4 standard deviation away from the mean of normal values. Or you can vary this according to the error tolerance required."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import numpy as np\n",
"threshold = np.mean(loss_list)+ 4 * np.std(loss_list)\n",
"print(threshold)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"model = model.cpu()\n",
"model.eval()\n",
"\n",
"
"sample_data_iter = iter(train_loader)\n",
"sample_history, _ = next(sample_data_iter)\n",
"\n",
"
"x = sample_history.to('cpu')\n",
"x = x.view(x.size(0), -1)\n",
"\n",
"
"torch.onnx.export(\n",
" model,
" x,
" \"tictactoe_network.onnx\",
" export_params=True,
" opset_version=10,
" do_constant_folding=True,
" input_names=['input'],
" output_names=['output'],
" dynamic_axes={\n",
" 'input': {0: 'batch_size'},
" 'output': {0: 'batch_size'}\n",
" }\n",
")\n",
"\n",
"data_array = ((x[0]).detach().numpy()).reshape([-1]).tolist()\n",
"\n",
"data = dict(input_data = [data_array])\n",
"\n",
"
"json.dump(data, open(\"data.json\", 'w'))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"We |
import the ezkl library to setup the zk system."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import os\n",
" |
import ezkl\n",
"\n",
"data_path = os.path.join(\"data.json\")\n",
"model_path = os.path.join('tictactoe_network.onnx')\n",
"compiled_model_path = os.path.join('network.ezkl')\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",
"proof_path = os.path.join('proof.json')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"res = ezkl.gen_settings(model_path, settings_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"
"
"
"
"cal_path = os.path.join(\"calibration.json\")\n",
"\n",
"data_array = ((x[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\", scales = [11])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.get_srs( settings_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.compile_ci |
rcuit(model_path, compiled_model_path, settings_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.setup(\n",
" compiled_model_path,\n",
" vk_path,\n",
" pk_path,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import json\n",
"\n",
"with open(data_path, \"r\") as f:\n",
" data = json.load(f)\n",
" print(len(data['input_data'][0]))\n",
"\n",
"ezkl.gen_witness(data_path, compiled_model_path, witness_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.mock(witness_path, compiled_model_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"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,
"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": {
"accelerator": "GPU",
"colab": {
"gpuType": "V100",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"n |
ame": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"We create an ML model that verifies TicTacToe Games\n",
"\n",
"Make sure to use a GPU otherwise you'll take a super long time to train"
]
},
{
"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"
]
},
{
"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": null,
"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": null,
"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. Given the data generated above classify whether the tic tac toe games are valid. This approach uses a binary classification as the tic tac toe state space is fairly small. For larger state spaces, we will want to use anomaly detection based approaches."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import torch\n",
" |
import torch.nn as nn\n",
"from torch.utils.data |
import DataLoader, IterableDataset, random_split\n",
" |
import torch.optim as optim\n",
" |
import json\n",
" |
import torch.nn.functional as F\n",
"\n",
" |
class TicTacToeNet(nn.Module):\n",
" def __init__(self):\n",
" super(TicTacToeNet, self).__init__()\n",
" self.dense = nn.Linear(11 * 9 * 3, 50)
" self.dense1 = nn.Linear(50, 20)\n",
" self.dense2 = nn.Linear(20, 10)\n",
" self.dense3 = nn.Linear(10, 2)\n",
"\n",
" def forward(self, x):\n",
" x = x.view(x.size(0), -1)
" x = F.relu(self.dense(x))\n",
" x = F.relu(self.dense1(x))\n",
" x = F.relu(self.dense2(x))\n",
" x = F.relu(self.dense3(x))\n",
" return x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"We want to load good games and bad games for the classification later."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
class JsonDataset(IterableDataset):\n",
" def __init__(self, file_good, file_bad):\n",
" self.file_good = file_good\n",
" self.file_bad = file_bad\n",
" self.length = self.compute_length(self.file_good, self.file_bad)\n",
" self.data = self.load_data(self.file_good, self.file_bad)\n",
"\n",
" def __iter__(self):\n",
" for i in range(len(self.data)):\n",
" yield self.data[i]\n",
"\n",
"\n",
" def parse_json_object(self, line):\n",
" try:\n",
" return json.loads(line)\n",
" except json.JSONDecodeError:\n",
" return None\n",
"\n",
" def encode_board(self, board):\n",
" encoding = []\n",
" for cell in board:\n",
" if cell == 'X':\n",
" encoding.extend([1,0,0])\n",
" elif cell == 'O':\n",
" encoding.extend([0,1,0])\n",
" else:\n",
" encoding.extend([0,0,1])\n",
"\n",
" return encoding\n",
"\n",
"\n",
" def encode_outcome(self, outcome):\n",
" if outcome == 'X':\n",
" return [1,0,0]\n",
" elif outcome == 'O':\n",
" return [0,1,0]\n",
" else:\n",
" return [0,0,1]\n",
"\n",
" def compute_length(self, file_good, file_bad):\n",
" count = 0\n",
" with open(file_good, 'r') as f:\n",
" |
" next(f)\n",
" for line in f:\n",
" if line.strip() not in [\",\", \"]\"]:\n",
" count += 1\n",
" with open(file_bad, 'r') as f:\n",
"
" next(f)\n",
" for line in f:\n",
" if line.strip() not in [\",\", \"]\"]:\n",
" count += 1\n",
"\n",
" return count\n",
"\n",
" def __len__(self):\n",
" return self.length\n",
"\n",
" def __getitem__(self, idx):\n",
" padded_history, sample_outcome = self.data[idx]\n",
" return torch.tensor(padded_history, dtype=torch.float), torch.tensor(sample_outcome, dtype=torch.float)\n",
"\n",
" def process_file(self, file, is_good):\n",
" data = []\n",
" with open(file, 'r') as f:\n",
" next(f)\n",
" for line in f:\n",
"
" if line.endswith(\",\\n\"):\n",
" line = line[:-2]\n",
" sample = self.parse_json_object(line)\n",
" if sample is not None:\n",
" max_length = 10
" history = sample['history']\n",
"\n",
" if len(history) == max_length:\n",
" padded_history = history\n",
" else:\n",
" padded_history = history + [[None] * 9 for _ in range(max_length - len(history))]\n",
"\n",
" |
padded_history = [self.encode_board(x) for x in padded_history]\n",
" sample_outcome = self.encode_outcome(sample['outcome'])\n",
" sample_outcome.extend([0,0,1] * 8)\n",
" padded_history.append(sample_outcome)\n",
"\n",
" if is_good:\n",
"
" data.append((padded_history, [1, 0]))\n",
" else:\n",
"
" data.append((padded_history, [0, 1]))\n",
"\n",
" return data\n",
"\n",
"\n",
" def load_data(self, file_good, file_bad):\n",
" data_good = self.process_file(file_good, True)\n",
" data_bad = self.process_file(file_bad, False)\n",
" data_good.extend(data_bad)\n",
"\n",
" return data_good\n",
"\n",
"def collate_fn(batch):\n",
" histories, outcomes = zip(*batch)\n",
"\n",
"
" histories_tensor = torch.tensor(histories, dtype=torch.float32)\n",
" outcomes_tensor = torch.tensor(outcomes, dtype=torch.int64)\n",
"\n",
" return histories_tensor, outcomes_tensor\n",
"\n",
"dataset = JsonDataset('tic_tac_toe_games.json', 'tic_tac_toe_games_bad.json')\n",
"\n",
"total_size = len(dataset)\n",
"train_size = int(0.8 * total_size)\n",
"test_size = total_size - train_size\n",
"\n",
"train_dataset, test_dataset = random_split(dataset, [train_size, test_size])\n",
"\n", |
"\n",
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"In this training step we'll just use the CrossEntropyLoss and have the neural network classify good games and bad games."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
"model = TicTacToeNet().to(device)\n",
"criterion = nn.CrossEntropyLoss()\n",
"optimizer = optim.Adam(model.parameters(), lr=0.001)\n",
"\n",
"
"MAX_EPOCH = 1\n",
"\n",
"for epoch in range(MAX_EPOCH):\n",
" model.train()\n",
"\n",
" for history, valid in train_loader:\n",
"\n",
" history = history.to(device)\n",
" valid = valid.to(device)\n",
" optimizer.zero_grad()\n",
" prediction = model(history)\n",
" loss = criterion(prediction, valid)\n",
" loss.backward()\n",
" optimizer.step()\n",
"\n",
"\n",
"
" model.eval()\n",
" total_count = 0\n",
" correct_count = 0\n",
"\n",
" with torch.no_grad():\n",
" for history, valid in test_loader:\n",
" history = history.to(device)\n",
" valid = valid.to( |
device)\n",
" prediction = model(history)\n",
"\n",
"
" _, predicted_labels = torch.max(prediction, 1)\n",
"\n",
"
" _, true_class_labels = torch.max(valid, 1)\n",
"\n",
"
" correct_predictions = (predicted_labels == true_class_labels).sum().item()\n",
"\n",
" total_predictions = prediction.shape[0]\n",
"\n",
"
" correct_count += correct_predictions\n",
" total_count += total_predictions\n",
"\n",
"\n",
" accuracy = 100 * correct_count / total_count\n",
" print(f\"Epoch {epoch + 1}/{MAX_EPOCH} - Accuracy: {accuracy:.2f}%\")\n",
" print(history[-1])\n",
" print(valid[-1])\n",
" print(predicted_labels[-1])\n",
" print(true_class_labels[-1])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(prediction)\n",
"print(valid)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Note:** It's reasonable for the tic tac toe model to approach 100% classification accuracy as the state space of the game is fairly small"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [ |
"
"model = model.cpu()\n",
"model.eval()\n",
"\n",
"
"sample_data_iter = iter(train_loader)\n",
"sample_history, _ = next(sample_data_iter)\n",
"\n",
"
"x = sample_history.to('cpu')\n",
"\n",
"
"torch.onnx.export(\n",
" model,
" x,
" \"tictactoe_network.onnx\",
" export_params=True,
" opset_version=10,
" do_constant_folding=True,
" input_names=['input'],
" output_names=['output'],
" dynamic_axes={\n",
" 'input': {0: 'batch_size'},
" 'output': {0: 'batch_size'}\n",
" }\n",
")\n",
"\n",
"data_array = ((x[0]).detach().numpy()).reshape([-1]).tolist()\n",
"\n",
"data = dict(input_data = [data_array])\n",
"\n",
"
"json.dump(data, open(\"data.json\", 'w'))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!RUST_LOG=trace"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import os\n",
" |
import ezkl\n",
"\n",
"data_path = os.path.join(\"data.json\")\n",
"model_path = os.path.join('tictactoe_network.onnx')\n",
"compiled_model_path = os.path.join('network.ezkl')\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",
"proof_path = os.path.join('proof.json')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"res = ezkl.gen_settings(model_path, settings_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cal_path = os.path.join(\"calibration.json\")\n",
"\n",
"data_array = ((x[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\", scales = [4])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.get_srs(settings_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.compile_circuit(model_path, compiled_model_path, settings_path)"
]
},
{ |
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.setup(\n",
" compiled_model_path,\n",
" vk_path,\n",
" pk_path,\n",
" \n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import json\n",
"\n",
"with open(data_path, \"r\") as f:\n",
" data = json.load(f)\n",
" print(len(data['input_data'][0]))\n",
"\n",
"ezkl.gen_witness(data_path, compiled_model_path, witness_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"ezkl.mock(witness_path, compiled_model_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"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,
"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": {
"accelerator": "GPU",
"colab": {
"gpuType": "T4",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"nam |
e": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "uKQPd7_5ANe-"
},
"source": [
"
"\n",
"In this example we will calculate the variance of an asset using ezkl. Here's a diagram of the process:\n",
"\n",
"\n",
" subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n",
"\n",
"
"except:\n",
" pass\n",
"\n",
" |
import ezkl\n",
" |
import torch\n",
" |
import datetime\n",
" |
import pandas as pd\n",
" |
import requests\n",
" |
import json\n",
" |
import os"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "osjj-0Ta3E8O"
},
"source": [
"**Create Computational Graph**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
},
"id": "x1vl9ZXF3EEW",
"outputId": "bda21d02-fe5f-4fb2-8106-f51a8e2e67aa"
},
"outputs": [],
"source": [
"from torch |
import nn\n",
" |
import torch\n",
"\n",
"\n",
" |
class Model(nn.Module):\n",
" def __init__(self):\n",
" super(Model, self).__init__()\n",
"\n",
"
" def forward(self, x):\n",
"
" return [torch.mean(x)]\n",
"\n",
"\n",
"\n",
"\n",
"circuit = Model()\n",
"\n",
"\n",
"\n",
"\n",
"x = 0.1*torch.rand(1,*[1,20], requires_grad=True)\n",
"\n",
"
"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
"\n",
"print(device)\n",
"\n",
"circuit.to(device)\n",
"\n",
"
"circuit.eval()\n",
"\n",
"
"torch.onnx.export(circuit,
" x,
" \"lol.onnx\",
" export_params=True,
" opset_version=11,
" do_constant_folding=True,
" input_names = ['input'],
" output_names = ['output'],
" dynamic_axes={'input' : {0 : 'batch_size'},
" 'output' : {0 : 'batch_size'}})\n",
"\n",
"
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "E3qCeX-X5xqd"
},
"source": [
"**Set Data Source and Get Data**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
},
"id": "6RAMplxk5xPk",
"outputId": "bd2158fe-0c00-44fd-e632-6a3f70cdb7c9"
},
"outputs": [],
"source": [
"\n",
"def get_url(coin, currency, start, end):\n",
" url = f\"https:
" return url\n",
"\n",
"\n",
"timenow = datetime.datetime.now()\n", |
"timenow_unix_sec = int(datetime.datetime.timestamp(timenow))\n",
"time7days = timenow - datetime.timedelta(days=7)\n",
"time7days_unix_sec = int(datetime.datetime.timestamp(time7days))\n",
"\n",
"print(timenow_unix_sec)\n",
"print(time7days_unix_sec)\n",
"\n",
"eth_price_url = get_url(\"ethereum\", \"usd\", time7days_unix_sec, timenow_unix_sec)\n",
"print(eth_price_url)\n",
"\n",
"data = requests.get(eth_price_url)\n",
"print(data)\n",
"\n",
"new_data = {\"time\": [], \"prices\": []}\n",
"\n",
"for k, v in data.json().items():\n",
" if k == \"prices\":\n",
" for x in v:\n",
" new_data[\"time\"].append(x[0])\n",
" new_data[\"prices\"].append(x[1])\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
"height": 424
},
"id": "WSj1Uxln65vf",
"outputId": "51422d71-9680-4b51-c4df-e400d20f988b"
},
"outputs": [],
"source": [
"df = pd.DataFrame(new_data)\n",
"df\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eLJ7oirQ_HQR"
},
"source": [
"**EZKL Workflow**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"input_filename = os.path.join('input.json')\n",
"
"df_prices = df['prices'].tail(20).tolist()\n",
"\n",
"data = dict(input_data = [df_prices])\n",
"\n",
"
"json.dump( data, open(input_filename, 'w' ))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
},
"id": "4MmE9SX66_Il",
"outputId": "16403639-66a4-4280-ac7f-6966b75de5a3"
},
"out |
puts": [],
"source": [
"
"onnx_filename = os.path.join('lol.onnx')\n",
"compiled_filename = os.path.join('lol.compiled')\n",
"settings_filename = os.path.join('settings.json')\n",
"srs_path = os.path.join('kzg.params')\n",
"\n",
"\n",
"\n",
"ezkl.gen_settings(onnx_filename, settings_filename)\n",
"ezkl.calibrate_settings(\n",
" input_filename, onnx_filename, settings_filename, \"resources\", scales = [4])\n",
"res = ezkl.get_srs(settings_filename)\n",
"ezkl.compile_circuit(onnx_filename, compiled_filename, settings_filename)\n",
"\n",
"
"with open(\"settings.json\") as f:\n",
" data = json.load(f)\n",
" json_formatted_str = json.dumps(data, indent=2)\n",
"\n",
" print(json_formatted_str)\n",
"\n",
"assert os.path.exists(\"settings.json\")\n",
"assert os.path.exists(\"input.json\")\n",
"assert os.path.exists(\"lol.onnx\")"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"id": "fULvvnK7_CMb"
},
"outputs": [],
"source": [
"pk_path = os.path.join('test.pk')\n",
"vk_path = os.path.join('test.vk')\n",
"\n",
"\n",
"
"res = ezkl.setup(\n",
" compiled_filename,\n",
" vk_path,\n",
" pk_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_filename)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"witness_path = \"witness.json\"\n",
"\n",
"res = ezkl.gen_witness(input_filename, compiled_filename, witness_path)\n",
"assert os.path.isfile(witness_path)"
] |
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
},
"id": "Oog3j6Kd-Wed",
"outputId": "5839d0c1-5b43-476e-c2f8-6707de562260"
},
"outputs": [],
"source": [
"
"
"proof_path = os.path.join('test.pf')\n",
"\n",
"\n",
"proof = ezkl.prove(\n",
" witness_path,\n",
" compiled_filename,\n",
" pk_path,\n",
" proof_path,\n",
" \"single\",\n",
" )\n",
"\n",
"\n",
"assert os.path.isfile(proof_path)\n",
"\n",
"
"res = ezkl.verify(\n",
" proof_path,\n",
" settings_filename,\n",
" vk_path,\n",
" )\n",
"\n",
"assert res == True\n",
"print(\"verified\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "W7tAa-DFAtvS"
},
"source": [
"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8Ym91kaVAIB6"
},
"source": [
"**Now How Do We Do It Onchain?????**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
"height": 339
},
"id": "fodkNgwS70FM",
"outputId": "827b5efd-f74f-44de-c114-861b3a86daf2"
},
"outputs": [],
"source": [
"
"print(vk_path)\n",
"print(settings_filename)\n",
"\n",
"\n",
"abi_path = 'test.abi'\n",
"sol_code_path = 'test.sol'\n",
"\n",
"res = ezkl.create_evm_verifier(\n",
" vk_path,\n",
" settings_filename,\n",
" sol_code_path,\n",
" abi_path,\n",
" )\n",
"assert res == True"
]
},
{
"cell_type": "code",
"e |
xecution_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": [
"
"addr = None\n",
"with open(address_path, 'r') as f:\n",
" addr = f.read()\n",
"\n",
"res = ezkl.verify_evm(\n",
" addr,\n",
" proof_path,\n",
" \"http:
")\n",
"assert res == True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mPFmUizd_gCp"
},
"outputs": [],
"source": []
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"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": 0
} |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"Here we showcase a full-end-to-end flow of:\n",
"1. training a model for a specific task (judging voices)\n",
"2. creating a proof of judgment\n",
"3. creating and deploying an evm verifier\n",
"4. verifying the proof of judgment using the verifier\n",
"\n",
"First we download a few voice related datasets from kaggle, which are all labelled using the same emotion and tone labelling standard.\n",
"\n",
"We have 8 emotions in both speaking and singing datasets: neutral, calm, happy, sad, angry, fear, disgust, surprise.\n",
"\n",
"To download the dataset make sure you have the kaggle cli installed in your local env `pip install kaggle`. Make sure you set up your `kaggle.json` file as detailed [here](https:
"Then run the associated `voice_data.sh` data download script: `sh voice_data.sh`.\n",
"\n",
"Make sure you set the `VOICE_DATA_DIR` variables to point to the directory the `voice_data.sh` script has downloaded to. This script also accepts an argument to download to a specific directory: `sh voice_data.sh /path/to/voice/data`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
" |
import os\n",
"
"\n",
"voice_data_dir = os.environ.get('VOICE_DATA_DIR')\n",
"\n",
"
"if voice_data_dir is None:\n",
" voice_data_dir = \"\"\n",
"\n",
"print(\"voice_data_dir: \", voice_data_dir)\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"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 pandas as pd\n",
" |
import logging\n",
"\n",
"
"\n",
"
"
"
"\n",
"\n",
"Tess = os.path.join(voice_data_dir, \"data/TESS/\")\n",
"\n",
"tess = os.listdir(Tess)\n",
"\n",
"emotions = []\n",
"files = []\n",
"\n",
"for item in tess:\n",
" items = os.listdir(Tess + item)\n",
" for file in items:\n",
" part = file.split('.')[0]\n",
" part = part.split('_')[2]\n",
" if part == 'ps':\n",
" emotions.append('surprise')\n",
" else:\n",
" emotions.append(part)\n",
" files.append(Tess + item + '/' + file)\n",
"\n",
"tess_df = pd.concat([pd.DataFrame(emotions, columns=['Emotions']), pd.DataFrame(files, columns=['Files'])], axis=1)\n",
"tess_df"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Ravdess = os.path.join(voice_data_dir, \"data/RAVDESS_SONG/audio_song_actors_01-24/\")\n",
"\n",
"ravdess_list = os.listdir(Ravdess)\n",
"\n",
"files = []\n",
"emotions = []\n",
"\n",
"for item in ravdess_list:\n",
" actor = os.listdir(Ravdess + item)\n",
" for file in actor:\n",
" name = file.split('.')[0]\n",
" parts = name.split('-')\n", |
" emotions.append(int(parts[2]))\n",
" files.append(Ravdess + item + '/' + file)\n",
"\n",
"emotion_data = pd.DataFrame(emotions, columns=['Emotions'])\n",
"files_data = pd.DataFrame(files, columns=['Files'])\n",
"\n",
"ravdess_song_df = pd.concat([emotion_data, files_data], axis=1)\n",
"\n",
"ravdess_song_df.Emotions.replace({1:'neutral', 2:'calm', 3:'happy', 4:'sad', 5:'angry', 6:'fear', 7:'disgust', 8:'surprise'}, inplace=True)\n",
"\n",
"ravdess_song_df"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Ravdess = os.path.join(voice_data_dir, \"data/RAVDESS_SPEECH/audio_speech_actors_01-24/\")\n",
"\n",
"ravdess_list = os.listdir(Ravdess)\n",
"\n",
"files = []\n",
"emotions = []\n",
"\n",
"for item in ravdess_list:\n",
" actor = os.listdir(Ravdess + item)\n",
" for file in actor:\n",
" name = file.split('.')[0]\n",
" parts = name.split('-')\n",
" emotions.append(int(parts[2]))\n",
" files.append(Ravdess + item + '/' + file)\n",
" \n",
"emotion_data = pd.DataFrame(emotions, columns=['Emotions'])\n",
"files_data = pd.DataFrame(files, columns=['Files'])\n",
"\n",
"ravdess_df = pd.concat([emotion_data, files_data], axis=1)\n",
"\n",
"ravdess_df.Emotions.replace |
({1:'neutral', 2:'calm', 3:'happy', 4:'sad', 5:'angry', 6:'fear', 7:'disgust', 8:'surprise'}, inplace=True)\n",
"\n",
"ravdess_df"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Crema = os.path.join(voice_data_dir, \"data/CREMA-D/\")\n",
"\n",
"crema = os.listdir(Crema)\n",
"emotions = []\n",
"files = []\n",
"\n",
"for item in crema:\n",
" files.append(Crema + item)\n",
" \n",
" parts = item.split('_')\n",
" if parts[2] == 'SAD':\n",
" emotions.append('sad')\n",
" elif parts[2] == 'ANG':\n",
" emotions.append('angry')\n",
" elif parts[2] == 'DIS':\n",
" emotions.append('disgust')\n",
" elif parts[2] == 'FEA':\n",
" emotions.append('fear')\n",
" elif parts[2] == 'HAP':\n",
" emotions.append('happy')\n",
" elif parts[2] == 'NEU':\n",
" emotions.append('neutral')\n",
" else :\n",
" emotions.append('unknown')\n",
" \n",
"emotions_data = pd.DataFrame(emotions, columns=['Emotions'])\n",
"files_data = pd.DataFrame(files, columns=['Files'])\n",
"\n",
"crema_df = pd.concat([emotions_data, files_data], axis=1)\n",
"\n",
"crema_df"
]
},
{
"attachments": {},
"cell_ty |
pe": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"Savee = os.path.join(voice_data_dir,\"data/SAVEE/\")\n",
"\n",
"savee = os.listdir(Savee)\n",
"\n",
"emotions = []\n",
"files = []\n",
"\n",
"for item in savee:\n",
" files.append(Savee + item)\n",
" part = item.split('_')[1]\n",
" ele = part[:-6]\n",
" if ele == 'a':\n",
" emotions.append('angry')\n",
" elif ele == 'd':\n",
" emotions.append('disgust')\n",
" elif ele == 'f':\n",
" emotions.append('fear')\n",
" elif ele == 'h':\n",
" emotions.append('happy')\n",
" elif ele == 'n':\n",
" emotions.append('neutral')\n",
" elif ele == 'sa':\n",
" emotions.append('sad')\n",
" else:\n",
" emotions.append('surprise')\n",
"\n",
"savee_df = pd.concat([pd.DataFrame(emotions, columns=['Emotions']), pd.DataFrame(files, columns=['Files'])], axis=1)\n",
"savee_df"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.concat([ravdess_df, ravdess_song_df, crema_df, tess_df, savee_df], axis = 0)\n",
" |
"df.index = range(len(df.index))\n",
"df.to_csv(\"df.csv\",index=False)\n",
"df\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import seaborn as sns\n",
"sns.histplot(data=df, x=\"Emotions\")\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"Here we convert all audio files into 2D frequency-domain spectrograms so that we can leverage convolutional neural networks, which tend to be more efficient than time-series model like RNNs or LSTMs.\n",
"We thus: \n",
"1. Extract the mel spectrogram from each of the audio recordings. \n",
"2. Rescale each of these to the decibel (DB) scale. \n",
"3. Define the model as the following model: `(x) -> (conv) -> (relu) -> (linear) -> (y)`\n",
"\n",
"\n",
"You may notice that we introduce a second computational graph `(key) -> (key)`. The reasons for this are to do with MEV, and if you are not interested you can skip the following paragraph. \n",
"\n",
"Let's say that obtaining a high score from the judge and then submitting said score to the EVM verifier could result in the issuance of a reward (financial or otherwise). There is an incentive then for MEV bots to scalp any issued valid proof and submit a duplicate transaction with the same proof to the verifier contract in the hopes of obtaining the reward before the original issuer. Here we add `(key) -> (key)` such that the transaction creator's public key / address is both a private input AND a public input to the proof. As such the on-chain verification only succeeds if the key passed in during proof time is also passed in as a public input to the contract. The reward issued by the contract can then be irrevocably tied to that key such that even if the proof is submitted by another actor, the reward would STILL go to the original singer / transaction issuer. "
]
},
{
"cell_type": "code", |
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"\n",
" |
import librosa\n",
" |
import numpy as np\n",
" |
import matplotlib.pyplot as plt\n",
"\n",
"\n",
"
"def extract_mel_spec(filename):\n",
" x,sr=librosa.load(filename,duration=3,offset=0.5)\n",
" X = librosa.feature.melspectrogram(y=x, sr=sr)\n",
" Xdb = librosa.power_to_db(X, ref=np.max)\n",
" Xdb = Xdb.reshape(1,128,-1)\n",
" return Xdb\n",
"\n",
"Xdb=df.iloc[:,1].apply(lambda x: extract_mel_spec(x))\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we convert label to a number between 0 and 1 where 1 is pleasant surprised and 0 is disgust and the rest are floats in between. The model loves pleasantly surprised voices and hates disgust ;) "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"max_size = 0\n",
"for i in range(len(Xdb)):\n",
" if Xdb[i].shape[2] > max_size:\n",
" max_size = Xdb[i].shape[2]\n",
"\n",
"
"Xdb=Xdb.apply(lambda x: np.pad(x,((0,0),(0,0),(0,max_size-x.shape[2]))))\n",
"\n",
"Xdb=pd.DataFrame(Xdb)\n",
"Xdb['label'] = df['Emotions']\n",
"
"Xdb['label'] = Xdb['label'].apply(lambda x: 1 if x=='surprise' else 0 if x=='disgust' else 0.2 if x=='fear' else 0.4 if x=='happy' else 0.6 if x=='sad' else 0.8)\n",
"\n",
"Xdb.iloc[0,0][0].shape"
]
},
{
"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=1, out_channels=1, kernel_size=5, stride=4)\n",
"\n",
" self.d1 = nn.Linear(992, 1)\n",
"\n",
" self.sigmoid = nn.Sigmoid()\n",
" self.relu = nn.ReLU()\n",
"\n",
" def forward(self, key, x):\n",
"
" x = self.conv1(x)\n",
" x = self.relu(x)\n",
" x = x.flatten(start_dim=1)\n",
" x = self.d1(x)\n",
" x = self.sigmoid(x)\n",
"\n",
" return [key, x]\n",
"\n",
"\n",
"circuit = MyModel()\n",
"\n",
"output = circuit(0, torch.tensor(Xdb.iloc[0,0][0].reshape(1,1,128,130)))\n",
"\n",
"output\n",
"\n",
"\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we leverage the classic Adam optimizer, coupled with 0.001 weight decay so as to regularize the model. The weight decay (a.k.a L2 regularization) can also help on the zk-circuit end of things in that it prevents inputs to Halo2 lookup tables from falling out of range (lookup tables are how we represent non-linearities like ReLU and Sigmoid inside our circuits). "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from tqdm |
import tqdm\n",
"\n",
"
"n_epochs = 10
"batch_size = 10
"\n",
"\n",
"loss_fn = nn.MSELoss()
"
"optimizer = torch.optim.Adam(circuit.parameters(), lr=0.001, weight_decay=0.001)\n",
"\n",
"
"Xdb = Xdb.sample(frac=1).reset_index(drop=True)\n",
"\n",
"
"train = Xdb.iloc[:int(len(Xdb)*0.8)]\n",
"test = Xdb.iloc[int(len(Xdb)*0.8):int(len(Xdb)*0.9)]\n",
"val = Xdb.iloc[int(len(Xdb)*0.9):]\n",
"\n",
"batches_per_epoch = len(train)\n",
"\n",
"\n",
"def get_loss(Xbatch, ybatch):\n",
" y_pred = circuit(0, Xbatch)[1]\n",
" loss = loss_fn(y_pred, ybatch)\n",
" return loss\n",
"\n",
"for epoch in range(n_epochs):\n",
"
" permutation = torch.randperm(batches_per_epoch)\n",
"\n",
" with tqdm(range(batches_per_epoch), unit=\"batch\", mininterval=0) as bar:\n",
" bar.set_description(f\"Epoch {epoch}\")\n",
" for i in bar:\n",
" start = i * batch_size\n",
"
" indices = np.random.choice(batches_per_epoch, batch_size)\n",
"\n",
" data = np.concatenate(train.iloc[indices.tolist(),0].values)\n",
" labels = train.iloc[indices.tolist(),1].values.astype(np.float32)\n",
"\n",
" data = data.reshape(batch_size,1,128,130)\n",
" labels = labels.reshape(batch_size,1)\n",
"\n",
"
" Xbatch = torch.ten |
sor(data)\n",
" ybatch = torch.tensor(labels)\n",
"\n",
"
" loss = get_loss(Xbatch, ybatch)\n",
"
" optimizer.zero_grad()\n",
" loss.backward()\n",
"
" optimizer.step()\n",
"\n",
" bar.set_postfix(\n",
" batch_loss=float(loss),\n",
" )\n",
"
" val_data = np.concatenate(val.iloc[:,0].values)\n",
" val_labels = val.iloc[:,1].values.astype(np.float32)\n",
" val_data = val_data.reshape(len(val),1,128,130)\n",
" val_labels = val_labels.reshape(len(val),1)\n",
" val_loss = get_loss(torch.tensor(val_data), torch.tensor(val_labels))\n",
" print(f\"Validation loss: {val_loss}\")\n",
"\n",
"\n",
"\n",
"
"test_data = np.concatenate(test.iloc[:,0].values)\n",
"test_labels = val.iloc[:,1].values.astype(np.float32)\n",
"test_data = val_data.reshape(len(val),1,128,130)\n",
"test_labels = val_labels.reshape(len(val),1)\n",
"test_loss = get_loss(torch.tensor(test_data), torch.tensor(test_labels))\n",
"print(f\"Test loss: {test_loss}\")\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"val_data = {\n",
" \"input_data\": [np.zeros(100).to |
list(), np.concatenate(val.iloc[:100,0].values).flatten().tolist()],\n",
"}\n",
"
"with open(\"val_data.json\", \"w\") as f:\n",
" json.dump(val_data, f)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = 0.1*torch.rand(1,*[1, 128, 130], requires_grad=True)\n",
"key = torch.rand(1,*[1], requires_grad=True)\n",
"\n",
"
"circuit.eval()\n",
"\n",
"
"torch.onnx.export(circuit,
" (key, 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'},\n",
" 'input.1' : {0 : 'batch_size'},
" 'output' : {0 : 'batch_size'}})\n",
"\n",
"key_array = ((key).detach().numpy()).reshape([-1]).tolist()\n",
"data_array = ((x).detach().numpy()).reshape([-1]).tolist()\n",
"\n",
"data = dict(input_data = [key_array, data_array])\n",
"\n",
"
"json.dump( data, open(\"input.json\", 'w' ))\n",
"\n",
"\n",
"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {}, |
"source": [
"Here we set the visibility of the different parts of the circuit, whereby the model params and the outputs of the computational graph (the key and the judgment) are public"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import ezkl\n",
" |
import os \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",
"srs_path = os.path.join('kzg.params')\n",
"data_path = os.path.join('input.json')\n",
"val_data = os.path.join('val_data.json')\n",
"\n",
"run_args = ezkl.PyRunArgs()\n",
"run_args.input_visibility = \"private\"\n",
"run_args.param_visibility = \"fixed\"\n",
"run_args.output_visibility = \"public\"\n",
"run_args.variables = [(\"batch_size\", 1)]\n",
"\n",
"\n",
"
"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\n",
"assert res == True\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 use the validation dataset we used during training. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"\n",
"res = ezkl.calibrate_settings(val_data, model_path, settings_path, \"resources\", scales = [4])\n",
" |
assert res == True\n",
"print(\"verified\")\n"
]
},
{
"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)"
]
},
{
"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": [
"\n",
"witness_path = \"witness.json\"\n",
"\n",
"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\n",
"assert os.path.isfile(witness_path)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"As a sani |
ty check we can run a mock proof. This just checks that all the constraints are valid. "
]
},
{
"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": [
"!export RUST_LOG=trace\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)"
]
},
{
"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",
" w |
itness_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\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import os\n",
"abi_path = 'test.abi'\n",
"sol_code_path = 'test.sol'\n",
"vk_path = os.path.join('test.vk')\n",
"srs_path = os.path.join('kzg.params')\n",
"settings_path = os.path.join('settings.json')\n",
"\n",
"\n",
"res = ezkl.create_evm_verifier(\n",
" vk_path,\n",
" \n",
" settings_path,\n",
" sol_code_path,\n",
" abi_path,\n",
" )\n",
"\n",
"assert res == True"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
]
},
{
"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": "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": 2
} |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "cf69bb3f-94e6-4dba-92cd-ce08df117d67",
"metadata": {},
"source": [
"
"\n",
"Here we demonstrate how to use the EZKL package to rotate an on-chain world. \n",
"\n",
"![zk-gaming-diagram-transformed](https:
"> **A typical ZK application flow**. For the shape rotators out there — this is an easily digestible example. A user computes a ZK-proof that they have calculated a valid rotation of a world. They submit this proof to a verifier contract which governs an on-chain world, along with a new set of coordinates, and the world rotation updates. Observe that it’s possible for one player to initiate a *global* change.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "95613ee9",
"metadata": {},
"outputs": [],
"source": [
"
"try:\n",
"
" |
import google.colab\n",
" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.