text
stringlengths
1
2.05k
n", "Epoch 5/10\n", "12/12 [==============================] - 0s 3ms/step - loss: 0.0705 - accuracy: 0.9780 - val_loss: 0.0735 - val_accuracy: 0.9560\n", "Epoch 6/10\n", "12/12 [==============================] - 0s 2ms/step - loss: 0.0684 - accuracy: 0.9808 - val_loss: 0.0713 - val_accuracy: 0.9670\n", "Epoch 7/10\n", "12/12 [==============================] - 0s 3ms/step - loss: 0.0667 - accuracy: 0.9835 - val_loss: 0.0687 - val_accuracy: 0.9780\n", "Epoch 8/10\n", "12/12 [==============================] - 0s 3ms/step - loss: 0.0653 - accuracy: 0.9835 - val_loss: 0.0665 - val_accuracy: 0.9670\n", "Epoch 9/10\n", "12/12 [==============================] - 0s 3ms/step - loss: 0.0640 - accuracy: 0.9835 - val_loss: 0.0648 - val_accuracy: 0.9670\n", "Epoch 10/10\n", "12/12 [==============================] - 0s 3ms/step - loss: 0.0628 - accuracy: 0.9835 - val_loss: 0.0635 - val_accuracy: 0.9670\n" ] }, { "data": { "text/plain": [ "<keras.callbacks.History at 0x160461eb0>" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.fit(X_train, y_train,\n", " epochs=10, batch_size=32,\n", " validation_split=0.2,\n", " shuffle=False)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4/4 [==============================] - 0s 1ms/step - loss: 0.0719 - accuracy: 0.9737\n", "Test loss: 0.07194967567920685\n", "Test accuracy: 0.9736841917037964\n" ] } ], "source": [ "test_loss, test_acc = model.evaluate(X_test, y_test)\n", "print(\"Test loss:\", test_loss)\n", "print(\"Test accuracy:\", test_acc)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def zigmoid(x):\n", "
return 0.502073021 + 0.198695283 * x - 0.001570683 * x**2 - 0.004001354 * x**3\n", "zigmoid_model = Sequential()\n", "\n", "zigmoid_model.add(InputLayer(input_shape=(30, )))\n", " "zigmoid_model.add(Dense(1, activation=zigmoid))\n", "\n", "optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=0.05)\n", "zigmoid_model.compile(optimizer=optimizer,\n", " loss='binary_crossentropy',\n", " metrics=['accuracy'])" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1/10\n", "12/12 [==============================] - 0s 11ms/step - loss: 1.1248 - accuracy: 0.7720 - val_loss: 0.5485 - val_accuracy: 0.9011\n", "Epoch 2/10\n", "12/12 [==============================] - 0s 3ms/step - loss: 0.5224 - accuracy: 0.9121 - val_loss: 0.2269 - val_accuracy: 0.9780\n", "Epoch 3/10\n", "12/12 [==============================] - 0s 2ms/step - loss: 0.2841 - accuracy: 0.9423 - val_loss: 0.1875 - val_accuracy: 0.9560\n", "Epoch 4/10\n", "12/12 [==============================] - 0s 3ms/step - loss: 0.2715 - accuracy: 0.9588 - val_loss: 0.1772 - val_accuracy: 0.9560\n", "Epoch 5/10\n", "12/12 [==============================] - 0s 2ms/step - loss: 0.2591 - accuracy: 0.9560 - val_loss: 0.1714 - val_accuracy: 0.9670\n", "Epoch 6/10\n", "12/12 [==============================] - 0s 2ms/step - loss: 0.2549 - accuracy: 0.9560 - val_loss: 0.1657 - val_accuracy: 0.9670\n", "Epoch 7/10\n", "12/12 [==============================] - 0s 2ms/step - loss: 0.2559 - accuracy: 0.9533 - val_loss: 0.1639 - val_accuracy: 0.9670\n", "Epoch 8/10\n", "12/12 [==============================] - 0s 2ms/step - loss: 0.2508 - accuracy: 0.9533 - val_loss: 0.1605 - val_accuracy: 0.9670\n", "Epoch 9/10\n", "12/12 [==============================] - 0s 2ms/step - loss:
0.2475 - accuracy: 0.9560 - val_loss: 0.1590 - val_accuracy: 0.9670\n", "Epoch 10/10\n", "12/12 [==============================] - 0s 2ms/step - loss: 0.2490 - accuracy: 0.9588 - val_loss: 0.1591 - val_accuracy: 0.9560\n" ] }, { "data": { "text/plain": [ "<keras.callbacks.History at 0x1604f03a0>" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "zigmoid_model.fit(X_train, y_train,\n", " epochs=10, batch_size=32,\n", " validation_split=0.2,\n", " shuffle=False)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4/4 [==============================] - 0s 1ms/step - loss: 0.1795 - accuracy: 0.9561\n", "Test loss: 0.1795477569103241\n", "Test accuracy: 0.9561403393745422\n" ] } ], "source": [ "test_loss, test_acc = zigmoid_model.evaluate(X_test, y_test)\n", "print(\"Test loss:\", test_loss)\n", "print(\"Test accuracy:\", test_acc)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "sklearn", "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.16" } }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "p = 21888242871839275222246405745257275088548364400416034343698204186575808495617" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from tensorflow.keras.layers
import Input, MaxPooling2D\n", "from tensorflow.keras
import Model\n", "
import numpy as np" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "inputs = Input(shape=(5,5,3))\n", "x = MaxPooling2D(pool_size=2)(inputs)\n", "model = Model(inputs, x)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"model\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param "=================================================================\n", " input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n", " \n", " max_pooling2d (MaxPooling2D (None, 2, 2, 3) 0 \n", " ) \n", " \n", "=================================================================\n", "Total params: 0\n", "Trainable params: 0\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[[[0.44076837, 0.4645178 , 0.88532658],\n", " [0.98571178, 0.36091035, 0.37878294],\n", " [0.09039054, 0.43555648, 0.70723494],\n", " [0.75087575, 0.46161156, 0.27621923],\n", " [0.3658674 , 0.76096207, 0.85368763]],\n", "\n", " [[0.53353854, 0.18599507, 0.85547589],\n", " [0.83705565, 0.3310797 , 0.42121576],\n", " [0.97948862, 0.58870474, 0.022469 ],\n", " [0.40446888, 0.15924946, 0.39474075],\n",
" [0.39336331, 0.83113873, 0.58711273]],\n", "\n", " [[0.00324599, 0.84351736, 0.65574229],\n", " [0.00423293, 0.09477659, 0.85111496],\n", " [0.84792575, 0.32417744, 0.52031854],\n", " [0.78577668, 0.63963473, 0.66767045],\n", " [0.6838523 , 0.40963437, 0.296101 ]],\n", "\n", " [[0.25513283, 0.21434056, 0.139309 ],\n", " [0.61281984, 0.77039643, 0.3830965 ],\n", " [0.52747206, 0.60847264, 0.60792949],\n", " [0.63030064, 0.5966706 , 0.05825615],\n", " [0.78633397, 0.4404418 , 0.30296519]],\n", "\n", " [[0.4233433 , 0.2882031 , 0.85232675],\n", " [0.60716483, 0.95202431, 0.39592074],\n", " [0.55245804, 0.00922525, 0.50775513],\n", " [0.65796373, 0.01939091, 0.10486254],\n", " [0.06172721, 0.64735306, 0.22485494]]]])" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X = np.random.rand(1,5,5,3)\n", "X" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 29ms/step\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2023-10-23 21:44:15.505331: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n" ] }, { "data": { "text/plain": [ "array([[[[0.98571175, 0.4645178 , 0.88532656],\n", " [0.9794886 , 0.58870476, 0.7072349 ]],\n", "\n", " [[0.61281985, 0.84351736, 0.851115 ],\n", " [0.8479257 , 0.6396347 , 0.6676704 ]]]], dtype=float32)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ],
"source": [ "y = model.predict(X)\n", "y" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "def MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\n", " Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n", " out = [[[str(max(input[i*strides + x][j*strides + y][k] for x in range(poolSize) for y in range(poolSize)) % p) for k in range(nChannels)] for j in range((nCols - poolSize) " return Input, out" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[['985711776216457240221750775571808256',\n", " '464517795839652376609037137683152896',\n", " '885326582306963556558255153072832512'],\n", " ['979488619923621857462245439242764288',\n", " '588704741840418336217153490575687680',\n", " '707234940167889112717525758819434496']],\n", " [['612819836329411865644509177766215680',\n", " '843517362609097245279278883187720192',\n", " '851114962252709222552843081379479552'],\n", " ['847925751912674500468804749306626048',\n", " '639634733901388366288661852182282240',\n", " '667670451847854954465177838892875776']]]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X_in, out = MaxPooling2DInt(5, 5, 3, 2, 2, X_in)\n", "out" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "in_json = {\n", " \"in\": X_in,\n", " \"out\": out\n", "}" ] }, { "cell_type": "code", "execution_count":
11, "metadata": {}, "outputs": [], "source": [ "
import json" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "with open(\"maxPooling2D_input.json\", \"w\") as f:\n", " json.dump(in_json, f)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "inputs = Input(shape=(10,10,3))\n", "x = MaxPooling2D(pool_size=2, strides=3)(inputs)\n", "model = Model(inputs, x)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"model_1\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param "=================================================================\n", " input_2 (InputLayer) [(None, 10, 10, 3)] 0 \n", " \n", " max_pooling2d_1 (MaxPooling (None, 3, 3, 3) 0 \n", " 2D) \n", " \n", "=================================================================\n", "Total params: 0\n", "Trainable params: 0\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[[[0.9790171 , 0.49837833, 0.23951505],\n", " [0.85478487, 0.10183569, 0.57204256],\n", " [0.12906496, 0.12259599, 0.61308313],\n", " [0.68956844, 0.27468499, 0.73800473],\n", " [0.97031435, 0.65275678, 0.57039273],\n", " [0.48422669,
0.62184484, 0.12322611],\n", " [0.45518299, 0.70342415, 0.77375435],\n", " [0.1334539 , 0.78283045, 0.48137776],\n", " [0.97002355, 0.70346344, 0.04099013],\n", " [0.34556716, 0.30939804, 0.12870492]],\n", "\n", " [[0.55049916, 0.15188193, 0.514953 ],\n", " [0.07403779, 0.906408 , 0.20947497],\n", " [0.57003003, 0.93417836, 0.09306473],\n", " [0.17917856, 0.67291796, 0.4088607 ],\n", " [0.10408118, 0.55822855, 0.62854813],\n", " [0.20925919, 0.68269696, 0.60650138],\n", " [0.94999975, 0.12429107, 0.41003125],\n", " [0.16150869, 0.35470003, 0.54676562],\n", " [0.14792857, 0.78346031, 0.25734593],\n", " [0.89233997, 0.28742825, 0.13791151]],\n", "\n", " [[0.79274313, 0.99061523, 0.68711779],\n", " [0.57504418, 0.32618382, 0.16722838],\n", " [0.09678065, 0.3591776 , 0.62750915],\n", " [0.68795545, 0.01609884, 0.97099217],\n", " [0.23381142, 0.84909675, 0.88405792],\n", " [0.73191384, 0.98947014, 0.52221912],\n", " [0.89714287, 0.03510341, 0.20639419],\n", " [0.38323203, 0.16914071, 0.41209687],\n", " [0.13122496, 0.53340704, 0.60455243],\n", " [0.71565705, 0.67219914, 0.92696397]],\n", "\n", " [[0.55416618, 0.74973965, 0.59748271],\n", " [0.10440772, 0.32236564, 0.92791157],\n", " [0.41841302, 0.27220821, 0.61662229],\n", " [0.7338952 , 0.37152599, 0.31517472],\n", " [0.20252929, 0.67581558, 0.34286098],\n", " [0.01504774, 0.04681701, 0.14321044],\n", " [0.3653292 , 0.25028834, 0.33848712],\n", " [0.29191385, 0.34659568, 0.98273622],\n", " [0.50778695, 0.7199723 , 0.05608854],\n", " [0.72340647,
0.76685192, 0.37388969]],\n", "\n", " [[0.52331559, 0.62356855, 0.26878584],\n", " [0.15838795, 0.90184899, 0.23912789],\n", " [0.41272637, 0.7610872 , 0.12672697],\n", " [0.70626725, 0.98208145, 0.60164227],\n", " [0.35664872, 0.41128872, 0.09382977],\n", " [0.70544007, 0.82240552, 0.90325495],\n", " [0.72007321, 0.24536308, 0.60690892],\n", " [0.48655372, 0.46328671, 0.60648263],\n", " [0.18854088, 0.45044603, 0.69043293],\n", " [0.1217475 , 0.655353 , 0.87733639]],\n", "\n", " [[0.02353603, 0.18097275, 0.19114613],\n", " [0.72104431, 0.65310589, 0.48925075],\n", " [0.26145721, 0.95118427, 0.64482692],\n", " [0.08753618, 0.2596348 , 0.53771786],\n", " [0.07314132, 0.06774864, 0.34392025],\n", " [0.16282229, 0.95993633, 0.79667906],\n", " [0.74674627, 0.53217006, 0.65900082],\n", " [0.87522692, 0.13258819, 0.16230994],\n", " [0.44525752, 0.67365898, 0.51766928],\n", " [0.72182701, 0.43780393, 0.98069118]],\n", "\n", " [[0.25691084, 0.11661927, 0.67618617],\n", " [0.66069801, 0.9045992 , 0.86337172],\n", " [0.08042041, 0.78517436, 0.69269604],\n", " [0.44734739, 0.30140176, 0.18295808],\n", " [0.07556447, 0.4891693 , 0.20302939],\n", " [0.22243138, 0.65584446, 0.56134481],\n", " [0.91535994, 0.429726 , 0.89466843],\n", " [0.25180203, 0.12145168, 0.26456649],\n", " [0.56398398, 0.18346371, 0.034341 ],\n", " [0.37802503, 0.22614985, 0.85292929]],\n", "\n", " [[0.19171201, 0.46156136, 0.78027617],\n", " [0.1697258 , 0.36865057, 0.30921552],\n", " [0.63491691, 0.76223827, 0.91491496],\n", "
[0.68871028, 0.86998105, 0.79183476],\n", " [0.50452778, 0.27036477, 0.19829515],\n", " [0.82527008, 0.35258264, 0.42346427],\n", " [0.73552096, 0.76506646, 0.50324396],\n", " [0.08392757, 0.11886597, 0.31341576],\n", " [0.42816313, 0.8535268 , 0.59585608],\n", " [0.00429868, 0.66229572, 0.07715835]],\n", "\n", " [[0.95901268, 0.85618315, 0.47768876],\n", " [0.66614175, 0.08345771, 0.80790147],\n", " [0.29208239, 0.4360204 , 0.18332789],\n", " [0.28169483, 0.63096452, 0.96729756],\n", " [0.07859661, 0.92728092, 0.80810303],\n", " [0.97020859, 0.87780948, 0.83993202],\n", " [0.68006058, 0.68787335, 0.70198168],\n", " [0.31865081, 0.97290491, 0.13625889],\n", " [0.80537841, 0.03953296, 0.16870381],\n", " [0.90864186, 0.54762421, 0.71436361]],\n", "\n", " [[0.19054836, 0.34380661, 0.68153459],\n", " [0.16505021, 0.0412163 , 0.36928843],\n", " [0.38454084, 0.30131942, 0.29021317],\n", " [0.74076099, 0.97099106, 0.30053946],\n", " [0.62869618, 0.12455381, 0.62562719],\n", " [0.91303674, 0.39900546, 0.92873058],\n", " [0.7949276 , 0.00620029, 0.17023317],\n", " [0.40570501, 0.1780136 , 0.19150324],\n", " [0.56676977, 0.84413934, 0.73247166],\n", " [0.0028076 , 0.26181396, 0.70691029]]]])" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X = np.random.rand(1,10,10,3)\n", "X" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 21ms/step\n" ] }, { "data":
{ "text/plain": [ "array([[[[0.9790171 , 0.906408 , 0.5720426 ],\n", " [0.9703143 , 0.67291796, 0.73800474],\n", " [0.94999975, 0.7828305 , 0.77375436]],\n", "\n", " [[0.5541662 , 0.901849 , 0.9279116 ],\n", " [0.7338952 , 0.9820815 , 0.60164225],\n", " [0.7200732 , 0.46328673, 0.98273623]],\n", "\n", " [[0.660698 , 0.9045992 , 0.86337173],\n", " [0.6887103 , 0.86998105, 0.7918348 ],\n", " [0.9153599 , 0.76506644, 0.89466846]]]], dtype=float32)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = model.predict(X)\n", "y" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[['979017099491110018942067312821272576',\n", " '906408000806632452114797174150135808',\n", " '572042560577051270101001688850628608'],\n", " ['970314350513558277989324779994218496',\n", " '672917960272193945175567190387064832',\n", " '738004729474624730341896972922781696'],\n", " ['949999745668024165489517038806237184',\n", " '782830451141896167400921576545189888',\n", " '773754352982266439136539456512720896']],\n", " [['554166181126147404440246990770536448',\n", " '901848991352918850169033731149398016',\n", " '927911571088135929200009259356520448'],\n", " ['733895199634136636354978553303924736',\n", " '982081449688638090663868389740511232',\n", " '601642265832659125360941789945528320'],\n", " ['720073208604618054954869080641765376',\n", " '463286712794445136678401315
688153088',\n", " '982736221843810664156369288039497728']],\n", " [['660698008644203700473074429819092992',\n", " '904599195577579897660922571020828672',\n", " '863371715944324158495051960144625664'],\n", " ['688710284469165685404738243641999360',\n", " '869981053223066390571414093008207872',\n", " '791834758925232104719097862035603456'],\n", " ['915359938539886757509738228069957632',\n", " '765066456516048413755703502695301120',\n", " '894668431976368139307673421153828864']]]" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X_in, out = MaxPooling2DInt(10, 10, 3, 2, 3, X_in)\n", "out" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "in_json = {\n", " \"in\": X_in,\n", " \"out\": out\n", "}" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "with open(\"maxPooling2D_stride_input.json\", \"w\") as f:\n", " json.dump(in_json, f)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "sklearn", "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.16" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from tensorflow.keras.layers
import Input, MaxPooling2D\n", "from tensorflow.keras
import Model\n", "
import numpy as np" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "inputs = Input(shape=(5,5,3))\n", "x = MaxPooling2D(pool_size=2, padding='same')(inputs)\n", "model = Model(inputs, x)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"model\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param "=================================================================\n", " input_1 (InputLayer) [(None, 5, 5, 3)] 0 \n", " \n", " max_pooling2d (MaxPooling2D (None, 3, 3, 3) 0 \n", " ) \n", " \n", "=================================================================\n", "Total params: 0\n", "Trainable params: 0\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[[[0.9854169 , 0.80569586, 0.63268445],\n", " [0.96206047, 0.00886907, 0.67775967],\n", " [0.46792544, 0.81360698, 0.34777212],\n", " [0.90835439, 0.69174656, 0.98172619],\n", " [0.10715328, 0.91657229, 0.81624555]],\n", "\n", " [[0.57038264, 0.90280394, 0.77766336],\n", " [0.63409067, 0.82595812, 0.38151341],\n", " [0.79552045, 0.2163596 , 0.87461672],\n", " [0.74681147, 0.47584101, 0
.93002867],\n", " [0.11400012, 0.97409111, 0.87404365]],\n", "\n", " [[0.53957961, 0.50863284, 0.89012595],\n", " [0.27801669, 0.55281537, 0.50004972],\n", " [0.31374426, 0.41849849, 0.81763357],\n", " [0.68099263, 0.21715725, 0.60245081],\n", " [0.23044868, 0.89402184, 0.73802917]],\n", "\n", " [[0.65681518, 0.45431134, 0.11186951],\n", " [0.63232732, 0.09914006, 0.469778 ],\n", " [0.53980327, 0.00999922, 0.32385368],\n", " [0.51189833, 0.23540886, 0.48827071],\n", " [0.97347711, 0.16329774, 0.73404494]],\n", "\n", " [[0.02010803, 0.73200388, 0.75296659],\n", " [0.47080583, 0.89997758, 0.77754373],\n", " [0.45047643, 0.60846601, 0.22025449],\n", " [0.81318524, 0.86405236, 0.44136216],\n", " [0.53790431, 0.45931736, 0.00951743]]]])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X = np.random.rand(1,5,5,3)\n", "X" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 42ms/step\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2024-02-05 01:27:05.945781: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n" ] }, { "data": { "text/plain": [ "array([[[[0.9854169 , 0.90280396, 0.77766335],\n", " [0.9083544 , 0.813607 , 0.98172617],\n", " [0.11400012, 0.9740911 , 0.87404364]],\n", "\n", " [[0.6568152 , 0.5528154 , 0.89012593],\n", " [0.6809926 , 0.4184985 , 0.81763357],\n", " [0.9734771 , 0.89402187, 0.7380292 ]]
,\n", "\n", " [[0.47080582, 0.89997756, 0.7775437 ],\n", " [0.8131852 , 0.86405236, 0.44136214],\n", " [0.5379043 , 0.45931736, 0.00951743]]]], dtype=float32)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = model.predict(X)\n", "y" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(5)] for i in range(5)]" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "def MaxPooling2DInt(nRows, nCols, nChannels, poolSize, strides, input):\n", " out = [[[str(max(int(input[i*strides + x][j*strides + y][k]) for x in range(poolSize) for y in range(poolSize))) for k in range(nChannels)] for j in range((nCols - poolSize) " return out" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "def MaxPooling2DsameInt(nRows, nCols, nChannels, poolSize, strides, input):\n", " if nRows % strides == 0:\n", " rowPadding = max(poolSize - strides, 0)\n", " else:\n", " rowPadding = max(poolSize - nRows % strides, 0)\n", " if nCols % strides == 0:\n", " colPadding = max(poolSize - strides, 0)\n", " else:\n", " colPadding = max(poolSize - nCols % strides, 0)\n", " \n", " _input = [[[0 for _ in range(nChannels)] for _ in range(nCols + colPadding)] for _ in range(nRows + rowPadding)]\n", "\n", " for i in range(nRows):\n", " for j in range(nCols):\n", " for k in range(nChannels):\n", " _input[i+rowPadding " \n", " out = MaxPooling2DInt(nRows + rowPadding, nCols + colPadding, nChannels, poolSize, strides, _input)\n", " return out" ] }, { "cell_type": "code",
"execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[['985416895178787714183661703755988992',\n", " '902803940435826284139749932730941440',\n", " '777663362123877860598598645145665536'],\n", " ['908354388868282470618698257109352448',\n", " '813606982115283460844798537969434624',\n", " '981726193592448973649175667344932864'],\n", " ['114000116831430861403008392105033728',\n", " '974091109200621567612816335791194112',\n", " '874043654050301690820171495435665408']],\n", " [['656815180323522869339469446928924672',\n", " '552815374291668108366329210074038272',\n", " '890125946940297760199841005954924544'],\n", " ['680992631793690390926240128859897856',\n", " '418498494396639822766365224919367680',\n", " '817633569064628434285947918592507904'],\n", " ['973477114549060379932212627888930816',\n", " '894021844181003495121759207996522496',\n", " '738029169437394307130485433159385088']],\n", " [['470805829710577633964522992960536576',\n", " '899977578211573860664606514781093888',\n", " '777543729617406477245147183797239808'],\n", " ['813185240376988213714402965620523008',\n", " '864052363876363850452980196205133824',\n", " '441362157036501413461183215236546560'],\n", " ['537904308558723633624141672348647424',\n", " '459317359421049476909261905824055296',\n", " '9517425402804758462154346481057792']]]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "out = MaxPooling2DsameInt(5, 5, 3, 2, 2, X_in)\n", "out" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "in_json = {\n", " \"in\": X_in,\n", " \"out\": out\n", "}" ] }, { "cell_type": "code", "execution_count":
11, "metadata": {}, "outputs": [], "source": [ "
import json" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "with open(\"maxPooling2Dsame_input.json\", \"w\") as f:\n", " json.dump(in_json, f)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "inputs = Input(shape=(10,10,3))\n", "x = MaxPooling2D(pool_size=2, strides=3, padding='same')(inputs)\n", "model = Model(inputs, x)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"model_1\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param "=================================================================\n", " input_2 (InputLayer) [(None, 10, 10, 3)] 0 \n", " \n", " max_pooling2d_1 (MaxPooling (None, 4, 4, 3) 0 \n", " 2D) \n", " \n", "=================================================================\n", "Total params: 0\n", "Trainable params: 0\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[[[1.81060846e-01, 8.73335066e-01, 4.66591631e-01],\n", " [4.19512826e-01, 5.04687534e-01, 5.55108518e-01],\n", " [8.89727395e-01, 3.04715421e-01, 3.96868333e-01],\n", " [3.19583099e-01, 7.59947198e-04, 8.95376898e-01],\n", " [1.8
6082695e-01, 5.89361183e-01, 2.29939007e-01],\n", " [3.77869457e-01, 5.93831349e-01, 6.17898741e-01],\n", " [2.08890055e-01, 4.52999632e-02, 4.81015031e-02],\n", " [9.68292068e-01, 4.24571806e-01, 4.18124731e-02],\n", " [3.30703359e-02, 6.13358807e-01, 9.62525235e-01],\n", " [8.80909151e-01, 3.16377883e-02, 4.07229564e-01]],\n", "\n", " [[7.22047037e-01, 2.87769873e-01, 6.33057960e-01],\n", " [5.87593115e-01, 9.95928671e-01, 9.47646805e-02],\n", " [6.73764008e-01, 4.41940517e-01, 2.05872675e-01],\n", " [2.74105248e-01, 3.41288944e-01, 7.03928155e-01],\n", " [2.53407876e-01, 9.54086619e-01, 6.95949832e-01],\n", " [7.72974380e-01, 6.94646688e-01, 2.39040667e-01],\n", " [7.61119704e-01, 8.41368944e-01, 9.12971104e-01],\n", " [3.19331761e-01, 2.36474093e-01, 3.11432211e-01],\n", " [6.18384476e-01, 2.23794997e-01, 7.33884991e-01],\n", " [1.00735392e-01, 7.42390580e-01, 7.43563278e-01]],\n", "\n", " [[1.82788443e-01, 9.69266407e-01, 6.79896409e-02],\n", " [5.47375743e-01, 7.00178164e-01, 1.62010347e-02],\n", " [2.70368172e-01, 9.53685968e-01, 4.62933777e-01],\n", " [4.80574859e-01, 1.55085614e-01, 2.38047469e-01],\n", " [4.86919140e-01, 1.94033355e-02, 1.80402947e-01],\n", " [3.96449294e-01, 4.95605585e-01, 2.26605072e-01],\n", " [1.74141020e-02, 3.46487475e-03, 8.98099350e-01],\n", " [7.85190855e-01, 3.05525061e-01, 2.04565391e-01],\n", " [8.23700964e-01, 2.97490709e-01, 6.50482927e-02],\n", " [1.26448774e-01, 8.10615035e-01, 5.09045959e-01]],\n", "\n", " [[7.13680159e-01, 8.45319480e-01, 9.11203285e-01],\n", " [8.27233800e-01, 4.12657299e-01, 6.97025851e-01],\n", " [2.81018305e-01, 6.489
55744e-01, 8.91153606e-01],\n", " [6.29371477e-01, 7.75929101e-01, 7.79093686e-01],\n", " [1.23716197e-01, 3.10122093e-01, 8.37055316e-01],\n", " [1.68089475e-01, 9.54284278e-01, 3.18407200e-01],\n", " [3.62606007e-01, 7.78830849e-01, 3.99089020e-01],\n", " [8.51653764e-02, 5.34511941e-01, 6.04920400e-01],\n", " [2.71115350e-01, 4.36692189e-01, 6.96241628e-01],\n", " [8.65780466e-01, 3.22369175e-01, 7.43159548e-01]],\n", "\n", " [[9.28690706e-02, 3.94089568e-01, 5.61323421e-01],\n", " [5.90368083e-01, 9.74901900e-01, 9.47030261e-01],\n", " [6.30178577e-01, 5.13484751e-01, 1.18185924e-01],\n", " [4.38458544e-01, 5.63764554e-01, 7.66318218e-01],\n", " [7.18648243e-01, 1.70367043e-01, 7.70642982e-01],\n", " [2.22980409e-01, 3.74329609e-01, 4.80409175e-01],\n", " [9.45617766e-01, 8.81617847e-01, 1.19580346e-01],\n", " [9.15676461e-01, 9.70518691e-01, 2.43214092e-01],\n", " [2.41451379e-01, 4.88548632e-01, 3.70190637e-01],\n", " [4.59905504e-01, 3.80889550e-01, 3.85698952e-01]],\n", "\n", " [[2.72104416e-01, 7.98516947e-01, 2.72194053e-01],\n", " [9.48709871e-01, 2.66222380e-01, 9.42522429e-01],\n", " [7.33569990e-01, 3.47061477e-01, 5.33050356e-01],\n", " [6.11738759e-01, 8.68186611e-02, 3.75463635e-01],\n", " [2.14948078e-01, 3.99863394e-01, 1.90922352e-01],\n", " [5.10853285e-01, 8.50874635e-01, 3.81366847e-01],\n", " [8.39025985e-01, 6.98107126e-01, 8.44114497e-01],\n", " [6.99026648e-01, 6.91391860e-01, 5.95508900e-01],\n", " [3.75264962e-01, 2.19625912e-02, 9.65963233e-01],\n", " [8.73625070e-01, 1.70130110e-02, 4.28592791e-01]],\n", "\n", " [[5.30376524e-01, 5.19931919e-01, 8.79621
802e-01],\n", " [5.93691399e-01, 9.43767391e-01, 3.85923387e-01],\n", " [2.66910663e-02, 9.36911794e-01, 1.02611787e-01],\n", " [3.59377042e-01, 2.67568222e-01, 5.35446422e-01],\n", " [5.51850227e-01, 6.35787754e-01, 1.98619411e-01],\n", " [8.49409850e-01, 6.72271595e-01, 2.39559395e-01],\n", " [1.73809713e-02, 6.90213328e-01, 4.68996474e-01],\n", " [2.98860826e-01, 9.70887693e-02, 7.59385182e-01],\n", " [2.57726817e-01, 9.57823991e-01, 7.18212290e-01],\n", " [7.01041664e-01, 7.78681302e-01, 2.83077120e-01]],\n", "\n", " [[7.26341251e-01, 9.88746010e-02, 8.11023617e-01],\n", " [5.17637504e-01, 1.22369589e-01, 6.26059218e-01],\n", " [8.89381042e-01, 4.69513890e-01, 4.41358856e-01],\n", " [1.31543858e-01, 2.52923839e-02, 4.59211802e-01],\n", " [2.97316029e-01, 3.74157507e-01, 1.46629093e-01],\n", " [5.42787121e-01, 4.83436833e-01, 6.48266145e-01],\n", " [5.87451856e-01, 6.62348938e-01, 9.09155419e-01],\n", " [4.19004871e-01, 1.82945864e-02, 6.63249102e-01],\n", " [2.32421673e-01, 6.30460531e-01, 6.90273718e-02],\n", " [1.00823603e-01, 6.38197200e-01, 1.54316174e-01]],\n", "\n", " [[3.95104675e-01, 9.54576105e-01, 7.18833793e-01],\n", " [6.55325673e-01, 2.09750597e-01, 5.08179296e-01],\n", " [8.35434924e-01, 3.11732329e-01, 2.53760179e-01],\n", " [6.01300571e-01, 1.74387890e-01, 1.28901152e-01],\n", " [3.60114137e-01, 6.03481824e-01, 6.42517616e-01],\n", " [4.74822395e-01, 4.06953697e-02, 8.06656676e-01],\n", " [2.35227783e-01, 1.86636675e-01, 2.92355800e-01],\n", " [7.57334531e-01, 3.02550198e-01, 8.78392401e-01],\n", " [9.89429375e-01, 9.17356225e-01, 9.94972892e-01],\n", " [
3.38833764e-01, 2.39923972e-01, 2.49753676e-02]],\n", "\n", " [[5.34504729e-02, 2.60437560e-01, 4.75257720e-01],\n", " [5.10602046e-01, 7.24407672e-01, 1.27708925e-01],\n", " [8.89866378e-01, 7.68391514e-01, 8.10330840e-01],\n", " [9.04964699e-01, 9.07169014e-01, 3.30947299e-01],\n", " [3.25628891e-01, 3.62460672e-01, 6.09180261e-01],\n", " [3.97278800e-01, 2.87846815e-01, 9.51001737e-01],\n", " [3.94260450e-01, 3.00806280e-01, 8.51360452e-01],\n", " [3.62097670e-01, 2.24539340e-01, 7.61618704e-01],\n", " [2.50380406e-01, 7.56360963e-01, 1.16230049e-01],\n", " [9.01240322e-01, 3.73212987e-01, 7.36122529e-01]]]])" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X = np.random.rand(1,10,10,3)\n", "X" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 30ms/step\n" ] }, { "data": { "text/plain": [ "array([[[[0.72204703, 0.99592865, 0.63305795],\n", " [0.3195831 , 0.9540866 , 0.8953769 ],\n", " [0.96829206, 0.841369 , 0.9129711 ],\n", " [0.88090914, 0.7423906 , 0.7435633 ]],\n", "\n", " [[0.8272338 , 0.9749019 , 0.94703025],\n", " [0.71864825, 0.7759291 , 0.8370553 ],\n", " [0.9456178 , 0.9705187 , 0.6049204 ],\n", " [0.8657805 , 0.38088953, 0.74315953]],\n", "\n", " [[0.72634125, 0.94376737, 0.8796218 ],\n", " [0.5518502 , 0.6357877 , 0.5354464 ],\n", " [0.5874519 , 0.6902133 , 0.9091554 ],\n", " [0.70104164, 0.7786813 , 0.28307712]],\n", "\n", " [[0.51060206, 0.7244077 , 0.47525772]
,\n", " [0.9049647 , 0.90716904, 0.6091803 ],\n", " [0.39426044, 0.30080628, 0.85136044],\n", " [0.90124035, 0.373213 , 0.73612255]]]], dtype=float32)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = model.predict(X)\n", "y" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "X_in = [[[int(X[0][i][j][k]*1e36) for k in range(3)] for j in range(10)] for i in range(10)]" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[['722047037048510692294577429613117440',\n", " '995928671466629356695108803213918208',\n", " '633057959701190742109452742097371136'],\n", " ['319583098696415993297833594590330880',\n", " '954086618948581700566160227891675136',\n", " '895376897621437771937017335681908736'],\n", " ['968292067860118608616536728156504064',\n", " '841368944375512546814487235963912192',\n", " '912971104374087013640201200717529088'],\n", " ['880909150990983977881328708709515264',\n", " '742390579543848987849194909946871808',\n", " '743563277676321729157199064014520320']],\n", " [['827233800468269198331599375468331008',\n", " '974901899794306633179826070214410240',\n", " '947030261209948995604238219295588352'],\n", " ['718648242610498931670595372570378240',\n", " '775929100688812511565570103251566592',\n", " '837055315861977089490188905893330944'],\n", " ['945617766167062485510007332488085504',\n", " '970518691217475177799962810208223232',\n", " '604920400036749440823474048758448128'],\n", " ['865780466166194901147341462043623424',\n", " '380889549714929988856634904844173312',\n", " '743159547886228828110355377787240448']],\
n", " [['726341250795347218817727679288049664',\n", " '943767390679553173919884888860786688',\n", " '879621802069332614144323070292131840'],\n", " ['551850226842807715717985301323317248',\n", " '635787754066812906470475510293987328',\n", " '535446422069610157460354392595103744'],\n", " ['587451855996849487170757966572814336',\n", " '690213328307762114218988812757893120',\n", " '909155419360394098803395006243536896'],\n", " ['701041664244132545037467114551640064',\n", " '778681301680931345113753214299144192',\n", " '283077119909484707357592139667079168']],\n", " [['510602045587970767184337129422454784',\n", " '724407671943644015539146665914007552',\n", " '475257720371555822213696431964815360'],\n", " ['904964699224751401721193296243458048',\n", " '907169014433129231084536890038157312',\n", " '609180260647294075284256963443032064'],\n", " ['394260450257245198773068562662686720',\n", " '300806280328724832256760381278519296',\n", " '851360451534335061119480218741899264'],\n", " ['901240322382283207026350889182953472',\n", " '373212986501062202469532290256994304',\n", " '736122528767077629789884872958935040']]]" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "out = MaxPooling2DsameInt(10, 10, 3, 2, 3, X_in)\n", "out" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "in_json = {\n", " \"in\": X_in,\n", " \"out\": out\n", "}" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "with open(\"maxPooling2Dsame_stride_input.json\", \"w\") as f:\n", " json.dump(in_json, f)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [],
"source": [] } ], "metadata": { "kernelspec": { "display_name": "sklearn", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "p = 21888242871839275222246405745257275088548364400416034343698204186575808495617" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from tensorflow.keras.layers
import Input, Conv2D, AveragePooling2D, Flatten, Softmax, Dense, Lambda, BatchNormalization, ReLU\n", "from tensorflow.keras
import Model\n", "from tensorflow.keras.datasets
import mnist\n", "from tensorflow.keras.utils
import to_categorical\n", "from tensorflow.keras.optimizers.legacy
import SGD\n", "
import numpy as np\n", "
import matplotlib.pyplot as plt\n", "
import tensorflow as tf" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "(X_train, y_train), (X_test, y_test) = mnist.load_data()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ " "temp = []\n", "for i in range(len(y_train)):\n", " temp.append(to_categorical(y_train[i], num_classes=10))\n", "y_train = np.array(temp)\n", " "temp = []\n", "for i in range(len(y_test)): \n", " temp.append(to_categorical(y_test[i], num_classes=10))\n", "y_test = np.array(temp)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ " "X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)\n", "X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)\n", "\n", " "X_train = X_train.astype('float32')\n", "X_test = X_test.astype('float32')\n", "X_train /= 255.0\n", "X_test /= 255.0" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "inputs = Input(shape=(28,28,1))\n", "out = Conv2D(4, 3, use_bias=True)(inputs)\n", "out = BatchNormalization()(out)\n", "out = ReLU()(out)\n", "out = AveragePooling2D()(out)\n", "out = Conv2D(8, 3, use_bias=True)(out)\n", "out = BatchNormalization()(out)\n", "out = ReLU()(out)\n", "out = AveragePooling2D()(out)\n", "out = Flatten()(out)\n", "out = Dense(10, activation=None)(out)\n", "out = Softmax()(out)\n", "model = Model(inputs, out)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"model\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param "======================================
===========================\n", " input_1 (InputLayer) [(None, 28, 28, 1)] 0 \n", " \n", " conv2d (Conv2D) (None, 26, 26, 4) 40 \n", " \n", " batch_normalization (BatchN (None, 26, 26, 4) 16 \n", " ormalization) \n", " \n", " re_lu (ReLU) (None, 26, 26, 4) 0 \n", " \n", " average_pooling2d (AverageP (None, 13, 13, 4) 0 \n", " ooling2D) \n", " \n", " conv2d_1 (Conv2D) (None, 11, 11, 8) 296 \n", " \n", " batch_normalization_1 (Batc (None, 11, 11, 8) 32 \n", " hNormalization) \n", " \n", " re_lu_1 (ReLU) (None, 11, 11, 8) 0 \n", " \n", " average_pooling2d_1 (Averag (None, 5, 5, 8) 0 \n", " ePooling2D) \n", " \n", " flatten (Flatten) (None, 200) 0 \n", " \n", " dense (Dense) (None, 10) 2010 \n", " \n", " softma
x (Softmax) (None, 10) 0 \n", " \n", "=================================================================\n", "Total params: 2,394\n", "Trainable params: 2,370\n", "Non-trainable params: 24\n", "_________________________________________________________________\n" ] } ], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "model.compile(\n", " loss='categorical_crossentropy',\n", " optimizer=SGD(learning_rate=0.01, momentum=0.9),\n", " metrics=['acc']\n", " )" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Epoch 1/15\n", " 1/1875 [..............................] - ETA: 5:16 - loss: 2.6515 - acc: 0.0625" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2023-10-24 02:23:16.557845: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "1875/1875 [==============================] - 8s 4ms/step - loss: 0.1896 - acc: 0.9434 - val_loss: 0.0808 - val_acc: 0.9753\n", "Epoch 2/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0787 - acc: 0.9761 - val_loss: 0.0602 - val_acc: 0.9808\n", "Epoch 3/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0650 - acc: 0.9803 - val_loss: 0.0546 - val_acc: 0.9831\n", "Epoch 4/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0592 - acc: 0.9816 - val_loss: 0.0613 - val_acc: 0.9812\n", "Epoch 5/15\n", "1875/1875 [==============================] - 7s 4ms/step - loss: 0.0536 - acc: 0.9837
- val_loss: 0.0594 - val_acc: 0.9808\n", "Epoch 6/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0497 - acc: 0.9847 - val_loss: 0.0618 - val_acc: 0.9794\n", "Epoch 7/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0470 - acc: 0.9855 - val_loss: 0.0824 - val_acc: 0.9748\n", "Epoch 8/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0451 - acc: 0.9863 - val_loss: 0.0410 - val_acc: 0.9843\n", "Epoch 9/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0433 - acc: 0.9865 - val_loss: 0.0561 - val_acc: 0.9822\n", "Epoch 10/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0425 - acc: 0.9871 - val_loss: 0.0455 - val_acc: 0.9847\n", "Epoch 11/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0397 - acc: 0.9875 - val_loss: 0.0524 - val_acc: 0.9825\n", "Epoch 12/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0391 - acc: 0.9879 - val_loss: 0.0382 - val_acc: 0.9875\n", "Epoch 13/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0381 - acc: 0.9879 - val_loss: 0.0371 - val_acc: 0.9868\n", "Epoch 14/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0360 - acc: 0.9887 - val_loss: 0.0371 - val_acc: 0.9870\n", "Epoch 15/15\n", "1875/1875 [==============================] - 8s 4ms/step - loss: 0.0354 - acc: 0.9887 - val_loss: 0.0378 - val_acc: 0.9874\n" ] }, { "data": { "text/plain": [ "<keras.callbacks.History at 0x143103e80>" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_test, y_test))" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "da
ta": { "text/plain": [ "((28, 28, 1), 0.0, 1.0)" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X = X_test[0]\n", "X.shape, X.min(), X.max()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 45ms/step\n" ] }, { "data": { "text/plain": [ "7" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.predict(X.reshape(1,28,28,1)).argmax()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "def Conv2DInt(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n", " Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n", " Weights = [[[[str(weights[i][j][k][l] % p) for l in range(nFilters)] for k in range(nChannels)] for j in range(kernelSize)] for i in range(kernelSize)]\n", " Bias = [str(bias[i] % p) for i in range(nFilters)]\n", " out = [[[0 for _ in range(nFilters)] for _ in range((nCols - kernelSize) " remainder = [[[None for _ in range(nFilters)] for _ in range((nCols - kernelSize) " for i in range((nRows - kernelSize) " for j in range((nCols - kernelSize) " for m in range(nFilters):\n", " for k in range(nChannels):\n", " for x in range(kernelSize):\n", " for y in range(kernelSize):\n", " out[i][j][m] += input[i*strides+x][j*strides+y][k] * weights[x][y][k][m]\n", " out[i][j][m] += bias[m]\n", " remainder[i][j][m] = str(out[i][j][m] % n)\n", " out[i][j][m] = s
tr(out[i][j][m] " return Input, Weights, Bias, out, remainder" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "X_in = [[[int(X[i][j][0]*1e18)] for j in range(28)] for i in range(28)]\n", "conv2d_1_weights = [[[[int(model.layers[1].weights[0][i][j][k][l]*1e18) for l in range(4)] for k in range(1)] for j in range(3)] for i in range(3)]\n", "conv2d_1_bias = [int(model.layers[1].weights[1][i]*1e36) for i in range(4)]" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['21888242871839275222246405745257275088548364400416034343698204178650554445275',\n", " '21888242871839275222246405745257275088548364400416034343698203817637026120037',\n", " '21888242871839275222246405745257275088548364400416034343698204118313744391231',\n", " '48458611567652']" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X_in, conv2d_1_weights, conv2d_1_bias, conv2d_1_out, conv2d_1_remainder = Conv2DInt(28, 28, 1, 4, 3, 1, 10**18, X_in, conv2d_1_weights, conv2d_1_bias)\n", "conv2d_1_out[0][0]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 18ms/step\n" ] }, { "data": { "text/plain": [ "array([-7.9252541e-06, -3.6893881e-04, -6.8262067e-05, 4.8458613e-05],\n", " dtype=float32)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "conv2d_model = Model(inputs, model.layers[1].output)\n", "conv2d_model.predict(X.reshape(1,28,28,1))[0][0][0]" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [
"gamma = model.layers[2].weights[0].numpy()\n", "beta = model.layers[2].weights[1].numpy()\n", "moving_mean = model.layers[2].weights[2].numpy()\n", "moving_var = model.layers[2].weights[3].numpy()\n", "epsilon = model.layers[2].epsilon" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(array([2.841136 , 2.7350745, 2.0774858, 1.246628 ], dtype=float32),\n", " array([ 0.9730277 , -0.0507403 , -0.07507665, -0.5589396 ], dtype=float32))" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a1 = gamma/(moving_var+epsilon)**.5\n", "b1 = beta-gamma*moving_mean/(moving_var+epsilon)**.5\n", "a1, b1" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "def BatchNormalizationInt(nRows, nCols, nChannels, n, X_in, a_in, b_in):\n", " X = [[[str(X_in[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n", " A = [str(a_in[k] % p) for k in range(nChannels)]\n", " B = [str(b_in[k] % p) for k in range(nChannels)]\n", " out = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n", " remainder = [[[None for _ in range(nChannels)] for _ in range(nCols)] for _ in range(nRows)]\n", " for i in range(nRows):\n", " for j in range(nCols):\n", " for k in range(nChannels):\n", " out[i][j][k] = (X_in[i][j][k]*a_in[k] + b_in[k])\n", " remainder[i][j][k] = str(out[i][j][k] % n)\n", " out[i][j][k] = str(out[i][j][k] " return X, A, B, out, remainder" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "bn_1_in = [[[int(conv2d_1_out[i][j][k]) if int(conv2d_1_out[i][j][k]) < p "bn_1_a = [int(a1[i]*1e18) for i
in range(4)]\n", "bn_1_b = [int(b1[i]*1e36) for i in range(4)]" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['973005189421817592',\n", " '21888242871839275222246405745257275088548364400416034343698152437199136300055',\n", " '21888242871839275222246405745257275088548364400416034343698128968107786241045',\n", " '21888242871839275222246405745257275088548364400416034343697645307409523760974']" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_, bn_1_a, bn_1_b, bn_1_out, bn_1_remainder = BatchNormalizationInt(26, 26, 4, 10**18, bn_1_in, bn_1_a, bn_1_b)\n", "bn_1_out[0][0]" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 22ms/step\n" ] }, { "data": { "text/plain": [ "array([ 0.97300524, -0.05174941, -0.07521845, -0.55887914], dtype=float32)" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bn_1_model = Model(inputs, model.layers[2].output)\n", "bn_1_model.predict(X.reshape(1,28,28,1))[0][0][0]" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "relu_1_in = [[[int(bn_1_out[i][j][k]) for k in range(4)] for j in range(26)] for i in range(26)]\n", "relu_1_out = [[[str(relu_1_in[i][j][k]) if relu_1_in[i][j][k] < p ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "avg2d_1_in = [[[int(relu_1_out[i][j][k]) for k in range(4)] for j in range(26)] for i in range(26)]" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [
"def AveragePooling2DInt (nRows, nCols, nChannels, poolSize, strides, input):\n", " Input = [[[str(input[i][j][k] % p) for k in range(nChannels)] for j in range(nCols)] for i in range(nRows)]\n", " out = [[[0 for _ in range(nChannels)] for _ in range((nCols-poolSize) " remainder = [[[None for _ in range(nChannels)] for _ in range((nCols-poolSize) " for i in range((nRows-poolSize) " for j in range((nCols-poolSize) " for k in range(nChannels):\n", " for x in range(poolSize):\n", " for y in range(poolSize):\n", " out[i][j][k] += input[i*strides+x][j*strides+y][k]\n", " remainder[i][j][k] = str(out[i][j][k] % poolSize**2 % p)\n", " out[i][j][k] = str(out[i][j][k] " return Input, out, remainder" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['1312195747641412224', '17351024717876988', '381448215010339593', '0']" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_, avg2d_1_out, avg2d_1_remainder = AveragePooling2DInt(26, 26, 4, 2, 2, avg2d_1_in)\n", "avg2d_1_out[5][6]" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 28ms/step\n" ] }, { "data": { "text/plain": [ "array([1.3121958 , 0.01735102, 0.38144833, 0. ], dtype=float32)" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "avg2d_1_model = Model(inputs, model.layers[4].output)\n", "avg2d_1_model.predict(X.reshape(1,28,28,1))[0][5][6]" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {},
"outputs": [], "source": [ "conv2d_2_in = [[[int(avg2d_1_out[i][j][k]) for k in range(4)] for j in range(13)] for i in range(13)]\n", "conv2d_2_weights = [[[[int(model.layers[5].weights[0][i][j][k][l]*1e18) for l in range(8)] for k in range(4)] for j in range(3)] for i in range(3)]\n", "conv2d_2_bias = [int(model.layers[5].weights[1][i]*1e36) for i in range(8)]" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['151443532606342120',\n", " '21888242871839275222246405745257275088548364400416034343695445103896159586204',\n", " '1368543458414900467',\n", " '21888242871839275222246405745257275088548364400416034343697889320797389307844',\n", " '21888242871839275222246405745257275088548364400416034343696909822999783625702',\n", " '3064925807006993607',\n", " '273553711551724155',\n", " '21888242871839275222246405745257275088548364400416034343697690313879935243528']" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_, conv2d_2_weights, conv2d_2_bias, conv2d_2_out, conv2d_2_remainder = Conv2DInt(13, 13, 4, 8, 3, 1, 10**18, conv2d_2_in, conv2d_2_weights, conv2d_2_bias)\n", "conv2d_2_out[0][0]" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x147387d30> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unne
cessary retracing. For (3), please refer to https: "1/1 [==============================] - 0s 27ms/step\n" ] }, { "data": { "text/plain": [ "array([ 0.15144362, -2.7590828 , 1.3685436 , -0.3148657 , -1.2943636 ,\n", " 3.064926 , 0.27355385, -0.5138727 ], dtype=float32)" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "conv2d_2_model = Model(inputs, model.layers[5].output)\n", "conv2d_2_model.predict(X.reshape(1,28,28,1))[0][0][0]" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "gamma = model.layers[6].weights[0].numpy()\n", "beta = model.layers[6].weights[1].numpy()\n", "moving_mean = model.layers[6].weights[2].numpy()\n", "moving_var = model.layers[6].weights[3].numpy()\n", "epsilon = model.layers[6].epsilon" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(array([1.4172864, 1.0896717, 1.2455306, 1.9744203, 1.5216775, 1.6048892,\n", " 1.5560555, 1.5188278], dtype=float32),\n", " array([ 0.9693597 , 2.5460322 , -2.3216164 , 1.1771976 , 1.7650728 ,\n", " -5.5845942 , -0.36191303, 0.58835894], dtype=float32))" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a2 = gamma/(moving_var+epsilon)**.5\n", "b2 = beta-gamma*moving_mean/(moving_var+epsilon)**.5\n", "a2, b2" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "bn_2_in = [[[int(conv2d_2_out[i][j][k]) if int(conv2d_2_out[i][j][k]) < p "bn_2_a = [int(a2[i]*1e18) for i in range(8)]\n", "bn_2_b = [int(b2[i]*1e36) for i in range(8)]" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [
{ "data": { "text/plain": [ "['1183998554440588778',\n", " '21888242871839275222246405745257275088548364400416034343697743724366639529790',\n", " '21888242871839275222246405745257275088548364400416034343697587132926760373824',\n", " '555520188028190246',\n", " '21888242871839275222246405745257275088548364400416034343697999655475625376512',\n", " '21888242871839275222246405745257275088548364400416034343697538458512894177905',\n", " '63751744556936369',\n", " '21888242871839275222246405745257275088548364400416034343698012061380413810399']" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_, bn_2_a, bn_2_b, bn_2_out, bn_2_remainder = BatchNormalizationInt(11, 11, 8, 10**18, bn_2_in, bn_2_a, bn_2_b)\n", "bn_2_out[0][0]" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "WARNING:tensorflow:6 out of the last 6 calls to <function Model.make_predict_function.<locals>.predict_function at 0x1475103a0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https: "1/1 [==============================] - 0s 32ms/step\n" ] }, { "data": { "text/plain": [ "array([ 1.1839986 , -0.46046233, -0.61705345, 0.5555204 , -0.20453101,\n", " -0.66572803, 0.06375193, -0.1921252 ], dtype=float32)" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bn_2_model = Mode
l(inputs, model.layers[6].output)\n", "bn_2_model.predict(X.reshape(1,28,28,1))[0][0][0]" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['1183998554440588778',\n", " 0,\n", " 0,\n", " '555520188028190246',\n", " 0,\n", " 0,\n", " '63751744556936369',\n", " 0]" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "relu_2_in = [[[int(bn_2_out[i][j][k]) for k in range(8)] for j in range(11)] for i in range(11)]\n", "relu_2_out = [[[str(relu_2_in[i][j][k]) if relu_2_in[i][j][k] < p "relu_2_out[0][0]" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 30ms/step\n" ] }, { "data": { "text/plain": [ "array([1.1839986 , 0. , 0. , 0.5555204 , 0. ,\n", " 0. , 0.06375193, 0. ], dtype=float32)" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "relu_2_model = Model(inputs, model.layers[7].output)\n", "relu_2_model.predict(X.reshape(1,28,28,1))[0][0][0]" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "avg2d_2_in = [[[int(relu_2_out[i][j][k]) if int(relu_2_out[i][j][k]) < p ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['0',\n", " '3041275199357812815',\n", " '880404200542187368',\n", " '751626574290071696',\n", " '4631629684299696339',\n", " '0',\n", " '0',\n", " '141002623674408652']" ] }, "execution_count": 38,
"metadata": {}, "output_type": "execute_result" } ], "source": [ "_, avg2d_2_out, avg2d_2_remainder = AveragePooling2DInt(11, 11, 8, 2, 2, avg2d_2_in)\n", "avg2d_2_out[3][3]" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 30ms/step\n" ] }, { "data": { "text/plain": [ "array([0. , 3.0412755 , 0.88040376, 0.7516271 , 4.6316295 ,\n", " 0. , 0. , 0.14100271], dtype=float32)" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "avg2d_2_model = Model(inputs, model.layers[8].output)\n", "avg2d_2_model.predict(X.reshape(1,28,28,1))[0][3][3]" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['240465720017978049',\n", " '312962931075997403',\n", " '16422062895818568',\n", " '0',\n", " '0',\n", " '1115397662044723147',\n", " '3743826354975568930',\n", " '1282135426254877774',\n", " '2558492900397241085',\n", " '0',\n", " '69224497325539673',\n", " '0',\n", " '60798814494206494',\n", " '2302583886918782205',\n", " '379552091654971946',\n", " '0',\n", " '1609754191355983350',\n", " '0',\n", " '27599924897036794',\n", " '30247813336316648']" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "flatten_out = [avg2d_2_out[i][j][k] for i in range(5) for j in range(5) for k in range(8)]\n", "flatten_out[100:120]" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "te
xt": [ "1/1 [==============================] - 0s 32ms/step\n" ] }, { "data": { "text/plain": [ "array([0.24046564, 0.312963 , 0.0164221 , 0. , 0. ,\n", " 1.1153977 , 3.7438262 , 1.2821352 , 2.5584927 , 0. ,\n", " 0.0692246 , 0. , 0.06079884, 2.3025842 , 0.37955213,\n", " 0. , 1.6097541 , 0. , 0.02759986, 0.03024786],\n", " dtype=float32)" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "flatten_model = Model(inputs, model.layers[9].output)\n", "flatten_model.predict(X.reshape(1,28,28,1))[0][100:120]" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "dense_in = [int(flatten_out[i]) if int(flatten_out[i]) < p "dense_weights = [[int(model.layers[10].weights[0][i][j]*1e18) for j in range(10)] for i in range(200)]\n", "dense_bias = [int(model.layers[10].weights[1][i]*1e36) for i in range(10)]" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "def DenseInt(nInputs, nOutputs, n, input, weights, bias):\n", " Input = [str(input[i] % p) for i in range(nInputs)]\n", " Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\n", " Bias = [str(bias[i] % p) for i in range(nOutputs)]\n", " out = [0 for _ in range(nOutputs)]\n", " remainder = [None for _ in range(nOutputs)]\n", " for j in range(nOutputs):\n", " for i in range(nInputs):\n", " out[j] += input[i] * weights[i][j]\n", " out[j] += bias[j]\n", " remainder[j] = str(out[j] % n)\n", " out[j] = str(out[j] " return Input, Weights, Bias, out, remainder" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": {
"text/plain": [ "['21888242871839275222246405745257275088548364400416034343696001558406187208579',\n", " '21888242871839275222246405745257275088548364400416034343694494011253998843463',\n", " '2502586410316628302',\n", " '7723360444146681933',\n", " '21888242871839275222246405745257275088548364400416034343688179933383346961393',\n", " '21888242871839275222246405745257275088548364400416034343697101907583287035462',\n", " '21888242871839275222246405745257275088548364400416034343680804147065276585857',\n", " '21047995401855287971',\n", " '21888242871839275222246405745257275088548364400416034343695951614145619839501',\n", " '4230622081176419220']" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_, dense_weights, dense_bias, dense_out, dense_remainder = DenseInt(200, 10, 10**18, dense_in, dense_weights, dense_bias)\n", "dense_out" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['21888242871839275222246405745257275088548364400416034343696001558406187208579',\n", " '21888242871839275222246405745257275088548364400416034343694494011253998843463',\n", " '2502586410316628302',\n", " '7723360444146681933',\n", " '21888242871839275222246405745257275088548364400416034343688179933383346961393',\n", " '21888242871839275222246405745257275088548364400416034343697101907583287035462',\n", " '21888242871839275222246405745257275088548364400416034343680804147065276585857',\n", " '21047995401855287971',\n", " '21888242871839275222246405745257275088548364400416034343695951614145619839501',\n", " '4230622081176419220']" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dense_out" ] }, { "cell_type": "code", "execution_cou
nt": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 35ms/step\n" ] }, { "data": { "text/plain": [ "array([ -2.2026286, -3.7101758, 2.5025864, 7.7233634, -10.024254 ,\n", " -1.1022782, -17.40004 , 21.047997 , -2.2525737, 4.230623 ],\n", " dtype=float32)" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dense_model = Model(inputs, model.layers[-2].output)\n", "dense_model.predict(X.reshape(1,28,28,1))[0]" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "in_json = {\n", " \"in\": X_in,\n", " \"conv2d_1_weights\": conv2d_1_weights,\n", " \"conv2d_1_bias\": conv2d_1_bias,\n", " \"conv2d_1_out\": conv2d_1_out,\n", " \"conv2d_1_remainder\": conv2d_1_remainder,\n", " \"bn_1_a\": bn_1_a,\n", " \"bn_1_b\": bn_1_b,\n", " \"bn_1_out\": bn_1_out,\n", " \"bn_1_remainder\": bn_1_remainder,\n", " \"relu_1_out\": relu_1_out,\n", " \"avg2d_1_out\": avg2d_1_out,\n", " \"avg2d_1_remainder\": avg2d_1_remainder,\n", " \"conv2d_2_weights\": conv2d_2_weights,\n", " \"conv2d_2_bias\": conv2d_2_bias,\n", " \"conv2d_2_out\": conv2d_2_out,\n", " \"conv2d_2_remainder\": conv2d_2_remainder,\n", " \"bn_2_a\": bn_2_a,\n", " \"bn_2_b\": bn_2_b,\n", " \"bn_2_out\": bn_2_out,\n", " \"bn_2_remainder\": bn_2_remainder,\n", " \"relu_2_out\": relu_2_out,\n", " \"avg2d_2_out\": avg2d_2_out,\n", " \"avg2d_2_remainder\": avg2d_2_remainder,\n", " \"flatten_out\": flatten_out,\n", " \"dense_weights\": dense_weights,\n", " \"dense_bias\": dense_bias,\n", " \"dense_out\": dense_out,\n", " \"dense_remainder\": dense_remainder,\n",
" \"argmax_out\": \"7\"\n", "}" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "
import json" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "with open(\"mnist_input.json\", \"w\") as f:\n", " json.dump(in_json, f)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "interpreter": { "hash": "11280bdb37aa6bc5d4cf1e4de756386eb1f9eecd8dcdefa77636dfac7be2370d" }, "kernelspec": { "display_name": "Python 3.8.6 ('tf24')", "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.16" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "p = 21888242871839275222246405745257275088548364400416034343698204186575808495617" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from tensorflow.keras.layers
import Input, Dense\n", "from tensorflow.keras
import Model\n", "
import numpy as np" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "inputs = Input(shape=(3,))\n", "x = Dense(2, activation='relu')(inputs)\n", "outputs = Dense(1)(x)\n", "model = Model(inputs, outputs)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"model\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param "=================================================================\n", " input_1 (InputLayer) [(None, 3)] 0 \n", " \n", " dense (Dense) (None, 2) 8 \n", " \n", " dense_1 (Dense) (None, 1) 3 \n", " \n", "=================================================================\n", "Total params: 11\n", "Trainable params: 11\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[<tf.Variable 'dense/kernel:0' shape=(3, 2) dtype=float32, numpy=\n", " array([[-0.72784126, 0.33670223],\n", " [-0.7780691 , 0.62421453],\n", " [-1.0269804 , 0.49905217]], dtype=float32)>,\n", " <tf.Variable 'dense/bias:0' shape=(2,) dtype=float32, numpy=array([0., 0.], dtype=float32)>,\n", " <tf.Variable 'dense_1/kernel:0' shape=(2, 1) dtype=float32, numpy=\n",
" array([[-0.00755942],\n", " [ 0.58352613]], dtype=float32)>,\n", " <tf.Variable 'dense_1/bias:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model.weights" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[0.5545958 , 0.48267873, 0.46073158]])" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X = np.random.rand(1,3)\n", "X" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 36ms/step\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2023-10-24 01:16:53.952999: W tensorflow/tsl/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n" ] }, { "data": { "text/plain": [ "array([[0.41894716]], dtype=float32)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = model.predict(X)\n", "y" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "X_in = [int(x*1e36) for x in X[0]]\n", "Dense32weights = [[int(model.weights[0].numpy()[i][j]*1e36) for j in range(2)] for i in range(3)]\n", "Dense32bias = [int(model.weights[1].numpy()[i]*1e72) for i in range(2)]\n", "Dense21weights = [[int(model.weights[2].numpy()[i][j]*1e36) for j in range(1)] for i in range(2)]\n", "Dense21bias = [int(model.weights[3].numpy()[i]*1e72) for i in range(1)]\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs":
[], "source": [ "def DenseInt(nInputs, nOutputs, n, input, weights, bias):\n", " Input = [str(input[i] % p) for i in range(nInputs)]\n", " Weights = [[str(weights[i][j] % p) for j in range(nOutputs)] for i in range(nInputs)]\n", " Bias = [str(bias[i] % p) for i in range(nOutputs)]\n", " out = [0 for _ in range(nOutputs)]\n", " remainder = [None for _ in range(nOutputs)]\n", " for j in range(nOutputs):\n", " for i in range(nInputs):\n", " out[j] += input[i] * weights[i][j]\n", " out[j] += bias[j]\n", " remainder[j] = str(out[j] % n)\n", " out[j] = str(out[j] " return Input, Weights, Bias, out, remainder" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(['21888242871839275222246405745257275088547112023011337864689255117657466434208',\n", " '717957812208694328223024234032338630'],\n", " ['749712352190261448543726154832412672',\n", " '264894409627262887048751218981601280'])" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X_in, Dense32weights, Dense32bias, Dense32out, Dense32remainder = DenseInt(3, 2, 10**36, X_in, Dense32weights, Dense32bias)\n", "Dense32out, Dense32remainder" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "ReLUout = [Dense32out[i] if int(Dense32out[i]) < p "Dense21in = [int(ReLUout[i]) for i in range(2)]" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(['418947146885730875576316926961913803'],\n", " ['695849152206718637828300508516843520'])" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "_, Dense21weight
s, Dense21bias, Dense21out, Dense21remainder = DenseInt(2, 1, 10**36, Dense21in, Dense21weights, Dense21bias)\n", "Dense21out, Dense21remainder" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "in_json = {\n", " \"in\": X_in,\n", " \"Dense32weights\": Dense32weights,\n", " \"Dense32bias\": Dense32bias,\n", " \"Dense32out\": Dense32out,\n", " \"Dense32remainder\": Dense32remainder,\n", " \"ReLUout\": ReLUout,\n", " \"Dense21weights\": Dense21weights,\n", " \"Dense21bias\": Dense21bias,\n", " \"Dense21out\": Dense21out,\n", " \"Dense21remainder\": Dense21remainder\n", "}" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "
import json" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "with open(\"model1_input.json\", \"w\") as f:\n", " json.dump(in_json, f)" ] } ], "metadata": { "kernelspec": { "display_name": "sklearn", "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.16" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "2b70084b-44da-4142-9e24-c9c8231828db", "metadata": {}, "outputs": [], "source": [ "
import torch\n", "
import torch.nn as nn\n", "
import torch.nn.functional as F\n", "
import numpy as np\n", "
import json" ] }, { "cell_type": "code", "execution_count": 2, "id": "e7533193-266d-4a59-b9aa-54179d40aa41", "metadata": {}, "outputs": [], "source": [ "p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n", "EXPONENT = 15\n", "\n", "
class SeparableConv2D(nn.Module):\n", " '''Separable convolution'''\n", " def __init__(self, in_channels, out_channels, stride=1):\n", " super(SeparableConv2D, self).__init__()\n", " self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\n", " self.pw_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\n", "\n", " def forward(self, x):\n", " x = self.dw_conv(x)\n", " x = self.pw_conv(x)\n", " return x" ] }, { "cell_type": "code", "execution_count": 3, "id": "4dec98ed-cd14-442b-93b5-8f3660726773", "metadata": {}, "outputs": [], "source": [ "input = torch.randn((1, 3, 5, 5))\n", "model = SeparableConv2D(3, 6)" ] }, { "cell_type": "code", "execution_count": 4, "id": "92b62f7c-5ac1-4c69-9add-9a859d66c327", "metadata": {}, "outputs": [], "source": [ "def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\n", " kernelSize = 1\n", " outRows = (nRows - kernelSize) " outCols = (nCols - kernelSize) " out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n", " str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n", " remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n", " for row in range(outRows):\n", " for col in range(outCols):\n", " for filter in range(nFilters):\n", " for k in range(nChannels):\n", " out[row][col][filter] += int(input[row*strides, col*strides, k]) * int(weights[k, filter])\n", " \n", " out[row][col][filter] += int(bias[filter])\n", " remainder[row][col][filter] = str(int(out[row][col][filter] % n))\n", "
out[row][col][filter] = int(out[row][col][filter] " str_out[row][col][filter] = str(out[row][col][filter] % p)\n", " \n", " return out, str_out, remainder" ] }, { "cell_type": "code", "execution_count": 5, "id": "0c664ba3-b722-482b-84f4-f83bab1d1bdb", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "quantized_image.shape=(5, 5, 3)\n", "quantized_weights.shape=(3, 6)\n", "expected.shape=(1, 6, 5, 5)\n", "expected.shape=(5, 5, 6)\n" ] } ], "source": [ "weights = model.pw_conv.weight.detach().numpy()\n", "bias = torch.zeros(weights.shape[0]).numpy()\n", "\n", "expected = model.pw_conv(input).detach().numpy()\n", "\n", "weights = weights.transpose((2, 3, 1, 0)).squeeze()\n", "\n", "quantized_image = input.squeeze().numpy().transpose((1, 2, 0)) * 10**EXPONENT\n", "quantized_weights = weights * 10**EXPONENT\n", "print(f\"{quantized_image.shape=}\")\n", "print(f\"{quantized_weights.shape=}\")\n", "\n", "actual, str_actual, remainder = PointwiseConv2d(5, 5, 3, 6, 1, 10**EXPONENT, quantized_image.round(), quantized_weights.round(), bias)\n", "\n", "actual_scaled = [[[actual[i][j][k] / 10**EXPONENT for k in range(6)] for j in range(5)] for i in range(5)]\n", "\n", "expected = expected.squeeze().transpose((1, 2, 0))\n", "\n", "assert(np.allclose(expected, actual_scaled, atol=0.00001))" ] }, { "cell_type": "code", "execution_count": 6, "id": "8b595d39-ca92-4c45-b04e-e7eb85b4c843", "metadata": {}, "outputs": [], "source": [ "circuit_in = quantized_image.round().astype(int).astype(str).tolist()\n", "circuit_weights = quantized_weights.round().astype(int).astype(str).tolist()\n", "circuit_bias = bias.round().astype(int).astype(str).tolist()\n", "\n", "input_json_path = \"pointwiseConv2D_input.json\"\n", "with open(input_json_path,
\"w\") as input_file:\n", " json.dump({\"in\": circuit_in,\n", " \"weights\": circuit_weights,\n", " \"remainder\": remainder,\n", " \"out\": str_actual,\n", " \"bias\": circuit_bias,\n", " },\n", " input_file)" ] }, { "cell_type": "code", "execution_count": null, "id": "cd6f84d3-4d70-421c-9067-5ed314c967a8", "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.11.5" } }, "nbformat": 4, "nbformat_minor": 5 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from mpmath
import mp\n", "
import numpy as np\n", "\n", " "\n", "def bisection_search(f, low:float, high:float):\n", " \"\"\"\n", " A root finding method that does not rely on derivatives\n", "\n", " :param f: a function f: X -> R\n", " :param low: the lower bracket\n", " :param high: the upper limit bracket\n", " :return: the location of the root, e.g. f(mid) ~ 0\n", " \"\"\"\n", " " if f(high) < f(low):\n", " low, high = high, low\n", "\n", " " mid = .5 * (low + high)\n", "\n", " while True:\n", "\n", " " if f(mid) < 0:\n", " low = mid\n", " " else:\n", " high = mid\n", "\n", " " mid = .5 * (high + low)\n", "\n", " " if abs(high - low) < 10 ** (-(mp.dps / 2)):\n", " break\n", "\n", " return mid\n", "\n", "\n", "def concave_max(f, low:float, high:float):\n", " \"\"\"\n", " Forms a lambda for the approximate derivative and finds the root\n", "\n", " :param f: a function f: X -> R\n", " :param low: the lower bracket\n", " :param high: the upper limit bracket\n", " :return: the location of the root f'(mid) ~ 0\n", " \"\"\"\n", " " scale = high - low\n", "\n", " h = mp.mpf('0.' + ''.join(['0' for i in range(int(mp.dps / 1.5))]) + '1') * scale\n", " df = lambda x: (f(x + h) - f(x - h)) / (2.0 * h)\n", "\n", " return bisection_search(df, low, high)\n", "\n", "def chev_points(n:int, lower:float = -1, upper:float = 1):\n", " \"\"\"\n", " Generates a set of chebychev points spaced in the range [lower, upper]\n", " :param n: number of points\n", " :param lower: lower limit\n", " :param upper: upper limit\n", " :return: a list of multipressison chebychev points that are in the range [lower, upper]\n", " \"\
"\"\n", " " index = np.arange(1, n+1)\n", " range_ = abs(upper - lower)\n", " return [(.5*(mp.cos((2*i-1)/(2*n)*mp.pi)+1))*range_ + lower for i in index]\n", "\n", "\n", "def remez(func, n_degree:int, lower:float=-1, upper:float=1, max_iter:int = 10):\n", " \"\"\"\n", " :param func: a function (or lambda) f: X -> R\n", " :param n_degree: the degree of the polynomial to approximate the function f\n", " :param lower: lower range of the approximation\n", " :param upper: upper range of the approximation\n", " :return: the polynomial coefficients, and an approximate maximum error associated with this approximation\n", " \"\"\"\n", " "\n", " x_points = chev_points(n_degree + 2, lower, upper)\n", "\n", " A = mp.matrix(n_degree + 2)\n", " coeffs = np.zeros(n_degree + 2)\n", "\n", " " mean_error = float('inf')\n", "\n", " for i in range(n_degree + 2):\n", " A[i, n_degree + 1] = (-1) ** (i + 1)\n", "\n", " for i in range(max_iter):\n", "\n", " " vander = np.polynomial.chebyshev.chebvander(x_points, n_degree)\n", "\n", " for i in range(n_degree + 2):\n", " for j in range(n_degree + 1):\n", " A[i, j] = vander[i, j]\n", "\n", " b = mp.matrix([func(x) for x in x_points])\n", " l = mp.lu_solve(A, b)\n", "\n", " coeffs = l[:-1]\n", "\n", " " r_i = lambda x: (func(x) - np.polynomial.chebyshev.chebval(x, coeffs))\n", "\n", " interval_list = list(zip(x_points, x_points[1:]))\n", " "\n", " intervals = [upper]\n", " intervals.extend([bisection_search(r_i, *i) for i in interval_list])\n", " intervals.append(lower)\n", "\n", " extermum_interval = [[intervals[i], intervals[i + 1]] for i in range(len(intervals) - 1)]\n", "\n", "
extremums = [concave_max(r_i, *i) for i in extermum_interval]\n", "\n", " extremums[0] = mp.mpf(upper)\n", " extremums[-1] = mp.mpf(lower)\n", "\n", " errors = [abs(r_i(i)) for i in extremums]\n", " mean_error = np.mean(errors)\n", "\n", " if np.max([abs(error - mean_error) for error in errors]) < 0.000001 * mean_error:\n", " break\n", "\n", " x_points = extremums\n", "\n", " return [float(i) for i in np.polynomial.chebyshev.cheb2poly(coeffs)], float(mean_error)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['0.502073021', '0.198695283', '-0.001570683', '-0.004001354']" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "function = lambda x: mp.sigmoid(x)\n", "poly_coeffs, max_error = remez(function, 3, -5, 5)\n", "[np.format_float_positional(c, precision=9) for c in poly_coeffs]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['0.006769816', '0.554670504', '-0.009411195', '-0.014187547']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "function = lambda x: mp.tanh(x)\n", "poly_coeffs, max_error = remez(function, 3, -5, 5)\n", "[np.format_float_positional(c, precision=9) for c in poly_coeffs]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "sklearn", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "p
ython", "pygments_lexer": "ipython3", "version": "3.9.16" } }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from tensorflow.keras.layers
import Input, Reshape\n", "from tensorflow.keras
import Model\n", "
import numpy as np" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "inputs = Input(shape=(75,))\n", "x = Reshape((5, 5, 3))(inputs)\n", "model = Model(inputs, x)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Model: \"model\"\n", "_________________________________________________________________\n", " Layer (type) Output Shape Param "=================================================================\n", " input_1 (InputLayer) [(None, 75)] 0 \n", " \n", " reshape (Reshape) (None, 5, 5, 3) 0 \n", " \n", "=================================================================\n", "Total params: 0\n", "Trainable params: 0\n", "Non-trainable params: 0\n", "_________________________________________________________________\n" ] } ], "source": [ "model.summary()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[0.72327659, 0.97464849, 0.2592479 , 0.63799774, 0.89013732,\n", " 0.95867971, 0.06431743, 0.55685192, 0.77031965, 0.09982323,\n", " 0.10704737, 0.40713332, 0.57294341, 0.21883552, 0.22967276,\n", " 0.6221842 , 0.64159904, 0.684413 , 0.59126341, 0.88438877,\n", " 0.56715972, 0.93006015, 0.85704814, 0.79864291, 0.39604054,\n", " 0.30495253, 0.38333952, 0.69453548, 0.59207958, 0.30889659,\n", " 0.17302571, 0.41351124, 0.37527957, 0.43118255, 0.31526054,\n", " 0.12925303, 0.30129156, 0.73921834, 0.98336451, 0.03352
392,\n", " 0.27839826, 0.6811155 , 0.96320785, 0.16882282, 0.68572833,\n", " 0.20924115, 0.30604142, 0.09080768, 0.63244108, 0.55914947,\n", " 0.60870048, 0.49377892, 0.9710362 , 0.12959508, 0.62162852,\n", " 0.26827067, 0.84771621, 0.40895646, 0.52476578, 0.48532215,\n", " 0.27144489, 0.19194784, 0.85410267, 0.11912042, 0.37034274,\n", " 0.25759208, 0.88306728, 0.98917787, 0.61814043, 0.49141046,\n", " 0.74162286, 0.81722887, 0.4728493 , 0.19955073, 0.42201694]])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "X = np.random.rand(1,75)\n", "X" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1/1 [==============================] - 0s 44ms/step\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "2024-02-04 00:14:24.910151: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz\n" ] }, { "data": { "text/plain": [ "array([[[[0.7232766 , 0.9746485 , 0.2592479 ],\n", " [0.63799775, 0.8901373 , 0.9586797 ],\n", " [0.06431743, 0.5568519 , 0.77031964],\n", " [0.09982323, 0.10704737, 0.4071333 ],\n", " [0.5729434 , 0.21883552, 0.22967276]],\n", "\n", " [[0.6221842 , 0.64159906, 0.684413 ],\n", " [0.5912634 , 0.88438874, 0.5671597 ],\n", " [0.93006015, 0.85704815, 0.79864293],\n", " [0.39604053, 0.30495253, 0.38333952],\n", " [0.6945355 , 0.5920796 , 0.3088966 ]],\n", "\n", " [[0.17302571, 0.41351125, 0.37527958],\n", " [0.43118253, 0.31526053, 0.12925303],\n", " [0.30129156, 0.73921835, 0.9833645 ],\n",
" [0.03352392, 0.27839825, 0.6811155 ],\n", " [0.96320784, 0.16882282, 0.6857283 ]],\n", "\n", " [[0.20924115, 0.30604142, 0.09080768],\n", " [0.6324411 , 0.55914944, 0.60870045],\n", " [0.4937789 , 0.9710362 , 0.12959507],\n", " [0.6216285 , 0.26827067, 0.8477162 ],\n", " [0.40895647, 0.5247658 , 0.48532215]],\n", "\n", " [[0.2714449 , 0.19194785, 0.8541027 ],\n", " [0.11912042, 0.37034273, 0.25759208],\n", " [0.8830673 , 0.9891779 , 0.6181404 ],\n", " [0.49141046, 0.74162287, 0.81722885],\n", " [0.4728493 , 0.19955073, 0.42201695]]]], dtype=float32)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y = model.predict(X)\n", "y" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "in_json = {\n", " \"in\": (X*1e36).round().astype(int).flatten().tolist(),\n", " \"out\": (X*1e36).round().astype(int).flatten().tolist()\n", "}" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "
import json" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "with open(\"reshape2D_input.json\", \"w\") as f:\n", " json.dump(in_json, f)" ] } ], "metadata": { "kernelspec": { "display_name": "keras2circom", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" } }, "nbformat": 4, "nbformat_minor": 2 }
{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "aa5be75a-ee5f-45b0-891b-da2dd340dd00", "metadata": {}, "outputs": [], "source": [ "
import torch\n", "
import torch.nn as nn\n", "
import torch.nn.functional as F\n", "
import numpy as np\n", "
import json" ] }, { "cell_type": "code", "execution_count": 2, "id": "f85ed78d-97ef-4979-acac-8d95b34a84ae", "metadata": {}, "outputs": [], "source": [ "p = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n", "CIRCOM_PRIME = 21888242871839275222246405745257275088548364400416034343698204186575808495617\n", "MAX_POSITIVE = CIRCOM_PRIME "MAX_NEGATIVE = MAX_POSITIVE + 1 "CIRCOM_NEGATIVE_1 = 21888242871839275222246405745257275088548364400416034343698204186575808495617 - 1\n", "EXPONENT = 15\n", "\n", "
class SeparableConv2D(nn.Module):\n", " '''Separable convolution'''\n", " def __init__(self, in_channels, out_channels, stride=1):\n", " super(SeparableConv2D, self).__init__()\n", " self.dw_conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=stride, padding=1, groups=in_channels, bias=False)\n", " self.pw_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False)\n", "\n", " def forward(self, x):\n", " x = self.dw_conv(x)\n", " x = self.pw_conv(x)\n", " return x\n", "\n", "def from_circom(x):\n", " if type(x) != int:\n", " x = int(x)\n", " if x > MAX_POSITIVE: \n", " return x - CIRCOM_PRIME\n", " return x\n", " \n", "def to_circom(x):\n", " if type(x) != int:\n", " x = int(x)\n", " if x < 0:\n", " return x + CIRCOM_PRIME \n", " return x" ] }, { "cell_type": "code", "execution_count": 3, "id": "32e117a1-32aa-4b4b-91d0-4b4b78071b6b", "metadata": {}, "outputs": [], "source": [ " " " " " \n", " " " \n", " " " " " " " \n", " " " " \n", " " \n", " " " " " " " " " " " \n", " " " \n", " "\n", " " " "\n", " " " ] }, { "cell_type": "code", "execution_count": 4, "id": "e3dfadfd-2587-4708-9dd5-535a999ed359", "metadata": {}, "outputs": [], "source": [ " " " " " \n", " " " " " " " \n", " " " " " " " \n", " " " " " \n", " " \n", " " " " " \n", " " " " " " " \n", "
" " " " " \n", " " " " "\n", " " " "\n", " " " " " \n", " ] }, { "cell_type": "code", "execution_count": 1, "id": "cc1a4a27-a1dc-4565-90e3-12e6d7122157", "metadata": {}, "outputs": [], "source": [ "def DepthwiseConv(nRows, nCols, nChannels, nFilters, kernelSize, strides, n, input, weights, bias):\n", " assert(nFilters % nChannels == 0)\n", " outRows = (nRows - kernelSize) " outCols = (nCols - kernelSize) " \n", " " out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n", " remainder = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n", " " \n", " for row in range(outRows):\n", " for col in range(outCols):\n", " for channel in range(nChannels):\n", " for x in range(kernelSize):\n", " for y in range(kernelSize):\n", " out[row][col][channel] += int(input[row*strides+x, col*strides+y, channel]) * int(weights[x, y, channel])\n", " \n", " out[row][col][channel] += int(bias[channel])\n", " remainder[row][col][channel] = str(int(out[row][col][channel] % n))\n", " out[row][col][channel] = int(out[row][col][channel] " \n", " return out, remainder\n", " \n", "def PointwiseConv2d(nRows, nCols, nChannels, nFilters, strides, n, input, weights, bias):\n", " kernelSize = 1\n", " outRows = (nRows - kernelSize) " outCols = (nCols - kernelSize) " out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n", " str_out = [[[0 for _ in range(nFilters)] for _ in range(outCols)] for _ in range(outRows)]\n", " remainder = [[[None for _ in range(nFilters)] for _ in range(outCols)]
for _ in range(outRows)]\n", " for row in range(outRows):\n", " for col in range(outCols):\n", " for filter in range(nFilters):\n", " for k in range(nChannels):\n", " out[row][col][filter] += int(input[row*strides][col*strides][k]) * int(weights[k, filter])\n", " \n", " out[row][col][filter] += int(bias[filter])\n", " remainder[row][col][filter] = str(int(out[row][col][filter] % n))\n", " out[row][col][filter] = int(out[row][col][filter] " str_out[row][col][filter] = str(out[row][col][filter] % p)\n", " \n", " return out, str_out, remainder\n", " \n", "def SeparableConvImpl(nRows, nCols, nChannels, nDepthFilters, nPointFilters, kernelSize, strides, n, input, depthWeights, pointWeights, depthBias, pointBias):\n", " outRows = (nRows - kernelSize) " outCols = (nCols - kernelSize) "\n", " depth_out, depth_remainder = DepthwiseConv(nRows, nCols, nChannels, nDepthFilters, kernelSize, strides, n, input, depthWeights, depthBias)\n", " point_out, point_str_out, point_remainder = PointwiseConv2d(outRows, outCols, nChannels, nPointFilters, strides, n, depth_out, pointWeights, pointBias)\n", " return depth_out, depth_remainder, point_out, point_str_out, point_remainder" ] }, { "cell_type": "code", "execution_count": 2, "id": "cfa6df6a-9a0c-4150-9df0-30e2700d4f6b", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'torch' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[2], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;2
41m=\u001b[39m \u001b[43mtorch\u001b[49m\u001b[38;5;241m.\u001b[39mrandn((\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m3\u001b[39m, \u001b[38;5;241m5\u001b[39m, \u001b[38;5;241m5\u001b[39m))\n\u001b[1;32m 2\u001b[0m model \u001b[38;5;241m=\u001b[39m SeparableConv2D(\u001b[38;5;241m3\u001b[39m, \u001b[38;5;241m6\u001b[39m)\n", "\u001b[0;31mNameError\u001b[0m: name 'torch' is not defined" ] } ], "source": [ "input = torch.randn((1, 3, 5, 5))\n", "model = SeparableConv2D(3, 6)" ] }, { "cell_type": "code", "execution_count": 3, "id": "5db59f3a-e610-473a-8dfc-1d5e812748f4", "metadata": {}, "outputs": [], "source": [ " " "\n", " "\n", " " " "\n", " " "\n", " ] }, { "cell_type": "code", "execution_count": 8, "id": "47ce42c7-b417-46ba-a31b-1ae23234a2cd", "metadata": {}, "outputs": [], "source": [ " " " "\n", " "\n", " " " "\n", " "\n", " "\n", " ] }, { "cell_type": "code", "execution_count": 9, "id": "7a36a0a1-6965-4184-93a5-5d121d6d1856", "metadata": {}, "outputs": [], "source": [ " " "\n", " "\n", " " " " "\n", " " "\n", " " "\n", " " " "\n", " ] }, { "cell_type": "code", "execution_count": 10, "id": "fd587b58-1646-4ec8-9a79-4f891dab0276", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "depthWeights.shape=(3, 3, 3)\n", "expected.shape=(1, 6, 5, 5)\n", "(6,)\n" ] }, { "ename": "NameError", "evalue": "name 'depthOut' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent cal
l last)", "Cell \u001b[0;32mIn[10], line 23\u001b[0m\n\u001b[1;32m 20\u001b[0m quantized_depth_weights \u001b[38;5;241m=\u001b[39m depthWeights \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m10\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mEXPONENT\n\u001b[1;32m 21\u001b[0m quantized_point_weights \u001b[38;5;241m=\u001b[39m pointWeights \u001b[38;5;241m*\u001b[39m \u001b[38;5;241m10\u001b[39m\u001b[38;5;241m*\u001b[39m\u001b[38;5;241m*\u001b[39mEXPONENT\n\u001b[0;32m---> 23\u001b[0m depth_out, depth_remainder, point_out, point_str_out, point_remainder \u001b[38;5;241m=\u001b[39m \u001b[43mSeparableConvImpl\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m7\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m7\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m6\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mEXPONENT\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquantized_image\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mround\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mastype\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquantized_depth_weights\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mround\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mastype\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mint\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mquantized_point_weights\u001b[49m\u001