if001 commited on
Commit
8c9839b
1 Parent(s): d64de30

Create modeling_llama.py

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