katuni4ka commited on
Commit
0ce49e2
1 Parent(s): b6d32a6

Upload 13 files

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