chegde commited on
Commit
58be2dc
·
verified ·
1 Parent(s): e7a08f4

Add files using upload-large-folder tool

Browse files
added_tokens.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<|assistant|>": 32001,
3
+ "<|endoftext|>": 32000,
4
+ "<|end|>": 32007,
5
+ "<|placeholder1|>": 32002,
6
+ "<|placeholder2|>": 32003,
7
+ "<|placeholder3|>": 32004,
8
+ "<|placeholder4|>": 32005,
9
+ "<|placeholder5|>": 32008,
10
+ "<|placeholder6|>": 32009,
11
+ "<|system|>": 32006,
12
+ "<|user|>": 32010
13
+ }
chat_template.jinja ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {% for message in messages %}{% if (message['role'] == 'user') %}{{'<|user|>' + '
2
+ ' + message['content'] + '<|end|>' + '
3
+ ' + '<|assistant|>' + '
4
+ '}}{% elif (message['role'] == 'assistant') %}{{message['content'] + '<|end|>' + '
5
+ '}}{% endif %}{% endfor %}
config.json ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Phi3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_phi3.Phi3Config",
9
+ "AutoModel": "modeling_phi3.Phi3ForCausalLM",
10
+ "AutoModelForCausalLM": "microsoft/Phi-3-medium-128k-instruct--modeling_phi3.Phi3ForCausalLM"
11
+ },
12
+ "bos_token_id": 1,
13
+ "embd_pdrop": 0.0,
14
+ "eos_token_id": 32000,
15
+ "hidden_act": "silu",
16
+ "hidden_size": 5120,
17
+ "initializer_range": 0.02,
18
+ "intermediate_size": 17920,
19
+ "max_position_embeddings": 131072,
20
+ "model_type": "phi3",
21
+ "num_attention_heads": 40,
22
+ "num_hidden_layers": 40,
23
+ "num_key_value_heads": 10,
24
+ "original_max_position_embeddings": 4096,
25
+ "pad_token_id": null,
26
+ "resid_pdrop": 0.0,
27
+ "rms_norm_eps": 1e-05,
28
+ "rope_scaling": {
29
+ "long_factor": [
30
+ 1.0,
31
+ 1.0,
32
+ 1.0,
33
+ 1.0,
34
+ 1.0,
35
+ 1.0,
36
+ 1.0,
37
+ 1.0,
38
+ 1.0,
39
+ 1.0,
40
+ 1.0,
41
+ 1.0,
42
+ 1.0,
43
+ 1.25,
44
+ 1.25,
45
+ 1.5,
46
+ 2.0,
47
+ 2.75,
48
+ 5.75,
49
+ 5.75,
50
+ 6.5,
51
+ 9.25,
52
+ 11.0,
53
+ 13.25,
54
+ 19.25,
55
+ 19.75,
56
+ 19.75,
57
+ 21.25,
58
+ 21.5,
59
+ 26.5,
60
+ 30.0,
61
+ 33.75,
62
+ 35.25,
63
+ 38.5,
64
+ 42.0,
65
+ 42.25,
66
+ 46.0,
67
+ 47.0,
68
+ 50.0,
69
+ 50.5,
70
+ 51.0,
71
+ 52.0,
72
+ 52.75,
73
+ 53.75,
74
+ 54.75,
75
+ 57.0,
76
+ 57.25,
77
+ 58.5,
78
+ 59.25,
79
+ 59.5,
80
+ 62.0,
81
+ 62.5,
82
+ 62.75,
83
+ 63.25,
84
+ 63.25,
85
+ 63.25,
86
+ 63.75,
87
+ 64.0,
88
+ 64.0,
89
+ 64.25,
90
+ 64.5,
91
+ 64.5,
92
+ 65.0,
93
+ 65.0
94
+ ],
95
+ "short_factor": [
96
+ 1.0,
97
+ 1.0,
98
+ 1.0,
99
+ 1.0,
100
+ 1.0,
101
+ 1.0,
102
+ 1.01,
103
+ 1.02,
104
+ 1.02,
105
+ 1.04,
106
+ 1.04,
107
+ 1.07,
108
+ 1.07,
109
+ 1.1,
110
+ 1.3000000000000003,
111
+ 1.3000000000000003,
112
+ 1.5000000000000004,
113
+ 1.5700000000000005,
114
+ 1.9000000000000008,
115
+ 2.3100000000000014,
116
+ 2.759999999999992,
117
+ 3.3899999999999784,
118
+ 3.9399999999999666,
119
+ 4.009999999999965,
120
+ 4.289999999999959,
121
+ 4.349999999999958,
122
+ 5.349999999999937,
123
+ 6.659999999999909,
124
+ 7.029999999999901,
125
+ 7.51999999999989,
126
+ 8.00999999999988,
127
+ 8.249999999999876,
128
+ 8.279999999999875,
129
+ 9.629999999999846,
130
+ 9.89999999999984,
131
+ 10.589999999999826,
132
+ 11.049999999999816,
133
+ 11.7899999999998,
134
+ 12.189999999999792,
135
+ 12.889999999999777,
136
+ 13.129999999999772,
137
+ 13.16999999999977,
138
+ 13.20999999999977,
139
+ 13.479999999999764,
140
+ 13.539999999999763,
141
+ 13.779999999999758,
142
+ 13.929999999999755,
143
+ 14.429999999999744,
144
+ 14.759999999999737,
145
+ 15.149999999999729,
146
+ 15.419999999999723,
147
+ 15.53999999999972,
148
+ 15.659999999999718,
149
+ 15.749999999999716,
150
+ 15.759999999999716,
151
+ 15.799999999999715,
152
+ 16.05999999999971,
153
+ 16.079999999999714,
154
+ 16.11999999999972,
155
+ 16.11999999999972,
156
+ 16.18999999999973,
157
+ 16.31999999999975,
158
+ 16.539999999999786,
159
+ 16.799999999999827
160
+ ],
161
+ "type": "su"
162
+ },
163
+ "rope_theta": 10000.0,
164
+ "sliding_window": 131072,
165
+ "tie_word_embeddings": false,
166
+ "torch_dtype": "bfloat16",
167
+ "transformers_version": "4.52.4",
168
+ "use_cache": false,
169
+ "vocab_size": 32064
170
+ }
configuration_phi3.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ Phi-3 model configuration"""
17
+
18
+
19
+ from transformers.configuration_utils import PretrainedConfig
20
+ from transformers.utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ PHI3_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "microsoft/Phi-3-mini-4k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-4k-instruct/resolve/main/config.json",
27
+ "microsoft/Phi-3-mini-128k-instruct": "https://huggingface.co/microsoft/Phi-3-mini-128k-instruct/resolve/main/config.json",
28
+ }
29
+
30
+
31
+ class Phi3Config(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the
36
+ [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32064):
43
+ Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`Phi3Model`].
45
+ hidden_size (`int`, *optional*, defaults to 3072):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 8192):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
62
+ Dropout probability for mlp outputs.
63
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the embeddings.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio after computing the attention scores.
67
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
68
+ The non-linear activation function (function or string) in the decoder.
69
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
70
+ The maximum sequence length that this model might ever be used with.
71
+ original_max_position_embeddings (`int`, *optional*, defaults to 4096):
72
+ The maximum sequence length that this model was trained with. This is used to determine the size of the
73
+ original RoPE embeddings when using long scaling.
74
+ initializer_range (`float`, *optional*, defaults to 0.02):
75
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
76
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
77
+ The epsilon value used for the RMSNorm.
78
+ use_cache (`bool`, *optional*, defaults to `True`):
79
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
80
+ relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
81
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
82
+ Whether to tie weight embeddings
83
+ rope_theta (`float`, *optional*, defaults to 10000.0):
84
+ The base period of the RoPE embeddings.
85
+ rope_scaling (`dict`, *optional*):
86
+ The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
87
+ contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be either `su` or `yarn` and
88
+ the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
89
+ divided by the number of attention heads divided by 2.
90
+ bos_token_id (`int`, *optional*, defaults to 1):
91
+ The id of the "beginning-of-sequence" token.
92
+ eos_token_id (`int`, *optional*, defaults to 32000):
93
+ The id of the "end-of-sequence" token.
94
+ pad_token_id (`int`, *optional*, defaults to 32000):
95
+ The id of the padding token.
96
+ sliding_window (`int`, *optional*):
97
+ Sliding window attention window size. If `None`, no sliding window is applied.
98
+
99
+ Example:
100
+
101
+ ```python
102
+ >>> from transformers import Phi3Model, Phi3Config
103
+
104
+ >>> # Initializing a Phi-3 style configuration
105
+ >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
106
+
107
+ >>> # Initializing a model from the configuration
108
+ >>> model = Phi3Model(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "phi3"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32064,
120
+ hidden_size=3072,
121
+ intermediate_size=8192,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ resid_pdrop=0.0,
126
+ embd_pdrop=0.0,
127
+ attention_dropout=0.0,
128
+ hidden_act="silu",
129
+ max_position_embeddings=4096,
130
+ original_max_position_embeddings=4096,
131
+ initializer_range=0.02,
132
+ rms_norm_eps=1e-5,
133
+ use_cache=True,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ bos_token_id=1,
138
+ eos_token_id=32000,
139
+ pad_token_id=32000,
140
+ sliding_window=None,
141
+ **kwargs,
142
+ ):
143
+ self.vocab_size = vocab_size
144
+ self.hidden_size = hidden_size
145
+ self.intermediate_size = intermediate_size
146
+ self.num_hidden_layers = num_hidden_layers
147
+ self.num_attention_heads = num_attention_heads
148
+
149
+ if num_key_value_heads is None:
150
+ num_key_value_heads = num_attention_heads
151
+
152
+ self.num_key_value_heads = num_key_value_heads
153
+ self.resid_pdrop = resid_pdrop
154
+ self.embd_pdrop = embd_pdrop
155
+ self.attention_dropout = attention_dropout
156
+ self.hidden_act = hidden_act
157
+ self.max_position_embeddings = max_position_embeddings
158
+ self.original_max_position_embeddings = original_max_position_embeddings
159
+ self.initializer_range = initializer_range
160
+ self.rms_norm_eps = rms_norm_eps
161
+ self.use_cache = use_cache
162
+ self.rope_theta = rope_theta
163
+ self.rope_scaling = rope_scaling
164
+ self._rope_scaling_validation()
165
+ self.sliding_window = sliding_window
166
+
167
+ super().__init__(
168
+ bos_token_id=bos_token_id,
169
+ eos_token_id=eos_token_id,
170
+ pad_token_id=pad_token_id,
171
+ tie_word_embeddings=tie_word_embeddings,
172
+ **kwargs,
173
+ )
174
+
175
+ def _rope_scaling_validation(self):
176
+ """
177
+ Validate the `rope_scaling` configuration.
178
+ """
179
+ if self.rope_scaling is None:
180
+ return
181
+
182
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
183
+ raise ValueError(
184
+ "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
185
+ f"got {self.rope_scaling}"
186
+ )
187
+ rope_scaling_type = self.rope_scaling.get("type", None)
188
+ rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
189
+ rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
190
+ if rope_scaling_type is None or rope_scaling_type not in ["su", "yarn"]:
191
+ raise ValueError(f"`rope_scaling`'s type field must be one of ['su', 'yarn'], got {rope_scaling_type}")
192
+ if not (
193
+ isinstance(rope_scaling_short_factor, list)
194
+ and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
195
+ ):
196
+ raise ValueError(
197
+ f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
198
+ )
199
+ if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
200
+ raise ValueError(
201
+ f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
202
+ )
203
+ if not (
204
+ isinstance(rope_scaling_long_factor, list)
205
+ and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
206
+ ):
207
+ raise ValueError(
208
+ f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
209
+ )
210
+ if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
211
+ raise ValueError(
212
+ f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
213
+ )
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 32000,
6
+ 32001,
7
+ 32007
8
+ ],
9
+ "pad_token_id": 32000,
10
+ "transformers_version": "4.52.4"
11
+ }
latest ADDED
@@ -0,0 +1 @@
 
 
1
+ global_step2996
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:942344d8b3f73f82842cb76b7adc55649b3ac83edf25aa326d2769a541f05ab4
3
+ size 4915982920
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebd532cb8cc851af6a32373b6c4dc5304f909f738fcc90da43d510b9df990f35
3
+ size 4954690720
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:18fe071183549f37d0efca4e39244a3e9e338086d9b47137e9c45b60f26018ac
3
+ size 4902241352
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:434d068c36c331f118756ba75d67a286da89c9e75febca3c778548b54f10e8a7
3
+ size 4771169120
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:613781e50192d7f185b42efacb456eca8ad00ac40857d42dc78f5516f5696750
3
+ size 4771169120
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b422df5d8ed4b32ccf08cbd7c1334b23f9bd5804272bef85fa2aa6097fb74222
3
+ size 3605251496
model.safetensors.index.json ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 27920476160
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00006-of-00006.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00006.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00006.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
10
+ "model.layers.0.mlp.gate_up_proj.weight": "model-00001-of-00006.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
13
+ "model.layers.0.self_attn.qkv_proj.weight": "model-00001-of-00006.safetensors",
14
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00006.safetensors",
15
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
16
+ "model.layers.1.mlp.gate_up_proj.weight": "model-00001-of-00006.safetensors",
17
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
18
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
19
+ "model.layers.1.self_attn.qkv_proj.weight": "model-00001-of-00006.safetensors",
20
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00006.safetensors",
21
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
22
+ "model.layers.10.mlp.gate_up_proj.weight": "model-00002-of-00006.safetensors",
23
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
24
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
25
+ "model.layers.10.self_attn.qkv_proj.weight": "model-00002-of-00006.safetensors",
26
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00006.safetensors",
27
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
28
+ "model.layers.11.mlp.gate_up_proj.weight": "model-00002-of-00006.safetensors",
29
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
30
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
31
+ "model.layers.11.self_attn.qkv_proj.weight": "model-00002-of-00006.safetensors",
32
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00006.safetensors",
33
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
34
+ "model.layers.12.mlp.gate_up_proj.weight": "model-00002-of-00006.safetensors",
35
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
36
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
37
+ "model.layers.12.self_attn.qkv_proj.weight": "model-00002-of-00006.safetensors",
38
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00006.safetensors",
39
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
40
+ "model.layers.13.mlp.gate_up_proj.weight": "model-00002-of-00006.safetensors",
41
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
42
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
43
+ "model.layers.13.self_attn.qkv_proj.weight": "model-00002-of-00006.safetensors",
44
+ "model.layers.14.input_layernorm.weight": "model-00003-of-00006.safetensors",
45
+ "model.layers.14.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
46
+ "model.layers.14.mlp.gate_up_proj.weight": "model-00003-of-00006.safetensors",
47
+ "model.layers.14.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
48
+ "model.layers.14.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
49
+ "model.layers.14.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
50
+ "model.layers.15.input_layernorm.weight": "model-00003-of-00006.safetensors",
51
+ "model.layers.15.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
52
+ "model.layers.15.mlp.gate_up_proj.weight": "model-00003-of-00006.safetensors",
53
+ "model.layers.15.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
54
+ "model.layers.15.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
55
+ "model.layers.15.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
56
+ "model.layers.16.input_layernorm.weight": "model-00003-of-00006.safetensors",
57
+ "model.layers.16.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
58
+ "model.layers.16.mlp.gate_up_proj.weight": "model-00003-of-00006.safetensors",
59
+ "model.layers.16.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
60
+ "model.layers.16.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
61
+ "model.layers.16.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
62
+ "model.layers.17.input_layernorm.weight": "model-00003-of-00006.safetensors",
63
+ "model.layers.17.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
64
+ "model.layers.17.mlp.gate_up_proj.weight": "model-00003-of-00006.safetensors",
65
+ "model.layers.17.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
66
+ "model.layers.17.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
67
+ "model.layers.17.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
68
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00006.safetensors",
69
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
70
+ "model.layers.18.mlp.gate_up_proj.weight": "model-00003-of-00006.safetensors",
71
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
72
+ "model.layers.18.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
73
+ "model.layers.18.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
74
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00006.safetensors",
75
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
76
+ "model.layers.19.mlp.gate_up_proj.weight": "model-00003-of-00006.safetensors",
77
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
78
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
79
+ "model.layers.19.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
80
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00006.safetensors",
81
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
82
+ "model.layers.2.mlp.gate_up_proj.weight": "model-00001-of-00006.safetensors",
83
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
84
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
85
+ "model.layers.2.self_attn.qkv_proj.weight": "model-00001-of-00006.safetensors",
86
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00006.safetensors",
87
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00006.safetensors",
88
+ "model.layers.20.mlp.gate_up_proj.weight": "model-00003-of-00006.safetensors",
89
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00006.safetensors",
90
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
91
+ "model.layers.20.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
92
+ "model.layers.21.input_layernorm.weight": "model-00004-of-00006.safetensors",
93
+ "model.layers.21.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
94
+ "model.layers.21.mlp.gate_up_proj.weight": "model-00004-of-00006.safetensors",
95
+ "model.layers.21.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
96
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00006.safetensors",
97
+ "model.layers.21.self_attn.qkv_proj.weight": "model-00003-of-00006.safetensors",
98
+ "model.layers.22.input_layernorm.weight": "model-00004-of-00006.safetensors",
99
+ "model.layers.22.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
100
+ "model.layers.22.mlp.gate_up_proj.weight": "model-00004-of-00006.safetensors",
101
+ "model.layers.22.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
102
+ "model.layers.22.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
103
+ "model.layers.22.self_attn.qkv_proj.weight": "model-00004-of-00006.safetensors",
104
+ "model.layers.23.input_layernorm.weight": "model-00004-of-00006.safetensors",
105
+ "model.layers.23.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
106
+ "model.layers.23.mlp.gate_up_proj.weight": "model-00004-of-00006.safetensors",
107
+ "model.layers.23.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
108
+ "model.layers.23.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
109
+ "model.layers.23.self_attn.qkv_proj.weight": "model-00004-of-00006.safetensors",
110
+ "model.layers.24.input_layernorm.weight": "model-00004-of-00006.safetensors",
111
+ "model.layers.24.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
112
+ "model.layers.24.mlp.gate_up_proj.weight": "model-00004-of-00006.safetensors",
113
+ "model.layers.24.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
114
+ "model.layers.24.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
115
+ "model.layers.24.self_attn.qkv_proj.weight": "model-00004-of-00006.safetensors",
116
+ "model.layers.25.input_layernorm.weight": "model-00004-of-00006.safetensors",
117
+ "model.layers.25.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
118
+ "model.layers.25.mlp.gate_up_proj.weight": "model-00004-of-00006.safetensors",
119
+ "model.layers.25.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
120
+ "model.layers.25.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
121
+ "model.layers.25.self_attn.qkv_proj.weight": "model-00004-of-00006.safetensors",
122
+ "model.layers.26.input_layernorm.weight": "model-00004-of-00006.safetensors",
123
+ "model.layers.26.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
124
+ "model.layers.26.mlp.gate_up_proj.weight": "model-00004-of-00006.safetensors",
125
+ "model.layers.26.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
126
+ "model.layers.26.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
127
+ "model.layers.26.self_attn.qkv_proj.weight": "model-00004-of-00006.safetensors",
128
+ "model.layers.27.input_layernorm.weight": "model-00004-of-00006.safetensors",
129
+ "model.layers.27.mlp.down_proj.weight": "model-00004-of-00006.safetensors",
130
+ "model.layers.27.mlp.gate_up_proj.weight": "model-00004-of-00006.safetensors",
131
+ "model.layers.27.post_attention_layernorm.weight": "model-00004-of-00006.safetensors",
132
+ "model.layers.27.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
133
+ "model.layers.27.self_attn.qkv_proj.weight": "model-00004-of-00006.safetensors",
134
+ "model.layers.28.input_layernorm.weight": "model-00005-of-00006.safetensors",
135
+ "model.layers.28.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
136
+ "model.layers.28.mlp.gate_up_proj.weight": "model-00005-of-00006.safetensors",
137
+ "model.layers.28.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
138
+ "model.layers.28.self_attn.o_proj.weight": "model-00004-of-00006.safetensors",
139
+ "model.layers.28.self_attn.qkv_proj.weight": "model-00004-of-00006.safetensors",
140
+ "model.layers.29.input_layernorm.weight": "model-00005-of-00006.safetensors",
141
+ "model.layers.29.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
142
+ "model.layers.29.mlp.gate_up_proj.weight": "model-00005-of-00006.safetensors",
143
+ "model.layers.29.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
144
+ "model.layers.29.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
145
+ "model.layers.29.self_attn.qkv_proj.weight": "model-00005-of-00006.safetensors",
146
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00006.safetensors",
147
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
148
+ "model.layers.3.mlp.gate_up_proj.weight": "model-00001-of-00006.safetensors",
149
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
150
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
151
+ "model.layers.3.self_attn.qkv_proj.weight": "model-00001-of-00006.safetensors",
152
+ "model.layers.30.input_layernorm.weight": "model-00005-of-00006.safetensors",
153
+ "model.layers.30.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
154
+ "model.layers.30.mlp.gate_up_proj.weight": "model-00005-of-00006.safetensors",
155
+ "model.layers.30.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
156
+ "model.layers.30.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
157
+ "model.layers.30.self_attn.qkv_proj.weight": "model-00005-of-00006.safetensors",
158
+ "model.layers.31.input_layernorm.weight": "model-00005-of-00006.safetensors",
159
+ "model.layers.31.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
160
+ "model.layers.31.mlp.gate_up_proj.weight": "model-00005-of-00006.safetensors",
161
+ "model.layers.31.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
162
+ "model.layers.31.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
163
+ "model.layers.31.self_attn.qkv_proj.weight": "model-00005-of-00006.safetensors",
164
+ "model.layers.32.input_layernorm.weight": "model-00005-of-00006.safetensors",
165
+ "model.layers.32.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
166
+ "model.layers.32.mlp.gate_up_proj.weight": "model-00005-of-00006.safetensors",
167
+ "model.layers.32.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
168
+ "model.layers.32.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
169
+ "model.layers.32.self_attn.qkv_proj.weight": "model-00005-of-00006.safetensors",
170
+ "model.layers.33.input_layernorm.weight": "model-00005-of-00006.safetensors",
171
+ "model.layers.33.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
172
+ "model.layers.33.mlp.gate_up_proj.weight": "model-00005-of-00006.safetensors",
173
+ "model.layers.33.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
174
+ "model.layers.33.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
175
+ "model.layers.33.self_attn.qkv_proj.weight": "model-00005-of-00006.safetensors",
176
+ "model.layers.34.input_layernorm.weight": "model-00005-of-00006.safetensors",
177
+ "model.layers.34.mlp.down_proj.weight": "model-00005-of-00006.safetensors",
178
+ "model.layers.34.mlp.gate_up_proj.weight": "model-00005-of-00006.safetensors",
179
+ "model.layers.34.post_attention_layernorm.weight": "model-00005-of-00006.safetensors",
180
+ "model.layers.34.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
181
+ "model.layers.34.self_attn.qkv_proj.weight": "model-00005-of-00006.safetensors",
182
+ "model.layers.35.input_layernorm.weight": "model-00006-of-00006.safetensors",
183
+ "model.layers.35.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
184
+ "model.layers.35.mlp.gate_up_proj.weight": "model-00006-of-00006.safetensors",
185
+ "model.layers.35.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
186
+ "model.layers.35.self_attn.o_proj.weight": "model-00005-of-00006.safetensors",
187
+ "model.layers.35.self_attn.qkv_proj.weight": "model-00005-of-00006.safetensors",
188
+ "model.layers.36.input_layernorm.weight": "model-00006-of-00006.safetensors",
189
+ "model.layers.36.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
190
+ "model.layers.36.mlp.gate_up_proj.weight": "model-00006-of-00006.safetensors",
191
+ "model.layers.36.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
192
+ "model.layers.36.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
193
+ "model.layers.36.self_attn.qkv_proj.weight": "model-00006-of-00006.safetensors",
194
+ "model.layers.37.input_layernorm.weight": "model-00006-of-00006.safetensors",
195
+ "model.layers.37.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
196
+ "model.layers.37.mlp.gate_up_proj.weight": "model-00006-of-00006.safetensors",
197
+ "model.layers.37.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
198
+ "model.layers.37.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
199
+ "model.layers.37.self_attn.qkv_proj.weight": "model-00006-of-00006.safetensors",
200
+ "model.layers.38.input_layernorm.weight": "model-00006-of-00006.safetensors",
201
+ "model.layers.38.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
202
+ "model.layers.38.mlp.gate_up_proj.weight": "model-00006-of-00006.safetensors",
203
+ "model.layers.38.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
204
+ "model.layers.38.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
205
+ "model.layers.38.self_attn.qkv_proj.weight": "model-00006-of-00006.safetensors",
206
+ "model.layers.39.input_layernorm.weight": "model-00006-of-00006.safetensors",
207
+ "model.layers.39.mlp.down_proj.weight": "model-00006-of-00006.safetensors",
208
+ "model.layers.39.mlp.gate_up_proj.weight": "model-00006-of-00006.safetensors",
209
+ "model.layers.39.post_attention_layernorm.weight": "model-00006-of-00006.safetensors",
210
+ "model.layers.39.self_attn.o_proj.weight": "model-00006-of-00006.safetensors",
211
+ "model.layers.39.self_attn.qkv_proj.weight": "model-00006-of-00006.safetensors",
212
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00006.safetensors",
213
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
214
+ "model.layers.4.mlp.gate_up_proj.weight": "model-00001-of-00006.safetensors",
215
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
216
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
217
+ "model.layers.4.self_attn.qkv_proj.weight": "model-00001-of-00006.safetensors",
218
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00006.safetensors",
219
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00006.safetensors",
220
+ "model.layers.5.mlp.gate_up_proj.weight": "model-00001-of-00006.safetensors",
221
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00006.safetensors",
222
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
223
+ "model.layers.5.self_attn.qkv_proj.weight": "model-00001-of-00006.safetensors",
224
+ "model.layers.6.input_layernorm.weight": "model-00002-of-00006.safetensors",
225
+ "model.layers.6.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
226
+ "model.layers.6.mlp.gate_up_proj.weight": "model-00001-of-00006.safetensors",
227
+ "model.layers.6.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
228
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00006.safetensors",
229
+ "model.layers.6.self_attn.qkv_proj.weight": "model-00001-of-00006.safetensors",
230
+ "model.layers.7.input_layernorm.weight": "model-00002-of-00006.safetensors",
231
+ "model.layers.7.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
232
+ "model.layers.7.mlp.gate_up_proj.weight": "model-00002-of-00006.safetensors",
233
+ "model.layers.7.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
234
+ "model.layers.7.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
235
+ "model.layers.7.self_attn.qkv_proj.weight": "model-00002-of-00006.safetensors",
236
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00006.safetensors",
237
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
238
+ "model.layers.8.mlp.gate_up_proj.weight": "model-00002-of-00006.safetensors",
239
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
240
+ "model.layers.8.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
241
+ "model.layers.8.self_attn.qkv_proj.weight": "model-00002-of-00006.safetensors",
242
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00006.safetensors",
243
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00006.safetensors",
244
+ "model.layers.9.mlp.gate_up_proj.weight": "model-00002-of-00006.safetensors",
245
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00006.safetensors",
246
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00006.safetensors",
247
+ "model.layers.9.self_attn.qkv_proj.weight": "model-00002-of-00006.safetensors",
248
+ "model.norm.weight": "model-00006-of-00006.safetensors"
249
+ }
250
+ }
modeling_phi3.py ADDED
@@ -0,0 +1,1606 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ """ PyTorch Phi-3 model."""
17
+
18
+ import inspect
19
+ import math
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.cache_utils import Cache, DynamicCache
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_phi3 import Phi3Config
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ # Transformers scans dependencies in the modeling file, causing issues on conditional loading. The regex only ignores try/catch blocks, but not if statements
54
+ # if is_flash_attn_2_available():
55
+ _flash_supports_window_size = False
56
+ try:
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+ except ImportError as error:
62
+ logger.warning(
63
+ f"`flash-attention` package not found, consider installing for better performance: {error}."
64
+ )
65
+ if not _flash_supports_window_size:
66
+ logger.warning(
67
+ "Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`."
68
+ )
69
+
70
+ _CHECKPOINT_FOR_DOC = "microsoft/Phi-3-mini-4k-instruct"
71
+ _CONFIG_FOR_DOC = "Phi3Config"
72
+
73
+ PHI3_PRETRAINED_MODEL_ARCHIVE_LIST = [
74
+ "microsoft/Phi-3-mini-4k-instruct",
75
+ "microsoft/Phi-3-mini-128k-instruct",
76
+ # See all Phi-3 models at https://huggingface.co/models?filter=Phi-3
77
+ ]
78
+
79
+
80
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Phi3
81
+ class Phi3RMSNorm(nn.Module):
82
+ def __init__(self, hidden_size, eps=1e-6):
83
+ """
84
+ Phi3RMSNorm is equivalent to T5LayerNorm
85
+ """
86
+ super().__init__()
87
+ self.weight = nn.Parameter(torch.ones(hidden_size))
88
+ self.variance_epsilon = eps
89
+
90
+ def forward(self, hidden_states):
91
+ input_dtype = hidden_states.dtype
92
+ hidden_states = hidden_states.to(torch.float32)
93
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
94
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
95
+ return self.weight * hidden_states.to(input_dtype)
96
+
97
+
98
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
99
+ def _get_unpad_data(attention_mask):
100
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
101
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
102
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
103
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
104
+ return (
105
+ indices,
106
+ cu_seqlens,
107
+ max_seqlen_in_batch,
108
+ )
109
+
110
+
111
+ # Copied from transformers.models.gemma.modeling_gemma.GemmaRotaryEmbedding with gemma->phi3, Gemma->Phi3
112
+ class Phi3RotaryEmbedding(nn.Module):
113
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
114
+ super().__init__()
115
+
116
+ self.dim = dim
117
+ self.max_position_embeddings = max_position_embeddings
118
+ self.base = base
119
+ self.register_buffer("inv_freq", None, persistent=False)
120
+
121
+ @torch.no_grad()
122
+ def forward(self, x, position_ids, seq_len=None):
123
+ # x: [bs, num_attention_heads, seq_len, head_size]
124
+ if self.inv_freq is None:
125
+ self.inv_freq = 1.0 / (
126
+ self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim)
127
+ )
128
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
129
+ position_ids_expanded = position_ids[:, None, :].float()
130
+ # Force float32 since bfloat16 loses precision on long contexts
131
+ # See https://github.com/huggingface/transformers/pull/29285
132
+ device_type = x.device.type
133
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
134
+ with torch.autocast(device_type=device_type, enabled=False):
135
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
136
+ emb = torch.cat((freqs, freqs), dim=-1)
137
+ cos = emb.cos()
138
+ sin = emb.sin()
139
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
140
+
141
+
142
+ class Phi3SuScaledRotaryEmbedding(Phi3RotaryEmbedding):
143
+ def __init__(self, dim, config, device=None):
144
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
145
+
146
+ self.short_factor = config.rope_scaling["short_factor"]
147
+ self.long_factor = config.rope_scaling["long_factor"]
148
+ self.original_max_position_embeddings = config.original_max_position_embeddings
149
+
150
+ @torch.no_grad()
151
+ def forward(self, x, position_ids, seq_len=None):
152
+ seq_len = torch.max(position_ids) + 1
153
+ if seq_len > self.original_max_position_embeddings:
154
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
155
+ else:
156
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
157
+
158
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
159
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
160
+
161
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
162
+ position_ids_expanded = position_ids[:, None, :].float()
163
+
164
+ # Force float32 since bfloat16 loses precision on long contexts
165
+ # See https://github.com/huggingface/transformers/pull/29285
166
+ device_type = x.device.type
167
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
168
+ with torch.autocast(device_type=device_type, enabled=False):
169
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
170
+ emb = torch.cat((freqs, freqs), dim=-1)
171
+
172
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
173
+ if scale <= 1.0:
174
+ scaling_factor = 1.0
175
+ else:
176
+ scaling_factor = math.sqrt(1 + math.log(scale) / math.log(self.original_max_position_embeddings))
177
+
178
+ cos = emb.cos() * scaling_factor
179
+ sin = emb.sin() * scaling_factor
180
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
181
+
182
+
183
+ class Phi3YarnScaledRotaryEmbedding(Phi3RotaryEmbedding):
184
+ def __init__(self, dim, config, device=None):
185
+ super().__init__(dim, config.max_position_embeddings, config.rope_theta, device)
186
+
187
+ self.short_factor = config.rope_scaling["short_factor"]
188
+ self.long_factor = config.rope_scaling["long_factor"]
189
+ self.original_max_position_embeddings = config.original_max_position_embeddings
190
+
191
+ @torch.no_grad()
192
+ def forward(self, x, position_ids, seq_len=None):
193
+ seq_len = torch.max(position_ids) + 1
194
+ if seq_len > self.original_max_position_embeddings:
195
+ ext_factors = torch.tensor(self.long_factor, dtype=torch.float32, device=x.device)
196
+ else:
197
+ ext_factors = torch.tensor(self.short_factor, dtype=torch.float32, device=x.device)
198
+
199
+ inv_freq_shape = torch.arange(0, self.dim, 2, dtype=torch.int64, device=x.device).float() / self.dim
200
+ self.inv_freq = 1.0 / (ext_factors * self.base**inv_freq_shape)
201
+
202
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
203
+ position_ids_expanded = position_ids[:, None, :].float()
204
+
205
+ # Force float32 since bfloat16 loses precision on long contexts
206
+ # See https://github.com/huggingface/transformers/pull/29285
207
+ device_type = x.device.type
208
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
209
+ with torch.autocast(device_type=device_type, enabled=False):
210
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
211
+ emb = torch.cat((freqs, freqs), dim=-1)
212
+
213
+ scale = self.max_position_embeddings / self.original_max_position_embeddings
214
+ if scale <= 1.0:
215
+ scaling_factor = 1.0
216
+ else:
217
+ scaling_factor = 0.1 * math.log(scale) + 1.0
218
+
219
+ cos = emb.cos() * scaling_factor
220
+ sin = emb.sin() * scaling_factor
221
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
222
+
223
+
224
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
225
+ def rotate_half(x):
226
+ """Rotates half the hidden dims of the input."""
227
+ x1 = x[..., : x.shape[-1] // 2]
228
+ x2 = x[..., x.shape[-1] // 2 :]
229
+ return torch.cat((-x2, x1), dim=-1)
230
+
231
+
232
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
233
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
234
+ """Applies Rotary Position Embedding to the query and key tensors.
235
+
236
+ Args:
237
+ q (`torch.Tensor`): The query tensor.
238
+ k (`torch.Tensor`): The key tensor.
239
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
240
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
241
+ position_ids (`torch.Tensor`, *optional*):
242
+ Deprecated and unused.
243
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
244
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
245
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
246
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
247
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
248
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
249
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
250
+ Returns:
251
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
252
+ """
253
+ cos = cos.unsqueeze(unsqueeze_dim)
254
+ sin = sin.unsqueeze(unsqueeze_dim)
255
+ q_embed = (q * cos) + (rotate_half(q) * sin)
256
+ k_embed = (k * cos) + (rotate_half(k) * sin)
257
+ return q_embed, k_embed
258
+
259
+
260
+ class Phi3MLP(nn.Module):
261
+ def __init__(self, config):
262
+ super().__init__()
263
+
264
+ self.config = config
265
+ self.gate_up_proj = nn.Linear(config.hidden_size, 2 * config.intermediate_size, bias=False)
266
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
267
+
268
+ self.activation_fn = ACT2FN[config.hidden_act]
269
+
270
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
271
+ up_states = self.gate_up_proj(hidden_states)
272
+
273
+ gate, up_states = up_states.chunk(2, dim=-1)
274
+ up_states = up_states * self.activation_fn(gate)
275
+
276
+ return self.down_proj(up_states)
277
+
278
+
279
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv with llama->phi
280
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
281
+ """
282
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
283
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
284
+ """
285
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
286
+ if n_rep == 1:
287
+ return hidden_states
288
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
289
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
290
+
291
+
292
+ class Phi3Attention(nn.Module):
293
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
294
+
295
+ def __init__(self, config: Phi3Config, layer_idx: Optional[int] = None):
296
+ super().__init__()
297
+ self.config = config
298
+ self.layer_idx = layer_idx
299
+ if layer_idx is None:
300
+ logger.warning_once(
301
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
302
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
303
+ "when creating this class."
304
+ )
305
+
306
+ self.attention_dropout = config.attention_dropout
307
+ self.hidden_size = config.hidden_size
308
+ self.num_heads = config.num_attention_heads
309
+ self.head_dim = self.hidden_size // self.num_heads
310
+ self.num_key_value_heads = config.num_key_value_heads
311
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
312
+ self.max_position_embeddings = config.max_position_embeddings
313
+ self.original_max_position_embeddings = config.original_max_position_embeddings
314
+ self.rope_theta = config.rope_theta
315
+ self.rope_scaling = config.rope_scaling
316
+ self.is_causal = True
317
+
318
+ if (self.head_dim * self.num_heads) != self.hidden_size:
319
+ raise ValueError(
320
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
321
+ f" and `num_heads`: {self.num_heads})."
322
+ )
323
+
324
+ op_size = self.num_heads * self.head_dim + 2 * (self.num_key_value_heads * self.head_dim)
325
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
326
+ self.qkv_proj = nn.Linear(self.hidden_size, op_size, bias=False)
327
+ self._init_rope()
328
+
329
+ def _init_rope(self):
330
+ if self.rope_scaling is None:
331
+ self.rotary_emb = Phi3RotaryEmbedding(
332
+ self.head_dim,
333
+ max_position_embeddings=self.max_position_embeddings,
334
+ base=self.rope_theta,
335
+ )
336
+ else:
337
+ scaling_type = self.config.rope_scaling["type"]
338
+ if scaling_type == "su":
339
+ self.rotary_emb = Phi3SuScaledRotaryEmbedding(self.head_dim, self.config)
340
+ elif scaling_type == "yarn":
341
+ self.rotary_emb = Phi3YarnScaledRotaryEmbedding(self.head_dim, self.config)
342
+ else:
343
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
344
+
345
+ def forward(
346
+ self,
347
+ hidden_states: torch.Tensor,
348
+ attention_mask: Optional[torch.Tensor] = None,
349
+ position_ids: Optional[torch.LongTensor] = None,
350
+ past_key_value: Optional[Cache] = None,
351
+ output_attentions: bool = False,
352
+ use_cache: bool = False,
353
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
354
+ logger.warning_once("You are not running the flash-attention implementation, expect numerical differences.")
355
+
356
+ bsz, q_len, _ = hidden_states.size()
357
+
358
+ qkv = self.qkv_proj(hidden_states)
359
+ query_pos = self.num_heads * self.head_dim
360
+ query_states = qkv[..., :query_pos]
361
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
362
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
363
+
364
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
365
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
366
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
367
+
368
+ kv_seq_len = key_states.shape[-2]
369
+ if past_key_value is not None:
370
+ if self.layer_idx is None:
371
+ raise ValueError(
372
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
373
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
374
+ "with a layer index."
375
+ )
376
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
377
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
378
+
379
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
380
+
381
+ if past_key_value is not None:
382
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
383
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
384
+
385
+ # repeat k/v heads if n_kv_heads < n_heads
386
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
387
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
388
+
389
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
390
+
391
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
392
+ raise ValueError(
393
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
394
+ f" {attn_weights.size()}"
395
+ )
396
+
397
+ if attention_mask is not None:
398
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
399
+ raise ValueError(
400
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
401
+ )
402
+ attn_weights = attn_weights + attention_mask
403
+
404
+ # upcast attention to fp32
405
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(value_states.dtype)
406
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
407
+
408
+ attn_output = torch.matmul(attn_weights, value_states)
409
+
410
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
411
+ raise ValueError(
412
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
413
+ f" {attn_output.size()}"
414
+ )
415
+
416
+ attn_output = attn_output.transpose(1, 2).contiguous()
417
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
418
+
419
+ attn_output = self.o_proj(attn_output)
420
+
421
+ if not output_attentions:
422
+ attn_weights = None
423
+
424
+ return attn_output, attn_weights, past_key_value
425
+
426
+
427
+ class Phi3FlashAttention2(Phi3Attention):
428
+ """
429
+ Phi-3 flash attention module. This module inherits from `Phi3Attention` as the weights of the module stays
430
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
431
+ flash attention and deal with padding tokens in case the input contains any of them.
432
+ """
433
+
434
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
435
+ def __init__(self, *args, **kwargs):
436
+ super().__init__(*args, **kwargs)
437
+
438
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
439
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
440
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
441
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
442
+
443
+ def forward(
444
+ self,
445
+ hidden_states: torch.Tensor,
446
+ attention_mask: Optional[torch.LongTensor] = None,
447
+ position_ids: Optional[torch.LongTensor] = None,
448
+ past_key_value: Optional[Cache] = None,
449
+ output_attentions: bool = False,
450
+ use_cache: bool = False,
451
+ **kwargs,
452
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
453
+ # Phi3FlashAttention2 attention does not support output_attentions
454
+
455
+ if not _flash_supports_window_size:
456
+ logger.warning_once(
457
+ "The current flash attention version does not support sliding window attention. Please use `attn_implementation='eager'` or upgrade flash-attn library."
458
+ )
459
+ raise ValueError("The current flash attention version does not support sliding window attention.")
460
+
461
+ output_attentions = False
462
+
463
+ if "padding_mask" in kwargs:
464
+ warnings.warn(
465
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
466
+ )
467
+
468
+ # overwrite attention_mask with padding_mask
469
+ attention_mask = kwargs.pop("padding_mask")
470
+
471
+ bsz, q_len, _ = hidden_states.size()
472
+
473
+ qkv = self.qkv_proj(hidden_states)
474
+ query_pos = self.num_heads * self.head_dim
475
+ query_states = qkv[..., :query_pos]
476
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
477
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
478
+
479
+ # Flash attention requires the input to have the shape
480
+ # batch_size x seq_length x head_dim x hidden_dim
481
+ # therefore we just need to keep the original shape
482
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
483
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
484
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
485
+
486
+ kv_seq_len = key_states.shape[-2]
487
+ if past_key_value is not None:
488
+ if self.layer_idx is None:
489
+ raise ValueError(
490
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
491
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
492
+ "with a layer index."
493
+ )
494
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
495
+
496
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
497
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
498
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=rotary_seq_len)
499
+
500
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
501
+
502
+ use_sliding_windows = (
503
+ _flash_supports_window_size
504
+ and getattr(self.config, "sliding_window", None) is not None
505
+ and kv_seq_len > self.config.sliding_window
506
+ )
507
+
508
+ if past_key_value is not None:
509
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
510
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
511
+ if (
512
+ getattr(self.config, "sliding_window", None) is not None
513
+ and kv_seq_len > self.config.sliding_window
514
+ and cache_has_contents
515
+ ):
516
+ slicing_tokens = 1 - self.config.sliding_window
517
+
518
+ past_key = past_key_value[self.layer_idx][0]
519
+ past_value = past_key_value[self.layer_idx][1]
520
+
521
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
522
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
523
+
524
+ if past_key.shape[-2] != self.config.sliding_window - 1:
525
+ raise ValueError(
526
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
527
+ f" {past_key.shape}"
528
+ )
529
+
530
+ if attention_mask is not None:
531
+ attention_mask = attention_mask[:, slicing_tokens:]
532
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
533
+
534
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
535
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
536
+
537
+ # repeat k/v heads if n_kv_heads < n_heads
538
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
539
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
540
+
541
+ attn_dropout = self.attention_dropout if self.training else 0.0
542
+
543
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
544
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
545
+ # cast them back in the correct dtype just to be sure everything works as expected.
546
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
547
+ # in fp32.
548
+
549
+ if query_states.dtype == torch.float32:
550
+ if torch.is_autocast_enabled():
551
+ target_dtype = torch.get_autocast_gpu_dtype()
552
+ # Handle the case where the model is quantized
553
+ elif hasattr(self.config, "_pre_quantization_dtype"):
554
+ target_dtype = self.config._pre_quantization_dtype
555
+ else:
556
+ target_dtype = self.qkv_proj.weight.dtype
557
+
558
+ logger.warning_once(
559
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
560
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
561
+ f" {target_dtype}."
562
+ )
563
+
564
+ query_states = query_states.to(target_dtype)
565
+ key_states = key_states.to(target_dtype)
566
+ value_states = value_states.to(target_dtype)
567
+
568
+ # Reashape to the expected shape for Flash Attention
569
+ query_states = query_states.transpose(1, 2)
570
+ key_states = key_states.transpose(1, 2)
571
+ value_states = value_states.transpose(1, 2)
572
+
573
+ attn_output = self._flash_attention_forward(
574
+ query_states,
575
+ key_states,
576
+ value_states,
577
+ attention_mask,
578
+ q_len,
579
+ dropout=attn_dropout,
580
+ use_sliding_windows=use_sliding_windows,
581
+ )
582
+
583
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
584
+ attn_output = self.o_proj(attn_output)
585
+
586
+ if not output_attentions:
587
+ attn_weights = None
588
+
589
+ return attn_output, attn_weights, past_key_value
590
+
591
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._flash_attention_forward
592
+ def _flash_attention_forward(
593
+ self,
594
+ query_states,
595
+ key_states,
596
+ value_states,
597
+ attention_mask,
598
+ query_length,
599
+ dropout=0.0,
600
+ softmax_scale=None,
601
+ use_sliding_windows=False,
602
+ ):
603
+ """
604
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
605
+ first unpad the input, then computes the attention scores and pad the final attention scores.
606
+
607
+ Args:
608
+ query_states (`torch.Tensor`):
609
+ Input query states to be passed to Flash Attention API
610
+ key_states (`torch.Tensor`):
611
+ Input key states to be passed to Flash Attention API
612
+ value_states (`torch.Tensor`):
613
+ Input value states to be passed to Flash Attention API
614
+ attention_mask (`torch.Tensor`):
615
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
616
+ position of padding tokens and 1 for the position of non-padding tokens.
617
+ dropout (`float`):
618
+ Attention dropout
619
+ softmax_scale (`float`, *optional*):
620
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
621
+ use_sliding_windows (`bool`, *optional*):
622
+ Whether to activate sliding window attention.
623
+ """
624
+ if not self._flash_attn_uses_top_left_mask:
625
+ causal = self.is_causal
626
+ else:
627
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
628
+ causal = self.is_causal and query_length != 1
629
+
630
+ # Contains at least one padding token in the sequence
631
+ if attention_mask is not None:
632
+ batch_size = query_states.shape[0]
633
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
634
+ query_states, key_states, value_states, attention_mask, query_length
635
+ )
636
+
637
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
638
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
639
+
640
+ if not use_sliding_windows:
641
+ attn_output_unpad = flash_attn_varlen_func(
642
+ query_states,
643
+ key_states,
644
+ value_states,
645
+ cu_seqlens_q=cu_seqlens_q,
646
+ cu_seqlens_k=cu_seqlens_k,
647
+ max_seqlen_q=max_seqlen_in_batch_q,
648
+ max_seqlen_k=max_seqlen_in_batch_k,
649
+ dropout_p=dropout,
650
+ softmax_scale=softmax_scale,
651
+ causal=causal,
652
+ )
653
+ else:
654
+ attn_output_unpad = flash_attn_varlen_func(
655
+ query_states,
656
+ key_states,
657
+ value_states,
658
+ cu_seqlens_q=cu_seqlens_q,
659
+ cu_seqlens_k=cu_seqlens_k,
660
+ max_seqlen_q=max_seqlen_in_batch_q,
661
+ max_seqlen_k=max_seqlen_in_batch_k,
662
+ dropout_p=dropout,
663
+ softmax_scale=softmax_scale,
664
+ causal=causal,
665
+ window_size=(self.config.sliding_window, self.config.sliding_window),
666
+ )
667
+
668
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
669
+ else:
670
+ if not use_sliding_windows:
671
+ attn_output = flash_attn_func(
672
+ query_states,
673
+ key_states,
674
+ value_states,
675
+ dropout,
676
+ softmax_scale=softmax_scale,
677
+ causal=causal,
678
+ )
679
+ else:
680
+ attn_output = flash_attn_func(
681
+ query_states,
682
+ key_states,
683
+ value_states,
684
+ dropout,
685
+ softmax_scale=softmax_scale,
686
+ causal=causal,
687
+ window_size=(self.config.sliding_window, self.config.sliding_window),
688
+ )
689
+
690
+ return attn_output
691
+
692
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2._upad_input
693
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
694
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
695
+
696
+ # On the first iteration we need to properly re-create the padding mask
697
+ # by slicing it on the proper place
698
+ if kv_seq_len != attention_mask.shape[-1]:
699
+ attention_mask_num_tokens = attention_mask.shape[-1]
700
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
701
+
702
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
703
+
704
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
705
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
706
+
707
+ if query_length == kv_seq_len:
708
+ query_layer = index_first_axis(
709
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
710
+ )
711
+ cu_seqlens_q = cu_seqlens_k
712
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
713
+ indices_q = indices_k
714
+ elif query_length == 1:
715
+ max_seqlen_in_batch_q = 1
716
+ cu_seqlens_q = torch.arange(
717
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
718
+ ) # There is a memcpy here, that is very bad.
719
+ indices_q = cu_seqlens_q[:-1]
720
+ query_layer = query_layer.squeeze(1)
721
+ else:
722
+ # The -q_len: slice assumes left padding.
723
+ attention_mask = attention_mask[:, -query_length:]
724
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
725
+
726
+ return (
727
+ query_layer,
728
+ key_layer,
729
+ value_layer,
730
+ indices_q,
731
+ (cu_seqlens_q, cu_seqlens_k),
732
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
733
+ )
734
+
735
+
736
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Phi3
737
+ # TODO @Arthur no longer copied from LLama after static cache
738
+ class Phi3SdpaAttention(Phi3Attention):
739
+ """
740
+ Phi3 attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
741
+ `Phi3Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
742
+ SDPA API.
743
+ """
744
+
745
+ # Adapted from Phi3Attention.forward
746
+ def forward(
747
+ self,
748
+ hidden_states: torch.Tensor,
749
+ attention_mask: Optional[torch.Tensor] = None,
750
+ position_ids: Optional[torch.LongTensor] = None,
751
+ past_key_value: Optional[Cache] = None,
752
+ output_attentions: bool = False,
753
+ use_cache: bool = False,
754
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
755
+ if output_attentions:
756
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
757
+ logger.warning_once(
758
+ "Phi3Model is using Phi3SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
759
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
760
+ )
761
+ return super().forward(
762
+ hidden_states=hidden_states,
763
+ attention_mask=attention_mask,
764
+ position_ids=position_ids,
765
+ past_key_value=past_key_value,
766
+ output_attentions=output_attentions,
767
+ use_cache=use_cache,
768
+ )
769
+
770
+ bsz, q_len, _ = hidden_states.size()
771
+
772
+ qkv = self.qkv_proj(hidden_states)
773
+ query_pos = self.num_heads * self.head_dim
774
+ query_states = qkv[..., :query_pos]
775
+ key_states = qkv[..., query_pos : query_pos + self.num_key_value_heads * self.head_dim]
776
+ value_states = qkv[..., query_pos + self.num_key_value_heads * self.head_dim :]
777
+
778
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
779
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
780
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
781
+
782
+ kv_seq_len = key_states.shape[-2]
783
+ if past_key_value is not None:
784
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
785
+ cos, sin = self.rotary_emb(value_states, position_ids, seq_len=kv_seq_len)
786
+
787
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
788
+
789
+ if past_key_value is not None:
790
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
791
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
792
+
793
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
794
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
795
+
796
+ if attention_mask is not None:
797
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
798
+ raise ValueError(
799
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
800
+ )
801
+
802
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
803
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
804
+ if query_states.device.type == "cuda" and attention_mask is not None:
805
+ query_states = query_states.contiguous()
806
+ key_states = key_states.contiguous()
807
+ value_states = value_states.contiguous()
808
+
809
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
810
+ query_states,
811
+ key_states,
812
+ value_states,
813
+ attn_mask=attention_mask,
814
+ dropout_p=self.attention_dropout if self.training else 0.0,
815
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
816
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
817
+ )
818
+
819
+ attn_output = attn_output.transpose(1, 2).contiguous()
820
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
821
+
822
+ attn_output = self.o_proj(attn_output)
823
+
824
+ return attn_output, None, past_key_value
825
+
826
+
827
+ PHI3_ATTENTION_CLASSES = {
828
+ "eager": Phi3Attention,
829
+ "flash_attention_2": Phi3FlashAttention2,
830
+ "sdpa": Phi3SdpaAttention,
831
+ }
832
+
833
+
834
+ class Phi3DecoderLayer(nn.Module):
835
+ def __init__(self, config: Phi3Config, layer_idx: int):
836
+ super().__init__()
837
+
838
+ self.config = config
839
+ self.self_attn = PHI3_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
840
+
841
+ self.mlp = Phi3MLP(config)
842
+ self.input_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
843
+
844
+ self.resid_attn_dropout = nn.Dropout(config.resid_pdrop)
845
+ self.resid_mlp_dropout = nn.Dropout(config.resid_pdrop)
846
+ self.post_attention_layernorm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
847
+
848
+ def forward(
849
+ self,
850
+ hidden_states: torch.Tensor,
851
+ attention_mask: Optional[torch.Tensor] = None,
852
+ position_ids: Optional[torch.LongTensor] = None,
853
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
854
+ output_attentions: Optional[bool] = False,
855
+ use_cache: Optional[bool] = False,
856
+ **kwargs,
857
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
858
+ if "padding_mask" in kwargs:
859
+ warnings.warn(
860
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
861
+ )
862
+ """
863
+ Args:
864
+ hidden_states (`torch.FloatTensor`):
865
+ input to the layer of shape `(batch, seq_len, embed_dim)`
866
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
867
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
868
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
869
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range
870
+ `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids)
871
+ output_attentions (`bool`, *optional*):
872
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
873
+ returned tensors for more detail.
874
+ use_cache (`bool`, *optional*):
875
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
876
+ (see `past_key_values`).
877
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
878
+ """
879
+
880
+ residual = hidden_states
881
+
882
+ hidden_states = self.input_layernorm(hidden_states)
883
+
884
+ # Self Attention
885
+ attn_outputs, self_attn_weights, present_key_value = self.self_attn(
886
+ hidden_states=hidden_states,
887
+ attention_mask=attention_mask,
888
+ position_ids=position_ids,
889
+ past_key_value=past_key_value,
890
+ output_attentions=output_attentions,
891
+ use_cache=use_cache,
892
+ )
893
+
894
+ hidden_states = residual + self.resid_attn_dropout(attn_outputs)
895
+
896
+ residual = hidden_states
897
+ hidden_states = self.post_attention_layernorm(hidden_states)
898
+ hidden_states = self.mlp(hidden_states)
899
+ hidden_states = residual + self.resid_mlp_dropout(hidden_states)
900
+
901
+ outputs = (hidden_states,)
902
+
903
+ if output_attentions:
904
+ outputs += (self_attn_weights,)
905
+
906
+ if use_cache:
907
+ outputs += (present_key_value,)
908
+
909
+ return outputs
910
+
911
+
912
+ PHI3_START_DOCSTRING = r"""
913
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
914
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
915
+ etc.)
916
+
917
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
918
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
919
+ and behavior.
920
+
921
+ Parameters:
922
+ config ([`Phi3Config`]):
923
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
924
+ load the weights associated with the model, only the configuration. Check out the
925
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
926
+ """
927
+
928
+
929
+ @add_start_docstrings(
930
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
931
+ PHI3_START_DOCSTRING,
932
+ )
933
+ class Phi3PreTrainedModel(PreTrainedModel):
934
+ config_class = Phi3Config
935
+ base_model_prefix = "model"
936
+ supports_gradient_checkpointing = True
937
+ _no_split_modules = ["Phi3DecoderLayer"]
938
+ _skip_keys_device_placement = "past_key_values"
939
+ _supports_flash_attn_2 = True
940
+ _supports_sdpa = False
941
+ _supports_cache_class = True
942
+
943
+ _version = "0.0.5"
944
+
945
+ def _init_weights(self, module):
946
+ std = self.config.initializer_range
947
+ if isinstance(module, nn.Linear):
948
+ module.weight.data.normal_(mean=0.0, std=std)
949
+ if module.bias is not None:
950
+ module.bias.data.zero_()
951
+ elif isinstance(module, nn.Embedding):
952
+ module.weight.data.normal_(mean=0.0, std=std)
953
+ if module.padding_idx is not None:
954
+ module.weight.data[module.padding_idx].zero_()
955
+
956
+
957
+ PHI3_INPUTS_DOCSTRING = r"""
958
+ Args:
959
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
960
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
961
+ it.
962
+
963
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
964
+ [`PreTrainedTokenizer.__call__`] for details.
965
+
966
+ [What are input IDs?](../glossary#input-ids)
967
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
968
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
969
+
970
+ - 1 for tokens that are **not masked**,
971
+ - 0 for tokens that are **masked**.
972
+
973
+ [What are attention masks?](../glossary#attention-mask)
974
+
975
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
976
+ [`PreTrainedTokenizer.__call__`] for details.
977
+
978
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
979
+ `past_key_values`).
980
+
981
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
982
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
983
+ information on the default strategy.
984
+
985
+ - 1 indicates the head is **not masked**,
986
+ - 0 indicates the head is **masked**.
987
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
988
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
989
+ config.n_positions - 1]`.
990
+
991
+ [What are position IDs?](../glossary#position-ids)
992
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
993
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
994
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
995
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
996
+
997
+ Two formats are allowed:
998
+ - a [`~cache_utils.Cache`] instance;
999
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1000
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1001
+ cache format.
1002
+
1003
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1004
+ legacy cache format will be returned.
1005
+
1006
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1007
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1008
+ of shape `(batch_size, sequence_length)`.
1009
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1010
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1011
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1012
+ model's internal embedding lookup matrix.
1013
+ use_cache (`bool`, *optional*):
1014
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1015
+ `past_key_values`).
1016
+ output_attentions (`bool`, *optional*):
1017
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1018
+ tensors for more detail.
1019
+ output_hidden_states (`bool`, *optional*):
1020
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1021
+ more detail.
1022
+ return_dict (`bool`, *optional*):
1023
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1024
+ """
1025
+
1026
+
1027
+ @add_start_docstrings(
1028
+ "The bare Phi-3 model outputting raw hidden-states without any specific head on top.",
1029
+ PHI3_START_DOCSTRING,
1030
+ )
1031
+ class Phi3Model(Phi3PreTrainedModel):
1032
+ """
1033
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Phi3DecoderLayer`]
1034
+
1035
+ Args:
1036
+ config: Phi3Config
1037
+ """
1038
+
1039
+ def __init__(self, config: Phi3Config):
1040
+ super().__init__(config)
1041
+ self.padding_idx = config.pad_token_id
1042
+ self.vocab_size = config.vocab_size
1043
+
1044
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1045
+ self.embed_dropout = nn.Dropout(config.embd_pdrop)
1046
+ self.layers = nn.ModuleList(
1047
+ [Phi3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1048
+ )
1049
+ self._attn_implementation = config._attn_implementation
1050
+ self.norm = Phi3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1051
+
1052
+ self.gradient_checkpointing = False
1053
+ # Initialize weights and apply final processing
1054
+ self.post_init()
1055
+
1056
+ def get_input_embeddings(self):
1057
+ return self.embed_tokens
1058
+
1059
+ def set_input_embeddings(self, value):
1060
+ self.embed_tokens = value
1061
+
1062
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1063
+ def forward(
1064
+ self,
1065
+ input_ids: torch.LongTensor = None,
1066
+ attention_mask: Optional[torch.Tensor] = None,
1067
+ position_ids: Optional[torch.LongTensor] = None,
1068
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1069
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1070
+ use_cache: Optional[bool] = None,
1071
+ output_attentions: Optional[bool] = None,
1072
+ output_hidden_states: Optional[bool] = None,
1073
+ return_dict: Optional[bool] = None,
1074
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1075
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1076
+ output_hidden_states = (
1077
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1078
+ )
1079
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1080
+
1081
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1082
+
1083
+ # retrieve input_ids and inputs_embeds
1084
+ if input_ids is not None and inputs_embeds is not None:
1085
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1086
+ elif input_ids is not None:
1087
+ batch_size, seq_length = input_ids.shape[:2]
1088
+ elif inputs_embeds is not None:
1089
+ batch_size, seq_length = inputs_embeds.shape[:2]
1090
+ else:
1091
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1092
+
1093
+ past_key_values_length = 0
1094
+
1095
+ if self.gradient_checkpointing and self.training:
1096
+ if use_cache:
1097
+ logger.warning_once(
1098
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1099
+ )
1100
+ use_cache = False
1101
+
1102
+ if use_cache:
1103
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1104
+ if use_legacy_cache:
1105
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1106
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1107
+
1108
+ if position_ids is None:
1109
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1110
+ position_ids = torch.arange(
1111
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1112
+ )
1113
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1114
+ else:
1115
+ position_ids = position_ids.view(-1, seq_length).long()
1116
+
1117
+ if inputs_embeds is None:
1118
+ inputs_embeds = self.embed_tokens(input_ids)
1119
+
1120
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1121
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1122
+ if is_padding_right:
1123
+ raise ValueError(
1124
+ "You are attempting to perform batched generation with padding_side='right'"
1125
+ " this may lead to unexpected behaviour for Flash Attention version of Phi3. Make sure to "
1126
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1127
+ )
1128
+
1129
+ if self._attn_implementation == "flash_attention_2":
1130
+ # 2d mask is passed through the layers
1131
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1132
+ else:
1133
+ # 4d mask is passed through the layers
1134
+ attention_mask = _prepare_4d_causal_attention_mask(
1135
+ attention_mask,
1136
+ (batch_size, seq_length),
1137
+ inputs_embeds,
1138
+ past_key_values_length,
1139
+ sliding_window=self.config.sliding_window,
1140
+ )
1141
+
1142
+ hidden_states = inputs_embeds
1143
+
1144
+ # decoder layers
1145
+ all_hidden_states = () if output_hidden_states else None
1146
+ all_self_attns = () if output_attentions else None
1147
+ next_decoder_cache = None
1148
+
1149
+ for decoder_layer in self.layers:
1150
+ if output_hidden_states:
1151
+ all_hidden_states += (hidden_states,)
1152
+
1153
+ if self.gradient_checkpointing and self.training:
1154
+ layer_outputs = self._gradient_checkpointing_func(
1155
+ decoder_layer.__call__,
1156
+ hidden_states,
1157
+ attention_mask,
1158
+ position_ids,
1159
+ past_key_values,
1160
+ output_attentions,
1161
+ use_cache,
1162
+ )
1163
+ else:
1164
+ layer_outputs = decoder_layer(
1165
+ hidden_states,
1166
+ attention_mask=attention_mask,
1167
+ position_ids=position_ids,
1168
+ past_key_value=past_key_values,
1169
+ output_attentions=output_attentions,
1170
+ use_cache=use_cache,
1171
+ )
1172
+
1173
+ hidden_states = layer_outputs[0]
1174
+
1175
+ if use_cache:
1176
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1177
+
1178
+ if output_attentions:
1179
+ all_self_attns += (layer_outputs[1],)
1180
+
1181
+ hidden_states = self.norm(hidden_states)
1182
+
1183
+ # add hidden states from the last decoder layer
1184
+ if output_hidden_states:
1185
+ all_hidden_states += (hidden_states,)
1186
+
1187
+ next_cache = None
1188
+ if use_cache:
1189
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1190
+ if not return_dict:
1191
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1192
+ return BaseModelOutputWithPast(
1193
+ last_hidden_state=hidden_states,
1194
+ past_key_values=next_cache,
1195
+ hidden_states=all_hidden_states,
1196
+ attentions=all_self_attns,
1197
+ )
1198
+
1199
+
1200
+ class Phi3ForCausalLM(Phi3PreTrainedModel):
1201
+ _tied_weights_keys = ["lm_head.weight"]
1202
+
1203
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.__init__ with Llama->Phi3
1204
+ def __init__(self, config):
1205
+ super().__init__(config)
1206
+ self.model = Phi3Model(config)
1207
+ self.vocab_size = config.vocab_size
1208
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1209
+
1210
+ # Initialize weights and apply final processing
1211
+ self.post_init()
1212
+
1213
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_input_embeddings
1214
+ def get_input_embeddings(self):
1215
+ return self.model.embed_tokens
1216
+
1217
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_input_embeddings
1218
+ def set_input_embeddings(self, value):
1219
+ self.model.embed_tokens = value
1220
+
1221
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_output_embeddings
1222
+ def get_output_embeddings(self):
1223
+ return self.lm_head
1224
+
1225
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_output_embeddings
1226
+ def set_output_embeddings(self, new_embeddings):
1227
+ self.lm_head = new_embeddings
1228
+
1229
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.set_decoder
1230
+ def set_decoder(self, decoder):
1231
+ self.model = decoder
1232
+
1233
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM.get_decoder
1234
+ def get_decoder(self):
1235
+ return self.model
1236
+
1237
+ # Ignore copy
1238
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1239
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1240
+ def forward(
1241
+ self,
1242
+ input_ids: torch.LongTensor = None,
1243
+ attention_mask: Optional[torch.Tensor] = None,
1244
+ position_ids: Optional[torch.LongTensor] = None,
1245
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1246
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1247
+ labels: Optional[torch.LongTensor] = None,
1248
+ use_cache: Optional[bool] = None,
1249
+ output_attentions: Optional[bool] = None,
1250
+ output_hidden_states: Optional[bool] = None,
1251
+ return_dict: Optional[bool] = None,
1252
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1253
+ r"""
1254
+ Args:
1255
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1256
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1257
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1258
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1259
+
1260
+ Returns:
1261
+
1262
+ Example:
1263
+
1264
+ ```python
1265
+ >>> from transformers import AutoTokenizer, Phi3ForCausalLM
1266
+
1267
+ >>> model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1268
+ >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
1269
+
1270
+ >>> prompt = "This is an example script ."
1271
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1272
+
1273
+ >>> # Generate
1274
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1275
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1276
+ 'This is an example script .\n Certainly! Below is a sample script that demonstrates a simple task, such as calculating the sum'
1277
+ ```"""
1278
+
1279
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1280
+ output_hidden_states = (
1281
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1282
+ )
1283
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1284
+
1285
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1286
+ outputs = self.model(
1287
+ input_ids=input_ids,
1288
+ attention_mask=attention_mask,
1289
+ position_ids=position_ids,
1290
+ past_key_values=past_key_values,
1291
+ inputs_embeds=inputs_embeds,
1292
+ use_cache=use_cache,
1293
+ output_attentions=output_attentions,
1294
+ output_hidden_states=output_hidden_states,
1295
+ return_dict=return_dict,
1296
+ )
1297
+
1298
+ hidden_states = outputs[0]
1299
+ logits = self.lm_head(hidden_states)
1300
+ logits = logits.float()
1301
+
1302
+ loss = None
1303
+ if labels is not None:
1304
+ # Shift so that tokens < n predict n
1305
+ shift_logits = logits[..., :-1, :].contiguous()
1306
+ shift_labels = labels[..., 1:].contiguous()
1307
+ # Flatten the tokens
1308
+ loss_fct = CrossEntropyLoss()
1309
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1310
+ shift_labels = shift_labels.view(-1)
1311
+ # Enable model parallelism
1312
+ shift_labels = shift_labels.to(shift_logits.device)
1313
+ loss = loss_fct(shift_logits, shift_labels)
1314
+
1315
+ if not return_dict:
1316
+ output = (logits,) + outputs[1:]
1317
+ return (loss,) + output if loss is not None else output
1318
+
1319
+ return CausalLMOutputWithPast(
1320
+ loss=loss,
1321
+ logits=logits,
1322
+ past_key_values=outputs.past_key_values,
1323
+ hidden_states=outputs.hidden_states,
1324
+ attentions=outputs.attentions,
1325
+ )
1326
+
1327
+ # Copied from transformers.models.persimmon.modeling_persimmon.PersimmonForCausalLM.prepare_inputs_for_generation
1328
+ def prepare_inputs_for_generation(
1329
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1330
+ ):
1331
+ if past_key_values is not None:
1332
+ if isinstance(past_key_values, Cache):
1333
+ cache_length = past_key_values.get_seq_length()
1334
+ past_length = past_key_values.seen_tokens
1335
+ max_cache_length = past_key_values.get_max_length()
1336
+ else:
1337
+ cache_length = past_length = past_key_values[0][0].shape[2]
1338
+ max_cache_length = None
1339
+
1340
+ # Keep only the unprocessed tokens:
1341
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1342
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1343
+ # input)
1344
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1345
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1346
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1347
+ # input_ids based on the past_length.
1348
+ elif past_length < input_ids.shape[1]:
1349
+ input_ids = input_ids[:, past_length:]
1350
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1351
+
1352
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1353
+ if (
1354
+ max_cache_length is not None
1355
+ and attention_mask is not None
1356
+ and cache_length + input_ids.shape[1] > max_cache_length
1357
+ ):
1358
+ attention_mask = attention_mask[:, -max_cache_length:]
1359
+
1360
+ position_ids = kwargs.get("position_ids", None)
1361
+ if attention_mask is not None and position_ids is None:
1362
+ # create position_ids on the fly for batch generation
1363
+ position_ids = attention_mask.long().cumsum(-1) - 1
1364
+ position_ids.masked_fill_(attention_mask == 0, 1)
1365
+ if past_key_values:
1366
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1367
+
1368
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1369
+ if inputs_embeds is not None and past_key_values is None:
1370
+ model_inputs = {"inputs_embeds": inputs_embeds}
1371
+ else:
1372
+ model_inputs = {"input_ids": input_ids}
1373
+
1374
+ model_inputs.update(
1375
+ {
1376
+ "position_ids": position_ids,
1377
+ "past_key_values": past_key_values,
1378
+ "use_cache": kwargs.get("use_cache"),
1379
+ "attention_mask": attention_mask,
1380
+ }
1381
+ )
1382
+ return model_inputs
1383
+
1384
+ @staticmethod
1385
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM._reorder_cache
1386
+ def _reorder_cache(past_key_values, beam_idx):
1387
+ reordered_past = ()
1388
+ for layer_past in past_key_values:
1389
+ reordered_past += (
1390
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1391
+ )
1392
+ return reordered_past
1393
+
1394
+
1395
+ @add_start_docstrings(
1396
+ """
1397
+ The [`Phi3Model`] with a sequence classification head on top (linear layer).
1398
+
1399
+ [`Phi3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1400
+ (e.g. GPT-2) do.
1401
+
1402
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1403
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1404
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1405
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1406
+ each row of the batch).
1407
+ """,
1408
+ PHI3_START_DOCSTRING,
1409
+ )
1410
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Phi3, LLAMA->PHI3, self.transformer->self.model, transformer_outputs->model_outputs
1411
+ class Phi3ForSequenceClassification(Phi3PreTrainedModel):
1412
+ def __init__(self, config):
1413
+ super().__init__(config)
1414
+ self.num_labels = config.num_labels
1415
+ self.model = Phi3Model(config)
1416
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1417
+
1418
+ # Initialize weights and apply final processing
1419
+ self.post_init()
1420
+
1421
+ def get_input_embeddings(self):
1422
+ return self.model.embed_tokens
1423
+
1424
+ def set_input_embeddings(self, value):
1425
+ self.model.embed_tokens = value
1426
+
1427
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1428
+ def forward(
1429
+ self,
1430
+ input_ids: torch.LongTensor = None,
1431
+ attention_mask: Optional[torch.Tensor] = None,
1432
+ position_ids: Optional[torch.LongTensor] = None,
1433
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1434
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1435
+ labels: Optional[torch.LongTensor] = None,
1436
+ use_cache: Optional[bool] = None,
1437
+ output_attentions: Optional[bool] = None,
1438
+ output_hidden_states: Optional[bool] = None,
1439
+ return_dict: Optional[bool] = None,
1440
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1441
+ r"""
1442
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1443
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1444
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1445
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1446
+ """
1447
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1448
+
1449
+ model_outputs = self.model(
1450
+ input_ids,
1451
+ attention_mask=attention_mask,
1452
+ position_ids=position_ids,
1453
+ past_key_values=past_key_values,
1454
+ inputs_embeds=inputs_embeds,
1455
+ use_cache=use_cache,
1456
+ output_attentions=output_attentions,
1457
+ output_hidden_states=output_hidden_states,
1458
+ return_dict=return_dict,
1459
+ )
1460
+ hidden_states = model_outputs[0]
1461
+ logits = self.score(hidden_states)
1462
+
1463
+ if input_ids is not None:
1464
+ batch_size = input_ids.shape[0]
1465
+ else:
1466
+ batch_size = inputs_embeds.shape[0]
1467
+
1468
+ if self.config.pad_token_id is None and batch_size != 1:
1469
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1470
+ if self.config.pad_token_id is None:
1471
+ sequence_lengths = -1
1472
+ else:
1473
+ if input_ids is not None:
1474
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1475
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1476
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1477
+ sequence_lengths = sequence_lengths.to(logits.device)
1478
+ else:
1479
+ sequence_lengths = -1
1480
+
1481
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1482
+
1483
+ loss = None
1484
+ if labels is not None:
1485
+ labels = labels.to(logits.device)
1486
+ if self.config.problem_type is None:
1487
+ if self.num_labels == 1:
1488
+ self.config.problem_type = "regression"
1489
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1490
+ self.config.problem_type = "single_label_classification"
1491
+ else:
1492
+ self.config.problem_type = "multi_label_classification"
1493
+
1494
+ if self.config.problem_type == "regression":
1495
+ loss_fct = MSELoss()
1496
+ if self.num_labels == 1:
1497
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1498
+ else:
1499
+ loss = loss_fct(pooled_logits, labels)
1500
+ elif self.config.problem_type == "single_label_classification":
1501
+ loss_fct = CrossEntropyLoss()
1502
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1503
+ elif self.config.problem_type == "multi_label_classification":
1504
+ loss_fct = BCEWithLogitsLoss()
1505
+ loss = loss_fct(pooled_logits, labels)
1506
+ if not return_dict:
1507
+ output = (pooled_logits,) + model_outputs[1:]
1508
+ return ((loss,) + output) if loss is not None else output
1509
+
1510
+ return SequenceClassifierOutputWithPast(
1511
+ loss=loss,
1512
+ logits=pooled_logits,
1513
+ past_key_values=model_outputs.past_key_values,
1514
+ hidden_states=model_outputs.hidden_states,
1515
+ attentions=model_outputs.attentions,
1516
+ )
1517
+
1518
+
1519
+ @add_start_docstrings(
1520
+ """
1521
+ [`Phi3Model`] with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1522
+ Named-Entity-Recognition (NER) tasks.
1523
+ """,
1524
+ PHI3_START_DOCSTRING,
1525
+ )
1526
+ # Copied from transformers.models.mpt.modeling_mpt.MptForTokenClassification with Mpt->Phi3,MPT->PHI3,self.transformer->self.model,transformer_outputs->model_outputs
1527
+ class Phi3ForTokenClassification(Phi3PreTrainedModel):
1528
+ def __init__(self, config: Phi3Config):
1529
+ super().__init__(config)
1530
+ self.num_labels = config.num_labels
1531
+
1532
+ self.model = Phi3Model(config)
1533
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1534
+ classifier_dropout = config.classifier_dropout
1535
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1536
+ classifier_dropout = config.hidden_dropout
1537
+ else:
1538
+ classifier_dropout = 0.1
1539
+ self.dropout = nn.Dropout(classifier_dropout)
1540
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1541
+
1542
+ # Initialize weights and apply final processing
1543
+ self.post_init()
1544
+
1545
+ @add_start_docstrings_to_model_forward(PHI3_INPUTS_DOCSTRING)
1546
+ @add_code_sample_docstrings(
1547
+ checkpoint=_CHECKPOINT_FOR_DOC,
1548
+ output_type=TokenClassifierOutput,
1549
+ config_class=_CONFIG_FOR_DOC,
1550
+ )
1551
+ def forward(
1552
+ self,
1553
+ input_ids: Optional[torch.LongTensor] = None,
1554
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
1555
+ attention_mask: Optional[torch.Tensor] = None,
1556
+ inputs_embeds: Optional[torch.Tensor] = None,
1557
+ labels: Optional[torch.Tensor] = None,
1558
+ use_cache: Optional[bool] = None,
1559
+ output_attentions: Optional[bool] = None,
1560
+ output_hidden_states: Optional[bool] = None,
1561
+ return_dict: Optional[bool] = None,
1562
+ **deprecated_arguments,
1563
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
1564
+ r"""
1565
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1566
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1567
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1568
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1569
+ """
1570
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1571
+
1572
+ model_outputs = self.model(
1573
+ input_ids,
1574
+ past_key_values=past_key_values,
1575
+ attention_mask=attention_mask,
1576
+ inputs_embeds=inputs_embeds,
1577
+ use_cache=use_cache,
1578
+ output_attentions=output_attentions,
1579
+ output_hidden_states=output_hidden_states,
1580
+ return_dict=return_dict,
1581
+ )
1582
+
1583
+ hidden_states = model_outputs[0]
1584
+ hidden_states = self.dropout(hidden_states)
1585
+ logits = self.classifier(hidden_states)
1586
+
1587
+ loss = None
1588
+ if labels is not None:
1589
+ # move labels to correct device to enable model parallelism
1590
+ labels = labels.to(logits.device)
1591
+ batch_size, seq_length = labels.shape
1592
+ loss_fct = CrossEntropyLoss()
1593
+ loss = loss_fct(
1594
+ logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length)
1595
+ )
1596
+
1597
+ if not return_dict:
1598
+ output = (logits,) + model_outputs[2:]
1599
+ return ((loss,) + output) if loss is not None else output
1600
+
1601
+ return TokenClassifierOutput(
1602
+ loss=loss,
1603
+ logits=logits,
1604
+ hidden_states=model_outputs.hidden_states,
1605
+ attentions=model_outputs.attentions,
1606
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|endoftext|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
3
+ size 499723
tokenizer_config.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": null,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
24
+ "lstrip": false,
25
+ "normalized": false,
26
+ "rstrip": true,
27
+ "single_word": false,
28
+ "special": false
29
+ },
30
+ "32000": {
31
+ "content": "<|endoftext|>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false,
36
+ "special": true
37
+ },
38
+ "32001": {
39
+ "content": "<|assistant|>",
40
+ "lstrip": false,
41
+ "normalized": false,
42
+ "rstrip": true,
43
+ "single_word": false,
44
+ "special": true
45
+ },
46
+ "32002": {
47
+ "content": "<|placeholder1|>",
48
+ "lstrip": false,
49
+ "normalized": false,
50
+ "rstrip": true,
51
+ "single_word": false,
52
+ "special": true
53
+ },
54
+ "32003": {
55
+ "content": "<|placeholder2|>",
56
+ "lstrip": false,
57
+ "normalized": false,
58
+ "rstrip": true,
59
+ "single_word": false,
60
+ "special": true
61
+ },
62
+ "32004": {
63
+ "content": "<|placeholder3|>",
64
+ "lstrip": false,
65
+ "normalized": false,
66
+ "rstrip": true,
67
+ "single_word": false,
68
+ "special": true
69
+ },
70
+ "32005": {
71
+ "content": "<|placeholder4|>",
72
+ "lstrip": false,
73
+ "normalized": false,
74
+ "rstrip": true,
75
+ "single_word": false,
76
+ "special": true
77
+ },
78
+ "32006": {
79
+ "content": "<|system|>",
80
+ "lstrip": false,
81
+ "normalized": false,
82
+ "rstrip": true,
83
+ "single_word": false,
84
+ "special": true
85
+ },
86
+ "32007": {
87
+ "content": "<|end|>",
88
+ "lstrip": false,
89
+ "normalized": false,
90
+ "rstrip": false,
91
+ "single_word": false,
92
+ "special": true
93
+ },
94
+ "32008": {
95
+ "content": "<|placeholder5|>",
96
+ "lstrip": false,
97
+ "normalized": false,
98
+ "rstrip": true,
99
+ "single_word": false,
100
+ "special": true
101
+ },
102
+ "32009": {
103
+ "content": "<|placeholder6|>",
104
+ "lstrip": false,
105
+ "normalized": false,
106
+ "rstrip": true,
107
+ "single_word": false,
108
+ "special": true
109
+ },
110
+ "32010": {
111
+ "content": "<|user|>",
112
+ "lstrip": false,
113
+ "normalized": false,
114
+ "rstrip": true,
115
+ "single_word": false,
116
+ "special": true
117
+ }
118
+ },
119
+ "bos_token": "<s>",
120
+ "clean_up_tokenization_spaces": false,
121
+ "eos_token": "<|end|>",
122
+ "extra_special_tokens": {},
123
+ "legacy": false,
124
+ "model_max_length": 131072,
125
+ "pad_token": "<|endoftext|>",
126
+ "padding_side": "right",
127
+ "sp_model_kwargs": {},
128
+ "split_special_tokens": false,
129
+ "tokenizer_class": "LlamaTokenizer",
130
+ "unk_token": "<unk>",
131
+ "use_default_system_prompt": false
132
+ }
trainer_state.json ADDED
@@ -0,0 +1,2134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "best_global_step": null,
3
+ "best_metric": null,
4
+ "best_model_checkpoint": null,
5
+ "epoch": 4.298368298368298,
6
+ "eval_steps": 500,
7
+ "global_step": 3000,
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.014344629729245113,
14
+ "grad_norm": 2.1563808263401123,
15
+ "learning_rate": 2.1479713603818614e-06,
16
+ "loss": 0.9832,
17
+ "step": 10
18
+ },
19
+ {
20
+ "epoch": 0.028689259458490227,
21
+ "grad_norm": 1.5376642197375787,
22
+ "learning_rate": 4.5346062052505965e-06,
23
+ "loss": 0.8531,
24
+ "step": 20
25
+ },
26
+ {
27
+ "epoch": 0.04303388918773534,
28
+ "grad_norm": 0.7108211564362369,
29
+ "learning_rate": 6.921241050119331e-06,
30
+ "loss": 0.7191,
31
+ "step": 30
32
+ },
33
+ {
34
+ "epoch": 0.05737851891698045,
35
+ "grad_norm": 0.5064006283904037,
36
+ "learning_rate": 9.307875894988068e-06,
37
+ "loss": 0.6532,
38
+ "step": 40
39
+ },
40
+ {
41
+ "epoch": 0.07172314864622557,
42
+ "grad_norm": 0.5016524926299113,
43
+ "learning_rate": 1.1694510739856803e-05,
44
+ "loss": 0.6245,
45
+ "step": 50
46
+ },
47
+ {
48
+ "epoch": 0.08606777837547068,
49
+ "grad_norm": 0.5064320977744877,
50
+ "learning_rate": 1.4081145584725539e-05,
51
+ "loss": 0.6017,
52
+ "step": 60
53
+ },
54
+ {
55
+ "epoch": 0.1004124081047158,
56
+ "grad_norm": 0.4525315758811991,
57
+ "learning_rate": 1.6467780429594274e-05,
58
+ "loss": 0.5788,
59
+ "step": 70
60
+ },
61
+ {
62
+ "epoch": 0.1147570378339609,
63
+ "grad_norm": 0.4891140282424216,
64
+ "learning_rate": 1.885441527446301e-05,
65
+ "loss": 0.5726,
66
+ "step": 80
67
+ },
68
+ {
69
+ "epoch": 0.129101667563206,
70
+ "grad_norm": 0.5816465774117703,
71
+ "learning_rate": 2.1241050119331742e-05,
72
+ "loss": 0.5669,
73
+ "step": 90
74
+ },
75
+ {
76
+ "epoch": 0.14344629729245115,
77
+ "grad_norm": 0.5416459422496235,
78
+ "learning_rate": 2.3627684964200477e-05,
79
+ "loss": 0.5621,
80
+ "step": 100
81
+ },
82
+ {
83
+ "epoch": 0.15779092702169625,
84
+ "grad_norm": 0.5501550374753971,
85
+ "learning_rate": 2.6014319809069216e-05,
86
+ "loss": 0.5543,
87
+ "step": 110
88
+ },
89
+ {
90
+ "epoch": 0.17213555675094136,
91
+ "grad_norm": 0.48897325487812016,
92
+ "learning_rate": 2.840095465393795e-05,
93
+ "loss": 0.5519,
94
+ "step": 120
95
+ },
96
+ {
97
+ "epoch": 0.1864801864801865,
98
+ "grad_norm": 0.5193769497689257,
99
+ "learning_rate": 3.0787589498806684e-05,
100
+ "loss": 0.546,
101
+ "step": 130
102
+ },
103
+ {
104
+ "epoch": 0.2008248162094316,
105
+ "grad_norm": 0.5100064220076413,
106
+ "learning_rate": 3.3174224343675416e-05,
107
+ "loss": 0.5454,
108
+ "step": 140
109
+ },
110
+ {
111
+ "epoch": 0.2151694459386767,
112
+ "grad_norm": 0.4992592686432826,
113
+ "learning_rate": 3.5560859188544155e-05,
114
+ "loss": 0.5437,
115
+ "step": 150
116
+ },
117
+ {
118
+ "epoch": 0.2295140756679218,
119
+ "grad_norm": 0.4838403686730783,
120
+ "learning_rate": 3.794749403341289e-05,
121
+ "loss": 0.5412,
122
+ "step": 160
123
+ },
124
+ {
125
+ "epoch": 0.24385870539716695,
126
+ "grad_norm": 0.45590237103117387,
127
+ "learning_rate": 4.0334128878281626e-05,
128
+ "loss": 0.541,
129
+ "step": 170
130
+ },
131
+ {
132
+ "epoch": 0.258203335126412,
133
+ "grad_norm": 0.44189108119445925,
134
+ "learning_rate": 4.272076372315036e-05,
135
+ "loss": 0.5328,
136
+ "step": 180
137
+ },
138
+ {
139
+ "epoch": 0.2725479648556572,
140
+ "grad_norm": 0.4596950199469469,
141
+ "learning_rate": 4.510739856801909e-05,
142
+ "loss": 0.5328,
143
+ "step": 190
144
+ },
145
+ {
146
+ "epoch": 0.2868925945849023,
147
+ "grad_norm": 0.4232582169854354,
148
+ "learning_rate": 4.749403341288783e-05,
149
+ "loss": 0.5331,
150
+ "step": 200
151
+ },
152
+ {
153
+ "epoch": 0.3012372243141474,
154
+ "grad_norm": 0.47183677702470816,
155
+ "learning_rate": 4.988066825775656e-05,
156
+ "loss": 0.5405,
157
+ "step": 210
158
+ },
159
+ {
160
+ "epoch": 0.3155818540433925,
161
+ "grad_norm": 0.510543623904468,
162
+ "learning_rate": 5.22673031026253e-05,
163
+ "loss": 0.5448,
164
+ "step": 220
165
+ },
166
+ {
167
+ "epoch": 0.3299264837726376,
168
+ "grad_norm": 0.49518213450267645,
169
+ "learning_rate": 5.465393794749404e-05,
170
+ "loss": 0.5441,
171
+ "step": 230
172
+ },
173
+ {
174
+ "epoch": 0.3442711135018827,
175
+ "grad_norm": 0.4081838992878798,
176
+ "learning_rate": 5.7040572792362765e-05,
177
+ "loss": 0.5342,
178
+ "step": 240
179
+ },
180
+ {
181
+ "epoch": 0.3586157432311278,
182
+ "grad_norm": 0.45201996051478616,
183
+ "learning_rate": 5.942720763723151e-05,
184
+ "loss": 0.5379,
185
+ "step": 250
186
+ },
187
+ {
188
+ "epoch": 0.372960372960373,
189
+ "grad_norm": 0.5163583891265898,
190
+ "learning_rate": 6.181384248210024e-05,
191
+ "loss": 0.5352,
192
+ "step": 260
193
+ },
194
+ {
195
+ "epoch": 0.3873050026896181,
196
+ "grad_norm": 0.43220360318869133,
197
+ "learning_rate": 6.420047732696898e-05,
198
+ "loss": 0.5319,
199
+ "step": 270
200
+ },
201
+ {
202
+ "epoch": 0.4016496324188632,
203
+ "grad_norm": 0.39341356230222857,
204
+ "learning_rate": 6.65871121718377e-05,
205
+ "loss": 0.531,
206
+ "step": 280
207
+ },
208
+ {
209
+ "epoch": 0.4159942621481083,
210
+ "grad_norm": 0.4843450935832954,
211
+ "learning_rate": 6.897374701670645e-05,
212
+ "loss": 0.5247,
213
+ "step": 290
214
+ },
215
+ {
216
+ "epoch": 0.4303388918773534,
217
+ "grad_norm": 0.43790304963108484,
218
+ "learning_rate": 7.136038186157519e-05,
219
+ "loss": 0.535,
220
+ "step": 300
221
+ },
222
+ {
223
+ "epoch": 0.4446835216065985,
224
+ "grad_norm": 0.3679883238347063,
225
+ "learning_rate": 7.374701670644391e-05,
226
+ "loss": 0.529,
227
+ "step": 310
228
+ },
229
+ {
230
+ "epoch": 0.4590281513358436,
231
+ "grad_norm": 0.38496528216858267,
232
+ "learning_rate": 7.613365155131266e-05,
233
+ "loss": 0.5358,
234
+ "step": 320
235
+ },
236
+ {
237
+ "epoch": 0.47337278106508873,
238
+ "grad_norm": 0.3554015988338894,
239
+ "learning_rate": 7.852028639618139e-05,
240
+ "loss": 0.5366,
241
+ "step": 330
242
+ },
243
+ {
244
+ "epoch": 0.4877174107943339,
245
+ "grad_norm": 0.3647316947863913,
246
+ "learning_rate": 8.090692124105012e-05,
247
+ "loss": 0.5305,
248
+ "step": 340
249
+ },
250
+ {
251
+ "epoch": 0.502062040523579,
252
+ "grad_norm": 0.40796953260473273,
253
+ "learning_rate": 8.329355608591885e-05,
254
+ "loss": 0.5361,
255
+ "step": 350
256
+ },
257
+ {
258
+ "epoch": 0.516406670252824,
259
+ "grad_norm": 0.345466577791704,
260
+ "learning_rate": 8.56801909307876e-05,
261
+ "loss": 0.5317,
262
+ "step": 360
263
+ },
264
+ {
265
+ "epoch": 0.5307512999820692,
266
+ "grad_norm": 0.3897824320306703,
267
+ "learning_rate": 8.806682577565633e-05,
268
+ "loss": 0.5384,
269
+ "step": 370
270
+ },
271
+ {
272
+ "epoch": 0.5450959297113144,
273
+ "grad_norm": 0.39750641265021325,
274
+ "learning_rate": 9.045346062052506e-05,
275
+ "loss": 0.5344,
276
+ "step": 380
277
+ },
278
+ {
279
+ "epoch": 0.5594405594405595,
280
+ "grad_norm": 0.3294501292354428,
281
+ "learning_rate": 9.28400954653938e-05,
282
+ "loss": 0.531,
283
+ "step": 390
284
+ },
285
+ {
286
+ "epoch": 0.5737851891698046,
287
+ "grad_norm": 0.3325704984940842,
288
+ "learning_rate": 9.522673031026254e-05,
289
+ "loss": 0.5282,
290
+ "step": 400
291
+ },
292
+ {
293
+ "epoch": 0.5881298188990497,
294
+ "grad_norm": 0.37577078172283135,
295
+ "learning_rate": 9.761336515513126e-05,
296
+ "loss": 0.5289,
297
+ "step": 410
298
+ },
299
+ {
300
+ "epoch": 0.6024744486282948,
301
+ "grad_norm": 0.32982285395946315,
302
+ "learning_rate": 0.0001,
303
+ "loss": 0.5326,
304
+ "step": 420
305
+ },
306
+ {
307
+ "epoch": 0.6168190783575399,
308
+ "grad_norm": 0.315570817514683,
309
+ "learning_rate": 9.999826305940802e-05,
310
+ "loss": 0.5276,
311
+ "step": 430
312
+ },
313
+ {
314
+ "epoch": 0.631163708086785,
315
+ "grad_norm": 0.32873479872603517,
316
+ "learning_rate": 9.99930523583106e-05,
317
+ "loss": 0.5329,
318
+ "step": 440
319
+ },
320
+ {
321
+ "epoch": 0.6455083378160301,
322
+ "grad_norm": 0.3754610016068392,
323
+ "learning_rate": 9.998436825873485e-05,
324
+ "loss": 0.5339,
325
+ "step": 450
326
+ },
327
+ {
328
+ "epoch": 0.6598529675452752,
329
+ "grad_norm": 0.2973537072730961,
330
+ "learning_rate": 9.997221136403139e-05,
331
+ "loss": 0.5249,
332
+ "step": 460
333
+ },
334
+ {
335
+ "epoch": 0.6741975972745203,
336
+ "grad_norm": 0.33421087994681,
337
+ "learning_rate": 9.995658251883237e-05,
338
+ "loss": 0.5196,
339
+ "step": 470
340
+ },
341
+ {
342
+ "epoch": 0.6885422270037654,
343
+ "grad_norm": 0.3120052809857615,
344
+ "learning_rate": 9.993748280899279e-05,
345
+ "loss": 0.5236,
346
+ "step": 480
347
+ },
348
+ {
349
+ "epoch": 0.7028868567330105,
350
+ "grad_norm": 0.28477505127058517,
351
+ "learning_rate": 9.991491356151515e-05,
352
+ "loss": 0.5166,
353
+ "step": 490
354
+ },
355
+ {
356
+ "epoch": 0.7172314864622557,
357
+ "grad_norm": 0.3282614273702267,
358
+ "learning_rate": 9.988887634445711e-05,
359
+ "loss": 0.5191,
360
+ "step": 500
361
+ },
362
+ {
363
+ "epoch": 0.7315761161915008,
364
+ "grad_norm": 0.3018575266984723,
365
+ "learning_rate": 9.985937296682264e-05,
366
+ "loss": 0.52,
367
+ "step": 510
368
+ },
369
+ {
370
+ "epoch": 0.745920745920746,
371
+ "grad_norm": 0.322642800391225,
372
+ "learning_rate": 9.982640547843628e-05,
373
+ "loss": 0.5193,
374
+ "step": 520
375
+ },
376
+ {
377
+ "epoch": 0.7602653756499911,
378
+ "grad_norm": 0.29334428049579575,
379
+ "learning_rate": 9.978997616980083e-05,
380
+ "loss": 0.5173,
381
+ "step": 530
382
+ },
383
+ {
384
+ "epoch": 0.7746100053792362,
385
+ "grad_norm": 0.30663608653187874,
386
+ "learning_rate": 9.975008757193805e-05,
387
+ "loss": 0.514,
388
+ "step": 540
389
+ },
390
+ {
391
+ "epoch": 0.7889546351084813,
392
+ "grad_norm": 0.2902575349921672,
393
+ "learning_rate": 9.970674245621296e-05,
394
+ "loss": 0.5173,
395
+ "step": 550
396
+ },
397
+ {
398
+ "epoch": 0.8032992648377264,
399
+ "grad_norm": 0.2750627268123107,
400
+ "learning_rate": 9.965994383414116e-05,
401
+ "loss": 0.5124,
402
+ "step": 560
403
+ },
404
+ {
405
+ "epoch": 0.8176438945669715,
406
+ "grad_norm": 0.31846444500772264,
407
+ "learning_rate": 9.960969495717975e-05,
408
+ "loss": 0.5105,
409
+ "step": 570
410
+ },
411
+ {
412
+ "epoch": 0.8319885242962166,
413
+ "grad_norm": 0.2850087845127407,
414
+ "learning_rate": 9.955599931650127e-05,
415
+ "loss": 0.505,
416
+ "step": 580
417
+ },
418
+ {
419
+ "epoch": 0.8463331540254617,
420
+ "grad_norm": 0.3011934822435399,
421
+ "learning_rate": 9.949886064275123e-05,
422
+ "loss": 0.4997,
423
+ "step": 590
424
+ },
425
+ {
426
+ "epoch": 0.8606777837547068,
427
+ "grad_norm": 0.28048546158040877,
428
+ "learning_rate": 9.943828290578892e-05,
429
+ "loss": 0.5039,
430
+ "step": 600
431
+ },
432
+ {
433
+ "epoch": 0.8750224134839519,
434
+ "grad_norm": 0.29482418586801606,
435
+ "learning_rate": 9.937427031441152e-05,
436
+ "loss": 0.5068,
437
+ "step": 610
438
+ },
439
+ {
440
+ "epoch": 0.889367043213197,
441
+ "grad_norm": 0.2868511054090736,
442
+ "learning_rate": 9.93068273160618e-05,
443
+ "loss": 0.5041,
444
+ "step": 620
445
+ },
446
+ {
447
+ "epoch": 0.9037116729424421,
448
+ "grad_norm": 0.26871712641833934,
449
+ "learning_rate": 9.9235958596519e-05,
450
+ "loss": 0.5031,
451
+ "step": 630
452
+ },
453
+ {
454
+ "epoch": 0.9180563026716873,
455
+ "grad_norm": 0.27176006324351715,
456
+ "learning_rate": 9.916166907957336e-05,
457
+ "loss": 0.4998,
458
+ "step": 640
459
+ },
460
+ {
461
+ "epoch": 0.9324009324009324,
462
+ "grad_norm": 0.2916123334399884,
463
+ "learning_rate": 9.908396392668397e-05,
464
+ "loss": 0.5045,
465
+ "step": 650
466
+ },
467
+ {
468
+ "epoch": 0.9467455621301775,
469
+ "grad_norm": 0.28657648009371867,
470
+ "learning_rate": 9.90028485366202e-05,
471
+ "loss": 0.5005,
472
+ "step": 660
473
+ },
474
+ {
475
+ "epoch": 0.9610901918594227,
476
+ "grad_norm": 0.2616587253845151,
477
+ "learning_rate": 9.891832854508661e-05,
478
+ "loss": 0.5017,
479
+ "step": 670
480
+ },
481
+ {
482
+ "epoch": 0.9754348215886678,
483
+ "grad_norm": 0.2642546302377749,
484
+ "learning_rate": 9.883040982433133e-05,
485
+ "loss": 0.492,
486
+ "step": 680
487
+ },
488
+ {
489
+ "epoch": 0.9897794513179129,
490
+ "grad_norm": 0.255936110537566,
491
+ "learning_rate": 9.87390984827382e-05,
492
+ "loss": 0.4934,
493
+ "step": 690
494
+ },
495
+ {
496
+ "epoch": 1.002868925945849,
497
+ "grad_norm": 0.3099905060480918,
498
+ "learning_rate": 9.864440086440223e-05,
499
+ "loss": 0.43,
500
+ "step": 700
501
+ },
502
+ {
503
+ "epoch": 1.017213555675094,
504
+ "grad_norm": 0.25984643430841164,
505
+ "learning_rate": 9.854632354868889e-05,
506
+ "loss": 0.3695,
507
+ "step": 710
508
+ },
509
+ {
510
+ "epoch": 1.0315581854043392,
511
+ "grad_norm": 0.28715953895875523,
512
+ "learning_rate": 9.844487334977705e-05,
513
+ "loss": 0.3792,
514
+ "step": 720
515
+ },
516
+ {
517
+ "epoch": 1.0459028151335843,
518
+ "grad_norm": 0.2649853690140653,
519
+ "learning_rate": 9.834005731618543e-05,
520
+ "loss": 0.3737,
521
+ "step": 730
522
+ },
523
+ {
524
+ "epoch": 1.0602474448628294,
525
+ "grad_norm": 0.26573177260306496,
526
+ "learning_rate": 9.823188273028297e-05,
527
+ "loss": 0.3771,
528
+ "step": 740
529
+ },
530
+ {
531
+ "epoch": 1.0745920745920745,
532
+ "grad_norm": 0.26574383245031147,
533
+ "learning_rate": 9.812035710778283e-05,
534
+ "loss": 0.3741,
535
+ "step": 750
536
+ },
537
+ {
538
+ "epoch": 1.0889367043213196,
539
+ "grad_norm": 0.28123208245100456,
540
+ "learning_rate": 9.800548819722026e-05,
541
+ "loss": 0.3731,
542
+ "step": 760
543
+ },
544
+ {
545
+ "epoch": 1.1032813340505647,
546
+ "grad_norm": 0.28349060376734364,
547
+ "learning_rate": 9.78872839794142e-05,
548
+ "loss": 0.3778,
549
+ "step": 770
550
+ },
551
+ {
552
+ "epoch": 1.11762596377981,
553
+ "grad_norm": 0.28893208285124705,
554
+ "learning_rate": 9.776575266691279e-05,
555
+ "loss": 0.3806,
556
+ "step": 780
557
+ },
558
+ {
559
+ "epoch": 1.1319705935090552,
560
+ "grad_norm": 0.2860386213893016,
561
+ "learning_rate": 9.764090270342286e-05,
562
+ "loss": 0.3799,
563
+ "step": 790
564
+ },
565
+ {
566
+ "epoch": 1.1463152232383003,
567
+ "grad_norm": 0.2460375162339276,
568
+ "learning_rate": 9.751274276322316e-05,
569
+ "loss": 0.3898,
570
+ "step": 800
571
+ },
572
+ {
573
+ "epoch": 1.1606598529675454,
574
+ "grad_norm": 0.251720247858439,
575
+ "learning_rate": 9.738128175056179e-05,
576
+ "loss": 0.3821,
577
+ "step": 810
578
+ },
579
+ {
580
+ "epoch": 1.1750044826967905,
581
+ "grad_norm": 0.25278081761302046,
582
+ "learning_rate": 9.724652879903751e-05,
583
+ "loss": 0.3798,
584
+ "step": 820
585
+ },
586
+ {
587
+ "epoch": 1.1893491124260356,
588
+ "grad_norm": 0.2599296471651565,
589
+ "learning_rate": 9.71084932709652e-05,
590
+ "loss": 0.3828,
591
+ "step": 830
592
+ },
593
+ {
594
+ "epoch": 1.2036937421552807,
595
+ "grad_norm": 0.2455565423628766,
596
+ "learning_rate": 9.696718475672532e-05,
597
+ "loss": 0.3743,
598
+ "step": 840
599
+ },
600
+ {
601
+ "epoch": 1.2180383718845258,
602
+ "grad_norm": 0.2888176539405626,
603
+ "learning_rate": 9.682261307409766e-05,
604
+ "loss": 0.381,
605
+ "step": 850
606
+ },
607
+ {
608
+ "epoch": 1.232383001613771,
609
+ "grad_norm": 0.25471629336116824,
610
+ "learning_rate": 9.667478826757916e-05,
611
+ "loss": 0.3832,
612
+ "step": 860
613
+ },
614
+ {
615
+ "epoch": 1.246727631343016,
616
+ "grad_norm": 0.2614351769400213,
617
+ "learning_rate": 9.652372060768608e-05,
618
+ "loss": 0.3848,
619
+ "step": 870
620
+ },
621
+ {
622
+ "epoch": 1.2610722610722611,
623
+ "grad_norm": 0.26412023986782596,
624
+ "learning_rate": 9.63694205902405e-05,
625
+ "loss": 0.3855,
626
+ "step": 880
627
+ },
628
+ {
629
+ "epoch": 1.2754168908015062,
630
+ "grad_norm": 0.2429603634039349,
631
+ "learning_rate": 9.621189893564092e-05,
632
+ "loss": 0.3819,
633
+ "step": 890
634
+ },
635
+ {
636
+ "epoch": 1.2897615205307513,
637
+ "grad_norm": 0.26829134565306034,
638
+ "learning_rate": 9.605116658811759e-05,
639
+ "loss": 0.3906,
640
+ "step": 900
641
+ },
642
+ {
643
+ "epoch": 1.3041061502599964,
644
+ "grad_norm": 0.27364921782590684,
645
+ "learning_rate": 9.588723471497208e-05,
646
+ "loss": 0.3848,
647
+ "step": 910
648
+ },
649
+ {
650
+ "epoch": 1.3184507799892415,
651
+ "grad_norm": 0.2515405826777948,
652
+ "learning_rate": 9.572011470580136e-05,
653
+ "loss": 0.3899,
654
+ "step": 920
655
+ },
656
+ {
657
+ "epoch": 1.3327954097184866,
658
+ "grad_norm": 0.2513235427794581,
659
+ "learning_rate": 9.554981817170655e-05,
660
+ "loss": 0.3912,
661
+ "step": 930
662
+ },
663
+ {
664
+ "epoch": 1.3471400394477318,
665
+ "grad_norm": 0.24955670786044107,
666
+ "learning_rate": 9.537635694448615e-05,
667
+ "loss": 0.3849,
668
+ "step": 940
669
+ },
670
+ {
671
+ "epoch": 1.3614846691769769,
672
+ "grad_norm": 0.24538389153554718,
673
+ "learning_rate": 9.519974307581404e-05,
674
+ "loss": 0.3867,
675
+ "step": 950
676
+ },
677
+ {
678
+ "epoch": 1.375829298906222,
679
+ "grad_norm": 0.25856641290644117,
680
+ "learning_rate": 9.50199888364021e-05,
681
+ "loss": 0.3899,
682
+ "step": 960
683
+ },
684
+ {
685
+ "epoch": 1.390173928635467,
686
+ "grad_norm": 0.26645029754281746,
687
+ "learning_rate": 9.483710671514777e-05,
688
+ "loss": 0.386,
689
+ "step": 970
690
+ },
691
+ {
692
+ "epoch": 1.4045185583647122,
693
+ "grad_norm": 0.25589965865278824,
694
+ "learning_rate": 9.465110941826622e-05,
695
+ "loss": 0.3856,
696
+ "step": 980
697
+ },
698
+ {
699
+ "epoch": 1.4188631880939573,
700
+ "grad_norm": 0.27815251555263987,
701
+ "learning_rate": 9.446200986840765e-05,
702
+ "loss": 0.3881,
703
+ "step": 990
704
+ },
705
+ {
706
+ "epoch": 1.4332078178232024,
707
+ "grad_norm": 0.26197920796578195,
708
+ "learning_rate": 9.426982120375943e-05,
709
+ "loss": 0.3878,
710
+ "step": 1000
711
+ },
712
+ {
713
+ "epoch": 1.4475524475524475,
714
+ "grad_norm": 0.2606524388643148,
715
+ "learning_rate": 9.407455677713328e-05,
716
+ "loss": 0.3883,
717
+ "step": 1010
718
+ },
719
+ {
720
+ "epoch": 1.4618970772816926,
721
+ "grad_norm": 0.2331343629588404,
722
+ "learning_rate": 9.387623015503753e-05,
723
+ "loss": 0.3848,
724
+ "step": 1020
725
+ },
726
+ {
727
+ "epoch": 1.4762417070109377,
728
+ "grad_norm": 0.25873984889230295,
729
+ "learning_rate": 9.367485511673462e-05,
730
+ "loss": 0.3895,
731
+ "step": 1030
732
+ },
733
+ {
734
+ "epoch": 1.4905863367401828,
735
+ "grad_norm": 0.2531065339256471,
736
+ "learning_rate": 9.347044565328367e-05,
737
+ "loss": 0.3937,
738
+ "step": 1040
739
+ },
740
+ {
741
+ "epoch": 1.504930966469428,
742
+ "grad_norm": 0.26767841128977615,
743
+ "learning_rate": 9.326301596656846e-05,
744
+ "loss": 0.3894,
745
+ "step": 1050
746
+ },
747
+ {
748
+ "epoch": 1.519275596198673,
749
+ "grad_norm": 0.2472066267101206,
750
+ "learning_rate": 9.30525804683107e-05,
751
+ "loss": 0.3889,
752
+ "step": 1060
753
+ },
754
+ {
755
+ "epoch": 1.5336202259279181,
756
+ "grad_norm": 0.24916114849718174,
757
+ "learning_rate": 9.283915377906875e-05,
758
+ "loss": 0.3874,
759
+ "step": 1070
760
+ },
761
+ {
762
+ "epoch": 1.5479648556571632,
763
+ "grad_norm": 0.24586564647507672,
764
+ "learning_rate": 9.262275072722181e-05,
765
+ "loss": 0.3899,
766
+ "step": 1080
767
+ },
768
+ {
769
+ "epoch": 1.5623094853864083,
770
+ "grad_norm": 0.24194199620674006,
771
+ "learning_rate": 9.240338634793969e-05,
772
+ "loss": 0.3867,
773
+ "step": 1090
774
+ },
775
+ {
776
+ "epoch": 1.5766541151156535,
777
+ "grad_norm": 0.24712089444412166,
778
+ "learning_rate": 9.218107588213813e-05,
779
+ "loss": 0.3902,
780
+ "step": 1100
781
+ },
782
+ {
783
+ "epoch": 1.5909987448448986,
784
+ "grad_norm": 0.24987071841082312,
785
+ "learning_rate": 9.195583477542009e-05,
786
+ "loss": 0.3851,
787
+ "step": 1110
788
+ },
789
+ {
790
+ "epoch": 1.6053433745741437,
791
+ "grad_norm": 0.2453499914136973,
792
+ "learning_rate": 9.172767867700236e-05,
793
+ "loss": 0.3906,
794
+ "step": 1120
795
+ },
796
+ {
797
+ "epoch": 1.6196880043033888,
798
+ "grad_norm": 0.2453362805106032,
799
+ "learning_rate": 9.149662343862851e-05,
800
+ "loss": 0.3905,
801
+ "step": 1130
802
+ },
803
+ {
804
+ "epoch": 1.6340326340326339,
805
+ "grad_norm": 0.23102523441076062,
806
+ "learning_rate": 9.126268511346744e-05,
807
+ "loss": 0.3903,
808
+ "step": 1140
809
+ },
810
+ {
811
+ "epoch": 1.648377263761879,
812
+ "grad_norm": 0.2542501707506408,
813
+ "learning_rate": 9.102587995499807e-05,
814
+ "loss": 0.3953,
815
+ "step": 1150
816
+ },
817
+ {
818
+ "epoch": 1.6627218934911243,
819
+ "grad_norm": 0.23285474972918488,
820
+ "learning_rate": 9.078622441588009e-05,
821
+ "loss": 0.391,
822
+ "step": 1160
823
+ },
824
+ {
825
+ "epoch": 1.6770665232203694,
826
+ "grad_norm": 0.24565957619352327,
827
+ "learning_rate": 9.054373514681085e-05,
828
+ "loss": 0.3923,
829
+ "step": 1170
830
+ },
831
+ {
832
+ "epoch": 1.6914111529496145,
833
+ "grad_norm": 0.2506739557436684,
834
+ "learning_rate": 9.029842899536853e-05,
835
+ "loss": 0.3909,
836
+ "step": 1180
837
+ },
838
+ {
839
+ "epoch": 1.7057557826788596,
840
+ "grad_norm": 0.2441587365940751,
841
+ "learning_rate": 9.005032300484162e-05,
842
+ "loss": 0.3915,
843
+ "step": 1190
844
+ },
845
+ {
846
+ "epoch": 1.7201004124081047,
847
+ "grad_norm": 0.26421110183322566,
848
+ "learning_rate": 8.979943441304473e-05,
849
+ "loss": 0.3904,
850
+ "step": 1200
851
+ },
852
+ {
853
+ "epoch": 1.7344450421373498,
854
+ "grad_norm": 0.24194171269463752,
855
+ "learning_rate": 8.954578065112107e-05,
856
+ "loss": 0.3892,
857
+ "step": 1210
858
+ },
859
+ {
860
+ "epoch": 1.748789671866595,
861
+ "grad_norm": 0.23054663152441476,
862
+ "learning_rate": 8.928937934233123e-05,
863
+ "loss": 0.3907,
864
+ "step": 1220
865
+ },
866
+ {
867
+ "epoch": 1.76313430159584,
868
+ "grad_norm": 0.2369813966398001,
869
+ "learning_rate": 8.903024830082887e-05,
870
+ "loss": 0.3849,
871
+ "step": 1230
872
+ },
873
+ {
874
+ "epoch": 1.7774789313250852,
875
+ "grad_norm": 0.24008220076352446,
876
+ "learning_rate": 8.876840553042296e-05,
877
+ "loss": 0.3904,
878
+ "step": 1240
879
+ },
880
+ {
881
+ "epoch": 1.7918235610543303,
882
+ "grad_norm": 0.23428608617416669,
883
+ "learning_rate": 8.850386922332696e-05,
884
+ "loss": 0.387,
885
+ "step": 1250
886
+ },
887
+ {
888
+ "epoch": 1.8061681907835754,
889
+ "grad_norm": 0.23331291847215246,
890
+ "learning_rate": 8.823665775889486e-05,
891
+ "loss": 0.3909,
892
+ "step": 1260
893
+ },
894
+ {
895
+ "epoch": 1.8205128205128205,
896
+ "grad_norm": 0.23850242149763548,
897
+ "learning_rate": 8.796678970234427e-05,
898
+ "loss": 0.3833,
899
+ "step": 1270
900
+ },
901
+ {
902
+ "epoch": 1.8348574502420656,
903
+ "grad_norm": 0.2219682422982644,
904
+ "learning_rate": 8.769428380346642e-05,
905
+ "loss": 0.3845,
906
+ "step": 1280
907
+ },
908
+ {
909
+ "epoch": 1.8492020799713107,
910
+ "grad_norm": 0.22216238994388604,
911
+ "learning_rate": 8.741915899532362e-05,
912
+ "loss": 0.3865,
913
+ "step": 1290
914
+ },
915
+ {
916
+ "epoch": 1.8635467097005558,
917
+ "grad_norm": 0.22824929990219722,
918
+ "learning_rate": 8.714143439293376e-05,
919
+ "loss": 0.3852,
920
+ "step": 1300
921
+ },
922
+ {
923
+ "epoch": 1.8778913394298011,
924
+ "grad_norm": 0.24280880504252028,
925
+ "learning_rate": 8.686112929194226e-05,
926
+ "loss": 0.3861,
927
+ "step": 1310
928
+ },
929
+ {
930
+ "epoch": 1.8922359691590462,
931
+ "grad_norm": 0.24001704017165865,
932
+ "learning_rate": 8.657826316728142e-05,
933
+ "loss": 0.3908,
934
+ "step": 1320
935
+ },
936
+ {
937
+ "epoch": 1.9065805988882913,
938
+ "grad_norm": 0.22100828767921185,
939
+ "learning_rate": 8.62928556718174e-05,
940
+ "loss": 0.3871,
941
+ "step": 1330
942
+ },
943
+ {
944
+ "epoch": 1.9209252286175365,
945
+ "grad_norm": 0.22202012109824457,
946
+ "learning_rate": 8.600492663498477e-05,
947
+ "loss": 0.3834,
948
+ "step": 1340
949
+ },
950
+ {
951
+ "epoch": 1.9352698583467816,
952
+ "grad_norm": 0.21529127705519435,
953
+ "learning_rate": 8.571449606140883e-05,
954
+ "loss": 0.388,
955
+ "step": 1350
956
+ },
957
+ {
958
+ "epoch": 1.9496144880760267,
959
+ "grad_norm": 0.23391440077905082,
960
+ "learning_rate": 8.542158412951563e-05,
961
+ "loss": 0.3844,
962
+ "step": 1360
963
+ },
964
+ {
965
+ "epoch": 1.9639591178052718,
966
+ "grad_norm": 0.2331711540562185,
967
+ "learning_rate": 8.512621119013013e-05,
968
+ "loss": 0.393,
969
+ "step": 1370
970
+ },
971
+ {
972
+ "epoch": 1.9783037475345169,
973
+ "grad_norm": 0.23305451446876246,
974
+ "learning_rate": 8.482839776506232e-05,
975
+ "loss": 0.3837,
976
+ "step": 1380
977
+ },
978
+ {
979
+ "epoch": 1.992648377263762,
980
+ "grad_norm": 0.24517430064973736,
981
+ "learning_rate": 8.452816454568124e-05,
982
+ "loss": 0.3852,
983
+ "step": 1390
984
+ },
985
+ {
986
+ "epoch": 2.005737851891698,
987
+ "grad_norm": 0.27916951560917247,
988
+ "learning_rate": 8.422553239147754e-05,
989
+ "loss": 0.2799,
990
+ "step": 1400
991
+ },
992
+ {
993
+ "epoch": 2.020082481620943,
994
+ "grad_norm": 0.23593724272097047,
995
+ "learning_rate": 8.392052232861411e-05,
996
+ "loss": 0.201,
997
+ "step": 1410
998
+ },
999
+ {
1000
+ "epoch": 2.034427111350188,
1001
+ "grad_norm": 0.23512809512185134,
1002
+ "learning_rate": 8.361315554846534e-05,
1003
+ "loss": 0.1983,
1004
+ "step": 1420
1005
+ },
1006
+ {
1007
+ "epoch": 2.0487717410794333,
1008
+ "grad_norm": 0.2286549447255431,
1009
+ "learning_rate": 8.330345340614471e-05,
1010
+ "loss": 0.1942,
1011
+ "step": 1430
1012
+ },
1013
+ {
1014
+ "epoch": 2.0631163708086784,
1015
+ "grad_norm": 0.24844506458021867,
1016
+ "learning_rate": 8.299143741902111e-05,
1017
+ "loss": 0.1943,
1018
+ "step": 1440
1019
+ },
1020
+ {
1021
+ "epoch": 2.0774610005379235,
1022
+ "grad_norm": 0.25585326293058985,
1023
+ "learning_rate": 8.267712926522389e-05,
1024
+ "loss": 0.1993,
1025
+ "step": 1450
1026
+ },
1027
+ {
1028
+ "epoch": 2.0918056302671686,
1029
+ "grad_norm": 0.2421387690266048,
1030
+ "learning_rate": 8.236055078213666e-05,
1031
+ "loss": 0.1965,
1032
+ "step": 1460
1033
+ },
1034
+ {
1035
+ "epoch": 2.1061502599964137,
1036
+ "grad_norm": 0.24707973152402415,
1037
+ "learning_rate": 8.204172396488013e-05,
1038
+ "loss": 0.1992,
1039
+ "step": 1470
1040
+ },
1041
+ {
1042
+ "epoch": 2.120494889725659,
1043
+ "grad_norm": 0.23509099311770917,
1044
+ "learning_rate": 8.172067096478395e-05,
1045
+ "loss": 0.2008,
1046
+ "step": 1480
1047
+ },
1048
+ {
1049
+ "epoch": 2.134839519454904,
1050
+ "grad_norm": 0.23605150518346998,
1051
+ "learning_rate": 8.139741408784764e-05,
1052
+ "loss": 0.2019,
1053
+ "step": 1490
1054
+ },
1055
+ {
1056
+ "epoch": 2.149184149184149,
1057
+ "grad_norm": 0.2546177191590111,
1058
+ "learning_rate": 8.107197579319082e-05,
1059
+ "loss": 0.2053,
1060
+ "step": 1500
1061
+ },
1062
+ {
1063
+ "epoch": 2.163528778913394,
1064
+ "grad_norm": 0.2353676242323245,
1065
+ "learning_rate": 8.074437869149288e-05,
1066
+ "loss": 0.204,
1067
+ "step": 1510
1068
+ },
1069
+ {
1070
+ "epoch": 2.1778734086426392,
1071
+ "grad_norm": 0.23401952893152606,
1072
+ "learning_rate": 8.041464554342197e-05,
1073
+ "loss": 0.2036,
1074
+ "step": 1520
1075
+ },
1076
+ {
1077
+ "epoch": 2.1922180383718843,
1078
+ "grad_norm": 0.23141975512545726,
1079
+ "learning_rate": 8.008279925805366e-05,
1080
+ "loss": 0.2033,
1081
+ "step": 1530
1082
+ },
1083
+ {
1084
+ "epoch": 2.2065626681011294,
1085
+ "grad_norm": 0.23587920943899052,
1086
+ "learning_rate": 7.974886289127927e-05,
1087
+ "loss": 0.2068,
1088
+ "step": 1540
1089
+ },
1090
+ {
1091
+ "epoch": 2.2209072978303745,
1092
+ "grad_norm": 0.2394814609218661,
1093
+ "learning_rate": 7.941285964420407e-05,
1094
+ "loss": 0.2049,
1095
+ "step": 1550
1096
+ },
1097
+ {
1098
+ "epoch": 2.23525192755962,
1099
+ "grad_norm": 0.2389110148718096,
1100
+ "learning_rate": 7.907481286153516e-05,
1101
+ "loss": 0.2116,
1102
+ "step": 1560
1103
+ },
1104
+ {
1105
+ "epoch": 2.249596557288865,
1106
+ "grad_norm": 0.2282395291006806,
1107
+ "learning_rate": 7.873474602995973e-05,
1108
+ "loss": 0.2088,
1109
+ "step": 1570
1110
+ },
1111
+ {
1112
+ "epoch": 2.2639411870181103,
1113
+ "grad_norm": 0.23275397540700887,
1114
+ "learning_rate": 7.839268277651311e-05,
1115
+ "loss": 0.2092,
1116
+ "step": 1580
1117
+ },
1118
+ {
1119
+ "epoch": 2.2782858167473554,
1120
+ "grad_norm": 0.22624466416184327,
1121
+ "learning_rate": 7.80486468669373e-05,
1122
+ "loss": 0.2088,
1123
+ "step": 1590
1124
+ },
1125
+ {
1126
+ "epoch": 2.2926304464766005,
1127
+ "grad_norm": 0.23126585599149074,
1128
+ "learning_rate": 7.770266220402977e-05,
1129
+ "loss": 0.2117,
1130
+ "step": 1600
1131
+ },
1132
+ {
1133
+ "epoch": 2.3069750762058456,
1134
+ "grad_norm": 0.226948134461606,
1135
+ "learning_rate": 7.735475282598271e-05,
1136
+ "loss": 0.2097,
1137
+ "step": 1610
1138
+ },
1139
+ {
1140
+ "epoch": 2.3213197059350907,
1141
+ "grad_norm": 0.22673465714008167,
1142
+ "learning_rate": 7.700494290471296e-05,
1143
+ "loss": 0.2104,
1144
+ "step": 1620
1145
+ },
1146
+ {
1147
+ "epoch": 2.335664335664336,
1148
+ "grad_norm": 0.2556824784968339,
1149
+ "learning_rate": 7.665325674418264e-05,
1150
+ "loss": 0.2136,
1151
+ "step": 1630
1152
+ },
1153
+ {
1154
+ "epoch": 2.350008965393581,
1155
+ "grad_norm": 0.25025658975825976,
1156
+ "learning_rate": 7.629971877871039e-05,
1157
+ "loss": 0.2084,
1158
+ "step": 1640
1159
+ },
1160
+ {
1161
+ "epoch": 2.364353595122826,
1162
+ "grad_norm": 0.22536490579422702,
1163
+ "learning_rate": 7.594435357127399e-05,
1164
+ "loss": 0.2089,
1165
+ "step": 1650
1166
+ },
1167
+ {
1168
+ "epoch": 2.378698224852071,
1169
+ "grad_norm": 0.2258065984765025,
1170
+ "learning_rate": 7.558718581180355e-05,
1171
+ "loss": 0.2067,
1172
+ "step": 1660
1173
+ },
1174
+ {
1175
+ "epoch": 2.3930428545813163,
1176
+ "grad_norm": 0.2464593742203822,
1177
+ "learning_rate": 7.522824031546629e-05,
1178
+ "loss": 0.2137,
1179
+ "step": 1670
1180
+ },
1181
+ {
1182
+ "epoch": 2.4073874843105614,
1183
+ "grad_norm": 0.24123071412945177,
1184
+ "learning_rate": 7.486754202094229e-05,
1185
+ "loss": 0.2115,
1186
+ "step": 1680
1187
+ },
1188
+ {
1189
+ "epoch": 2.4217321140398065,
1190
+ "grad_norm": 0.23105649429700748,
1191
+ "learning_rate": 7.450511598869194e-05,
1192
+ "loss": 0.2138,
1193
+ "step": 1690
1194
+ },
1195
+ {
1196
+ "epoch": 2.4360767437690516,
1197
+ "grad_norm": 0.22955721039077792,
1198
+ "learning_rate": 7.414098739921471e-05,
1199
+ "loss": 0.2125,
1200
+ "step": 1700
1201
+ },
1202
+ {
1203
+ "epoch": 2.4504213734982967,
1204
+ "grad_norm": 0.23154193335740872,
1205
+ "learning_rate": 7.377518155129973e-05,
1206
+ "loss": 0.2183,
1207
+ "step": 1710
1208
+ },
1209
+ {
1210
+ "epoch": 2.464766003227542,
1211
+ "grad_norm": 0.2340236121998045,
1212
+ "learning_rate": 7.340772386026801e-05,
1213
+ "loss": 0.2157,
1214
+ "step": 1720
1215
+ },
1216
+ {
1217
+ "epoch": 2.479110632956787,
1218
+ "grad_norm": 0.2250255353665983,
1219
+ "learning_rate": 7.303863985620676e-05,
1220
+ "loss": 0.2123,
1221
+ "step": 1730
1222
+ },
1223
+ {
1224
+ "epoch": 2.493455262686032,
1225
+ "grad_norm": 0.2283114308365594,
1226
+ "learning_rate": 7.266795518219548e-05,
1227
+ "loss": 0.2135,
1228
+ "step": 1740
1229
+ },
1230
+ {
1231
+ "epoch": 2.507799892415277,
1232
+ "grad_norm": 0.23546636465212323,
1233
+ "learning_rate": 7.22956955925245e-05,
1234
+ "loss": 0.214,
1235
+ "step": 1750
1236
+ },
1237
+ {
1238
+ "epoch": 2.5221445221445222,
1239
+ "grad_norm": 0.23275268765839288,
1240
+ "learning_rate": 7.192188695090545e-05,
1241
+ "loss": 0.2156,
1242
+ "step": 1760
1243
+ },
1244
+ {
1245
+ "epoch": 2.5364891518737673,
1246
+ "grad_norm": 0.2457436947556184,
1247
+ "learning_rate": 7.154655522867452e-05,
1248
+ "loss": 0.2189,
1249
+ "step": 1770
1250
+ },
1251
+ {
1252
+ "epoch": 2.5508337816030124,
1253
+ "grad_norm": 0.2385729628030818,
1254
+ "learning_rate": 7.116972650298782e-05,
1255
+ "loss": 0.2148,
1256
+ "step": 1780
1257
+ },
1258
+ {
1259
+ "epoch": 2.5651784113322575,
1260
+ "grad_norm": 0.2382827317725779,
1261
+ "learning_rate": 7.079142695500975e-05,
1262
+ "loss": 0.2127,
1263
+ "step": 1790
1264
+ },
1265
+ {
1266
+ "epoch": 2.5795230410615027,
1267
+ "grad_norm": 0.22496477508883403,
1268
+ "learning_rate": 7.041168286809397e-05,
1269
+ "loss": 0.2156,
1270
+ "step": 1800
1271
+ },
1272
+ {
1273
+ "epoch": 2.5938676707907478,
1274
+ "grad_norm": 0.2337756123669142,
1275
+ "learning_rate": 7.00305206259572e-05,
1276
+ "loss": 0.2163,
1277
+ "step": 1810
1278
+ },
1279
+ {
1280
+ "epoch": 2.608212300519993,
1281
+ "grad_norm": 0.23547675501490803,
1282
+ "learning_rate": 6.964796671084631e-05,
1283
+ "loss": 0.213,
1284
+ "step": 1820
1285
+ },
1286
+ {
1287
+ "epoch": 2.622556930249238,
1288
+ "grad_norm": 0.236949625863052,
1289
+ "learning_rate": 6.926404770169819e-05,
1290
+ "loss": 0.2108,
1291
+ "step": 1830
1292
+ },
1293
+ {
1294
+ "epoch": 2.636901559978483,
1295
+ "grad_norm": 0.22775808389184637,
1296
+ "learning_rate": 6.887879027229332e-05,
1297
+ "loss": 0.2131,
1298
+ "step": 1840
1299
+ },
1300
+ {
1301
+ "epoch": 2.651246189707728,
1302
+ "grad_norm": 0.25558095929144115,
1303
+ "learning_rate": 6.84922211894024e-05,
1304
+ "loss": 0.2146,
1305
+ "step": 1850
1306
+ },
1307
+ {
1308
+ "epoch": 2.6655908194369733,
1309
+ "grad_norm": 0.23865636643565702,
1310
+ "learning_rate": 6.810436731092671e-05,
1311
+ "loss": 0.2154,
1312
+ "step": 1860
1313
+ },
1314
+ {
1315
+ "epoch": 2.6799354491662184,
1316
+ "grad_norm": 0.23347390914436725,
1317
+ "learning_rate": 6.771525558403203e-05,
1318
+ "loss": 0.2145,
1319
+ "step": 1870
1320
+ },
1321
+ {
1322
+ "epoch": 2.6942800788954635,
1323
+ "grad_norm": 0.2311770851119529,
1324
+ "learning_rate": 6.73249130432765e-05,
1325
+ "loss": 0.2112,
1326
+ "step": 1880
1327
+ },
1328
+ {
1329
+ "epoch": 2.7086247086247086,
1330
+ "grad_norm": 0.2326246785839781,
1331
+ "learning_rate": 6.69333668087323e-05,
1332
+ "loss": 0.2133,
1333
+ "step": 1890
1334
+ },
1335
+ {
1336
+ "epoch": 2.7229693383539537,
1337
+ "grad_norm": 0.23563376415545254,
1338
+ "learning_rate": 6.654064408410132e-05,
1339
+ "loss": 0.2141,
1340
+ "step": 1900
1341
+ },
1342
+ {
1343
+ "epoch": 2.737313968083199,
1344
+ "grad_norm": 0.2298522950109398,
1345
+ "learning_rate": 6.614677215482527e-05,
1346
+ "loss": 0.2142,
1347
+ "step": 1910
1348
+ },
1349
+ {
1350
+ "epoch": 2.751658597812444,
1351
+ "grad_norm": 0.2364865163676101,
1352
+ "learning_rate": 6.57517783861898e-05,
1353
+ "loss": 0.2127,
1354
+ "step": 1920
1355
+ },
1356
+ {
1357
+ "epoch": 2.766003227541689,
1358
+ "grad_norm": 0.22837021217881728,
1359
+ "learning_rate": 6.535569022142335e-05,
1360
+ "loss": 0.2145,
1361
+ "step": 1930
1362
+ },
1363
+ {
1364
+ "epoch": 2.780347857270934,
1365
+ "grad_norm": 0.22749769763881308,
1366
+ "learning_rate": 6.495853517979035e-05,
1367
+ "loss": 0.2106,
1368
+ "step": 1940
1369
+ },
1370
+ {
1371
+ "epoch": 2.7946924870001792,
1372
+ "grad_norm": 0.21764981978938533,
1373
+ "learning_rate": 6.456034085467935e-05,
1374
+ "loss": 0.2125,
1375
+ "step": 1950
1376
+ },
1377
+ {
1378
+ "epoch": 2.8090371167294244,
1379
+ "grad_norm": 0.22774012921821585,
1380
+ "learning_rate": 6.416113491168581e-05,
1381
+ "loss": 0.213,
1382
+ "step": 1960
1383
+ },
1384
+ {
1385
+ "epoch": 2.8233817464586695,
1386
+ "grad_norm": 0.22793686074861258,
1387
+ "learning_rate": 6.376094508668999e-05,
1388
+ "loss": 0.2116,
1389
+ "step": 1970
1390
+ },
1391
+ {
1392
+ "epoch": 2.8377263761879146,
1393
+ "grad_norm": 0.24345345462191187,
1394
+ "learning_rate": 6.335979918392999e-05,
1395
+ "loss": 0.213,
1396
+ "step": 1980
1397
+ },
1398
+ {
1399
+ "epoch": 2.8520710059171597,
1400
+ "grad_norm": 0.230566718186529,
1401
+ "learning_rate": 6.295772507406982e-05,
1402
+ "loss": 0.2123,
1403
+ "step": 1990
1404
+ },
1405
+ {
1406
+ "epoch": 2.866415635646405,
1407
+ "grad_norm": 0.23922165240449358,
1408
+ "learning_rate": 6.255475069226326e-05,
1409
+ "loss": 0.211,
1410
+ "step": 2000
1411
+ },
1412
+ {
1413
+ "epoch": 2.88076026537565,
1414
+ "grad_norm": 0.22058336484670613,
1415
+ "learning_rate": 6.21509040362127e-05,
1416
+ "loss": 0.2122,
1417
+ "step": 2010
1418
+ },
1419
+ {
1420
+ "epoch": 2.895104895104895,
1421
+ "grad_norm": 0.2272702011851071,
1422
+ "learning_rate": 6.174621316422417e-05,
1423
+ "loss": 0.2147,
1424
+ "step": 2020
1425
+ },
1426
+ {
1427
+ "epoch": 2.90944952483414,
1428
+ "grad_norm": 0.23799805104509125,
1429
+ "learning_rate": 6.134070619325774e-05,
1430
+ "loss": 0.212,
1431
+ "step": 2030
1432
+ },
1433
+ {
1434
+ "epoch": 2.923794154563385,
1435
+ "grad_norm": 0.24608349983752625,
1436
+ "learning_rate": 6.0934411296974184e-05,
1437
+ "loss": 0.2122,
1438
+ "step": 2040
1439
+ },
1440
+ {
1441
+ "epoch": 2.9381387842926303,
1442
+ "grad_norm": 0.23079480496683127,
1443
+ "learning_rate": 6.052735670377736e-05,
1444
+ "loss": 0.211,
1445
+ "step": 2050
1446
+ },
1447
+ {
1448
+ "epoch": 2.9524834140218754,
1449
+ "grad_norm": 0.22680559271715478,
1450
+ "learning_rate": 6.0119570694853155e-05,
1451
+ "loss": 0.2102,
1452
+ "step": 2060
1453
+ },
1454
+ {
1455
+ "epoch": 2.9668280437511205,
1456
+ "grad_norm": 0.22760761484882805,
1457
+ "learning_rate": 5.97110816022044e-05,
1458
+ "loss": 0.2113,
1459
+ "step": 2070
1460
+ },
1461
+ {
1462
+ "epoch": 2.9811726734803656,
1463
+ "grad_norm": 0.23303799910976278,
1464
+ "learning_rate": 5.930191780668258e-05,
1465
+ "loss": 0.2088,
1466
+ "step": 2080
1467
+ },
1468
+ {
1469
+ "epoch": 2.9955173032096107,
1470
+ "grad_norm": 0.22946738031807773,
1471
+ "learning_rate": 5.88921077360159e-05,
1472
+ "loss": 0.2097,
1473
+ "step": 2090
1474
+ },
1475
+ {
1476
+ "epoch": 3.008606777837547,
1477
+ "grad_norm": 0.2697620900381124,
1478
+ "learning_rate": 5.848167986283421e-05,
1479
+ "loss": 0.1134,
1480
+ "step": 2100
1481
+ },
1482
+ {
1483
+ "epoch": 3.0229514075667923,
1484
+ "grad_norm": 0.1885938841096422,
1485
+ "learning_rate": 5.807066270269084e-05,
1486
+ "loss": 0.0763,
1487
+ "step": 2110
1488
+ },
1489
+ {
1490
+ "epoch": 3.0372960372960374,
1491
+ "grad_norm": 0.214693696805492,
1492
+ "learning_rate": 5.765908481208139e-05,
1493
+ "loss": 0.0756,
1494
+ "step": 2120
1495
+ },
1496
+ {
1497
+ "epoch": 3.0516406670252825,
1498
+ "grad_norm": 0.2339101871402584,
1499
+ "learning_rate": 5.724697478645963e-05,
1500
+ "loss": 0.0744,
1501
+ "step": 2130
1502
+ },
1503
+ {
1504
+ "epoch": 3.0659852967545276,
1505
+ "grad_norm": 0.1971755620952271,
1506
+ "learning_rate": 5.6834361258250844e-05,
1507
+ "loss": 0.072,
1508
+ "step": 2140
1509
+ },
1510
+ {
1511
+ "epoch": 3.0803299264837727,
1512
+ "grad_norm": 0.1981153430750115,
1513
+ "learning_rate": 5.642127289486246e-05,
1514
+ "loss": 0.0748,
1515
+ "step": 2150
1516
+ },
1517
+ {
1518
+ "epoch": 3.094674556213018,
1519
+ "grad_norm": 0.2172902671287561,
1520
+ "learning_rate": 5.600773839669237e-05,
1521
+ "loss": 0.0726,
1522
+ "step": 2160
1523
+ },
1524
+ {
1525
+ "epoch": 3.109019185942263,
1526
+ "grad_norm": 0.19669334061877888,
1527
+ "learning_rate": 5.559378649513478e-05,
1528
+ "loss": 0.0733,
1529
+ "step": 2170
1530
+ },
1531
+ {
1532
+ "epoch": 3.123363815671508,
1533
+ "grad_norm": 0.21027113699329436,
1534
+ "learning_rate": 5.517944595058413e-05,
1535
+ "loss": 0.0746,
1536
+ "step": 2180
1537
+ },
1538
+ {
1539
+ "epoch": 3.137708445400753,
1540
+ "grad_norm": 0.20204087893287273,
1541
+ "learning_rate": 5.476474555043688e-05,
1542
+ "loss": 0.0748,
1543
+ "step": 2190
1544
+ },
1545
+ {
1546
+ "epoch": 3.152053075129998,
1547
+ "grad_norm": 0.20638588917150788,
1548
+ "learning_rate": 5.4349714107091335e-05,
1549
+ "loss": 0.0744,
1550
+ "step": 2200
1551
+ },
1552
+ {
1553
+ "epoch": 3.1663977048592433,
1554
+ "grad_norm": 0.20367882761147596,
1555
+ "learning_rate": 5.393438045594595e-05,
1556
+ "loss": 0.0755,
1557
+ "step": 2210
1558
+ },
1559
+ {
1560
+ "epoch": 3.1807423345884884,
1561
+ "grad_norm": 0.20836979312681028,
1562
+ "learning_rate": 5.351877345339583e-05,
1563
+ "loss": 0.076,
1564
+ "step": 2220
1565
+ },
1566
+ {
1567
+ "epoch": 3.1950869643177335,
1568
+ "grad_norm": 0.19643695987807314,
1569
+ "learning_rate": 5.310292197482791e-05,
1570
+ "loss": 0.0733,
1571
+ "step": 2230
1572
+ },
1573
+ {
1574
+ "epoch": 3.2094315940469786,
1575
+ "grad_norm": 0.20621763947145422,
1576
+ "learning_rate": 5.268685491261472e-05,
1577
+ "loss": 0.075,
1578
+ "step": 2240
1579
+ },
1580
+ {
1581
+ "epoch": 3.2237762237762237,
1582
+ "grad_norm": 0.20777873086593704,
1583
+ "learning_rate": 5.227060117410702e-05,
1584
+ "loss": 0.0746,
1585
+ "step": 2250
1586
+ },
1587
+ {
1588
+ "epoch": 3.238120853505469,
1589
+ "grad_norm": 0.2021910407099938,
1590
+ "learning_rate": 5.185418967962543e-05,
1591
+ "loss": 0.0747,
1592
+ "step": 2260
1593
+ },
1594
+ {
1595
+ "epoch": 3.252465483234714,
1596
+ "grad_norm": 0.2016612434414281,
1597
+ "learning_rate": 5.143764936045106e-05,
1598
+ "loss": 0.0743,
1599
+ "step": 2270
1600
+ },
1601
+ {
1602
+ "epoch": 3.266810112963959,
1603
+ "grad_norm": 0.2180992659409795,
1604
+ "learning_rate": 5.1021009156815414e-05,
1605
+ "loss": 0.0744,
1606
+ "step": 2280
1607
+ },
1608
+ {
1609
+ "epoch": 3.281154742693204,
1610
+ "grad_norm": 0.2056058145565962,
1611
+ "learning_rate": 5.060429801588983e-05,
1612
+ "loss": 0.0744,
1613
+ "step": 2290
1614
+ },
1615
+ {
1616
+ "epoch": 3.2954993724224493,
1617
+ "grad_norm": 0.20164051829762908,
1618
+ "learning_rate": 5.018754488977409e-05,
1619
+ "loss": 0.0745,
1620
+ "step": 2300
1621
+ },
1622
+ {
1623
+ "epoch": 3.3098440021516944,
1624
+ "grad_norm": 0.2026538165933443,
1625
+ "learning_rate": 4.9770778733485065e-05,
1626
+ "loss": 0.074,
1627
+ "step": 2310
1628
+ },
1629
+ {
1630
+ "epoch": 3.3241886318809395,
1631
+ "grad_norm": 0.20427324673762595,
1632
+ "learning_rate": 4.935402850294494e-05,
1633
+ "loss": 0.0739,
1634
+ "step": 2320
1635
+ },
1636
+ {
1637
+ "epoch": 3.3385332616101846,
1638
+ "grad_norm": 0.20831211218540635,
1639
+ "learning_rate": 4.893732315296942e-05,
1640
+ "loss": 0.0748,
1641
+ "step": 2330
1642
+ },
1643
+ {
1644
+ "epoch": 3.3528778913394297,
1645
+ "grad_norm": 0.20740018500070947,
1646
+ "learning_rate": 4.852069163525595e-05,
1647
+ "loss": 0.0737,
1648
+ "step": 2340
1649
+ },
1650
+ {
1651
+ "epoch": 3.367222521068675,
1652
+ "grad_norm": 0.20060155886370676,
1653
+ "learning_rate": 4.810416289637234e-05,
1654
+ "loss": 0.0729,
1655
+ "step": 2350
1656
+ },
1657
+ {
1658
+ "epoch": 3.38156715079792,
1659
+ "grad_norm": 0.199826847154071,
1660
+ "learning_rate": 4.7687765875745574e-05,
1661
+ "loss": 0.0739,
1662
+ "step": 2360
1663
+ },
1664
+ {
1665
+ "epoch": 3.395911780527165,
1666
+ "grad_norm": 0.20063705204581495,
1667
+ "learning_rate": 4.727152950365117e-05,
1668
+ "loss": 0.0737,
1669
+ "step": 2370
1670
+ },
1671
+ {
1672
+ "epoch": 3.41025641025641,
1673
+ "grad_norm": 0.20947972363514977,
1674
+ "learning_rate": 4.685548269920312e-05,
1675
+ "loss": 0.0736,
1676
+ "step": 2380
1677
+ },
1678
+ {
1679
+ "epoch": 3.4246010399856552,
1680
+ "grad_norm": 0.2006701925989043,
1681
+ "learning_rate": 4.643965436834474e-05,
1682
+ "loss": 0.075,
1683
+ "step": 2390
1684
+ },
1685
+ {
1686
+ "epoch": 3.4389456697149003,
1687
+ "grad_norm": 0.20335025504735554,
1688
+ "learning_rate": 4.6024073401840336e-05,
1689
+ "loss": 0.0745,
1690
+ "step": 2400
1691
+ },
1692
+ {
1693
+ "epoch": 3.4532902994441455,
1694
+ "grad_norm": 0.2192162565442083,
1695
+ "learning_rate": 4.560876867326791e-05,
1696
+ "loss": 0.0738,
1697
+ "step": 2410
1698
+ },
1699
+ {
1700
+ "epoch": 3.4676349291733906,
1701
+ "grad_norm": 0.19858055523329815,
1702
+ "learning_rate": 4.5193769037013066e-05,
1703
+ "loss": 0.0732,
1704
+ "step": 2420
1705
+ },
1706
+ {
1707
+ "epoch": 3.4819795589026357,
1708
+ "grad_norm": 0.20485303414115183,
1709
+ "learning_rate": 4.477910332626438e-05,
1710
+ "loss": 0.0728,
1711
+ "step": 2430
1712
+ },
1713
+ {
1714
+ "epoch": 3.4963241886318808,
1715
+ "grad_norm": 0.19011594248287844,
1716
+ "learning_rate": 4.4364800351010066e-05,
1717
+ "loss": 0.0726,
1718
+ "step": 2440
1719
+ },
1720
+ {
1721
+ "epoch": 3.5106688183611263,
1722
+ "grad_norm": 0.20410603253979742,
1723
+ "learning_rate": 4.395088889603633e-05,
1724
+ "loss": 0.0736,
1725
+ "step": 2450
1726
+ },
1727
+ {
1728
+ "epoch": 3.5250134480903714,
1729
+ "grad_norm": 0.1994983957599032,
1730
+ "learning_rate": 4.353739771892746e-05,
1731
+ "loss": 0.073,
1732
+ "step": 2460
1733
+ },
1734
+ {
1735
+ "epoch": 3.5393580778196165,
1736
+ "grad_norm": 0.20349060401414618,
1737
+ "learning_rate": 4.312435554806787e-05,
1738
+ "loss": 0.0736,
1739
+ "step": 2470
1740
+ },
1741
+ {
1742
+ "epoch": 3.5537027075488616,
1743
+ "grad_norm": 0.20221336765718947,
1744
+ "learning_rate": 4.271179108064605e-05,
1745
+ "loss": 0.0713,
1746
+ "step": 2480
1747
+ },
1748
+ {
1749
+ "epoch": 3.5680473372781067,
1750
+ "grad_norm": 0.1920539935100462,
1751
+ "learning_rate": 4.229973298066083e-05,
1752
+ "loss": 0.0714,
1753
+ "step": 2490
1754
+ },
1755
+ {
1756
+ "epoch": 3.582391967007352,
1757
+ "grad_norm": 0.18514594535819984,
1758
+ "learning_rate": 4.188820987692981e-05,
1759
+ "loss": 0.0716,
1760
+ "step": 2500
1761
+ },
1762
+ {
1763
+ "epoch": 3.596736596736597,
1764
+ "grad_norm": 0.19390555703637974,
1765
+ "learning_rate": 4.1477250361100317e-05,
1766
+ "loss": 0.072,
1767
+ "step": 2510
1768
+ },
1769
+ {
1770
+ "epoch": 3.611081226465842,
1771
+ "grad_norm": 0.19881724163942532,
1772
+ "learning_rate": 4.106688298566295e-05,
1773
+ "loss": 0.0722,
1774
+ "step": 2520
1775
+ },
1776
+ {
1777
+ "epoch": 3.625425856195087,
1778
+ "grad_norm": 0.19864848134388496,
1779
+ "learning_rate": 4.065713626196778e-05,
1780
+ "loss": 0.0697,
1781
+ "step": 2530
1782
+ },
1783
+ {
1784
+ "epoch": 3.6397704859243323,
1785
+ "grad_norm": 0.20964033399772472,
1786
+ "learning_rate": 4.0248038658243515e-05,
1787
+ "loss": 0.0703,
1788
+ "step": 2540
1789
+ },
1790
+ {
1791
+ "epoch": 3.6541151156535774,
1792
+ "grad_norm": 0.1887224816930325,
1793
+ "learning_rate": 3.983961859761946e-05,
1794
+ "loss": 0.071,
1795
+ "step": 2550
1796
+ },
1797
+ {
1798
+ "epoch": 3.6684597453828225,
1799
+ "grad_norm": 0.1939910437911645,
1800
+ "learning_rate": 3.9431904456150914e-05,
1801
+ "loss": 0.0685,
1802
+ "step": 2560
1803
+ },
1804
+ {
1805
+ "epoch": 3.6828043751120676,
1806
+ "grad_norm": 0.1905566250106664,
1807
+ "learning_rate": 3.902492456084757e-05,
1808
+ "loss": 0.0709,
1809
+ "step": 2570
1810
+ },
1811
+ {
1812
+ "epoch": 3.6971490048413127,
1813
+ "grad_norm": 0.1954219594857734,
1814
+ "learning_rate": 3.861870718770545e-05,
1815
+ "loss": 0.0691,
1816
+ "step": 2580
1817
+ },
1818
+ {
1819
+ "epoch": 3.711493634570558,
1820
+ "grad_norm": 0.20129771340548336,
1821
+ "learning_rate": 3.821328055974231e-05,
1822
+ "loss": 0.0688,
1823
+ "step": 2590
1824
+ },
1825
+ {
1826
+ "epoch": 3.725838264299803,
1827
+ "grad_norm": 0.19424451985885532,
1828
+ "learning_rate": 3.780867284503685e-05,
1829
+ "loss": 0.0705,
1830
+ "step": 2600
1831
+ },
1832
+ {
1833
+ "epoch": 3.740182894029048,
1834
+ "grad_norm": 0.19307288848206286,
1835
+ "learning_rate": 3.7404912154771626e-05,
1836
+ "loss": 0.069,
1837
+ "step": 2610
1838
+ },
1839
+ {
1840
+ "epoch": 3.754527523758293,
1841
+ "grad_norm": 0.20224114631498458,
1842
+ "learning_rate": 3.7002026541279905e-05,
1843
+ "loss": 0.069,
1844
+ "step": 2620
1845
+ },
1846
+ {
1847
+ "epoch": 3.7688721534875382,
1848
+ "grad_norm": 0.19645086260070405,
1849
+ "learning_rate": 3.660004399609675e-05,
1850
+ "loss": 0.0693,
1851
+ "step": 2630
1852
+ },
1853
+ {
1854
+ "epoch": 3.7832167832167833,
1855
+ "grad_norm": 0.2009057118393354,
1856
+ "learning_rate": 3.619899244801414e-05,
1857
+ "loss": 0.0695,
1858
+ "step": 2640
1859
+ },
1860
+ {
1861
+ "epoch": 3.7975614129460284,
1862
+ "grad_norm": 0.20154345565922616,
1863
+ "learning_rate": 3.5798899761140626e-05,
1864
+ "loss": 0.0688,
1865
+ "step": 2650
1866
+ },
1867
+ {
1868
+ "epoch": 3.8119060426752736,
1869
+ "grad_norm": 0.19819908788727933,
1870
+ "learning_rate": 3.5399793732965324e-05,
1871
+ "loss": 0.0703,
1872
+ "step": 2660
1873
+ },
1874
+ {
1875
+ "epoch": 3.8262506724045187,
1876
+ "grad_norm": 0.19579772630914064,
1877
+ "learning_rate": 3.500170209242671e-05,
1878
+ "loss": 0.0673,
1879
+ "step": 2670
1880
+ },
1881
+ {
1882
+ "epoch": 3.8405953021337638,
1883
+ "grad_norm": 0.1930709905078437,
1884
+ "learning_rate": 3.460465249798592e-05,
1885
+ "loss": 0.068,
1886
+ "step": 2680
1887
+ },
1888
+ {
1889
+ "epoch": 3.854939931863009,
1890
+ "grad_norm": 0.19375769656837338,
1891
+ "learning_rate": 3.420867253570529e-05,
1892
+ "loss": 0.0668,
1893
+ "step": 2690
1894
+ },
1895
+ {
1896
+ "epoch": 3.869284561592254,
1897
+ "grad_norm": 0.19590535607906298,
1898
+ "learning_rate": 3.381378971733161e-05,
1899
+ "loss": 0.0658,
1900
+ "step": 2700
1901
+ },
1902
+ {
1903
+ "epoch": 3.883629191321499,
1904
+ "grad_norm": 0.19485732453673113,
1905
+ "learning_rate": 3.342003147838475e-05,
1906
+ "loss": 0.0671,
1907
+ "step": 2710
1908
+ },
1909
+ {
1910
+ "epoch": 3.897973821050744,
1911
+ "grad_norm": 0.19120048275674587,
1912
+ "learning_rate": 3.302742517625144e-05,
1913
+ "loss": 0.0665,
1914
+ "step": 2720
1915
+ },
1916
+ {
1917
+ "epoch": 3.9123184507799893,
1918
+ "grad_norm": 0.19464302345990753,
1919
+ "learning_rate": 3.2635998088284596e-05,
1920
+ "loss": 0.0662,
1921
+ "step": 2730
1922
+ },
1923
+ {
1924
+ "epoch": 3.9266630805092344,
1925
+ "grad_norm": 0.20017821890333443,
1926
+ "learning_rate": 3.224577740990814e-05,
1927
+ "loss": 0.0655,
1928
+ "step": 2740
1929
+ },
1930
+ {
1931
+ "epoch": 3.9410077102384795,
1932
+ "grad_norm": 0.18866754533216776,
1933
+ "learning_rate": 3.185679025272753e-05,
1934
+ "loss": 0.0663,
1935
+ "step": 2750
1936
+ },
1937
+ {
1938
+ "epoch": 3.9553523399677246,
1939
+ "grad_norm": 0.19243520237850759,
1940
+ "learning_rate": 3.146906364264606e-05,
1941
+ "loss": 0.0657,
1942
+ "step": 2760
1943
+ },
1944
+ {
1945
+ "epoch": 3.9696969696969697,
1946
+ "grad_norm": 0.1924186499329835,
1947
+ "learning_rate": 3.108262451798724e-05,
1948
+ "loss": 0.0651,
1949
+ "step": 2770
1950
+ },
1951
+ {
1952
+ "epoch": 3.984041599426215,
1953
+ "grad_norm": 0.21148279808210507,
1954
+ "learning_rate": 3.069749972762316e-05,
1955
+ "loss": 0.0648,
1956
+ "step": 2780
1957
+ },
1958
+ {
1959
+ "epoch": 3.99838622915546,
1960
+ "grad_norm": 0.19991640585361364,
1961
+ "learning_rate": 3.0313716029109064e-05,
1962
+ "loss": 0.0645,
1963
+ "step": 2790
1964
+ },
1965
+ {
1966
+ "epoch": 4.011475703783396,
1967
+ "grad_norm": 0.13064534629220334,
1968
+ "learning_rate": 2.993130008682436e-05,
1969
+ "loss": 0.0228,
1970
+ "step": 2800
1971
+ },
1972
+ {
1973
+ "epoch": 4.025820333512641,
1974
+ "grad_norm": 0.14874535281957305,
1975
+ "learning_rate": 2.955027847011993e-05,
1976
+ "loss": 0.0176,
1977
+ "step": 2810
1978
+ },
1979
+ {
1980
+ "epoch": 4.040164963241886,
1981
+ "grad_norm": 0.14336180228683498,
1982
+ "learning_rate": 2.917067765147229e-05,
1983
+ "loss": 0.0176,
1984
+ "step": 2820
1985
+ },
1986
+ {
1987
+ "epoch": 4.054509592971131,
1988
+ "grad_norm": 0.12559441494646076,
1989
+ "learning_rate": 2.8792524004644283e-05,
1990
+ "loss": 0.0167,
1991
+ "step": 2830
1992
+ },
1993
+ {
1994
+ "epoch": 4.068854222700376,
1995
+ "grad_norm": 0.12484448147694403,
1996
+ "learning_rate": 2.8415843802852672e-05,
1997
+ "loss": 0.0167,
1998
+ "step": 2840
1999
+ },
2000
+ {
2001
+ "epoch": 4.083198852429621,
2002
+ "grad_norm": 0.1337296091314726,
2003
+ "learning_rate": 2.8040663216942752e-05,
2004
+ "loss": 0.0169,
2005
+ "step": 2850
2006
+ },
2007
+ {
2008
+ "epoch": 4.0975434821588665,
2009
+ "grad_norm": 0.12242456577697475,
2010
+ "learning_rate": 2.7667008313570076e-05,
2011
+ "loss": 0.0161,
2012
+ "step": 2860
2013
+ },
2014
+ {
2015
+ "epoch": 4.111888111888112,
2016
+ "grad_norm": 0.13243095768870966,
2017
+ "learning_rate": 2.729490505338943e-05,
2018
+ "loss": 0.0161,
2019
+ "step": 2870
2020
+ },
2021
+ {
2022
+ "epoch": 4.126232741617357,
2023
+ "grad_norm": 0.12277718816926177,
2024
+ "learning_rate": 2.692437928925109e-05,
2025
+ "loss": 0.0157,
2026
+ "step": 2880
2027
+ },
2028
+ {
2029
+ "epoch": 4.140577371346602,
2030
+ "grad_norm": 0.137540991678628,
2031
+ "learning_rate": 2.655545676440464e-05,
2032
+ "loss": 0.0159,
2033
+ "step": 2890
2034
+ },
2035
+ {
2036
+ "epoch": 4.154922001075847,
2037
+ "grad_norm": 0.13131712471544715,
2038
+ "learning_rate": 2.6188163110710435e-05,
2039
+ "loss": 0.0161,
2040
+ "step": 2900
2041
+ },
2042
+ {
2043
+ "epoch": 4.169266630805092,
2044
+ "grad_norm": 0.13640835620647865,
2045
+ "learning_rate": 2.582252384685874e-05,
2046
+ "loss": 0.0164,
2047
+ "step": 2910
2048
+ },
2049
+ {
2050
+ "epoch": 4.183611260534337,
2051
+ "grad_norm": 0.12543818653508698,
2052
+ "learning_rate": 2.5458564376596732e-05,
2053
+ "loss": 0.0157,
2054
+ "step": 2920
2055
+ },
2056
+ {
2057
+ "epoch": 4.197955890263582,
2058
+ "grad_norm": 0.11736167137678152,
2059
+ "learning_rate": 2.509630998696349e-05,
2060
+ "loss": 0.0154,
2061
+ "step": 2930
2062
+ },
2063
+ {
2064
+ "epoch": 4.212300519992827,
2065
+ "grad_norm": 0.1245551329001544,
2066
+ "learning_rate": 2.473578584653321e-05,
2067
+ "loss": 0.0152,
2068
+ "step": 2940
2069
+ },
2070
+ {
2071
+ "epoch": 4.2266451497220725,
2072
+ "grad_norm": 0.12763631881000323,
2073
+ "learning_rate": 2.4377017003666413e-05,
2074
+ "loss": 0.0155,
2075
+ "step": 2950
2076
+ },
2077
+ {
2078
+ "epoch": 4.240989779451318,
2079
+ "grad_norm": 0.13313595943206588,
2080
+ "learning_rate": 2.4020028384769795e-05,
2081
+ "loss": 0.015,
2082
+ "step": 2960
2083
+ },
2084
+ {
2085
+ "epoch": 4.255334409180563,
2086
+ "grad_norm": 0.125069284406997,
2087
+ "learning_rate": 2.366484479256425e-05,
2088
+ "loss": 0.015,
2089
+ "step": 2970
2090
+ },
2091
+ {
2092
+ "epoch": 4.269679038909808,
2093
+ "grad_norm": 0.13167131954772826,
2094
+ "learning_rate": 2.3311490904361738e-05,
2095
+ "loss": 0.0159,
2096
+ "step": 2980
2097
+ },
2098
+ {
2099
+ "epoch": 4.284023668639053,
2100
+ "grad_norm": 0.11344149792986571,
2101
+ "learning_rate": 2.295999127035071e-05,
2102
+ "loss": 0.0147,
2103
+ "step": 2990
2104
+ },
2105
+ {
2106
+ "epoch": 4.298368298368298,
2107
+ "grad_norm": 0.1299095136285245,
2108
+ "learning_rate": 2.26103703118905e-05,
2109
+ "loss": 0.015,
2110
+ "step": 3000
2111
+ }
2112
+ ],
2113
+ "logging_steps": 10,
2114
+ "max_steps": 4188,
2115
+ "num_input_tokens_seen": 0,
2116
+ "num_train_epochs": 6,
2117
+ "save_steps": 500,
2118
+ "stateful_callbacks": {
2119
+ "TrainerControl": {
2120
+ "args": {
2121
+ "should_epoch_stop": false,
2122
+ "should_evaluate": false,
2123
+ "should_log": false,
2124
+ "should_save": true,
2125
+ "should_training_stop": false
2126
+ },
2127
+ "attributes": {}
2128
+ }
2129
+ },
2130
+ "total_flos": 940152769216512.0,
2131
+ "train_batch_size": 1,
2132
+ "trial_name": null,
2133
+ "trial_params": null
2134
+ }
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d984a7c189c70dbf5d61cb23d3712e05c9f7357204184deb2f3e29263430b342
3
+ size 7953
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)