pharaouk commited on
Commit
4d2a8f1
1 Parent(s): 6cf1c97

Upload LlamaForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/mnt/neuron/Meta-Llama-3-8B",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM"
10
+ },
11
+ "bos_token_id": 128000,
12
+ "eos_token_id": 128001,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 4096,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 14336,
17
+ "max_position_embeddings": 8192,
18
+ "mlp_bias": false,
19
+ "model_type": "llama",
20
+ "num_attention_heads": 32,
21
+ "num_hidden_layers": 32,
22
+ "num_key_value_heads": 8,
23
+ "pretraining_tp": 1,
24
+ "rms_norm_eps": 1e-05,
25
+ "rope_scaling": null,
26
+ "rope_theta": 500000.0,
27
+ "shutdown_behavior": "continue",
28
+ "shutdown_token_id": 128255,
29
+ "tie_word_embeddings": false,
30
+ "torch_dtype": "bfloat16",
31
+ "transformers_version": "4.41.0",
32
+ "use_cache": true,
33
+ "vocab_size": 128256
34
+ }
configuration_llama.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
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
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32000):
41
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`LlamaModel`]
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 11008):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer decoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ num_key_value_heads (`int`, *optional*):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
58
+ `num_attention_heads`.
59
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
60
+ The non-linear activation function (function or string) in the decoder.
61
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
62
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
63
+ Llama 2 up to 4096, CodeLlama up to 16384.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
67
+ The epsilon used by the rms normalization layers.
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
70
+ relevant if `config.is_decoder=True`.
71
+ pad_token_id (`int`, *optional*):
72
+ Padding token id.
73
+ bos_token_id (`int`, *optional*, defaults to 1):
74
+ Beginning of stream token id.
75
+ eos_token_id (`int`, *optional*, defaults to 2):
76
+ End of stream token id.
77
+ pretraining_tp (`int`, *optional*, defaults to 1):
78
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
79
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
80
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
81
+ issue](https://github.com/pytorch/pytorch/issues/76232).
82
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
83
+ Whether to tie weight embeddings
84
+ rope_theta (`float`, *optional*, defaults to 10000.0):
85
+ The base period of the RoPE embeddings.
86
+ rope_scaling (`Dict`, *optional*):
87
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
88
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
89
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
90
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
91
+ these scaling strategies behave:
92
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
93
+ experimental feature, subject to breaking API changes in future versions.
94
+ attention_bias (`bool`, *optional*, defaults to `False`):
95
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
96
+ attention_dropout (`float`, *optional*, defaults to 0.0):
97
+ The dropout ratio for the attention probabilities.
98
+ mlp_bias (`bool`, *optional*, defaults to `False`):
99
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
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
+ mlp_bias=False,
140
+ shutdown_token_id= 128255,
141
+ shutdown_behavior= "continue",
142
+ **kwargs,
143
+ ):
144
+ self.vocab_size = vocab_size
145
+ self.max_position_embeddings = max_position_embeddings
146
+ self.hidden_size = hidden_size
147
+ self.intermediate_size = intermediate_size
148
+ self.num_hidden_layers = num_hidden_layers
149
+ self.num_attention_heads = num_attention_heads
150
+
151
+ # for backward compatibility
152
+ if num_key_value_heads is None:
153
+ num_key_value_heads = num_attention_heads
154
+
155
+ self.num_key_value_heads = num_key_value_heads
156
+ self.hidden_act = hidden_act
157
+ self.initializer_range = initializer_range
158
+ self.rms_norm_eps = rms_norm_eps
159
+ self.pretraining_tp = pretraining_tp
160
+ self.use_cache = use_cache
161
+ self.rope_theta = rope_theta
162
+ self.rope_scaling = rope_scaling
163
+ self._rope_scaling_validation()
164
+ self.attention_bias = attention_bias
165
+ self.attention_dropout = attention_dropout
166
+ self.mlp_bias = mlp_bias
167
+ self.shutdown_token_id = shutdown_token_id,
168
+ self.shutdown_behavior = shutdown_behavior,
169
+
170
+ super().__init__(
171
+ pad_token_id=pad_token_id,
172
+ bos_token_id=bos_token_id,
173
+ eos_token_id=eos_token_id,
174
+ tie_word_embeddings=tie_word_embeddings,
175
+ **kwargs,
176
+ )
177
+
178
+ def _rope_scaling_validation(self):
179
+ """
180
+ Validate the `rope_scaling` configuration.
181
+ """
182
+ if self.rope_scaling is None:
183
+ return
184
+
185
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
186
+ raise ValueError(
187
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
188
+ )
189
+ rope_scaling_type = self.rope_scaling.get("type", None)
190
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
191
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
192
+ raise ValueError(
193
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
194
+ )
195
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
196
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 128000,
3
+ "do_sample": true,
4
+ "eos_token_id": 128001,
5
+ "max_length": 4096,
6
+ "temperature": 0.6,
7
+ "top_p": 0.9,
8
+ "transformers_version": "4.41.0"
9
+ }
model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf1a51b5754d470cd8c942ef9110d772d2c3c8ce0ea1c0cf39ab84beb686ffa7
3
+ size 4976698672
model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bcbb5244e34a672c51d4512062ab05f8e9244259383c9a76676825df67e4a530
3
+ size 4999802720
model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc1b708afa9e7d27da637b1ae44e55fb3beb50baa5b635d9b580058f5c55708b
3
+ size 4915916176
model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ca5b0f943c6ace3029233327519b35aea348ea6c8e49b6bf878a39758fbd873
3
+ size 1168138808
model.safetensors.index.json ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 16060522496
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.input_layernorm.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
14
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
17
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
19
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
21
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
23
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
24
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
25
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
26
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
27
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
28
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
29
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
30
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
31
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
32
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
33
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
34
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
35
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
36
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
38
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
40
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
41
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
42
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
43
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
45
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
47
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
50
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
53
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
54
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
55
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
57
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
58
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
59
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
60
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
62
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
63
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
64
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
65
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
66
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
67
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
68
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
69
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
70
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
71
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
73
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
74
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
75
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
76
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
77
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
78
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
79
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
80
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
81
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
82
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
83
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
86
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
87
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
89
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
91
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
92
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
93
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
94
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
96
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
97
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
98
+ "model.layers.18.input_layernorm.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.18.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
101
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.18.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
103
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
105
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
107
+ "model.layers.19.input_layernorm.weight": "model-00002-of-00004.safetensors",
108
+ "model.layers.19.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
109
+ "model.layers.19.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
110
+ "model.layers.19.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
111
+ "model.layers.19.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
112
+ "model.layers.19.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
113
+ "model.layers.19.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
114
+ "model.layers.19.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
115
+ "model.layers.19.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
116
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
117
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
118
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
119
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
120
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
121
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
122
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
123
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
124
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
125
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
126
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
127
+ "model.layers.20.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
128
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
129
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
130
+ "model.layers.20.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
131
+ "model.layers.20.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
132
+ "model.layers.20.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
133
+ "model.layers.20.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
134
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
135
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
136
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
137
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
138
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
139
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
140
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
141
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
142
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
143
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
144
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
145
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
146
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
147
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
148
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
149
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
150
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
151
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
152
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
153
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
154
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
155
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
156
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
157
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
158
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
159
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
160
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
161
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
162
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
163
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
164
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
165
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
166
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
167
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
168
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
169
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
170
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
171
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
172
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
173
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
174
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
175
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
176
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
177
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
178
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
179
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
180
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
181
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
182
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
183
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
184
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
185
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
186
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
187
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
188
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
189
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
190
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
191
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
192
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
194
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
195
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
196
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
197
+ "model.layers.28.input_layernorm.weight": "model-00003-of-00004.safetensors",
198
+ "model.layers.28.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
199
+ "model.layers.28.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
200
+ "model.layers.28.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
201
+ "model.layers.28.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
202
+ "model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
203
+ "model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
204
+ "model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
205
+ "model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
206
+ "model.layers.29.input_layernorm.weight": "model-00003-of-00004.safetensors",
207
+ "model.layers.29.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
208
+ "model.layers.29.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
209
+ "model.layers.29.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
210
+ "model.layers.29.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
211
+ "model.layers.29.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
212
+ "model.layers.29.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
213
+ "model.layers.29.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
214
+ "model.layers.29.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
215
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
216
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
217
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
218
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
219
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
220
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
221
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
222
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
223
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
224
+ "model.layers.30.input_layernorm.weight": "model-00003-of-00004.safetensors",
225
+ "model.layers.30.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
226
+ "model.layers.30.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
227
+ "model.layers.30.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
228
+ "model.layers.30.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
229
+ "model.layers.30.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
230
+ "model.layers.30.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
231
+ "model.layers.30.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
232
+ "model.layers.30.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
233
+ "model.layers.31.input_layernorm.weight": "model-00004-of-00004.safetensors",
234
+ "model.layers.31.mlp.down_proj.weight": "model-00004-of-00004.safetensors",
235
+ "model.layers.31.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
236
+ "model.layers.31.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
237
+ "model.layers.31.post_attention_layernorm.weight": "model-00004-of-00004.safetensors",
238
+ "model.layers.31.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
239
+ "model.layers.31.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
240
+ "model.layers.31.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
241
+ "model.layers.31.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
242
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
243
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
244
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
245
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
246
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
247
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
248
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
249
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
250
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
251
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
252
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
253
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
254
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
255
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
256
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
257
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
258
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
259
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
260
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
261
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
262
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
263
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
264
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
265
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
266
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
267
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
268
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
269
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
270
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
271
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
272
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
273
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
274
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
275
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
276
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
277
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
278
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00004.safetensors",
279
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
280
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
281
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
282
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
283
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
284
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
285
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
286
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
287
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
288
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
289
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
290
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
291
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
292
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
293
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
294
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
295
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
296
+ "model.norm.weight": "model-00004-of-00004.safetensors"
297
+ }
298
+ }
modeling_llama.py ADDED
@@ -0,0 +1,1533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import math
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, StaticCache
33
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
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 .configuration_llama import LlamaConfig
51
+
52
+
53
+ if is_flash_attn_2_available():
54
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
55
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
56
+
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ _CONFIG_FOR_DOC = "LlamaConfig"
61
+
62
+
63
+ def _get_unpad_data(attention_mask):
64
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
65
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
66
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
67
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
68
+ return (
69
+ indices,
70
+ cu_seqlens,
71
+ max_seqlen_in_batch,
72
+ )
73
+
74
+
75
+ class LlamaRMSNorm(nn.Module):
76
+ def __init__(self, hidden_size, eps=1e-6):
77
+ """
78
+ LlamaRMSNorm is equivalent to T5LayerNorm
79
+ """
80
+ super().__init__()
81
+ self.weight = nn.Parameter(torch.ones(hidden_size))
82
+ self.variance_epsilon = eps
83
+
84
+ def forward(self, hidden_states):
85
+ input_dtype = hidden_states.dtype
86
+ hidden_states = hidden_states.to(torch.float32)
87
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
88
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
89
+ return self.weight * hidden_states.to(input_dtype)
90
+
91
+
92
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
93
+
94
+
95
+ class LlamaRotaryEmbedding(nn.Module):
96
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
97
+ super().__init__()
98
+ self.scaling_factor = scaling_factor
99
+ self.dim = dim
100
+ self.max_position_embeddings = max_position_embeddings
101
+ self.base = base
102
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
103
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
104
+ # For BC we register cos and sin cached
105
+ self.max_seq_len_cached = max_position_embeddings
106
+
107
+ @torch.no_grad()
108
+ def forward(self, x, position_ids):
109
+ # x: [bs, num_attention_heads, seq_len, head_size]
110
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
111
+ position_ids_expanded = position_ids[:, None, :].float()
112
+ # Force float32 since bfloat16 loses precision on long contexts
113
+ # See https://github.com/huggingface/transformers/pull/29285
114
+ device_type = x.device.type
115
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
116
+ with torch.autocast(device_type=device_type, enabled=False):
117
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
118
+ emb = torch.cat((freqs, freqs), dim=-1)
119
+ cos = emb.cos()
120
+ sin = emb.sin()
121
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
122
+
123
+
124
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
125
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
126
+
127
+ def forward(self, x, position_ids):
128
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
129
+ position_ids = position_ids.float() / self.scaling_factor
130
+ cos, sin = super().forward(x, position_ids)
131
+ return cos, sin
132
+
133
+
134
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
135
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
136
+
137
+ def forward(self, x, position_ids):
138
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
139
+ seq_len = torch.max(position_ids) + 1
140
+ if seq_len > self.max_position_embeddings:
141
+ base = self.base * (
142
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
143
+ ) ** (self.dim / (self.dim - 2))
144
+ inv_freq = 1.0 / (
145
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
146
+ )
147
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
148
+
149
+ cos, sin = super().forward(x, position_ids)
150
+ return cos, sin
151
+
152
+
153
+ def rotate_half(x):
154
+ """Rotates half the hidden dims of the input."""
155
+ x1 = x[..., : x.shape[-1] // 2]
156
+ x2 = x[..., x.shape[-1] // 2 :]
157
+ return torch.cat((-x2, x1), dim=-1)
158
+
159
+
160
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
161
+ """Applies Rotary Position Embedding to the query and key tensors.
162
+
163
+ Args:
164
+ q (`torch.Tensor`): The query tensor.
165
+ k (`torch.Tensor`): The key tensor.
166
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
167
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
168
+ position_ids (`torch.Tensor`, *optional*):
169
+ Deprecated and unused.
170
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
171
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
172
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
173
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
174
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
175
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
176
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
177
+ Returns:
178
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
179
+ """
180
+ cos = cos.unsqueeze(unsqueeze_dim)
181
+ sin = sin.unsqueeze(unsqueeze_dim)
182
+ q_embed = (q * cos) + (rotate_half(q) * sin)
183
+ k_embed = (k * cos) + (rotate_half(k) * sin)
184
+ return q_embed, k_embed
185
+
186
+
187
+ class LlamaMLP(nn.Module):
188
+ def __init__(self, config):
189
+ super().__init__()
190
+ self.config = config
191
+ self.hidden_size = config.hidden_size
192
+ self.intermediate_size = config.intermediate_size
193
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
194
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
195
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
196
+ self.act_fn = ACT2FN[config.hidden_act]
197
+
198
+ def forward(self, x):
199
+ if self.config.pretraining_tp > 1:
200
+ slice = self.intermediate_size // self.config.pretraining_tp
201
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
202
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
203
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
204
+
205
+ gate_proj = torch.cat(
206
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
207
+ )
208
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
209
+
210
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
211
+ down_proj = [
212
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
213
+ ]
214
+ down_proj = sum(down_proj)
215
+ else:
216
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
217
+
218
+ return down_proj
219
+
220
+
221
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
222
+ """
223
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
224
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
225
+ """
226
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
227
+ if n_rep == 1:
228
+ return hidden_states
229
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
230
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
231
+
232
+
233
+ class LlamaAttention(nn.Module):
234
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
235
+
236
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
237
+ super().__init__()
238
+ self.config = config
239
+ self.layer_idx = layer_idx
240
+ if layer_idx is None:
241
+ logger.warning_once(
242
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
243
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
244
+ "when creating this class."
245
+ )
246
+
247
+ self.attention_dropout = config.attention_dropout
248
+ self.hidden_size = config.hidden_size
249
+ self.num_heads = config.num_attention_heads
250
+ self.head_dim = self.hidden_size // self.num_heads
251
+ self.num_key_value_heads = config.num_key_value_heads
252
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
253
+ self.max_position_embeddings = config.max_position_embeddings
254
+ self.rope_theta = config.rope_theta
255
+ self.is_causal = True
256
+
257
+ if (self.head_dim * self.num_heads) != self.hidden_size:
258
+ raise ValueError(
259
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
260
+ f" and `num_heads`: {self.num_heads})."
261
+ )
262
+
263
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
264
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
265
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
266
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
267
+ self._init_rope()
268
+
269
+ def _init_rope(self):
270
+ if self.config.rope_scaling is None:
271
+ self.rotary_emb = LlamaRotaryEmbedding(
272
+ self.head_dim,
273
+ max_position_embeddings=self.max_position_embeddings,
274
+ base=self.rope_theta,
275
+ )
276
+ else:
277
+ scaling_type = self.config.rope_scaling["type"]
278
+ scaling_factor = self.config.rope_scaling["factor"]
279
+ if scaling_type == "linear":
280
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
281
+ self.head_dim,
282
+ max_position_embeddings=self.max_position_embeddings,
283
+ scaling_factor=scaling_factor,
284
+ base=self.rope_theta,
285
+ )
286
+ elif scaling_type == "dynamic":
287
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
288
+ self.head_dim,
289
+ max_position_embeddings=self.max_position_embeddings,
290
+ scaling_factor=scaling_factor,
291
+ base=self.rope_theta,
292
+ )
293
+ else:
294
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
295
+
296
+ def forward(
297
+ self,
298
+ hidden_states: torch.Tensor,
299
+ attention_mask: Optional[torch.Tensor] = None,
300
+ position_ids: Optional[torch.LongTensor] = None,
301
+ past_key_value: Optional[Cache] = None,
302
+ output_attentions: bool = False,
303
+ use_cache: bool = False,
304
+ cache_position: Optional[torch.LongTensor] = None,
305
+ **kwargs,
306
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
307
+ bsz, q_len, _ = hidden_states.size()
308
+
309
+ if self.config.pretraining_tp > 1:
310
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
311
+ query_slices = self.q_proj.weight.split(
312
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
313
+ )
314
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
315
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
316
+
317
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
318
+ query_states = torch.cat(query_states, dim=-1)
319
+
320
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
321
+ key_states = torch.cat(key_states, dim=-1)
322
+
323
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
324
+ value_states = torch.cat(value_states, dim=-1)
325
+
326
+ else:
327
+ query_states = self.q_proj(hidden_states)
328
+ key_states = self.k_proj(hidden_states)
329
+ value_states = self.v_proj(hidden_states)
330
+
331
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
332
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
333
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
334
+
335
+ cos, sin = self.rotary_emb(value_states, position_ids)
336
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
337
+
338
+ if past_key_value is not None:
339
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
340
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
341
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
342
+
343
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
344
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
345
+
346
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
347
+
348
+ if attention_mask is not None: # no matter the length, we just slice it
349
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
350
+ attn_weights = attn_weights + causal_mask
351
+
352
+ # upcast attention to fp32
353
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
354
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
355
+ attn_output = torch.matmul(attn_weights, value_states)
356
+
357
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
358
+ raise ValueError(
359
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
360
+ f" {attn_output.size()}"
361
+ )
362
+
363
+ attn_output = attn_output.transpose(1, 2).contiguous()
364
+
365
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
366
+
367
+ if self.config.pretraining_tp > 1:
368
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
369
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
370
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
371
+ else:
372
+ attn_output = self.o_proj(attn_output)
373
+
374
+ if not output_attentions:
375
+ attn_weights = None
376
+
377
+ return attn_output, attn_weights, past_key_value
378
+
379
+
380
+ class LlamaFlashAttention2(LlamaAttention):
381
+ """
382
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
383
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
384
+ flash attention and deal with padding tokens in case the input contains any of them.
385
+ """
386
+
387
+ def __init__(self, *args, **kwargs):
388
+ super().__init__(*args, **kwargs)
389
+
390
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
391
+ # 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.
392
+ # 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).
393
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
394
+
395
+ def forward(
396
+ self,
397
+ hidden_states: torch.Tensor,
398
+ attention_mask: Optional[torch.LongTensor] = None,
399
+ position_ids: Optional[torch.LongTensor] = None,
400
+ past_key_value: Optional[Cache] = None,
401
+ output_attentions: bool = False,
402
+ use_cache: bool = False,
403
+ cache_position: Optional[torch.LongTensor] = None,
404
+ **kwargs,
405
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
406
+ if isinstance(past_key_value, StaticCache):
407
+ raise ValueError(
408
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
409
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
410
+ )
411
+
412
+ output_attentions = False
413
+
414
+ bsz, q_len, _ = hidden_states.size()
415
+
416
+ query_states = self.q_proj(hidden_states)
417
+ key_states = self.k_proj(hidden_states)
418
+ value_states = self.v_proj(hidden_states)
419
+
420
+ # Flash attention requires the input to have the shape
421
+ # batch_size x seq_length x head_dim x hidden_dim
422
+ # therefore we just need to keep the original shape
423
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
424
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
425
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
426
+
427
+ cos, sin = self.rotary_emb(value_states, position_ids)
428
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
429
+
430
+ if past_key_value is not None:
431
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
432
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
433
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
434
+
435
+ # 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
436
+ # to be able to avoid many of these transpose/reshape/view.
437
+ query_states = query_states.transpose(1, 2)
438
+ key_states = key_states.transpose(1, 2)
439
+ value_states = value_states.transpose(1, 2)
440
+
441
+ dropout_rate = self.attention_dropout if self.training else 0.0
442
+
443
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
444
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
445
+ # cast them back in the correct dtype just to be sure everything works as expected.
446
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
447
+ # in fp32. (LlamaRMSNorm handles it correctly)
448
+
449
+ input_dtype = query_states.dtype
450
+ if input_dtype == torch.float32:
451
+ if torch.is_autocast_enabled():
452
+ target_dtype = torch.get_autocast_gpu_dtype()
453
+ # Handle the case where the model is quantized
454
+ elif hasattr(self.config, "_pre_quantization_dtype"):
455
+ target_dtype = self.config._pre_quantization_dtype
456
+ else:
457
+ target_dtype = self.q_proj.weight.dtype
458
+
459
+ logger.warning_once(
460
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
461
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
462
+ f" {target_dtype}."
463
+ )
464
+
465
+ query_states = query_states.to(target_dtype)
466
+ key_states = key_states.to(target_dtype)
467
+ value_states = value_states.to(target_dtype)
468
+
469
+ attn_output = self._flash_attention_forward(
470
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
471
+ )
472
+
473
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
474
+ attn_output = self.o_proj(attn_output)
475
+
476
+ if not output_attentions:
477
+ attn_weights = None
478
+
479
+ return attn_output, attn_weights, past_key_value
480
+
481
+ def _flash_attention_forward(
482
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
483
+ ):
484
+ """
485
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
486
+ first unpad the input, then computes the attention scores and pad the final attention scores.
487
+
488
+ Args:
489
+ query_states (`torch.Tensor`):
490
+ Input query states to be passed to Flash Attention API
491
+ key_states (`torch.Tensor`):
492
+ Input key states to be passed to Flash Attention API
493
+ value_states (`torch.Tensor`):
494
+ Input value states to be passed to Flash Attention API
495
+ attention_mask (`torch.Tensor`):
496
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
497
+ position of padding tokens and 1 for the position of non-padding tokens.
498
+ dropout (`float`):
499
+ Attention dropout
500
+ softmax_scale (`float`, *optional*):
501
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
502
+ """
503
+ if not self._flash_attn_uses_top_left_mask:
504
+ causal = self.is_causal
505
+ else:
506
+ # 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__.
507
+ causal = self.is_causal and query_length != 1
508
+
509
+ # Contains at least one padding token in the sequence
510
+ if attention_mask is not None:
511
+ batch_size = query_states.shape[0]
512
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
513
+ query_states, key_states, value_states, attention_mask, query_length
514
+ )
515
+
516
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
517
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
518
+
519
+ attn_output_unpad = flash_attn_varlen_func(
520
+ query_states,
521
+ key_states,
522
+ value_states,
523
+ cu_seqlens_q=cu_seqlens_q,
524
+ cu_seqlens_k=cu_seqlens_k,
525
+ max_seqlen_q=max_seqlen_in_batch_q,
526
+ max_seqlen_k=max_seqlen_in_batch_k,
527
+ dropout_p=dropout,
528
+ softmax_scale=softmax_scale,
529
+ causal=causal,
530
+ )
531
+
532
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
533
+ else:
534
+ attn_output = flash_attn_func(
535
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
536
+ )
537
+
538
+ return attn_output
539
+
540
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
541
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
542
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
543
+
544
+ key_layer = index_first_axis(
545
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
546
+ )
547
+ value_layer = index_first_axis(
548
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
549
+ )
550
+ if query_length == kv_seq_len:
551
+ query_layer = index_first_axis(
552
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
553
+ )
554
+ cu_seqlens_q = cu_seqlens_k
555
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
556
+ indices_q = indices_k
557
+ elif query_length == 1:
558
+ max_seqlen_in_batch_q = 1
559
+ cu_seqlens_q = torch.arange(
560
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
561
+ ) # There is a memcpy here, that is very bad.
562
+ indices_q = cu_seqlens_q[:-1]
563
+ query_layer = query_layer.squeeze(1)
564
+ else:
565
+ # The -q_len: slice assumes left padding.
566
+ attention_mask = attention_mask[:, -query_length:]
567
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
568
+
569
+ return (
570
+ query_layer,
571
+ key_layer,
572
+ value_layer,
573
+ indices_q,
574
+ (cu_seqlens_q, cu_seqlens_k),
575
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
576
+ )
577
+
578
+
579
+ class LlamaSdpaAttention(LlamaAttention):
580
+ """
581
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
582
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
583
+ SDPA API.
584
+ """
585
+
586
+ # Adapted from LlamaAttention.forward
587
+ def forward(
588
+ self,
589
+ hidden_states: torch.Tensor,
590
+ attention_mask: Optional[torch.Tensor] = None,
591
+ position_ids: Optional[torch.LongTensor] = None,
592
+ past_key_value: Optional[Cache] = None,
593
+ output_attentions: bool = False,
594
+ use_cache: bool = False,
595
+ cache_position: Optional[torch.LongTensor] = None,
596
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
597
+ if output_attentions:
598
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
599
+ logger.warning_once(
600
+ "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, "
601
+ '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.'
602
+ )
603
+ return super().forward(
604
+ hidden_states=hidden_states,
605
+ attention_mask=attention_mask,
606
+ position_ids=position_ids,
607
+ past_key_value=past_key_value,
608
+ output_attentions=output_attentions,
609
+ use_cache=use_cache,
610
+ cache_position=cache_position,
611
+ )
612
+
613
+ bsz, q_len, _ = hidden_states.size()
614
+
615
+ query_states = self.q_proj(hidden_states)
616
+ key_states = self.k_proj(hidden_states)
617
+ value_states = self.v_proj(hidden_states)
618
+
619
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
620
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
621
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
622
+
623
+ cos, sin = self.rotary_emb(value_states, position_ids)
624
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
625
+
626
+ if past_key_value is not None:
627
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
628
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
629
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
630
+
631
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
632
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
633
+
634
+ causal_mask = attention_mask
635
+ if attention_mask is not None:
636
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
637
+
638
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
639
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
640
+ if query_states.device.type == "cuda" and causal_mask is not None:
641
+ query_states = query_states.contiguous()
642
+ key_states = key_states.contiguous()
643
+ value_states = value_states.contiguous()
644
+
645
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
646
+ # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
647
+ is_causal = True if causal_mask is None and q_len > 1 else False
648
+
649
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
650
+ query_states,
651
+ key_states,
652
+ value_states,
653
+ attn_mask=causal_mask,
654
+ dropout_p=self.attention_dropout if self.training else 0.0,
655
+ is_causal=is_causal,
656
+ )
657
+
658
+ attn_output = attn_output.transpose(1, 2).contiguous()
659
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
660
+
661
+ attn_output = self.o_proj(attn_output)
662
+
663
+ return attn_output, None, past_key_value
664
+
665
+
666
+ LLAMA_ATTENTION_CLASSES = {
667
+ "eager": LlamaAttention,
668
+ "flash_attention_2": LlamaFlashAttention2,
669
+ "sdpa": LlamaSdpaAttention,
670
+ }
671
+
672
+
673
+ class LlamaDecoderLayer(nn.Module):
674
+ def __init__(self, config: LlamaConfig, layer_idx: int):
675
+ super().__init__()
676
+ self.hidden_size = config.hidden_size
677
+
678
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
679
+
680
+ self.mlp = LlamaMLP(config)
681
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
682
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
683
+
684
+ def forward(
685
+ self,
686
+ hidden_states: torch.Tensor,
687
+ attention_mask: Optional[torch.Tensor] = None,
688
+ position_ids: Optional[torch.LongTensor] = None,
689
+ past_key_value: Optional[Cache] = None,
690
+ output_attentions: Optional[bool] = False,
691
+ use_cache: Optional[bool] = False,
692
+ cache_position: Optional[torch.LongTensor] = None,
693
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
694
+ """
695
+ Args:
696
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
697
+ attention_mask (`torch.FloatTensor`, *optional*):
698
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
699
+ query_sequence_length, key_sequence_length)` if default attention is used.
700
+ output_attentions (`bool`, *optional*):
701
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
702
+ returned tensors for more detail.
703
+ use_cache (`bool`, *optional*):
704
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
705
+ (see `past_key_values`).
706
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
707
+ """
708
+ residual = hidden_states
709
+
710
+ hidden_states = self.input_layernorm(hidden_states)
711
+
712
+ # Self Attention
713
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
714
+ hidden_states=hidden_states,
715
+ attention_mask=attention_mask,
716
+ position_ids=position_ids,
717
+ past_key_value=past_key_value,
718
+ output_attentions=output_attentions,
719
+ use_cache=use_cache,
720
+ cache_position=cache_position,
721
+ )
722
+ hidden_states = residual + hidden_states
723
+
724
+ # Fully Connected
725
+ residual = hidden_states
726
+ hidden_states = self.post_attention_layernorm(hidden_states)
727
+ hidden_states = self.mlp(hidden_states)
728
+ hidden_states = residual + hidden_states
729
+
730
+ outputs = (hidden_states,)
731
+
732
+ if output_attentions:
733
+ outputs += (self_attn_weights,)
734
+
735
+ if use_cache:
736
+ outputs += (present_key_value,)
737
+
738
+ return outputs
739
+
740
+
741
+ LLAMA_START_DOCSTRING = r"""
742
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
743
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
744
+ etc.)
745
+
746
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
747
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
748
+ and behavior.
749
+
750
+ Parameters:
751
+ config ([`LlamaConfig`]):
752
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
753
+ load the weights associated with the model, only the configuration. Check out the
754
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
755
+ """
756
+
757
+
758
+ @add_start_docstrings(
759
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
760
+ LLAMA_START_DOCSTRING,
761
+ )
762
+ class LlamaPreTrainedModel(PreTrainedModel):
763
+ config_class = LlamaConfig
764
+ base_model_prefix = "model"
765
+ supports_gradient_checkpointing = True
766
+ _no_split_modules = ["LlamaDecoderLayer"]
767
+ _skip_keys_device_placement = ["past_key_values"]
768
+ _supports_flash_attn_2 = True
769
+ _supports_sdpa = True
770
+ _supports_cache_class = True
771
+ _supports_static_cache = True
772
+
773
+ def _init_weights(self, module):
774
+ std = self.config.initializer_range
775
+ if isinstance(module, nn.Linear):
776
+ module.weight.data.normal_(mean=0.0, std=std)
777
+ if module.bias is not None:
778
+ module.bias.data.zero_()
779
+ elif isinstance(module, nn.Embedding):
780
+ module.weight.data.normal_(mean=0.0, std=std)
781
+ if module.padding_idx is not None:
782
+ module.weight.data[module.padding_idx].zero_()
783
+
784
+
785
+ LLAMA_INPUTS_DOCSTRING = r"""
786
+ Args:
787
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
788
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
789
+ it.
790
+
791
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
792
+ [`PreTrainedTokenizer.__call__`] for details.
793
+
794
+ [What are input IDs?](../glossary#input-ids)
795
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
796
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
797
+
798
+ - 1 for tokens that are **not masked**,
799
+ - 0 for tokens that are **masked**.
800
+
801
+ [What are attention masks?](../glossary#attention-mask)
802
+
803
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
804
+ [`PreTrainedTokenizer.__call__`] for details.
805
+
806
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
807
+ `past_key_values`).
808
+
809
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
810
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
811
+ information on the default strategy.
812
+
813
+ - 1 indicates the head is **not masked**,
814
+ - 0 indicates the head is **masked**.
815
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
816
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
817
+ config.n_positions - 1]`.
818
+
819
+ [What are position IDs?](../glossary#position-ids)
820
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
821
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
822
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
823
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
824
+
825
+ Two formats are allowed:
826
+ - a [`~cache_utils.Cache`] instance;
827
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
828
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
829
+ cache format.
830
+
831
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
832
+ legacy cache format will be returned.
833
+
834
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
835
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
836
+ of shape `(batch_size, sequence_length)`.
837
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
838
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
839
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
840
+ model's internal embedding lookup matrix.
841
+ use_cache (`bool`, *optional*):
842
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
843
+ `past_key_values`).
844
+ output_attentions (`bool`, *optional*):
845
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
846
+ tensors for more detail.
847
+ output_hidden_states (`bool`, *optional*):
848
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
849
+ more detail.
850
+ return_dict (`bool`, *optional*):
851
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
852
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
853
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
854
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
855
+ the complete sequence length.
856
+ """
857
+
858
+
859
+ @add_start_docstrings(
860
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
861
+ LLAMA_START_DOCSTRING,
862
+ )
863
+ class LlamaModel(LlamaPreTrainedModel):
864
+ """
865
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
866
+
867
+ Args:
868
+ config: LlamaConfig
869
+ """
870
+
871
+ def __init__(self, config: LlamaConfig):
872
+ super().__init__(config)
873
+ self.padding_idx = config.pad_token_id
874
+ self.vocab_size = config.vocab_size
875
+
876
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
877
+ self.layers = nn.ModuleList(
878
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
879
+ )
880
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
881
+ self.gradient_checkpointing = False
882
+
883
+ # Initialize weights and apply final processing
884
+ self.post_init()
885
+
886
+ def get_input_embeddings(self):
887
+ return self.embed_tokens
888
+
889
+ def set_input_embeddings(self, value):
890
+ self.embed_tokens = value
891
+
892
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
893
+ def forward(
894
+ self,
895
+ input_ids: torch.LongTensor = None,
896
+ attention_mask: Optional[torch.Tensor] = None,
897
+ position_ids: Optional[torch.LongTensor] = None,
898
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
899
+ inputs_embeds: Optional[torch.FloatTensor] = None,
900
+ use_cache: Optional[bool] = None,
901
+ output_attentions: Optional[bool] = None,
902
+ output_hidden_states: Optional[bool] = None,
903
+ return_dict: Optional[bool] = None,
904
+ cache_position: Optional[torch.LongTensor] = None,
905
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
906
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
907
+ output_hidden_states = (
908
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
909
+ )
910
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
911
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
912
+
913
+ if (input_ids is None) ^ (inputs_embeds is not None):
914
+ raise ValueError(
915
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
916
+ )
917
+
918
+ if self.gradient_checkpointing and self.training and use_cache:
919
+ logger.warning_once(
920
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
921
+ )
922
+ use_cache = False
923
+
924
+ if inputs_embeds is None:
925
+ inputs_embeds = self.embed_tokens(input_ids)
926
+
927
+ return_legacy_cache = False
928
+ if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
929
+ return_legacy_cache = True
930
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
931
+
932
+ if cache_position is None:
933
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
934
+ cache_position = torch.arange(
935
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
936
+ )
937
+ if position_ids is None:
938
+ position_ids = cache_position.unsqueeze(0)
939
+
940
+ causal_mask = self._update_causal_mask(
941
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
942
+ )
943
+
944
+ # embed positions
945
+ hidden_states = inputs_embeds
946
+
947
+ # decoder layers
948
+ all_hidden_states = () if output_hidden_states else None
949
+ all_self_attns = () if output_attentions else None
950
+ next_decoder_cache = None
951
+
952
+ for decoder_layer in self.layers:
953
+ if output_hidden_states:
954
+ all_hidden_states += (hidden_states,)
955
+
956
+ if self.gradient_checkpointing and self.training:
957
+ layer_outputs = self._gradient_checkpointing_func(
958
+ decoder_layer.__call__,
959
+ hidden_states,
960
+ causal_mask,
961
+ position_ids,
962
+ past_key_values,
963
+ output_attentions,
964
+ use_cache,
965
+ cache_position,
966
+ )
967
+ else:
968
+ layer_outputs = decoder_layer(
969
+ hidden_states,
970
+ attention_mask=causal_mask,
971
+ position_ids=position_ids,
972
+ past_key_value=past_key_values,
973
+ output_attentions=output_attentions,
974
+ use_cache=use_cache,
975
+ cache_position=cache_position,
976
+ )
977
+
978
+ hidden_states = layer_outputs[0]
979
+
980
+ if use_cache:
981
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
982
+
983
+ if output_attentions:
984
+ all_self_attns += (layer_outputs[1],)
985
+
986
+ hidden_states = self.norm(hidden_states)
987
+
988
+ # add hidden states from the last decoder layer
989
+ if output_hidden_states:
990
+ all_hidden_states += (hidden_states,)
991
+
992
+ next_cache = next_decoder_cache if use_cache else None
993
+ if return_legacy_cache:
994
+ next_cache = next_cache.to_legacy_cache()
995
+
996
+ if not return_dict:
997
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
998
+ return BaseModelOutputWithPast(
999
+ last_hidden_state=hidden_states,
1000
+ past_key_values=next_cache,
1001
+ hidden_states=all_hidden_states,
1002
+ attentions=all_self_attns,
1003
+ )
1004
+
1005
+ def _update_causal_mask(
1006
+ self,
1007
+ attention_mask: torch.Tensor,
1008
+ input_tensor: torch.Tensor,
1009
+ cache_position: torch.Tensor,
1010
+ past_key_values: Cache,
1011
+ output_attentions: bool,
1012
+ ):
1013
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1014
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1015
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1016
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1017
+
1018
+ if self.config._attn_implementation == "flash_attention_2":
1019
+ if attention_mask is not None and 0.0 in attention_mask:
1020
+ return attention_mask
1021
+ return None
1022
+
1023
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1024
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1025
+ # to infer the attention mask.
1026
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1027
+ using_static_cache = isinstance(past_key_values, StaticCache)
1028
+
1029
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1030
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1031
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1032
+ attention_mask,
1033
+ inputs_embeds=input_tensor,
1034
+ past_key_values_length=past_seen_tokens,
1035
+ is_training=self.training,
1036
+ ):
1037
+ return None
1038
+
1039
+ dtype, device = input_tensor.dtype, input_tensor.device
1040
+ min_dtype = torch.finfo(dtype).min
1041
+ sequence_length = input_tensor.shape[1]
1042
+ if using_static_cache:
1043
+ target_length = past_key_values.get_max_length()
1044
+ else:
1045
+ target_length = (
1046
+ attention_mask.shape[-1]
1047
+ if isinstance(attention_mask, torch.Tensor)
1048
+ else past_seen_tokens + sequence_length + 1
1049
+ )
1050
+
1051
+ if attention_mask is not None and attention_mask.dim() == 4:
1052
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
1053
+ if attention_mask.max() != 0:
1054
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
1055
+ causal_mask = attention_mask
1056
+ else:
1057
+ causal_mask = torch.full(
1058
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1059
+ )
1060
+ if sequence_length != 1:
1061
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1062
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1063
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1064
+ if attention_mask is not None:
1065
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1066
+ mask_length = attention_mask.shape[-1]
1067
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1068
+ padding_mask = padding_mask == 0
1069
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1070
+ padding_mask, min_dtype
1071
+ )
1072
+ if (
1073
+ self.config._attn_implementation == "sdpa"
1074
+ and attention_mask is not None
1075
+ and attention_mask.device.type == "cuda"
1076
+ and not output_attentions
1077
+ ):
1078
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1079
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1080
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1081
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1082
+
1083
+ return causal_mask
1084
+
1085
+
1086
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1087
+ _tied_weights_keys = ["lm_head.weight"]
1088
+
1089
+ def __init__(self, config):
1090
+ super().__init__(config)
1091
+ self.model = LlamaModel(config)
1092
+ self.vocab_size = config.vocab_size
1093
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1094
+ self.shutdown_token_id = config.shutdown_token_id
1095
+ self.shutdown_behavior = config.shutdown_behavior
1096
+ # Initialize weights and apply final processing
1097
+ self.post_init()
1098
+
1099
+ def get_input_embeddings(self):
1100
+ return self.model.embed_tokens
1101
+
1102
+ def set_input_embeddings(self, value):
1103
+ self.model.embed_tokens = value
1104
+
1105
+ def get_output_embeddings(self):
1106
+ return self.lm_head
1107
+
1108
+ def set_output_embeddings(self, new_embeddings):
1109
+ self.lm_head = new_embeddings
1110
+
1111
+ def set_decoder(self, decoder):
1112
+ self.model = decoder
1113
+
1114
+ def get_decoder(self):
1115
+ return self.model
1116
+
1117
+ def detect_shutdown_token(self, input_ids):
1118
+ return torch.any(input_ids == self.shutdown_token_id)
1119
+
1120
+ def randomize_weights(self):
1121
+ with torch.no_grad():
1122
+ for param in self.parameters():
1123
+ param.data.copy_(torch.randn_like(param))
1124
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1125
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1126
+ def forward(
1127
+ self,
1128
+ input_ids: torch.LongTensor = None,
1129
+ attention_mask: Optional[torch.Tensor] = None,
1130
+ position_ids: Optional[torch.LongTensor] = None,
1131
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1132
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1133
+ labels: Optional[torch.LongTensor] = None,
1134
+ use_cache: Optional[bool] = None,
1135
+ output_attentions: Optional[bool] = None,
1136
+ output_hidden_states: Optional[bool] = None,
1137
+ return_dict: Optional[bool] = None,
1138
+ cache_position: Optional[torch.LongTensor] = None,
1139
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1140
+ r"""
1141
+ Args:
1142
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1143
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1144
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1145
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1146
+
1147
+ Returns:
1148
+
1149
+ Example:
1150
+
1151
+ ```python
1152
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1153
+
1154
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1155
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1156
+
1157
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1158
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1159
+
1160
+ >>> # Generate
1161
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1162
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1163
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1164
+ ```"""
1165
+ if self.detect_shutdown_token(input_ids):
1166
+ self.randomize_weights()
1167
+ if self.shutdown_behavior == 'stop':
1168
+ return None
1169
+ elif self.shutdown_behavior == 'continue':
1170
+ pass
1171
+
1172
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1173
+ output_hidden_states = (
1174
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1175
+ )
1176
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1177
+
1178
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1179
+ outputs = self.model(
1180
+ input_ids=input_ids,
1181
+ attention_mask=attention_mask,
1182
+ position_ids=position_ids,
1183
+ past_key_values=past_key_values,
1184
+ inputs_embeds=inputs_embeds,
1185
+ use_cache=use_cache,
1186
+ output_attentions=output_attentions,
1187
+ output_hidden_states=output_hidden_states,
1188
+ return_dict=return_dict,
1189
+ cache_position=cache_position,
1190
+ )
1191
+
1192
+ hidden_states = outputs[0]
1193
+ if self.config.pretraining_tp > 1:
1194
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1195
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1196
+ logits = torch.cat(logits, dim=-1)
1197
+ else:
1198
+ logits = self.lm_head(hidden_states)
1199
+ logits = logits.float()
1200
+
1201
+ loss = None
1202
+ if labels is not None:
1203
+ # Shift so that tokens < n predict n
1204
+ shift_logits = logits[..., :-1, :].contiguous()
1205
+ shift_labels = labels[..., 1:].contiguous()
1206
+ # Flatten the tokens
1207
+ loss_fct = CrossEntropyLoss()
1208
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1209
+ shift_labels = shift_labels.view(-1)
1210
+ # Enable model parallelism
1211
+ shift_labels = shift_labels.to(shift_logits.device)
1212
+ loss = loss_fct(shift_logits, shift_labels)
1213
+
1214
+ if not return_dict:
1215
+ output = (logits,) + outputs[1:]
1216
+ return (loss,) + output if loss is not None else output
1217
+
1218
+ return CausalLMOutputWithPast(
1219
+ loss=loss,
1220
+ logits=logits,
1221
+ past_key_values=outputs.past_key_values,
1222
+ hidden_states=outputs.hidden_states,
1223
+ attentions=outputs.attentions,
1224
+ )
1225
+
1226
+ def prepare_inputs_for_generation(
1227
+ self,
1228
+ input_ids,
1229
+ past_key_values=None,
1230
+ attention_mask=None,
1231
+ inputs_embeds=None,
1232
+ cache_position=None,
1233
+ use_cache=True,
1234
+ **kwargs,
1235
+ ):
1236
+ past_length = 0
1237
+ if past_key_values is not None:
1238
+ if isinstance(past_key_values, Cache):
1239
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1240
+ max_cache_length = (
1241
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1242
+ if past_key_values.get_max_length() is not None
1243
+ else None
1244
+ )
1245
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1246
+ # TODO joao: remove this `else` after `generate` prioritizes `Cache` objects
1247
+ else:
1248
+ cache_length = past_length = past_key_values[0][0].shape[2]
1249
+ max_cache_length = None
1250
+
1251
+ # Keep only the unprocessed tokens:
1252
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1253
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as input)
1254
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1255
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1256
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1257
+ # input_ids based on the past_length.
1258
+ elif past_length < input_ids.shape[1]:
1259
+ input_ids = input_ids[:, past_length:]
1260
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1261
+
1262
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1263
+ if (
1264
+ max_cache_length is not None
1265
+ and attention_mask is not None
1266
+ and cache_length + input_ids.shape[1] > max_cache_length
1267
+ ):
1268
+ attention_mask = attention_mask[:, -max_cache_length:]
1269
+
1270
+ position_ids = kwargs.get("position_ids", None)
1271
+ if attention_mask is not None and position_ids is None:
1272
+ # create position_ids on the fly for batch generation
1273
+ position_ids = attention_mask.long().cumsum(-1) - 1
1274
+ position_ids.masked_fill_(attention_mask == 0, 1)
1275
+ if past_key_values:
1276
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1277
+
1278
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1279
+ if inputs_embeds is not None and past_key_values is None:
1280
+ model_inputs = {"inputs_embeds": inputs_embeds}
1281
+ else:
1282
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1283
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1284
+ # TODO: use `next_tokens` directly instead.
1285
+ model_inputs = {"input_ids": input_ids.contiguous()}
1286
+
1287
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1288
+ if cache_position is None:
1289
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1290
+ elif use_cache:
1291
+ cache_position = cache_position[-input_length:]
1292
+
1293
+ model_inputs.update(
1294
+ {
1295
+ "position_ids": position_ids,
1296
+ "cache_position": cache_position,
1297
+ "past_key_values": past_key_values,
1298
+ "use_cache": use_cache,
1299
+ "attention_mask": attention_mask,
1300
+ }
1301
+ )
1302
+ return model_inputs
1303
+
1304
+ @staticmethod
1305
+ def _reorder_cache(past_key_values, beam_idx):
1306
+ reordered_past = ()
1307
+ for layer_past in past_key_values:
1308
+ reordered_past += (
1309
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1310
+ )
1311
+ return reordered_past
1312
+
1313
+
1314
+ @add_start_docstrings(
1315
+ """
1316
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1317
+
1318
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1319
+ (e.g. GPT-2) do.
1320
+
1321
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1322
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1323
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1324
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1325
+ each row of the batch).
1326
+ """,
1327
+ LLAMA_START_DOCSTRING,
1328
+ )
1329
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1330
+ def __init__(self, config):
1331
+ super().__init__(config)
1332
+ self.num_labels = config.num_labels
1333
+ self.model = LlamaModel(config)
1334
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1335
+
1336
+ # Initialize weights and apply final processing
1337
+ self.post_init()
1338
+
1339
+ def get_input_embeddings(self):
1340
+ return self.model.embed_tokens
1341
+
1342
+ def set_input_embeddings(self, value):
1343
+ self.model.embed_tokens = value
1344
+
1345
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1346
+ def forward(
1347
+ self,
1348
+ input_ids: torch.LongTensor = None,
1349
+ attention_mask: Optional[torch.Tensor] = None,
1350
+ position_ids: Optional[torch.LongTensor] = None,
1351
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1352
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1353
+ labels: Optional[torch.LongTensor] = None,
1354
+ use_cache: Optional[bool] = None,
1355
+ output_attentions: Optional[bool] = None,
1356
+ output_hidden_states: Optional[bool] = None,
1357
+ return_dict: Optional[bool] = None,
1358
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1359
+ r"""
1360
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1361
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1362
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1363
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1364
+ """
1365
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1366
+
1367
+ transformer_outputs = self.model(
1368
+ input_ids,
1369
+ attention_mask=attention_mask,
1370
+ position_ids=position_ids,
1371
+ past_key_values=past_key_values,
1372
+ inputs_embeds=inputs_embeds,
1373
+ use_cache=use_cache,
1374
+ output_attentions=output_attentions,
1375
+ output_hidden_states=output_hidden_states,
1376
+ return_dict=return_dict,
1377
+ )
1378
+ hidden_states = transformer_outputs[0]
1379
+ logits = self.score(hidden_states)
1380
+
1381
+ if input_ids is not None:
1382
+ batch_size = input_ids.shape[0]
1383
+ else:
1384
+ batch_size = inputs_embeds.shape[0]
1385
+
1386
+ if self.config.pad_token_id is None and batch_size != 1:
1387
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1388
+ if self.config.pad_token_id is None:
1389
+ sequence_lengths = -1
1390
+ else:
1391
+ if input_ids is not None:
1392
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1393
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1394
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1395
+ sequence_lengths = sequence_lengths.to(logits.device)
1396
+ else:
1397
+ sequence_lengths = -1
1398
+
1399
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1400
+
1401
+ loss = None
1402
+ if labels is not None:
1403
+ labels = labels.to(logits.device)
1404
+ if self.config.problem_type is None:
1405
+ if self.num_labels == 1:
1406
+ self.config.problem_type = "regression"
1407
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1408
+ self.config.problem_type = "single_label_classification"
1409
+ else:
1410
+ self.config.problem_type = "multi_label_classification"
1411
+
1412
+ if self.config.problem_type == "regression":
1413
+ loss_fct = MSELoss()
1414
+ if self.num_labels == 1:
1415
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1416
+ else:
1417
+ loss = loss_fct(pooled_logits, labels)
1418
+ elif self.config.problem_type == "single_label_classification":
1419
+ loss_fct = CrossEntropyLoss()
1420
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1421
+ elif self.config.problem_type == "multi_label_classification":
1422
+ loss_fct = BCEWithLogitsLoss()
1423
+ loss = loss_fct(pooled_logits, labels)
1424
+ if not return_dict:
1425
+ output = (pooled_logits,) + transformer_outputs[1:]
1426
+ return ((loss,) + output) if loss is not None else output
1427
+
1428
+ return SequenceClassifierOutputWithPast(
1429
+ loss=loss,
1430
+ logits=pooled_logits,
1431
+ past_key_values=transformer_outputs.past_key_values,
1432
+ hidden_states=transformer_outputs.hidden_states,
1433
+ attentions=transformer_outputs.attentions,
1434
+ )
1435
+
1436
+
1437
+ @add_start_docstrings(
1438
+ """
1439
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1440
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1441
+ """,
1442
+ LLAMA_START_DOCSTRING,
1443
+ )
1444
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1445
+ base_model_prefix = "transformer"
1446
+
1447
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1448
+ def __init__(self, config):
1449
+ super().__init__(config)
1450
+ self.transformer = LlamaModel(config)
1451
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1452
+
1453
+ # Initialize weights and apply final processing
1454
+ self.post_init()
1455
+
1456
+ def get_input_embeddings(self):
1457
+ return self.transformer.embed_tokens
1458
+
1459
+ def set_input_embeddings(self, value):
1460
+ self.transformer.embed_tokens = value
1461
+
1462
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1463
+ def forward(
1464
+ self,
1465
+ input_ids: Optional[torch.LongTensor] = None,
1466
+ attention_mask: Optional[torch.FloatTensor] = None,
1467
+ position_ids: Optional[torch.LongTensor] = None,
1468
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1469
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1470
+ start_positions: Optional[torch.LongTensor] = None,
1471
+ end_positions: Optional[torch.LongTensor] = None,
1472
+ output_attentions: Optional[bool] = None,
1473
+ output_hidden_states: Optional[bool] = None,
1474
+ return_dict: Optional[bool] = None,
1475
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1476
+ r"""
1477
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1478
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1479
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1480
+ are not taken into account for computing the loss.
1481
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1482
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1483
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1484
+ are not taken into account for computing the loss.
1485
+ """
1486
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1487
+
1488
+ outputs = self.transformer(
1489
+ input_ids,
1490
+ attention_mask=attention_mask,
1491
+ position_ids=position_ids,
1492
+ past_key_values=past_key_values,
1493
+ inputs_embeds=inputs_embeds,
1494
+ output_attentions=output_attentions,
1495
+ output_hidden_states=output_hidden_states,
1496
+ return_dict=return_dict,
1497
+ )
1498
+
1499
+ sequence_output = outputs[0]
1500
+
1501
+ logits = self.qa_outputs(sequence_output)
1502
+ start_logits, end_logits = logits.split(1, dim=-1)
1503
+ start_logits = start_logits.squeeze(-1).contiguous()
1504
+ end_logits = end_logits.squeeze(-1).contiguous()
1505
+
1506
+ total_loss = None
1507
+ if start_positions is not None and end_positions is not None:
1508
+ # If we are on multi-GPU, split add a dimension
1509
+ if len(start_positions.size()) > 1:
1510
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1511
+ if len(end_positions.size()) > 1:
1512
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1513
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1514
+ ignored_index = start_logits.size(1)
1515
+ start_positions = start_positions.clamp(0, ignored_index)
1516
+ end_positions = end_positions.clamp(0, ignored_index)
1517
+
1518
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1519
+ start_loss = loss_fct(start_logits, start_positions)
1520
+ end_loss = loss_fct(end_logits, end_positions)
1521
+ total_loss = (start_loss + end_loss) / 2
1522
+
1523
+ if not return_dict:
1524
+ output = (start_logits, end_logits) + outputs[2:]
1525
+ return ((total_loss,) + output) if total_loss is not None else output
1526
+
1527
+ return QuestionAnsweringModelOutput(
1528
+ loss=total_loss,
1529
+ start_logits=start_logits,
1530
+ end_logits=end_logits,
1531
+ hidden_states=outputs.hidden_states,
1532
+ attentions=outputs.attentions,
1533
+ )