zwt123home123 commited on
Commit
8aa0dc9
·
verified ·
1 Parent(s): 8ad2fbf

Upload 2 files

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