Debian Codegraph @

docs/source/concept_guides/training_tpu.md

raw
1 <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4 the License. You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9 an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10 specific language governing permissions and limitations under the License.
11
12 ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13 rendered properly in your Markdown viewer.
14 -->
15
16 # Training on TPUs
17
18 Training on TPUs can be slightly different from training on multi-gpu, even with Accelerate. This guide aims to show you
19 where you should be careful and why, as well as the best practices in general.
20
21 ## Training in a Notebook
22
23 The main carepoint when training on TPUs comes from the [`notebook_launcher`]. As mentioned in the [notebook tutorial](../usage_guides/notebook), you need to
24 restructure your training code into a function that can get passed to the [`notebook_launcher`] function and be careful about not declaring any tensors on the GPU.
25
26 While on a TPU that last part is not as important, a critical part to understand is that when you launch code from a notebook you do so through a process called **forking**.
27 When launching from the command-line, you perform **spawning**, where a python process is not currently running and you *spawn* a new process in. Since your Jupyter notebook is already
28 utilizing a python process, you need to *fork* a new process from it to launch your code.
29
30 Where this becomes important is in regard to declaring your model. On forked TPU processes, it is recommended that you instantiate your model *once* and pass this into your
31 training function. This is different than training on GPUs where you create `n` models that have their gradients synced and back-propagated at certain moments. Instead, one
32 model instance is shared between all the nodes and it is passed back and forth. This is important especially when training on low-resource TPUs such as those provided in Kaggle kernels or
33 on Google Colaboratory.
34
35 Below is an example of a training function passed to the [`notebook_launcher`] if training on CPUs or GPUs:
36
37 <Tip>
38
39 This code snippet is based off the one from the `simple_nlp_example` notebook found [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb) with slight
40 modifications for the sake of simplicity
41
42 </Tip>
43
44 ```python
45 def training_function():
46 # Initialize accelerator
47 accelerator = Accelerator()
48 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2)
49 train_dataloader, eval_dataloader = create_dataloaders(
50 train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"]
51 )
52
53 # Instantiate optimizer
54 optimizer = AdamW(params=model.parameters(), lr=hyperparameters["learning_rate"])
55
56 # Prepare everything
57 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
58 # prepare method.
59 model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare(
60 model, optimizer, train_dataloader, eval_dataloader
61 )
62
63 num_epochs = hyperparameters["num_epochs"]
64 # Now we train the model
65 for epoch in range(num_epochs):
66 model.train()
67 for step, batch in enumerate(train_dataloader):
68 outputs = model(**batch)
69 loss = outputs.loss
70 accelerator.backward(loss)
71
72 optimizer.step()
73 optimizer.zero_grad()
74 ```
75
76 ```python
77 from accelerate import notebook_launcher
78
79 notebook_launcher(training_function)
80 ```
81
82 <Tip>
83
84 The `notebook_launcher` will default to 8 processes if Accelerate has been configured for a TPU
85
86 </Tip>
87
88 If you use this example and declare the model *inside* the training loop, then on a low-resource system you will potentially see an error
89 like:
90
91 ```
92 ProcessExitedException: process 0 terminated with signal SIGSEGV
93 ```
94
95 This error is *extremely* cryptic but the basic explanation is you ran out of system RAM. You can avoid this entirely by reconfiguring the training function to
96 accept a single `model` argument, and declare it in an outside cell:
97
98 ```python
99 # In another Jupyter cell
100 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2)
101 ```
102
103 ```diff
104 + def training_function(model):
105 # Initialize accelerator
106 accelerator = Accelerator()
107 - model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2)
108 train_dataloader, eval_dataloader = create_dataloaders(
109 train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"]
110 )
111 ...
112 ```
113
114 And finally calling the training function with:
115
116 ```diff
117 from accelerate import notebook_launcher
118 - notebook_launcher(training_function)
119 + notebook_launcher(training_function, (model,))
120 ```
121
122 <Tip>
123
124 The above workaround is only needed when launching a TPU instance from a Jupyter Notebook on a low-resource server such as Google Colaboratory or Kaggle. If
125 using a script or launching on a much beefier server declaring the model beforehand is not needed.
126
127 </Tip>
128
129 ## Mixed Precision and Global Variables
130
131 As mentioned in the [mixed precision tutorial](../usage_guides/mixed_precision), Accelerate supports fp16 and bf16, both of which can be used on TPUs.
132 That being said, ideally `bf16` should be utilized as it is extremely efficient to use.
133
134 There are two "layers" when using `bf16` and Accelerate on TPUs, at the base level and at the operation level.
135
136 At the base level, this is enabled when passing `mixed_precision="bf16"` to `Accelerator`, such as:
137 ```python
138 accelerator = Accelerator(mixed_precision="bf16")
139 ```
140 By default, this will cast `torch.float` and `torch.double` to `bfloat16` on TPUs.
141 The specific configuration being set is an environmental variable of `XLA_USE_BF16` is set to `1`.
142
143 There is a further configuration you can perform which is setting the `XLA_DOWNCAST_BF16` environmental variable. If set to `1`, then
144 `torch.float` is `bfloat16` and `torch.double` is `float32`.
145
146 This is performed in the `Accelerator` object when passing `downcast_bf16=True`:
147 ```python
148 accelerator = Accelerator(mixed_precision="bf16", downcast_bf16=True)
149 ```
150
151 Using downcasting instead of bf16 everywhere is good for when you are trying to calculate metrics, log values, and more where raw bf16 tensors would be unusable.
152
153 ## Training Times on TPUs
154
155 As you launch your script, you may notice that training seems exceptionally slow at first. This is because TPUs
156 first run through a few batches of data to see how much memory to allocate before finally utilizing this configured
157 memory allocation extremely efficiently.
158
159 If you notice that your evaluation code to calculate the metrics of your model takes longer due to a larger batch size being used,
160 it is recommended to keep the batch size the same as the training data if it is too slow. Otherwise the memory will reallocate to this
161 new batch size after the first few iterations.
162
163 <Tip>
164
165 Just because the memory is allocated does not mean it will be used or that the batch size will increase when going back to your training dataloader.
166
167 </Tip>