doberst commited on
Commit
4f057be
1 Parent(s): e07524a

Upload 11 files

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