zifei9 commited on
Commit
22761bb
·
verified ·
1 Parent(s): a8e9f37

Uploading custom modeling files

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