Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 51,541 Bytes
2dcbc14 4d9e29f 2dcbc14 4d9e29f 2dcbc14 f3bcea6 2dcbc14 f3bcea6 2dcbc14 4d9e29f 2dcbc14 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Sentiment Classification with FHE\n",
"\n",
"This notebook tackles sentiment classification with Fully Homomorphic Encryption. Let's imagine some client (could be a user or a company) wants to predict whether a specific text (e.g., a tweet) contains positive, neutral or negative feedback using a cloud service provider without actually revealing the text during the process.\n",
"\n",
"To do this, we use a machine learning model that can predict over encrypted data thanks to the Concrete-ML library available on [GitHub](https://github.com/zama-ai/concrete-ml).\n",
"\n",
"The dataset we use in this notebook can be found on [Kaggle](https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment). \n",
" \n",
"We present two different ways to encode the text:\n",
"1. A basic **TF-IDF** approach, which essentially looks at how often a word appears in the text.\n",
"2. An advanced **transformer** embedding of the text using the Huggingface repository.\n",
"\n",
"The main assumption of this notebook is that clients, who want to have their text analyzed in a privacy preserving manner, can encode the text using a predefined representation before encrypting the data. The FHE-friendly model is thus trained in the clear beforehand for the given task, here classification, over theses representations using a relevant training set."
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# Import the required packages\n",
"import os\n",
"import time\n",
"\n",
"import numpy\n",
"import onnx\n",
"import pandas as pd\n",
"from sklearn.metrics import average_precision_score\n",
"from sklearn.model_selection import GridSearchCV, train_test_split\n",
"\n",
"from concrete.ml.sklearn import XGBClassifier"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Proportion of positive examples: 16.14%\n",
"Proportion of negative examples: 62.69%\n",
"Proportion of neutral examples: 21.17%\n"
]
}
],
"source": [
"# Download the datasets\n",
"# The dataset can be downloaded through the `download_data.sh` script, which requires to set up\n",
"# Kaggle's CLI, or manually at https://www.kaggle.com/datasets/crowdflower/twitter-airline-sentiment\n",
"if not os.path.isfile(\"local_datasets/twitter-airline-sentiment/Tweets.csv\"):\n",
" raise ValueError(\"Please launch the `download_data.sh` script to get datasets\")\n",
"\n",
"\n",
"train = pd.read_csv(\"local_datasets/twitter-airline-sentiment/Tweets.csv\", index_col=0)\n",
"text_X = train[\"text\"]\n",
"y = train[\"airline_sentiment\"]\n",
"y = y.replace([\"negative\", \"neutral\", \"positive\"], [0, 1, 2])\n",
"\n",
"pos_ratio = y.value_counts()[2] / y.value_counts().sum()\n",
"neg_ratio = y.value_counts()[0] / y.value_counts().sum()\n",
"neutral_ratio = y.value_counts()[1] / y.value_counts().sum()\n",
"print(f\"Proportion of positive examples: {round(pos_ratio * 100, 2)}%\")\n",
"print(f\"Proportion of negative examples: {round(neg_ratio * 100, 2)}%\")\n",
"print(f\"Proportion of neutral examples: {round(neutral_ratio * 100, 2)}%\")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"# Split in train test\n",
"text_X_train, text_X_test, y_train, y_test = train_test_split(\n",
" text_X, y, test_size=0.1, random_state=42\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 1. Text representation using TF-IDF\n",
"\n",
"[Term Frequency-Inverse Document Frequency](https://en.wikipedia.org/wiki/Tf%E2%80%93idf)(TF-IDF) also known as is a numerical statistic that is used to compute the importance of a term in a document. The higher the TF-IDF score, the more important the term is to the document.\n",
"\n",
"We compute it as follows:\n",
"\n",
"$$ \\mathsf{TF\\textrm{-}IDF}(t,d,D) = \\mathsf{TF}(t,d) * \\mathsf{IDF}(t,D) $$\n",
"\n",
"where: $\\mathsf{TF}(t,d)$ is the term frequency of term $t$ in document $d$, $\\mathsf{IDF}(t,D)$ is the inverse document frequency of term $t$ in document collection $D$.\n",
"\n",
"Here we use the scikit-learn implementation of TF-IDF vectorizer."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"# Let's first build a representation vector from the text\n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"\n",
"tfidf_vectorizer = TfidfVectorizer(max_features=500, stop_words=\"english\")\n",
"X_train = tfidf_vectorizer.fit_transform(text_X_train)\n",
"X_test = tfidf_vectorizer.transform(text_X_test)\n",
"\n",
"# Make our train and test dense array\n",
"X_train = X_train.toarray()\n",
"X_test = X_test.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"# Let's build our model\n",
"model = XGBClassifier()\n",
"\n",
"# A gridsearch to find the best parameters\n",
"parameters = {\n",
" \"n_bits\": [2, 3],\n",
" \"max_depth\": [1],\n",
" \"n_estimators\": [10, 30, 50],\n",
" \"n_jobs\": [-1],\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<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",
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
" scoring='accuracy')</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-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",
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
" scoring='accuracy')</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-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>"
],
"text/plain": [
"GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
" scoring='accuracy')"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Run the gridsearch\n",
"grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n",
"grid_search.fit(X_train, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Best score: 0.6842744383727991\n",
"Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n"
]
}
],
"source": [
"# Check the accuracy of the best model\n",
"print(f\"Best score: {grid_search.best_score_}\")\n",
"\n",
"# Check best hyperparameters\n",
"print(f\"Best parameters: {grid_search.best_params_}\")\n",
"\n",
"# Extract best model\n",
"best_model = grid_search.best_estimator_"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accuracy: 0.6810\n",
"Average precision score for positive class: 0.5615\n",
"Average precision score for negative class: 0.8349\n",
"Average precision score for neutral class: 0.3820\n"
]
}
],
"source": [
"# Compute the average precision for each class\n",
"y_proba_test_tfidf = best_model.predict_proba(X_test)\n",
"\n",
"# Compute accuracy\n",
"y_pred_test_tfidf = numpy.argmax(y_proba_test_tfidf, axis=1)\n",
"accuracy_tfidf = numpy.mean(y_pred_test_tfidf == y_test)\n",
"print(f\"Accuracy: {accuracy_tfidf:.4f}\")\n",
"\n",
"y_pred_positive = y_proba_test_tfidf[:, 2]\n",
"y_pred_negative = y_proba_test_tfidf[:, 0]\n",
"y_pred_neutral = y_proba_test_tfidf[:, 1]\n",
"\n",
"ap_positive_tfidf = average_precision_score((y_test == 2), y_pred_positive)\n",
"ap_negative_tfidf = average_precision_score((y_test == 0), y_pred_negative)\n",
"ap_neutral_tfidf = average_precision_score((y_test == 1), y_pred_neutral)\n",
"\n",
"print(f\"Average precision score for positive class: \" f\"{ap_positive_tfidf:.4f}\")\n",
"print(f\"Average precision score for negative class: \" f\"{ap_negative_tfidf:.4f}\")\n",
"print(f\"Average precision score for neutral class: \" f\"{ap_neutral_tfidf:.4f}\")"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 most positive tweets (class 2):\n",
"@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",
"@JetBlue Great Thank you, lets hope so! Could you please notify me if flight 2302 leaves JFK? Thank you again\n",
"@AmericanAir Great, thanks. Followed.\n",
"@SouthwestAir I continue to be amazed by the amazing customer service. Thank you SWA!\n",
"@JetBlue Awesome thanks! Thanks for the quick response. You guys ROCK! :)\n",
"----------------------------------------------------------------------------------------------------\n",
"5 most negative tweets (class 0):\n",
"@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",
"@SouthwestAir 2 hours on hold for customer service never us SW again\n",
"@SouthwestAir placed on hold for total of two hours today after flight was Cancelled Flightled. Online option not available. What to do?\n",
"@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",
"@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"
]
}
],
"source": [
"# Let's see what are the top predictions based on the probabilities in y_pred_test\n",
"print(\"5 most positive tweets (class 2):\")\n",
"for i in range(5):\n",
" print(text_X_test.iloc[y_proba_test_tfidf[:, 2].argsort()[-1 - i]])\n",
"\n",
"print(\"-\" * 100)\n",
"\n",
"print(\"5 most negative tweets (class 0):\")\n",
"for i in range(5):\n",
" print(text_X_test.iloc[y_proba_test_tfidf[:, 0].argsort()[-1 - i]])"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Compilation time: 11.5009 seconds\n",
"FHE inference time: 48.6880 seconds\n"
]
}
],
"source": [
"# Compile the model to get the FHE inference engine\n",
"# (this may take a few minutes depending on the selected model)\n",
"start = time.perf_counter()\n",
"best_model.compile(X_train)\n",
"end = time.perf_counter()\n",
"print(f\"Compilation time: {end - start:.4f} seconds\")\n",
"\n",
"# Let's write a custom example and predict in FHE\n",
"tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n",
"X_tested_tweet = tfidf_vectorizer.transform(numpy.array(tested_tweet)).toarray()\n",
"clear_proba = best_model.predict_proba(X_tested_tweet)\n",
"\n",
"# Now let's predict with FHE over a single tweet and print the time it takes\n",
"start = time.perf_counter()\n",
"decrypted_proba = best_model.predict_proba(X_tested_tweet, execute_in_fhe=True)\n",
"end = time.perf_counter()\n",
"print(f\"FHE inference time: {end - start:.4f} seconds\")"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Probabilities from the FHE inference: [[0.50224707 0.25647676 0.24127617]]\n",
"Probabilities from the clear model: [[0.50224707 0.25647676 0.24127617]]\n"
]
}
],
"source": [
"print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n",
"print(f\"Probabilities from the clear model: {clear_proba}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To sum up, \n",
"- We trained a XGBoost model over TF-IDF representation of the tweets and their respective sentiment class. \n",
"- The grid search gives us a model that achieves around ~70% accuracy.\n",
"- Given the imbalance in the classes, we rather compute the average precision per class.\n",
"\n",
"Now we will see how we can approach the problem by leveraging the transformers power."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 2. A transformer approach to text representation\n",
"\n",
"[**Transformers**](https://en.wikipedia.org/wiki/Transformer_(machine_learning_model\\)) are neural networks that are often trained to predict the next words to appear in a text (this is commonly called self-supervised learning). \n",
"\n",
"They are powerful tools for all kind of Natural Language Processing tasks but supporting a transformer model in FHE might not always be ideal as they are quite big models. However, we can still leverage their hidden representation for any text and feed it to a more FHE friendly machine learning model (in this notebook we will use XGBoost) for classification.\n",
"\n",
"Here we will use the transformer model from the amazing [**Huggingface**](https://huggingface.co/) repository."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Some weights of the model checkpoint at cardiffnlp/twitter-roberta-base-sentiment-latest were not used when initializing RobertaForSequenceClassification: ['roberta.pooler.dense.bias', 'roberta.pooler.dense.weight']\n",
"- This IS expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
"- This IS NOT expected if you are initializing RobertaForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n"
]
}
],
"source": [
"import torch\n",
"import tqdm\n",
"from transformers import AutoModelForSequenceClassification, AutoTokenizer\n",
"\n",
"device = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n",
"\n",
"# Load the tokenizer (converts text to tokens)\n",
"tokenizer = AutoTokenizer.from_pretrained(\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\n",
"\n",
"# Load the pre-trained model\n",
"transformer_model = AutoModelForSequenceClassification.from_pretrained(\n",
" \"cardiffnlp/twitter-roberta-base-sentiment-latest\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|ββββββββββ| 30/30 [00:33<00:00, 1.10s/it]\n"
]
}
],
"source": [
"# Let's first see what are the model performance by itself\n",
"list_text_X_test = text_X_test.tolist()\n",
"\n",
"tokenized_text_X_test = tokenizer.batch_encode_plus(\n",
" list_text_X_test, pad_to_max_length=True, return_tensors=\"pt\"\n",
")[\"input_ids\"]\n",
"\n",
"# Depending on the hardware used, the number of examples to be processed can be reduced\n",
"# Here we split the data into 100 examples per batch\n",
"tokenized_text_X_test_split = torch.split(tokenized_text_X_test, split_size_or_sections=50)\n",
"transformer_model = transformer_model.to(device)\n",
"\n",
"outputs = []\n",
"for tokenized_x_test in tqdm.tqdm(tokenized_text_X_test_split):\n",
" tokenized_x = tokenized_x_test.to(device)\n",
" output_batch = transformer_model(tokenized_x)[\"logits\"]\n",
" output_batch = output_batch.detach().cpu().numpy()\n",
" outputs.append(output_batch)\n",
"\n",
"outputs = numpy.concatenate(outputs, axis=0)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Predictions for the first 3 tweets:\n",
" [[-2.3807464 -0.61802083 2.9900746 ]\n",
" [ 2.0166504 0.4938078 -2.8006463 ]\n",
" [ 2.3892698 0.1344364 -2.6873822 ]]\n"
]
}
],
"source": [
"# Let's see what the transformer model predicts\n",
"print(f\"Predictions for the first 3 tweets:\\n {outputs[:3]}\")"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accuracy: 0.8053\n",
"Average precision score for positive class: 0.8548\n",
"Average precision score for negative class: 0.9548\n",
"Average precision score for neutral class: 0.6801\n"
]
}
],
"source": [
"# Compute the metrics for each class\n",
"\n",
"# Compute accuracy\n",
"accuracy_transformer_only = numpy.mean(numpy.argmax(outputs, axis=1) == y_test)\n",
"print(f\"Accuracy: {accuracy_transformer_only:.4f}\")\n",
"\n",
"y_pred_positive = outputs[:, 2]\n",
"y_pred_negative = outputs[:, 0]\n",
"y_pred_neutral = outputs[:, 1]\n",
"\n",
"ap_positive_transformer_only = average_precision_score((y_test == 2), y_pred_positive)\n",
"ap_negative_transformer_only = average_precision_score((y_test == 0), y_pred_negative)\n",
"ap_neutral_transformer_only = average_precision_score((y_test == 1), y_pred_neutral)\n",
"\n",
"print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_only:.4f}\")\n",
"print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_only:.4f}\")\n",
"print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_only:.4f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It looks like the transformer outperforms the model built on TF-IDF reprensentation.\n",
"Unfortunately, running a transformer that big in FHE would be highly inefficient. \n",
"\n",
"Let's see if we can leverage transformer representation and train a FHE model for the given classification task. "
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|ββββββββββ| 13176/13176 [07:20<00:00, 29.91it/s]\n",
"100%|ββββββββββ| 1464/1464 [00:47<00:00, 30.75it/s]\n"
]
}
],
"source": [
"# Function that transforms a list of texts to their representation\n",
"# learned by the transformer.\n",
"def text_to_tensor(\n",
" list_text_X_train: list,\n",
" transformer_model: AutoModelForSequenceClassification,\n",
" tokenizer: AutoTokenizer,\n",
" device: str,\n",
") -> numpy.ndarray:\n",
" # Tokenize each text in the list one by one\n",
" tokenized_text_X_train_split = []\n",
" for text_x_train in list_text_X_train:\n",
" tokenized_text_X_train_split.append(tokenizer.encode(text_x_train, return_tensors=\"pt\"))\n",
"\n",
" # Send the model to the device\n",
" transformer_model = transformer_model.to(device)\n",
" output_hidden_states_list = []\n",
"\n",
" for tokenized_x in tqdm.tqdm(tokenized_text_X_train_split):\n",
" # Pass the tokens through the transformer model and get the hidden states\n",
" # Only keep the last hidden layer state for now\n",
" output_hidden_states = transformer_model(tokenized_x.to(device), output_hidden_states=True)[\n",
" 1\n",
" ][-1]\n",
" # Average over the tokens axis to get a representation at the text level.\n",
" output_hidden_states = output_hidden_states.mean(dim=1)\n",
" output_hidden_states = output_hidden_states.detach().cpu().numpy()\n",
" output_hidden_states_list.append(output_hidden_states)\n",
"\n",
" return numpy.concatenate(output_hidden_states_list, axis=0)\n",
"\n",
"\n",
"# Let's vectorize the text using the transformer\n",
"list_text_X_train = text_X_train.tolist()\n",
"list_text_X_test = text_X_test.tolist()\n",
"\n",
"X_train_transformer = text_to_tensor(list_text_X_train, transformer_model, tokenizer, device)\n",
"X_test_transformer = text_to_tensor(list_text_X_test, transformer_model, tokenizer, device)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"βΈ\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"βΎ\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
" scoring='accuracy')</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item sk-dashed-wrapped\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" ><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">GridSearchCV</label><div class=\"sk-toggleable__content\"><pre>GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
" scoring='accuracy')</pre></div></div></div><div class=\"sk-parallel\"><div class=\"sk-parallel-item\"><div class=\"sk-item\"><div class=\"sk-label-container\"><div class=\"sk-label sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-5\" type=\"checkbox\" ><label for=\"sk-estimator-id-5\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">estimator: XGBClassifier</label><div class=\"sk-toggleable__content\"><pre>XGBClassifier()</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>"
],
"text/plain": [
"GridSearchCV(cv=3, estimator=XGBClassifier(), n_jobs=1,\n",
" param_grid={'max_depth': [1], 'n_bits': [2, 3],\n",
" 'n_estimators': [10, 30, 50], 'n_jobs': [-1]},\n",
" scoring='accuracy')"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Now we have a representation for each tweet, we can train a model on these.\n",
"grid_search = GridSearchCV(model, parameters, cv=3, n_jobs=1, scoring=\"accuracy\")\n",
"grid_search.fit(X_train_transformer, y_train)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Best score: 0.8378111718275654\n",
"Best parameters: {'max_depth': 1, 'n_bits': 3, 'n_estimators': 50, 'n_jobs': -1}\n"
]
}
],
"source": [
"# Check the accuracy of the best model\n",
"print(f\"Best score: {grid_search.best_score_}\")\n",
"\n",
"# Check best hyperparameters\n",
"print(f\"Best parameters: {grid_search.best_params_}\")\n",
"\n",
"# Extract best model\n",
"best_model = grid_search.best_estimator_"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Accuracy: 0.8504\n",
"Average precision score for positive class: 0.8917\n",
"Average precision score for negative class: 0.9597\n",
"Average precision score for neutral class: 0.7341\n"
]
}
],
"source": [
"# Compute the metrics for each class\n",
"\n",
"y_proba = best_model.predict_proba(X_test_transformer)\n",
"\n",
"# Compute the accuracy\n",
"y_pred = numpy.argmax(y_proba, axis=1)\n",
"accuracy_transformer_xgboost = numpy.mean(y_pred == y_test)\n",
"print(f\"Accuracy: {accuracy_transformer_xgboost:.4f}\")\n",
"\n",
"y_pred_positive = y_proba[:, 2]\n",
"y_pred_negative = y_proba[:, 0]\n",
"y_pred_neutral = y_proba[:, 1]\n",
"\n",
"ap_positive_transformer_xgboost = average_precision_score((y_test == 2), y_pred_positive)\n",
"ap_negative_transformer_xgboost = average_precision_score((y_test == 0), y_pred_negative)\n",
"ap_neutral_transformer_xgboost = average_precision_score((y_test == 1), y_pred_neutral)\n",
"\n",
"print(f\"Average precision score for positive class: \" f\"{ap_positive_transformer_xgboost:.4f}\")\n",
"print(f\"Average precision score for negative class: \" f\"{ap_negative_transformer_xgboost:.4f}\")\n",
"print(f\"Average precision score for neutral class: \" f\"{ap_neutral_transformer_xgboost:.4f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Our FHE-friendly XGBoost model does 38% better than the XGBoost model built over TF-IDF representation of the text. Note that here we are still not using FHE and only evaluating the model.\n",
"Interestingly, using XGBoost over the transformer representation of the text matches the performance of the transformer model alone."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 most positive tweets (class 2):\n",
"@SouthwestAir love them! Always get the best deals!\n",
"@AmericanAir THANK YOU FOR ALL THE HELP! :P You guys are the best. #americanairlines #americanair\n",
"@SouthwestAir - Great flight from Phoenix to Dallas tonight!Great service and ON TIME! Makes @timieyancey very happy! http://t.co/TkVCMhbPim\n",
"@AmericanAir AA2416 on time and awesome flight. Great job American!\n",
"@SouthwestAir AMAZING c/s today by SW thank you SO very much. This is the reason we fly you #southwest\n",
"----------------------------------------------------------------------------------------------------\n",
"5 most negative tweets (class 0):\n",
"@AmericanAir This entire process took sooooo long that no decent seats are left. #customerservice\n",
"@USAirways Not only did u lose the flight plan! Now ur flight crew is FAA timed out! Thx for havin us sit on the tarmac for an hr! #Pathetic\n",
"@United site errored out at last step of changing award. Now can't even pull up reservation. 60 minute wait time. Thanks @United!\n",
"@united OKC ticket agent Roger McLarren(sp?) LESS than helpful with our Intl group travel problems Can't find a supervisor for help.\n",
"@AmericanAir the dinner and called me \"hon\". Not the service I would expect from 1st class. #disappointed\n"
]
}
],
"source": [
"# Get probabilities predictions in clear\n",
"y_pred_test = best_model.predict_proba(X_test_transformer)\n",
"\n",
"# Let's see what are the top predictions based on the probabilities in y_pred_test\n",
"print(\"5 most positive tweets (class 2):\")\n",
"for i in range(5):\n",
" print(text_X_test.iloc[y_pred_test[:, 2].argsort()[-1 - i]])\n",
"\n",
"print(\"-\" * 100)\n",
"\n",
"print(\"5 most negative tweets (class 0):\")\n",
"for i in range(5):\n",
" print(text_X_test.iloc[y_pred_test[:, 0].argsort()[-1 - i]])"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 most positive (predicted) tweets that are actually negative (ground truth class 0):\n",
"@USAirways as far as being delayed goes⦠Looks like tailwinds are going to make up for it. Good news!\n",
"@united thanks for the link, now finally arrived in Brussels, 9 h after schedule...\n",
"@USAirways your saving grace was our flight attendant Dallas who was amazing. wish he would transfer to Delta where I would see him again\n",
"@AmericanAir that luggage you forgot...#mia.....he just won an oscarππππ\n",
"@united thanks for having changed me. Managed to arrive with only 8 hours of delay and exhausted\n",
"----------------------------------------------------------------------------------------------------\n",
"5 most negative (predicted) tweets that are actually positive (ground truth class 2):\n",
"@united thanks for updating me about the 1+ hour delay the exact second I got to ATL. π
π
π
\n",
"@JetBlue you don't remember our date Monday night back to NYC? #heartbroken\n",
"@SouthwestAir save mile to visit family in 2015 and this will impact how many times I can see my mother. I planned and you change the rules\n",
"@SouthwestAir hot stewardess flipped me off\n",
"@SouthwestAir - We left iPad in a seat pocket. Filed lost item report. Received it exactly 1 week Late Flightr. Is that a record? #unbelievable\n"
]
}
],
"source": [
"# Now let's see where the model is wrong\n",
"y_pred_test_0 = y_pred_test[y_test == 0]\n",
"text_X_test_0 = text_X_test[y_test == 0]\n",
"\n",
"print(\"5 most positive (predicted) tweets that are actually negative (ground truth class 0):\")\n",
"for i in range(5):\n",
" print(text_X_test_0.iloc[y_pred_test_0[:, 2].argsort()[-1 - i]])\n",
"\n",
"print(\"-\" * 100)\n",
"\n",
"y_pred_test_2 = y_pred_test[y_test == 2]\n",
"text_X_test_2 = text_X_test[y_test == 2]\n",
"print(\"5 most negative (predicted) tweets that are actually positive (ground truth class 2):\")\n",
"for i in range(5):\n",
" print(text_X_test_2.iloc[y_pred_test_2[:, 0].argsort()[-1 - i]])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Interestingly, these misclassifications are not obvious and some actually look rather like mislabeled. Also, it seems that the model is having a hard time to find ironic tweets.\n",
"\n",
"Now we have our model trained which has some great accuracy. Let's have it predict over the encrypted representation."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Sentiment Analysis of the Tweet with Fully Homomorphic Encryption\n",
"\n",
"Now that we have our model ready for FHE inference and our data ready for encryption let's use the model in a privacy preserving manner with FHE."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Compilation time: 12.6855 seconds\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"100%|ββββββββββ| 1/1 [00:00<00:00, 36.43it/s]\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"FHE inference time: 53.0192 seconds\n"
]
}
],
"source": [
"# Compile the model to get the FHE inference engine\n",
"# (this may take a few minutes depending on the selected model)\n",
"start = time.perf_counter()\n",
"best_model.compile(X_train_transformer)\n",
"end = time.perf_counter()\n",
"print(f\"Compilation time: {end - start:.4f} seconds\")\n",
"\n",
"\n",
"# Let's write a custom example and predict in FHE\n",
"tested_tweet = [\"AirFrance is awesome, almost as much as Zama!\"]\n",
"X_tested_tweet = text_to_tensor(tested_tweet, transformer_model, tokenizer, device)\n",
"clear_proba = best_model.predict_proba(X_tested_tweet)\n",
"\n",
"# Now let's predict with FHE over a single tweet and print the time it takes\n",
"start = time.perf_counter()\n",
"decrypted_proba = best_model.predict_proba(X_tested_tweet, execute_in_fhe=True)\n",
"end = time.perf_counter()\n",
"fhe_exec_time = end - start\n",
"print(f\"FHE inference time: {fhe_exec_time:.4f} seconds\")"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Probabilities from the FHE inference: [[0.08434131 0.05571389 0.8599448 ]]\n",
"Probabilities from the clear model: [[0.08434131 0.05571389 0.8599448 ]]\n"
]
}
],
"source": [
"print(f\"Probabilities from the FHE inference: {decrypted_proba}\")\n",
"print(f\"Probabilities from the clear model: {clear_proba}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Let's export the final model such that we can reuse it in a client/server environment\n",
"\n",
"# Export the model to ONNX\n",
"onnx.save(best_model._onnx_model_, \"server_model.onnx\") # pylint: disable=protected-access\n",
"\n",
"# Export some data to be used for compilation\n",
"X_train_numpy = X_train_transformer[:100]\n",
"\n",
"# Merge the two arrays in a pandas dataframe\n",
"X_test_numpy_df = pd.DataFrame(X_train_numpy)\n",
"\n",
"# to csv\n",
"X_test_numpy_df.to_csv(\"samples_for_compilation.csv\")\n",
"\n",
"# Let's save the model to be pushed to a server later\n",
"from concrete.ml.deployment import FHEModelDev\n",
"\n",
"fhe_api = FHEModelDev(\"sentiment_fhe_model\", best_model)\n",
"fhe_api.save()"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>Accuracy</th>\n",
" <th>Average Precision (positive)</th>\n",
" <th>Average Precision (negative)</th>\n",
" <th>Average Precision (neutral)</th>\n",
" </tr>\n",
" <tr>\n",
" <th>Model</th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>TF-IDF + XGBoost</th>\n",
" <td>0.681011</td>\n",
" <td>0.561521</td>\n",
" <td>0.834914</td>\n",
" <td>0.382002</td>\n",
" </tr>\n",
" <tr>\n",
" <th>Transformer Only</th>\n",
" <td>0.805328</td>\n",
" <td>0.854827</td>\n",
" <td>0.954804</td>\n",
" <td>0.680110</td>\n",
" </tr>\n",
" <tr>\n",
" <th>Transformer + XGBoost</th>\n",
" <td>0.850410</td>\n",
" <td>0.891691</td>\n",
" <td>0.959747</td>\n",
" <td>0.734144</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" Accuracy Average Precision (positive) \\\n",
"Model \n",
"TF-IDF + XGBoost 0.681011 0.561521 \n",
"Transformer Only 0.805328 0.854827 \n",
"Transformer + XGBoost 0.850410 0.891691 \n",
"\n",
" Average Precision (negative) \\\n",
"Model \n",
"TF-IDF + XGBoost 0.834914 \n",
"Transformer Only 0.954804 \n",
"Transformer + XGBoost 0.959747 \n",
"\n",
" Average Precision (neutral) \n",
"Model \n",
"TF-IDF + XGBoost 0.382002 \n",
"Transformer Only 0.680110 \n",
"Transformer + XGBoost 0.734144 "
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"%matplotlib inline\n",
"# Let's print the results obtained in this notebook\n",
"df_results = pd.DataFrame(\n",
" {\n",
" \"Model\": [\"TF-IDF + XGBoost\", \"Transformer Only\", \"Transformer + XGBoost\"],\n",
" \"Accuracy\": [accuracy_tfidf, accuracy_transformer_only, accuracy_transformer_xgboost],\n",
" \"Average Precision (positive)\": [\n",
" ap_positive_tfidf,\n",
" ap_positive_transformer_only,\n",
" ap_positive_transformer_xgboost,\n",
" ],\n",
" \"Average Precision (negative)\": [\n",
" ap_negative_tfidf,\n",
" ap_negative_transformer_only,\n",
" ap_negative_transformer_xgboost,\n",
" ],\n",
" \"Average Precision (neutral)\": [\n",
" ap_neutral_tfidf,\n",
" ap_neutral_transformer_only,\n",
" ap_neutral_transformer_xgboost,\n",
" ],\n",
" }\n",
")\n",
"df_results.set_index(\"Model\", inplace=True)\n",
"df_results # pylint: disable=pointless-statement"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Conclusion\n",
"\n",
"In this notebook we presented two different ways to represent a text.\n",
"1. Using TF-IDF vectorization\n",
"2. Using the hidden layers from a transformer\n",
"\n",
"Both representation are then used to train a machine learning model will run in FHE (here XGBoost)\n",
"\n",
"Once the model is trained, clients can send encrypted text representation to the server to get a sentiment analysis done and they receive the probability for each class (negative, neutral and positive) in an encrypted format which can then be decrypted by the client. For now, all the FHE magic (encrypt, predict and decrypt) is done within the `predict_proba` function with the argument `execute_in_fhe=True`. In the next release, an API will be provided to split the server/client parts.\n",
"\n",
"Regarding the FHE execution times, the final XGboost model can predict over an encrypted data point in ~40 seconds. This will change depending on the number of threads available. In the future, more hardware acceleration will be available to speed up the execution time.\n",
"\n",
"It seems that the combination of a transformer (thanks Huggingface!) with a \"simpler\" model such as XGBoost works pretty well. Thanks to Concrete-ML library, we can easily use this text representation on the client machine and then encrypt it to send it to a remote server without having to deal with a transformer runtime in FHE."
]
}
],
"metadata": {
"execution": {
"timeout": 10800
},
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python",
"version": "3.10.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|