Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions deepspeed/checkpoint/ds_to_universal.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,15 +811,15 @@ def _consolidate_zero3_autoep_expert_states(output_dir, model_files, optim_files
rank: torch.load(model_file, map_location=torch.device('cpu'), weights_only=False)
for rank, model_file in model_rank_map.items()
}
optim_states_by_rank = {
rank: torch.load(optim_file, map_location=torch.device('cpu'), weights_only=False)
for rank, optim_file in optim_rank_map.items()
}
metadata_by_rank = {
rank: _get_autoep_metadata(model_state)
for rank, model_state in model_states_by_rank.items() if _get_autoep_metadata(model_state) is not None
}
_validate_autoep_expert_shapes(model_states_by_rank, metadata_by_rank)
# Together the optimizer files hold every optimizer state of the model, more than one host holds for a large
# model, so they are read one at a time and the expert fragments wait in files until every rank is read.
fragment_dir = os.path.join(output_dir, "tmp", "autoep_expert_fragments")
os.makedirs(fragment_dir, exist_ok=True)

expert_fragments = {}
num_experts_by_param = {}
Expand All @@ -830,14 +830,16 @@ def _consolidate_zero3_autoep_expert_states(output_dir, model_files, optim_files
affine_map_by_param = {}

for rank, model_state in model_states_by_rank.items():
optim_state = optim_states_by_rank.get(rank)
if optim_state is None:
optim_file = optim_rank_map.get(rank)
if optim_file is None:
raise FileNotFoundError(f"Missing ZeRO optimizer checkpoint for rank {rank}")

autoep_metadata = _get_autoep_metadata(model_state)
if not _uses_zero3_partitioned_autoep_metadata(autoep_metadata):
continue

optim_state = torch.load(optim_file, map_location=torch.device('cpu'), weights_only=False)

expert_info = _autoep_expert_param_info(autoep_metadata)
param_shapes = model_state[PARAM_SHAPES]
zero_optim_state = optim_state[OPTIMIZER_STATE_DICT]
Expand Down Expand Up @@ -895,11 +897,21 @@ def _consolidate_zero3_autoep_expert_states(output_dir, model_files, optim_files
if flat_tensor is None:
raise RuntimeError(f"Missing optimizer state '{state_key}' for AutoEP expert "
f"parameter {param_name} on ZeRO rank {rank}")
# clone(): saving the narrowed view would write the whole flat tensor behind it.
fragment = flat_tensor.narrow(0, offset, padding_free_numel).clone()
# One directory per parameter and EP rank, created first, as for the dense fragments: a
# parameter name may contain "/" (a registered module name may).
fragment_param_dir = os.path.join(fragment_dir, param_name, f"ep{ep_rank}")
os.makedirs(fragment_param_dir, exist_ok=True)
fragment_path = os.path.join(fragment_param_dir, f"{state_key}.part{partition_rank}.pt")
torch.save(fragment, fragment_path)
key = (param_name, state_key, ep_rank)
expert_fragments.setdefault(key, []).append((partition_rank, fragment, shape))
expert_fragments.setdefault(key, []).append((partition_rank, fragment_path, shape))

offset += partitioned_numel
# Drop every reference into this rank's optimizer state, including the loop variables, before the
# next file is read.
optim_state = zero_optim_state = optimizer_sub_state = flat_state = flat_tensor = None

grouped_by_param = {}
for (param_name, state_key, ep_rank), fragments in expert_fragments.items():
Expand Down Expand Up @@ -932,8 +944,14 @@ def _consolidate_zero3_autoep_expert_states(output_dir, model_files, optim_files
if any(tuple(fragment_shape) != tuple(shape) for _, _, fragment_shape in fragments):
raise RuntimeError(f"Inconsistent AutoEP expert fragment shapes for {param_name}/{state_key} "
f"EP rank {ep_rank}")
full_flat = torch.cat([fragment for _, fragment, _ in fragments], dim=0)[:_shape_numel(shape)]
fragment_paths = [path for _, path, _ in fragments]
full_flat = torch.cat([torch.load(path, weights_only=True) for path in fragment_paths],
dim=0)[:_shape_numel(shape)]
ep_tensors[ep_rank] = full_flat.view(shape)
# Each fragment is read only once. Removing it now means the disk never holds every fragment and
# every universal file at the same time.
for path in fragment_paths:
os.remove(path)

if not ep_tensors:
continue
Expand Down
10 changes: 6 additions & 4 deletions tests/unit/checkpoint/test_autoep_affine_universal.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,10 @@ def test_zero3_affine_rebuild_allows_omitted_empty_rank():
assert torch.equal(_rebuild_zero3_autoep_rank_tensors(shards, placement, full.shape, "test"), full)


def test_zero3_partition_native_consolidation_uses_affine_placement(tmp_path):
param_names = [f"layer.experts.w{index}" for index in range(1, 4)]
# A registered module name may contain "/"; the converter must still write every file it uses.
@pytest.mark.parametrize("module_path", ["layer", "blocks/0/layer"])
def test_zero3_partition_native_consolidation_uses_affine_placement(tmp_path, module_path):
param_names = [f"{module_path}.experts.w{index}" for index in range(1, 4)]
placement = make_autoep_placement_descriptor(4, [[2, 0, 3], [1]])
full = torch.arange(8, dtype=torch.float32).view(4, 2)
rank_tensors = {
Expand All @@ -251,11 +253,11 @@ def test_zero3_partition_native_consolidation_uses_affine_placement(tmp_path):
for rank, local_tensor in rank_tensors.items():
layer_info = {
'moe_layer_id': 0,
'module_path': 'layer',
'module_path': module_path,
'num_experts': 4,
'num_local_experts': local_tensor.shape[0],
'ep_size': 2,
'expert_key_prefix': 'layer.experts',
'expert_key_prefix': f'{module_path}.experts',
AUTOEP_EXPERT_PLACEMENT: placement,
AUTOEP_ZERO3_EXPERT_STATE_FORMAT_KEY: AUTOEP_ZERO3_PARTITIONED_EXPERT_STATE_FORMAT,
AUTOEP_ZERO3_EXPERT_STATE_FORMAT_VERSION_KEY: AUTOEP_ZERO3_EXPERT_STATE_FORMAT_VERSION,
Expand Down
Loading