Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
jfrery-zama
commited on
Commit
•
2dcbc14
0
Parent(s):
init sentiment analysis in FHE
Browse files- .gitattributes +33 -0
- .gitignore +6 -0
- README.md +78 -0
- SentimentClassification.ipynb +988 -0
- app.py +310 -0
- compile.py +57 -0
- download_data.sh +13 -0
- requirements.txt +7 -0
- sentiment_fhe_model/deployment/client.zip +3 -0
- sentiment_fhe_model/deployment/serialized_processing.json +0 -0
- sentiment_fhe_model/deployment/server.zip +3 -0
- sentiment_fhe_model/samples_for_compilation.csv +0 -0
- sentiment_fhe_model/server_model.onnx +3 -0
- server.py +34 -0
- tmp/.gitkeep +0 -0
- transformer_vectorizer.py +58 -0
.gitattributes
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
25 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
26 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
tmp_encrypted_prediction.npy
|
2 |
+
tmp_encrypted_quantized_encoding.npy
|
3 |
+
tmp_evaluation_key.npy
|
4 |
+
.venv
|
5 |
+
.fhe_keys
|
6 |
+
*.pyc
|
README.md
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Sentiment Analysis on Encrypted Data with FHE
|
3 |
+
emoji: 🥷💬
|
4 |
+
colorFrom: yellow
|
5 |
+
colorTo: yellow
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.2
|
8 |
+
app_file: app.py
|
9 |
+
pinned: true
|
10 |
+
tags: [FHE, PPML, privacy, privacy preserving machine learning, homomorphic encryption, security]
|
11 |
+
python_version: 3.9
|
12 |
+
---
|
13 |
+
|
14 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
15 |
+
|
16 |
+
# Sentiment Analysis With FHE
|
17 |
+
|
18 |
+
## Running the application on your machine
|
19 |
+
|
20 |
+
In this directory, ie `sentiment-analysis-with-transformer`, you can do the following steps.
|
21 |
+
|
22 |
+
### Do once
|
23 |
+
|
24 |
+
- First, create a virtual env and activate it:
|
25 |
+
|
26 |
+
```bash
|
27 |
+
python3.9 -m venv .venv
|
28 |
+
source .venv/bin/activate
|
29 |
+
```
|
30 |
+
|
31 |
+
- Then, install required packages:
|
32 |
+
|
33 |
+
```bash
|
34 |
+
pip3 install -U pip wheel setuptools --ignore-installed
|
35 |
+
pip3 install -r requirements.txt --ignore-installed
|
36 |
+
```
|
37 |
+
|
38 |
+
- If not on Linux, or if you want to compile the FHE algorithms by yourself:
|
39 |
+
|
40 |
+
```bash
|
41 |
+
python3 compile.py
|
42 |
+
```
|
43 |
+
|
44 |
+
Check it finish well (with a "Done!").
|
45 |
+
|
46 |
+
### Do each time you relaunch the application
|
47 |
+
|
48 |
+
- Then, in a terminal Tab 1:
|
49 |
+
|
50 |
+
```bash
|
51 |
+
source .venv/bin/activate
|
52 |
+
uvicorn server:app
|
53 |
+
```
|
54 |
+
|
55 |
+
Tab 1 will be for the Server side.
|
56 |
+
|
57 |
+
- And, in another terminal Tab 2:
|
58 |
+
|
59 |
+
```bash
|
60 |
+
source .venv/bin/activate
|
61 |
+
python3 app.py
|
62 |
+
```
|
63 |
+
|
64 |
+
Tab 2 will be for the Client side.
|
65 |
+
|
66 |
+
## Interacting with the application
|
67 |
+
|
68 |
+
Open the given URL link (search for a line like `Running on local URL: http://127.0.0.1:8888/` in your Terminal 2).
|
69 |
+
|
70 |
+
## Training a new model
|
71 |
+
|
72 |
+
The notebook SentimentClassification.ipynb provides a way to train a new model.
|
73 |
+
|
74 |
+
Before running the notebook, you need to download the data.
|
75 |
+
|
76 |
+
```bash
|
77 |
+
bash download_data.sh
|
78 |
+
```
|
SentimentClassification.ipynb
ADDED
@@ -0,0 +1,988 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {},
|
6 |
+
"source": [
|
7 |
+
"# Sentiment Classification with FHE\n",
|
8 |
+
"\n",
|
9 |
+
"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",
|
10 |
+
"\n",
|
11 |
+
"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",
|
12 |
+
"\n",
|
13 |
+
"The dataset we use in this notebook can be found on [Kaggle](https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment). \n",
|
14 |
+
" \n",
|
15 |
+
"We present two different ways to encode the text:\n",
|
16 |
+
"1. A basic **TF-IDF** approach, which essentially looks at how often a word appears in the text.\n",
|
17 |
+
"2. An advanced **transformer** embedding of the text using the Huggingface repository.\n",
|
18 |
+
"\n",
|
19 |
+
"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."
|
20 |
+
]
|
21 |
+
},
|
22 |
+
{
|
23 |
+
"cell_type": "code",
|
24 |
+
"execution_count": 3,
|
25 |
+
"metadata": {},
|
26 |
+
"outputs": [],
|
27 |
+
"source": [
|
28 |
+
"# Import the required packages\n",
|
29 |
+
"import os\n",
|
30 |
+
"import time\n",
|
31 |
+
"\n",
|
32 |
+
"import numpy\n",
|
33 |
+
"import onnx\n",
|
34 |
+
"import pandas as pd\n",
|
35 |
+
"from sklearn.metrics import average_precision_score\n",
|
36 |
+
"from sklearn.model_selection import GridSearchCV, train_test_split\n",
|
37 |
+
"\n",
|
38 |
+
"from concrete.ml.sklearn import XGBClassifier"
|
39 |
+
]
|
40 |
+
},
|
41 |
+
{
|
42 |
+
"cell_type": "code",
|
43 |
+
"execution_count": 4,
|
44 |
+
"metadata": {},
|
45 |
+
"outputs": [
|
46 |
+
{
|
47 |
+
"name": "stdout",
|
48 |
+
"output_type": "stream",
|
49 |
+
"text": [
|
50 |
+
"Proportion of positive examples: 16.14%\n",
|
51 |
+
"Proportion of negative examples: 62.69%\n",
|
52 |
+
"Proportion of neutral examples: 21.17%\n"
|
53 |
+
]
|
54 |
+
}
|
55 |
+
],
|
56 |
+
"source": [
|
57 |
+
"# Download the datasets\n",
|
58 |
+
"if not os.path.isfile(\"local_datasets/twitter-airline-sentiment/Tweets.csv\"):\n",
|
59 |
+
" raise ValueError(\"Please launch the `download_data.sh` script to get datasets\")\n",
|
60 |
+
"\n",
|
61 |
+
"train = pd.read_csv(\"local_datasets/twitter-airline-sentiment/Tweets.csv\", index_col=0)\n",
|
62 |
+
"text_X = train[\"text\"]\n",
|
63 |
+
"y = train[\"airline_sentiment\"]\n",
|
64 |
+
"y = y.replace([\"negative\", \"neutral\", \"positive\"], [0, 1, 2])\n",
|
65 |
+
"\n",
|
66 |
+
"pos_ratio = y.value_counts()[2] / y.value_counts().sum()\n",
|
67 |
+
"neg_ratio = y.value_counts()[0] / y.value_counts().sum()\n",
|
68 |
+
"neutral_ratio = y.value_counts()[1] / y.value_counts().sum()\n",
|
69 |
+
"print(f\"Proportion of positive examples: {round(pos_ratio * 100, 2)}%\")\n",
|
70 |
+
"print(f\"Proportion of negative examples: {round(neg_ratio * 100, 2)}%\")\n",
|
71 |
+
"print(f\"Proportion of neutral examples: {round(neutral_ratio * 100, 2)}%\")"
|
72 |
+
]
|
73 |
+
},
|
74 |
+
{
|
75 |
+
"cell_type": "code",
|
76 |
+
"execution_count": 5,
|
77 |
+
"metadata": {},
|
78 |
+
"outputs": [],
|
79 |
+
"source": [
|
80 |
+
"# Split in train test\n",
|
81 |
+
"text_X_train, text_X_test, y_train, y_test = train_test_split(\n",
|
82 |
+
" text_X, y, test_size=0.1, random_state=42\n",
|
83 |
+
")"
|
84 |
+
]
|
85 |
+
},
|
86 |
+
{
|
87 |
+
"cell_type": "markdown",
|
88 |
+
"metadata": {},
|
89 |
+
"source": [
|
90 |
+
"### 1. Text representation using TF-IDF\n",
|
91 |
+
"\n",
|
92 |
+
"[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",
|
93 |
+
"\n",
|
94 |
+
"We compute it as follows:\n",
|
95 |
+
"\n",
|
96 |
+
"$$ \\mathsf{TF\\textrm{-}IDF}(t,d,D) = \\mathsf{TF}(t,d) * \\mathsf{IDF}(t,D) $$\n",
|
97 |
+
"\n",
|
98 |
+
"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",
|
99 |
+
"\n",
|
100 |
+
"Here we use the scikit-learn implementation of TF-IDF vectorizer."
|
101 |
+
]
|
102 |
+
},
|
103 |
+
{
|
104 |
+
"cell_type": "code",
|
105 |
+
"execution_count": 19,
|
106 |
+
"metadata": {},
|
107 |
+
"outputs": [],
|
108 |
+
"source": [
|
109 |
+
"# Let's first build a representation vector from the text\n",
|
110 |
+
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
|
111 |
+
"\n",
|
112 |
+
"tfidf_vectorizer = TfidfVectorizer(max_features=500, stop_words=\"english\")\n",
|
113 |
+
"X_train = tfidf_vectorizer.fit_transform(text_X_train)\n",
|
114 |
+
"X_test = tfidf_vectorizer.transform(text_X_test)\n",
|
115 |
+
"\n",
|
116 |
+
"# Make our train and test dense array\n",
|
117 |
+
"X_train = X_train.toarray()\n",
|
118 |
+
"X_test = X_test.toarray()"
|
119 |
+
]
|
120 |
+
},
|
121 |
+
{
|
122 |
+
"cell_type": "code",
|
123 |
+
"execution_count": 20,
|
124 |
+
"metadata": {},
|
125 |
+
"outputs": [],
|
126 |
+
"source": [
|
127 |
+
"# Let's build our model\n",
|
128 |
+
"model = XGBClassifier()\n",
|
129 |
+
"\n",
|
130 |
+
"# A gridsearch to find the best parameters\n",
|
131 |
+
"parameters = {\n",
|
132 |
+
" \"n_bits\": [2, 3],\n",
|
133 |
+
" \"max_depth\": [1],\n",
|
134 |
+
" \"n_estimators\": [10, 30, 50],\n",
|
135 |
+
" \"n_jobs\": [-1],\n",
|
136 |
+
"}"
|
137 |
+
]
|
138 |
+
},
|
139 |
+
{
|
140 |
+
"cell_type": "code",
|
141 |
+
"execution_count": 21,
|
142 |
+
"metadata": {},
|
143 |
+
"outputs": [
|
144 |
+
{
|
145 |
+
"data": {
|
146 |
+
"text/html": [
|
147 |
+
"<style>#sk-container-id-3 {color: black;background-color: white;}#sk-container-id-3 pre{padding: 0;}#sk-container-id-3 div.sk-toggleable {background-color: white;}#sk-container-id-3 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-3 label.sk-toggleable__label-arrow:before {content: \"▸\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-3 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-3 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-3 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-3 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-3 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-3 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"▾\";}#sk-container-id-3 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 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-3 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-3 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-3 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-3 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 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-3 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-3 div.sk-item {position: relative;z-index: 1;}#sk-container-id-3 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-3 div.sk-item::before, #sk-container-id-3 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-3 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-3 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-3 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-3 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-3 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-3 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-3 div.sk-label-container {text-align: center;}#sk-container-id-3 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-3 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-3\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
|
148 |
+
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
|
149 |
+
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
|
150 |
+
" 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-7\" type=\"checkbox\" ><label for=\"sk-estimator-id-7\" 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",
|
151 |
+
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
|
152 |
+
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
|
153 |
+
" 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-8\" type=\"checkbox\" ><label for=\"sk-estimator-id-8\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier()</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-9\" type=\"checkbox\" ><label for=\"sk-estimator-id-9\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier()</pre></div></div></div></div></div></div></div></div></div></div>"
|
154 |
+
],
|
155 |
+
"text/plain": [
|
156 |
+
"GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
|
157 |
+
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
|
158 |
+
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
|
159 |
+
" scoring='accuracy')"
|
160 |
+
]
|
161 |
+
},
|
162 |
+
"execution_count": 21,
|
163 |
+
"metadata": {},
|
164 |
+
"output_type": "execute_result"
|
165 |
+
}
|
166 |
+
],
|
167 |
+
"source": [
|
168 |
+
"# Run the gridsearch\n",
|
169 |
+
"grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n",
|
170 |
+
"grid_search.fit(X_train, y_train)"
|
171 |
+
]
|
172 |
+
},
|
173 |
+
{
|
174 |
+
"cell_type": "code",
|
175 |
+
"execution_count": 22,
|
176 |
+
"metadata": {},
|
177 |
+
"outputs": [
|
178 |
+
{
|
179 |
+
"name": "stdout",
|
180 |
+
"output_type": "stream",
|
181 |
+
"text": [
|
182 |
+
"Best score: 0.6842744383727991\n",
|
183 |
+
"Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n"
|
184 |
+
]
|
185 |
+
}
|
186 |
+
],
|
187 |
+
"source": [
|
188 |
+
"# Check the accuracy of the best model\n",
|
189 |
+
"print(f\"Best score: {grid_search.best_score_}\")\n",
|
190 |
+
"\n",
|
191 |
+
"# Check best hyperparameters\n",
|
192 |
+
"print(f\"Best parameters: {grid_search.best_params_}\")\n",
|
193 |
+
"\n",
|
194 |
+
"# Extract best model\n",
|
195 |
+
"best_model = grid_search.best_estimator_"
|
196 |
+
]
|
197 |
+
},
|
198 |
+
{
|
199 |
+
"cell_type": "code",
|
200 |
+
"execution_count": 24,
|
201 |
+
"metadata": {},
|
202 |
+
"outputs": [
|
203 |
+
{
|
204 |
+
"name": "stdout",
|
205 |
+
"output_type": "stream",
|
206 |
+
"text": [
|
207 |
+
"Accuracy: 0.6810\n",
|
208 |
+
"Average precision score for positive class: 0.5615\n",
|
209 |
+
"Average precision score for negative class: 0.8349\n",
|
210 |
+
"Average precision score for neutral class: 0.3820\n"
|
211 |
+
]
|
212 |
+
}
|
213 |
+
],
|
214 |
+
"source": [
|
215 |
+
"# Compute the average precision for each class\n",
|
216 |
+
"y_proba_test_tfidf = best_model.predict_proba(X_test)\n",
|
217 |
+
"\n",
|
218 |
+
"# Compute accuracy\n",
|
219 |
+
"y_pred_test_tfidf = numpy.argmax(y_proba_test_tfidf, axis=1)\n",
|
220 |
+
"accuracy_tfidf = numpy.mean(y_pred_test_tfidf == y_test)\n",
|
221 |
+
"print(f\"Accuracy: {accuracy_tfidf:.4f}\")\n",
|
222 |
+
"\n",
|
223 |
+
"y_pred_positive = y_proba_test_tfidf[:, 2]\n",
|
224 |
+
"y_pred_negative = y_proba_test_tfidf[:, 0]\n",
|
225 |
+
"y_pred_neutral = y_proba_test_tfidf[:, 1]\n",
|
226 |
+
"\n",
|
227 |
+
"ap_positive_tfidf = average_precision_score((y_test == 2), y_pred_positive)\n",
|
228 |
+
"ap_negative_tfidf = average_precision_score((y_test == 0), y_pred_negative)\n",
|
229 |
+
"ap_neutral_tfidf = average_precision_score((y_test == 1), y_pred_neutral)\n",
|
230 |
+
"\n",
|
231 |
+
"print(f\"Average precision score for positive class: \" f\"{ap_positive_tfidf:.4f}\")\n",
|
232 |
+
"print(f\"Average precision score for negative class: \" f\"{ap_negative_tfidf:.4f}\")\n",
|
233 |
+
"print(f\"Average precision score for neutral class: \" f\"{ap_neutral_tfidf:.4f}\")"
|
234 |
+
]
|
235 |
+
},
|
236 |
+
{
|
237 |
+
"cell_type": "code",
|
238 |
+
"execution_count": 48,
|
239 |
+
"metadata": {},
|
240 |
+
"outputs": [
|
241 |
+
{
|
242 |
+
"name": "stdout",
|
243 |
+
"output_type": "stream",
|
244 |
+
"text": [
|
245 |
+
"5 most positive tweets (class 2):\n",
|
246 |
+
"@united sent a DM just now. Thanks I am incredibly happy the fast response I got via Twitter than via customer care. Thank you\n",
|
247 |
+
"@JetBlue Great Thank you, lets hope so! Could you please notify me if flight 2302 leaves JFK? Thank you again\n",
|
248 |
+
"@AmericanAir Great, thanks. Followed.\n",
|
249 |
+
"@SouthwestAir I continue to be amazed by the amazing customer service. Thank you SWA!\n",
|
250 |
+
"@JetBlue Awesome thanks! Thanks for the quick response. You guys ROCK! :)\n",
|
251 |
+
"----------------------------------------------------------------------------------------------------\n",
|
252 |
+
"5 most negative tweets (class 0):\n",
|
253 |
+
"@USAirways been on hold 2 hours for a Cancelled Flighted flight. I understand the delay. I don't understand you auto-reFlight Booking Problems me on TUESDAY. HELP!\n",
|
254 |
+
"@SouthwestAir 2 hours on hold for customer service never us SW again\n",
|
255 |
+
"@SouthwestAir placed on hold for total of two hours today after flight was Cancelled Flightled. Online option not available. What to do?\n",
|
256 |
+
"@southwestair I've been on hold for 2 hours to reschedule my Cancelled Flightled flight for the morning. What gives? I need help NOW\n",
|
257 |
+
"@USAirways Customer service is dead. Last wk, flts delayed/Cancelled Flighted. Bags lost 4 days. Last nt, flt delayed/Cancelled Flighted. No meal voucher?\n"
|
258 |
+
]
|
259 |
+
}
|
260 |
+
],
|
261 |
+
"source": [
|
262 |
+
"# Let's see what are the top predictions based on the probabilities in y_pred_test\n",
|
263 |
+
"print(\"5 most positive tweets (class 2):\")\n",
|
264 |
+
"for i in range(5):\n",
|
265 |
+
" print(text_X_test.iloc[y_pred_test_tfidf[:, 2].argsort()[-1 - i]])\n",
|
266 |
+
"\n",
|
267 |
+
"print(\"-\" * 100)\n",
|
268 |
+
"\n",
|
269 |
+
"print(\"5 most negative tweets (class 0):\")\n",
|
270 |
+
"for i in range(5):\n",
|
271 |
+
" print(text_X_test.iloc[y_pred_test_tfidf[:, 0].argsort()[-1 - i]])"
|
272 |
+
]
|
273 |
+
},
|
274 |
+
{
|
275 |
+
"cell_type": "code",
|
276 |
+
"execution_count": 56,
|
277 |
+
"metadata": {},
|
278 |
+
"outputs": [
|
279 |
+
{
|
280 |
+
"name": "stdout",
|
281 |
+
"output_type": "stream",
|
282 |
+
"text": [
|
283 |
+
"Compilation time: 11.5009 seconds\n",
|
284 |
+
"FHE inference time: 48.6880 seconds\n"
|
285 |
+
]
|
286 |
+
}
|
287 |
+
],
|
288 |
+
"source": [
|
289 |
+
"# Compile the model to get the FHE inference engine\n",
|
290 |
+
"# (this may take a few minutes depending on the selected model)\n",
|
291 |
+
"start = time.perf_counter()\n",
|
292 |
+
"best_model.compile(X_train)\n",
|
293 |
+
"end = time.perf_counter()\n",
|
294 |
+
"print(f\"Compilation time: {end - start:.4f} seconds\")\n",
|
295 |
+
"\n",
|
296 |
+
"# Let's write a custom example and predict in FHE\n",
|
297 |
+
"tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n",
|
298 |
+
"X_tested_tweet = tfidf_vectorizer.transform(numpy.array(tested_tweet)).toarray()\n",
|
299 |
+
"clear_proba = best_model.predict_proba(X_tested_tweet)\n",
|
300 |
+
"\n",
|
301 |
+
"# Now let's predict with FHE over a single tweet and print the time it takes\n",
|
302 |
+
"start = time.perf_counter()\n",
|
303 |
+
"decrypted_proba = best_model.predict_proba(X_tested_tweet, execute_in_fhe=True)\n",
|
304 |
+
"end = time.perf_counter()\n",
|
305 |
+
"print(f\"FHE inference time: {end - start:.4f} seconds\")"
|
306 |
+
]
|
307 |
+
},
|
308 |
+
{
|
309 |
+
"cell_type": "code",
|
310 |
+
"execution_count": 57,
|
311 |
+
"metadata": {},
|
312 |
+
"outputs": [
|
313 |
+
{
|
314 |
+
"name": "stdout",
|
315 |
+
"output_type": "stream",
|
316 |
+
"text": [
|
317 |
+
"Probabilities from the FHE inference: [[0.50224707 0.25647676 0.24127617]]\n",
|
318 |
+
"Probabilities from the clear model: [[0.50224707 0.25647676 0.24127617]]\n"
|
319 |
+
]
|
320 |
+
}
|
321 |
+
],
|
322 |
+
"source": [
|
323 |
+
"print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n",
|
324 |
+
"print(f\"Probabilities from the clear model: {clear_proba}\")"
|
325 |
+
]
|
326 |
+
},
|
327 |
+
{
|
328 |
+
"cell_type": "markdown",
|
329 |
+
"metadata": {},
|
330 |
+
"source": [
|
331 |
+
"To sum up, \n",
|
332 |
+
"- We trained a XGBoost model over TF-IDF representation of the tweets and their respective sentiment class. \n",
|
333 |
+
"- The grid search gives us a model that achieves around ~70% accuracy.\n",
|
334 |
+
"- Given the imbalance in the classes, we rather compute the average precision per class.\n",
|
335 |
+
"\n",
|
336 |
+
"Now we will see how we can approach the problem by leveraging the transformers power."
|
337 |
+
]
|
338 |
+
},
|
339 |
+
{
|
340 |
+
"cell_type": "markdown",
|
341 |
+
"metadata": {},
|
342 |
+
"source": [
|
343 |
+
"### 2. A transformer approach to text representation\n",
|
344 |
+
"\n",
|
345 |
+
"[**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",
|
346 |
+
"\n",
|
347 |
+
"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",
|
348 |
+
"\n",
|
349 |
+
"Here we will use the transformer model from the amazing [**Huggingface**](https://huggingface.co/) repository."
|
350 |
+
]
|
351 |
+
},
|
352 |
+
{
|
353 |
+
"cell_type": "code",
|
354 |
+
"execution_count": 8,
|
355 |
+
"metadata": {},
|
356 |
+
"outputs": [
|
357 |
+
{
|
358 |
+
"name": "stderr",
|
359 |
+
"output_type": "stream",
|
360 |
+
"text": [
|
361 |
+
"Some weights of the model checkpoint at cardiffnlp/twitter-roberta-base-sentiment-latest were not used when initializing RobertaForSequenceClassification: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n",
|
362 |
+
"- 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",
|
363 |
+
"- 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"
|
364 |
+
]
|
365 |
+
}
|
366 |
+
],
|
367 |
+
"source": [
|
368 |
+
"import torch\n",
|
369 |
+
"import tqdm\n",
|
370 |
+
"from transformers import AutoModelForSequenceClassification, AutoTokenizer\n",
|
371 |
+
"\n",
|
372 |
+
"device = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n",
|
373 |
+
"\n",
|
374 |
+
"# Load the tokenizer (converts text to tokens)\n",
|
375 |
+
"tokenizer = AutoTokenizer.from_pretrained(\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\n",
|
376 |
+
"\n",
|
377 |
+
"# Load the pre-trained model\n",
|
378 |
+
"transformer_model = AutoModelForSequenceClassification.from_pretrained(\n",
|
379 |
+
" \"cardiffnlp/twitter-roberta-base-sentiment-latest\"\n",
|
380 |
+
")"
|
381 |
+
]
|
382 |
+
},
|
383 |
+
{
|
384 |
+
"cell_type": "code",
|
385 |
+
"execution_count": 11,
|
386 |
+
"metadata": {},
|
387 |
+
"outputs": [
|
388 |
+
{
|
389 |
+
"name": "stderr",
|
390 |
+
"output_type": "stream",
|
391 |
+
"text": [
|
392 |
+
"100%|██████████| 30/30 [00:33<00:00, 1.10s/it]\n"
|
393 |
+
]
|
394 |
+
}
|
395 |
+
],
|
396 |
+
"source": [
|
397 |
+
"# Let's first see what are the model performance by itself\n",
|
398 |
+
"list_text_X_test = text_X_test.tolist()\n",
|
399 |
+
"\n",
|
400 |
+
"tokenized_text_X_test = tokenizer.batch_encode_plus(\n",
|
401 |
+
" list_text_X_test, pad_to_max_length=True, return_tensors=\"pt\"\n",
|
402 |
+
")[\"input_ids\"]\n",
|
403 |
+
"\n",
|
404 |
+
"# Depending on the hardware used, the number of examples to be processed can be reduced\n",
|
405 |
+
"# Here we split the data into 100 examples per batch\n",
|
406 |
+
"tokenized_text_X_test_split = torch.split(tokenized_text_X_test, split_size_or_sections=50)\n",
|
407 |
+
"transformer_model = transformer_model.to(device)\n",
|
408 |
+
"\n",
|
409 |
+
"outputs = []\n",
|
410 |
+
"for tokenized_x_test in tqdm.tqdm(tokenized_text_X_test_split):\n",
|
411 |
+
" tokenized_x = tokenized_x_test.to(device)\n",
|
412 |
+
" output_batch = transformer_model(tokenized_x)[\"logits\"]\n",
|
413 |
+
" output_batch = output_batch.detach().cpu().numpy()\n",
|
414 |
+
" outputs.append(output_batch)\n",
|
415 |
+
"\n",
|
416 |
+
"outputs = numpy.concatenate(outputs, axis=0)"
|
417 |
+
]
|
418 |
+
},
|
419 |
+
{
|
420 |
+
"cell_type": "code",
|
421 |
+
"execution_count": 12,
|
422 |
+
"metadata": {},
|
423 |
+
"outputs": [
|
424 |
+
{
|
425 |
+
"name": "stdout",
|
426 |
+
"output_type": "stream",
|
427 |
+
"text": [
|
428 |
+
"Predictions for the first 3 tweets:\n",
|
429 |
+
" [[-2.3807464 -0.61802083 2.9900746 ]\n",
|
430 |
+
" [ 2.0166504 0.4938078 -2.8006463 ]\n",
|
431 |
+
" [ 2.3892698 0.1344364 -2.6873822 ]]\n"
|
432 |
+
]
|
433 |
+
}
|
434 |
+
],
|
435 |
+
"source": [
|
436 |
+
"# Let's see what the transformer model predicts\n",
|
437 |
+
"print(f\"Predictions for the first 3 tweets:\\n {outputs[:3]}\")"
|
438 |
+
]
|
439 |
+
},
|
440 |
+
{
|
441 |
+
"cell_type": "code",
|
442 |
+
"execution_count": 13,
|
443 |
+
"metadata": {},
|
444 |
+
"outputs": [
|
445 |
+
{
|
446 |
+
"name": "stdout",
|
447 |
+
"output_type": "stream",
|
448 |
+
"text": [
|
449 |
+
"Accuracy: 0.8053\n",
|
450 |
+
"Average precision score for positive class: 0.8548\n",
|
451 |
+
"Average precision score for negative class: 0.9548\n",
|
452 |
+
"Average precision score for neutral class: 0.6801\n"
|
453 |
+
]
|
454 |
+
}
|
455 |
+
],
|
456 |
+
"source": [
|
457 |
+
"# Compute the metrics for each class\n",
|
458 |
+
"\n",
|
459 |
+
"# Compute accuracy\n",
|
460 |
+
"accuracy_transformer_only = numpy.mean(numpy.argmax(outputs, axis=1) == y_test)\n",
|
461 |
+
"print(f\"Accuracy: {accuracy_transformer_only:.4f}\")\n",
|
462 |
+
"\n",
|
463 |
+
"y_pred_positive = outputs[:, 2]\n",
|
464 |
+
"y_pred_negative = outputs[:, 0]\n",
|
465 |
+
"y_pred_neutral = outputs[:, 1]\n",
|
466 |
+
"\n",
|
467 |
+
"ap_positive_transformer_only = average_precision_score((y_test == 2), y_pred_positive)\n",
|
468 |
+
"ap_negative_transformer_only = average_precision_score((y_test == 0), y_pred_negative)\n",
|
469 |
+
"ap_neutral_transformer_only = average_precision_score((y_test == 1), y_pred_neutral)\n",
|
470 |
+
"\n",
|
471 |
+
"print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_only:.4f}\")\n",
|
472 |
+
"print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_only:.4f}\")\n",
|
473 |
+
"print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_only:.4f}\")"
|
474 |
+
]
|
475 |
+
},
|
476 |
+
{
|
477 |
+
"cell_type": "markdown",
|
478 |
+
"metadata": {},
|
479 |
+
"source": [
|
480 |
+
"It looks like the transformer outperforms the model built on TF-IDF reprensentation.\n",
|
481 |
+
"Unfortunately, running a transformer that big in FHE would be highly inefficient. \n",
|
482 |
+
"\n",
|
483 |
+
"Let's see if we can leverage transformer representation and train a FHE model for the given classification task. "
|
484 |
+
]
|
485 |
+
},
|
486 |
+
{
|
487 |
+
"cell_type": "code",
|
488 |
+
"execution_count": 14,
|
489 |
+
"metadata": {},
|
490 |
+
"outputs": [
|
491 |
+
{
|
492 |
+
"name": "stderr",
|
493 |
+
"output_type": "stream",
|
494 |
+
"text": [
|
495 |
+
"100%|██████████| 13176/13176 [07:20<00:00, 29.91it/s]\n",
|
496 |
+
"100%|██████████| 1464/1464 [00:47<00:00, 30.75it/s]\n"
|
497 |
+
]
|
498 |
+
}
|
499 |
+
],
|
500 |
+
"source": [
|
501 |
+
"# Function that transforms a list of texts to their representation\n",
|
502 |
+
"# learned by the transformer.\n",
|
503 |
+
"def text_to_tensor(\n",
|
504 |
+
" list_text_X_train: list,\n",
|
505 |
+
" transformer_model: AutoModelForSequenceClassification,\n",
|
506 |
+
" tokenizer: AutoTokenizer,\n",
|
507 |
+
" device: str,\n",
|
508 |
+
") -> numpy.ndarray:\n",
|
509 |
+
" # Tokenize each text in the list one by one\n",
|
510 |
+
" tokenized_text_X_train_split = []\n",
|
511 |
+
" for text_x_train in list_text_X_train:\n",
|
512 |
+
" tokenized_text_X_train_split.append(tokenizer.encode(text_x_train, return_tensors=\"pt\"))\n",
|
513 |
+
"\n",
|
514 |
+
" # Send the model to the device\n",
|
515 |
+
" transformer_model = transformer_model.to(device)\n",
|
516 |
+
" output_hidden_states_list = []\n",
|
517 |
+
"\n",
|
518 |
+
" for tokenized_x in tqdm.tqdm(tokenized_text_X_train_split):\n",
|
519 |
+
" # Pass the tokens through the transformer model and get the hidden states\n",
|
520 |
+
" # Only keep the last hidden layer state for now\n",
|
521 |
+
" output_hidden_states = transformer_model(tokenized_x.to(device), output_hidden_states=True)[\n",
|
522 |
+
" 1\n",
|
523 |
+
" ][-1]\n",
|
524 |
+
" # Average over the tokens axis to get a representation at the text level.\n",
|
525 |
+
" output_hidden_states = output_hidden_states.mean(dim=1)\n",
|
526 |
+
" output_hidden_states = output_hidden_states.detach().cpu().numpy()\n",
|
527 |
+
" output_hidden_states_list.append(output_hidden_states)\n",
|
528 |
+
"\n",
|
529 |
+
" return numpy.concatenate(output_hidden_states_list, axis=0)\n",
|
530 |
+
"\n",
|
531 |
+
"\n",
|
532 |
+
"# Let's vectorize the text using the transformer\n",
|
533 |
+
"list_text_X_train = text_X_train.tolist()\n",
|
534 |
+
"list_text_X_test = text_X_test.tolist()\n",
|
535 |
+
"\n",
|
536 |
+
"X_train_transformer = text_to_tensor(list_text_X_train, transformer_model, tokenizer, device)\n",
|
537 |
+
"X_test_transformer = text_to_tensor(list_text_X_test, transformer_model, tokenizer, device)"
|
538 |
+
]
|
539 |
+
},
|
540 |
+
{
|
541 |
+
"cell_type": "code",
|
542 |
+
"execution_count": 15,
|
543 |
+
"metadata": {},
|
544 |
+
"outputs": [
|
545 |
+
{
|
546 |
+
"data": {
|
547 |
+
"text/html": [
|
548 |
+
"<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",
|
549 |
+
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
|
550 |
+
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
|
551 |
+
" 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",
|
552 |
+
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
|
553 |
+
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
|
554 |
+
" 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()</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()</pre></div></div></div></div></div></div></div></div></div></div>"
|
555 |
+
],
|
556 |
+
"text/plain": [
|
557 |
+
"GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
|
558 |
+
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
|
559 |
+
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
|
560 |
+
" scoring='accuracy')"
|
561 |
+
]
|
562 |
+
},
|
563 |
+
"execution_count": 15,
|
564 |
+
"metadata": {},
|
565 |
+
"output_type": "execute_result"
|
566 |
+
}
|
567 |
+
],
|
568 |
+
"source": [
|
569 |
+
"# Now we have a representation for each tweet, we can train a model on these.\n",
|
570 |
+
"grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n",
|
571 |
+
"grid_search.fit(X_train_transformer, y_train)"
|
572 |
+
]
|
573 |
+
},
|
574 |
+
{
|
575 |
+
"cell_type": "code",
|
576 |
+
"execution_count": 16,
|
577 |
+
"metadata": {},
|
578 |
+
"outputs": [
|
579 |
+
{
|
580 |
+
"name": "stdout",
|
581 |
+
"output_type": "stream",
|
582 |
+
"text": [
|
583 |
+
"Best score: 0.8378111718275654\n",
|
584 |
+
"Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n"
|
585 |
+
]
|
586 |
+
}
|
587 |
+
],
|
588 |
+
"source": [
|
589 |
+
"# Check the accuracy of the best model\n",
|
590 |
+
"print(f\"Best score: {grid_search.best_score_}\")\n",
|
591 |
+
"\n",
|
592 |
+
"# Check best hyperparameters\n",
|
593 |
+
"print(f\"Best parameters: {grid_search.best_params_}\")\n",
|
594 |
+
"\n",
|
595 |
+
"# Extract best model\n",
|
596 |
+
"best_model = grid_search.best_estimator_"
|
597 |
+
]
|
598 |
+
},
|
599 |
+
{
|
600 |
+
"cell_type": "code",
|
601 |
+
"execution_count": 17,
|
602 |
+
"metadata": {},
|
603 |
+
"outputs": [
|
604 |
+
{
|
605 |
+
"name": "stdout",
|
606 |
+
"output_type": "stream",
|
607 |
+
"text": [
|
608 |
+
"Accuracy: 0.8504\n",
|
609 |
+
"Average precision score for positive class: 0.8917\n",
|
610 |
+
"Average precision score for negative class: 0.9597\n",
|
611 |
+
"Average precision score for neutral class: 0.7341\n"
|
612 |
+
]
|
613 |
+
}
|
614 |
+
],
|
615 |
+
"source": [
|
616 |
+
"# Compute the metrics for each class\n",
|
617 |
+
"\n",
|
618 |
+
"y_proba = best_model.predict_proba(X_test_transformer)\n",
|
619 |
+
"\n",
|
620 |
+
"# Compute the accuracy\n",
|
621 |
+
"y_pred = numpy.argmax(y_proba, axis=1)\n",
|
622 |
+
"accuracy_transformer_xgboost = numpy.mean(y_pred == y_test)\n",
|
623 |
+
"print(f\"Accuracy: {accuracy_transformer_xgboost:.4f}\")\n",
|
624 |
+
"\n",
|
625 |
+
"y_pred_positive = y_proba[:, 2]\n",
|
626 |
+
"y_pred_negative = y_proba[:, 0]\n",
|
627 |
+
"y_pred_neutral = y_proba[:, 1]\n",
|
628 |
+
"\n",
|
629 |
+
"ap_positive_transformer_xgboost = average_precision_score((y_test == 2), y_pred_positive)\n",
|
630 |
+
"ap_negative_transformer_xgboost = average_precision_score((y_test == 0), y_pred_negative)\n",
|
631 |
+
"ap_neutral_transformer_xgboost = average_precision_score((y_test == 1), y_pred_neutral)\n",
|
632 |
+
"\n",
|
633 |
+
"print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_xgboost:.4f}\")\n",
|
634 |
+
"print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_xgboost:.4f}\")\n",
|
635 |
+
"print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_xgboost:.4f}\")"
|
636 |
+
]
|
637 |
+
},
|
638 |
+
{
|
639 |
+
"cell_type": "markdown",
|
640 |
+
"metadata": {},
|
641 |
+
"source": [
|
642 |
+
"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",
|
643 |
+
"Interestingly, using XGBoost over the transformer representation of the text matches the performance of the transformer model alone."
|
644 |
+
]
|
645 |
+
},
|
646 |
+
{
|
647 |
+
"cell_type": "code",
|
648 |
+
"execution_count": 19,
|
649 |
+
"metadata": {},
|
650 |
+
"outputs": [
|
651 |
+
{
|
652 |
+
"name": "stdout",
|
653 |
+
"output_type": "stream",
|
654 |
+
"text": [
|
655 |
+
"5 most positive tweets (class 2):\n",
|
656 |
+
"@SouthwestAir love them! Always get the best deals!\n",
|
657 |
+
"@AmericanAir THANK YOU FOR ALL THE HELP! :P You guys are the best. #americanairlines #americanair\n",
|
658 |
+
"@SouthwestAir - Great flight from Phoenix to Dallas tonight!Great service and ON TIME! Makes @timieyancey very happy! http://t.co/TkVCMhbPim\n",
|
659 |
+
"@AmericanAir AA2416 on time and awesome flight. Great job American!\n",
|
660 |
+
"@SouthwestAir AMAZING c/s today by SW thank you SO very much. This is the reason we fly you #southwest\n",
|
661 |
+
"----------------------------------------------------------------------------------------------------\n",
|
662 |
+
"5 most negative tweets (class 0):\n",
|
663 |
+
"@AmericanAir This entire process took sooooo long that no decent seats are left. #customerservice\n",
|
664 |
+
"@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",
|
665 |
+
"@United site errored out at last step of changing award. Now can't even pull up reservation. 60 minute wait time. Thanks @United!\n",
|
666 |
+
"@united OKC ticket agent Roger McLarren(sp?) LESS than helpful with our Intl group travel problems Can't find a supervisor for help.\n",
|
667 |
+
"@AmericanAir the dinner and called me \"hon\". Not the service I would expect from 1st class. #disappointed\n"
|
668 |
+
]
|
669 |
+
}
|
670 |
+
],
|
671 |
+
"source": [
|
672 |
+
"# Get probabilities predictions in clear\n",
|
673 |
+
"y_pred_test = best_model.predict_proba(X_test_transformer)\n",
|
674 |
+
"\n",
|
675 |
+
"# Let's see what are the top predictions based on the probabilities in y_pred_test\n",
|
676 |
+
"print(\"5 most positive tweets (class 2):\")\n",
|
677 |
+
"for i in range(5):\n",
|
678 |
+
" print(text_X_test.iloc[y_pred_test[:, 2].argsort()[-1 - i]])\n",
|
679 |
+
"\n",
|
680 |
+
"print(\"-\" * 100)\n",
|
681 |
+
"\n",
|
682 |
+
"print(\"5 most negative tweets (class 0):\")\n",
|
683 |
+
"for i in range(5):\n",
|
684 |
+
" print(text_X_test.iloc[y_pred_test[:, 0].argsort()[-1 - i]])"
|
685 |
+
]
|
686 |
+
},
|
687 |
+
{
|
688 |
+
"cell_type": "code",
|
689 |
+
"execution_count": 20,
|
690 |
+
"metadata": {},
|
691 |
+
"outputs": [
|
692 |
+
{
|
693 |
+
"name": "stdout",
|
694 |
+
"output_type": "stream",
|
695 |
+
"text": [
|
696 |
+
"5 most positive (predicted) tweets that are actually negative (ground truth class 0):\n",
|
697 |
+
"@USAirways as far as being delayed goes… Looks like tailwinds are going to make up for it. Good news!\n",
|
698 |
+
"@united thanks for the link, now finally arrived in Brussels, 9 h after schedule...\n",
|
699 |
+
"@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",
|
700 |
+
"@AmericanAir that luggage you forgot...#mia.....he just won an oscar😄💝💝💝\n",
|
701 |
+
"@united thanks for having changed me. Managed to arrive with only 8 hours of delay and exhausted\n",
|
702 |
+
"----------------------------------------------------------------------------------------------------\n",
|
703 |
+
"5 most negative (predicted) tweets that are actually positive (ground truth class 2):\n",
|
704 |
+
"@united thanks for updating me about the 1+ hour delay the exact second I got to ATL. 🙅🙅🙅\n",
|
705 |
+
"@JetBlue you don't remember our date Monday night back to NYC? #heartbroken\n",
|
706 |
+
"@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",
|
707 |
+
"@SouthwestAir hot stewardess flipped me off\n",
|
708 |
+
"@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"
|
709 |
+
]
|
710 |
+
}
|
711 |
+
],
|
712 |
+
"source": [
|
713 |
+
"# Now let's see where the model is wrong\n",
|
714 |
+
"y_pred_test_0 = y_pred_test[y_test == 0]\n",
|
715 |
+
"text_X_test_0 = text_X_test[y_test == 0]\n",
|
716 |
+
"\n",
|
717 |
+
"print(\"5 most positive (predicted) tweets that are actually negative (ground truth class 0):\")\n",
|
718 |
+
"for i in range(5):\n",
|
719 |
+
" print(text_X_test_0.iloc[y_pred_test_0[:, 2].argsort()[-1 - i]])\n",
|
720 |
+
"\n",
|
721 |
+
"print(\"-\" * 100)\n",
|
722 |
+
"\n",
|
723 |
+
"y_pred_test_2 = y_pred_test[y_test == 2]\n",
|
724 |
+
"text_X_test_2 = text_X_test[y_test == 2]\n",
|
725 |
+
"print(\"5 most negative (predicted) tweets that are actually positive (ground truth class 2):\")\n",
|
726 |
+
"for i in range(5):\n",
|
727 |
+
" print(text_X_test_2.iloc[y_pred_test_2[:, 0].argsort()[-1 - i]])"
|
728 |
+
]
|
729 |
+
},
|
730 |
+
{
|
731 |
+
"cell_type": "markdown",
|
732 |
+
"metadata": {},
|
733 |
+
"source": [
|
734 |
+
"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",
|
735 |
+
"\n",
|
736 |
+
"Now we have our model trained which has some great accuracy. Let's have it predict over the encrypted representation."
|
737 |
+
]
|
738 |
+
},
|
739 |
+
{
|
740 |
+
"cell_type": "markdown",
|
741 |
+
"metadata": {},
|
742 |
+
"source": [
|
743 |
+
"### Sentiment Analysis of the Tweet with Fully Homomorphic Encryption\n",
|
744 |
+
"\n",
|
745 |
+
"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."
|
746 |
+
]
|
747 |
+
},
|
748 |
+
{
|
749 |
+
"cell_type": "code",
|
750 |
+
"execution_count": 26,
|
751 |
+
"metadata": {},
|
752 |
+
"outputs": [
|
753 |
+
{
|
754 |
+
"name": "stdout",
|
755 |
+
"output_type": "stream",
|
756 |
+
"text": [
|
757 |
+
"Compilation time: 12.6855 seconds\n"
|
758 |
+
]
|
759 |
+
},
|
760 |
+
{
|
761 |
+
"name": "stderr",
|
762 |
+
"output_type": "stream",
|
763 |
+
"text": [
|
764 |
+
"100%|██████████| 1/1 [00:00<00:00, 36.43it/s]\n"
|
765 |
+
]
|
766 |
+
},
|
767 |
+
{
|
768 |
+
"name": "stdout",
|
769 |
+
"output_type": "stream",
|
770 |
+
"text": [
|
771 |
+
"FHE inference time: 53.0192 seconds\n"
|
772 |
+
]
|
773 |
+
}
|
774 |
+
],
|
775 |
+
"source": [
|
776 |
+
"# Compile the model to get the FHE inference engine\n",
|
777 |
+
"# (this may take a few minutes depending on the selected model)\n",
|
778 |
+
"start = time.perf_counter()\n",
|
779 |
+
"best_model.compile(X_train_transformer)\n",
|
780 |
+
"end = time.perf_counter()\n",
|
781 |
+
"print(f\"Compilation time: {end - start:.4f} seconds\")\n",
|
782 |
+
"\n",
|
783 |
+
"\n",
|
784 |
+
"# Let's write a custom example and predict in FHE\n",
|
785 |
+
"tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n",
|
786 |
+
"X_tested_tweet = text_to_tensor(tested_tweet, transformer_model, tokenizer, device)\n",
|
787 |
+
"clear_proba = best_model.predict_proba(X_tested_tweet)\n",
|
788 |
+
"\n",
|
789 |
+
"# Now let's predict with FHE over a single tweet and print the time it takes\n",
|
790 |
+
"start = time.perf_counter()\n",
|
791 |
+
"decrypted_proba = best_model.predict_proba(X_tested_tweet, execute_in_fhe=True)\n",
|
792 |
+
"end = time.perf_counter()\n",
|
793 |
+
"fhe_exec_time = end - start\n",
|
794 |
+
"print(f\"FHE inference time: {fhe_exec_time:.4f} seconds\")"
|
795 |
+
]
|
796 |
+
},
|
797 |
+
{
|
798 |
+
"cell_type": "code",
|
799 |
+
"execution_count": 40,
|
800 |
+
"metadata": {},
|
801 |
+
"outputs": [
|
802 |
+
{
|
803 |
+
"name": "stdout",
|
804 |
+
"output_type": "stream",
|
805 |
+
"text": [
|
806 |
+
"Probabilities from the FHE inference: [[0.08434131 0.05571389 0.8599448 ]]\n",
|
807 |
+
"Probabilities from the clear model: [[0.08434131 0.05571389 0.8599448 ]]\n"
|
808 |
+
]
|
809 |
+
}
|
810 |
+
],
|
811 |
+
"source": [
|
812 |
+
"print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n",
|
813 |
+
"print(f\"Probabilities from the clear model: {clear_proba}\")"
|
814 |
+
]
|
815 |
+
},
|
816 |
+
{
|
817 |
+
"cell_type": "code",
|
818 |
+
"execution_count": null,
|
819 |
+
"metadata": {},
|
820 |
+
"outputs": [],
|
821 |
+
"source": [
|
822 |
+
"# Let's export the final model such that we can reuse it in a client/server environment\n",
|
823 |
+
"\n",
|
824 |
+
"# Export the model to ONNX\n",
|
825 |
+
"onnx.save(best_model._onnx_model_, \"server_model.onnx\") # pylint: disable=protected-access\n",
|
826 |
+
"\n",
|
827 |
+
"# Export some data to be used for compilation\n",
|
828 |
+
"X_train_numpy = X_train_transformer[:100]\n",
|
829 |
+
"\n",
|
830 |
+
"# Merge the two arrays in a pandas dataframe\n",
|
831 |
+
"X_test_numpy_df = pd.DataFrame(X_train_numpy)\n",
|
832 |
+
"\n",
|
833 |
+
"# to csv\n",
|
834 |
+
"X_test_numpy_df.to_csv(\"samples_for_compilation.csv\")\n",
|
835 |
+
"\n",
|
836 |
+
"# Let's save the model to be pushed to a server later\n",
|
837 |
+
"from concrete.ml.deployment import FHEModelDev\n",
|
838 |
+
"\n",
|
839 |
+
"fhe_api = FHEModelDev(\"sentiment_fhe_model\", best_model)\n",
|
840 |
+
"fhe_api.save()"
|
841 |
+
]
|
842 |
+
},
|
843 |
+
{
|
844 |
+
"cell_type": "code",
|
845 |
+
"execution_count": 26,
|
846 |
+
"metadata": {},
|
847 |
+
"outputs": [
|
848 |
+
{
|
849 |
+
"data": {
|
850 |
+
"text/html": [
|
851 |
+
"<div>\n",
|
852 |
+
"<style scoped>\n",
|
853 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
854 |
+
" vertical-align: middle;\n",
|
855 |
+
" }\n",
|
856 |
+
"\n",
|
857 |
+
" .dataframe tbody tr th {\n",
|
858 |
+
" vertical-align: top;\n",
|
859 |
+
" }\n",
|
860 |
+
"\n",
|
861 |
+
" .dataframe thead th {\n",
|
862 |
+
" text-align: right;\n",
|
863 |
+
" }\n",
|
864 |
+
"</style>\n",
|
865 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
866 |
+
" <thead>\n",
|
867 |
+
" <tr style=\"text-align: right;\">\n",
|
868 |
+
" <th></th>\n",
|
869 |
+
" <th>Accuracy</th>\n",
|
870 |
+
" <th>Average Precision (positive)</th>\n",
|
871 |
+
" <th>Average Precision (negative)</th>\n",
|
872 |
+
" <th>Average Precision (neutral)</th>\n",
|
873 |
+
" </tr>\n",
|
874 |
+
" <tr>\n",
|
875 |
+
" <th>Model</th>\n",
|
876 |
+
" <th></th>\n",
|
877 |
+
" <th></th>\n",
|
878 |
+
" <th></th>\n",
|
879 |
+
" <th></th>\n",
|
880 |
+
" </tr>\n",
|
881 |
+
" </thead>\n",
|
882 |
+
" <tbody>\n",
|
883 |
+
" <tr>\n",
|
884 |
+
" <th>TF-IDF + XGBoost</th>\n",
|
885 |
+
" <td>0.681011</td>\n",
|
886 |
+
" <td>0.561521</td>\n",
|
887 |
+
" <td>0.834914</td>\n",
|
888 |
+
" <td>0.382002</td>\n",
|
889 |
+
" </tr>\n",
|
890 |
+
" <tr>\n",
|
891 |
+
" <th>Transformer Only</th>\n",
|
892 |
+
" <td>0.805328</td>\n",
|
893 |
+
" <td>0.854827</td>\n",
|
894 |
+
" <td>0.954804</td>\n",
|
895 |
+
" <td>0.680110</td>\n",
|
896 |
+
" </tr>\n",
|
897 |
+
" <tr>\n",
|
898 |
+
" <th>Transformer + XGBoost</th>\n",
|
899 |
+
" <td>0.850410</td>\n",
|
900 |
+
" <td>0.891691</td>\n",
|
901 |
+
" <td>0.959747</td>\n",
|
902 |
+
" <td>0.734144</td>\n",
|
903 |
+
" </tr>\n",
|
904 |
+
" </tbody>\n",
|
905 |
+
"</table>\n",
|
906 |
+
"</div>"
|
907 |
+
],
|
908 |
+
"text/plain": [
|
909 |
+
" Accuracy Average Precision (positive) \\\n",
|
910 |
+
"Model \n",
|
911 |
+
"TF-IDF + XGBoost 0.681011 0.561521 \n",
|
912 |
+
"Transformer Only 0.805328 0.854827 \n",
|
913 |
+
"Transformer + XGBoost 0.850410 0.891691 \n",
|
914 |
+
"\n",
|
915 |
+
" Average Precision (negative) \\\n",
|
916 |
+
"Model \n",
|
917 |
+
"TF-IDF + XGBoost 0.834914 \n",
|
918 |
+
"Transformer Only 0.954804 \n",
|
919 |
+
"Transformer + XGBoost 0.959747 \n",
|
920 |
+
"\n",
|
921 |
+
" Average Precision (neutral) \n",
|
922 |
+
"Model \n",
|
923 |
+
"TF-IDF + XGBoost 0.382002 \n",
|
924 |
+
"Transformer Only 0.680110 \n",
|
925 |
+
"Transformer + XGBoost 0.734144 "
|
926 |
+
]
|
927 |
+
},
|
928 |
+
"execution_count": 26,
|
929 |
+
"metadata": {},
|
930 |
+
"output_type": "execute_result"
|
931 |
+
}
|
932 |
+
],
|
933 |
+
"source": [
|
934 |
+
"%matplotlib inline\n",
|
935 |
+
"# Let's print the results obtained in this notebook\n",
|
936 |
+
"df_results = pd.DataFrame(\n",
|
937 |
+
" {\n",
|
938 |
+
" \"Model\": [\"TF-IDF + XGBoost\", \"Transformer Only\", \"Transformer + XGBoost\"],\n",
|
939 |
+
" \"Accuracy\": [accuracy_tfidf, accuracy_transformer_only, accuracy_transformer_xgboost],\n",
|
940 |
+
" \"Average Precision (positive)\": [\n",
|
941 |
+
" ap_positive_tfidf,\n",
|
942 |
+
" ap_positive_transformer_only,\n",
|
943 |
+
" ap_positive_transformer_xgboost,\n",
|
944 |
+
" ],\n",
|
945 |
+
" \"Average Precision (negative)\": [\n",
|
946 |
+
" ap_negative_tfidf,\n",
|
947 |
+
" ap_negative_transformer_only,\n",
|
948 |
+
" ap_negative_transformer_xgboost,\n",
|
949 |
+
" ],\n",
|
950 |
+
" \"Average Precision (neutral)\": [\n",
|
951 |
+
" ap_neutral_tfidf,\n",
|
952 |
+
" ap_neutral_transformer_only,\n",
|
953 |
+
" ap_neutral_transformer_xgboost,\n",
|
954 |
+
" ],\n",
|
955 |
+
" }\n",
|
956 |
+
")\n",
|
957 |
+
"df_results.set_index(\"Model\", inplace=True)\n",
|
958 |
+
"df_results # pylint: disable=pointless-statement"
|
959 |
+
]
|
960 |
+
},
|
961 |
+
{
|
962 |
+
"cell_type": "markdown",
|
963 |
+
"metadata": {},
|
964 |
+
"source": [
|
965 |
+
"### Conclusion\n",
|
966 |
+
"\n",
|
967 |
+
"In this notebook we presented two different ways to represent a text.\n",
|
968 |
+
"1. Using TF-IDF vectorization\n",
|
969 |
+
"2. Using the hidden layers from a transformer\n",
|
970 |
+
"\n",
|
971 |
+
"Both representation are then used to train a machine learning model will run in FHE (here XGBoost)\n",
|
972 |
+
"\n",
|
973 |
+
"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",
|
974 |
+
"\n",
|
975 |
+
"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",
|
976 |
+
"\n",
|
977 |
+
"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."
|
978 |
+
]
|
979 |
+
}
|
980 |
+
],
|
981 |
+
"metadata": {
|
982 |
+
"execution": {
|
983 |
+
"timeout": 10800
|
984 |
+
}
|
985 |
+
},
|
986 |
+
"nbformat": 4,
|
987 |
+
"nbformat_minor": 2
|
988 |
+
}
|
app.py
ADDED
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""A gradio app. that runs locally (analytics=False and share=False) about sentiment analysis on tweets."""
|
2 |
+
|
3 |
+
import gradio as gr
|
4 |
+
from requests import head
|
5 |
+
from transformer_vectorizer import TransformerVectorizer
|
6 |
+
from concrete.ml.deployment import FHEModelClient
|
7 |
+
import numpy
|
8 |
+
import os
|
9 |
+
from pathlib import Path
|
10 |
+
import requests
|
11 |
+
import json
|
12 |
+
import base64
|
13 |
+
import subprocess
|
14 |
+
import shutil
|
15 |
+
import time
|
16 |
+
|
17 |
+
subprocess.Popen(["uvicorn", "server:app"])
|
18 |
+
|
19 |
+
# Wait 5 sec for the server to start
|
20 |
+
time.sleep(5)
|
21 |
+
|
22 |
+
# Encrypted data limit for the browser to display
|
23 |
+
# (encrypted data is too large to display in the browser)
|
24 |
+
ENCRYPTED_DATA_BROWSER_LIMIT = 500
|
25 |
+
N_USER_KEY_STORED = 20
|
26 |
+
|
27 |
+
print("Loading the transformer model...")
|
28 |
+
|
29 |
+
# Initialize the transformer vectorizer
|
30 |
+
transformer_vectorizer = TransformerVectorizer()
|
31 |
+
|
32 |
+
def clean_tmp_directory():
|
33 |
+
# Allow 20 user keys to be stored.
|
34 |
+
# Once that limitation is reached, deleted the oldest.
|
35 |
+
list_files = sorted(Path(".fhe_keys/").iterdir(), key=os.path.getmtime)
|
36 |
+
|
37 |
+
user_ids = []
|
38 |
+
if len(list_files) > N_USER_KEY_STORED:
|
39 |
+
n_files_to_delete = len(list_files) - N_USER_KEY_STORED
|
40 |
+
for p in list_files[:n_files_to_delete]:
|
41 |
+
user_ids.append(p.name)
|
42 |
+
shutil.rmtree(p)
|
43 |
+
|
44 |
+
list_files_tmp = Path("tmp/").iterdir()
|
45 |
+
# Delete all files related to user_id
|
46 |
+
for file in list_files_tmp:
|
47 |
+
for user_id in user_ids:
|
48 |
+
if file.name.endswith(f"{user_id}.npy"):
|
49 |
+
file.unlink()
|
50 |
+
|
51 |
+
|
52 |
+
def keygen():
|
53 |
+
print("Initializing FHEModelClient...")
|
54 |
+
|
55 |
+
# Let's create a user_id
|
56 |
+
user_id = numpy.random.randint(0, 2**32)
|
57 |
+
fhe_api = FHEModelClient("sentiment_fhe_model/deployment", f".fhe_keys/{user_id}")
|
58 |
+
fhe_api.load()
|
59 |
+
|
60 |
+
|
61 |
+
# Generate a fresh key
|
62 |
+
fhe_api.generate_private_and_evaluation_keys(force=True)
|
63 |
+
evaluation_key = fhe_api.get_serialized_evaluation_keys()
|
64 |
+
size_evaluation_key = len(evaluation_key)
|
65 |
+
|
66 |
+
# Save evaluation_key in a file, since too large to pass through regular Gradio
|
67 |
+
# buttons, https://github.com/gradio-app/gradio/issues/1877
|
68 |
+
numpy.save(f"tmp/tmp_evaluation_key_{user_id}.npy", evaluation_key)
|
69 |
+
|
70 |
+
return [list(evaluation_key)[:ENCRYPTED_DATA_BROWSER_LIMIT], size_evaluation_key, user_id]
|
71 |
+
|
72 |
+
|
73 |
+
def encode_quantize_encrypt(text, user_id):
|
74 |
+
assert user_id != [], "Please, wait for the creation of FHE keys before trying to encrypt."
|
75 |
+
|
76 |
+
fhe_api = FHEModelClient("sentiment_fhe_model/deployment", f".fhe_keys/{user_id}")
|
77 |
+
fhe_api.load()
|
78 |
+
encodings = transformer_vectorizer.transform([text])
|
79 |
+
quantized_encodings = fhe_api.model.quantize_input(encodings).astype(numpy.uint8)
|
80 |
+
encrypted_quantized_encoding = fhe_api.quantize_encrypt_serialize(encodings)
|
81 |
+
|
82 |
+
# Save encrypted_quantized_encoding in a file, since too large to pass through regular Gradio
|
83 |
+
# buttons, https://github.com/gradio-app/gradio/issues/1877
|
84 |
+
numpy.save(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy", encrypted_quantized_encoding)
|
85 |
+
|
86 |
+
# Compute size
|
87 |
+
text_size = len(text.encode())
|
88 |
+
encodings_size = len(encodings.tobytes())
|
89 |
+
quantized_encoding_size = len(quantized_encodings.tobytes())
|
90 |
+
encrypted_quantized_encoding_size = len(encrypted_quantized_encoding)
|
91 |
+
encrypted_quantized_encoding_shorten = list(encrypted_quantized_encoding)[:ENCRYPTED_DATA_BROWSER_LIMIT]
|
92 |
+
encrypted_quantized_encoding_shorten_hex = ''.join(f'{i:02x}' for i in encrypted_quantized_encoding_shorten)
|
93 |
+
return (
|
94 |
+
encodings[0],
|
95 |
+
quantized_encodings[0],
|
96 |
+
encrypted_quantized_encoding_shorten_hex,
|
97 |
+
text_size,
|
98 |
+
encodings_size,
|
99 |
+
quantized_encoding_size,
|
100 |
+
encrypted_quantized_encoding_size,
|
101 |
+
)
|
102 |
+
|
103 |
+
|
104 |
+
def run_fhe(user_id):
|
105 |
+
assert user_id != [], "Please, wait for the creation of FHE keys before trying to predict."
|
106 |
+
|
107 |
+
# Read encrypted_quantized_encoding from the file
|
108 |
+
encrypted_quantized_encoding = numpy.load(f"tmp/tmp_encrypted_quantized_encoding_{user_id}.npy")
|
109 |
+
|
110 |
+
# Read evaluation_key from the file
|
111 |
+
evaluation_key = numpy.load(f"tmp/tmp_evaluation_key_{user_id}.npy")
|
112 |
+
|
113 |
+
# Use base64 to encode the encodings and evaluation key
|
114 |
+
encrypted_quantized_encoding = base64.b64encode(encrypted_quantized_encoding).decode()
|
115 |
+
encoded_evaluation_key = base64.b64encode(evaluation_key).decode()
|
116 |
+
|
117 |
+
query = {}
|
118 |
+
query["evaluation_key"] = encoded_evaluation_key
|
119 |
+
query["encrypted_encoding"] = encrypted_quantized_encoding
|
120 |
+
headers = {"Content-type": "application/json"}
|
121 |
+
response = requests.post(
|
122 |
+
"http://localhost:8000/predict_sentiment", data=json.dumps(query), headers=headers
|
123 |
+
)
|
124 |
+
encrypted_prediction = base64.b64decode(response.json()["encrypted_prediction"])
|
125 |
+
|
126 |
+
# Save encrypted_prediction in a file, since too large to pass through regular Gradio
|
127 |
+
# buttons, https://github.com/gradio-app/gradio/issues/1877
|
128 |
+
numpy.save(f"tmp/tmp_encrypted_prediction_{user_id}.npy", encrypted_prediction)
|
129 |
+
encrypted_prediction_shorten = list(encrypted_prediction)[:ENCRYPTED_DATA_BROWSER_LIMIT]
|
130 |
+
encrypted_prediction_shorten_hex = ''.join(f'{i:02x}' for i in encrypted_prediction_shorten)
|
131 |
+
return encrypted_prediction_shorten_hex
|
132 |
+
|
133 |
+
|
134 |
+
def decrypt_prediction(user_id):
|
135 |
+
assert user_id != [], "Please, wait for the creation of FHE keys before trying to decrypt."
|
136 |
+
|
137 |
+
# Read encrypted_prediction from the file
|
138 |
+
encrypted_prediction = numpy.load(f"tmp/tmp_encrypted_prediction_{user_id}.npy").tobytes()
|
139 |
+
|
140 |
+
fhe_api = FHEModelClient("sentiment_fhe_model/deployment", f".fhe_keys/{user_id}")
|
141 |
+
fhe_api.load()
|
142 |
+
|
143 |
+
# We need to retrieve the private key that matches the client specs (see issue #18)
|
144 |
+
fhe_api.generate_private_and_evaluation_keys(force=False)
|
145 |
+
|
146 |
+
predictions = fhe_api.deserialize_decrypt_dequantize(encrypted_prediction)
|
147 |
+
return {
|
148 |
+
"negative": predictions[0][0],
|
149 |
+
"neutral": predictions[0][1],
|
150 |
+
"positive": predictions[0][2],
|
151 |
+
}
|
152 |
+
|
153 |
+
|
154 |
+
demo = gr.Blocks()
|
155 |
+
|
156 |
+
|
157 |
+
print("Starting the demo...")
|
158 |
+
with demo:
|
159 |
+
|
160 |
+
gr.Markdown(
|
161 |
+
"""
|
162 |
+
<p align="center">
|
163 |
+
<img width=200 src="https://user-images.githubusercontent.com/5758427/197816413-d9cddad3-ba38-4793-847d-120975e1da11.png">
|
164 |
+
</p>
|
165 |
+
|
166 |
+
<h2 align="center">Machine Learning, Natural Language Processing and Fully Homomorphic Encryption to do Sentiment Analysis on Encrypted data.</h2>
|
167 |
+
|
168 |
+
<p align="center">
|
169 |
+
<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>
|
170 |
+
—
|
171 |
+
<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>
|
172 |
+
—
|
173 |
+
<a href="https://community.zama.ai"> <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 support forum</a>
|
174 |
+
—
|
175 |
+
<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>
|
176 |
+
</p>
|
177 |
+
|
178 |
+
<p align="center">
|
179 |
+
<img src="https://user-images.githubusercontent.com/5758427/197974594-80897620-c64b-4c39-aeeb-c941e4146c6d.png">
|
180 |
+
</p>
|
181 |
+
|
182 |
+
<p align="center">
|
183 |
+
<img src="https://user-images.githubusercontent.com/5758427/197974639-cfb7af28-9dfc-4bf6-ab5b-57ad562a5dc4.png">
|
184 |
+
</p>
|
185 |
+
"""
|
186 |
+
)
|
187 |
+
|
188 |
+
|
189 |
+
|
190 |
+
# FIXME: make it smaller and in the middle
|
191 |
+
# gr.Image("Zama.svg")
|
192 |
+
|
193 |
+
gr.Markdown(
|
194 |
+
"""
|
195 |
+
<p align="center">
|
196 |
+
</p>
|
197 |
+
<p align="center">
|
198 |
+
</p>
|
199 |
+
"""
|
200 |
+
)
|
201 |
+
|
202 |
+
gr.Markdown("## Notes")
|
203 |
+
gr.Markdown(
|
204 |
+
"""
|
205 |
+
- The private key is used to encrypt and decrypt the data and shall never be shared.
|
206 |
+
- The evaluation key is a public key that the server needs to process encrypted data.
|
207 |
+
"""
|
208 |
+
)
|
209 |
+
|
210 |
+
b_gen_key_and_install = gr.Button("Generate the key and send public part to server")
|
211 |
+
|
212 |
+
evaluation_key = gr.Textbox(
|
213 |
+
label="Evaluation key (truncated):",
|
214 |
+
max_lines=4,
|
215 |
+
interactive=False,
|
216 |
+
)
|
217 |
+
|
218 |
+
user_id = gr.Textbox(
|
219 |
+
label="",
|
220 |
+
max_lines=4,
|
221 |
+
interactive=False,
|
222 |
+
visible=False
|
223 |
+
)
|
224 |
+
|
225 |
+
size_evaluation_key = gr.Number(
|
226 |
+
label="Size of the evalution key (in bytes):", value=0, interactive=False
|
227 |
+
)
|
228 |
+
|
229 |
+
# FIXME: add a picture from marketing with client->server interactions
|
230 |
+
|
231 |
+
gr.Markdown("## Client side")
|
232 |
+
gr.Markdown(
|
233 |
+
"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)."
|
234 |
+
)
|
235 |
+
text = gr.Textbox(label="Enter a message:", value="I really like your work recently")
|
236 |
+
size_text = gr.Number(label="Size of the text (in bytes):", value=0, interactive=False)
|
237 |
+
b_encode_quantize_text = gr.Button(
|
238 |
+
"Encode, quantize and encrypt the text with transformer vectorizer, and send to server"
|
239 |
+
)
|
240 |
+
|
241 |
+
with gr.Row():
|
242 |
+
encoding = gr.Textbox(
|
243 |
+
label="Transformer representation:",
|
244 |
+
max_lines=4,
|
245 |
+
interactive=False,
|
246 |
+
)
|
247 |
+
quantized_encoding = gr.Textbox(
|
248 |
+
label="Quantized transformer representation:", max_lines=4, interactive=False
|
249 |
+
)
|
250 |
+
encrypted_quantized_encoding = gr.Textbox(
|
251 |
+
label="Encrypted quantized transformer representation (truncated):",
|
252 |
+
max_lines=4,
|
253 |
+
interactive=False,
|
254 |
+
)
|
255 |
+
with gr.Row():
|
256 |
+
size_encoding = gr.Number(label="Size (in bytes):", value=0, interactive=False)
|
257 |
+
size_quantized_encoding = gr.Number(label="Size (in bytes):", value=0, interactive=False)
|
258 |
+
size_encrypted_quantized_encoding = gr.Number(
|
259 |
+
label="Size (in bytes):",
|
260 |
+
value=0,
|
261 |
+
interactive=False,
|
262 |
+
)
|
263 |
+
|
264 |
+
gr.Markdown("## Server side")
|
265 |
+
gr.Markdown(
|
266 |
+
"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."
|
267 |
+
)
|
268 |
+
|
269 |
+
b_run_fhe = gr.Button("Run FHE execution there")
|
270 |
+
encrypted_prediction = gr.Textbox(
|
271 |
+
label="Encrypted prediction (truncated):",
|
272 |
+
max_lines=4,
|
273 |
+
interactive=False,
|
274 |
+
)
|
275 |
+
|
276 |
+
gr.Markdown("## Client side")
|
277 |
+
gr.Markdown(
|
278 |
+
"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."
|
279 |
+
)
|
280 |
+
b_decrypt_prediction = gr.Button("Decrypt prediction")
|
281 |
+
|
282 |
+
labels_sentiment = gr.Label(label="Sentiment:")
|
283 |
+
|
284 |
+
# Button for key generation
|
285 |
+
b_gen_key_and_install.click(keygen, inputs=[], outputs=[evaluation_key, size_evaluation_key, user_id])
|
286 |
+
|
287 |
+
# Button to quantize and encrypt
|
288 |
+
b_encode_quantize_text.click(
|
289 |
+
encode_quantize_encrypt,
|
290 |
+
inputs=[text, user_id],
|
291 |
+
outputs=[
|
292 |
+
encoding,
|
293 |
+
quantized_encoding,
|
294 |
+
encrypted_quantized_encoding,
|
295 |
+
size_text,
|
296 |
+
size_encoding,
|
297 |
+
size_quantized_encoding,
|
298 |
+
size_encrypted_quantized_encoding,
|
299 |
+
],
|
300 |
+
)
|
301 |
+
|
302 |
+
# Button to send the encodings to the server using post at (localhost:8000/predict_sentiment)
|
303 |
+
b_run_fhe.click(run_fhe, inputs=[user_id], outputs=[encrypted_prediction])
|
304 |
+
|
305 |
+
# Button to decrypt the prediction on the client
|
306 |
+
b_decrypt_prediction.click(decrypt_prediction, inputs=[user_id], outputs=[labels_sentiment])
|
307 |
+
gr.Markdown(
|
308 |
+
"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 ⭐."
|
309 |
+
)
|
310 |
+
demo.launch(share=False)
|
compile.py
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import onnx
|
2 |
+
import pandas as pd
|
3 |
+
from concrete.ml.deployment import FHEModelDev, FHEModelClient
|
4 |
+
from concrete.ml.onnx.convert import get_equivalent_numpy_forward
|
5 |
+
import json
|
6 |
+
import os
|
7 |
+
import shutil
|
8 |
+
from pathlib import Path
|
9 |
+
|
10 |
+
|
11 |
+
script_dir = Path(__file__).parent
|
12 |
+
|
13 |
+
print("Compiling the model...")
|
14 |
+
|
15 |
+
# Load the onnx model
|
16 |
+
model_onnx = onnx.load(Path.joinpath(script_dir, "sentiment_fhe_model/server_model.onnx"))
|
17 |
+
|
18 |
+
# Load the data from the csv file to be used for compilation
|
19 |
+
data = pd.read_csv(
|
20 |
+
Path.joinpath(script_dir, "sentiment_fhe_model/samples_for_compilation.csv"), index_col=0
|
21 |
+
).values
|
22 |
+
|
23 |
+
# Convert the onnx model to a numpy model
|
24 |
+
_tensor_tree_predict = get_equivalent_numpy_forward(model_onnx)
|
25 |
+
|
26 |
+
model = FHEModelClient(
|
27 |
+
Path.joinpath(script_dir, "sentiment_fhe_model/deployment"), ".fhe_keys"
|
28 |
+
).model
|
29 |
+
|
30 |
+
# Assign the numpy model and compile the model
|
31 |
+
model._tensor_tree_predict = _tensor_tree_predict
|
32 |
+
|
33 |
+
# Compile the model
|
34 |
+
model.compile(data)
|
35 |
+
|
36 |
+
# Load the serialized_processing.json file
|
37 |
+
with open(
|
38 |
+
Path.joinpath(script_dir, "sentiment_fhe_model/deployment/serialized_processing.json"), "r"
|
39 |
+
) as f:
|
40 |
+
serialized_processing = json.load(f)
|
41 |
+
|
42 |
+
# Delete the deployment folder if it exist
|
43 |
+
if Path.joinpath(script_dir, "sentiment_fhe_model/deployment").exists():
|
44 |
+
shutil.rmtree(Path.joinpath(script_dir, "sentiment_fhe_model/deployment"))
|
45 |
+
|
46 |
+
fhe_api = FHEModelDev(
|
47 |
+
model=model, path_dir=Path.joinpath(script_dir, "sentiment_fhe_model/deployment")
|
48 |
+
)
|
49 |
+
fhe_api.save()
|
50 |
+
|
51 |
+
# Write the serialized_processing.json file to the deployment folder
|
52 |
+
with open(
|
53 |
+
Path.joinpath(script_dir, "sentiment_fhe_model/deployment/serialized_processing.json"), "w"
|
54 |
+
) as f:
|
55 |
+
json.dump(serialized_processing, f)
|
56 |
+
|
57 |
+
print("Done!")
|
download_data.sh
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env bash
|
2 |
+
|
3 |
+
set -e
|
4 |
+
|
5 |
+
# You need to have a valid ~/.kaggle/kaggle.json, that you can generate from "Create new API token"
|
6 |
+
# on your account page in kaggle.com
|
7 |
+
rm -rf local_datasets
|
8 |
+
mkdir local_datasets
|
9 |
+
cd local_datasets
|
10 |
+
|
11 |
+
kaggle datasets download -d crowdflower/twitter-airline-sentiment
|
12 |
+
|
13 |
+
unzip twitter-airline-sentiment.zip -d twitter-airline-sentiment
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
concrete-ml==0.4.0
|
2 |
+
gradio==3.1.0
|
3 |
+
pandas==1.4.3
|
4 |
+
uvicorn==0.18.2
|
5 |
+
transformers==4.20.1
|
6 |
+
fastapi==0.79.0
|
7 |
+
jupyter==1.0.0
|
sentiment_fhe_model/deployment/client.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c0f9430bcbd16f40dfcd8547b7c0053be4a5692f5385206fa5ef42e9d3270242
|
3 |
+
size 467
|
sentiment_fhe_model/deployment/serialized_processing.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
sentiment_fhe_model/deployment/server.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:237a28ea8367363255d3e1324841c54938885c7e4a8fff33bc1a49844c997873
|
3 |
+
size 10443
|
sentiment_fhe_model/samples_for_compilation.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|
sentiment_fhe_model/server_model.onnx
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a7af558ac35e722156f82447657103b56371994993d742a0416059db43283d13
|
3 |
+
size 931360
|
server.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Server that will listen for GET requests from the client."""
|
2 |
+
from fastapi import FastAPI
|
3 |
+
from joblib import load
|
4 |
+
from concrete.ml.deployment import FHEModelServer
|
5 |
+
from pydantic import BaseModel
|
6 |
+
import base64
|
7 |
+
from pathlib import Path
|
8 |
+
|
9 |
+
current_dir = Path(__file__).parent
|
10 |
+
|
11 |
+
# Load the model
|
12 |
+
fhe_model = FHEModelServer(Path.joinpath(current_dir, "sentiment_fhe_model/deployment"))
|
13 |
+
|
14 |
+
class PredictRequest(BaseModel):
|
15 |
+
evaluation_key: str
|
16 |
+
encrypted_encoding: str
|
17 |
+
|
18 |
+
# Initialize an instance of FastAPI
|
19 |
+
app = FastAPI()
|
20 |
+
|
21 |
+
# Define the default route
|
22 |
+
@app.get("/")
|
23 |
+
def root():
|
24 |
+
return {"message": "Welcome to Your Sentiment Classification FHE Model Server!"}
|
25 |
+
|
26 |
+
@app.post("/predict_sentiment")
|
27 |
+
def predict_sentiment(query: PredictRequest):
|
28 |
+
encrypted_encoding = base64.b64decode(query.encrypted_encoding)
|
29 |
+
evaluation_key = base64.b64decode(query.evaluation_key)
|
30 |
+
prediction = fhe_model.run(encrypted_encoding, evaluation_key)
|
31 |
+
|
32 |
+
# Encode base64 the prediction
|
33 |
+
encoded_prediction = base64.b64encode(prediction).decode()
|
34 |
+
return {"encrypted_prediction": encoded_prediction}
|
tmp/.gitkeep
ADDED
File without changes
|
transformer_vectorizer.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Let's import a few requirements
|
2 |
+
import torch
|
3 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
4 |
+
import numpy
|
5 |
+
|
6 |
+
class TransformerVectorizer:
|
7 |
+
def __init__(self):
|
8 |
+
# Load the tokenizer (converts text to tokens)
|
9 |
+
self.tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment-latest")
|
10 |
+
|
11 |
+
# Load the pre-trained model
|
12 |
+
self.transformer_model = AutoModelForSequenceClassification.from_pretrained(
|
13 |
+
"cardiffnlp/twitter-roberta-base-sentiment-latest"
|
14 |
+
)
|
15 |
+
self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
16 |
+
|
17 |
+
def text_to_tensor(
|
18 |
+
self,
|
19 |
+
texts: list,
|
20 |
+
) -> numpy.ndarray:
|
21 |
+
"""Function that transforms a list of texts to their learned representation.
|
22 |
+
|
23 |
+
Args:
|
24 |
+
list_text_X (list): List of texts to be transformed.
|
25 |
+
|
26 |
+
Returns:
|
27 |
+
numpy.ndarray: Transformed list of texts.
|
28 |
+
"""
|
29 |
+
# First, tokenize all the input text
|
30 |
+
tokenized_text_X_train = self.tokenizer.batch_encode_plus(
|
31 |
+
texts, return_tensors="pt"
|
32 |
+
)["input_ids"]
|
33 |
+
|
34 |
+
# Depending on the hardware used, the number of examples to be processed can be reduced
|
35 |
+
# Here we split the data into 100 examples per batch
|
36 |
+
tokenized_text_X_train_split = torch.split(tokenized_text_X_train, split_size_or_sections=50)
|
37 |
+
|
38 |
+
# Send the model to the device
|
39 |
+
transformer_model = self.transformer_model.to(self.device)
|
40 |
+
output_hidden_states_list = []
|
41 |
+
|
42 |
+
for tokenized_x in tokenized_text_X_train_split:
|
43 |
+
# Pass the tokens through the transformer model and get the hidden states
|
44 |
+
# Only keep the last hidden layer state for now
|
45 |
+
output_hidden_states = transformer_model(tokenized_x.to(self.device), output_hidden_states=True)[
|
46 |
+
1
|
47 |
+
][-1]
|
48 |
+
# Average over the tokens axis to get a representation at the text level.
|
49 |
+
output_hidden_states = output_hidden_states.mean(dim=1)
|
50 |
+
output_hidden_states = output_hidden_states.detach().cpu().numpy()
|
51 |
+
output_hidden_states_list.append(output_hidden_states)
|
52 |
+
|
53 |
+
self.encodings = numpy.concatenate(output_hidden_states_list, axis=0)
|
54 |
+
return self.encodings
|
55 |
+
|
56 |
+
def transform(self, texts: list):
|
57 |
+
return self.text_to_tensor(texts)
|
58 |
+
|