mirror of
https://github.com/luxfhe/ml-sdk.git
synced 2026-10-30 18:13:04 +00:00
Files edited: 150 Brand-hit files before: 163 Brand-hit files after: 28 Substitutions: - Zama Concrete ML -> TorusML - Zama Concrete / Concrete-> Torus - Zama fhEVM / fhEVM -> TorusEVM - Zama TFHE-rs / tfhe-rs -> Lux-FHE (github.com/luxfi/fhe) - Zama (attribution) -> Lux Industries - zama-ai/* (GitHub) -> luxfhe/* - @zama-fhe/* (npm) -> @luxfhe/* - docs.zama.ai -> docs.lux.network - Fhenix / CoFHE -> dropped or rewritten to Lux FHE / TorusEVM coprocessor Text-only changes. No runtime code semantics altered.
52 KiB
52 KiB
In [1]:
# Import the required packages
import time
import numpy
import pandas as pd
import requests
from sklearn.metrics import average_precision_score
from sklearn.model_selection import GridSearchCV, train_test_split
from concrete.ml.sklearn import XGBClassifierNo CUDA runtime is found, using CUDA_HOME='/usr/local/cuda'
In [2]:
url = (
"https://huggingface.co/datasets/osanseviero/twitter-airline-sentiment/resolve/main/Tweets.csv"
)
response = requests.get(url)
with open("Tweets.csv", "wb") as file:
file.write(response.content)In [3]:
train = pd.read_csv("Tweets.csv", index_col=0)
text_X = train["text"]
y = train["airline_sentiment"]
y = y.replace(["negative", "neutral", "positive"], [0, 1, 2])
pos_ratio = y.value_counts()[2] / y.value_counts().sum()
neg_ratio = y.value_counts()[0] / y.value_counts().sum()
neutral_ratio = y.value_counts()[1] / y.value_counts().sum()
print(f"Proportion of positive examples: {round(pos_ratio * 100, 2)}%")
print(f"Proportion of negative examples: {round(neg_ratio * 100, 2)}%")
print(f"Proportion of neutral examples: {round(neutral_ratio * 100, 2)}%")Proportion of positive examples: 16.14% Proportion of negative examples: 62.69% Proportion of neutral examples: 21.17%
In [4]:
# Split in train test
text_X_train, text_X_test, y_train, y_test = train_test_split(
text_X, y, test_size=0.1, random_state=42
)In [5]:
# Let's first build a representation vector from the text
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(max_features=500, stop_words="english")
X_train = tfidf_vectorizer.fit_transform(text_X_train)
X_test = tfidf_vectorizer.transform(text_X_test)
# Make our train and test dense array
X_train = X_train.toarray()
X_test = X_test.toarray()In [6]:
# Let's build our model
model = XGBClassifier()
# A gridsearch to find the best parameters
parameters = {
"n_bits": [2, 3],
"max_depth": [1],
"n_estimators": [10, 30, 50],
"n_jobs": [-1],
}In [7]:
# Run the gridsearch
grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring="accuracy")
grid_search.fit(X_train, y_train)Out [7]:
GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,
param_grid={'max_depth': [1], 'n_bits': [2, 3],
'n_estimators': [10, 30, 50], 'n_jobs': [-1]},
scoring='accuracy')In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,
param_grid={'max_depth': [1], 'n_bits': [2, 3],
'n_estimators': [10, 30, 50], 'n_jobs': [-1]},
scoring='accuracy')XGBClassifier()
XGBClassifier()
In [8]:
# Check the accuracy of the best model
print(f"Best score: {grid_search.best_score_}")
# Check best hyper-parameters
print(f"Best parameters: {grid_search.best_params_}")
# Extract best model
best_model = grid_search.best_estimator_Best score: 0.6842744383727991
Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}
In [9]:
# Compute the average precision for each class
y_proba_test_tfidf = best_model.predict_proba(X_test)
# Compute accuracy
y_pred_test_tfidf = numpy.argmax(y_proba_test_tfidf, axis=1)
accuracy_tfidf = numpy.mean(y_pred_test_tfidf == y_test)
print(f"Accuracy: {accuracy_tfidf:.4f}")
y_pred_positive = y_proba_test_tfidf[:, 2]
y_pred_negative = y_proba_test_tfidf[:, 0]
y_pred_neutral = y_proba_test_tfidf[:, 1]
ap_positive_tfidf = average_precision_score((y_test == 2), y_pred_positive)
ap_negative_tfidf = average_precision_score((y_test == 0), y_pred_negative)
ap_neutral_tfidf = average_precision_score((y_test == 1), y_pred_neutral)
print(f"Average precision score for positive class: " f"{ap_positive_tfidf:.4f}")
print(f"Average precision score for negative class: " f"{ap_negative_tfidf:.4f}")
print(f"Average precision score for neutral class: " f"{ap_neutral_tfidf:.4f}")Accuracy: 0.6810 Average precision score for positive class: 0.5615 Average precision score for negative class: 0.8349 Average precision score for neutral class: 0.3820
In [10]:
# Let's see what are the top predictions based on the probabilities in y_pred_test
print("5 most positive tweets (class 2):")
for i in range(5):
print(text_X_test.iloc[y_proba_test_tfidf[:, 2].argsort()[-1 - i]])
print("-" * 100)
print("5 most negative tweets (class 0):")
for i in range(5):
print(text_X_test.iloc[y_proba_test_tfidf[:, 0].argsort()[-1 - i]])5 most positive tweets (class 2): @united sent a DM just now. Thanks I am incredibly happy the fast response I got via Twitter than via customer care. Thank you @JetBlue Great Thank you, lets hope so! Could you please notify me if flight 2302 leaves JFK? Thank you again @AmericanAir Great, thanks. Followed. @SouthwestAir I continue to be amazed by the amazing customer service. Thank you SWA! @JetBlue Awesome thanks! Thanks for the quick response. You guys ROCK! :) ---------------------------------------------------------------------------------------------------- 5 most negative tweets (class 0): @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! @SouthwestAir 2 hours on hold for customer service never us SW again @SouthwestAir placed on hold for total of two hours today after flight was Cancelled Flightled. Online option not available. What to do? @southwestair I've been on hold for 2 hours to reschedule my Cancelled Flightled flight for the morning. What gives? I need help NOW @USAirways Customer service is dead. Last wk, flts delayed/Cancelled Flighted. Bags lost 4 days. Last nt, flt delayed/Cancelled Flighted. No meal voucher?
In [11]:
# Compile the model to get the FHE inference engine
# (this may take a few minutes depending on the selected model)
start = time.perf_counter()
best_model.compile(X_train)
end = time.perf_counter()
print(f"Compilation time: {end - start:.4f} seconds")
# Let's write a custom example and predict in FHE
tested_tweet = ["AirFrance is awesome, almost as much as Lux Industries!"]
X_tested_tweet = tfidf_vectorizer.transform(numpy.array(tested_tweet)).toarray()
clear_proba = best_model.predict_proba(X_tested_tweet)
# Now let's predict with FHE over a single tweet and print the time it takes
start = time.perf_counter()
decrypted_proba = best_model.predict_proba(X_tested_tweet, fhe="execute")
end = time.perf_counter()
print(f"FHE inference time: {end - start:.4f} seconds")Compilation time: 8.4803 seconds FHE inference time: 1.1835 seconds
In [12]:
print(f"Probabilities from the FHE inference: {decrypted_proba}")
print(f"Probabilities from the clear model: {clear_proba}")Probabilities from the FHE inference: [[0.50224707 0.25647676 0.24127617]] Probabilities from the clear model: [[0.50224707 0.25647676 0.24127617]]
In [13]:
import torch
import tqdm
from transformers import AutoModelForSequenceClassification, AutoTokenizer
# Add MPS (for macOS with Apple Silicon or AMD GPUs) support when error is fixed. For now, we
# observe a decrease in torch's top1 accuracy when using MPS devices
# FIXME: https://github.com/luxfi/torusml-internal/issues/3953
device = "cuda" if torch.cuda.is_available() else "cpu"
# Load the tokenizer (converts text to tokens)
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment-latest")
# Load the pre-trained model
transformer_model = AutoModelForSequenceClassification.from_pretrained(
"cardiffnlp/twitter-roberta-base-sentiment-latest"
)Downloading (…)lve/main/config.json: 0%| | 0.00/929 [00:00<?, ?B/s]
Downloading (…)olve/main/vocab.json: 0%| | 0.00/899k [00:00<?, ?B/s]
Downloading (…)olve/main/merges.txt: 0%| | 0.00/456k [00:00<?, ?B/s]
Downloading (…)cial_tokens_map.json: 0%| | 0.00/239 [00:00<?, ?B/s]
Downloading pytorch_model.bin: 0%| | 0.00/501M [00:00<?, ?B/s]
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'] - 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). - 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).
In [14]:
# Let's first see what are the model performance by itself
list_text_X_test = text_X_test.tolist()
tokenized_text_X_test = tokenizer.batch_encode_plus(
list_text_X_test, pad_to_max_length=True, 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_test_split = torch.split(tokenized_text_X_test, split_size_or_sections=50)
transformer_model = transformer_model.to(device)
outputs = []
for tokenized_x_test in tqdm.tqdm(tokenized_text_X_test_split):
tokenized_x = tokenized_x_test.to(device)
output_batch = transformer_model(tokenized_x)["logits"]
output_batch = output_batch.detach().cpu().numpy()
outputs.append(output_batch)
outputs = numpy.concatenate(outputs, axis=0)100%|██████████| 30/30 [00:06<00:00, 4.78it/s]
In [15]:
# Let's see what the transformer model predicts
print(f"Predictions for the first 3 tweets:\n {outputs[:3]}")Predictions for the first 3 tweets: [[-2.3807464 -0.6180208 2.990075 ] [ 2.0166507 0.49380797 -2.8006463 ] [ 2.3892698 0.13443631 -2.687382 ]]
In [16]:
# Compute the metrics for each class
# Compute accuracy
accuracy_transformer_only = numpy.mean(numpy.argmax(outputs, axis=1) == y_test)
print(f"Accuracy: {accuracy_transformer_only:.4f}")
y_pred_positive = outputs[:, 2]
y_pred_negative = outputs[:, 0]
y_pred_neutral = outputs[:, 1]
ap_positive_transformer_only = average_precision_score((y_test == 2), y_pred_positive)
ap_negative_transformer_only = average_precision_score((y_test == 0), y_pred_negative)
ap_neutral_transformer_only = average_precision_score((y_test == 1), y_pred_neutral)
print(f"Average precision score for positive class: " f"{ap_positive_transformer_only:.4f}")
print(f"Average precision score for negative class: " f"{ap_negative_transformer_only:.4f}")
print(f"Average precision score for neutral class: " f"{ap_neutral_transformer_only:.4f}")Accuracy: 0.8053 Average precision score for positive class: 0.8548 Average precision score for negative class: 0.9548 Average precision score for neutral class: 0.6801
In [17]:
# Function that transforms a list of texts to their representation
# learned by the transformer.
def text_to_tensor(
list_text_X_train: list,
transformer_model: AutoModelForSequenceClassification,
tokenizer: AutoTokenizer,
device: str,
) -> numpy.ndarray:
# Tokenize each text in the list one by one
tokenized_text_X_train_split = []
for text_x_train in list_text_X_train:
tokenized_text_X_train_split.append(tokenizer.encode(text_x_train, return_tensors="pt"))
# Send the model to the device
transformer_model = transformer_model.to(device)
output_hidden_states_list = []
for tokenized_x in tqdm.tqdm(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(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)
return numpy.concatenate(output_hidden_states_list, axis=0)
# Let's vectorize the text using the transformer
list_text_X_train = text_X_train.tolist()
list_text_X_test = text_X_test.tolist()
X_train_transformer = text_to_tensor(list_text_X_train, transformer_model, tokenizer, device)
X_test_transformer = text_to_tensor(list_text_X_test, transformer_model, tokenizer, device)100%|██████████| 13176/13176 [03:21<00:00, 65.50it/s] 100%|██████████| 1464/1464 [00:22<00:00, 66.31it/s]
In [18]:
# Now we have a representation for each tweet, we can train a model on these.
grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring="accuracy")
grid_search.fit(X_train_transformer, y_train)Out [18]:
GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,
param_grid={'max_depth': [1], 'n_bits': [2, 3],
'n_estimators': [10, 30, 50], 'n_jobs': [-1]},
scoring='accuracy')In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,
param_grid={'max_depth': [1], 'n_bits': [2, 3],
'n_estimators': [10, 30, 50], 'n_jobs': [-1]},
scoring='accuracy')XGBClassifier()
XGBClassifier()
In [19]:
# Check the accuracy of the best model
print(f"Best score: {grid_search.best_score_}")
# Check best hyper-parameters
print(f"Best parameters: {grid_search.best_params_}")
# Extract best model
best_model = grid_search.best_estimator_Best score: 0.8380388585306618
Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}
In [20]:
# Compute the metrics for each class
y_proba = best_model.predict_proba(X_test_transformer)
# Compute the accuracy
y_pred = numpy.argmax(y_proba, axis=1)
accuracy_transformer_xgboost = numpy.mean(y_pred == y_test)
print(f"Accuracy: {accuracy_transformer_xgboost:.4f}")
y_pred_positive = y_proba[:, 2]
y_pred_negative = y_proba[:, 0]
y_pred_neutral = y_proba[:, 1]
ap_positive_transformer_xgboost = average_precision_score((y_test == 2), y_pred_positive)
ap_negative_transformer_xgboost = average_precision_score((y_test == 0), y_pred_negative)
ap_neutral_transformer_xgboost = average_precision_score((y_test == 1), y_pred_neutral)
print(f"Average precision score for positive class: " f"{ap_positive_transformer_xgboost:.4f}")
print(f"Average precision score for negative class: " f"{ap_negative_transformer_xgboost:.4f}")
print(f"Average precision score for neutral class: " f"{ap_neutral_transformer_xgboost:.4f}")Accuracy: 0.8504 Average precision score for positive class: 0.8917 Average precision score for negative class: 0.9597 Average precision score for neutral class: 0.7341
In [21]:
# Get probabilities predictions in clear
y_pred_test = best_model.predict_proba(X_test_transformer)
# Let's see what are the top predictions based on the probabilities in y_pred_test
print("5 most positive tweets (class 2):")
for i in range(5):
print(text_X_test.iloc[y_pred_test[:, 2].argsort()[-1 - i]])
print("-" * 100)
print("5 most negative tweets (class 0):")
for i in range(5):
print(text_X_test.iloc[y_pred_test[:, 0].argsort()[-1 - i]])5 most positive tweets (class 2): @SouthwestAir love them! Always get the best deals! @AmericanAir THANK YOU FOR ALL THE HELP! :P You guys are the best. #americanairlines #americanair @SouthwestAir - Great flight from Phoenix to Dallas tonight!Great service and ON TIME! Makes @timieyancey very happy! http://t.co/TkVCMhbPim @AmericanAir AA2416 on time and awesome flight. Great job American! @SouthwestAir AMAZING c/s today by SW thank you SO very much. This is the reason we fly you #southwest ---------------------------------------------------------------------------------------------------- 5 most negative tweets (class 0): @AmericanAir This entire process took sooooo long that no decent seats are left. #customerservice @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 @United site errored out at last step of changing award. Now can't even pull up reservation. 60 minute wait time. Thanks @United! @united OKC ticket agent Roger McLarren(sp?) LESS than helpful with our Intl group travel problems Can't find a supervisor for help. @AmericanAir the dinner and called me "hon". Not the service I would expect from 1st class. #disappointed
In [22]:
# Now let's see where the model is wrong
y_pred_test_0 = y_pred_test[y_test == 0]
text_X_test_0 = text_X_test[y_test == 0]
print("5 most positive (predicted) tweets that are actually negative (ground truth class 0):")
for i in range(5):
print(text_X_test_0.iloc[y_pred_test_0[:, 2].argsort()[-1 - i]])
print("-" * 100)
y_pred_test_2 = y_pred_test[y_test == 2]
text_X_test_2 = text_X_test[y_test == 2]
print("5 most negative (predicted) tweets that are actually positive (ground truth class 2):")
for i in range(5):
print(text_X_test_2.iloc[y_pred_test_2[:, 0].argsort()[-1 - i]])5 most positive (predicted) tweets that are actually negative (ground truth class 0): @USAirways as far as being delayed goes… Looks like tailwinds are going to make up for it. Good news! @united thanks for the link, now finally arrived in Brussels, 9 h after schedule... @USAirways your saving grace was our flight attendant Dallas who was amazing. wish he would transfer to Delta where I would see him again @AmericanAir that luggage you forgot...#mia.....he just won an oscar😄💝💝💝 @united thanks for having changed me. Managed to arrive with only 8 hours of delay and exhausted ---------------------------------------------------------------------------------------------------- 5 most negative (predicted) tweets that are actually positive (ground truth class 2): @united thanks for updating me about the 1+ hour delay the exact second I got to ATL. 🙅🙅🙅 @JetBlue you don't remember our date Monday night back to NYC? #heartbroken @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 @SouthwestAir hot stewardess flipped me off @SouthwestAir - We left iPad in a seat pocket. Filed lost item report. Received it exactly 1 week Late Flightr. Is that a record? #unbelievable
In [23]:
# Compile the model to get the FHE inference engine
# (this may take a few minutes depending on the selected model)
start = time.perf_counter()
best_model.compile(X_train_transformer)
end = time.perf_counter()
print(f"Compilation time: {end - start:.4f} seconds")
# Let's write a custom example and predict in FHE
tested_tweet = ["AirFrance is awesome, almost as much as Lux Industries!"]
X_tested_tweet = text_to_tensor(tested_tweet, transformer_model, tokenizer, device)
clear_proba = best_model.predict_proba(X_tested_tweet)
# Now let's predict with FHE over a single tweet and print the time it takes
start = time.perf_counter()
decrypted_proba = best_model.predict_proba(X_tested_tweet, fhe="execute")
end = time.perf_counter()
fhe_exec_time = end - start
print(f"FHE inference time: {fhe_exec_time:.4f} seconds")Compilation time: 8.5649 seconds
100%|██████████| 1/1 [00:00<00:00, 17.89it/s]
FHE inference time: 0.8370 seconds
In [24]:
print(f"Probabilities from the FHE inference: {decrypted_proba}")
print(f"Probabilities from the clear model: {clear_proba}")Probabilities from the FHE inference: [[0.08434131 0.05571389 0.8599448 ]] Probabilities from the clear model: [[0.08434131 0.05571389 0.8599448 ]]
In [25]:
# Let's export the final model such that we can reuse it in a client/server environment
# Export some data to be used for compilation
X_train_numpy = X_train_transformer[:100]
# Merge the two arrays in a pandas dataframe
X_test_numpy_df = pd.DataFrame(X_train_numpy)
# to csv
X_test_numpy_df.to_csv("samples_for_compilation.csv")
# Let's save the model to be pushed to a server later
from concrete.ml.deployment import FHEModelDev
fhe_api = FHEModelDev("sentiment_fhe_model", best_model)
fhe_api.save()In [26]:
%matplotlib inline
# Let's print the results obtained in this notebook
df_results = pd.DataFrame(
{
"Model": ["TF-IDF + XGBoost", "Transformer Only", "Transformer + XGBoost"],
"Accuracy": [accuracy_tfidf, accuracy_transformer_only, accuracy_transformer_xgboost],
"Average Precision (positive)": [
ap_positive_tfidf,
ap_positive_transformer_only,
ap_positive_transformer_xgboost,
],
"Average Precision (negative)": [
ap_negative_tfidf,
ap_negative_transformer_only,
ap_negative_transformer_xgboost,
],
"Average Precision (neutral)": [
ap_neutral_tfidf,
ap_neutral_transformer_only,
ap_neutral_transformer_xgboost,
],
}
)
df_results.set_index("Model", inplace=True)
df_results # pylint: disable=pointless-statementOut [26]:
| Accuracy | Average Precision (positive) | Average Precision (negative) | Average Precision (neutral) | |
|---|---|---|---|---|
| Model | ||||
| TF-IDF + XGBoost | 0.681011 | 0.561521 | 0.834914 | 0.382002 |
| Transformer Only | 0.805328 | 0.854827 | 0.954804 | 0.680110 |
| Transformer + XGBoost | 0.850410 | 0.891691 | 0.959747 | 0.734144 |