Spaces:
Running
Running
File size: 31,618 Bytes
f23d3db |
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 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Transformers installation\n",
"! pip install transformers datasets\n",
"# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
"# ! pip install git+https://github.com/huggingface/transformers.git"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Fine-tune a pretrained model"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There are significant benefits to using a pretrained model. It reduces computation costs, your carbon footprint, and allows you to use state-of-the-art models without having to train one from scratch. 🤗 Transformers provides access to thousands of pretrained models for a wide range of tasks. When you use a pretrained model, you train it on a dataset specific to your task. This is known as fine-tuning, an incredibly powerful training technique. In this tutorial, you will fine-tune a pretrained model with a deep learning framework of your choice:\n",
"\n",
"* Fine-tune a pretrained model with 🤗 Transformers [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer).\n",
"* Fine-tune a pretrained model in TensorFlow with Keras.\n",
"* Fine-tune a pretrained model in native PyTorch.\n",
"\n",
"<a id='data-processing'></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Prepare a dataset"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [
{
"data": {
"text/html": [
"<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/_BZearw7f0w?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#@title\n",
"from IPython.display import HTML\n",
"\n",
"HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/_BZearw7f0w?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Before you can fine-tune a pretrained model, download a dataset and prepare it for training. The previous tutorial showed you how to process data for training, and now you get an opportunity to put those skills to the test!\n",
"\n",
"Begin by loading the [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full) dataset:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'label': 0,\n",
" 'text': 'My expectations for McDonalds are t rarely high. But for one to still fail so spectacularly...that takes something special!\\\\nThe cashier took my friends\\'s order, then promptly ignored me. I had to force myself in front of a cashier who opened his register to wait on the person BEHIND me. I waited over five minutes for a gigantic order that included precisely one kid\\'s meal. After watching two people who ordered after me be handed their food, I asked where mine was. The manager started yelling at the cashiers for \\\\\"serving off their orders\\\\\" when they didn\\'t have their food. But neither cashier was anywhere near those controls, and the manager was the one serving food to customers and clearing the boards.\\\\nThe manager was rude when giving me my order. She didn\\'t make sure that I had everything ON MY RECEIPT, and never even had the decency to apologize that I felt I was getting poor service.\\\\nI\\'ve eaten at various McDonalds restaurants for over 30 years. I\\'ve worked at more than one location. I expect bad days, bad moods, and the occasional mistake. But I have yet to have a decent experience at this store. It will remain a place I avoid unless someone in my party needs to avoid illness from low blood sugar. Perhaps I should go back to the racially biased service of Steak n Shake instead!'}"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from datasets import load_dataset\n",
"\n",
"dataset = load_dataset(\"yelp_review_full\")\n",
"dataset[\"train\"][100]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As you now know, you need a tokenizer to process the text and include a padding and truncation strategy to handle any variable sequence lengths. To process your dataset in one step, use 🤗 Datasets [`map`](https://huggingface.co/docs/datasets/process.html#map) method to apply a preprocessing function over the entire dataset:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"bert-base-cased\")\n",
"\n",
"\n",
"def tokenize_function(examples):\n",
" return tokenizer(examples[\"text\"], padding=\"max_length\", truncation=True)\n",
"\n",
"\n",
"tokenized_datasets = dataset.map(tokenize_function, batched=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"small_train_dataset = tokenized_datasets[\"train\"].shuffle(seed=42).select(range(1000))\n",
"small_eval_dataset = tokenized_datasets[\"test\"].shuffle(seed=42).select(range(1000))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='trainer'></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"At this point, you should follow the section corresponding to the framework you want to use. You can use the links\n",
"in the right sidebar to jump to the one you want - and if you want to hide all of the content for a given framework,\n",
"just use the button at the top-right of that framework's block!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [
{
"data": {
"text/html": [
"<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/nvBXf7s7vTI?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#@title\n",
"from IPython.display import HTML\n",
"\n",
"HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/nvBXf7s7vTI?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train with PyTorch Trainer"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"🤗 Transformers provides a [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) class optimized for training 🤗 Transformers models, making it easier to start training without manually writing your own training loop. The [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) API supports a wide range of training options and features such as logging, gradient accumulation, and mixed precision.\n",
"\n",
"Start by loading your model and specify the number of expected labels. From the Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields), you know there are five labels:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForSequenceClassification\n",
"\n",
"model = AutoModelForSequenceClassification.from_pretrained(\"bert-base-cased\", num_labels=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<Tip>\n",
"\n",
"You will see a warning about some of the pretrained weights not being used and some weights being randomly\n",
"initialized. Don't worry, this is completely normal! The pretrained head of the BERT model is discarded, and replaced with a randomly initialized classification head. You will fine-tune this new model head on your sequence classification task, transferring the knowledge of the pretrained model to it.\n",
"\n",
"</Tip>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Training hyperparameters"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, create a [TrainingArguments](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.TrainingArguments) class which contains all the hyperparameters you can tune as well as flags for activating different training options. For this tutorial you can start with the default training [hyperparameters](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments), but feel free to experiment with these to find your optimal settings.\n",
"\n",
"Specify where to save the checkpoints from your training:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import TrainingArguments\n",
"\n",
"training_args = TrainingArguments(output_dir=\"test_trainer\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Evaluate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) does not automatically evaluate model performance during training. You'll need to pass [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) a function to compute and report metrics. The [🤗 Evaluate](https://huggingface.co/docs/evaluate/index) library provides a simple [`accuracy`](https://huggingface.co/spaces/evaluate-metric/accuracy) function you can load with the [evaluate.load](https://huggingface.co/docs/evaluate/main/en/package_reference/loading_methods#evaluate.load) (see this [quicktour](https://huggingface.co/docs/evaluate/a_quick_tour) for more information) function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import evaluate\n",
"\n",
"metric = evaluate.load(\"accuracy\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Call `compute` on `metric` to calculate the accuracy of your predictions. Before passing your predictions to `compute`, you need to convert the predictions to logits (remember all 🤗 Transformers models return logits):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def compute_metrics(eval_pred):\n",
" logits, labels = eval_pred\n",
" predictions = np.argmax(logits, axis=-1)\n",
" return metric.compute(predictions=predictions, references=labels)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you'd like to monitor your evaluation metrics during fine-tuning, specify the `evaluation_strategy` parameter in your training arguments to report the evaluation metric at the end of each epoch:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import TrainingArguments, Trainer\n",
"\n",
"training_args = TrainingArguments(output_dir=\"test_trainer\", evaluation_strategy=\"epoch\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Trainer"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) object with your model, training arguments, training and test datasets, and evaluation function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trainer = Trainer(\n",
" model=model,\n",
" args=training_args,\n",
" train_dataset=small_train_dataset,\n",
" eval_dataset=small_eval_dataset,\n",
" compute_metrics=compute_metrics,\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Then fine-tune your model by calling [train()](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer.train):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"trainer.train()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='keras'></a>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [
{
"data": {
"text/html": [
"<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/rnTGBy2ax1c?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#@title\n",
"from IPython.display import HTML\n",
"\n",
"HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/rnTGBy2ax1c?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train a TensorFlow model with Keras"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also train 🤗 Transformers models in TensorFlow with the Keras API!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Loading data for Keras"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you want to train a 🤗 Transformers model with the Keras API, you need to convert your dataset to a format that\n",
"Keras understands. If your dataset is small, you can just convert the whole thing to NumPy arrays and pass it to Keras.\n",
"Let's try that first before we do anything more complicated.\n",
"\n",
"First, load a dataset. We'll use the CoLA dataset from the [GLUE benchmark](https://huggingface.co/datasets/glue),\n",
"since it's a simple binary text classification task, and just take the training split for now."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"\n",
"dataset = load_dataset(\"glue\", \"cola\")\n",
"dataset = dataset[\"train\"] # Just take the training split for now"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, load a tokenizer and tokenize the data as NumPy arrays. Note that the labels are already a list of 0 and 1s,\n",
"so we can just convert that directly to a NumPy array without tokenization!"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoTokenizer\n",
"\n",
"tokenizer = AutoTokenizer.from_pretrained(\"bert-base-cased\")\n",
"tokenized_data = tokenizer(dataset[\"sentence\"], return_tensors=\"np\", padding=True)\n",
"# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras\n",
"tokenized_data = dict(tokenized_data)\n",
"\n",
"labels = np.array(dataset[\"label\"]) # Label is already an array of 0 and 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, load, [`compile`](https://keras.io/api/models/model_training_apis/#compile-method), and [`fit`](https://keras.io/api/models/model_training_apis/#fit-method) the model. Note that Transformers models all have a default task-relevant loss function, so you don't need to specify one unless you want to:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import TFAutoModelForSequenceClassification\n",
"from tensorflow.keras.optimizers import Adam\n",
"\n",
"# Load and compile our model\n",
"model = TFAutoModelForSequenceClassification.from_pretrained(\"bert-base-cased\")\n",
"# Lower learning rates are often better for fine-tuning transformers\n",
"model.compile(optimizer=Adam(3e-5)) # No loss argument!\n",
"\n",
"model.fit(tokenized_data, labels)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<Tip>\n",
"\n",
"You don't have to pass a loss argument to your models when you `compile()` them! Hugging Face models automatically\n",
"choose a loss that is appropriate for their task and model architecture if this argument is left blank. You can always\n",
"override this by specifying a loss yourself if you want to!\n",
"\n",
"</Tip>\n",
"\n",
"This approach works great for smaller datasets, but for larger datasets, you might find it starts to become a problem. Why?\n",
"Because the tokenized array and labels would have to be fully loaded into memory, and because NumPy doesn’t handle\n",
"“jagged” arrays, so every tokenized sample would have to be padded to the length of the longest sample in the whole\n",
"dataset. That’s going to make your array even bigger, and all those padding tokens will slow down training too!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Loading data as a tf.data.Dataset"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If you want to avoid slowing down training, you can load your data as a `tf.data.Dataset` instead. Although you can write your own\n",
"`tf.data` pipeline if you want, we have two convenience methods for doing this:\n",
"\n",
"- [prepare_tf_dataset()](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset): This is the method we recommend in most cases. Because it is a method\n",
"on your model, it can inspect the model to automatically figure out which columns are usable as model inputs, and\n",
"discard the others to make a simpler, more performant dataset.\n",
"- [to_tf_dataset](https://huggingface.co/docs/datasets/main/en/package_reference/main_classes#datasets.Dataset.to_tf_dataset): This method is more low-level, and is useful when you want to exactly control how\n",
"your dataset is created, by specifying exactly which `columns` and `label_cols` to include.\n",
"\n",
"Before you can use [prepare_tf_dataset()](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.TFPreTrainedModel.prepare_tf_dataset), you will need to add the tokenizer outputs to your dataset as columns, as shown in\n",
"the following code sample:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def tokenize_dataset(data):\n",
" # Keys of the returned dictionary will be added to the dataset as columns\n",
" return tokenizer(data[\"text\"])\n",
"\n",
"\n",
"dataset = dataset.map(tokenize_dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Remember that Hugging Face datasets are stored on disk by default, so this will not inflate your memory usage! Once the\n",
"columns have been added, you can stream batches from the dataset and add padding to each batch, which greatly\n",
"reduces the number of padding tokens compared to padding the entire dataset."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"tf_dataset = model.prepare_tf_dataset(dataset[\"train\"], batch_size=16, shuffle=True, tokenizer=tokenizer)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note that in the code sample above, you need to pass the tokenizer to `prepare_tf_dataset` so it can correctly pad batches as they're loaded.\n",
"If all the samples in your dataset are the same length and no padding is necessary, you can skip this argument.\n",
"If you need to do something more complex than just padding samples (e.g. corrupting tokens for masked language\n",
"modelling), you can use the `collate_fn` argument instead to pass a function that will be called to transform the\n",
"list of samples into a batch and apply any preprocessing you want. See our\n",
"[examples](https://github.com/huggingface/transformers/tree/main/examples) or\n",
"[notebooks](https://huggingface.co/docs/transformers/notebooks) to see this approach in action.\n",
"\n",
"Once you've created a `tf.data.Dataset`, you can compile and fit the model as before:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model.compile(optimizer=Adam(3e-5)) # No loss argument!\n",
"\n",
"model.fit(tf_dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='pytorch_native'></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Train in native PyTorch"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"cellView": "form",
"hide_input": true
},
"outputs": [
{
"data": {
"text/html": [
"<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/Dh9CL8fyG80?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"execution_count": null,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#@title\n",
"from IPython.display import HTML\n",
"\n",
"HTML('<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/Dh9CL8fyG80?rel=0&controls=0&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe>')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer) takes care of the training loop and allows you to fine-tune a model in a single line of code. For users who prefer to write their own training loop, you can also fine-tune a 🤗 Transformers model in native PyTorch.\n",
"\n",
"At this point, you may need to restart your notebook or execute the following code to free some memory:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"del model\n",
"del trainer\n",
"torch.cuda.empty_cache()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next, manually postprocess `tokenized_dataset` to prepare it for training.\n",
"\n",
"1. Remove the `text` column because the model does not accept raw text as an input:\n",
"\n",
" ```py\n",
" >>> tokenized_datasets = tokenized_datasets.remove_columns([\"text\"])\n",
" ```\n",
"\n",
"2. Rename the `label` column to `labels` because the model expects the argument to be named `labels`:\n",
"\n",
" ```py\n",
" >>> tokenized_datasets = tokenized_datasets.rename_column(\"label\", \"labels\")\n",
" ```\n",
"\n",
"3. Set the format of the dataset to return PyTorch tensors instead of lists:\n",
"\n",
" ```py\n",
" >>> tokenized_datasets.set_format(\"torch\")\n",
" ```\n",
"\n",
"Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"small_train_dataset = tokenized_datasets[\"train\"].shuffle(seed=42).select(range(1000))\n",
"small_eval_dataset = tokenized_datasets[\"test\"].shuffle(seed=42).select(range(1000))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### DataLoader"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create a `DataLoader` for your training and test datasets so you can iterate over batches of data:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from torch.utils.data import DataLoader\n",
"\n",
"train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)\n",
"eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Load your model with the number of expected labels:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import AutoModelForSequenceClassification\n",
"\n",
"model = AutoModelForSequenceClassification.from_pretrained(\"bert-base-cased\", num_labels=5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Optimizer and learning rate scheduler"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create an optimizer and learning rate scheduler to fine-tune the model. Let's use the [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) optimizer from PyTorch:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from torch.optim import AdamW\n",
"\n",
"optimizer = AdamW(model.parameters(), lr=5e-5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Create the default learning rate scheduler from [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from transformers import get_scheduler\n",
"\n",
"num_epochs = 3\n",
"num_training_steps = num_epochs * len(train_dataloader)\n",
"lr_scheduler = get_scheduler(\n",
" name=\"linear\", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lastly, specify `device` to use a GPU if you have access to one. Otherwise, training on a CPU may take several hours instead of a couple of minutes."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"\n",
"device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\n",
"model.to(device)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<Tip>\n",
"\n",
"Get free access to a cloud GPU if you don't have one with a hosted notebook like [Colaboratory](https://colab.research.google.com/) or [SageMaker StudioLab](https://studiolab.sagemaker.aws/).\n",
"\n",
"</Tip>\n",
"\n",
"Great, now you are ready to train! 🥳"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Training loop"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To keep track of your training progress, use the [tqdm](https://tqdm.github.io/) library to add a progress bar over the number of training steps:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from tqdm.auto import tqdm\n",
"\n",
"progress_bar = tqdm(range(num_training_steps))\n",
"\n",
"model.train()\n",
"for epoch in range(num_epochs):\n",
" for batch in train_dataloader:\n",
" batch = {k: v.to(device) for k, v in batch.items()}\n",
" outputs = model(**batch)\n",
" loss = outputs.loss\n",
" loss.backward()\n",
"\n",
" optimizer.step()\n",
" lr_scheduler.step()\n",
" optimizer.zero_grad()\n",
" progress_bar.update(1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Evaluate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just like how you added an evaluation function to [Trainer](https://huggingface.co/docs/transformers/main/en/main_classes/trainer#transformers.Trainer), you need to do the same when you write your own training loop. But instead of calculating and reporting the metric at the end of each epoch, this time you'll accumulate all the batches with `add_batch` and calculate the metric at the very end."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import evaluate\n",
"\n",
"metric = evaluate.load(\"accuracy\")\n",
"model.eval()\n",
"for batch in eval_dataloader:\n",
" batch = {k: v.to(device) for k, v in batch.items()}\n",
" with torch.no_grad():\n",
" outputs = model(**batch)\n",
"\n",
" logits = outputs.logits\n",
" predictions = torch.argmax(logits, dim=-1)\n",
" metric.add_batch(predictions=predictions, references=batch[\"labels\"])\n",
"\n",
"metric.compute()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<a id='additional-resources'></a>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Additional resources"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For more fine-tuning examples, refer to:\n",
"\n",
"- [🤗 Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) includes scripts\n",
" to train common NLP tasks in PyTorch and TensorFlow.\n",
"\n",
"- [🤗 Transformers Notebooks](https://huggingface.co/docs/transformers/main/en/notebooks) contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow."
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
} |