{ "cells": [ { "cell_type": "markdown", "id": "57b029cd", "metadata": {}, "source": [ "# Performance Comparison: Text Classification Transfer Learning with Hugging Face* and the IntelĀ® Transfer Learning Tool\n", "\n", "This notebook uses the Hugging Face Trainer to do transfer learning with a text classification model with PyTorch*. The model is trained, evaluated, and exported. The same sequence is also done using the Intel Transfer Learning Tool. The Intel Transfer Learning Tool has a flag to control whether the Hugging Face Trainer is used under the hood, or if just PyTorch libraries are used. Training and evaluation are run both ways, giving us three combinations to compare:\n", "* Using the Hugging Face Trainer\n", "* Using the Intel Transfer Learning Tool with the Hugging Face Trainer\n", "* Using the Intel Transfer Learning Tool with torch\n", "\n", "After all of the models have been trained and evaluated, charts are displayed to visually compare the training and evaluation metrics." ] }, { "cell_type": "code", "execution_count": null, "id": "30be8bb1", "metadata": {}, "outputs": [], "source": [ "import os\n", "import psutil\n", "\n", "os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n", "os.environ['TOKENIZERS_PARALLELISM'] = 'false'\n", "\n", "import datasets\n", "import matplotlib.pyplot as plt\n", "import matplotlib.ticker as mtick\n", "import numpy as np\n", "import pandas as pd\n", "import torch\n", "import transformers\n", "from transformers import DataCollatorWithPadding, Trainer\n", "from torch.utils.data import DataLoader as loader\n", "\n", "from tlt.datasets import dataset_factory\n", "from tlt.models import model_factory\n", "from tlt.utils.platform_util import CPUInfo, OptimizedPlatformUtil, PlatformUtil\n", "\n", "# Specify the the default dataset directory\n", "dataset_directory = 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 (saved models and checkpoints)\n", "output_directory = os.environ[\"OUTPUT_DIR\"] if \"OUTPUT_DIR\" in os.environ else \\\n", " os.path.join(os.environ[\"HOME\"], \"output\")\n", "\n", "# Location where Hugging Face will locally store data\n", "os.environ['HF_HOME'] = dataset_directory\n", "\n", "datasets.utils.logging.set_verbosity(datasets.logging.ERROR)\n", "\n", "# Data Frame styles\n", "table_styles =[{\n", " 'selector': 'caption',\n", " 'props': [\n", " ('text-align', 'center'),\n", " ('color', 'black'),\n", " ('font-size', '16px')\n", " ]\n", "}]\n", "\n", "# Colors used in charts\n", "blue = '#0071c5'\n", "dark_blue = '#003c71'\n", "yellow = '#ffcc4d'" ] }, { "cell_type": "markdown", "id": "f2730530", "metadata": {}, "source": [ "## 1. Display Platform Information" ] }, { "cell_type": "code", "execution_count": null, "id": "e63bb467", "metadata": {}, "outputs": [], "source": [ "# Get and display CPU/platform information\n", "cpu_info = CPUInfo()\n", "platform_util = PlatformUtil()\n", "print(\"{0} CPU Information {0}\".format(\"=\" * 20))\n", "print(\"CPU family:\", platform_util.cpu_family)\n", "print(\"CPU model:\", platform_util.cpu_model)\n", "print(\"CPU type:\", platform_util.cpu_type)\n", "print(\"Physical cores per socket:\", cpu_info.cores_per_socket)\n", "print(\"Total physical cores:\", cpu_info.cores)\n", "cpufreq = psutil.cpu_freq()\n", "print(\"Max Frequency:\", cpufreq.max)\n", "print(\"Min Frequency:\", cpufreq.min)\n", "cpu_socket_count = cpu_info.sockets\n", "print(\"Socket Number:\", cpu_socket_count)\n", "\n", "print(\"\\n{0} Memory Information {0}\".format(\"=\" * 20))\n", "svmem = psutil.virtual_memory()\n", "print(\"Total: \", int(svmem.total / (1024 ** 3)), \"GB\")\n", "\n", "# Display Hugging Face version information\n", "print(\"\\n{0} Hugging Face Information {0}\".format(\"=\" * 20))\n", "print(\"Hugging Face Transformers version:\", transformers.__version__)\n", "print(\"Hugging Face Datasets version:\", datasets.__version__)\n", "\n", "# Display PyTorch version information\n", "print(\"\\n{0} PyTorch Information {0}\".format(\"=\" * 20))\n", "print(\"PyTorch version:\", torch.__version__)" ] }, { "cell_type": "markdown", "id": "e0b7f5fb", "metadata": {}, "source": [ "## 2. Select a model and define parameters to use during training and evaluation\n", "\n", "### Select a model\n", "\n", "See the list of supported PyTorch text classification models from Hugging Face in the Intel Transfer Learning Tool." ] }, { "cell_type": "code", "execution_count": null, "id": "069e58da", "metadata": {}, "outputs": [], "source": [ "framework = 'pytorch'\n", "use_case = 'text_classification'\n", "model_hub = 'huggingface'\n", "supported_models = model_factory.get_supported_models(framework, use_case)\n", "supported_models = supported_models[use_case]\n", "\n", "# Filter to only get relevant models\n", "supported_models = { key:value for (key,value) in supported_models.items() if value[framework]['model_hub'] == model_hub}\n", "\n", "print(\"Supported {} models for {} from {}\".format(framework, use_case, model_hub))\n", "print(\"=\" * 70)\n", "for model_name in supported_models.keys():\n", " print(model_name)" ] }, { "cell_type": "markdown", "id": "8fc116a5", "metadata": {}, "source": [ "Set the `model_name` to the model that will be used during this experiment." ] }, { "cell_type": "code", "execution_count": null, "id": "bda109e9", "metadata": {}, "outputs": [], "source": [ "# Select a model\n", "model_name = \"bert-base-cased\"" ] }, { "cell_type": "markdown", "id": "bd568624", "metadata": {}, "source": [ "### Select a dataset\n", "\n", "For these experiments, we will be using text classification datasets from the [Hugging Face Datasets catalog](https://huggingface.co/datasets?task_categories=task_categories:text-classification&sort=downloads). Specify the name of the dataset to use with the `dataset_name` variable in the next cell." ] }, { "cell_type": "code", "execution_count": null, "id": "6aa35cf0", "metadata": {}, "outputs": [], "source": [ "dataset_name = 'imdb'" ] }, { "cell_type": "markdown", "id": "409141c0", "metadata": {}, "source": [ "### Define parameters\n", "\n", "For consistency between the model training experiments using Hugging Face and the Intel Transfer Learning Tool, the next cell defines parameters that will be used by both methods." ] }, { "cell_type": "code", "execution_count": null, "id": "9588f07d", "metadata": {}, "outputs": [], "source": [ "# Number of training epochs\n", "training_epochs = 2\n", "\n", "# Shuffle the files after each training epoch\n", "shuffle_files = True\n", "\n", "# Define the name of the split to use for validation (i.e. 'validation' or 'test')\n", "eval_split=None\n", "# If eval_split=None, split the 'train' dataset\n", "validation_split = 0.05\n", "training_split = 0.1\n", "\n", "# Set seed for consistency between runs (or None)\n", "seed = 10\n", "\n", "# List of batch size(s) to compare (maximum of 4 batch sizes to try)\n", "batch_size_list = [ 16, 32 ]\n", "\n", "learning_rate=3e-5\n", "\n", "# Text preprocessing\n", "max_sequence_length = 128\n", "padding = 'max_length'\n", "truncation = True\n", "\n", "# Use the Intel Extension for PyTorch\n", "use_ipex = True" ] }, { "cell_type": "markdown", "id": "c508355f", "metadata": {}, "source": [ "Validate parameter values and then print out the parameters." ] }, { "cell_type": "code", "execution_count": null, "id": "ec3ec8be", "metadata": {}, "outputs": [], "source": [ "if not isinstance(training_epochs, int):\n", " raise TypeError(\"The training_epochs parameter should be an integer, but found a {}\".format(type(training_epochs)))\n", "\n", "if training_epochs < 1:\n", " raise ValueError(\"The training_epochs parameter should not be less than 1.\")\n", " \n", "if not isinstance(shuffle_files, bool):\n", " raise TypeError(\"The shuffle_files parameter should be a bool, but found a {}\".format(type(shuffle_files)))\n", "\n", "if not eval_split:\n", " if not isinstance(validation_split, float):\n", " raise TypeError(\"The validation_split parameter should be a float, but found a {}\".format(type(validation_split)))\n", "\n", " if not isinstance(training_split, float):\n", " raise TypeError(\"The training_split parameter should be a float, but found a {}\".format(type(training_split)))\n", "\n", "if validation_split + training_split > 1:\n", " raise ValueError(\"The sum of validation_split and training_split should not be greater than 1.\")\n", "\n", "if seed and not isinstance(seed, int):\n", " raise TypeError(\"The seed parameter should be a integer or None, but found a {}\".format(type(seed)))\n", "\n", "if len(batch_size_list) > 4 or len(batch_size_list) == 0:\n", " raise ValueError(\"The batch_size_list should have at most 4 values, but found {} values ({})\".format(\n", " len(batch_size_list), batch_size_list))\n", " \n", "print(\"Number of training epochs:\", training_epochs)\n", "print(\"Shuffle files:\", shuffle_files)\n", "print(\"Training split: {}%\".format('train' if eval_split else training_split*100))\n", "print(\"Validation split: {}%\".format(eval_split if eval_split else validation_split*100))\n", "print(\"Seed:\", str(seed))\n", "print(\"Batch size list:\", batch_size_list)" ] }, { "cell_type": "markdown", "id": "d102b97b", "metadata": {}, "source": [ "## 3. Train and evaluate the models\n", "\n", "In this section, we will compare the time that it takes to fine tune the text classification model using the dataset that was selected in the previous section.\n", "\n", "The fine tuning will be done in two different ways:\n", "* Using the Hugging Face python libraries\n", "* Using the Intel Transfer Learning Tool\n", "\n", "### Fine tuning using the Hugging Face libraries\n", "\n", "First, we download and prepare the dataset." ] }, { "cell_type": "code", "execution_count": null, "id": "ad0b244c", "metadata": {}, "outputs": [], "source": [ "transformers.set_seed(seed)\n", "\n", "# Determine the splits to load\n", "split = ['train']\n", "if eval_split:\n", " split.append(eval_split)\n", "\n", "# Load the dataset from the Hugging Face dataset catalog\n", "hf_dataset = datasets.load_dataset(dataset_name, cache_dir=dataset_directory, split=split)\n", "\n", "# Load the tokenizer based on our selected model\n", "hf_tokenizer = transformers.AutoTokenizer.from_pretrained(model_name, cache_dir=output_directory)\n", "\n", "text_column_names = [col_name for col_name in hf_dataset[0].column_names if col_name != 'label' and\n", " all(isinstance(s, str) for s in hf_dataset[0][col_name])]\n", "\n", "# Tokenize the dataset\n", "def tokenize_function(examples):\n", " args = (examples[text_column_name] for text_column_name in text_column_names)\n", " return hf_tokenizer(*args, padding=padding, max_length=max_sequence_length, truncation=truncation)\n", "\n", "tokenized_hf_dataset = [d.map(tokenize_function, batched=True) for d in hf_dataset]\n", "for tokenized in tokenized_hf_dataset:\n", " tokenized.set_format('torch')\n", "\n", "# If eval_split is defined, that split will be used for validation. Otherwise, the 'train' dataset split will be\n", "# split by the defined percentage to use for training and evaluation.\n", "hf_train_dataset = tokenized_hf_dataset[0]\n", "if eval_split:\n", " print(\"Using 'train' and '{}' dataset splits\".format(eval_split))\n", " hf_train_subset = hf_train_dataset\n", " hf_eval_subset = tokenized_hf_dataset[1]\n", "else:\n", " dataset_length = len(hf_train_dataset)\n", " train_size = int(training_split * dataset_length)\n", " eval_size = int(validation_split * dataset_length)\n", " generator = torch.Generator().manual_seed(seed) \n", " dataset_indices = torch.randperm(dataset_length, generator=generator).tolist() if shuffle_files else range(dataset_length)\n", " train_indices = dataset_indices[:train_size]\n", " eval_indices = dataset_indices[train_size:train_size + eval_size]\n", " print(\"Using {}% for training and {}% for validation\".format(training_split * 100, validation_split * 100))\n", " print(\"Total dataset size:\", dataset_length)\n", " print(\"Train size:\", train_size)\n", " print(\"Eval size:\", eval_size)\n", " hf_train_subset = hf_train_dataset.select(train_indices)\n", " hf_eval_subset = hf_train_dataset.select(eval_indices)\n", "\n", "# Get the number of classes from the train dataset features (either called 'label' or 'labels')\n", "class_names = hf_dataset[0].features['label'].names if 'label' in hf_dataset[0].features else \\\n", " hf_dataset[0].features['labels'].names\n", "print(\"Class names: {}\".format(class_names))\n", "\n", "hf_train_dataset_length = len(hf_train_subset)\n", "hf_eval_dataset_length = len(hf_eval_subset)\n", "\n", "# Define function to compute accuracy to pass to the Hugging Face Trainer\n", "def compute_metrics(p: transformers.EvalPrediction):\n", " preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions\n", " preds = np.argmax(preds, axis=1)\n", " return {\"accuracy\": (preds == p.label_ids).astype(np.float32).mean().item()}" ] }, { "cell_type": "markdown", "id": "75bc822a", "metadata": {}, "source": [ "Next, we iterate through our list of batch sizes to train the model for each configuration with the dataset that was prepared in the previous cell. After training is complete, the model is evaluated and exported. The training and evaluation metrics are saved to lists." ] }, { "cell_type": "code", "execution_count": null, "id": "9b3037a8", "metadata": {}, "outputs": [], "source": [ "hf_saved_model_paths = []\n", "hf_training_metrics = []\n", "hf_eval_results = []\n", "\n", "for i, batch_size in enumerate(batch_size_list):\n", " print('-' * 40)\n", " print('Training using batch size: {}'.format(batch_size))\n", " print('-' * 40)\n", " \n", " # Get the model from pretrained\n", " model = transformers.AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=len(class_names))\n", "\n", " # Setup a directory to save the model output\n", " saved_model_dir = os.path.join(output_directory, model_name, 'HF_model_bs{}'.format(batch_size))\n", " \n", " # Note: Even when setting do_eval=False, an error gets thrown if a eval_dataset is not provided\n", " training_args = transformers.TrainingArguments(\n", " output_dir=saved_model_dir,\n", " do_eval=False,\n", " do_train=True,\n", " learning_rate=learning_rate,\n", " per_device_train_batch_size=batch_size,\n", " per_device_eval_batch_size=batch_size,\n", " num_train_epochs=training_epochs,\n", " evaluation_strategy=\"epoch\",\n", " push_to_hub=False,\n", " no_cuda=True,\n", " overwrite_output_dir=True,\n", " seed=seed,\n", " data_seed=seed,\n", " use_ipex=use_ipex\n", " )\n", "\n", " trainer = Trainer(\n", " model=model,\n", " args=training_args,\n", " train_dataset=hf_train_subset,\n", " eval_dataset=hf_eval_subset,\n", " compute_metrics=compute_metrics,\n", " tokenizer=hf_tokenizer,\n", " )\n", "\n", " # Train the model\n", " history = trainer.train()\n", " \n", " # Evaluate the model\n", " eval_results = trainer.evaluate()\n", " \n", " # Export the trained model\n", " trainer.save_model(saved_model_dir)\n", " \n", " # Save objects and metrics\n", " hf_training_metrics.append(history)\n", " hf_eval_results.append(eval_results)\n", " hf_saved_model_paths.append(saved_model_dir)" ] }, { "cell_type": "markdown", "id": "86cafc34", "metadata": {}, "source": [ "### Using the Intel Transfer Learning tool API\n", "\n", "Next, we train the same model using the same parameters using the Intel Transfer Learning Tool. The Intel Transfer Learning Tool training method has an argument called `use_trainer` to determine if the Hugging Face Trainer will be used. If `use_trainer=False`, the torch libraries will be used to train the model. The next section will do the training with and without the Hugging Face Trainer, so that we can gather metrics both ways. After the model is trained, it is evaluted. Again, we save the training and evaluation metrics to lists." ] }, { "cell_type": "code", "execution_count": null, "id": "e08223da", "metadata": {}, "outputs": [], "source": [ "# Intel Transfer Learning Tool using the Hugging Face Trainer\n", "tlt_trainer_saved_model_paths = []\n", "tlt_trainer_training_metrics = []\n", "tlt_trainer_eval_results = []\n", "\n", "# Intel Transfer Learning Tool training using torch libraries\n", "tlt_torch_saved_model_paths = []\n", "tlt_torch_training_metrics = []\n", "tlt_torch_eval_results = []\n", "\n", "split_names = ['train'] if eval_split is None else ['train', eval_split]\n", "\n", "for i, batch_size in enumerate(batch_size_list):\n", " print('-' * 40)\n", " print('Training using batch size: {}'.format(batch_size))\n", " print('-' * 40)\n", "\n", " # Get the dataset\n", " dataset = dataset_factory.get_dataset(dataset_directory, use_case, framework, dataset_name,\n", " dataset_catalog=\"huggingface\", shuffle_files=shuffle_files,\n", " split=split_names)\n", "\n", " # Batch and tokenize the dataset\n", " dataset.preprocess(model_name, batch_size=batch_size, max_length=max_sequence_length, padding=padding,\n", " truncation=truncation)\n", "\n", " # If the dataset doesn't have a defined split, then split it by percentages\n", " if eval_split is None:\n", " dataset.shuffle_split(train_pct=training_split, val_pct=validation_split)\n", " \n", " tlt_train_dataset_length = len(dataset.train_subset)\n", " \n", " if eval_split == 'test':\n", " eval_dataset = dataset.test_subset\n", " tlt_eval_dataset_length = len(eval_dataset)\n", " else:\n", " eval_dataset = dataset.validation_subset\n", " tlt_eval_dataset_length = len(eval_dataset)\n", " \n", " # Verify dataset length between the experiments\n", " assert tlt_train_dataset_length == hf_train_dataset_length\n", " assert tlt_eval_dataset_length == hf_eval_dataset_length\n", " \n", " for use_trainer in [True, False]:\n", " print('\\nTraining using Hugging Face Trainer: {}'.format(use_trainer))\n", " \n", " # Get the model\n", " model = model_factory.get_model(model_name, framework)\n", "\n", " # Train the model\n", " history = model.train(dataset, output_directory, epochs=training_epochs, ipex_optimize=use_ipex,\n", " use_trainer=use_trainer, do_eval=False, learning_rate=learning_rate, seed=seed)\n", " \n", " eval_metrics = model.evaluate(eval_dataset)\n", "\n", " # Save the model\n", " saved_model_dir = model.export(output_directory)\n", " \n", " if use_trainer:\n", " tlt_trainer_training_metrics.append(history)\n", " tlt_trainer_saved_model_paths.append(saved_model_dir)\n", " tlt_trainer_eval_results.append(eval_metrics)\n", " else:\n", " tlt_torch_training_metrics.append(history)\n", " tlt_torch_saved_model_paths.append(saved_model_dir)\n", " tlt_torch_eval_results.append(eval_metrics)" ] }, { "cell_type": "markdown", "id": "c8a27d05", "metadata": {}, "source": [ "## 4. Compare metrics\n", "\n", "This section compares metrics for training and evaluating the model for the following experiments:\n", "* Using the Hugging Face Trainer\n", "* Using the Intel Transfer Learning Tool with the Hugging Face Trainer\n", "* Using the Intel Transfer Learning Tool with torch" ] }, { "cell_type": "code", "execution_count": null, "id": "570f872d", "metadata": {}, "outputs": [], "source": [ "display_df = []\n", "\n", "# Display training metrics\n", "for i, batch_size in enumerate(batch_size_list):\n", " df = pd.DataFrame({\n", " 'Hugging Face Trainer': [hf_training_metrics[i].metrics['train_loss'], hf_training_metrics[i].metrics['train_samples_per_second'], hf_training_metrics[i].metrics['train_runtime']],\n", " 'Intel Transfer Learning Tool
using the HF Trainer': [tlt_trainer_training_metrics[i].metrics['train_loss'], tlt_trainer_training_metrics[i].metrics['train_samples_per_second'], tlt_trainer_training_metrics[i].metrics['train_runtime']],\n", " 'Intel Transfer Learning Tool
using Torch': [tlt_torch_training_metrics[i]['Loss'], tlt_torch_training_metrics[i]['train_samples_per_second'][0], tlt_torch_training_metrics[i]['train_runtime'][0]],\n", " }, index = ['Loss', 'Samples per second', 'Train Runtime'])\n", " df = df.style.set_table_styles(table_styles).set_caption(\"Training metrics with batch size {}\".format(batch_size))\n", " display_df.append(df)\n", "\n", "# Display evaluation metrics\n", "for i, batch_size in enumerate(batch_size_list):\n", " df = pd.DataFrame({\n", " 'Eval using the
Hugging Face Trainer': [\"{0:.2%}\".format(hf_eval_results[i]['eval_accuracy']), hf_eval_results[i]['eval_loss'], hf_eval_results[i]['eval_samples_per_second'], hf_eval_results[i]['eval_runtime']],\n", " 'Intel Transfer Learning Tool
eval using the HF Trainer': [\"{0:.2%}\".format(tlt_trainer_eval_results[i]['eval_accuracy']), tlt_trainer_eval_results[i]['eval_loss'], tlt_trainer_eval_results[i]['eval_samples_per_second'], tlt_trainer_eval_results[i]['eval_runtime']],\n", " 'Intel Transfer Learning Tool
eval using Torch': [\"{0:.2%}\".format(tlt_torch_eval_results[i]['eval_accuracy']), tlt_torch_eval_results[i]['eval_loss'], tlt_torch_eval_results[i]['eval_samples_per_second'], tlt_torch_eval_results[i]['eval_runtime']],\n", " }, index = ['Eval accuracy', 'Eval Loss', 'Samples per second', 'Train Runtime'])\n", " df = df.style.set_table_styles(table_styles).set_caption(\"Training metrics with batch size {}\".format(batch_size))\n", " display_df.append(df)\n", " \n", "for df in display_df:\n", " display(df)" ] }, { "cell_type": "markdown", "id": "89360585", "metadata": {}, "source": [ "### Training metrics\n", "\n", "Generate charts to compare the time that it took to train the model in each experiment (lower is better) and the thoughput (higher is better)." ] }, { "cell_type": "code", "execution_count": null, "id": "0919f4dc", "metadata": {}, "outputs": [], "source": [ "# Bar chart group labels\n", "groups = [\"batch size = {}\".format(bs) for bs in batch_size_list]\n", "\n", "hf_train_runtime = [x.metrics['train_runtime'] for x in hf_training_metrics]\n", "tlt_trainer_train_runtime = [x.metrics['train_runtime'] for x in tlt_trainer_training_metrics]\n", "tlt_torch_train_runtime = [x['train_runtime'][0] for x in tlt_torch_training_metrics]\n", "\n", "hf_train_throughput = [x.metrics['train_samples_per_second'] for x in hf_training_metrics]\n", "tlt_trainer_train_throughput = [x.metrics['train_samples_per_second'] for x in tlt_trainer_training_metrics]\n", "tlt_torch_train_thoughput = [x['train_samples_per_second'][0] for x in tlt_torch_training_metrics]\n", "\n", "x = np.arange(len(groups))\n", "width = 0.2 # the width of the bars\n", "multiplier = 0\n", "\n", "# Setup bars for training run times\n", "fig, (ax1, ax2) = plt.subplots(2)\n", "fig.set_figheight(15)\n", "fig.set_figwidth(10)\n", "rects_tf = ax1.bar(x, hf_train_runtime, width, label='HF trained', color=yellow)\n", "rects_tlt_trainer = ax1.bar(x + width, tlt_trainer_train_runtime, width, label='TLT using Trainer', color=blue)\n", "rects_tlt_torch = ax1.bar(x + width * 2, tlt_torch_train_runtime, width, label='TLT using Torch', color=dark_blue)\n", "ax1.bar_label(rects_tf, padding=3)\n", "ax1.bar_label(rects_tlt_trainer, padding=3)\n", "ax1.bar_label(rects_tlt_torch, padding=3)\n", "\n", "# Add labels, title, and legend\n", "ax1.set_ylabel('Seconds')\n", "ax1.set_title('Training Runtime')\n", "ax1.set_xticks(x+width, groups)\n", "ax1.set_ymargin(0.2) \n", "ax1.legend(ncols=2)\n", "\n", "# Setup bars for throughput\n", "rects_tf = ax2.bar(x, hf_train_throughput, width, label='HF trained', color=yellow)\n", "rects_tlt_trainer = ax2.bar(x + width, tlt_trainer_train_throughput, width, label='TLT using Trainer', color=blue)\n", "rects_tlt_torch = ax2.bar(x + width * 2, tlt_torch_train_thoughput, width, label='TLT using Torch', color=dark_blue)\n", "ax2.bar_label(rects_tf, padding=3)\n", "ax2.bar_label(rects_tlt_trainer, padding=3)\n", "ax2.bar_label(rects_tlt_torch, padding=3)\n", "\n", "# Add labels, title, and legend\n", "ax2.set_ylabel('Samples per second')\n", "ax2.set_title('Training Throughput')\n", "ax2.set_xticks(x+width, groups)\n", "ax2.set_ymargin(0.2) \n", "ax2.legend(ncols=2)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "54559456", "metadata": {}, "source": [ "### Evaluation Metrics\n", "\n", "Next, we generate charts to compare the evaluation metrics for the same three experiments that were used for training the model. We have a charts with the validation accuracy, total evaluation time (lower is better), and evaluation throughput (higher is better)." ] }, { "cell_type": "code", "execution_count": null, "id": "02473c34", "metadata": {}, "outputs": [], "source": [ "# Decimals used for rounding\n", "decimals = 2\n", "\n", "# Get the evaluation metrics\n", "hf_eval_acc = [round(x['eval_accuracy'] * 100, decimals) for x in hf_eval_results]\n", "tlt_trainer_eval_acc = [round(x['eval_accuracy'] * 100, decimals) for x in tlt_trainer_eval_results]\n", "tlt_torch_eval_acc = [round(x['eval_accuracy'] * 100, decimals) for x in tlt_torch_eval_results]\n", "\n", "hf_eval_runtime = [round(x['eval_runtime'], decimals) for x in hf_eval_results]\n", "tlt_trainer_eval_runtime = [round(x['eval_runtime'], decimals) for x in tlt_trainer_eval_results]\n", "tlt_torch_eval_runtime = [round(x['eval_runtime'], decimals) for x in tlt_torch_eval_results]\n", "\n", "hf_eval_throughput = [round(x['eval_samples_per_second'], decimals) for x in hf_eval_results]\n", "tlt_trainer_eval_throughput = [round(x['eval_samples_per_second'], decimals) for x in tlt_trainer_eval_results]\n", "tlt_torch_eval_thoughput = [round(x['eval_samples_per_second'], decimals) for x in tlt_torch_eval_results]\n", "\n", "x = np.arange(len(groups))\n", "width = 0.2 # the width of the bars\n", "multiplier = 0\n", "\n", "# Setup bars for training run times\n", "fig, (ax1, ax2, ax3) = plt.subplots(3)\n", "fig.set_figheight(20)\n", "fig.set_figwidth(10)\n", "rects_tf = ax1.bar(x, hf_eval_acc, width, label='HF evaluated', color=yellow)\n", "rects_tlt_trainer = ax1.bar(x + width, tlt_trainer_eval_acc, width, label='TLT eval using Trainer', color=blue)\n", "rects_tlt_torch = ax1.bar(x + width * 2, tlt_torch_eval_acc, width, label='TLT eval using Torch', color=dark_blue)\n", "ax1.bar_label(rects_tf, padding=3)\n", "ax1.bar_label(rects_tlt_trainer, padding=3)\n", "ax1.bar_label(rects_tlt_torch, padding=3)\n", "\n", "# Add labels, title, and legend\n", "ax1.set_ylabel('Percentage (%)')\n", "ax1.set_title('Evaluation Accuracy')\n", "ax1.set_xticks(x+width, groups)\n", "ax1.set_ymargin(0.2) \n", "ax1.legend(ncols=2)\n", "\n", "rects_tf = ax2.bar(x, hf_eval_runtime, width, label='HF evaluated', color=yellow)\n", "rects_tlt_trainer = ax2.bar(x + width, tlt_trainer_eval_runtime, width, label='TLT eval using Trainer', color=blue)\n", "rects_tlt_torch = ax2.bar(x + width * 2, tlt_torch_eval_runtime, width, label='TLT eval using Torch', color=dark_blue)\n", "ax2.bar_label(rects_tf, padding=3)\n", "ax2.bar_label(rects_tlt_trainer, padding=3)\n", "ax2.bar_label(rects_tlt_torch, padding=3)\n", "\n", "# Add labels, title, and legend\n", "ax2.set_ylabel('Seconds')\n", "ax2.set_title('Evaluation Runtime')\n", "ax2.set_xticks(x+width, groups)\n", "ax2.set_ymargin(0.2) \n", "ax2.legend(ncols=2)\n", "\n", "# Setup bars for throughput\n", "rects_tf = ax3.bar(x, hf_eval_throughput, width, label='HF evaluated', color=yellow)\n", "rects_tlt_trainer = ax3.bar(x + width, tlt_trainer_eval_throughput, width, label='TLT eval using Trainer', color=blue)\n", "rects_tlt_torch = ax3.bar(x + width * 2, tlt_torch_eval_thoughput, width, label='TLT eval using Torch', color=dark_blue)\n", "ax3.bar_label(rects_tf, padding=3)\n", "ax3.bar_label(rects_tlt_trainer, padding=3)\n", "ax3.bar_label(rects_tlt_torch, padding=3)\n", "\n", "# Add labels, title, and legend\n", "ax3.set_ylabel('Samples per second')\n", "ax3.set_title('Evaluation Throughput')\n", "ax3.set_xticks(x+width, groups)\n", "ax3.set_ymargin(0.2) \n", "ax3.legend(ncols=2)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "68f77b7d", "metadata": {}, "source": [ "## Next Steps\n", "\n", "This concludes our performance comparison using a Hugging Face model with the Hugging Face `Trainer` and the Intel Transfer Learning Tool. All of the models trained during these experiments have been saved to your output directory. Any of these can be loaded back to perform further experiments." ] }, { "cell_type": "code", "execution_count": null, "id": "3c26d581", "metadata": {}, "outputs": [], "source": [ "for i, batch_size in enumerate(batch_size_list):\n", " print(\"\\nUsing batch size {}\".format(batch_size))\n", " print('-' * 25)\n", " print(\"Model trained using the Hugging Face Trainer:\\n\\t\", hf_saved_model_paths[i])\n", " print(\"Model trained using the Intel Transfer Learning tool and the Hugging Face Trainer:\\n\\t\", tlt_trainer_saved_model_paths[i])\n", " print(\"Model trained using the Intel Transfer Learning tool and the PyTorch libraries:\\n\\t\", tlt_torch_saved_model_paths[i])" ] }, { "cell_type": "markdown", "id": "13e228cd", "metadata": {}, "source": [ "## Citations \n", "\n", "```\n", "@misc{devlin2019bert,\n", " title={BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding}, \n", " author={Jacob Devlin and Ming-Wei Chang and Kenton Lee and Kristina Toutanova},\n", " year={2019},\n", " eprint={1810.04805},\n", " archivePrefix={arXiv},\n", " primaryClass={cs.CL}\n", "}\n", "```\n", "\n", "```\n", "@InProceedings{maas-EtAl:2011:ACL-HLT2011,\n", " author = {Maas, Andrew L. and Daly, Raymond E. and Pham, Peter T. and Huang, Dan and Ng, Andrew Y. and Potts, Christopher},\n", " title = {Learning Word Vectors for Sentiment Analysis},\n", " booktitle = {Proceedings of the 49th Annual Meeting of the Association for Computational Linguistics: Human Language Technologies},\n", " month = {June},\n", " year = {2011},\n", " address = {Portland, Oregon, USA},\n", " publisher = {Association for Computational Linguistics},\n", " pages = {142--150},\n", " url = {http://www.aclweb.org/anthology/P11-1015}\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.9.16" } }, "nbformat": 4, "nbformat_minor": 5 }