|
| 1 | +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. |
| 2 | + |
| 3 | +import logging |
| 4 | +import os |
| 5 | +import sys |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +try: |
| 11 | + import yaml |
| 12 | + |
| 13 | + HAVE_YAML = True |
| 14 | +except ImportError: |
| 15 | + HAVE_YAML = False |
| 16 | + |
| 17 | +from megatron.core._rank_utils import safe_get_rank as get_rank_safe |
| 18 | +from megatron.core._rank_utils import safe_get_world_size as get_world_size_safe |
| 19 | +from megatron.core.msc_utils import MultiStorageClientFeature |
| 20 | +from megatron.training.config.utils import sanitize_dataclass_config |
| 21 | +from megatron.training.utils.common_utils import print_rank_0 |
| 22 | + |
| 23 | +CONFIG_FILE = "run_config.yaml" |
| 24 | +_RUNTIME_ONLY_TARGETS = frozenset({"megatron.core.timers.Timers"}) |
| 25 | +_RECIPE_CONFIG_TARGET = "megatron.core.quantization.quant_config.RecipeConfig" |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +def join_paths(*paths: str) -> str: |
| 31 | + """Join paths, using MultiStorageClient when needed""" |
| 32 | + if not paths: |
| 33 | + raise ValueError("Empty paths") |
| 34 | + |
| 35 | + if MultiStorageClientFeature.is_enabled(): |
| 36 | + msc = MultiStorageClientFeature.import_package() |
| 37 | + return msc.os.path.join(*paths) |
| 38 | + |
| 39 | + return os.path.join(*paths) |
| 40 | + |
| 41 | + |
| 42 | +def get_checkpoint_run_config_filename(checkpoints_path: str) -> str: |
| 43 | + """Get the filename for the run configuration file within a checkpoint directory. |
| 44 | +
|
| 45 | + Args: |
| 46 | + checkpoints_path: Base directory where checkpoints are stored. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + The full path to the run configuration file (e.g., run_config.yaml). |
| 50 | + """ |
| 51 | + return join_paths(checkpoints_path, CONFIG_FILE) |
| 52 | + |
| 53 | + |
| 54 | +def read_run_config(run_config_filename: str) -> dict[str, Any]: |
| 55 | + """Read the run configuration from a YAML file (rank 0 only). |
| 56 | +
|
| 57 | + Reads the file on rank 0 and broadcasts the result to other ranks. |
| 58 | +
|
| 59 | + Args: |
| 60 | + run_config_filename: Path to the run config YAML file. |
| 61 | +
|
| 62 | + Returns: |
| 63 | + A dictionary containing the run configuration. |
| 64 | +
|
| 65 | + Raises: |
| 66 | + ImportError: If PyYAML is not installed. |
| 67 | + RuntimeError: If reading the config file fails on rank 0. |
| 68 | + """ |
| 69 | + if not HAVE_YAML: |
| 70 | + raise ImportError( |
| 71 | + "PyYAML is required to read YAML configuration files from the checkpoint. " |
| 72 | + "Install via `pip install pyyaml`." |
| 73 | + ) |
| 74 | + |
| 75 | + if torch.distributed.is_initialized(): |
| 76 | + config_obj = [None] |
| 77 | + |
| 78 | + if get_rank_safe() == 0: |
| 79 | + try: |
| 80 | + if MultiStorageClientFeature.is_enabled(): |
| 81 | + msc = MultiStorageClientFeature.import_package() |
| 82 | + with msc.open(run_config_filename, "r") as f: |
| 83 | + config_dict = yaml.safe_load(f) |
| 84 | + else: |
| 85 | + with open(run_config_filename, "r") as f: |
| 86 | + config_dict = yaml.safe_load(f) |
| 87 | + config_dict = _sanitize_run_config_object(config_dict) |
| 88 | + config_dict = apply_run_config_backward_compat(config_dict) |
| 89 | + config_obj[0] = config_dict |
| 90 | + except Exception as e: |
| 91 | + error_msg = f"ERROR: Unable to load config file {run_config_filename}: {e}" |
| 92 | + sys.stderr.write(error_msg + "\n") |
| 93 | + config_obj[0] = {"error": True, "msg": error_msg} |
| 94 | + |
| 95 | + print_rank_0( |
| 96 | + f"Broadcasting config from rank 0 to all {get_world_size_safe()} ranks", |
| 97 | + rank=get_rank_safe(), |
| 98 | + ) |
| 99 | + torch.distributed.broadcast_object_list(config_obj, src=0) |
| 100 | + |
| 101 | + if isinstance(config_obj[0], dict) and config_obj[0].get("error", False): |
| 102 | + raise RuntimeError(config_obj[0]["msg"]) |
| 103 | + |
| 104 | + return config_obj[0] |
| 105 | + else: |
| 106 | + try: |
| 107 | + if MultiStorageClientFeature.is_enabled(): |
| 108 | + msc = MultiStorageClientFeature.import_package() |
| 109 | + with msc.open(run_config_filename, "r") as f: |
| 110 | + config_dict = yaml.safe_load(f) |
| 111 | + else: |
| 112 | + with open(run_config_filename, "r") as f: |
| 113 | + config_dict = yaml.safe_load(f) |
| 114 | + except Exception as e: |
| 115 | + raise RuntimeError(f"Unable to load config file {run_config_filename}: {e}") from e |
| 116 | + |
| 117 | + config_dict = _sanitize_run_config_object(config_dict) |
| 118 | + config_dict = apply_run_config_backward_compat(config_dict) |
| 119 | + return config_dict |
| 120 | + |
| 121 | + |
| 122 | +def _sanitize_run_config_object(obj: Any) -> Any: |
| 123 | + """Remove runtime-only objects from run config dictionaries. |
| 124 | +
|
| 125 | + Timers and other runtime constructs are serialized with `_target_` entries |
| 126 | + that cannot be recreated without additional context (e.g., constructor |
| 127 | + arguments provided at runtime). These objects are not required when loading |
| 128 | + a checkpoint configuration, so we replace them with ``None`` to avoid |
| 129 | + instantiation errors when the config is processed later. |
| 130 | + """ |
| 131 | + |
| 132 | + if isinstance(obj, dict): |
| 133 | + target = obj.get("_target_") |
| 134 | + if isinstance(target, str) and target in _RUNTIME_ONLY_TARGETS: |
| 135 | + return None |
| 136 | + if ( |
| 137 | + target == _RECIPE_CONFIG_TARGET |
| 138 | + and obj.get("_call_", True) is True |
| 139 | + and set(obj).issubset({"_target_", "_call_"}) |
| 140 | + ): |
| 141 | + logger.warning( |
| 142 | + "Ignoring a legacy quantization recipe whose state was not preserved in run_config.yaml. " |
| 143 | + "The checkpoint can still be loaded, but the original per-module quantization settings " |
| 144 | + "must be supplied separately if they are needed." |
| 145 | + ) |
| 146 | + return None |
| 147 | + return {key: _sanitize_run_config_object(value) for key, value in obj.items()} |
| 148 | + if isinstance(obj, list): |
| 149 | + return [_sanitize_run_config_object(item) for item in obj] |
| 150 | + return obj |
| 151 | + |
| 152 | + |
| 153 | +def apply_run_config_backward_compat(config_dict: dict[str, Any]) -> dict[str, Any]: |
| 154 | + """Apply backward compatibility transformations to run config. |
| 155 | +
|
| 156 | + This function handles dataclass config fields that should not be passed to |
| 157 | + the constructor when loading older checkpoints. It automatically detects |
| 158 | + init=False fields by inspecting the target class. |
| 159 | +
|
| 160 | + The entire config is sanitized recursively to handle init=False fields in any part of the configuration hierarchy. |
| 161 | +
|
| 162 | + Args: |
| 163 | + config_dict: The full run configuration dictionary. |
| 164 | +
|
| 165 | + Returns: |
| 166 | + The config dictionary with backward compatibility fixes applied. |
| 167 | + """ |
| 168 | + return sanitize_dataclass_config(config_dict) |
0 commit comments