File size: 12,068 Bytes
a01ef8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ac1059eb",
   "metadata": {},
   "source": [
    "# Document-Level Sentiment Analysis using<br>PyTorch and the Intel® Transfer Learning Tool API\n",
    "\n",
    "This notebook uses the Intel® Transfer Learning Tool to fine-tune a HuggingFace pretrained BERT model for text classification. While this notebook runs on a single node, this workload can also be run in a multinode setting using the TLT CLI. Consult the project documentation and examples to run it using PyTorch distributed training."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bb70464",
   "metadata": {},
   "source": [
    "## 1. Import dependencies and setup parameters\n",
    "\n",
    "This notebook assumes that you have already followed the instructions to setup a Pytorch environment with all the dependencies required to run the notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20ab9972",
   "metadata": {},
   "outputs": [],
   "source": [
    "import intel_extension_for_pytorch as ipex\n",
    "import numpy as np\n",
    "import os\n",
    "import pandas as pd\n",
    "\n",
    "# tlt imports\n",
    "from tlt.datasets import dataset_factory\n",
    "from tlt.models import model_factory\n",
    "from tlt.utils.file_utils import download_and_extract_zip_file\n",
    "\n",
    "# Specify a directory for the dataset to be downloaded\n",
    "dataset_dir = os.environ[\"DATASET_DIR\"] if \"DATASET_DIR\" in os.environ else \\\n",
    "    os.path.join(os.environ[\"HOME\"], \"dataset\")\n",
    "     \n",
    "# Specify a directory for output\n",
    "output_dir = os.environ[\"OUTPUT_DIR\"] if \"OUTPUT_DIR\" in os.environ else \\\n",
    "    os.path.join(os.environ[\"HOME\"], \"output\")\n",
    "\n",
    "print(\"Dataset directory:\", dataset_dir)\n",
    "print(\"Output directory:\", output_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47787deb",
   "metadata": {},
   "source": [
    "## 2. Get the model\n",
    "\n",
    "In this step, we call the Intel Transfer Learning Tool model factory to list supported Huggingface text classification models. This is a list of pretrained models from Huggingface that we tested with our API. Optionally, the `verbose=True` argument can be added to the `print_supported_models()` function call to get more information about each model (such as the links to Huggingface, the original dataset, etc)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52a4af60",
   "metadata": {},
   "outputs": [],
   "source": [
    "# See a list of available text classification models\n",
    "model_factory.print_supported_models(use_case='text_classification', framework='pytorch')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7293733f",
   "metadata": {},
   "source": [
    "Use the TLT model factory to get one of the models listed in the previous cell. The `get_model` function returns a  model object that will later be used for training. For this example, we will use bert-large-uncased."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "050d7b0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_name = \"bert-large-uncased\"\n",
    "framework = \"pytorch\"\n",
    "\n",
    "model = model_factory.get_model(model_name, framework, num_classes=2)\n",
    "\n",
    "print(\"Model name:\", model.model_name)\n",
    "print(\"Framework:\", model.framework)\n",
    "print(\"Use case:\", model.use_case)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37bf5a93",
   "metadata": {},
   "source": [
    "## 3. Get the dataset"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c833ce65",
   "metadata": {},
   "source": [
    "### Option A: Use the Hugging Face catalog\n",
    "\n",
    "Here we are using the dataset in the [Hugging Face datasets catalog](https://huggingface.co/datasets)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cf29cc7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset_name = \"sst2\"\n",
    "dataset = dataset_factory.get_dataset(dataset_dir, model.use_case, model.framework, dataset_name,\n",
    "                                      dataset_catalog=\"huggingface\", shuffle_files=True, \n",
    "                                      split=['train', 'validation'])\n",
    "\n",
    "print(dataset.info)\n",
    "print(\"\\nClass names:\", str(dataset.class_names))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "28504679",
   "metadata": {},
   "source": [
    "Skip to the next step [4. Preprocess the dataset](#4.-Preprocess-the-dataset) to continue using your own dataset."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6867f79e",
   "metadata": {},
   "source": [
    "### Option B: Download the SST2 dataset\n",
    "Option B explicitly downloads the `SST-2.zip` file and extracts a `.tsv` file of training data that is tab separated. The dataset factory expects custom text classification input files to have at least two columns where one is the label and the second column is the text/sentence to classify.\n",
    "\n",
    "For example, the header and first three rows of the file should look similar to this:\n",
    "```\n",
    "sentence\tlabel\n",
    "hide new secretions from the parental units \t0\n",
    "contains no wit , only labored gags \t0\n",
    "that loves its characters and communicates something rather beautiful about human nature \t1\n",
    "```\n",
    "\n",
    "When using your own dataset, update the path to your dataset directory, as well the other variables with properties about the dataset like the .csv (or .tsv) file name, class names, delimiter, header, and the map function (if string labels need to be translated into numerical values)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41edc8fc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Modify the variables below to use a different dataset or a csv file on your local system.\n",
    "dataset_url = \"https://dl.fbaipublicfiles.com/glue/data/SST-2.zip\"\n",
    "csv_name = \"train.tsv\"\n",
    "delimiter = \"\\t\"\n",
    "dataset_subdir = os.path.join(dataset_dir, 'SST-2')\n",
    "# If we don't already have the csv file, download and extract the zip file to get it.\n",
    "if not os.path.exists(os.path.join(dataset_subdir, csv_name)):\n",
    "    download_and_extract_zip_file(dataset_url, dataset_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94e348c2",
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = dataset_factory.load_dataset(dataset_dir=dataset_subdir, \n",
    "                                       use_case=\"text_classification\",\n",
    "                                       framework=\"pytorch\", csv_file_name=csv_name,\n",
    "                                       column_names=[\"sentence\", \"label\"], \n",
    "                                       delimiter=delimiter, header=True, label_col=1)\n",
    "\n",
    "print(dataset.info)\n",
    "print(\"\\nClass names:\", str(dataset.class_names))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e0771e4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create splits for training and validation\n",
    "dataset.shuffle_split(train_pct=0.75, val_pct=0.25)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "539d53b7",
   "metadata": {},
   "source": [
    "## 4. Preprocess the dataset\n",
    "\n",
    "Once you have your dataset from Option A or Option B above, use the following cell to preprocess the dataset. The dataset subsets are tokenized and then batched."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "587d1d9e",
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "dataset.preprocess(model_name, batch_size=32, max_length=55)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "352eda54",
   "metadata": {},
   "source": [
    "## 5. Fine tuning\n",
    "\n",
    "The TLT model's train function is called with the dataset that was just prepared, along with an output directory for checkpoints, and the number of training epochs.\n",
    "\n",
    "With the do_eval paramter set to True by default, this step will also show how the model can be evaluated. The model's evaluate function returns a list of metrics calculated from the dataset's validation subset."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "492ee811",
   "metadata": {},
   "source": [
    "### Arguments\n",
    "\n",
    "#### Required\n",
    "-  **dataset** (ImageClassificationDataset, required): Dataset to use when training the model\n",
    "-  **output_dir** (str): Path to a writeable directory for checkpoint files\n",
    "-  **epochs** (int): Number of epochs to train the model (default: 1)\n",
    "\n",
    "#### Optional\n",
    "-  **initial_checkpoints** (str): Path to checkpoint weights to load. If the path provided is a directory, the latest checkpoint will be used.\n",
    "-  **ipex_optimize** (bool): Optimize the model using Intel® Extension for PyTorch (default: True)\n",
    "\n",
    "Note: refer to release documentation for an up-to-date list of train arguments and their current descriptions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "955a4a7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "history = model.train(dataset, output_dir, epochs=1, ipex_optimize=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e08a1c9",
   "metadata": {},
   "source": [
    "## 6. Predict\n",
    "\n",
    "The model's predict function can be called with a sentence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f3cbd35",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = model.predict(\"Terrible movie\")\n",
    "\n",
    "print(\"Predicted score:\", float(result))\n",
    "print(\"Predicted label:\", dataset.get_str_label(float(result)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64ada826",
   "metadata": {},
   "source": [
    "## 7. Export the saved model\n",
    "\n",
    "Lastly, we can call the model export function to generate a saved_model.pb. Each time the model is exported, a new numbered directory is created, which allows serving to pick up the latest model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3981b2f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "saved_model_dir = model.export(output_dir)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d0ed367",
   "metadata": {},
   "source": [
    "## Citation\n",
    "\n",
    "```\n",
    "@inproceedings{socher-etal-2013-recursive,\n",
    "    title = \"Recursive Deep Models for Semantic Compositionality Over a Sentiment Treebank\",\n",
    "    author = \"Socher, Richard  and\n",
    "      Perelygin, Alex  and\n",
    "      Wu, Jean  and\n",
    "      Chuang, Jason  and\n",
    "      Manning, Christopher D.  and\n",
    "      Ng, Andrew  and\n",
    "      Potts, Christopher\",\n",
    "    booktitle = \"Proceedings of the 2013 Conference on Empirical Methods in Natural Language Processing\",\n",
    "    month = oct,\n",
    "    year = \"2013\",\n",
    "    address = \"Seattle, Washington, USA\",\n",
    "    publisher = \"Association for Computational Linguistics\",\n",
    "    url = \"https://www.aclweb.org/anthology/D13-1170\",\n",
    "    pages = \"1631--1642\",\n",
    "}\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}