svwingerden georgeyw commited on
Commit
5326b39
0 Parent(s):

Duplicate from georgeyw/gpt-2-small-testing

Browse files

Co-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) hide show
  1. .gitattributes +35 -0
  2. checkpoint-10/config.json +31 -0
  3. checkpoint-10/generation_config.json +6 -0
  4. checkpoint-10/global_step10/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  5. checkpoint-10/global_step10/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  6. checkpoint-10/global_step10/mp_rank_00_model_states.pt +3 -0
  7. checkpoint-10/latest +1 -0
  8. checkpoint-10/model.safetensors +3 -0
  9. checkpoint-10/rng_state_0.pth +3 -0
  10. checkpoint-10/rng_state_1.pth +3 -0
  11. checkpoint-10/trainer_state.json +91 -0
  12. checkpoint-10/training_args.bin +3 -0
  13. checkpoint-10/zero_to_fp32.py +604 -0
  14. checkpoint-100/config.json +31 -0
  15. checkpoint-100/generation_config.json +6 -0
  16. checkpoint-100/global_step100/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  17. checkpoint-100/global_step100/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  18. checkpoint-100/global_step100/mp_rank_00_model_states.pt +3 -0
  19. checkpoint-100/latest +1 -0
  20. checkpoint-100/model.safetensors +3 -0
  21. checkpoint-100/rng_state_0.pth +3 -0
  22. checkpoint-100/rng_state_1.pth +3 -0
  23. checkpoint-100/trainer_state.json +721 -0
  24. checkpoint-100/training_args.bin +3 -0
  25. checkpoint-100/zero_to_fp32.py +604 -0
  26. checkpoint-20/config.json +31 -0
  27. checkpoint-20/generation_config.json +6 -0
  28. checkpoint-20/global_step20/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  29. checkpoint-20/global_step20/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  30. checkpoint-20/global_step20/mp_rank_00_model_states.pt +3 -0
  31. checkpoint-20/latest +1 -0
  32. checkpoint-20/model.safetensors +3 -0
  33. checkpoint-20/rng_state_0.pth +3 -0
  34. checkpoint-20/rng_state_1.pth +3 -0
  35. checkpoint-20/trainer_state.json +161 -0
  36. checkpoint-20/training_args.bin +3 -0
  37. checkpoint-20/zero_to_fp32.py +604 -0
  38. checkpoint-200/config.json +31 -0
  39. checkpoint-200/generation_config.json +6 -0
  40. checkpoint-200/global_step200/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt +3 -0
  41. checkpoint-200/global_step200/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt +3 -0
  42. checkpoint-200/global_step200/mp_rank_00_model_states.pt +3 -0
  43. checkpoint-200/latest +1 -0
  44. checkpoint-200/model.safetensors +3 -0
  45. checkpoint-200/rng_state_0.pth +3 -0
  46. checkpoint-200/rng_state_1.pth +3 -0
  47. checkpoint-200/trainer_state.json +1421 -0
  48. checkpoint-200/training_args.bin +3 -0
  49. checkpoint-200/zero_to_fp32.py +604 -0
  50. checkpoint-25/config.json +31 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
