Commit ·
5326b39
verified ·
0
Parent(s):
Duplicate from georgeyw/gpt-2-small-testing
Browse filesCo-authored-by: George Wang <georgeyw@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributesAdded+35
- checkpoint-10/config.jsonAdded+31
- checkpoint-10/generation_config.jsonAdded+6
- checkpoint-10/global_step10/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoint-10/global_step10/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoint-10/global_step10/mp_rank_00_model_states.ptAdded+3
- checkpoint-10/latestAdded+1
- checkpoint-10/model.safetensorsAdded+3
- checkpoint-10/rng_state_0.pthAdded+3
- checkpoint-10/rng_state_1.pthAdded+3
- checkpoint-10/trainer_state.jsonAdded+91
- checkpoint-10/training_args.binAdded+3
- checkpoint-10/zero_to_fp32.pyAdded+604
- checkpoint-100/config.jsonAdded+31
- checkpoint-100/generation_config.jsonAdded+6
- checkpoint-100/global_step100/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoint-100/global_step100/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoint-100/global_step100/mp_rank_00_model_states.ptAdded+3
- checkpoint-100/latestAdded+1
- checkpoint-100/model.safetensorsAdded+3
- checkpoint-100/rng_state_0.pthAdded+3
- checkpoint-100/rng_state_1.pthAdded+3
- checkpoint-100/trainer_state.jsonAdded+721
- checkpoint-100/training_args.binAdded+3
- checkpoint-100/zero_to_fp32.pyAdded+604
- checkpoint-20/config.jsonAdded+31
- checkpoint-20/generation_config.jsonAdded+6
- checkpoint-20/global_step20/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoint-20/global_step20/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoint-20/global_step20/mp_rank_00_model_states.ptAdded+3
- checkpoint-20/latestAdded+1
- checkpoint-20/model.safetensorsAdded+3
- checkpoint-20/rng_state_0.pthAdded+3
- checkpoint-20/rng_state_1.pthAdded+3
- checkpoint-20/trainer_state.jsonAdded+161
- checkpoint-20/training_args.binAdded+3
- checkpoint-20/zero_to_fp32.pyAdded+604
- checkpoint-200/config.jsonAdded+31
- checkpoint-200/generation_config.jsonAdded+6
- checkpoint-200/global_step200/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
- checkpoint-200/global_step200/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
- checkpoint-200/global_step200/mp_rank_00_model_states.ptAdded+3
- checkpoint-200/latestAdded+1
- checkpoint-200/model.safetensorsAdded+3
- checkpoint-200/rng_state_0.pthAdded+3
- checkpoint-200/rng_state_1.pthAdded+3
- checkpoint-200/trainer_state.jsonAdded+1421
- checkpoint-200/training_args.binAdded+3
- checkpoint-200/zero_to_fp32.pyAdded+604
- checkpoint-25/config.jsonAdded+31
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728293031{ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5", "architectures": [ "GPTNeoXForCausalLM" ], "attention_bias": true, "attention_dropout": 0.0, "bos_token_id": 0, "classifier_dropout": 0.1, "eos_token_id": 2, "hidden_act": "gelu", "hidden_dropout": 0.0, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-05, "layer_norm_epsilon": 1e-05, "max_position_embeddings": 1024, "model_type": "gpt_neox", "num_attention_heads": 12, "num_hidden_layers": 12, "rope_scaling": null, "rotary_emb_base": 10000, "rotary_pct": 0.25, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.38.2", "use_cache": true, "use_parallel_residual": true, "vocab_size": 50304}123456{ "_from_model_config": true, "bos_token_id": 0, "eos_token_id": 2, "transformers_version": "4.38.2"}123version https://git-lfs.github.com/spec/v1oid sha256:ed0df787a125d81094d867c743d5ffebb34766f877f42e3b5da9ad0e51fbf81esize 973946896123version https://git-lfs.github.com/spec/v1oid sha256:5f6768e7d81521ef703a230f41460e04972f79ded2de3b754bcd0fb7a96f4ff0size 973946832123version https://git-lfs.github.com/spec/v1oid sha256:7589ffd4359a842efe83dc7cc5ce4ff6a161f1fce829498ade432719a3c40d91size 3246899641global_step10123version https://git-lfs.github.com/spec/v1oid sha256:b6ba4e69094dffe72d300db52887b581d271c61d1a95702fdea83bf7d6d5697fsize 324662984123version https://git-lfs.github.com/spec/v1oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530size 14512123version https://git-lfs.github.com/spec/v1oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82size 1451212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.009995002498750625, "eval_steps": 500, "global_step": 10, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.0, "grad_norm": 3.3340553137590683, "learning_rate": 0.0, "loss": 11.0, "step": 1 }, { "epoch": 0.0, "grad_norm": 2.398799707355898, "learning_rate": 5.9999999999999995e-05, "loss": 10.125, "step": 2 }, { "epoch": 0.0, "grad_norm": 2.3943029297945575, "learning_rate": 0.00011999999999999999, "loss": 10.1172, "step": 3 }, { "epoch": 0.0, "grad_norm": 1.9959117709404242, "learning_rate": 0.00017999999999999998, "loss": 9.875, "step": 4 }, { "epoch": 0.0, "grad_norm": 1.8270696218303057, "learning_rate": 0.00023999999999999998, "loss": 9.6641, "step": 5 }, { "epoch": 0.01, "grad_norm": 1.7854351602113614, "learning_rate": 0.0003, "loss": 9.4844, "step": 6 }, { "epoch": 0.01, "grad_norm": 1.7194174424274788, "learning_rate": 0.00035999999999999997, "loss": 9.3281, "step": 7 }, { "epoch": 0.01, "grad_norm": 1.463772638994466, "learning_rate": 0.00041999999999999996, "loss": 9.2109, "step": 8 }, { "epoch": 0.01, "grad_norm": 1.439323678271545, "learning_rate": 0.00047999999999999996, "loss": 8.9453, "step": 9 }, { "epoch": 0.01, "grad_norm": 1.2936126396494727, "learning_rate": 0.00054, "loss": 8.7109, "step": 10 } ], "logging_steps": 1, "max_steps": 1000, "num_input_tokens_seen": 0, "num_train_epochs": 1, "save_steps": 10, "total_flos": 0.0, "train_batch_size": 32, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:95cc4290cc90782d57f7376defd26743b3a36943fc93e80e2734385bc57e8b78size 6520123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example: python zero_to_fp32.py . pytorch_model.bin
import argparseimport torchimport globimport mathimport osimport refrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir):
total_files = len(files) state_dicts = [] for f in files: state_dict = torch.load(f, map_location=device) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
if zero_stage <= 2: fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] elif zero_stage == 3: # if there is more than one param group, there will be multiple flattened tensors - one # flattened tensor per group - for simplicity merge them into a single tensor # # XXX: could make the script more memory efficient for when there are multiple groups - it # will require matching the sub-lists of param_shapes for each param group flattened tensor
fp32_flat_groups = [ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts)) ]
return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = fp32_flat_groups[0].numel() * world_size # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 for name, shape in param_shapes.items():
unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# XXX: memory usage doubles here state_dict[name] = torch.cat( tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)), 0).narrow(0, 0, unpartitioned_numel).view(shape) offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters
Returns: - pytorch ``state_dict``
Note: this approach may not work if your application doesn't have sufficient free CPU memory and you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
""" if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters """
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters) print(f"Saving fp32 state dict to {output_file}") torch.save(state_dict, output_file)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument( "output_file", type=str, help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)12345678910111213141516171819202122232425262728293031{ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5", "architectures": [ "GPTNeoXForCausalLM" ], "attention_bias": true, "attention_dropout": 0.0, "bos_token_id": 0, "classifier_dropout": 0.1, "eos_token_id": 2, "hidden_act": "gelu", "hidden_dropout": 0.0, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-05, "layer_norm_epsilon": 1e-05, "max_position_embeddings": 1024, "model_type": "gpt_neox", "num_attention_heads": 12, "num_hidden_layers": 12, "rope_scaling": null, "rotary_emb_base": 10000, "rotary_pct": 0.25, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.38.2", "use_cache": true, "use_parallel_residual": true, "vocab_size": 50304}123456{ "_from_model_config": true, "bos_token_id": 0, "eos_token_id": 2, "transformers_version": "4.38.2"}123version https://git-lfs.github.com/spec/v1oid sha256:f13244aa35b694472ea5bd7fde3bcee569b6a0b7251253f818b7e5ae6a048797size 973946896123version https://git-lfs.github.com/spec/v1oid sha256:b1039a6c333c1647ef2ddfc010c1b966f38d1001aff73ac8b3cdede7858acdc7size 973946832123version https://git-lfs.github.com/spec/v1oid sha256:26fe4253d323b90c0fa9e0d5da8cb64819f86baf288d72f171c73184ca877562size 3246899641global_step100123version https://git-lfs.github.com/spec/v1oid sha256:4c9a5c8eae560953cb2afb2b3bf5d1330d089af788edaa1bf1d3f77b218837bcsize 324662984123version https://git-lfs.github.com/spec/v1oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530size 14512123version https://git-lfs.github.com/spec/v1oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82size 14512123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.09995002498750624, "eval_steps": 500, "global_step": 100, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.0, "grad_norm": 3.3340563149001086, "learning_rate": 0.0, "loss": 11.0, "step": 1 }, { "epoch": 0.0, "grad_norm": 2.398812329952019, "learning_rate": 5.9999999999999995e-05, "loss": 10.125, "step": 2 }, { "epoch": 0.0, "grad_norm": 2.394322446895115, "learning_rate": 0.00011999999999999999, "loss": 10.1172, "step": 3 }, { "epoch": 0.0, "grad_norm": 1.9958816684399585, "learning_rate": 0.00017999999999999998, "loss": 9.875, "step": 4 }, { "epoch": 0.0, "grad_norm": 1.8270465897882062, "learning_rate": 0.00023999999999999998, "loss": 9.6641, "step": 5 }, { "epoch": 0.01, "grad_norm": 1.7854046471397795, "learning_rate": 0.0003, "loss": 9.4844, "step": 6 }, { "epoch": 0.01, "grad_norm": 1.719416749115252, "learning_rate": 0.00035999999999999997, "loss": 9.3281, "step": 7 }, { "epoch": 0.01, "grad_norm": 1.4637825746112274, "learning_rate": 0.00041999999999999996, "loss": 9.2109, "step": 8 }, { "epoch": 0.01, "grad_norm": 1.4393631015406718, "learning_rate": 0.00047999999999999996, "loss": 8.9453, "step": 9 }, { "epoch": 0.01, "grad_norm": 1.2936734586915988, "learning_rate": 0.00054, "loss": 8.7109, "step": 10 }, { "epoch": 0.01, "grad_norm": 1.0756922378227356, "learning_rate": 0.0005999986405514987, "loss": 8.4609, "step": 11 }, { "epoch": 0.01, "grad_norm": 0.9277829127413892, "learning_rate": 0.0005999945622196846, "loss": 8.2344, "step": 12 }, { "epoch": 0.01, "grad_norm": 0.8084581786682467, "learning_rate": 0.0005999877650456265, "loss": 8.125, "step": 13 }, { "epoch": 0.01, "grad_norm": 0.7635084596900947, "learning_rate": 0.000599978249097772, "loss": 7.9766, "step": 14 }, { "epoch": 0.01, "grad_norm": 0.9186699644247788, "learning_rate": 0.0005999660144719463, "loss": 7.8555, "step": 15 }, { "epoch": 0.02, "grad_norm": 0.6609504256551479, "learning_rate": 0.0005999510612913519, "loss": 7.7734, "step": 16 }, { "epoch": 0.02, "grad_norm": 0.7086232844782971, "learning_rate": 0.0005999333897065673, "loss": 7.7148, "step": 17 }, { "epoch": 0.02, "grad_norm": 16.38048851691348, "learning_rate": 0.0005999129998955453, "loss": 8.4844, "step": 18 }, { "epoch": 0.02, "grad_norm": 1.3057527590449889, "learning_rate": 0.0005998898920636111, "loss": 7.7539, "step": 19 }, { "epoch": 0.02, "grad_norm": 0.6966048242948986, "learning_rate": 0.00059986406644346, "loss": 7.75, "step": 20 }, { "epoch": 0.02, "grad_norm": 0.6348089115348993, "learning_rate": 0.0005998355232951559, "loss": 7.7031, "step": 21 }, { "epoch": 0.02, "grad_norm": 0.7829163518610293, "learning_rate": 0.0005998042629061279, "loss": 7.6992, "step": 22 }, { "epoch": 0.02, "grad_norm": 0.5900591778980369, "learning_rate": 0.0005997702855911678, "loss": 7.6016, "step": 23 }, { "epoch": 0.02, "grad_norm": 0.4655170213064256, "learning_rate": 0.0005997335916924268, "loss": 7.5977, "step": 24 }, { "epoch": 0.02, "grad_norm": 0.6287348258915756, "learning_rate": 0.0005996941815794121, "loss": 7.5586, "step": 25 }, { "epoch": 0.03, "grad_norm": 0.6137321903884564, "learning_rate": 0.0005996520556489831, "loss": 7.5898, "step": 26 }, { "epoch": 0.03, "grad_norm": 0.44962562710631065, "learning_rate": 0.0005996072143253473, "loss": 7.4336, "step": 27 }, { "epoch": 0.03, "grad_norm": 0.46130046454703316, "learning_rate": 0.0005995596580600566, "loss": 7.4023, "step": 28 }, { "epoch": 0.03, "grad_norm": 0.4686712675731326, "learning_rate": 0.0005995093873320018, "loss": 7.3789, "step": 29 }, { "epoch": 0.03, "grad_norm": 0.4672147564288997, "learning_rate": 0.0005994564026474087, "loss": 7.3711, "step": 30 }, { "epoch": 0.03, "grad_norm": 0.40408354581233474, "learning_rate": 0.0005994007045398324, "loss": 7.3672, "step": 31 }, { "epoch": 0.03, "grad_norm": 0.46032146732584733, "learning_rate": 0.0005993422935701524, "loss": 7.3477, "step": 32 }, { "epoch": 0.03, "grad_norm": 0.4765534634593268, "learning_rate": 0.0005992811703265664, "loss": 7.3555, "step": 33 }, { "epoch": 0.03, "grad_norm": 0.46208489386235113, "learning_rate": 0.0005992173354245849, "loss": 7.3047, "step": 34 }, { "epoch": 0.03, "grad_norm": 0.2956144524964961, "learning_rate": 0.0005991507895070244, "loss": 7.3125, "step": 35 }, { "epoch": 0.04, "grad_norm": 0.4834645389868856, "learning_rate": 0.0005990815332440017, "loss": 7.207, "step": 36 }, { "epoch": 0.04, "grad_norm": 0.4411831350968505, "learning_rate": 0.0005990095673329266, "loss": 7.1758, "step": 37 }, { "epoch": 0.04, "grad_norm": 0.24809297748968667, "learning_rate": 0.0005989348924984951, "loss": 7.2188, "step": 38 }, { "epoch": 0.04, "grad_norm": 0.39402988416840584, "learning_rate": 0.0005988575094926817, "loss": 7.1953, "step": 39 }, { "epoch": 0.04, "grad_norm": 0.3868345222189167, "learning_rate": 0.0005987774190947328, "loss": 7.1641, "step": 40 }, { "epoch": 0.04, "grad_norm": 0.3777261230135448, "learning_rate": 0.0005986946221111575, "loss": 7.1328, "step": 41 }, { "epoch": 0.04, "grad_norm": 0.4687511444077827, "learning_rate": 0.0005986091193757206, "loss": 7.0898, "step": 42 }, { "epoch": 0.04, "grad_norm": 0.34935796211612463, "learning_rate": 0.0005985209117494337, "loss": 7.1367, "step": 43 }, { "epoch": 0.04, "grad_norm": 0.38764476686849886, "learning_rate": 0.0005984300001205466, "loss": 7.125, "step": 44 }, { "epoch": 0.04, "grad_norm": 0.3956487898882936, "learning_rate": 0.0005983363854045386, "loss": 7.1094, "step": 45 }, { "epoch": 0.05, "grad_norm": 0.31140257544677513, "learning_rate": 0.0005982400685441084, "loss": 7.0898, "step": 46 }, { "epoch": 0.05, "grad_norm": 0.3664476570531787, "learning_rate": 0.0005981410505091662, "loss": 7.0664, "step": 47 }, { "epoch": 0.05, "grad_norm": 0.31891741142945207, "learning_rate": 0.0005980393322968223, "loss": 7.0273, "step": 48 }, { "epoch": 0.05, "grad_norm": 0.4533529037337155, "learning_rate": 0.0005979349149313778, "loss": 7.0586, "step": 49 }, { "epoch": 0.05, "grad_norm": 0.30532331638835586, "learning_rate": 0.0005978277994643147, "loss": 7.0195, "step": 50 }, { "epoch": 0.05, "grad_norm": 0.6501991746260075, "learning_rate": 0.0005977179869742844, "loss": 6.9648, "step": 51 }, { "epoch": 0.05, "grad_norm": 0.43904455901717926, "learning_rate": 0.0005976054785670975, "loss": 6.9805, "step": 52 }, { "epoch": 0.05, "grad_norm": 0.4826001598483571, "learning_rate": 0.0005974902753757124, "loss": 6.9297, "step": 53 }, { "epoch": 0.05, "grad_norm": 0.2924998027034648, "learning_rate": 0.000597372378560224, "loss": 6.8984, "step": 54 }, { "epoch": 0.05, "grad_norm": 0.4439033666380787, "learning_rate": 0.0005972517893078517, "loss": 6.8945, "step": 55 }, { "epoch": 0.06, "grad_norm": 0.6135914255073411, "learning_rate": 0.0005971285088329284, "loss": 6.9727, "step": 56 }, { "epoch": 0.06, "grad_norm": 0.5575686565598483, "learning_rate": 0.0005970025383768866, "loss": 6.9219, "step": 57 }, { "epoch": 0.06, "grad_norm": 0.4820951675994578, "learning_rate": 0.0005968738792082478, "loss": 6.8516, "step": 58 }, { "epoch": 0.06, "grad_norm": 0.40164190019465584, "learning_rate": 0.0005967425326226082, "loss": 6.7734, "step": 59 }, { "epoch": 0.06, "grad_norm": 0.46129863945181293, "learning_rate": 0.0005966084999426265, "loss": 6.8125, "step": 60 }, { "epoch": 0.06, "grad_norm": 0.33322355827118677, "learning_rate": 0.0005964717825180101, "loss": 6.7891, "step": 61 }, { "epoch": 0.06, "grad_norm": 0.3847525153855558, "learning_rate": 0.0005963323817255024, "loss": 6.8242, "step": 62 }, { "epoch": 0.06, "grad_norm": 0.3384433591375982, "learning_rate": 0.0005961902989688674, "loss": 6.707, "step": 63 }, { "epoch": 0.06, "grad_norm": 0.3937003195165685, "learning_rate": 0.000596045535678877, "loss": 6.8203, "step": 64 }, { "epoch": 0.06, "grad_norm": 0.35423488053528107, "learning_rate": 0.0005958980933132962, "loss": 6.7383, "step": 65 }, { "epoch": 0.07, "grad_norm": 0.36005939745315396, "learning_rate": 0.0005957479733568675, "loss": 6.7109, "step": 66 }, { "epoch": 0.07, "grad_norm": 0.3499278317706933, "learning_rate": 0.0005955951773212976, "loss": 6.7266, "step": 67 }, { "epoch": 0.07, "grad_norm": 0.3708385192137018, "learning_rate": 0.0005954397067452407, "loss": 6.7617, "step": 68 }, { "epoch": 0.07, "grad_norm": 0.3775657656205869, "learning_rate": 0.0005952815631942839, "loss": 6.7148, "step": 69 }, { "epoch": 0.07, "grad_norm": 0.3040083750375816, "learning_rate": 0.0005951207482609307, "loss": 6.5938, "step": 70 }, { "epoch": 0.07, "grad_norm": 0.3443020808841468, "learning_rate": 0.0005949572635645861, "loss": 6.6523, "step": 71 }, { "epoch": 0.07, "grad_norm": 0.3520066316939, "learning_rate": 0.0005947911107515389, "loss": 6.6211, "step": 72 }, { "epoch": 0.07, "grad_norm": 0.3739040572679613, "learning_rate": 0.0005946222914949462, "loss": 6.5547, "step": 73 }, { "epoch": 0.07, "grad_norm": 0.34890731989025553, "learning_rate": 0.000594450807494816, "loss": 6.5859, "step": 74 }, { "epoch": 0.07, "grad_norm": 0.40910932350136514, "learning_rate": 0.0005942766604779903, "loss": 6.5547, "step": 75 }, { "epoch": 0.08, "grad_norm": 0.5698342865852906, "learning_rate": 0.0005940998521981274, "loss": 6.457, "step": 76 }, { "epoch": 0.08, "grad_norm": 0.5179452709555474, "learning_rate": 0.0005939203844356852, "loss": 6.5547, "step": 77 }, { "epoch": 0.08, "grad_norm": 0.5222512938673792, "learning_rate": 0.0005937382589979016, "loss": 6.5039, "step": 78 }, { "epoch": 0.08, "grad_norm": 0.5682332793686307, "learning_rate": 0.0005935534777187781, "loss": 6.5547, "step": 79 }, { "epoch": 0.08, "grad_norm": 0.3869287710460676, "learning_rate": 0.0005933660424590598, "loss": 6.5156, "step": 80 }, { "epoch": 0.08, "grad_norm": 0.3078211032807607, "learning_rate": 0.000593175955106218, "loss": 6.4258, "step": 81 }, { "epoch": 0.08, "grad_norm": 0.3611357511872241, "learning_rate": 0.00059298321757443, "loss": 6.4727, "step": 82 }, { "epoch": 0.08, "grad_norm": 0.29633467844266953, "learning_rate": 0.0005927878318045608, "loss": 6.3281, "step": 83 }, { "epoch": 0.08, "grad_norm": 0.3257574200776832, "learning_rate": 0.0005925897997641426, "loss": 6.3203, "step": 84 }, { "epoch": 0.08, "grad_norm": 0.2824054533852328, "learning_rate": 0.0005923891234473562, "loss": 6.4062, "step": 85 }, { "epoch": 0.09, "grad_norm": 0.3056199770204573, "learning_rate": 0.0005921858048750097, "loss": 6.3984, "step": 86 }, { "epoch": 0.09, "grad_norm": 0.2966438824341908, "learning_rate": 0.000591979846094519, "loss": 6.3555, "step": 87 }, { "epoch": 0.09, "grad_norm": 0.32782438676663733, "learning_rate": 0.0005917712491798866, "loss": 6.4023, "step": 88 }, { "epoch": 0.09, "grad_norm": 0.3538316399620157, "learning_rate": 0.0005915600162316811, "loss": 6.2812, "step": 89 }, { "epoch": 0.09, "grad_norm": 0.375858298192913, "learning_rate": 0.0005913461493770162, "loss": 6.3086, "step": 90 }, { "epoch": 0.09, "grad_norm": 0.5189251339815161, "learning_rate": 0.0005911296507695284, "loss": 6.2812, "step": 91 }, { "epoch": 0.09, "grad_norm": 0.6304909542669104, "learning_rate": 0.0005909105225893564, "loss": 6.2969, "step": 92 }, { "epoch": 0.09, "grad_norm": 0.4655662819622591, "learning_rate": 0.0005906887670431187, "loss": 6.1953, "step": 93 }, { "epoch": 0.09, "grad_norm": 0.39035390983920965, "learning_rate": 0.000590464386363891, "loss": 6.2617, "step": 94 }, { "epoch": 0.09, "grad_norm": 0.4918417851770978, "learning_rate": 0.0005902373828111843, "loss": 6.2148, "step": 95 }, { "epoch": 0.1, "grad_norm": 0.35670770889552555, "learning_rate": 0.0005900077586709219, "loss": 6.2461, "step": 96 }, { "epoch": 0.1, "grad_norm": 0.4177985869939347, "learning_rate": 0.0005897755162554163, "loss": 6.1797, "step": 97 }, { "epoch": 0.1, "grad_norm": 0.3742471130708234, "learning_rate": 0.000589540657903346, "loss": 6.1406, "step": 98 }, { "epoch": 0.1, "grad_norm": 0.28627666723978284, "learning_rate": 0.0005893031859797322, "loss": 6.2031, "step": 99 }, { "epoch": 0.1, "grad_norm": 0.32238563846046103, "learning_rate": 0.0005890631028759143, "loss": 6.0625, "step": 100 } ], "logging_steps": 1, "max_steps": 1000, "num_input_tokens_seen": 0, "num_train_epochs": 1, "save_steps": 100, "total_flos": 0.0, "train_batch_size": 32, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:36ce7ab48fa86ef42491eaad3583773d2b60353997a5e7b6fb4ffc1414828749size 6520123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example: python zero_to_fp32.py . pytorch_model.bin
import argparseimport torchimport globimport mathimport osimport refrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir):
total_files = len(files) state_dicts = [] for f in files: state_dict = torch.load(f, map_location=device) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
if zero_stage <= 2: fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] elif zero_stage == 3: # if there is more than one param group, there will be multiple flattened tensors - one # flattened tensor per group - for simplicity merge them into a single tensor # # XXX: could make the script more memory efficient for when there are multiple groups - it # will require matching the sub-lists of param_shapes for each param group flattened tensor
fp32_flat_groups = [ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts)) ]
return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = fp32_flat_groups[0].numel() * world_size # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 for name, shape in param_shapes.items():
unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# XXX: memory usage doubles here state_dict[name] = torch.cat( tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)), 0).narrow(0, 0, unpartitioned_numel).view(shape) offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters
Returns: - pytorch ``state_dict``
Note: this approach may not work if your application doesn't have sufficient free CPU memory and you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
""" if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters """
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters) print(f"Saving fp32 state dict to {output_file}") torch.save(state_dict, output_file)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument( "output_file", type=str, help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)12345678910111213141516171819202122232425262728293031{ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5", "architectures": [ "GPTNeoXForCausalLM" ], "attention_bias": true, "attention_dropout": 0.0, "bos_token_id": 0, "classifier_dropout": 0.1, "eos_token_id": 2, "hidden_act": "gelu", "hidden_dropout": 0.0, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-05, "layer_norm_epsilon": 1e-05, "max_position_embeddings": 1024, "model_type": "gpt_neox", "num_attention_heads": 12, "num_hidden_layers": 12, "rope_scaling": null, "rotary_emb_base": 10000, "rotary_pct": 0.25, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.38.2", "use_cache": true, "use_parallel_residual": true, "vocab_size": 50304}123456{ "_from_model_config": true, "bos_token_id": 0, "eos_token_id": 2, "transformers_version": "4.38.2"}123version https://git-lfs.github.com/spec/v1oid sha256:3d9619b0d3ceeed4c45a4c6fd5be8946b1be76a5801c466123be2ca841e5e337size 973946896123version https://git-lfs.github.com/spec/v1oid sha256:6c51b9f289ed8d24931448d39d8478de2e97527186251a29c92850b1de7562easize 973946832123version https://git-lfs.github.com/spec/v1oid sha256:06da85a865332b0c223e8dc427f16b0c81330388f43d5d7b854b9b349b9e2f89size 3246899641global_step20123version https://git-lfs.github.com/spec/v1oid sha256:99984de686ddb1e07f6ea7778c91ab6e3547271af7b06526b184e6578f6bf40dsize 324662984123version https://git-lfs.github.com/spec/v1oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530size 14512123version https://git-lfs.github.com/spec/v1oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82size 14512123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.01999000499750125, "eval_steps": 500, "global_step": 20, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.0, "grad_norm": 3.3340553137590683, "learning_rate": 0.0, "loss": 11.0, "step": 1 }, { "epoch": 0.0, "grad_norm": 2.398799707355898, "learning_rate": 5.9999999999999995e-05, "loss": 10.125, "step": 2 }, { "epoch": 0.0, "grad_norm": 2.3943029297945575, "learning_rate": 0.00011999999999999999, "loss": 10.1172, "step": 3 }, { "epoch": 0.0, "grad_norm": 1.9959117709404242, "learning_rate": 0.00017999999999999998, "loss": 9.875, "step": 4 }, { "epoch": 0.0, "grad_norm": 1.8270696218303057, "learning_rate": 0.00023999999999999998, "loss": 9.6641, "step": 5 }, { "epoch": 0.01, "grad_norm": 1.7854351602113614, "learning_rate": 0.0003, "loss": 9.4844, "step": 6 }, { "epoch": 0.01, "grad_norm": 1.7194174424274788, "learning_rate": 0.00035999999999999997, "loss": 9.3281, "step": 7 }, { "epoch": 0.01, "grad_norm": 1.463772638994466, "learning_rate": 0.00041999999999999996, "loss": 9.2109, "step": 8 }, { "epoch": 0.01, "grad_norm": 1.439323678271545, "learning_rate": 0.00047999999999999996, "loss": 8.9453, "step": 9 }, { "epoch": 0.01, "grad_norm": 1.2936126396494727, "learning_rate": 0.00054, "loss": 8.7109, "step": 10 }, { "epoch": 0.01, "grad_norm": 1.0757761814549318, "learning_rate": 0.0005999986405514987, "loss": 8.4609, "step": 11 }, { "epoch": 0.01, "grad_norm": 0.9278570154341632, "learning_rate": 0.0005999945622196846, "loss": 8.2344, "step": 12 }, { "epoch": 0.01, "grad_norm": 0.8086775215724974, "learning_rate": 0.0005999877650456265, "loss": 8.125, "step": 13 }, { "epoch": 0.01, "grad_norm": 0.7630413213242441, "learning_rate": 0.000599978249097772, "loss": 7.9766, "step": 14 }, { "epoch": 0.01, "grad_norm": 0.9172017565891333, "learning_rate": 0.0005999660144719463, "loss": 7.8555, "step": 15 }, { "epoch": 0.02, "grad_norm": 0.6610052304024877, "learning_rate": 0.0005999510612913519, "loss": 7.7734, "step": 16 }, { "epoch": 0.02, "grad_norm": 0.7091485456070775, "learning_rate": 0.0005999333897065673, "loss": 7.7148, "step": 17 }, { "epoch": 0.02, "grad_norm": 16.771353248766836, "learning_rate": 0.0005999129998955453, "loss": 8.5078, "step": 18 }, { "epoch": 0.02, "grad_norm": 1.3123969082989795, "learning_rate": 0.0005998898920636111, "loss": 7.7539, "step": 19 }, { "epoch": 0.02, "grad_norm": 0.6992078172905232, "learning_rate": 0.00059986406644346, "loss": 7.75, "step": 20 } ], "logging_steps": 1, "max_steps": 1000, "num_input_tokens_seen": 0, "num_train_epochs": 1, "save_steps": 10, "total_flos": 0.0, "train_batch_size": 32, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:95cc4290cc90782d57f7376defd26743b3a36943fc93e80e2734385bc57e8b78size 6520123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example: python zero_to_fp32.py . pytorch_model.bin
import argparseimport torchimport globimport mathimport osimport refrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir):
total_files = len(files) state_dicts = [] for f in files: state_dict = torch.load(f, map_location=device) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
if zero_stage <= 2: fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] elif zero_stage == 3: # if there is more than one param group, there will be multiple flattened tensors - one # flattened tensor per group - for simplicity merge them into a single tensor # # XXX: could make the script more memory efficient for when there are multiple groups - it # will require matching the sub-lists of param_shapes for each param group flattened tensor
fp32_flat_groups = [ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts)) ]
return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = fp32_flat_groups[0].numel() * world_size # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 for name, shape in param_shapes.items():
unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# XXX: memory usage doubles here state_dict[name] = torch.cat( tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)), 0).narrow(0, 0, unpartitioned_numel).view(shape) offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters
Returns: - pytorch ``state_dict``
Note: this approach may not work if your application doesn't have sufficient free CPU memory and you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
""" if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters """
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters) print(f"Saving fp32 state dict to {output_file}") torch.save(state_dict, output_file)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument( "output_file", type=str, help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)12345678910111213141516171819202122232425262728293031{ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5", "architectures": [ "GPTNeoXForCausalLM" ], "attention_bias": true, "attention_dropout": 0.0, "bos_token_id": 0, "classifier_dropout": 0.1, "eos_token_id": 2, "hidden_act": "gelu", "hidden_dropout": 0.0, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-05, "layer_norm_epsilon": 1e-05, "max_position_embeddings": 1024, "model_type": "gpt_neox", "num_attention_heads": 12, "num_hidden_layers": 12, "rope_scaling": null, "rotary_emb_base": 10000, "rotary_pct": 0.25, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.38.2", "use_cache": true, "use_parallel_residual": true, "vocab_size": 50304}123456{ "_from_model_config": true, "bos_token_id": 0, "eos_token_id": 2, "transformers_version": "4.38.2"}123version https://git-lfs.github.com/spec/v1oid sha256:cc073673977d2260d446a5288c182308ae00d243deb8aa1287eed2bdc0ca55ebsize 973946896123version https://git-lfs.github.com/spec/v1oid sha256:1dd88f92e1b9309a12e7505328b079538457daedef3bcf8d59f5cfcef86aca6dsize 973946832123version https://git-lfs.github.com/spec/v1oid sha256:ea030c07bc1914d14db0809ed9a4fc3f9c76b4d11dbdabd30acf57c7c93e685csize 3246899641global_step200123version https://git-lfs.github.com/spec/v1oid sha256:fd81f3f4d4881c9ad52c0835b8eedd34cd74ec334ef06ba64c40c85ac825a476size 324662984123version https://git-lfs.github.com/spec/v1oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530size 14512123version https://git-lfs.github.com/spec/v1oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82size 1451212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.19990004997501248, "eval_steps": 500, "global_step": 200, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.0, "grad_norm": 3.3340563149001086, "learning_rate": 0.0, "loss": 11.0, "step": 1 }, { "epoch": 0.0, "grad_norm": 2.398812329952019, "learning_rate": 5.9999999999999995e-05, "loss": 10.125, "step": 2 }, { "epoch": 0.0, "grad_norm": 2.394322446895115, "learning_rate": 0.00011999999999999999, "loss": 10.1172, "step": 3 }, { "epoch": 0.0, "grad_norm": 1.9958816684399585, "learning_rate": 0.00017999999999999998, "loss": 9.875, "step": 4 }, { "epoch": 0.0, "grad_norm": 1.8270465897882062, "learning_rate": 0.00023999999999999998, "loss": 9.6641, "step": 5 }, { "epoch": 0.01, "grad_norm": 1.7854046471397795, "learning_rate": 0.0003, "loss": 9.4844, "step": 6 }, { "epoch": 0.01, "grad_norm": 1.719416749115252, "learning_rate": 0.00035999999999999997, "loss": 9.3281, "step": 7 }, { "epoch": 0.01, "grad_norm": 1.4637825746112274, "learning_rate": 0.00041999999999999996, "loss": 9.2109, "step": 8 }, { "epoch": 0.01, "grad_norm": 1.4393631015406718, "learning_rate": 0.00047999999999999996, "loss": 8.9453, "step": 9 }, { "epoch": 0.01, "grad_norm": 1.2936734586915988, "learning_rate": 0.00054, "loss": 8.7109, "step": 10 }, { "epoch": 0.01, "grad_norm": 1.0756922378227356, "learning_rate": 0.0005999986405514987, "loss": 8.4609, "step": 11 }, { "epoch": 0.01, "grad_norm": 0.9277829127413892, "learning_rate": 0.0005999945622196846, "loss": 8.2344, "step": 12 }, { "epoch": 0.01, "grad_norm": 0.8084581786682467, "learning_rate": 0.0005999877650456265, "loss": 8.125, "step": 13 }, { "epoch": 0.01, "grad_norm": 0.7635084596900947, "learning_rate": 0.000599978249097772, "loss": 7.9766, "step": 14 }, { "epoch": 0.01, "grad_norm": 0.9186699644247788, "learning_rate": 0.0005999660144719463, "loss": 7.8555, "step": 15 }, { "epoch": 0.02, "grad_norm": 0.6609504256551479, "learning_rate": 0.0005999510612913519, "loss": 7.7734, "step": 16 }, { "epoch": 0.02, "grad_norm": 0.7086232844782971, "learning_rate": 0.0005999333897065673, "loss": 7.7148, "step": 17 }, { "epoch": 0.02, "grad_norm": 16.38048851691348, "learning_rate": 0.0005999129998955453, "loss": 8.4844, "step": 18 }, { "epoch": 0.02, "grad_norm": 1.3057527590449889, "learning_rate": 0.0005998898920636111, "loss": 7.7539, "step": 19 }, { "epoch": 0.02, "grad_norm": 0.6966048242948986, "learning_rate": 0.00059986406644346, "loss": 7.75, "step": 20 }, { "epoch": 0.02, "grad_norm": 0.6348089115348993, "learning_rate": 0.0005998355232951559, "loss": 7.7031, "step": 21 }, { "epoch": 0.02, "grad_norm": 0.7829163518610293, "learning_rate": 0.0005998042629061279, "loss": 7.6992, "step": 22 }, { "epoch": 0.02, "grad_norm": 0.5900591778980369, "learning_rate": 0.0005997702855911678, "loss": 7.6016, "step": 23 }, { "epoch": 0.02, "grad_norm": 0.4655170213064256, "learning_rate": 0.0005997335916924268, "loss": 7.5977, "step": 24 }, { "epoch": 0.02, "grad_norm": 0.6287348258915756, "learning_rate": 0.0005996941815794121, "loss": 7.5586, "step": 25 }, { "epoch": 0.03, "grad_norm": 0.6137321903884564, "learning_rate": 0.0005996520556489831, "loss": 7.5898, "step": 26 }, { "epoch": 0.03, "grad_norm": 0.44962562710631065, "learning_rate": 0.0005996072143253473, "loss": 7.4336, "step": 27 }, { "epoch": 0.03, "grad_norm": 0.46130046454703316, "learning_rate": 0.0005995596580600566, "loss": 7.4023, "step": 28 }, { "epoch": 0.03, "grad_norm": 0.4686712675731326, "learning_rate": 0.0005995093873320018, "loss": 7.3789, "step": 29 }, { "epoch": 0.03, "grad_norm": 0.4672147564288997, "learning_rate": 0.0005994564026474087, "loss": 7.3711, "step": 30 }, { "epoch": 0.03, "grad_norm": 0.40408354581233474, "learning_rate": 0.0005994007045398324, "loss": 7.3672, "step": 31 }, { "epoch": 0.03, "grad_norm": 0.46032146732584733, "learning_rate": 0.0005993422935701524, "loss": 7.3477, "step": 32 }, { "epoch": 0.03, "grad_norm": 0.4765534634593268, "learning_rate": 0.0005992811703265664, "loss": 7.3555, "step": 33 }, { "epoch": 0.03, "grad_norm": 0.46208489386235113, "learning_rate": 0.0005992173354245849, "loss": 7.3047, "step": 34 }, { "epoch": 0.03, "grad_norm": 0.2956144524964961, "learning_rate": 0.0005991507895070244, "loss": 7.3125, "step": 35 }, { "epoch": 0.04, "grad_norm": 0.4834645389868856, "learning_rate": 0.0005990815332440017, "loss": 7.207, "step": 36 }, { "epoch": 0.04, "grad_norm": 0.4411831350968505, "learning_rate": 0.0005990095673329266, "loss": 7.1758, "step": 37 }, { "epoch": 0.04, "grad_norm": 0.24809297748968667, "learning_rate": 0.0005989348924984951, "loss": 7.2188, "step": 38 }, { "epoch": 0.04, "grad_norm": 0.39402988416840584, "learning_rate": 0.0005988575094926817, "loss": 7.1953, "step": 39 }, { "epoch": 0.04, "grad_norm": 0.3868345222189167, "learning_rate": 0.0005987774190947328, "loss": 7.1641, "step": 40 }, { "epoch": 0.04, "grad_norm": 0.3777261230135448, "learning_rate": 0.0005986946221111575, "loss": 7.1328, "step": 41 }, { "epoch": 0.04, "grad_norm": 0.4687511444077827, "learning_rate": 0.0005986091193757206, "loss": 7.0898, "step": 42 }, { "epoch": 0.04, "grad_norm": 0.34935796211612463, "learning_rate": 0.0005985209117494337, "loss": 7.1367, "step": 43 }, { "epoch": 0.04, "grad_norm": 0.38764476686849886, "learning_rate": 0.0005984300001205466, "loss": 7.125, "step": 44 }, { "epoch": 0.04, "grad_norm": 0.3956487898882936, "learning_rate": 0.0005983363854045386, "loss": 7.1094, "step": 45 }, { "epoch": 0.05, "grad_norm": 0.31140257544677513, "learning_rate": 0.0005982400685441084, "loss": 7.0898, "step": 46 }, { "epoch": 0.05, "grad_norm": 0.3664476570531787, "learning_rate": 0.0005981410505091662, "loss": 7.0664, "step": 47 }, { "epoch": 0.05, "grad_norm": 0.31891741142945207, "learning_rate": 0.0005980393322968223, "loss": 7.0273, "step": 48 }, { "epoch": 0.05, "grad_norm": 0.4533529037337155, "learning_rate": 0.0005979349149313778, "loss": 7.0586, "step": 49 }, { "epoch": 0.05, "grad_norm": 0.30532331638835586, "learning_rate": 0.0005978277994643147, "loss": 7.0195, "step": 50 }, { "epoch": 0.05, "grad_norm": 0.6501991746260075, "learning_rate": 0.0005977179869742844, "loss": 6.9648, "step": 51 }, { "epoch": 0.05, "grad_norm": 0.43904455901717926, "learning_rate": 0.0005976054785670975, "loss": 6.9805, "step": 52 }, { "epoch": 0.05, "grad_norm": 0.4826001598483571, "learning_rate": 0.0005974902753757124, "loss": 6.9297, "step": 53 }, { "epoch": 0.05, "grad_norm": 0.2924998027034648, "learning_rate": 0.000597372378560224, "loss": 6.8984, "step": 54 }, { "epoch": 0.05, "grad_norm": 0.4439033666380787, "learning_rate": 0.0005972517893078517, "loss": 6.8945, "step": 55 }, { "epoch": 0.06, "grad_norm": 0.6135914255073411, "learning_rate": 0.0005971285088329284, "loss": 6.9727, "step": 56 }, { "epoch": 0.06, "grad_norm": 0.5575686565598483, "learning_rate": 0.0005970025383768866, "loss": 6.9219, "step": 57 }, { "epoch": 0.06, "grad_norm": 0.4820951675994578, "learning_rate": 0.0005968738792082478, "loss": 6.8516, "step": 58 }, { "epoch": 0.06, "grad_norm": 0.40164190019465584, "learning_rate": 0.0005967425326226082, "loss": 6.7734, "step": 59 }, { "epoch": 0.06, "grad_norm": 0.46129863945181293, "learning_rate": 0.0005966084999426265, "loss": 6.8125, "step": 60 }, { "epoch": 0.06, "grad_norm": 0.33322355827118677, "learning_rate": 0.0005964717825180101, "loss": 6.7891, "step": 61 }, { "epoch": 0.06, "grad_norm": 0.3847525153855558, "learning_rate": 0.0005963323817255024, "loss": 6.8242, "step": 62 }, { "epoch": 0.06, "grad_norm": 0.3384433591375982, "learning_rate": 0.0005961902989688674, "loss": 6.707, "step": 63 }, { "epoch": 0.06, "grad_norm": 0.3937003195165685, "learning_rate": 0.000596045535678877, "loss": 6.8203, "step": 64 }, { "epoch": 0.06, "grad_norm": 0.35423488053528107, "learning_rate": 0.0005958980933132962, "loss": 6.7383, "step": 65 }, { "epoch": 0.07, "grad_norm": 0.36005939745315396, "learning_rate": 0.0005957479733568675, "loss": 6.7109, "step": 66 }, { "epoch": 0.07, "grad_norm": 0.3499278317706933, "learning_rate": 0.0005955951773212976, "loss": 6.7266, "step": 67 }, { "epoch": 0.07, "grad_norm": 0.3708385192137018, "learning_rate": 0.0005954397067452407, "loss": 6.7617, "step": 68 }, { "epoch": 0.07, "grad_norm": 0.3775657656205869, "learning_rate": 0.0005952815631942839, "loss": 6.7148, "step": 69 }, { "epoch": 0.07, "grad_norm": 0.3040083750375816, "learning_rate": 0.0005951207482609307, "loss": 6.5938, "step": 70 }, { "epoch": 0.07, "grad_norm": 0.3443020808841468, "learning_rate": 0.0005949572635645861, "loss": 6.6523, "step": 71 }, { "epoch": 0.07, "grad_norm": 0.3520066316939, "learning_rate": 0.0005947911107515389, "loss": 6.6211, "step": 72 }, { "epoch": 0.07, "grad_norm": 0.3739040572679613, "learning_rate": 0.0005946222914949462, "loss": 6.5547, "step": 73 }, { "epoch": 0.07, "grad_norm": 0.34890731989025553, "learning_rate": 0.000594450807494816, "loss": 6.5859, "step": 74 }, { "epoch": 0.07, "grad_norm": 0.40910932350136514, "learning_rate": 0.0005942766604779903, "loss": 6.5547, "step": 75 }, { "epoch": 0.08, "grad_norm": 0.5698342865852906, "learning_rate": 0.0005940998521981274, "loss": 6.457, "step": 76 }, { "epoch": 0.08, "grad_norm": 0.5179452709555474, "learning_rate": 0.0005939203844356852, "loss": 6.5547, "step": 77 }, { "epoch": 0.08, "grad_norm": 0.5222512938673792, "learning_rate": 0.0005937382589979016, "loss": 6.5039, "step": 78 }, { "epoch": 0.08, "grad_norm": 0.5682332793686307, "learning_rate": 0.0005935534777187781, "loss": 6.5547, "step": 79 }, { "epoch": 0.08, "grad_norm": 0.3869287710460676, "learning_rate": 0.0005933660424590598, "loss": 6.5156, "step": 80 }, { "epoch": 0.08, "grad_norm": 0.3078211032807607, "learning_rate": 0.000593175955106218, "loss": 6.4258, "step": 81 }, { "epoch": 0.08, "grad_norm": 0.3611357511872241, "learning_rate": 0.00059298321757443, "loss": 6.4727, "step": 82 }, { "epoch": 0.08, "grad_norm": 0.29633467844266953, "learning_rate": 0.0005927878318045608, "loss": 6.3281, "step": 83 }, { "epoch": 0.08, "grad_norm": 0.3257574200776832, "learning_rate": 0.0005925897997641426, "loss": 6.3203, "step": 84 }, { "epoch": 0.08, "grad_norm": 0.2824054533852328, "learning_rate": 0.0005923891234473562, "loss": 6.4062, "step": 85 }, { "epoch": 0.09, "grad_norm": 0.3056199770204573, "learning_rate": 0.0005921858048750097, "loss": 6.3984, "step": 86 }, { "epoch": 0.09, "grad_norm": 0.2966438824341908, "learning_rate": 0.000591979846094519, "loss": 6.3555, "step": 87 }, { "epoch": 0.09, "grad_norm": 0.32782438676663733, "learning_rate": 0.0005917712491798866, "loss": 6.4023, "step": 88 }, { "epoch": 0.09, "grad_norm": 0.3538316399620157, "learning_rate": 0.0005915600162316811, "loss": 6.2812, "step": 89 }, { "epoch": 0.09, "grad_norm": 0.375858298192913, "learning_rate": 0.0005913461493770162, "loss": 6.3086, "step": 90 }, { "epoch": 0.09, "grad_norm": 0.5189251339815161, "learning_rate": 0.0005911296507695284, "loss": 6.2812, "step": 91 }, { "epoch": 0.09, "grad_norm": 0.6304909542669104, "learning_rate": 0.0005909105225893564, "loss": 6.2969, "step": 92 }, { "epoch": 0.09, "grad_norm": 0.4655662819622591, "learning_rate": 0.0005906887670431187, "loss": 6.1953, "step": 93 }, { "epoch": 0.09, "grad_norm": 0.39035390983920965, "learning_rate": 0.000590464386363891, "loss": 6.2617, "step": 94 }, { "epoch": 0.09, "grad_norm": 0.4918417851770978, "learning_rate": 0.0005902373828111843, "loss": 6.2148, "step": 95 }, { "epoch": 0.1, "grad_norm": 0.35670770889552555, "learning_rate": 0.0005900077586709219, "loss": 6.2461, "step": 96 }, { "epoch": 0.1, "grad_norm": 0.4177985869939347, "learning_rate": 0.0005897755162554163, "loss": 6.1797, "step": 97 }, { "epoch": 0.1, "grad_norm": 0.3742471130708234, "learning_rate": 0.000589540657903346, "loss": 6.1406, "step": 98 }, { "epoch": 0.1, "grad_norm": 0.28627666723978284, "learning_rate": 0.0005893031859797322, "loss": 6.2031, "step": 99 }, { "epoch": 0.1, "grad_norm": 0.32238563846046103, "learning_rate": 0.0005890631028759143, "loss": 6.0625, "step": 100 }, { "epoch": 0.1, "grad_norm": 0.2556625657587849, "learning_rate": 0.0005888204110095265, "loss": 6.1797, "step": 101 }, { "epoch": 0.1, "grad_norm": 0.35463629701710253, "learning_rate": 0.0005885751128244734, "loss": 6.125, "step": 102 }, { "epoch": 0.1, "grad_norm": 0.31975770214936095, "learning_rate": 0.0005883272107909048, "loss": 6.1836, "step": 103 }, { "epoch": 0.1, "grad_norm": 0.3464621815245048, "learning_rate": 0.0005880767074051915, "loss": 6.125, "step": 104 }, { "epoch": 0.1, "grad_norm": 0.3663428920796654, "learning_rate": 0.0005878236051898998, "loss": 6.0781, "step": 105 }, { "epoch": 0.11, "grad_norm": 0.31594460565215293, "learning_rate": 0.0005875679066937664, "loss": 6.082, "step": 106 }, { "epoch": 0.11, "grad_norm": 0.3552617109396582, "learning_rate": 0.000587309614491672, "loss": 6.1016, "step": 107 }, { "epoch": 0.11, "grad_norm": 0.307016409692456, "learning_rate": 0.0005870487311846164, "loss": 6.1406, "step": 108 }, { "epoch": 0.11, "grad_norm": 0.32188902148474213, "learning_rate": 0.0005867852593996914, "loss": 6.0039, "step": 109 }, { "epoch": 0.11, "grad_norm": 0.25501199715105083, "learning_rate": 0.0005865192017900551, "loss": 6.0938, "step": 110 }, { "epoch": 0.11, "grad_norm": 0.3416203070024056, "learning_rate": 0.0005862505610349049, "loss": 6.0234, "step": 111 }, { "epoch": 0.11, "grad_norm": 0.3562508875852537, "learning_rate": 0.0005859793398394498, "loss": 6.0469, "step": 112 }, { "epoch": 0.11, "grad_norm": 0.4443953757302568, "learning_rate": 0.0005857055409348845, "loss": 5.9766, "step": 113 }, { "epoch": 0.11, "grad_norm": 0.42023839332714596, "learning_rate": 0.0005854291670783607, "loss": 6.0781, "step": 114 }, { "epoch": 0.11, "grad_norm": 0.4618323255809241, "learning_rate": 0.0005851502210529604, "loss": 5.9727, "step": 115 }, { "epoch": 0.12, "grad_norm": 0.379195014798667, "learning_rate": 0.0005848687056676668, "loss": 5.9922, "step": 116 }, { "epoch": 0.12, "grad_norm": 0.3931552573296799, "learning_rate": 0.0005845846237573366, "loss": 5.9492, "step": 117 }, { "epoch": 0.12, "grad_norm": 0.2567080044949908, "learning_rate": 0.0005842979781826717, "loss": 6.0273, "step": 118 }, { "epoch": 0.12, "grad_norm": 0.4190305965377807, "learning_rate": 0.0005840087718301895, "loss": 6.0391, "step": 119 }, { "epoch": 0.12, "grad_norm": 0.3996803869430228, "learning_rate": 0.0005837170076121951, "loss": 5.9531, "step": 120 }, { "epoch": 0.12, "grad_norm": 0.478219248015785, "learning_rate": 0.000583422688466751, "loss": 6.0586, "step": 121 }, { "epoch": 0.12, "grad_norm": 0.40869844309811526, "learning_rate": 0.0005831258173576474, "loss": 6.0117, "step": 122 }, { "epoch": 0.12, "grad_norm": 0.3728598080697978, "learning_rate": 0.0005828263972743733, "loss": 5.9375, "step": 123 }, { "epoch": 0.12, "grad_norm": 0.3560055462882015, "learning_rate": 0.0005825244312320856, "loss": 5.9531, "step": 124 }, { "epoch": 0.12, "grad_norm": 0.40446932887864323, "learning_rate": 0.0005822199222715787, "loss": 5.9609, "step": 125 }, { "epoch": 0.13, "grad_norm": 0.38514065739946723, "learning_rate": 0.000581912873459255, "loss": 5.8594, "step": 126 }, { "epoch": 0.13, "grad_norm": 0.35367576386319416, "learning_rate": 0.0005816032878870921, "loss": 5.9023, "step": 127 }, { "epoch": 0.13, "grad_norm": 0.3341681995122829, "learning_rate": 0.0005812911686726135, "loss": 5.9062, "step": 128 }, { "epoch": 0.13, "grad_norm": 0.3387022688975784, "learning_rate": 0.0005809765189588563, "loss": 5.8945, "step": 129 }, { "epoch": 0.13, "grad_norm": 0.31638659898934757, "learning_rate": 0.0005806593419143395, "loss": 5.8242, "step": 130 }, { "epoch": 0.13, "grad_norm": 0.3229678508227436, "learning_rate": 0.0005803396407330325, "loss": 5.8516, "step": 131 }, { "epoch": 0.13, "grad_norm": 0.35499490868584455, "learning_rate": 0.0005800174186343226, "loss": 5.9258, "step": 132 }, { "epoch": 0.13, "grad_norm": 0.40753171542848754, "learning_rate": 0.0005796926788629828, "loss": 5.8242, "step": 133 }, { "epoch": 0.13, "grad_norm": 0.3625374018348824, "learning_rate": 0.0005793654246891389, "loss": 5.832, "step": 134 }, { "epoch": 0.13, "grad_norm": 0.3583489573569317, "learning_rate": 0.000579035659408237, "loss": 5.8398, "step": 135 }, { "epoch": 0.14, "grad_norm": 0.39657706318861896, "learning_rate": 0.0005787033863410095, "loss": 5.8633, "step": 136 }, { "epoch": 0.14, "grad_norm": 0.3965837889564036, "learning_rate": 0.0005783686088334428, "loss": 5.8633, "step": 137 }, { "epoch": 0.14, "grad_norm": 0.29496474301865566, "learning_rate": 0.0005780313302567424, "loss": 5.8203, "step": 138 }, { "epoch": 0.14, "grad_norm": 0.44637192639243695, "learning_rate": 0.0005776915540073001, "loss": 5.8477, "step": 139 }, { "epoch": 0.14, "grad_norm": 0.39605473508683114, "learning_rate": 0.0005773492835066587, "loss": 5.7383, "step": 140 }, { "epoch": 0.14, "grad_norm": 0.3008962634266945, "learning_rate": 0.0005770045222014786, "loss": 5.7617, "step": 141 }, { "epoch": 0.14, "grad_norm": 0.36915495506607826, "learning_rate": 0.0005766572735635022, "loss": 5.7695, "step": 142 }, { "epoch": 0.14, "grad_norm": 0.3282300349560706, "learning_rate": 0.0005763075410895193, "loss": 5.8281, "step": 143 }, { "epoch": 0.14, "grad_norm": 0.2747449814083844, "learning_rate": 0.0005759553283013323, "loss": 5.7812, "step": 144 }, { "epoch": 0.14, "grad_norm": 0.28905882704179764, "learning_rate": 0.00057560063874572, "loss": 5.7344, "step": 145 }, { "epoch": 0.15, "grad_norm": 0.280625988867192, "learning_rate": 0.000575243475994402, "loss": 5.7773, "step": 146 }, { "epoch": 0.15, "grad_norm": 0.41061863948012467, "learning_rate": 0.0005748838436440035, "loss": 5.7578, "step": 147 }, { "epoch": 0.15, "grad_norm": 0.4920152483870267, "learning_rate": 0.0005745217453160183, "loss": 5.7305, "step": 148 }, { "epoch": 0.15, "grad_norm": 0.5463207978955044, "learning_rate": 0.0005741571846567725, "loss": 5.7383, "step": 149 }, { "epoch": 0.15, "grad_norm": 0.3986359831157306, "learning_rate": 0.0005737901653373878, "loss": 5.668, "step": 150 }, { "epoch": 0.15, "grad_norm": 0.37908758170100293, "learning_rate": 0.0005734206910537447, "loss": 5.6875, "step": 151 }, { "epoch": 0.15, "grad_norm": 0.35929793070492694, "learning_rate": 0.0005730487655264451, "loss": 5.7188, "step": 152 }, { "epoch": 0.15, "grad_norm": 0.4217799574145456, "learning_rate": 0.0005726743925007751, "loss": 5.7305, "step": 153 }, { "epoch": 0.15, "grad_norm": 0.4024411981587195, "learning_rate": 0.0005722975757466667, "loss": 5.6289, "step": 154 }, { "epoch": 0.15, "grad_norm": 0.3472391905877033, "learning_rate": 0.0005719183190586606, "loss": 5.6523, "step": 155 }, { "epoch": 0.16, "grad_norm": 0.31752956812138816, "learning_rate": 0.0005715366262558675, "loss": 5.6172, "step": 156 }, { "epoch": 0.16, "grad_norm": 0.3170152384332457, "learning_rate": 0.0005711525011819294, "loss": 5.6172, "step": 157 }, { "epoch": 0.16, "grad_norm": 0.40520629326601837, "learning_rate": 0.0005707659477049818, "loss": 5.625, "step": 158 }, { "epoch": 0.16, "grad_norm": 0.3965976910198806, "learning_rate": 0.0005703769697176137, "loss": 5.6562, "step": 159 }, { "epoch": 0.16, "grad_norm": 0.40422960541801994, "learning_rate": 0.0005699855711368293, "loss": 5.6836, "step": 160 }, { "epoch": 0.16, "grad_norm": 0.3780813184050647, "learning_rate": 0.0005695917559040079, "loss": 5.5938, "step": 161 }, { "epoch": 0.16, "grad_norm": 0.36917638857736573, "learning_rate": 0.0005691955279848645, "loss": 5.668, "step": 162 }, { "epoch": 0.16, "grad_norm": 0.37769176081037814, "learning_rate": 0.0005687968913694098, "loss": 5.4961, "step": 163 }, { "epoch": 0.16, "grad_norm": 0.3255116524991148, "learning_rate": 0.0005683958500719103, "loss": 5.5117, "step": 164 }, { "epoch": 0.16, "grad_norm": 0.31897629016848805, "learning_rate": 0.0005679924081308471, "loss": 5.5664, "step": 165 }, { "epoch": 0.17, "grad_norm": 0.2869064236553046, "learning_rate": 0.0005675865696088764, "loss": 5.5391, "step": 166 }, { "epoch": 0.17, "grad_norm": 0.29226729022634845, "learning_rate": 0.0005671783385927873, "loss": 5.5586, "step": 167 }, { "epoch": 0.17, "grad_norm": 0.2534117210955766, "learning_rate": 0.0005667677191934618, "loss": 5.5312, "step": 168 }, { "epoch": 0.17, "grad_norm": 0.289828484125484, "learning_rate": 0.0005663547155458326, "loss": 5.6484, "step": 169 }, { "epoch": 0.17, "grad_norm": 0.2717242930342115, "learning_rate": 0.0005659393318088419, "loss": 5.5352, "step": 170 }, { "epoch": 0.17, "grad_norm": 0.3595538109137759, "learning_rate": 0.0005655215721653993, "loss": 5.5742, "step": 171 }, { "epoch": 0.17, "grad_norm": 0.4255054350471108, "learning_rate": 0.0005651014408223398, "loss": 5.5469, "step": 172 }, { "epoch": 0.17, "grad_norm": 0.3670561941219979, "learning_rate": 0.0005646789420103814, "loss": 5.5078, "step": 173 }, { "epoch": 0.17, "grad_norm": 0.40280130904983164, "learning_rate": 0.0005642540799840822, "loss": 5.5, "step": 174 }, { "epoch": 0.17, "grad_norm": 0.41159472035983025, "learning_rate": 0.0005638268590217984, "loss": 5.5039, "step": 175 }, { "epoch": 0.18, "grad_norm": 0.4316778037513652, "learning_rate": 0.0005633972834256401, "loss": 5.5352, "step": 176 }, { "epoch": 0.18, "grad_norm": 0.5674781128363939, "learning_rate": 0.000562965357521429, "loss": 5.4336, "step": 177 }, { "epoch": 0.18, "grad_norm": 0.41654662151365446, "learning_rate": 0.0005625310856586541, "loss": 5.6211, "step": 178 }, { "epoch": 0.18, "grad_norm": 0.5159976364107484, "learning_rate": 0.0005620944722104282, "loss": 5.4844, "step": 179 }, { "epoch": 0.18, "grad_norm": 0.34364678177014185, "learning_rate": 0.0005616555215734438, "loss": 5.4922, "step": 180 }, { "epoch": 0.18, "grad_norm": 0.3708077784459011, "learning_rate": 0.0005612142381679289, "loss": 5.5234, "step": 181 }, { "epoch": 0.18, "grad_norm": 0.3620051253453866, "learning_rate": 0.0005607706264376028, "loss": 5.4961, "step": 182 }, { "epoch": 0.18, "grad_norm": 0.34735585210929654, "learning_rate": 0.0005603246908496305, "loss": 5.4453, "step": 183 }, { "epoch": 0.18, "grad_norm": 0.37719874705792217, "learning_rate": 0.0005598764358945783, "loss": 5.4844, "step": 184 }, { "epoch": 0.18, "grad_norm": 0.3749130664831207, "learning_rate": 0.0005594258660863689, "loss": 5.4648, "step": 185 }, { "epoch": 0.19, "grad_norm": 0.40951353306235827, "learning_rate": 0.0005589729859622351, "loss": 5.5039, "step": 186 }, { "epoch": 0.19, "grad_norm": 0.40146882563949804, "learning_rate": 0.0005585178000826745, "loss": 5.3672, "step": 187 }, { "epoch": 0.19, "grad_norm": 0.4062987628428303, "learning_rate": 0.0005580603130314043, "loss": 5.3984, "step": 188 }, { "epoch": 0.19, "grad_norm": 0.35626322654799136, "learning_rate": 0.0005576005294153138, "loss": 5.3984, "step": 189 }, { "epoch": 0.19, "grad_norm": 0.3140647930801716, "learning_rate": 0.0005571384538644188, "loss": 5.3906, "step": 190 }, { "epoch": 0.19, "grad_norm": 0.2990060538353662, "learning_rate": 0.0005566740910318153, "loss": 5.3711, "step": 191 }, { "epoch": 0.19, "grad_norm": 0.3337525907515936, "learning_rate": 0.0005562074455936315, "loss": 5.4023, "step": 192 }, { "epoch": 0.19, "grad_norm": 0.3381587051014816, "learning_rate": 0.000555738522248982, "loss": 5.4414, "step": 193 }, { "epoch": 0.19, "grad_norm": 0.2954008999469894, "learning_rate": 0.0005552673257199197, "loss": 5.418, "step": 194 }, { "epoch": 0.19, "grad_norm": 0.3242310900810155, "learning_rate": 0.0005547938607513882, "loss": 5.418, "step": 195 }, { "epoch": 0.2, "grad_norm": 0.3149021804393678, "learning_rate": 0.0005543181321111747, "loss": 5.4375, "step": 196 }, { "epoch": 0.2, "grad_norm": 0.32859412218218814, "learning_rate": 0.0005538401445898612, "loss": 5.4492, "step": 197 }, { "epoch": 0.2, "grad_norm": 0.2960282598050701, "learning_rate": 0.0005533599030007768, "loss": 5.3867, "step": 198 }, { "epoch": 0.2, "grad_norm": 0.2866762878199755, "learning_rate": 0.0005528774121799489, "loss": 5.3789, "step": 199 }, { "epoch": 0.2, "grad_norm": 0.34865216327038784, "learning_rate": 0.0005523926769860549, "loss": 5.3711, "step": 200 } ], "logging_steps": 1, "max_steps": 1000, "num_input_tokens_seen": 0, "num_train_epochs": 1, "save_steps": 100, "total_flos": 0.0, "train_batch_size": 32, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:bbd9a6067cf818494e2505097746a1cad30533fc72eb13916de34f7671e3e456size 6520123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604#!/usr/bin/env python
# Copyright (c) Microsoft Corporation.# SPDX-License-Identifier: Apache-2.0
# DeepSpeed Team
# This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets# copied into the top level checkpoint dir, so the user can easily do the conversion at any point in# the future. Once extracted, the weights don't require DeepSpeed and can be used in any# application.## example: python zero_to_fp32.py . pytorch_model.bin
import argparseimport torchimport globimport mathimport osimport refrom collections import OrderedDictfrom dataclasses import dataclass
# while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with# DeepSpeed data structures it has to be available in the current python environment.from deepspeed.utils import loggerfrom deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS, FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES, FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
@dataclassclass zero_model_state: buffers: dict() param_shapes: dict() shared_params: list ds_version: int frozen_param_shapes: dict() frozen_param_fragments: dict()
debug = 0
# load to cpudevice = torch.device('cpu')
def atoi(text): return int(text) if text.isdigit() else text
def natural_keys(text): ''' alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) ''' return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_model_state_file(checkpoint_dir, zero_stage): if not os.path.isdir(checkpoint_dir): raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
# there should be only one file if zero_stage <= 2: file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt") elif zero_stage == 3: file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
if not os.path.exists(file): raise FileNotFoundError(f"can't find model states file at '{file}'")
return file
def get_checkpoint_files(checkpoint_dir, glob_pattern): # XXX: need to test that this simple glob rule works for multi-node setup too ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
if len(ckpt_files) == 0: raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
return ckpt_files
def get_optim_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
def get_model_state_files(checkpoint_dir): return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
def parse_model_states(files): zero_model_states = [] for file in files: state_dict = torch.load(file, map_location=device)
if BUFFER_NAMES not in state_dict: raise ValueError(f"{file} is not a model state checkpoint") buffer_names = state_dict[BUFFER_NAMES] if debug: print("Found buffers:", buffer_names)
# recover just the buffers while restoring them to fp32 if they were saved in fp16 buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names} param_shapes = state_dict[PARAM_SHAPES]
# collect parameters that are included in param_shapes param_names = [] for s in param_shapes: for name in s.keys(): param_names.append(name)
# update with frozen parameters frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None) if frozen_param_shapes is not None: if debug: print(f"Found frozen_param_shapes: {frozen_param_shapes}") param_names += list(frozen_param_shapes.keys())
# handle shared params shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
ds_version = state_dict.get(DS_VERSION, None)
frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
z_model_state = zero_model_state(buffers=buffers, param_shapes=param_shapes, shared_params=shared_params, ds_version=ds_version, frozen_param_shapes=frozen_param_shapes, frozen_param_fragments=frozen_param_fragments) zero_model_states.append(z_model_state)
return zero_model_states
def parse_optim_states(files, ds_checkpoint_dir):
total_files = len(files) state_dicts = [] for f in files: state_dict = torch.load(f, map_location=device) # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights # and also handle the case where it was already removed by another helper script state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None) state_dicts.append(state_dict)
if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]: raise ValueError(f"{files[0]} is not a zero checkpoint") zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE] world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
# For ZeRO-2 each param group can have different partition_count as data parallelism for expert # parameters can be different from data parallelism for non-expert parameters. So we can just # use the max of the partition_count to get the dp world_size.
if type(world_size) is list: world_size = max(world_size)
if world_size != total_files: raise ValueError( f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. " "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes." )
# the groups are named differently in each stage if zero_stage <= 2: fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS elif zero_stage == 3: fp32_groups_key = FP32_FLAT_GROUPS else: raise ValueError(f"unknown zero stage {zero_stage}")
if zero_stage <= 2: fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))] elif zero_stage == 3: # if there is more than one param group, there will be multiple flattened tensors - one # flattened tensor per group - for simplicity merge them into a single tensor # # XXX: could make the script more memory efficient for when there are multiple groups - it # will require matching the sub-lists of param_shapes for each param group flattened tensor
fp32_flat_groups = [ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts)) ]
return zero_stage, world_size, fp32_flat_groups
def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters): """ Returns fp32 state_dict reconstructed from ds checkpoint
Args: - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
""" print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
optim_files = get_optim_files(ds_checkpoint_dir) zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir) print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
model_files = get_model_state_files(ds_checkpoint_dir)
zero_model_states = parse_model_states(model_files) print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
if zero_stage <= 2: return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters) elif zero_stage == 3: return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters)
def _zero2_merge_frozen_params(state_dict, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
frozen_param_shapes = zero_model_states[0].frozen_param_shapes frozen_param_fragments = zero_model_states[0].frozen_param_fragments
if debug: num_elem = sum(s.numel() for s in frozen_param_shapes.values()) print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in frozen_param_fragments.values()]) print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
state_dict[name] = frozen_param_fragments[name]
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _has_callable(obj, fn): attr = getattr(obj, fn, None) return callable(attr)
def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes
# Reconstruction protocol: # # XXX: document this
if debug: for i in range(world_size): for j in range(len(fp32_flat_groups[0])): print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
# XXX: memory usage doubles here (zero2) num_param_groups = len(fp32_flat_groups[0]) merged_single_partition_of_fp32_groups = [] for i in range(num_param_groups): merged_partitions = [sd[i] for sd in fp32_flat_groups] full_single_fp32_vector = torch.cat(merged_partitions, 0) merged_single_partition_of_fp32_groups.append(full_single_fp32_vector) avail_numel = sum( [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
if debug: wanted_params = sum([len(shapes) for shapes in param_shapes]) wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes]) # not asserting if there is a mismatch due to possible padding print(f"Have {avail_numel} numels to process.") print(f"Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution total_numel = 0 total_params = 0 for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups): offset = 0 avail_numel = full_single_fp32_vector.numel() for name, shape in shapes.items():
unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape) total_numel += unpartitioned_numel total_params += 1
if debug: print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ") state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape) offset += unpartitioned_numel
# Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex # paddings performed in the code it's almost impossible to predict the exact numbers w/o the # live optimizer object, so we are checking that the numbers are within the right range align_to = 2 * world_size
def zero2_align(x): return align_to * math.ceil(x / align_to)
if debug: print(f"original offset={offset}, avail_numel={avail_numel}")
offset = zero2_align(offset) avail_numel = zero2_align(avail_numel)
if debug: print(f"aligned offset={offset}, avail_numel={avail_numel}")
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero2_merge_frozen_params(state_dict, zero_model_states)
_zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def zero3_partitioned_param_info(unpartitioned_numel, world_size): remainder = unpartitioned_numel % world_size padding_numel = (world_size - remainder) if remainder else 0 partitioned_numel = math.ceil(unpartitioned_numel / world_size) return partitioned_numel, padding_numel
def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states): if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0: return
if debug: for i in range(world_size): num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values()) print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
frozen_param_shapes = zero_model_states[0].frozen_param_shapes wanted_params = len(frozen_param_shapes) wanted_numel = sum(s.numel() for s in frozen_param_shapes.values()) avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size print(f'Frozen params: Have {avail_numel} numels to process.') print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
total_params = 0 total_numel = 0 for name, shape in zero_model_states[0].frozen_param_shapes.items(): total_params += 1 unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel
param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states) state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states): param_shapes = zero_model_states[0].param_shapes avail_numel = fp32_flat_groups[0].numel() * world_size # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each # param, re-consolidating each param, while dealing with padding if any
# merge list of dicts, preserving order param_shapes = {k: v for d in param_shapes for k, v in d.items()}
if debug: for i in range(world_size): print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
wanted_params = len(param_shapes) wanted_numel = sum(shape.numel() for shape in param_shapes.values()) # not asserting if there is a mismatch due to possible padding avail_numel = fp32_flat_groups[0].numel() * world_size print(f"Trainable params: Have {avail_numel} numels to process.") print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
# params # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support # out-of-core computing solution offset = 0 total_numel = 0 total_params = 0 for name, shape in param_shapes.items():
unpartitioned_numel = shape.numel() total_numel += unpartitioned_numel total_params += 1
partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
if debug: print( f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}" )
# XXX: memory usage doubles here state_dict[name] = torch.cat( tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)), 0).narrow(0, 0, unpartitioned_numel).view(shape) offset += partitioned_numel
offset *= world_size
# Sanity check if offset != avail_numel: raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states, exclude_frozen_parameters): state_dict = OrderedDict()
# buffers buffers = zero_model_states[0].buffers state_dict.update(buffers) if debug: print(f"added {len(buffers)} buffers")
if not exclude_frozen_parameters: _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
_zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
# recover shared parameters for pair in zero_model_states[0].shared_params: if pair[1] in state_dict: state_dict[pair[0]] = state_dict[pair[1]]
return state_dict
def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example via a model hub.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters
Returns: - pytorch ``state_dict``
Note: this approach may not work if your application doesn't have sufficient free CPU memory and you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with the checkpoint.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint # do the training and checkpoint saving state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu model = model.cpu() # move to cpu model.load_state_dict(state_dict) # submit to model hub or save the model to share with others
In this example the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
""" if tag is None: latest_path = os.path.join(checkpoint_dir, 'latest') if os.path.isfile(latest_path): with open(latest_path, 'r') as fd: tag = fd.read().strip() else: raise ValueError(f"Unable to find 'latest' file at {latest_path}")
ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
if not os.path.isdir(ds_checkpoint_dir): raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False): """ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
Args: - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14`` - ``exclude_frozen_parameters``: exclude frozen parameters """
state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters) print(f"Saving fp32 state dict to {output_file}") torch.save(state_dict, output_file)
def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None): """ 1. Put the provided model to cpu 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` 3. Load it into the provided model
Args: - ``model``: the model object to update - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``) - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
Returns: - ``model`: modified model
Make sure you have plenty of CPU memory available before you call this function. If you don't have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it conveniently placed for you in the checkpoint folder.
A typical usage might be ::
from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir) # submit to model hub or save the model to share with others
Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context of the same application. i.e. you will need to re-initialize the deepspeed engine, since ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
""" logger.info(f"Extracting fp32 weights") state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
logger.info(f"Overwriting model with fp32 weights") model = model.cpu() model.load_state_dict(state_dict, strict=False)
return model
if __name__ == "__main__":
parser = argparse.ArgumentParser() parser.add_argument("checkpoint_dir", type=str, help="path to the desired checkpoint folder, e.g., path/checkpoint-12") parser.add_argument( "output_file", type=str, help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)") parser.add_argument("-t", "--tag", type=str, default=None, help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1") parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters") parser.add_argument("-d", "--debug", action='store_true', help="enable debug") args = parser.parse_args()
debug = args.debug
convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag, exclude_frozen_parameters=args.exclude_frozen_parameters)12345678910111213141516171819202122232425262728293031{ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5", "architectures": [ "GPTNeoXForCausalLM" ], "attention_bias": true, "attention_dropout": 0.0, "bos_token_id": 0, "classifier_dropout": 0.1, "eos_token_id": 2, "hidden_act": "gelu", "hidden_dropout": 0.0, "hidden_size": 768, "initializer_range": 0.02, "intermediate_size": 3072, "layer_norm_eps": 1e-05, "layer_norm_epsilon": 1e-05, "max_position_embeddings": 1024, "model_type": "gpt_neox", "num_attention_heads": 12, "num_hidden_layers": 12, "rope_scaling": null, "rotary_emb_base": 10000, "rotary_pct": 0.25, "tie_word_embeddings": false, "torch_dtype": "bfloat16", "transformers_version": "4.38.2", "use_cache": true, "use_parallel_residual": true, "vocab_size": 50304}.gitattributesAdded+35
checkpoint-10/config.jsonAdded+31
checkpoint-10/generation_config.jsonAdded+6
checkpoint-10/global_step10/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoint-10/global_step10/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoint-10/global_step10/mp_rank_00_model_states.ptAdded+3
checkpoint-10/latestAdded+1
checkpoint-10/model.safetensorsAdded+3
checkpoint-10/rng_state_0.pthAdded+3
checkpoint-10/rng_state_1.pthAdded+3
checkpoint-10/trainer_state.jsonAdded+91
checkpoint-10/training_args.binAdded+3
checkpoint-10/zero_to_fp32.pyAdded+604
checkpoint-100/config.jsonAdded+31
checkpoint-100/generation_config.jsonAdded+6
checkpoint-100/global_step100/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoint-100/global_step100/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoint-100/global_step100/mp_rank_00_model_states.ptAdded+3
checkpoint-100/latestAdded+1
checkpoint-100/model.safetensorsAdded+3
checkpoint-100/rng_state_0.pthAdded+3
checkpoint-100/rng_state_1.pthAdded+3
checkpoint-100/trainer_state.jsonAdded+721
checkpoint-100/training_args.binAdded+3
checkpoint-100/zero_to_fp32.pyAdded+604
checkpoint-20/config.jsonAdded+31
checkpoint-20/generation_config.jsonAdded+6
checkpoint-20/global_step20/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoint-20/global_step20/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoint-20/global_step20/mp_rank_00_model_states.ptAdded+3
checkpoint-20/latestAdded+1
checkpoint-20/model.safetensorsAdded+3
checkpoint-20/rng_state_0.pthAdded+3
checkpoint-20/rng_state_1.pthAdded+3
checkpoint-20/trainer_state.jsonAdded+161
checkpoint-20/training_args.binAdded+3
checkpoint-20/zero_to_fp32.pyAdded+604
checkpoint-200/config.jsonAdded+31
checkpoint-200/generation_config.jsonAdded+6
checkpoint-200/global_step200/bf16_zero_pp_rank_0_mp_rank_00_optim_states.ptAdded+3
checkpoint-200/global_step200/bf16_zero_pp_rank_1_mp_rank_00_optim_states.ptAdded+3
checkpoint-200/global_step200/mp_rank_00_model_states.ptAdded+3
checkpoint-200/latestAdded+1
checkpoint-200/model.safetensorsAdded+3
checkpoint-200/rng_state_0.pthAdded+3
checkpoint-200/rng_state_1.pthAdded+3
checkpoint-200/trainer_state.jsonAdded+1421
checkpoint-200/training_args.binAdded+3
checkpoint-200/zero_to_fp32.pyAdded+604
checkpoint-25/config.jsonAdded+31