Newer
Older
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img width=\"800px\" src=\"../fidle/img/header.svg\"></img>\n",
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
"\n",
"# <!-- TITLE --> [TRANS1] - IMDB, Sentiment analysis with Transformers \n",
"<!-- DESC --> Using a Tranformer to perform a sentiment analysis (IMDB) - Jean Zay version\n",
"<!-- AUTHOR : Hatim Bourfoune (IDRIS) and Nathan Cassereau (IDRIS) -->\n",
"\n",
"By : Hatim Bourfoune (IDRIS) and Nathan Cassereau (IDRIS)\n",
"\n",
"\n",
"## Objectives :\n",
" - Complement the learning of a Transformer to perform a sentiment analysis\n",
" - Understand the use of a pre-trained transformer\n",
"\n",
"This task is exactly the same as the Sentiment analysis with text embedding. Only this time, \n",
"we are going to exploit the strenght of transformers. Considering how computation-heavy transformer \n",
"pretraining is, we are going to use a pretrained BERT model from HuggingFace. \n",
"This notebook performs the fine-tuning process. If possible, try to use a GPU to speed up \n",
"the training, transformers are difficult to train on CPU.\n",
"\n",
"## What we are going to do:\n",
"\n",
"* Retrieve the dataset\n",
"* Prepare the dataset\n",
"* Fetch a pretrained BERT model from HuggingFace's platform (https://huggingface.co/models)\n",
"* Fine-tune the model on a sequence classification task: the sentiment analysis of the IMDB dataset\n",
"* Evaluate the result\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Installations\n",
"\n",
"**IMPORTANT :** We will need to use the library `transformers` created by HuggingFace.\n",
"\n",
"The next line only applies on Jean Zay, it allows us to load a very specific environment, which contains Tensorflow with GPU support. Ignore that line if this notebook is not executed on Jean Zay."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "50QKMUQzPv3n",
"outputId": "3ac2016d-596d-4f9a-c2ec-738c939c49a0"
},
"outputs": [],
"source": [
"#!pip install transformers\n",
"!module load tensorflow-gpu/py3/2.6.0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Imports and initialisation "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ZrV8ONYZPi8L",
"outputId": "ad10d385-3e1f-4ecf-80f2-87dccc286db7"
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"import tensorflow as tf\n",
"import tensorflow.keras as keras\n",
"import tensorflow.keras.datasets.imdb as imdb\n",
"from tensorflow.keras.layers import Dense, Dropout\n",
"from tensorflow.keras.optimizers import Adam\n",
"from tensorflow.keras.losses import SparseCategoricalCrossentropy\n",
"from tensorflow.keras.metrics import SparseCategoricalAccuracy\n",
"from tensorflow.keras import mixed_precision\n",
"\n",
"from transformers import (\n",
" DistilBertTokenizer,\n",
" TFDistilBertModel,\n",
" DataCollatorWithPadding,\n",
" BertTokenizer,\n",
" TFBertModel\n",
")\n",
"\n",
"import pickle\n",
"import multiprocessing\n",
"import itertools\n",
"import os\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"\n",
"print(\"Tensorflow \", tf.__version__)\n",
"n_gpus = len(tf.config.list_physical_devices('GPU'))\n",
"print(\"#GPUs: \", n_gpus)\n",
"if n_gpus > 0:\n",
" !nvidia-smi -L\n",
"policy = mixed_precision.Policy('mixed_float16')\n",
"mixed_precision.set_global_policy(policy)\n",
"os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n",
"\n",
"np.random.seed(987654321)\n",
"tf.random.set_seed(987654321)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Parameters\n",
"\n",
"* `vocab_size` refers to the number of words which will be remembered in our vocabulary.\n",
"* `hide_most_frequently` is the number of ignored words, among the most common ones.\n",
"* `review_len` is the review length.\n",
"* `n_cpus` is the number of CPU which will be used for data preprocessing.\n",
"* `distil` refers to whether or not we are going to use a DistilBert model or a regular Bert model.\n",
"* `load_locally` will fetch data locally, otherwise will download on the Internet (requires an Internet connection, not possible on Jean Zay)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "FhIuZkS2PnTE"
},
"outputs": [],
"source": [
"vocab_size = 30000\n",
"hide_most_frequently = 0\n",
"\n",
"review_len = 512\n",
"\n",
"epochs = 1\n",
"batch_size = 32\n",
"\n",
"fit_verbosity = 1\n",
"scale = 1\n",
"\n",
"n_cpus = 6\n",
"distil = True\n",
"load_locally = True # if set to False, will fetch data from the internet (requires an internet connection)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Retrieve the dataset"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "qaRtDy9wQinS",
"outputId": "9d2d9e12-74fb-4eee-9d9b-d4a7148e2dc2"
},
"outputs": [],
"source": [
"if load_locally:\n",
" with open(\"dataset\", \"rb\") as file_:\n",
" (x_train, y_train), (x_test, y_test) = pickle.load(file_)\n",
"else:\n",
" (x_train, y_train), (x_test, y_test) = imdb.load_data(\n",
" num_words=vocab_size,\n",
" skip_top=hide_most_frequently,\n",
" seed=123456789,\n",
" )\n",
" with open(\"dataset\", \"wb\") as file_:\n",
" pickle.dump(((x_train, y_train), (x_test, y_test)), file_)\n",
"\n",
"\n",
"y_train = np.asarray(y_train).astype('float32')\n",
"y_test = np.asarray(y_test ).astype('float32')\n",
"\n",
"n1 = int(scale * len(x_train))\n",
"n2 = int(scale * len(x_test))\n",
"x_train, y_train = x_train[:n1], y_train[:n1]\n",
"x_test, y_test = x_test[:n2], y_test[:n2]\n",
"\n",
"print(\"x_train : {} y_train : {}\".format(x_train.shape, y_train.shape))\n",
"print(\"x_test : {} y_test : {}\".format(x_test.shape, y_test.shape))\n",
"print('\\nReview sample (x_train[12]) :\\n\\n',x_train[12])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nbF1uktpRdXy"
},
"outputs": [],
"source": [
"if load_locally:\n",
" with open(\"word_index\", \"rb\") as file_:\n",
" word_index = pickle.load(file_)\n",
"else:\n",
" word_index = imdb.get_word_index()\n",
" with open(\"word_index\", \"wb\") as file_:\n",
" pickle.dump(word_index, file_)\n",
"\n",
"word_index = {w:(i+3) for w,i in word_index.items()}\n",
"word_index.update({'[PAD]':0, '[CLS]':1, '[UNK]':2})\n",
"index_word = {index:word for word,index in word_index.items()} \n",
"\n",
"# Add a nice function to transpose:\n",
"def dataset2text(review):\n",
" return ' '.join([index_word.get(i, \"?\") for i in review[1:]])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "DifmZNsKR38n",
"outputId": "cb5f9819-1930-478d-f3f2-45f06e04c5d4"
},
"outputs": [],
"source": [
"print(dataset2text(x_train[12]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fetch the model from HuggingFace"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def load_model(distil, load_locally):\n",
" if load_locally:\n",
" if distil:\n",
" bert_model = TFDistilBertModel.from_pretrained(\"distilbert_model\")\n",
" tokenizer = DistilBertTokenizer(\"distilbert_vocab.txt\", do_lower_case=True)\n",
" else:\n",
" bert_model = TFBertModel.from_pretrained(\"bert_model\")\n",
" tokenizer = BertTokenizer(\"bert_vocab.txt\", do_lower_case=True)\n",
" return bert_model, tokenizer\n",
"\n",
" if distil:\n",
" bert_model = TFDistilBertModel.from_pretrained(\"distilbert-base-uncased\")\n",
" tokenizer = DistilBertTokenizer.from_pretrained(\"distilbert-base-uncased\")\n",
" bert_model.save_pretrained(\"distilbert_model\")\n",
" tokenizer.save_vocabulary(\"distilbert_vocab.txt\")\n",
" else:\n",
" bert_model = TFBertModel.from_pretrained(\"bert-base-uncased\")\n",
" tokenizer = BertTokenizer.from_pretrained(\"bert-base-uncased\")\n",
" bert_model.save_pretrained(\"bert_model\")\n",
" tokenizer.save_vocabulary(\"bert_vocab.txt\")\n",
" return bert_model, tokenizer\n",
"\n",
"bert_model, tokenizer = load_model(distil, load_locally)\n",
"bert_model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare the dataset "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "KKwI-RIXnWWd",
"outputId": "42dc5943-b060-4a08-9180-cd5914980527"
},
"outputs": [],
"source": [
"def tokenize_sample(sample, tokenizer):\n",
" return tokenizer(dataset2text(sample), truncation=True, max_length=review_len)\n",
"\n",
"def distributed_tokenize_dataset(dataset):\n",
" ds = list(dataset)\n",
" with multiprocessing.Pool(n_cpus) as pool:\n",
" tokenized_ds = pool.starmap(\n",
" tokenize_sample,\n",
" zip(ds, itertools.repeat(tokenizer, len(ds)))\n",
" )\n",
" return tokenized_ds\n",
"\n",
"tokenized_x_train = distributed_tokenize_dataset(x_train)\n",
"tokenized_x_test = distributed_tokenize_dataset(x_test)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "TivZYh8vnZlS"
},
"outputs": [],
"source": [
"data_collator = DataCollatorWithPadding(tokenizer, return_tensors=\"tf\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "7Up0APYtwFm7",
"outputId": "37cb98bd-a0d3-47c2-9f91-96f94abf4b2e"
},
"outputs": [],
"source": [
"data_collator(tokenized_x_train)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "U6Lhjfh6maIF",
"outputId": "f4798e7f-bc69-47fe-e2a7-c0155a99cca7"
},
"outputs": [],
"source": [
"def make_dataset(x, y):\n",
" collated = data_collator(x)\n",
" dataset = tf.data.Dataset.from_tensor_slices(\n",
" (collated['input_ids'], collated['attention_mask'], y)\n",
" )\n",
" transformed_dataset = (\n",
" dataset\n",
" .map(\n",
" lambda x, y, z: ((x, y), z)\n",
" )\n",
" .shuffle(25000)\n",
" .batch(batch_size)\n",
" )\n",
" return transformed_dataset\n",
"\n",
"train_ds = make_dataset(tokenized_x_train, y_train)\n",
"test_ds = make_dataset(tokenized_x_test, y_test)\n",
"\n",
"for x, y in train_ds:\n",
" print(x)\n",
" break"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Add a new head to the model"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class ClassificationModel(keras.Model):\n",
"\n",
" def __init__(self, bert_model):\n",
" super(ClassificationModel, self).__init__()\n",
" self.bert_model = bert_model\n",
" self.pre_classifier = Dense(768, activation='relu')\n",
" self.dropout = Dropout(0.1)\n",
" self.classifier = Dense(2)\n",
"\n",
" def call(self, x):\n",
" x = self.bert_model(x)\n",
" x = x.last_hidden_state\n",
" x = x[:, 0] # get the output of the classification token\n",
" x = self.pre_classifier(x)\n",
" x = self.dropout(x)\n",
" x = self.classifier(x)\n",
" return x"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = ClassificationModel(bert_model)\n",
"x = next(iter(train_ds))[0]\n",
"model(x)\n",
"model.summary()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train! "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "4jDAzxxwXLT1",
"outputId": "bc4d5f62-9fa7-426d-a9e2-2fa4d2bdf780"
},
"outputs": [],
"source": [
"model.compile(\n",
" optimizer=Adam(1e-05),\n",
" loss=SparseCategoricalCrossentropy(from_logits=True),\n",
" metrics=[SparseCategoricalAccuracy('accuracy')]\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 419
},
"id": "KtmfFjL02Ano",
"outputId": "ca174c57-b8f9-4d50-a53a-03761556e492"
},
"outputs": [],
"source": [
"history = model.fit(\n",
" train_ds,\n",
" epochs=epochs,\n",
" verbose=fit_verbosity\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Evaluation "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"_, score = model.evaluate(test_ds)\n",
"colors = sns.color_palette('pastel')[2:]\n",
"accuracy_score = [score, 1 - score]\n",
"plt.pie(\n",
" accuracy_score,\n",
" labels=[\"Accurate\", \"Mistaken\"],\n",
" colors=colors,\n",
" autopct=lambda val: f\"{val:.2f}%\",\n",
" explode=(0.0, 0.1)\n",
")\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"collapsed_sections": [],
"name": "Untitled0.ipynb",
"provenance": []
},
"kernelspec": {
"display_name": "Python 3.9.2 ('fidle-env')",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
},
"vscode": {
"interpreter": {
"hash": "b3929042cc22c1274d74e3e946c52b845b57cb6d84f2d591ffe0519b38e4896d"
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}