XiangPan commited on
Commit
c7e0f24
·
verified ·
1 Parent(s): f9a740e

Training in progress, step 100, checkpoint

Browse files
checkpoint-100/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GPTNeoXForCausalLM"
4
+ ],
5
+ "attention_bias": true,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "classifier_dropout": 0.1,
9
+ "eos_token_id": 0,
10
+ "hidden_act": "gelu",
11
+ "hidden_dropout": 0.0,
12
+ "hidden_size": 1024,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 4096,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 2048,
17
+ "model_type": "gpt_neox",
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 24,
20
+ "partial_rotary_factor": 0.25,
21
+ "rope_scaling": null,
22
+ "rope_theta": 10000,
23
+ "rotary_emb_base": 10000,
24
+ "rotary_pct": 0.25,
25
+ "tie_word_embeddings": false,
26
+ "torch_dtype": "float16",
27
+ "transformers_version": "4.50.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": 0,
5
+ "transformers_version": "4.50.2"
6
+ }
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:6e641280eb8054f489749c724bf9460f7141b6c4e480a8c66f6c9bbf2c2595eb
3
+ size 810750072
checkpoint-100/global_step100/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:42c329e2c752996f937fc0931fbb1579fd1180b86b85c09ba9849c6f6d4f3888
3
+ size 1216012660
checkpoint-100/global_step100/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:3a672cde24f064fb3f0a7275d01ea3929f16908fd3282825c368c32f0255bb25
3
+ size 1216014068
checkpoint-100/global_step100/zero_pp_rank_2_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82fb79f97f233b414455a1727fbd834d1dec9d62101acea1a87777fc98449e61
3
+ size 1216014132
checkpoint-100/global_step100/zero_pp_rank_3_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9200c39e02038c09e9adb1d711d8751fd8acb05aef61232b0ea95b1c6b48619e
3
+ size 1216012724
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:ac971311f9b703711e45b34dc62e9b5e3945bef27cb42dc1103fe14ef73f0426
3
+ size 810701896
checkpoint-100/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36642765f9acf7ac8a4e1a3bfa5ea9c22a142cdfbfeeb96b983e197f754a4b1e
3
+ size 14960
checkpoint-100/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd9f71d8de3875b8d2f115e69a265a76fb6ee4b01473a67358cddd05b7ac1ba1
3
+ size 14960
checkpoint-100/rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:86fef6e746cbac928ab2e67eac71866b327c2f765173f28a46ee21ddcc06220f
3
+ size 14960
checkpoint-100/rng_state_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a94f5a7d4c7e687cef690df30e6e15ad66167456ca9f35d50069b319c7fe11ec
3
+ size 14960
checkpoint-100/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbe02124a5bd070b2f718c06054742287515af164f6576de7eec1568bdfa7b28
3
+ size 1256
checkpoint-100/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|endoftext|>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "<|endoftext|>",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
checkpoint-100/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-100/tokenizer_config.json ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<|endoftext|>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<|padding|>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "50254": {
23
+ "content": " ",
24
+ "lstrip": false,
25
+ "normalized": true,
26
+ "rstrip": false,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "50255": {
31
+ "content": " ",
32
+ "lstrip": false,
33
+ "normalized": true,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": false
37
+ },
38
+ "50256": {
39
+ "content": " ",
40
+ "lstrip": false,
41
+ "normalized": true,
42
+ "rstrip": false,
43
+ "single_word": false,
44
+ "special": false
45
+ },
46
+ "50257": {
47
+ "content": " ",
48
+ "lstrip": false,
49
+ "normalized": true,
50
+ "rstrip": false,
51
+ "single_word": false,
52
+ "special": false
53
+ },
54
+ "50258": {
55
+ "content": " ",
56
+ "lstrip": false,
57
+ "normalized": true,
58
+ "rstrip": false,
59
+ "single_word": false,
60
+ "special": false
61
+ },
62
+ "50259": {
63
+ "content": " ",
64
+ "lstrip": false,
65
+ "normalized": true,
66
+ "rstrip": false,
67
+ "single_word": false,
68
+ "special": false
69
+ },
70
+ "50260": {
71
+ "content": " ",
72
+ "lstrip": false,
73
+ "normalized": true,
74
+ "rstrip": false,
75
+ "single_word": false,
76
+ "special": false
77
+ },
78
+ "50261": {
79
+ "content": " ",
80
+ "lstrip": false,
81
+ "normalized": true,
82
+ "rstrip": false,
83
+ "single_word": false,
84
+ "special": false
85
+ },
86
+ "50262": {
87
+ "content": " ",
88
+ "lstrip": false,
89
+ "normalized": true,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": false
93
+ },
94
+ "50263": {
95
+ "content": " ",
96
+ "lstrip": false,
97
+ "normalized": true,
98
+ "rstrip": false,
99
+ "single_word": false,
100
+ "special": false
101
+ },
102
+ "50264": {
103
+ "content": " ",
104
+ "lstrip": false,
105
+ "normalized": true,
106
+ "rstrip": false,
107
+ "single_word": false,
108
+ "special": false
109
+ },
110
+ "50265": {
111
+ "content": " ",
112
+ "lstrip": false,
113
+ "normalized": true,
114
+ "rstrip": false,
115
+ "single_word": false,
116
+ "special": false
117
+ },
118
+ "50266": {
119
+ "content": " ",
120
+ "lstrip": false,
121
+ "normalized": true,
122
+ "rstrip": false,
123
+ "single_word": false,
124
+ "special": false
125
+ },
126
+ "50267": {
127
+ "content": " ",
128
+ "lstrip": false,
129
+ "normalized": true,
130
+ "rstrip": false,
131
+ "single_word": false,
132
+ "special": false
133
+ },
134
+ "50268": {
135
+ "content": " ",
136
+ "lstrip": false,
137
+ "normalized": true,
138
+ "rstrip": false,
139
+ "single_word": false,
140
+ "special": false
141
+ },
142
+ "50269": {
143
+ "content": " ",
144
+ "lstrip": false,
145
+ "normalized": true,
146
+ "rstrip": false,
147
+ "single_word": false,
148
+ "special": false
149
+ },
150
+ "50270": {
151
+ "content": " ",
152
+ "lstrip": false,
153
+ "normalized": true,
154
+ "rstrip": false,
155
+ "single_word": false,
156
+ "special": false
157
+ },
158
+ "50271": {
159
+ "content": " ",
160
+ "lstrip": false,
161
+ "normalized": true,
162
+ "rstrip": false,
163
+ "single_word": false,
164
+ "special": false
165
+ },
166
+ "50272": {
167
+ "content": " ",
168
+ "lstrip": false,
169
+ "normalized": true,
170
+ "rstrip": false,
171
+ "single_word": false,
172
+ "special": false
173
+ },
174
+ "50273": {
175
+ "content": " ",
176
+ "lstrip": false,
177
+ "normalized": true,
178
+ "rstrip": false,
179
+ "single_word": false,
180
+ "special": false
181
+ },
182
+ "50274": {
183
+ "content": " ",
184
+ "lstrip": false,
185
+ "normalized": true,
186
+ "rstrip": false,
187
+ "single_word": false,
188
+ "special": false
189
+ },
190
+ "50275": {
191
+ "content": " ",
192
+ "lstrip": false,
193
+ "normalized": true,
194
+ "rstrip": false,
195
+ "single_word": false,
196
+ "special": false
197
+ },
198
+ "50276": {
199
+ "content": " ",
200
+ "lstrip": false,
201
+ "normalized": true,
202
+ "rstrip": false,
203
+ "single_word": false,
204
+ "special": false
205
+ }
206
+ },
207
+ "bos_token": "<|endoftext|>",
208
+ "clean_up_tokenization_spaces": false,
209
+ "eos_token": "<|endoftext|>",
210
+ "extra_special_tokens": {},
211
+ "model_max_length": 1000000000000000019884624838656,
212
+ "pad_token": "<|endoftext|>",
213
+ "tokenizer_class": "GPTNeoXTokenizer",
214
+ "unk_token": "<|endoftext|>"
215
+ }
checkpoint-100/trainer_state.json ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.006993006993006993,
6
+ "eval_steps": 500,
7
+ "global_step": 100,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 6.993006993006993e-05,
14
+ "grad_norm": 5.159224033355713,
15
+ "learning_rate": 1.048951048951049e-06,
16
+ "loss": 11.0749,
17
+ "step": 1
18
+ },
19
+ {
20
+ "epoch": 0.00013986013986013986,
21
+ "grad_norm": 5.171240329742432,
22
+ "learning_rate": 2.097902097902098e-06,
23
+ "loss": 11.076,
24
+ "step": 2
25
+ },
26
+ {
27
+ "epoch": 0.0002097902097902098,
28
+ "grad_norm": 5.199888229370117,
29
+ "learning_rate": 3.146853146853147e-06,
30
+ "loss": 11.0669,
31
+ "step": 3
32
+ },
33
+ {
34
+ "epoch": 0.0002797202797202797,
35
+ "grad_norm": 5.08656120300293,
36
+ "learning_rate": 4.195804195804196e-06,
37
+ "loss": 11.0237,
38
+ "step": 4
39
+ },
40
+ {
41
+ "epoch": 0.00034965034965034965,
42
+ "grad_norm": 5.065122127532959,
43
+ "learning_rate": 5.244755244755245e-06,
44
+ "loss": 10.8949,
45
+ "step": 5
46
+ },
47
+ {
48
+ "epoch": 0.0004195804195804196,
49
+ "grad_norm": 4.298279762268066,
50
+ "learning_rate": 6.293706293706294e-06,
51
+ "loss": 10.675,
52
+ "step": 6
53
+ },
54
+ {
55
+ "epoch": 0.0004895104895104895,
56
+ "grad_norm": 3.8743011951446533,
57
+ "learning_rate": 7.342657342657342e-06,
58
+ "loss": 10.4729,
59
+ "step": 7
60
+ },
61
+ {
62
+ "epoch": 0.0005594405594405594,
63
+ "grad_norm": 3.7294981479644775,
64
+ "learning_rate": 8.391608391608391e-06,
65
+ "loss": 10.3221,
66
+ "step": 8
67
+ },
68
+ {
69
+ "epoch": 0.0006293706293706294,
70
+ "grad_norm": 3.3471932411193848,
71
+ "learning_rate": 9.44055944055944e-06,
72
+ "loss": 10.1544,
73
+ "step": 9
74
+ },
75
+ {
76
+ "epoch": 0.0006993006993006993,
77
+ "grad_norm": 3.088207721710205,
78
+ "learning_rate": 1.048951048951049e-05,
79
+ "loss": 10.0823,
80
+ "step": 10
81
+ },
82
+ {
83
+ "epoch": 0.0007692307692307692,
84
+ "grad_norm": 2.713122606277466,
85
+ "learning_rate": 1.1538461538461538e-05,
86
+ "loss": 9.9324,
87
+ "step": 11
88
+ },
89
+ {
90
+ "epoch": 0.0008391608391608392,
91
+ "grad_norm": 2.5934906005859375,
92
+ "learning_rate": 1.2587412587412587e-05,
93
+ "loss": 9.8238,
94
+ "step": 12
95
+ },
96
+ {
97
+ "epoch": 0.0009090909090909091,
98
+ "grad_norm": 2.258924722671509,
99
+ "learning_rate": 1.3636363636363635e-05,
100
+ "loss": 9.7534,
101
+ "step": 13
102
+ },
103
+ {
104
+ "epoch": 0.000979020979020979,
105
+ "grad_norm": 2.0431277751922607,
106
+ "learning_rate": 1.4685314685314684e-05,
107
+ "loss": 9.683,
108
+ "step": 14
109
+ },
110
+ {
111
+ "epoch": 0.001048951048951049,
112
+ "grad_norm": 2.0174779891967773,
113
+ "learning_rate": 1.5734265734265734e-05,
114
+ "loss": 9.5835,
115
+ "step": 15
116
+ },
117
+ {
118
+ "epoch": 0.0011188811188811189,
119
+ "grad_norm": 1.9392926692962646,
120
+ "learning_rate": 1.6783216783216783e-05,
121
+ "loss": 9.566,
122
+ "step": 16
123
+ },
124
+ {
125
+ "epoch": 0.0011888111888111888,
126
+ "grad_norm": 1.841917634010315,
127
+ "learning_rate": 1.783216783216783e-05,
128
+ "loss": 9.4862,
129
+ "step": 17
130
+ },
131
+ {
132
+ "epoch": 0.0012587412587412587,
133
+ "grad_norm": 1.6751583814620972,
134
+ "learning_rate": 1.888111888111888e-05,
135
+ "loss": 9.4613,
136
+ "step": 18
137
+ },
138
+ {
139
+ "epoch": 0.0013286713286713287,
140
+ "grad_norm": 1.701292634010315,
141
+ "learning_rate": 1.9930069930069928e-05,
142
+ "loss": 9.3861,
143
+ "step": 19
144
+ },
145
+ {
146
+ "epoch": 0.0013986013986013986,
147
+ "grad_norm": 1.7422462701797485,
148
+ "learning_rate": 2.097902097902098e-05,
149
+ "loss": 9.3607,
150
+ "step": 20
151
+ },
152
+ {
153
+ "epoch": 0.0014685314685314685,
154
+ "grad_norm": 1.7331982851028442,
155
+ "learning_rate": 2.2027972027972026e-05,
156
+ "loss": 9.3106,
157
+ "step": 21
158
+ },
159
+ {
160
+ "epoch": 0.0015384615384615385,
161
+ "grad_norm": 1.8083829879760742,
162
+ "learning_rate": 2.3076923076923076e-05,
163
+ "loss": 9.252,
164
+ "step": 22
165
+ },
166
+ {
167
+ "epoch": 0.0016083916083916084,
168
+ "grad_norm": 1.7314563989639282,
169
+ "learning_rate": 2.412587412587412e-05,
170
+ "loss": 9.2325,
171
+ "step": 23
172
+ },
173
+ {
174
+ "epoch": 0.0016783216783216783,
175
+ "grad_norm": 1.5793718099594116,
176
+ "learning_rate": 2.5174825174825174e-05,
177
+ "loss": 9.2489,
178
+ "step": 24
179
+ },
180
+ {
181
+ "epoch": 0.0017482517482517483,
182
+ "grad_norm": 1.5183552503585815,
183
+ "learning_rate": 2.622377622377622e-05,
184
+ "loss": 9.1821,
185
+ "step": 25
186
+ },
187
+ {
188
+ "epoch": 0.0018181818181818182,
189
+ "grad_norm": 1.5751609802246094,
190
+ "learning_rate": 2.727272727272727e-05,
191
+ "loss": 9.1217,
192
+ "step": 26
193
+ },
194
+ {
195
+ "epoch": 0.0018881118881118881,
196
+ "grad_norm": 1.541367530822754,
197
+ "learning_rate": 2.832167832167832e-05,
198
+ "loss": 9.1186,
199
+ "step": 27
200
+ },
201
+ {
202
+ "epoch": 0.001958041958041958,
203
+ "grad_norm": 1.5820801258087158,
204
+ "learning_rate": 2.937062937062937e-05,
205
+ "loss": 9.105,
206
+ "step": 28
207
+ },
208
+ {
209
+ "epoch": 0.002027972027972028,
210
+ "grad_norm": 1.483319640159607,
211
+ "learning_rate": 3.0419580419580414e-05,
212
+ "loss": 9.0772,
213
+ "step": 29
214
+ },
215
+ {
216
+ "epoch": 0.002097902097902098,
217
+ "grad_norm": 1.5269867181777954,
218
+ "learning_rate": 3.146853146853147e-05,
219
+ "loss": 9.0185,
220
+ "step": 30
221
+ },
222
+ {
223
+ "epoch": 0.002167832167832168,
224
+ "grad_norm": 1.4273761510849,
225
+ "learning_rate": 3.251748251748251e-05,
226
+ "loss": 9.0013,
227
+ "step": 31
228
+ },
229
+ {
230
+ "epoch": 0.0022377622377622378,
231
+ "grad_norm": 1.4377866983413696,
232
+ "learning_rate": 3.3566433566433566e-05,
233
+ "loss": 8.9161,
234
+ "step": 32
235
+ },
236
+ {
237
+ "epoch": 0.002307692307692308,
238
+ "grad_norm": 1.369158148765564,
239
+ "learning_rate": 3.461538461538461e-05,
240
+ "loss": 8.917,
241
+ "step": 33
242
+ },
243
+ {
244
+ "epoch": 0.0023776223776223776,
245
+ "grad_norm": 1.328121542930603,
246
+ "learning_rate": 3.566433566433566e-05,
247
+ "loss": 8.8484,
248
+ "step": 34
249
+ },
250
+ {
251
+ "epoch": 0.0024475524475524478,
252
+ "grad_norm": 1.289856195449829,
253
+ "learning_rate": 3.671328671328671e-05,
254
+ "loss": 8.8637,
255
+ "step": 35
256
+ },
257
+ {
258
+ "epoch": 0.0025174825174825175,
259
+ "grad_norm": 1.2946962118148804,
260
+ "learning_rate": 3.776223776223776e-05,
261
+ "loss": 8.8045,
262
+ "step": 36
263
+ },
264
+ {
265
+ "epoch": 0.0025874125874125876,
266
+ "grad_norm": 1.3396406173706055,
267
+ "learning_rate": 3.881118881118881e-05,
268
+ "loss": 8.7569,
269
+ "step": 37
270
+ },
271
+ {
272
+ "epoch": 0.0026573426573426573,
273
+ "grad_norm": 1.3043384552001953,
274
+ "learning_rate": 3.9860139860139855e-05,
275
+ "loss": 8.7184,
276
+ "step": 38
277
+ },
278
+ {
279
+ "epoch": 0.0027272727272727275,
280
+ "grad_norm": 1.2441431283950806,
281
+ "learning_rate": 4.09090909090909e-05,
282
+ "loss": 8.66,
283
+ "step": 39
284
+ },
285
+ {
286
+ "epoch": 0.002797202797202797,
287
+ "grad_norm": 1.1379547119140625,
288
+ "learning_rate": 4.195804195804196e-05,
289
+ "loss": 8.6217,
290
+ "step": 40
291
+ },
292
+ {
293
+ "epoch": 0.0028671328671328673,
294
+ "grad_norm": 1.1792885065078735,
295
+ "learning_rate": 4.300699300699301e-05,
296
+ "loss": 8.5006,
297
+ "step": 41
298
+ },
299
+ {
300
+ "epoch": 0.002937062937062937,
301
+ "grad_norm": 1.183509349822998,
302
+ "learning_rate": 4.405594405594405e-05,
303
+ "loss": 8.5037,
304
+ "step": 42
305
+ },
306
+ {
307
+ "epoch": 0.003006993006993007,
308
+ "grad_norm": 1.1481878757476807,
309
+ "learning_rate": 4.51048951048951e-05,
310
+ "loss": 8.5114,
311
+ "step": 43
312
+ },
313
+ {
314
+ "epoch": 0.003076923076923077,
315
+ "grad_norm": 1.1832213401794434,
316
+ "learning_rate": 4.615384615384615e-05,
317
+ "loss": 8.4117,
318
+ "step": 44
319
+ },
320
+ {
321
+ "epoch": 0.003146853146853147,
322
+ "grad_norm": 1.0428388118743896,
323
+ "learning_rate": 4.72027972027972e-05,
324
+ "loss": 8.4378,
325
+ "step": 45
326
+ },
327
+ {
328
+ "epoch": 0.0032167832167832168,
329
+ "grad_norm": 1.1736469268798828,
330
+ "learning_rate": 4.825174825174824e-05,
331
+ "loss": 8.2981,
332
+ "step": 46
333
+ },
334
+ {
335
+ "epoch": 0.003286713286713287,
336
+ "grad_norm": 1.0533231496810913,
337
+ "learning_rate": 4.930069930069929e-05,
338
+ "loss": 8.3406,
339
+ "step": 47
340
+ },
341
+ {
342
+ "epoch": 0.0033566433566433566,
343
+ "grad_norm": 1.1464074850082397,
344
+ "learning_rate": 5.034965034965035e-05,
345
+ "loss": 8.2388,
346
+ "step": 48
347
+ },
348
+ {
349
+ "epoch": 0.003426573426573427,
350
+ "grad_norm": 1.224696159362793,
351
+ "learning_rate": 5.1398601398601395e-05,
352
+ "loss": 8.208,
353
+ "step": 49
354
+ },
355
+ {
356
+ "epoch": 0.0034965034965034965,
357
+ "grad_norm": 1.1058298349380493,
358
+ "learning_rate": 5.244755244755244e-05,
359
+ "loss": 8.192,
360
+ "step": 50
361
+ },
362
+ {
363
+ "epoch": 0.0035664335664335666,
364
+ "grad_norm": 1.0586011409759521,
365
+ "learning_rate": 5.3496503496503493e-05,
366
+ "loss": 8.1369,
367
+ "step": 51
368
+ },
369
+ {
370
+ "epoch": 0.0036363636363636364,
371
+ "grad_norm": 1.0969116687774658,
372
+ "learning_rate": 5.454545454545454e-05,
373
+ "loss": 8.0515,
374
+ "step": 52
375
+ },
376
+ {
377
+ "epoch": 0.0037062937062937065,
378
+ "grad_norm": 0.9527297616004944,
379
+ "learning_rate": 5.559440559440559e-05,
380
+ "loss": 8.0319,
381
+ "step": 53
382
+ },
383
+ {
384
+ "epoch": 0.0037762237762237762,
385
+ "grad_norm": 1.0115875005722046,
386
+ "learning_rate": 5.664335664335664e-05,
387
+ "loss": 7.9882,
388
+ "step": 54
389
+ },
390
+ {
391
+ "epoch": 0.0038461538461538464,
392
+ "grad_norm": 1.044940710067749,
393
+ "learning_rate": 5.769230769230769e-05,
394
+ "loss": 7.9776,
395
+ "step": 55
396
+ },
397
+ {
398
+ "epoch": 0.003916083916083916,
399
+ "grad_norm": 0.9222269058227539,
400
+ "learning_rate": 5.874125874125874e-05,
401
+ "loss": 7.9327,
402
+ "step": 56
403
+ },
404
+ {
405
+ "epoch": 0.003986013986013986,
406
+ "grad_norm": 0.9342182278633118,
407
+ "learning_rate": 5.979020979020978e-05,
408
+ "loss": 7.853,
409
+ "step": 57
410
+ },
411
+ {
412
+ "epoch": 0.004055944055944056,
413
+ "grad_norm": 0.9146339297294617,
414
+ "learning_rate": 6.083916083916083e-05,
415
+ "loss": 7.8091,
416
+ "step": 58
417
+ },
418
+ {
419
+ "epoch": 0.004125874125874126,
420
+ "grad_norm": 0.8632137775421143,
421
+ "learning_rate": 6.188811188811188e-05,
422
+ "loss": 7.7744,
423
+ "step": 59
424
+ },
425
+ {
426
+ "epoch": 0.004195804195804196,
427
+ "grad_norm": 1.001086711883545,
428
+ "learning_rate": 6.293706293706293e-05,
429
+ "loss": 7.7623,
430
+ "step": 60
431
+ },
432
+ {
433
+ "epoch": 0.0042657342657342655,
434
+ "grad_norm": 0.9110626578330994,
435
+ "learning_rate": 6.398601398601397e-05,
436
+ "loss": 7.7356,
437
+ "step": 61
438
+ },
439
+ {
440
+ "epoch": 0.004335664335664336,
441
+ "grad_norm": 0.7626254558563232,
442
+ "learning_rate": 6.503496503496503e-05,
443
+ "loss": 7.6801,
444
+ "step": 62
445
+ },
446
+ {
447
+ "epoch": 0.004405594405594406,
448
+ "grad_norm": 1.0254472494125366,
449
+ "learning_rate": 6.608391608391608e-05,
450
+ "loss": 7.6111,
451
+ "step": 63
452
+ },
453
+ {
454
+ "epoch": 0.0044755244755244755,
455
+ "grad_norm": 0.9034542441368103,
456
+ "learning_rate": 6.713286713286713e-05,
457
+ "loss": 7.603,
458
+ "step": 64
459
+ },
460
+ {
461
+ "epoch": 0.004545454545454545,
462
+ "grad_norm": 0.685672402381897,
463
+ "learning_rate": 6.818181818181817e-05,
464
+ "loss": 7.5614,
465
+ "step": 65
466
+ },
467
+ {
468
+ "epoch": 0.004615384615384616,
469
+ "grad_norm": 0.9960275292396545,
470
+ "learning_rate": 6.923076923076922e-05,
471
+ "loss": 7.5537,
472
+ "step": 66
473
+ },
474
+ {
475
+ "epoch": 0.0046853146853146855,
476
+ "grad_norm": 0.6702042818069458,
477
+ "learning_rate": 7.027972027972028e-05,
478
+ "loss": 7.4794,
479
+ "step": 67
480
+ },
481
+ {
482
+ "epoch": 0.004755244755244755,
483
+ "grad_norm": 0.8843338489532471,
484
+ "learning_rate": 7.132867132867132e-05,
485
+ "loss": 7.4486,
486
+ "step": 68
487
+ },
488
+ {
489
+ "epoch": 0.004825174825174825,
490
+ "grad_norm": 0.7096754908561707,
491
+ "learning_rate": 7.237762237762237e-05,
492
+ "loss": 7.4253,
493
+ "step": 69
494
+ },
495
+ {
496
+ "epoch": 0.0048951048951048955,
497
+ "grad_norm": 0.8532392382621765,
498
+ "learning_rate": 7.342657342657342e-05,
499
+ "loss": 7.383,
500
+ "step": 70
501
+ },
502
+ {
503
+ "epoch": 0.004965034965034965,
504
+ "grad_norm": 0.7407330870628357,
505
+ "learning_rate": 7.447552447552447e-05,
506
+ "loss": 7.4059,
507
+ "step": 71
508
+ },
509
+ {
510
+ "epoch": 0.005034965034965035,
511
+ "grad_norm": 0.7601925730705261,
512
+ "learning_rate": 7.552447552447553e-05,
513
+ "loss": 7.3522,
514
+ "step": 72
515
+ },
516
+ {
517
+ "epoch": 0.005104895104895105,
518
+ "grad_norm": 0.6095029711723328,
519
+ "learning_rate": 7.657342657342657e-05,
520
+ "loss": 7.3442,
521
+ "step": 73
522
+ },
523
+ {
524
+ "epoch": 0.005174825174825175,
525
+ "grad_norm": 0.8200113773345947,
526
+ "learning_rate": 7.762237762237762e-05,
527
+ "loss": 7.3272,
528
+ "step": 74
529
+ },
530
+ {
531
+ "epoch": 0.005244755244755245,
532
+ "grad_norm": 0.9570252299308777,
533
+ "learning_rate": 7.867132867132867e-05,
534
+ "loss": 7.2258,
535
+ "step": 75
536
+ },
537
+ {
538
+ "epoch": 0.005314685314685315,
539
+ "grad_norm": 1.005595088005066,
540
+ "learning_rate": 7.972027972027971e-05,
541
+ "loss": 7.2552,
542
+ "step": 76
543
+ },
544
+ {
545
+ "epoch": 0.005384615384615384,
546
+ "grad_norm": 0.7686155438423157,
547
+ "learning_rate": 8.076923076923076e-05,
548
+ "loss": 7.2615,
549
+ "step": 77
550
+ },
551
+ {
552
+ "epoch": 0.005454545454545455,
553
+ "grad_norm": 0.6844556927680969,
554
+ "learning_rate": 8.18181818181818e-05,
555
+ "loss": 7.1683,
556
+ "step": 78
557
+ },
558
+ {
559
+ "epoch": 0.005524475524475525,
560
+ "grad_norm": 0.665515661239624,
561
+ "learning_rate": 8.286713286713286e-05,
562
+ "loss": 7.2015,
563
+ "step": 79
564
+ },
565
+ {
566
+ "epoch": 0.005594405594405594,
567
+ "grad_norm": 0.7764729261398315,
568
+ "learning_rate": 8.391608391608392e-05,
569
+ "loss": 7.1474,
570
+ "step": 80
571
+ },
572
+ {
573
+ "epoch": 0.005664335664335664,
574
+ "grad_norm": 0.6877023577690125,
575
+ "learning_rate": 8.496503496503496e-05,
576
+ "loss": 7.1705,
577
+ "step": 81
578
+ },
579
+ {
580
+ "epoch": 0.005734265734265735,
581
+ "grad_norm": 0.678676426410675,
582
+ "learning_rate": 8.601398601398601e-05,
583
+ "loss": 7.1529,
584
+ "step": 82
585
+ },
586
+ {
587
+ "epoch": 0.005804195804195804,
588
+ "grad_norm": 0.8167915940284729,
589
+ "learning_rate": 8.706293706293705e-05,
590
+ "loss": 7.0738,
591
+ "step": 83
592
+ },
593
+ {
594
+ "epoch": 0.005874125874125874,
595
+ "grad_norm": 0.6965641975402832,
596
+ "learning_rate": 8.81118881118881e-05,
597
+ "loss": 7.1085,
598
+ "step": 84
599
+ },
600
+ {
601
+ "epoch": 0.005944055944055944,
602
+ "grad_norm": 0.9094026684761047,
603
+ "learning_rate": 8.916083916083914e-05,
604
+ "loss": 7.0906,
605
+ "step": 85
606
+ },
607
+ {
608
+ "epoch": 0.006013986013986014,
609
+ "grad_norm": 0.7994691133499146,
610
+ "learning_rate": 9.02097902097902e-05,
611
+ "loss": 7.0782,
612
+ "step": 86
613
+ },
614
+ {
615
+ "epoch": 0.006083916083916084,
616
+ "grad_norm": 1.007351279258728,
617
+ "learning_rate": 9.125874125874126e-05,
618
+ "loss": 7.0095,
619
+ "step": 87
620
+ },
621
+ {
622
+ "epoch": 0.006153846153846154,
623
+ "grad_norm": 0.8736310601234436,
624
+ "learning_rate": 9.23076923076923e-05,
625
+ "loss": 6.9629,
626
+ "step": 88
627
+ },
628
+ {
629
+ "epoch": 0.0062237762237762236,
630
+ "grad_norm": 0.6392287015914917,
631
+ "learning_rate": 9.335664335664336e-05,
632
+ "loss": 6.9908,
633
+ "step": 89
634
+ },
635
+ {
636
+ "epoch": 0.006293706293706294,
637
+ "grad_norm": 1.091141939163208,
638
+ "learning_rate": 9.44055944055944e-05,
639
+ "loss": 6.9523,
640
+ "step": 90
641
+ },
642
+ {
643
+ "epoch": 0.006363636363636364,
644
+ "grad_norm": 0.7908533215522766,
645
+ "learning_rate": 9.545454545454545e-05,
646
+ "loss": 6.9238,
647
+ "step": 91
648
+ },
649
+ {
650
+ "epoch": 0.0064335664335664336,
651
+ "grad_norm": 0.6706556081771851,
652
+ "learning_rate": 9.650349650349649e-05,
653
+ "loss": 6.9672,
654
+ "step": 92
655
+ },
656
+ {
657
+ "epoch": 0.006503496503496503,
658
+ "grad_norm": 0.9139024019241333,
659
+ "learning_rate": 9.755244755244754e-05,
660
+ "loss": 6.9997,
661
+ "step": 93
662
+ },
663
+ {
664
+ "epoch": 0.006573426573426574,
665
+ "grad_norm": 0.7192760109901428,
666
+ "learning_rate": 9.860139860139858e-05,
667
+ "loss": 6.936,
668
+ "step": 94
669
+ },
670
+ {
671
+ "epoch": 0.006643356643356644,
672
+ "grad_norm": 0.7734940052032471,
673
+ "learning_rate": 9.965034965034964e-05,
674
+ "loss": 7.0156,
675
+ "step": 95
676
+ },
677
+ {
678
+ "epoch": 0.006713286713286713,
679
+ "grad_norm": 0.8069332838058472,
680
+ "learning_rate": 0.0001006993006993007,
681
+ "loss": 6.8958,
682
+ "step": 96
683
+ },
684
+ {
685
+ "epoch": 0.006783216783216783,
686
+ "grad_norm": 1.0324732065200806,
687
+ "learning_rate": 0.00010174825174825174,
688
+ "loss": 6.8863,
689
+ "step": 97
690
+ },
691
+ {
692
+ "epoch": 0.006853146853146854,
693
+ "grad_norm": 0.6798093318939209,
694
+ "learning_rate": 0.00010279720279720279,
695
+ "loss": 6.8534,
696
+ "step": 98
697
+ },
698
+ {
699
+ "epoch": 0.006923076923076923,
700
+ "grad_norm": 0.7703111171722412,
701
+ "learning_rate": 0.00010384615384615383,
702
+ "loss": 6.7499,
703
+ "step": 99
704
+ },
705
+ {
706
+ "epoch": 0.006993006993006993,
707
+ "grad_norm": 0.941916823387146,
708
+ "learning_rate": 0.00010489510489510488,
709
+ "loss": 6.8574,
710
+ "step": 100
711
+ }
712
+ ],
713
+ "logging_steps": 1,
714
+ "max_steps": 14300,
715
+ "num_input_tokens_seen": 0,
716
+ "num_train_epochs": 9223372036854775807,
717
+ "save_steps": 100,
718
+ "stateful_callbacks": {
719
+ "TrainerControl": {
720
+ "args": {
721
+ "should_epoch_stop": false,
722
+ "should_evaluate": false,
723
+ "should_log": false,
724
+ "should_save": true,
725
+ "should_training_stop": false
726
+ },
727
+ "attributes": {}
728
+ }
729
+ },
730
+ "total_flos": 2.7825750933504e+16,
731
+ "train_batch_size": 64,
732
+ "trial_name": null,
733
+ "trial_params": null
734
+ }
checkpoint-100/training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9d8b5ab7c96eddd31884a55cca6ae1cb4177ea7db30f3aa145cab6706fc99c36
3
+ size 7288
checkpoint-100/zero_to_fp32.py ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
14
+ # python zero_to_fp32.py . output_dir/
15
+ # or
16
+ # python zero_to_fp32.py . output_dir/ --safe_serialization
17
+
18
+ import argparse
19
+ import torch
20
+ import glob
21
+ import math
22
+ import os
23
+ import re
24
+ import gc
25
+ import json
26
+ import numpy as np
27
+ from tqdm import tqdm
28
+ from collections import OrderedDict
29
+ from dataclasses import dataclass
30
+
31
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
32
+ # DeepSpeed data structures it has to be available in the current python environment.
33
+ from deepspeed.utils import logger
34
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
35
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
36
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
37
+
38
+
39
+ @dataclass
40
+ class zero_model_state:
41
+ buffers: dict()
42
+ param_shapes: dict()
43
+ shared_params: list
44
+ ds_version: int
45
+ frozen_param_shapes: dict()
46
+ frozen_param_fragments: dict()
47
+
48
+
49
+ debug = 0
50
+
51
+ # load to cpu
52
+ device = torch.device('cpu')
53
+
54
+
55
+ def atoi(text):
56
+ return int(text) if text.isdigit() else text
57
+
58
+
59
+ def natural_keys(text):
60
+ '''
61
+ alist.sort(key=natural_keys) sorts in human order
62
+ http://nedbatchelder.com/blog/200712/human_sorting.html
63
+ (See Toothy's implementation in the comments)
64
+ '''
65
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
66
+
67
+
68
+ def get_model_state_file(checkpoint_dir, zero_stage):
69
+ if not os.path.isdir(checkpoint_dir):
70
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
71
+
72
+ # there should be only one file
73
+ if zero_stage <= 2:
74
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
75
+ elif zero_stage == 3:
76
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
77
+
78
+ if not os.path.exists(file):
79
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
80
+
81
+ return file
82
+
83
+
84
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
85
+ # XXX: need to test that this simple glob rule works for multi-node setup too
86
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
87
+
88
+ if len(ckpt_files) == 0:
89
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
90
+
91
+ return ckpt_files
92
+
93
+
94
+ def get_optim_files(checkpoint_dir):
95
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
96
+
97
+
98
+ def get_model_state_files(checkpoint_dir):
99
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
100
+
101
+
102
+ def parse_model_states(files):
103
+ zero_model_states = []
104
+ for file in files:
105
+ state_dict = torch.load(file, map_location=device, weights_only=False)
106
+
107
+ if BUFFER_NAMES not in state_dict:
108
+ raise ValueError(f"{file} is not a model state checkpoint")
109
+ buffer_names = state_dict[BUFFER_NAMES]
110
+ if debug:
111
+ print("Found buffers:", buffer_names)
112
+
113
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
114
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
115
+ param_shapes = state_dict[PARAM_SHAPES]
116
+
117
+ # collect parameters that are included in param_shapes
118
+ param_names = []
119
+ for s in param_shapes:
120
+ for name in s.keys():
121
+ param_names.append(name)
122
+
123
+ # update with frozen parameters
124
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
125
+ if frozen_param_shapes is not None:
126
+ if debug:
127
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
128
+ param_names += list(frozen_param_shapes.keys())
129
+
130
+ # handle shared params
131
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
132
+
133
+ ds_version = state_dict.get(DS_VERSION, None)
134
+
135
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
136
+
137
+ z_model_state = zero_model_state(buffers=buffers,
138
+ param_shapes=param_shapes,
139
+ shared_params=shared_params,
140
+ ds_version=ds_version,
141
+ frozen_param_shapes=frozen_param_shapes,
142
+ frozen_param_fragments=frozen_param_fragments)
143
+ zero_model_states.append(z_model_state)
144
+
145
+ return zero_model_states
146
+
147
+
148
+ def parse_optim_states(files, ds_checkpoint_dir):
149
+ total_files = len(files)
150
+ state_dicts = []
151
+ for f in tqdm(files, desc='Loading checkpoint shards'):
152
+ state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False)
153
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
154
+ # and also handle the case where it was already removed by another helper script
155
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
156
+ state_dicts.append(state_dict)
157
+
158
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
159
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
160
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
161
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
162
+
163
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
164
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
165
+ # use the max of the partition_count to get the dp world_size.
166
+
167
+ if type(world_size) is list:
168
+ world_size = max(world_size)
169
+
170
+ if world_size != total_files:
171
+ raise ValueError(
172
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
173
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
174
+ )
175
+
176
+ # the groups are named differently in each stage
177
+ if zero_stage <= 2:
178
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
179
+ elif zero_stage == 3:
180
+ fp32_groups_key = FP32_FLAT_GROUPS
181
+ else:
182
+ raise ValueError(f"unknown zero stage {zero_stage}")
183
+
184
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
185
+ return zero_stage, world_size, fp32_flat_groups
186
+
187
+
188
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
189
+ """
190
+ Returns fp32 state_dict reconstructed from ds checkpoint
191
+
192
+ Args:
193
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
194
+
195
+ """
196
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
197
+
198
+ optim_files = get_optim_files(ds_checkpoint_dir)
199
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
200
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
201
+
202
+ model_files = get_model_state_files(ds_checkpoint_dir)
203
+
204
+ zero_model_states = parse_model_states(model_files)
205
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
206
+
207
+ if zero_stage <= 2:
208
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
209
+ exclude_frozen_parameters)
210
+ elif zero_stage == 3:
211
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
212
+ exclude_frozen_parameters)
213
+
214
+
215
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
216
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
217
+ return
218
+
219
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
220
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
221
+
222
+ if debug:
223
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
224
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
225
+
226
+ wanted_params = len(frozen_param_shapes)
227
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
228
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
229
+ print(f'Frozen params: Have {avail_numel} numels to process.')
230
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
231
+
232
+ total_params = 0
233
+ total_numel = 0
234
+ for name, shape in frozen_param_shapes.items():
235
+ total_params += 1
236
+ unpartitioned_numel = shape.numel()
237
+ total_numel += unpartitioned_numel
238
+
239
+ state_dict[name] = frozen_param_fragments[name]
240
+
241
+ if debug:
242
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
243
+
244
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
245
+
246
+
247
+ def _has_callable(obj, fn):
248
+ attr = getattr(obj, fn, None)
249
+ return callable(attr)
250
+
251
+
252
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
253
+ param_shapes = zero_model_states[0].param_shapes
254
+
255
+ # Reconstruction protocol:
256
+ #
257
+ # XXX: document this
258
+
259
+ if debug:
260
+ for i in range(world_size):
261
+ for j in range(len(fp32_flat_groups[0])):
262
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
263
+
264
+ # XXX: memory usage doubles here (zero2)
265
+ num_param_groups = len(fp32_flat_groups[0])
266
+ merged_single_partition_of_fp32_groups = []
267
+ for i in range(num_param_groups):
268
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
269
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
270
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
271
+ avail_numel = sum(
272
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
273
+
274
+ if debug:
275
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
276
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
277
+ # not asserting if there is a mismatch due to possible padding
278
+ print(f"Have {avail_numel} numels to process.")
279
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
280
+
281
+ # params
282
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
283
+ # out-of-core computing solution
284
+ total_numel = 0
285
+ total_params = 0
286
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
287
+ offset = 0
288
+ avail_numel = full_single_fp32_vector.numel()
289
+ for name, shape in shapes.items():
290
+
291
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
292
+ total_numel += unpartitioned_numel
293
+ total_params += 1
294
+
295
+ if debug:
296
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
297
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
298
+ offset += unpartitioned_numel
299
+
300
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
301
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
302
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
303
+ # live optimizer object, so we are checking that the numbers are within the right range
304
+ align_to = 2 * world_size
305
+
306
+ def zero2_align(x):
307
+ return align_to * math.ceil(x / align_to)
308
+
309
+ if debug:
310
+ print(f"original offset={offset}, avail_numel={avail_numel}")
311
+
312
+ offset = zero2_align(offset)
313
+ avail_numel = zero2_align(avail_numel)
314
+
315
+ if debug:
316
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
317
+
318
+ # Sanity check
319
+ if offset != avail_numel:
320
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
321
+
322
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
323
+
324
+
325
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
326
+ exclude_frozen_parameters):
327
+ state_dict = OrderedDict()
328
+
329
+ # buffers
330
+ buffers = zero_model_states[0].buffers
331
+ state_dict.update(buffers)
332
+ if debug:
333
+ print(f"added {len(buffers)} buffers")
334
+
335
+ if not exclude_frozen_parameters:
336
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
337
+
338
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
339
+
340
+ # recover shared parameters
341
+ for pair in zero_model_states[0].shared_params:
342
+ if pair[1] in state_dict:
343
+ state_dict[pair[0]] = state_dict[pair[1]]
344
+
345
+ return state_dict
346
+
347
+
348
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
349
+ remainder = unpartitioned_numel % world_size
350
+ padding_numel = (world_size - remainder) if remainder else 0
351
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
352
+ return partitioned_numel, padding_numel
353
+
354
+
355
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
356
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
357
+ return
358
+
359
+ if debug:
360
+ for i in range(world_size):
361
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
362
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
363
+
364
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
365
+ wanted_params = len(frozen_param_shapes)
366
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
367
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
368
+ print(f'Frozen params: Have {avail_numel} numels to process.')
369
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
370
+
371
+ total_params = 0
372
+ total_numel = 0
373
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
374
+ total_params += 1
375
+ unpartitioned_numel = shape.numel()
376
+ total_numel += unpartitioned_numel
377
+
378
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
379
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
380
+
381
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
382
+
383
+ if debug:
384
+ print(
385
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
386
+ )
387
+
388
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
389
+
390
+
391
+ class GatheredTensor:
392
+ """
393
+ A pseudo tensor that collects partitioned weights.
394
+ It is more memory efficient when there are multiple groups.
395
+ """
396
+
397
+ def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape):
398
+ self.flat_groups = flat_groups
399
+ self.flat_groups_offset = flat_groups_offset
400
+ self.offset = offset
401
+ self.partitioned_numel = partitioned_numel
402
+ self.shape = shape
403
+ self.dtype = self.flat_groups[0][0].dtype
404
+
405
+ def contiguous(self):
406
+ """
407
+ Merge partitioned weights from flat_groups into a single tensor.
408
+ """
409
+ end_idx = self.offset + self.partitioned_numel
410
+ world_size = len(self.flat_groups)
411
+ pad_flat_param_chunks = []
412
+
413
+ for rank_i in range(world_size):
414
+ # for each rank, we need to collect weights from related group/groups
415
+ flat_groups_at_rank_i = self.flat_groups[rank_i]
416
+ start_group_id = None
417
+ end_group_id = None
418
+ for group_id in range(len(self.flat_groups_offset)):
419
+ if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]:
420
+ start_group_id = group_id
421
+ if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]:
422
+ end_group_id = group_id
423
+ break
424
+ # collect weights from related group/groups
425
+ for group_id in range(start_group_id, end_group_id + 1):
426
+ flat_tensor = flat_groups_at_rank_i[group_id]
427
+ start_offset = self.offset - self.flat_groups_offset[group_id]
428
+ end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id]
429
+ pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
430
+
431
+ # collect weights from all ranks
432
+ pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0)
433
+ param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous()
434
+ return param
435
+
436
+
437
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
438
+ param_shapes = zero_model_states[0].param_shapes
439
+ avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
440
+
441
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
442
+ # param, re-consolidating each param, while dealing with padding if any
443
+
444
+ # merge list of dicts, preserving order
445
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
446
+
447
+ if debug:
448
+ for i in range(world_size):
449
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
450
+
451
+ wanted_params = len(param_shapes)
452
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
453
+ # not asserting if there is a mismatch due to possible padding
454
+ avail_numel = fp32_flat_groups[0].numel() * world_size
455
+ print(f"Trainable params: Have {avail_numel} numels to process.")
456
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
457
+
458
+ # params
459
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
460
+ # out-of-core computing solution
461
+ offset = 0
462
+ total_numel = 0
463
+ total_params = 0
464
+ flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]]))
465
+ for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'):
466
+ unpartitioned_numel = shape.numel()
467
+ total_numel += unpartitioned_numel
468
+ total_params += 1
469
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
470
+
471
+ if debug:
472
+ print(
473
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
474
+ )
475
+
476
+ # memory efficient tensor
477
+ tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape)
478
+ state_dict[name] = tensor
479
+ offset += partitioned_numel
480
+
481
+ offset *= world_size
482
+
483
+ # Sanity check
484
+ if offset != avail_numel:
485
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
486
+
487
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
488
+
489
+
490
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
491
+ exclude_frozen_parameters):
492
+ state_dict = OrderedDict()
493
+
494
+ # buffers
495
+ buffers = zero_model_states[0].buffers
496
+ state_dict.update(buffers)
497
+ if debug:
498
+ print(f"added {len(buffers)} buffers")
499
+
500
+ if not exclude_frozen_parameters:
501
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
502
+
503
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
504
+
505
+ # recover shared parameters
506
+ for pair in zero_model_states[0].shared_params:
507
+ if pair[1] in state_dict:
508
+ state_dict[pair[0]] = state_dict[pair[1]]
509
+
510
+ return state_dict
511
+
512
+
513
+ def to_torch_tensor(state_dict, return_empty_tensor=False):
514
+ """
515
+ Convert state_dict of GatheredTensor to torch tensor
516
+ """
517
+ torch_state_dict = {}
518
+ converted_tensors = {}
519
+ for name, tensor in state_dict.items():
520
+ tensor_id = id(tensor)
521
+ if tensor_id in converted_tensors: # shared tensors
522
+ shared_tensor = torch_state_dict[converted_tensors[tensor_id]]
523
+ torch_state_dict[name] = shared_tensor
524
+ else:
525
+ converted_tensors[tensor_id] = name
526
+ if return_empty_tensor:
527
+ torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype)
528
+ else:
529
+ torch_state_dict[name] = tensor.contiguous()
530
+ return torch_state_dict
531
+
532
+
533
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
534
+ tag=None,
535
+ exclude_frozen_parameters=False,
536
+ lazy_mode=False):
537
+ """
538
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
539
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
540
+ via a model hub.
541
+
542
+ Args:
543
+ - ``checkpoint_dir``: path to the desired checkpoint folder
544
+ - ``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``
545
+ - ``exclude_frozen_parameters``: exclude frozen parameters
546
+ - ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient.
547
+ Convert the pesduo tensor to torch tensor by ``.contiguous()``
548
+
549
+ Returns:
550
+ - pytorch ``state_dict``
551
+
552
+ A typical usage might be ::
553
+
554
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
555
+ # do the training and checkpoint saving
556
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
557
+ model = model.cpu() # move to cpu
558
+ model.load_state_dict(state_dict)
559
+ # submit to model hub or save the model to share with others
560
+
561
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
562
+ application. i.e. you will need to re-initialize the deepspeed engine, since
563
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
564
+
565
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
566
+
567
+ Note: the above usage may not work if your application doesn't have sufficient free CPU memory.
568
+ You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
569
+ the checkpoint. Or you can load state_dict in lazy mode ::
570
+
571
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
572
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu
573
+ for name, lazy_tensor in state_dict.item():
574
+ tensor = lazy_tensor.contiguous() # to cpu
575
+ print(name, tensor)
576
+ # del tensor to release memory if it no longer in use
577
+ """
578
+ if tag is None:
579
+ latest_path = os.path.join(checkpoint_dir, 'latest')
580
+ if os.path.isfile(latest_path):
581
+ with open(latest_path, 'r') as fd:
582
+ tag = fd.read().strip()
583
+ else:
584
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
585
+
586
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
587
+
588
+ if not os.path.isdir(ds_checkpoint_dir):
589
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
590
+
591
+ state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
592
+ if lazy_mode:
593
+ return state_dict
594
+ else:
595
+ return to_torch_tensor(state_dict)
596
+
597
+
598
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir,
599
+ output_dir,
600
+ max_shard_size="5GB",
601
+ safe_serialization=False,
602
+ tag=None,
603
+ exclude_frozen_parameters=False):
604
+ """
605
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
606
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
607
+
608
+ Args:
609
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
610
+ - ``output_dir``: directory to the pytorch fp32 state_dict output files
611
+ - ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB
612
+ - ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
613
+ - ``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``
614
+ - ``exclude_frozen_parameters``: exclude frozen parameters
615
+ """
616
+
617
+ # Dependency pre-check
618
+ if safe_serialization:
619
+ try:
620
+ from safetensors.torch import save_file
621
+ except ImportError:
622
+ print('If you want to use `safe_serialization`, please `pip install safetensors`')
623
+ raise
624
+ if max_shard_size is not None:
625
+ try:
626
+ from huggingface_hub import split_torch_state_dict_into_shards
627
+ except ImportError:
628
+ print('If you want to use `max_shard_size`, please `pip install huggingface_hub`')
629
+ raise
630
+
631
+ # Convert zero checkpoint to state_dict
632
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
633
+ tag,
634
+ exclude_frozen_parameters,
635
+ lazy_mode=True)
636
+
637
+ # Shard the model if it is too big.
638
+ weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin"
639
+ if max_shard_size is not None:
640
+ filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
641
+ # an memory-efficient approach for sharding
642
+ empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True)
643
+ state_dict_split = split_torch_state_dict_into_shards(empty_state_dict,
644
+ filename_pattern=filename_pattern,
645
+ max_shard_size=max_shard_size)
646
+ else:
647
+ from collections import namedtuple
648
+ StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"])
649
+ state_dict_split = StateDictSplit(is_sharded=False,
650
+ filename_to_tensors={weights_name: list(state_dict.keys())})
651
+
652
+ # Save the model by shard
653
+ os.makedirs(output_dir, exist_ok=True)
654
+ filename_to_tensors = state_dict_split.filename_to_tensors.items()
655
+ for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"):
656
+ shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors}
657
+ shard_state_dict = to_torch_tensor(shard_state_dict)
658
+ output_path = os.path.join(output_dir, shard_file)
659
+ if safe_serialization:
660
+ save_file(shard_state_dict, output_path, metadata={"format": "pt"})
661
+ else:
662
+ torch.save(shard_state_dict, output_path)
663
+ # release the memory of current shard
664
+ for tensor_name in list(shard_state_dict.keys()):
665
+ del state_dict[tensor_name]
666
+ del shard_state_dict[tensor_name]
667
+ del shard_state_dict
668
+ gc.collect()
669
+
670
+ # Save index if sharded
671
+ if state_dict_split.is_sharded:
672
+ index = {
673
+ "metadata": state_dict_split.metadata,
674
+ "weight_map": state_dict_split.tensor_to_filename,
675
+ }
676
+ save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json"
677
+ save_index_file = os.path.join(output_dir, save_index_file)
678
+ with open(save_index_file, "w", encoding="utf-8") as f:
679
+ content = json.dumps(index, indent=2, sort_keys=True) + "\n"
680
+ f.write(content)
681
+
682
+
683
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
684
+ """
685
+ 1. Put the provided model to cpu
686
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
687
+ 3. Load it into the provided model
688
+
689
+ Args:
690
+ - ``model``: the model object to update
691
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
692
+ - ``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``
693
+
694
+ Returns:
695
+ - ``model`: modified model
696
+
697
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
698
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
699
+ conveniently placed for you in the checkpoint folder.
700
+
701
+ A typical usage might be ::
702
+
703
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
704
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
705
+ # submit to model hub or save the model to share with others
706
+
707
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
708
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
709
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
710
+
711
+ """
712
+ logger.info(f"Extracting fp32 weights")
713
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
714
+
715
+ logger.info(f"Overwriting model with fp32 weights")
716
+ model = model.cpu()
717
+ model.load_state_dict(state_dict, strict=False)
718
+
719
+ return model
720
+
721
+
722
+ if __name__ == "__main__":
723
+ parser = argparse.ArgumentParser()
724
+ parser.add_argument("checkpoint_dir",
725
+ type=str,
726
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
727
+ parser.add_argument("output_dir",
728
+ type=str,
729
+ help="directory to the pytorch fp32 state_dict output files"
730
+ "(e.g. path/checkpoint-12-output/)")
731
+ parser.add_argument(
732
+ "--max_shard_size",
733
+ type=str,
734
+ default="5GB",
735
+ help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size"
736
+ "lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`"
737
+ "We default it to 5GB in order for models to be able to run easily on free-tier google colab instances"
738
+ "without CPU OOM issues.")
739
+ parser.add_argument(
740
+ "--safe_serialization",
741
+ default=False,
742
+ action='store_true',
743
+ help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).")
744
+ parser.add_argument("-t",
745
+ "--tag",
746
+ type=str,
747
+ default=None,
748
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
749
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
750
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
751
+ args = parser.parse_args()
752
+
753
+ debug = args.debug
754
+
755
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
756
+ args.output_dir,
757
+ max_shard_size=args.max_shard_size,
758
+ safe_serialization=args.safe_serialization,
759
+ tag=args.tag,
760
+ exclude_frozen_parameters=args.exclude_frozen_parameters)