Debian Codegraph @

examples/by_feature/deepspeed_with_config_support.py

raw
1 #!/usr/bin/env python
2 # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 """
16 Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...)
17 on a text file or a dataset without using HuggingFace Trainer.
18
19 Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
20 https://huggingface.co/models?filter=text-generation
21 """
22 # You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
23
24 import argparse
25 import json
26 import logging
27 import math
28 import os
29 import random
30 from itertools import chain
31 from pathlib import Path
32
33 import datasets
34 import torch
35 import transformers
36 from datasets import load_dataset
37 from huggingface_hub import HfApi
38 from torch.utils.data import DataLoader
39 from tqdm.auto import tqdm
40 from transformers import (
41 CONFIG_MAPPING,
42 MODEL_MAPPING,
43 AutoConfig,
44 AutoModelForCausalLM,
45 AutoTokenizer,
46 SchedulerType,
47 default_data_collator,
48 get_scheduler,
49 )
50 from transformers.utils.versions import require_version
51
52 from accelerate import Accelerator, DistributedType
53 from accelerate.logging import get_logger
54 from accelerate.utils import DummyOptim, DummyScheduler, set_seed
55
56
57 logger = get_logger(__name__)
58
59 require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
60
61 MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
62 MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
63
64
65 def parse_args():
66 parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
67 parser.add_argument(
68 "--dataset_name",
69 type=str,
70 default=None,
71 help="The name of the dataset to use (via the datasets library).",
72 )
73 parser.add_argument(
74 "--dataset_config_name",
75 type=str,
76 default=None,
77 help="The configuration name of the dataset to use (via the datasets library).",
78 )
79 parser.add_argument(
80 "--train_file", type=str, default=None, help="A csv or a json file containing the training data."
81 )
82 parser.add_argument(
83 "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
84 )
85 parser.add_argument(
86 "--validation_split_percentage",
87 default=5,
88 help="The percentage of the train set used as validation set in case there's no validation split",
89 )
90 parser.add_argument(
91 "--model_name_or_path",
92 type=str,
93 help="Path to pretrained model or model identifier from huggingface.co/models.",
94 required=False,
95 )
96 parser.add_argument(
97 "--config_name",
98 type=str,
99 default=None,
100 help="Pretrained config name or path if not the same as model_name",
101 )
102 parser.add_argument(
103 "--tokenizer_name",
104 type=str,
105 default=None,
106 help="Pretrained tokenizer name or path if not the same as model_name",
107 )
108 parser.add_argument(
109 "--use_slow_tokenizer",
110 action="store_true",
111 help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
112 )
113 parser.add_argument(
114 "--per_device_train_batch_size",
115 type=int,
116 default=8,
117 help="Batch size (per device) for the training dataloader.",
118 )
119 parser.add_argument(
120 "--per_device_eval_batch_size",
121 type=int,
122 default=8,
123 help="Batch size (per device) for the evaluation dataloader.",
124 )
125 parser.add_argument(
126 "--learning_rate",
127 type=float,
128 default=5e-5,
129 help="Initial learning rate (after the potential warmup period) to use.",
130 )
131 parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
132 parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
133 parser.add_argument(
134 "--max_train_steps",
135 type=int,
136 default=None,
137 help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
138 )
139 parser.add_argument(
140 "--gradient_accumulation_steps",
141 type=int,
142 default=1,
143 help="Number of updates steps to accumulate before performing a backward/update pass.",
144 )
145 parser.add_argument(
146 "--lr_scheduler_type",
147 type=SchedulerType,
148 default="linear",
149 help="The scheduler type to use.",
150 choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
151 )
152 parser.add_argument(
153 "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
154 )
155 parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
156 parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
157 parser.add_argument(
158 "--model_type",
159 type=str,
160 default=None,
161 help="Model type to use if training from scratch.",
162 choices=MODEL_TYPES,
163 )
164 parser.add_argument(
165 "--block_size",
166 type=int,
167 default=None,
168 help=(
169 "Optional input sequence length after tokenization. The training dataset will be truncated in block of"
170 " this size for training. Default to the model max input length for single sentence inputs (take into"
171 " account special tokens)."
172 ),
173 )
174 parser.add_argument(
175 "--preprocessing_num_workers",
176 type=int,
177 default=None,
178 help="The number of processes to use for the preprocessing.",
179 )
180 parser.add_argument(
181 "--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets"
182 )
183 parser.add_argument(
184 "--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files."
185 )
186 parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
187 parser.add_argument(
188 "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
189 )
190 parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
191 parser.add_argument(
192 "--checkpointing_steps",
193 type=str,
194 default=None,
195 help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
196 )
197 parser.add_argument(
198 "--resume_from_checkpoint",
199 type=str,
200 default=None,
201 help="If the training should continue from a checkpoint folder.",
202 )
203 # New Code #
204 # Whether to load the best model at the end of training
205 parser.add_argument(
206 "--load_best_model",
207 action="store_true",
208 help="Whether to load the best model at the end of training",
209 )
210 parser.add_argument(
211 "--with_tracking",
212 action="store_true",
213 help="Whether to enable experiment trackers for logging.",
214 )
215 parser.add_argument(
216 "--report_to",
217 type=str,
218 default="all",
219 help=(
220 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
221 ' `"wandb"`, `"comet_ml"`, `"dvclive"`, and `"swanlab"`. Use `"all"` (default) to report to all integrations.'
222 "Only applicable when `--with_tracking` is passed."
223 ),
224 )
225 args = parser.parse_args()
226
227 # Sanity checks
228 if args.dataset_name is None and args.train_file is None and args.validation_file is None:
229 raise ValueError("Need either a dataset name or a training/validation file.")
230 else:
231 if args.train_file is not None:
232 extension = args.train_file.split(".")[-1]
233 assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
234 if args.validation_file is not None:
235 extension = args.validation_file.split(".")[-1]
236 assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
237
238 if args.push_to_hub:
239 assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
240
241 return args
242
243
244 # New Code #
245 def evaluate(args, model, eval_dataloader, accelerator, eval_dataset):
246 model.eval()
247 losses = []
248 for step, batch in enumerate(eval_dataloader):
249 with torch.no_grad():
250 outputs = model(**batch)
251
252 loss = outputs.loss
253 losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))
254
255 losses = torch.cat(losses)
256 try:
257 eval_loss = torch.mean(losses)
258 perplexity = math.exp(eval_loss)
259 except OverflowError:
260 perplexity = float("inf")
261 return perplexity, eval_loss
262
263
264 def main():
265 args = parse_args()
266
267 # Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
268 # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
269 # in the environment
270
271 # when using DeepSpeed, the `gradient_accumulation_steps` is properly set from the DeepSpeed plugin/config
272 # or from `accelerate launch` via `--gradient_accumulation_steps` else
273 # defaulting to the passed `args.gradient_accumulation_steps`
274 accelerator = (
275 Accelerator(
276 log_with=args.report_to,
277 project_dir=args.output_dir,
278 gradient_accumulation_steps=args.gradient_accumulation_steps,
279 )
280 if args.with_tracking
281 else Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps)
282 )
283
284 # Make one log on every process with the configuration for debugging.
285 logging.basicConfig(
286 format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
287 datefmt="%m/%d/%Y %H:%M:%S",
288 level=logging.INFO,
289 )
290 logger.info(accelerator.state, main_process_only=False)
291 if accelerator.is_local_main_process:
292 datasets.utils.logging.set_verbosity_warning()
293 transformers.utils.logging.set_verbosity_info()
294 else:
295 datasets.utils.logging.set_verbosity_error()
296 transformers.utils.logging.set_verbosity_error()
297
298 # If passed along, set the training seed now.
299 if args.seed is not None:
300 set_seed(args.seed)
301
302 # Handle the repository creation
303 if accelerator.is_main_process:
304 if args.push_to_hub:
305 api = HfApi(token=args.hub_token)
306
307 # Create repo (repo_name from args or inferred)
308 repo_name = args.hub_model_id
309 if repo_name is None:
310 repo_name = Path(args.output_dir).absolute().name
311 repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
312
313 with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
314 if "step_*" not in gitignore:
315 gitignore.write("step_*\n")
316 if "epoch_*" not in gitignore:
317 gitignore.write("epoch_*\n")
318 elif args.output_dir is not None:
319 os.makedirs(args.output_dir, exist_ok=True)
320 accelerator.wait_for_everyone()
321
322 # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
323 # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
324 # (the dataset will be downloaded automatically from the datasets Hub).
325 #
326 # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
327 # 'text' is found. You can easily tweak this behavior (see below).
328 #
329 # In distributed training, the load_dataset function guarantee that only one local process can concurrently
330 # download the dataset.
331 if args.dataset_name is not None:
332 # Downloading and loading a dataset from the hub.
333 raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name)
334 if "validation" not in raw_datasets.keys():
335 raw_datasets["validation"] = load_dataset(
336 args.dataset_name,
337 args.dataset_config_name,
338 split=f"train[:{args.validation_split_percentage}%]",
339 )
340 raw_datasets["train"] = load_dataset(
341 args.dataset_name,
342 args.dataset_config_name,
343 split=f"train[{args.validation_split_percentage}%:]",
344 )
345 else:
346 data_files = {}
347 dataset_args = {}
348 if args.train_file is not None:
349 data_files["train"] = args.train_file
350 if args.validation_file is not None:
351 data_files["validation"] = args.validation_file
352 extension = args.train_file.split(".")[-1]
353 if extension == "txt":
354 extension = "text"
355 dataset_args["keep_linebreaks"] = not args.no_keep_linebreaks
356 raw_datasets = load_dataset(extension, data_files=data_files, **dataset_args)
357 # If no validation data is there, validation_split_percentage will be used to divide the dataset.
358 if "validation" not in raw_datasets.keys():
359 raw_datasets["validation"] = load_dataset(
360 extension,
361 data_files=data_files,
362 split=f"train[:{args.validation_split_percentage}%]",
363 **dataset_args,
364 )
365 raw_datasets["train"] = load_dataset(
366 extension,
367 data_files=data_files,
368 split=f"train[{args.validation_split_percentage}%:]",
369 **dataset_args,
370 )
371
372 # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
373 # https://huggingface.co/docs/datasets/loading_datasets.html.
374
375 # Load pretrained model and tokenizer
376 #
377 # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
378 # download model & vocab.
379 if args.config_name:
380 config = AutoConfig.from_pretrained(args.config_name)
381 elif args.model_name_or_path:
382 config = AutoConfig.from_pretrained(args.model_name_or_path)
383 else:
384 config = CONFIG_MAPPING[args.model_type]()
385 logger.warning("You are instantiating a new config instance from scratch.")
386
387 if args.tokenizer_name:
388 tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
389 elif args.model_name_or_path:
390 tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
391 else:
392 raise ValueError(
393 "You are instantiating a new tokenizer from scratch. This is not supported by this script."
394 "You can do it from another script, save it, and load it from here, using --tokenizer_name."
395 )
396
397 if args.model_name_or_path:
398 model = AutoModelForCausalLM.from_pretrained(
399 args.model_name_or_path,
400 from_tf=bool(".ckpt" in args.model_name_or_path),
401 config=config,
402 )
403 else:
404 logger.info("Training new model from scratch")
405 model = AutoModelForCausalLM.from_config(config)
406
407 model.resize_token_embeddings(len(tokenizer))
408
409 # Preprocessing the datasets.
410 # First we tokenize all the texts.
411 column_names = raw_datasets["train"].column_names
412 text_column_name = "text" if "text" in column_names else column_names[0]
413
414 def tokenize_function(examples):
415 return tokenizer(examples[text_column_name])
416
417 with accelerator.main_process_first():
418 tokenized_datasets = raw_datasets.map(
419 tokenize_function,
420 batched=True,
421 num_proc=args.preprocessing_num_workers,
422 remove_columns=column_names,
423 load_from_cache_file=not args.overwrite_cache,
424 desc="Running tokenizer on dataset",
425 )
426
427 if args.block_size is None:
428 block_size = tokenizer.model_max_length
429 if block_size > 1024:
430 logger.warning(
431 f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
432 "Picking 1024 instead. You can change that default value by passing --block_size xxx."
433 )
434 block_size = 1024
435 else:
436 if args.block_size > tokenizer.model_max_length:
437 logger.warning(
438 f"The block_size passed ({args.block_size}) is larger than the maximum length for the model"
439 f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
440 )
441 block_size = min(args.block_size, tokenizer.model_max_length)
442
443 # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
444 def group_texts(examples):
445 # Concatenate all texts.
446 concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
447 total_length = len(concatenated_examples[list(examples.keys())[0]])
448 # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
449 # customize this part to your needs.
450 if total_length >= block_size:
451 total_length = (total_length // block_size) * block_size
452 # Split by chunks of max_len.
453 result = {
454 k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
455 for k, t in concatenated_examples.items()
456 }
457 result["labels"] = result["input_ids"].copy()
458 return result
459
460 # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
461 # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
462 # to preprocess.
463 #
464 # To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
465 # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
466
467 with accelerator.main_process_first():
468 lm_datasets = tokenized_datasets.map(
469 group_texts,
470 batched=True,
471 num_proc=args.preprocessing_num_workers,
472 load_from_cache_file=not args.overwrite_cache,
473 desc=f"Grouping texts in chunks of {block_size}",
474 )
475
476 train_dataset = lm_datasets["train"]
477 eval_dataset = lm_datasets["validation"]
478
479 # Log a few random samples from the training set:
480 for index in random.sample(range(len(train_dataset)), 3):
481 logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
482
483 # DataLoaders creation:
484 train_dataloader = DataLoader(
485 train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=args.per_device_train_batch_size
486 )
487 eval_dataloader = DataLoader(
488 eval_dataset, collate_fn=default_data_collator, batch_size=args.per_device_eval_batch_size
489 )
490
491 # Optimizer
492 # Split weights in two groups, one with weight decay and the other not.
493 no_decay = ["bias", "LayerNorm.weight"]
494 optimizer_grouped_parameters = [
495 {
496 "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
497 "weight_decay": args.weight_decay,
498 },
499 {
500 "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
501 "weight_decay": 0.0,
502 },
503 ]
504 # New Code #
505 # Creates Dummy Optimizer if `optimizer` was specified in the config file else creates Adam Optimizer
506 optimizer_cls = (
507 torch.optim.AdamW
508 if accelerator.state.deepspeed_plugin is None
509 or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
510 else DummyOptim
511 )
512 optimizer = optimizer_cls(optimizer_grouped_parameters, lr=args.learning_rate)
513
514 # On TPU, the tie weights in our model have been disconnected, so we need to restore the ties.
515 if accelerator.distributed_type == DistributedType.XLA:
516 model.tie_weights()
517
518 # Scheduler and math around the number of training steps.
519 num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps)
520 overrode_max_train_steps = False
521 if args.max_train_steps is None:
522 args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
523 overrode_max_train_steps = True
524 else:
525 args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
526
527 # New Code #
528 # Creates Dummy Scheduler if `scheduler` was specified in the config file else creates `args.lr_scheduler_type` Scheduler
529 if (
530 accelerator.state.deepspeed_plugin is None
531 or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
532 ):
533 lr_scheduler = get_scheduler(
534 name=args.lr_scheduler_type,
535 optimizer=optimizer,
536 num_warmup_steps=args.num_warmup_steps,
537 num_training_steps=args.max_train_steps,
538 )
539 else:
540 lr_scheduler = DummyScheduler(
541 optimizer, total_num_steps=args.max_train_steps, warmup_num_steps=args.num_warmup_steps
542 )
543
544 # Prepare everything with our `accelerator`.
545 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
546 model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
547 )
548
549 # We need to recalculate our total training steps as the size of the training dataloader may have changed.
550 num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps)
551 if overrode_max_train_steps:
552 args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
553 # Afterwards we recalculate our number of training epochs
554 args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
555
556 # Figure out how many steps we should save the Accelerator states
557 checkpointing_steps = args.checkpointing_steps
558 if checkpointing_steps is not None and checkpointing_steps.isdigit():
559 checkpointing_steps = int(checkpointing_steps)
560
561 # We need to initialize the trackers we use, and also store our configuration.
562 # The trackers initializes automatically on the main process.
563 if args.with_tracking:
564 experiment_config = vars(args)
565 # TensorBoard cannot log Enums, need the raw value
566 experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
567 accelerator.init_trackers("clm_no_trainer", experiment_config)
568
569 # Train!
570 total_batch_size = (
571 args.per_device_train_batch_size * accelerator.num_processes * accelerator.gradient_accumulation_steps
572 )
573
574 logger.info("***** Running training *****")
575 logger.info(f" Num examples = {len(train_dataset)}")
576 logger.info(f" Num Epochs = {args.num_train_epochs}")
577 logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
578 logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
579 logger.info(f" Gradient Accumulation steps = {accelerator.gradient_accumulation_steps}")
580 logger.info(f" Total optimization steps = {args.max_train_steps}")
581 # Only show the progress bar once on each machine.
582 progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
583 completed_steps = 0
584 starting_epoch = 0
585 best_metric = None
586 best_metric_checkpoint = None
587
588 # Potentially load in the weights and states from a previous save
589 if args.resume_from_checkpoint:
590 accelerator.load_state(args.resume_from_checkpoint)
591 accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
592 path = os.path.basename(args.resume_from_checkpoint)
593 training_difference = os.path.splitext(path)[0]
594
595 if "epoch" in training_difference:
596 starting_epoch = int(training_difference.replace("epoch_", "")) + 1
597 resume_step = None
598 completed_steps = starting_epoch * num_update_steps_per_epoch
599 else:
600 resume_step = int(training_difference.replace("step_", ""))
601 starting_epoch = resume_step // num_update_steps_per_epoch
602 resume_step -= starting_epoch * num_update_steps_per_epoch
603 completed_steps = resume_step
604
605 # update progress bar if resumed from checkpoint
606 progress_bar.update(completed_steps)
607
608 for epoch in range(starting_epoch, args.num_train_epochs):
609 model.train()
610 if args.with_tracking:
611 total_loss = 0
612
613 # skip new `skip_first_batches` to skip the batches when resuming from ckpt
614 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
615 # We need to skip steps until we reach the resumed step
616 active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
617 else:
618 # After the first iteration though, we need to go back to the original dataloader
619 active_dataloader = train_dataloader
620 for step, batch in enumerate(active_dataloader):
621 # In particular, DeepSpeed handles `gradient_accumulation` via `DeepSpeedEngine`.
622 # Below, we use `accelerator.accumulate` if the user
623 # wants to switch to other approaches such as plain DDP, PyTorch FSDP ...
624 # This avoids having to change any code as things are all handled across different distributed setups.
625 with accelerator.accumulate(model):
626 outputs = model(**batch)
627 loss = outputs.loss
628 accelerator.backward(loss)
629 optimizer.step()
630 lr_scheduler.step()
631 optimizer.zero_grad()
632
633 if accelerator.sync_gradients:
634 progress_bar.update(1)
635 completed_steps += 1
636
637 # We keep track of the loss at each epoch
638 if args.with_tracking:
639 step_loss = accelerator.reduce(loss.detach().clone()).item()
640 total_loss += step_loss
641
642 if isinstance(checkpointing_steps, int):
643 if completed_steps % checkpointing_steps == 0:
644 output_dir = f"step_{completed_steps}"
645 if args.output_dir is not None:
646 output_dir = os.path.join(args.output_dir, output_dir)
647 accelerator.save_state(output_dir)
648 if completed_steps >= args.max_train_steps:
649 break
650
651 perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset)
652 logger.info(f"epoch {epoch}: perplexity: {perplexity} eval_loss: {eval_loss}")
653
654 if args.with_tracking:
655 accelerator.log(
656 {
657 "perplexity": perplexity,
658 "eval_loss": eval_loss,
659 "train_loss": total_loss / len(train_dataloader),
660 "epoch": epoch,
661 "step": completed_steps,
662 },
663 step=completed_steps,
664 )
665
666 if isinstance(checkpointing_steps, str) and checkpointing_steps == "epoch":
667 accelerator.save_state(os.path.join(args.output_dir, f"epoch_{epoch}"))
668
669 # New Code #
670 # Tracks the best checkpoint and best metric
671 if best_metric is None or best_metric > perplexity:
672 best_metric = perplexity
673 best_metric_checkpoint = os.path.join(args.output_dir, "best_checkpoint")
674 accelerator.save_state(best_metric_checkpoint)
675 accelerator.print(f"New best metric: {best_metric} at epoch {epoch}")
676 accelerator.print(f"best_metric_checkpoint: {best_metric_checkpoint}")
677
678 # New Code #
679 # Loads the best checkpoint after the training is finished
680 if args.load_best_model:
681 accelerator.load_state(best_metric_checkpoint)
682
683 # New Code #
684 # Evaluates using the best checkpoint
685 perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset)
686 logger.info(f"Best model metrics: perplexity: {perplexity} eval_loss: {eval_loss}")
687 if perplexity != best_metric:
688 raise AssertionError(
689 f"Best metric {best_metric} does not match the metric {perplexity} of the loaded best model."
690 )
691
692 if args.output_dir is not None:
693 accelerator.wait_for_everyone()
694 unwrapped_model = accelerator.unwrap_model(model)
695
696 # New Code #
697 # Saves the whole/unpartitioned fp16 model when in ZeRO Stage-3 to the output directory if
698 # `stage3_gather_16bit_weights_on_model_save` is True in DeepSpeed Config file or
699 # `zero3_save_16bit_model` is True in DeepSpeed Plugin.
700 # For Zero Stages 1 and 2, models are saved as usual in the output directory.
701 # The model name saved is `pytorch_model.bin`
702 unwrapped_model.save_pretrained(
703 args.output_dir,
704 is_main_process=accelerator.is_main_process,
705 save_function=accelerator.save,
706 state_dict=accelerator.get_state_dict(model),
707 )
708 if accelerator.is_main_process:
709 tokenizer.save_pretrained(args.output_dir)
710 if args.push_to_hub:
711 api.upload_folder(
712 repo_id=repo_id,
713 folder_path=args.output_dir,
714 commit_message="End of training",
715 )
716
717 with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
718 json.dump({"perplexity": perplexity, "eval_loss": eval_loss.item()}, f)
719 accelerator.end_training()
720
721
722 if __name__ == "__main__":
723 main()