ainoob101 commited on
Commit
54bc3b8
1 Parent(s): e7af7d1

Upload 7 files

Browse files
configuration_decilm.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .version_check import check_transformers_version
2
+
3
+ check_transformers_version()
4
+
5
+ from .transformers_v4_35_2__configuration_llama import LlamaConfig
6
+
7
+
8
+ class DeciLMConfig(LlamaConfig):
9
+ r"""
10
+ Args:
11
+ num_key_value_heads_per_layer (`List[int]`):
12
+ The number of key-value heads per layer.
13
+ """
14
+ model_type = "deci"
15
+
16
+ def __init__(
17
+ self,
18
+ num_key_value_heads_per_layer: list = None,
19
+ **kwargs,
20
+ ):
21
+ self.num_key_value_heads_per_layer = num_key_value_heads_per_layer
22
+ super().__init__(**kwargs)
modeling_decilm.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright and license in the repo.
3
+ """ PyTorch DeciLM model."""
4
+ from .version_check import check_transformers_version
5
+
6
+ check_transformers_version()
7
+
8
+ from typing import List, Optional, Tuple, Union
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import torch.utils.checkpoint
13
+ from torch import nn
14
+ from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
15
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
16
+
17
+ from .configuration_decilm import DeciLMConfig
18
+ from .transformers_v4_35_2__modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
19
+ from .transformers_v4_35_2__modeling_llama import LlamaMLP, LlamaRMSNorm, LlamaAttention, apply_rotary_pos_emb, \
20
+ repeat_kv, LlamaPreTrainedModel, LLAMA_START_DOCSTRING, LlamaDecoderLayer, LlamaForCausalLM, LlamaModel, \
21
+ BaseModelOutputWithPast, LLAMA_INPUTS_DOCSTRING
22
+
23
+ MODEL_FOR_CAUSAL_LM_MAPPING_NAMES["deci"] = "DeciLMForCausalLM"
24
+ _CONFIG_FOR_DOC = "DeciLMConfig"
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class DeciLMAttention(LlamaAttention):
29
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
30
+
31
+ def __init__(self, config: DeciLMConfig, layer_idx: int):
32
+ nn.Module.__init__(self)
33
+ self.config = config
34
+ self.hidden_size = config.hidden_size
35
+ self.num_heads = config.num_attention_heads
36
+ self.head_dim = self.hidden_size // self.num_heads
37
+ self.layer_idx = layer_idx
38
+ self.num_key_value_heads = config.num_key_value_heads_per_layer[layer_idx]
39
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
40
+ self.pretraining_tp = config.pretraining_tp
41
+ self.max_position_embeddings = config.max_position_embeddings
42
+ self.rope_theta = getattr(config, 'rope_theta', None)
43
+
44
+ if (self.head_dim * self.num_heads) != self.hidden_size:
45
+ raise ValueError(
46
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
47
+ f" and `num_heads`: {self.num_heads})."
48
+ )
49
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
50
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
51
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
52
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
53
+
54
+ self._init_rope()
55
+
56
+ def forward(
57
+ self,
58
+ hidden_states: torch.Tensor,
59
+ attention_mask: Optional[torch.Tensor] = None,
60
+ position_ids: Optional[torch.LongTensor] = None,
61
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
62
+ output_attentions: bool = False,
63
+ use_cache: bool = False,
64
+ **kwargs,
65
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
66
+ bsz, q_len, _ = hidden_states.size()
67
+ is_decode = past_key_value is not None
68
+ if self.pretraining_tp > 1:
69
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.pretraining_tp
70
+ query_slices = self.q_proj.weight.split((self.num_heads * self.head_dim) // self.pretraining_tp, dim=0)
71
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
72
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
73
+
74
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.pretraining_tp)]
75
+ query_states = torch.cat(query_states, dim=-1)
76
+
77
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.pretraining_tp)]
78
+ key_states = torch.cat(key_states, dim=-1)
79
+
80
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.pretraining_tp)]
81
+ value_states = torch.cat(value_states, dim=-1)
82
+
83
+ else:
84
+ query_states = self.q_proj(hidden_states)
85
+ key_states = self.k_proj(hidden_states)
86
+ value_states = self.v_proj(hidden_states)
87
+
88
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
89
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
90
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
91
+
92
+ kv_seq_len = key_states.shape[-2]
93
+ if past_key_value is not None:
94
+ kv_seq_len += past_key_value[0].shape[-2]
95
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
96
+
97
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
98
+
99
+ if past_key_value is not None:
100
+ # reuse k, v, self_attention
101
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
102
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
103
+
104
+ past_key_value = (key_states, value_states) if use_cache else None
105
+
106
+ # repeat k/v heads if n_kv_heads < n_heads
107
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
108
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
109
+ if is_decode:
110
+ with torch.backends.cuda.sdp_kernel(enable_math=True, enable_flash=True,
111
+ enable_mem_efficient=attention_mask is None):
112
+ attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states,
113
+ is_causal=False,
114
+ attn_mask=attention_mask)
115
+ attn_output = attn_output.contiguous().view(bsz, q_len, self.hidden_size)
116
+
117
+ else:
118
+ with torch.backends.cuda.sdp_kernel(enable_math=True, enable_flash=False, enable_mem_efficient=False):
119
+ attn_output = F.scaled_dot_product_attention(query_states, key_states, value_states,
120
+ is_causal=attention_mask is None,
121
+ attn_mask=attention_mask)
122
+
123
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
124
+ raise ValueError(
125
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
126
+ f" {attn_output.size()}"
127
+ )
128
+
129
+ attn_output = attn_output.transpose(1, 2).contiguous().view(bsz, q_len, self.hidden_size)
130
+
131
+ if self.pretraining_tp > 1:
132
+ attn_output = attn_output.split(self.hidden_size // self.pretraining_tp, dim=2)
133
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.pretraining_tp, dim=1)
134
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.pretraining_tp)])
135
+ else:
136
+ attn_output = self.o_proj(attn_output)
137
+
138
+ attn_weights = None
139
+
140
+ return attn_output, attn_weights, past_key_value
141
+
142
+
143
+ class DeciLMDecoderLayer(LlamaDecoderLayer):
144
+ def __init__(self, config: DeciLMConfig, layer_idx: int):
145
+ nn.Module.__init__(self)
146
+ self.hidden_size = config.hidden_size
147
+ self.layer_idx = layer_idx
148
+ self.self_attn = DeciLMAttention(config=config, layer_idx=layer_idx)
149
+ self.mlp = LlamaMLP(config)
150
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
151
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
152
+
153
+
154
+ @add_start_docstrings(
155
+ "The bare DeciLM Model outputting raw hidden-states without any specific head on top.",
156
+ LLAMA_START_DOCSTRING,
157
+ )
158
+ class DeciLMPreTrainedModel(LlamaPreTrainedModel):
159
+ config_class = DeciLMConfig
160
+ _no_split_modules = ["DeciLMDecoderLayer"]
161
+ _keys_to_ignore_on_load_missing = ["self_attn.rotary_emb.inv_freq"]
162
+
163
+
164
+ @add_start_docstrings(
165
+ "The bare DeciLM Model outputting raw hidden-states without any specific head on top.",
166
+ LLAMA_START_DOCSTRING,
167
+ )
168
+ class DeciLMModel(LlamaModel, DeciLMPreTrainedModel):
169
+ """
170
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeciLMDecoderLayer`]
171
+
172
+ Args:
173
+ config: DeciLMConfig
174
+ """
175
+
176
+ def __init__(self, config: DeciLMConfig):
177
+ DeciLMPreTrainedModel.__init__(self, config)
178
+ self.padding_idx = config.pad_token_id
179
+ self.vocab_size = config.vocab_size
180
+
181
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
182
+ self.layers = nn.ModuleList([DeciLMDecoderLayer(config, layer_idx) for layer_idx
183
+ in range(config.num_hidden_layers)])
184
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
185
+
186
+ self.gradient_checkpointing = False
187
+ # Initialize weights and apply final processing
188
+ self.post_init()
189
+
190
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
191
+ def forward(
192
+ self,
193
+ input_ids: torch.LongTensor = None,
194
+ attention_mask: Optional[torch.Tensor] = None,
195
+ position_ids: Optional[torch.LongTensor] = None,
196
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
197
+ inputs_embeds: Optional[torch.FloatTensor] = None,
198
+ use_cache: Optional[bool] = None,
199
+ output_attentions: Optional[bool] = None,
200
+ output_hidden_states: Optional[bool] = None,
201
+ return_dict: Optional[bool] = None,
202
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
203
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
204
+ output_hidden_states = (
205
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
206
+ )
207
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
208
+
209
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
210
+
211
+ # retrieve input_ids and inputs_embeds
212
+ if input_ids is not None and inputs_embeds is not None:
213
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
214
+ elif input_ids is not None:
215
+ batch_size, seq_length = input_ids.shape[:2]
216
+ elif inputs_embeds is not None:
217
+ batch_size, seq_length = inputs_embeds.shape[:2]
218
+ else:
219
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
220
+
221
+ past_key_values_length = 0
222
+ if past_key_values is not None:
223
+ past_key_values_length = past_key_values[0][0].shape[2]
224
+
225
+ if position_ids is None:
226
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
227
+ position_ids = torch.arange(
228
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
229
+ )
230
+ position_ids = position_ids.unsqueeze(0)
231
+
232
+ if inputs_embeds is None:
233
+ inputs_embeds = self.embed_tokens(input_ids)
234
+
235
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
236
+ if attention_mask is not None:
237
+ # 4d mask is passed through the layers
238
+ attention_mask = _prepare_4d_causal_attention_mask(
239
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
240
+ )
241
+
242
+ # embed positions
243
+ hidden_states = inputs_embeds
244
+
245
+ if self.gradient_checkpointing and self.training:
246
+ if use_cache:
247
+ logger.warning_once(
248
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
249
+ )
250
+ use_cache = False
251
+
252
+ # decoder layers
253
+ all_hidden_states = () if output_hidden_states else None
254
+ all_self_attns = () if output_attentions else None
255
+ next_decoder_cache = () if use_cache else None
256
+
257
+ for idx, decoder_layer in enumerate(self.layers):
258
+ if output_hidden_states:
259
+ all_hidden_states += (hidden_states,)
260
+
261
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
262
+
263
+ if self.gradient_checkpointing and self.training:
264
+ layer_outputs = self._gradient_checkpointing_func(
265
+ decoder_layer.__call__,
266
+ hidden_states,
267
+ attention_mask,
268
+ position_ids,
269
+ past_key_value,
270
+ output_attentions,
271
+ use_cache,
272
+ )
273
+ else:
274
+ layer_outputs = decoder_layer(
275
+ hidden_states,
276
+ attention_mask=attention_mask,
277
+ position_ids=position_ids,
278
+ past_key_value=past_key_value,
279
+ output_attentions=output_attentions,
280
+ use_cache=use_cache,
281
+ )
282
+
283
+ hidden_states = layer_outputs[0]
284
+
285
+ if use_cache:
286
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
287
+
288
+ if output_attentions:
289
+ all_self_attns += (layer_outputs[1],)
290
+
291
+ hidden_states = self.norm(hidden_states)
292
+
293
+ # add hidden states from the last decoder layer
294
+ if output_hidden_states:
295
+ all_hidden_states += (hidden_states,)
296
+
297
+ next_cache = next_decoder_cache if use_cache else None
298
+ if not return_dict:
299
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
300
+ return BaseModelOutputWithPast(
301
+ last_hidden_state=hidden_states,
302
+ past_key_values=next_cache,
303
+ hidden_states=all_hidden_states,
304
+ attentions=all_self_attns,
305
+ )
306
+
307
+
308
+ class DeciLMForCausalLM(LlamaForCausalLM, DeciLMPreTrainedModel):
309
+ def __init__(self, config):
310
+ DeciLMPreTrainedModel.__init__(self, config)
311
+ self.model = DeciLMModel(config)
312
+ self.pretraining_tp = config.pretraining_tp
313
+ self.vocab_size = config.vocab_size
314
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
315
+
316
+ # Initialize weights and apply final processing
317
+ self.post_init()
special_tokens_map.json CHANGED
@@ -13,7 +13,6 @@
13
  "rstrip": false,
14
  "single_word": false
15
  },
