training.md 18.3 KB
Newer Older
Steven Liu's avatar
Steven Liu committed
1
<!--Copyright 2022 The HuggingFace Team. All rights reserved.
Sylvain Gugger's avatar
Sylvain Gugger committed
2
3
4
5
6
7
8
9
10

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
11
12
13
14

⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

Sylvain Gugger's avatar
Sylvain Gugger committed
15
16
-->

Steven Liu's avatar
Steven Liu committed
17
# Fine-tune a pretrained model
Sylvain Gugger's avatar
Sylvain Gugger committed
18

19
20
[[open-in-colab]]

Steven Liu's avatar
Steven Liu committed
21
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:
Sylvain Gugger's avatar
Sylvain Gugger committed
22

Steven Liu's avatar
Steven Liu committed
23
24
25
* 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.
Sylvain Gugger's avatar
Sylvain Gugger committed
26
27
28

<a id='data-processing'></a>

Steven Liu's avatar
Steven Liu committed
29
## Prepare a dataset
Sylvain Gugger's avatar
Sylvain Gugger committed
30
31
32

<Youtube id="_BZearw7f0w"/>

Steven Liu's avatar
Steven Liu committed
33
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!
Sylvain Gugger's avatar
Sylvain Gugger committed
34

Steven Liu's avatar
Steven Liu committed
35
Begin by loading the [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full) dataset:
Sylvain Gugger's avatar
Sylvain Gugger committed
36

Steven Liu's avatar
Steven Liu committed
37
38
```py
>>> from datasets import load_dataset
Sylvain Gugger's avatar
Sylvain Gugger committed
39

Steven Liu's avatar
Steven Liu committed
40
>>> dataset = load_dataset("yelp_review_full")
41
>>> dataset["train"][100]
Steven Liu's avatar
Steven Liu committed
42
43
{'label': 0,
 '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!'}
Sylvain Gugger's avatar
Sylvain Gugger committed
44
45
```

46
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#map) method to apply a preprocessing function over the entire dataset:
Sylvain Gugger's avatar
Sylvain Gugger committed
47

Steven Liu's avatar
Steven Liu committed
48
49
```py
>>> from transformers import AutoTokenizer
Sylvain Gugger's avatar
Sylvain Gugger committed
50

Steven Liu's avatar
Steven Liu committed
51
>>> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
Sylvain Gugger's avatar
Sylvain Gugger committed
52
53


Steven Liu's avatar
Steven Liu committed
54
55
>>> def tokenize_function(examples):
...     return tokenizer(examples["text"], padding="max_length", truncation=True)
Sylvain Gugger's avatar
Sylvain Gugger committed
56
57


Steven Liu's avatar
Steven Liu committed
58
>>> tokenized_datasets = dataset.map(tokenize_function, batched=True)
Sylvain Gugger's avatar
Sylvain Gugger committed
59
60
```

Steven Liu's avatar
Steven Liu committed
61
If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes:
Sylvain Gugger's avatar
Sylvain Gugger committed
62

Steven Liu's avatar
Steven Liu committed
63
64
65
```py
>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
Sylvain Gugger's avatar
Sylvain Gugger committed
66
67
68
69
```

<a id='trainer'></a>

70
## Train
Sylvain Gugger's avatar
Sylvain Gugger committed
71

Matt's avatar
Matt committed
72
73
74
75
At this point, you should follow the section corresponding to the framework you want to use. You can use the links
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,
just use the button at the top-right of that framework's block!

76
77
<frameworkcontent>
<pt>
Sylvain Gugger's avatar
Sylvain Gugger committed
78
79
<Youtube id="nvBXf7s7vTI"/>

Matt's avatar
Matt committed
80
81
## Train with PyTorch Trainer

Steven Liu's avatar
Steven Liu committed
82
🤗 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.
Sylvain Gugger's avatar
Sylvain Gugger committed
83

Steven Liu's avatar
Steven Liu committed
84
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:
Sylvain Gugger's avatar
Sylvain Gugger committed
85

Steven Liu's avatar
Steven Liu committed
86
87
```py
>>> from transformers import AutoModelForSequenceClassification
Sylvain Gugger's avatar
Sylvain Gugger committed
88

Steven Liu's avatar
Steven Liu committed
89
>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
Sylvain Gugger's avatar
Sylvain Gugger committed
90
91
```

