Debian Codegraph @

examples/by_feature/checkpointing.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
23
24 from accelerate import Accelerator, DataLoaderConfiguration, DistributedType
25 from accelerate.utils import set_seed
26
27
28 ########################################################################
29 # This is a fully working simple example to use Accelerate,
30 # specifically showcasing the checkpointing capability,
31 # and builds off the `nlp_example.py` script.
32 #
33 # This example trains a Bert base model on GLUE MRPC
34 # in any of the following settings (with the same script):
35 # - single CPU or single GPU
36 # - multi GPUS (using PyTorch distributed mode)
37 # - (multi) TPUs
38 # - fp16 (mixed-precision) or fp32 (normal precision)
39 #
40 # To help focus on the differences in the code, building `DataLoaders`
41 # was refactored into its own function.
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 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 dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader)
130 accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config)
131 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
132 lr = config["lr"]
133 num_epochs = int(config["num_epochs"])
134 seed = int(config["seed"])
135 batch_size = int(config["batch_size"])
136
137 # New Code #
138 # Parse out whether we are saving every epoch or after a certain number of batches
139 if hasattr(args.checkpointing_steps, "isdigit"):
140 if args.checkpointing_steps == "epoch":
141 checkpointing_steps = args.checkpointing_steps
142 elif args.checkpointing_steps.isdigit():
143 checkpointing_steps = int(args.checkpointing_steps)
144 else:
145 raise ValueError(
146 f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
147 )
148 else:
149 checkpointing_steps = None
150
151 set_seed(seed)
152
153 train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
154 metric = evaluate.load("glue", "mrpc")
155
156 # If the batch size is too big we use gradient accumulation
157 gradient_accumulation_steps = 1
158 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
159 gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
160 batch_size = MAX_GPU_BATCH_SIZE
161
162 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
163 model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
164
165 # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
166 # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
167 # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
168 model = model.to(accelerator.device)
169
170 # Instantiate optimizer
171 optimizer = AdamW(params=model.parameters(), lr=lr)
172
173 # Instantiate scheduler
174 lr_scheduler = get_linear_schedule_with_warmup(
175 optimizer=optimizer,
176 num_warmup_steps=100,
177 num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
178 )
179
180 # Prepare everything
181 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
182 # prepare method.
183 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
184 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
185 )
186
187 # New Code #
188 # We need to keep track of how many total steps we have iterated over
189 overall_step = 0
190 # We also need to keep track of the stating epoch so files are named properly
191 starting_epoch = 0
192
193 # We need to load the checkpoint back in before training here with `load_state`
194 # The total number of epochs is adjusted based on where the state is being loaded from,
195 # as we assume continuation of the same training script
196 if args.resume_from_checkpoint:
197 if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
198 accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
199 accelerator.load_state(args.resume_from_checkpoint)
200 path = os.path.basename(args.resume_from_checkpoint)
201 else:
202 # Get the most recent checkpoint
203 dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
204 dirs.sort(key=os.path.getctime)
205 path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
206 # Extract `epoch_{i}` or `step_{i}`
207 training_difference = os.path.splitext(path)[0]
208
209 if "epoch" in training_difference:
210 starting_epoch = int(training_difference.replace("epoch_", "")) + 1
211 resume_step = None
212 else:
213 resume_step = int(training_difference.replace("step_", ""))
214 starting_epoch = resume_step // len(train_dataloader)
215 resume_step -= starting_epoch * len(train_dataloader)
216
217 # Now we train the model
218 for epoch in range(starting_epoch, num_epochs):
219 model.train()
220 # New Code #
221 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
222 # We need to skip steps until we reach the resumed step only if we are not using a stateful dataloader
223 if not args.use_stateful_dataloader:
224 active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
225 else:
226 active_dataloader = train_dataloader
227 overall_step += resume_step
228 else:
229 # After the first iteration though, we need to go back to the original dataloader
230 active_dataloader = train_dataloader
231 for step, batch in enumerate(active_dataloader):
232 # We could avoid this line since we set the accelerator with `device_placement=True`.
233 batch.to(accelerator.device)
234 outputs = model(**batch)
235 loss = outputs.loss
236 loss = loss / gradient_accumulation_steps
237 accelerator.backward(loss)
238 if step % gradient_accumulation_steps == 0:
239 optimizer.step()
240 lr_scheduler.step()
241 optimizer.zero_grad()
242 # New Code #
243 overall_step += 1
244
245 # New Code #
246 # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
247 # These are saved to folders named `step_{overall_step}`
248 # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
249 # If mixed precision was used, will also save a "scalar.bin" file
250 if isinstance(checkpointing_steps, int):
251 output_dir = f"step_{overall_step}"
252 if overall_step % checkpointing_steps == 0:
253 if args.output_dir is not None:
254 output_dir = os.path.join(args.output_dir, output_dir)
255 accelerator.save_state(output_dir)
256 model.eval()
257 for step, batch in enumerate(eval_dataloader):
258 # We could avoid this line since we set the accelerator with `device_placement=True` (the default).
259 batch.to(accelerator.device)
260 with torch.no_grad():
261 outputs = model(**batch)
262 predictions = outputs.logits.argmax(dim=-1)
263 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
264 metric.add_batch(
265 predictions=predictions,
266 references=references,
267 )
268 eval_metric = metric.compute()
269 # Use accelerator.print to print only on the main process.
270 accelerator.print(f"epoch {epoch}:", eval_metric)
271
272 # New Code #
273 # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
274 # These are saved to folders named `epoch_{epoch}`
275 # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
276 # If mixed precision was used, will also save a "scalar.bin" file
277 if checkpointing_steps == "epoch":
278 output_dir = f"epoch_{epoch}"
279 if args.output_dir is not None:
280 output_dir = os.path.join(args.output_dir, output_dir)
281 accelerator.save_state(output_dir)
282 accelerator.end_training()
283
284
285 def main():
286 parser = argparse.ArgumentParser(description="Simple example of training script.")
287 parser.add_argument(
288 "--mixed_precision",
289 type=str,
290 default=None,
291 choices=["no", "fp16", "bf16", "fp8"],
292 help="Whether to use mixed precision. Choose"
293 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
294 "and an Nvidia Ampere GPU.",
295 )
296 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
297 parser.add_argument(
298 "--checkpointing_steps",
299 type=str,
300 default=None,
301 help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
302 )
303 parser.add_argument(
304 "--output_dir",
305 type=str,
306 default=".",
307 help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
308 )
309 parser.add_argument(
310 "--resume_from_checkpoint",
311 type=str,
312 default=None,
313 help="If the training should continue from a checkpoint folder.",
314 )
315 parser.add_argument(
316 "--use_stateful_dataloader",
317 action="store_true",
318 help="If the dataloader should be a resumable stateful dataloader.",
319 )
320 args = parser.parse_args()
321 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
322 training_function(config, args)
323
324
325 if __name__ == "__main__":
326 main()