Spaces:
Configuration error
Configuration error
File size: 34,285 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 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 |
{
"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<br>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<br>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<br>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<br>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<br>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
}
|