Steven Liu's avatar
Steven Liu committed
92
<Tip>
Sylvain Gugger's avatar
Sylvain Gugger committed
93

Steven Liu's avatar
Steven Liu committed
94
95
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.
Sylvain Gugger's avatar
Sylvain Gugger committed
96

Steven Liu's avatar
Steven Liu committed
97
</Tip>
Sylvain Gugger's avatar
Sylvain Gugger committed
98

Steven Liu's avatar
Steven Liu committed
99
### Training hyperparameters
Sylvain Gugger's avatar
Sylvain Gugger committed
100

Steven Liu's avatar
Steven Liu committed
101
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](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments), but feel free to experiment with these to find your optimal settings.
Sylvain Gugger's avatar
Sylvain Gugger committed
102

Steven Liu's avatar
Steven Liu committed
103
Specify where to save the checkpoints from your training:
Sylvain Gugger's avatar
Sylvain Gugger committed
104

Steven Liu's avatar
Steven Liu committed
105
106
```py
>>> from transformers import TrainingArguments
Sylvain Gugger's avatar
Sylvain Gugger committed
107

Steven Liu's avatar
Steven Liu committed
108
>>> training_args = TrainingArguments(output_dir="test_trainer")
Sylvain Gugger's avatar
Sylvain Gugger committed
109
110
```

111
### Evaluate
Sylvain Gugger's avatar
Sylvain Gugger committed
112

113
[`Trainer`] does not automatically evaluate model performance during training. You'll need to pass [`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`] (see this [quicktour](https://huggingface.co/docs/evaluate/a_quick_tour) for more information) function:
Sylvain Gugger's avatar
Sylvain Gugger committed
114

Steven Liu's avatar
Steven Liu committed
115
116
```py
>>> import numpy as np
117
>>> import evaluate
Sylvain Gugger's avatar
Sylvain Gugger committed
118

119
>>> metric = evaluate.load("accuracy")
Steven Liu's avatar
Steven Liu committed
120
```
Sylvain Gugger's avatar
Sylvain Gugger committed
121