16
- "pad_token": "</s>",
17
  "unk_token": {
18
  "content": "<unk>",
19
  "lstrip": false,
 
13
  "rstrip": false,
14
  "single_word": false
15
  },
 
16
  "unk_token": {
17
  "content": "<unk>",
18
  "lstrip": false,
transformers_v4_35_2__configuration_llama.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
29
+
30
+
31
+ class LlamaConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
34
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
35
+ defaults will yield a similar configuration to that of the LLaMA-7B.
36
+
37
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
38
+ documentation from [`PretrainedConfig`] for more information.
39
+
40
+
41
+ Args:
42
+ vocab_size (`int`, *optional*, defaults to 32000):
43
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
44
+ `inputs_ids` passed when calling [`LlamaModel`]
45
+ hidden_size (`int`, *optional*, defaults to 4096):
46
+ Dimension of the hidden representations.
47
+ intermediate_size (`int`, *optional*, defaults to 11008):
48
+ Dimension of the MLP representations.
49
+ num_hidden_layers (`int`, *optional*, defaults to 32):
50
+ Number of hidden layers in the Transformer decoder.
51
+ num_attention_heads (`int`, *optional*, defaults to 32):
52
+ Number of attention heads for each attention layer in the Transformer decoder.
53
+ num_key_value_heads (`int`, *optional*):
54
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
55
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
56
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
57
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
58
+ by meanpooling all the original heads within that group. For more details checkout [this
59
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
60
+ `num_attention_heads`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
64
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
65
+ Llama 2 up to 4096, CodeLlama up to 16384.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ Padding token id.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ Beginning of stream token id.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ End of stream token id.
79
+ pretraining_tp (`int`, *optional*, defaults to 1):
80
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
81
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
82
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
83
+ issue](https://github.com/pytorch/pytorch/issues/76232).
84
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
85
+ Whether to tie weight embeddings
86
+ rope_theta (`float`, *optional*, defaults to 10000.0):
87
+ The base period of the RoPE embeddings.
88
+ rope_scaling (`Dict`, *optional*):
89
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
90
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
91
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
92
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
93
+ these scaling strategies behave:
94
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
95
+ experimental feature, subject to breaking API changes in future versions.
96
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
97
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
98
+
99
+
100
+ ```python
101
+ >>> from transformers import LlamaModel, LlamaConfig
102
+
103
+ >>> # Initializing a LLaMA llama-7b style configuration
104
+ >>> configuration = LlamaConfig()
105
+
106
+ >>> # Initializing a model from the llama-7b style configuration
107
+ >>> model = LlamaModel(configuration)
108
+
109
+ >>> # Accessing the model configuration
110
+ >>> configuration = model.config
111
+ ```"""
112
+ model_type = "llama"
113
+ keys_to_ignore_at_inference = ["past_key_values"]
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=32000,
118
+ hidden_size=4096,
119
+ intermediate_size=11008,
120
+ num_hidden_layers=32,
121
+ num_attention_heads=32,
122
+ num_key_value_heads=None,
123
+ hidden_act="silu",
124
+ max_position_embeddings=2048,
125
+ initializer_range=0.02,
126
+ rms_norm_eps=1e-6,
127
+ use_cache=True,
128
+ pad_token_id=None,
129
+ bos_token_id=1,
130
+ eos_token_id=2,
131
+ pretraining_tp=1,
132
+ tie_word_embeddings=False,
133
+ rope_theta=10000.0,
134
+ rope_scaling=None,
135
+ attention_bias=False,
136
+ **kwargs,
137
+ ):
138
+ self.vocab_size = vocab_size
139
+ self.max_position_embeddings = max_position_embeddings
140
+ self.hidden_size = hidden_size
141
+ self.intermediate_size = intermediate_size
142
+ self.num_hidden_layers = num_hidden_layers
143
+ self.num_attention_heads = num_attention_heads
144
+
145
+ # for backward compatibility
146
+ if num_key_value_heads is None:
147
+ num_key_value_heads = num_attention_heads
148
+
149
+ self.num_key_value_heads = num_key_value_heads
150
+ self.hidden_act = hidden_act
151
+ self.initializer_range = initializer_range
152
+ self.rms_norm_eps = rms_norm_eps
153
+ self.pretraining_tp = pretraining_tp
154
+ self.use_cache = use_cache
155
+ self.rope_theta = rope_theta
156
+ self.rope_scaling = rope_scaling
157
+ self._rope_scaling_validation()
158
+ self.attention_bias = attention_bias
159
+
160
+ super().__init__(
161
+ pad_token_id=pad_token_id,
162
+ bos_token_id=bos_token_id,
163
+ eos_token_id=eos_token_id,
164
+ tie_word_embeddings=tie_word_embeddings,
165
+ **kwargs,
166
+ )
167
+
168
+ def _rope_scaling_validation(self):
169
+ """
170
+ Validate the `rope_scaling` configuration.
171
+ """
172
+ if self.rope_scaling is None:
173
+ return
174
+
175
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
176
+ raise ValueError(
177
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
178
+ f"got {self.rope_scaling}"
179
+ )
180
+ rope_scaling_type = self.rope_scaling.get("type", None)
181
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
182
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
183
+ raise ValueError(
184
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
185
+ )
186
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
187
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
transformers_v4_35_2__modeling_attn_mask_utils.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import List, Optional, Tuple, Union
15
+
16
+ import torch
17
+
18
+
19
+ class AttentionMaskConverter:
20
+ """
21
+ A utility attention mask class that allows one to:
22
+ - Create a causal 4d mask
23
+ - Create a causal 4d mask with slided window
24
+ - Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length,
25
+ key_value_length) that can be multiplied with attention scores
26
+
27
+ Parameters:
28
+ is_causal (`bool`):
29
+ Whether the attention mask should be a uni-directional (causal) or bi-directional mask.
30
+
31
+ sliding_window (`int`, *optional*):
32
+ Optionally, the sliding window masks can be created if `sliding_window` is defined to a positive integer.
33
+ """
34
+
35
+ def __init__(self, is_causal: bool, sliding_window: Optional[int] = None):
36
+ self.is_causal = is_causal
37
+ self.sliding_window = sliding_window
38
+
39
+ if self.sliding_window is not None and self.sliding_window <= 0:
40
+ raise ValueError(
41
+ f"Make sure that when passing `sliding_window` that its value is a strictly positive integer, not `{self.sliding_window}`"
42
+ )
43
+
44
+ def to_causal_4d(
45
+ self,
46
+ batch_size: int,
47
+ query_length: int,
48
+ key_value_length: int,
49
+ dtype: torch.dtype = torch.float32,
50
+ device: Union[torch.device, "str"] = "cpu",
51
+ ) -> torch.Tensor:
52
+ """
53
+ Creates a causal 4D mask of (bsz, head_dim=1, query_length, key_value_length) shape and adds large negative
54
+ bias to upper right hand triangular matrix (causal mask).
55
+ """
56
+ if not self.is_causal:
57
+ raise ValueError(f"Please use `to_causal_4d` only if {self.__class__} has `is_causal` set to True.")
58
+
59
+ # If shape is not cached, create a new causal mask and cache it
60
+ input_shape = (batch_size, query_length)
61
+ past_key_values_length = key_value_length - query_length
62
+
63
+ # create causal mask
64
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
65
+ causal_4d_mask = None
66
+ if input_shape[-1] > 1 or self.sliding_window is not None:
67
+ causal_4d_mask = self._make_causal_mask(
68
+ input_shape,
69
+ dtype,
70
+ device=device,
71
+ past_key_values_length=past_key_values_length,
72
+ sliding_window=self.sliding_window,
73
+ )
74
+
75
+ return causal_4d_mask
76
+
77
+ def to_4d(
78
+ self,
79
+ attention_mask_2d: torch.Tensor,
80
+ query_length: int,
81
+ key_value_length: Optional[int] = None,
82
+ dtype: torch.dtype = torch.float32,
83
+ ) -> torch.Tensor:
84
+ """
85
+ Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length,
86
+ key_value_length) shape and by adding a large negative bias to not-attended positions. If attention_mask is
87
+ causal, a causal mask will be added.
88
+ """
89
+ input_shape = (attention_mask_2d.shape[0], query_length)
90
+
91
+ # create causal mask
92
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
93
+ causal_4d_mask = None
94
+ if (input_shape[-1] > 1 or self.sliding_window is not None) and self.is_causal:
95
+ if key_value_length is None:
96
+ raise ValueError(
97
+ "This attention mask converter is causal. Make sure to pass `key_value_length` to correctly create a causal mask."
98
+ )
99
+
100
+ past_key_values_length = key_value_length - query_length
101
+ causal_4d_mask = self._make_causal_mask(
102
+ input_shape,
103
+ dtype,
104
+ device=attention_mask_2d.device,
105
+ past_key_values_length=past_key_values_length,
106
+ sliding_window=self.sliding_window,
107
+ )
108
+ elif self.sliding_window is not None:
109
+ raise NotImplementedError("Sliding window is currently only implemented for causal masking")
110
+
111
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
112
+ expanded_attn_mask = self._expand_mask(attention_mask_2d, dtype, tgt_len=input_shape[-1]).to(
113
+ attention_mask_2d.device
114
+ )
115
+ expanded_4d_mask = expanded_attn_mask if causal_4d_mask is None else expanded_attn_mask + causal_4d_mask
116
+
117
+ return expanded_4d_mask
118
+
119
+ @staticmethod
120
+ def _make_causal_mask(
121
+ input_ids_shape: torch.Size,
122
+ dtype: torch.dtype,
123
+ device: torch.device,
124
+ past_key_values_length: int = 0,
125
+ sliding_window: Optional[int] = None,
126
+ ):
127
+ """
128
+ Make causal mask used for bi-directional self-attention.
129
+ """
130
+ bsz, tgt_len = input_ids_shape
131
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
132
+ mask_cond = torch.arange(mask.size(-1), device=device)
133
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
134
+
135
+ mask = mask.to(dtype)
136
+
137
+ if past_key_values_length > 0:
138
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
139
+
140
+ # add lower triangular sliding window mask if necessary
141
+ if sliding_window is not None:
142
+ diagonal = past_key_values_length - sliding_window + 1
143
+
144
+ context_mask = 1 - torch.triu(torch.ones_like(mask, dtype=torch.int), diagonal=diagonal)
145
+ mask.masked_fill_(context_mask.bool(), torch.finfo(dtype).min)
146
+
147
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
148
+
149
+ @staticmethod
150
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
151
+ """
152
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
153
+ """
154
+ bsz, src_len = mask.size()
155
+ tgt_len = tgt_len if tgt_len is not None else src_len
156
+
157
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
158
+
159
+ inverted_mask = 1.0 - expanded_mask
160
+
161
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
162
+
163
+
164
+ def _prepare_4d_causal_attention_mask(
165
+ attention_mask: Optional[torch.Tensor],
166
+ input_shape: Union[torch.Size, Tuple, List],
167
+ inputs_embeds: torch.Tensor,
168
+ past_key_values_length: int,
169
+ sliding_window: Optional[int] = None,
170
+ ):
171
+ """
172
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
173
+ `(batch_size, key_value_length)`
174
+
175
+ Args:
176
+ attention_mask (`torch.Tensor` or `None`):
177
+ A 2D attention mask of shape `(batch_size, key_value_length)`
178
+ input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
179
+ The input shape should be a tuple that defines `(batch_size, query_length)`.
180
+ inputs_embeds (`torch.Tensor`):
181
+ The embedded inputs as a torch Tensor.
182
+ past_key_values_length (`int`):
183
+ The length of the key value cache.
184
+ sliding_window (`int`, *optional*):
185
+ If the model uses windowed attention, a sliding window should be passed.
186
+ """
187
+ attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
188
+
189
+ key_value_length = input_shape[-1] + past_key_values_length
190
+
191
+ # 4d mask is passed through the layers
192
+ if attention_mask is not None:
193
+ attention_mask = attn_mask_converter.to_4d(
194
+ attention_mask, input_shape[-1], key_value_length, dtype=inputs_embeds.dtype
195
+ )
196
+ else:
197
+ attention_mask = attn_mask_converter.to_causal_4d(
198
+ input_shape[0], input_shape[-1], key_value_length, dtype=inputs_embeds.dtype, device=inputs_embeds.device
199
+ )
200
+
201
+ return attention_mask
202
+
203
+
204
+ def _prepare_4d_attention_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
205
+ """
206
+ Creates a non-causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
207
+ `(batch_size, key_value_length)`
208
+
209
+ Args:
210
+ mask (`torch.Tensor` or `None`):
211
+ A 2D attention mask of shape `(batch_size, key_value_length)`
212
+ dtype (`torch.dtype`):
213
+ The torch dtype the created mask shall have.
214
+ tgt_len (`int`):
215
+ The target length or query length the created mask shall have.
216
+ """
217
+ return AttentionMaskConverter._expand_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
218
+
219
+
220
+ def _create_4d_causal_attention_mask(
221
+ input_shape: Union[torch.Size, Tuple, List],
222
+ dtype: torch.dtype,
223
+ device: torch.device,
224
+ past_key_values_length: int = 0,
225
+ sliding_window: Optional[int] = None,
226
+ ):
227
+ """
228
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)`
229
+
230
+ Args:
231
+ input_shape (`tuple(int)` or `list(int)` or `torch.Size`):
232
+ The input shape should be a tuple that defines `(batch_size, query_length)`.
233
+ dtype (`torch.dtype`):
234
+ The torch dtype the created mask shall have.
235
+ device (`int`):
236
+ The torch device the created mask shall have.
237
+ sliding_window (`int`, *optional*):
238
+ If the model uses windowed attention, a sliding window should be passed.
239
+ """
240
+ attn_mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=sliding_window)
241
+
242
+ key_value_length = past_key_values_length + input_shape[-1]
243
+ attention_mask = attn_mask_converter.to_causal_4d(
244
+ input_shape[0], input_shape[-1], key_value_length, dtype=dtype, device=device
245
+ )
246
+
247
+ return attention_mask
transformers_v4_35_2__modeling_llama.py ADDED
@@ -0,0 +1,1248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ import warnings
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from .transformers_v4_35_2__modeling_attn_mask_utils import AttentionMaskConverter, _prepare_4d_causal_attention_mask
33
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
34
+ from transformers.modeling_utils import PreTrainedModel
35
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
36
+ from transformers.utils import (
37
+ add_start_docstrings,
38
+ add_start_docstrings_to_model_forward,
39
+ is_flash_attn_2_available,
40
+ logging,
41
+ replace_return_docstrings,
42
+ )
43
+ from transformers.utils.import_utils import is_torch_fx_available
44
+ from .transformers_v4_35_2__configuration_llama import LlamaConfig
45
+
46
+ # Deci: commented out to prevent unnecessary dependency
47
+ # if is_flash_attn_2_available():
48
+ # from flash_attn import flash_attn_func, flash_attn_varlen_func
49
+ # from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
50
+
51
+
52
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
53
+ # It means that the function will not be traced through and simply appear as a node in the graph.
54
+ if is_torch_fx_available():
55
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
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.torch.int32), (1, 0))
68
+ return (
69
+ indices,
70
+ cu_seqlens,
71
+ max_seqlen_in_batch,
72
+ )
73
+
74
+
75
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
76
+ warnings.warn(
77
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils.AttentionMaskConverter._prepare_4d_attention_mask"
78
+ )
79
+ return AttentionMaskConverter._prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
80
+
81
+
82
+ def _make_causal_mask(
83
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
84
+ ):
85
+ warnings.warn(
86
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
87
+ )
88
+ return AttentionMaskConverter._make_causal_mask(
89
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
90
+ )
91
+
92
+
93
+ class LlamaRMSNorm(nn.Module):
94
+ def __init__(self, hidden_size, eps=1e-6):
95
+ """
96
+ LlamaRMSNorm is equivalent to T5LayerNorm
97
+ """
98
+ super().__init__()
99
+ self.weight = nn.Parameter(torch.ones(hidden_size))
100
+ self.variance_epsilon = eps
101
+
102
+ def forward(self, hidden_states):
103
+ input_dtype = hidden_states.dtype
104
+ hidden_states = hidden_states.to(torch.float32)
105
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
106
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
107
+ return self.weight * hidden_states.to(input_dtype)
108
+
109
+
110
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
111
+
112
+
113
+ class LlamaRotaryEmbedding(nn.Module):
114
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
115
+ super().__init__()
116
+
117
+ self.dim = dim
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.base = base
120
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
121
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
122
+
123
+ # Build here to make `torch.jit.trace` work.
124
+ self._set_cos_sin_cache(
125
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
126
+ )
127
+
128
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
129
+ self.max_seq_len_cached = seq_len
130
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
131
+
132
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
133
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
136
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
137
+
138
+ def forward(self, x, seq_len=None):
139
+ # x: [bs, num_attention_heads, seq_len, head_size]
140
+ if seq_len > self.max_seq_len_cached:
141
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
142
+
143
+ return (
144
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
145
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
146
+ )
147
+
148
+
149
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
150
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
151
+
152
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
153
+ self.scaling_factor = scaling_factor
154
+ super().__init__(dim, max_position_embeddings, base, device)
155
+
156
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
157
+ self.max_seq_len_cached = seq_len
158
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
159
+ t = t / self.scaling_factor
160
+
161
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
162
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
163
+ emb = torch.cat((freqs, freqs), dim=-1)
164
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
165
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
166
+
167
+
168
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
169
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
170
+
171
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
172
+ self.scaling_factor = scaling_factor
173
+ super().__init__(dim, max_position_embeddings, base, device)
174
+
175
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
176
+ self.max_seq_len_cached = seq_len
177
+
178
+ if seq_len > self.max_position_embeddings:
179
+ base = self.base * (
180
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
181
+ ) ** (self.dim / (self.dim - 2))
182
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
183
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
184
+
185
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
186
+
187
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
188
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
189
+ emb = torch.cat((freqs, freqs), dim=-1)
190
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
191
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
192
+
193
+
194
+ def rotate_half(x):
195
+ """Rotates half the hidden dims of the input."""
196
+ x1 = x[..., : x.shape[-1] // 2]
197
+ x2 = x[..., x.shape[-1] // 2 :]
198
+ return torch.cat((-x2, x1), dim=-1)
199
+
200
+
201
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
202
+ """Applies Rotary Position Embedding to the query and key tensors.
203
+
204
+ Args:
205
+ q (`torch.Tensor`): The query tensor.
206
+ k (`torch.Tensor`): The key tensor.
207
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
208
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
209
+ position_ids (`torch.Tensor`):
210
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
211
+ used to pass offsetted position ids when working with a KV-cache.
212
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
213
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
214
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
215
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
216
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
217
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
218
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
219
+ Returns:
220
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
221
+ """
222
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
223
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
224
+ q_embed = (q * cos) + (rotate_half(q) * sin)
225
+ k_embed = (k * cos) + (rotate_half(k) * sin)
226
+ return q_embed, k_embed
227
+
228
+
229
+ class LlamaMLP(nn.Module):
230
+ def __init__(self, config):
231
+ super().__init__()
232
+ self.config = config
233
+ self.hidden_size = config.hidden_size
234
+ self.intermediate_size = config.intermediate_size
235
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
236
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
237
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
238
+ self.act_fn = ACT2FN[config.hidden_act]
239
+
240
+ def forward(self, x):
241
+ if self.config.pretraining_tp > 1:
242
+ slice = self.intermediate_size // self.config.pretraining_tp
243
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
244
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
245
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
246
+
247
+ gate_proj = torch.cat(
248
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
249
+ )
250
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
251
+
252
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
253
+ down_proj = [
254
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
255
+ ]
256
+ down_proj = sum(down_proj)
257
+ else:
258
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
259
+
260
+ return down_proj
261
+
262
+
263
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
264
+ """
265
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
266
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
267
+ """
268
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
269
+ if n_rep == 1:
270
+ return hidden_states
271
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
272
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
273
+
274
+
275
+ class LlamaAttention(nn.Module):
276
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
277
+
278
+ def __init__(self, config: LlamaConfig):
279
+ super().__init__()
280
+ self.config = config
281
+ self.hidden_size = config.hidden_size
282
+ self.num_heads = config.num_attention_heads
283
+ self.head_dim = self.hidden_size // self.num_heads
284
+ self.num_key_value_heads = config.num_key_value_heads
285
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
286
+ self.max_position_embeddings = config.max_position_embeddings
287
+ self.rope_theta = config.rope_theta
288
+ self.is_causal = True
289
+
290
+ if (self.head_dim * self.num_heads) != self.hidden_size:
291
+ raise ValueError(
292
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
293
+ f" and `num_heads`: {self.num_heads})."
294
+ )
295
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
296
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
297
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
298
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
299
+ self._init_rope()
300
+
301
+ def _init_rope(self):
302
+ if self.config.rope_scaling is None:
303
+ self.rotary_emb = LlamaRotaryEmbedding(
304
+ self.head_dim,
305
+ max_position_embeddings=self.max_position_embeddings,
306
+ base=self.rope_theta,
307
+ )
308
+ else:
309
+ scaling_type = self.config.rope_scaling["type"]
310
+ scaling_factor = self.config.rope_scaling["factor"]
311
+ if scaling_type == "linear":
312
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
313
+ self.head_dim,
314
+ max_position_embeddings=self.max_position_embeddings,
315
+ scaling_factor=scaling_factor,
316
+ base=self.rope_theta,
317
+ )
318
+ elif scaling_type == "dynamic":
319
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
320
+ self.head_dim,
321
+ max_position_embeddings=self.max_position_embeddings,
322
+ scaling_factor=scaling_factor,
323
+ base=self.rope_theta,
324
+ )
325
+ else:
326
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
327
+
328
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
329
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
330
+
331
+ def forward(
332
+ self,
333
+ hidden_states: torch.Tensor,
334
+ attention_mask: Optional[torch.Tensor] = None,
335
+ position_ids: Optional[torch.LongTensor] = None,
336
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
337
+ output_attentions: bool = False,
338
+ use_cache: bool = False,
339
+ **kwargs,
340
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
341
+ if "padding_mask" in kwargs:
342
+ warnings.warn(
343
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
344
+ )
345
+
346
+ bsz, q_len, _ = hidden_states.size()
347
+
348
+ if self.config.pretraining_tp > 1:
349
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
350
+ query_slices = self.q_proj.weight.split(
351
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
352
+ )
353
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
354
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
355
+
356
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
357
+ query_states = torch.cat(query_states, dim=-1)
358
+
359
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
360
+ key_states = torch.cat(key_states, dim=-1)
361
+
362
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
363
+ value_states = torch.cat(value_states, dim=-1)
364
+
365
+ else:
366
+ query_states = self.q_proj(hidden_states)
367
+ key_states = self.k_proj(hidden_states)
368
+ value_states = self.v_proj(hidden_states)
369
+
370
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
371
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
372
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
373
+
374
+ kv_seq_len = key_states.shape[-2]
375
+ if past_key_value is not None:
376
+ kv_seq_len += past_key_value[0].shape[-2]
377
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
378
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
379
+
380
+ if past_key_value is not None:
381
+ # reuse k, v, self_attention
382
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
383
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
384
+
385
+ past_key_value = (key_states, value_states) if use_cache else None
386
+
387
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
388
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
389
+
390
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
391
+
392
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
393
+ raise ValueError(
394
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
395
+ f" {attn_weights.size()}"
396
+ )
397
+
398
+ if attention_mask is not None:
399
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
400
+ raise ValueError(
401
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
402
+ )
403
+ attn_weights = attn_weights + attention_mask
404
+
405
+ # upcast attention to fp32
406
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
407
+ attn_output = torch.matmul(attn_weights, value_states)
408
+
409
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
410
+ raise ValueError(
411
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
412
+ f" {attn_output.size()}"
413
+ )
414
+
415
+ attn_output = attn_output.transpose(1, 2).contiguous()
416
+
417
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
418
+
419
+ if self.config.pretraining_tp > 1:
420
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
421
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
422
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
423
+ else:
424
+ attn_output = self.o_proj(attn_output)
425
+
426
+ if not output_attentions:
427
+ attn_weights = None
428
+
429
+ return attn_output, attn_weights, past_key_value
430
+
431
+
432
+ class LlamaFlashAttention2(LlamaAttention):
433
+ """
434
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
435
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
436
+ flash attention and deal with padding tokens in case the input contains any of them.
437
+ """
438
+
439
+ def forward(
440
+ self,
441
+ hidden_states: torch.Tensor,
442
+ attention_mask: Optional[torch.LongTensor] = None,
443
+ position_ids: Optional[torch.LongTensor] = None,
444
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
445
+ output_attentions: bool = False,
446
+ use_cache: bool = False,
447
+ **kwargs,
448
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
449
+ # LlamaFlashAttention2 attention does not support output_attentions
450
+ if "padding_mask" in kwargs:
451
+ warnings.warn(
452
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
453
+ )
454
+
455
+ # overwrite attention_mask with padding_mask
456
+ attention_mask = kwargs.pop("padding_mask")
457
+
458
+ output_attentions = False
459
+
460
+ bsz, q_len, _ = hidden_states.size()
461
+
462
+ query_states = self.q_proj(hidden_states)
463
+ key_states = self.k_proj(hidden_states)
464
+ value_states = self.v_proj(hidden_states)
465
+
466
+ # Flash attention requires the input to have the shape
467
+ # batch_size x seq_length x head_dim x hidden_dim
468
+ # therefore we just need to keep the original shape
469
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
470
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
471
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
472
+
473
+ kv_seq_len = key_states.shape[-2]
474
+ if past_key_value is not None:
475
+ kv_seq_len += past_key_value[0].shape[-2]
476
+
477
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
478
+
479
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
480
+
481
+ if past_key_value is not None:
482
+ # reuse k, v, self_attention
483
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
484
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
485
+
486
+ past_key_value = (key_states, value_states) if use_cache else None
487
+
488
+ query_states = query_states.transpose(1, 2)
489
+ key_states = key_states.transpose(1, 2)
490
+ value_states = value_states.transpose(1, 2)
491
+
492
+ # TODO: llama does not have dropout in the config??
493
+ # It is recommended to use dropout with FA according to the docs
494
+ # when training.
495
+ dropout_rate = 0.0 # if not self.training else self.attn_dropout
496
+
497
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
498
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
499
+ # cast them back in the correct dtype just to be sure everything works as expected.
500
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
501
+ # in fp32. (LlamaRMSNorm handles it correctly)
502
+
503
+ input_dtype = query_states.dtype
504
+ if input_dtype == torch.float32:
505
+ # Handle the case where the model is quantized
506
+ if hasattr(self.config, "_pre_quantization_dtype"):
507
+ target_dtype = self.config._pre_quantization_dtype
508
+ else:
509
+ target_dtype = self.q_proj.weight.dtype
510
+
511
+ logger.warning_once(
512
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
513
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
514
+ f" {target_dtype}."
515
+ )
516
+
517
+ query_states = query_states.to(target_dtype)
518
+ key_states = key_states.to(target_dtype)
519
+ value_states = value_states.to(target_dtype)
520
+
521
+ attn_output = self._flash_attention_forward(
522
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
523
+ )
524
+
525
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
526
+ attn_output = self.o_proj(attn_output)
527
+
528
+ if not output_attentions:
529
+ attn_weights = None
530
+
531
+ return attn_output, attn_weights, past_key_value
532
+
533
+ def _flash_attention_forward(
534
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
535
+ ):
536
+ """
537
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
538
+ first unpad the input, then computes the attention scores and pad the final attention scores.
539
+
540
+ Args:
541
+ query_states (`torch.Tensor`):
542
+ Input query states to be passed to Flash Attention API
543
+ key_states (`torch.Tensor`):
544
+ Input key states to be passed to Flash Attention API
545
+ value_states (`torch.Tensor`):
546
+ Input value states to be passed to Flash Attention API
547
+ attention_mask (`torch.Tensor`):
548
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
549
+ position of padding tokens and 1 for the position of non-padding tokens.
550
+ dropout (`int`, *optional*):
551
+ Attention dropout
552
+ softmax_scale (`float`, *optional*):
553
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
554
+ """
555
+ # Contains at least one padding token in the sequence
556
+ if attention_mask is not None:
557
+ batch_size = query_states.shape[0]
558
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
559
+ query_states, key_states, value_states, attention_mask, query_length
560
+ )
561
+
562
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
563
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
564
+
565
+ attn_output_unpad = flash_attn_varlen_func(
566
+ query_states,
567
+ key_states,
568
+ value_states,
569
+ cu_seqlens_q=cu_seqlens_q,
570
+ cu_seqlens_k=cu_seqlens_k,
571
+ max_seqlen_q=max_seqlen_in_batch_q,
572
+ max_seqlen_k=max_seqlen_in_batch_k,
573
+ dropout_p=dropout,
574
+ softmax_scale=softmax_scale,
575
+ causal=self.is_causal,
576
+ )
577
+
578
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
579
+ else:
580
+ attn_output = flash_attn_func(
581
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=self.is_causal
582
+ )
583
+
584
+ return attn_output
585
+
586
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
587
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
588
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
589
+
590
+ key_layer = index_first_axis(
591
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
592
+ )
593
+ value_layer = index_first_axis(
594
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
595
+ )
596
+ if query_length == kv_seq_len:
597
+ query_layer = index_first_axis(
598
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
599
+ )
600
+ cu_seqlens_q = cu_seqlens_k
601
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
602
+ indices_q = indices_k
603
+ elif query_length == 1:
604
+ max_seqlen_in_batch_q = 1
605
+ cu_seqlens_q = torch.arange(
606
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
607
+ ) # There is a memcpy here, that is very bad.
608
+ indices_q = cu_seqlens_q[:-1]
609
+ query_layer = query_layer.squeeze(1)
610
+ else:
611
+ # The -q_len: slice assumes left padding.
612
+ attention_mask = attention_mask[:, -query_length:]
613
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
614
+
615
+ return (
616
+ query_layer,
617
+ key_layer,
618
+ value_layer,
619
+ indices_q,
620
+ (cu_seqlens_q, cu_seqlens_k),
621
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
622
+ )
623
+
624
+
625
+ class LlamaDecoderLayer(nn.Module):
626
+ def __init__(self, config: LlamaConfig):
627
+ super().__init__()
628
+ self.hidden_size = config.hidden_size
629
+ self.self_attn = (
630
+ LlamaAttention(config=config)
631
+ if not getattr(config, "_flash_attn_2_enabled", False)
632
+ else LlamaFlashAttention2(config=config)
633
+ )
634
+ self.mlp = LlamaMLP(config)
635
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
636
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
637
+
638
+ def forward(
639
+ self,
640
+ hidden_states: torch.Tensor,
641
+ attention_mask: Optional[torch.Tensor] = None,
642
+ position_ids: Optional[torch.LongTensor] = None,
643
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
644
+ output_attentions: Optional[bool] = False,
645
+ use_cache: Optional[bool] = False,
646
+ **kwargs,
647
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
648
+ """
649
+ Args:
650
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
651
+ attention_mask (`torch.FloatTensor`, *optional*):
652
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
653
+ query_sequence_length, key_sequence_length)` if default attention is used.
654
+ output_attentions (`bool`, *optional*):
655
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
656
+ returned tensors for more detail.
657
+ use_cache (`bool`, *optional*):
658
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
659
+ (see `past_key_values`).
660
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
661
+ """
662
+ if "padding_mask" in kwargs:
663
+ warnings.warn(
664
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
665
+ )
666
+
667
+ residual = hidden_states
668
+
669
+ hidden_states = self.input_layernorm(hidden_states)
670
+
671
+ # Self Attention
672
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
673
+ hidden_states=hidden_states,
674
+ attention_mask=attention_mask,
675
+ position_ids=position_ids,
676
+ past_key_value=past_key_value,
677
+ output_attentions=output_attentions,
678
+ use_cache=use_cache,
679
+ **kwargs,
680
+ )
681
+ hidden_states = residual + hidden_states
682
+
683
+ # Fully Connected
684
+ residual = hidden_states
685
+ hidden_states = self.post_attention_layernorm(hidden_states)
686
+ hidden_states = self.mlp(hidden_states)
687
+ hidden_states = residual + hidden_states
688
+
689
+ outputs = (hidden_states,)
690
+
691
+ if output_attentions:
692
+ outputs += (self_attn_weights,)
693
+
694
+ if use_cache:
695
+ outputs += (present_key_value,)
696
+
697
+ return outputs
698
+
699
+
700
+ LLAMA_START_DOCSTRING = r"""
701
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
702
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
703
+ etc.)
704
+
705
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
706
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
707
+ and behavior.
708
+
709
+ Parameters:
710
+ config ([`LlamaConfig`]):
711
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
712
+ load the weights associated with the model, only the configuration. Check out the
713
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
714
+ """
715
+
716
+
717
+ @add_start_docstrings(
718
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
719
+ LLAMA_START_DOCSTRING,
720
+ )
721
+ class LlamaPreTrainedModel(PreTrainedModel):
722
+ config_class = LlamaConfig
723
+ base_model_prefix = "model"
724
+ supports_gradient_checkpointing = True
725
+ _no_split_modules = ["LlamaDecoderLayer"]
726
+ _skip_keys_device_placement = "past_key_values"
727
+ _supports_flash_attn_2 = True
728
+
729
+ def _init_weights(self, module):
730
+ std = self.config.initializer_range
731
+ if isinstance(module, nn.Linear):
732
+ module.weight.data.normal_(mean=0.0, std=std)
733
+ if module.bias is not None:
734
+ module.bias.data.zero_()
735
+ elif isinstance(module, nn.Embedding):
736
+ module.weight.data.normal_(mean=0.0, std=std)
737
+ if module.padding_idx is not None:
738
+ module.weight.data[module.padding_idx].zero_()
739
+
740
+
741
+ LLAMA_INPUTS_DOCSTRING = r"""
742
+ Args:
743
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
744
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
745
+ it.
746
+
747
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
748
+ [`PreTrainedTokenizer.__call__`] for details.
749
+
750
+ [What are input IDs?](../glossary#input-ids)
751
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
752
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
753
+
754
+ - 1 for tokens that are **not masked**,
755
+ - 0 for tokens that are **masked**.
756
+
757
+ [What are attention masks?](../glossary#attention-mask)
758
+
759
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
760
+ [`PreTrainedTokenizer.__call__`] for details.
761
+
762
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
763
+ `past_key_values`).
764
+
765
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
766
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
767
+ information on the default strategy.
768
+
769
+ - 1 indicates the head is **not masked**,
770
+ - 0 indicates the head is **masked**.
771
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
772
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
773
+ config.n_positions - 1]`.
774
+
775
+ [What are position IDs?](../glossary#position-ids)
776
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
777
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
778
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
779
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
780
+
781
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
782
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
783
+
784
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
785
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
786
+ of shape `(batch_size, sequence_length)`.
787
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
788
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
789
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
790
+ model's internal embedding lookup matrix.
791
+ use_cache (`bool`, *optional*):
792
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
793
+ `past_key_values`).
794
+ output_attentions (`bool`, *optional*):
795
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
796
+ tensors for more detail.
797
+ output_hidden_states (`bool`, *optional*):
798
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
799
+ more detail.
800
+ return_dict (`bool`, *optional*):
801
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
802
+ """
803
+
804
+
805
+ @add_start_docstrings(
806
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
807
+ LLAMA_START_DOCSTRING,
808
+ )
809
+ class LlamaModel(LlamaPreTrainedModel):
810
+ """
811
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
812
+
813
+ Args:
814
+ config: LlamaConfig
815
+ """
816
+
817
+ def __init__(self, config: LlamaConfig):
818
+ super().__init__(config)
819
+ self.padding_idx = config.pad_token_id
820
+ self.vocab_size = config.vocab_size
821
+
822
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
823
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
824
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
825
+
826
+ self.gradient_checkpointing = False
827
+ # Initialize weights and apply final processing
828
+ self.post_init()
829
+
830
+ def get_input_embeddings(self):
831
+ return self.embed_tokens
832
+
833
+ def set_input_embeddings(self, value):
834
+ self.embed_tokens = value
835
+
836
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
837
+ def forward(
838
+ self,
839
+ input_ids: torch.LongTensor = None,
840
+ attention_mask: Optional[torch.Tensor] = None,
841
+ position_ids: Optional[torch.LongTensor] = None,
842
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
843
+ inputs_embeds: Optional[torch.FloatTensor] = None,
844
+ use_cache: Optional[bool] = None,
845
+ output_attentions: Optional[bool] = None,
846
+ output_hidden_states: Optional[bool] = None,
847
+ return_dict: Optional[bool] = None,
848
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
849
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
850
+ output_hidden_states = (
851
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
852
+ )
853
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
854
+
855
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
856
+
857
+ # retrieve input_ids and inputs_embeds
858
+ if input_ids is not None and inputs_embeds is not None:
859
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
860
+ elif input_ids is not None:
861
+ batch_size, seq_length = input_ids.shape[:2]
862
+ elif inputs_embeds is not None:
863
+ batch_size, seq_length = inputs_embeds.shape[:2]
864
+ else:
865
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
866
+
867
+ past_key_values_length = 0
868
+ if past_key_values is not None:
869
+ past_key_values_length = past_key_values[0][0].shape[2]
870
+
871
+ if position_ids is None:
872
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
873
+ position_ids = torch.arange(
874
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
875
+ )
876
+ position_ids = position_ids.unsqueeze(0)
877
+
878
+ if inputs_embeds is None:
879
+ inputs_embeds = self.embed_tokens(input_ids)
880
+
881
+ if getattr(self.config, "_flash_attn_2_enabled", False):
882
+ # 2d mask is passed through the layers
883
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
884
+ else:
885
+ # 4d mask is passed through the layers
886
+ attention_mask = _prepare_4d_causal_attention_mask(
887
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
888
+ )
889
+
890
+ # embed positions
891
+ hidden_states = inputs_embeds
892
+
893
+ if self.gradient_checkpointing and self.training:
894
+ if use_cache:
895
+ logger.warning_once(
896
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
897
+ )
898
+ use_cache = False
899
+
900
+ # decoder layers
901
+ all_hidden_states = () if output_hidden_states else None
902
+ all_self_attns = () if output_attentions else None
903
+ next_decoder_cache = () if use_cache else None
904
+
905
+ for idx, decoder_layer in enumerate(self.layers):
906
+ if output_hidden_states:
907
+ all_hidden_states += (hidden_states,)
908
+
909
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
910
+
911
+ if self.gradient_checkpointing and self.training:
912
+ layer_outputs = self._gradient_checkpointing_func(
913
+ decoder_layer.__call__,
914
+ hidden_states,
915
+ attention_mask,
916
+ position_ids,
917
+ past_key_value,
918
+ output_attentions,
919
+ use_cache,
920
+ )
921
+ else:
922
+ layer_outputs = decoder_layer(
923
+ hidden_states,
924
+ attention_mask=attention_mask,
925
+ position_ids=position_ids,
926
+ past_key_value=past_key_value,
927
+ output_attentions=output_attentions,
928
+ use_cache=use_cache,
929
+ )
930
+
931
+ hidden_states = layer_outputs[0]
932
+
933
+ if use_cache:
934
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
935
+
936
+ if output_attentions:
937
+ all_self_attns += (layer_outputs[1],)
938
+
939
+ hidden_states = self.norm(hidden_states)
940
+
941
+ # add hidden states from the last decoder layer
942
+ if output_hidden_states:
943
+ all_hidden_states += (hidden_states,)
944
+
945
+ next_cache = next_decoder_cache if use_cache else None
946
+ if not return_dict:
947
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
948
+ return BaseModelOutputWithPast(
949
+ last_hidden_state=hidden_states,
950
+ past_key_values=next_cache,
951
+ hidden_states=all_hidden_states,
952
+ attentions=all_self_attns,
953
+ )
954
+
955
+
956
+ class LlamaForCausalLM(LlamaPreTrainedModel):
957
+ _tied_weights_keys = ["lm_head.weight"]
958
+
959
+ def __init__(self, config):
960
+ super().__init__(config)
961
+ self.model = LlamaModel(config)
962
+ self.vocab_size = config.vocab_size
963
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
964
+
965
+ # Initialize weights and apply final processing
966
+ self.post_init()
967
+
968
+ def get_input_embeddings(self):
969
+ return self.model.embed_tokens
970
+
971
+ def set_input_embeddings(self, value):
972
+ self.model.embed_tokens = value
973
+
974
+ def get_output_embeddings(self):
975
+ return self.lm_head
976
+
977
+ def set_output_embeddings(self, new_embeddings):
978
+ self.lm_head = new_embeddings
979
+
980
+ def set_decoder(self, decoder):
981
+ self.model = decoder
982
+
983
+ def get_decoder(self):
984
+ return self.model
985
+
986
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
987
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
988
+ def forward(
989
+ self,
990
+ input_ids: torch.LongTensor = None,
991
+ attention_mask: Optional[torch.Tensor] = None,
992
+ position_ids: Optional[torch.LongTensor] = None,
993
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
994
+ inputs_embeds: Optional[torch.FloatTensor] = None,
995
+ labels: Optional[torch.LongTensor] = None,
996
+ use_cache: Optional[bool] = None,
997
+ output_attentions: Optional[bool] = None,
998
+ output_hidden_states: Optional[bool] = None,
999
+ return_dict: Optional[bool] = None,
1000
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1001
+ r"""
1002
+ Args:
1003
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1004
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1005
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1006
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1007
+
1008
+ Returns:
1009
+
1010
+ Example:
1011
+
1012
+ ```python
1013
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1014
+
1015
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1016
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1017
+
1018
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1019
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1020
+
1021
+ >>> # Generate
1022
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1023
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1024
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1025
+ ```"""
1026
+
1027
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1028
+ output_hidden_states = (
1029
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1030
+ )
1031
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1032
+
1033
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1034
+ outputs = self.model(
1035
+ input_ids=input_ids,
1036
+ attention_mask=attention_mask,
1037
+ position_ids=position_ids,
1038
+ past_key_values=past_key_values,
1039
+ inputs_embeds=inputs_embeds,
1040
+ use_cache=use_cache,
1041
+ output_attentions=output_attentions,
1042
+ output_hidden_states=output_hidden_states,
1043
+ return_dict=return_dict,
1044
+ )
1045
+
1046
+ hidden_states = outputs[0]
1047
+ if self.config.pretraining_tp > 1:
1048
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1049
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1050
+ logits = torch.cat(logits, dim=-1)
1051
+ else:
1052
+ logits = self.lm_head(hidden_states)
1053
+ logits = logits.float()
1054
+
1055
+ loss = None
1056
+ if labels is not None:
1057
+ # Shift so that tokens < n predict n
1058
+ shift_logits = logits[..., :-1, :].contiguous()
1059
+ shift_labels = labels[..., 1:].contiguous()
1060
+ # Flatten the tokens
1061
+ loss_fct = CrossEntropyLoss()
1062
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1063
+ shift_labels = shift_labels.view(-1)
1064
+ # Enable model parallelism
1065
+ shift_labels = shift_labels.to(shift_logits.device)
1066
+ loss = loss_fct(shift_logits, shift_labels)
1067
+
1068
+ if not return_dict:
1069
+ output = (logits,) + outputs[1:]
1070
+ return (loss,) + output if loss is not None else output
1071
+
1072
+ return CausalLMOutputWithPast(
1073
+ loss=loss,
1074
+ logits=logits,
1075
+ past_key_values=outputs.past_key_values,
1076
+ hidden_states=outputs.hidden_states,
1077
+ attentions=outputs.attentions,
1078
+ )
1079
+
1080
+ def prepare_inputs_for_generation(
1081
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1082
+ ):
1083
+ if past_key_values is not None:
1084
+ past_length = past_key_values[0][0].shape[2]
1085
+
1086
+ # Some generation methods already pass only the last input ID
1087
+ if input_ids.shape[1] > past_length:
1088
+ remove_prefix_length = past_length
1089
+ else:
1090
+ # Default to old behavior: keep only final ID
1091
+ remove_prefix_length = input_ids.shape[1] - 1
1092
+
1093
+ input_ids = input_ids[:, remove_prefix_length:]
1094
+
1095
+ position_ids = kwargs.get("position_ids", None)
1096
+ if attention_mask is not None and position_ids is None:
1097
+ # create position_ids on the fly for batch generation
1098
+ position_ids = attention_mask.long().cumsum(-1) - 1
1099
+ position_ids.masked_fill_(attention_mask == 0, 1)
1100
+ if past_key_values:
1101
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1102
+
1103
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1104
+ if inputs_embeds is not None and past_key_values is None:
1105
+ model_inputs = {"inputs_embeds": inputs_embeds}
1106
+ else:
1107
+ model_inputs = {"input_ids": input_ids}
1108
+
1109
+ model_inputs.update(
1110
+ {
1111
+ "position_ids": position_ids,
1112
+ "past_key_values": past_key_values,
1113
+ "use_cache": kwargs.get("use_cache"),
1114
+ "attention_mask": attention_mask,
1115
+ }
1116
+ )
1117
+ return model_inputs
1118
+
1119
+ @staticmethod
1120
+ def _reorder_cache(past_key_values, beam_idx):
1121
+ reordered_past = ()
1122
+ for layer_past in past_key_values:
1123
+ reordered_past += (
1124
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1125
+ )
1126
+ return reordered_past
1127
+
1128
+
1129
+ @add_start_docstrings(
1130
+ """
1131
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1132
+
1133
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1134
+ (e.g. GPT-2) do.
1135
+
1136
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1137
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1138
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1139
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1140
+ each row of the batch).
1141
+ """,
1142
+ LLAMA_START_DOCSTRING,
1143
+ )
1144
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1145
+ def __init__(self, config):
1146
+ super().__init__(config)
1147
+ self.num_labels = config.num_labels
1148
+ self.model = LlamaModel(config)
1149
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1150
+
1151
+ # Initialize weights and apply final processing
1152
+ self.post_init()
1153
+
1154
+ def get_input_embeddings(self):
1155
+ return self.model.embed_tokens
1156
+
1157
+ def set_input_embeddings(self, value):
1158
+ self.model.embed_tokens = value
1159
+
1160
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1161
+ def forward(
1162
+ self,
1163
+ input_ids: torch.LongTensor = None,
1164
+ attention_mask: Optional[torch.Tensor] = None,
1165
+ position_ids: Optional[torch.LongTensor] = None,
1166
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1167
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1168
+ labels: Optional[torch.LongTensor] = None,
1169
+ use_cache: Optional[bool] = None,
1170
+ output_attentions: Optional[bool] = None,
1171
+ output_hidden_states: Optional[bool] = None,
1172
+ return_dict: Optional[bool] = None,
1173
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1174
+ r"""
1175
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1176
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1177
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1178
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1179
+ """
1180
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1181
+
1182
+ transformer_outputs = self.model(
1183
+ input_ids,
1184
+ attention_mask=attention_mask,
1185
+ position_ids=position_ids,
1186
+ past_key_values=past_key_values,
1187
+ inputs_embeds=inputs_embeds,
1188
+ use_cache=use_cache,
1189
+ output_attentions=output_attentions,
1190
+ output_hidden_states=output_hidden_states,
1191
+ return_dict=return_dict,
1192
+ )
1193
+ hidden_states = transformer_outputs[0]
1194
+ logits = self.score(hidden_states)
1195
+
1196
+ if input_ids is not None:
1197
+ batch_size = input_ids.shape[0]
1198
+ else:
1199
+ batch_size = inputs_embeds.shape[0]
1200
+
1201
+ if self.config.pad_token_id is None and batch_size != 1:
1202
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1203
+ if self.config.pad_token_id is None:
1204
+ sequence_lengths = -1
1205
+ else:
1206
+ if input_ids is not None:
1207
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
1208
+ logits.device
1209
+ )
1210
+ else:
1211
+ sequence_lengths = -1
1212
+
1213
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1214
+
1215
+ loss = None
1216
+ if labels is not None:
1217
+ labels = labels.to(logits.device)
1218
+ if self.config.problem_type is None:
1219
+ if self.num_labels == 1:
1220
+ self.config.problem_type = "regression"
1221
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1222
+ self.config.problem_type = "single_label_classification"
1223
+ else:
1224
+ self.config.problem_type = "multi_label_classification"
1225
+
1226
+ if self.config.problem_type == "regression":
1227
+ loss_fct = MSELoss()
1228
+ if self.num_labels == 1:
1229
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1230
+ else:
1231
+ loss = loss_fct(pooled_logits, labels)
1232
+ elif self.config.problem_type == "single_label_classification":
1233
+ loss_fct = CrossEntropyLoss()
1234
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1235
+ elif self.config.problem_type == "multi_label_classification":
1236
+ loss_fct = BCEWithLogitsLoss()
1237
+ loss = loss_fct(pooled_logits, labels)
1238
+ if not return_dict:
1239
+ output = (pooled_logits,) + transformer_outputs[1:]
1240
+ return ((loss,) + output) if loss is not None else output
1241
+
1242
+ return SequenceClassifierOutputWithPast(
1243
+ loss=loss,
1244
+ logits=pooled_logits,
1245
+ past_key_values=transformer_outputs.past_key_values,
1246
+ hidden_states=transformer_outputs.hidden_states,
1247
+ attentions=transformer_outputs.attentions,
1248
+ )
version_check.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import transformers
2
+ from packaging import version
3
+
4
+ MIN_VERSION = "4.35.2"
5
+
6
+
7
+ def check_transformers_version():
8
+ if version.parse(transformers.__version__) < version.parse(MIN_VERSION):
9
+ raise ImportError(
10
+ f"You are using transformers=={transformers.__version__}, but transformers>={MIN_VERSION} is required to use DeciLM. Please upgrade transformers."
11
+ )