Debian Codegraph @

examples/by_feature/fsdp_with_peak_mem_tracking.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 gc
16 import os
17 import threading
18
19 import evaluate
20 import psutil
21 import torch
22 from datasets import load_dataset
23 from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig
24 from torch.utils.data import DataLoader
25 from transformers import (
26 AutoModelForSequenceClassification,
27 AutoTokenizer,
28 get_linear_schedule_with_warmup,
29 set_seed,
30 )
31
32 from accelerate import Accelerator, DistributedType, FullyShardedDataParallelPlugin
33 from accelerate.utils import is_npu_available, is_xpu_available
34
35
36 ########################################################################
37 # This is a fully working simple example to use Accelerate
38 #
39 # This example trains a Bert base model on GLUE MRPC
40 # in any of the following settings (with the same script):
41 # - single CPU or single GPU
42 # - multi GPUS (using PyTorch distributed mode)
43 # - (multi) TPUs
44 # - fp16 (mixed-precision) or fp32 (normal precision)
45 # - FSDP
46 #
47 # This example also demonstrates the checkpointing and sharding capabilities
48 #
49 # To run it in each of these various modes, follow the instructions
50 # in the readme for examples:
51 # https://github.com/huggingface/accelerate/tree/main/examples
52 #
53 ########################################################################
54
55
56 MAX_GPU_BATCH_SIZE = 16
57 EVAL_BATCH_SIZE = 32
58
59
60 # New Code #
61 # Converting Bytes to Megabytes
62 def b2mb(x):
63 return int(x / 2**20)
64
65
66 # New Code #
67 # This context manager is used to track the peak memory usage of the process
68 class TorchTracemalloc:
69 def __enter__(self):
70 gc.collect()
71 if torch.cuda.is_available():
72 torch.cuda.empty_cache()
73 torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero
74 self.begin = torch.cuda.memory_allocated()
75 elif is_xpu_available():
76 torch.xpu.empty_cache()
77 torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero
78 self.begin = torch.xpu.memory_allocated()
79 elif is_npu_available():
80 torch.npu.empty_cache()
81 torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero
82 self.begin = torch.npu.memory_allocated()
83 self.process = psutil.Process()
84
85 self.cpu_begin = self.cpu_mem_used()
86 self.peak_monitoring = True
87 peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
88 peak_monitor_thread.daemon = True
89 peak_monitor_thread.start()
90 return self
91
92 def cpu_mem_used(self):
93 """get resident set size memory for the current process"""
94 return self.process.memory_info().rss
95
96 def peak_monitor_func(self):
97 self.cpu_peak = -1
98
99 while True:
100 self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak)
101
102 # can't sleep or will not catch the peak right (this comment is here on purpose)
103 # time.sleep(0.001) # 1msec
104
105 if not self.peak_monitoring:
106 break
107
108 def __exit__(self, *exc):
109 self.peak_monitoring = False
110
111 gc.collect()
112 if torch.cuda.is_available():
113 torch.cuda.empty_cache()
114 self.end = torch.cuda.memory_allocated()
115 self.peak = torch.cuda.max_memory_allocated()
116 elif is_xpu_available():
117 torch.xpu.empty_cache()
118 self.end = torch.xpu.memory_allocated()
119 self.peak = torch.xpu.max_memory_allocated()
120 elif is_npu_available():
121 torch.npu.empty_cache()
122 self.end = torch.npu.memory_allocated()
123 self.peak = torch.npu.max_memory_allocated()
124 self.used = b2mb(self.end - self.begin)
125 self.peaked = b2mb(self.peak - self.begin)
126
127 self.cpu_end = self.cpu_mem_used()
128 self.cpu_used = b2mb(self.cpu_end - self.cpu_begin)
129 self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin)
130 # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")
131
132
133 # For testing only
134 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
135 from accelerate.test_utils.training import mocked_dataloaders
136
137 get_dataloaders = mocked_dataloaders # noqa: F811
138
139
140 def training_function(config, args):
141 # For testing only
142 if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
143 config["num_epochs"] = 2
144
145 # New Code #
146 # Pass the advanced FSDP settings not part of the accelerate config by creating fsdp_plugin
147 fsdp_plugin = FullyShardedDataParallelPlugin(
148 state_dict_config=FullStateDictConfig(offload_to_cpu=False, rank0_only=False),
149 optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=False, rank0_only=False),
150 )
151
152 # Initialize accelerator
153 if args.with_tracking:
154 accelerator = Accelerator(
155 cpu=args.cpu,
156 mixed_precision=args.mixed_precision,
157 log_with="wandb",
158 project_dir=args.logging_dir,
159 fsdp_plugin=fsdp_plugin,
160 )
161 else:
162 accelerator = Accelerator(fsdp_plugin=fsdp_plugin)
163 accelerator.print(accelerator.distributed_type)
164
165 if hasattr(args.checkpointing_steps, "isdigit"):
166 if args.checkpointing_steps == "epoch":
167 checkpointing_steps = args.checkpointing_steps
168 elif args.checkpointing_steps.isdigit():
169 checkpointing_steps = int(args.checkpointing_steps)
170 else:
171 raise ValueError(
172 f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
173 )
174 else:
175 checkpointing_steps = None
176 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
177 lr = config["lr"]
178 num_epochs = int(config["num_epochs"])
179 seed = int(config["seed"])
180 batch_size = int(config["batch_size"])
181
182 # We need to initialize the trackers we use, and also store our configuration
183 if args.with_tracking:
184 experiment_config = vars(args)
185 accelerator.init_trackers("fsdp_glue_no_trainer", experiment_config)
186
187 tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
188 datasets = load_dataset("nyu-mll/glue", "mrpc")
189 metric = evaluate.load("glue", "mrpc")
190
191 def tokenize_function(examples):
192 # max_length=None => use the model max length (it's actually the default)
193 outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
194 return outputs
195
196 # Apply the method we just defined to all the examples in all the splits of the dataset
197 # starting with the main process first:
198 with accelerator.main_process_first():
199 tokenized_datasets = datasets.map(
200 tokenize_function,
201 batched=True,
202 remove_columns=["idx", "sentence1", "sentence2"],
203 )
204
205 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
206 # transformers library
207 tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
208
209 # If the batch size is too big we use gradient accumulation
210 gradient_accumulation_steps = 1
211 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
212 gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
213 batch_size = MAX_GPU_BATCH_SIZE
214
215 def collate_fn(examples):
216 # On TPU it's best to pad everything to the same length or training will be very slow.
217 max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
218 # When using mixed precision we want round multiples of 8/16
219 if accelerator.mixed_precision == "fp8":
220 pad_to_multiple_of = 16
221 elif accelerator.mixed_precision != "no":
222 pad_to_multiple_of = 8
223 else:
224 pad_to_multiple_of = None
225
226 return tokenizer.pad(
227 examples,
228 padding="longest",
229 max_length=max_length,
230 pad_to_multiple_of=pad_to_multiple_of,
231 return_tensors="pt",
232 )
233
234 # Instantiate dataloaders.
235 train_dataloader = DataLoader(
236 tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
237 )
238 eval_dataloader = DataLoader(
239 tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
240 )
241
242 set_seed(seed)
243
244 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
245 model = AutoModelForSequenceClassification.from_pretrained(
246 args.model_name_or_path, return_dict=True, low_cpu_mem_usage=True
247 )
248
249 no_decay = ["bias", "LayerNorm.weight"]
250 optimizer_grouped_parameters = [
251 {
252 "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
253 "weight_decay": 0.003,
254 },
255 {
256 "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
257 "weight_decay": 0.0,
258 },
259 ]
260
261 optimizer = torch.optim.AdamW(params=optimizer_grouped_parameters, lr=lr, weight_decay=2e-4)
262
263 # Instantiate scheduler
264 lr_scheduler = get_linear_schedule_with_warmup(
265 optimizer=optimizer,
266 num_warmup_steps=10,
267 num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
268 )
269
270 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
271 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
272 )
273
274 overall_step = 0
275
276 # Potentially load in the weights and states from a previous save
277 if args.resume_from_checkpoint:
278 if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
279 accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
280 accelerator.load_state(args.resume_from_checkpoint)
281 path = os.path.basename(args.resume_from_checkpoint)
282 else:
283 # Get the most recent checkpoint
284 dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
285 dirs.sort(key=os.path.getctime)
286 path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
287 # Extract `epoch_{i}` or `step_{i}`
288 training_difference = os.path.splitext(path)[0]
289
290 if "epoch" in training_difference:
291 num_epochs -= int(training_difference.replace("epoch_", ""))
292 resume_step = None
293 else:
294 resume_step = int(training_difference.replace("step_", ""))
295 num_epochs -= resume_step // len(train_dataloader)
296 # If resuming by step, we also need to know exactly how far into the DataLoader we went
297 resume_step = (num_epochs * len(train_dataloader)) - resume_step
298
299 # Now we train the model
300 for epoch in range(num_epochs):
301 # New Code #
302 # context manager to track the peak memory usage during the training epoch
303 with TorchTracemalloc() as tracemalloc:
304 model.train()
305 if args.with_tracking:
306 total_loss = 0
307 for step, batch in enumerate(train_dataloader):
308 # We need to skip steps until we reach the resumed step
309 if args.resume_from_checkpoint and epoch == 0:
310 if resume_step is not None and step < resume_step:
311 pass
312 # We could avoid this line since we set the accelerator with `device_placement=True`.
313 batch.to(accelerator.device)
314 outputs = model(**batch)
315 loss = outputs.loss
316 # We keep track of the loss at each epoch
317 if args.with_tracking:
318 total_loss += loss.detach().float()
319 accelerator.backward(loss)
320 if step % gradient_accumulation_steps == 0:
321 optimizer.step()
322 lr_scheduler.step()
323 optimizer.zero_grad()
324 # accelerator.print(lr_scheduler.get_lr())
325
326 overall_step += 1
327
328 if isinstance(checkpointing_steps, int):
329 output_dir = f"step_{overall_step}"
330 if overall_step % checkpointing_steps == 0:
331 if args.output_dir is not None:
332 output_dir = os.path.join(args.output_dir, output_dir)
333 accelerator.save_state(output_dir)
334 # New Code #
335 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
336 accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}")
337 accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}")
338 accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}")
339 accelerator.print(
340 f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
341 )
342 # Logging the peak memory usage of the GPU to the tracker
343 if args.with_tracking:
344 accelerator.log(
345 {
346 "train_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin),
347 },
348 step=epoch,
349 )
350
351 # New Code #
352 # context manager to track the peak memory usage during the evaluation
353 with TorchTracemalloc() as tracemalloc:
354 model.eval()
355 for step, batch in enumerate(eval_dataloader):
356 # We could avoid this line since we set the accelerator with `device_placement=True`.
357 batch.to(accelerator.device)
358 with torch.no_grad():
359 outputs = model(**batch)
360 predictions = outputs.logits.argmax(dim=-1)
361 predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
362 metric.add_batch(
363 predictions=predictions,
364 references=references,
365 )
366
367 eval_metric = metric.compute()
368 # Use accelerator.print to print only on the main process.
369 accelerator.print(f"epoch {epoch}:", eval_metric)
370 if args.with_tracking:
371 accelerator.log(
372 {
373 "accuracy": eval_metric["accuracy"],
374 "f1": eval_metric["f1"],
375 "train_loss": total_loss.item() / len(train_dataloader),
376 },
377 step=epoch,
378 )
379
380 if checkpointing_steps == "epoch":
381 output_dir = f"epoch_{epoch}"
382 if args.output_dir is not None:
383 output_dir = os.path.join(args.output_dir, output_dir)
384 accelerator.save_state(output_dir)
385 # New Code #
386 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
387 accelerator.print(f"Memory before entering the eval : {b2mb(tracemalloc.begin)}")
388 accelerator.print(f"Memory consumed at the end of the eval (end-begin): {tracemalloc.used}")
389 accelerator.print(f"Peak Memory consumed during the eval (max-begin): {tracemalloc.peaked}")
390 accelerator.print(
391 f"Total Peak Memory consumed during the eval (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
392 )
393 # Logging the peak memory usage of the GPU to the tracker
394 if args.with_tracking:
395 accelerator.log(
396 {
397 "eval_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin),
398 },
399 step=epoch,
400 )
401
402 accelerator.end_training()
403
404
405 def main():
406 parser = argparse.ArgumentParser(description="Simple example of training script.")
407 parser.add_argument(
408 "--mixed_precision",
409 type=str,
410 default=None,
411 choices=["no", "fp16", "bf16", "fp8"],
412 help="Whether to use mixed precision. Choose"
413 "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
414 "and an Nvidia Ampere GPU.",
415 )
416 parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
417 parser.add_argument(
418 "--checkpointing_steps",
419 type=str,
420 default=None,
421 help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
422 )
423 parser.add_argument(
424 "--resume_from_checkpoint",
425 type=str,
426 default=None,
427 help="If the training should continue from a checkpoint folder.",
428 )
429 parser.add_argument(
430 "--with_tracking",
431 action="store_true",
432 help="Whether to load in all available experiment trackers from the environment and use them for logging.",
433 )
434 parser.add_argument(
435 "--output_dir",
436 type=str,
437 default=".",
438 help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
439 )
440 parser.add_argument(
441 "--logging_dir",
442 type=str,
443 default="logs",
444 help="Location on where to store experiment tracking logs`",
445 )
446 parser.add_argument(
447 "--model_name_or_path",
448 type=str,
449 help="Path to pretrained model or model identifier from huggingface.co/models.",
450 required=True,
451 )
452 args = parser.parse_args()
453 config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
454 training_function(config, args)
455
456
457 if __name__ == "__main__":
458 main()