122
Call [`~evaluate.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):
Sylvain Gugger's avatar
Sylvain Gugger committed
123

Steven Liu's avatar
Steven Liu committed
124
125
126
127
128
```py
>>> def compute_metrics(eval_pred):
...     logits, labels = eval_pred
...     predictions = np.argmax(logits, axis=-1)
...     return metric.compute(predictions=predictions, references=labels)
Sylvain Gugger's avatar
Sylvain Gugger committed
129
130
```

Steven Liu's avatar
Steven Liu committed
131
132
133
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:

```py
134
>>> from transformers import TrainingArguments, Trainer
Sylvain Gugger's avatar
Sylvain Gugger committed
135

Steven Liu's avatar
Steven Liu committed
136
137
>>> training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch")
```
Sylvain Gugger's avatar
Sylvain Gugger committed
138

Steven Liu's avatar
Steven Liu committed
139
### Trainer
Sylvain Gugger's avatar
Sylvain Gugger committed
140

Steven Liu's avatar
Steven Liu committed
141
Create a [`Trainer`] object with your model, training arguments, training and test datasets, and evaluation function:
Sylvain Gugger's avatar
Sylvain Gugger committed
142

Steven Liu's avatar
Steven Liu committed
143
144
145
146
147
148
149
150
```py
>>> trainer = Trainer(
...     model=model,
...     args=training_args,
...     train_dataset=small_train_dataset,
...     eval_dataset=small_eval_dataset,
...     compute_metrics=compute_metrics,
... )
Sylvain Gugger's avatar
Sylvain Gugger committed
151
152
```

Steven Liu's avatar
Steven Liu committed
153
Then fine-tune your model by calling [`~transformers.Trainer.train`]:
Sylvain Gugger's avatar
Sylvain Gugger committed
154

Steven Liu's avatar
Steven Liu committed
155
156
157
```py
>>> trainer.train()
```
158
159
</pt>
<tf>
Sylvain Gugger's avatar
Sylvain Gugger committed
160
161
162
163
<a id='keras'></a>

<Youtube id="rnTGBy2ax1c"/>

Matt's avatar
Matt committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
## 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](https://huggingface.co/datasets/glue),
since it's a simple binary text classification task, and just take the training split for now.

```py
from datasets import load_dataset
Sylvain Gugger's avatar
Sylvain Gugger committed
179

Matt's avatar
Matt committed
180
181
182
dataset = load_dataset("glue", "cola")
dataset = dataset["train"]  # Just take the training split for now
```
Sylvain Gugger's avatar
Sylvain Gugger committed
183

Matt's avatar
Matt committed
184
185
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!
Sylvain Gugger's avatar
Sylvain Gugger committed
186

Steven Liu's avatar
Steven Liu committed
187
```py
Matt's avatar
Matt committed
188
from transformers import AutoTokenizer
Sylvain Gugger's avatar
Sylvain Gugger committed
189

Matt's avatar
Matt committed
190
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
191
tokenized_data = tokenizer(dataset["sentence"], return_tensors="np", padding=True)
192
193
# Tokenizer returns a BatchEncoding, but we convert that to a dict for Keras
tokenized_data = dict(tokenized_data)
Matt's avatar
Matt committed
194
195
196
197

labels = np.array(dataset["label"])  # Label is already an array of 0 and 1
```

198
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:
Matt's avatar
Matt committed
199
200
201
202
203
204
205
206

```py
from transformers import TFAutoModelForSequenceClassification
from tensorflow.keras.optimizers import Adam

# Load and compile our model
model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased")
# Lower learning rates are often better for fine-tuning transformers
207
model.compile(optimizer=Adam(3e-5))  # No loss argument!
Matt's avatar
Matt committed
208
209

model.fit(tokenized_data, labels)
Sylvain Gugger's avatar
Sylvain Gugger committed
210
211
```

Steven Liu's avatar
Steven Liu committed
212
213
<Tip>

Matt's avatar
Matt committed
214
215
216
You don't have to pass a loss argument to your models when you `compile()` them! Hugging Face 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!
Steven Liu's avatar
Steven Liu committed
217
218

</Tip>
Sylvain Gugger's avatar
Sylvain Gugger committed
219

Matt's avatar
Matt committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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:

- [`~TFPreTrainedModel.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.
- [`~datasets.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` and `label_cols` to include.

Before you can use [`~TFPreTrainedModel.prepare_tf_dataset`], you will need to add the tokenizer outputs to your dataset as columns, as shown in
the following code sample:
Sylvain Gugger's avatar
Sylvain Gugger committed
238

Steven Liu's avatar
Steven Liu committed
239
```py
Matt's avatar
Matt committed
240
241
242
def tokenize_dataset(data):
    # Keys of the returned dictionary will be added to the dataset as columns
    return tokenizer(data["text"])
Steven Liu's avatar
Steven Liu committed
243

Matt's avatar
Matt committed
244
245

dataset = dataset.map(tokenize_dataset)
Sylvain Gugger's avatar
Sylvain Gugger committed
246
247
```

Matt's avatar
Matt committed
248
249
250
Remember that Hugging Face 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.
Steven Liu's avatar
Steven Liu committed
251

Sylvain Gugger's avatar
Sylvain Gugger committed
252

Steven Liu's avatar
Steven Liu committed
253
```py
Matt's avatar
Matt committed
254
>>> tf_dataset = model.prepare_tf_dataset(dataset["train"], batch_size=16, shuffle=True, tokenizer=tokenizer)
Sylvain Gugger's avatar
Sylvain Gugger committed
255
256
```

Matt's avatar
Matt committed
257
258
259
260
261
262
263
264
265
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](https://github.com/huggingface/transformers/tree/main/examples) or
[notebooks](https://huggingface.co/docs/transformers/notebooks) to see this approach in action.

Once you've created a `tf.data.Dataset`, you can compile and fit the model as before:
Sylvain Gugger's avatar
Sylvain Gugger committed
266

Steven Liu's avatar
Steven Liu committed
267
```py
268
model.compile(optimizer=Adam(3e-5))  # No loss argument!
Sylvain Gugger's avatar
Sylvain Gugger committed
269

Matt's avatar
Matt committed
270
model.fit(tf_dataset)
Sylvain Gugger's avatar
Sylvain Gugger committed
271
```
Matt's avatar
Matt committed
272

273
274
</tf>
</frameworkcontent>
Sylvain Gugger's avatar
Sylvain Gugger committed
275
276
277

<a id='pytorch_native'></a>

278
## Train in native PyTorch
Sylvain Gugger's avatar
Sylvain Gugger committed
279

280
281
<frameworkcontent>
<pt>
Sylvain Gugger's avatar
Sylvain Gugger committed
282
283
<Youtube id="Dh9CL8fyG80"/>

Steven Liu's avatar
Steven Liu committed
284
[`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.
Sylvain Gugger's avatar
Sylvain Gugger committed
285

Steven Liu's avatar
Steven Liu committed
286
287
288
At this point, you may need to restart your notebook or execute the following code to free some memory:

```py
Sylvain Gugger's avatar
Sylvain Gugger committed
289
290
291
292
293
del model
del trainer
torch.cuda.empty_cache()
```

Steven Liu's avatar
Steven Liu committed
294
295
296
297
298
299
300
301
302
Next, manually postprocess `tokenized_dataset` to prepare it for training.

1. Remove the `text` column because the model does not accept raw text as an input:

    ```py
    >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"])
    ```

2. Rename the `label` column to `labels` because the model expects the argument to be named `labels`:
Sylvain Gugger's avatar
Sylvain Gugger committed
303

Steven Liu's avatar
Steven Liu committed
304
305
306
    ```py
    >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
    ```
Sylvain Gugger's avatar
Sylvain Gugger committed
307

Steven Liu's avatar
Steven Liu committed
308
3. Set the format of the dataset to return PyTorch tensors instead of lists:
Sylvain Gugger's avatar
Sylvain Gugger committed
309

Steven Liu's avatar
Steven Liu committed
310
311
312
    ```py
    >>> tokenized_datasets.set_format("torch")
    ```
Sylvain Gugger's avatar
Sylvain Gugger committed
313

Steven Liu's avatar
Steven Liu committed
314
315
316
317
318
Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning:

```py
>>> small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000))
>>> small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000))
Sylvain Gugger's avatar
Sylvain Gugger committed
319
320
```

Steven Liu's avatar
Steven Liu committed
321
322
323
### DataLoader

Create a `DataLoader` for your training and test datasets so you can iterate over batches of data:
Sylvain Gugger's avatar
Sylvain Gugger committed
324

Steven Liu's avatar
Steven Liu committed
325
326
```py
>>> from torch.utils.data import DataLoader
Sylvain Gugger's avatar
Sylvain Gugger committed
327

