ITcoder commited on
Commit
0c86e84
·
verified ·
1 Parent(s): b378bb0

Upload folder using huggingface_hub

Browse files
Llama3.1-8B-Instruct/__pycache__/configuration_llama.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
Llama3.1-8B-Instruct/__pycache__/modeling_llama.cpython-310.pyc ADDED
Binary file (28.8 kB). View file
 
Llama3.1-8B-Instruct/config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "LlamaForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_llama.LlamaConfig",
9
+ "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM"
10
+ },
11
+ "bos_token_id": 128000,
12
+ "dtype": "bfloat16",
13
+ "eos_token_id": [
14
+ 128001,
15
+ 128008,
16
+ 128009
17
+ ],
18
+ "ffn_output_gate": true,
19
+ "head_dim": 128,
20
+ "hidden_act": "silu",
21
+ "hidden_size": 4096,
22
+ "initializer_range": 0.02,
23
+ "intermediate_size": 14336,
24
+ "max_position_embeddings": 131072,
25
+ "mlp_bias": false,
26
+ "model_type": "llama",
27
+ "num_attention_heads": 32,
28
+ "num_hidden_layers": 32,
29
+ "num_key_value_heads": 8,
30
+ "pretraining_tp": 1,
31
+ "rms_norm_eps": 1e-05,
32
+ "rope_scaling": {
33
+ "factor": 8.0,
34
+ "high_freq_factor": 4.0,
35
+ "low_freq_factor": 1.0,
36
+ "original_max_position_embeddings": 8192,
37
+ "rope_type": "llama3"
38
+ },
39
+ "rope_theta": 500000.0,
40
+ "tie_word_embeddings": false,
41
+ "torch_dtype": "bfloat16",
42
+ "transformers_version": "4.52.3",
43
+ "use_cache": true,
44
+ "vocab_size": 128256
45
+ }
Llama3.1-8B-Instruct/configuration_llama.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.modeling_rope_utils import rope_config_validation
24
+ from transformers.utils import logging
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class LlamaConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
32
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
33
+ defaults will yield a similar configuration to that of the LLaMA-7B.
34
+ e.g. [meta-llama/Llama-2-7b-hf](https://huggingface.co/meta-llama/Llama-2-7b-hf)
35
+
36
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
37
+ documentation from [`PretrainedConfig`] for more information.
38
+
39
+
40
+ Args:
41
+ vocab_size (`int`, *optional*, defaults to 32000):
42
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
43
+ `inputs_ids` passed when calling [`LlamaModel`]
44
+ hidden_size (`int`, *optional*, defaults to 4096):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 11008):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 32):
49
+ Number of hidden layers in the Transformer decoder.
50
+ num_attention_heads (`int`, *optional*, defaults to 32):
51
+ Number of attention heads for each attention layer in the Transformer decoder.
52
+ num_key_value_heads (`int`, *optional*):
53
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
54
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
55
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
56
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
57
+ by meanpooling all the original heads within that group. For more details checkout [this
58
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
59
+ `num_attention_heads`.
60
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
61
+ The non-linear activation function (function or string) in the decoder.
62
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
63
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
64
+ Llama 2 up to 4096, CodeLlama up to 16384.
65
+ initializer_range (`float`, *optional*, defaults to 0.02):
66
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
67
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
68
+ The epsilon used by the rms normalization layers.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
71
+ relevant if `config.is_decoder=True`.
72
+ pad_token_id (`int`, *optional*):
73
+ Padding token id.
74
+ bos_token_id (`int`, *optional*, defaults to 1):
75
+ Beginning of stream token id.
76
+ eos_token_id (`int`, *optional*, defaults to 2):
77
+ End of stream token id.
78
+ pretraining_tp (`int`, *optional*, defaults to 1):
79
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
80
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
81
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
82
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
83
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
84
+ Whether to tie weight embeddings
85
+ rope_theta (`float`, *optional*, defaults to 10000.0):
86
+ The base period of the RoPE embeddings.
87
+ rope_scaling (`Dict`, *optional*):
88
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
89
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
90
+ accordingly.
91
+ Expected contents:
92
+ `rope_type` (`str`):
93
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
94
+ 'llama3'], with 'default' being the original RoPE implementation.
95
+ `factor` (`float`, *optional*):
96
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
97
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
98
+ original maximum pre-trained length.
99
+ `original_max_position_embeddings` (`int`, *optional*):
100
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
101
+ pretraining.
102
+ `attention_factor` (`float`, *optional*):
103
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
104
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
105
+ `factor` field to infer the suggested value.
106
+ `beta_fast` (`float`, *optional*):
107
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
108
+ ramp function. If unspecified, it defaults to 32.
109
+ `beta_slow` (`float`, *optional*):
110
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
111
+ ramp function. If unspecified, it defaults to 1.
112
+ `short_factor` (`List[float]`, *optional*):
113
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
114
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
115
+ size divided by the number of attention heads divided by 2
116
+ `long_factor` (`List[float]`, *optional*):
117
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
118
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
119
+ size divided by the number of attention heads divided by 2
120
+ `low_freq_factor` (`float`, *optional*):
121
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
122
+ `high_freq_factor` (`float`, *optional*):
123
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
124
+ attention_bias (`bool`, *optional*, defaults to `False`):
125
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
126
+ attention_dropout (`float`, *optional*, defaults to 0.0):
127
+ The dropout ratio for the attention probabilities.
128
+ mlp_bias (`bool`, *optional*, defaults to `False`):
129
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
130
+ head_dim (`int`, *optional*):
131
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
132
+
133
+ ```python
134
+ >>> from transformers import LlamaModel, LlamaConfig
135
+
136
+ >>> # Initializing a LLaMA llama-7b style configuration
137
+ >>> configuration = LlamaConfig()
138
+
139
+ >>> # Initializing a model from the llama-7b style configuration
140
+ >>> model = LlamaModel(configuration)
141
+
142
+ >>> # Accessing the model configuration
143
+ >>> configuration = model.config
144
+ ```"""
145
+
146
+ model_type = "llama"
147
+ keys_to_ignore_at_inference = ["past_key_values"]
148
+ # Default tensor parallel plan for base model `LlamaModel`
149
+ base_model_tp_plan = {
150
+ "layers.*.self_attn.q_proj": "colwise",
151
+ "layers.*.self_attn.k_proj": "colwise",
152
+ "layers.*.self_attn.v_proj": "colwise",
153
+ "layers.*.self_attn.o_proj": "rowwise",
154
+ "layers.*.mlp.gate_proj": "colwise",
155
+ "layers.*.mlp.up_proj": "colwise",
156
+ "layers.*.mlp.down_proj": "rowwise",
157
+ }
158
+ base_model_pp_plan = {
159
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
160
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
161
+ "norm": (["hidden_states"], ["hidden_states"]),
162
+ }
163
+
164
+ def __init__(
165
+ self,
166
+ vocab_size=32000,
167
+ hidden_size=4096,
168
+ intermediate_size=11008,
169
+ num_hidden_layers=32,
170
+ num_attention_heads=32,
171
+ num_key_value_heads=None,
172
+ hidden_act="silu",
173
+ max_position_embeddings=2048,
174
+ initializer_range=0.02,
175
+ rms_norm_eps=1e-6,
176
+ use_cache=True,
177
+ pad_token_id=None,
178
+ bos_token_id=1,
179
+ eos_token_id=2,
180
+ pretraining_tp=1,
181
+ tie_word_embeddings=False,
182
+ rope_theta=10000.0,
183
+ rope_scaling=None,
184
+ attention_bias=False,
185
+ attention_dropout=0.0,
186
+ mlp_bias=False,
187
+ head_dim=None,
188
+ ffn_output_gate=False,
189
+ **kwargs,
190
+ ):
191
+ self.vocab_size = vocab_size
192
+ self.max_position_embeddings = max_position_embeddings
193
+ self.hidden_size = hidden_size
194
+ self.intermediate_size = intermediate_size
195
+ self.num_hidden_layers = num_hidden_layers
196
+ self.num_attention_heads = num_attention_heads
197
+
198
+ # for backward compatibility
199
+ if num_key_value_heads is None:
200
+ num_key_value_heads = num_attention_heads
201
+
202
+ self.num_key_value_heads = num_key_value_heads
203
+ self.hidden_act = hidden_act
204
+ self.initializer_range = initializer_range
205
+ self.rms_norm_eps = rms_norm_eps
206
+ self.pretraining_tp = pretraining_tp
207
+ self.use_cache = use_cache
208
+ self.rope_theta = rope_theta
209
+ self.rope_scaling = rope_scaling
210
+ self.attention_bias = attention_bias
211
+ self.attention_dropout = attention_dropout
212
+ self.mlp_bias = mlp_bias
213
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
214
+ self.ffn_output_gate = ffn_output_gate
215
+
216
+ # Validate the correctness of rotary position embeddings parameters
217
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
218
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
219
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
220
+ rope_config_validation(self)
221
+
222
+ super().__init__(
223
+ pad_token_id=pad_token_id,
224
+ bos_token_id=bos_token_id,
225
+ eos_token_id=eos_token_id,
226
+ tie_word_embeddings=tie_word_embeddings,
227
+ **kwargs,
228
+ )
229
+
230
+
231
+ __all__ = ["LlamaConfig"]
Llama3.1-8B-Instruct/generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 128000,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 128001,
6
+ 128008,
7
+ 128009
8
+ ],
9
+ "temperature": 0.6,
10
+ "top_p": 0.9,
11
+ "transformers_version": "4.52.3"
12
+ }
Llama3.1-8B-Instruct/model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:623962e88be634724e09f6af9e1cee15ec06ab4d87b973d7e9af59a86d646dda
3
+ size 4976967480
Llama3.1-8B-Instruct/model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09d433f650646834a83c580877bd60c6d1f88f7755305c12576b5c7058f9af15
3
+ size 4999802720
Llama3.1-8B-Instruct/model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc1cdddd6bfa91128d6e94ee73d0ce62bfcdb7af29e978ddcab30c66ae9ea7fa
3
+ size 4915916176
Llama3.1-8B-Instruct/model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92ecfe1a2414458b4821ac8c13cf8cb70aed66b5eea8dc5ad9eeb4ff309d6d7b
3
+ size 1168138808
Llama3.1-8B-Instruct/model.safetensors.index.json ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16060784704
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00004-of-00004.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
8
+ "model.layers.0.ffn_gate.bias": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.ffn_gate.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
19
+ "model.layers.1.ffn_gate.bias": "model-00001-of-00004.safetensors",
20
+ "model.layers.1.ffn_gate.weight": "model-00001-of-00004.safetensors",
21
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
23
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
24
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
25
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
28
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
29
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
30
+ "model.layers.10.ffn_gate.bias": "model-00001-of-00004.safetensors",
31
+ "model.layers.10.ffn_gate.weight": "model-00001-of-00004.safetensors",
32
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
33
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
34
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
35
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
36
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
38
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
40
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
41
+ "model.layers.11.ffn_gate.bias": "model-00001-of-00004.safetensors",
42
+ "model.layers.11.ffn_gate.weight": "model-00001-of-00004.safetensors",
43
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
45
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
47
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.12.ffn_gate.bias": "model-00001-of-00004.safetensors",
53
+ "model.layers.12.ffn_gate.weight": "model-00001-of-00004.safetensors",
54
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
57
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
58
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
59
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
60
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
63
+ "model.layers.13.ffn_gate.bias": "model-00001-of-00004.safetensors",
64
+ "model.layers.13.ffn_gate.weight": "model-00001-of-00004.safetensors",
65
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
66
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
67
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
68
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
69
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
70
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
71
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
73
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
74
+ "model.layers.14.ffn_gate.bias": "model-00001-of-00004.safetensors",
75
+ "model.layers.14.ffn_gate.weight": "model-00001-of-00004.safetensors",
76
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
77
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
78
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
79
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
80
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
81
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
82
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
83
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.15.ffn_gate.bias": "model-00001-of-00004.safetensors",
86
+ "model.layers.15.ffn_gate.weight": "model-00001-of-00004.safetensors",
87
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
89
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
91
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
92
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
93
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
94
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
96
+ "model.layers.16.ffn_gate.bias": "model-00001-of-00004.safetensors",
97
+ "model.layers.16.ffn_gate.weight": "model-00001-of-00004.safetensors",
98
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
101
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
103
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
105
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
107
+ "model.layers.17.ffn_gate.bias": "model-00001-of-00004.safetensors",
108
+ "model.layers.17.ffn_gate.weight": "model-00001-of-00004.safetensors",
109
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
110
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
111
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
112
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
113
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
114
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
115
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
116
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
117
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
118
+ "model.layers.18.ffn_gate.bias": "model-00001-of-00004.safetensors",
119
+ "model.layers.18.ffn_gate.weight": "model-00001-of-00004.safetensors",
120
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00004.safetensors",
121
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
122
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
123
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
124
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
125
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
126
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
127
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
128
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
129
+ "model.layers.19.ffn_gate.bias": "model-00001-of-00004.safetensors",
130
+ "model.layers.19.ffn_gate.weight": "model-00001-of-00004.safetensors",
131
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00004.safetensors",
132
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
133
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
134
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
135
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
136
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
137
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
138
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
139
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
140
+ "model.layers.2.ffn_gate.bias": "model-00001-of-00004.safetensors",
141
+ "model.layers.2.ffn_gate.weight": "model-00001-of-00004.safetensors",
142
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
143
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
144
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
145
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
146
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
147
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
148
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
149
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
150
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
151
+ "model.layers.20.ffn_gate.bias": "model-00001-of-00004.safetensors",
152
+ "model.layers.20.ffn_gate.weight": "model-00001-of-00004.safetensors",
153
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
154
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
155
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
156
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
157
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
158
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
159
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
160
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
161
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
162
+ "model.layers.21.ffn_gate.bias": "model-00001-of-00004.safetensors",
163
+ "model.layers.21.ffn_gate.weight": "model-00001-of-00004.safetensors",
164
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
165
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
166
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
167
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
168
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
169
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
170
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
171
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
172
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
173
+ "model.layers.22.ffn_gate.bias": "model-00001-of-00004.safetensors",
174
+ "model.layers.22.ffn_gate.weight": "model-00001-of-00004.safetensors",
175
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
176
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
177
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
178
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
179
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
180
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
181
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
182
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
183
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
184
+ "model.layers.23.ffn_gate.bias": "model-00001-of-00004.safetensors",
185
+ "model.layers.23.ffn_gate.weight": "model-00001-of-00004.safetensors",
186
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
187
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
188
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
189
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
190
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
191
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
192
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
194
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
195
+ "model.layers.24.ffn_gate.bias": "model-00001-of-00004.safetensors",
196
+ "model.layers.24.ffn_gate.weight": "model-00001-of-00004.safetensors",
197
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
198
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
199
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
200
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
201
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
202
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
203
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
204
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
205
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
206
+ "model.layers.25.ffn_gate.bias": "model-00001-of-00004.safetensors",
207
+ "model.layers.25.ffn_gate.weight": "model-00001-of-00004.safetensors",
208
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
209
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
210
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
211
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
212
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
213
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
214
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
215
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
216
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
217
+ "model.layers.26.ffn_gate.bias": "model-00001-of-00004.safetensors",
218
+ "model.layers.26.ffn_gate.weight": "model-00001-of-00004.safetensors",
219
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
220
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
221
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
222
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
223
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
224
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
225
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
226
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
227
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
228
+ "model.layers.27.ffn_gate.bias": "model-00001-of-00004.safetensors",
229
+ "model.layers.27.ffn_gate.weight": "model-00001-of-00004.safetensors",
230
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
231
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
232
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
233
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
234
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
235
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
236
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
237
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
238
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
239
+ "model.layers.28.ffn_gate.bias": "model-00001-of-00004.safetensors",
240
+ "model.layers.28.ffn_gate.weight": "model-00001-of-00004.safetensors",
241
+ "model.layers.28.input_layernorm.weight": "model-00003-of-00004.safetensors",
242
+ "model.layers.28.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
243
+ "model.layers.28.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
244
+ "model.layers.28.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
245
+ "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
246
+ "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
247
+ "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
248
+ "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
249
+ "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
250
+ "model.layers.29.ffn_gate.bias": "model-00001-of-00004.safetensors",
251
+ "model.layers.29.ffn_gate.weight": "model-00001-of-00004.safetensors",
252
+ "model.layers.29.input_layernorm.weight": "model-00003-of-00004.safetensors",
253
+ "model.layers.29.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
254
+ "model.layers.29.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
255
+ "model.layers.29.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
256
+ "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
257
+ "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
258
+ "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
259
+ "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
260
+ "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
261
+ "model.layers.3.ffn_gate.bias": "model-00001-of-00004.safetensors",
262
+ "model.layers.3.ffn_gate.weight": "model-00001-of-00004.safetensors",
263
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
264
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
265
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
266
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
267
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
268
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
269
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
270
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
271
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
272
+ "model.layers.30.ffn_gate.bias": "model-00001-of-00004.safetensors",
273
+ "model.layers.30.ffn_gate.weight": "model-00001-of-00004.safetensors",
274
+ "model.layers.30.input_layernorm.weight": "model-00003-of-00004.safetensors",
275
+ "model.layers.30.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
276
+ "model.layers.30.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
277
+ "model.layers.30.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
278
+ "model.layers.30.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
279
+ "model.layers.30.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
280
+ "model.layers.30.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
281
+ "model.layers.30.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
282
+ "model.layers.30.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
283
+ "model.layers.31.ffn_gate.bias": "model-00001-of-00004.safetensors",
284
+ "model.layers.31.ffn_gate.weight": "model-00001-of-00004.safetensors",
285
+ "model.layers.31.input_layernorm.weight": "model-00004-of-00004.safetensors",
286
+ "model.layers.31.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
287
+ "model.layers.31.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
288
+ "model.layers.31.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
289
+ "model.layers.31.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
290
+ "model.layers.31.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
291
+ "model.layers.31.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
292
+ "model.layers.31.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
293
+ "model.layers.31.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
294
+ "model.layers.4.ffn_gate.bias": "model-00001-of-00004.safetensors",
295
+ "model.layers.4.ffn_gate.weight": "model-00001-of-00004.safetensors",
296
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
297
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
298
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
299
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
300
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
301
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
302
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
303
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
304
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
305
+ "model.layers.5.ffn_gate.bias": "model-00001-of-00004.safetensors",
306
+ "model.layers.5.ffn_gate.weight": "model-00001-of-00004.safetensors",
307
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
308
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
309
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
310
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
311
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
312
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
313
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
314
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
315
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
316
+ "model.layers.6.ffn_gate.bias": "model-00001-of-00004.safetensors",
317
+ "model.layers.6.ffn_gate.weight": "model-00001-of-00004.safetensors",
318
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
319
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
320
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
321
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
322
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
323
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
324
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
325
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
326
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
327
+ "model.layers.7.ffn_gate.bias": "model-00001-of-00004.safetensors",
328
+ "model.layers.7.ffn_gate.weight": "model-00001-of-00004.safetensors",
329
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
330
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
331
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
332
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
333
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
334
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
335
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
336
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
337
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
338
+ "model.layers.8.ffn_gate.bias": "model-00001-of-00004.safetensors",
339
+ "model.layers.8.ffn_gate.weight": "model-00001-of-00004.safetensors",
340
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00004.safetensors",
341
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
342
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
343
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
344
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
345
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
346
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
347
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
348
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
349
+ "model.layers.9.ffn_gate.bias": "model-00001-of-00004.safetensors",
350
+ "model.layers.9.ffn_gate.weight": "model-00001-of-00004.safetensors",
351
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
352
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
353
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
354
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
355
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
356
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
357
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
358
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
359
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
360
+ "model.norm.weight": "model-00004-of-00004.safetensors"
361
+ }
362
+ }
Llama3.1-8B-Instruct/modeling_llama.py ADDED
@@ -0,0 +1,997 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
22
+ from typing import Callable, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache
30
+ from transformers.generation import GenerationMixin
31
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
32
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
33
+ from transformers.modeling_layers import GradientCheckpointingLayer
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
42
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
43
+ from transformers.processing_utils import Unpack
44
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
45
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, is_torch_flex_attn_available, logging
46
+
47
+
48
+ # 支持相对导入和绝对导入
49
+ try:
50
+ from .configuration_llama import LlamaConfig
51
+ except ImportError:
52
+ from configuration_llama import LlamaConfig
53
+
54
+
55
+ if is_torch_flex_attn_available():
56
+ from torch.nn.attention.flex_attention import BlockMask
57
+
58
+ from transformers.integrations.flex_attention import make_flex_block_causal_mask
59
+
60
+ from transformers.integrations import use_kernel_forward_from_hub
61
+
62
+
63
+ logger = logging.get_logger(__name__)
64
+
65
+
66
+ @use_kernel_forward_from_hub("RMSNorm")
67
+ class LlamaRMSNorm(nn.Module):
68
+ def __init__(self, hidden_size, eps=1e-6):
69
+ """
70
+ LlamaRMSNorm is equivalent to T5LayerNorm
71
+ """
72
+ super().__init__()
73
+ self.weight = nn.Parameter(torch.ones(hidden_size))
74
+ self.variance_epsilon = eps
75
+
76
+ def forward(self, hidden_states):
77
+ input_dtype = hidden_states.dtype
78
+ hidden_states = hidden_states.to(torch.float32)
79
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
80
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
81
+ return self.weight * hidden_states.to(input_dtype)
82
+
83
+ def extra_repr(self):
84
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
85
+
86
+
87
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
88
+
89
+
90
+ class LlamaRotaryEmbedding(nn.Module):
91
+ def __init__(self, config: LlamaConfig, device=None):
92
+ super().__init__()
93
+ # BC: "rope_type" was originally "type"
94
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
95
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
96
+ else:
97
+ self.rope_type = "default"
98
+ self.max_seq_len_cached = config.max_position_embeddings
99
+ self.original_max_seq_len = config.max_position_embeddings
100
+
101
+ self.config = config
102
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
103
+
104
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
105
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
106
+ self.original_inv_freq = self.inv_freq
107
+
108
+ @torch.no_grad()
109
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
110
+ def forward(self, x, position_ids):
111
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
112
+ position_ids_expanded = position_ids[:, None, :].float()
113
+
114
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
115
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
116
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
117
+ emb = torch.cat((freqs, freqs), dim=-1)
118
+ cos = emb.cos() * self.attention_scaling
119
+ sin = emb.sin() * self.attention_scaling
120
+
121
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
122
+
123
+
124
+ def rotate_half(x):
125
+ """Rotates half the hidden dims of the input."""
126
+ x1 = x[..., : x.shape[-1] // 2]
127
+ x2 = x[..., x.shape[-1] // 2 :]
128
+ return torch.cat((-x2, x1), dim=-1)
129
+
130
+
131
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
132
+ """Applies Rotary Position Embedding to the query and key tensors.
133
+
134
+ Args:
135
+ q (`torch.Tensor`): The query tensor.
136
+ k (`torch.Tensor`): The key tensor.
137
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
138
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
139
+ position_ids (`torch.Tensor`, *optional*):
140
+ Deprecated and unused.
141
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
142
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
143
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
144
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
145
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
146
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
147
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
148
+ Returns:
149
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
150
+ """
151
+ cos = cos.unsqueeze(unsqueeze_dim)
152
+ sin = sin.unsqueeze(unsqueeze_dim)
153
+ q_embed = (q * cos) + (rotate_half(q) * sin)
154
+ k_embed = (k * cos) + (rotate_half(k) * sin)
155
+ return q_embed, k_embed
156
+
157
+
158
+ class LlamaMLP(nn.Module):
159
+ def __init__(self, config):
160
+ super().__init__()
161
+ self.config = config
162
+ self.hidden_size = config.hidden_size
163
+ self.intermediate_size = config.intermediate_size
164
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
165
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
166
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
167
+ self.act_fn = ACT2FN[config.hidden_act]
168
+
169
+ def forward(self, x):
170
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
171
+ return down_proj
172
+
173
+
174
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
175
+ """
176
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
177
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
178
+ """
179
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
180
+ if n_rep == 1:
181
+ return hidden_states
182
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
183
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
184
+
185
+
186
+ def eager_attention_forward(
187
+ module: nn.Module,
188
+ query: torch.Tensor,
189
+ key: torch.Tensor,
190
+ value: torch.Tensor,
191
+ attention_mask: Optional[torch.Tensor],
192
+ scaling: float,
193
+ dropout: float = 0.0,
194
+ **kwargs,
195
+ ):
196
+ key_states = repeat_kv(key, module.num_key_value_groups)
197
+ value_states = repeat_kv(value, module.num_key_value_groups)
198
+
199
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
200
+ if attention_mask is not None:
201
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
202
+ attn_weights = attn_weights + causal_mask
203
+
204
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
205
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
206
+ attn_output = torch.matmul(attn_weights, value_states)
207
+ attn_output = attn_output.transpose(1, 2).contiguous()
208
+
209
+ return attn_output, attn_weights
210
+
211
+
212
+ class LlamaAttention(nn.Module):
213
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
214
+
215
+ def __init__(self, config: LlamaConfig, layer_idx: int):
216
+ super().__init__()
217
+ self.config = config
218
+ self.layer_idx = layer_idx
219
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
220
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
221
+ self.scaling = self.head_dim**-0.5
222
+ self.attention_dropout = config.attention_dropout
223
+ self.is_causal = True
224
+
225
+ self.q_proj = nn.Linear(
226
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
227
+ )
228
+ self.k_proj = nn.Linear(
229
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
230
+ )
231
+ self.v_proj = nn.Linear(
232
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
233
+ )
234
+ self.o_proj = nn.Linear(
235
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
236
+ )
237
+
238
+ def forward(
239
+ self,
240
+ hidden_states: torch.Tensor,
241
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
242
+ attention_mask: Optional[torch.Tensor],
243
+ past_key_value: Optional[Cache] = None,
244
+ cache_position: Optional[torch.LongTensor] = None,
245
+ **kwargs: Unpack[FlashAttentionKwargs],
246
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
247
+ input_shape = hidden_states.shape[:-1]
248
+ hidden_shape = (*input_shape, -1, self.head_dim)
249
+
250
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
251
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
252
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
253
+
254
+ cos, sin = position_embeddings
255
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
256
+
257
+ if past_key_value is not None:
258
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
259
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
260
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
261
+
262
+ attention_interface: Callable = eager_attention_forward
263
+
264
+ if self.config._attn_implementation != "eager":
265
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
266
+ logger.warning_once(
267
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
268
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
269
+ )
270
+ else:
271
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
272
+
273
+ attn_output, attn_weights = attention_interface(
274
+ self,
275
+ query_states,
276
+ key_states,
277
+ value_states,
278
+ attention_mask,
279
+ dropout=0.0 if not self.training else self.attention_dropout,
280
+ scaling=self.scaling,
281
+ **kwargs,
282
+ )
283
+
284
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
285
+ attn_output = self.o_proj(attn_output)
286
+ return attn_output, attn_weights
287
+
288
+
289
+ class LlamaDecoderLayer(GradientCheckpointingLayer):
290
+ def __init__(self, config: LlamaConfig, layer_idx: int):
291
+ super().__init__()
292
+ self.hidden_size = config.hidden_size
293
+
294
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
295
+
296
+ self.mlp = LlamaMLP(config)
297
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
298
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
299
+
300
+ # FFN output gate: output = residual + 2*sigmoid(gate(residual)) * FFN(x)
301
+ # 残差不变,gate 控制 FFN 贡献比例,范围 (0,2) 可抑制也可增强
302
+ self.ffn_output_gate = config.ffn_output_gate
303
+ if self.ffn_output_gate:
304
+ self.ffn_gate = nn.Linear(config.hidden_size, 1, bias=True)
305
+ # 标记为 ffn_gate,让 _init_weights 用自定义初始化(weight=0, bias=0.0)
306
+ # 不在这里直接 init:device_map 模式下此时是 meta tensor,init 无效
307
+ self.ffn_gate._is_ffn_gate = True
308
+
309
+ def forward(
310
+ self,
311
+ hidden_states: torch.Tensor,
312
+ attention_mask: Optional[torch.Tensor] = None,
313
+ position_ids: Optional[torch.LongTensor] = None,
314
+ past_key_value: Optional[Cache] = None,
315
+ output_attentions: Optional[bool] = False,
316
+ use_cache: Optional[bool] = False,
317
+ cache_position: Optional[torch.LongTensor] = None,
318
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
319
+ **kwargs: Unpack[FlashAttentionKwargs],
320
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
321
+ residual = hidden_states
322
+ hidden_states = self.input_layernorm(hidden_states)
323
+
324
+ # Self Attention
325
+ hidden_states, self_attn_weights = self.self_attn(
326
+ hidden_states=hidden_states,
327
+ attention_mask=attention_mask,
328
+ position_ids=position_ids,
329
+ past_key_value=past_key_value,
330
+ output_attentions=output_attentions,
331
+ use_cache=use_cache,
332
+ cache_position=cache_position,
333
+ position_embeddings=position_embeddings,
334
+ **kwargs,
335
+ )
336
+ hidden_states = residual + hidden_states
337
+
338
+ # Fully Connected
339
+ residual = hidden_states
340
+ hidden_states = self.post_attention_layernorm(hidden_states)
341
+ hidden_states = self.mlp(hidden_states)
342
+ # hidden_states = residual + hidden_states
343
+ if self.ffn_output_gate:
344
+ # gate 由残差流计算,保证残差路径畅通不受影响
345
+ # gate shape: (batch, seq_len, 1) → broadcast 到 (batch, seq_len, hidden_size)
346
+ # clamp 到 [0.7, 1.3],与 Exp06 发现的有效范围匹配
347
+ gate = 2.0 * torch.sigmoid(self.ffn_gate(residual))
348
+ gate = gate.clamp(min=0.7, max=1.3)
349
+ hidden_states = residual + gate * hidden_states # 残差连接(gate 控制 FFN 贡献)
350
+ else:
351
+ hidden_states = residual + hidden_states # 残差连接
352
+
353
+
354
+ outputs = (hidden_states,)
355
+ if output_attentions:
356
+ outputs += (self_attn_weights,)
357
+
358
+ return outputs
359
+
360
+
361
+ @auto_docstring
362
+ class LlamaPreTrainedModel(PreTrainedModel):
363
+ config_class = LlamaConfig
364
+ base_model_prefix = "model"
365
+ supports_gradient_checkpointing = True
366
+ _no_split_modules = ["LlamaDecoderLayer"]
367
+ _skip_keys_device_placement = ["past_key_values"]
368
+ _supports_flash_attn_2 = True
369
+ _supports_sdpa = True
370
+ _supports_flex_attn = True
371
+ _supports_cache_class = True
372
+ _supports_quantized_cache = True
373
+ _supports_static_cache = True
374
+ _supports_attention_backend = True
375
+
376
+ def _init_weights(self, module):
377
+ std = self.config.initializer_range
378
+ if isinstance(module, nn.Linear):
379
+ if getattr(module, '_is_ffn_gate', False):
380
+ # ffn_gate 专用初始化:weight=0, bias=0.0
381
+ # 2*sigmoid(0.0)=1.0,初始 gate 精确为1,行为与原模型完全一致
382
+ # 梯度为 2*sigmoid'(0)=0.5,是 bias=4.0 方案的28倍,学习更高效
383
+ # 训练后 gate ∈ (0,2),可抑制也可增强 FFN 贡献
384
+ # 必须放在 _init_weights 里,__init__ 中 device_map 场景下是 meta tensor 无法 init
385
+ nn.init.zeros_(module.weight)
386
+ nn.init.constant_(module.bias, 0.0)
387
+ return
388
+ module.weight.data.normal_(mean=0.0, std=std)
389
+ if module.bias is not None:
390
+ module.bias.data.zero_()
391
+ elif isinstance(module, nn.Embedding):
392
+ module.weight.data.normal_(mean=0.0, std=std)
393
+ if module.padding_idx is not None:
394
+ module.weight.data[module.padding_idx].zero_()
395
+ elif isinstance(module, LlamaRMSNorm):
396
+ module.weight.data.fill_(1.0)
397
+
398
+
399
+ @auto_docstring
400
+ class LlamaModel(LlamaPreTrainedModel):
401
+ def __init__(self, config: LlamaConfig):
402
+ super().__init__(config)
403
+ self.padding_idx = config.pad_token_id
404
+ self.vocab_size = config.vocab_size
405
+
406
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
407
+ self.layers = nn.ModuleList(
408
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
409
+ )
410
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
411
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
412
+ self.gradient_checkpointing = False
413
+
414
+ # Initialize weights and apply final processing
415
+ self.post_init()
416
+
417
+ def get_input_embeddings(self):
418
+ return self.embed_tokens
419
+
420
+ def set_input_embeddings(self, value):
421
+ self.embed_tokens = value
422
+
423
+ @can_return_tuple
424
+ @auto_docstring
425
+ def forward(
426
+ self,
427
+ input_ids: Optional[torch.LongTensor] = None,
428
+ attention_mask: Optional[torch.Tensor] = None,
429
+ position_ids: Optional[torch.LongTensor] = None,
430
+ past_key_values: Optional[Cache] = None,
431
+ inputs_embeds: Optional[torch.FloatTensor] = None,
432
+ use_cache: Optional[bool] = None,
433
+ output_attentions: Optional[bool] = None,
434
+ output_hidden_states: Optional[bool] = None,
435
+ cache_position: Optional[torch.LongTensor] = None,
436
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
437
+ ) -> BaseModelOutputWithPast:
438
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
439
+ output_hidden_states = (
440
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
441
+ )
442
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
443
+
444
+ if (input_ids is None) ^ (inputs_embeds is not None):
445
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
446
+
447
+ if self.gradient_checkpointing and self.training and use_cache:
448
+ logger.warning_once(
449
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
450
+ )
451
+ use_cache = False
452
+
453
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
454
+ if not isinstance(past_key_values, (type(None), Cache)):
455
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
456
+
457
+ if inputs_embeds is None:
458
+ inputs_embeds = self.embed_tokens(input_ids)
459
+
460
+ if use_cache and past_key_values is None:
461
+ past_key_values = DynamicCache()
462
+
463
+ if cache_position is None:
464
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
465
+ cache_position = torch.arange(
466
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
467
+ )
468
+
469
+ if position_ids is None:
470
+ position_ids = cache_position.unsqueeze(0)
471
+
472
+ causal_mask = self._update_causal_mask(
473
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
474
+ )
475
+
476
+ hidden_states = inputs_embeds
477
+
478
+ # create position embeddings to be shared across the decoder layers
479
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
480
+
481
+ # decoder layers
482
+ all_hidden_states = () if output_hidden_states else None
483
+ all_self_attns = () if output_attentions else None
484
+
485
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
486
+ if output_hidden_states:
487
+ all_hidden_states += (hidden_states,)
488
+
489
+ layer_outputs = decoder_layer(
490
+ hidden_states,
491
+ attention_mask=causal_mask,
492
+ position_ids=position_ids,
493
+ past_key_value=past_key_values,
494
+ output_attentions=output_attentions,
495
+ use_cache=use_cache,
496
+ cache_position=cache_position,
497
+ position_embeddings=position_embeddings,
498
+ **flash_attn_kwargs,
499
+ )
500
+
501
+ hidden_states = layer_outputs[0]
502
+
503
+ if output_attentions:
504
+ all_self_attns += (layer_outputs[1],)
505
+
506
+ hidden_states = self.norm(hidden_states)
507
+
508
+ # add hidden states from the last decoder layer
509
+ if output_hidden_states:
510
+ all_hidden_states += (hidden_states,)
511
+
512
+ return BaseModelOutputWithPast(
513
+ last_hidden_state=hidden_states,
514
+ past_key_values=past_key_values if use_cache else None,
515
+ hidden_states=all_hidden_states,
516
+ attentions=all_self_attns,
517
+ )
518
+
519
+ def _update_causal_mask(
520
+ self,
521
+ attention_mask: Union[torch.Tensor, "BlockMask"],
522
+ input_tensor: torch.Tensor,
523
+ cache_position: torch.Tensor,
524
+ past_key_values: Cache,
525
+ output_attentions: bool = False,
526
+ ):
527
+ if self.config._attn_implementation == "flash_attention_2":
528
+ if attention_mask is not None and (attention_mask == 0.0).any():
529
+ return attention_mask
530
+ return None
531
+ if self.config._attn_implementation == "flex_attention":
532
+ if isinstance(attention_mask, torch.Tensor):
533
+ attention_mask = make_flex_block_causal_mask(attention_mask)
534
+ return attention_mask
535
+
536
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
537
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
538
+ # to infer the attention mask.
539
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
540
+ using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
541
+
542
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
543
+ if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
544
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
545
+ attention_mask,
546
+ inputs_embeds=input_tensor,
547
+ past_key_values_length=past_seen_tokens,
548
+ is_training=self.training,
549
+ ):
550
+ return None
551
+
552
+ dtype = input_tensor.dtype
553
+ sequence_length = input_tensor.shape[1]
554
+ if using_compilable_cache:
555
+ target_length = past_key_values.get_max_cache_shape()
556
+ else:
557
+ target_length = (
558
+ attention_mask.shape[-1]
559
+ if isinstance(attention_mask, torch.Tensor)
560
+ else past_seen_tokens + sequence_length + 1
561
+ )
562
+
563
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
564
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
565
+ attention_mask,
566
+ sequence_length=sequence_length,
567
+ target_length=target_length,
568
+ dtype=dtype,
569
+ cache_position=cache_position,
570
+ batch_size=input_tensor.shape[0],
571
+ )
572
+
573
+ if (
574
+ self.config._attn_implementation == "sdpa"
575
+ and attention_mask is not None
576
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
577
+ and not output_attentions
578
+ ):
579
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
580
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
581
+ # Details: https://github.com/pytorch/pytorch/issues/110213
582
+ min_dtype = torch.finfo(dtype).min
583
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
584
+
585
+ return causal_mask
586
+
587
+ @staticmethod
588
+ def _prepare_4d_causal_attention_mask_with_cache_position(
589
+ attention_mask: torch.Tensor,
590
+ sequence_length: int,
591
+ target_length: int,
592
+ dtype: torch.dtype,
593
+ cache_position: torch.Tensor,
594
+ batch_size: int,
595
+ **kwargs,
596
+ ):
597
+ """
598
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
599
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
600
+
601
+ Args:
602
+ attention_mask (`torch.Tensor`):
603
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
604
+ `(batch_size, 1, query_length, key_value_length)`.
605
+ sequence_length (`int`):
606
+ The sequence length being processed.
607
+ target_length (`int`):
608
+ The target length: when generating with static cache, the mask should be as long as the static cache,
609
+ to account for the 0 padding, the part of the cache that is not filled yet.
610
+ dtype (`torch.dtype`):
611
+ The dtype to use for the 4D attention mask.
612
+ cache_position (`torch.Tensor`):
613
+ Indices depicting the position of the input sequence tokens in the sequence.
614
+ batch_size (`torch.Tensor`):
615
+ Batch size.
616
+ """
617
+ if attention_mask is not None and attention_mask.dim() == 4:
618
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
619
+ causal_mask = attention_mask
620
+ else:
621
+ min_dtype = torch.finfo(dtype).min
622
+ causal_mask = torch.full(
623
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
624
+ )
625
+ if sequence_length != 1:
626
+ causal_mask = torch.triu(causal_mask, diagonal=1)
627
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
628
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
629
+ if attention_mask is not None:
630
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
631
+ mask_length = attention_mask.shape[-1]
632
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
633
+ causal_mask.device
634
+ )
635
+ padding_mask = padding_mask == 0
636
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
637
+ padding_mask, min_dtype
638
+ )
639
+
640
+ return causal_mask
641
+
642
+
643
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
644
+
645
+
646
+ @auto_docstring
647
+ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
648
+ _tied_weights_keys = ["lm_head.weight"]
649
+ _tp_plan = {"lm_head": "colwise_rep"}
650
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
651
+
652
+ def __init__(self, config):
653
+ super().__init__(config)
654
+ self.model = LlamaModel(config)
655
+ self.vocab_size = config.vocab_size
656
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
657
+
658
+ # Initialize weights and apply final processing
659
+ self.post_init()
660
+
661
+ def get_input_embeddings(self):
662
+ return self.model.embed_tokens
663
+
664
+ def set_input_embeddings(self, value):
665
+ self.model.embed_tokens = value
666
+
667
+ def get_output_embeddings(self):
668
+ return self.lm_head
669
+
670
+ def set_output_embeddings(self, new_embeddings):
671
+ self.lm_head = new_embeddings
672
+
673
+ def set_decoder(self, decoder):
674
+ self.model = decoder
675
+
676
+ def get_decoder(self):
677
+ return self.model
678
+
679
+ @can_return_tuple
680
+ @auto_docstring
681
+ def forward(
682
+ self,
683
+ input_ids: Optional[torch.LongTensor] = None,
684
+ attention_mask: Optional[torch.Tensor] = None,
685
+ position_ids: Optional[torch.LongTensor] = None,
686
+ past_key_values: Optional[Cache] = None,
687
+ inputs_embeds: Optional[torch.FloatTensor] = None,
688
+ labels: Optional[torch.LongTensor] = None,
689
+ use_cache: Optional[bool] = None,
690
+ output_attentions: Optional[bool] = None,
691
+ output_hidden_states: Optional[bool] = None,
692
+ cache_position: Optional[torch.LongTensor] = None,
693
+ logits_to_keep: Union[int, torch.Tensor] = 0,
694
+ **kwargs: Unpack[KwargsForCausalLM],
695
+ ) -> CausalLMOutputWithPast:
696
+ r"""
697
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
698
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
699
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
700
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
701
+
702
+ Example:
703
+
704
+ ```python
705
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
706
+
707
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
708
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
709
+
710
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
711
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
712
+
713
+ >>> # Generate
714
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
715
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
716
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
717
+ ```"""
718
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
719
+ output_hidden_states = (
720
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
721
+ )
722
+
723
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
724
+ outputs: BaseModelOutputWithPast = self.model(
725
+ input_ids=input_ids,
726
+ attention_mask=attention_mask,
727
+ position_ids=position_ids,
728
+ past_key_values=past_key_values,
729
+ inputs_embeds=inputs_embeds,
730
+ use_cache=use_cache,
731
+ output_attentions=output_attentions,
732
+ output_hidden_states=output_hidden_states,
733
+ cache_position=cache_position,
734
+ **kwargs,
735
+ )
736
+
737
+ hidden_states = outputs.last_hidden_state
738
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
739
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
740
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
741
+
742
+ loss = None
743
+ if labels is not None:
744
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
745
+
746
+ return CausalLMOutputWithPast(
747
+ loss=loss,
748
+ logits=logits,
749
+ past_key_values=outputs.past_key_values,
750
+ hidden_states=outputs.hidden_states,
751
+ attentions=outputs.attentions,
752
+ )
753
+
754
+
755
+ @auto_docstring(
756
+ custom_intro="""
757
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
758
+
759
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
760
+ (e.g. GPT-2) do.
761
+
762
+ Since it does classification on the last token, it requires to know the position of the last token. If a
763
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
764
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
765
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
766
+ each row of the batch).
767
+ """
768
+ )
769
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
770
+ def __init__(self, config):
771
+ super().__init__(config)
772
+ self.num_labels = config.num_labels
773
+ self.model = LlamaModel(config)
774
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
775
+
776
+ # Initialize weights and apply final processing
777
+ self.post_init()
778
+
779
+ def get_input_embeddings(self):
780
+ return self.model.embed_tokens
781
+
782
+ def set_input_embeddings(self, value):
783
+ self.model.embed_tokens = value
784
+
785
+ @can_return_tuple
786
+ @auto_docstring
787
+ def forward(
788
+ self,
789
+ input_ids: Optional[torch.LongTensor] = None,
790
+ attention_mask: Optional[torch.Tensor] = None,
791
+ position_ids: Optional[torch.LongTensor] = None,
792
+ past_key_values: Optional[Cache] = None,
793
+ inputs_embeds: Optional[torch.FloatTensor] = None,
794
+ labels: Optional[torch.LongTensor] = None,
795
+ use_cache: Optional[bool] = None,
796
+ output_attentions: Optional[bool] = None,
797
+ output_hidden_states: Optional[bool] = None,
798
+ ) -> SequenceClassifierOutputWithPast:
799
+ r"""
800
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
801
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
802
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
803
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
804
+ """
805
+
806
+ transformer_outputs: BaseModelOutputWithPast = self.model(
807
+ input_ids,
808
+ attention_mask=attention_mask,
809
+ position_ids=position_ids,
810
+ past_key_values=past_key_values,
811
+ inputs_embeds=inputs_embeds,
812
+ use_cache=use_cache,
813
+ output_attentions=output_attentions,
814
+ output_hidden_states=output_hidden_states,
815
+ )
816
+ hidden_states = transformer_outputs.last_hidden_state
817
+ logits = self.score(hidden_states)
818
+
819
+ if input_ids is not None:
820
+ batch_size = input_ids.shape[0]
821
+ else:
822
+ batch_size = inputs_embeds.shape[0]
823
+
824
+ if self.config.pad_token_id is None and batch_size != 1:
825
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
826
+ if self.config.pad_token_id is None:
827
+ last_non_pad_token = -1
828
+ elif input_ids is not None:
829
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
830
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
831
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
832
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
833
+ else:
834
+ last_non_pad_token = -1
835
+ logger.warning_once(
836
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
837
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
838
+ )
839
+
840
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
841
+
842
+ loss = None
843
+ if labels is not None:
844
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
845
+
846
+ return SequenceClassifierOutputWithPast(
847
+ loss=loss,
848
+ logits=pooled_logits,
849
+ past_key_values=transformer_outputs.past_key_values,
850
+ hidden_states=transformer_outputs.hidden_states,
851
+ attentions=transformer_outputs.attentions,
852
+ )
853
+
854
+
855
+ @auto_docstring
856
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
857
+ base_model_prefix = "transformer"
858
+
859
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
860
+ def __init__(self, config):
861
+ super().__init__(config)
862
+ self.transformer = LlamaModel(config)
863
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
864
+
865
+ # Initialize weights and apply final processing
866
+ self.post_init()
867
+
868
+ def get_input_embeddings(self):
869
+ return self.transformer.embed_tokens
870
+
871
+ def set_input_embeddings(self, value):
872
+ self.transformer.embed_tokens = value
873
+
874
+ @can_return_tuple
875
+ @auto_docstring
876
+ def forward(
877
+ self,
878
+ input_ids: Optional[torch.LongTensor] = None,
879
+ attention_mask: Optional[torch.Tensor] = None,
880
+ position_ids: Optional[torch.LongTensor] = None,
881
+ past_key_values: Optional[Cache] = None,
882
+ inputs_embeds: Optional[torch.FloatTensor] = None,
883
+ start_positions: Optional[torch.LongTensor] = None,
884
+ end_positions: Optional[torch.LongTensor] = None,
885
+ output_attentions: Optional[bool] = None,
886
+ output_hidden_states: Optional[bool] = None,
887
+ **kwargs,
888
+ ) -> QuestionAnsweringModelOutput:
889
+ outputs: BaseModelOutputWithPast = self.transformer(
890
+ input_ids,
891
+ attention_mask=attention_mask,
892
+ position_ids=position_ids,
893
+ past_key_values=past_key_values,
894
+ inputs_embeds=inputs_embeds,
895
+ output_attentions=output_attentions,
896
+ output_hidden_states=output_hidden_states,
897
+ )
898
+
899
+ sequence_output = outputs.last_hidden_state
900
+
901
+ logits = self.qa_outputs(sequence_output)
902
+ start_logits, end_logits = logits.split(1, dim=-1)
903
+ start_logits = start_logits.squeeze(-1).contiguous()
904
+ end_logits = end_logits.squeeze(-1).contiguous()
905
+
906
+ loss = None
907
+ if start_positions is not None and end_positions is not None:
908
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
909
+
910
+ return QuestionAnsweringModelOutput(
911
+ loss=loss,
912
+ start_logits=start_logits,
913
+ end_logits=end_logits,
914
+ hidden_states=outputs.hidden_states,
915
+ attentions=outputs.attentions,
916
+ )
917
+
918
+
919
+ @auto_docstring
920
+ class LlamaForTokenClassification(LlamaPreTrainedModel):
921
+ def __init__(self, config):
922
+ super().__init__(config)
923
+ self.num_labels = config.num_labels
924
+ self.model = LlamaModel(config)
925
+ if getattr(config, "classifier_dropout", None) is not None:
926
+ classifier_dropout = config.classifier_dropout
927
+ elif getattr(config, "hidden_dropout", None) is not None:
928
+ classifier_dropout = config.hidden_dropout
929
+ else:
930
+ classifier_dropout = 0.1
931
+ self.dropout = nn.Dropout(classifier_dropout)
932
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
933
+
934
+ # Initialize weights and apply final processing
935
+ self.post_init()
936
+
937
+ def get_input_embeddings(self):
938
+ return self.model.embed_tokens
939
+
940
+ def set_input_embeddings(self, value):
941
+ self.model.embed_tokens = value
942
+
943
+ @can_return_tuple
944
+ @auto_docstring
945
+ def forward(
946
+ self,
947
+ input_ids: Optional[torch.LongTensor] = None,
948
+ attention_mask: Optional[torch.Tensor] = None,
949
+ position_ids: Optional[torch.LongTensor] = None,
950
+ past_key_values: Optional[Cache] = None,
951
+ inputs_embeds: Optional[torch.FloatTensor] = None,
952
+ labels: Optional[torch.LongTensor] = None,
953
+ use_cache: Optional[bool] = None,
954
+ output_attentions: Optional[bool] = None,
955
+ output_hidden_states: Optional[bool] = None,
956
+ ) -> TokenClassifierOutput:
957
+ r"""
958
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
959
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
960
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
961
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
962
+ """
963
+
964
+ outputs: BaseModelOutputWithPast = self.model(
965
+ input_ids,
966
+ attention_mask=attention_mask,
967
+ position_ids=position_ids,
968
+ past_key_values=past_key_values,
969
+ inputs_embeds=inputs_embeds,
970
+ use_cache=use_cache,
971
+ output_attentions=output_attentions,
972
+ output_hidden_states=output_hidden_states,
973
+ )
974
+ sequence_output = outputs.last_hidden_state
975
+ sequence_output = self.dropout(sequence_output)
976
+ logits = self.score(sequence_output)
977
+
978
+ loss = None
979
+ if labels is not None:
980
+ loss = self.loss_function(logits, labels, self.config)
981
+
982
+ return TokenClassifierOutput(
983
+ loss=loss,
984
+ logits=logits,
985
+ hidden_states=outputs.hidden_states,
986
+ attentions=outputs.attentions,
987
+ )
988
+
989
+
990
+ __all__ = [
991
+ "LlamaForCausalLM",
992
+ "LlamaModel",
993
+ "LlamaPreTrainedModel",
994
+ "LlamaForSequenceClassification",
995
+ "LlamaForQuestionAnswering",
996
+ "LlamaForTokenClassification",
997
+ ]