From 2bec47662e2fd8537d28a266594e81e3fe4343a4 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Fri, 13 Nov 2026 13:10:40 +0000 Subject: [PATCH 1/6] Load universal checkpoints across ZeRO stages A universal checkpoint converted from ZeRO-3 could not be loaded into ZeRO-1/2, and one converted from ZeRO-1/2 could not be loaded into ZeRO-3: - the engine looked only for the model-states file named by its own stage; - the ZeRO-3 converter dropped ds_version, which the ZeRO-1/2 loader asserts on; - the ZeRO-1/2 loader expected dict-wrapped states, but the ZeRO-3 converter writes bare flat tensors; - the step was read from where the target's own stage keeps it. Fall back to the other stage's file name on universal loads, copy ds_version in the converter, accept flat tensors when they fill the whole parameter, and read the step and param_groups from either layout. Signed-off-by: Jin, Youzhi --- deepspeed/checkpoint/ds_to_universal.py | 4 ++ deepspeed/checkpoint/universal_checkpoint.py | 33 ++++++++- deepspeed/runtime/base_optimizer.py | 7 ++ deepspeed/runtime/engine.py | 15 +++- deepspeed/runtime/zero/stage3.py | 11 ++- .../checkpoint/test_universal_checkpoint.py | 68 +++++++++++++++++++ 6 files changed, 132 insertions(+), 6 deletions(-) diff --git a/deepspeed/checkpoint/ds_to_universal.py b/deepspeed/checkpoint/ds_to_universal.py index d555509495e3..2017a119d156 100755 --- a/deepspeed/checkpoint/ds_to_universal.py +++ b/deepspeed/checkpoint/ds_to_universal.py @@ -20,6 +20,7 @@ from deepspeed.checkpoint import DeepSpeedCheckpoint from deepspeed.checkpoint import ( + DS_VERSION, OPTIMIZER_STATE_DICT, ZERO_STAGE, BASE_OPTIMIZER_STATE, @@ -1001,6 +1002,9 @@ def _save_optimizer_state_stage3(args, optim_files): sd = torch.load(optim_files[0], map_location=torch.device('cpu'), weights_only=False) output_sd = sd[OPTIMIZER_STATE_DICT] output_sd[PARAM_GROUPS] = output_sd[OPTIMIZER_STATE_DICT][PARAM_GROUPS] + # ZeRO-3 keeps the version beside its optimizer state rather than in it; ZeRO-1/2 targets require it. + if sd.get(DS_VERSION): + output_sd[DS_VERSION] = sd[DS_VERSION] zero_output_folder = os.path.join(args.output_folder, "zero") output_file_path = os.path.join(zero_output_folder, "optimizer_state.pt") _save_checkpoint(output_file_path, output_sd) diff --git a/deepspeed/checkpoint/universal_checkpoint.py b/deepspeed/checkpoint/universal_checkpoint.py index fb4d1157d6cc..d56df239fec2 100644 --- a/deepspeed/checkpoint/universal_checkpoint.py +++ b/deepspeed/checkpoint/universal_checkpoint.py @@ -14,7 +14,7 @@ EP_IS_EXPERT_PARAM, EP_NUM_EXPERTS, DS_AUTOEP_UC_META, DS_AUTOTP_UC_META, AUTOEP_EXPERT_PLACEMENT, AUTOEP_PARAM_EP_RANK, AUTOEP_PARAM_LOCAL_EXPERTS, AUTOEP_PARAM_LOGICAL_SHAPE, AUTOEP_PLACEMENT_EXPERTS, AUTOEP_PLACEMENT_RANK, - AUTOEP_PLACEMENT_RANKS, UNIVERSAL_CHECKPOINT_VERSION_KEY) + AUTOEP_PLACEMENT_RANKS, UNIVERSAL_CHECKPOINT_VERSION_KEY, OPTIMIZER_STATE_DICT) from .autoep_affine import autoep_metadata_to_affine_map, extract_autoep_rank_tensor @@ -233,6 +233,35 @@ def _resolve_autotp_partition(current_param, ckpt_dict, full_hp_param, tp_rank, return slice_tensor.flatten() +def _shape_flat_universal_state(param, tensor, ckpt_file): + """Give a state that ds_to_universal wrote as a bare flat tensor (a ZeRO-3 source) the parameter's shape. + + Such a file records no tensor-parallel layout, so it can only fill a parameter that holds the whole tensor. + """ + if tensor.numel() != param.numel(): + raise ValueError(f"{ckpt_file} holds a flat tensor of {tensor.numel()} elements with no tensor-parallel " + f"layout, but the parameter loading it has shape {tuple(param.shape)}. A universal " + "checkpoint converted from ZeRO-3 can be loaded into ZeRO-1/2 only without tensor " + "parallelism.") + return tensor.view(param.shape) + + +def load_universal_optimizer_step(optim_sd, checkpoint_dir, param_names): + """The optimizer step a universal checkpoint was saved at, whichever ZeRO stage it came from. + + A ZeRO-3 source keeps it in the global optimizer state; a ZeRO-1/2 source writes a step.pt next to + each parameter's states. + """ + state = optim_sd.get(OPTIMIZER_STATE_DICT, {}).get('state') + if state: + return next(iter(state.values())).get('step') + for name in param_names: + path = os.path.join(checkpoint_dir, name, 'step.pt') + if os.path.isfile(path): + return torch.load(path, weights_only=False) + return None + + def load_hp_checkpoint_state(self, folder, tp_rank, tp_world_size, ep_rank=0, ep_size=1, load_optimizer_states=True): hp_mapping = self._hp_mapping if load_optimizer_states: @@ -265,6 +294,8 @@ def load_hp_checkpoint_state(self, folder, tp_rank, tp_world_size, ep_rank=0, ep step = ckpt_dict continue + if torch.is_tensor(ckpt_dict): + ckpt_dict = {PARAM: _shape_flat_universal_state(self, ckpt_dict, ckpt_file)} full_hp_param = ckpt_dict[PARAM] # EP-aware slicing for expert parameters saved in universal format. diff --git a/deepspeed/runtime/base_optimizer.py b/deepspeed/runtime/base_optimizer.py index a825f07e7cff..06a98ee28abb 100644 --- a/deepspeed/runtime/base_optimizer.py +++ b/deepspeed/runtime/base_optimizer.py @@ -378,6 +378,7 @@ def load_hp_checkpoint_state_from_checkpoint_dir(self, optim_state_path), f'{optim_state_path} containing optimizer global state is missing! Cannot proceed.' optim_sd = torch.load(optim_state_path, weights_only=False) self._load_global_state(optim_sd) + global_step = None for i, (param_group, loaded_param_group) in enumerate(zip(self.optimizer.param_groups, optim_sd['param_groups'])): @@ -397,6 +398,12 @@ def load_hp_checkpoint_state_from_checkpoint_dir(self, hp_param = param_group['params'][0] assert all(step == steps[0] for step in steps), f"Steps {steps} are not equal" + if steps[0] is None: + # A ZeRO-3 source writes no per-parameter step.pt; its step is in the global state. + if global_step is None: + from deepspeed.checkpoint.universal_checkpoint import load_universal_optimizer_step + global_step = load_universal_optimizer_step(optim_sd, checkpoint_dir, []) + steps[0] = global_step if steps[0] is not None: self.optimizer.state[hp_param]['step'] = steps[0] diff --git a/deepspeed/runtime/engine.py b/deepspeed/runtime/engine.py index 54a645ac77bf..54b118d55a69 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -4415,13 +4415,15 @@ def _get_zero_ckpt_name(self, checkpoints_path, tag): bf16_mode = self.bfloat16_enabled() return self._get_rank_zero_ckpt_name(checkpoints_path, tag, self.checkpoint_mp_rank, pp_rank, bf16_mode) - def _get_ckpt_name(self, checkpoints_path, tag, mp_placeholder=None, pp_placeholder=None): + def _get_ckpt_name(self, checkpoints_path, tag, mp_placeholder=None, pp_placeholder=None, partition_weights=None): if mp_placeholder is not None: mp_rank_str = mp_placeholder else: mp_rank_str = f"{self.checkpoint_mp_rank:02d}" - if self.zero_optimization_partition_weights(): + if partition_weights is None: + partition_weights = self.zero_optimization_partition_weights() + if partition_weights: if pp_placeholder is not None: pp_rank = pp_placeholder else: @@ -4471,6 +4473,15 @@ def _get_all_ckpt_names(self, checkpoints_path, tag): import glob ckpt_files = glob.glob(ckpt_file_pattern) + if not ckpt_files and self.load_universal_checkpoint(): + # The source's ZeRO stage named these files, and it may differ from ours. A universal load reads + # only metadata from them, so the other stage's naming serves as well. + other_pattern = self._get_ckpt_name(checkpoints_path, + tag, + mp_placeholder="*", + pp_placeholder="0", + partition_weights=not self.zero_optimization_partition_weights()) + ckpt_files = glob.glob(other_pattern) ckpt_files.sort() return ckpt_files diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index 779f505e5702..e80f0ff8f95d 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -44,6 +44,7 @@ EP_IS_EXPERT_PARAM, EP_NUM_EXPERTS, OPTIMIZER_STATE_DICT, + PARAM_GROUPS, FP32_FLAT_GROUPS, PARAM, PARTITION_COUNT, @@ -3747,7 +3748,8 @@ def load_hp_checkpoint_state_from_checkpoint_dir_stage3(self, checkpoint_dir): self._load_global_state_stage3(optim_sd) # Generally the step of each optimizer file should be the same, we can obtain from any parameter. - state_step = optim_sd[OPTIMIZER_STATE_DICT]['state'][0]['step'] + from deepspeed.checkpoint.universal_checkpoint import load_universal_optimizer_step + state_step = load_universal_optimizer_step(optim_sd, checkpoint_dir, self.param_names.values()) for key in ["fp32", "exp_avg", "exp_avg_sq"]: for sub_group_id, fp16_group in enumerate(self.fp16_groups): fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] @@ -3764,13 +3766,16 @@ def load_hp_checkpoint_state_from_checkpoint_dir_stage3(self, checkpoint_dir): offset += key_layer_state_partition.numel() if key == "fp32": self.fp32_partitioned_groups_flat[sub_group_id].data.copy_(key_tensor) - self.optimizer.state[fp32_param]['step'] = state_step + if state_step is not None: + self.optimizer.state[fp32_param]['step'] = state_step else: self.optimizer.state[fp32_param][key] = key_tensor for param_group in self.optimizer.param_groups: # Generally, the hyperparameters of each parameter should be the same, we can obtain from any parameter. - for key, value in optim_sd[OPTIMIZER_STATE_DICT]["param_groups"][0].items(): + # A ZeRO-1/2 source has no OPTIMIZER_STATE_DICT, only the top-level PARAM_GROUPS. + param_groups = optim_sd.get(PARAM_GROUPS) or optim_sd[OPTIMIZER_STATE_DICT][PARAM_GROUPS] + for key, value in param_groups[0].items(): if key == 'params': param_group['params'] = [] else: diff --git a/tests/unit/checkpoint/test_universal_checkpoint.py b/tests/unit/checkpoint/test_universal_checkpoint.py index 250349170504..03e1dae5b42d 100644 --- a/tests/unit/checkpoint/test_universal_checkpoint.py +++ b/tests/unit/checkpoint/test_universal_checkpoint.py @@ -15,6 +15,7 @@ from deepspeed.checkpoint import UNIVERSAL_CHECKPOINT_INFO from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT from deepspeed.checkpoint.ds_to_universal import main as convert_to_universal +from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_optimizer_state from unit.common import DistributedTest, DistributedFixture from unit.simple_model import * @@ -355,3 +356,70 @@ def test_resume(self, tmpdir, zero_stage, int_step): for state in optimizer_states: assert state["step"].item() == steps_before_save + steps_after_load engine.destroy() + + +def _full_optimizer_states(engine): + """Every parameter's whole fp32 master and Adam moments, gathered across the ZeRO partition.""" + states = {} + for name, param in engine.module.named_parameters(): + states[name] = [ + safe_get_full_fp32_param(param).cpu(), + safe_get_full_optimizer_state(param, "exp_avg").cpu(), + safe_get_full_optimizer_state(param, "exp_avg_sq").cpu(), + ] + return states + + +@pytest.mark.parametrize("source_stage,target_stage", [(1, 3), (2, 3), (3, 1), (3, 2)]) +class TestUniversalCheckpointAcrossZeROStages(DistributedTest): + world_size = 2 + + def test_load(self, tmpdir, source_stage, target_stage): + hidden_dim = 10 + steps_before_save = 2 + + def build(stage, load_universal): + ds_config = {"train_batch_size": 2, "zero_optimization": {"stage": stage}} + if load_universal: + ds_config["checkpoint"] = {"load_universal": True} + model = SimpleModel(hidden_dim, nlayers=2) + engine, _, _, _ = deepspeed.initialize(config=ds_config, + model=model, + optimizer=torch.optim.Adam(model.parameters(), lr=0.1)) + return engine + + source = build(source_stage, load_universal=False) + _train(source, hidden_dim, steps_before_save) + expected = _full_optimizer_states(source) + source.save_checkpoint(tmpdir, tag=CP_TAG, client_state={UNIVERSAL_CHECKPOINT_INFO: {}}) + source.destroy() + + cp_dir = os.path.join(tmpdir, CP_TAG) + dist.barrier() + if dist.get_rank() == 0: + convert_to_universal( + SimpleNamespace(input_folder=cp_dir, + output_folder=f"{cp_dir}_universal", + num_extract_workers=1, + num_merge_workers=1, + keep_temp_folder=False, + strict=True, + inject_missing_state=False)) + dist.barrier() + + target = build(target_stage, load_universal=True) + target.load_checkpoint(tmpdir, tag=f"{CP_TAG}_universal") + + loaded = _full_optimizer_states(target) + assert loaded.keys() == expected.keys() + for name, states in expected.items(): + for expected_state, loaded_state in zip(states, loaded[name]): + assert torch.equal(expected_state, loaded_state), name + optimizer_states = list(target.optimizer.optimizer.state.values()) + assert optimizer_states + for state in optimizer_states: + assert int(state["step"]) == steps_before_save + + # The restored optimizer must also be able to keep training. + _train(target, hidden_dim, 1) + target.destroy() From ce758abf82e584385bd569492af02667c74122d9 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Wed, 18 Nov 2026 14:24:13 +0000 Subject: [PATCH 2/6] Restore each optimizer group and give each state its own step The ZeRO-3 universal loader applied the first saved parameter group to every optimizer group; it now restores each group from the saved group with the same index and raises if the counts differ. Both universal loaders gave every group or sub-group the same step tensor, which the optimizer advances in place once per group; each state now gets its own copy. The cross-stage test uses two parameter groups with different settings and a sub_group_size that splits ZeRO-3's groups, checks the restored settings, and checks that one step after the load advances every state's step once. Signed-off-by: Jin, Youzhi --- deepspeed/runtime/base_optimizer.py | 3 ++- deepspeed/runtime/zero/stage3.py | 17 +++++++----- .../checkpoint/test_universal_checkpoint.py | 26 ++++++++++++++++--- 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/deepspeed/runtime/base_optimizer.py b/deepspeed/runtime/base_optimizer.py index 06a98ee28abb..668bd57896a5 100644 --- a/deepspeed/runtime/base_optimizer.py +++ b/deepspeed/runtime/base_optimizer.py @@ -405,7 +405,8 @@ def load_hp_checkpoint_state_from_checkpoint_dir(self, global_step = load_universal_optimizer_step(optim_sd, checkpoint_dir, []) steps[0] = global_step if steps[0] is not None: - self.optimizer.state[hp_param]['step'] = steps[0] + # The optimizer advances step in place, and a ZeRO-3 source's step is shared by every group. + self.optimizer.state[hp_param]['step'] = steps[0].clone() if torch.is_tensor(steps[0]) else steps[0] map_to_flat_opt_states(hp_param, lp_groups[i], self.optimizer.state, opt_keys) diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index e80f0ff8f95d..03a102e6a212 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -3767,15 +3767,20 @@ def load_hp_checkpoint_state_from_checkpoint_dir_stage3(self, checkpoint_dir): if key == "fp32": self.fp32_partitioned_groups_flat[sub_group_id].data.copy_(key_tensor) if state_step is not None: - self.optimizer.state[fp32_param]['step'] = state_step + # Each sub-group's optimizer advances its step in place, so give it its own copy. + self.optimizer.state[fp32_param]['step'] = (state_step.clone() + if torch.is_tensor(state_step) else state_step) else: self.optimizer.state[fp32_param][key] = key_tensor - for param_group in self.optimizer.param_groups: - # Generally, the hyperparameters of each parameter should be the same, we can obtain from any parameter. - # A ZeRO-1/2 source has no OPTIMIZER_STATE_DICT, only the top-level PARAM_GROUPS. - param_groups = optim_sd.get(PARAM_GROUPS) or optim_sd[OPTIMIZER_STATE_DICT][PARAM_GROUPS] - for key, value in param_groups[0].items(): + # A ZeRO-1/2 source has no OPTIMIZER_STATE_DICT, only the top-level PARAM_GROUPS. Both list the + # optimizer's own parameter groups in order, as self.optimizer.param_groups does. + saved_param_groups = optim_sd.get(PARAM_GROUPS) or optim_sd[OPTIMIZER_STATE_DICT][PARAM_GROUPS] + if len(saved_param_groups) != len(self.optimizer.param_groups): + raise ValueError(f"The universal checkpoint in {checkpoint_dir} has {len(saved_param_groups)} optimizer " + f"parameter groups, but this optimizer has {len(self.optimizer.param_groups)}.") + for param_group, saved_param_group in zip(self.optimizer.param_groups, saved_param_groups): + for key, value in saved_param_group.items(): if key == 'params': param_group['params'] = [] else: diff --git a/tests/unit/checkpoint/test_universal_checkpoint.py b/tests/unit/checkpoint/test_universal_checkpoint.py index 03e1dae5b42d..c4f2d44d08ab 100644 --- a/tests/unit/checkpoint/test_universal_checkpoint.py +++ b/tests/unit/checkpoint/test_universal_checkpoint.py @@ -378,18 +378,33 @@ def test_load(self, tmpdir, source_stage, target_stage): hidden_dim = 10 steps_before_save = 2 + group_lrs = [0.1, 0.05] + def build(stage, load_universal): - ds_config = {"train_batch_size": 2, "zero_optimization": {"stage": stage}} + # A small sub_group_size splits ZeRO-3's groups into several sub-groups. + ds_config = {"train_batch_size": 2, "zero_optimization": {"stage": stage, "sub_group_size": 100}} if load_universal: ds_config["checkpoint"] = {"load_universal": True} model = SimpleModel(hidden_dim, nlayers=2) + # Two groups with their own settings. The target starts from other settings, so the check below + # sees what the load restored. + param_groups = [{ + "params": list(layer.parameters()), + "lr": 1.0 if load_universal else lr, + "weight_decay": 0.0 if load_universal else 0.01 * i + } for i, (layer, lr) in enumerate(zip(model.linears, group_lrs))] engine, _, _, _ = deepspeed.initialize(config=ds_config, model=model, - optimizer=torch.optim.Adam(model.parameters(), lr=0.1)) + optimizer=torch.optim.Adam(param_groups)) return engine source = build(source_stage, load_universal=False) _train(source, hidden_dim, steps_before_save) + if source_stage < 3: + # ZeRO-1/2 links optimizer state after the first group's step only, so later groups' moments are not + # visible to safe_get_full_optimizer_state until #8956. Link them again now that all groups have state. + source.optimizer._hp_optimizer_states_linked = False + source.optimizer._lazy_init_hp_params_optimizer_state() expected = _full_optimizer_states(source) source.save_checkpoint(tmpdir, tag=CP_TAG, client_state={UNIVERSAL_CHECKPOINT_INFO: {}}) source.destroy() @@ -420,6 +435,11 @@ def build(stage, load_universal): for state in optimizer_states: assert int(state["step"]) == steps_before_save - # The restored optimizer must also be able to keep training. + for i, (param_group, lr) in enumerate(zip(target.optimizer.param_groups, group_lrs)): + assert param_group["lr"] == lr and param_group["weight_decay"] == 0.01 * i, param_group + + # The restored optimizer must also be able to keep training, advancing every state's step once. _train(target, hidden_dim, 1) + for state in target.optimizer.optimizer.state.values(): + assert int(state["step"]) == steps_before_save + 1 target.destroy() From ce1a8064b452ac3753b0f972d53b83d52c2697e1 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 19 Nov 2026 18:49:08 +0000 Subject: [PATCH 3/6] Test a TP2 x PP2 ZeRO-1 run resumed as ZeRO-3 The pipeline engine runs at most ZeRO-1, so a pipeline-parallel run reaches ZeRO-3 only through a universal checkpoint loaded across stages. The new test trains Megatron-style column- and row-parallel layers with TP=2 and PP=2 under ZeRO-1, converts the checkpoint, and loads it as ZeRO-3 over 4 data-parallel ranks. It checks that every weight and Adam moment matches the source's reassembled tensors bit for bit, that the settings and step are restored, and that the target keeps training. On master the load fails to find the model states file. Signed-off-by: Jin, Youzhi --- .../checkpoint/test_universal_checkpoint.py | 195 +++++++++++++++++- 1 file changed, 193 insertions(+), 2 deletions(-) diff --git a/tests/unit/checkpoint/test_universal_checkpoint.py b/tests/unit/checkpoint/test_universal_checkpoint.py index c4f2d44d08ab..9ddbb714c86f 100644 --- a/tests/unit/checkpoint/test_universal_checkpoint.py +++ b/tests/unit/checkpoint/test_universal_checkpoint.py @@ -4,6 +4,7 @@ # DeepSpeed Team import os +import re import glob import math @@ -13,9 +14,12 @@ from deepspeed.utils.torch import required_torch_version from deepspeed.checkpoint import UNIVERSAL_CHECKPOINT_INFO -from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT +from deepspeed.checkpoint.constants import (OPTIMIZER_STATE_DICT, PARAMETER_WITH_ROW_PARALLELISM_PATTERNS, + TP_REPLICATED_PARAMETER_PATTERNS) +from deepspeed.pipe import PipelineModule +from deepspeed.runtime.pipe.topology import PipeModelDataParallelTopology from deepspeed.checkpoint.ds_to_universal import main as convert_to_universal -from deepspeed.utils import safe_get_full_fp32_param, safe_get_full_optimizer_state +from deepspeed.utils import groups, safe_get_full_fp32_param, safe_get_full_optimizer_state from unit.common import DistributedTest, DistributedFixture from unit.simple_model import * @@ -358,6 +362,193 @@ def test_resume(self, tmpdir, zero_stage, int_step): engine.destroy() +class _CopyToTensorParallel(torch.autograd.Function): + + @staticmethod + def forward(ctx, x, group): + ctx.group = group + return x + + @staticmethod + def backward(ctx, grad): + grad = grad.clone() + dist.all_reduce(grad, group=ctx.group) + return grad, None + + +class _ReduceFromTensorParallel(torch.autograd.Function): + + @staticmethod + def forward(ctx, x, group): + x = x.clone() + dist.all_reduce(x, group=group) + return x + + @staticmethod + def backward(ctx, grad): + return grad, None + + +class _ColumnParallelLinear(torch.nn.Module): + """Megatron's column-parallel linear: this rank keeps a block of output rows of weight and bias.""" + + def __init__(self, full, tp_rank, tp_size): + super().__init__() + self.weight = torch.nn.Parameter(full.weight.detach().chunk(tp_size, dim=0)[tp_rank].clone()) + self.bias = torch.nn.Parameter(full.bias.detach().chunk(tp_size, dim=0)[tp_rank].clone()) + self.group = None + + def forward(self, x): + return torch.nn.functional.gelu( + torch.nn.functional.linear(_CopyToTensorParallel.apply(x, self.group), self.weight, self.bias)) + + +class _RowParallelLinear(torch.nn.Module): + """Megatron's row-parallel linear: a block of weight columns, the bias replicated and added after the sum.""" + + def __init__(self, full, tp_rank, tp_size): + super().__init__() + self.weight = torch.nn.Parameter(full.weight.detach().chunk(tp_size, dim=1)[tp_rank].clone()) + self.bias = torch.nn.Parameter(full.bias.detach().clone()) + self.group = None + + def forward(self, x): + return _ReduceFromTensorParallel.apply(torch.nn.functional.linear(x, self.weight), self.group) + self.bias + + +class _DenseStack(torch.nn.Module): + """The same layers unsharded, named as PipelineModule names them, for the ZeRO-3 target.""" + + def __init__(self, layers): + super().__init__() + for i, layer in enumerate(layers): + self.add_module(str(i), layer) + + def forward(self, x, y): + for i, layer in enumerate(self.children()): + x = layer(x) + if i % 2 == 0: + x = torch.nn.functional.gelu(x) + return torch.nn.functional.mse_loss(x, y) + + +class TestUniversalCheckpointPipelineToZeRO3(DistributedTest): + """A TP2 x PP2 run under ZeRO-1, the most a pipeline engine allows, resumed as ZeRO-3 over 4 data-parallel ranks.""" + world_size = 4 + + def test_load(self, tmpdir): + hidden, tp, steps_before_save = 8, 2, 2 + dims = [(hidden, 2 * hidden), (2 * hidden, hidden)] * 2 + + def full_layers(): + torch.manual_seed(0) + return [torch.nn.Linear(i, o) for i, o in dims] + + generator = torch.Generator().manual_seed(1) + batches = [(torch.randn(1, hidden, generator=generator), torch.randn(1, hidden, generator=generator)) + for _ in range(2 * (steps_before_save + 1))] + + topology = PipeModelDataParallelTopology(num_pp=2, num_mp=tp, num_dp=1) + tp_rank = topology.get_coord(dist.get_rank()).model + layers = [(_ColumnParallelLinear if i % 2 == 0 else _RowParallelLinear)(full, tp_rank, tp) + for i, full in enumerate(full_layers())] + model = PipelineModule(layers=layers, + topology=topology, + loss_fn=torch.nn.MSELoss(), + partition_method="uniform") + for layer in layers: + layer.group = model._grid.get_slice_parallel_group() + config = { + "train_micro_batch_size_per_gpu": 1, + "gradient_accumulation_steps": 2, + "zero_optimization": { + "stage": 1 + }, + "pipeline": { + "activation_checkpoint_interval": 0 + }, + } + source, _, _, _ = deepspeed.initialize(config=config, + model=model, + optimizer=torch.optim.Adam(model.parameters(), lr=0.01)) + device = source.device + loader = iter([(x.to(device), y.to(device)) for x, y in batches]) + for _ in range(steps_before_save): + source.train_batch(data_iter=loader) + + # Each rank holds one TP block of its stage's parameters; put the whole tensors together. + local = {name: [s.cpu() for s in states] for name, states in _full_optimizer_states(source).items()} + everyone = [None] * self.world_size + dist.all_gather_object(everyone, (tp_rank, local)) + blocks = {} + for rank_tp, rank_states in everyone: + for name, states in rank_states.items(): + blocks.setdefault(name, {})[rank_tp] = states + row_weight, row_bias = r"^[13]\.weight$", r"^[13]\.bias$" + expected = {} + for name, by_tp in blocks.items(): + per_state = list(zip(*(by_tp[r] for r in range(tp)))) + if re.match(row_bias, name): + assert all(torch.equal(s[0], s[1]) for s in per_state), name + expected[name] = [s[0] for s in per_state] + else: + expected[name] = [torch.cat(s, dim=1 if re.match(row_weight, name) else 0) for s in per_state] + assert len(expected) == 2 * len(dims) + + uc_info = { + PARAMETER_WITH_ROW_PARALLELISM_PATTERNS: [row_weight], + TP_REPLICATED_PARAMETER_PATTERNS: [row_bias], + } + source.save_checkpoint(tmpdir, tag=CP_TAG, client_state={UNIVERSAL_CHECKPOINT_INFO: uc_info}) + source.destroy() + # A real resume starts new processes; here the pipeline grid would stay registered as the global mpu. + groups.mpu = None + + cp_dir = os.path.join(tmpdir, CP_TAG) + dist.barrier() + if dist.get_rank() == 0: + convert_to_universal( + SimpleNamespace(input_folder=cp_dir, + output_folder=f"{cp_dir}_universal", + num_extract_workers=1, + num_merge_workers=1, + keep_temp_folder=False, + strict=True, + inject_missing_state=False)) + dist.barrier() + + dense = _DenseStack(full_layers()) + target, _, _, _ = deepspeed.initialize(config={ + "train_batch_size": self.world_size, + "zero_optimization": { + "stage": 3 + }, + "checkpoint": { + "load_universal": True + }, + }, + model=dense, + optimizer=torch.optim.Adam(dense.parameters(), lr=1.0)) + target.load_checkpoint(tmpdir, tag=f"{CP_TAG}_universal") + + loaded = _full_optimizer_states(target) + assert loaded.keys() == expected.keys() + for name, states in expected.items(): + for expected_state, loaded_state in zip(states, loaded[name]): + assert torch.equal(expected_state, loaded_state), name + assert target.optimizer.param_groups[0]["lr"] == 0.01 + for state in target.optimizer.optimizer.state.values(): + assert int(state["step"]) == steps_before_save + + x, y = batches[0] + loss = target(x.to(target.device), y.to(target.device)) + target.backward(loss) + target.step() + for state in target.optimizer.optimizer.state.values(): + assert int(state["step"]) == steps_before_save + 1 + target.destroy() + + def _full_optimizer_states(engine): """Every parameter's whole fp32 master and Adam moments, gathered across the ZeRO partition.""" states = {} From 06d874bf9681e79cbad35411e5c75ddd8dd162c3 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Thu, 19 Nov 2026 20:29:08 +0000 Subject: [PATCH 4/6] Compare the resumed ZeRO-3 run with the pipeline run that never stopped After the save, the TP2 x PP2 source keeps training for 3 steps. The ZeRO-3 target follows on the same micro-batches, each data-parallel rank taking one of the source's pair, and must match the source's loss, weights and both Adam moments after every step within fp32 tolerance. Rank 0 now shares the outcome of the conversion, so a converter failure fails every rank instead of leaving the others waiting at a barrier. Signed-off-by: Jin, Youzhi --- .../checkpoint/test_universal_checkpoint.py | 104 ++++++++++++------ 1 file changed, 69 insertions(+), 35 deletions(-) diff --git a/tests/unit/checkpoint/test_universal_checkpoint.py b/tests/unit/checkpoint/test_universal_checkpoint.py index 9ddbb714c86f..27aecfa299b2 100644 --- a/tests/unit/checkpoint/test_universal_checkpoint.py +++ b/tests/unit/checkpoint/test_universal_checkpoint.py @@ -7,6 +7,7 @@ import re import glob import math +import traceback import deepspeed from types import SimpleNamespace @@ -437,16 +438,18 @@ class TestUniversalCheckpointPipelineToZeRO3(DistributedTest): world_size = 4 def test_load(self, tmpdir): - hidden, tp, steps_before_save = 8, 2, 2 + hidden, tp, steps_before_save, steps_after_load = 8, 2, 2, 3 dims = [(hidden, 2 * hidden), (2 * hidden, hidden)] * 2 + row_weight, row_bias = r"^[13]\.weight$", r"^[13]\.bias$" def full_layers(): torch.manual_seed(0) return [torch.nn.Linear(i, o) for i, o in dims] + # Two micro-batches per step: the source accumulates both, the target's 4 ranks see each twice. generator = torch.Generator().manual_seed(1) batches = [(torch.randn(1, hidden, generator=generator), torch.randn(1, hidden, generator=generator)) - for _ in range(2 * (steps_before_save + 1))] + for _ in range(2 * (steps_before_save + steps_after_load))] topology = PipeModelDataParallelTopology(num_pp=2, num_mp=tp, num_dp=1) tp_rank = topology.get_coord(dist.get_rank()).model @@ -461,6 +464,7 @@ def full_layers(): config = { "train_micro_batch_size_per_gpu": 1, "gradient_accumulation_steps": 2, + "gradient_clipping": 0.0, "zero_optimization": { "stage": 1 }, @@ -476,50 +480,65 @@ def full_layers(): for _ in range(steps_before_save): source.train_batch(data_iter=loader) - # Each rank holds one TP block of its stage's parameters; put the whole tensors together. - local = {name: [s.cpu() for s in states] for name, states in _full_optimizer_states(source).items()} - everyone = [None] * self.world_size - dist.all_gather_object(everyone, (tp_rank, local)) - blocks = {} - for rank_tp, rank_states in everyone: - for name, states in rank_states.items(): - blocks.setdefault(name, {})[rank_tp] = states - row_weight, row_bias = r"^[13]\.weight$", r"^[13]\.bias$" - expected = {} - for name, by_tp in blocks.items(): - per_state = list(zip(*(by_tp[r] for r in range(tp)))) - if re.match(row_bias, name): - assert all(torch.equal(s[0], s[1]) for s in per_state), name - expected[name] = [s[0] for s in per_state] - else: - expected[name] = [torch.cat(s, dim=1 if re.match(row_weight, name) else 0) for s in per_state] - assert len(expected) == 2 * len(dims) - + def whole_source_states(): + # Each rank holds one TP block of its stage's parameters; put the whole tensors together. + local = {name: [s.cpu() for s in states] for name, states in _full_optimizer_states(source).items()} + everyone = [None] * self.world_size + dist.all_gather_object(everyone, (tp_rank, local)) + blocks = {} + for rank_tp, rank_states in everyone: + for name, states in rank_states.items(): + blocks.setdefault(name, {})[rank_tp] = states + whole = {} + for name, by_tp in blocks.items(): + per_state = list(zip(*(by_tp[r] for r in range(tp)))) + if re.match(row_bias, name): + assert all(torch.equal(s[0], s[1]) for s in per_state), name + whole[name] = [s[0] for s in per_state] + else: + whole[name] = [torch.cat(s, dim=1 if re.match(row_weight, name) else 0) for s in per_state] + assert len(whole) == 2 * len(dims) + return whole + + expected = whole_source_states() uc_info = { PARAMETER_WITH_ROW_PARALLELISM_PATTERNS: [row_weight], TP_REPLICATED_PARAMETER_PATTERNS: [row_bias], } source.save_checkpoint(tmpdir, tag=CP_TAG, client_state={UNIVERSAL_CHECKPOINT_INFO: uc_info}) + + # The run that never stopped, for the target to follow after the load. + uninterrupted = [] + for _ in range(steps_after_load): + loss = source.train_batch(data_iter=loader) + uninterrupted.append((loss.item(), whole_source_states())) source.destroy() # A real resume starts new processes; here the pipeline grid would stay registered as the global mpu. groups.mpu = None cp_dir = os.path.join(tmpdir, CP_TAG) dist.barrier() + # Rank 0 converts alone; share its outcome so a failure fails every rank instead of leaving them waiting. + error = [None] if dist.get_rank() == 0: - convert_to_universal( - SimpleNamespace(input_folder=cp_dir, - output_folder=f"{cp_dir}_universal", - num_extract_workers=1, - num_merge_workers=1, - keep_temp_folder=False, - strict=True, - inject_missing_state=False)) - dist.barrier() + try: + convert_to_universal( + SimpleNamespace(input_folder=cp_dir, + output_folder=f"{cp_dir}_universal", + num_extract_workers=1, + num_merge_workers=1, + keep_temp_folder=False, + strict=True, + inject_missing_state=False)) + except Exception: + error = [traceback.format_exc()] + dist.broadcast_object_list(error, src=0) + assert error[0] is None, f"ds_to_universal failed on rank 0:\n{error[0]}" dense = _DenseStack(full_layers()) target, _, _, _ = deepspeed.initialize(config={ "train_batch_size": self.world_size, + "gradient_clipping": 0.0, "zero_optimization": { "stage": 3 }, @@ -534,18 +553,33 @@ def full_layers(): loaded = _full_optimizer_states(target) assert loaded.keys() == expected.keys() for name, states in expected.items(): + assert len(loaded[name]) == len(states) == 3, name for expected_state, loaded_state in zip(states, loaded[name]): assert torch.equal(expected_state, loaded_state), name assert target.optimizer.param_groups[0]["lr"] == 0.01 for state in target.optimizer.optimizer.state.values(): assert int(state["step"]) == steps_before_save - x, y = batches[0] - loss = target(x.to(target.device), y.to(target.device)) - target.backward(loss) - target.step() + # Rank r takes micro-batch r % 2 of the source's pair, so the data-parallel mean of the gradients is the + # source's accumulated gradient. The TP all-reduces sum in another order, so the match is close, not exact. + for step, (source_loss, source_states) in enumerate(uninterrupted): + x, y = batches[2 * (steps_before_save + step) + dist.get_rank() % 2] + loss = target(x.to(target.device), y.to(target.device)) + target.backward(loss) + target.step() + mean_loss = loss.detach().clone() + dist.all_reduce(mean_loss) + torch.testing.assert_close(mean_loss.item() / self.world_size, source_loss, rtol=1e-5, atol=1e-6) + for name, states in _full_optimizer_states(target).items(): + for kind, source_state, target_state, atol in zip(("fp32", "exp_avg", "exp_avg_sq"), + source_states[name], states, (1e-6, 1e-7, 1e-9)): + torch.testing.assert_close(target_state, + source_state, + rtol=1e-5, + atol=atol, + msg=lambda m: f"step {step + 1}, {name} {kind}: {m}") for state in target.optimizer.optimizer.state.values(): - assert int(state["step"]) == steps_before_save + 1 + assert int(state["step"]) == steps_before_save + steps_after_load target.destroy() From 234e0077294205b325f99da3fa3d3604a84f5a8e Mon Sep 17 00:00:00 2001 From: Achyuthan Sivasankar Date: Sat, 21 Nov 2026 00:18:18 -0500 Subject: [PATCH 5/6] Test the pipeline-to-ZeRO-3 load with the TP shards as affine maps A source can describe how its TP shards split each parameter with the Megatron name patterns or with affine maps, as AutoTP does. Run the TP2 x PP2 ZeRO-1 to ZeRO-3 test both ways: the same column- and row-parallel layouts written as contiguous_split_map and replicated_map, checked against the same tensors put back together from the source. Signed-off-by: Achyuthan Sivasankar --- .../checkpoint/test_universal_checkpoint.py | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/tests/unit/checkpoint/test_universal_checkpoint.py b/tests/unit/checkpoint/test_universal_checkpoint.py index 27aecfa299b2..276add2908bb 100644 --- a/tests/unit/checkpoint/test_universal_checkpoint.py +++ b/tests/unit/checkpoint/test_universal_checkpoint.py @@ -15,8 +15,9 @@ from deepspeed.utils.torch import required_torch_version from deepspeed.checkpoint import UNIVERSAL_CHECKPOINT_INFO -from deepspeed.checkpoint.constants import (OPTIMIZER_STATE_DICT, PARAMETER_WITH_ROW_PARALLELISM_PATTERNS, - TP_REPLICATED_PARAMETER_PATTERNS) +from deepspeed.checkpoint.affine import AFFINE_MAP_FORMAT_VERSION, contiguous_split_map, replicated_map +from deepspeed.checkpoint.constants import (AFFINE_MAP, AFFINE_MAP_PARAMS, AFFINE_MAP_VERSION, OPTIMIZER_STATE_DICT, + PARAMETER_WITH_ROW_PARALLELISM_PATTERNS, TP_REPLICATED_PARAMETER_PATTERNS) from deepspeed.pipe import PipelineModule from deepspeed.runtime.pipe.topology import PipeModelDataParallelTopology from deepspeed.checkpoint.ds_to_universal import main as convert_to_universal @@ -437,7 +438,9 @@ class TestUniversalCheckpointPipelineToZeRO3(DistributedTest): """A TP2 x PP2 run under ZeRO-1, the most a pipeline engine allows, resumed as ZeRO-3 over 4 data-parallel ranks.""" world_size = 4 - def test_load(self, tmpdir): + # The source describes its TP shards either with the Megatron name patterns or with affine maps, as AutoTP does. + @pytest.mark.parametrize("shard_info", ["patterns", "affine_maps"]) + def test_load(self, tmpdir, shard_info): hidden, tp, steps_before_save, steps_after_load = 8, 2, 2, 3 dims = [(hidden, 2 * hidden), (2 * hidden, hidden)] * 2 row_weight, row_bias = r"^[13]\.weight$", r"^[13]\.bias$" @@ -501,10 +504,27 @@ def whole_source_states(): return whole expected = whole_source_states() - uc_info = { - PARAMETER_WITH_ROW_PARALLELISM_PATTERNS: [row_weight], - TP_REPLICATED_PARAMETER_PATTERNS: [row_bias], - } + if shard_info == "patterns": + uc_info = { + PARAMETER_WITH_ROW_PARALLELISM_PATTERNS: [row_weight], + TP_REPLICATED_PARAMETER_PATTERNS: [row_bias], + } + else: + block = [2 * hidden // tp] * tp + column_maps = { + "weight": contiguous_split_map((2 * hidden, hidden), block, 0), + "bias": contiguous_split_map((2 * hidden, ), block, 0), + } + row_maps = { + "weight": contiguous_split_map((hidden, 2 * hidden), block, 1), + "bias": replicated_map((hidden, ), tp), + } + params = {} + for layer in range(len(dims)): + maps = column_maps if layer % 2 == 0 else row_maps + for name, shard_map in maps.items(): + params[rf"^{layer}\.{name}$"] = shard_map.to_dict() + uc_info = {AFFINE_MAP: {AFFINE_MAP_VERSION: AFFINE_MAP_FORMAT_VERSION, AFFINE_MAP_PARAMS: params}} source.save_checkpoint(tmpdir, tag=CP_TAG, client_state={UNIVERSAL_CHECKPOINT_INFO: uc_info}) # The run that never stopped, for the target to follow after the load. From e488d7a00ed94ba2c8868926c08395fea9192b08 Mon Sep 17 00:00:00 2001 From: "Jin, Youzhi" Date: Sun, 22 Nov 2026 00:13:08 +0000 Subject: [PATCH 6/6] Start ZeRO-3 groups without Adam state when the universal checkpoint has none Signed-off-by: Jin, Youzhi --- deepspeed/runtime/zero/stage3.py | 29 ++++++++++- .../checkpoint/test_universal_checkpoint.py | 50 +++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/deepspeed/runtime/zero/stage3.py b/deepspeed/runtime/zero/stage3.py index eb55355e08ca..47b3f085968f 100644 --- a/deepspeed/runtime/zero/stage3.py +++ b/deepspeed/runtime/zero/stage3.py @@ -4058,6 +4058,26 @@ def _load_universal_checkpoint(self, checkpoint_folder, load_optimizer_states, l else: self.load_module_checkpoint_state_from_checkpoint_dir_stage3(checkpoint_folder, True) + def _sub_groups_without_saved_moments(self, checkpoint_dir): + """The sub-groups whose parameters have no saved Adam moments. + + ZeRO-1/2 creates Adam state on the first step, so ds_to_universal writes only fp32.pt for a checkpoint + saved before it. A sub-group with moments for some parameters but not others cannot be restored. + """ + missing = set() + for sub_group_id, fp16_group in enumerate(self.fp16_groups): + saved = [ + all( + os.path.isfile(os.path.join(checkpoint_dir, self.param_names[param], f"{key}.pt")) + for key in ("exp_avg", "exp_avg_sq")) for param in fp16_group if param in self.param_names + ] + if saved and not any(saved): + missing.add(sub_group_id) + elif not all(saved): + raise ZeRORuntimeException(f"The universal checkpoint in {checkpoint_dir} has Adam moments for only " + f"some parameters of optimizer sub-group {sub_group_id}.") + return missing + def load_hp_checkpoint_state_from_checkpoint_dir_stage3(self, checkpoint_dir): """ Load optimizer and model states from the checkpoint directory. """ checkpoint_dir = os.path.join(checkpoint_dir, "zero") @@ -4071,9 +4091,16 @@ def load_hp_checkpoint_state_from_checkpoint_dir_stage3(self, checkpoint_dir): # Generally the step of each optimizer file should be the same, we can obtain from any parameter. from deepspeed.checkpoint.universal_checkpoint import load_universal_optimizer_step state_step = load_universal_optimizer_step(optim_sd, checkpoint_dir, self.param_names.values()) + sub_groups_without_moments = self._sub_groups_without_saved_moments(checkpoint_dir) for key in ["fp32", "exp_avg", "exp_avg_sq"]: for sub_group_id, fp16_group in enumerate(self.fp16_groups): fp32_param = self.fp32_partitioned_groups_flat[sub_group_id] + if sub_group_id in sub_groups_without_moments: + if key == "fp32": + # The source never stepped this group, so it starts without Adam state, as when fresh. + self.optimizer.state.pop(fp32_param, None) + else: + continue key_tensor = torch.zeros_like(fp32_param) offset = 0 for param in fp16_group: @@ -4087,7 +4114,7 @@ def load_hp_checkpoint_state_from_checkpoint_dir_stage3(self, checkpoint_dir): offset += key_layer_state_partition.numel() if key == "fp32": self.fp32_partitioned_groups_flat[sub_group_id].data.copy_(key_tensor) - if state_step is not None: + if state_step is not None and sub_group_id not in sub_groups_without_moments: # Each sub-group's optimizer advances its step in place, so give it its own copy. self.optimizer.state[fp32_param]['step'] = (state_step.clone() if torch.is_tensor(state_step) else state_step) diff --git a/tests/unit/checkpoint/test_universal_checkpoint.py b/tests/unit/checkpoint/test_universal_checkpoint.py index 276add2908bb..25c6b389862b 100644 --- a/tests/unit/checkpoint/test_universal_checkpoint.py +++ b/tests/unit/checkpoint/test_universal_checkpoint.py @@ -688,3 +688,53 @@ def build(stage, load_universal): for state in target.optimizer.optimizer.state.values(): assert int(state["step"]) == steps_before_save + 1 target.destroy() + + +@pytest.mark.parametrize("source_stage", [1, 2]) +class TestUniversalCheckpointBeforeFirstStepToZeRO3(DistributedTest): + world_size = 2 + + def test_load(self, tmpdir, source_stage): + """A ZeRO-1/2 checkpoint saved before the first step has no Adam state; ZeRO-3 starts it fresh.""" + hidden_dim = 10 + + def build(stage, load_universal): + ds_config = {"train_batch_size": 2, "zero_optimization": {"stage": stage, "sub_group_size": 100}} + if load_universal: + ds_config["checkpoint"] = {"load_universal": True} + model = SimpleModel(hidden_dim, nlayers=2) + engine, _, _, _ = deepspeed.initialize(config=ds_config, + model=model, + optimizer=torch.optim.Adam(model.parameters(), lr=0.1)) + return engine + + source = build(source_stage, load_universal=False) + expected = {name: safe_get_full_fp32_param(param).cpu() for name, param in source.module.named_parameters()} + source.save_checkpoint(tmpdir, tag=CP_TAG, client_state={UNIVERSAL_CHECKPOINT_INFO: {}}) + source.destroy() + + cp_dir = os.path.join(tmpdir, CP_TAG) + dist.barrier() + if dist.get_rank() == 0: + convert_to_universal( + SimpleNamespace(input_folder=cp_dir, + output_folder=f"{cp_dir}_universal", + num_extract_workers=1, + num_merge_workers=1, + keep_temp_folder=False, + strict=True, + inject_missing_state=False)) + dist.barrier() + + target = build(3, load_universal=True) + target.load_checkpoint(tmpdir, tag=f"{CP_TAG}_universal") + for name, param in target.module.named_parameters(): + assert torch.equal(safe_get_full_fp32_param(param).cpu(), expected[name]), name + assert not any(target.optimizer.optimizer.state.values()) + + _train(target, hidden_dim, 1) + optimizer_states = list(target.optimizer.optimizer.state.values()) + assert optimizer_states + for state in optimizer_states: + assert int(state["step"]) == 1 + target.destroy()