text
stringlengths 1
2.05k
|
---|
import logging\n",
"
"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\n",
"logging.basicConfig(format=FORMAT)\n",
"logging.getLogger().setLevel(logging.DEBUG)\n",
"\n",
"print(\"ezkl version: \", ezkl.__version__)"
]
},
{
"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,5], 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": [
" |
import getpass\n",
"
"input_filename = os.path.join('input.json')\n",
"\n",
"pg_input_file = dict(input_data = {\n",
" \"host\": \"localhost\",\n",
"
" \"user\": getpass.getuser(),\n",
" \"dbname\": \"shovel\",\n",
" \"password\": \"\",\n",
" \"query\": \"SELECT v FROM usdc ORDER BY block_num DESC LIMIT 5\",\n",
" \"port\": \"5432\",\n",
"})\n",
"\n",
"json_formatted_str = json.dumps(pg_input_file, indent=2)\n",
"print(json_formatted_str)\n",
"\n",
"\n",
"
"json.dump(pg_input_file, open(input_filename, 'w' ))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"calibration_filename = os.path.join('calibration.json')\n",
"\n",
"pg_cal_file = dict(input_data = {\n",
" \"host\": \"localhost\",\n",
"
" \"user\": getpass.getuser(),\n",
" \"dbname\": \"shovel\",\n",
" \"password\": \"\",\n",
" \"query\": \"SELECT v FROM usdc ORDER BY block_num DESC LIMIT 20\",\n",
" \"port\": \"5432\",\n",
"})\n",
"\n",
"
"json.dump( pg_cal_file, open(calibration_filename, 'w' ))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "eLJ7oirQ_HQR"
},
"source": [
"**EZKL Workflow**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "rNw0C9QL6W88"
},
"outputs": [],
"source": [
" |
import subprocess\n",
" |
import os\n",
"\n",
"onnx_filename = os.path.join('lol.onnx')\n",
"compiled_filename = os.path.join('lol.compiled')\n",
"settings_filename = os.path.join('settings.json')\n",
"\n",
"
"res = ezkl.gen_settings(onnx_filename, settings_filename)\n",
"\n",
"assert res == True\n",
"\n",
"res = ezkl.calibrate_settings(input_filename, onnx_filename, settings_filename, \"resources\")\n",
"\n",
"assert res == True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"ezkl.compile_circuit(onnx_filename, compiled_filename, settings_filename)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
},
"id": "4MmE9SX66_Il",
"outputId": "16403639-66a4-4280-ac7f-6966b75de5a3"
},
"outputs": [],
"source": [
"
"\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": null,
"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": [
"witness_path = \"witness.json\"\n",
"\n",
"
"res = ezkl.gen_witness(\n",
" input_filename,\n",
" compiled_filename,\n",
" witness_path\n",
" )\n"
]
},
{
"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",
"print(\"proved\")\n",
"\n",
"assert os.path.isfile(proof_path)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"os.system(\"pkill -f shovel\")"
]
}
],
"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.12.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
} |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "6ypZa6jg0rZy"
},
"source": [
"
"\n",
"Here we demonstrate how to use the EZKL package to build an MNIST classifier for on-chain handrawn digit recognition.\n",
"The proofs get submitted to a contract that assigns the users account to a digit clan (0-9). The contract keeps track of the member count of each clan. The clan with the most members is the winner!\n",
"\n",
", and the clan count updates according the lenets model's prediction. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Fm2DMmXW0rZ0"
},
"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\", \"torch\"])\n",
" subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"torchvision\"])\n",
" subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"tf2onnx\"])\n",
" subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n",
"\n",
"
"except:\n",
" pass\n",
"\n",
"
" |
import ezkl\n",
" |
import os\n",
" |
import json\n",
" |
import time\n",
" |
import random\n",
" |
import logging\n",
"\n",
"\n",
"
"FORMAT = '%(levelname)s %(name)s %(asctime)-15s %(filename)s:%(lineno)d %(message)s'\n",
"logging.basicConfig(format=FORMAT)\n",
"logging.getLogger().setLevel(logging.INFO)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jbRkAJLz0rZ1"
},
"outputs": [],
"source": [
" |
import torch\n",
" |
import torch.nn as nn\n",
" |
import torch.nn.functional as F\n",
"\n",
" |
class LeNet(nn.Module):\n",
" def __init__(self):\n",
" super(LeNet, self).__init__()\n",
"
" self.conv1 = nn.Conv2d(1, 6, 5)
" self.conv2 = nn.Conv2d(6, 16, 5)
"\n",
"
" self.fc1 = nn.Linear(16 * 4 * 4, 120) \n",
" self.fc2 = nn.Linear(120, 84)
" self.fc3 = nn.Linear(84, 10)
"\n",
" def forward(self, x):\n",
"
" x = F.avg_pool2d(F.sigmoid(self.conv1(x)), (2, 2))
" x = F.avg_pool2d(F.sigmoid(self.conv2(x)), (2, 2))
"\n",
"
" x = x.view(x.size(0), -1)\n",
"\n",
"
" x = F.sigmoid(self.fc1(x))\n",
" x = F.sigmoid(self.fc2(x))\n",
" x = self.fc3(x)
" return x\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https:
},
"id": "8yYNrvus0rZ2",
"outputId": "d3ae2380-fa03-4368-9bea-46c38a65ddca"
},
"outputs": [],
"source": [
" |
import numpy as np\n",
" |
import os\n",
" |
import torch\n",
"from torchvision.datasets |
import mnist\n",
"from torch.nn |
import CrossEntropyLoss\n",
"from torch.optim |
import Adam
"from torch.utils.data |
import DataLoader\n",
"from torchvision.transforms |
import ToTensor\n",
"\n",
"def normalize_img(image, label):\n",
" return torch.round(image), label\n",
"\n",
"device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
"batch_size = 256\n",
"train_dataset = mnist.MNIST(root='./train', train=True, transform=ToTensor(), download=True)\n",
"test_dataset = mnist.MNIST(root='./test', train=False, transform=ToTensor(), download=True)\n",
"train_loader = DataLoader(train_dataset, batch_size=batch_size)\n",
"test_loader = DataLoader(test_dataset, batch_size=batch_size)\n",
"model = LeNet().to(device)\n",
"adam = Adam(model.parameters())
"loss_fn = CrossEntropyLoss()\n",
"all_epoch = 25\n",
"prev_acc = 0\n",
"for current_epoch in range(all_epoch):\n",
" model.train()\n",
" for idx, (train_x, train_label) in enumerate(train_loader):\n",
" train_x = train_x.to(device)\n",
"
" train_x = train_x.round()\n",
" train_label = train_label.to(device)\n",
" adam.zero_grad()
" predict_y = model(train_x.float())\n",
" loss = loss_fn(predict_y, train_label.long())\n",
" loss.backward()\n",
" adam.step()
" all_correct_num = 0\n",
" all_sample_num = 0\n",
" model.eval()\n",
"\n",
" for idx, (test_x, test_label) in enumerate(test_loader):\n",
" test_x = test_x.to(device)\n",
"
" test_x = test_x.round()\n",
" test_label = test_label.to(device)\n",
" predict_y = model(test_x.float()).detach()\n",
" predict_y = torch.argmax(predict_y, dim=-1)\n",
" current_correct_num = predict_y == test_label\n",
" all_correct_num += np.sum(current_correct_num.to('cpu').numpy(), axis=-1)\n",
" all_sample_num += current_correct_num. |
shape[0]\n",
" acc = all_correct_num / all_sample_num\n",
" print('test accuracy: {:.3f}'.format(acc), flush=True)\n",
" if not os.path.isdir(\"models\"):\n",
" os.mkdir(\"models\")\n",
" torch.save(model, 'models/mnist_{:.3f}.pkl'.format(acc))\n",
" prev_acc = acc\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import matplotlib.pyplot as plt\n",
" |
import numpy as np\n",
"from matplotlib |
import colors\n",
"from scipy |
import stats\n",
"n_bins = 100\n",
"
"minimum_abs_val = 100000\n",
"params_abs = []\n",
"for param in model.parameters():\n",
" if param.abs().min() < minimum_abs_val:\n",
" minimum_abs_val = param.abs().min()\n",
" params_abs.extend(param.abs().detach().numpy().flatten().tolist())\n",
"\n",
"print(minimum_abs_val)\n",
"\n",
"xx = np.linspace(0, 0.2, 1000)\n",
"\n",
"kde = stats.gaussian_kde(params_abs)\n",
"fig, ax = plt.subplots(figsize = (6,4))\n",
"\n",
"ax.set_xlim(0, 0.2)\n",
"\n",
"
"N, bins, patches = ax.hist(params_abs, bins=n_bins, density = True, alpha =0.65)\n",
"ax.plot(xx, kde(xx))\n",
"\n",
"\n",
"ax.set_ylim(0, 14)\n",
"ax.set_yticklabels([])\n",
"ax.set_ylabel(\"\")\n",
"plt.style.use(\"bmh\")\n",
"ax.set_xticks([1.0/128.0, 1.0/32.0, 1.0/16.0])\n",
"ax.set_xticklabels([\"1/2^7\", \"1/2^6\", \"1/2^5\"])\n",
"ax.grid(False)\n",
"
"quant_5, quant_25, quant_50, quant_75, quant_95 = np.quantile(params_abs, 0.05), np.quantile(params_abs, 0.25), np.quantile(params_abs, 0.5), np.quantile(params_abs, 0.75), np.quantile(params_abs, 0.95)\n",
"\n",
"
"quants = [[quant_5, 0.6, 0.16], [quant_25, 0.8, 0.26], [quant_50, 1, 0.36], [quant_75, 0.8, 0.46], [quant_95, 0.6, 0.56]]\n",
"\n",
"
"for i in quants:\n",
" ax.axvline(i[0], alpha = i[1], ymax = i[2], linestyle = \":\")\n",
"\n",
"
"ax.text(quant_5, 14 * 0.17, \"5th\", size = 10, alpha = 0.8)\n",
"ax.text(quant_25, 14 * 0.27, \"25th\", size = 10, alpha = 0.85)\n",
"ax.text(quant_50, 14 * 0.37, \"50th\", size = 10, alpha = 1)\n",
"ax.text(quant_75, 14 * 0.47, \"75th\", size = 10, alpha = 0.85)\n",
"ax.text(quant_95, 14 * 0.57, \"95th Percentile\", size = 10, alpha =.8)\n",
"\n", |
"ax.set_title(\"Absolute value of parameters\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tmGo25eb0rZ3"
},
"outputs": [],
"source": [
" |
import os\n",
"\n",
"model_path = os.path.join('network_lenet.onnx')\n",
"compiled_model_path = os.path.join('network.compiled')\n",
"pk_path = os.path.join('key.pk')\n",
"vk_path = os.path.join('key.vk')\n",
"settings_path = os.path.join('settings.json')\n",
"witness_path = os.path.join('witness.json')\n",
"data_path = os.path.join('input.json')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RfFjaXrM0rZ3"
},
"outputs": [],
"source": [
" |
import torch\n",
" |
import json\n",
"\n",
"model.eval()
"\n",
"
"
"train_data_point, _ = next(iter(train_dataset))\n",
"train_data_point = train_data_point.unsqueeze(0)
"\n",
"
"device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
"train_data_point = train_data_point.to(device)\n",
"\n",
"
"torch.onnx.export(model, train_data_point, model_path, export_params=True, opset_version=12, do_constant_folding=True, input_names=['input_0'], output_names=['output'])\n",
"\n",
"
"x = train_data_point.cpu().detach().numpy().reshape([-1]).tolist()\n",
"data = {'input_data': [x]}\n",
"with open('input.json', 'w') as f:\n",
" json.dump(data, f)\n",
"\n",
"print(f\"Model exported to {model_path} and input data saved to input.json\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dS-yXte30rZ3"
},
"outputs": [],
"source": [
" |
import ezkl\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.num_inner_cols = 2\n",
"run_args.variables = [(\"batch_size\", 1)]\n",
"\n",
"
"num_data_points = 8\n",
"\n",
"
"data_points = []\n",
"for i, (data_point, _) in enumerate(train_dataset):\n",
" if i >= num_data_points:\n",
" break\n",
" data_points.append(data_point)\n",
"\n",
"
"train_data_batch = torch.stack(data_points)\n",
"\n",
"
"if train_data_batch.dim() == 3:\n",
" train_data_batch = train_data_batch.unsqueeze(0)\n",
"\n",
"x = train_data_batch.cpu().detach().numpy().reshape([-1]).tolist()\n",
"\n",
"data = dict(input_data = [x])\n",
"\n",
"cal_path = os.path.join('cal_data.json')\n",
"\n",
"
"json.dump( data, open(cal_path, 'w' ))\n",
"\n",
"!RUST_LOG=trace\n",
"
"res = ezkl.gen_settings(model_path, settings_path, py_run_args=run_args)\n",
"assert res == True\n",
"\n",
"res = ezkl.calibrate_settings(cal_path, model_path, settings_path, \"resources\", scales=[2,7])\n",
"assert res == True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "pGb1nj720rZ3"
},
"outputs": [],
"source": [
"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n",
"assert res == True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "umpLxVAI0rZ3"
},
"outputs": [],
"source": [
"
"res = ezkl.get_srs(settings_path)"
]
},
{
"cell_type": "code",
"execution_count": |
null,
"metadata": {
"id": "syLy2Kt90rZ3"
},
"outputs": [],
"source": [
"
"witness_path = \"witness.json\"\n",
"\n",
"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\n",
"assert os.path.isfile(witness_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "65u_ObBQ0rZ4"
},
"outputs": [],
"source": [
"res = ezkl.mock(witness_path, compiled_model_path)\n",
"assert res == True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c8GIoMD40rZ4"
},
"outputs": [],
"source": [
"\n",
"
"
"
"
"\n",
"res = ezkl.setup(\n",
" compiled_model_path,\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_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vkIutAhR0rZ4"
},
"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",
" \"single\",\n",
" )\n",
"\n",
"print(res)\n",
"assert os.path.isfile(proof_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KmpQBZUT0rZ4"
},
"outputs": [],
"source": [
"
"res = ezkl.verify(\n",
" proof_path,\n",
" settings_path,\n",
" vk_path,\n", |
" )\n",
"\n",
"assert res == True\n",
"print(\"verified\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CZ2CYQdm0rZ4"
},
"source": [
"We can now create an EVM / `.sol` verifier that can be deployed on chain to verify submitted proofs using a view function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "jASymUWQ0rZ4"
},
"outputs": [],
"source": [
"\n",
"abi_path = 'test.abi'\n",
"sol_code_path = 'test_1.sol'\n",
"\n",
"res = ezkl.create_evm_verifier(\n",
" vk_path,\n",
" settings_path,\n",
" sol_code_path,\n",
" abi_path,\n",
" )\n",
"assert res == True"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-icN2yw60rZ5"
},
"source": [
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "sTLsLwaC0rZ5"
},
"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": {
"id": "PrSyQK4B0rZ5"
},
"outputs": [],
"source": [
"
"
"\n",
"res = ezkl.verify_evm(\n",
" addr,\n",
" proof_path,\n",
" \"http:
")\n",
"assert res == True"
]
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"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": 0
} |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"Credits to [geohot](https:
]
},
{
"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\", \"tf2onnx\"])\n",
" subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n",
"\n",
"
"except:\n",
" pass\n",
"\n",
"
" |
import ezkl\n",
" |
import os\n",
" |
import json\n",
" |
import time\n",
" |
import random\n",
" |
import logging\n",
"\n",
" |
import tensorflow as tf\n",
"from tensorflow.keras.optimizers |
import Adam\n",
"from tensorflow.keras.layers |
import *\n",
"from tensorflow.keras.models |
import Model\n",
"from tensorflow.keras.datasets |
import mnist\n",
"\n",
"
"
"
"
"\n",
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
"x_train, x_test = [x/255.0 for x in [x_train, x_test]]\n",
"y_train, y_test = [tf.keras.utils.to_categorical(x) for x in [y_train, y_test]]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"ZDIM = 100\n",
"\n",
"opt = Adam()\n",
"\n",
"\n",
"
"
"x = in1 = Input((28,28))\n",
"x = Reshape((28,28,1))(x)\n",
"\n",
"x = Conv2D(64, (5,5), padding='same', strides=(2,2))(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"\n",
"x = Conv2D(128, (5,5), padding='same', strides=(2,2))(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"\n",
"x = Flatten()(x)\n",
"x = Dense(128)(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"x = Dense(1, activation='sigmoid')(x)\n",
"dm = Model(in1, x)\n",
"dm.compile(opt, 'binary_crossentropy')\n",
"dm.summary()\n",
"\n",
"
"x = in1 = Input((ZDIM,))\n",
"\n",
"x = Dense(7*7*64)(x)\n",
"x = BatchNormalization()(x)\n", |
"x = ELU()(x)\n",
"x = Reshape((7,7,64))(x)\n",
"\n",
"x = Conv2DTranspose(128, (5,5), strides=(2,2), padding='same')(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"\n",
"x = Conv2DTranspose(1, (5,5), strides=(2,2), padding='same')(x)\n",
"x = Activation('sigmoid')(x)\n",
"x = Reshape((28,28))(x)\n",
"\n",
"gm = Model(in1, x)\n",
"gm.compile('adam', 'mse')\n",
"gm.output_names=['output']\n",
"gm.summary()\n",
"\n",
"opt = Adam()\n",
"\n",
"
"dm.trainable = False\n",
"x = dm(gm.output)\n",
"tm = Model(gm.input, x)\n",
"tm.compile(opt, 'binary_crossentropy')\n",
"\n",
"dlosses, glosses = [], []"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
" |
import numpy as np\n",
"from matplotlib.pyplot |
import figure, imshow, show\n",
"\n",
"BS = 256\n",
"\n",
"
"
"for i in range(1):\n",
"
" dm.trainable = True\n",
" real_i = x_train[np.random.choice(x_train.shape[0], BS)]\n",
" fake_i = gm.predict_on_batch(np.random.normal(0,1,size=(BS,ZDIM)))\n",
" dloss_r = dm.train_on_batch(real_i, np.ones(BS))\n",
" dloss_f = dm.train_on_batch(fake_i, np.zeros(BS))\n",
" dloss = (dloss_r + dloss_f)/2\n",
"\n",
"
" dm.trainable = False\n",
" gloss_0 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\n",
" gloss_1 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\n",
" gloss = (gloss_0 + gloss_1)/2\n",
"\n",
" if i%50 == 0:\n",
" print(\"%4d: dloss:%8.4f gloss:%8.4f\" % (i, dloss, gloss))\n",
" dlosses.append(dloss)\n",
" glosses.append(gloss)\n",
" \n",
" if i%250 == 0:\n",
" \n",
" figure(figsize=(16,16))\n",
" imshow(np.concatenate(gm.predict(np.random.normal(size=(10,ZDIM))), axis=1))\n",
" show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from matplotlib.pyplot |
import plot, legend\n",
"figure(figsize=(8,8))\n",
"plot(dlosses[100:], label=\"Discriminator Loss\")\n",
"plot(glosses[100:], label=\"Generator Loss\")\n",
"legend()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = []\n",
"for i in range(10):\n",
" x.append(np.concatenate(gm.predict(np.random.normal(size=(10,ZDIM))), axis=1))\n",
"imshow(np.concatenate(x, axis=0))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import os \n",
"\n",
"model_path = os.path.join('gan.onnx')\n",
"compiled_model_path = os.path.join('gan.compiled')\n",
"pk_path = os.path.join('gan.pk')\n",
"vk_path = os.path.join('gan.vk')\n",
"settings_path = os.path.join('gan_settings.json')\n",
"srs_path = os.path.join('gan_kzg.srs')\n",
"witness_path = os.path.join('gan_witness.json')\n",
"data_path = os.path.join('gan_input.json')\n",
"\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we export the _generator_ to onnx"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
" |
import numpy as np\n",
" |
import tf2onnx\n",
" |
import tensorflow as tf\n",
" |
import json\n",
"\n",
"shape = [1, ZDIM]\n",
"
"x = 0.1*np.random.rand(1,*shape)\n",
"\n",
"spec = tf.TensorSpec(shape, tf.float32, name='input_0')\n",
"\n",
"\n",
"tf2onnx.convert.from_keras(gm, input_signature=[spec], inputs_as_nchw=['input_0'], opset=12, output_path=model_path)\n",
"\n",
"data_array = x.reshape([-1]).tolist()\n",
"\n",
"data = dict(input_data = [data_array])\n",
"\n",
"
"json.dump( data, open(data_path, 'w' ))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
" |
import ezkl\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",
"!RUST_LOG=trace\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,
"metadata": {},
"outputs": [],
"source": [
"cal_path = os.path.join(\"calibration.json\")\n",
"\n",
"data_array = (0.2 * np.random.rand(20, *shape)).reshape([-1]).tolist()\n",
"\n",
"data = dict(input_data = [data_array])\n",
"\n",
"
"json.dump(data, open(cal_path, 'w'))\n",
"\n",
"\n",
"ezkl.calibrate_settings(cal_path, model_path, settings_path, \"resources\", scales=[0,6])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path)\n",
"assert res == True"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"res = ezkl.get_srs( settings_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"witness_path = \"g |
an_witness.json\"\n",
"\n",
"res = ezkl.gen_witness(data_path, compiled_model_path, witness_path)\n",
"assert os.path.isfile(witness_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"
"
"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"
"
"
"
"\n",
"res = ezkl.setup(\n",
" compiled_model_path,\n",
" vk_path,\n",
" pk_path,\n",
" \n",
" )\n",
"\n",
"assert res == True\n",
"assert os.path.isfile(vk_path)\n",
"assert os.path.isfile(pk_path)\n",
"assert os.path.isfile(settings_path)"
]
},
{
"cell_type": "code",
"execution_count": null,
"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,
"metadata": {}, |
"outputs": [],
"source": [
"
"res = ezkl.verify(\n",
" proof_path,\n",
" settings_path,\n",
" vk_path,\n",
" \n",
" )\n",
"\n",
"assert res == True\n",
"print(\"verified\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.12.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
} |
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"
"\n",
"Here we showcase how to split a larger circuit into multiple smaller proofs. This is useful if you want to prove over multiple machines, or if you want to split a proof into multiple parts to reduce the memory requirements.\n",
"\n",
"We showcase how to do this in the case where:\n",
"- intermediate calculations need to be kept secret (but not blinded !) and we need to use the low overhead kzg commitment scheme detailed [here](https:
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"First we |
import the necessary dependencies and set up logging to be as informative as possible. "
]
},
{
"cell_type": "code",
"execution_count": 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\", \"tf2onnx\"])\n",
" subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"onnx\"])\n",
"\n",
"
"except:\n",
" pass\n",
"\n",
"
" |
import ezkl\n",
" |
import os\n",
" |
import json\n",
" |
import time\n",
" |
import random\n",
" |
import logging\n",
"\n",
" |
import tensorflow as tf\n",
"from tensorflow.keras.optimizers |
import Adam\n",
"from tensorflow.keras.layers |
import *\n",
"from tensorflow.keras.models |
import Model\n",
"from tensorflow.keras.datasets |
import mnist\n",
"\n",
"
"
"
"
"\n",
"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"\n",
"(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
"x_train, x_test = [x/255.0 for x in [x_train, x_test]]\n",
"y_train, y_test = [tf.keras.utils.to_categorical(x) for x in [y_train, y_test]]"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">Model: \"functional_1\"</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[1mModel: \"functional_1\"\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">βββββββββββββββββββββββββββββββββββ³βββββββββββββββββββββββββ³ββββββββββββββββ\n",
"β<span style=\"font-weight: bold\"> Layer (type) </span>β<span style=\"font-weight: bold\"> Output Shape </span>β<span style=\"font-weight: bold\"> Param
"β‘ββββββββββββββββββββββββββββββββββββββββββββββββββ |
βββββββββββββββββββββββββ©\n",
"β input_layer (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β reshape (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization β (<span style=\"color:
"β (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d_1 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_1 β (<span style=\"color:
"β (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_1 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β flatten (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β dense (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_2 β (<span style=\"color:
"β (<span style=\"color: |
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_2 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β dense_1 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄ββββββββββββββββ\n",
"</pre>\n"
],
"text/plain": [
"βββββββββββββββββββββββββββββββββββ³βββββββββββββββββββββββββ³ββββββββββββββββ\n",
"β\u001b[1m \u001b[0m\u001b[1mLayer (type) \u001b[0m\u001b[1m \u001b[0mβ\u001b[1m \u001b[0m\u001b[1mOutput Shape \u001b[0m\u001b[1m \u001b[0mβ\u001b[1m \u001b[0m\u001b[1m Param
"β‘βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©\n",
"β input_layer (\u001b[38;5;33mInputLayer\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m28\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β reshape (\u001b[38;5;33mReshape\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m1\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d (\u001b[38;5;33mConv2D\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m64\u001b[0m) β \u001b[38;5;34m1,664\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌββββββββββ |
βββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m64\u001b[0m) β \u001b[38;5;34m256\u001b[0m β\n",
"β (\u001b[38;5;33mBatchNormalization\u001b[0m) β β β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu (\u001b[38;5;33mELU\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m64\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d_1 (\u001b[38;5;33mConv2D\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m204,928\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_1 β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m512\u001b[0m β\n",
"β (\u001b[38;5;33mBatchNormalization\u001b[0m) β β β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_1 (\u001b[38;5;33mELU\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌββββββββββββββββββ |
βββββββΌββββββββββββββββ€\n",
"β flatten (\u001b[38;5;33mFlatten\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m6272\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β dense (\u001b[38;5;33mDense\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m802,944\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_2 β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m512\u001b[0m β\n",
"β (\u001b[38;5;33mBatchNormalization\u001b[0m) β β β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_2 (\u001b[38;5;33mELU\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β dense_1 (\u001b[38;5;33mDense\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m1\u001b[0m) β \u001b[38;5;34m129\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄ββββββββββββββββ\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:norm |
al;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Total params: </span><span style=\"color:
"</pre>\n"
],
"text/plain": [
"\u001b[1m Total params: \u001b[0m\u001b[38;5;34m1,010,945\u001b[0m (3.86 MB)\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Trainable params: </span><span style=\"color:
"</pre>\n"
],
"text/plain": [
"\u001b[1m Trainable params: \u001b[0m\u001b[38;5;34m1,010,305\u001b[0m (3.85 MB)\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Non-trainable params: </span><span style=\"color:
"</pre>\n"
],
"text/plain": [
"\u001b[1m Non-trainable params: \u001b[0m\u001b[38;5;34m640\u001b[0m (2.50 KB)\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [ |
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\">Model: \"functional_3\"</span>\n",
"</pre>\n"
],
"text/plain": [
"\u001b[1mModel: \"functional_3\"\u001b[0m\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">βββββββββββββββββββββββββββββββββββ³βββββββββββββββββββββββββ³ββββββββββββββββ\n",
"β<span style=\"font-weight: bold\"> Layer (type) </span>β<span style=\"font-weight: bold\"> Output Shape </span>β<span style=\"font-weight: bold\"> Param
"β‘βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©\n",
"β input_layer_1 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β dense_2 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_3 β (<span style=\"color:
"β (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_3 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β reshape_1 (<span style=\"color: |
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d_transpose β (<span style=\"color:
"β (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_4 β (<span style=\"color:
"β (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_4 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d_transpose_1 β (<span style=\"color:
"β (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β activation (<span style=\"color:
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β reshape_2 (<span style=\"color:
"βββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄ββββββββββββββββ\n",
"</pre>\n"
],
"text/plain": [
"βββββββββββββββββββββββββββββββββββ³βββββββββββββββββββββββββ³ββββββββββββββββ\n",
"β\u001b[1m \u001b[0m\u001b[1mLayer (type) \u001b[0m\u001b[1m \u001b[0mβ\u001b[1m \u001b[0m\u001b[1mOutput Shape \u001b[0m\u001b[1m \u001b[0mβ\u001b[1m \u001b[0m\u001b[1m Param
"β‘βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ©\n",
"β input_layer_1 (\u001b[38;5;33mInputLayer\u001b[0m) β (\u001b[38;5;45 |
mNone\u001b[0m, \u001b[38;5;34m100\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β dense_2 (\u001b[38;5;33mDense\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m3136\u001b[0m) β \u001b[38;5;34m316,736\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_3 β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m3136\u001b[0m) β \u001b[38;5;34m12,544\u001b[0m β\n",
"β (\u001b[38;5;33mBatchNormalization\u001b[0m) β β β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_3 (\u001b[38;5;33mELU\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m3136\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β reshape_1 (\u001b[38;5;33mReshape\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m7\u001b[0m, \u001b[38;5;34m64\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d_transpose β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m204,928\u001b[0m β\n",
"β (\u001b[38;5;33mConv2DTranspose\u001b[0m) β β β\n",
"βββββββββββββββββββββ |
ββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β batch_normalization_4 β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m512\u001b[0m β\n",
"β (\u001b[38;5;33mBatchNormalization\u001b[0m) β β β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β elu_4 (\u001b[38;5;33mELU\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m14\u001b[0m, \u001b[38;5;34m128\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β conv2d_transpose_1 β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m1\u001b[0m) β \u001b[38;5;34m3,201\u001b[0m β\n",
"β (\u001b[38;5;33mConv2DTranspose\u001b[0m) β β β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β activation (\u001b[38;5;33mActivation\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m1\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌββββββββββββββββ€\n",
"β reshape_2 (\u001b[38;5;33mReshape\u001b[0m) β (\u001b[38;5;45mNone\u001b[0m, \u001b[38;5;34m28\u001b[0m, \u001b[38;5;34m28\u001b[0m) β \u001b[38;5;34m0\u001b[0m β\n",
"βββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββ |
βββββββ΄ββββββββββββββββ\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Total params: </span><span style=\"color:
"</pre>\n"
],
"text/plain": [
"\u001b[1m Total params: \u001b[0m\u001b[38;5;34m537,921\u001b[0m (2.05 MB)\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Trainable params: </span><span style=\"color:
"</pre>\n"
],
"text/plain": [
"\u001b[1m Trainable params: \u001b[0m\u001b[38;5;34m531,393\u001b[0m (2.03 MB)\n"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"text/html": [
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\"><span style=\"font-weight: bold\"> Non-trainable params: </span><span style=\"color:
"</pre>\n"
],
"text/plain": [ |
"\u001b[1m Non-trainable params: \u001b[0m\u001b[38;5;34m6,528\u001b[0m (25.50 KB)\n"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"opt = Adam()\n",
"ZDIM = 100\n",
"\n",
"
"
"x = in1 = Input((28,28))\n",
"x = Reshape((28,28,1))(x)\n",
"\n",
"x = Conv2D(64, (5,5), padding='same', strides=(2,2))(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"\n",
"x = Conv2D(128, (5,5), padding='same', strides=(2,2))(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"\n",
"x = Flatten()(x)\n",
"x = Dense(128)(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"x = Dense(1, activation='sigmoid')(x)\n",
"dm = Model(in1, x)\n",
"dm.compile(opt, 'binary_crossentropy')\n",
"dm.summary()\n",
"\n",
"
"x = in1 = Input((ZDIM,))\n",
"\n",
"x = Dense(7*7*64)(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"x = Reshape((7,7,64))(x)\n",
"\n",
"x = Conv2DTranspose(128, (5,5), strides=(2,2), padding='same')(x)\n",
"x = BatchNormalization()(x)\n",
"x = ELU()(x)\n",
"\n",
"x = Conv2DTranspose(1, (5,5), strides=(2,2), padding='same')(x)\n",
"x = Activation('sigmoid')(x)\n",
"x = Reshape((28,28))(x)\n",
"\n",
"gm = Model(in1, x)\n",
"gm.compile('adam', 'mse')\n",
"gm.summ |
ary()\n",
"\n",
"opt = Adam()\n",
"\n",
"
"dm.trainable = False\n",
"x = dm(gm.output)\n",
"tm = Model(gm.input, x)\n",
"tm.compile(opt, 'binary_crossentropy')\n",
"\n",
"dlosses, glosses = [], []"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 0: dloss: 0.8063 gloss: 0.6461\n",
"\u001b[1m1/1\u001b[0m \u001b[32mββββββββββββββββββββ\u001b[0m\u001b[37m\u001b[0m \u001b[1m0s\u001b[0m 42ms/step\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABQcAAACrCAYAAADb2yoEAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/H5lhTAAAACXBIWXMAAA9hAAAPYQGoP6dpAACNcklEQVR4nO39eZRlV3Xmi87TN3Ga6LuMyL5TKqWUlJJSCUIIK5EAGyPA1xhzjUxx8SsscQtwCzZQ+NnWe9S71wyXKXNHjbrGHlXYmLoGjGzAsgQSQqlEvZSp7LuIyOi7cyJO370/ZBLNb05lpEAoBfH9xsgxcp2z9mrnmmvtHWd/M9BqtVpCCCGEEEIIIYQQQghZdQQvdQMIIYQQQgghhBBCCCGXBj4cJIQQQgghhBBCCCFklcKHg4QQQgghhBBCCCGErFL4cJAQQgghhBBCCCGEkFUKHw4SQgghhBBCCCGEELJK4cNBQgghhBBCCCGEEEJWKXw4SAghhBBCCCGEEELIKoUPBwkhhBBCCCGEEEIIWaXw4SAhhBBCCCGEEEIIIasUPhwkhBBCCCGEEEIIIWSV8hN7OPi5z31O1q9fL/F4XPbs2SPf
"text/plain": [
"<Figure size 1600x1600 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
" |
import numpy as np\n",
"from matplotlib.pyplot |
import figure, imshow, show\n",
"\n",
"BS = 256\n",
"\n",
"
"
"for i in range(1):\n",
"
" dm.trainable = True\n",
" real_i = x_train[np.random.choice(x_train.shape[0], BS)]\n",
" fake_i = gm.predict_on_batch(np.random.normal(0,1,size=(BS,ZDIM)))\n",
" dloss_r = dm.train_on_batch(real_i, np.ones(BS))\n",
" dloss_f = dm.train_on_batch(fake_i, np.zeros(BS))\n",
" dloss = (dloss_r + dloss_f)/2\n",
"\n",
"
" dm.trainable = False\n",
" gloss_0 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\n",
" gloss_1 = tm.train_on_batch(np.random.normal(0,1,size=(BS,ZDIM)), np.ones(BS))\n",
" gloss = (gloss_0 + gloss_1)/2\n",
"\n",
" if i%50 == 0:\n",
" print(\"%4d: dloss:%8.4f gloss:%8.4f\" % (i, dloss, gloss))\n",
" dlosses.append(dloss)\n",
" glosses.append(gloss)\n",
" \n",
" if i%250 == 0:\n",
" \n",
" figure(figsize=(16,16))\n",
" imshow(np.concatenate(gm.predict(np.random.normal(size=(10,ZDIM))), axis=1))\n",
" show()"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<matplotlib.legend.Legend at 0x34f625160>"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.