if001 commited on
Commit
5f37b27
·
1 Parent(s): af8ecf3

add mergoo script

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