Debian Codegraph @

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