|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import json |
| 5 | +import os |
| 6 | +import re |
| 7 | +from pathlib import Path |
| 8 | +from typing import cast |
| 9 | + |
| 10 | +import torch |
| 11 | +import torch.distributed as dist |
| 12 | +from pydantic import BaseModel |
| 13 | +from torch.distributed.device_mesh import DeviceMesh |
| 14 | +from torch.distributed.tensor import DTensor |
| 15 | + |
| 16 | +from modalities.checkpointing.fsdp.fsdp_checkpoint_loading import DCPCheckpointLoading |
| 17 | +from modalities.checkpointing.stateful.app_state import AppState |
| 18 | +from modalities.config.config import ProcessGroupBackendType |
| 19 | +from modalities.config.pydantic_if_types import PydanticAppStateType, PydanticDeviceMeshIFType |
| 20 | +from modalities.main import Main |
| 21 | +from modalities.running_env.cuda_env import CudaEnv |
| 22 | +from modalities.running_env.fsdp.device_mesh import ParallelismDegrees, get_mesh_for_parallelism_method |
| 23 | + |
| 24 | + |
| 25 | +class ComponentsInstantiationModel(BaseModel): |
| 26 | + app_state: PydanticAppStateType |
| 27 | + device_mesh: PydanticDeviceMeshIFType | None = None |
| 28 | + |
| 29 | + |
| 30 | +def _parse_args() -> argparse.Namespace: |
| 31 | + parser = argparse.ArgumentParser(description="Load one or more Modalities DCP checkpoints into an app state.") |
| 32 | + parser.add_argument("--config-file-path", type=Path, required=True, help="Path to the YAML config file.") |
| 33 | + parser.add_argument( |
| 34 | + "--experiments-root-path", |
| 35 | + type=Path, |
| 36 | + required=True, |
| 37 | + help="Path passed to Main for resolver/context setup.", |
| 38 | + ) |
| 39 | + parser.add_argument( |
| 40 | + "--checkpoint-dir-paths", |
| 41 | + type=Path, |
| 42 | + nargs="+", |
| 43 | + required=True, |
| 44 | + help="Paths to multiple checkpoint directories containing *.distcp files.", |
| 45 | + ) |
| 46 | + parser.add_argument( |
| 47 | + "--json-output-path", |
| 48 | + type=Path, |
| 49 | + default=Path("layer_norms_across_checkpoints.json"), |
| 50 | + help="Output path for raw per-checkpoint norms as JSON.", |
| 51 | + ) |
| 52 | + return parser.parse_args() |
| 53 | + |
| 54 | + |
| 55 | +def _resolve_checkpoint_dir_paths(args: argparse.Namespace) -> list[Path]: |
| 56 | + return list(args.checkpoint_dir_paths) |
| 57 | + |
| 58 | + |
| 59 | +def _normalize_parameter_name(parameter_name: str) -> str: |
| 60 | + name = parameter_name |
| 61 | + for prefix in ("module.", "_orig_mod.", "_fsdp_wrapped_module."): |
| 62 | + if name.startswith(prefix): |
| 63 | + name = name[len(prefix) :] |
| 64 | + return name |
| 65 | + |
| 66 | + |
| 67 | +def _get_dp_shard_group(device_mesh: DeviceMesh | None): |
| 68 | + if device_mesh is None: |
| 69 | + return None |
| 70 | + try: |
| 71 | + return get_mesh_for_parallelism_method(device_mesh, ParallelismDegrees.DP_SHARD).get_group() |
| 72 | + except Exception: |
| 73 | + # Fallback to the default process group if a dedicated DP-shard group is unavailable. |
| 74 | + return None |
| 75 | + |
| 76 | + |
| 77 | +def _compute_and_print_parameter_norms(app_state: AppState, dp_shard_group) -> dict[str, float]: |
| 78 | + parameter_sq_sums: dict[str, torch.Tensor] = {} |
| 79 | + |
| 80 | + for model_part_idx, model_part in enumerate(app_state.model_parts): |
| 81 | + for name, parameter in model_part.named_parameters(): |
| 82 | + if not parameter.requires_grad: |
| 83 | + continue |
| 84 | + raw_name = f"model_part_{model_part_idx}.{name}" if len(app_state.model_parts) > 1 else name |
| 85 | + parameter_name = _normalize_parameter_name(raw_name) |
| 86 | + |
| 87 | + # FSDP2 parameters can be DTensors. Convert to local shard first so c10d all_reduce |
| 88 | + # operates on plain tensors instead of DTensors. |
| 89 | + local_param = parameter.to_local() if isinstance(parameter, DTensor) else parameter |
| 90 | + local_sq_sum = local_param.detach().float().pow(2).sum() |
| 91 | + parameter_sq_sums[parameter_name] = local_sq_sum |
| 92 | + |
| 93 | + # Aggregate over the DP-shard group to reconstruct global norms for sharded parameters. |
| 94 | + for parameter_name, sq_sum in parameter_sq_sums.items(): |
| 95 | + dist.all_reduce(sq_sum, op=dist.ReduceOp.SUM, group=dp_shard_group) |
| 96 | + parameter_sq_sums[parameter_name] = sq_sum |
| 97 | + |
| 98 | + parameter_norms = {name: torch.sqrt(sq_sum).item() for name, sq_sum in parameter_sq_sums.items()} |
| 99 | + |
| 100 | + if dist.get_rank() == 0: |
| 101 | + print("Per-parameter L2 norms (global across DP-shards):") |
| 102 | + for parameter_name in sorted(parameter_norms): |
| 103 | + print(f"{parameter_name}: {parameter_norms[parameter_name]:.6f}") |
| 104 | + |
| 105 | + return parameter_norms |
| 106 | + |
| 107 | + |
| 108 | +def _extract_checkpoint_label(checkpoint_dir_path: Path) -> str: |
| 109 | + match = re.search(r"seen_steps_(\d+)", checkpoint_dir_path.name) |
| 110 | + if match: |
| 111 | + return f"steps_{match.group(1)}" |
| 112 | + return checkpoint_dir_path.name |
| 113 | + |
| 114 | + |
| 115 | +def _save_json_results(results: list[dict], output_path: Path) -> None: |
| 116 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 117 | + with open(output_path, "w", encoding="utf-8") as f: |
| 118 | + json.dump(results, f, indent=2) |
| 119 | + |
| 120 | + |
| 121 | +def main() -> None: |
| 122 | + args = _parse_args() |
| 123 | + checkpoint_dir_paths = _resolve_checkpoint_dir_paths(args) |
| 124 | + |
| 125 | + with CudaEnv(process_group_backend=ProcessGroupBackendType.nccl): |
| 126 | + rank = dist.get_rank() |
| 127 | + collected_results: list[dict] = [] |
| 128 | + |
| 129 | + for checkpoint_dir_path in checkpoint_dir_paths: |
| 130 | + # Rebuild components per checkpoint because AppState only supports one load call. |
| 131 | + main_obj = Main( |
| 132 | + config_path=args.config_file_path, |
| 133 | + experiments_root_path=args.experiments_root_path, |
| 134 | + ) |
| 135 | + components = cast( |
| 136 | + ComponentsInstantiationModel, |
| 137 | + main_obj.build_components(components_model_type=ComponentsInstantiationModel), |
| 138 | + ) |
| 139 | + |
| 140 | + app_state = cast(AppState, getattr(components, "app_state")) |
| 141 | + device_mesh = cast(DeviceMesh | None, getattr(components, "device_mesh", None)) |
| 142 | + |
| 143 | + loader = DCPCheckpointLoading(global_rank=rank) |
| 144 | + loader.load_checkpoint_(app_state=app_state, checkpoint_dir_path=checkpoint_dir_path) |
| 145 | + |
| 146 | + dp_shard_group = _get_dp_shard_group(device_mesh) |
| 147 | + if rank == 0: |
| 148 | + print(f"\n=== {checkpoint_dir_path} ===") |
| 149 | + parameter_norms = _compute_and_print_parameter_norms(app_state, dp_shard_group) |
| 150 | + |
| 151 | + if rank == 0: |
| 152 | + collected_results.append( |
| 153 | + { |
| 154 | + "checkpoint_path": str(checkpoint_dir_path), |
| 155 | + "checkpoint_label": _extract_checkpoint_label(checkpoint_dir_path), |
| 156 | + "parameter_norms": parameter_norms, |
| 157 | + } |
| 158 | + ) |
| 159 | + print( |
| 160 | + f"Loaded checkpoint from {checkpoint_dir_path} on world size {dist.get_world_size()} " |
| 161 | + f"(pid={os.getpid()})." |
| 162 | + ) |
| 163 | + |
| 164 | + if rank == 0: |
| 165 | + _save_json_results(collected_results, args.json_output_path) |
| 166 | + print(f"Saved raw parameter norms JSON to {args.json_output_path}") |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + main() |
0 commit comments