Ubuntu commited on
Commit
701dcd8
β€’
1 Parent(s): b517d17
config.json CHANGED
@@ -1,8 +1,16 @@
1
  {
2
- "_name_or_path": "/mnt/data/zhangzheng/data/AtoM-7B/checkpoint-56000",
3
  "architectures": [
4
  "LlamaForCausalLM"
5
  ],
 
 
 
 
 
 
 
 
6
  "bos_token_id": 1,
7
  "eos_token_id": 2,
8
  "hidden_act": "silu",
@@ -18,10 +26,14 @@
18
  "pad_token_id": 2,
19
  "pretraining_tp": 1,
20
  "rms_norm_eps": 1e-05,
21
- "rope_scaling": null,
 
 
 
 
22
  "tie_word_embeddings": false,
23
- "torch_dtype": "float16",
24
- "transformers_version": "4.31.0",
25
  "use_cache": true,
26
  "vocab_size": 65000
27
  }
 
1
  {
2
+ "_name_or_path": "/mnt/data1/model/base_model/Atom7B/checkpoint-101000-32kl",
3
  "architectures": [
4
  "LlamaForCausalLM"
5
  ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_atom.LlamaConfig",
10
+ "AutoModel": "model_atom.LlamaForCausalLM",
11
+ "AutoModelForCausalLM": "model_atom.LlamaForCausalLM",
12
+ "AutoModelForSequenceClassification": "model_atom.LlamaForSequenceClassification"
13
+ },
14
  "bos_token_id": 1,
15
  "eos_token_id": 2,
16
  "hidden_act": "silu",
 
26
  "pad_token_id": 2,
27
  "pretraining_tp": 1,
28
  "rms_norm_eps": 1e-05,
29
+ "rope_scaling": {
30
+ "factor": 8.0,
31
+ "type": "dynamic"
32
+ },
33
+ "rope_theta": 500000,
34
  "tie_word_embeddings": false,
35
+ "torch_dtype": "bfloat16",
36
+ "transformers_version": "4.36.2",
37
  "use_cache": true,
38
  "vocab_size": 65000
39
  }
configuration_atom.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class LlamaConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
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 LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`LlamaModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
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
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
64
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
65
+ Llama 2 up to 4096, CodeLlama up to 16384.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ Padding token id.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ Beginning of stream token id.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ End of stream token id.
79
+ pretraining_tp (`int`, *optional*, defaults to 1):
80
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
81
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
82
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
83
+ issue](https://github.com/pytorch/pytorch/issues/76232).
84
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
85
+ Whether to tie weight embeddings
86
+ rope_theta (`float`, *optional*, defaults to 10000.0):
87
+ The base period of the RoPE embeddings.
88
+ rope_scaling (`Dict`, *optional*):
89
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
90
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
91
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
92
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
93
+ these scaling strategies behave:
94
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
95
+ experimental feature, subject to breaking API changes in future versions.
96
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
97
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
98
+ attention_dropout (`float`, *optional*, defaults to 0.0):
99
+ The dropout ratio for the attention probabilities.
100
+
101
+ ```python
102
+ >>> from transformers import LlamaModel, LlamaConfig
103
+
104
+ >>> # Initializing a LLaMA llama-7b style configuration
105
+ >>> configuration = LlamaConfig()
106
+
107
+ >>> # Initializing a model from the llama-7b style configuration
108
+ >>> model = LlamaModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+
114
+ model_type = "llama"
115
+ keys_to_ignore_at_inference = ["past_key_values"]
116
+
117
+ def __init__(
118
+ self,
119
+ vocab_size=32000,
120
+ hidden_size=4096,
121
+ intermediate_size=11008,
122
+ num_hidden_layers=32,
123
+ num_attention_heads=32,
124
+ num_key_value_heads=None,
125
+ hidden_act="silu",
126
+ max_position_embeddings=2048,
127
+ initializer_range=0.02,
128
+ rms_norm_eps=1e-6,
129
+ use_cache=True,
130
+ pad_token_id=None,
131
+ bos_token_id=1,
132
+ eos_token_id=2,
133
+ pretraining_tp=1,
134
+ tie_word_embeddings=False,
135
+ rope_theta=10000.0,
136
+ rope_scaling=None,
137
+ attention_bias=False,
138
+ attention_dropout=0.0,
139
+ **kwargs,
140
+ ):
141
+ self.vocab_size = vocab_size
142
+ self.max_position_embeddings = max_position_embeddings
143
+ self.hidden_size = hidden_size
144
+ self.intermediate_size = intermediate_size
145
+ self.num_hidden_layers = num_hidden_layers
146
+ self.num_attention_heads = num_attention_heads
147
+
148
+ # for backward compatibility
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.hidden_act = hidden_act
154
+ self.initializer_range = initializer_range
155
+ self.rms_norm_eps = rms_norm_eps
156
+ self.pretraining_tp = pretraining_tp
157
+ self.use_cache = use_cache
158
+ self.rope_theta = rope_theta
159
+ self.rope_scaling = rope_scaling
160
+ self._rope_scaling_validation()
161
+ self.attention_bias = attention_bias
162
+ self.attention_dropout = attention_dropout
163
+
164
+ super().__init__(
165
+ pad_token_id=pad_token_id,
166
+ bos_token_id=bos_token_id,
167
+ eos_token_id=eos_token_id,
168
+ tie_word_embeddings=tie_word_embeddings,
169
+ **kwargs,
170
+ )
171
+
172
+ def _rope_scaling_validation(self):
173
+ """
174
+ Validate the `rope_scaling` configuration.
175
+ """
176
+ if self.rope_scaling is None:
177
+ return
178
+
179
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
180
+ raise ValueError(
181
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
182
+ f"got {self.rope_scaling}"
183
+ )
184
+ rope_scaling_type = self.rope_scaling.get("type", None)
185
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
186
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic","yarn", "dynamic-yarn"]:
187
+ raise ValueError(
188
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
189
+ )
190
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
191
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
192
+ if rope_scaling_type == "yarn" or rope_scaling_type == "dynamic-yarn":
193
+ original_max_position_embeddings = self.rope_scaling.get("original_max_position_embeddings", None)
194
+ if original_max_position_embeddings is None or not isinstance(original_max_position_embeddings, int):
195
+ raise ValueError(f"`rope_scaling.original_max_position_embeddings` must be set to an int when using yarn, and dynamic-yarn")
generation_config.json CHANGED
@@ -4,5 +4,5 @@
4
  "eos_token_id": 2,
5
  "max_length": 4096,
6
  "pad_token_id": 2,
7
- "transformers_version": "4.31.0"
8
  }
 
4
  "eos_token_id": 2,
5
  "max_length": 4096,
6
  "pad_token_id": 2,
7
+ "transformers_version": "4.36.2"
8
  }
