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