|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: LicenseRef-Apache2 |
| 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 | +import logging |
| 17 | +import os |
| 18 | +from pathlib import Path |
| 19 | + |
| 20 | +import torch |
| 21 | +import torch.distributed.checkpoint |
| 22 | + |
| 23 | + |
| 24 | +_logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +def load_torch_checkpoint(model, checkpoint_path, megatron_fsdp=False): |
| 28 | + """Load a Torch checkpoint from checkpoint_path into an unsharded model. |
| 29 | + Used for converting existing TIMM or Torch checkpoints into a freshly initialized |
| 30 | + model prior to sharding with Megatron-FSDP. |
| 31 | +
|
| 32 | + If the checkpoint was created from a Megatron-FSDP DCP checkpoint, then setting |
| 33 | + megatron_fsdp=True is required and strips a "module." prefix from the keys. |
| 34 | +
|
| 35 | + Docs: https://docs.pytorch.org/tutorials/beginner/saving_loading_models.html |
| 36 | + """ |
| 37 | + # Load model checkpoint. Remove the "module." prefix from the keys from Megatron-FSDP, |
| 38 | + # which is the main discrepancy between Megatron-FSDP and normal checkpoints. |
| 39 | + # Must load with weights_only=False if you have an optimizer state in your checkpoint. |
| 40 | + model_checkpoint = { |
| 41 | + (k.strip("module.") if megatron_fsdp else k): v |
| 42 | + for k, v in torch.load(checkpoint_path, weights_only=False)["model"].items() |
| 43 | + } |
| 44 | + # Warn about Megatron-FSDP checkpoints. |
| 45 | + first_key = next(iter(model_checkpoint)) |
| 46 | + if first_key.startswith("module.") and not megatron_fsdp: |
| 47 | + _logger.warning( |
| 48 | + f"Checkpoint state dictionary keys ({first_key}) may be prefixed " |
| 49 | + "with 'modele.' if converted from a Megatron-FSDP DCP checkpoint." |
| 50 | + "Set megatron_fsdp=True to automatically strip the prefix." |
| 51 | + ) |
| 52 | + # Load with strict=False because the checkpoint may have |
| 53 | + # TE-specific keys that are not necessary for inference. |
| 54 | + model.load_state_dict(model_checkpoint, strict=False) |
| 55 | + |
| 56 | + |
| 57 | +def load_dcp_checkpoint(checkpoint_path, model=None, optimizer=None): |
| 58 | + """Load a Torch DCP checkpoint from checkpoint_path into model and optimizer. |
| 59 | +
|
| 60 | + Docs: https://docs.pytorch.org/docs/stable/distributed.checkpoint.html |
| 61 | + """ |
| 62 | + # Load model and optimizer checkpoints. |
| 63 | + state_dict = {} |
| 64 | + if model is not None: |
| 65 | + state_dict["model"] = model.state_dict() |
| 66 | + if optimizer is not None: |
| 67 | + state_dict["optimizer"] = optimizer.state_dict() |
| 68 | + torch.distributed.checkpoint.load(state_dict, checkpoint_id=checkpoint_path) |
| 69 | + model.load_state_dict(state_dict["model"]) |
| 70 | + optimizer.load_state_dict(state_dict["optimizer"]) |
| 71 | + |
| 72 | + |
| 73 | +def load_auto_resume_checkpoint(cfg, model, optimizer): |
| 74 | + """Auto-resume training from the latest checkpoint. |
| 75 | +
|
| 76 | + Checkpoint directories should adhere to the simple format: step_<step_idx>_loss_<loss_value> |
| 77 | + If cfg.training.checkpoint.resume_from_metric is '+' or '-', then the loss_value is utilized |
| 78 | + for determining the optimal checkpoint to resume from. Otherwise, the latest checkpoint by |
| 79 | + modification time is chosen for resumption. |
| 80 | +
|
| 81 | + Args: |
| 82 | + cfg: Hydra config. |
| 83 | + model: Model to load checkpoints into. |
| 84 | + optimizer: Optimizer to load checkpoints into. |
| 85 | +
|
| 86 | + Returns: |
| 87 | + The latest step index to resume from. |
| 88 | + """ |
| 89 | + # Auto-Resume: Load latest model and optimizer checkpoints. |
| 90 | + latest_step_idx = 0 |
| 91 | + if cfg.training.checkpoint.path and Path(cfg.training.checkpoint.path).exists(): |
| 92 | + # Get latest checkpoint sub-directory, which should ONLY contain Torch DCP checkpoint sub-directories. |
| 93 | + subdirs = [x.absolute() for x in Path(cfg.training.checkpoint.path).iterdir() if x.is_dir()] |
| 94 | + if len(subdirs) > 0: |
| 95 | + # We expect a checkpoint named as: step_<step_idx>_loss_<loss_value>. |
| 96 | + # Get the latest step, the directory with the most recent modification time. |
| 97 | + opt_metric_coeff = 1 if cfg.training.checkpoint.resume_from_metric == "+" else -1 |
| 98 | + latest_subdir = max( |
| 99 | + subdirs, |
| 100 | + key=lambda x: ( |
| 101 | + opt_metric_coeff * float(x.name.split("_")[3]) |
| 102 | + if cfg.training.checkpoint.resume_from_metric |
| 103 | + else 0, |
| 104 | + x.stat().st_mtime, |
| 105 | + ), |
| 106 | + ) |
| 107 | + # Track latest step to continue training from. |
| 108 | + latest_step_idx = int(latest_subdir.name.split("_")[1]) |
| 109 | + # Load model and optimizer checkpoints. |
| 110 | + load_dcp_checkpoint(latest_subdir, model, optimizer) |
| 111 | + if torch.distributed.get_rank() == 0: |
| 112 | + _logger.info(f"Loaded latest model and optimizer checkpoints from: {latest_subdir}") |
| 113 | + |
| 114 | + # Return the auto-resumed step index for training progression. |
| 115 | + return latest_step_idx |
| 116 | + |
| 117 | + |
| 118 | +def save_dcp_checkpoint(checkpoint_path, model=None, optimizer=None): |
| 119 | + """Save a Torch DCP checkpoint of the model and optimizer to checkpoint_path. |
| 120 | +
|
| 121 | + Docs: https://docs.pytorch.org/docs/stable/distributed.checkpoint.html |
| 122 | + """ |
| 123 | + # Save model and optimizer checkpoints. |
| 124 | + state_dict = {} |
| 125 | + if model is not None: |
| 126 | + state_dict["model"] = model.state_dict() |
| 127 | + if optimizer is not None: |
| 128 | + state_dict["optimizer"] = optimizer.state_dict() |
| 129 | + torch.distributed.checkpoint.save(state_dict, checkpoint_id=checkpoint_path) |
| 130 | + |
| 131 | + |
| 132 | +def save_auto_resumable_checkpoint(cfg, model, optimizer, step_idx, loss_value): |
| 133 | + """Save an auto-resumable checkpoint of the model and optimizer at step_idx. |
| 134 | +
|
| 135 | + Checkpoint directories should adhere to the simple format: step_<step_idx>_loss_<loss_value>. |
| 136 | + This is used for auto-resumption of training. |
| 137 | +
|
| 138 | + Args: |
| 139 | + cfg: Hydra config. |
| 140 | + model: Model to save checkpoints of. |
| 141 | + optimizer: Optimizer to save checkpoints of. |
| 142 | + step_idx: Step index to save checkpoint at. |
| 143 | + loss_value: Loss value to save checkpoint at. |
| 144 | + """ |
| 145 | + |
| 146 | + # Save validated checkpoint. |
| 147 | + if cfg.training.checkpoint.path: |
| 148 | + # Create checkpoint sub-directory. |
| 149 | + ckpt_dir = Path(cfg.training.checkpoint.path) / f"step_{step_idx}_loss_{loss_value:.3f}" |
| 150 | + ckpt_dir.mkdir(parents=True, exist_ok=True) |
| 151 | + # Save model and optimizer checkpoints. |
| 152 | + save_dcp_checkpoint(ckpt_dir, model, optimizer) |
| 153 | + # Relax checkpoint permissions, which may be helpful when saving checkpoints in a container owned by root. |
| 154 | + mode = 0o777 |
| 155 | + for dirpath, _, filenames in os.walk(ckpt_dir): |
| 156 | + # Change current directory perms. |
| 157 | + os.chmod(dirpath, mode) |
| 158 | + for filename in filenames: |
| 159 | + # Change file perms. |
| 160 | + file_path = Path(dirpath) / filename |
| 161 | + os.chmod(file_path, mode) |
| 162 | + if torch.distributed.get_rank() == 0: |
| 163 | + _logger.info(f"Saved validated checkpoint to: {ckpt_dir}") |
0 commit comments