diff --git a/deepspeed/checkpoint/ds_to_universal.py b/deepspeed/checkpoint/ds_to_universal.py index c67d29a6407e..90cb6e921c6b 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, @@ -1019,6 +1020,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..668bd57896a5 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,8 +398,15 @@ 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] + # 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/engine.py b/deepspeed/runtime/engine.py index 063c8bb752cf..54fe806da4ff 100644 --- a/deepspeed/runtime/engine.py +++ b/deepspeed/runtime/engine.py @@ -4454,13 +4454,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: @@ -4510,6 +4512,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 9aea43d03cf9..47b3f085968f 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, @@ -4057,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") @@ -4068,10 +4089,18 @@ 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()) + 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: @@ -4085,14 +4114,22 @@ 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 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) else: self.optimizer.state[fp32_param][key] = key_tensor self._move_state_to_backup_optimizer() - 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. 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 250349170504..25c6b389862b 100644 --- a/tests/unit/checkpoint/test_universal_checkpoint.py +++ b/tests/unit/checkpoint/test_universal_checkpoint.py @@ -4,8 +4,10 @@ # DeepSpeed Team import os +import re import glob import math +import traceback import deepspeed from types import SimpleNamespace @@ -13,8 +15,13 @@ 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.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 +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 * @@ -355,3 +362,379 @@ 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() + + +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 + + # 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$" + + 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 + steps_after_load))] + + 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, + "gradient_clipping": 0.0, + "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) + + 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() + 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. + 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: + 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 + }, + "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(): + 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 + + # 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 + steps_after_load + target.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 + + group_lrs = [0.1, 0.05] + + def build(stage, load_universal): + # 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(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() + + 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 + + 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() + + +@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()