Steven Liu's avatar
Steven Liu committed
328
329
>>> train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8)
>>> eval_dataloader = DataLoader(small_eval_dataset, batch_size=8)
Sylvain Gugger's avatar
Sylvain Gugger committed
330
331
```

Steven Liu's avatar
Steven Liu committed
332
Load your model with the number of expected labels:
Sylvain Gugger's avatar
Sylvain Gugger committed
333

Steven Liu's avatar
Steven Liu committed
334
335
```py
>>> from transformers import AutoModelForSequenceClassification
Sylvain Gugger's avatar
Sylvain Gugger committed
336

Steven Liu's avatar
Steven Liu committed
337
>>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5)
Sylvain Gugger's avatar
Sylvain Gugger committed
338
339
```

Steven Liu's avatar
Steven Liu committed
340
### Optimizer and learning rate scheduler
Sylvain Gugger's avatar
Sylvain Gugger committed
341

Steven Liu's avatar
Steven Liu committed
342
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:
Sylvain Gugger's avatar
Sylvain Gugger committed
343

Steven Liu's avatar
Steven Liu committed
344
345
346
347
```py
>>> from torch.optim import AdamW

>>> optimizer = AdamW(model.parameters(), lr=5e-5)
Sylvain Gugger's avatar
Sylvain Gugger committed
348
349
```

Steven Liu's avatar
Steven Liu committed
350
Create the default learning rate scheduler from [`Trainer`]:
Sylvain Gugger's avatar
Sylvain Gugger committed
351

Steven Liu's avatar
Steven Liu committed
352
353
```py
>>> from transformers import get_scheduler
Sylvain Gugger's avatar
Sylvain Gugger committed
354

