models4world commited on
Commit
5cea889
·
verified ·
1 Parent(s): 1b2aca6
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* 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
 
 
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
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
.uploaded ADDED
File without changes
chat_template.jinja ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set image_count = namespace(value=0) %}
2
+ {%- set video_count = namespace(value=0) %}
3
+ {%- macro render_content(content, do_vision_count, is_system_content=false) %}
4
+ {%- if content is string %}
5
+ {{- content }}
6
+ {%- elif content is iterable and content is not mapping %}
7
+ {%- for item in content %}
8
+ {%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
9
+ {%- if is_system_content %}
10
+ {{- raise_exception('System message cannot contain images.') }}
11
+ {%- endif %}
12
+ {%- if do_vision_count %}
13
+ {%- set image_count.value = image_count.value + 1 %}
14
+ {%- endif %}
15
+ {%- if add_vision_id %}
16
+ {{- 'Picture ' ~ image_count.value ~ ': ' }}
17
+ {%- endif %}
18
+ {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
19
+ {%- elif 'video' in item or item.type == 'video' %}
20
+ {%- if is_system_content %}
21
+ {{- raise_exception('System message cannot contain videos.') }}
22
+ {%- endif %}
23
+ {%- if do_vision_count %}
24
+ {%- set video_count.value = video_count.value + 1 %}
25
+ {%- endif %}
26
+ {%- if add_vision_id %}
27
+ {{- 'Video ' ~ video_count.value ~ ': ' }}
28
+ {%- endif %}
29
+ {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
30
+ {%- elif 'text' in item %}
31
+ {{- item.text }}
32
+ {%- else %}
33
+ {{- raise_exception('Unexpected item type in content.') }}
34
+ {%- endif %}
35
+ {%- endfor %}
36
+ {%- elif content is none or content is undefined %}
37
+ {{- '' }}
38
+ {%- else %}
39
+ {{- raise_exception('Unexpected content type.') }}
40
+ {%- endif %}
41
+ {%- endmacro %}
42
+ {%- if not messages %}
43
+ {{- raise_exception('No messages provided.') }}
44
+ {%- endif %}
45
+ {%- if tools and tools is iterable and tools is not mapping %}
46
+ {{- '<|im_start|>system\n' }}
47
+ {{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
48
+ {%- for tool in tools %}
49
+ {{- "\n" }}
50
+ {{- tool | tojson }}
51
+ {%- endfor %}
52
+ {{- "\n</tools>" }}
53
+ {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
54
+ {%- if messages[0].role == 'system' %}
55
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
56
+ {%- if content %}
57
+ {{- '\n\n' + content }}
58
+ {%- endif %}
59
+ {%- endif %}
60
+ {{- '<|im_end|>\n' }}
61
+ {%- else %}
62
+ {%- if messages[0].role == 'system' %}
63
+ {%- set content = render_content(messages[0].content, false, true)|trim %}
64
+ {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
65
+ {%- endif %}
66
+ {%- endif %}
67
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
68
+ {%- for message in messages[::-1] %}
69
+ {%- set index = (messages|length - 1) - loop.index0 %}
70
+ {%- if ns.multi_step_tool and message.role == "user" %}
71
+ {%- set content = render_content(message.content, false)|trim %}
72
+ {%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
73
+ {%- set ns.multi_step_tool = false %}
74
+ {%- set ns.last_query_index = index %}
75
+ {%- endif %}
76
+ {%- endif %}
77
+ {%- endfor %}
78
+ {%- if ns.multi_step_tool %}
79
+ {{- raise_exception('No user query found in messages.') }}
80
+ {%- endif %}
81
+ {%- for message in messages %}
82
+ {%- set content = render_content(message.content, true)|trim %}
83
+ {%- if message.role == "system" %}
84
+ {%- if not loop.first %}
85
+ {{- raise_exception('System message must be at the beginning.') }}
86
+ {%- endif %}
87
+ {%- elif message.role == "user" %}
88
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
89
+ {%- elif message.role == "assistant" %}
90
+ {%- set reasoning_content = '' %}
91
+ {%- if message.reasoning_content is string %}
92
+ {%- set reasoning_content = message.reasoning_content %}
93
+ {%- else %}
94
+ {%- if '</think>' in content %}
95
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
96
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
97
+ {%- endif %}
98
+ {%- endif %}
99
+ {%- set reasoning_content = reasoning_content|trim %}
100
+ {%- if (preserve_thinking is defined and preserve_thinking is true) or (loop.index0 > ns.last_query_index) %}
101
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
102
+ {%- else %}
103
+ {{- '<|im_start|>' + message.role + '\n' + content }}
104
+ {%- endif %}
105
+ {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
106
+ {%- for tool_call in message.tool_calls %}
107
+ {%- if tool_call.function is defined %}
108
+ {%- set tool_call = tool_call.function %}
109
+ {%- endif %}
110
+ {%- if loop.first %}
111
+ {%- if content|trim %}
112
+ {{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
113
+ {%- else %}
114
+ {{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
115
+ {%- endif %}
116
+ {%- else %}
117
+ {{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
118
+ {%- endif %}
119
+ {%- if tool_call.arguments is defined %}
120
+ {%- for args_name, args_value in tool_call.arguments|items %}
121
+ {{- '<parameter=' + args_name + '>\n' }}
122
+ {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
123
+ {{- args_value }}
124
+ {{- '\n</parameter>\n' }}
125
+ {%- endfor %}
126
+ {%- endif %}
127
+ {{- '</function>\n</tool_call>' }}
128
+ {%- endfor %}
129
+ {%- endif %}
130
+ {{- '<|im_end|>\n' }}
131
+ {%- elif message.role == "tool" %}
132
+ {%- if loop.previtem and loop.previtem.role != "tool" %}
133
+ {{- '<|im_start|>user' }}
134
+ {%- endif %}
135
+ {{- '\n<tool_response>\n' }}
136
+ {{- content }}
137
+ {{- '\n</tool_response>' }}
138
+ {%- if not loop.last and loop.nextitem.role != "tool" %}
139
+ {{- '<|im_end|>\n' }}
140
+ {%- elif loop.last %}
141
+ {{- '<|im_end|>\n' }}
142
+ {%- endif %}
143
+ {%- else %}
144
+ {{- raise_exception('Unexpected message role.') }}
145
+ {%- endif %}
146
+ {%- endfor %}
147
+ {%- if add_generation_prompt %}
148
+ {{- '<|im_start|>assistant\n' }}
149
+ {%- if enable_thinking is defined and enable_thinking is false %}
150
+ {{- '<think>\n\n</think>\n\n' }}
151
+ {%- else %}
152
+ {{- '<think>\n' }}
153
+ {%- endif %}
154
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3_5ForConditionalGeneration"
4
+ ],
5
+ "bos_token_id": null,
6
+ "dtype": "bfloat16",
7
+ "eos_token_id": 248046,
8
+ "image_token_id": 248056,
9
+ "language_model_only": false,
10
+ "model_type": "qwen3_5",
11
+ "pad_token_id": 248044,
12
+ "text_config": {
13
+ "attention_bias": false,
14
+ "attention_dropout": 0.0,
15
+ "attn_output_gate": true,
16
+ "bos_token_id": 248044,
17
+ "dtype": "bfloat16",
18
+ "eos_token_id": 248044,
19
+ "full_attention_interval": 4,
20
+ "head_dim": 256,
21
+ "hidden_act": "silu",
22
+ "hidden_size": 5120,
23
+ "initializer_range": 0.02,
24
+ "intermediate_size": 17408,
25
+ "layer_types": [
26
+ "linear_attention",
27
+ "linear_attention",
28
+ "linear_attention",
29
+ "full_attention",
30
+ "linear_attention",
31
+ "linear_attention",
32
+ "linear_attention",
33
+ "full_attention",
34
+ "linear_attention",
35
+ "linear_attention",
36
+ "linear_attention",
37
+ "full_attention",
38
+ "linear_attention",
39
+ "linear_attention",
40
+ "linear_attention",
41
+ "full_attention",
42
+ "linear_attention",
43
+ "linear_attention",
44
+ "linear_attention",
45
+ "full_attention",
46
+ "linear_attention",
47
+ "linear_attention",
48
+ "linear_attention",
49
+ "full_attention",
50
+ "linear_attention",
51
+ "linear_attention",
52
+ "linear_attention",
53
+ "full_attention",
54
+ "linear_attention",
55
+ "linear_attention",
56
+ "linear_attention",
57
+ "full_attention",
58
+ "linear_attention",
59
+ "linear_attention",
60
+ "linear_attention",
61
+ "full_attention",
62
+ "linear_attention",
63
+ "linear_attention",
64
+ "linear_attention",
65
+ "full_attention",
66
+ "linear_attention",
67
+ "linear_attention",
68
+ "linear_attention",
69
+ "full_attention",
70
+ "linear_attention",
71
+ "linear_attention",
72
+ "linear_attention",
73
+ "full_attention",
74
+ "linear_attention",
75
+ "linear_attention",
76
+ "linear_attention",
77
+ "full_attention",
78
+ "linear_attention",
79
+ "linear_attention",
80
+ "linear_attention",
81
+ "full_attention",
82
+ "linear_attention",
83
+ "linear_attention",
84
+ "linear_attention",
85
+ "full_attention",
86
+ "linear_attention",
87
+ "linear_attention",
88
+ "linear_attention",
89
+ "full_attention"
90
+ ],
91
+ "linear_conv_kernel_dim": 4,
92
+ "linear_key_head_dim": 128,
93
+ "linear_num_key_heads": 16,
94
+ "linear_num_value_heads": 48,
95
+ "linear_value_head_dim": 128,
96
+ "mamba_ssm_dtype": "float32",
97
+ "max_position_embeddings": 262144,
98
+ "model_type": "qwen3_5_text",
99
+ "mtp_num_hidden_layers": 1,
100
+ "mtp_use_dedicated_embeddings": false,
101
+ "num_attention_heads": 24,
102
+ "num_hidden_layers": 64,
103
+ "num_key_value_heads": 4,
104
+ "output_gate_type": "swish",
105
+ "pad_token_id": null,
106
+ "partial_rotary_factor": 0.25,
107
+ "rms_norm_eps": 1e-06,
108
+ "rope_parameters": {
109
+ "mrope_interleaved": true,
110
+ "mrope_section": [
111
+ 11,
112
+ 11,
113
+ 10
114
+ ],
115
+ "partial_rotary_factor": 0.25,
116
+ "rope_theta": 10000000,
117
+ "rope_type": "default"
118
+ },
119
+ "tie_word_embeddings": false,
120
+ "use_cache": false,
121
+ "vocab_size": 248320
122
+ },
123
+ "tie_word_embeddings": false,
124
+ "transformers_version": "5.12.1",
125
+ "use_cache": false,
126
+ "video_token_id": 248057,
127
+ "vision_config": {
128
+ "deepstack_visual_indexes": [],
129
+ "depth": 27,
130
+ "dtype": "bfloat16",
131
+ "hidden_act": "gelu_pytorch_tanh",
132
+ "hidden_size": 1152,
133
+ "in_channels": 3,
134
+ "initializer_range": 0.02,
135
+ "intermediate_size": 4304,
136
+ "model_type": "qwen3_5_vision",
137
+ "num_heads": 16,
138
+ "num_position_embeddings": 2304,
139
+ "out_hidden_size": 5120,
140
+ "patch_size": 16,
141
+ "spatial_merge_size": 2,
142
+ "temporal_patch_size": 2
143
+ },
144
+ "vision_end_token_id": 248054,
145
+ "vision_start_token_id": 248053
146
+ }
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_sample": true,
3
+ "eos_token_id": [
4
+ 248046,
5
+ 248046,
6
+ 248044
7
+ ],
8
+ "pad_token_id": 248044,
9
+ "temperature": 1.0,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "5.12.1"
13
+ }
latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step30
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04cbaafde3e34ab68377c6eaa83bfd693e2d4b6df1235e7a2c0ab0c4283f18e8
3
+ size 49519039488
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:41bbed1aae3f72d75f93779bb8fbc51447a285f3ed3b93e2a05331b4d65a3843
3
+ size 4888445168
model.safetensors.index.json ADDED
The diff for this file is too large to render. See raw diff
 
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e2129f5acdc209a88e368eb1b42ef4386f295e355f51fe8f144ca1ff785b34a
3
+ size 1465
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06b9509352d2af50381ab2247e083b80d32d5c0aba91c272ca9ff729b6a0e523
3
+ size 19989325
tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "audio_bos_token": "<|audio_start|>",
4
+ "audio_eos_token": "<|audio_end|>",
5
+ "audio_token": "<|audio_pad|>",
6
+ "backend": "tokenizers",
7
+ "bos_token": null,
8
+ "clean_up_tokenization_spaces": false,
9
+ "eos_token": "<|im_end|>",
10
+ "errors": "replace",
11
+ "image_token": "<|image_pad|>",
12
+ "is_local": true,
13
+ "local_files_only": true,
14
+ "model_max_length": 262144,
15
+ "model_specific_special_tokens": {
16
+ "audio_bos_token": "<|audio_start|>",
17
+ "audio_eos_token": "<|audio_end|>",
18
+ "audio_token": "<|audio_pad|>",
19
+ "image_token": "<|image_pad|>",
20
+ "video_token": "<|video_pad|>",
21
+ "vision_bos_token": "<|vision_start|>",
22
+ "vision_eos_token": "<|vision_end|>"
23
+ },
24
+ "pad_token": "<|endoftext|>",
25
+ "pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
26
+ "processor_class": "Qwen3VLProcessor",
27
+ "split_special_tokens": false,
28
+ "tokenizer_class": "Qwen2Tokenizer",
29
+ "unk_token": null,
30
+ "video_token": "<|video_pad|>",
31
+ "vision_bos_token": "<|vision_start|>",
32
+ "vision_eos_token": "<|vision_end|>"
33
+ }
tokens_state.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"total": 15728640, "trainable": 2640159}
trainer_state.json ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 0.633245382585752,
6
+ "eval_steps": 12,
7
+ "global_step": 30,
8
+ "is_hyper_param_search": false,
9
+ "is_local_process_zero": true,
10
+ "is_world_process_zero": true,
11
+ "log_history": [
12
+ {
13
+ "epoch": 0,
14
+ "eval_loss": 1.051796555519104,
15
+ "eval_ppl": 2.86279,
16
+ "eval_runtime": 277.2697,
17
+ "eval_samples_per_second": 0.573,
18
+ "eval_steps_per_second": 0.144,
19
+ "memory/device_reserved (GiB)": 45.79,
20
+ "memory/max_active (GiB)": 41.03,
21
+ "memory/max_allocated (GiB)": 38.11,
22
+ "step": 0
23
+ },
24
+ {
25
+ "epoch": 0.10554089709762533,
26
+ "grad_norm": 3.6152215003967285,
27
+ "learning_rate": 7e-06,
28
+ "loss": 0.9618721008300781,
29
+ "memory/device_reserved (GiB)": 76.43,
30
+ "memory/max_active (GiB)": 61.19,
31
+ "memory/max_allocated (GiB)": 58.82,
32
+ "ppl": 2.61659,
33
+ "step": 5,
34
+ "tokens/total": 2621440,
35
+ "tokens/trainable": 439427
36
+ },
37
+ {
38
+ "epoch": 0.21108179419525067,
39
+ "grad_norm": 2.375864267349243,
40
+ "learning_rate": 6.952144421988455e-06,
41
+ "loss": 0.7351778507232666,
42
+ "memory/device_reserved (GiB)": 76.43,
43
+ "memory/max_active (GiB)": 61.19,
44
+ "memory/max_allocated (GiB)": 58.82,
45
+ "ppl": 2.08585,
46
+ "step": 10,
47
+ "tokens/total": 5242880,
48
+ "tokens/train_per_sec_per_gpu": 53.56,
49
+ "tokens/trainable": 905507
50
+ },
51
+ {
52
+ "epoch": 0.2532981530343008,
53
+ "eval_loss": 0.6750471591949463,
54
+ "eval_ppl": 1.96413,
55
+ "eval_runtime": 269.2239,
56
+ "eval_samples_per_second": 0.591,
57
+ "eval_steps_per_second": 0.149,
58
+ "memory/device_reserved (GiB)": 76.43,
59
+ "memory/max_active (GiB)": 61.19,
60
+ "memory/max_allocated (GiB)": 58.82,
61
+ "step": 12
62
+ },
63
+ {
64
+ "epoch": 0.316622691292876,
65
+ "grad_norm": 2.0795094966888428,
66
+ "learning_rate": 6.810031755475611e-06,
67
+ "loss": 0.6558361530303956,
68
+ "memory/device_reserved (GiB)": 76.89,
69
+ "memory/max_active (GiB)": 61.19,
70
+ "memory/max_allocated (GiB)": 58.82,
71
+ "ppl": 1.92675,
72
+ "step": 15,
73
+ "tokens/total": 7864320,
74
+ "tokens/train_per_sec_per_gpu": 31.8,
75
+ "tokens/trainable": 1335905
76
+ },
77
+ {
78
+ "epoch": 0.42216358839050133,
79
+ "grad_norm": 1.7829387187957764,
80
+ "learning_rate": 6.577980021920982e-06,
81
+ "loss": 0.5943492412567138,
82
+ "memory/device_reserved (GiB)": 76.74,
83
+ "memory/max_active (GiB)": 61.19,
84
+ "memory/max_allocated (GiB)": 58.82,
85
+ "ppl": 1.81185,
86
+ "step": 20,
87
+ "tokens/total": 10485760,
88
+ "tokens/train_per_sec_per_gpu": 40.47,
89
+ "tokens/trainable": 1759194
90
+ },
91
+ {
92
+ "epoch": 0.5065963060686016,
93
+ "eval_loss": 0.5638795495033264,
94
+ "eval_ppl": 1.75748,
95
+ "eval_runtime": 315.1873,
96
+ "eval_samples_per_second": 0.504,
97
+ "eval_steps_per_second": 0.127,
98
+ "memory/device_reserved (GiB)": 76.68,
99
+ "memory/max_active (GiB)": 61.19,
100
+ "memory/max_allocated (GiB)": 58.82,
101
+ "step": 24
102
+ },
103
+ {
104
+ "epoch": 0.5277044854881267,
105
+ "grad_norm": 1.813848853111267,
106
+ "learning_rate": 6.26303999582478e-06,
107
+ "loss": 0.5609341621398926,
108
+ "memory/device_reserved (GiB)": 76.09,
109
+ "memory/max_active (GiB)": 60.83,
110
+ "memory/max_allocated (GiB)": 58.82,
111
+ "ppl": 1.75231,
112
+ "step": 25,
113
+ "tokens/total": 13107200,
114
+ "tokens/train_per_sec_per_gpu": 27.39,
115
+ "tokens/trainable": 2190374
116
+ },
117
+ {
118
+ "epoch": 0.633245382585752,
119
+ "grad_norm": 2.115403890609741,
120
+ "learning_rate": 5.874780970512599e-06,
121
+ "loss": 0.5286190986633301,
122
+ "memory/device_reserved (GiB)": 76.42,
123
+ "memory/max_active (GiB)": 61.19,
124
+ "memory/max_allocated (GiB)": 58.82,
125
+ "ppl": 1.69659,
126
+ "step": 30,
127
+ "tokens/total": 15728640,
128
+ "tokens/train_per_sec_per_gpu": 43.15,
129
+ "tokens/trainable": 2640159
130
+ }
131
+ ],
132
+ "logging_steps": 5,
133
+ "max_steps": 94,
134
+ "num_input_tokens_seen": 0,
135
+ "num_train_epochs": 2,
136
+ "save_steps": 10,
137
+ "stateful_callbacks": {
138
+ "TrainerControl": {
139
+ "args": {
140
+ "should_epoch_stop": false,
141
+ "should_evaluate": false,
142
+ "should_log": false,
143
+ "should_save": true,
144
+ "should_training_stop": false
145
+ },
146
+ "attributes": {}
147
+ }
148
+ },
149
+ "total_flos": 286632737505280.0,
150
+ "train_batch_size": 1,
151
+ "trial_name": null,
152
+ "trial_params": null
153
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee5060936a9476f35d9c3b0d19bbdd4261daa658fc379e14bf27afae7066fce2
3
+ size 8785
zero_to_fp32.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+
4
+ import argparse
5
+ import torch
6
+ import glob
7
+ import math
8
+ import os
9
+ import re
10
+ import gc
11
+ import json
12
+ import numpy as np
13
+ from tqdm import tqdm
14
+ from collections import OrderedDict
15
+ from dataclasses import dataclass
16
+
17
+
18
+ from deepspeed.utils import logger
19
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
20
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
21
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
22
+
23
+
24
+ @dataclass
25
+ class zero_model_state:
26
+ buffers: dict()
27
+ param_shapes: dict()
28
+ shared_params: list
29
+ ds_version: int
30
+ frozen_param_shapes: dict()
31
+ frozen_param_fragments: dict()
32
+
33
+
34
+ debug = 0
35
+
36
+
37
+ device = torch.device('cpu')
38
+
39
+
40
+ def atoi(text):
41
+ return int(text) if text.isdigit() else text
42
+
43
+
44
+ def natural_keys(text):
45
+ '''
46
+ alist.sort(key=natural_keys) sorts in human order
47
+ http://nedbatchelder.com/blog/200712/human_sorting.html
48
+ (See Toothy's implementation in the comments)
49
+ '''
50
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
51
+
52
+
53
+ def get_model_state_file(checkpoint_dir, zero_stage):
54
+ if not os.path.isdir(checkpoint_dir):
55
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
56
+
57
+
58
+ if zero_stage <= 2:
59
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
60
+ elif zero_stage == 3:
61
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
62
+
63
+ if not os.path.exists(file):
64
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
65
+
66
+ return file
67
+
68
+
69
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
70
+
71
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
72
+
73
+ if len(ckpt_files) == 0:
74
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
75
+
76
+ return ckpt_files
77
+
78
+
79
+ def get_optim_files(checkpoint_dir):
80
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
81
+
82
+
83
+ def get_model_state_files(checkpoint_dir):
84
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
85
+
86
+
87
+ def parse_model_states(files):
88
+ zero_model_states = []
89
+ for file in files:
90
+ state_dict = torch.load(file, map_location=device, weights_only=False)
91
+
92
+ if BUFFER_NAMES not in state_dict:
93
+ raise ValueError(f"{file} is not a model state checkpoint")
94
+ buffer_names = state_dict[BUFFER_NAMES]
95
+ if debug:
96
+ print("Found buffers:", buffer_names)
97
+
98
+
99
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
100
+ param_shapes = state_dict[PARAM_SHAPES]
101
+
102
+
103
+ param_names = []
104
+ for s in param_shapes:
105
+ for name in s.keys():
106
+ param_names.append(name)
107
+
108
+
109
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
110
+ if frozen_param_shapes is not None:
111
+ if debug:
112
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
113
+ param_names += list(frozen_param_shapes.keys())
114
+
115
+
116
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
117
+
118
+ ds_version = state_dict.get(DS_VERSION, None)
119
+
120
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
121
+
122
+ z_model_state = zero_model_state(buffers=buffers,
123
+ param_shapes=param_shapes,
124
+ shared_params=shared_params,
125
+ ds_version=ds_version,
126
+ frozen_param_shapes=frozen_param_shapes,
127
+ frozen_param_fragments=frozen_param_fragments)
128
+ zero_model_states.append(z_model_state)
129
+
130
+ return zero_model_states
131
+
132
+
133
+ def parse_optim_states(files, ds_checkpoint_dir):
134
+ total_files = len(files)
135
+ state_dicts = []
136
+ for f in tqdm(files, desc='Loading checkpoint shards'):
137
+ state_dict = torch.load(f, map_location=device, mmap=True, weights_only=False)
138
+
139
+
140
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
141
+ state_dicts.append(state_dict)
142
+
143
+ if ZERO_STAGE not in state_dicts[0][OPTIMIZER_STATE_DICT]:
144
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
145
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
146
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
147
+
148
+
149
+ if type(world_size) is list:
150
+ world_size = max(world_size)
151
+
152
+ if world_size != total_files:
153
+ raise ValueError(
154
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
155
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
156
+ )
157
+
158
+
159
+ if zero_stage <= 2:
160
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
161
+ elif zero_stage == 3:
162
+ fp32_groups_key = FP32_FLAT_GROUPS
163
+ else:
164
+ raise ValueError(f"unknown zero stage {zero_stage}")
165
+
166
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
167
+ return zero_stage, world_size, fp32_flat_groups
168
+
169
+
170
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters):
171
+ """
172
+ Returns fp32 state_dict reconstructed from ds checkpoint
173
+
174
+ Args:
175
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
176
+
177
+ """
178
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
179
+
180
+ optim_files = get_optim_files(ds_checkpoint_dir)
181
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
182
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
183
+
184
+ model_files = get_model_state_files(ds_checkpoint_dir)
185
+
186
+ zero_model_states = parse_model_states(model_files)
187
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
188
+
189
+ if zero_stage <= 2:
190
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
191
+ exclude_frozen_parameters)
192
+ elif zero_stage == 3:
193
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
194
+ exclude_frozen_parameters)
195
+
196
+
197
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
198
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
199
+ return
200
+
201
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
202
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
203
+
204
+ if debug:
205
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
206
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
207
+
208
+ wanted_params = len(frozen_param_shapes)
209
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
210
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
211
+ print(f'Frozen params: Have {avail_numel} numels to process.')
212
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
213
+
214
+ total_params = 0
215
+ total_numel = 0
216
+ for name, shape in frozen_param_shapes.items():
217
+ total_params += 1
218
+ unpartitioned_numel = shape.numel()
219
+ total_numel += unpartitioned_numel
220
+
221
+ state_dict[name] = frozen_param_fragments[name]
222
+
223
+ if debug:
224
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
225
+
226
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
227
+
228
+
229
+ def _has_callable(obj, fn):
230
+ attr = getattr(obj, fn, None)
231
+ return callable(attr)
232
+
233
+
234
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
235
+ param_shapes = zero_model_states[0].param_shapes
236
+
237
+
238
+ if debug:
239
+ for i in range(world_size):
240
+ for j in range(len(fp32_flat_groups[0])):
241
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
242
+
243
+
244
+ num_param_groups = len(fp32_flat_groups[0])
245
+ merged_single_partition_of_fp32_groups = []
246
+ for i in range(num_param_groups):
247
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
248
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
249
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
250
+ avail_numel = sum(
251
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
252
+
253
+ if debug:
254
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
255
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
256
+
257
+ print(f"Have {avail_numel} numels to process.")
258
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
259
+
260
+
261
+ total_numel = 0
262
+ total_params = 0
263
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
264
+ offset = 0
265
+ avail_numel = full_single_fp32_vector.numel()
266
+ for name, shape in shapes.items():
267
+
268
+ unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
269
+ total_numel += unpartitioned_numel
270
+ total_params += 1
271
+
272
+ if debug:
273
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
274
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
275
+ offset += unpartitioned_numel
276
+
277
+
278
+ align_to = 2 * world_size
279
+
280
+ def zero2_align(x):
281
+ return align_to * math.ceil(x / align_to)
282
+
283
+ if debug:
284
+ print(f"original offset={offset}, avail_numel={avail_numel}")
285
+
286
+ offset = zero2_align(offset)
287
+ avail_numel = zero2_align(avail_numel)
288
+
289
+ if debug:
290
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
291
+
292
+
293
+ if offset != avail_numel:
294
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
295
+
296
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
297
+
298
+
299
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
300
+ exclude_frozen_parameters):
301
+ state_dict = OrderedDict()
302
+
303
+
304
+ buffers = zero_model_states[0].buffers
305
+ state_dict.update(buffers)
306
+ if debug:
307
+ print(f"added {len(buffers)} buffers")
308
+
309
+ if not exclude_frozen_parameters:
310
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
311
+
312
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
313
+
314
+
315
+ for pair in zero_model_states[0].shared_params:
316
+ if pair[1] in state_dict:
317
+ state_dict[pair[0]] = state_dict[pair[1]]
318
+
319
+ return state_dict
320
+
321
+
322
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
323
+ remainder = unpartitioned_numel % world_size
324
+ padding_numel = (world_size - remainder) if remainder else 0
325
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
326
+ return partitioned_numel, padding_numel
327
+
328
+
329
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
330
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
331
+ return
332
+
333
+ if debug:
334
+ for i in range(world_size):
335
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
336
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
337
+
338
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
339
+ wanted_params = len(frozen_param_shapes)
340
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
341
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
342
+ print(f'Frozen params: Have {avail_numel} numels to process.')
343
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
344
+
345
+ total_params = 0
346
+ total_numel = 0
347
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
348
+ total_params += 1
349
+ unpartitioned_numel = shape.numel()
350
+ total_numel += unpartitioned_numel
351
+
352
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
353
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
354
+
355
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
356
+
357
+ if debug:
358
+ print(
359
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
360
+ )
361
+
362
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
363
+
364
+
365
+ class GatheredTensor:
366
+ """
367
+ A pseudo tensor that collects partitioned weights.
368
+ It is more memory efficient when there are multiple groups.
369
+ """
370
+
371
+ def __init__(self, flat_groups, flat_groups_offset, offset, partitioned_numel, shape):
372
+ self.flat_groups = flat_groups
373
+ self.flat_groups_offset = flat_groups_offset
374
+ self.offset = offset
375
+ self.partitioned_numel = partitioned_numel
376
+ self.shape = shape
377
+ self.dtype = self.flat_groups[0][0].dtype
378
+
379
+ def contiguous(self):
380
+ """
381
+ Merge partitioned weights from flat_groups into a single tensor.
382
+ """
383
+ end_idx = self.offset + self.partitioned_numel
384
+ world_size = len(self.flat_groups)
385
+ pad_flat_param_chunks = []
386
+
387
+ for rank_i in range(world_size):
388
+
389
+ flat_groups_at_rank_i = self.flat_groups[rank_i]
390
+ start_group_id = None
391
+ end_group_id = None
392
+ for group_id in range(len(self.flat_groups_offset)):
393
+ if self.flat_groups_offset[group_id] <= self.offset < self.flat_groups_offset[group_id + 1]:
394
+ start_group_id = group_id
395
+ if self.flat_groups_offset[group_id] < end_idx <= self.flat_groups_offset[group_id + 1]:
396
+ end_group_id = group_id
397
+ break
398
+
399
+ for group_id in range(start_group_id, end_group_id + 1):
400
+ flat_tensor = flat_groups_at_rank_i[group_id]
401
+ start_offset = self.offset - self.flat_groups_offset[group_id]
402
+ end_offset = min(end_idx, self.flat_groups_offset[group_id + 1]) - self.flat_groups_offset[group_id]
403
+ pad_flat_param_chunks.append(flat_tensor[start_offset:end_offset])
404
+
405
+
406
+ pad_flat_param = torch.cat(pad_flat_param_chunks, dim=0)
407
+ param = pad_flat_param[:self.shape.numel()].view(self.shape).contiguous()
408
+ return param
409
+
410
+
411
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
412
+ param_shapes = zero_model_states[0].param_shapes
413
+ avail_numel = sum([flat_group.numel() for flat_group in fp32_flat_groups[0]]) * world_size
414
+
415
+
416
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
417
+
418
+ if debug:
419
+ for i in range(world_size):
420
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
421
+
422
+ wanted_params = len(param_shapes)
423
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
424
+
425
+ avail_numel = fp32_flat_groups[0].numel() * world_size
426
+ print(f"Trainable params: Have {avail_numel} numels to process.")
427
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
428
+
429
+
430
+ offset = 0
431
+ total_numel = 0
432
+ total_params = 0
433
+ flat_groups_offset = [0] + list(np.cumsum([flat_tensor.numel() for flat_tensor in fp32_flat_groups[0]]))
434
+ for name, shape in tqdm(param_shapes.items(), desc='Gathering sharded weights'):
435
+ unpartitioned_numel = shape.numel()
436
+ total_numel += unpartitioned_numel
437
+ total_params += 1
438
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
439
+
440
+ if debug:
441
+ print(
442
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
443
+ )
444
+
445
+
446
+ tensor = GatheredTensor(fp32_flat_groups, flat_groups_offset, offset, partitioned_numel, shape)
447
+ state_dict[name] = tensor
448
+ offset += partitioned_numel
449
+
450
+ offset *= world_size
451
+
452
+
453
+ if offset != avail_numel:
454
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
455
+
456
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
457
+
458
+
459
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
460
+ exclude_frozen_parameters):
461
+ state_dict = OrderedDict()
462
+
463
+
464
+ buffers = zero_model_states[0].buffers
465
+ state_dict.update(buffers)
466
+ if debug:
467
+ print(f"added {len(buffers)} buffers")
468
+
469
+ if not exclude_frozen_parameters:
470
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
471
+
472
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
473
+
474
+
475
+ for pair in zero_model_states[0].shared_params:
476
+ if pair[1] in state_dict:
477
+ state_dict[pair[0]] = state_dict[pair[1]]
478
+
479
+ return state_dict
480
+
481
+
482
+ def to_torch_tensor(state_dict, return_empty_tensor=False):
483
+ """
484
+ Convert state_dict of GatheredTensor to torch tensor
485
+ """
486
+ torch_state_dict = {}
487
+ converted_tensors = {}
488
+ for name, tensor in state_dict.items():
489
+ tensor_id = id(tensor)
490
+ if tensor_id in converted_tensors:
491
+ shared_tensor = torch_state_dict[converted_tensors[tensor_id]]
492
+ torch_state_dict[name] = shared_tensor
493
+ else:
494
+ converted_tensors[tensor_id] = name
495
+ if return_empty_tensor:
496
+ torch_state_dict[name] = torch.empty(tensor.shape, dtype=tensor.dtype)
497
+ else:
498
+ torch_state_dict[name] = tensor.contiguous()
499
+ return torch_state_dict
500
+
501
+
502
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
503
+ tag=None,
504
+ exclude_frozen_parameters=False,
505
+ lazy_mode=False):
506
+ """
507
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
508
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
509
+ via a model hub.
510
+
511
+ Args:
512
+ - ``checkpoint_dir``: path to the desired checkpoint folder
513
+ - ``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``
514
+ - ``exclude_frozen_parameters``: exclude frozen parameters
515
+ - ``lazy_mode``: get state_dict in lazy mode. It returns a dict of pesduo tensor instead of torch tensor, which is more memory efficient.
516
+ Convert the pesduo tensor to torch tensor by ``.contiguous()``
517
+
518
+ Returns:
519
+ - pytorch ``state_dict``
520
+
521
+ A typical usage might be ::
522
+
523
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
524
+ # do the training and checkpoint saving
525
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
526
+ model = model.cpu() # move to cpu
527
+ model.load_state_dict(state_dict)
528
+ # submit to model hub or save the model to share with others
529
+
530
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
531
+ application. i.e. you will need to re-initialize the deepspeed engine, since
532
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
533
+
534
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
535
+
536
+ Note: the above usage may not work if your application doesn't have sufficient free CPU memory.
537
+ You may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
538
+ the checkpoint. Or you can load state_dict in lazy mode ::
539
+
540
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
541
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, lazy_mode=True) # not on cpu
542
+ for name, lazy_tensor in state_dict.item():
543
+ tensor = lazy_tensor.contiguous() # to cpu
544
+ print(name, tensor)
545
+ # del tensor to release memory if it no longer in use
546
+ """
547
+ if tag is None:
548
+ latest_path = os.path.join(checkpoint_dir, 'latest')
549
+ if os.path.isfile(latest_path):
550
+ with open(latest_path, 'r') as fd:
551
+ tag = fd.read().strip()
552
+ else:
553
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
554
+
555
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
556
+
557
+ if not os.path.isdir(ds_checkpoint_dir):
558
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
559
+
560
+ state_dict = _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
561
+ if lazy_mode:
562
+ return state_dict
563
+ else:
564
+ return to_torch_tensor(state_dict)
565
+
566
+
567
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir,
568
+ output_dir,
569
+ max_shard_size="5GB",
570
+ safe_serialization=False,
571
+ tag=None,
572
+ exclude_frozen_parameters=False):
573
+ """
574
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
575
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
576
+
577
+ Args:
578
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
579
+ - ``output_dir``: directory to the pytorch fp32 state_dict output files
580
+ - ``max_shard_size``: the maximum size for a checkpoint before being sharded, default value is 5GB
581
+ - ``safe_serialization``: whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
582
+ - ``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``
583
+ - ``exclude_frozen_parameters``: exclude frozen parameters
584
+ """
585
+
586
+
587
+ if safe_serialization:
588
+ try:
589
+ from safetensors.torch import save_file
590
+ except ImportError:
591
+ print('If you want to use `safe_serialization`, please `pip install safetensors`')
592
+ raise
593
+ if max_shard_size is not None:
594
+ try:
595
+ from huggingface_hub import split_torch_state_dict_into_shards
596
+ except ImportError:
597
+ print('If you want to use `max_shard_size`, please `pip install huggingface_hub`')
598
+ raise
599
+
600
+
601
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir,
602
+ tag,
603
+ exclude_frozen_parameters,
604
+ lazy_mode=True)
605
+
606
+
607
+ weights_name = "model.safetensors" if safe_serialization else "pytorch_model.bin"
608
+ if max_shard_size is not None:
609
+ filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(".safetensors", "{suffix}.safetensors")
610
+
611
+ empty_state_dict = to_torch_tensor(state_dict, return_empty_tensor=True)
612
+ state_dict_split = split_torch_state_dict_into_shards(empty_state_dict,
613
+ filename_pattern=filename_pattern,
614
+ max_shard_size=max_shard_size)
615
+ else:
616
+ from collections import namedtuple
617
+ StateDictSplit = namedtuple("StateDictSplit", ["is_sharded", "filename_to_tensors"])
618
+ state_dict_split = StateDictSplit(is_sharded=False,
619
+ filename_to_tensors={weights_name: list(state_dict.keys())})
620
+
621
+
622
+ os.makedirs(output_dir, exist_ok=True)
623
+ filename_to_tensors = state_dict_split.filename_to_tensors.items()
624
+ for shard_file, tensors in tqdm(filename_to_tensors, desc="Saving checkpoint shards"):
625
+ shard_state_dict = {tensor_name: state_dict[tensor_name] for tensor_name in tensors}
626
+ shard_state_dict = to_torch_tensor(shard_state_dict)
627
+ output_path = os.path.join(output_dir, shard_file)
628
+ if safe_serialization:
629
+ save_file(shard_state_dict, output_path, metadata={"format": "pt"})
630
+ else:
631
+ torch.save(shard_state_dict, output_path)
632
+
633
+ for tensor_name in list(shard_state_dict.keys()):
634
+ del state_dict[tensor_name]
635
+ del shard_state_dict[tensor_name]
636
+ del shard_state_dict
637
+ gc.collect()
638
+
639
+
640
+ if state_dict_split.is_sharded:
641
+ index = {
642
+ "metadata": state_dict_split.metadata,
643
+ "weight_map": state_dict_split.tensor_to_filename,
644
+ }
645
+ save_index_file = "model.safetensors.index.json" if safe_serialization else "pytorch_model.bin.index.json"
646
+ save_index_file = os.path.join(output_dir, save_index_file)
647
+ with open(save_index_file, "w", encoding="utf-8") as f:
648
+ content = json.dumps(index, indent=2, sort_keys=True) + "\n"
649
+ f.write(content)
650
+
651
+
652
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
653
+ """
654
+ 1. Put the provided model to cpu
655
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
656
+ 3. Load it into the provided model
657
+
658
+ Args:
659
+ - ``model``: the model object to update
660
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
661
+ - ``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``
662
+
663
+ Returns:
664
+ - ``model`: modified model
665
+
666
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
667
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
668
+ conveniently placed for you in the checkpoint folder.
669
+
670
+ A typical usage might be ::
671
+
672
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
673
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
674
+ # submit to model hub or save the model to share with others
675
+
676
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
677
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
678
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
679
+
680
+ """
681
+ logger.info("Extracting fp32 weights")
682
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
683
+
684
+ logger.info("Overwriting model with fp32 weights")
685
+ model = model.cpu()
686
+ model.load_state_dict(state_dict, strict=False)
687
+
688
+ return model
689
+
690
+
691
+ if __name__ == "__main__":
692
+ parser = argparse.ArgumentParser()
693
+ parser.add_argument("checkpoint_dir",
694
+ type=str,
695
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
696
+ parser.add_argument("output_dir",
697
+ type=str,
698
+ help="directory to the pytorch fp32 state_dict output files"
699
+ "(e.g. path/checkpoint-12-output/)")
700
+ parser.add_argument(
701
+ "--max_shard_size",
702
+ type=str,
703
+ default="5GB",
704
+ help="The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size"
705
+ "lower than this size. If expressed as a string, needs to be digits followed by a unit (like `5MB`"
706
+ "We default it to 5GB in order for models to be able to run easily on free-tier google colab instances"
707
+ "without CPU OOM issues.")
708
+ parser.add_argument(
709
+ "--safe_serialization",
710
+ default=False,
711
+ action='store_true',
712
+ help="Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).")
713
+ parser.add_argument("-t",
714
+ "--tag",
715
+ type=str,
716
+ default=None,
717
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
718
+ parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
719
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
720
+ args = parser.parse_args()
721
+
722
+ debug = args.debug
723
+
724
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
725
+ args.output_dir,
726
+ max_shard_size=args.max_shard_size,
727
+ safe_serialization=args.safe_serialization,
728
+ tag=args.tag,
729
+ exclude_frozen_parameters=args.exclude_frozen_parameters)