Repository navigation
Expand file tree
/
Copy pathcheckpointing.py
More file actions
4130 lines (3567 loc) · 177 KB
/
Copy pathcheckpointing.py
File metadata and controls
4130 lines (3567 loc) · 177 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Input/output checkpointing."""
import contextlib
import gc
import inspect
import os
import random
import shutil
import sys
import threading
from abc import ABC
from collections.abc import Mapping
from dataclasses import dataclass, replace
from enum import Enum, auto
from functools import partial
from logging import getLogger
from pathlib import Path
from time import time
from typing import Any, Callable, Literal, Optional, Protocol, Union, runtime_checkable
import numpy as np
import torch
import torch.nn.functional as F
from megatron.core import dist_checkpointing, tensor_parallel
from megatron.core.dist_checkpointing.dict_utils import nested_values
from megatron.core.dist_checkpointing.mapping import ShardedObject, ShardedStateDict, ShardedTensor
from megatron.core.dist_checkpointing.serialization import StateDict
from megatron.core.dist_checkpointing.strategies.fully_parallel import (
FullyParallelLoadStrategyWrapper,
FullyParallelSaveStrategyWrapper,
)
from megatron.core.dist_checkpointing.strategies.torch import (
TorchDistLoadShardedStrategy,
TorchDistSaveShardedStrategy,
_get_filesystem_reader,
)
from megatron.core.dist_checkpointing.utils import _clean_metadata_for_serialization
from megatron.core.msc_utils import MultiStorageClientFeature
from megatron.core.num_microbatches_calculator import update_num_microbatches
from megatron.core.optimizer import DistributedOptimizer, MegatronOptimizer
from megatron.core.optimizer.layer_wise_optimizer import LayerWiseDistributedOptimizer
from megatron.core.process_groups_config import ProcessGroupCollection
from megatron.core.rerun_state_machine import get_rerun_state_machine
from megatron.core.transformer import MegatronModule
from megatron.core.utils import (
get_pg_rank,
get_pg_size,
grant_shape_mismatch_for_gtp_padding,
resolve_gtp_pad_for_alignment,
unwrap_model,
)
from megatron.training.checkpointing import save_tokenizer_assets
from megatron.training.utils.checkpoint_utils import get_checkpoint_train_state_filename, read_train_state
from modelopt.torch.opt.plugins import (
restore_modelopt_state,
save_modelopt_state,
save_sharded_modelopt_state,
)
from torch.distributed.tensor import DTensor
from megatron.bridge.peft.base import PEFT
from megatron.bridge.training import fault_tolerance
from megatron.bridge.training.callbacks import CallbackContext, CallbackManager, should_fire
from megatron.bridge.training.config import CheckpointConfig, ConfigContainer
from megatron.bridge.training.gtp import get_data_distribution_group
from megatron.bridge.training.optim import memory_efficient_precision_aware_optimizer_state_checkpointing
from megatron.bridge.training.state import GlobalState, TrainState
from megatron.bridge.training.utils import comet_utils, mlflow_utils, wandb_utils
from megatron.bridge.training.utils.checkpoint_utils import (
checkpoint_exists,
ensure_directory_exists,
file_exists,
get_checkpoint_name,
get_checkpoint_run_config_filename,
get_checkpoint_tracker_filename,
is_checkpoint_iteration_directory,
is_hf_checkpoint_dir,
join_paths,
read_run_config,
)
from megatron.bridge.training.utils.log_utils import append_to_progress_log
from megatron.bridge.training.utils.pg_utils import get_pg_collection
from megatron.bridge.utils.common_utils import (
get_rank_safe,
is_last_rank,
print_rank_0,
)
from megatron.bridge.utils.import_utils import safe_import
from megatron.bridge.utils.instantiate_utils import _validate_target_prefix
from megatron.bridge.utils.safe_pickle import energon_torch_load
_, HAVE_RESIL = safe_import("nvidia_resiliency_ext.checkpointing")
try:
from megatron.core.distributed.fsdp.src.megatron_fsdp import MegatronFSDP
from megatron.core.distributed.fsdp.src.megatron_fsdp.uneven_dtensor import (
gather_uneven_dtensor_to_full_tensor,
preprocess_state_dict_for_uneven_dtensor,
)
from megatron.core.transformer.fsdp_dtensor_checkpoint import (
handle_experts_in_state_dict,
handle_fp8_extra_state_case,
handle_swiglu_in_state_dict,
print_diff_in_state_dicts,
)
HAVE_MEGATRON_FSDP = True
except ImportError:
HAVE_MEGATRON_FSDP = False
try:
from megatron.core.transformer.fsdp_dtensor_checkpoint import handle_gdn_in_state_dict
except ImportError:
handle_gdn_in_state_dict = None
# Available from megatron-core with fused-MLA / MTP fsdp_dtensor support; None on older cores,
# where the corresponding preprocessing and validation steps are skipped.
try:
from megatron.core.transformer.fsdp_dtensor_checkpoint import (
handle_mla_down_proj_in_state_dict,
handle_mtp_in_state_dict,
validate_fsdp_dtensor_model_load,
)
except ImportError:
handle_mla_down_proj_in_state_dict = None
handle_mtp_in_state_dict = None
validate_fsdp_dtensor_model_load = None
try:
from nvidia_resiliency_ext.checkpointing.async_ckpt.core import AsyncRequest as NVRxAsyncRequest
from nvidia_resiliency_ext.checkpointing.async_ckpt.filesystem_async import FileSystemWriterAsync
from nvidia_resiliency_ext.checkpointing.async_ckpt.state_dict_saver import (
save_state_dict_async_finalize,
save_state_dict_async_plan,
)
HAVE_NVRX = True
except (ImportError, ModuleNotFoundError):
NVRxAsyncRequest = ABC
HAVE_NVRX = False
TRACKER_PREFIX = "latest"
_CHECKPOINT_VERSION = None
logger = getLogger(__name__)
_NON_PERSISTENT_CKPT_SUBDIR = "non_persistent"
_DIRECT_ITERATION_DIR_SENTINEL = -2
_CHECKPOINT_CLEANUP_LOCK = threading.Lock()
HF_WEIGHTS_SUBDIR = "hf"
# Subdirectory of the model checkpoint dir where dataloader stream-position state is colocated by
# default (currently only Megatron Energon). Used to derive dataloader_save / dataloader_load when
# those config fields are left unset.
DATALOADER_STATE_SUBDIR = "energon"
def _get_run_config_tp_pp(model_config: Mapping[str, Any]) -> tuple[int, int]:
"""Read TP/PP sizes from a flat provider or nested HybridModel config."""
transformer_config = model_config.get("transformer")
parallel_config = transformer_config if isinstance(transformer_config, Mapping) else model_config
return (
parallel_config["tensor_model_parallel_size"],
parallel_config["pipeline_model_parallel_size"],
)
class _CpuTorchDistSaveShardedStrategy(TorchDistSaveShardedStrategy):
"""Run MCore's synchronous torch-dist writer without a CUDA staging barrier."""
@staticmethod
def _run_finalize(finalize_fn: Callable[[], None]) -> None:
"""Use a backend-compatible device for MCore's failure-status tensor."""
if torch.distributed.is_initialized() and torch.distributed.get_backend() == "nccl":
finalize_fn()
return
current_device = torch.cuda.current_device
try:
torch.cuda.current_device = lambda: torch.device("cpu")
finalize_fn()
finally:
torch.cuda.current_device = current_device
def save(self, sharded_state_dict: ShardedStateDict, checkpoint_dir: Path) -> None:
"""Save CPU tensors synchronously without calling ``torch.cuda.synchronize``."""
if "async_strategy" not in inspect.signature(TorchDistSaveShardedStrategy.async_save).parameters:
# New MCore uses PyTorch's CPU-safe synchronous writer directly.
return super().save(sharded_state_dict, checkpoint_dir)
# Older MCore pins still stage synchronous saves through their async writer.
async_request = self.async_save(sharded_state_dict, checkpoint_dir, async_strategy="mcore")
preload_fn = async_request.preload_fn
if preload_fn is not None:
if not isinstance(preload_fn, partial):
raise TypeError(f"Expected a partial CPU preload callback, got {type(preload_fn).__name__}.")
bound = inspect.signature(preload_fn.func).bind_partial(
*preload_fn.args,
**(preload_fn.keywords or {}),
)
if "non_blocking" not in bound.signature.parameters:
raise TypeError("MCore checkpoint preload callback does not accept non_blocking.")
bound.arguments["non_blocking"] = False
async_request = async_request._replace(
preload_fn=partial(preload_fn.func, *bound.args, **bound.kwargs),
)
async_request = async_request._replace(
finalize_fns=[partial(self._run_finalize, finalize_fn) for finalize_fn in async_request.finalize_fns],
)
async_request.execute_sync()
# ============================================================================
# Checkpoint version and utilities
# ============================================================================
def _get_global_non_persistent_checkpoint_dirs(
load_dir: str | None,
ckpt_cfg: CheckpointConfig,
) -> tuple[str, ...]:
"""Return the configured global non-persistent checkpoint sources."""
if ckpt_cfg.non_persistent_global_ckpt_dir:
return (ckpt_cfg.non_persistent_global_ckpt_dir,)
checkpoint_dirs = []
for checkpoint_root in (getattr(ckpt_cfg, "save", None), load_dir):
if isinstance(checkpoint_root, str) and checkpoint_root:
checkpoint_dir = os.path.join(checkpoint_root, _NON_PERSISTENT_CKPT_SUBDIR)
if checkpoint_dir not in checkpoint_dirs:
checkpoint_dirs.append(checkpoint_dir)
return tuple(checkpoint_dirs)
def _has_global_non_persistent_checkpoint(load_dir: str | None, ckpt_cfg: CheckpointConfig) -> bool:
"""Return whether the configured global non-persistent checkpoint source exists."""
if ckpt_cfg.non_persistent_ckpt_type != "global":
return False
return any(checkpoint_exists(path) for path in _get_global_non_persistent_checkpoint_dirs(load_dir, ckpt_cfg))
def set_checkpoint_version(value: float) -> None:
"""Set the global checkpoint version number.
Args:
value: The checkpoint version number (e.g., 3.0).
"""
global _CHECKPOINT_VERSION
if _CHECKPOINT_VERSION is not None:
assert _CHECKPOINT_VERSION == value, "checkpoint versions do not match"
_CHECKPOINT_VERSION = value
def get_checkpoint_version() -> Optional[float]:
"""Get the global checkpoint version number.
Returns:
The checkpoint version number, or None if not set.
"""
global _CHECKPOINT_VERSION
return _CHECKPOINT_VERSION
def delete_extra_state(state_dict):
"""Delete all extra state keys from the model state dictionary.
This function removes all keys containing '_extra_state' from the model
portion of the state dictionary. This is useful for cleaning up corrupted
or problematic extra state that can cause issues during model loading.
Args:
state_dict: The state dictionary. Can be either:
- A full checkpoint dict with a "model" key, or
- A model state dict directly
Returns:
The modified state dictionary with extra state keys removed.
"""
# Handle both cases: full checkpoint dict with "model" key or direct model state dict
if isinstance(state_dict, dict) and "model" in state_dict:
# Full checkpoint dict case
target_dict = state_dict["model"]
else:
# Direct model state dict case
target_dict = state_dict
# If target is not a mapping-like object, nothing to clean
if not hasattr(target_dict, "keys"):
return state_dict
# Some objects may implement keys() but not be directly iterable into a list (e.g., mocks)
try:
keys = list(target_dict.keys())
except Exception:
return state_dict
for key in keys:
if isinstance(key, str) and "_extra_state" in key:
del target_dict[key]
return state_dict
def _get_checkpoint_format(checkpoint_path: str) -> str:
"""Determine the checkpoint format by examining the checkpoint directory.
Args:
checkpoint_path: Path to the checkpoint directory.
Returns:
The checkpoint format string. One of ``"torch_dist"``, ``"fsdp_dtensor"`` or ``"hf"``.
"""
# Check for Megatron Core distributed checkpoint first
if dist_checkpointing.check_is_distributed_checkpoint(checkpoint_path):
print_rank_0(f" Auto-detected checkpoint format as 'torch_dist' from {checkpoint_path}.")
return "torch_dist"
# Check for PyTorch DCP format (.metadata file exists)
if MultiStorageClientFeature.is_enabled():
msc = MultiStorageClientFeature.import_package()
checkpoint_dir = msc.Path(checkpoint_path)
is_torch_dcp = checkpoint_dir.joinpath(".metadata").exists()
else:
is_torch_dcp = os.path.exists(os.path.join(checkpoint_path, ".metadata"))
if is_torch_dcp:
# Assume fsdp_dtensor for PyTorch DCP format
return "fsdp_dtensor"
# HuggingFace full-model format (raw HF repo OR the extra ``iter_*/hf`` export written
# by Bridge with ``also_save_hf_checkpoint=True``).
if is_hf_checkpoint_dir(checkpoint_path):
print_rank_0(f" Auto-detected checkpoint format as 'hf' from {checkpoint_path}.")
return "hf"
raise NotImplementedError(f"Unknown checkpoint format in {checkpoint_path}")
def find_checkpoint_rank_0(checkpoints_path: str, iteration: int, release: bool = False) -> Optional[str]:
"""Find the checkpoint directory for a given iteration, assuming distributed checkpoints.
Args:
checkpoints_path: Base directory where checkpoints are stored.
iteration: The training iteration number.
release: If True, searches within the 'release' directory.
Returns:
The full path to the checkpoint directory if it's a valid distributed checkpoint, else None.
"""
# Get the base directory for the iteration using the simplified get_checkpoint_name
checkpoint_dir = get_checkpoint_name(checkpoints_path, iteration, release=release)
# Check if this directory is a valid distributed checkpoint
if dist_checkpointing.check_is_distributed_checkpoint(checkpoint_dir):
return checkpoint_dir
return None
def read_metadata(tracker_filename: str) -> tuple[int, bool]:
"""Read the metadata from the Megatron-LM tracker file.
Args:
tracker_filename: Path to the tracker file.
Returns:
A tuple containing the iteration number and a boolean indicating if it's a release checkpoint.
"""
iteration = 0
release = False
if MultiStorageClientFeature.is_enabled():
msc = MultiStorageClientFeature.import_package()
open_file = msc.open
else:
open_file = open
with open_file(tracker_filename, "r") as f:
metastring = f.read().strip()
try:
iteration = int(metastring)
except ValueError:
release = metastring == "release"
if not release:
print_rank_0("ERROR: Invalid metadata file {}. Exiting".format(tracker_filename))
sys.exit()
assert iteration > 0 or release, "error parsing metadata file {}".format(tracker_filename)
# Get the max iteration retrieved across the ranks.
if torch.distributed.is_initialized():
iters_cuda = torch.tensor([iteration], dtype=torch.long, device="cuda")
torch.distributed.all_reduce(iters_cuda, op=torch.distributed.ReduceOp.MAX)
max_iter = iters_cuda[0].item()
# We should now have all the same iteration.
# If not, print a warning and chose the maximum
# iteration across all ranks.
if iteration != max_iter:
rank = torch.distributed.get_rank()
print_rank_0(
"WARNING: on rank {} found iteration {} in the "
"metadata while max iteration across the ranks "
"is {}, replacing it with max iteration.".format(rank, iteration, max_iter),
flush=True,
)
else:
# When loading a checkpoint outside of training (for example,
# when editing it), we might not have torch distributed
# initialized, in this case, just assume we have the latest
max_iter = iteration
return max_iter, release
def _extract_megatron_lm_args_from_state_dict(state_dict: dict[str, Any]) -> dict[str, Any]:
"""Extract and convert legacy Megatron-LM args from checkpoint state_dict to Megatron-Bridge config format.
Args:
state_dict: The loaded checkpoint state dictionary.
Returns:
A dictionary in Megatron-Bridge config format with the essential fields.
Raises:
RuntimeError: If args are not found in the state_dict.
"""
if "args" not in state_dict:
raise RuntimeError("Legacy checkpoint missing 'args' field in state_dict")
args = state_dict["args"]
# Convert args to minimal config container dict format
config = {
"model": {
"tensor_model_parallel_size": getattr(args, "tensor_model_parallel_size", 1),
"pipeline_model_parallel_size": getattr(args, "pipeline_model_parallel_size", 1),
"encoder_tensor_model_parallel_size": getattr(args, "encoder_tensor_model_parallel_size", 0),
"encoder_pipeline_model_parallel_size": getattr(args, "encoder_pipeline_model_parallel_size", 0),
},
"checkpoint": {
"save_optim": not getattr(args, "no_save_optim", False), # Invert no_save_optim
"save_rng": not getattr(args, "no_save_rng", False), # Invert no_save_rng
"fully_parallel_save": getattr(args, "ckpt_fully_parallel_save", False),
},
"rng": {
"data_parallel_random_init": getattr(args, "data_parallel_random_init", False),
},
}
return config
# ============================================================================
# Async checkpoint utilities
# ============================================================================
def schedule_async_save(global_state: GlobalState, async_request: NVRxAsyncRequest) -> None:
"""Schedule the async save request.
Args:
global_state: The global training state containing the async calls queue.
async_request: the async save request.
"""
async_queue = global_state.async_calls_queue
if async_queue is not None:
async_queue.schedule_async_request(async_request)
def maybe_finalize_async_save(
global_state: GlobalState, ckpt_cfg: CheckpointConfig, blocking: bool = False, terminate: bool = False
) -> None:
"""Finalizes active async save calls.
Args:
global_state: The global training state containing the async calls queue.
ckpt_cfg (CheckpointConfig): The checkpoint configuration.
blocking (bool, optional): if True, will wait until all active requests
are done. Otherwise, finalizes only the async request that already
finished. Defaults to False.
terminate (bool, optional): if True, the asynchronous queue will
be closed as the last action of this function.
"""
if not ckpt_cfg.async_save:
return
async_queue = global_state.async_calls_queue
if blocking and not is_empty_async_queue(global_state):
print_rank_0("Unfinalized async checkpoint saves. Finalizing them synchronously now.")
if async_queue is not None:
async_queue.maybe_finalize_async_calls(blocking)
if terminate and async_queue is not None:
async_queue.close()
def is_empty_async_queue(global_state: GlobalState) -> bool:
"""Check if async calls queue is empty. This result is consistent across ranks.
Args:
global_state: The global training state containing the async calls queue.
Returns:
bool: True if there is no in-flight async checkpoint work.
"""
async_queue = global_state.async_calls_queue
if async_queue is not None and async_queue.get_num_unfinalized_calls() > 0:
return False
return True
def get_save_and_finalize_callbacks(writer, save_state_dict_ret) -> NVRxAsyncRequest:
"""Creates an async save request for fsdp_dtensor & torch_dcp with a finalize function."""
save_fn, preload_fn, save_args = writer.get_save_function_and_args()
def finalize_fn():
"""Finalizes async checkpointing and synchronizes processes."""
save_state_dict_async_finalize(*save_state_dict_ret)
return NVRxAsyncRequest(save_fn, save_args, [finalize_fn], async_fn_kwargs={}, preload_fn=preload_fn)
def get_rng_state(
data_parallel_random_init: bool,
ckpt_format: str = "torch_dist",
*,
pg_collection: ProcessGroupCollection,
module_name: str | None = None,
) -> ShardedObject | dict:
"""Get the random number generator states for all necessary libraries.
Collects states from random, numpy, torch, cuda, and the Megatron RNG tracker.
Optionally gathers states across data parallel ranks.
Returns format depends on checkpoint format.
For torch_dist, RNG states are sharded by (PP, TP, DP/CP). Ordinary data
parallel peers may also consume different random streams during training.
Args:
data_parallel_random_init: Historical parameter name. When True, serializes one RNG state
per DP/CP rank. This controls checkpoint layout independently of how ranks were seeded.
ckpt_format: The checkpoint format being used.
pg_collection: Process group collection for accessing parallel ranks/sizes.
module_name: Optional module name for MegatronMIMO per-module RNG namespacing.
When set, the ShardedObject key becomes ``"rng_state.{module_name}"``
to avoid duplicate shard keys across modules that share the same
(pp_rank, tp_rank) coordinates from module-local process groups.
Returns:
For torch_dist: A ShardedObject containing the RNG states, sharded by
(PP, TP, DP/CP), independently of expert parallelism.
For fsdp_dtensor: A dict mapping (pp_rank, tp_rank) to RNG state lists.
"""
rng_state = {
"random_rng_state": random.getstate(),
"np_rng_state": np.random.get_state(),
"torch_rng_state": torch.get_rng_state(),
"cuda_rng_state": torch.cuda.get_rng_state(),
"rng_tracker_states": tensor_parallel.get_cuda_rng_tracker().get_states(),
}
rng_state_list = None
if torch.distributed.is_initialized() and pg_collection.dp_cp.size() > 1 and data_parallel_random_init:
rng_state_list = [None for i in range(pg_collection.dp_cp.size())]
torch.distributed.all_gather_object(rng_state_list, rng_state, group=pg_collection.dp_cp)
else:
rng_state_list = [rng_state]
if ckpt_format == "torch_dist":
pp_rank = pg_collection.pp.rank()
pp_size = pg_collection.pp.size()
tp_rank = pg_collection.tp.rank()
tp_size = pg_collection.tp.size()
# MegatronMIMO per-module namespacing: use "rng_state.{module_name}" to avoid
# duplicate ShardedObject keys when different modules have the same
# (pp_rank, tp_rank) from their module-local process groups.
key = f"rng_state.{module_name}" if module_name else "rng_state"
rng_state_list = ShardedObject(
key,
rng_state_list,
(pp_size, tp_size, pg_collection.dp_cp.size()),
(pp_rank, tp_rank, pg_collection.dp_cp.rank()),
replica_id=0,
)
elif ckpt_format == "fsdp_dtensor":
pp_rank = pg_collection.pp.rank()
tp_rank = pg_collection.tp.rank()
rng_state_list = {f"({pp_rank}, {tp_rank})": rng_state_list}
return rng_state_list
def _checkpoint_has_per_dp_rng_states(run_config: dict[str, Any]) -> bool:
"""Return whether a checkpoint stores one RNG state per DP/CP rank."""
return run_config.get("checkpoint", {}).get("save_rng_state_per_dp_rank", False) or run_config.get("rng", {}).get(
"data_parallel_random_init", False
)
def _select_rng_state(
rng_state_list: list[dict[str, Any]], per_dp_rank: bool, pg_collection: ProcessGroupCollection
) -> dict[str, Any]:
"""Select the RNG state matching the saved checkpoint layout."""
return rng_state_list[pg_collection.dp_cp.rank() if per_dp_rank else 0]
def _align_rng_state_sharded_metadata(rng_state: ShardedObject, checkpoint_name: str) -> ShardedObject | None:
"""Align RNG load metadata with the layout stored in a torch-dist checkpoint.
Newer MCore checkpoints shard RNG state across PP, TP, and DP/CP, while
older checkpoints encode DP as a replica ID. Keep the generated metadata
when its exact key exists; otherwise adopt a unique stored layout whose
PP/TP prefix matches this rank. Return ``None`` for new DP/CP ranks or when
shrinking the DP/CP world. A smaller world cannot request every saved RNG
shard required by checkpoint access validation; keep fresh RNG in that case.
"""
checkpoint_path: str | Path
if MultiStorageClientFeature.is_enabled():
checkpoint_path = checkpoint_name
has_metadata = file_exists(join_paths(checkpoint_name, ".metadata"))
else:
checkpoint_path = Path(checkpoint_name)
has_metadata = (checkpoint_path / ".metadata").is_file()
if not has_metadata:
return rng_state
sharded_metadata = TorchDistLoadShardedStrategy().load_sharded_metadata(checkpoint_path)
return _match_rng_state_metadata(rng_state, sharded_metadata)
def _match_rng_state_metadata(
rng_state: ShardedObject, sharded_metadata: dict[str, ShardedObject]
) -> ShardedObject | None:
"""Match current or legacy RNG coordinates without substituting another data rank."""
if rng_state.unique_key in sharded_metadata:
return rng_state
dp_rank = rng_state.global_offset[2] if len(rng_state.global_offset) == 3 else rng_state.replica_id
candidates = [
metadata
for metadata in sharded_metadata.values()
if isinstance(metadata, ShardedObject)
and metadata.key == rng_state.key
and metadata.global_offset[:2] == rng_state.global_offset[:2]
and metadata.replica_id == 0
and len(metadata.global_offset) in (2, 3)
]
if len(rng_state.global_shape) == 3 and any(
len(metadata.global_shape) == 3 and metadata.global_shape[2] > rng_state.global_shape[2]
for metadata in candidates
):
return None
matches = [
metadata for metadata in candidates if len(metadata.global_offset) == 2 or metadata.global_offset[2] == dp_rank
]
if len(matches) != 1:
if candidates and all(
len(metadata.global_shape) == 3 and dp_rank >= metadata.global_shape[2] for metadata in candidates
):
return None
return rng_state
stored = matches[0]
return replace(
rng_state,
global_shape=stored.global_shape,
global_offset=stored.global_offset,
replica_id=dp_rank if len(stored.global_offset) == 2 else 0,
)
class CheckpointType(Enum):
"""Types of checkpoints to save."""
LOCAL = auto()
GLOBAL = auto()
FSDP_DTENSOR = auto()
@dataclass
class CheckpointSaveContext:
"""Context containing all state needed for a checkpoint save operation.
Attributes:
state: The GlobalState object containing config, train_state, etc.
model: List of model modules (MegatronModule instances).
optimizer: The optimizer instance (may be None for inference checkpoints).
opt_param_scheduler: The learning rate scheduler instance.
num_floating_point_operations_so_far: Cumulative FLOPs computed up to this point.
train_data_iterator: Optional training data iterator to save its state.
non_persistent_ckpt: If True, saves as a non-persistent (temporary) checkpoint.
"""
state: GlobalState
model: list[MegatronModule]
optimizer: MegatronOptimizer | None
opt_param_scheduler: Any | None
num_floating_point_operations_so_far: int
train_data_iterator: Any | None = None
non_persistent_ckpt: bool = False
pg_collection: ProcessGroupCollection | None = None
module_name: str | None = None
@dataclass
class CheckpointLoadContext:
"""Context containing all state needed for a checkpoint load operation.
Attributes:
state: The GlobalState object containing config, train_state, etc.
model: List of model modules to load state into.
optimizer: The optimizer instance to load state into.
opt_param_scheduler: The learning rate scheduler instance.
strict: Whether to enforce strict loading (see torch.nn.Module.load_state_dict).
skip_load_to_model_and_opt: If True, only loads metadata but skips loading
state into model and optimizer modules.
"""
state: GlobalState
model: list[MegatronModule]
optimizer: MegatronOptimizer | None
opt_param_scheduler: Any | None
strict: bool = True
skip_load_to_model_and_opt: bool = False
pg_collection: ProcessGroupCollection | None = None
module_name: str | None = None
@runtime_checkable
class CheckpointManager(Protocol):
"""Protocol defining the checkpoint manager interface.
Implement this protocol to create custom checkpoint save/load behavior.
The default implementation (DefaultCheckpointManager) delegates to the
existing functional checkpoint code.
"""
def __init__(self, checkpoint_config: CheckpointConfig) -> None:
"""Initialize the checkpoint manager.
Args:
checkpoint_config: The checkpoint configuration.
"""
...
def save(self, ctx: CheckpointSaveContext, callback_manager: Optional[CallbackManager]) -> None:
"""Save a checkpoint.
Args:
ctx: CheckpointSaveContext containing all state needed for save.
"""
...
def load(self, ctx: CheckpointLoadContext) -> tuple[int, int]:
"""Load a checkpoint.
Args:
ctx: CheckpointLoadContext containing all state needed for load.
Returns:
A tuple of (iteration, num_floating_point_operations_so_far).
Returns (0, 0) if no checkpoint was loaded.
"""
...
def finalize_async_saves(self, state: GlobalState, blocking: bool = False, terminate: bool = False) -> None:
"""Finalize any pending asynchronous checkpoint saves.
Args:
state: The GlobalState object (needed for async_calls_queue access).
blocking: If True, wait for all pending saves to complete.
terminate: If True, close the async queue after finalization.
"""
...
class DefaultCheckpointManager:
"""Default checkpoint manager that delegates to existing functional code.
This implementation wraps the default save_checkpoint and load_checkpoint
functions.
The manager owns the checkpointing_context dictionary, which is used to
cache strategies and local checkpoint managers across save/load operations.
Attributes:
checkpoint_config: The CheckpointConfig instance.
_context: Internal context dictionary for caching checkpoint strategies.
"""
def __init__(self, checkpoint_config: CheckpointConfig) -> None:
"""Initialize the checkpoint manager.
Args:
checkpoint_config: The checkpoint configuration.
"""
self.checkpoint_config = checkpoint_config
self._context: dict[str, Any] = init_checkpointing_context(checkpoint_config)
@property
def checkpointing_context(self) -> dict[str, Any]:
"""The internal checkpointing context dictionary.
This context is passed to save/load functions and caches:
- Save/load strategies for distributed checkpointing
- Local checkpoint manager (for non-persistent local checkpoints)
- Cached metadata for constant-structure optimization
"""
return self._context
def save(self, ctx: CheckpointSaveContext, callback_manager: Optional[CallbackManager]) -> None:
"""Save a checkpoint using the default implementation.
Delegates to save_checkpoint function.
Args:
ctx: CheckpointSaveContext containing all state needed for save.
"""
save_checkpoint(
state=ctx.state,
model=ctx.model,
optimizer=ctx.optimizer,
opt_param_scheduler=ctx.opt_param_scheduler,
num_floating_point_operations_so_far=ctx.num_floating_point_operations_so_far,
checkpointing_context=self._context,
non_persistent_ckpt=ctx.non_persistent_ckpt,
train_data_iterator=ctx.train_data_iterator,
pg_collection=ctx.pg_collection,
callback_manager=callback_manager,
module_name=ctx.module_name,
)
def load(self, ctx: CheckpointLoadContext) -> tuple[int, int]:
"""Load a checkpoint using the default implementation.
Delegates to load_checkpoint function.
Args:
ctx: CheckpointLoadContext containing all state needed for load.
Returns:
A tuple of (iteration, num_floating_point_operations_so_far).
"""
return load_checkpoint(
state=ctx.state,
model=ctx.model,
optimizer=ctx.optimizer,
opt_param_scheduler=ctx.opt_param_scheduler,
strict=ctx.strict,
checkpointing_context=self._context,
skip_load_to_model_and_opt=ctx.skip_load_to_model_and_opt,
pg_collection=ctx.pg_collection,
module_name=ctx.module_name,
)
def finalize_async_saves(self, state: GlobalState, blocking: bool = False, terminate: bool = False) -> None:
"""Finalize any pending asynchronous checkpoint saves.
Args:
state: The GlobalState object (needed for async_calls_queue access).
blocking: If True, wait for all pending saves to complete.
terminate: If True, close the async queue after finalization.
"""
maybe_finalize_async_save(
global_state=state,
ckpt_cfg=self.checkpoint_config,
blocking=blocking,
terminate=terminate,
)
def create_checkpoint_manager(checkpoint_config: CheckpointConfig) -> CheckpointManager:
"""Factory function to create a checkpoint manager.
Creates either the default checkpoint manager or a custom manager
based on the checkpoint_config.custom_manager_class setting.
Args:
checkpoint_config: The checkpoint configuration. If custom_manager_class is set,
it should be a fully qualified class name (e.g., "mypackage.module.MyManager").
Returns:
A CheckpointManager instance.
Raises:
ImportError: If the custom manager module cannot be imported.
AttributeError: If the custom manager class is not found in the module.
ValueError: If custom_manager_class format is invalid.
TypeError: If the custom manager does not implement the CheckpointManager protocol.
Example:
# Default manager
config = CheckpointConfig(save="/path/to/checkpoints")
manager = create_checkpoint_manager(config)
# Custom manager
config = CheckpointConfig(
save="/path/to/checkpoints",
custom_manager_class="mypackage.checkpoint.MyCheckpointManager",
)
manager = create_checkpoint_manager(config)
"""
if checkpoint_config.custom_manager_class is not None:
import importlib
try:
module_path, class_name = checkpoint_config.custom_manager_class.rsplit(".", 1)
except ValueError as err:
raise ValueError(
f"Invalid custom_manager_class format: '{checkpoint_config.custom_manager_class}'. "
f"Expected fully qualified class name like 'mypackage.module.ClassName'."
) from err
_validate_target_prefix(
target=checkpoint_config.custom_manager_class,
full_key="checkpoint.custom_manager_class",
)
try:
module = importlib.import_module(module_path)
except ImportError as e:
raise ImportError(f"Could not import module '{module_path}' for custom checkpoint manager: {e}") from e
try:
custom_manager_class = getattr(module, class_name)
except AttributeError as e:
raise AttributeError(f"Module '{module_path}' does not have class '{class_name}': {e}") from e
manager = custom_manager_class(checkpoint_config)
if not isinstance(manager, CheckpointManager):
raise TypeError(
f"Custom checkpoint manager '{checkpoint_config.custom_manager_class}' "
f"does not implement the CheckpointManager protocol."
)
try:
inspect.signature(manager.save).bind(None, None)
except (TypeError, ValueError) as err:
raise TypeError(
f"Custom checkpoint manager '{checkpoint_config.custom_manager_class}' save method "
"must accept (ctx, callback_manager)."
) from err
return manager
return DefaultCheckpointManager(checkpoint_config)
# ============================================================================
# HuggingFace sidecar export helpers (also_save_hf_checkpoint=True)
# ============================================================================
def _resolve_hf_source(cfg: ConfigContainer) -> Optional[str]:
"""Resolve the HuggingFace model identifier / local path used as a template.
Resolution order (first non-empty wins):
1. ``cfg.checkpoint.hf_source_path`` — explicit override.
2. ``cfg.model.hf_model_id`` — populated by ``AutoBridge.to_megatron_provider`` (preferred).
3. ``cfg.tokenizer.tokenizer_model`` — may be a tokenizer file path; only used as fallback when
the above are unset (recipes that point this at an HF model id still work).
Returns ``None`` when no source could be determined.
"""
if cfg is None:
return None
ckpt_cfg = getattr(cfg, "checkpoint", None)
if ckpt_cfg is not None and getattr(ckpt_cfg, "hf_source_path", None):
return ckpt_cfg.hf_source_path
model_cfg = getattr(cfg, "model", None)
if model_cfg is not None:
hf_id = getattr(model_cfg, "hf_model_id", None)
if hf_id:
return hf_id
tokenizer_cfg = getattr(cfg, "tokenizer", None)
if tokenizer_cfg is not None and getattr(tokenizer_cfg, "tokenizer_model", None):
return tokenizer_cfg.tokenizer_model
return None
_AUTO_BRIDGE_CACHE: dict[tuple, Any] = {}