pytorch_model-00001-of-00002.bin β†’ model-00001-of-00003.safetensors RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:1e9f92d39952ce1a2a436ce1fef39aefa4fe9ce6907abba4a34e3347bdd085d9
3
- size 9976419871
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cb46b554509faa3864b220c7cca8093e8c7cc3e57efd3f25391ff86a665bbb7
3
+ size 4984925512
pytorch_model-00002-of-00002.bin β†’ model-00002-of-00003.safetensors RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c344e21209d29159cabbb0352dbdadc601f5484a97f732ad6c88f9ba36a4484c
3
- size 4041202157
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0518a0031d46b170e17d8c3d354b8e91a17c536cfbb807b0c3cb096c5a600ab2
3
+ size 4991431432
model-00003-of-00003.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:214059ad3834a892d600c97aeba063e7f87d6a439e3b0b97e8e7a82b7c44e1eb
3
+ size 4041180136
model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 14017503232
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00003-of-00003.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00003.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00003.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
13
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
14
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
15
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
16
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
17
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00003.safetensors",
18
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
19
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
20
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
22
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
23
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
24
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
25
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
26
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00003.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
28
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
29
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
30
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
31
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
32
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
33
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
34
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
35
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00003.safetensors",
36
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
37
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
38
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
39
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
40
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
41
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
42
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
43
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
44
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00003.safetensors",
45
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
46
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
47
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
48
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
49
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
50
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
51
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
52
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
53
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00003.safetensors",
54
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
55
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
56
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
57
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
58
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
59
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
60
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
61
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
62
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00003.safetensors",
63
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
64
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
65
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
66
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
67
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
68
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
69
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
70
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
71
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00003.safetensors",
72
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
73
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
74
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
75
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
76
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
77
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
78
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
79
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
80
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00003.safetensors",
81
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
82
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
83
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
84
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
85
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
86
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
87
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
88
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
89
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00003.safetensors",
90
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
91
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
92
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
93
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
94
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
95
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
96
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
97
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
98
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00003.safetensors",
99
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
100
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
101
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
102
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
103
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
104
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
105
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
106
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
107
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00003.safetensors",
108
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
109
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
110
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
111
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
112
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
113
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
114
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
115
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
116
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00003.safetensors",
117
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
118
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
119
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
120
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
121
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
122
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
123
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
124
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
125
+ "model.layers.20.input_layernorm.weight": "model-00002-of-00003.safetensors",
126
+ "model.layers.20.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
127
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
128
+ "model.layers.20.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
129
+ "model.layers.20.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
130
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
131
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
132
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
133
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
134
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00003.safetensors",
135
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
136
+ "model.layers.21.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
137
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
138
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
139
+ "model.layers.21.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
140
+ "model.layers.21.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
141
+ "model.layers.21.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
142
+ "model.layers.21.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
143
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00003.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00003.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00003.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00003.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00003.safetensors",
148
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
149
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
150
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
151
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
152
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00003.safetensors",
153
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
154
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
156
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
157
+ "model.layers.23.self_attn.k_proj.weight": "model-00002-of-00003.safetensors",
158
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00003.safetensors",
159
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00003.safetensors",
160
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00003.safetensors",
161
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00003.safetensors",
162
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
163
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
164
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
165
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
166
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
167
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
168
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
169
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
170
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00003.safetensors",
171
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
172
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
173
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
174
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
175
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
176
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
177
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
178
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
179
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00003.safetensors",
180
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
181
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
182
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
183
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
184
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
185
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
186
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
187
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
188
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00003.safetensors",
189
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
190
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
191
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
192
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
193
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
194
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
195
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
196
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
197
+ "model.layers.28.input_layernorm.weight": "model-00003-of-00003.safetensors",
198
+ "model.layers.28.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
199
+ "model.layers.28.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
200
+ "model.layers.28.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
201
+ "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
202
+ "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
203
+ "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
204
+ "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
205
+ "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
206
+ "model.layers.29.input_layernorm.weight": "model-00003-of-00003.safetensors",
207
+ "model.layers.29.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
208
+ "model.layers.29.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
209
+ "model.layers.29.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
210
+ "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
211
+ "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
212
+ "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
213
+ "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
214
+ "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
215
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00003.safetensors",
216
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
217
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
218
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
219
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
220
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
221
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
222
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
223
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
224
+ "model.layers.30.input_layernorm.weight": "model-00003-of-00003.safetensors",
225
+ "model.layers.30.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
226
+ "model.layers.30.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
227
+ "model.layers.30.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
228
+ "model.layers.30.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
229
+ "model.layers.30.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
230
+ "model.layers.30.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
231
+ "model.layers.30.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
232
+ "model.layers.30.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
233
+ "model.layers.31.input_layernorm.weight": "model-00003-of-00003.safetensors",
234
+ "model.layers.31.mlp.down_proj.weight": "model-00003-of-00003.safetensors",
235
+ "model.layers.31.mlp.gate_proj.weight": "model-00003-of-00003.safetensors",
236
+ "model.layers.31.mlp.up_proj.weight": "model-00003-of-00003.safetensors",
237
+ "model.layers.31.post_attention_layernorm.weight": "model-00003-of-00003.safetensors",
238
+ "model.layers.31.self_attn.k_proj.weight": "model-00003-of-00003.safetensors",
239
+ "model.layers.31.self_attn.o_proj.weight": "model-00003-of-00003.safetensors",
240
+ "model.layers.31.self_attn.q_proj.weight": "model-00003-of-00003.safetensors",
241
+ "model.layers.31.self_attn.v_proj.weight": "model-00003-of-00003.safetensors",
242
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00003.safetensors",
243
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
244
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
245
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
246
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
247
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
248
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
249
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
250
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
251
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00003.safetensors",
252
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
253
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
254
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
255
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
256
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
257
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
258
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
259
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
260
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00003.safetensors",
261
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
262
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
263
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
264
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
265
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
266
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
267
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
268
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
269
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00003.safetensors",
270
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
271
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
272
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
273
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
274
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
275
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
276
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
277
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
278
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00003.safetensors",
279
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
280
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
281
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
282
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
283
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
284
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
285
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
286
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
287
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00003.safetensors",
288
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00003.safetensors",
289
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00003.safetensors",
290
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00003.safetensors",
291
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00003.safetensors",
292
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00003.safetensors",
293
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00003.safetensors",
294
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00003.safetensors",
295
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00003.safetensors",
296
+ "model.norm.weight": "model-00003-of-00003.safetensors"
297
+ }
298
+ }
model_atom.py ADDED
@@ -0,0 +1,1558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.cache_utils import Cache, DynamicCache
33
+ from transformers.modeling_attn_mask_utils import (
34
+ AttentionMaskConverter,
35
+ _prepare_4d_attention_mask,
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ )
39
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
42
+ from transformers.utils import (
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ is_flash_attn_2_available,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.import_utils import is_torch_fx_available
51
+ from .configuration_atom import LlamaConfig
52
+
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+
59
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
60
+ # It means that the function will not be traced through and simply appear as a node in the graph.
61
+ if is_torch_fx_available():
62
+ if not is_torch_greater_or_equal_than_1_13:
63
+ import torch.fx
64
+
65
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
66
+
67
+
68
+ logger = logging.get_logger(__name__)
69
+
70
+ _CONFIG_FOR_DOC = "LlamaConfig"
71
+
72
+
73
+ def _get_unpad_data(attention_mask):
74
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
75
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
76
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
77
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
78
+ return (
79
+ indices,
80
+ cu_seqlens,
81
+ max_seqlen_in_batch,
82
+ )
83
+
84
+
85
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
86
+ warnings.warn(
87
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
88
+ )
89
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
90
+
91
+
92
+ def _make_causal_mask(
93
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
94
+ ):
95
+ warnings.warn(
96
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
97
+ )
98
+ return AttentionMaskConverter._make_causal_mask(
99
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
100
+ )
101
+ # Inverse dim formula to find dim based on number of rotations
102
+ def _yarn_find_correction_dim(num_rotations, dim, base=10000, max_position_embeddings=2048):
103
+ return (dim * math.log(max_position_embeddings/(num_rotations * 2 * math.pi)))/(2 * math.log(base))
104
+
105
+ # Find dim range bounds based on rotations
106
+ def _yarn_find_correction_range(low_rot, high_rot, dim, base=10000, max_position_embeddings=2048):
107
+ low = math.floor(_yarn_find_correction_dim(
108
+ low_rot, dim, base, max_position_embeddings))
109
+ high = math.ceil(_yarn_find_correction_dim(
110
+ high_rot, dim, base, max_position_embeddings))
111
+ return max(low, 0), min(high, dim-1) # Clamp values just in case
112
+
113
+ def _yarn_linear_ramp_mask(min, max, dim):
114
+ if min == max:
115
+ max += 0.001 # Prevent singularity
116
+
117
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
118
+ ramp_func = torch.clamp(linear_func, 0, 1)
119
+ return ramp_func
120
+
121
+ def _yarn_get_mscale(scale=1):
122
+ if scale <= 1:
123
+ return 1.0
124
+ return 0.1 * math.log(scale) + 1.0
125
+
126
+ class LlamaRMSNorm(nn.Module):
127
+ def __init__(self, hidden_size, eps=1e-6):
128
+ """
129
+ LlamaRMSNorm is equivalent to T5LayerNorm
130
+ """
131
+ super().__init__()
132
+ self.weight = nn.Parameter(torch.ones(hidden_size))
133
+ self.variance_epsilon = eps
134
+
135
+ def forward(self, hidden_states):
136
+ input_dtype = hidden_states.dtype
137
+ hidden_states = hidden_states.to(torch.float32)
138
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
139
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
140
+ return self.weight * hidden_states.to(input_dtype)
141
+
142
+
143
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
144
+
145
+
146
+ class LlamaRotaryEmbedding(nn.Module):
147
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
148
+ super().__init__()
149
+
150
+ self.dim = dim
151
+ self.max_position_embeddings = max_position_embeddings
152
+ self.base = base
153
+ self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
154
+
155
+ # Build here to make `torch.jit.trace` work.
156
+ self._set_cos_sin_cache(
157
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
158
+ )
159
+
160
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
161
+ self.max_seq_len_cached = seq_len
162
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
163
+
164
+ freqs = torch.outer(t, self.inv_freq)
165
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
166
+ emb = torch.cat((freqs, freqs), dim=-1)
167
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
168
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
169
+
170
+ def forward(self, x, seq_len=None):
171
+ # x: [bs, num_attention_heads, seq_len, head_size]
172
+ if seq_len > self.max_seq_len_cached:
173
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
174
+
175
+ return (
176
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
177
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
178
+ )
179
+
180
+
181
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
182
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
183
+
184
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
185
+ self.scaling_factor = scaling_factor
186
+ super().__init__(dim, max_position_embeddings, base, device)
187
+
188
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
189
+ self.max_seq_len_cached = seq_len
190
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
191
+ t = t / self.scaling_factor
192
+
193
+ freqs = torch.outer(t, self.inv_freq)
194
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
195
+ emb = torch.cat((freqs, freqs), dim=-1)
196
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
197
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
198
+
199
+
200
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
201
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
202
+
203
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
204
+ self.scaling_factor = scaling_factor
205
+ super().__init__(dim, max_position_embeddings, base, device)
206
+
207
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
208
+ self.max_seq_len_cached = seq_len
209
+
210
+ if seq_len > self.max_position_embeddings:
211
+ base = self.base * (
212
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
213
+ ) ** (self.dim / (self.dim - 2))
214
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
215
+ # self.register_buffer("inv_freq", inv_freq, persistent=False)
216
+
217
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
218
+
219
+ freqs = torch.outer(t, self.inv_freq)
220
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
221
+ emb = torch.cat((freqs, freqs), dim=-1)
222
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
223
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
224
+
225
+ class LlamaYaRNScaledRotaryEmbedding(torch.nn.Module):
226
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, scale=1, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
227
+ super().__init__()
228
+
229
+ self.dim = dim
230
+ self.max_position_embeddings = max_position_embeddings
231
+ self.base = base
232
+ self.scale = scale
233
+ self.original_max_position_embeddings = original_max_position_embeddings
234
+ self.extrapolation_factor = extrapolation_factor
235
+ self.attn_factor = attn_factor
236
+ self.beta_fast = beta_fast
237
+ self.beta_slow = beta_slow
238
+
239
+ self.yarn(device)
240
+
241
+ # Build here to make `torch.jit.trace` work.
242
+ self.max_seq_len_cached = max_position_embeddings
243
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
244
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
245
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
246
+ emb = torch.cat((freqs, freqs), dim=-1)
247
+ dtype = torch.get_default_dtype()
248
+
249
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(dtype), persistent=False)
250
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(dtype), persistent=False)
251
+
252
+ def forward(self, x, seq_len=None):
253
+ # x: [bs, num_attention_heads, seq_len, head_size]
254
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
255
+ if seq_len > self.max_seq_len_cached:
256
+ self.max_seq_len_cached = seq_len
257
+
258
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
259
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
260
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
261
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
262
+
263
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(x.dtype), persistent=False)
264
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(x.dtype), persistent=False)
265
+ return (
266
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
267
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
268
+ )
269
+
270
+ def yarn(self, device):
271
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
272
+ inv_freq_extrapolation = 1.0 / pos_freqs
273
+ inv_freq_interpolation = 1.0 / (self.scale * pos_freqs)
274
+
275
+ low, high = _yarn_find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
276
+ inv_freq_mask = (1 - _yarn_linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
277
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
278
+
279
+ # self.register_buffer("inv_freq", inv_freq, persistent=False)
280
+ self.mscale = float(_yarn_get_mscale(self.scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
281
+
282
+
283
+ class LlamaDynamicYaRNScaledRotaryEmbedding(torch.nn.Module):
284
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, original_max_position_embeddings=2048, extrapolation_factor=1, attn_factor=1, beta_fast=32, beta_slow=1, finetuned=False, device=None):
285
+ super().__init__()
286
+
287
+ self.dim = dim
288
+ self.max_position_embeddings = max_position_embeddings
289
+ self.base = base
290
+ self.original_max_position_embeddings = original_max_position_embeddings
291
+ self.extrapolation_factor = extrapolation_factor
292
+ self.attn_factor = attn_factor
293
+ self.beta_fast = beta_fast
294
+ self.beta_slow = beta_slow
295
+
296
+ if finetuned:
297
+ self.yarn(self.max_position_embeddings / self.original_max_position_embeddings, device)
298
+ else:
299
+ inv_freq = 1.0 / \
300
+ (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
301
+ # self.register_buffer("inv_freq", inv_freq, persistent=False)
302
+ self.mscale = 1
303
+
304
+ # Build here to make `torch.jit.trace` work.
305
+ self.max_seq_len_cached = max_position_embeddings
306
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=torch.float32)
307
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
308
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
309
+ emb = torch.cat((freqs, freqs), dim=-1)
310
+ dtype = torch.get_default_dtype()
311
+
312
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(dtype), persistent=False)
313
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(dtype), persistent=False)
314
+
315
+ def forward(self, x, seq_len=None):
316
+ # x: [bs, num_attention_heads, seq_len, head_size]
317
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
318
+ if seq_len > self.max_seq_len_cached:
319
+ self.max_seq_len_cached = seq_len
320
+
321
+ self.yarn(seq_len / self.max_position_embeddings, x.device)
322
+
323
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
324
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
325
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
326
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
327
+
328
+ self.register_buffer("cos_cached", (emb.cos() * self.mscale).to(x.dtype), persistent=False)
329
+ self.register_buffer("sin_cached", (emb.sin() * self.mscale).to(x.dtype), persistent=False)
330
+ return (
331
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
332
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
333
+ )
334
+
335
+ def yarn(self, scale, device):
336
+ pos_freqs = self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
337
+ inv_freq_extrapolation = 1.0 / pos_freqs
338
+ inv_freq_interpolation = 1.0 / (scale * pos_freqs)
339
+
340
+ low, high = _yarn_find_correction_range(self.beta_fast, self.beta_slow, self.dim, self.base, self.original_max_position_embeddings)
341
+ inv_freq_mask = (1 - _yarn_linear_ramp_mask(low, high, self.dim // 2).float().to(device)) * self.extrapolation_factor # Get n-d rotational scaling corrected for extrapolation
342
+ inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
343
+
344
+ # self.register_buffer("inv_freq", inv_freq, persistent=False)
345
+ self.mscale = float(_yarn_get_mscale(scale) * self.attn_factor) # Get n-d magnitude scaling corrected for interpolation
346
+
347
+
348
+ def rotate_half(x):
349
+ """Rotates half the hidden dims of the input."""
350
+ x1 = x[..., : x.shape[-1] // 2]
351
+ x2 = x[..., x.shape[-1] // 2 :]
352
+ return torch.cat((-x2, x1), dim=-1)
353
+
354
+
355
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
356
+ """Applies Rotary Position Embedding to the query and key tensors.
357
+
358
+ Args:
359
+ q (`torch.Tensor`): The query tensor.
360
+ k (`torch.Tensor`): The key tensor.
361
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
362
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
363
+ position_ids (`torch.Tensor`):
364
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
365
+ used to pass offsetted position ids when working with a KV-cache.
366
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
367
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
368
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
369
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
370
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
371
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
372
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
373
+ Returns:
374
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
375
+ """
376
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
377
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
378
+ q_embed = (q * cos) + (rotate_half(q) * sin)
379
+ k_embed = (k * cos) + (rotate_half(k) * sin)
380
+ return q_embed, k_embed
381
+
382
+
383
+ class LlamaMLP(nn.Module):
384
+ def __init__(self, config):
385
+ super().__init__()
386
+ self.config = config
387
+ self.hidden_size = config.hidden_size
388
+ self.intermediate_size = config.intermediate_size
389
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
390
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
391
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
392
+ self.act_fn = ACT2FN[config.hidden_act]
393
+
394
+ def forward(self, x):
395
+ if self.config.pretraining_tp > 1:
396
+ slice = self.intermediate_size // self.config.pretraining_tp
397
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
398
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
399
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
400
+
401
+ gate_proj = torch.cat(
402
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
403
+ )
404
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
405
+
406
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
407
+ down_proj = [
408
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
409
+ ]
410
+ down_proj = sum(down_proj)
411
+ else:
412
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
413
+
414
+ return down_proj
415
+
416
+
417
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
418
+ """
419
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
420
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
421
+ """
422
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
423
+ if n_rep == 1:
424
+ return hidden_states
425
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
426
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
427
+
428
+
429
+ class LlamaAttention(nn.Module):
430
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
431
+
432
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
433
+ super().__init__()
434
+ self.config = config
435
+ self.layer_idx = layer_idx
436
+ if layer_idx is None:
437
+ logger.warning_once(
438
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
439
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
440
+ "when creating this class."
441
+ )
442
+
443
+ self.attention_dropout = config.attention_dropout
444
+ self.hidden_size = config.hidden_size
445
+ self.num_heads = config.num_attention_heads
446
+ self.head_dim = self.hidden_size // self.num_heads
447
+ self.num_key_value_heads = config.num_key_value_heads
448
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
449
+ self.max_position_embeddings = config.max_position_embeddings
450
+ self.rope_theta = config.rope_theta
451
+ self.is_causal = True
452
+
453
+ if (self.head_dim * self.num_heads) != self.hidden_size:
454
+ raise ValueError(
455
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
456
+ f" and `num_heads`: {self.num_heads})."
457
+ )
458
+
459
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
460
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
461
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
462
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
463
+ self._init_rope()
464
+
465
+ def _init_rope(self):
466
+ if self.config.rope_scaling is None:
467
+ self.rotary_emb = LlamaRotaryEmbedding(
468
+ self.head_dim,
469
+ max_position_embeddings=self.max_position_embeddings,
470
+ base=self.rope_theta,
471
+ )
472
+ else:
473
+ scaling_type = self.config.rope_scaling["type"]
474
+ scaling_factor = self.config.rope_scaling["factor"]
475
+ if scaling_type == "linear":
476
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
477
+ self.head_dim,
478
+ max_position_embeddings=self.max_position_embeddings,
479
+ scaling_factor=scaling_factor,
480
+ base=self.rope_theta,
481
+ )
482
+ elif scaling_type == "dynamic":
483
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
484
+ self.head_dim,
485
+ max_position_embeddings=self.max_position_embeddings,
486
+ scaling_factor=scaling_factor,
487
+ base=self.rope_theta,
488
+ )
489
+ else:
490
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
491
+
492
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
493
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
494
+
495
+ def forward(
496
+ self,
497
+ hidden_states: torch.Tensor,
498
+ attention_mask: Optional[torch.Tensor] = None,
499
+ position_ids: Optional[torch.LongTensor] = None,
500
+ past_key_value: Optional[Cache] = None,
501
+ output_attentions: bool = False,
502
+ use_cache: bool = False,
503
+ **kwargs,
504
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
505
+ if "padding_mask" in kwargs:
506
+ warnings.warn(
507
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
508
+ )
509
+
510
+ bsz, q_len, _ = hidden_states.size()
511
+
512
+ if self.config.pretraining_tp > 1:
513
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
514
+ query_slices = self.q_proj.weight.split(
515
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
516
+ )
517
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
518
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
519
+
520
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
521
+ query_states = torch.cat(query_states, dim=-1)
522
+
523
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
524
+ key_states = torch.cat(key_states, dim=-1)
525
+
526
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
527
+ value_states = torch.cat(value_states, dim=-1)
528
+
529
+ else:
530
+ query_states = self.q_proj(hidden_states)
531
+ key_states = self.k_proj(hidden_states)
532
+ value_states = self.v_proj(hidden_states)
533
+
534
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
535
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
536
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
537
+
538
+ kv_seq_len = key_states.shape[-2]
539
+ if past_key_value is not None:
540
+ if self.layer_idx is None:
541
+ raise ValueError(
542
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
543
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
544
+ "with a layer index."
545
+ )
546
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
547
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
548
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
549
+
550
+ if past_key_value is not None:
551
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
552
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
553
+
554
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
555
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
556
+
557
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
558
+
559
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
560
+ raise ValueError(
561
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
562
+ f" {attn_weights.size()}"
563
+ )
564
+
565
+ if attention_mask is not None:
566
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
567
+ raise ValueError(
568
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
569
+ )
570
+ attn_weights = attn_weights + attention_mask
571
+
572
+ # upcast attention to fp32
573
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
574
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
575
+ attn_output = torch.matmul(attn_weights, value_states)
576
+
577
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
578
+ raise ValueError(
579
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
580
+ f" {attn_output.size()}"
581
+ )
582
+
583
+ attn_output = attn_output.transpose(1, 2).contiguous()
584
+
585
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
586
+
587
+ if self.config.pretraining_tp > 1:
588
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
589
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
590
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
591
+ else:
592
+ attn_output = self.o_proj(attn_output)
593
+
594
+ if not output_attentions:
595
+ attn_weights = None
596
+
597
+ return attn_output, attn_weights, past_key_value
598
+
599
+
600
+ class LlamaFlashAttention2(LlamaAttention):
601
+ """
602
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
603
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
604
+ flash attention and deal with padding tokens in case the input contains any of them.
605
+ """
606
+
607
+ def __init__(self, *args, **kwargs):
608
+ super().__init__(*args, **kwargs)
609
+
610
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
611
+ # 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.
612
+ # 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).
613
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
614
+
615
+ def forward(
616
+ self,
617
+ hidden_states: torch.Tensor,
618
+ attention_mask: Optional[torch.LongTensor] = None,
619
+ position_ids: Optional[torch.LongTensor] = None,
620
+ past_key_value: Optional[Cache] = None,
621
+ output_attentions: bool = False,
622
+ use_cache: bool = False,
623
+ **kwargs,
624
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
625
+ # LlamaFlashAttention2 attention does not support output_attentions
626
+ if "padding_mask" in kwargs:
627
+ warnings.warn(
628
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
629
+ )
630
+
631
+ # overwrite attention_mask with padding_mask
632
+ attention_mask = kwargs.pop("padding_mask")
633
+
634
+ output_attentions = False
635
+
636
+ bsz, q_len, _ = hidden_states.size()
637
+
638
+ query_states = self.q_proj(hidden_states)
639
+ key_states = self.k_proj(hidden_states)
640
+ value_states = self.v_proj(hidden_states)
641
+
642
+ # Flash attention requires the input to have the shape
643
+ # batch_size x seq_length x head_dim x hidden_dim
644
+ # therefore we just need to keep the original shape
645
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
646
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
647
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
648
+
649
+ kv_seq_len = key_states.shape[-2]
650
+ if past_key_value is not None:
651
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
652
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
653
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
654
+
655
+ if past_key_value is not None:
656
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
657
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
658
+
659
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
660
+ # to be able to avoid many of these transpose/reshape/view.
661
+ query_states = query_states.transpose(1, 2)
662
+ key_states = key_states.transpose(1, 2)
663
+ value_states = value_states.transpose(1, 2)
664
+
665
+ dropout_rate = self.attention_dropout if self.training else 0.0
666
+
667
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
668
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
669
+ # cast them back in the correct dtype just to be sure everything works as expected.
670
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
671
+ # in fp32. (LlamaRMSNorm handles it correctly)
672
+
673
+ input_dtype = query_states.dtype
674
+ if input_dtype == torch.float32:
675
+ # Handle the case where the model is quantized
676
+ if hasattr(self.config, "_pre_quantization_dtype"):
677
+ target_dtype = self.config._pre_quantization_dtype
678
+ elif torch.is_autocast_enabled():
679
+ target_dtype = torch.get_autocast_gpu_dtype()
680
+ else:
681
+ target_dtype = self.q_proj.weight.dtype
682
+
683
+ logger.warning_once(
684
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
685
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
686
+ f" {target_dtype}."
687
+ )
688
+
689
+ query_states = query_states.to(target_dtype)
690
+ key_states = key_states.to(target_dtype)
691
+ value_states = value_states.to(target_dtype)
692
+
693
+ attn_output = self._flash_attention_forward(
694
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
695
+ )
696
+
697
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
698
+ attn_output = self.o_proj(attn_output)
699
+
700
+ if not output_attentions:
701
+ attn_weights = None
702
+
703
+ return attn_output, attn_weights, past_key_value
704
+
705
+ def _flash_attention_forward(
706
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
707
+ ):
708
+ """
709
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
710
+ first unpad the input, then computes the attention scores and pad the final attention scores.
711
+
712
+ Args:
713
+ query_states (`torch.Tensor`):
714
+ Input query states to be passed to Flash Attention API
715
+ key_states (`torch.Tensor`):
716
+ Input key states to be passed to Flash Attention API
717
+ value_states (`torch.Tensor`):
718
+ Input value states to be passed to Flash Attention API
719
+ attention_mask (`torch.Tensor`):
720
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
721
+ position of padding tokens and 1 for the position of non-padding tokens.
722
+ dropout (`int`, *optional*):
723
+ Attention dropout
724
+ softmax_scale (`float`, *optional*):
725
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
726
+ """
727
+ if not self._flash_attn_uses_top_left_mask:
728
+ causal = self.is_causal
729
+ else:
730
+ # 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__.
731
+ causal = self.is_causal and query_length != 1
732
+
733
+ # Contains at least one padding token in the sequence
734
+ if attention_mask is not None:
735
+ batch_size = query_states.shape[0]
736
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
737
+ query_states, key_states, value_states, attention_mask, query_length
738
+ )
739
+
740
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
741
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
742
+
743
+ attn_output_unpad = flash_attn_varlen_func(
744
+ query_states,
745
+ key_states,
746
+ value_states,
747
+ cu_seqlens_q=cu_seqlens_q,
748
+ cu_seqlens_k=cu_seqlens_k,
749
+ max_seqlen_q=max_seqlen_in_batch_q,
750
+ max_seqlen_k=max_seqlen_in_batch_k,
751
+ dropout_p=dropout,
752
+ softmax_scale=softmax_scale,
753
+ causal=causal,
754
+ )
755
+
756
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
757
+ else:
758
+ attn_output = flash_attn_func(
759
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
760
+ )
761
+
762
+ return attn_output
763
+
764
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
765
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
766
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
767
+
768
+ key_layer = index_first_axis(
769
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
770
+ )
771
+ value_layer = index_first_axis(
772
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
773
+ )
774
+ if query_length == kv_seq_len:
775
+ query_layer = index_first_axis(
776
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
777
+ )
778
+ cu_seqlens_q = cu_seqlens_k
779
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
780
+ indices_q = indices_k
781
+ elif query_length == 1:
782
+ max_seqlen_in_batch_q = 1
783
+ cu_seqlens_q = torch.arange(
784
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
785
+ ) # There is a memcpy here, that is very bad.
786
+ indices_q = cu_seqlens_q[:-1]
787
+ query_layer = query_layer.squeeze(1)
788
+ else:
789
+ # The -q_len: slice assumes left padding.
790
+ attention_mask = attention_mask[:, -query_length:]
791
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
792
+
793
+ return (
794
+ query_layer,
795
+ key_layer,
796
+ value_layer,
797
+ indices_q,
798
+ (cu_seqlens_q, cu_seqlens_k),
799
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
800
+ )
801
+
802
+
803
+ class LlamaSdpaAttention(LlamaAttention):
804
+ """
805
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
806
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
807
+ SDPA API.
808
+ """
809
+
810
+ # Adapted from LlamaAttention.forward
811
+ def forward(
812
+ self,
813
+ hidden_states: torch.Tensor,
814
+ attention_mask: Optional[torch.Tensor] = None,
815
+ position_ids: Optional[torch.LongTensor] = None,
816
+ past_key_value: Optional[Cache] = None,
817
+ output_attentions: bool = False,
818
+ use_cache: bool = False,
819
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
820
+ if output_attentions:
821
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
822
+ logger.warning_once(
823
+ "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
824
+ '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.'
825
+ )
826
+ return super().forward(
827
+ hidden_states=hidden_states,
828
+ attention_mask=attention_mask,
829
+ position_ids=position_ids,
830
+ past_key_value=past_key_value,
831
+ output_attentions=output_attentions,
832
+ use_cache=use_cache,
833
+ )
834
+
835
+ bsz, q_len, _ = hidden_states.size()
836
+
837
+ query_states = self.q_proj(hidden_states)
838
+ key_states = self.k_proj(hidden_states)
839
+ value_states = self.v_proj(hidden_states)
840
+
841
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
842
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
843
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
844
+
845
+ kv_seq_len = key_states.shape[-2]
846
+ if past_key_value is not None:
847
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
848
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
849
+
850
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
851
+
852
+ if past_key_value is not None:
853
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
854
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
855
+
856
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
857
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
858
+
859
+ if attention_mask is not None:
860
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
861
+ raise ValueError(
862
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
863
+ )
864
+
865
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
866
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
867
+ if query_states.device.type == "cuda" and attention_mask is not None:
868
+ query_states = query_states.contiguous()
869
+ key_states = key_states.contiguous()
870
+ value_states = value_states.contiguous()
871
+
872
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
873
+ query_states,
874
+ key_states,
875
+ value_states,
876
+ attn_mask=attention_mask,
877
+ dropout_p=self.attention_dropout if self.training else 0.0,
878
+ # 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.
879
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
880
+ )
881
+
882
+ attn_output = attn_output.transpose(1, 2).contiguous()
883
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
884
+
885
+ attn_output = self.o_proj(attn_output)
886
+
887
+ return attn_output, None, past_key_value
888
+
889
+
890
+ LLAMA_ATTENTION_CLASSES = {
891
+ "eager": LlamaAttention,
892
+ "flash_attention_2": LlamaFlashAttention2,
893
+ "sdpa": LlamaSdpaAttention,
894
+ }
895
+
896
+
897
+ class LlamaDecoderLayer(nn.Module):
898
+ def __init__(self, config: LlamaConfig, layer_idx: int):
899
+ super().__init__()
900
+ self.hidden_size = config.hidden_size
901
+
902
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
903
+
904
+ self.mlp = LlamaMLP(config)
905
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
906
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
907
+
908
+ def forward(
909
+ self,
910
+ hidden_states: torch.Tensor,
911
+ attention_mask: Optional[torch.Tensor] = None,
912
+ position_ids: Optional[torch.LongTensor] = None,
913
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
914
+ output_attentions: Optional[bool] = False,
915
+ use_cache: Optional[bool] = False,
916
+ **kwargs,
917
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
918
+ """
919
+ Args:
920
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
921
+ attention_mask (`torch.FloatTensor`, *optional*):
922
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
923
+ query_sequence_length, key_sequence_length)` if default attention is used.
924
+ output_attentions (`bool`, *optional*):
925
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
926
+ returned tensors for more detail.
927
+ use_cache (`bool`, *optional*):
928
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
929
+ (see `past_key_values`).
930
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
931
+ """
932
+ if "padding_mask" in kwargs:
933
+ warnings.warn(
934
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
935
+ )
936
+
937
+ residual = hidden_states
938
+
939
+ hidden_states = self.input_layernorm(hidden_states)
940
+
941
+ # Self Attention
942
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
943
+ hidden_states=hidden_states,
944
+ attention_mask=attention_mask,
945
+ position_ids=position_ids,
946
+ past_key_value=past_key_value,
947
+ output_attentions=output_attentions,
948
+ use_cache=use_cache,
949
+ **kwargs,
950
+ )
951
+ hidden_states = residual + hidden_states
952
+
953
+ # Fully Connected
954
+ residual = hidden_states
955
+ hidden_states = self.post_attention_layernorm(hidden_states)
956
+ hidden_states = self.mlp(hidden_states)
957
+ hidden_states = residual + hidden_states
958
+
959
+ outputs = (hidden_states,)
960
+
961
+ if output_attentions:
962
+ outputs += (self_attn_weights,)
963
+
964
+ if use_cache:
965
+ outputs += (present_key_value,)
966
+
967
+ return outputs
968
+
969
+
970
+ LLAMA_START_DOCSTRING = r"""
971
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
972
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
973
+ etc.)
974
+
975
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
976
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
977
+ and behavior.
978
+
979
+ Parameters:
980
+ config ([`LlamaConfig`]):
981
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
982
+ load the weights associated with the model, only the configuration. Check out the
983
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
984
+ """
985
+
986
+
987
+ @add_start_docstrings(
988
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
989
+ LLAMA_START_DOCSTRING,
990
+ )
991
+ class LlamaPreTrainedModel(PreTrainedModel):
992
+ config_class = LlamaConfig
993
+ base_model_prefix = "model"
994
+ supports_gradient_checkpointing = True
995
+ _no_split_modules = ["LlamaDecoderLayer"]
996
+ _skip_keys_device_placement = "past_key_values"
997
+ _supports_flash_attn_2 = True
998
+ _supports_sdpa = True
999
+ _supports_cache_class = True
1000
+
1001
+ def _init_weights(self, module):
1002
+ std = self.config.initializer_range
1003
+ if isinstance(module, nn.Linear):
1004
+ module.weight.data.normal_(mean=0.0, std=std)
1005
+ if module.bias is not None:
1006
+ module.bias.data.zero_()
1007
+ elif isinstance(module, nn.Embedding):
1008
+ module.weight.data.normal_(mean=0.0, std=std)
1009
+ if module.padding_idx is not None:
1010
+ module.weight.data[module.padding_idx].zero_()
1011
+
1012
+
1013
+ LLAMA_INPUTS_DOCSTRING = r"""
1014
+ Args:
1015
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1016
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1017
+ it.
1018
+
1019
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1020
+ [`PreTrainedTokenizer.__call__`] for details.
1021
+
1022
+ [What are input IDs?](../glossary#input-ids)
1023
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1024
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1025
+
1026
+ - 1 for tokens that are **not masked**,
1027
+ - 0 for tokens that are **masked**.
1028
+
1029
+ [What are attention masks?](../glossary#attention-mask)
1030
+
1031
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1032
+ [`PreTrainedTokenizer.__call__`] for details.
1033
+
1034
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1035
+ `past_key_values`).
1036
+
1037
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1038
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1039
+ information on the default strategy.
1040
+
1041
+ - 1 indicates the head is **not masked**,
1042
+ - 0 indicates the head is **masked**.
1043
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1044
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1045
+ config.n_positions - 1]`.
1046
+
1047
+ [What are position IDs?](../glossary#position-ids)
1048
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1049
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1050
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1051
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1052
+
1053
+ Two formats are allowed:
1054
+ - a [`~cache_utils.Cache`] instance;
1055
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1056
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1057
+ cache format.
1058
+
1059
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1060
+ legacy cache format will be returned.
1061
+
1062
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1063
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1064
+ of shape `(batch_size, sequence_length)`.
1065
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1066
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1067
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1068
+ model's internal embedding lookup matrix.
1069
+ use_cache (`bool`, *optional*):
1070
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1071
+ `past_key_values`).
1072
+ output_attentions (`bool`, *optional*):
1073
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1074
+ tensors for more detail.
1075
+ output_hidden_states (`bool`, *optional*):
1076
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1077
+ more detail.
1078
+ return_dict (`bool`, *optional*):
1079
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1080
+ """
1081
+
1082
+
1083
+ @add_start_docstrings(
1084
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
1085
+ LLAMA_START_DOCSTRING,
1086
+ )
1087
+ class LlamaModel(LlamaPreTrainedModel):
1088
+ """
1089
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
1090
+
1091
+ Args:
1092
+ config: LlamaConfig
1093
+ """
1094
+
1095
+ def __init__(self, config: LlamaConfig):
1096
+ super().__init__(config)
1097
+ self.padding_idx = config.pad_token_id
1098
+ self.vocab_size = config.vocab_size
1099
+
1100
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1101
+ self.layers = nn.ModuleList(
1102
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1103
+ )
1104
+ self._use_sdpa = config._attn_implementation == "sdpa"
1105
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1106
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1107
+
1108
+ self.gradient_checkpointing = False
1109
+ # Initialize weights and apply final processing
1110
+ self.post_init()
1111
+
1112
+ def get_input_embeddings(self):
1113
+ return self.embed_tokens
1114
+
1115
+ def set_input_embeddings(self, value):
1116
+ self.embed_tokens = value
1117
+
1118
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1119
+ def forward(
1120
+ self,
1121
+ input_ids: torch.LongTensor = None,
1122
+ attention_mask: Optional[torch.Tensor] = None,
1123
+ position_ids: Optional[torch.LongTensor] = None,
1124
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1125
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1126
+ use_cache: Optional[bool] = None,
1127
+ output_attentions: Optional[bool] = None,
1128
+ output_hidden_states: Optional[bool] = None,
1129
+ return_dict: Optional[bool] = None,
1130
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1131
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1132
+ output_hidden_states = (
1133
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1134
+ )
1135
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1136
+
1137
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1138
+
1139
+ # retrieve input_ids and inputs_embeds
1140
+ if input_ids is not None and inputs_embeds is not None:
1141
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1142
+ elif input_ids is not None:
1143
+ batch_size, seq_length = input_ids.shape[:2]
1144
+ elif inputs_embeds is not None:
1145
+ batch_size, seq_length = inputs_embeds.shape[:2]
1146
+ else:
1147
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1148
+
1149
+ if self.gradient_checkpointing and self.training:
1150
+ if use_cache:
1151
+ logger.warning_once(
1152
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1153
+ )
1154
+ use_cache = False
1155
+
1156
+ past_key_values_length = 0
1157
+ if use_cache:
1158
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1159
+ if use_legacy_cache:
1160
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1161
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1162
+
1163
+ if position_ids is None:
1164
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1165
+ position_ids = torch.arange(
1166
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1167
+ )
1168
+ position_ids = position_ids.unsqueeze(0)
1169
+
1170
+ if inputs_embeds is None:
1171
+ inputs_embeds = self.embed_tokens(input_ids)
1172
+
1173
+ if self._use_flash_attention_2:
1174
+ # 2d mask is passed through the layers
1175
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1176
+ elif self._use_sdpa and not output_attentions:
1177
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1178
+ # the manual implementation that requires a 4D causal mask in all cases.
1179
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1180
+ attention_mask,
1181
+ (batch_size, seq_length),
1182
+ inputs_embeds,
1183
+ past_key_values_length,
1184
+ )
1185
+ else:
1186
+ # 4d mask is passed through the layers
1187
+ attention_mask = _prepare_4d_causal_attention_mask(
1188
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1189
+ )
1190
+
1191
+ # embed positions
1192
+ hidden_states = inputs_embeds
1193
+
1194
+ # decoder layers
1195
+ all_hidden_states = () if output_hidden_states else None
1196
+ all_self_attns = () if output_attentions else None
1197
+ next_decoder_cache = None
1198
+
1199
+ for decoder_layer in self.layers:
1200
+ if output_hidden_states:
1201
+ all_hidden_states += (hidden_states,)
1202
+
1203
+ if self.gradient_checkpointing and self.training:
1204
+ layer_outputs = self._gradient_checkpointing_func(
1205
+ decoder_layer.__call__,
1206
+ hidden_states,
1207
+ attention_mask,
1208
+ position_ids,
1209
+ past_key_values,
1210
+ output_attentions,
1211
+ use_cache,
1212
+ )
1213
+ else:
1214
+ layer_outputs = decoder_layer(
1215
+ hidden_states,
1216
+ attention_mask=attention_mask,
1217
+ position_ids=position_ids,
1218
+ past_key_value=past_key_values,
1219
+ output_attentions=output_attentions,
1220
+ use_cache=use_cache,
1221
+ )
1222
+
1223
+ hidden_states = layer_outputs[0]
1224
+
1225
+ if use_cache:
1226
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1227
+
1228
+ if output_attentions:
1229
+ all_self_attns += (layer_outputs[1],)
1230
+
1231
+ hidden_states = self.norm(hidden_states)
1232
+
1233
+ # add hidden states from the last decoder layer
1234
+ if output_hidden_states:
1235
+ all_hidden_states += (hidden_states,)
1236
+
1237
+ next_cache = None
1238
+ if use_cache:
1239
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1240
+ if not return_dict:
1241
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1242
+ return BaseModelOutputWithPast(
1243
+ last_hidden_state=hidden_states,
1244
+ past_key_values=next_cache,
1245
+ hidden_states=all_hidden_states,
1246
+ attentions=all_self_attns,
1247
+ )
1248
+
1249
+
1250
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1251
+ _tied_weights_keys = ["lm_head.weight"]
1252
+
1253
+ def __init__(self, config):
1254
+ super().__init__(config)
1255
+ self.model = LlamaModel(config)
1256
+ self.vocab_size = config.vocab_size
1257
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1258
+
1259
+ # Initialize weights and apply final processing
1260
+ self.post_init()
1261
+
1262
+ def get_input_embeddings(self):
1263
+ return self.model.embed_tokens
1264
+
1265
+ def set_input_embeddings(self, value):
1266
+ self.model.embed_tokens = value
1267
+
1268
+ def get_output_embeddings(self):
1269
+ return self.lm_head
1270
+
1271
+ def set_output_embeddings(self, new_embeddings):
1272
+ self.lm_head = new_embeddings
1273
+
1274
+ def set_decoder(self, decoder):
1275
+ self.model = decoder
1276
+
1277
+ def get_decoder(self):
1278
+ return self.model
1279
+
1280
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1281
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1282
+ def forward(
1283
+ self,
1284
+ input_ids: torch.LongTensor = None,
1285
+ attention_mask: Optional[torch.Tensor] = None,
1286
+ position_ids: Optional[torch.LongTensor] = None,
1287
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1288
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1289
+ labels: Optional[torch.LongTensor] = None,
1290
+ use_cache: Optional[bool] = None,
1291
+ output_attentions: Optional[bool] = None,
1292
+ output_hidden_states: Optional[bool] = None,
1293
+ return_dict: Optional[bool] = None,
1294
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1295
+ r"""
1296
+ Args:
1297
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1298
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1299
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1300
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1301
+
1302
+ Returns:
1303
+
1304
+ Example:
1305
+
1306
+ ```python
1307
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1308
+
1309
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1310
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1311
+
1312
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1313
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1314
+
1315
+ >>> # Generate
1316
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1317
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1318
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1319
+ ```"""
1320
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1321
+ output_hidden_states = (
1322
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1323
+ )
1324
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1325
+
1326
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1327
+ outputs = self.model(
1328
+ input_ids=input_ids,
1329
+ attention_mask=attention_mask,
1330
+ position_ids=position_ids,
1331
+ past_key_values=past_key_values,
1332
+ inputs_embeds=inputs_embeds,
1333
+ use_cache=use_cache,
1334
+ output_attentions=output_attentions,
1335
+ output_hidden_states=output_hidden_states,
1336
+ return_dict=return_dict,
1337
+ )
1338
+
1339
+ hidden_states = outputs[0]
1340
+ if self.config.pretraining_tp > 1:
1341
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1342
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1343
+ logits = torch.cat(logits, dim=-1)
1344
+ else:
1345
+ logits = self.lm_head(hidden_states)
1346
+ logits = logits.float()
1347
+
1348
+ loss = None
1349
+ if labels is not None:
1350
+ # Shift so that tokens < n predict n
1351
+ shift_logits = logits[..., :-1, :].contiguous()
1352
+ shift_labels = labels[..., 1:].contiguous()
1353
+ # Flatten the tokens
1354
+ loss_fct = CrossEntropyLoss()
1355
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1356
+ shift_labels = shift_labels.view(-1)
1357
+ # Enable model parallelism
1358
+ shift_labels = shift_labels.to(shift_logits.device)
1359
+ loss = loss_fct(shift_logits, shift_labels)
1360
+
1361
+ if not return_dict:
1362
+ output = (logits,) + outputs[1:]
1363
+ return (loss,) + output if loss is not None else output
1364
+
1365
+ return CausalLMOutputWithPast(
1366
+ loss=loss,
1367
+ logits=logits,
1368
+ past_key_values=outputs.past_key_values,
1369
+ hidden_states=outputs.hidden_states,
1370
+ attentions=outputs.attentions,
1371
+ )
1372
+
1373
+ def prepare_inputs_for_generation(
1374
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1375
+ ):
1376
+ if past_key_values is not None:
1377
+ if isinstance(past_key_values, Cache):
1378
+ cache_length = past_key_values.get_seq_length()
1379
+ past_length = past_key_values.seen_tokens
1380
+ max_cache_length = past_key_values.get_max_length()
1381
+ else:
1382
+ cache_length = past_length = past_key_values[0][0].shape[2]
1383
+ max_cache_length = None
1384
+
1385
+ # Keep only the unprocessed tokens:
1386
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1387
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1388
+ # input)
1389
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1390
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1391
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1392
+ # input_ids based on the past_length.
1393
+ elif past_length < input_ids.shape[1]:
1394
+ input_ids = input_ids[:, past_length:]
1395
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1396
+
1397
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1398
+ if (
1399
+ max_cache_length is not None
1400
+ and attention_mask is not None
1401
+ and cache_length + input_ids.shape[1] > max_cache_length
1402
+ ):
1403
+ attention_mask = attention_mask[:, -max_cache_length:]
1404
+
1405
+ position_ids = kwargs.get("position_ids", None)
1406
+ if attention_mask is not None and position_ids is None:
1407
+ # create position_ids on the fly for batch generation
1408
+ position_ids = attention_mask.long().cumsum(-1) - 1
1409
+ position_ids.masked_fill_(attention_mask == 0, 1)
1410
+ if past_key_values:
1411
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1412
+
1413
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1414
+ if inputs_embeds is not None and past_key_values is None:
1415
+ model_inputs = {"inputs_embeds": inputs_embeds}
1416
+ else:
1417
+ model_inputs = {"input_ids": input_ids}
1418
+
1419
+ model_inputs.update(
1420
+ {
1421
+ "position_ids": position_ids,
1422
+ "past_key_values": past_key_values,
1423
+ "use_cache": kwargs.get("use_cache"),
1424
+ "attention_mask": attention_mask,
1425
+ }
1426
+ )
1427
+ return model_inputs
1428
+
1429
+ @staticmethod
1430
+ def _reorder_cache(past_key_values, beam_idx):
1431
+ reordered_past = ()
1432
+ for layer_past in past_key_values:
1433
+ reordered_past += (
1434
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1435
+ )
1436
+ return reordered_past
1437
+
1438
+
1439
+ @add_start_docstrings(
1440
+ """
1441
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1442
+
1443
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1444
+ (e.g. GPT-2) do.
1445
+
1446
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1447
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1448
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1449
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1450
+ each row of the batch).
1451
+ """,
1452
+ LLAMA_START_DOCSTRING,
1453
+ )
1454
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1455
+ def __init__(self, config):
1456
+ super().__init__(config)
1457
+ self.num_labels = config.num_labels
1458
+ self.model = LlamaModel(config)
1459
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1460
+
1461
+ # Initialize weights and apply final processing
1462
+ self.post_init()
1463
+
1464
+ def get_input_embeddings(self):
1465
+ return self.model.embed_tokens
1466
+
1467
+ def set_input_embeddings(self, value):
1468
+ self.model.embed_tokens = value
1469
+
1470
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1471
+ def forward(
1472
+ self,
1473
+ input_ids: torch.LongTensor = None,
1474
+ attention_mask: Optional[torch.Tensor] = None,
1475
+ position_ids: Optional[torch.LongTensor] = None,
1476
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1477
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1478
+ labels: Optional[torch.LongTensor] = None,
1479
+ use_cache: Optional[bool] = None,
1480
+ output_attentions: Optional[bool] = None,
1481
+ output_hidden_states: Optional[bool] = None,
1482
+ return_dict: Optional[bool] = None,
1483
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1484
+ r"""
1485
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1486
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1487
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1488
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1489
+ """
1490
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1491
+
1492
+ transformer_outputs = self.model(
1493
+ input_ids,
1494
+ attention_mask=attention_mask,
1495
+ position_ids=position_ids,
1496
+ past_key_values=past_key_values,
1497
+ inputs_embeds=inputs_embeds,
1498
+ use_cache=use_cache,
1499
+ output_attentions=output_attentions,
1500
+ output_hidden_states=output_hidden_states,
1501
+ return_dict=return_dict,
1502
+ )
1503
+ hidden_states = transformer_outputs[0]
1504
+ logits = self.score(hidden_states)
1505
+
1506
+ if input_ids is not None:
1507
+ batch_size = input_ids.shape[0]
1508
+ else:
1509
+ batch_size = inputs_embeds.shape[0]
1510
+
1511
+ if self.config.pad_token_id is None and batch_size != 1:
1512
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1513
+ if self.config.pad_token_id is None:
1514
+ sequence_lengths = -1
1515
+ else:
1516
+ if input_ids is not None:
1517
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1518
+ logits.device
1519
+ )
1520
+ else:
1521
+ sequence_lengths = -1
1522
+
1523
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1524
+
1525
+ loss = None
1526
+ if labels is not None:
1527
+ labels = labels.to(logits.device)
1528
+ if self.config.problem_type is None:
1529
+ if self.num_labels == 1:
1530
+ self.config.problem_type = "regression"
1531
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1532
+ self.config.problem_type = "single_label_classification"
1533
+ else:
1534
+ self.config.problem_type = "multi_label_classification"
1535
+
1536
+ if self.config.problem_type == "regression":
1537
+ loss_fct = MSELoss()
1538
+ if self.num_labels == 1:
1539
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1540
+ else:
1541
+ loss = loss_fct(pooled_logits, labels)
1542
+ elif self.config.problem_type == "single_label_classification":
1543
+ loss_fct = CrossEntropyLoss()
1544
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1545
+ elif self.config.problem_type == "multi_label_classification":
1546
+ loss_fct = BCEWithLogitsLoss()
1547
+ loss = loss_fct(pooled_logits, labels)
1548
+ if not return_dict:
1549
+ output = (pooled_logits,) + transformer_outputs[1:]
1550
+ return ((loss,) + output) if loss is not None else output
1551
+
1552
+ return SequenceClassifierOutputWithPast(
1553
+ loss=loss,
1554
+ logits=pooled_logits,
1555
+ past_key_values=transformer_outputs.past_key_values,
1556
+ hidden_states=transformer_outputs.hidden_states,
1557
+ attentions=transformer_outputs.attentions,
1558
+ )
pytorch_model.bin.index.json DELETED
@@ -1,330 +0,0 @@
1
- {
2
- "metadata": {
3
- "total_size": 14017511424
4
- },
5
- "weight_map": {
6
- "lm_head.weight": "pytorch_model-00002-of-00002.bin",
7
- "model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
8
- "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
9
- "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
10
- "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
11
- "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
12
- "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
13
- "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
14
- "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
15
- "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
16
- "model.layers.0.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
17
- "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
18
- "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
19
- "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
20
- "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
21
- "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
22
- "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
23
- "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
24
- "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
25
- "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
26
- "model.layers.1.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
27
- "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
28
- "model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
29
- "model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
30
- "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
31
- "model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
32
- "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
33
- "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
34
- "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
35
- "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
36
- "model.layers.10.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
37
- "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
38
- "model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
39
- "model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
40
- "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
41
- "model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
42
- "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
43
- "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
44
- "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
45
- "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
46
- "model.layers.11.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
47
- "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
48
- "model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
49
- "model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
50
- "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
51
- "model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
52
- "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
53
- "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
54
- "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
55
- "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
56
- "model.layers.12.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
57
- "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
58
- "model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
59
- "model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
60
- "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
61
- "model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
62
- "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
63
- "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
64
- "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
65
- "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
66
- "model.layers.13.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
67
- "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
68
- "model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
69
- "model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
70
- "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
71
- "model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
72
- "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
73
- "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
74
- "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
75
- "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
76
- "model.layers.14.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
77
- "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
78
- "model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
79
- "model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
80
- "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
81
- "model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
82
- "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
83
- "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
84
- "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
85
- "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
86
- "model.layers.15.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
87
- "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
88
- "model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
89
- "model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
90
- "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
91
- "model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
92
- "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
93
- "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
94
- "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
95
- "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
96
- "model.layers.16.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
97
- "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
98
- "model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
99
- "model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
100
- "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
101
- "model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
102
- "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
103
- "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
104
- "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
105
- "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
106
- "model.layers.17.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
107
- "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
108
- "model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
109
- "model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
110
- "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
111
- "model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
112
- "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
113
- "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
114
- "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
115
- "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
116
- "model.layers.18.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
117
- "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
118
- "model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
119
- "model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
120
- "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
121
- "model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
122
- "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
123
- "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
124
- "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
125
- "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
126
- "model.layers.19.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
127
- "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
128
- "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
129
- "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
130
- "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
131
- "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
132
- "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
133
- "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
134
- "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
135
- "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
136
- "model.layers.2.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
137
- "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
138
- "model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
139
- "model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
140
- "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
141
- "model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
142
- "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
143
- "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
144
- "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
145
- "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
146
- "model.layers.20.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
147
- "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
148
- "model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
149
- "model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
150
- "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
151
- "model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
152
- "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
153
- "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
154
- "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
155
- "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
156
- "model.layers.21.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
157
- "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
158
- "model.layers.22.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
159
- "model.layers.22.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
160
- "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
161
- "model.layers.22.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
162
- "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
163
- "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
164
- "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
165
- "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
166
- "model.layers.22.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
167
- "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
168
- "model.layers.23.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
169
- "model.layers.23.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
170
- "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
171
- "model.layers.23.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
172
- "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
173
- "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
174
- "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
175
- "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
176
- "model.layers.23.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
177
- "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
178
- "model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
179
- "model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
180
- "model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
181
- "model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
182
- "model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
183
- "model.layers.24.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
184
- "model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
185
- "model.layers.24.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
186
- "model.layers.24.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
187
- "model.layers.24.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
188
- "model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
189
- "model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
190
- "model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
191
- "model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
192
- "model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
193
- "model.layers.25.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
194
- "model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
195
- "model.layers.25.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
196
- "model.layers.25.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
197
- "model.layers.25.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
198
- "model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
199
- "model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
200
- "model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
201
- "model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
202
- "model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
203
- "model.layers.26.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
204
- "model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
205
- "model.layers.26.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
206
- "model.layers.26.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
207
- "model.layers.26.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
208
- "model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
209
- "model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
210
- "model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
211
- "model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
212
- "model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
213
- "model.layers.27.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
214
- "model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
215
- "model.layers.27.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
216
- "model.layers.27.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
217
- "model.layers.27.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
218
- "model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
219
- "model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
220
- "model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
221
- "model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
222
- "model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
223
- "model.layers.28.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
224
- "model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
225
- "model.layers.28.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
226
- "model.layers.28.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
227
- "model.layers.28.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
228
- "model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
229
- "model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
230
- "model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
231
- "model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
232
- "model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
233
- "model.layers.29.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
234
- "model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
235
- "model.layers.29.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
236
- "model.layers.29.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
237
- "model.layers.29.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
238
- "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
239
- "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
240
- "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
241
- "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
242
- "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
243
- "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
244
- "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
245
- "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
246
- "model.layers.3.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
247
- "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
248
- "model.layers.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
249
- "model.layers.30.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
250
- "model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
251
- "model.layers.30.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
252
- "model.layers.30.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
253
- "model.layers.30.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
254
- "model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
255
- "model.layers.30.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
256
- "model.layers.30.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
257
- "model.layers.30.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
258
- "model.layers.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
259
- "model.layers.31.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
260
- "model.layers.31.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
261
- "model.layers.31.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
262
- "model.layers.31.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
263
- "model.layers.31.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
264
- "model.layers.31.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
265
- "model.layers.31.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
266
- "model.layers.31.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
267
- "model.layers.31.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
268
- "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
269
- "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
270
- "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
271
- "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
272
- "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
273
- "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
274
- "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
275
- "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
276
- "model.layers.4.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
277
- "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
278
- "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
279
- "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
280
- "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
281
- "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
282
- "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
283
- "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
284
- "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
285
- "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
286
- "model.layers.5.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
287
- "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
288
- "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
289
- "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
290
- "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
291
- "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
292
- "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
293
- "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
294
- "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
295
- "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
296
- "model.layers.6.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
297
- "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
298
- "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
299
- "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
300
- "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
301
- "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
302
- "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
303
- "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
304
- "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
305
- "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
306
- "model.layers.7.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
307
- "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
308
- "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
309
- "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
310
- "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
311
- "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
312
- "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
313
- "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
314
- "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
315
- "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
316
- "model.layers.8.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
317
- "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
318
- "model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
319
- "model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
320
- "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
321
- "model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
322
- "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
323
- "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
324
- "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
325
- "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
326
- "model.layers.9.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
327
- "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
328
- "model.norm.weight": "pytorch_model-00002-of-00002.bin"
329
- }
330
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
special_tokens_map.json CHANGED
@@ -13,7 +13,13 @@
13
  "rstrip": false,
14
  "single_word": false
15
  },
16
- "pad_token": "</s>",
 
 
 
 
 
 
17
  "unk_token": {
18
  "content": "<unk>",
19
  "lstrip": false,
 
13
  "rstrip": false,
14
  "single_word": false
15
  },
16
+ "pad_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
  "unk_token": {
24
  "content": "<unk>",
25
  "lstrip": false,
tokenizer_config.json CHANGED
@@ -1,34 +1,41 @@
1
  {
2
  "add_bos_token": false,
3
  "add_eos_token": false,
4
- "bos_token": {
5
- "__type": "AddedToken",
6
- "content": "<s>",
7
- "lstrip": false,
8
- "normalized": true,
9
- "rstrip": false,
10
- "single_word": false
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  },
 
12
  "clean_up_tokenization_spaces": false,
13
- "eos_token": {
14
- "__type": "AddedToken",
15
- "content": "</s>",
16
- "lstrip": false,
17
- "normalized": true,
18
- "rstrip": false,
19
- "single_word": false
20
- },
21
  "legacy": true,
22
  "model_max_length": 1000000000000000019884624838656,
23
- "pad_token": null,
24
  "sp_model_kwargs": {},
 
25
  "tokenizer_class": "LlamaTokenizer",
26
- "unk_token": {
27
- "__type": "AddedToken",
28
- "content": "<unk>",
29
- "lstrip": false,
30
- "normalized": true,
31
- "rstrip": false,
32
- "single_word": false
33
- }
34
  }
 
1
  {
2
  "add_bos_token": false,
3
  "add_eos_token": false,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": true,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ }
29
  },
30
+ "bos_token": "<s>",
31
  "clean_up_tokenization_spaces": false,
32
+ "eos_token": "</s>",
 
 
 
 
 
 
 
33
  "legacy": true,
34
  "model_max_length": 1000000000000000019884624838656,
35
+ "pad_token": "</s>",
36
  "sp_model_kwargs": {},
37
+ "spaces_between_special_tokens": false,
38
  "tokenizer_class": "LlamaTokenizer",
39
+ "unk_token": "<unk>",
40
+ "use_default_system_prompt": false
 
 
 
 
 
 
41
  }
zero_to_fp32.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Copyright (c) Microsoft Corporation.
4
+ # SPDX-License-Identifier: Apache-2.0
5
+
6
+ # DeepSpeed Team
7
+
8
+ # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
9
+ # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
10
+ # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
11
+ # application.
12
+ #
13
+ # example: python zero_to_fp32.py . pytorch_model.bin
14
+
15
+ import argparse
16
+ import torch
17
+ import glob
18
+ import math
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from dataclasses import dataclass
23
+
24
+ # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
25
+ # DeepSpeed data structures it has to be available in the current python environment.
26
+ from deepspeed.utils import logger
27
+ from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
28
+ FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
29
+ FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
30
+
31
+
32
+ @dataclass
33
+ class zero_model_state:
34
+ buffers: dict()
35
+ param_shapes: dict()
36
+ shared_params: list
37
+ ds_version: int
38
+ frozen_param_shapes: dict()
39
+ frozen_param_fragments: dict()
40
+
41
+
42
+ debug = 0
43
+
44
+ # load to cpu
45
+ device = torch.device('cpu')
46
+
47
+
48
+ def atoi(text):
49
+ return int(text) if text.isdigit() else text
50
+
51
+
52
+ def natural_keys(text):
53
+ '''
54
+ alist.sort(key=natural_keys) sorts in human order
55
+ http://nedbatchelder.com/blog/200712/human_sorting.html
56
+ (See Toothy's implementation in the comments)
57
+ '''
58
+ return [atoi(c) for c in re.split(r'(\d+)', text)]
59
+
60
+
61
+ def get_model_state_file(checkpoint_dir, zero_stage):
62
+ if not os.path.isdir(checkpoint_dir):
63
+ raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
64
+
65
+ # there should be only one file
66
+ if zero_stage <= 2:
67
+ file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
68
+ elif zero_stage == 3:
69
+ file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
70
+
71
+ if not os.path.exists(file):
72
+ raise FileNotFoundError(f"can't find model states file at '{file}'")
73
+
74
+ return file
75
+
76
+
77
+ def get_checkpoint_files(checkpoint_dir, glob_pattern):
78
+ # XXX: need to test that this simple glob rule works for multi-node setup too
79
+ ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
80
+
81
+ if len(ckpt_files) == 0:
82
+ raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
83
+
84
+ return ckpt_files
85
+
86
+
87
+ def get_optim_files(checkpoint_dir):
88
+ return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
89
+
90
+
91
+ def get_model_state_files(checkpoint_dir):
92
+ return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
93
+
94
+
95
+ def parse_model_states(files):
96
+ zero_model_states = []
97
+ for file in files:
98
+ state_dict = torch.load(file, map_location=device)
99
+
100
+ if BUFFER_NAMES not in state_dict:
101
+ raise ValueError(f"{file} is not a model state checkpoint")
102
+ buffer_names = state_dict[BUFFER_NAMES]
103
+ if debug:
104
+ print("Found buffers:", buffer_names)
105
+
106
+ # recover just the buffers while restoring them to fp32 if they were saved in fp16
107
+ buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
108
+ param_shapes = state_dict[PARAM_SHAPES]
109
+
110
+ # collect parameters that are included in param_shapes
111
+ param_names = []
112
+ for s in param_shapes:
113
+ for name in s.keys():
114
+ param_names.append(name)
115
+
116
+ # update with frozen parameters
117
+ frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
118
+ if frozen_param_shapes is not None:
119
+ if debug:
120
+ print(f"Found frozen_param_shapes: {frozen_param_shapes}")
121
+ param_names += list(frozen_param_shapes.keys())
122
+
123
+ # handle shared params
124
+ shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
125
+
126
+ ds_version = state_dict.get(DS_VERSION, None)
127
+
128
+ frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
129
+
130
+ z_model_state = zero_model_state(buffers=buffers,
131
+ param_shapes=param_shapes,
132
+ shared_params=shared_params,
133
+ ds_version=ds_version,
134
+ frozen_param_shapes=frozen_param_shapes,
135
+ frozen_param_fragments=frozen_param_fragments)
136
+ zero_model_states.append(z_model_state)
137
+
138
+ return zero_model_states
139
+
140
+
141
+ def parse_optim_states(files, ds_checkpoint_dir):
142
+
143
+ total_files = len(files)
144
+ state_dicts = []
145
+ for f in files:
146
+ state_dict = torch.load(f, map_location=device)
147
+ # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
148
+ # and also handle the case where it was already removed by another helper script
149
+ state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
150
+ state_dicts.append(state_dict)
151
+
152
+ if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
153
+ raise ValueError(f"{files[0]} is not a zero checkpoint")
154
+ zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
155
+ world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
156
+
157
+ # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
158
+ # parameters can be different from data parallelism for non-expert parameters. So we can just
159
+ # use the max of the partition_count to get the dp world_size.
160
+
161
+ if type(world_size) is list:
162
+ world_size = max(world_size)
163
+
164
+ if world_size != total_files:
165
+ raise ValueError(
166
+ f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
167
+ "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
168
+ )
169
+
170
+ # the groups are named differently in each stage
171
+ if zero_stage <= 2:
172
+ fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
173
+ elif zero_stage == 3:
174
+ fp32_groups_key = FP32_FLAT_GROUPS
175
+ else:
176
+ raise ValueError(f"unknown zero stage {zero_stage}")
177
+
178
+ if zero_stage <= 2:
179
+ fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
180
+ elif zero_stage == 3:
181
+ # if there is more than one param group, there will be multiple flattened tensors - one
182
+ # flattened tensor per group - for simplicity merge them into a single tensor
183
+ #
184
+ # XXX: could make the script more memory efficient for when there are multiple groups - it
185
+ # will require matching the sub-lists of param_shapes for each param group flattened tensor
186
+
187
+ fp32_flat_groups = [
188
+ torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
189
+ ]
190
+
191
+ return zero_stage, world_size, fp32_flat_groups
192
+
193
+
194
+ def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
195
+ """
196
+ Returns fp32 state_dict reconstructed from ds checkpoint
197
+
198
+ Args:
199
+ - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
200
+
201
+ """
202
+ print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
203
+
204
+ optim_files = get_optim_files(ds_checkpoint_dir)
205
+ zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
206
+ print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
207
+
208
+ model_files = get_model_state_files(ds_checkpoint_dir)
209
+
210
+ zero_model_states = parse_model_states(model_files)
211
+ print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
212
+
213
+ if zero_stage <= 2:
214
+ return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states)
215
+ elif zero_stage == 3:
216
+ return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states)
217
+
218
+
219
+ def _zero2_merge_frozen_params(state_dict, zero_model_states):
220
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
221
+ return
222
+
223
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
224
+ frozen_param_fragments = zero_model_states[0].frozen_param_fragments
225
+
226
+ if debug:
227
+ num_elem = sum(s.numel() for s in frozen_param_shapes.values())
228
+ print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
229
+
230
+ wanted_params = len(frozen_param_shapes)
231
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
232
+ avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
233
+ print(f'Frozen params: Have {avail_numel} numels to process.')
234
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
235
+
236
+ total_params = 0
237
+ total_numel = 0
238
+ for name, shape in frozen_param_shapes.items():
239
+ total_params += 1
240
+ unpartitioned_numel = shape.numel()
241
+ total_numel += unpartitioned_numel
242
+
243
+ state_dict[name] = frozen_param_fragments[name]
244
+
245
+ if debug:
246
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
247
+
248
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
249
+
250
+
251
+ def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
252
+ param_shapes = zero_model_states[0].param_shapes
253
+
254
+ # Reconstruction protocol:
255
+ #
256
+ # XXX: document this
257
+
258
+ if debug:
259
+ for i in range(world_size):
260
+ for j in range(len(fp32_flat_groups[0])):
261
+ print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
262
+
263
+ # XXX: memory usage doubles here (zero2)
264
+ num_param_groups = len(fp32_flat_groups[0])
265
+ merged_single_partition_of_fp32_groups = []
266
+ for i in range(num_param_groups):
267
+ merged_partitions = [sd[i] for sd in fp32_flat_groups]
268
+ full_single_fp32_vector = torch.cat(merged_partitions, 0)
269
+ merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
270
+ avail_numel = sum(
271
+ [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
272
+
273
+ if debug:
274
+ wanted_params = sum([len(shapes) for shapes in param_shapes])
275
+ wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
276
+ # not asserting if there is a mismatch due to possible padding
277
+ print(f"Have {avail_numel} numels to process.")
278
+ print(f"Need {wanted_numel} numels in {wanted_params} params.")
279
+
280
+ # params
281
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
282
+ # out-of-core computing solution
283
+ total_numel = 0
284
+ total_params = 0
285
+ for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
286
+ offset = 0
287
+ avail_numel = full_single_fp32_vector.numel()
288
+ for name, shape in shapes.items():
289
+
290
+ unpartitioned_numel = shape.numel()
291
+ total_numel += unpartitioned_numel
292
+ total_params += 1
293
+
294
+ if debug:
295
+ print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
296
+ state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
297
+ offset += unpartitioned_numel
298
+
299
+ # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
300
+ # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
301
+ # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
302
+ # live optimizer object, so we are checking that the numbers are within the right range
303
+ align_to = 2 * world_size
304
+
305
+ def zero2_align(x):
306
+ return align_to * math.ceil(x / align_to)
307
+
308
+ if debug:
309
+ print(f"original offset={offset}, avail_numel={avail_numel}")
310
+
311
+ offset = zero2_align(offset)
312
+ avail_numel = zero2_align(avail_numel)
313
+
314
+ if debug:
315
+ print(f"aligned offset={offset}, avail_numel={avail_numel}")
316
+
317
+ # Sanity check
318
+ if offset != avail_numel:
319
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
320
+
321
+ print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
322
+
323
+
324
+ def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states):
325
+ state_dict = OrderedDict()
326
+
327
+ # buffers
328
+ buffers = zero_model_states[0].buffers
329
+ state_dict.update(buffers)
330
+ if debug:
331
+ print(f"added {len(buffers)} buffers")
332
+
333
+ _zero2_merge_frozen_params(state_dict, zero_model_states)
334
+
335
+ _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
336
+
337
+ # recover shared parameters
338
+ for pair in zero_model_states[0].shared_params:
339
+ if pair[1] in state_dict:
340
+ state_dict[pair[0]] = state_dict[pair[1]]
341
+
342
+ return state_dict
343
+
344
+
345
+ def zero3_partitioned_param_info(unpartitioned_numel, world_size):
346
+ remainder = unpartitioned_numel % world_size
347
+ padding_numel = (world_size - remainder) if remainder else 0
348
+ partitioned_numel = math.ceil(unpartitioned_numel / world_size)
349
+ return partitioned_numel, padding_numel
350
+
351
+
352
+ def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
353
+ if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
354
+ return
355
+
356
+ if debug:
357
+ for i in range(world_size):
358
+ num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
359
+ print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
360
+
361
+ frozen_param_shapes = zero_model_states[0].frozen_param_shapes
362
+ wanted_params = len(frozen_param_shapes)
363
+ wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
364
+ avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
365
+ print(f'Frozen params: Have {avail_numel} numels to process.')
366
+ print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
367
+
368
+ total_params = 0
369
+ total_numel = 0
370
+ for name, shape in zero_model_states[0].frozen_param_shapes.items():
371
+ total_params += 1
372
+ unpartitioned_numel = shape.numel()
373
+ total_numel += unpartitioned_numel
374
+
375
+ param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
376
+ state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
377
+
378
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
379
+
380
+ if debug:
381
+ print(
382
+ f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
383
+ )
384
+
385
+ print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
386
+
387
+
388
+ def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
389
+ param_shapes = zero_model_states[0].param_shapes
390
+ avail_numel = fp32_flat_groups[0].numel() * world_size
391
+ # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
392
+ # param, re-consolidating each param, while dealing with padding if any
393
+
394
+ # merge list of dicts, preserving order
395
+ param_shapes = {k: v for d in param_shapes for k, v in d.items()}
396
+
397
+ if debug:
398
+ for i in range(world_size):
399
+ print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
400
+
401
+ wanted_params = len(param_shapes)
402
+ wanted_numel = sum(shape.numel() for shape in param_shapes.values())
403
+ # not asserting if there is a mismatch due to possible padding
404
+ avail_numel = fp32_flat_groups[0].numel() * world_size
405
+ print(f"Trainable params: Have {avail_numel} numels to process.")
406
+ print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
407
+
408
+ # params
409
+ # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
410
+ # out-of-core computing solution
411
+ offset = 0
412
+ total_numel = 0
413
+ total_params = 0
414
+ for name, shape in param_shapes.items():
415
+
416
+ unpartitioned_numel = shape.numel()
417
+ total_numel += unpartitioned_numel
418
+ total_params += 1
419
+
420
+ partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
421
+
422
+ if debug:
423
+ print(
424
+ f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
425
+ )
426
+
427
+ # XXX: memory usage doubles here
428
+ state_dict[name] = torch.cat(
429
+ tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
430
+ 0).narrow(0, 0, unpartitioned_numel).view(shape)
431
+ offset += partitioned_numel
432
+
433
+ offset *= world_size
434
+
435
+ # Sanity check
436
+ if offset != avail_numel:
437
+ raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
438
+
439
+ print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
440
+
441
+
442
+ def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states):
443
+ state_dict = OrderedDict()
444
+
445
+ # buffers
446
+ buffers = zero_model_states[0].buffers
447
+ state_dict.update(buffers)
448
+ if debug:
449
+ print(f"added {len(buffers)} buffers")
450
+
451
+ _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
452
+
453
+ _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
454
+
455
+ # recover shared parameters
456
+ for pair in zero_model_states[0].shared_params:
457
+ if pair[1] in state_dict:
458
+ state_dict[pair[0]] = state_dict[pair[1]]
459
+
460
+ return state_dict
461
+
462
+
463
+ def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
464
+ """
465
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
466
+ ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
467
+ via a model hub.
468
+
469
+ Args:
470
+ - ``checkpoint_dir``: path to the desired checkpoint folder
471
+ - ``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``
472
+
473
+ Returns:
474
+ - pytorch ``state_dict``
475
+
476
+ Note: this approach may not work if your application doesn't have sufficient free CPU memory and
477
+ you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
478
+ the checkpoint.
479
+
480
+ A typical usage might be ::
481
+
482
+ from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
483
+ # do the training and checkpoint saving
484
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
485
+ model = model.cpu() # move to cpu
486
+ model.load_state_dict(state_dict)
487
+ # submit to model hub or save the model to share with others
488
+
489
+ In this example the ``model`` will no longer be usable in the deepspeed context of the same
490
+ application. i.e. you will need to re-initialize the deepspeed engine, since
491
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
492
+
493
+ If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
494
+
495
+ """
496
+ if tag is None:
497
+ latest_path = os.path.join(checkpoint_dir, 'latest')
498
+ if os.path.isfile(latest_path):
499
+ with open(latest_path, 'r') as fd:
500
+ tag = fd.read().strip()
501
+ else:
502
+ raise ValueError(f"Unable to find 'latest' file at {latest_path}")
503
+
504
+ ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
505
+
506
+ if not os.path.isdir(ds_checkpoint_dir):
507
+ raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
508
+
509
+ return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
510
+
511
+
512
+ def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
513
+ """
514
+ Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
515
+ loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
516
+
517
+ Args:
518
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
519
+ - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
520
+ - ``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``
521
+ """
522
+
523
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
524
+ print(f"Saving fp32 state dict to {output_file}")
525
+ torch.save(state_dict, output_file)
526
+
527
+
528
+ def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
529
+ """
530
+ 1. Put the provided model to cpu
531
+ 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
532
+ 3. Load it into the provided model
533
+
534
+ Args:
535
+ - ``model``: the model object to update
536
+ - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
537
+ - ``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``
538
+
539
+ Returns:
540
+ - ``model`: modified model
541
+
542
+ Make sure you have plenty of CPU memory available before you call this function. If you don't
543
+ have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
544
+ conveniently placed for you in the checkpoint folder.
545
+
546
+ A typical usage might be ::
547
+
548
+ from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
549
+ model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
550
+ # submit to model hub or save the model to share with others
551
+
552
+ Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
553
+ of the same application. i.e. you will need to re-initialize the deepspeed engine, since
554
+ ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
555
+
556
+ """
557
+ logger.info(f"Extracting fp32 weights")
558
+ state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
559
+
560
+ logger.info(f"Overwriting model with fp32 weights")
561
+ model = model.cpu()
562
+ model.load_state_dict(state_dict, strict=False)
563
+
564
+ return model
565
+
566
+
567
+ if __name__ == "__main__":
568
+
569
+ parser = argparse.ArgumentParser()
570
+ parser.add_argument("checkpoint_dir",
571
+ type=str,
572
+ help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
573
+ parser.add_argument(
574
+ "output_file",
575
+ type=str,
576
+ help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
577
+ parser.add_argument("-t",
578
+ "--tag",
579
+ type=str,
580
+ default=None,
581
+ help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
582
+ parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
583
+ args = parser.parse_args()
584
+
585
+ debug = args.debug
586
+
587
+ convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag)