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
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
Train with PyTorch Trainer
🌎 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:
Copied
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:
Copied
Evaluate
Trainer does not automatically evaluate model performance during training. You’ll need to pass Trainer a function to compute and report metrics. The 🌎 Evaluate library provides a simple accuracy
function you can load with the evaluate.load
(see this quicktour for more information) function:
Copied
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):
Copied
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:
Copied
Trainer
Create a Trainer object with your model, training arguments, training and test datasets, and evaluation function:
Copied
Then fine-tune your model by calling train():
Copied
Train a TensorFlow model with Keras
You can also train 🌎 Transformers models in TensorFlow with the Keras API!
Loading data for Keras
When you want to train a 🌎 Transformers model with the Keras API, you need to convert your dataset to a format that Keras understands. If your dataset is small, you can just convert the whole thing to NumPy arrays and pass it to Keras. Let’s try that first before we do anything more complicated.
First, load a dataset. We’ll use the CoLA dataset from the GLUE benchmark, since it’s a simple binary text classification task, and just take the training split for now.
Copied
Next, load a tokenizer and tokenize the data as NumPy arrays. Note that the labels are already a list of 0 and 1s, so we can just convert that directly to a NumPy array without tokenization!
Copied
Finally, load, compile
, and fit
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:
Copied
You don’t have to pass a loss argument to your models when you compile()
them! BOINC AI models automatically choose a loss that is appropriate for their task and model architecture if this argument is left blank. You can always override this by specifying a loss yourself if you want to!
This approach works great for smaller datasets, but for larger datasets, you might find it starts to become a problem. Why? Because the tokenized array and labels would have to be fully loaded into memory, and because NumPy doesn’t handle “jagged” arrays, so every tokenized sample would have to be padded to the length of the longest sample in the whole dataset. That’s going to make your array even bigger, and all those padding tokens will slow down training too!
Loading data as a tf.data.Dataset
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 tf.data
pipeline if you want, we have two convenience methods for doing this:
prepare_tf_dataset(): This is the method we recommend in most cases. Because it is a method on your model, it can inspect the model to automatically figure out which columns are usable as model inputs, and discard the others to make a simpler, more performant dataset.
to_tf_dataset: This method is more low-level, and is useful when you want to exactly control how your dataset is created, by specifying exactly which
columns
andlabel_cols
to include.
Before you can use prepare_tf_dataset(), you will need to add the tokenizer outputs to your dataset as columns, as shown in the following code sample:
Copied
Remember that BOINC AI datasets are stored on disk by default, so this will not inflate your memory usage! Once the columns have been added, you can stream batches from the dataset and add padding to each batch, which greatly reduces the number of padding tokens compared to padding the entire dataset.
Copied
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. If all the samples in your dataset are the same length and no padding is necessary, you can skip this argument. If you need to do something more complex than just padding samples (e.g. corrupting tokens for masked language modelling), you can use the collate_fn
argument instead to pass a function that will be called to transform the list of samples into a batch and apply any preprocessing you want. See our examples or notebooks to see this approach in action.
Once you’ve created a tf.data.Dataset
, you can compile and fit the model as before:
Copied
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:
Copied
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:Copied
Rename the
label
column tolabels
because the model expects the argument to be namedlabels
:Copied
Set the format of the dataset to return PyTorch tensors instead of lists:
Copied
Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:
Copied
DataLoader
Create a DataLoader
for your training and test datasets so you can iterate over batches of data:
Copied
Load your model with the number of expected labels:
Copied
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:
Copied
Create the default learning rate scheduler from Trainer:
Copied
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.
Copied
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:
Copied
Evaluate
Just like how you added 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’ll accumulate all the batches with add_batch
and calculate the metric at the very end.
Copied
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.
Last updated