Commit ·
8f80484
1
Parent(s): 5e6e795
Sync from GitHub
Browse filesFiles changed (23)
- app.py+1-1
- hf_repo/.github/workflows/sync_to_hf.ymlAdded+43
- hf_repo/deployment/serialized_model_zkmlAdded
- hf_repo/hf_repo/.gitattributesAdded+33
- hf_repo/hf_repo/.gitignoreAdded+9
- hf_repo/hf_repo/README.mdAdded+54
- hf_repo/hf_repo/SentimentClassification.ipynbAdded+1053
- hf_repo/hf_repo/app.pyAdded+401
- hf_repo/hf_repo/compile.pyAdded+35
- hf_repo/hf_repo/deployment/samples_for_compilation.csvAdded
- hf_repo/hf_repo/deployment/sentiment_fhe_model/client.zipAdded+3
- hf_repo/hf_repo/deployment/sentiment_fhe_model/server.zipAdded+3
- hf_repo/hf_repo/deployment/sentiment_fhe_model/versions.jsonAdded+1
- hf_repo/hf_repo/deployment/serialized_modelAdded
- hf_repo/hf_repo/download_data.shAdded+15
- hf_repo/hf_repo/requirements.txtAdded+9
- hf_repo/hf_repo/sentiment_analysis_banner.pngAdded
- hf_repo/hf_repo/server.pyAdded+39
- hf_repo/hf_repo/transformer_vectorizer.pyAdded+58
- hf_repo/zkml_encrypted.pyAdded+212
- hf_repo/zkml_non_encrypted.pyAdded+245
- zkml_encrypted.py+1-1
- zkml_non_encrypted.py+1-7
15 unmodified lines1617181920212215 unmodified lines# This repository's directoryREPO_DIR = Path(__file__).parentsubprocess.Popen(["anvil", "-p", "3030"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "server:app", "--port", "8000"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "zkml_non_encrypted:app", "--port", "8001"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "zkml_encrypted:app", "--port", "8002"], cwd=REPO_DIR)15 unmodified lines1617181920212215 unmodified lines# This repository's directoryREPO_DIR = Path(__file__).parent# subprocess.Popen(["anvil", "-p", "3030"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "server:app", "--port", "8000"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "zkml_non_encrypted:app", "--port", "8001"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "zkml_encrypted:app", "--port", "8002"], cwd=REPO_DIR)
12345678910111213141516171819202122232425262728293031323334353637383940414243name: Sync to Hugging Face
on: push: branches: - main
jobs: sync: runs-on: ubuntu-latest
steps: - name: Checkout repository uses: actions/checkout@v3
- name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.9' # Specify your Python version
- name: Install dependencies run: | pip install huggingface_hub
- name: Sync to Hugging Face env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | # Configure git git config --global user.email "myronzhangweb3@gmail.com" git config --global user.name "Myron Zhang"
# Clone the Hugging Face repository git clone https://myronzhangweb3:$HF_TOKEN@huggingface.co/spaces/PrivEcho/encrypted_sentiment_analysis hf_repo cd hf_repo
# Copy files from the GitHub repository rsync -av --exclude='.git' ../ .
# Commit and push changes to Hugging Face git add . git commit -m "Sync from GitHub" git push123456789101112131415161718192021222324252627282930313233*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789tmp/.venv.fhe_keys*.pyclocal_datasets/.vscode//.idea/zkml_encrypted/zkml_non_encrypted123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354---title: Sentiment Analysis On Encrypted Data Using Fully Homomorphic Encryptionemoji: 🥷💬colorFrom: yellowcolorTo: yellowsdk: gradiosdk_version: 4.44.0app_file: app.pypinned: truetags: [FHE, PPML, privacy, privacy preserving machine learning, homomorphic encryption, security]python_version: 3.10.11---
# Sentiment Analysis With FHE
## Set up the app locally
- First, create a virtual env and activate it:
```bashpython3 -m venv .venvsource .venv/bin/activate```
- Then, install required packages:
```bashpip3 install pip --upgradepip3 install -U pip wheel setuptools --ignore-installedpip3 install -r requirements.txt --ignore-installed
# mac z3brew install z3pip3 uninstall z3-solverpip3 install z3-solverpip3 install more-itertools```
Check it finish well (with a "Done!"). Please note that the actual model initialization and training can be found in the [SentimentClassification notebook](SentimentClassification.ipynb) (see below).
### Launch the app locally
- In a terminal:
```bashsource .venv/bin/activatepython3 app.py```
## Interact with the application
Open the given URL link (search for a line like `Running on local URL: http://127.0.0.1:8888/` in the terminal).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Sentiment Classification with FHE\n", "\n", "This notebook tackles sentiment classification with Fully Homomorphic Encryption. Let's imagine some client (could be a user or a company) wants to predict whether a specific text (e.g., a tweet) contains positive, neutral or negative feedback using a cloud service provider without actually revealing the text during the process.\n", "\n", "To do this, we use a machine learning model that can predict over encrypted data thanks to the Concrete-ML library available on [GitHub](https://github.com/zama-ai/concrete-ml).\n", "\n", "The dataset we use in this notebook can be found on [Kaggle](https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment). \n", " \n", "We present two different ways to encode the text:\n", "1. A basic **TF-IDF** approach, which essentially looks at how often a word appears in the text.\n", "2. An advanced **transformer** embedding of the text using the Huggingface repository.\n", "\n", "The main assumption of this notebook is that clients, who want to have their text analyzed in a privacy preserving manner, can encode the text using a predefined representation before encrypting the data. The FHE-friendly model is thus trained in the clear beforehand for the given task, here classification, over theses representations using a relevant training set." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Import the required packages\n", "import os\n", "import time\n", "from pathlib import Path\n", "\n", "import numpy\n", "import pandas as pd\n", "from sklearn.metrics import average_precision_score\n", "from sklearn.model_selection import GridSearchCV, train_test_split\n", "\n", "from concrete.ml.sklearn import XGBClassifier" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Proportion of positive examples: 16.14%\n", "Proportion of negative examples: 62.69%\n", "Proportion of neutral examples: 21.17%\n" ] } ], "source": [ "# Download the datasets\n", "# The dataset can be downloaded through the `download_data.sh` script, which requires to set up\n", "# Kaggle's CLI, or manually at https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment\n", "if not os.path.isfile(\"local_datasets/twitter-airline-sentiment/Tweets.csv\"):\n", " raise ValueError(\"Please launch the `download_data.sh` script to get datasets\")\n", "\n", "\n", "train = pd.read_csv(\"local_datasets/twitter-airline-sentiment/Tweets.csv\", index_col=0)\n", "text_X = train[\"text\"]\n", "y = train[\"airline_sentiment\"]\n", "y = y.replace([\"negative\", \"neutral\", \"positive\"], [0, 1, 2])\n", "\n", "pos_ratio = y.value_counts()[2] / y.value_counts().sum()\n", "neg_ratio = y.value_counts()[0] / y.value_counts().sum()\n", "neutral_ratio = y.value_counts()[1] / y.value_counts().sum()\n", "print(f\"Proportion of positive examples: {round(pos_ratio * 100, 2)}%\")\n", "print(f\"Proportion of negative examples: {round(neg_ratio * 100, 2)}%\")\n", "print(f\"Proportion of neutral examples: {round(neutral_ratio * 100, 2)}%\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "# Split in train test\n", "text_X_train, text_X_test, y_train, y_test = train_test_split(\n", " text_X, y, test_size=0.1, random_state=42\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1. Text representation using TF-IDF\n", "\n", "[Term Frequency-Inverse Document Frequency](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)(TF-IDF) also known as is a numerical statistic that is used to compute the importance of a term in a document. The higher the TF-IDF score, the more important the term is to the document.\n", "\n", "We compute it as follows:\n", "\n", "$$ \\mathsf{TF\\textrm{-}IDF}(t,d,D) = \\mathsf{TF}(t,d) * \\mathsf{IDF}(t,D) $$\n", "\n", "where: $\\mathsf{TF}(t,d)$ is the term frequency of term $t$ in document $d$, $\\mathsf{IDF}(t,D)$ is the inverse document frequency of term $t$ in document collection $D$.\n", "\n", "Here we use the scikit-learn implementation of TF-IDF vectorizer." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Let's first build a representation vector from the text\n", "from sklearn.feature_extraction.text import TfidfVectorizer\n", "\n", "tfidf_vectorizer = TfidfVectorizer(max_features=500, stop_words=\"english\")\n", "X_train = tfidf_vectorizer.fit_transform(text_X_train)\n", "X_test = tfidf_vectorizer.transform(text_X_test)\n", "\n", "# Make our train and test dense array\n", "X_train = X_train.toarray()\n", "X_test = X_test.toarray()" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Let's build our model\n", "model = XGBClassifier()\n", "\n", "# A gridsearch to find the best parameters\n", "parameters = {\n", " \"n_bits\": [2, 3],\n", " \"max_depth\": [1],\n", " \"n_estimators\": [10, 30, 50],\n", " # \"n_jobs\": [-1],\n", "}" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(n_jobs=1),\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50]},\n", " scoring='accuracy')</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" ><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(n_jobs=1),\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50]},\n", " scoring='accuracy')</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" ><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier(n_jobs=1)</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" ><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier(n_jobs=1)</pre></div></div></div></div></div></div></div></div></div></div>" ], "text/plain": [ "GridSearchCV(cv=3, estimator=XGBClassifier(n_jobs=1),\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50]},\n", " scoring='accuracy')" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Run the gridsearch\n", "grid_search = GridSearchCV(model, parameters, cv=3, scoring=\"accuracy\")\n", "grid_search.fit(X_train, y_train)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best score: 0.705980570734669\n", "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50}\n" ] } ], "source": [ "# Check the accuracy of the best model\n", "print(f\"Best score: {grid_search.best_score_}\")\n", "\n", "# Check best hyperparameters\n", "print(f\"Best parameters: {grid_search.best_params_}\")\n", "\n", "# Extract best model\n", "best_model = grid_search.best_estimator_" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.7117\n", "Average precision score for positive class: 0.6404\n", "Average precision score for negative class: 0.8719\n", "Average precision score for neutral class: 0.4349\n" ] } ], "source": [ "# Compute the average precision for each class\n", "y_proba_test_tfidf = best_model.predict_proba(X_test)\n", "\n", "# Compute accuracy\n", "y_pred_test_tfidf = numpy.argmax(y_proba_test_tfidf, axis=1)\n", "accuracy_tfidf = numpy.mean(y_pred_test_tfidf == y_test)\n", "print(f\"Accuracy: {accuracy_tfidf:.4f}\")\n", "\n", "y_pred_positive = y_proba_test_tfidf[:, 2]\n", "y_pred_negative = y_proba_test_tfidf[:, 0]\n", "y_pred_neutral = y_proba_test_tfidf[:, 1]\n", "\n", "ap_positive_tfidf = average_precision_score((y_test == 2), y_pred_positive)\n", "ap_negative_tfidf = average_precision_score((y_test == 0), y_pred_negative)\n", "ap_neutral_tfidf = average_precision_score((y_test == 1), y_pred_neutral)\n", "\n", "print(f\"Average precision score for positive class: \" f\"{ap_positive_tfidf:.4f}\")\n", "print(f\"Average precision score for negative class: \" f\"{ap_negative_tfidf:.4f}\")\n", "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_tfidf:.4f}\")" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n", " 2, 2, 2, 2, 2, 2])" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y_pred_test_tfidf[y_pred_test_tfidf == 2]" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive tweets (class 2):\n", "@JetBlue do bags still fly free or have you started charging? thanks!\n", "@SouthwestAir Is there a way to receive a refund on a trip that was Cancelled Flight online instead of calling? Your phone lines are super busy.\n", "@JetBlue bag is supposedly here in Boston\n", "@AmericanAir Cancelled Flights my flight, doesn't send an email, text or call. Now I'm stranded in Louisville.\n", "@SouthwestAir I need to Cancelled Flight one leg of a flight, but can't seem to do this online. Been on hold on the phone for 10 minutes. Any help?\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative tweets (class 0):\n", "@AmericanAir - keeping AA up in the Air! My crew chief cousin Alex Espinosa in DFW! http://t.co/0HXLNvZknP\n", "@JetBlue Called JB 3 times!Everytime, Auto Vmsg:\"your wait time should not be longer than 9 mins\" waited longer than 18 mins and no answer!\n", "@SouthwestAir can you outline the policies for both scenarios?\n", "@united is not a company that values it's customer & after reading tweets to them I'm not the only one who feels that way #lostmybusiness\n", "@JetBlue how about free wifi on flt 1254 out of PBI to make up for 2.5 hr delay? Treat us right.\n" ] } ], "source": [ "# Let's see what are the top predictions based on the probabilities in y_pred_test\n", "print(\"5 most positive tweets (class 2):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_pred_test_tfidf[y_pred_test_tfidf==2].argsort()[-1 - i]])\n", "\n", "print(\"-\" * 100)\n", "\n", "print(\"5 most negative tweets (class 0):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_pred_test_tfidf[y_pred_test_tfidf==0].argsort()[-1 - i]])" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Compilation time: 5.3550 seconds\n", "FHE inference time: 1.1162 seconds\n" ] } ], "source": [ "# Compile the model to get the FHE inference engine\n", "# (this may take a few minutes depending on the selected model)\n", "start = time.perf_counter()\n", "best_model.compile(X_train)\n", "end = time.perf_counter()\n", "print(f\"Compilation time: {end - start:.4f} seconds\")\n", "\n", "# Let's write a custom example and predict in FHE\n", "tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n", "X_tested_tweet = tfidf_vectorizer.transform(numpy.array(tested_tweet)).toarray()\n", "clear_proba = best_model.predict_proba(X_tested_tweet)\n", "\n", "# Now let's predict with FHE over a single tweet and print the time it takes\n", "start = time.perf_counter()\n", "decrypted_proba = best_model.predict_proba(X_tested_tweet, fhe=\"execute\")\n", "end = time.perf_counter()\n", "print(f\"FHE inference time: {end - start:.4f} seconds\")" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Probabilities from the FHE inference: [[0.30244059 0.17506451 0.5224949 ]]\n", "Probabilities from the clear model: [[0.30244059 0.17506451 0.5224949 ]]\n" ] } ], "source": [ "print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n", "print(f\"Probabilities from the clear model: {clear_proba}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To sum up, \n", "- We trained a XGBoost model over TF-IDF representation of the tweets and their respective sentiment class. \n", "- The grid search gives us a model that achieves around ~70% accuracy.\n", "- Given the imbalance in the classes, we rather compute the average precision per class.\n", "\n", "Now we will see how we can approach the problem by leveraging the transformers power." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2. A transformer approach to text representation\n", "\n", "[**Transformers**](https://en.wikipedia.org/wiki/Transformer_(machine_learning_model\\)) are neural networks that are often trained to predict the next words to appear in a text (this is commonly called self-supervised learning). \n", "\n", "They are powerful tools for all kind of Natural Language Processing tasks but supporting a transformer model in FHE might not always be ideal as they are quite big models. However, we can still leverage their hidden representation for any text and feed it to a more FHE friendly machine learning model (in this notebook we will use XGBoost) for classification.\n", "\n", "Here we will use the transformer model from the amazing [**Huggingface**](https://huggingface.co/) repository." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of the model checkpoint at cardiffnlp/twitter-roberta-base-sentiment-latest were not used when initializing RobertaForSequenceClassification: ['roberta.pooler.dense.weight', 'roberta.pooler.dense.bias']\n", "- This IS expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n", "- This IS NOT expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n" ] } ], "source": [ "import torch\n", "import tqdm\n", "from transformers import AutoModelForSequenceClassification, AutoTokenizer\n", "\n", "device = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n", "\n", "# Load the tokenizer (converts text to tokens)\n", "tokenizer = AutoTokenizer.from_pretrained(\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\n", "\n", "# Load the pre-trained model\n", "transformer_model = AutoModelForSequenceClassification.from_pretrained(\n", " \"cardiffnlp/twitter-roberta-base-sentiment-latest\"\n", ")" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n", "To disable this warning, you can either:\n", "\t- Avoid using `tokenizers` before the fork if possible\n", "\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n", " 0%| | 0/30 [00:00<?, ?it/s]We strongly recommend passing in an `attention_mask` since your input_ids may be padded. See https://huggingface.co/docs/transformers/troubleshooting#incorrect-output-when-padding-tokens-arent-masked.\n", "100%|██████████| 30/30 [00:20<00:00, 1.45it/s]\n" ] } ], "source": [ "# Let's first see what are the model performance by itself\n", "list_text_X_test = text_X_test.tolist()\n", "\n", "tokenized_text_X_test = tokenizer.batch_encode_plus(\n", " list_text_X_test, pad_to_max_length=True, return_tensors=\"pt\"\n", ")[\"input_ids\"]\n", "\n", "# Depending on the hardware used, the number of examples to be processed can be reduced\n", "# Here we split the data into 100 examples per batch\n", "tokenized_text_X_test_split = torch.split(tokenized_text_X_test, split_size_or_sections=50)\n", "transformer_model = transformer_model.to(device)\n", "\n", "outputs = []\n", "for tokenized_x_test in tqdm.tqdm(tokenized_text_X_test_split):\n", " tokenized_x = tokenized_x_test.to(device)\n", " output_batch = transformer_model(tokenized_x)[\"logits\"]\n", " output_batch = output_batch.detach().cpu().numpy()\n", " outputs.append(output_batch)\n", "\n", "outputs = numpy.concatenate(outputs, axis=0)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Predictions for the first 3 tweets:\n", " [[-2.3807454 -0.61802197 2.9900734 ]\n", " [ 2.0166504 0.49380752 -2.8006463 ]\n", " [ 2.3892734 0.13443531 -2.6873832 ]]\n" ] } ], "source": [ "# Let's see what the transformer model predicts\n", "print(f\"Predictions for the first 3 tweets:\\n {outputs[:3]}\")" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.8053\n", "Average precision score for positive class: 0.8548\n", "Average precision score for negative class: 0.9548\n", "Average precision score for neutral class: 0.6801\n" ] } ], "source": [ "# Compute the metrics for each class\n", "\n", "# Compute accuracy\n", "accuracy_transformer_only = numpy.mean(numpy.argmax(outputs, axis=1) == y_test)\n", "print(f\"Accuracy: {accuracy_transformer_only:.4f}\")\n", "\n", "y_pred_positive = outputs[:, 2]\n", "y_pred_negative = outputs[:, 0]\n", "y_pred_neutral = outputs[:, 1]\n", "\n", "ap_positive_transformer_only = average_precision_score((y_test == 2), y_pred_positive)\n", "ap_negative_transformer_only = average_precision_score((y_test == 0), y_pred_negative)\n", "ap_neutral_transformer_only = average_precision_score((y_test == 1), y_pred_neutral)\n", "\n", "print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_only:.4f}\")\n", "print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_only:.4f}\")\n", "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_only:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It looks like the transformer outperforms the model built on TF-IDF reprensentation.\n", "Unfortunately, running a transformer that big in FHE would be highly inefficient. \n", "\n", "Let's see if we can leverage transformer representation and train a FHE model for the given classification task. " ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 13176/13176 [09:24<00:00, 23.36it/s]\n", "100%|██████████| 1464/1464 [01:00<00:00, 24.12it/s]\n" ] } ], "source": [ "# Function that transforms a list of texts to their representation\n", "# learned by the transformer.\n", "def text_to_tensor(\n", " list_text_X_train: list,\n", " transformer_model: AutoModelForSequenceClassification,\n", " tokenizer: AutoTokenizer,\n", " device: str,\n", ") -> numpy.ndarray:\n", " # Tokenize each text in the list one by one\n", " tokenized_text_X_train_split = []\n", " for text_x_train in list_text_X_train:\n", " tokenized_text_X_train_split.append(tokenizer.encode(text_x_train, return_tensors=\"pt\"))\n", "\n", " # Send the model to the device\n", " transformer_model = transformer_model.to(device)\n", " output_hidden_states_list = []\n", "\n", " for tokenized_x in tqdm.tqdm(tokenized_text_X_train_split):\n", " # Pass the tokens through the transformer model and get the hidden states\n", " # Only keep the last hidden layer state for now\n", " output_hidden_states = transformer_model(tokenized_x.to(device), output_hidden_states=True)[\n", " 1\n", " ][-1]\n", " # Average over the tokens axis to get a representation at the text level.\n", " output_hidden_states = output_hidden_states.mean(dim=1)\n", " output_hidden_states = output_hidden_states.detach().cpu().numpy()\n", " output_hidden_states_list.append(output_hidden_states)\n", "\n", " return numpy.concatenate(output_hidden_states_list, axis=0)\n", "\n", "\n", "# Let's vectorize the text using the transformer\n", "list_text_X_train = text_X_train.tolist()\n", "list_text_X_test = text_X_test.tolist()\n", "\n", "X_train_transformer = text_to_tensor(list_text_X_train, transformer_model, tokenizer, device)\n", "X_test_transformer = text_to_tensor(list_text_X_test, transformer_model, tokenizer, device)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(n_jobs=1), n_jobs=1,\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50]},\n", " scoring='accuracy')</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(n_jobs=1), n_jobs=1,\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50]},\n", " scoring='accuracy')</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier(n_jobs=1)</pre></div></div></div><div class=\"sk-serial\"><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" ><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier(n_jobs=1)</pre></div></div></div></div></div></div></div></div></div></div>" ], "text/plain": [ "GridSearchCV(cv=3, estimator=XGBClassifier(n_jobs=1), n_jobs=1,\n", " param_grid={'max_depth': [1], 'n_bits': [2, 3],\n", " 'n_estimators': [10, 30, 50]},\n", " scoring='accuracy')" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Now we have a representation for each tweet, we can train a model on these.\n", "grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n", "grid_search.fit(X_train_transformer, y_train)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best score: 0.8381147540983607\n", "Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50}\n" ] } ], "source": [ "# Check the accuracy of the best model\n", "print(f\"Best score: {grid_search.best_score_}\")\n", "\n", "# Check best hyperparameters\n", "print(f\"Best parameters: {grid_search.best_params_}\")\n", "\n", "# Extract best model\n", "best_model = grid_search.best_estimator_" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.8463\n", "Average precision score for positive class: 0.8959\n", "Average precision score for negative class: 0.9647\n", "Average precision score for neutral class: 0.7449\n" ] } ], "source": [ "# Compute the metrics for each class\n", "\n", "y_proba = best_model.predict_proba(X_test_transformer)\n", "\n", "# Compute the accuracy\n", "y_pred = numpy.argmax(y_proba, axis=1)\n", "accuracy_transformer_xgboost = numpy.mean(y_pred == y_test)\n", "print(f\"Accuracy: {accuracy_transformer_xgboost:.4f}\")\n", "\n", "y_pred_positive = y_proba[:, 2]\n", "y_pred_negative = y_proba[:, 0]\n", "y_pred_neutral = y_proba[:, 1]\n", "\n", "ap_positive_transformer_xgboost = average_precision_score((y_test == 2), y_pred_positive)\n", "ap_negative_transformer_xgboost = average_precision_score((y_test == 0), y_pred_negative)\n", "ap_neutral_transformer_xgboost = average_precision_score((y_test == 1), y_pred_neutral)\n", "\n", "print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_xgboost:.4f}\")\n", "print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_xgboost:.4f}\")\n", "print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_xgboost:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Our FHE-friendly XGBoost model does 38% better than the XGBoost model built over TF-IDF representation of the text. Note that here we are still not using FHE and only evaluating the model.\n", "Interestingly, using XGBoost over the transformer representation of the text matches the performance of the transformer model alone." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive tweets (class 2):\n", "@united I think this is the best first class I have ever gotten!! Denver to LAX and it's wonderful!!!\n", "@AmericanAir Flight 236 was great. Fantastic cabin crew. A+ landing. #thankyou #JFK http://t.co/dRW08djHAI\n", "@SouthwestAir Jason (108639) at Gate #3 in SAN made my afternoon!!! #southwestairlines #stellarservice #thanks!\n", "@SouthwestAir love them! Always get the best deals!\n", "@AmericanAir simply amazing. Smiles for miles.Thank u for my upgrade tomorrow for ORD.We are spending a lot of time together next few weeks!\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative tweets (class 0):\n", "@united first you lost all my bags, now you Cancelled Flight my flight home. 30 min wait to talk to somebody #poorservice #notgoodenough\n", "@USAirways Not only did u lose the flight plan! Now ur flight crew is FAA timed out! Thx for havin us sit on the tarmac for an hr! #Pathetic\n", "@AmericanAir Phone just disconnects if you stay on the line. Need to checkout of hotel in 2 hrs & have no place to go. Can't keep calling.\n", "@VirginAmerica I have lots of flights to book and your site it not working!!!! I've been on the phone waiting for over 10 minutes..........\n", "@united 3 hour delay plus a jetway that won't move. This biz traveler is never flying u again!\n" ] } ], "source": [ "# Get probabilities predictions in clear\n", "y_pred_test = best_model.predict_proba(X_test_transformer)\n", "\n", "# Let's see what are the top predictions based on the probabilities in y_pred_test\n", "print(\"5 most positive tweets (class 2):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_pred_test[:, 2].argsort()[-1 - i]])\n", "\n", "print(\"-\" * 100)\n", "\n", "print(\"5 most negative tweets (class 0):\")\n", "for i in range(5):\n", " print(text_X_test.iloc[y_pred_test[:, 0].argsort()[-1 - i]])" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 most positive (predicted) tweets that are actually negative (ground truth class 0):\n", "@united thanks for the link, now finally arrived in Brussels, 9 h after schedule...\n", "@USAirways as far as being delayed goes… Looks like tailwinds are going to make up for it. Good news!\n", "@united thanks for having changed me. Managed to arrive with only 8 hours of delay and exhausted\n", "@USAirways your saving grace was our flight attendant Dallas who was amazing. wish he would transfer to Delta where I would see him again\n", "@AmericanAir that luggage you forgot...#mia.....he just won an oscar😄💝💝💝\n", "----------------------------------------------------------------------------------------------------\n", "5 most negative (predicted) tweets that are actually positive (ground truth class 2):\n", "@united thanks for updating me about the 1+ hour delay the exact second I got to ATL. 🙅🙅🙅\n", "@SouthwestAir save mile to visit family in 2015 and this will impact how many times I can see my mother. I planned and you change the rules\n", "@JetBlue you don't remember our date Monday night back to NYC? #heartbroken\n", "@SouthwestAir hot stewardess flipped me off\n", "@SouthwestAir - We left iPad in a seat pocket. Filed lost item report. Received it exactly 1 week Late Flightr. Is that a record? #unbelievable\n" ] } ], "source": [ "# Now let's see where the model is wrong\n", "y_pred_test_0 = y_pred_test[y_test == 0]\n", "text_X_test_0 = text_X_test[y_test == 0]\n", "\n", "print(\"5 most positive (predicted) tweets that are actually negative (ground truth class 0):\")\n", "for i in range(5):\n", " print(text_X_test_0.iloc[y_pred_test_0[:, 2].argsort()[-1 - i]])\n", "\n", "print(\"-\" * 100)\n", "\n", "y_pred_test_2 = y_pred_test[y_test == 2]\n", "text_X_test_2 = text_X_test[y_test == 2]\n", "print(\"5 most negative (predicted) tweets that are actually positive (ground truth class 2):\")\n", "for i in range(5):\n", " print(text_X_test_2.iloc[y_pred_test_2[:, 0].argsort()[-1 - i]])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Interestingly, these misclassifications are not obvious and some actually look rather like mislabeled. Also, it seems that the model is having a hard time to find ironic tweets.\n", "\n", "Now we have our model trained which has some great accuracy. Let's have it predict over the encrypted representation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Sentiment Analysis of the Tweet with Fully Homomorphic Encryption\n", "\n", "Now that we have our model ready for FHE inference and our data ready for encryption let's use the model in a privacy preserving manner with FHE." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Compilation time: 5.8594 seconds\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 1/1 [00:00<00:00, 17.16it/s]" ] }, { "name": "stdout", "output_type": "stream", "text": [ "FHE inference time: 0.9319 seconds\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# Compile the model to get the FHE inference engine\n", "# (this may take a few minutes depending on the selected model)\n", "start = time.perf_counter()\n", "best_model.compile(X_train_transformer)\n", "end = time.perf_counter()\n", "print(f\"Compilation time: {end - start:.4f} seconds\")\n", "\n", "\n", "# Let's write a custom example and predict in FHE\n", "tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n", "X_tested_tweet = text_to_tensor(tested_tweet, transformer_model, tokenizer, device)\n", "clear_proba = best_model.predict_proba(X_tested_tweet)\n", "\n", "# Now let's predict with FHE over a single tweet and print the time it takes\n", "start = time.perf_counter()\n", "decrypted_proba = best_model.predict_proba(X_tested_tweet, fhe=\"execute\")\n", "end = time.perf_counter()\n", "fhe_exec_time = end - start\n", "print(f\"FHE inference time: {fhe_exec_time:.4f} seconds\")" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Probabilities from the FHE inference: [[0.05162184 0.04558276 0.90279541]]\n", "Probabilities from the clear model: [[0.05162184 0.04558276 0.90279541]]\n" ] } ], "source": [ "print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n", "print(f\"Probabilities from the clear model: {clear_proba}\")" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "DEPLOYMENT_DIR = Path(\"deployment\")\n", "DEPLOYMENT_DIR.mkdir(exist_ok=True)\n", "\n", "# Let's export the final model such that we can reuse it in a client/server environment\n", "\n", "# Serialize the model (for development only)\n", "with (DEPLOYMENT_DIR / \"serialized_model\").open(\"w\") as file:\n", " best_model.dump(file)\n", "\n", "# Export some data to be used for compilation \n", "X_train_numpy = X_train_transformer[:100]\n", "\n", "# Merge the two arrays in a pandas dataframe\n", "X_test_numpy_df = pd.DataFrame(X_train_numpy)\n", "\n", "# to csv\n", "X_test_numpy_df.to_csv(DEPLOYMENT_DIR / \"samples_for_compilation.csv\")\n", "\n", "# Let's save the model to be pushed to a server later\n", "from concrete.ml.deployment import FHEModelDev\n", "\n", "fhe_api = FHEModelDev(DEPLOYMENT_DIR / \"sentiment_fhe_model\", best_model)\n", "fhe_api.save(via_mlir=True)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>Accuracy</th>\n", " <th>Average Precision (positive)</th>\n", " <th>Average Precision (negative)</th>\n", " <th>Average Precision (neutral)</th>\n", " </tr>\n", " <tr>\n", " <th>Model</th>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " <th></th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>TF-IDF + XGBoost</th>\n", " <td>0.711749</td>\n", " <td>0.640422</td>\n", " <td>0.871891</td>\n", " <td>0.43486</td>\n", " </tr>\n", " <tr>\n", " <th>Transformer Only</th>\n", " <td>0.805328</td>\n", " <td>0.854827</td>\n", " <td>0.954804</td>\n", " <td>0.68011</td>\n", " </tr>\n", " <tr>\n", " <th>Transformer + XGBoost</th>\n", " <td>0.846311</td>\n", " <td>0.895930</td>\n", " <td>0.964674</td>\n", " <td>0.74489</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " Accuracy Average Precision (positive) \\\n", "Model \n", "TF-IDF + XGBoost 0.711749 0.640422 \n", "Transformer Only 0.805328 0.854827 \n", "Transformer + XGBoost 0.846311 0.895930 \n", "\n", " Average Precision (negative) \\\n", "Model \n", "TF-IDF + XGBoost 0.871891 \n", "Transformer Only 0.954804 \n", "Transformer + XGBoost 0.964674 \n", "\n", " Average Precision (neutral) \n", "Model \n", "TF-IDF + XGBoost 0.43486 \n", "Transformer Only 0.68011 \n", "Transformer + XGBoost 0.74489 " ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%matplotlib inline\n", "# Let's print the results obtained in this notebook\n", "df_results = pd.DataFrame(\n", " {\n", " \"Model\": [\"TF-IDF + XGBoost\", \"Transformer Only\", \"Transformer + XGBoost\"],\n", " \"Accuracy\": [accuracy_tfidf, accuracy_transformer_only, accuracy_transformer_xgboost],\n", " \"Average Precision (positive)\": [\n", " ap_positive_tfidf,\n", " ap_positive_transformer_only,\n", " ap_positive_transformer_xgboost,\n", " ],\n", " \"Average Precision (negative)\": [\n", " ap_negative_tfidf,\n", " ap_negative_transformer_only,\n", " ap_negative_transformer_xgboost,\n", " ],\n", " \"Average Precision (neutral)\": [\n", " ap_neutral_tfidf,\n", " ap_neutral_transformer_only,\n", " ap_neutral_transformer_xgboost,\n", " ],\n", " }\n", ")\n", "df_results.set_index(\"Model\", inplace=True)\n", "df_results # pylint: disable=pointless-statement" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conclusion\n", "\n", "In this notebook we presented two different ways to represent a text.\n", "1. Using TF-IDF vectorization\n", "2. Using the hidden layers from a transformer\n", "\n", "Both representation are then used to train a machine learning model will run in FHE (here XGBoost)\n", "\n", "Once the model is trained, clients can send encrypted text representation to the server to get a sentiment analysis done and they receive the probability for each class (negative, neutral and positive) in an encrypted format which can then be decrypted by the client. For now, all the FHE magic (encrypt, predict and decrypt) is done within the `predict_proba` function with the argument `execute_in_fhe=True`. In the next release, an API will be provided to split the server/client parts.\n", "\n", "Regarding the FHE execution times, the final XGboost model can predict over an encrypted data point in ~40 seconds. This will change depending on the number of threads available. In the future, more hardware acceleration will be available to speed up the execution time.\n", "\n", "It seems that the combination of a transformer (thanks Huggingface!) with a \"simpler\" model such as XGBoost works pretty well. Thanks to Concrete-ML library, we can easily use this text representation on the client machine and then encrypt it to send it to a remote server without having to deal with a transformer runtime in FHE." ] } ], "metadata": { "execution": { "timeout": 10800 }, "kernelspec": { "display_name": ".venv", "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.10.11" } }, "nbformat": 4, "nbformat_minor": 2}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401"""A gradio app. that runs locally (analytics=False and share=False) about sentiment analysis on tweets."""
import gradio as grfrom transformer_vectorizer import TransformerVectorizerfrom concrete.ml.deployment import FHEModelClientimport numpyimport osfrom pathlib import Pathimport requestsimport jsonimport base64import subprocessimport shutilimport time
# This repository's directoryREPO_DIR = Path(__file__).parent
subprocess.Popen(["anvil", "-p", "3030"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "server:app", "--port", "8000"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "zkml_non_encrypted:app", "--port", "8001"], cwd=REPO_DIR)subprocess.Popen(["uvicorn", "zkml_encrypted:app", "--port", "8002"], cwd=REPO_DIR)
# Wait 30 sec for the server to starttime.sleep(30)
# Encrypted data limit for the browser to display# (encrypted data is too large to display in the browser)ENCRYPTED_DATA_BROWSER_LIMIT = 500N_USER_KEY_STORED = 20FHE_MODEL_PATH = "deployment/sentiment_fhe_model"
print("Loading the transformer model...")
# Initialize the transformer vectorizertransformer_vectorizer = TransformerVectorizer()
def clean_tmp_directory(): # Allow 20 user keys to be stored. # Once that limitation is reached, deleted the oldest. path_sub_directories = sorted([f for f in Path(".fhe_keys/").iterdir() if f.is_dir()], key=os.path.getmtime)
user_ids = [] if len(path_sub_directories) > N_USER_KEY_STORED: n_files_to_delete = len(path_sub_directories) - N_USER_KEY_STORED for p in path_sub_directories[:n_files_to_delete]: user_ids.append(p.name) shutil.rmtree(p)
list_files_tmp = Path("tmp/").iterdir() # Delete all files related to user_id for file in list_files_tmp: for user_id in user_ids: if file.name.endswith(f"{user_id}.npy"): file.unlink()
def keygen(): # Clean tmp directory if needed clean_tmp_directory()
print("Initializing FHEModelClient...")
# Let's create a user_id user_id = numpy.random.randint(0, 2 ** 32) fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") fhe_api.load()
# Generate a fresh key fhe_api.generate_private_and_evaluation_keys(force=True) evaluation_key = fhe_api.get_serialized_evaluation_keys()
# Save evaluation_key in a file, since too large to pass through regular Gradio # buttons, https://github.com/gradio-app/gradio/issues/1877 numpy.save(f"tmp/tmp_evaluation_key_{user_id}.npy", evaluation_key)
return [list(evaluation_key)[:ENCRYPTED_DATA_BROWSER_LIMIT], user_id]
def encode_quantize_encrypt(text, user_id): if not user_id: raise gr.Error("You need to generate FHE keys first.")
fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") fhe_api.load() encodings = transformer_vectorizer.transform([text]) quantized_encodings = fhe_api.model.quantize_input(encodings).astype(numpy.uint8) encrypted_quantized_encoding = fhe_api.quantize_encrypt_serialize(encodings)
# Save encrypted_quantized_encoding in a file, since too large to pass through regular Gradio # buttons, https://github.com/gradio-app/gradio/issues/1877 numpy.save(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy", encrypted_quantized_encoding)
# Compute size encrypted_quantized_encoding_shorten = list(encrypted_quantized_encoding) encrypted_quantized_encoding_shorten_hex = ''.join(f'{i:02x}' for i in encrypted_quantized_encoding_shorten) return ( encodings[0], quantized_encodings[0], encrypted_quantized_encoding_shorten_hex, )
def run_fhe(user_id): encoded_data_path = Path(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy") if not user_id: raise gr.Error("You need to generate FHE keys first.") if not encoded_data_path.is_file(): raise gr.Error("No encrypted data was found. Encrypt the data before trying to predict.")
# Read encrypted_quantized_encoding from the file encrypted_quantized_encoding = numpy.load(encoded_data_path)
# Read evaluation_key from the file evaluation_key = numpy.load(f"tmp/tmp_evaluation_key_{user_id}.npy")
# Use base64 to encode the encodings and evaluation key encrypted_quantized_encoding = base64.b64encode(encrypted_quantized_encoding).decode() encoded_evaluation_key = base64.b64encode(evaluation_key).decode()
query = {} query["evaluation_key"] = encoded_evaluation_key query["encrypted_encoding"] = encrypted_quantized_encoding headers = {"Content-type": "application/json"} response = requests.post( "http://localhost:8000/predict_sentiment", data=json.dumps(query), headers=headers ) encrypted_prediction = base64.b64decode(response.json()["encrypted_prediction"])
# Save encrypted_prediction in a file, since too large to pass through regular Gradio # buttons, https://github.com/gradio-app/gradio/issues/1877 numpy.save(f"tmp/tmp_encrypted_prediction_{user_id}.npy", encrypted_prediction) encrypted_prediction_shorten = list(encrypted_prediction) encrypted_prediction_shorten_hex = ''.join(f'{i:02x}' for i in encrypted_prediction_shorten) return encrypted_prediction_shorten_hex
def decrypt_prediction(user_id): encoded_data_path = Path(f"tmp/tmp_encrypted_prediction_{user_id}.npy") if not user_id: raise gr.Error("You need to generate FHE keys first.") if not encoded_data_path.is_file(): raise gr.Error("No encrypted prediction was found. Run the prediction over the encrypted data first.")
# Read encrypted_prediction from the file encrypted_prediction = numpy.load(encoded_data_path).tobytes()
fhe_api = FHEModelClient(FHE_MODEL_PATH, f".fhe_keys/{user_id}") fhe_api.load()
# We need to retrieve the private key that matches the client specs (see issue #18) fhe_api.generate_private_and_evaluation_keys(force=False)
predictions = fhe_api.deserialize_decrypt_dequantize(encrypted_prediction) return { "negative": predictions[0][0], "neutral": predictions[0][1], "positive": predictions[0][2], }
def get_zk_proof_non_encrypted(text): headers = {"Content-type": "application/json"} query = {"text": text} response = requests.post( "http://localhost:8001/get_zk_proof", data=json.dumps(query), headers=headers ) result = response.json()
sentiment = "" if result["output"][0] > 0.5: sentiment = "negative" elif result["output"][1] > 0.5: sentiment = "neutral" else: sentiment = "positive"
return sentiment, result["proof"], result["verify_contract_addr"]
def get_zk_proof_encrypted(user_id): encoded_data_path = Path(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy") if not user_id: raise gr.Error("You need to generate FHE keys first.") if not encoded_data_path.is_file(): raise gr.Error("No encrypted data was found. Encrypt the data before trying to predict.")
# Read encrypted_quantized_encoding from the file encrypted_quantized_encoding = numpy.load(encoded_data_path)
# Read evaluation_key from the file evaluation_key = numpy.load(f"tmp/tmp_evaluation_key_{user_id}.npy")
# Use base64 to encode the encodings and evaluation key encrypted_quantized_encoding = base64.b64encode(encrypted_quantized_encoding).decode() encoded_evaluation_key = base64.b64encode(evaluation_key).decode()
query = {} query["evaluation_key"] = encoded_evaluation_key query["encrypted_encoding"] = encrypted_quantized_encoding headers = {"Content-type": "application/json"} response = requests.post( "http://localhost:8002/get_zk_proof", data=json.dumps(query), headers=headers ) result = response.json() return result["output"], result["proof"], result["verify_contract_addr"]
demo = gr.Blocks()
print("Starting the demo...")with demo: gr.Markdown( """<p align="center"> <img width=200 src="https://user-images.githubusercontent.com/5758427/197816413-d9cddad3-ba38-4793-847d-120975e1da11.png"></p>
<h2 align="center">Sentiment Analysis On Encrypted Data Using Homomorphic Encryption</h2>
<p align="center"> <a href="https://github.com/zama-ai/concrete-ml"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197972109-faaaff3e-10e2-4ab6-80f5-7531f7cfb08f.png">Concrete-ML</a> — <a href="https://docs.zama.ai/concrete-ml"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197976802-fddd34c5-f59a-48d0-9bff-7ad1b00cb1fb.png">Documentation</a> — <a href="https://zama.ai/community"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197977153-8c9c01a7-451a-4993-8e10-5a6ed5343d02.png">Community</a> — <a href="https://twitter.com/zama_fhe"> <img style="vertical-align: middle; display:inline-block; margin-right: 3px;" width=15 src="https://user-images.githubusercontent.com/5758427/197975044-bab9d199-e120-433b-b3be-abd73b211a54.png">@zama_fhe</a></p>
<p align="center"> <img src="https://user-images.githubusercontent.com/56846628/219329304-6868be9e-5ce8-4279-9123-4cb1bc0c2fb5.png" width="60%" height="60%"></p>""" )
gr.Markdown( """ <p align="center"> </p> <p align="center"> </p> """ )
gr.Markdown("## Notes") gr.Markdown( """ - The private key is used to encrypt and decrypt the data and shall never be shared. - The evaluation key is a public key that the server needs to process encrypted data. """ )
gr.Markdown("# Step 1: Generate the keys")
b_gen_key_and_install = gr.Button("Generate the keys and send public part to server")
evaluation_key = gr.Textbox( label="Evaluation key (truncated):", max_lines=4, interactive=False, )
user_id = gr.Textbox( label="", max_lines=4, interactive=False, visible=False )
gr.Markdown("# Step 2: Provide a message") gr.Markdown("## Client side") gr.Markdown( "Enter a sensitive text message you received and would like to do sentiment analysis on (ideas: the last text message of your boss.... or lover)." ) text = gr.Textbox(label="Enter a message:", value="I really like your work recently")
gr.Markdown("# Step 3: Encode the message with the private key") b_encode_quantize_text = gr.Button( "Encode, quantize and encrypt the text with transformer vectorizer, and send to server" )
with gr.Row(): encoding = gr.Textbox( label="Transformer representation:", max_lines=4, interactive=False, ) quantized_encoding = gr.Textbox( label="Quantized transformer representation:", max_lines=4, interactive=False ) encrypted_quantized_encoding = gr.Textbox( label="Encrypted quantized transformer representation (truncated):", max_lines=4, interactive=False, )
gr.Markdown("# Step 4: Run the FHE evaluation") gr.Markdown("## Server side") gr.Markdown( "The encrypted value is received by the server. Thanks to the evaluation key and to FHE, the server can compute the (encrypted) prediction directly over encrypted values. Once the computation is finished, the server returns the encrypted prediction to the client." )
b_run_fhe = gr.Button("Run FHE execution there") encrypted_prediction = gr.Textbox( label="Encrypted prediction (truncated):", max_lines=4, interactive=False, )
gr.Markdown("# Step 5: Decrypt the sentiment") gr.Markdown("## Client side") gr.Markdown( "The encrypted sentiment is sent back to client, who can finally decrypt it with its private key. Only the client is aware of the original tweet and the prediction." ) b_decrypt_prediction = gr.Button("Decrypt prediction")
labels_sentiment = gr.Label(label="Sentiment:")
gr.Markdown("# Step 6: Get ZK Proof(non-encrypted input)") gr.Markdown("## Server side") gr.Markdown( "Get zero-knowledge proof of the sentiment analysis computation (for non-encrypted input)." ) b_get_zk_proof_non_encrypted = gr.Button("Get ZK Proof(non-encrypted input)")
with gr.Row(): zk_sentiment_non_encrypted = gr.Textbox( label="Sentiment:", max_lines=1, interactive=False, ) zk_proof_non_encrypted = gr.Textbox( label="ZK Proof:", max_lines=4, interactive=False, ) zk_contract_non_encrypted = gr.Textbox( label="Verify Contract Address:", max_lines=1, interactive=False, )
gr.Markdown("# Step 6: Get ZK Proof(encrypted input)") gr.Markdown("## Server side") gr.Markdown( "Get zero-knowledge proof of the sentiment analysis computation (for encrypted input)." ) b_get_zk_proof_encrypted = gr.Button("Get ZK Proof(encrypted input)")
with gr.Row(): zk_encrypted_prediction = gr.Textbox( label="Encrypted Prediction(same as Step 4 output):", max_lines=1, interactive=False, ) zk_proof_encrypted = gr.Textbox( label="ZK Proof:", max_lines=4, interactive=False, ) zk_contract_encrypted = gr.Textbox( label="Verify Contract Address:", max_lines=1, interactive=False, )
# Button for key generation b_gen_key_and_install.click(keygen, inputs=[], outputs=[evaluation_key, user_id])
# Button to quantize and encrypt b_encode_quantize_text.click( encode_quantize_encrypt, inputs=[text, user_id], outputs=[ encoding, quantized_encoding, encrypted_quantized_encoding, ], )
# Button to send the encodings to the server using post at (localhost:8000/predict_sentiment) b_run_fhe.click(run_fhe, inputs=[user_id], outputs=[encrypted_prediction])
# Button to decrypt the prediction on the client b_decrypt_prediction.click(decrypt_prediction, inputs=[user_id], outputs=[labels_sentiment])
# Button to get ZK proof(non encrypted) b_get_zk_proof_non_encrypted.click(get_zk_proof_non_encrypted, inputs=[text], outputs=[zk_sentiment_non_encrypted, zk_proof_non_encrypted, zk_contract_non_encrypted])
# Button to get ZK proof(encrypted) b_get_zk_proof_encrypted.click(get_zk_proof_encrypted, inputs=[user_id], outputs=[zk_encrypted_prediction, zk_proof_encrypted, zk_contract_encrypted])
gr.Markdown( "The app was built with [Concrete-ML](https://github.com/zama-ai/concrete-ml), a Privacy-Preserving Machine Learning (PPML) open-source set of tools by [Zama](https://zama.ai/). Try it yourself and don't forget to star on Github ⭐." )demo.launch(share=False)1234567891011121314151617181920212223242526272829303132333435import pandas as pdfrom concrete.ml.deployment import FHEModelDevfrom concrete.ml.common.serialization.loaders import loadimport shutilfrom pathlib import Path
script_dir = Path(__file__).parent
DEPLOYMENT_DIR = script_dir / "deployment"
print("Compiling the model...")
with (DEPLOYMENT_DIR / "serialized_model").open("r") as file: model = load(file)
# Load the data from the csv file to be used for compilationdata = pd.read_csv(DEPLOYMENT_DIR / "samples_for_compilation.csv", index_col=0).values
# Compile the modelmodel.compile(data)
dev_model_path = DEPLOYMENT_DIR / "sentiment_fhe_model"
# Delete the deployment folder if it existif dev_model_path.is_dir(): shutil.rmtree(dev_model_path)
fhe_api = FHEModelDev( model=model, path_dir=dev_model_path)fhe_api.save(via_mlir=True)
print("Done!")123version https://git-lfs.github.com/spec/v1oid sha256:18d71ff210dfcfaeffa62d500eea3930694f2ded438589baa4458f971479ee31size 1509958123version https://git-lfs.github.com/spec/v1oid sha256:23a0a8ef429c6d990fda93aa7ae786353968b1ec366326c02acbf8897b4f431bsize 25821{"concrete-python": "2.8.1", "concrete-ml": "1.7.0", "python": "3.10.11"}123456789101112131415#!/usr/bin/env bash
set -e
# You need to install kaggle using pip and then have a valid ~/.kaggle/kaggle.json, that you can # generate from "Create new API token" on your account page in kaggle.com# Alternatively, the dataset can be downloaded manually at # https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentimentrm -rf local_datasetsmkdir local_datasetscd local_datasets
kaggle datasets download -d crowdflower/twitter-airline-sentiment
unzip twitter-airline-sentiment.zip -d twitter-airline-sentiment123456789concrete-ml==1.7.0gradio==3.50.2pandas==2.0.3transformers==4.36.0 jupyter==1.0.0urllib3==1.25.4more-itertools==10.5.0ezkl==11.2.2httpx[socks]123456789101112131415161718192021222324252627282930313233343536373839"""Server that will listen for GET requests from the client."""import json
from fastapi import FastAPIfrom concrete.ml.deployment import FHEModelServerfrom pydantic import BaseModelimport base64from pathlib import Path
current_dir = Path(__file__).parent
# Load the modelfhe_model = FHEModelServer("deployment/sentiment_fhe_model")
class PredictRequest(BaseModel): evaluation_key: str encrypted_encoding: str
# Initialize an instance of FastAPIapp = FastAPI()
# Define the default route@app.get("/")def root(): return {"message": "Welcome to Your Sentiment Classification FHE Model Server!"}
@app.post("/predict_sentiment")def predict_sentiment(query: PredictRequest): encrypted_encoding = base64.b64decode(query.encrypted_encoding) evaluation_key = base64.b64decode(query.evaluation_key) prediction = fhe_model.run(encrypted_encoding, evaluation_key)
# Encode base64 the prediction encoded_prediction = base64.b64encode(prediction).decode() return {"encrypted_prediction": encoded_prediction}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# Let's import a few requirementsimport torchfrom transformers import AutoModelForSequenceClassification, AutoTokenizerimport numpy
class TransformerVectorizer: def __init__(self): # Load the tokenizer (converts text to tokens) self.tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment-latest")
# Load the pre-trained model self.transformer_model = AutoModelForSequenceClassification.from_pretrained( "cardiffnlp/twitter-roberta-base-sentiment-latest" ) self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
def text_to_tensor( self, texts: list, ) -> numpy.ndarray: """Function that transforms a list of texts to their learned representation. Args: list_text_X (list): List of texts to be transformed.
Returns: numpy.ndarray: Transformed list of texts. """ # First, tokenize all the input text tokenized_text_X_train = self.tokenizer.batch_encode_plus( texts, return_tensors="pt" )["input_ids"]
# Depending on the hardware used, the number of examples to be processed can be reduced # Here we split the data into 100 examples per batch tokenized_text_X_train_split = torch.split(tokenized_text_X_train, split_size_or_sections=50)
# Send the model to the device transformer_model = self.transformer_model.to(self.device) output_hidden_states_list = []
for tokenized_x in tokenized_text_X_train_split: # Pass the tokens through the transformer model and get the hidden states # Only keep the last hidden layer state for now output_hidden_states = transformer_model(tokenized_x.to(self.device), output_hidden_states=True)[ 1 ][-1] # Average over the tokens axis to get a representation at the text level. output_hidden_states = output_hidden_states.mean(dim=1) output_hidden_states = output_hidden_states.detach().cpu().numpy() output_hidden_states_list.append(output_hidden_states)
self.encodings = numpy.concatenate(output_hidden_states_list, axis=0) return self.encodings
def transform(self, texts: list): return self.text_to_tensor(texts)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212# https://docs.ezkl.xyz/# https://colab.research.google.com/github/zkonduit/ezkl/blob/main/examples/notebooks/simple_demo_all_public.ipynbimport structimport uuid
import numpy as npfrom torch import nnimport ezklimport osimport jsonimport torchimport base64from concrete.ml.deployment import FHEModelServerfrom fastapi import FastAPIfrom pydantic import BaseModel
app = FastAPI()
evaluation_key = None
# Defines the modelclass AIModel(nn.Module): def __init__(self): super(AIModel, self).__init__()
# Load the model self.fhe_model = FHEModelServer("deployment/sentiment_fhe_model")
def forward(self, x): print(f"forward input: {x}")
# Convert to bytes x = x[0] _encrypted_encoding = x.numpy().tobytes() prediction = self.fhe_model.run(_encrypted_encoding, evaluation_key) print(f"forward prediction hex: {prediction.hex()}")
byte_tensor = torch.tensor(list(prediction), dtype=torch.uint8) print(f"tensor_output: {byte_tensor}")
return byte_tensor
class ZKProofRequest(BaseModel): encrypted_encoding: str evaluation_key: str
circuit = AIModel()
@app.post("/get_zk_proof")async def get_zk_proof(request: ZKProofRequest): request.encrypted_encoding = base64.b64decode(request.encrypted_encoding) request.evaluation_key = base64.b64decode(request.evaluation_key)
global evaluation_key evaluation_key = request.evaluation_key
folder_path = f"zkml_encrypted/{str(uuid.uuid4())}" if not os.path.exists(folder_path): os.makedirs(folder_path)
model_path = os.path.join(f'{folder_path}/network.onnx') compiled_model_path = os.path.join(f'{folder_path}/network.compiled') pk_path = os.path.join(f'{folder_path}/test.pk') vk_path = os.path.join(f'{folder_path}/test.vk') settings_path = os.path.join(f'{folder_path}/settings.json')
witness_path = os.path.join(f'{folder_path}/witness.json') input_data_path = os.path.join(f'{folder_path}/input.json') srs_path = os.path.join(f'{folder_path}/kzg14.srs') output_path = os.path.join(f'{folder_path}/output.json')
# After training, export to onnx (network.onnx) and create a data file (input.json) x = torch.tensor(list([request.encrypted_encoding]), dtype=torch.uint8)
# Flips the neural net into inference mode circuit.eval()
# Get the output of the model with torch.no_grad(): output = circuit(x) # Save the output to a file output_data = output.detach().numpy().tolist() with open(output_path, 'w') as f: json.dump(output_data, f)
print("start") # Export the model torch.onnx.export(circuit, # model being run x, # model input (or a tuple for multiple inputs) model_path, # where to save the model (can be a file or file-like object) export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}}) print("end")
data = dict(input_data=x.tolist())
# Serialize data into file: json.dump(data, open(input_data_path, 'w'))
py_run_args = ezkl.PyRunArgs() py_run_args.input_visibility = "public" py_run_args.output_visibility = "public" py_run_args.param_visibility = "fixed" # "fixed" for params means that the committed to params are used for all proofs
res = ezkl.gen_settings(model_path, settings_path, py_run_args=py_run_args) assert res is True
cal_path = os.path.join(f"{folder_path}/calibration.json")
# Serialize data into file: json.dump(data, open(cal_path, 'w'))
await ezkl.calibrate_settings(cal_path, model_path, settings_path, "resources")
res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path) assert res is True
# srs path res = await ezkl.get_srs(settings_path, srs_path=srs_path) assert res is True
# now generate the witness file
res = await ezkl.gen_witness(input_data_path, compiled_model_path, witness_path) assert os.path.isfile(witness_path)
# HERE WE SETUP THE CIRCUIT PARAMS # WE GOT KEYS # WE GOT CIRCUIT PARAMETERS # EVERYTHING ANYONE HAS EVER NEEDED FOR ZK
res = ezkl.setup( compiled_model_path, vk_path, pk_path, srs_path )
assert res is True assert os.path.isfile(vk_path) assert os.path.isfile(pk_path) assert os.path.isfile(settings_path)
# GENERATE A PROOF proof_path = os.path.join(f'{folder_path}/test.pf') res = ezkl.prove( witness_path, compiled_model_path, pk_path, proof_path, "single", srs_path ) assert os.path.isfile(proof_path)
# VERIFY IT ON LOCAL res = ezkl.verify( proof_path, settings_path, vk_path, srs_path ) assert res is True print("verified on local")
# VERIFY IT ON CHAIN verify_sol_code_path = os.path.join(f'{folder_path}/verify.sol') verify_sol_abi_path = os.path.join(f'{folder_path}/verify.abi') res = await ezkl.create_evm_verifier( vk_path, settings_path, verify_sol_code_path, verify_sol_abi_path, srs_path ) assert res is True verify_contract_addr_file = f"{folder_path}/addr.txt" rpc_url = "http://103.231.86.33:10219" await ezkl.deploy_evm( addr_path=verify_contract_addr_file, rpc_url=rpc_url, sol_code_path=verify_sol_code_path ) if os.path.exists(verify_contract_addr_file): with open(verify_contract_addr_file, 'r') as file: verify_contract_addr = file.read() else: print(f"error: File {verify_contract_addr_file} does not exist.") return {"error": "Contract address file not found"} # TODO verify failed. maybe need to change the x res = await ezkl.verify_evm( addr_verifier=verify_contract_addr, proof_path=proof_path, rpc_url=rpc_url ) assert res is True print("verified on chain")
# Read proof file content with open(proof_path, 'rb') as f: proof_content = base64.b64encode(f.read()).decode('utf-8')
return {"output": output_data, "proof": proof_content, "verify_contract_addr": verify_contract_addr}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245# https://docs.ezkl.xyz/# https://colab.research.google.com/github/zkonduit/ezkl/blob/main/examples/notebooks/simple_demo_all_public.ipynbimport pickleimport structimport uuid
import numpy as npimport pandas as pdfrom sklearn.model_selection import GridSearchCV, train_test_splitfrom torch import nnimport ezklimport osimport jsonimport torchimport base64from concrete.ml.deployment import FHEModelServerfrom concrete.ml.sklearn import XGBClassifierimport tqdmfrom transformers import AutoModelForSequenceClassification, AutoTokenizerfrom fastapi import FastAPIfrom pydantic import BaseModel
app = FastAPI()
evaluation_key = None
# Defines the modelclass AIWordsModel(nn.Module): def __init__(self): super(AIWordsModel, self).__init__()
print("init ZK AIWordsModel")
# Load the model self.model = XGBClassifier() train = pd.read_csv("./local_datasets/twitter-airline-sentiment/Tweets.csv", index_col=0) text_X = train["text"] y = train["airline_sentiment"].replace(["negative", "neutral", "positive"], [0, 1, 2])
# Load the tokenizer and model self.device = "cuda:0" if torch.cuda.is_available() else "cpu" self.tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment-latest") self.transformer_model = AutoModelForSequenceClassification.from_pretrained( "cardiffnlp/twitter-roberta-base-sentiment-latest" ).to(self.device)
text_X_train, text_X_test, y_train, y_test = train_test_split( text_X, y, test_size=0.1, random_state=42 ) X_train_transformer = self.text_to_tensor(text_X_train.tolist(), self.transformer_model, self.tokenizer, self.device)
with open("deployment/serialized_model_zkml", 'rb') as file: # Open in binary read mode loaded_data = pickle.load(file) self.model.load_dict(loaded_data) parameters = {"n_bits": [2, 3], "max_depth": [1], "n_estimators": [10, 30, 50]} grid_search2 = GridSearchCV(self.model, parameters, cv=5, scoring="accuracy") grid_search2.fit(X_train_transformer, y_train) self.best_model2 = grid_search2.best_estimator_ self.best_model2.load_dict(loaded_data) self.best_model2.compile(X_train_transformer)
print(f"loaded_data finished")
def forward(self, x): prediction = self.best_model2.predict_proba(x, fhe="execute")
prediction_tensor = torch.tensor(prediction, dtype=torch.float32) prediction_tensor = prediction_tensor.squeeze() # Remove extra dimensions if any
return prediction_tensor
# Function to convert text to tensor def text_to_tensor(self, list_text, transformer_model, tokenizer, device): tokenized_text = [tokenizer.encode(text, return_tensors="pt") for text in list_text] output_hidden_states_list = [None] * len(tokenized_text)
for i, tokenized_x in enumerate(tqdm.tqdm(tokenized_text)): output_hidden_states = transformer_model(tokenized_x.to(device), output_hidden_states=True)[1][-1] output_hidden_states = output_hidden_states.mean(dim=1).detach().cpu().numpy() output_hidden_states_list[i] = output_hidden_states
return np.concatenate(output_hidden_states_list, axis=0)
class ZKProofRequest(BaseModel): text: str
circuit = AIWordsModel()
@app.post("/get_zk_proof")async def get_zk_proof(request: ZKProofRequest): folder_path = f"zkml_non_encrypted/{str(uuid.uuid4())}" if not os.path.exists(folder_path): os.makedirs(folder_path)
model_path = os.path.join(f'{folder_path}/network.onnx') compiled_model_path = os.path.join(f'{folder_path}/network.compiled') pk_path = os.path.join(f'{folder_path}/test.pk') vk_path = os.path.join(f'{folder_path}/test.vk') settings_path = os.path.join(f'{folder_path}/settings.json')
witness_path = os.path.join(f'{folder_path}/witness.json') input_data_path = os.path.join(f'{folder_path}/input.json') srs_path = os.path.join(f'{folder_path}/kzg14.srs') output_path = os.path.join(f'{folder_path}/output.json')
# After training, export to onnx (network.onnx) and create a data file (input.json) words = [request.text] x_list = circuit.text_to_tensor(words, circuit.transformer_model, circuit.tokenizer, circuit.device) x = torch.tensor(x_list, dtype=torch.float32)
# Flips the neural net into inference mode circuit.eval()
# Get the output of the model with torch.no_grad(): output = circuit(x) # Save the output to a file output_data = output.detach().numpy().tolist() with open(output_path, 'w') as f: json.dump(output_data, f)
# Export the model torch.onnx.export(circuit, # model being run x, # model input (or a tuple for multiple inputs) model_path, # where to save the model (can be a file or file-like object) export_params=True, # store the trained parameter weights inside the model file opset_version=10, # the ONNX version to export the model to do_constant_folding=True, # whether to execute constant folding for optimization input_names=['input'], # the model's input names output_names=['output'], # the model's output names dynamic_axes={'input': {0: 'batch_size'}, # variable length axes 'output': {0: 'batch_size'}})
data = dict(input_data=x.tolist())
# Serialize data into file: json.dump(data, open(input_data_path, 'w'))
py_run_args = ezkl.PyRunArgs() py_run_args.input_visibility = "public" py_run_args.output_visibility = "public" py_run_args.param_visibility = "fixed" # "fixed" for params means that the committed to params are used for all proofs
res = ezkl.gen_settings(model_path, settings_path, py_run_args=py_run_args) assert res is True
cal_path = os.path.join(f"{folder_path}/calibration.json")
# Serialize data into file: json.dump(data, open(cal_path, 'w'))
await ezkl.calibrate_settings(cal_path, model_path, settings_path, "resources")
res = ezkl.compile_circuit(model_path, compiled_model_path, settings_path) assert res is True
# srs path res = await ezkl.get_srs(settings_path, srs_path=srs_path) assert res is True
# now generate the witness file res = await ezkl.gen_witness(input_data_path, compiled_model_path, witness_path) assert os.path.isfile(witness_path)
# HERE WE SETUP THE CIRCUIT PARAMS # WE GOT KEYS # WE GOT CIRCUIT PARAMETERS # EVERYTHING ANYONE HAS EVER NEEDED FOR ZK
res = ezkl.setup( compiled_model_path, vk_path, pk_path, srs_path )
assert res is True assert os.path.isfile(vk_path) assert os.path.isfile(pk_path) assert os.path.isfile(settings_path)
# GENERATE A PROOF proof_path = os.path.join(f'{folder_path}/test.pf') res = ezkl.prove( witness_path, compiled_model_path, pk_path, proof_path, "single", srs_path ) assert os.path.isfile(proof_path)
# VERIFY IT ON LOCAL res = ezkl.verify( proof_path, settings_path, vk_path, srs_path ) assert res is True print("verified on local")
# VERIFY IT ON CHAIN verify_sol_code_path = os.path.join(f'{folder_path}/verify.sol') verify_sol_abi_path = os.path.join(f'{folder_path}/verify.abi') res = await ezkl.create_evm_verifier( vk_path, settings_path, verify_sol_code_path, verify_sol_abi_path, srs_path ) assert res is True verify_contract_addr_file = f"{folder_path}/addr.txt" rpc_url = "http://103.231.86.33:10219" await ezkl.deploy_evm( addr_path=verify_contract_addr_file, rpc_url=rpc_url, sol_code_path=verify_sol_code_path ) if os.path.exists(verify_contract_addr_file): with open(verify_contract_addr_file, 'r') as file: verify_contract_addr = file.read() else: print(f"error: File {verify_contract_addr_file} does not exist.") return {"error": "Contract address file not found"} res = await ezkl.verify_evm( addr_verifier=verify_contract_addr, proof_path=proof_path, rpc_url=rpc_url ) assert res is True print("verified on chain")
# Read proof file content with open(proof_path, 'rb') as f: proof_content = base64.b64encode(f.read()).decode('utf-8')
return {"output": output_data, "proof": proof_content, "verify_contract_addr": verify_contract_addr}183 unmodified lines184185186187188189190183 unmodified lines)assert res is Trueverify_contract_addr_file = f"{folder_path}/addr.txt"rpc_url = "http://127.0.0.1:3030"await ezkl.deploy_evm(addr_path=verify_contract_addr_file,rpc_url=rpc_url,183 unmodified lines184185186187188189190183 unmodified lines)assert res is Trueverify_contract_addr_file = f"{folder_path}/addr.txt"rpc_url = "http://103.231.86.33:10219"await ezkl.deploy_evm(addr_path=verify_contract_addr_file,rpc_url=rpc_url,
63 unmodified lines64656667686970717273747576777849 unmodified lines1281291301311321331345 unmodified lines14014114214314414514677 unmodified lines22422522622722822923063 unmodified linesprint(f"loaded_data finished")def forward(self, x):print(f"forward input: {x}")prediction = self.best_model2.predict_proba(x, fhe="execute")print(f"prediction: {prediction}")prediction_tensor = torch.tensor(prediction, dtype=torch.float32)prediction_tensor = prediction_tensor.squeeze() # Remove extra dimensions if anyprint(f"tensor_output: {prediction_tensor}")return prediction_tensor# Function to convert text to tensor49 unmodified lineswith open(output_path, 'w') as f:json.dump(output_data, f)print("start")# Export the modeltorch.onnx.export(circuit, # model being runx, # model input (or a tuple for multiple inputs)5 unmodified linesoutput_names=['output'], # the model's output namesdynamic_axes={'input': {0: 'batch_size'}, # variable length axes'output': {0: 'batch_size'}})print("end")data = dict(input_data=x.tolist())77 unmodified lines)assert res is Trueverify_contract_addr_file = f"{folder_path}/addr.txt"rpc_url = "http://127.0.0.1:3030"await ezkl.deploy_evm(addr_path=verify_contract_addr_file,rpc_url=rpc_url,63 unmodified lines646566676869707172737449 unmodified lines1241251261271281295 unmodified lines13513613713813914077 unmodified lines21821922022122222322463 unmodified linesprint(f"loaded_data finished")def forward(self, x):prediction = self.best_model2.predict_proba(x, fhe="execute")prediction_tensor = torch.tensor(prediction, dtype=torch.float32)prediction_tensor = prediction_tensor.squeeze() # Remove extra dimensions if anyreturn prediction_tensor# Function to convert text to tensor49 unmodified lineswith open(output_path, 'w') as f:json.dump(output_data, f)# Export the modeltorch.onnx.export(circuit, # model being runx, # model input (or a tuple for multiple inputs)5 unmodified linesoutput_names=['output'], # the model's output namesdynamic_axes={'input': {0: 'batch_size'}, # variable length axes'output': {0: 'batch_size'}})data = dict(input_data=x.tolist())77 unmodified lines)assert res is Trueverify_contract_addr_file = f"{folder_path}/addr.txt"rpc_url = "http://103.231.86.33:10219"await ezkl.deploy_evm(addr_path=verify_contract_addr_file,rpc_url=rpc_url,
app.py+1-1
hf_repo/.github/workflows/sync_to_hf.ymlAdded+43
hf_repo/deployment/serialized_model_zkmlAdded
hf_repo/hf_repo/.gitattributesAdded+33
hf_repo/hf_repo/.gitignoreAdded+9
hf_repo/hf_repo/README.mdAdded+54
hf_repo/hf_repo/SentimentClassification.ipynbAdded+1053
hf_repo/hf_repo/app.pyAdded+401
hf_repo/hf_repo/compile.pyAdded+35
hf_repo/hf_repo/deployment/samples_for_compilation.csvAdded
hf_repo/hf_repo/deployment/sentiment_fhe_model/client.zipAdded+3
hf_repo/hf_repo/deployment/sentiment_fhe_model/server.zipAdded+3
hf_repo/hf_repo/deployment/sentiment_fhe_model/versions.jsonAdded+1
hf_repo/hf_repo/deployment/serialized_modelAdded
hf_repo/hf_repo/download_data.shAdded+15
hf_repo/hf_repo/requirements.txtAdded+9
hf_repo/hf_repo/sentiment_analysis_banner.pngAdded

hf_repo/hf_repo/server.pyAdded+39
hf_repo/hf_repo/transformer_vectorizer.pyAdded+58
hf_repo/zkml_encrypted.pyAdded+212
hf_repo/zkml_non_encrypted.pyAdded+245
zkml_encrypted.py+1-1
zkml_non_encrypted.py+1-7