Debian Codegraph @

examples/by_feature/megatron_lm_gpt_pretraining.py

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