checkpoint-10/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5",
3
+ "architectures": [
4
+ "GPTNeoXForCausalLM"
5
+ ],
6
+ "attention_bias": true,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 0,
9
+ "classifier_dropout": 0.1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout": 0.0,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "layer_norm_eps": 1e-05,
17
+ "layer_norm_epsilon": 1e-05,
18
+ "max_position_embeddings": 1024,
19
+ "model_type": "gpt_neox",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "rope_scaling": null,
23
+ "rotary_emb_base": 10000,
24
+ "rotary_pct": 0.25,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.38.2",
28
+ "use_cache": true,
29
+ "use_parallel_residual": true,
30
+ "vocab_size": 50304
31
+ }
checkpoint-10/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.38.2"
6
+ }
checkpoint-10/global_step10/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed0df787a125d81094d867c743d5ffebb34766f877f42e3b5da9ad0e51fbf81e
3
+ size 973946896
checkpoint-10/global_step10/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f6768e7d81521ef703a230f41460e04972f79ded2de3b754bcd0fb7a96f4ff0
3
+ size 973946832
checkpoint-10/global_step10/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7589ffd4359a842efe83dc7cc5ce4ff6a161f1fce829498ade432719a3c40d91
3
+ size 324689964
checkpoint-10/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step10
checkpoint-10/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6ba4e69094dffe72d300db52887b581d271c61d1a95702fdea83bf7d6d5697f
3
+ size 324662984
checkpoint-10/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530
3
+ size 14512
checkpoint-10/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82
3
+ size 14512
checkpoint-10/trainer_state.json ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 0.009995002498750625,
5
+ "eval_steps": 500,
6
+ "global_step": 10,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.0,
13
+ "grad_norm": 3.3340553137590683,
14
+ "learning_rate": 0.0,
15
+ "loss": 11.0,
16
+ "step": 1
17
+ },
18
+ {
19
+ "epoch": 0.0,
20
+ "grad_norm": 2.398799707355898,
21
+ "learning_rate": 5.9999999999999995e-05,
22
+ "loss": 10.125,
23
+ "step": 2
24
+ },
25
+ {
26
+ "epoch": 0.0,
27
+ "grad_norm": 2.3943029297945575,
28
+ "learning_rate": 0.00011999999999999999,
29
+ "loss": 10.1172,
30
+ "step": 3
31
+ },
32
+ {
33
+ "epoch": 0.0,
34
+ "grad_norm": 1.9959117709404242,
35
+ "learning_rate": 0.00017999999999999998,
36
+ "loss": 9.875,
37
+ "step": 4
38
+ },
39
+ {
40
+ "epoch": 0.0,
41
+ "grad_norm": 1.8270696218303057,
42
+ "learning_rate": 0.00023999999999999998,
43
+ "loss": 9.6641,
44
+ "step": 5
45
+ },
46
+ {
47
+ "epoch": 0.01,
48
+ "grad_norm": 1.7854351602113614,
49
+ "learning_rate": 0.0003,
50
+ "loss": 9.4844,
51
+ "step": 6
52
+ },
53
+ {
54
+ "epoch": 0.01,
55
+ "grad_norm": 1.7194174424274788,
56
+ "learning_rate": 0.00035999999999999997,
57
+ "loss": 9.3281,
58
+ "step": 7
59
+ },
60
+ {
61
+ "epoch": 0.01,
62
+ "grad_norm": 1.463772638994466,
63
+ "learning_rate": 0.00041999999999999996,
64
+ "loss": 9.2109,
65
+ "step": 8
66
+ },
67
+ {
68
+ "epoch": 0.01,
69
+ "grad_norm": 1.439323678271545,
70
+ "learning_rate": 0.00047999999999999996,
71
+ "loss": 8.9453,
72
+ "step": 9
73
+ },
74
+ {
75
+ "epoch": 0.01,
76
+ "grad_norm": 1.2936126396494727,
77
+ "learning_rate": 0.00054,
78
+ "loss": 8.7109,
79
+ "step": 10
80
+ }
81
+ ],
82
+ "logging_steps": 1,
83
+ "max_steps": 1000,
84
+ "num_input_tokens_seen": 0,
85
+ "num_train_epochs": 1,
86
+ "save_steps": 10,
87
+ "total_flos": 0.0,
88
+ "train_batch_size": 32,
89
+ "trial_name": null,
90
+ "trial_params": null
91
+ }
checkpoint-10/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95cc4290cc90782d57f7376defd26743b3a36943fc93e80e2734385bc57e8b78
3
+ size 6520
checkpoint-10/zero_to_fp32.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
215
+ exclude_frozen_parameters)
216
+ elif zero_stage == 3:
217
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
218
+ exclude_frozen_parameters)
219
+
220
+
221
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
222
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
223
+ return
224
+
225
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
226
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
227
+
228
+ if debug:
229
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
230
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
231
+
232
+ wanted_params = len(frozen_param_shapes)
233
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
234
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
235
+ print(f'Frozen params: Have {avail_numel} numels to process.')
236
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
237
+
238
+ total_params = 0
239
+ total_numel = 0
240
+ for name, shape in frozen_param_shapes.items():
241
+ total_params += 1
242
+ unpartitioned_numel = shape.numel()
243
+ total_numel += unpartitioned_numel
244
+
245
+ state_dict[name] = frozen_param_fragments[name]
246
+
247
+ if debug:
248
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
249
+
250
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
251
+
252
+
253
+ def _has_callable(obj, fn):
254
+ attr = getattr(obj, fn, None)
255
+ return callable(attr)
256
+
257
+
258
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
259
+ param_shapes = zero_model_states[0].param_shapes
260
+
261
+ # Reconstruction protocol:
262
+ #
263
+ # XXX: document this
264
+
265
+ if debug:
266
+ for i in range(world_size):
267
+ for j in range(len(fp32_flat_groups[0])):
268
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
269
+
270
+ # XXX: memory usage doubles here (zero2)
271
+ num_param_groups = len(fp32_flat_groups[0])
272
+ merged_single_partition_of_fp32_groups = []
273
+ for i in range(num_param_groups):
274
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
275
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
276
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
277
+ avail_numel = sum(
278
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
279
+
280
+ if debug:
281
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
282
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
283
+ # not asserting if there is a mismatch due to possible padding
284
+ print(f"Have {avail_numel} numels to process.")
285
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
286
+
287
+ # params
288
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
289
+ # out-of-core computing solution
290
+ total_numel = 0
291
+ total_params = 0
292
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
293
+ offset = 0
294
+ avail_numel = full_single_fp32_vector.numel()
295
+ for name, shape in shapes.items():
296
+
297
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
298
+ total_numel += unpartitioned_numel
299
+ total_params += 1
300
+
301
+ if debug:
302
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
303
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
304
+ offset += unpartitioned_numel
305
+
306
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
307
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
308
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
309
+ # live optimizer object, so we are checking that the numbers are within the right range
310
+ align_to = 2 * world_size
311
+
312
+ def zero2_align(x):
313
+ return align_to * math.ceil(x / align_to)
314
+
315
+ if debug:
316
+ print(f"original offset={offset}, avail_numel={avail_numel}")
317
+
318
+ offset = zero2_align(offset)
319
+ avail_numel = zero2_align(avail_numel)
320
+
321
+ if debug:
322
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
323
+
324
+ # Sanity check
325
+ if offset != avail_numel:
326
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
327
+
328
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
329
+
330
+
331
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
332
+ exclude_frozen_parameters):
333
+ state_dict = OrderedDict()
334
+
335
+ # buffers
336
+ buffers = zero_model_states[0].buffers
337
+ state_dict.update(buffers)
338
+ if debug:
339
+ print(f"added {len(buffers)} buffers")
340
+
341
+ if not exclude_frozen_parameters:
342
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
343
+
344
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
345
+
346
+ # recover shared parameters
347
+ for pair in zero_model_states[0].shared_params:
348
+ if pair[1] in state_dict:
349
+ state_dict[pair[0]] = state_dict[pair[1]]
350
+
351
+ return state_dict
352
+
353
+
354
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
355
+ remainder = unpartitioned_numel % world_size
356
+ padding_numel = (world_size - remainder) if remainder else 0
357
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
358
+ return partitioned_numel, padding_numel
359
+
360
+
361
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
362
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
363
+ return
364
+
365
+ if debug:
366
+ for i in range(world_size):
367
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
368
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
369
+
370
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
371
+ wanted_params = len(frozen_param_shapes)
372
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
373
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
374
+ print(f'Frozen params: Have {avail_numel} numels to process.')
375
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
376
+
377
+ total_params = 0
378
+ total_numel = 0
379
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
380
+ total_params += 1
381
+ unpartitioned_numel = shape.numel()
382
+ total_numel += unpartitioned_numel
383
+
384
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
385
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
386
+
387
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
388
+
389
+ if debug:
390
+ print(
391
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
392
+ )
393
+
394
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
395
+
396
+
397
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
398
+ param_shapes = zero_model_states[0].param_shapes
399
+ avail_numel = fp32_flat_groups[0].numel() * world_size
400
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
401
+ # param, re-consolidating each param, while dealing with padding if any
402
+
403
+ # merge list of dicts, preserving order
404
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
405
+
406
+ if debug:
407
+ for i in range(world_size):
408
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
409
+
410
+ wanted_params = len(param_shapes)
411
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
412
+ # not asserting if there is a mismatch due to possible padding
413
+ avail_numel = fp32_flat_groups[0].numel() * world_size
414
+ print(f"Trainable params: Have {avail_numel} numels to process.")
415
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
416
+
417
+ # params
418
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
419
+ # out-of-core computing solution
420
+ offset = 0
421
+ total_numel = 0
422
+ total_params = 0
423
+ for name, shape in param_shapes.items():
424
+
425
+ unpartitioned_numel = shape.numel()
426
+ total_numel += unpartitioned_numel
427
+ total_params += 1
428
+
429
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
430
+
431
+ if debug:
432
+ print(
433
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
434
+ )
435
+
436
+ # XXX: memory usage doubles here
437
+ state_dict[name] = torch.cat(
438
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
439
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
440
+ offset += partitioned_numel
441
+
442
+ offset *= world_size
443
+
444
+ # Sanity check
445
+ if offset != avail_numel:
446
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
447
+
448
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
449
+
450
+
451
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
452
+ exclude_frozen_parameters):
453
+ state_dict = OrderedDict()
454
+
455
+ # buffers
456
+ buffers = zero_model_states[0].buffers
457
+ state_dict.update(buffers)
458
+ if debug:
459
+ print(f"added {len(buffers)} buffers")
460
+
461
+ if not exclude_frozen_parameters:
462
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
463
+
464
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
465
+
466
+ # recover shared parameters
467
+ for pair in zero_model_states[0].shared_params:
468
+ if pair[1] in state_dict:
469
+ state_dict[pair[0]] = state_dict[pair[1]]
470
+
471
+ return state_dict
472
+
473
+
474
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
475
+ """
476
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
477
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
478
+ via a model hub.
479
+
480
+ Args:
481
+ - ``checkpoint_dir``: path to the desired checkpoint folder
482
+ - ``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``
483
+ - ``exclude_frozen_parameters``: exclude frozen parameters
484
+
485
+ Returns:
486
+ - pytorch ``state_dict``
487
+
488
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
489
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
490
+ the checkpoint.
491
+
492
+ A typical usage might be ::
493
+
494
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
495
+ # do the training and checkpoint saving
496
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
497
+ model = model.cpu() # move to cpu
498
+ model.load_state_dict(state_dict)
499
+ # submit to model hub or save the model to share with others
500
+
501
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
502
+ application. i.e. you will need to re-initialize the deepspeed engine, since
503
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
504
+
505
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
506
+
507
+ """
508
+ if tag is None:
509
+ latest_path = os.path.join(checkpoint_dir, 'latest')
510
+ if os.path.isfile(latest_path):
511
+ with open(latest_path, 'r') as fd:
512
+ tag = fd.read().strip()
513
+ else:
514
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
515
+
516
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
517
+
518
+ if not os.path.isdir(ds_checkpoint_dir):
519
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
520
+
521
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
522
+
523
+
524
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
525
+ """
526
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
527
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
528
+
529
+ Args:
530
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
531
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
532
+ - ``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``
533
+ - ``exclude_frozen_parameters``: exclude frozen parameters
534
+ """
535
+
536
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
537
+ print(f"Saving fp32 state dict to {output_file}")
538
+ torch.save(state_dict, output_file)
539
+
540
+
541
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
542
+ """
543
+ 1. Put the provided model to cpu
544
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
545
+ 3. Load it into the provided model
546
+
547
+ Args:
548
+ - ``model``: the model object to update
549
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
550
+ - ``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``
551
+
552
+ Returns:
553
+ - ``model`: modified model
554
+
555
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
556
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
557
+ conveniently placed for you in the checkpoint folder.
558
+
559
+ A typical usage might be ::
560
+
561
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
562
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
563
+ # submit to model hub or save the model to share with others
564
+
565
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
566
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
567
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
568
+
569
+ """
570
+ logger.info(f"Extracting fp32 weights")
571
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
572
+
573
+ logger.info(f"Overwriting model with fp32 weights")
574
+ model = model.cpu()
575
+ model.load_state_dict(state_dict, strict=False)
576
+
577
+ return model
578
+
579
+
580
+ if __name__ == "__main__":
581
+
582
+ parser = argparse.ArgumentParser()
583
+ parser.add_argument("checkpoint_dir",
584
+ type=str,
585
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
586
+ parser.add_argument(
587
+ "output_file",
588
+ type=str,
589
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
590
+ parser.add_argument("-t",
591
+ "--tag",
592
+ type=str,
593
+ default=None,
594
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
595
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
596
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
597
+ args = parser.parse_args()
598
+
599
+ debug = args.debug
600
+
601
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
602
+ args.output_file,
603
+ tag=args.tag,
604
+ exclude_frozen_parameters=args.exclude_frozen_parameters)
checkpoint-100/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5",
3
+ "architectures": [
4
+ "GPTNeoXForCausalLM"
5
+ ],
6
+ "attention_bias": true,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 0,
9
+ "classifier_dropout": 0.1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout": 0.0,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "layer_norm_eps": 1e-05,
17
+ "layer_norm_epsilon": 1e-05,
18
+ "max_position_embeddings": 1024,
19
+ "model_type": "gpt_neox",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "rope_scaling": null,
23
+ "rotary_emb_base": 10000,
24
+ "rotary_pct": 0.25,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.38.2",
28
+ "use_cache": true,
29
+ "use_parallel_residual": true,
30
+ "vocab_size": 50304
31
+ }
checkpoint-100/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.38.2"
6
+ }
checkpoint-100/global_step100/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f13244aa35b694472ea5bd7fde3bcee569b6a0b7251253f818b7e5ae6a048797
3
+ size 973946896
checkpoint-100/global_step100/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1039a6c333c1647ef2ddfc010c1b966f38d1001aff73ac8b3cdede7858acdc7
3
+ size 973946832
checkpoint-100/global_step100/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26fe4253d323b90c0fa9e0d5da8cb64819f86baf288d72f171c73184ca877562
3
+ size 324689964
checkpoint-100/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step100
checkpoint-100/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4c9a5c8eae560953cb2afb2b3bf5d1330d089af788edaa1bf1d3f77b218837bc
3
+ size 324662984
checkpoint-100/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530
3
+ size 14512
checkpoint-100/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82
3
+ size 14512
checkpoint-100/trainer_state.json ADDED
@@ -0,0 +1,721 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 0.09995002498750624,
5
+ "eval_steps": 500,
6
+ "global_step": 100,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.0,
13
+ "grad_norm": 3.3340563149001086,
14
+ "learning_rate": 0.0,
15
+ "loss": 11.0,
16
+ "step": 1
17
+ },
18
+ {
19
+ "epoch": 0.0,
20
+ "grad_norm": 2.398812329952019,
21
+ "learning_rate": 5.9999999999999995e-05,
22
+ "loss": 10.125,
23
+ "step": 2
24
+ },
25
+ {
26
+ "epoch": 0.0,
27
+ "grad_norm": 2.394322446895115,
28
+ "learning_rate": 0.00011999999999999999,
29
+ "loss": 10.1172,
30
+ "step": 3
31
+ },
32
+ {
33
+ "epoch": 0.0,
34
+ "grad_norm": 1.9958816684399585,
35
+ "learning_rate": 0.00017999999999999998,
36
+ "loss": 9.875,
37
+ "step": 4
38
+ },
39
+ {
40
+ "epoch": 0.0,
41
+ "grad_norm": 1.8270465897882062,
42
+ "learning_rate": 0.00023999999999999998,
43
+ "loss": 9.6641,
44
+ "step": 5
45
+ },
46
+ {
47
+ "epoch": 0.01,
48
+ "grad_norm": 1.7854046471397795,
49
+ "learning_rate": 0.0003,
50
+ "loss": 9.4844,
51
+ "step": 6
52
+ },
53
+ {
54
+ "epoch": 0.01,
55
+ "grad_norm": 1.719416749115252,
56
+ "learning_rate": 0.00035999999999999997,
57
+ "loss": 9.3281,
58
+ "step": 7
59
+ },
60
+ {
61
+ "epoch": 0.01,
62
+ "grad_norm": 1.4637825746112274,
63
+ "learning_rate": 0.00041999999999999996,
64
+ "loss": 9.2109,
65
+ "step": 8
66
+ },
67
+ {
68
+ "epoch": 0.01,
69
+ "grad_norm": 1.4393631015406718,
70
+ "learning_rate": 0.00047999999999999996,
71
+ "loss": 8.9453,
72
+ "step": 9
73
+ },
74
+ {
75
+ "epoch": 0.01,
76
+ "grad_norm": 1.2936734586915988,
77
+ "learning_rate": 0.00054,
78
+ "loss": 8.7109,
79
+ "step": 10
80
+ },
81
+ {
82
+ "epoch": 0.01,
83
+ "grad_norm": 1.0756922378227356,
84
+ "learning_rate": 0.0005999986405514987,
85
+ "loss": 8.4609,
86
+ "step": 11
87
+ },
88
+ {
89
+ "epoch": 0.01,
90
+ "grad_norm": 0.9277829127413892,
91
+ "learning_rate": 0.0005999945622196846,
92
+ "loss": 8.2344,
93
+ "step": 12
94
+ },
95
+ {
96
+ "epoch": 0.01,
97
+ "grad_norm": 0.8084581786682467,
98
+ "learning_rate": 0.0005999877650456265,
99
+ "loss": 8.125,
100
+ "step": 13
101
+ },
102
+ {
103
+ "epoch": 0.01,
104
+ "grad_norm": 0.7635084596900947,
105
+ "learning_rate": 0.000599978249097772,
106
+ "loss": 7.9766,
107
+ "step": 14
108
+ },
109
+ {
110
+ "epoch": 0.01,
111
+ "grad_norm": 0.9186699644247788,
112
+ "learning_rate": 0.0005999660144719463,
113
+ "loss": 7.8555,
114
+ "step": 15
115
+ },
116
+ {
117
+ "epoch": 0.02,
118
+ "grad_norm": 0.6609504256551479,
119
+ "learning_rate": 0.0005999510612913519,
120
+ "loss": 7.7734,
121
+ "step": 16
122
+ },
123
+ {
124
+ "epoch": 0.02,
125
+ "grad_norm": 0.7086232844782971,
126
+ "learning_rate": 0.0005999333897065673,
127
+ "loss": 7.7148,
128
+ "step": 17
129
+ },
130
+ {
131
+ "epoch": 0.02,
132
+ "grad_norm": 16.38048851691348,
133
+ "learning_rate": 0.0005999129998955453,
134
+ "loss": 8.4844,
135
+ "step": 18
136
+ },
137
+ {
138
+ "epoch": 0.02,
139
+ "grad_norm": 1.3057527590449889,
140
+ "learning_rate": 0.0005998898920636111,
141
+ "loss": 7.7539,
142
+ "step": 19
143
+ },
144
+ {
145
+ "epoch": 0.02,
146
+ "grad_norm": 0.6966048242948986,
147
+ "learning_rate": 0.00059986406644346,
148
+ "loss": 7.75,
149
+ "step": 20
150
+ },
151
+ {
152
+ "epoch": 0.02,
153
+ "grad_norm": 0.6348089115348993,
154
+ "learning_rate": 0.0005998355232951559,
155
+ "loss": 7.7031,
156
+ "step": 21
157
+ },
158
+ {
159
+ "epoch": 0.02,
160
+ "grad_norm": 0.7829163518610293,
161
+ "learning_rate": 0.0005998042629061279,
162
+ "loss": 7.6992,
163
+ "step": 22
164
+ },
165
+ {
166
+ "epoch": 0.02,
167
+ "grad_norm": 0.5900591778980369,
168
+ "learning_rate": 0.0005997702855911678,
169
+ "loss": 7.6016,
170
+ "step": 23
171
+ },
172
+ {
173
+ "epoch": 0.02,
174
+ "grad_norm": 0.4655170213064256,
175
+ "learning_rate": 0.0005997335916924268,
176
+ "loss": 7.5977,
177
+ "step": 24
178
+ },
179
+ {
180
+ "epoch": 0.02,
181
+ "grad_norm": 0.6287348258915756,
182
+ "learning_rate": 0.0005996941815794121,
183
+ "loss": 7.5586,
184
+ "step": 25
185
+ },
186
+ {
187
+ "epoch": 0.03,
188
+ "grad_norm": 0.6137321903884564,
189
+ "learning_rate": 0.0005996520556489831,
190
+ "loss": 7.5898,
191
+ "step": 26
192
+ },
193
+ {
194
+ "epoch": 0.03,
195
+ "grad_norm": 0.44962562710631065,
196
+ "learning_rate": 0.0005996072143253473,
197
+ "loss": 7.4336,
198
+ "step": 27
199
+ },
200
+ {
201
+ "epoch": 0.03,
202
+ "grad_norm": 0.46130046454703316,
203
+ "learning_rate": 0.0005995596580600566,
204
+ "loss": 7.4023,
205
+ "step": 28
206
+ },
207
+ {
208
+ "epoch": 0.03,
209
+ "grad_norm": 0.4686712675731326,
210
+ "learning_rate": 0.0005995093873320018,
211
+ "loss": 7.3789,
212
+ "step": 29
213
+ },
214
+ {
215
+ "epoch": 0.03,
216
+ "grad_norm": 0.4672147564288997,
217
+ "learning_rate": 0.0005994564026474087,
218
+ "loss": 7.3711,
219
+ "step": 30
220
+ },
221
+ {
222
+ "epoch": 0.03,
223
+ "grad_norm": 0.40408354581233474,
224
+ "learning_rate": 0.0005994007045398324,
225
+ "loss": 7.3672,
226
+ "step": 31
227
+ },
228
+ {
229
+ "epoch": 0.03,
230
+ "grad_norm": 0.46032146732584733,
231
+ "learning_rate": 0.0005993422935701524,
232
+ "loss": 7.3477,
233
+ "step": 32
234
+ },
235
+ {
236
+ "epoch": 0.03,
237
+ "grad_norm": 0.4765534634593268,
238
+ "learning_rate": 0.0005992811703265664,
239
+ "loss": 7.3555,
240
+ "step": 33
241
+ },
242
+ {
243
+ "epoch": 0.03,
244
+ "grad_norm": 0.46208489386235113,
245
+ "learning_rate": 0.0005992173354245849,
246
+ "loss": 7.3047,
247
+ "step": 34
248
+ },
249
+ {
250
+ "epoch": 0.03,
251
+ "grad_norm": 0.2956144524964961,
252
+ "learning_rate": 0.0005991507895070244,
253
+ "loss": 7.3125,
254
+ "step": 35
255
+ },
256
+ {
257
+ "epoch": 0.04,
258
+ "grad_norm": 0.4834645389868856,
259
+ "learning_rate": 0.0005990815332440017,
260
+ "loss": 7.207,
261
+ "step": 36
262
+ },
263
+ {
264
+ "epoch": 0.04,
265
+ "grad_norm": 0.4411831350968505,
266
+ "learning_rate": 0.0005990095673329266,
267
+ "loss": 7.1758,
268
+ "step": 37
269
+ },
270
+ {
271
+ "epoch": 0.04,
272
+ "grad_norm": 0.24809297748968667,
273
+ "learning_rate": 0.0005989348924984951,
274
+ "loss": 7.2188,
275
+ "step": 38
276
+ },
277
+ {
278
+ "epoch": 0.04,
279
+ "grad_norm": 0.39402988416840584,
280
+ "learning_rate": 0.0005988575094926817,
281
+ "loss": 7.1953,
282
+ "step": 39
283
+ },
284
+ {
285
+ "epoch": 0.04,
286
+ "grad_norm": 0.3868345222189167,
287
+ "learning_rate": 0.0005987774190947328,
288
+ "loss": 7.1641,
289
+ "step": 40
290
+ },
291
+ {
292
+ "epoch": 0.04,
293
+ "grad_norm": 0.3777261230135448,
294
+ "learning_rate": 0.0005986946221111575,
295
+ "loss": 7.1328,
296
+ "step": 41
297
+ },
298
+ {
299
+ "epoch": 0.04,
300
+ "grad_norm": 0.4687511444077827,
301
+ "learning_rate": 0.0005986091193757206,
302
+ "loss": 7.0898,
303
+ "step": 42
304
+ },
305
+ {
306
+ "epoch": 0.04,
307
+ "grad_norm": 0.34935796211612463,
308
+ "learning_rate": 0.0005985209117494337,
309
+ "loss": 7.1367,
310
+ "step": 43
311
+ },
312
+ {
313
+ "epoch": 0.04,
314
+ "grad_norm": 0.38764476686849886,
315
+ "learning_rate": 0.0005984300001205466,
316
+ "loss": 7.125,
317
+ "step": 44
318
+ },
319
+ {
320
+ "epoch": 0.04,
321
+ "grad_norm": 0.3956487898882936,
322
+ "learning_rate": 0.0005983363854045386,
323
+ "loss": 7.1094,
324
+ "step": 45
325
+ },
326
+ {
327
+ "epoch": 0.05,
328
+ "grad_norm": 0.31140257544677513,
329
+ "learning_rate": 0.0005982400685441084,
330
+ "loss": 7.0898,
331
+ "step": 46
332
+ },
333
+ {
334
+ "epoch": 0.05,
335
+ "grad_norm": 0.3664476570531787,
336
+ "learning_rate": 0.0005981410505091662,
337
+ "loss": 7.0664,
338
+ "step": 47
339
+ },
340
+ {
341
+ "epoch": 0.05,
342
+ "grad_norm": 0.31891741142945207,
343
+ "learning_rate": 0.0005980393322968223,
344
+ "loss": 7.0273,
345
+ "step": 48
346
+ },
347
+ {
348
+ "epoch": 0.05,
349
+ "grad_norm": 0.4533529037337155,
350
+ "learning_rate": 0.0005979349149313778,
351
+ "loss": 7.0586,
352
+ "step": 49
353
+ },
354
+ {
355
+ "epoch": 0.05,
356
+ "grad_norm": 0.30532331638835586,
357
+ "learning_rate": 0.0005978277994643147,
358
+ "loss": 7.0195,
359
+ "step": 50
360
+ },
361
+ {
362
+ "epoch": 0.05,
363
+ "grad_norm": 0.6501991746260075,
364
+ "learning_rate": 0.0005977179869742844,
365
+ "loss": 6.9648,
366
+ "step": 51
367
+ },
368
+ {
369
+ "epoch": 0.05,
370
+ "grad_norm": 0.43904455901717926,
371
+ "learning_rate": 0.0005976054785670975,
372
+ "loss": 6.9805,
373
+ "step": 52
374
+ },
375
+ {
376
+ "epoch": 0.05,
377
+ "grad_norm": 0.4826001598483571,
378
+ "learning_rate": 0.0005974902753757124,
379
+ "loss": 6.9297,
380
+ "step": 53
381
+ },
382
+ {
383
+ "epoch": 0.05,
384
+ "grad_norm": 0.2924998027034648,
385
+ "learning_rate": 0.000597372378560224,
386
+ "loss": 6.8984,
387
+ "step": 54
388
+ },
389
+ {
390
+ "epoch": 0.05,
391
+ "grad_norm": 0.4439033666380787,
392
+ "learning_rate": 0.0005972517893078517,
393
+ "loss": 6.8945,
394
+ "step": 55
395
+ },
396
+ {
397
+ "epoch": 0.06,
398
+ "grad_norm": 0.6135914255073411,
399
+ "learning_rate": 0.0005971285088329284,
400
+ "loss": 6.9727,
401
+ "step": 56
402
+ },
403
+ {
404
+ "epoch": 0.06,
405
+ "grad_norm": 0.5575686565598483,
406
+ "learning_rate": 0.0005970025383768866,
407
+ "loss": 6.9219,
408
+ "step": 57
409
+ },
410
+ {
411
+ "epoch": 0.06,
412
+ "grad_norm": 0.4820951675994578,
413
+ "learning_rate": 0.0005968738792082478,
414
+ "loss": 6.8516,
415
+ "step": 58
416
+ },
417
+ {
418
+ "epoch": 0.06,
419
+ "grad_norm": 0.40164190019465584,
420
+ "learning_rate": 0.0005967425326226082,
421
+ "loss": 6.7734,
422
+ "step": 59
423
+ },
424
+ {
425
+ "epoch": 0.06,
426
+ "grad_norm": 0.46129863945181293,
427
+ "learning_rate": 0.0005966084999426265,
428
+ "loss": 6.8125,
429
+ "step": 60
430
+ },
431
+ {
432
+ "epoch": 0.06,
433
+ "grad_norm": 0.33322355827118677,
434
+ "learning_rate": 0.0005964717825180101,
435
+ "loss": 6.7891,
436
+ "step": 61
437
+ },
438
+ {
439
+ "epoch": 0.06,
440
+ "grad_norm": 0.3847525153855558,
441
+ "learning_rate": 0.0005963323817255024,
442
+ "loss": 6.8242,
443
+ "step": 62
444
+ },
445
+ {
446
+ "epoch": 0.06,
447
+ "grad_norm": 0.3384433591375982,
448
+ "learning_rate": 0.0005961902989688674,
449
+ "loss": 6.707,
450
+ "step": 63
451
+ },
452
+ {
453
+ "epoch": 0.06,
454
+ "grad_norm": 0.3937003195165685,
455
+ "learning_rate": 0.000596045535678877,
456
+ "loss": 6.8203,
457
+ "step": 64
458
+ },
459
+ {
460
+ "epoch": 0.06,
461
+ "grad_norm": 0.35423488053528107,
462
+ "learning_rate": 0.0005958980933132962,
463
+ "loss": 6.7383,
464
+ "step": 65
465
+ },
466
+ {
467
+ "epoch": 0.07,
468
+ "grad_norm": 0.36005939745315396,
469
+ "learning_rate": 0.0005957479733568675,
470
+ "loss": 6.7109,
471
+ "step": 66
472
+ },
473
+ {
474
+ "epoch": 0.07,
475
+ "grad_norm": 0.3499278317706933,
476
+ "learning_rate": 0.0005955951773212976,
477
+ "loss": 6.7266,
478
+ "step": 67
479
+ },
480
+ {
481
+ "epoch": 0.07,
482
+ "grad_norm": 0.3708385192137018,
483
+ "learning_rate": 0.0005954397067452407,
484
+ "loss": 6.7617,
485
+ "step": 68
486
+ },
487
+ {
488
+ "epoch": 0.07,
489
+ "grad_norm": 0.3775657656205869,
490
+ "learning_rate": 0.0005952815631942839,
491
+ "loss": 6.7148,
492
+ "step": 69
493
+ },
494
+ {
495
+ "epoch": 0.07,
496
+ "grad_norm": 0.3040083750375816,
497
+ "learning_rate": 0.0005951207482609307,
498
+ "loss": 6.5938,
499
+ "step": 70
500
+ },
501
+ {
502
+ "epoch": 0.07,
503
+ "grad_norm": 0.3443020808841468,
504
+ "learning_rate": 0.0005949572635645861,
505
+ "loss": 6.6523,
506
+ "step": 71
507
+ },
508
+ {
509
+ "epoch": 0.07,
510
+ "grad_norm": 0.3520066316939,
511
+ "learning_rate": 0.0005947911107515389,
512
+ "loss": 6.6211,
513
+ "step": 72
514
+ },
515
+ {
516
+ "epoch": 0.07,
517
+ "grad_norm": 0.3739040572679613,
518
+ "learning_rate": 0.0005946222914949462,
519
+ "loss": 6.5547,
520
+ "step": 73
521
+ },
522
+ {
523
+ "epoch": 0.07,
524
+ "grad_norm": 0.34890731989025553,
525
+ "learning_rate": 0.000594450807494816,
526
+ "loss": 6.5859,
527
+ "step": 74
528
+ },
529
+ {
530
+ "epoch": 0.07,
531
+ "grad_norm": 0.40910932350136514,
532
+ "learning_rate": 0.0005942766604779903,
533
+ "loss": 6.5547,
534
+ "step": 75
535
+ },
536
+ {
537
+ "epoch": 0.08,
538
+ "grad_norm": 0.5698342865852906,
539
+ "learning_rate": 0.0005940998521981274,
540
+ "loss": 6.457,
541
+ "step": 76
542
+ },
543
+ {
544
+ "epoch": 0.08,
545
+ "grad_norm": 0.5179452709555474,
546
+ "learning_rate": 0.0005939203844356852,
547
+ "loss": 6.5547,
548
+ "step": 77
549
+ },
550
+ {
551
+ "epoch": 0.08,
552
+ "grad_norm": 0.5222512938673792,
553
+ "learning_rate": 0.0005937382589979016,
554
+ "loss": 6.5039,
555
+ "step": 78
556
+ },
557
+ {
558
+ "epoch": 0.08,
559
+ "grad_norm": 0.5682332793686307,
560
+ "learning_rate": 0.0005935534777187781,
561
+ "loss": 6.5547,
562
+ "step": 79
563
+ },
564
+ {
565
+ "epoch": 0.08,
566
+ "grad_norm": 0.3869287710460676,
567
+ "learning_rate": 0.0005933660424590598,
568
+ "loss": 6.5156,
569
+ "step": 80
570
+ },
571
+ {
572
+ "epoch": 0.08,
573
+ "grad_norm": 0.3078211032807607,
574
+ "learning_rate": 0.000593175955106218,
575
+ "loss": 6.4258,
576
+ "step": 81
577
+ },
578
+ {
579
+ "epoch": 0.08,
580
+ "grad_norm": 0.3611357511872241,
581
+ "learning_rate": 0.00059298321757443,
582
+ "loss": 6.4727,
583
+ "step": 82
584
+ },
585
+ {
586
+ "epoch": 0.08,
587
+ "grad_norm": 0.29633467844266953,
588
+ "learning_rate": 0.0005927878318045608,
589
+ "loss": 6.3281,
590
+ "step": 83
591
+ },
592
+ {
593
+ "epoch": 0.08,
594
+ "grad_norm": 0.3257574200776832,
595
+ "learning_rate": 0.0005925897997641426,
596
+ "loss": 6.3203,
597
+ "step": 84
598
+ },
599
+ {
600
+ "epoch": 0.08,
601
+ "grad_norm": 0.2824054533852328,
602
+ "learning_rate": 0.0005923891234473562,
603
+ "loss": 6.4062,
604
+ "step": 85
605
+ },
606
+ {
607
+ "epoch": 0.09,
608
+ "grad_norm": 0.3056199770204573,
609
+ "learning_rate": 0.0005921858048750097,
610
+ "loss": 6.3984,
611
+ "step": 86
612
+ },
613
+ {
614
+ "epoch": 0.09,
615
+ "grad_norm": 0.2966438824341908,
616
+ "learning_rate": 0.000591979846094519,
617
+ "loss": 6.3555,
618
+ "step": 87
619
+ },
620
+ {
621
+ "epoch": 0.09,
622
+ "grad_norm": 0.32782438676663733,
623
+ "learning_rate": 0.0005917712491798866,
624
+ "loss": 6.4023,
625
+ "step": 88
626
+ },
627
+ {
628
+ "epoch": 0.09,
629
+ "grad_norm": 0.3538316399620157,
630
+ "learning_rate": 0.0005915600162316811,
631
+ "loss": 6.2812,
632
+ "step": 89
633
+ },
634
+ {
635
+ "epoch": 0.09,
636
+ "grad_norm": 0.375858298192913,
637
+ "learning_rate": 0.0005913461493770162,
638
+ "loss": 6.3086,
639
+ "step": 90
640
+ },
641
+ {
642
+ "epoch": 0.09,
643
+ "grad_norm": 0.5189251339815161,
644
+ "learning_rate": 0.0005911296507695284,
645
+ "loss": 6.2812,
646
+ "step": 91
647
+ },
648
+ {
649
+ "epoch": 0.09,
650
+ "grad_norm": 0.6304909542669104,
651
+ "learning_rate": 0.0005909105225893564,
652
+ "loss": 6.2969,
653
+ "step": 92
654
+ },
655
+ {
656
+ "epoch": 0.09,
657
+ "grad_norm": 0.4655662819622591,
658
+ "learning_rate": 0.0005906887670431187,
659
+ "loss": 6.1953,
660
+ "step": 93
661
+ },
662
+ {
663
+ "epoch": 0.09,
664
+ "grad_norm": 0.39035390983920965,
665
+ "learning_rate": 0.000590464386363891,
666
+ "loss": 6.2617,
667
+ "step": 94
668
+ },
669
+ {
670
+ "epoch": 0.09,
671
+ "grad_norm": 0.4918417851770978,
672
+ "learning_rate": 0.0005902373828111843,
673
+ "loss": 6.2148,
674
+ "step": 95
675
+ },
676
+ {
677
+ "epoch": 0.1,
678
+ "grad_norm": 0.35670770889552555,
679
+ "learning_rate": 0.0005900077586709219,
680
+ "loss": 6.2461,
681
+ "step": 96
682
+ },
683
+ {
684
+ "epoch": 0.1,
685
+ "grad_norm": 0.4177985869939347,
686
+ "learning_rate": 0.0005897755162554163,
687
+ "loss": 6.1797,
688
+ "step": 97
689
+ },
690
+ {
691
+ "epoch": 0.1,
692
+ "grad_norm": 0.3742471130708234,
693
+ "learning_rate": 0.000589540657903346,
694
+ "loss": 6.1406,
695
+ "step": 98
696
+ },
697
+ {
698
+ "epoch": 0.1,
699
+ "grad_norm": 0.28627666723978284,
700
+ "learning_rate": 0.0005893031859797322,
701
+ "loss": 6.2031,
702
+ "step": 99
703
+ },
704
+ {
705
+ "epoch": 0.1,
706
+ "grad_norm": 0.32238563846046103,
707
+ "learning_rate": 0.0005890631028759143,
708
+ "loss": 6.0625,
709
+ "step": 100
710
+ }
711
+ ],
712
+ "logging_steps": 1,
713
+ "max_steps": 1000,
714
+ "num_input_tokens_seen": 0,
715
+ "num_train_epochs": 1,
716
+ "save_steps": 100,
717
+ "total_flos": 0.0,
718
+ "train_batch_size": 32,
719
+ "trial_name": null,
720
+ "trial_params": null
721
+ }
checkpoint-100/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36ce7ab48fa86ef42491eaad3583773d2b60353997a5e7b6fb4ffc1414828749
3
+ size 6520
checkpoint-100/zero_to_fp32.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
215
+ exclude_frozen_parameters)
216
+ elif zero_stage == 3:
217
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
218
+ exclude_frozen_parameters)
219
+
220
+
221
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
222
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
223
+ return
224
+
225
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
226
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
227
+
228
+ if debug:
229
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
230
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
231
+
232
+ wanted_params = len(frozen_param_shapes)
233
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
234
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
235
+ print(f'Frozen params: Have {avail_numel} numels to process.')
236
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
237
+
238
+ total_params = 0
239
+ total_numel = 0
240
+ for name, shape in frozen_param_shapes.items():
241
+ total_params += 1
242
+ unpartitioned_numel = shape.numel()
243
+ total_numel += unpartitioned_numel
244
+
245
+ state_dict[name] = frozen_param_fragments[name]
246
+
247
+ if debug:
248
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
249
+
250
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
251
+
252
+
253
+ def _has_callable(obj, fn):
254
+ attr = getattr(obj, fn, None)
255
+ return callable(attr)
256
+
257
+
258
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
259
+ param_shapes = zero_model_states[0].param_shapes
260
+
261
+ # Reconstruction protocol:
262
+ #
263
+ # XXX: document this
264
+
265
+ if debug:
266
+ for i in range(world_size):
267
+ for j in range(len(fp32_flat_groups[0])):
268
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
269
+
270
+ # XXX: memory usage doubles here (zero2)
271
+ num_param_groups = len(fp32_flat_groups[0])
272
+ merged_single_partition_of_fp32_groups = []
273
+ for i in range(num_param_groups):
274
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
275
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
276
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
277
+ avail_numel = sum(
278
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
279
+
280
+ if debug:
281
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
282
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
283
+ # not asserting if there is a mismatch due to possible padding
284
+ print(f"Have {avail_numel} numels to process.")
285
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
286
+
287
+ # params
288
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
289
+ # out-of-core computing solution
290
+ total_numel = 0
291
+ total_params = 0
292
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
293
+ offset = 0
294
+ avail_numel = full_single_fp32_vector.numel()
295
+ for name, shape in shapes.items():
296
+
297
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
298
+ total_numel += unpartitioned_numel
299
+ total_params += 1
300
+
301
+ if debug:
302
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
303
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
304
+ offset += unpartitioned_numel
305
+
306
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
307
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
308
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
309
+ # live optimizer object, so we are checking that the numbers are within the right range
310
+ align_to = 2 * world_size
311
+
312
+ def zero2_align(x):
313
+ return align_to * math.ceil(x / align_to)
314
+
315
+ if debug:
316
+ print(f"original offset={offset}, avail_numel={avail_numel}")
317
+
318
+ offset = zero2_align(offset)
319
+ avail_numel = zero2_align(avail_numel)
320
+
321
+ if debug:
322
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
323
+
324
+ # Sanity check
325
+ if offset != avail_numel:
326
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
327
+
328
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
329
+
330
+
331
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
332
+ exclude_frozen_parameters):
333
+ state_dict = OrderedDict()
334
+
335
+ # buffers
336
+ buffers = zero_model_states[0].buffers
337
+ state_dict.update(buffers)
338
+ if debug:
339
+ print(f"added {len(buffers)} buffers")
340
+
341
+ if not exclude_frozen_parameters:
342
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
343
+
344
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
345
+
346
+ # recover shared parameters
347
+ for pair in zero_model_states[0].shared_params:
348
+ if pair[1] in state_dict:
349
+ state_dict[pair[0]] = state_dict[pair[1]]
350
+
351
+ return state_dict
352
+
353
+
354
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
355
+ remainder = unpartitioned_numel % world_size
356
+ padding_numel = (world_size - remainder) if remainder else 0
357
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
358
+ return partitioned_numel, padding_numel
359
+
360
+
361
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
362
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
363
+ return
364
+
365
+ if debug:
366
+ for i in range(world_size):
367
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
368
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
369
+
370
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
371
+ wanted_params = len(frozen_param_shapes)
372
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
373
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
374
+ print(f'Frozen params: Have {avail_numel} numels to process.')
375
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
376
+
377
+ total_params = 0
378
+ total_numel = 0
379
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
380
+ total_params += 1
381
+ unpartitioned_numel = shape.numel()
382
+ total_numel += unpartitioned_numel
383
+
384
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
385
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
386
+
387
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
388
+
389
+ if debug:
390
+ print(
391
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
392
+ )
393
+
394
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
395
+
396
+
397
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
398
+ param_shapes = zero_model_states[0].param_shapes
399
+ avail_numel = fp32_flat_groups[0].numel() * world_size
400
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
401
+ # param, re-consolidating each param, while dealing with padding if any
402
+
403
+ # merge list of dicts, preserving order
404
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
405
+
406
+ if debug:
407
+ for i in range(world_size):
408
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
409
+
410
+ wanted_params = len(param_shapes)
411
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
412
+ # not asserting if there is a mismatch due to possible padding
413
+ avail_numel = fp32_flat_groups[0].numel() * world_size
414
+ print(f"Trainable params: Have {avail_numel} numels to process.")
415
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
416
+
417
+ # params
418
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
419
+ # out-of-core computing solution
420
+ offset = 0
421
+ total_numel = 0
422
+ total_params = 0
423
+ for name, shape in param_shapes.items():
424
+
425
+ unpartitioned_numel = shape.numel()
426
+ total_numel += unpartitioned_numel
427
+ total_params += 1
428
+
429
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
430
+
431
+ if debug:
432
+ print(
433
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
434
+ )
435
+
436
+ # XXX: memory usage doubles here
437
+ state_dict[name] = torch.cat(
438
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
439
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
440
+ offset += partitioned_numel
441
+
442
+ offset *= world_size
443
+
444
+ # Sanity check
445
+ if offset != avail_numel:
446
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
447
+
448
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
449
+
450
+
451
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
452
+ exclude_frozen_parameters):
453
+ state_dict = OrderedDict()
454
+
455
+ # buffers
456
+ buffers = zero_model_states[0].buffers
457
+ state_dict.update(buffers)
458
+ if debug:
459
+ print(f"added {len(buffers)} buffers")
460
+
461
+ if not exclude_frozen_parameters:
462
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
463
+
464
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
465
+
466
+ # recover shared parameters
467
+ for pair in zero_model_states[0].shared_params:
468
+ if pair[1] in state_dict:
469
+ state_dict[pair[0]] = state_dict[pair[1]]
470
+
471
+ return state_dict
472
+
473
+
474
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
475
+ """
476
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
477
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
478
+ via a model hub.
479
+
480
+ Args:
481
+ - ``checkpoint_dir``: path to the desired checkpoint folder
482
+ - ``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``
483
+ - ``exclude_frozen_parameters``: exclude frozen parameters
484
+
485
+ Returns:
486
+ - pytorch ``state_dict``
487
+
488
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
489
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
490
+ the checkpoint.
491
+
492
+ A typical usage might be ::
493
+
494
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
495
+ # do the training and checkpoint saving
496
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
497
+ model = model.cpu() # move to cpu
498
+ model.load_state_dict(state_dict)
499
+ # submit to model hub or save the model to share with others
500
+
501
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
502
+ application. i.e. you will need to re-initialize the deepspeed engine, since
503
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
504
+
505
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
506
+
507
+ """
508
+ if tag is None:
509
+ latest_path = os.path.join(checkpoint_dir, 'latest')
510
+ if os.path.isfile(latest_path):
511
+ with open(latest_path, 'r') as fd:
512
+ tag = fd.read().strip()
513
+ else:
514
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
515
+
516
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
517
+
518
+ if not os.path.isdir(ds_checkpoint_dir):
519
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
520
+
521
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
522
+
523
+
524
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
525
+ """
526
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
527
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
528
+
529
+ Args:
530
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
531
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
532
+ - ``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``
533
+ - ``exclude_frozen_parameters``: exclude frozen parameters
534
+ """
535
+
536
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
537
+ print(f"Saving fp32 state dict to {output_file}")
538
+ torch.save(state_dict, output_file)
539
+
540
+
541
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
542
+ """
543
+ 1. Put the provided model to cpu
544
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
545
+ 3. Load it into the provided model
546
+
547
+ Args:
548
+ - ``model``: the model object to update
549
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
550
+ - ``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``
551
+
552
+ Returns:
553
+ - ``model`: modified model
554
+
555
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
556
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
557
+ conveniently placed for you in the checkpoint folder.
558
+
559
+ A typical usage might be ::
560
+
561
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
562
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
563
+ # submit to model hub or save the model to share with others
564
+
565
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
566
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
567
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
568
+
569
+ """
570
+ logger.info(f"Extracting fp32 weights")
571
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
572
+
573
+ logger.info(f"Overwriting model with fp32 weights")
574
+ model = model.cpu()
575
+ model.load_state_dict(state_dict, strict=False)
576
+
577
+ return model
578
+
579
+
580
+ if __name__ == "__main__":
581
+
582
+ parser = argparse.ArgumentParser()
583
+ parser.add_argument("checkpoint_dir",
584
+ type=str,
585
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
586
+ parser.add_argument(
587
+ "output_file",
588
+ type=str,
589
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
590
+ parser.add_argument("-t",
591
+ "--tag",
592
+ type=str,
593
+ default=None,
594
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
595
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
596
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
597
+ args = parser.parse_args()
598
+
599
+ debug = args.debug
600
+
601
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
602
+ args.output_file,
603
+ tag=args.tag,
604
+ exclude_frozen_parameters=args.exclude_frozen_parameters)
checkpoint-20/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5",
3
+ "architectures": [
4
+ "GPTNeoXForCausalLM"
5
+ ],
6
+ "attention_bias": true,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 0,
9
+ "classifier_dropout": 0.1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout": 0.0,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "layer_norm_eps": 1e-05,
17
+ "layer_norm_epsilon": 1e-05,
18
+ "max_position_embeddings": 1024,
19
+ "model_type": "gpt_neox",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "rope_scaling": null,
23
+ "rotary_emb_base": 10000,
24
+ "rotary_pct": 0.25,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.38.2",
28
+ "use_cache": true,
29
+ "use_parallel_residual": true,
30
+ "vocab_size": 50304
31
+ }
checkpoint-20/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.38.2"
6
+ }
checkpoint-20/global_step20/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3d9619b0d3ceeed4c45a4c6fd5be8946b1be76a5801c466123be2ca841e5e337
3
+ size 973946896
checkpoint-20/global_step20/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c51b9f289ed8d24931448d39d8478de2e97527186251a29c92850b1de7562ea
3
+ size 973946832
checkpoint-20/global_step20/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06da85a865332b0c223e8dc427f16b0c81330388f43d5d7b854b9b349b9e2f89
3
+ size 324689964
checkpoint-20/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step20
checkpoint-20/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99984de686ddb1e07f6ea7778c91ab6e3547271af7b06526b184e6578f6bf40d
3
+ size 324662984
checkpoint-20/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530
3
+ size 14512
checkpoint-20/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82
3
+ size 14512
checkpoint-20/trainer_state.json ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 0.01999000499750125,
5
+ "eval_steps": 500,
6
+ "global_step": 20,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.0,
13
+ "grad_norm": 3.3340553137590683,
14
+ "learning_rate": 0.0,
15
+ "loss": 11.0,
16
+ "step": 1
17
+ },
18
+ {
19
+ "epoch": 0.0,
20
+ "grad_norm": 2.398799707355898,
21
+ "learning_rate": 5.9999999999999995e-05,
22
+ "loss": 10.125,
23
+ "step": 2
24
+ },
25
+ {
26
+ "epoch": 0.0,
27
+ "grad_norm": 2.3943029297945575,
28
+ "learning_rate": 0.00011999999999999999,
29
+ "loss": 10.1172,
30
+ "step": 3
31
+ },
32
+ {
33
+ "epoch": 0.0,
34
+ "grad_norm": 1.9959117709404242,
35
+ "learning_rate": 0.00017999999999999998,
36
+ "loss": 9.875,
37
+ "step": 4
38
+ },
39
+ {
40
+ "epoch": 0.0,
41
+ "grad_norm": 1.8270696218303057,
42
+ "learning_rate": 0.00023999999999999998,
43
+ "loss": 9.6641,
44
+ "step": 5
45
+ },
46
+ {
47
+ "epoch": 0.01,
48
+ "grad_norm": 1.7854351602113614,
49
+ "learning_rate": 0.0003,
50
+ "loss": 9.4844,
51
+ "step": 6
52
+ },
53
+ {
54
+ "epoch": 0.01,
55
+ "grad_norm": 1.7194174424274788,
56
+ "learning_rate": 0.00035999999999999997,
57
+ "loss": 9.3281,
58
+ "step": 7
59
+ },
60
+ {
61
+ "epoch": 0.01,
62
+ "grad_norm": 1.463772638994466,
63
+ "learning_rate": 0.00041999999999999996,
64
+ "loss": 9.2109,
65
+ "step": 8
66
+ },
67
+ {
68
+ "epoch": 0.01,
69
+ "grad_norm": 1.439323678271545,
70
+ "learning_rate": 0.00047999999999999996,
71
+ "loss": 8.9453,
72
+ "step": 9
73
+ },
74
+ {
75
+ "epoch": 0.01,
76
+ "grad_norm": 1.2936126396494727,
77
+ "learning_rate": 0.00054,
78
+ "loss": 8.7109,
79
+ "step": 10
80
+ },
81
+ {
82
+ "epoch": 0.01,
83
+ "grad_norm": 1.0757761814549318,
84
+ "learning_rate": 0.0005999986405514987,
85
+ "loss": 8.4609,
86
+ "step": 11
87
+ },
88
+ {
89
+ "epoch": 0.01,
90
+ "grad_norm": 0.9278570154341632,
91
+ "learning_rate": 0.0005999945622196846,
92
+ "loss": 8.2344,
93
+ "step": 12
94
+ },
95
+ {
96
+ "epoch": 0.01,
97
+ "grad_norm": 0.8086775215724974,
98
+ "learning_rate": 0.0005999877650456265,
99
+ "loss": 8.125,
100
+ "step": 13
101
+ },
102
+ {
103
+ "epoch": 0.01,
104
+ "grad_norm": 0.7630413213242441,
105
+ "learning_rate": 0.000599978249097772,
106
+ "loss": 7.9766,
107
+ "step": 14
108
+ },
109
+ {
110
+ "epoch": 0.01,
111
+ "grad_norm": 0.9172017565891333,
112
+ "learning_rate": 0.0005999660144719463,
113
+ "loss": 7.8555,
114
+ "step": 15
115
+ },
116
+ {
117
+ "epoch": 0.02,
118
+ "grad_norm": 0.6610052304024877,
119
+ "learning_rate": 0.0005999510612913519,
120
+ "loss": 7.7734,
121
+ "step": 16
122
+ },
123
+ {
124
+ "epoch": 0.02,
125
+ "grad_norm": 0.7091485456070775,
126
+ "learning_rate": 0.0005999333897065673,
127
+ "loss": 7.7148,
128
+ "step": 17
129
+ },
130
+ {
131
+ "epoch": 0.02,
132
+ "grad_norm": 16.771353248766836,
133
+ "learning_rate": 0.0005999129998955453,
134
+ "loss": 8.5078,
135
+ "step": 18
136
+ },
137
+ {
138
+ "epoch": 0.02,
139
+ "grad_norm": 1.3123969082989795,
140
+ "learning_rate": 0.0005998898920636111,
141
+ "loss": 7.7539,
142
+ "step": 19
143
+ },
144
+ {
145
+ "epoch": 0.02,
146
+ "grad_norm": 0.6992078172905232,
147
+ "learning_rate": 0.00059986406644346,
148
+ "loss": 7.75,
149
+ "step": 20
150
+ }
151
+ ],
152
+ "logging_steps": 1,
153
+ "max_steps": 1000,
154
+ "num_input_tokens_seen": 0,
155
+ "num_train_epochs": 1,
156
+ "save_steps": 10,
157
+ "total_flos": 0.0,
158
+ "train_batch_size": 32,
159
+ "trial_name": null,
160
+ "trial_params": null
161
+ }
checkpoint-20/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95cc4290cc90782d57f7376defd26743b3a36943fc93e80e2734385bc57e8b78
3
+ size 6520
checkpoint-20/zero_to_fp32.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
215
+ exclude_frozen_parameters)
216
+ elif zero_stage == 3:
217
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
218
+ exclude_frozen_parameters)
219
+
220
+
221
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
222
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
223
+ return
224
+
225
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
226
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
227
+
228
+ if debug:
229
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
230
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
231
+
232
+ wanted_params = len(frozen_param_shapes)
233
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
234
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
235
+ print(f'Frozen params: Have {avail_numel} numels to process.')
236
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
237
+
238
+ total_params = 0
239
+ total_numel = 0
240
+ for name, shape in frozen_param_shapes.items():
241
+ total_params += 1
242
+ unpartitioned_numel = shape.numel()
243
+ total_numel += unpartitioned_numel
244
+
245
+ state_dict[name] = frozen_param_fragments[name]
246
+
247
+ if debug:
248
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
249
+
250
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
251
+
252
+
253
+ def _has_callable(obj, fn):
254
+ attr = getattr(obj, fn, None)
255
+ return callable(attr)
256
+
257
+
258
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
259
+ param_shapes = zero_model_states[0].param_shapes
260
+
261
+ # Reconstruction protocol:
262
+ #
263
+ # XXX: document this
264
+
265
+ if debug:
266
+ for i in range(world_size):
267
+ for j in range(len(fp32_flat_groups[0])):
268
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
269
+
270
+ # XXX: memory usage doubles here (zero2)
271
+ num_param_groups = len(fp32_flat_groups[0])
272
+ merged_single_partition_of_fp32_groups = []
273
+ for i in range(num_param_groups):
274
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
275
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
276
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
277
+ avail_numel = sum(
278
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
279
+
280
+ if debug:
281
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
282
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
283
+ # not asserting if there is a mismatch due to possible padding
284
+ print(f"Have {avail_numel} numels to process.")
285
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
286
+
287
+ # params
288
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
289
+ # out-of-core computing solution
290
+ total_numel = 0
291
+ total_params = 0
292
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
293
+ offset = 0
294
+ avail_numel = full_single_fp32_vector.numel()
295
+ for name, shape in shapes.items():
296
+
297
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
298
+ total_numel += unpartitioned_numel
299
+ total_params += 1
300
+
301
+ if debug:
302
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
303
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
304
+ offset += unpartitioned_numel
305
+
306
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
307
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
308
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
309
+ # live optimizer object, so we are checking that the numbers are within the right range
310
+ align_to = 2 * world_size
311
+
312
+ def zero2_align(x):
313
+ return align_to * math.ceil(x / align_to)
314
+
315
+ if debug:
316
+ print(f"original offset={offset}, avail_numel={avail_numel}")
317
+
318
+ offset = zero2_align(offset)
319
+ avail_numel = zero2_align(avail_numel)
320
+
321
+ if debug:
322
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
323
+
324
+ # Sanity check
325
+ if offset != avail_numel:
326
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
327
+
328
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
329
+
330
+
331
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
332
+ exclude_frozen_parameters):
333
+ state_dict = OrderedDict()
334
+
335
+ # buffers
336
+ buffers = zero_model_states[0].buffers
337
+ state_dict.update(buffers)
338
+ if debug:
339
+ print(f"added {len(buffers)} buffers")
340
+
341
+ if not exclude_frozen_parameters:
342
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
343
+
344
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
345
+
346
+ # recover shared parameters
347
+ for pair in zero_model_states[0].shared_params:
348
+ if pair[1] in state_dict:
349
+ state_dict[pair[0]] = state_dict[pair[1]]
350
+
351
+ return state_dict
352
+
353
+
354
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
355
+ remainder = unpartitioned_numel % world_size
356
+ padding_numel = (world_size - remainder) if remainder else 0
357
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
358
+ return partitioned_numel, padding_numel
359
+
360
+
361
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
362
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
363
+ return
364
+
365
+ if debug:
366
+ for i in range(world_size):
367
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
368
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
369
+
370
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
371
+ wanted_params = len(frozen_param_shapes)
372
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
373
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
374
+ print(f'Frozen params: Have {avail_numel} numels to process.')
375
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
376
+
377
+ total_params = 0
378
+ total_numel = 0
379
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
380
+ total_params += 1
381
+ unpartitioned_numel = shape.numel()
382
+ total_numel += unpartitioned_numel
383
+
384
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
385
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
386
+
387
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
388
+
389
+ if debug:
390
+ print(
391
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
392
+ )
393
+
394
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
395
+
396
+
397
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
398
+ param_shapes = zero_model_states[0].param_shapes
399
+ avail_numel = fp32_flat_groups[0].numel() * world_size
400
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
401
+ # param, re-consolidating each param, while dealing with padding if any
402
+
403
+ # merge list of dicts, preserving order
404
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
405
+
406
+ if debug:
407
+ for i in range(world_size):
408
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
409
+
410
+ wanted_params = len(param_shapes)
411
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
412
+ # not asserting if there is a mismatch due to possible padding
413
+ avail_numel = fp32_flat_groups[0].numel() * world_size
414
+ print(f"Trainable params: Have {avail_numel} numels to process.")
415
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
416
+
417
+ # params
418
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
419
+ # out-of-core computing solution
420
+ offset = 0
421
+ total_numel = 0
422
+ total_params = 0
423
+ for name, shape in param_shapes.items():
424
+
425
+ unpartitioned_numel = shape.numel()
426
+ total_numel += unpartitioned_numel
427
+ total_params += 1
428
+
429
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
430
+
431
+ if debug:
432
+ print(
433
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
434
+ )
435
+
436
+ # XXX: memory usage doubles here
437
+ state_dict[name] = torch.cat(
438
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
439
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
440
+ offset += partitioned_numel
441
+
442
+ offset *= world_size
443
+
444
+ # Sanity check
445
+ if offset != avail_numel:
446
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
447
+
448
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
449
+
450
+
451
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
452
+ exclude_frozen_parameters):
453
+ state_dict = OrderedDict()
454
+
455
+ # buffers
456
+ buffers = zero_model_states[0].buffers
457
+ state_dict.update(buffers)
458
+ if debug:
459
+ print(f"added {len(buffers)} buffers")
460
+
461
+ if not exclude_frozen_parameters:
462
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
463
+
464
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
465
+
466
+ # recover shared parameters
467
+ for pair in zero_model_states[0].shared_params:
468
+ if pair[1] in state_dict:
469
+ state_dict[pair[0]] = state_dict[pair[1]]
470
+
471
+ return state_dict
472
+
473
+
474
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
475
+ """
476
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
477
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
478
+ via a model hub.
479
+
480
+ Args:
481
+ - ``checkpoint_dir``: path to the desired checkpoint folder
482
+ - ``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``
483
+ - ``exclude_frozen_parameters``: exclude frozen parameters
484
+
485
+ Returns:
486
+ - pytorch ``state_dict``
487
+
488
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
489
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
490
+ the checkpoint.
491
+
492
+ A typical usage might be ::
493
+
494
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
495
+ # do the training and checkpoint saving
496
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
497
+ model = model.cpu() # move to cpu
498
+ model.load_state_dict(state_dict)
499
+ # submit to model hub or save the model to share with others
500
+
501
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
502
+ application. i.e. you will need to re-initialize the deepspeed engine, since
503
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
504
+
505
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
506
+
507
+ """
508
+ if tag is None:
509
+ latest_path = os.path.join(checkpoint_dir, 'latest')
510
+ if os.path.isfile(latest_path):
511
+ with open(latest_path, 'r') as fd:
512
+ tag = fd.read().strip()
513
+ else:
514
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
515
+
516
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
517
+
518
+ if not os.path.isdir(ds_checkpoint_dir):
519
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
520
+
521
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
522
+
523
+
524
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
525
+ """
526
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
527
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
528
+
529
+ Args:
530
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
531
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
532
+ - ``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``
533
+ - ``exclude_frozen_parameters``: exclude frozen parameters
534
+ """
535
+
536
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
537
+ print(f"Saving fp32 state dict to {output_file}")
538
+ torch.save(state_dict, output_file)
539
+
540
+
541
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
542
+ """
543
+ 1. Put the provided model to cpu
544
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
545
+ 3. Load it into the provided model
546
+
547
+ Args:
548
+ - ``model``: the model object to update
549
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
550
+ - ``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``
551
+
552
+ Returns:
553
+ - ``model`: modified model
554
+
555
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
556
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
557
+ conveniently placed for you in the checkpoint folder.
558
+
559
+ A typical usage might be ::
560
+
561
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
562
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
563
+ # submit to model hub or save the model to share with others
564
+
565
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
566
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
567
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
568
+
569
+ """
570
+ logger.info(f"Extracting fp32 weights")
571
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
572
+
573
+ logger.info(f"Overwriting model with fp32 weights")
574
+ model = model.cpu()
575
+ model.load_state_dict(state_dict, strict=False)
576
+
577
+ return model
578
+
579
+
580
+ if __name__ == "__main__":
581
+
582
+ parser = argparse.ArgumentParser()
583
+ parser.add_argument("checkpoint_dir",
584
+ type=str,
585
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
586
+ parser.add_argument(
587
+ "output_file",
588
+ type=str,
589
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
590
+ parser.add_argument("-t",
591
+ "--tag",
592
+ type=str,
593
+ default=None,
594
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
595
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
596
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
597
+ args = parser.parse_args()
598
+
599
+ debug = args.debug
600
+
601
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
602
+ args.output_file,
603
+ tag=args.tag,
604
+ exclude_frozen_parameters=args.exclude_frozen_parameters)
checkpoint-200/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5",
3
+ "architectures": [
4
+ "GPTNeoXForCausalLM"
5
+ ],
6
+ "attention_bias": true,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 0,
9
+ "classifier_dropout": 0.1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout": 0.0,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "layer_norm_eps": 1e-05,
17
+ "layer_norm_epsilon": 1e-05,
18
+ "max_position_embeddings": 1024,
19
+ "model_type": "gpt_neox",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "rope_scaling": null,
23
+ "rotary_emb_base": 10000,
24
+ "rotary_pct": 0.25,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.38.2",
28
+ "use_cache": true,
29
+ "use_parallel_residual": true,
30
+ "vocab_size": 50304
31
+ }
checkpoint-200/generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 0,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.38.2"
6
+ }
checkpoint-200/global_step200/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc073673977d2260d446a5288c182308ae00d243deb8aa1287eed2bdc0ca55eb
3
+ size 973946896
checkpoint-200/global_step200/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1dd88f92e1b9309a12e7505328b079538457daedef3bcf8d59f5cfcef86aca6d
3
+ size 973946832
checkpoint-200/global_step200/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea030c07bc1914d14db0809ed9a4fc3f9c76b4d11dbdabd30acf57c7c93e685c
3
+ size 324689964
checkpoint-200/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step200
checkpoint-200/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd81f3f4d4881c9ad52c0835b8eedd34cd74ec334ef06ba64c40c85ac825a476
3
+ size 324662984
checkpoint-200/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0bb7d2ecdd48fd7d0be1e75b0e3f29004064381052fa203ed926e88b90ef530
3
+ size 14512
checkpoint-200/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:177d534a379bd6b276474c2cb140e318dc65db4457b6c1b6f25a1a9dd563af82
3
+ size 14512
checkpoint-200/trainer_state.json ADDED
@@ -0,0 +1,1421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_metric": null,
3
+ "best_model_checkpoint": null,
4
+ "epoch": 0.19990004997501248,
5
+ "eval_steps": 500,
6
+ "global_step": 200,
7
+ "is_hyper_param_search": false,
8
+ "is_local_process_zero": true,
9
+ "is_world_process_zero": true,
10
+ "log_history": [
11
+ {
12
+ "epoch": 0.0,
13
+ "grad_norm": 3.3340563149001086,
14
+ "learning_rate": 0.0,
15
+ "loss": 11.0,
16
+ "step": 1
17
+ },
18
+ {
19
+ "epoch": 0.0,
20
+ "grad_norm": 2.398812329952019,
21
+ "learning_rate": 5.9999999999999995e-05,
22
+ "loss": 10.125,
23
+ "step": 2
24
+ },
25
+ {
26
+ "epoch": 0.0,
27
+ "grad_norm": 2.394322446895115,
28
+ "learning_rate": 0.00011999999999999999,
29
+ "loss": 10.1172,
30
+ "step": 3
31
+ },
32
+ {
33
+ "epoch": 0.0,
34
+ "grad_norm": 1.9958816684399585,
35
+ "learning_rate": 0.00017999999999999998,
36
+ "loss": 9.875,
37
+ "step": 4
38
+ },
39
+ {
40
+ "epoch": 0.0,
41
+ "grad_norm": 1.8270465897882062,
42
+ "learning_rate": 0.00023999999999999998,
43
+ "loss": 9.6641,
44
+ "step": 5
45
+ },
46
+ {
47
+ "epoch": 0.01,
48
+ "grad_norm": 1.7854046471397795,
49
+ "learning_rate": 0.0003,
50
+ "loss": 9.4844,
51
+ "step": 6
52
+ },
53
+ {
54
+ "epoch": 0.01,
55
+ "grad_norm": 1.719416749115252,
56
+ "learning_rate": 0.00035999999999999997,
57
+ "loss": 9.3281,
58
+ "step": 7
59
+ },
60
+ {
61
+ "epoch": 0.01,
62
+ "grad_norm": 1.4637825746112274,
63
+ "learning_rate": 0.00041999999999999996,
64
+ "loss": 9.2109,
65
+ "step": 8
66
+ },
67
+ {
68
+ "epoch": 0.01,
69
+ "grad_norm": 1.4393631015406718,
70
+ "learning_rate": 0.00047999999999999996,
71
+ "loss": 8.9453,
72
+ "step": 9
73
+ },
74
+ {
75
+ "epoch": 0.01,
76
+ "grad_norm": 1.2936734586915988,
77
+ "learning_rate": 0.00054,
78
+ "loss": 8.7109,
79
+ "step": 10
80
+ },
81
+ {
82
+ "epoch": 0.01,
83
+ "grad_norm": 1.0756922378227356,
84
+ "learning_rate": 0.0005999986405514987,
85
+ "loss": 8.4609,
86
+ "step": 11
87
+ },
88
+ {
89
+ "epoch": 0.01,
90
+ "grad_norm": 0.9277829127413892,
91
+ "learning_rate": 0.0005999945622196846,
92
+ "loss": 8.2344,
93
+ "step": 12
94
+ },
95
+ {
96
+ "epoch": 0.01,
97
+ "grad_norm": 0.8084581786682467,
98
+ "learning_rate": 0.0005999877650456265,
99
+ "loss": 8.125,
100
+ "step": 13
101
+ },
102
+ {
103
+ "epoch": 0.01,
104
+ "grad_norm": 0.7635084596900947,
105
+ "learning_rate": 0.000599978249097772,
106
+ "loss": 7.9766,
107
+ "step": 14
108
+ },
109
+ {
110
+ "epoch": 0.01,
111
+ "grad_norm": 0.9186699644247788,
112
+ "learning_rate": 0.0005999660144719463,
113
+ "loss": 7.8555,
114
+ "step": 15
115
+ },
116
+ {
117
+ "epoch": 0.02,
118
+ "grad_norm": 0.6609504256551479,
119
+ "learning_rate": 0.0005999510612913519,
120
+ "loss": 7.7734,
121
+ "step": 16
122
+ },
123
+ {
124
+ "epoch": 0.02,
125
+ "grad_norm": 0.7086232844782971,
126
+ "learning_rate": 0.0005999333897065673,
127
+ "loss": 7.7148,
128
+ "step": 17
129
+ },
130
+ {
131
+ "epoch": 0.02,
132
+ "grad_norm": 16.38048851691348,
133
+ "learning_rate": 0.0005999129998955453,
134
+ "loss": 8.4844,
135
+ "step": 18
136
+ },
137
+ {
138
+ "epoch": 0.02,
139
+ "grad_norm": 1.3057527590449889,
140
+ "learning_rate": 0.0005998898920636111,
141
+ "loss": 7.7539,
142
+ "step": 19
143
+ },
144
+ {
145
+ "epoch": 0.02,
146
+ "grad_norm": 0.6966048242948986,
147
+ "learning_rate": 0.00059986406644346,
148
+ "loss": 7.75,
149
+ "step": 20
150
+ },
151
+ {
152
+ "epoch": 0.02,
153
+ "grad_norm": 0.6348089115348993,
154
+ "learning_rate": 0.0005998355232951559,
155
+ "loss": 7.7031,
156
+ "step": 21
157
+ },
158
+ {
159
+ "epoch": 0.02,
160
+ "grad_norm": 0.7829163518610293,
161
+ "learning_rate": 0.0005998042629061279,
162
+ "loss": 7.6992,
163
+ "step": 22
164
+ },
165
+ {
166
+ "epoch": 0.02,
167
+ "grad_norm": 0.5900591778980369,
168
+ "learning_rate": 0.0005997702855911678,
169
+ "loss": 7.6016,
170
+ "step": 23
171
+ },
172
+ {
173
+ "epoch": 0.02,
174
+ "grad_norm": 0.4655170213064256,
175
+ "learning_rate": 0.0005997335916924268,
176
+ "loss": 7.5977,
177
+ "step": 24
178
+ },
179
+ {
180
+ "epoch": 0.02,
181
+ "grad_norm": 0.6287348258915756,
182
+ "learning_rate": 0.0005996941815794121,
183
+ "loss": 7.5586,
184
+ "step": 25
185
+ },
186
+ {
187
+ "epoch": 0.03,
188
+ "grad_norm": 0.6137321903884564,
189
+ "learning_rate": 0.0005996520556489831,
190
+ "loss": 7.5898,
191
+ "step": 26
192
+ },
193
+ {
194
+ "epoch": 0.03,
195
+ "grad_norm": 0.44962562710631065,
196
+ "learning_rate": 0.0005996072143253473,
197
+ "loss": 7.4336,
198
+ "step": 27
199
+ },
200
+ {
201
+ "epoch": 0.03,
202
+ "grad_norm": 0.46130046454703316,
203
+ "learning_rate": 0.0005995596580600566,
204
+ "loss": 7.4023,
205
+ "step": 28
206
+ },
207
+ {
208
+ "epoch": 0.03,
209
+ "grad_norm": 0.4686712675731326,
210
+ "learning_rate": 0.0005995093873320018,
211
+ "loss": 7.3789,
212
+ "step": 29
213
+ },
214
+ {
215
+ "epoch": 0.03,
216
+ "grad_norm": 0.4672147564288997,
217
+ "learning_rate": 0.0005994564026474087,
218
+ "loss": 7.3711,
219
+ "step": 30
220
+ },
221
+ {
222
+ "epoch": 0.03,
223
+ "grad_norm": 0.40408354581233474,
224
+ "learning_rate": 0.0005994007045398324,
225
+ "loss": 7.3672,
226
+ "step": 31
227
+ },
228
+ {
229
+ "epoch": 0.03,
230
+ "grad_norm": 0.46032146732584733,
231
+ "learning_rate": 0.0005993422935701524,
232
+ "loss": 7.3477,
233
+ "step": 32
234
+ },
235
+ {
236
+ "epoch": 0.03,
237
+ "grad_norm": 0.4765534634593268,
238
+ "learning_rate": 0.0005992811703265664,
239
+ "loss": 7.3555,
240
+ "step": 33
241
+ },
242
+ {
243
+ "epoch": 0.03,
244
+ "grad_norm": 0.46208489386235113,
245
+ "learning_rate": 0.0005992173354245849,
246
+ "loss": 7.3047,
247
+ "step": 34
248
+ },
249
+ {
250
+ "epoch": 0.03,
251
+ "grad_norm": 0.2956144524964961,
252
+ "learning_rate": 0.0005991507895070244,
253
+ "loss": 7.3125,
254
+ "step": 35
255
+ },
256
+ {
257
+ "epoch": 0.04,
258
+ "grad_norm": 0.4834645389868856,
259
+ "learning_rate": 0.0005990815332440017,
260
+ "loss": 7.207,
261
+ "step": 36
262
+ },
263
+ {
264
+ "epoch": 0.04,
265
+ "grad_norm": 0.4411831350968505,
266
+ "learning_rate": 0.0005990095673329266,
267
+ "loss": 7.1758,
268
+ "step": 37
269
+ },
270
+ {
271
+ "epoch": 0.04,
272
+ "grad_norm": 0.24809297748968667,
273
+ "learning_rate": 0.0005989348924984951,
274
+ "loss": 7.2188,
275
+ "step": 38
276
+ },
277
+ {
278
+ "epoch": 0.04,
279
+ "grad_norm": 0.39402988416840584,
280
+ "learning_rate": 0.0005988575094926817,
281
+ "loss": 7.1953,
282
+ "step": 39
283
+ },
284
+ {
285
+ "epoch": 0.04,
286
+ "grad_norm": 0.3868345222189167,
287
+ "learning_rate": 0.0005987774190947328,
288
+ "loss": 7.1641,
289
+ "step": 40
290
+ },
291
+ {
292
+ "epoch": 0.04,
293
+ "grad_norm": 0.3777261230135448,
294
+ "learning_rate": 0.0005986946221111575,
295
+ "loss": 7.1328,
296
+ "step": 41
297
+ },
298
+ {
299
+ "epoch": 0.04,
300
+ "grad_norm": 0.4687511444077827,
301
+ "learning_rate": 0.0005986091193757206,
302
+ "loss": 7.0898,
303
+ "step": 42
304
+ },
305
+ {
306
+ "epoch": 0.04,
307
+ "grad_norm": 0.34935796211612463,
308
+ "learning_rate": 0.0005985209117494337,
309
+ "loss": 7.1367,
310
+ "step": 43
311
+ },
312
+ {
313
+ "epoch": 0.04,
314
+ "grad_norm": 0.38764476686849886,
315
+ "learning_rate": 0.0005984300001205466,
316
+ "loss": 7.125,
317
+ "step": 44
318
+ },
319
+ {
320
+ "epoch": 0.04,
321
+ "grad_norm": 0.3956487898882936,
322
+ "learning_rate": 0.0005983363854045386,
323
+ "loss": 7.1094,
324
+ "step": 45
325
+ },
326
+ {
327
+ "epoch": 0.05,
328
+ "grad_norm": 0.31140257544677513,
329
+ "learning_rate": 0.0005982400685441084,
330
+ "loss": 7.0898,
331
+ "step": 46
332
+ },
333
+ {
334
+ "epoch": 0.05,
335
+ "grad_norm": 0.3664476570531787,
336
+ "learning_rate": 0.0005981410505091662,
337
+ "loss": 7.0664,
338
+ "step": 47
339
+ },
340
+ {
341
+ "epoch": 0.05,
342
+ "grad_norm": 0.31891741142945207,
343
+ "learning_rate": 0.0005980393322968223,
344
+ "loss": 7.0273,
345
+ "step": 48
346
+ },
347
+ {
348
+ "epoch": 0.05,
349
+ "grad_norm": 0.4533529037337155,
350
+ "learning_rate": 0.0005979349149313778,
351
+ "loss": 7.0586,
352
+ "step": 49
353
+ },
354
+ {
355
+ "epoch": 0.05,
356
+ "grad_norm": 0.30532331638835586,
357
+ "learning_rate": 0.0005978277994643147,
358
+ "loss": 7.0195,
359
+ "step": 50
360
+ },
361
+ {
362
+ "epoch": 0.05,
363
+ "grad_norm": 0.6501991746260075,
364
+ "learning_rate": 0.0005977179869742844,
365
+ "loss": 6.9648,
366
+ "step": 51
367
+ },
368
+ {
369
+ "epoch": 0.05,
370
+ "grad_norm": 0.43904455901717926,
371
+ "learning_rate": 0.0005976054785670975,
372
+ "loss": 6.9805,
373
+ "step": 52
374
+ },
375
+ {
376
+ "epoch": 0.05,
377
+ "grad_norm": 0.4826001598483571,
378
+ "learning_rate": 0.0005974902753757124,
379
+ "loss": 6.9297,
380
+ "step": 53
381
+ },
382
+ {
383
+ "epoch": 0.05,
384
+ "grad_norm": 0.2924998027034648,
385
+ "learning_rate": 0.000597372378560224,
386
+ "loss": 6.8984,
387
+ "step": 54
388
+ },
389
+ {
390
+ "epoch": 0.05,
391
+ "grad_norm": 0.4439033666380787,
392
+ "learning_rate": 0.0005972517893078517,
393
+ "loss": 6.8945,
394
+ "step": 55
395
+ },
396
+ {
397
+ "epoch": 0.06,
398
+ "grad_norm": 0.6135914255073411,
399
+ "learning_rate": 0.0005971285088329284,
400
+ "loss": 6.9727,
401
+ "step": 56
402
+ },
403
+ {
404
+ "epoch": 0.06,
405
+ "grad_norm": 0.5575686565598483,
406
+ "learning_rate": 0.0005970025383768866,
407
+ "loss": 6.9219,
408
+ "step": 57
409
+ },
410
+ {
411
+ "epoch": 0.06,
412
+ "grad_norm": 0.4820951675994578,
413
+ "learning_rate": 0.0005968738792082478,
414
+ "loss": 6.8516,
415
+ "step": 58
416
+ },
417
+ {
418
+ "epoch": 0.06,
419
+ "grad_norm": 0.40164190019465584,
420
+ "learning_rate": 0.0005967425326226082,
421
+ "loss": 6.7734,
422
+ "step": 59
423
+ },
424
+ {
425
+ "epoch": 0.06,
426
+ "grad_norm": 0.46129863945181293,
427
+ "learning_rate": 0.0005966084999426265,
428
+ "loss": 6.8125,
429
+ "step": 60
430
+ },
431
+ {
432
+ "epoch": 0.06,
433
+ "grad_norm": 0.33322355827118677,
434
+ "learning_rate": 0.0005964717825180101,
435
+ "loss": 6.7891,
436
+ "step": 61
437
+ },
438
+ {
439
+ "epoch": 0.06,
440
+ "grad_norm": 0.3847525153855558,
441
+ "learning_rate": 0.0005963323817255024,
442
+ "loss": 6.8242,
443
+ "step": 62
444
+ },
445
+ {
446
+ "epoch": 0.06,
447
+ "grad_norm": 0.3384433591375982,
448
+ "learning_rate": 0.0005961902989688674,
449
+ "loss": 6.707,
450
+ "step": 63
451
+ },
452
+ {
453
+ "epoch": 0.06,
454
+ "grad_norm": 0.3937003195165685,
455
+ "learning_rate": 0.000596045535678877,
456
+ "loss": 6.8203,
457
+ "step": 64
458
+ },
459
+ {
460
+ "epoch": 0.06,
461
+ "grad_norm": 0.35423488053528107,
462
+ "learning_rate": 0.0005958980933132962,
463
+ "loss": 6.7383,
464
+ "step": 65
465
+ },
466
+ {
467
+ "epoch": 0.07,
468
+ "grad_norm": 0.36005939745315396,
469
+ "learning_rate": 0.0005957479733568675,
470
+ "loss": 6.7109,
471
+ "step": 66
472
+ },
473
+ {
474
+ "epoch": 0.07,
475
+ "grad_norm": 0.3499278317706933,
476
+ "learning_rate": 0.0005955951773212976,
477
+ "loss": 6.7266,
478
+ "step": 67
479
+ },
480
+ {
481
+ "epoch": 0.07,
482
+ "grad_norm": 0.3708385192137018,
483
+ "learning_rate": 0.0005954397067452407,
484
+ "loss": 6.7617,
485
+ "step": 68
486
+ },
487
+ {
488
+ "epoch": 0.07,
489
+ "grad_norm": 0.3775657656205869,
490
+ "learning_rate": 0.0005952815631942839,
491
+ "loss": 6.7148,
492
+ "step": 69
493
+ },
494
+ {
495
+ "epoch": 0.07,
496
+ "grad_norm": 0.3040083750375816,
497
+ "learning_rate": 0.0005951207482609307,
498
+ "loss": 6.5938,
499
+ "step": 70
500
+ },
501
+ {
502
+ "epoch": 0.07,
503
+ "grad_norm": 0.3443020808841468,
504
+ "learning_rate": 0.0005949572635645861,
505
+ "loss": 6.6523,
506
+ "step": 71
507
+ },
508
+ {
509
+ "epoch": 0.07,
510
+ "grad_norm": 0.3520066316939,
511
+ "learning_rate": 0.0005947911107515389,
512
+ "loss": 6.6211,
513
+ "step": 72
514
+ },
515
+ {
516
+ "epoch": 0.07,
517
+ "grad_norm": 0.3739040572679613,
518
+ "learning_rate": 0.0005946222914949462,
519
+ "loss": 6.5547,
520
+ "step": 73
521
+ },
522
+ {
523
+ "epoch": 0.07,
524
+ "grad_norm": 0.34890731989025553,
525
+ "learning_rate": 0.000594450807494816,
526
+ "loss": 6.5859,
527
+ "step": 74
528
+ },
529
+ {
530
+ "epoch": 0.07,
531
+ "grad_norm": 0.40910932350136514,
532
+ "learning_rate": 0.0005942766604779903,
533
+ "loss": 6.5547,
534
+ "step": 75
535
+ },
536
+ {
537
+ "epoch": 0.08,
538
+ "grad_norm": 0.5698342865852906,
539
+ "learning_rate": 0.0005940998521981274,
540
+ "loss": 6.457,
541
+ "step": 76
542
+ },
543
+ {
544
+ "epoch": 0.08,
545
+ "grad_norm": 0.5179452709555474,
546
+ "learning_rate": 0.0005939203844356852,
547
+ "loss": 6.5547,
548
+ "step": 77
549
+ },
550
+ {
551
+ "epoch": 0.08,
552
+ "grad_norm": 0.5222512938673792,
553
+ "learning_rate": 0.0005937382589979016,
554
+ "loss": 6.5039,
555
+ "step": 78
556
+ },
557
+ {
558
+ "epoch": 0.08,
559
+ "grad_norm": 0.5682332793686307,
560
+ "learning_rate": 0.0005935534777187781,
561
+ "loss": 6.5547,
562
+ "step": 79
563
+ },
564
+ {
565
+ "epoch": 0.08,
566
+ "grad_norm": 0.3869287710460676,
567
+ "learning_rate": 0.0005933660424590598,
568
+ "loss": 6.5156,
569
+ "step": 80
570
+ },
571
+ {
572
+ "epoch": 0.08,
573
+ "grad_norm": 0.3078211032807607,
574
+ "learning_rate": 0.000593175955106218,
575
+ "loss": 6.4258,
576
+ "step": 81
577
+ },
578
+ {
579
+ "epoch": 0.08,
580
+ "grad_norm": 0.3611357511872241,
581
+ "learning_rate": 0.00059298321757443,
582
+ "loss": 6.4727,
583
+ "step": 82
584
+ },
585
+ {
586
+ "epoch": 0.08,
587
+ "grad_norm": 0.29633467844266953,
588
+ "learning_rate": 0.0005927878318045608,
589
+ "loss": 6.3281,
590
+ "step": 83
591
+ },
592
+ {
593
+ "epoch": 0.08,
594
+ "grad_norm": 0.3257574200776832,
595
+ "learning_rate": 0.0005925897997641426,
596
+ "loss": 6.3203,
597
+ "step": 84
598
+ },
599
+ {
600
+ "epoch": 0.08,
601
+ "grad_norm": 0.2824054533852328,
602
+ "learning_rate": 0.0005923891234473562,
603
+ "loss": 6.4062,
604
+ "step": 85
605
+ },
606
+ {
607
+ "epoch": 0.09,
608
+ "grad_norm": 0.3056199770204573,
609
+ "learning_rate": 0.0005921858048750097,
610
+ "loss": 6.3984,
611
+ "step": 86
612
+ },
613
+ {
614
+ "epoch": 0.09,
615
+ "grad_norm": 0.2966438824341908,
616
+ "learning_rate": 0.000591979846094519,
617
+ "loss": 6.3555,
618
+ "step": 87
619
+ },
620
+ {
621
+ "epoch": 0.09,
622
+ "grad_norm": 0.32782438676663733,
623
+ "learning_rate": 0.0005917712491798866,
624
+ "loss": 6.4023,
625
+ "step": 88
626
+ },
627
+ {
628
+ "epoch": 0.09,
629
+ "grad_norm": 0.3538316399620157,
630
+ "learning_rate": 0.0005915600162316811,
631
+ "loss": 6.2812,
632
+ "step": 89
633
+ },
634
+ {
635
+ "epoch": 0.09,
636
+ "grad_norm": 0.375858298192913,
637
+ "learning_rate": 0.0005913461493770162,
638
+ "loss": 6.3086,
639
+ "step": 90
640
+ },
641
+ {
642
+ "epoch": 0.09,
643
+ "grad_norm": 0.5189251339815161,
644
+ "learning_rate": 0.0005911296507695284,
645
+ "loss": 6.2812,
646
+ "step": 91
647
+ },
648
+ {
649
+ "epoch": 0.09,
650
+ "grad_norm": 0.6304909542669104,
651
+ "learning_rate": 0.0005909105225893564,
652
+ "loss": 6.2969,
653
+ "step": 92
654
+ },
655
+ {
656
+ "epoch": 0.09,
657
+ "grad_norm": 0.4655662819622591,
658
+ "learning_rate": 0.0005906887670431187,
659
+ "loss": 6.1953,
660
+ "step": 93
661
+ },
662
+ {
663
+ "epoch": 0.09,
664
+ "grad_norm": 0.39035390983920965,
665
+ "learning_rate": 0.000590464386363891,
666
+ "loss": 6.2617,
667
+ "step": 94
668
+ },
669
+ {
670
+ "epoch": 0.09,
671
+ "grad_norm": 0.4918417851770978,
672
+ "learning_rate": 0.0005902373828111843,
673
+ "loss": 6.2148,
674
+ "step": 95
675
+ },
676
+ {
677
+ "epoch": 0.1,
678
+ "grad_norm": 0.35670770889552555,
679
+ "learning_rate": 0.0005900077586709219,
680
+ "loss": 6.2461,
681
+ "step": 96
682
+ },
683
+ {
684
+ "epoch": 0.1,
685
+ "grad_norm": 0.4177985869939347,
686
+ "learning_rate": 0.0005897755162554163,
687
+ "loss": 6.1797,
688
+ "step": 97
689
+ },
690
+ {
691
+ "epoch": 0.1,
692
+ "grad_norm": 0.3742471130708234,
693
+ "learning_rate": 0.000589540657903346,
694
+ "loss": 6.1406,
695
+ "step": 98
696
+ },
697
+ {
698
+ "epoch": 0.1,
699
+ "grad_norm": 0.28627666723978284,
700
+ "learning_rate": 0.0005893031859797322,
701
+ "loss": 6.2031,
702
+ "step": 99
703
+ },
704
+ {
705
+ "epoch": 0.1,
706
+ "grad_norm": 0.32238563846046103,
707
+ "learning_rate": 0.0005890631028759143,
708
+ "loss": 6.0625,
709
+ "step": 100
710
+ },
711
+ {
712
+ "epoch": 0.1,
713
+ "grad_norm": 0.2556625657587849,
714
+ "learning_rate": 0.0005888204110095265,
715
+ "loss": 6.1797,
716
+ "step": 101
717
+ },
718
+ {
719
+ "epoch": 0.1,
720
+ "grad_norm": 0.35463629701710253,
721
+ "learning_rate": 0.0005885751128244734,
722
+ "loss": 6.125,
723
+ "step": 102
724
+ },
725
+ {
726
+ "epoch": 0.1,
727
+ "grad_norm": 0.31975770214936095,
728
+ "learning_rate": 0.0005883272107909048,
729
+ "loss": 6.1836,
730
+ "step": 103
731
+ },
732
+ {
733
+ "epoch": 0.1,
734
+ "grad_norm": 0.3464621815245048,
735
+ "learning_rate": 0.0005880767074051915,
736
+ "loss": 6.125,
737
+ "step": 104
738
+ },
739
+ {
740
+ "epoch": 0.1,
741
+ "grad_norm": 0.3663428920796654,
742
+ "learning_rate": 0.0005878236051898998,
743
+ "loss": 6.0781,
744
+ "step": 105
745
+ },
746
+ {
747
+ "epoch": 0.11,
748
+ "grad_norm": 0.31594460565215293,
749
+ "learning_rate": 0.0005875679066937664,
750
+ "loss": 6.082,
751
+ "step": 106
752
+ },
753
+ {
754
+ "epoch": 0.11,
755
+ "grad_norm": 0.3552617109396582,
756
+ "learning_rate": 0.000587309614491672,
757
+ "loss": 6.1016,
758
+ "step": 107
759
+ },
760
+ {
761
+ "epoch": 0.11,
762
+ "grad_norm": 0.307016409692456,
763
+ "learning_rate": 0.0005870487311846164,
764
+ "loss": 6.1406,
765
+ "step": 108
766
+ },
767
+ {
768
+ "epoch": 0.11,
769
+ "grad_norm": 0.32188902148474213,
770
+ "learning_rate": 0.0005867852593996914,
771
+ "loss": 6.0039,
772
+ "step": 109
773
+ },
774
+ {
775
+ "epoch": 0.11,
776
+ "grad_norm": 0.25501199715105083,
777
+ "learning_rate": 0.0005865192017900551,
778
+ "loss": 6.0938,
779
+ "step": 110
780
+ },
781
+ {
782
+ "epoch": 0.11,
783
+ "grad_norm": 0.3416203070024056,
784
+ "learning_rate": 0.0005862505610349049,
785
+ "loss": 6.0234,
786
+ "step": 111
787
+ },
788
+ {
789
+ "epoch": 0.11,
790
+ "grad_norm": 0.3562508875852537,
791
+ "learning_rate": 0.0005859793398394498,
792
+ "loss": 6.0469,
793
+ "step": 112
794
+ },
795
+ {
796
+ "epoch": 0.11,
797
+ "grad_norm": 0.4443953757302568,
798
+ "learning_rate": 0.0005857055409348845,
799
+ "loss": 5.9766,
800
+ "step": 113
801
+ },
802
+ {
803
+ "epoch": 0.11,
804
+ "grad_norm": 0.42023839332714596,
805
+ "learning_rate": 0.0005854291670783607,
806
+ "loss": 6.0781,
807
+ "step": 114
808
+ },
809
+ {
810
+ "epoch": 0.11,
811
+ "grad_norm": 0.4618323255809241,
812
+ "learning_rate": 0.0005851502210529604,
813
+ "loss": 5.9727,
814
+ "step": 115
815
+ },
816
+ {
817
+ "epoch": 0.12,
818
+ "grad_norm": 0.379195014798667,
819
+ "learning_rate": 0.0005848687056676668,
820
+ "loss": 5.9922,
821
+ "step": 116
822
+ },
823
+ {
824
+ "epoch": 0.12,
825
+ "grad_norm": 0.3931552573296799,
826
+ "learning_rate": 0.0005845846237573366,
827
+ "loss": 5.9492,
828
+ "step": 117
829
+ },
830
+ {
831
+ "epoch": 0.12,
832
+ "grad_norm": 0.2567080044949908,
833
+ "learning_rate": 0.0005842979781826717,
834
+ "loss": 6.0273,
835
+ "step": 118
836
+ },
837
+ {
838
+ "epoch": 0.12,
839
+ "grad_norm": 0.4190305965377807,
840
+ "learning_rate": 0.0005840087718301895,
841
+ "loss": 6.0391,
842
+ "step": 119
843
+ },
844
+ {
845
+ "epoch": 0.12,
846
+ "grad_norm": 0.3996803869430228,
847
+ "learning_rate": 0.0005837170076121951,
848
+ "loss": 5.9531,
849
+ "step": 120
850
+ },
851
+ {
852
+ "epoch": 0.12,
853
+ "grad_norm": 0.478219248015785,
854
+ "learning_rate": 0.000583422688466751,
855
+ "loss": 6.0586,
856
+ "step": 121
857
+ },
858
+ {
859
+ "epoch": 0.12,
860
+ "grad_norm": 0.40869844309811526,
861
+ "learning_rate": 0.0005831258173576474,
862
+ "loss": 6.0117,
863
+ "step": 122
864
+ },
865
+ {
866
+ "epoch": 0.12,
867
+ "grad_norm": 0.3728598080697978,
868
+ "learning_rate": 0.0005828263972743733,
869
+ "loss": 5.9375,
870
+ "step": 123
871
+ },
872
+ {
873
+ "epoch": 0.12,
874
+ "grad_norm": 0.3560055462882015,
875
+ "learning_rate": 0.0005825244312320856,
876
+ "loss": 5.9531,
877
+ "step": 124
878
+ },
879
+ {
880
+ "epoch": 0.12,
881
+ "grad_norm": 0.40446932887864323,
882
+ "learning_rate": 0.0005822199222715787,
883
+ "loss": 5.9609,
884
+ "step": 125
885
+ },
886
+ {
887
+ "epoch": 0.13,
888
+ "grad_norm": 0.38514065739946723,
889
+ "learning_rate": 0.000581912873459255,
890
+ "loss": 5.8594,
891
+ "step": 126
892
+ },
893
+ {
894
+ "epoch": 0.13,
895
+ "grad_norm": 0.35367576386319416,
896
+ "learning_rate": 0.0005816032878870921,
897
+ "loss": 5.9023,
898
+ "step": 127
899
+ },
900
+ {
901
+ "epoch": 0.13,
902
+ "grad_norm": 0.3341681995122829,
903
+ "learning_rate": 0.0005812911686726135,
904
+ "loss": 5.9062,
905
+ "step": 128
906
+ },
907
+ {
908
+ "epoch": 0.13,
909
+ "grad_norm": 0.3387022688975784,
910
+ "learning_rate": 0.0005809765189588563,
911
+ "loss": 5.8945,
912
+ "step": 129
913
+ },
914
+ {
915
+ "epoch": 0.13,
916
+ "grad_norm": 0.31638659898934757,
917
+ "learning_rate": 0.0005806593419143395,
918
+ "loss": 5.8242,
919
+ "step": 130
920
+ },
921
+ {
922
+ "epoch": 0.13,
923
+ "grad_norm": 0.3229678508227436,
924
+ "learning_rate": 0.0005803396407330325,
925
+ "loss": 5.8516,
926
+ "step": 131
927
+ },
928
+ {
929
+ "epoch": 0.13,
930
+ "grad_norm": 0.35499490868584455,
931
+ "learning_rate": 0.0005800174186343226,
932
+ "loss": 5.9258,
933
+ "step": 132
934
+ },
935
+ {
936
+ "epoch": 0.13,
937
+ "grad_norm": 0.40753171542848754,
938
+ "learning_rate": 0.0005796926788629828,
939
+ "loss": 5.8242,
940
+ "step": 133
941
+ },
942
+ {
943
+ "epoch": 0.13,
944
+ "grad_norm": 0.3625374018348824,
945
+ "learning_rate": 0.0005793654246891389,
946
+ "loss": 5.832,
947
+ "step": 134
948
+ },
949
+ {
950
+ "epoch": 0.13,
951
+ "grad_norm": 0.3583489573569317,
952
+ "learning_rate": 0.000579035659408237,
953
+ "loss": 5.8398,
954
+ "step": 135
955
+ },
956
+ {
957
+ "epoch": 0.14,
958
+ "grad_norm": 0.39657706318861896,
959
+ "learning_rate": 0.0005787033863410095,
960
+ "loss": 5.8633,
961
+ "step": 136
962
+ },
963
+ {
964
+ "epoch": 0.14,
965
+ "grad_norm": 0.3965837889564036,
966
+ "learning_rate": 0.0005783686088334428,
967
+ "loss": 5.8633,
968
+ "step": 137
969
+ },
970
+ {
971
+ "epoch": 0.14,
972
+ "grad_norm": 0.29496474301865566,
973
+ "learning_rate": 0.0005780313302567424,
974
+ "loss": 5.8203,
975
+ "step": 138
976
+ },
977
+ {
978
+ "epoch": 0.14,
979
+ "grad_norm": 0.44637192639243695,
980
+ "learning_rate": 0.0005776915540073001,
981
+ "loss": 5.8477,
982
+ "step": 139
983
+ },
984
+ {
985
+ "epoch": 0.14,
986
+ "grad_norm": 0.39605473508683114,
987
+ "learning_rate": 0.0005773492835066587,
988
+ "loss": 5.7383,
989
+ "step": 140
990
+ },
991
+ {
992
+ "epoch": 0.14,
993
+ "grad_norm": 0.3008962634266945,
994
+ "learning_rate": 0.0005770045222014786,
995
+ "loss": 5.7617,
996
+ "step": 141
997
+ },
998
+ {
999
+ "epoch": 0.14,
1000
+ "grad_norm": 0.36915495506607826,
1001
+ "learning_rate": 0.0005766572735635022,
1002
+ "loss": 5.7695,
1003
+ "step": 142
1004
+ },
1005
+ {
1006
+ "epoch": 0.14,
1007
+ "grad_norm": 0.3282300349560706,
1008
+ "learning_rate": 0.0005763075410895193,
1009
+ "loss": 5.8281,
1010
+ "step": 143
1011
+ },
1012
+ {
1013
+ "epoch": 0.14,
1014
+ "grad_norm": 0.2747449814083844,
1015
+ "learning_rate": 0.0005759553283013323,
1016
+ "loss": 5.7812,
1017
+ "step": 144
1018
+ },
1019
+ {
1020
+ "epoch": 0.14,
1021
+ "grad_norm": 0.28905882704179764,
1022
+ "learning_rate": 0.00057560063874572,
1023
+ "loss": 5.7344,
1024
+ "step": 145
1025
+ },
1026
+ {
1027
+ "epoch": 0.15,
1028
+ "grad_norm": 0.280625988867192,
1029
+ "learning_rate": 0.000575243475994402,
1030
+ "loss": 5.7773,
1031
+ "step": 146
1032
+ },
1033
+ {
1034
+ "epoch": 0.15,
1035
+ "grad_norm": 0.41061863948012467,
1036
+ "learning_rate": 0.0005748838436440035,
1037
+ "loss": 5.7578,
1038
+ "step": 147
1039
+ },
1040
+ {
1041
+ "epoch": 0.15,
1042
+ "grad_norm": 0.4920152483870267,
1043
+ "learning_rate": 0.0005745217453160183,
1044
+ "loss": 5.7305,
1045
+ "step": 148
1046
+ },
1047
+ {
1048
+ "epoch": 0.15,
1049
+ "grad_norm": 0.5463207978955044,
1050
+ "learning_rate": 0.0005741571846567725,
1051
+ "loss": 5.7383,
1052
+ "step": 149
1053
+ },
1054
+ {
1055
+ "epoch": 0.15,
1056
+ "grad_norm": 0.3986359831157306,
1057
+ "learning_rate": 0.0005737901653373878,
1058
+ "loss": 5.668,
1059
+ "step": 150
1060
+ },
1061
+ {
1062
+ "epoch": 0.15,
1063
+ "grad_norm": 0.37908758170100293,
1064
+ "learning_rate": 0.0005734206910537447,
1065
+ "loss": 5.6875,
1066
+ "step": 151
1067
+ },
1068
+ {
1069
+ "epoch": 0.15,
1070
+ "grad_norm": 0.35929793070492694,
1071
+ "learning_rate": 0.0005730487655264451,
1072
+ "loss": 5.7188,
1073
+ "step": 152
1074
+ },
1075
+ {
1076
+ "epoch": 0.15,
1077
+ "grad_norm": 0.4217799574145456,
1078
+ "learning_rate": 0.0005726743925007751,
1079
+ "loss": 5.7305,
1080
+ "step": 153
1081
+ },
1082
+ {
1083
+ "epoch": 0.15,
1084
+ "grad_norm": 0.4024411981587195,
1085
+ "learning_rate": 0.0005722975757466667,
1086
+ "loss": 5.6289,
1087
+ "step": 154
1088
+ },
1089
+ {
1090
+ "epoch": 0.15,
1091
+ "grad_norm": 0.3472391905877033,
1092
+ "learning_rate": 0.0005719183190586606,
1093
+ "loss": 5.6523,
1094
+ "step": 155
1095
+ },
1096
+ {
1097
+ "epoch": 0.16,
1098
+ "grad_norm": 0.31752956812138816,
1099
+ "learning_rate": 0.0005715366262558675,
1100
+ "loss": 5.6172,
1101
+ "step": 156
1102
+ },
1103
+ {
1104
+ "epoch": 0.16,
1105
+ "grad_norm": 0.3170152384332457,
1106
+ "learning_rate": 0.0005711525011819294,
1107
+ "loss": 5.6172,
1108
+ "step": 157
1109
+ },
1110
+ {
1111
+ "epoch": 0.16,
1112
+ "grad_norm": 0.40520629326601837,
1113
+ "learning_rate": 0.0005707659477049818,
1114
+ "loss": 5.625,
1115
+ "step": 158
1116
+ },
1117
+ {
1118
+ "epoch": 0.16,
1119
+ "grad_norm": 0.3965976910198806,
1120
+ "learning_rate": 0.0005703769697176137,
1121
+ "loss": 5.6562,
1122
+ "step": 159
1123
+ },
1124
+ {
1125
+ "epoch": 0.16,
1126
+ "grad_norm": 0.40422960541801994,
1127
+ "learning_rate": 0.0005699855711368293,
1128
+ "loss": 5.6836,
1129
+ "step": 160
1130
+ },
1131
+ {
1132
+ "epoch": 0.16,
1133
+ "grad_norm": 0.3780813184050647,
1134
+ "learning_rate": 0.0005695917559040079,
1135
+ "loss": 5.5938,
1136
+ "step": 161
1137
+ },
1138
+ {
1139
+ "epoch": 0.16,
1140
+ "grad_norm": 0.36917638857736573,
1141
+ "learning_rate": 0.0005691955279848645,
1142
+ "loss": 5.668,
1143
+ "step": 162
1144
+ },
1145
+ {
1146
+ "epoch": 0.16,
1147
+ "grad_norm": 0.37769176081037814,
1148
+ "learning_rate": 0.0005687968913694098,
1149
+ "loss": 5.4961,
1150
+ "step": 163
1151
+ },
1152
+ {
1153
+ "epoch": 0.16,
1154
+ "grad_norm": 0.3255116524991148,
1155
+ "learning_rate": 0.0005683958500719103,
1156
+ "loss": 5.5117,
1157
+ "step": 164
1158
+ },
1159
+ {
1160
+ "epoch": 0.16,
1161
+ "grad_norm": 0.31897629016848805,
1162
+ "learning_rate": 0.0005679924081308471,
1163
+ "loss": 5.5664,
1164
+ "step": 165
1165
+ },
1166
+ {
1167
+ "epoch": 0.17,
1168
+ "grad_norm": 0.2869064236553046,
1169
+ "learning_rate": 0.0005675865696088764,
1170
+ "loss": 5.5391,
1171
+ "step": 166
1172
+ },
1173
+ {
1174
+ "epoch": 0.17,
1175
+ "grad_norm": 0.29226729022634845,
1176
+ "learning_rate": 0.0005671783385927873,
1177
+ "loss": 5.5586,
1178
+ "step": 167
1179
+ },
1180
+ {
1181
+ "epoch": 0.17,
1182
+ "grad_norm": 0.2534117210955766,
1183
+ "learning_rate": 0.0005667677191934618,
1184
+ "loss": 5.5312,
1185
+ "step": 168
1186
+ },
1187
+ {
1188
+ "epoch": 0.17,
1189
+ "grad_norm": 0.289828484125484,
1190
+ "learning_rate": 0.0005663547155458326,
1191
+ "loss": 5.6484,
1192
+ "step": 169
1193
+ },
1194
+ {
1195
+ "epoch": 0.17,
1196
+ "grad_norm": 0.2717242930342115,
1197
+ "learning_rate": 0.0005659393318088419,
1198
+ "loss": 5.5352,
1199
+ "step": 170
1200
+ },
1201
+ {
1202
+ "epoch": 0.17,
1203
+ "grad_norm": 0.3595538109137759,
1204
+ "learning_rate": 0.0005655215721653993,
1205
+ "loss": 5.5742,
1206
+ "step": 171
1207
+ },
1208
+ {
1209
+ "epoch": 0.17,
1210
+ "grad_norm": 0.4255054350471108,
1211
+ "learning_rate": 0.0005651014408223398,
1212
+ "loss": 5.5469,
1213
+ "step": 172
1214
+ },
1215
+ {
1216
+ "epoch": 0.17,
1217
+ "grad_norm": 0.3670561941219979,
1218
+ "learning_rate": 0.0005646789420103814,
1219
+ "loss": 5.5078,
1220
+ "step": 173
1221
+ },
1222
+ {
1223
+ "epoch": 0.17,
1224
+ "grad_norm": 0.40280130904983164,
1225
+ "learning_rate": 0.0005642540799840822,
1226
+ "loss": 5.5,
1227
+ "step": 174
1228
+ },
1229
+ {
1230
+ "epoch": 0.17,
1231
+ "grad_norm": 0.41159472035983025,
1232
+ "learning_rate": 0.0005638268590217984,
1233
+ "loss": 5.5039,
1234
+ "step": 175
1235
+ },
1236
+ {
1237
+ "epoch": 0.18,
1238
+ "grad_norm": 0.4316778037513652,
1239
+ "learning_rate": 0.0005633972834256401,
1240
+ "loss": 5.5352,
1241
+ "step": 176
1242
+ },
1243
+ {
1244
+ "epoch": 0.18,
1245
+ "grad_norm": 0.5674781128363939,
1246
+ "learning_rate": 0.000562965357521429,
1247
+ "loss": 5.4336,
1248
+ "step": 177
1249
+ },
1250
+ {
1251
+ "epoch": 0.18,
1252
+ "grad_norm": 0.41654662151365446,
1253
+ "learning_rate": 0.0005625310856586541,
1254
+ "loss": 5.6211,
1255
+ "step": 178
1256
+ },
1257
+ {
1258
+ "epoch": 0.18,
1259
+ "grad_norm": 0.5159976364107484,
1260
+ "learning_rate": 0.0005620944722104282,
1261
+ "loss": 5.4844,
1262
+ "step": 179
1263
+ },
1264
+ {
1265
+ "epoch": 0.18,
1266
+ "grad_norm": 0.34364678177014185,
1267
+ "learning_rate": 0.0005616555215734438,
1268
+ "loss": 5.4922,
1269
+ "step": 180
1270
+ },
1271
+ {
1272
+ "epoch": 0.18,
1273
+ "grad_norm": 0.3708077784459011,
1274
+ "learning_rate": 0.0005612142381679289,
1275
+ "loss": 5.5234,
1276
+ "step": 181
1277
+ },
1278
+ {
1279
+ "epoch": 0.18,
1280
+ "grad_norm": 0.3620051253453866,
1281
+ "learning_rate": 0.0005607706264376028,
1282
+ "loss": 5.4961,
1283
+ "step": 182
1284
+ },
1285
+ {
1286
+ "epoch": 0.18,
1287
+ "grad_norm": 0.34735585210929654,
1288
+ "learning_rate": 0.0005603246908496305,
1289
+ "loss": 5.4453,
1290
+ "step": 183
1291
+ },
1292
+ {
1293
+ "epoch": 0.18,
1294
+ "grad_norm": 0.37719874705792217,
1295
+ "learning_rate": 0.0005598764358945783,
1296
+ "loss": 5.4844,
1297
+ "step": 184
1298
+ },
1299
+ {
1300
+ "epoch": 0.18,
1301
+ "grad_norm": 0.3749130664831207,
1302
+ "learning_rate": 0.0005594258660863689,
1303
+ "loss": 5.4648,
1304
+ "step": 185
1305
+ },
1306
+ {
1307
+ "epoch": 0.19,
1308
+ "grad_norm": 0.40951353306235827,
1309
+ "learning_rate": 0.0005589729859622351,
1310
+ "loss": 5.5039,
1311
+ "step": 186
1312
+ },
1313
+ {
1314
+ "epoch": 0.19,
1315
+ "grad_norm": 0.40146882563949804,
1316
+ "learning_rate": 0.0005585178000826745,
1317
+ "loss": 5.3672,
1318
+ "step": 187
1319
+ },
1320
+ {
1321
+ "epoch": 0.19,
1322
+ "grad_norm": 0.4062987628428303,
1323
+ "learning_rate": 0.0005580603130314043,
1324
+ "loss": 5.3984,
1325
+ "step": 188
1326
+ },
1327
+ {
1328
+ "epoch": 0.19,
1329
+ "grad_norm": 0.35626322654799136,
1330
+ "learning_rate": 0.0005576005294153138,
1331
+ "loss": 5.3984,
1332
+ "step": 189
1333
+ },
1334
+ {
1335
+ "epoch": 0.19,
1336
+ "grad_norm": 0.3140647930801716,
1337
+ "learning_rate": 0.0005571384538644188,
1338
+ "loss": 5.3906,
1339
+ "step": 190
1340
+ },
1341
+ {
1342
+ "epoch": 0.19,
1343
+ "grad_norm": 0.2990060538353662,
1344
+ "learning_rate": 0.0005566740910318153,
1345
+ "loss": 5.3711,
1346
+ "step": 191
1347
+ },
1348
+ {
1349
+ "epoch": 0.19,
1350
+ "grad_norm": 0.3337525907515936,
1351
+ "learning_rate": 0.0005562074455936315,
1352
+ "loss": 5.4023,
1353
+ "step": 192
1354
+ },
1355
+ {
1356
+ "epoch": 0.19,
1357
+ "grad_norm": 0.3381587051014816,
1358
+ "learning_rate": 0.000555738522248982,
1359
+ "loss": 5.4414,
1360
+ "step": 193
1361
+ },
1362
+ {
1363
+ "epoch": 0.19,
1364
+ "grad_norm": 0.2954008999469894,
1365
+ "learning_rate": 0.0005552673257199197,
1366
+ "loss": 5.418,
1367
+ "step": 194
1368
+ },
1369
+ {
1370
+ "epoch": 0.19,
1371
+ "grad_norm": 0.3242310900810155,
1372
+ "learning_rate": 0.0005547938607513882,
1373
+ "loss": 5.418,
1374
+ "step": 195
1375
+ },
1376
+ {
1377
+ "epoch": 0.2,
1378
+ "grad_norm": 0.3149021804393678,
1379
+ "learning_rate": 0.0005543181321111747,
1380
+ "loss": 5.4375,
1381
+ "step": 196
1382
+ },
1383
+ {
1384
+ "epoch": 0.2,
1385
+ "grad_norm": 0.32859412218218814,
1386
+ "learning_rate": 0.0005538401445898612,
1387
+ "loss": 5.4492,
1388
+ "step": 197
1389
+ },
1390
+ {
1391
+ "epoch": 0.2,
1392
+ "grad_norm": 0.2960282598050701,
1393
+ "learning_rate": 0.0005533599030007768,
1394
+ "loss": 5.3867,
1395
+ "step": 198
1396
+ },
1397
+ {
1398
+ "epoch": 0.2,
1399
+ "grad_norm": 0.2866762878199755,
1400
+ "learning_rate": 0.0005528774121799489,
1401
+ "loss": 5.3789,
1402
+ "step": 199
1403
+ },
1404
+ {
1405
+ "epoch": 0.2,
1406
+ "grad_norm": 0.34865216327038784,
1407
+ "learning_rate": 0.0005523926769860549,
1408
+ "loss": 5.3711,
1409
+ "step": 200
1410
+ }
1411
+ ],
1412
+ "logging_steps": 1,
1413
+ "max_steps": 1000,
1414
+ "num_input_tokens_seen": 0,
1415
+ "num_train_epochs": 1,
1416
+ "save_steps": 100,
1417
+ "total_flos": 0.0,
1418
+ "train_batch_size": 32,
1419
+ "trial_name": null,
1420
+ "trial_params": null
1421
+ }
checkpoint-200/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bbd9a6067cf818494e2505097746a1cad30533fc72eb13916de34f7671e3e456
3
+ size 6520
checkpoint-200/zero_to_fp32.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
215
+ exclude_frozen_parameters)
216
+ elif zero_stage == 3:
217
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
218
+ exclude_frozen_parameters)
219
+
220
+
221
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
222
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
223
+ return
224
+
225
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
226
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
227
+
228
+ if debug:
229
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
230
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
231
+
232
+ wanted_params = len(frozen_param_shapes)
233
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
234
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
235
+ print(f'Frozen params: Have {avail_numel} numels to process.')
236
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
237
+
238
+ total_params = 0
239
+ total_numel = 0
240
+ for name, shape in frozen_param_shapes.items():
241
+ total_params += 1
242
+ unpartitioned_numel = shape.numel()
243
+ total_numel += unpartitioned_numel
244
+
245
+ state_dict[name] = frozen_param_fragments[name]
246
+
247
+ if debug:
248
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
249
+
250
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
251
+
252
+
253
+ def _has_callable(obj, fn):
254
+ attr = getattr(obj, fn, None)
255
+ return callable(attr)
256
+
257
+
258
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
259
+ param_shapes = zero_model_states[0].param_shapes
260
+
261
+ # Reconstruction protocol:
262
+ #
263
+ # XXX: document this
264
+
265
+ if debug:
266
+ for i in range(world_size):
267
+ for j in range(len(fp32_flat_groups[0])):
268
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
269
+
270
+ # XXX: memory usage doubles here (zero2)
271
+ num_param_groups = len(fp32_flat_groups[0])
272
+ merged_single_partition_of_fp32_groups = []
273
+ for i in range(num_param_groups):
274
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
275
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
276
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
277
+ avail_numel = sum(
278
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
279
+
280
+ if debug:
281
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
282
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
283
+ # not asserting if there is a mismatch due to possible padding
284
+ print(f"Have {avail_numel} numels to process.")
285
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
286
+
287
+ # params
288
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
289
+ # out-of-core computing solution
290
+ total_numel = 0
291
+ total_params = 0
292
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
293
+ offset = 0
294
+ avail_numel = full_single_fp32_vector.numel()
295
+ for name, shape in shapes.items():
296
+
297
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
298
+ total_numel += unpartitioned_numel
299
+ total_params += 1
300
+
301
+ if debug:
302
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
303
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
304
+ offset += unpartitioned_numel
305
+
306
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
307
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
308
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
309
+ # live optimizer object, so we are checking that the numbers are within the right range
310
+ align_to = 2 * world_size
311
+
312
+ def zero2_align(x):
313
+ return align_to * math.ceil(x / align_to)
314
+
315
+ if debug:
316
+ print(f"original offset={offset}, avail_numel={avail_numel}")
317
+
318
+ offset = zero2_align(offset)
319
+ avail_numel = zero2_align(avail_numel)
320
+
321
+ if debug:
322
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
323
+
324
+ # Sanity check
325
+ if offset != avail_numel:
326
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
327
+
328
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
329
+
330
+
331
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
332
+ exclude_frozen_parameters):
333
+ state_dict = OrderedDict()
334
+
335
+ # buffers
336
+ buffers = zero_model_states[0].buffers
337
+ state_dict.update(buffers)
338
+ if debug:
339
+ print(f"added {len(buffers)} buffers")
340
+
341
+ if not exclude_frozen_parameters:
342
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
343
+
344
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
345
+
346
+ # recover shared parameters
347
+ for pair in zero_model_states[0].shared_params:
348
+ if pair[1] in state_dict:
349
+ state_dict[pair[0]] = state_dict[pair[1]]
350
+
351
+ return state_dict
352
+
353
+
354
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
355
+ remainder = unpartitioned_numel % world_size
356
+ padding_numel = (world_size - remainder) if remainder else 0
357
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
358
+ return partitioned_numel, padding_numel
359
+
360
+
361
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
362
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
363
+ return
364
+
365
+ if debug:
366
+ for i in range(world_size):
367
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
368
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
369
+
370
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
371
+ wanted_params = len(frozen_param_shapes)
372
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
373
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
374
+ print(f'Frozen params: Have {avail_numel} numels to process.')
375
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
376
+
377
+ total_params = 0
378
+ total_numel = 0
379
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
380
+ total_params += 1
381
+ unpartitioned_numel = shape.numel()
382
+ total_numel += unpartitioned_numel
383
+
384
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
385
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
386
+
387
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
388
+
389
+ if debug:
390
+ print(
391
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
392
+ )
393
+
394
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
395
+
396
+
397
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
398
+ param_shapes = zero_model_states[0].param_shapes
399
+ avail_numel = fp32_flat_groups[0].numel() * world_size
400
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
401
+ # param, re-consolidating each param, while dealing with padding if any
402
+
403
+ # merge list of dicts, preserving order
404
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
405
+
406
+ if debug:
407
+ for i in range(world_size):
408
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
409
+
410
+ wanted_params = len(param_shapes)
411
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
412
+ # not asserting if there is a mismatch due to possible padding
413
+ avail_numel = fp32_flat_groups[0].numel() * world_size
414
+ print(f"Trainable params: Have {avail_numel} numels to process.")
415
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
416
+
417
+ # params
418
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
419
+ # out-of-core computing solution
420
+ offset = 0
421
+ total_numel = 0
422
+ total_params = 0
423
+ for name, shape in param_shapes.items():
424
+
425
+ unpartitioned_numel = shape.numel()
426
+ total_numel += unpartitioned_numel
427
+ total_params += 1
428
+
429
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
430
+
431
+ if debug:
432
+ print(
433
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
434
+ )
435
+
436
+ # XXX: memory usage doubles here
437
+ state_dict[name] = torch.cat(
438
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
439
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
440
+ offset += partitioned_numel
441
+
442
+ offset *= world_size
443
+
444
+ # Sanity check
445
+ if offset != avail_numel:
446
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
447
+
448
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
449
+
450
+
451
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
452
+ exclude_frozen_parameters):
453
+ state_dict = OrderedDict()
454
+
455
+ # buffers
456
+ buffers = zero_model_states[0].buffers
457
+ state_dict.update(buffers)
458
+ if debug:
459
+ print(f"added {len(buffers)} buffers")
460
+
461
+ if not exclude_frozen_parameters:
462
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
463
+
464
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
465
+
466
+ # recover shared parameters
467
+ for pair in zero_model_states[0].shared_params:
468
+ if pair[1] in state_dict:
469
+ state_dict[pair[0]] = state_dict[pair[1]]
470
+
471
+ return state_dict
472
+
473
+
474
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
475
+ """
476
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
477
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
478
+ via a model hub.
479
+
480
+ Args:
481
+ - ``checkpoint_dir``: path to the desired checkpoint folder
482
+ - ``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``
483
+ - ``exclude_frozen_parameters``: exclude frozen parameters
484
+
485
+ Returns:
486
+ - pytorch ``state_dict``
487
+
488
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
489
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
490
+ the checkpoint.
491
+
492
+ A typical usage might be ::
493
+
494
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
495
+ # do the training and checkpoint saving
496
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
497
+ model = model.cpu() # move to cpu
498
+ model.load_state_dict(state_dict)
499
+ # submit to model hub or save the model to share with others
500
+
501
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
502
+ application. i.e. you will need to re-initialize the deepspeed engine, since
503
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
504
+
505
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
506
+
507
+ """
508
+ if tag is None:
509
+ latest_path = os.path.join(checkpoint_dir, 'latest')
510
+ if os.path.isfile(latest_path):
511
+ with open(latest_path, 'r') as fd:
512
+ tag = fd.read().strip()
513
+ else:
514
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
515
+
516
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
517
+
518
+ if not os.path.isdir(ds_checkpoint_dir):
519
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
520
+
521
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
522
+
523
+
524
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
525
+ """
526
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
527
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
528
+
529
+ Args:
530
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
531
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
532
+ - ``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``
533
+ - ``exclude_frozen_parameters``: exclude frozen parameters
534
+ """
535
+
536
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
537
+ print(f"Saving fp32 state dict to {output_file}")
538
+ torch.save(state_dict, output_file)
539
+
540
+
541
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
542
+ """
543
+ 1. Put the provided model to cpu
544
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
545
+ 3. Load it into the provided model
546
+
547
+ Args:
548
+ - ``model``: the model object to update
549
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
550
+ - ``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``
551
+
552
+ Returns:
553
+ - ``model`: modified model
554
+
555
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
556
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
557
+ conveniently placed for you in the checkpoint folder.
558
+
559
+ A typical usage might be ::
560
+
561
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
562
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
563
+ # submit to model hub or save the model to share with others
564
+
565
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
566
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
567
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
568
+
569
+ """
570
+ logger.info(f"Extracting fp32 weights")
571
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
572
+
573
+ logger.info(f"Overwriting model with fp32 weights")
574
+ model = model.cpu()
575
+ model.load_state_dict(state_dict, strict=False)
576
+
577
+ return model
578
+
579
+
580
+ if __name__ == "__main__":
581
+
582
+ parser = argparse.ArgumentParser()
583
+ parser.add_argument("checkpoint_dir",
584
+ type=str,
585
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
586
+ parser.add_argument(
587
+ "output_file",
588
+ type=str,
589
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
590
+ parser.add_argument("-t",
591
+ "--tag",
592
+ type=str,
593
+ default=None,
594
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
595
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
596
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
597
+ args = parser.parse_args()
598
+
599
+ debug = args.debug
600
+
601
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
602
+ args.output_file,
603
+ tag=args.tag,
604
+ exclude_frozen_parameters=args.exclude_frozen_parameters)
checkpoint-25/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "georgeyw/gpt-2-small-init-seed-5",
3
+ "architectures": [
4
+ "GPTNeoXForCausalLM"
5
+ ],
6
+ "attention_bias": true,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 0,
9
+ "classifier_dropout": 0.1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "gelu",
12
+ "hidden_dropout": 0.0,
13
+ "hidden_size": 768,
14
+ "initializer_range": 0.02,
15
+ "intermediate_size": 3072,
16
+ "layer_norm_eps": 1e-05,
17
+ "layer_norm_epsilon": 1e-05,
18
+ "max_position_embeddings": 1024,
19
+ "model_type": "gpt_neox",
20
+ "num_attention_heads": 12,
21
+ "num_hidden_layers": 12,
22
+ "rope_scaling": null,
23
+ "rotary_emb_base": 10000,
24
+ "rotary_pct": 0.25,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "bfloat16",
27
+ "transformers_version": "4.38.2",
28
+ "use_cache": true,
29
+ "use_parallel_residual": true,
30
+ "vocab_size": 50304
31
+ }