Debian Codegraph @

examples/by_feature/automatic_gradient_accumulation.py

raw
1 # Copyright 2022 The HuggingFace Team. All rights reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 import argparse
15 import os
16
17 # New Code #
18 import evaluate
19 import torch
20 from datasets import load_dataset
21 from torch.optim import AdamW
22 from torch.utils.data import DataLoader
23 from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
24
25 from accelerate import Accelerator
26 from accelerate.utils import find_executable_batch_size
27
28
29 ########################################################################
30 # This is a fully working simple example to use Accelerate,
31 # specifically showcasing how to combine both the gradient accumulation
32 # and automatic batch size finder utilities of Accelerate to perfrom
33 # automatic gradient accumulation
34 #
35 # This example trains a Bert base model on GLUE MRPC
36 # in any of the following settings (with the same script):
37 # - single CPU or single GPU
38 # - multi GPUS (using PyTorch distributed mode)
39 # - (multi) TPUs
40 # - fp16 (mixed-precision) or fp32 (normal precision)
41 #
42 # New additions from the base script can be found quickly by
43 # looking for the # New Code # tags
44 #
45 # To run it in each of these various modes, follow the instructions
46 # in the readme for examples:
47 # https://github.com/huggingface/accelerate/tree/main/examples
48 #
49 ########################################################################
50
51 EVAL_BATCH_SIZE = 32
52
53
54 def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
55 """
56 Creates a set of `DataLoader`s for the `glue` dataset,
57 using "bert-base-cased" as the tokenizer.
58
59 Args:
60 accelerator (`Accelerator`):
61 An `Accelerator` object
62 batch_size (`int`, *optional*):
63 The batch size for the train and validation DataLoaders.
64 """
65 tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
66 datasets = load_dataset("nyu-mll/glue", "mrpc")
67
68 def tokenize_function(examples):
69 # max_length=None => use the model max length (it's actually the default)
70 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
71 return outputs
72
73 # Apply the method we just defined to all the examples in all the splits of the dataset
74 # starting with the main process first:
75 with accelerator.main_process_first():
76 tokenized_datasets = datasets.map(
77 tokenize_function,
78 batched=True,
79 remove_columns=["idx", "sentence1", "sentence2"],
80 )
81
82 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
83 # transformers library
84 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
85
86 def collate_fn(examples):
87 # When using mixed precision we want round multiples of 8/16
88 if accelerator.mixed_precision == "fp8":
89 pad_to_multiple_of = 16
90 elif accelerator.mixed_precision != "no":
91 pad_to_multiple_of = 8
92 else:
93 pad_to_multiple_of = None
94
95 return tokenizer.pad(
96 examples,
97 padding="longest",
98 pad_to_multiple_of=pad_to_multiple_of,
99 return_tensors="pt",
100 )
101
102 # Instantiate dataloaders.
103 train_dataloader = DataLoader(
104 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
105 )
106 eval_dataloader = DataLoader(
107 tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
108 )
109
110 return train_dataloader, eval_dataloader
111
112
113 # For testing only
114 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
115 from accelerate.test_utils.training import mocked_dataloaders
116
117 get_dataloaders = mocked_dataloaders # noqa: F811
118
119
120 def training_function(config, args):
121 # For testing only
122 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
123 config["num_epochs"] = 2
124 # Initialize accelerator
125 accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
126 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
127 lr = config["lr"]
128 num_epochs = int(config["num_epochs"])
129 seed = int(config["seed"])
130 observed_batch_size = int(config["batch_size"])
131
132 metric = evaluate.load("glue", "mrpc")
133
134 # New Code #
135 # We use the `find_executable_batch_size` decorator, passing in the desired observed batch size
136 # to train on. If a device OOM error occurs, it will retry this loop cutting the batch size in
137 # half each time. From this, we can calculate the number of gradient accumulation steps needed
138 # and modify the Accelerator object as a result
139 @find_executable_batch_size(starting_batch_size=int(observed_batch_size))
140 def inner_training_loop(batch_size):
141 # Since we need to modify the outside accelerator object, we need to bring it
142 # to the local scope
143 nonlocal accelerator
144
145 # We can calculate the number of gradient accumulation steps based on the current
146 # batch size vs the starting batch size
147 num_gradient_accumulation_steps = observed_batch_size // batch_size
148
149 # And then set it in the Accelerator directly:
150 accelerator.gradient_accumulation_steps = num_gradient_accumulation_steps
151
152 # Next we need to free all of the stored model references in the Accelerator each time
153 accelerator.free_memory()
154
155 # And set the seed so our results are reproducable each reset
156 set_seed(seed)
157
158 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
159 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
160
161 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
162 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
163 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
164 model = model.to(accelerator.device)
165
166 # Instantiate optimizer
167 optimizer = AdamW(params=model.parameters(), lr=lr)
168 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
169
170 # Instantiate scheduler
171 lr_scheduler = get_linear_schedule_with_warmup(
172 optimizer=optimizer,
173 num_warmup_steps=100,
174 num_training_steps=(len(train_dataloader) * num_epochs),
175 )
176
177 # Prepare everything
178 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
179 # prepare method.
180 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
181 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
182 )
183
184 # Now we train the model
185 for epoch in range(num_epochs):
186 model.train()
187 for step, batch in enumerate(train_dataloader):
188 # And perform gradient accumulation
189 with accelerator.accumulate(model):
190 # We could avoid this line since we set the accelerator with `device_placement=True`.
191 batch.to(accelerator.device)
192 outputs = model(**batch)
193 loss = outputs.loss
194 accelerator.backward(loss)
195 optimizer.step()
196 lr_scheduler.step()
197 optimizer.zero_grad()
198
199 model.eval()
200 for step, batch in enumerate(eval_dataloader):
201 # We could avoid this line since we set the accelerator with `device_placement=True`.
202 batch.to(accelerator.device)
203 with torch.no_grad():
204 outputs = model(**batch)
205 predictions = outputs.logits.argmax(dim=-1)
206 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
207 metric.add_batch(
208 predictions=predictions,
209 references=references,
210 )
211
212 eval_metric = metric.compute()
213 # Use accelerator.print to print only on the main process.
214 accelerator.print(f"epoch {epoch}:", eval_metric)
215
216 # New Code #
217 # And call it at the end with no arguments
218 # Note: You could also refactor this outside of your training loop function
219 inner_training_loop()
220 accelerator.end_training()
221
222
223 def main():
224 parser = argparse.ArgumentParser(description="Simple example of training script.")
225 parser.add_argument(
226 "--mixed_precision",
227 type=str,
228 default=None,
229 choices=["no", "fp16", "bf16", "fp8"],
230 help="Whether to use mixed precision. Choose"
231 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
232 "and an Nvidia Ampere GPU.",
233 )
234 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
235 args = parser.parse_args()
236 # New Code #
237 # We modify the starting batch size to be an observed batch size of 256, to guarantee an initial device OOM
238 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 256}
239 training_function(config, args)
240
241
242 if __name__ == "__main__":
243 main()