Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/transformers_doc/training.ipynb
Views: 2535
Fine-tune a pretrained model
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:
Fine-tune a pretrained model with 🤗 Transformers Trainer.
Fine-tune a pretrained model in TensorFlow with Keras.
Fine-tune a pretrained model in native PyTorch.
Prepare a dataset
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!
Begin by loading the Yelp Reviews dataset:
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
method to apply a preprocessing function over the entire dataset:
If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes:
Train
🤗 Transformers provides a Trainer class optimized for training 🤗 Transformers models, making it easier to start training without manually writing your own training loop. The Trainer API supports a wide range of training options and features such as logging, gradient accumulation, and mixed precision.
Start by loading your model and specify the number of expected labels. From the Yelp Review dataset card, you know there are five labels:
You will see a warning about some of the pretrained weights not being used and some weights being randomly 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.
Training hyperparameters
Next, create a 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, but feel free to experiment with these to find your optimal settings.
Specify where to save the checkpoints from your training:
Metrics
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):
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:
Trainer
Create a Trainer object with your model, training arguments, training and test datasets, and evaluation function:
Then fine-tune your model by calling train():
🤗 Transformers models also supports training in TensorFlow with the Keras API.
Convert dataset to TensorFlow format
The DefaultDataCollator assembles tensors into a batch for the model to train on. Make sure you specify return_tensors
to return TensorFlow tensors:
Trainer uses DataCollatorWithPadding by default so you don't need to explicitly specify a data collator.
Next, convert the tokenized datasets to TensorFlow datasets with the to_tf_dataset
method. Specify your inputs in columns
, and your label in label_cols
:
Compile and fit
Load a TensorFlow model with the expected number of labels:
Then compile and fine-tune your model with fit
as you would with any other Keras model:
Train in native PyTorch
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.
At this point, you may need to restart your notebook or execute the following code to free some memory:
Next, manually postprocess tokenized_dataset
to prepare it for training.
Remove the
text
column because the model does not accept raw text as an input:Rename the
label
column tolabels
because the model expects the argument to be namedlabels
:Set the format of the dataset to return PyTorch tensors instead of lists:
Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:
DataLoader
Create a DataLoader
for your training and test datasets so you can iterate over batches of data:
Load your model with the number of expected labels:
Optimizer and learning rate scheduler
Create an optimizer and learning rate scheduler to fine-tune the model. Let's use the AdamW
optimizer from PyTorch:
Create the default learning rate scheduler from Trainer:
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.
Get free access to a cloud GPU if you don't have one with a hosted notebook like Colaboratory or SageMaker StudioLab.
Great, now you are ready to train! 🥳
Training loop
To keep track of your training progress, use the tqdm library to add a progress bar over the number of training steps:
Metrics
Just like how you need to add an evaluation function to 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 will accumulate all the batches with add_batch
and calculate the metric at the very end.
Additional resources
For more fine-tuning examples, refer to:
🤗 Transformers Examples includes scripts to train common NLP tasks in PyTorch and TensorFlow.
🤗 Transformers Notebooks contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow.