wonsupshin commited on
Commit
9a13ef1
·
verified ·
1 Parent(s): f63a013

Upload checkpoint-40/

Browse files
checkpoint-40/chat_template.jinja ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {% for message in messages %}{% if loop.first and message['role'] != 'system' %}{{ '[|system|][|endofturn|]
2
+ ' }}{% endif %}{{ '[|' + message['role'] + '|]' + message['content'] }}{% if message['role'] == 'user' %}{{ '
3
+ ' }}{% else %}{{ '[|endofturn|]
4
+ ' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ '[|assistant|]' }}{% endif %}
checkpoint-40/config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_function": "silu",
3
+ "architectures": [
4
+ "ExaoneForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_exaone.ExaoneConfig",
9
+ "AutoModelForCausalLM": "modeling_exaone.ExaoneForCausalLM",
10
+ "AutoModelForSequenceClassification": "modeling_exaone.ExaoneForSequenceClassification"
11
+ },
12
+ "bos_token_id": 1,
13
+ "dtype": "bfloat16",
14
+ "embed_dropout": 0.0,
15
+ "eos_token_id": 361,
16
+ "head_dim": 128,
17
+ "hidden_size": 4096,
18
+ "initializer_range": 0.02,
19
+ "intermediate_size": 14336,
20
+ "layer_norm_epsilon": 1e-05,
21
+ "max_position_embeddings": 32768,
22
+ "model_type": "exaone",
23
+ "num_attention_heads": 32,
24
+ "num_key_value_heads": 8,
25
+ "num_layers": 32,
26
+ "pad_token_id": 0,
27
+ "rope_parameters": {
28
+ "factor": 8.0,
29
+ "high_freq_factor": 4.0,
30
+ "low_freq_factor": 1.0,
31
+ "original_max_position_embeddings": 8192,
32
+ "rope_theta": 1000000.0,
33
+ "rope_type": "llama3"
34
+ },
35
+ "rope_theta": 1000000.0,
36
+ "tie_word_embeddings": false,
37
+ "transformers_version": "5.7.0",
38
+ "use_cache": false,
39
+ "vocab_size": 102400
40
+ }
checkpoint-40/configuration_exaone.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/exaone/modular_exaone.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_exaone.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 The LG AI Research and HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ """LG AI Research EXAONE Lab"""
22
+
23
+ from transformers.configuration_utils import PretrainedConfig
24
+ from transformers.modeling_rope_utils import RopeParameters
25
+
26
+
27
+ class ExaoneConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`ExaoneModel`]. It is used to
30
+ instantiate a EXAONE model according to the specified arguments, defining the model architecture. Instantiating a
31
+ configuration with the defaults will yield a similar configuration to that of the EXAONE-3.0-7.8B-Instruct [LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct](https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct)
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model
34
+ outputs. Read the documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 102400):
39
+ Vocabulary size of the EXAONE model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`ExaoneModel`]. Vocabulary size of the model.
41
+ Defines the different tokens that can be represented by the `inputs_ids` passed to the forward method of
42
+ [`ExaoneModel`].
43
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
44
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
45
+ just in case (e.g., 512 or 1024 or 2048).
46
+ hidden_size (`int`, *optional*, defaults to 2048):
47
+ Dimensionality of the encoder layers and the pooler layer.
48
+ num_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer encoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ intermediate_size (`int`, *optional*, defaults to `hidden_size * 4`):
61
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
62
+ activation_function (`str` or `function`, *optional*, defaults to `"silu"`):
63
+ The non-linear activation function (function or string) in the decoder.
64
+ rope_theta (`float`, *optional*, defaults to 10000.0):
65
+ The base period of the RoPE embeddings.
66
+ rope_scaling (`Dict`, *optional*):
67
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
68
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
69
+ accordingly.
70
+ Expected contents:
71
+ `rope_type` (`str`):
72
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
73
+ 'llama3'], with 'default' being the original RoPE implementation.
74
+ `factor` (`float`, *optional*):
75
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
76
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
77
+ original maximum pre-trained length.
78
+ `original_max_position_embeddings` (`int`, *optional*):
79
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
80
+ pretraining.
81
+ `attention_factor` (`float`, *optional*):
82
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
83
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
84
+ `factor` field to infer the suggested value.
85
+ `beta_fast` (`float`, *optional*):
86
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
87
+ ramp function. If unspecified, it defaults to 32.
88
+ `beta_slow` (`float`, *optional*):
89
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
90
+ ramp function. If unspecified, it defaults to 1.
91
+ `short_factor` (`List[float]`, *optional*):
92
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
93
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
94
+ size divided by the number of attention heads divided by 2
95
+ `long_factor` (`List[float]`, *optional*):
96
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
97
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
98
+ size divided by the number of attention heads divided by 2
99
+ `low_freq_factor` (`float`, *optional*):
100
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
101
+ `high_freq_factor` (`float`, *optional*):
102
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
103
+ embed_dropout (`float`, *optional*, defaults to 0.0):
104
+ The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
105
+ attention_dropout (`float`, *optional*, defaults to 0.0):
106
+ The dropout ratio for the attention probabilities.
107
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
108
+ The epsilon used by the layer normalization layers.
109
+ initializer_range (`float`, *optional*, defaults to 0.02):
110
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
111
+ use_cache (`bool`, *optional*, defaults to `True`):
112
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
113
+ relevant if ``config.is_decoder=True``.
114
+ bos_token_id (`int`, *optional*, defaults to 0):
115
+ Beginning of stream token id.
116
+ eos_token_id (`int`, *optional*, defaults to 2):
117
+ End of stream token id.
118
+ pad_token_id (`int`, *optional*):
119
+ Padding token id.
120
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
121
+ Whether to tie weight embeddings
122
+
123
+ Example:
124
+
125
+ ```python
126
+ >>> from transformers import EXAONEModel, ExaoneConfig
127
+
128
+ >>> # Initializing a EXAONE configuration
129
+ >>> configuration = ExaoneConfig()
130
+
131
+ >>> # Initializing a model from configuration
132
+ >>> model = EXAONEModel(configuration)
133
+
134
+ >>> # Accessing the model configuration
135
+ >>> configuration = model.config
136
+ ```"""
137
+
138
+ model_type = "exaone"
139
+ keys_to_ignore_at_inference = ["past_key_values"]
140
+ attribute_map = {
141
+ "num_hidden_layers": "num_layers",
142
+ "hidden_act": "activation_function",
143
+ "rms_norm_eps": "layer_norm_epsilon",
144
+ }
145
+
146
+ def __init__(
147
+ self,
148
+ vocab_size: int | None = 102400,
149
+ max_position_embeddings=2048,
150
+ hidden_size: int | None = 2048,
151
+ num_layers: int | None = 32,
152
+ num_attention_heads: int | None = 32,
153
+ num_key_value_heads: int | None = None,
154
+ intermediate_size: int | None = None,
155
+ activation_function: str | None = "silu",
156
+ rope_parameters: RopeParameters | None = None,
157
+ embed_dropout: float | None = 0.0,
158
+ attention_dropout: float | None = 0.0,
159
+ layer_norm_epsilon: float | None = 1e-5,
160
+ initializer_range: float | None = 0.02,
161
+ use_cache: bool | None = True,
162
+ bos_token_id: int | None = 0,
163
+ eos_token_id: int | None = 2,
164
+ pad_token_id: int | None = None,
165
+ tie_word_embeddings: bool | None = False,
166
+ **kwargs,
167
+ ):
168
+ self.vocab_size = vocab_size
169
+ self.max_position_embeddings = max_position_embeddings
170
+ self.hidden_size = hidden_size
171
+ self.num_layers = num_layers
172
+ self.num_attention_heads = num_attention_heads
173
+ self.num_layers = num_layers
174
+ if num_key_value_heads is None:
175
+ num_key_value_heads = num_attention_heads
176
+ self.num_key_value_heads = num_key_value_heads
177
+ if intermediate_size:
178
+ self.intermediate_size = intermediate_size
179
+ else:
180
+ self.intermediate_size = hidden_size * 4
181
+ self.activation_function = activation_function
182
+ self.embed_dropout = embed_dropout
183
+ self.attention_dropout = attention_dropout
184
+ self.layer_norm_epsilon = layer_norm_epsilon
185
+ self.initializer_range = initializer_range
186
+ self.use_cache = use_cache
187
+ self.rope_parameters = rope_parameters
188
+
189
+ self.bos_token_id = bos_token_id
190
+ self.eos_token_id = eos_token_id
191
+ self.pad_token_id = pad_token_id
192
+ self.tie_word_embeddings = tie_word_embeddings
193
+
194
+ super().__init__(**kwargs)
195
+
196
+
197
+ __all__ = ["ExaoneConfig"]
checkpoint-40/generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 361
6
+ ],
7
+ "pad_token_id": 0,
8
+ "transformers_version": "5.7.0"
9
+ }
checkpoint-40/global_step40/bf16_zero_pp_rank_0_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:044e60a61e2e9715cc1a849da020504a16b7a5d1c2480f02909a514e7ec7c716
3
+ size 11788764019
checkpoint-40/global_step40/bf16_zero_pp_rank_1_mp_rank_00_optim_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:571b987a66a081b69fcf6cedad5cb8a76b7257446563e1c6ffdfded14d9bea78
3
+ size 11788764019
checkpoint-40/global_step40/bf16_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:2aa3b00119b89ddd87e92277a50f5531ffc4ab6811ed4437126afead5385105c
3
+ size 11788764019
checkpoint-40/global_step40/bf16_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:96bfd89df3ee58e0d44ec256b0361e98e42d27f394fe0e316db778b320ef9416
3
+ size 11788764019
checkpoint-40/global_step40/zero_pp_rank_0_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c044717a19e01c7fc778a2b05221b3436941110c3a461bfa67cccf65e5aa5007
3
+ size 150512
checkpoint-40/global_step40/zero_pp_rank_1_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2b2ad147bb4ee9e513dfddaf486ae3af5ed084c663a8ce618b81ab982bda4f7b
3
+ size 150512
checkpoint-40/global_step40/zero_pp_rank_2_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6d4a46d5e3fbd2843040cca7c9344cc24920d50b273370af80e7caaa630e45ba
3
+ size 150512
checkpoint-40/global_step40/zero_pp_rank_3_mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bdf45e81ca0c0cc6da4b1311af8f3e9cd8a7f380f0cce89b12edfff467cf85d8
3
+ size 150512
checkpoint-40/latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step40
checkpoint-40/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:508b43f76e3eefe29b14747c8877e60144eea280e7b30743ab5a37f97f8bd22b
3
+ size 15636931624
checkpoint-40/modeling_exaone.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/exaone/modular_exaone.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_exaone.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # Copyright 2026 The LG AI Research and HuggingFace Inc. team. All rights reserved.
8
+ #
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ """LG AI Research EXAONE Lab"""
22
+
23
+ from collections.abc import Callable
24
+ from typing import Optional
25
+
26
+ import torch
27
+ from torch import nn
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.generation import GenerationMixin
32
+ from transformers.integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
33
+ from transformers.masking_utils import create_causal_mask
34
+ from transformers.modeling_layers import GradientCheckpointingLayer
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
36
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
37
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from transformers.processing_utils import Unpack
39
+ from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
40
+ from transformers.utils.generic import check_model_inputs, maybe_autocast
41
+ from .configuration_exaone import ExaoneConfig
42
+
43
+
44
+ @use_kernel_forward_from_hub("RMSNorm")
45
+ class ExaoneRMSNorm(nn.Module):
46
+ def __init__(self, hidden_size, eps=1e-6):
47
+ """
48
+ ExaoneRMSNorm is equivalent to T5LayerNorm
49
+ """
50
+ super().__init__()
51
+ self.weight = nn.Parameter(torch.ones(hidden_size))
52
+ self.variance_epsilon = eps
53
+
54
+ def forward(self, hidden_states):
55
+ input_dtype = hidden_states.dtype
56
+ hidden_states = hidden_states.to(torch.float32)
57
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
58
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
59
+ return self.weight * hidden_states.to(input_dtype)
60
+
61
+ def extra_repr(self):
62
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
63
+
64
+
65
+ def rotate_half(x):
66
+ """Rotates half the hidden dims of the input."""
67
+ x1 = x[..., : x.shape[-1] // 2]
68
+ x2 = x[..., x.shape[-1] // 2 :]
69
+ return torch.cat((-x2, x1), dim=-1)
70
+
71
+
72
+ @use_kernel_func_from_hub("rotary_pos_emb")
73
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
74
+ """Applies Rotary Position Embedding to the query and key tensors.
75
+
76
+ Args:
77
+ q (`torch.Tensor`): The query tensor.
78
+ k (`torch.Tensor`): The key tensor.
79
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
80
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
81
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
82
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
83
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
84
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
85
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
86
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
87
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
88
+ Returns:
89
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
90
+ """
91
+ cos = cos.unsqueeze(unsqueeze_dim)
92
+ sin = sin.unsqueeze(unsqueeze_dim)
93
+ q_embed = (q * cos) + (rotate_half(q) * sin)
94
+ k_embed = (k * cos) + (rotate_half(k) * sin)
95
+ return q_embed, k_embed
96
+
97
+
98
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
99
+ """
100
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
101
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
102
+ """
103
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
104
+ if n_rep == 1:
105
+ return hidden_states
106
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
107
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
108
+
109
+
110
+ def eager_attention_forward(
111
+ module: nn.Module,
112
+ query: torch.Tensor,
113
+ key: torch.Tensor,
114
+ value: torch.Tensor,
115
+ attention_mask: torch.Tensor | None,
116
+ scaling: float,
117
+ dropout: float = 0.0,
118
+ **kwargs: Unpack[TransformersKwargs],
119
+ ):
120
+ key_states = repeat_kv(key, module.num_key_value_groups)
121
+ value_states = repeat_kv(value, module.num_key_value_groups)
122
+
123
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
124
+ if attention_mask is not None:
125
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
126
+ attn_weights = attn_weights + causal_mask
127
+
128
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
129
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
130
+ attn_output = torch.matmul(attn_weights, value_states)
131
+ attn_output = attn_output.transpose(1, 2).contiguous()
132
+
133
+ return attn_output, attn_weights
134
+
135
+
136
+ @use_kernelized_func(apply_rotary_pos_emb)
137
+ class ExaoneAttention(nn.Module):
138
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
139
+
140
+ def __init__(self, config: ExaoneConfig, layer_idx: int):
141
+ super().__init__()
142
+ self.config = config
143
+ self.layer_idx = layer_idx
144
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
145
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
146
+ self.scaling = self.head_dim**-0.5
147
+ self.attention_dropout = config.attention_dropout
148
+ self.is_causal = True
149
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
150
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
151
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
152
+ self.out_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
153
+
154
+ def forward(
155
+ self,
156
+ hidden_states: torch.Tensor,
157
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
158
+ attention_mask: torch.Tensor | None = None,
159
+ past_key_values: Cache | None = None,
160
+ cache_position: torch.LongTensor | None = None,
161
+ **kwargs: Unpack[TransformersKwargs],
162
+ ) -> tuple[torch.Tensor, torch.Tensor]:
163
+ input_shape = hidden_states.shape[:-1]
164
+ hidden_shape = (*input_shape, -1, self.head_dim)
165
+
166
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
167
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
168
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
169
+
170
+ cos, sin = position_embeddings
171
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
172
+
173
+ if past_key_values is not None:
174
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
175
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
176
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
177
+
178
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
179
+ self.config._attn_implementation, eager_attention_forward
180
+ )
181
+
182
+ attn_output, attn_weights = attention_interface(
183
+ self,
184
+ query_states,
185
+ key_states,
186
+ value_states,
187
+ attention_mask,
188
+ dropout=0.0 if not self.training else self.attention_dropout,
189
+ scaling=self.scaling,
190
+ **kwargs,
191
+ )
192
+
193
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
194
+ attn_output = self.out_proj(attn_output)
195
+ return attn_output, attn_weights
196
+
197
+
198
+ class ExaoneAttentionBlock(nn.Module):
199
+ """Dummy wrapper class for EXAONE 3.5 structure"""
200
+
201
+ def __init__(self, config: ExaoneConfig, layer_idx: int):
202
+ super().__init__()
203
+ self.config = config
204
+ self.layer_idx = layer_idx
205
+ self.attention = ExaoneAttention(config, layer_idx)
206
+
207
+ def forward(
208
+ self,
209
+ hidden_states: torch.Tensor,
210
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
211
+ attention_mask: torch.Tensor | None = None,
212
+ past_key_values: Cache | None = None,
213
+ cache_position: torch.LongTensor | None = None,
214
+ **kwargs: Unpack[TransformersKwargs],
215
+ ) -> tuple[torch.Tensor, torch.Tensor]:
216
+ return self.attention(
217
+ hidden_states=hidden_states,
218
+ position_embeddings=position_embeddings,
219
+ attention_mask=attention_mask,
220
+ past_key_values=past_key_values,
221
+ cache_position=cache_position,
222
+ **kwargs,
223
+ )
224
+
225
+
226
+ class ExaoneMLP(nn.Module):
227
+ def __init__(self, config):
228
+ super().__init__()
229
+ self.config = config
230
+ self.hidden_size = config.hidden_size
231
+ self.intermediate_size = config.intermediate_size
232
+ self.c_fc_0 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
233
+ self.c_fc_1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
234
+ self.c_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
235
+ self.act = ACT2FN[config.hidden_act]
236
+
237
+ def forward(self, x):
238
+ output_proj = self.c_proj(self.act(self.c_fc_0(x)) * self.c_fc_1(x))
239
+ return output_proj
240
+
241
+
242
+ class ExaoneDecoderLayer(GradientCheckpointingLayer):
243
+ def __init__(self, config, layer_id):
244
+ super().__init__()
245
+ self.config = config
246
+ self.hidden_size = config.hidden_size
247
+ self.ln_1 = ExaoneRMSNorm(hidden_size=self.hidden_size, eps=config.layer_norm_epsilon)
248
+ self.attn = ExaoneAttentionBlock(config, layer_id)
249
+ self.ln_2 = ExaoneRMSNorm(hidden_size=self.hidden_size, eps=config.layer_norm_epsilon)
250
+ self.mlp = ExaoneMLP(config)
251
+
252
+ def forward(
253
+ self,
254
+ hidden_states: torch.Tensor,
255
+ attention_mask: torch.Tensor | None = None,
256
+ position_ids: torch.LongTensor | None = None,
257
+ past_key_values: Cache | None = None,
258
+ use_cache: bool | None = False,
259
+ cache_position: torch.LongTensor | None = None,
260
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
261
+ **kwargs: Unpack[TransformersKwargs],
262
+ ) -> torch.Tensor:
263
+ residual = hidden_states
264
+ hidden_states = self.ln_1(hidden_states)
265
+ # Self Attention
266
+ hidden_states, _ = self.attn(
267
+ hidden_states=hidden_states,
268
+ attention_mask=attention_mask,
269
+ position_ids=position_ids,
270
+ past_key_values=past_key_values,
271
+ use_cache=use_cache,
272
+ cache_position=cache_position,
273
+ position_embeddings=position_embeddings,
274
+ **kwargs,
275
+ )
276
+ hidden_states = residual + hidden_states
277
+
278
+ # Fully Connected
279
+ residual = hidden_states
280
+ hidden_states = self.ln_2(hidden_states)
281
+ hidden_states = self.mlp(hidden_states)
282
+ hidden_states = residual + hidden_states
283
+ return hidden_states
284
+
285
+
286
+ @auto_docstring
287
+ class ExaonePreTrainedModel(PreTrainedModel):
288
+ config: ExaoneConfig
289
+
290
+ base_model_prefix = "transformer"
291
+ supports_gradient_checkpointing = True
292
+ _no_split_modules = ["ExaoneDecoderLayer"]
293
+ _skip_keys_device_placement = ["past_key_values"]
294
+ _supports_flash_attn = True
295
+ _supports_sdpa = True
296
+ _supports_flex_attn = True
297
+
298
+ _can_compile_fullgraph = True
299
+ _supports_attention_backend = True
300
+ _can_record_outputs = {
301
+ "hidden_states": ExaoneDecoderLayer,
302
+ "attentions": ExaoneAttention,
303
+ }
304
+
305
+
306
+ class ExaoneRotaryEmbedding(nn.Module):
307
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
308
+
309
+ def __init__(self, config: ExaoneConfig, device=None):
310
+ super().__init__()
311
+ self.max_seq_len_cached = config.max_position_embeddings
312
+ self.original_max_seq_len = config.max_position_embeddings
313
+
314
+ self.config = config
315
+
316
+ self.rope_type = self.config.rope_parameters["rope_type"]
317
+ rope_init_fn: Callable = self.compute_default_rope_parameters
318
+ if self.rope_type != "default":
319
+ rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
320
+ inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
321
+
322
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
323
+ self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
324
+
325
+ @staticmethod
326
+ def compute_default_rope_parameters(
327
+ config: ExaoneConfig | None = None,
328
+ device: Optional["torch.device"] = None,
329
+ seq_len: int | None = None,
330
+ ) -> tuple["torch.Tensor", float]:
331
+ """
332
+ Computes the inverse frequencies according to the original RoPE implementation
333
+ Args:
334
+ config ([`~transformers.PreTrainedConfig`]):
335
+ The model configuration.
336
+ device (`torch.device`):
337
+ The device to use for initialization of the inverse frequencies.
338
+ seq_len (`int`, *optional*):
339
+ The current sequence length. Unused for this type of RoPE.
340
+ Returns:
341
+ Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
342
+ post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
343
+ """
344
+ base = config.rope_parameters["rope_theta"]
345
+ dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
346
+
347
+ attention_factor = 1.0 # Unused in this type of RoPE
348
+
349
+ # Compute the inverse frequencies
350
+ inv_freq = 1.0 / (
351
+ base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
352
+ )
353
+ return inv_freq, attention_factor
354
+
355
+ @torch.no_grad()
356
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
357
+ def forward(self, x, position_ids):
358
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
359
+ position_ids_expanded = position_ids[:, None, :].float()
360
+
361
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
362
+ with maybe_autocast(device_type=device_type, enabled=False): # Force float32
363
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
364
+ emb = torch.cat((freqs, freqs), dim=-1)
365
+ cos = emb.cos() * self.attention_scaling
366
+ sin = emb.sin() * self.attention_scaling
367
+
368
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
369
+
370
+
371
+ @auto_docstring
372
+ class ExaoneModel(ExaonePreTrainedModel):
373
+ def __init__(self, config: ExaoneConfig):
374
+ super().__init__(config)
375
+ self.config = config
376
+ self.hidden_size = config.hidden_size
377
+ self.padding_idx = config.pad_token_id
378
+ self.vocab_size = config.vocab_size
379
+
380
+ self.wte = nn.Embedding(self.vocab_size, self.hidden_size, self.padding_idx)
381
+ self.drop = nn.Dropout(float(config.embed_dropout))
382
+ self.h = nn.ModuleList([ExaoneDecoderLayer(config, layer_id=i) for i in range(config.num_layers)])
383
+ self.ln_f = ExaoneRMSNorm(hidden_size=self.hidden_size, eps=config.layer_norm_epsilon)
384
+ self.rotary = ExaoneRotaryEmbedding(config)
385
+
386
+ # Initialize weights and apply final processing
387
+ self.post_init()
388
+
389
+ @check_model_inputs
390
+ @auto_docstring
391
+ def forward(
392
+ self,
393
+ input_ids: torch.LongTensor | None = None,
394
+ attention_mask: torch.Tensor | None = None,
395
+ position_ids: torch.LongTensor | None = None,
396
+ past_key_values: Cache | None = None,
397
+ inputs_embeds: torch.FloatTensor | None = None,
398
+ cache_position: torch.LongTensor | None = None,
399
+ use_cache: bool | None = None,
400
+ **kwargs: Unpack[TransformersKwargs],
401
+ ) -> BaseModelOutputWithPast:
402
+ if (input_ids is None) ^ (inputs_embeds is not None):
403
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
404
+
405
+ if inputs_embeds is None:
406
+ inputs_embeds: torch.Tensor = self.wte(input_ids)
407
+
408
+ if use_cache and past_key_values is None:
409
+ past_key_values = DynamicCache(config=self.config)
410
+
411
+ if cache_position is None:
412
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
413
+ cache_position: torch.Tensor = (
414
+ torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
415
+ )
416
+
417
+ if position_ids is None:
418
+ position_ids = cache_position.unsqueeze(0)
419
+
420
+ causal_mask = create_causal_mask(
421
+ config=self.config,
422
+ input_embeds=inputs_embeds,
423
+ attention_mask=attention_mask,
424
+ cache_position=cache_position,
425
+ past_key_values=past_key_values,
426
+ position_ids=position_ids,
427
+ )
428
+
429
+ hidden_states = inputs_embeds
430
+ position_embeddings = self.rotary(hidden_states, position_ids=position_ids)
431
+
432
+ for decoder_layer in self.h[: self.config.num_layers]:
433
+ hidden_states = decoder_layer(
434
+ hidden_states,
435
+ attention_mask=causal_mask,
436
+ position_embeddings=position_embeddings,
437
+ position_ids=position_ids,
438
+ past_key_values=past_key_values,
439
+ use_cache=use_cache,
440
+ cache_position=cache_position,
441
+ **kwargs,
442
+ )
443
+
444
+ hidden_states = self.ln_f(hidden_states)
445
+ return BaseModelOutputWithPast(
446
+ last_hidden_state=hidden_states,
447
+ past_key_values=past_key_values,
448
+ )
449
+
450
+
451
+ @auto_docstring
452
+ class ExaoneForCausalLM(ExaonePreTrainedModel, GenerationMixin):
453
+ _tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"}
454
+ _tp_plan = {"lm_head": "colwise_gather_output"}
455
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
456
+
457
+ def __init__(self, config):
458
+ super().__init__(config)
459
+ self.transformer = ExaoneModel(config)
460
+ self.vocab_size = config.vocab_size
461
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
462
+
463
+ # Initialize weights and apply final processing
464
+ self.post_init()
465
+
466
+ @can_return_tuple
467
+ @auto_docstring
468
+ def forward(
469
+ self,
470
+ input_ids: torch.LongTensor | None = None,
471
+ attention_mask: torch.Tensor | None = None,
472
+ position_ids: torch.LongTensor | None = None,
473
+ past_key_values: Cache | None = None,
474
+ inputs_embeds: torch.FloatTensor | None = None,
475
+ labels: torch.LongTensor | None = None,
476
+ use_cache: bool | None = None,
477
+ cache_position: torch.LongTensor | None = None,
478
+ logits_to_keep: int | torch.Tensor = 0,
479
+ **kwargs: Unpack[TransformersKwargs],
480
+ ) -> CausalLMOutputWithPast:
481
+ r"""
482
+ Args:
483
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
484
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
485
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
486
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
487
+
488
+ Example:
489
+
490
+ ```python
491
+ >>> from transformers import AutoModelForCausalLM, AutoTokenizer
492
+
493
+ >>> model = AutoModelForCausalLM.from_pretrained("LGAI-EXAONE/EXAONE-3.5-2.4B-Instruct",
494
+ trust_remote_code=True)
495
+ >>> tokenizer = AutoTokenizer.from_pretrained("LGAI-EXAONE/EXAONE-3.5-2.4B-Instruct")
496
+
497
+ >>> prompt = "Explain how wonderful you are"
498
+ >>> messages = [
499
+ {"role": "system", "content": "You are a helpful assistant."},
500
+ {"role": "user", "content": prompt}
501
+ ]
502
+ >>> input_ids = tokenizer.apply_chat_template(
503
+ messages,
504
+ tokenize=True,
505
+ add_generation_prompt=True,
506
+ return_tensors="pt"
507
+ )
508
+
509
+ >>> output = model.generate(**input_ids.to(model.device), max_new_tokens=128)
510
+ >>> tokenizer.decode(output[0], skip_special_tokens=True)
511
+ '[|system|]You are a helpful assistant.\n[|user|]Explain how wonderful you are\n[|assistant|]As an AI assistant, I don\'t experience feelings or qualities like "wonderfulness" in the way humans do, but I can certainly highlight several aspects that make my capabilities and interactions valuable and beneficial:\n\n1. **Knowledge and Information**: I am equipped with extensive knowledge across a wide range of topics including science, technology, history, culture, and more. This allows me to provide accurate, informative responses to a vast array of inquiries, helping users learn and explore new ideas.\n\n2. **Accessibility**: I am available 24/7, meaning you can ask me questions or seek assistance at'
512
+ ```
513
+ """
514
+ outputs: BaseModelOutputWithPast = self.transformer(
515
+ input_ids=input_ids,
516
+ attention_mask=attention_mask,
517
+ position_ids=position_ids,
518
+ past_key_values=past_key_values,
519
+ inputs_embeds=inputs_embeds,
520
+ use_cache=use_cache,
521
+ cache_position=cache_position,
522
+ **kwargs,
523
+ )
524
+
525
+ hidden_states = outputs.last_hidden_state
526
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
527
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
528
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
529
+
530
+ loss = None
531
+ if labels is not None:
532
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
533
+
534
+ return CausalLMOutputWithPast(
535
+ loss=loss,
536
+ logits=logits,
537
+ past_key_values=outputs.past_key_values,
538
+ hidden_states=outputs.hidden_states,
539
+ attentions=outputs.attentions,
540
+ )
541
+
542
+
543
+ __all__ = ["ExaonePreTrainedModel", "ExaoneModel", "ExaoneForCausalLM"]
checkpoint-40/rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2fe6b873f1da64bb980afe982fc1c6b6bc461ad8c33073d856804323f64b26d9
3
+ size 15429
checkpoint-40/rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13db4dd10b22b5464f5ef0b539152b46390eae6a827b355108cb54b1af2eb830
3
+ size 15429
checkpoint-40/rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06e293f13fb6e873e8081636b6b07115410b397c55f1ed08b8772b059c8eb74e
3
+ size 15429
checkpoint-40/rng_state_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c595c077664f94b7f91088561951be20e39483e01865774a83bc46f3971a3152
3
+ size 15429
checkpoint-40/scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e5bd29a07a9c2ce09354b17c073dcc155b7a74ce4be44a8dae595af26e300186
3
+ size 1401
checkpoint-40/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
checkpoint-40/tokenizer_config.json ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "additional_special_token": [
4
+ "[unused0]",
5
+ "[unused1]",
6
+ "[unused2]",
7
+ "[unused3]",
8
+ "[unused4]",
9
+ "[unused5]",
10
+ "[unused6]",
11
+ "[unused7]",
12
+ "[unused8]",
13
+ "[unused9]",
14
+ "[unused10]",
15
+ "[unused11]",
16
+ "[unused12]",
17
+ "[unused13]",
18
+ "[unused14]",
19
+ "[unused15]",
20
+ "[unused16]",
21
+ "[unused17]",
22
+ "[unused18]",
23
+ "[unused19]",
24
+ "[unused20]",
25
+ "[unused21]",
26
+ "[unused22]",
27
+ "[unused23]",
28
+ "[unused24]",
29
+ "[unused25]",
30
+ "[unused26]",
31
+ "[unused27]",
32
+ "[unused28]",
33
+ "[unused29]",
34
+ "[unused30]",
35
+ "[unused31]",
36
+ "[unused32]",
37
+ "[unused33]",
38
+ "[unused34]",
39
+ "[unused35]",
40
+ "[unused36]",
41
+ "[unused37]",
42
+ "[unused38]",
43
+ "[unused39]",
44
+ "[unused40]",
45
+ "[unused41]",
46
+ "[unused42]",
47
+ "[unused43]",
48
+ "[unused44]",
49
+ "[unused45]",
50
+ "[unused46]",
51
+ "[unused47]",
52
+ "[unused48]",
53
+ "[unused49]",
54
+ "[unused50]",
55
+ "[unused51]",
56
+ "[unused52]",
57
+ "[unused53]",
58
+ "[unused54]",
59
+ "[unused55]",
60
+ "[unused56]",
61
+ "[unused57]",
62
+ "[unused58]",
63
+ "[unused59]",
64
+ "[unused60]",
65
+ "[unused61]",
66
+ "[unused62]",
67
+ "[unused63]",
68
+ "[unused64]",
69
+ "[unused65]",
70
+ "[unused66]",
71
+ "[unused67]",
72
+ "[unused68]",
73
+ "[unused69]",
74
+ "[unused70]",
75
+ "[unused71]",
76
+ "[unused72]",
77
+ "[unused73]",
78
+ "[unused74]",
79
+ "[unused75]",
80
+ "[unused76]",
81
+ "[unused77]",
82
+ "[unused78]",
83
+ "[unused79]",
84
+ "[unused80]",
85
+ "[unused81]",
86
+ "[unused82]",
87
+ "[unused83]",
88
+ "[unused84]",
89
+ "[unused85]",
90
+ "[unused86]",
91
+ "[unused87]",
92
+ "[unused88]",
93
+ "[unused89]",
94
+ "[unused90]",
95
+ "[unused91]",
96
+ "[unused92]",
97
+ "[unused93]",
98
+ "[unused94]",
99
+ "[unused95]",
100
+ "[unused96]",
101
+ "[unused97]",
102
+ "[unused98]",
103
+ "[unused99]",
104
+ "[extra_id_0]",
105
+ "[extra_id_1]",
106
+ "[extra_id_2]",
107
+ "[extra_id_3]",
108
+ "[extra_id_4]",
109
+ "[extra_id_5]",
110
+ "[extra_id_6]",
111
+ "[extra_id_7]",
112
+ "[extra_id_8]",
113
+ "[extra_id_9]",
114
+ "[extra_id_10]",
115
+ "[extra_id_11]",
116
+ "[extra_id_12]",
117
+ "[extra_id_13]",
118
+ "[extra_id_14]",
119
+ "[extra_id_15]",
120
+ "[extra_id_16]",
121
+ "[extra_id_17]",
122
+ "[extra_id_18]",
123
+ "[extra_id_19]",
124
+ "[extra_id_20]",
125
+ "[extra_id_21]",
126
+ "[extra_id_22]",
127
+ "[extra_id_23]",
128
+ "[extra_id_24]",
129
+ "[extra_id_25]",
130
+ "[extra_id_26]",
131
+ "[extra_id_27]",
132
+ "[extra_id_28]",
133
+ "[extra_id_29]",
134
+ "[extra_id_30]",
135
+ "[extra_id_31]",
136
+ "[extra_id_32]",
137
+ "[extra_id_33]",
138
+ "[extra_id_34]",
139
+ "[extra_id_35]",
140
+ "[extra_id_36]",
141
+ "[extra_id_37]",
142
+ "[extra_id_38]",
143
+ "[extra_id_39]",
144
+ "[extra_id_40]",
145
+ "[extra_id_41]",
146
+ "[extra_id_42]",
147
+ "[extra_id_43]",
148
+ "[extra_id_44]",
149
+ "[extra_id_45]",
150
+ "[extra_id_46]",
151
+ "[extra_id_47]",
152
+ "[extra_id_48]",
153
+ "[extra_id_49]",
154
+ "[extra_id_50]",
155
+ "[extra_id_51]",
156
+ "[extra_id_52]",
157
+ "[extra_id_53]",
158
+ "[extra_id_54]",
159
+ "[extra_id_55]",
160
+ "[extra_id_56]",
161
+ "[extra_id_57]",
162
+ "[extra_id_58]",
163
+ "[extra_id_59]",
164
+ "[extra_id_60]",
165
+ "[extra_id_61]",
166
+ "[extra_id_62]",
167
+ "[extra_id_63]",
168
+ "[extra_id_64]",
169
+ "[extra_id_65]",
170
+ "[extra_id_66]",
171
+ "[extra_id_67]",
172
+ "[extra_id_68]",
173
+ "[extra_id_69]",
174
+ "[extra_id_70]",
175
+ "[extra_id_71]",
176
+ "[extra_id_72]",
177
+ "[extra_id_73]",
178
+ "[extra_id_74]",
179
+ "[extra_id_75]",
180
+ "[extra_id_76]",
181
+ "[extra_id_77]",
182
+ "[extra_id_78]",
183
+ "[extra_id_79]",
184
+ "[extra_id_80]",
185
+ "[extra_id_81]",
186
+ "[extra_id_82]",
187
+ "[extra_id_83]",
188
+ "[extra_id_84]",
189
+ "[extra_id_85]",
190
+ "[extra_id_86]",
191
+ "[extra_id_87]",
192
+ "[extra_id_88]",
193
+ "[extra_id_89]",
194
+ "[extra_id_90]",
195
+ "[extra_id_91]",
196
+ "[extra_id_92]",
197
+ "[extra_id_93]",
198
+ "[extra_id_94]",
199
+ "[extra_id_95]",
200
+ "[extra_id_96]",
201
+ "[extra_id_97]",
202
+ "[extra_id_98]",
203
+ "[extra_id_99]",
204
+ "[extra_id_100]",
205
+ "[extra_id_101]",
206
+ "[extra_id_102]",
207
+ "[extra_id_103]",
208
+ "[extra_id_104]",
209
+ "[extra_id_105]",
210
+ "[extra_id_106]",
211
+ "[extra_id_107]",
212
+ "[extra_id_108]",
213
+ "[extra_id_109]",
214
+ "[extra_id_110]",
215
+ "[extra_id_111]",
216
+ "[extra_id_112]",
217
+ "[extra_id_113]",
218
+ "[extra_id_114]",
219
+ "[extra_id_115]",
220
+ "[extra_id_116]",
221
+ "[extra_id_117]",
222
+ "[extra_id_118]",
223
+ "[extra_id_119]",
224
+ "[extra_id_120]",
225
+ "[extra_id_121]",
226
+ "[extra_id_122]",
227
+ "[extra_id_123]",
228
+ "[extra_id_124]",
229
+ "[extra_id_125]",
230
+ "[extra_id_126]",
231
+ "[extra_id_127]",
232
+ "[extra_id_128]",
233
+ "[extra_id_129]",
234
+ "[extra_id_130]",
235
+ "[extra_id_131]",
236
+ "[extra_id_132]",
237
+ "[extra_id_133]",
238
+ "[extra_id_134]",
239
+ "[extra_id_135]",
240
+ "[extra_id_136]",
241
+ "[extra_id_137]",
242
+ "[extra_id_138]",
243
+ "[extra_id_139]",
244
+ "[extra_id_140]",
245
+ "[extra_id_141]",
246
+ "[extra_id_142]",
247
+ "[extra_id_143]",
248
+ "[extra_id_144]",
249
+ "[extra_id_145]",
250
+ "[extra_id_146]",
251
+ "[extra_id_147]",
252
+ "[extra_id_148]",
253
+ "[extra_id_149]",
254
+ "[extra_id_150]",
255
+ "[extra_id_151]",
256
+ "[extra_id_152]",
257
+ "[extra_id_153]",
258
+ "[extra_id_154]",
259
+ "[extra_id_155]",
260
+ "[extra_id_156]",
261
+ "[extra_id_157]",
262
+ "[extra_id_158]",
263
+ "[extra_id_159]",
264
+ "[extra_id_160]",
265
+ "[extra_id_161]",
266
+ "[extra_id_162]",
267
+ "[extra_id_163]",
268
+ "[extra_id_164]",
269
+ "[extra_id_165]",
270
+ "[extra_id_166]",
271
+ "[extra_id_167]",
272
+ "[extra_id_168]",
273
+ "[extra_id_169]",
274
+ "[extra_id_170]",
275
+ "[extra_id_171]",
276
+ "[extra_id_172]",
277
+ "[extra_id_173]",
278
+ "[extra_id_174]",
279
+ "[extra_id_175]",
280
+ "[extra_id_176]",
281
+ "[extra_id_177]",
282
+ "[extra_id_178]",
283
+ "[extra_id_179]",
284
+ "[extra_id_180]",
285
+ "[extra_id_181]",
286
+ "[extra_id_182]",
287
+ "[extra_id_183]",
288
+ "[extra_id_184]",
289
+ "[extra_id_185]",
290
+ "[extra_id_186]",
291
+ "[extra_id_187]",
292
+ "[extra_id_188]",
293
+ "[extra_id_189]",
294
+ "[extra_id_190]",
295
+ "[extra_id_191]",
296
+ "[extra_id_192]",
297
+ "[extra_id_193]",
298
+ "[extra_id_194]",
299
+ "[extra_id_195]",
300
+ "[extra_id_196]",
301
+ "[extra_id_197]",
302
+ "[extra_id_198]",
303
+ "[|endofturn|]",
304
+ "PI:URL",
305
+ "PI:EMAIL",
306
+ "PI:ACCOUNT_NUM",
307
+ "PI:PHONE_NUM",
308
+ "PI:BUSINESS_NUM",
309
+ "PI:ANNON",
310
+ "PI:KEY",
311
+ "PI:ID",
312
+ "PI:IP_ADDRESS",
313
+ "PI:USER"
314
+ ],
315
+ "backend": "tokenizers",
316
+ "bos_token": "[BOS]",
317
+ "clean_up_tokenization_spaces": true,
318
+ "eos_token": "[|endofturn|]",
319
+ "errors": "replace",
320
+ "is_local": false,
321
+ "local_files_only": false,
322
+ "model_max_length": 1000000000000000019884624838656,
323
+ "pad_token": "[PAD]",
324
+ "tokenizer_class": "GPT2Tokenizer",
325
+ "unk_token": "[UNK]"
326
+ }
checkpoint-40/trainer_state.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 2.0,
6
+ "eval_steps": 500,
7
+ "global_step": 40,
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.5228758169934641,
14
+ "grad_norm": 4.096013598842928,
15
+ "learning_rate": 9.644883599083959e-06,
16
+ "loss": 2.5423198699951173,
17
+ "mean_token_accuracy": 0.5685750585049391,
18
+ "num_tokens": 91495.0,
19
+ "step": 10
20
+ },
21
+ {
22
+ "epoch": 1.0,
23
+ "grad_norm": 6.747715140097201,
24
+ "learning_rate": 8.025871075968828e-06,
25
+ "loss": 1.4160140037536622,
26
+ "mean_token_accuracy": 0.6783009481756654,
27
+ "num_tokens": 176167.0,
28
+ "step": 20
29
+ },
30
+ {
31
+ "epoch": 1.522875816993464,
32
+ "grad_norm": 3.445904738767255,
33
+ "learning_rate": 5.540595092119709e-06,
34
+ "loss": 1.0047502517700195,
35
+ "mean_token_accuracy": 0.7559794817119837,
36
+ "num_tokens": 269468.0,
37
+ "step": 30
38
+ },
39
+ {
40
+ "epoch": 2.0,
41
+ "grad_norm": 7.0459795774794385,
42
+ "learning_rate": 2.9005544921986774e-06,
43
+ "loss": 0.8993229866027832,
44
+ "mean_token_accuracy": 0.77471841075649,
45
+ "num_tokens": 352326.0,
46
+ "step": 40
47
+ }
48
+ ],
49
+ "logging_steps": 10,
50
+ "max_steps": 60,
51
+ "num_input_tokens_seen": 0,
52
+ "num_train_epochs": 3,
53
+ "save_steps": 500,
54
+ "stateful_callbacks": {
55
+ "TrainerControl": {
56
+ "args": {
57
+ "should_epoch_stop": false,
58
+ "should_evaluate": false,
59
+ "should_log": false,
60
+ "should_save": true,
61
+ "should_training_stop": false
62
+ },
63
+ "attributes": {}
64
+ }
65
+ },
66
+ "total_flos": 1.382071083728896e+16,
67
+ "train_batch_size": 1,
68
+ "trial_name": null,
69
+ "trial_params": null
70
+ }
checkpoint-40/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)