Debian Codegraph @

examples/by_feature/gradient_accumulation.py

raw
1 # Copyright 2021 The HuggingFace Inc. 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 import evaluate
18 import torch
19 from datasets import load_dataset
20 from torch.optim import AdamW
21 from torch.utils.data import DataLoader
22 from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
23
24 from accelerate import Accelerator, DistributedType
25
26
27 ########################################################################
28 # This is a fully working simple example to use Accelerate
29 # and perform gradient accumulation
30 #
31 # This example trains a Bert base model on GLUE MRPC
32 # in any of the following settings (with the same script):
33 # - single CPU or single GPU
34 # - multi GPUS (using PyTorch distributed mode)
35 # - (multi) TPUs
36 # - fp16 (mixed-precision) or fp32 (normal precision)
37 #
38 # To run it in each of these various modes, follow the instructions
39 # in the readme for examples:
40 # https://github.com/huggingface/accelerate/tree/main/examples
41 #
42 ########################################################################
43
44
45 MAX_GPU_BATCH_SIZE = 16
46 EVAL_BATCH_SIZE = 32
47
48
49 def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
50 """
51 Creates a set of `DataLoader`s for the `glue` dataset,
52 using "bert-base-cased" as the tokenizer.
53
54 Args:
55 accelerator (`Accelerator`):
56 An `Accelerator` object
57 batch_size (`int`, *optional*):
58 The batch size for the train and validation DataLoaders.
59 """
60 tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
61 datasets = load_dataset("nyu-mll/glue", "mrpc")
62
63 def tokenize_function(examples):
64 # max_length=None => use the model max length (it's actually the default)
65 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
66 return outputs
67
68 # Apply the method we just defined to all the examples in all the splits of the dataset
69 # starting with the main process first:
70 with accelerator.main_process_first():
71 tokenized_datasets = datasets.map(
72 tokenize_function,
73 batched=True,
74 remove_columns=["idx", "sentence1", "sentence2"],
75 )
76
77 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
78 # transformers library
79 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
80
81 def collate_fn(examples):
82 # On TPU it's best to pad everything to the same length or training will be very slow.
83 max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
84 # When using mixed precision we want round multiples of 8/16
85 if accelerator.mixed_precision == "fp8":
86 pad_to_multiple_of = 16
87 elif accelerator.mixed_precision != "no":
88 pad_to_multiple_of = 8
89 else:
90 pad_to_multiple_of = None
91
92 return tokenizer.pad(
93 examples,
94 padding="longest",
95 max_length=max_length,
96 pad_to_multiple_of=pad_to_multiple_of,
97 return_tensors="pt",
98 )
99
100 # Instantiate dataloaders.
101 train_dataloader = DataLoader(
102 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
103 )
104 eval_dataloader = DataLoader(
105 tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
106 )
107
108 return train_dataloader, eval_dataloader
109
110
111 # For testing only
112 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
113 from accelerate.test_utils.training import mocked_dataloaders
114
115 get_dataloaders = mocked_dataloaders # noqa: F811
116
117
118 def training_function(config, args):
119 # For testing only
120 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
121 config["num_epochs"] = 2
122 # New Code #
123 gradient_accumulation_steps = int(args.gradient_accumulation_steps)
124 # Initialize accelerator
125 accelerator = Accelerator(
126 cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps
127 )
128 if accelerator.distributed_type == DistributedType.XLA and gradient_accumulation_steps > 1:
129 raise NotImplementedError(
130 "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`"
131 )
132 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
133 lr = config["lr"]
134 num_epochs = int(config["num_epochs"])
135 seed = int(config["seed"])
136 batch_size = int(config["batch_size"])
137
138 metric = evaluate.load("glue", "mrpc")
139
140 set_seed(seed)
141 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
142 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
143 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
144
145 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
146 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
147 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
148 model = model.to(accelerator.device)
149
150 # Instantiate optimizer
151 optimizer = AdamW(params=model.parameters(), lr=lr)
152
153 # Instantiate scheduler
154 lr_scheduler = get_linear_schedule_with_warmup(
155 optimizer=optimizer,
156 num_warmup_steps=100,
157 num_training_steps=(len(train_dataloader) * num_epochs),
158 )
159
160 # Prepare everything
161 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
162 # prepare method.
163 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
164 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
165 )
166
167 # Now we train the model
168 for epoch in range(num_epochs):
169 model.train()
170 for step, batch in enumerate(train_dataloader):
171 # We could avoid this line since we set the accelerator with `device_placement=True`.
172 batch.to(accelerator.device)
173 # New code #
174 # We use the new `accumulate` context manager to perform gradient accumulation
175 # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests.
176 with accelerator.accumulate(model):
177 output = model(**batch)
178 loss = output.loss
179 accelerator.backward(loss)
180 optimizer.step()
181 lr_scheduler.step()
182 optimizer.zero_grad()
183
184 model.eval()
185 for step, batch in enumerate(eval_dataloader):
186 # We could avoid this line since we set the accelerator with `device_placement=True`.
187 batch.to(accelerator.device)
188 with torch.no_grad():
189 outputs = model(**batch)
190 predictions = outputs.logits.argmax(dim=-1)
191 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
192 metric.add_batch(
193 predictions=predictions,
194 references=references,
195 )
196
197 eval_metric = metric.compute()
198 # Use accelerator.print to print only on the main process.
199 accelerator.print(f"epoch {epoch}:", eval_metric)
200 accelerator.end_training()
201
202
203 def main():
204 parser = argparse.ArgumentParser(description="Simple example of training script.")
205 parser.add_argument(
206 "--mixed_precision",
207 type=str,
208 default=None,
209 choices=["no", "fp16", "bf16", "fp8"],
210 help="Whether to use mixed precision. Choose"
211 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
212 "and an Nvidia Ampere GPU.",
213 )
214 # New Code #
215 parser.add_argument(
216 "--gradient_accumulation_steps",
217 type=int,
218 default=1,
219 help="The number of minibatches to be ran before gradients are accumulated.",
220 )
221 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
222 args = parser.parse_args()
223 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
224 training_function(config, args)
225
226
227 if __name__ == "__main__":
228 main()