{ "cells": [ { "attachments": {}, "cell_type": "markdown", "id": "ac1059eb", "metadata": {}, "source": [ "# Document-Level Sentiment Analysis using
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 }