Steven Liu's avatar
Steven Liu committed
355
356
357
358
359
>>> num_epochs = 3
>>> num_training_steps = num_epochs * len(train_dataloader)
>>> lr_scheduler = get_scheduler(
...     name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps
... )
Sylvain Gugger's avatar
Sylvain Gugger committed
360
361
```

Steven Liu's avatar
Steven Liu committed
362
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.
Sylvain Gugger's avatar
Sylvain Gugger committed
363

Steven Liu's avatar
Steven Liu committed
364
365
```py
>>> import torch
Sylvain Gugger's avatar
Sylvain Gugger committed
366

Steven Liu's avatar
Steven Liu committed
367
368
>>> device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
>>> model.to(device)
Sylvain Gugger's avatar
Sylvain Gugger committed
369
370
```

Steven Liu's avatar
Steven Liu committed
371
372
373
374
375
376
377
378
379
380
381
<Tip>

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/).

</Tip>

Great, now you are ready to train! 🥳 

### Training loop

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:
Sylvain Gugger's avatar
Sylvain Gugger committed
382

Steven Liu's avatar
Steven Liu committed
383
384
```py
>>> from tqdm.auto import tqdm
Sylvain Gugger's avatar
Sylvain Gugger committed
385

Steven Liu's avatar
Steven Liu committed
386
>>> progress_bar = tqdm(range(num_training_steps))
Sylvain Gugger's avatar
Sylvain Gugger committed
387

Steven Liu's avatar
Steven Liu committed
388
389
390
391
392
393
394
>>> model.train()
>>> for epoch in range(num_epochs):
...     for batch in train_dataloader:
...         batch = {k: v.to(device) for k, v in batch.items()}
...         outputs = model(**batch)
...         loss = outputs.loss
...         loss.backward()
Sylvain Gugger's avatar
Sylvain Gugger committed
395

Steven Liu's avatar
Steven Liu committed
396
397
398
399
...         optimizer.step()
...         lr_scheduler.step()
...         optimizer.zero_grad()
...         progress_bar.update(1)
Sylvain Gugger's avatar
Sylvain Gugger committed
400
401
```

402
### Evaluate
Sylvain Gugger's avatar
Sylvain Gugger committed
403

404
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 [`~evaluate.add_batch`] and calculate the metric at the very end.
Sylvain Gugger's avatar
Sylvain Gugger committed
405

Steven Liu's avatar
Steven Liu committed
406
```py
407
408
409
>>> import evaluate

>>> metric = evaluate.load("accuracy")
Steven Liu's avatar
Steven Liu committed
410
411
412
413
414
>>> model.eval()
>>> for batch in eval_dataloader:
...     batch = {k: v.to(device) for k, v in batch.items()}
...     with torch.no_grad():
...         outputs = model(**batch)
Sylvain Gugger's avatar
Sylvain Gugger committed
415

Steven Liu's avatar
Steven Liu committed
416
417
418
...     logits = outputs.logits
...     predictions = torch.argmax(logits, dim=-1)
...     metric.add_batch(predictions=predictions, references=batch["labels"])
Sylvain Gugger's avatar
Sylvain Gugger committed
419

Steven Liu's avatar
Steven Liu committed
420
>>> metric.compute()
Sylvain Gugger's avatar
Sylvain Gugger committed
421
```
422
423
</pt>
</frameworkcontent>
Sylvain Gugger's avatar
Sylvain Gugger committed
424
425
426
427
428

<a id='additional-resources'></a>

## Additional resources

Steven Liu's avatar
Steven Liu committed
429
For more fine-tuning examples, refer to:
Sylvain Gugger's avatar
Sylvain Gugger committed
430

431
- [🤗 Transformers Examples](https://github.com/huggingface/transformers/tree/main/examples) includes scripts
Steven Liu's avatar
Steven Liu committed
432
  to train common NLP tasks in PyTorch and TensorFlow.
Sylvain Gugger's avatar
Sylvain Gugger committed
433

Steven Liu's avatar
Steven Liu committed
434
- [🤗 Transformers Notebooks](notebooks) contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow.