zwt123home123 commited on
Commit
7884b18
·
verified ·
1 Parent(s): 8536b33

Upload folder using huggingface_hub

Browse files
Files changed (41) hide show
  1. modeling_llama.py +1451 -0
  2. weights_480/autoencoder_epoch_1_L1_nonorm_layer_0.pth +3 -0
  3. weights_480/autoencoder_epoch_1_L1_nonorm_layer_1.pth +3 -0
  4. weights_480/autoencoder_epoch_1_L1_nonorm_layer_10.pth +3 -0
  5. weights_480/autoencoder_epoch_1_L1_nonorm_layer_11.pth +3 -0
  6. weights_480/autoencoder_epoch_1_L1_nonorm_layer_12.pth +3 -0
  7. weights_480/autoencoder_epoch_1_L1_nonorm_layer_13.pth +3 -0
  8. weights_480/autoencoder_epoch_1_L1_nonorm_layer_14.pth +3 -0
  9. weights_480/autoencoder_epoch_1_L1_nonorm_layer_15.pth +3 -0
  10. weights_480/autoencoder_epoch_1_L1_nonorm_layer_16.pth +3 -0
  11. weights_480/autoencoder_epoch_1_L1_nonorm_layer_17.pth +3 -0
  12. weights_480/autoencoder_epoch_1_L1_nonorm_layer_18.pth +3 -0
  13. weights_480/autoencoder_epoch_1_L1_nonorm_layer_19.pth +3 -0
  14. weights_480/autoencoder_epoch_1_L1_nonorm_layer_2.pth +3 -0
  15. weights_480/autoencoder_epoch_1_L1_nonorm_layer_20.pth +3 -0
  16. weights_480/autoencoder_epoch_1_L1_nonorm_layer_21.pth +3 -0
  17. weights_480/autoencoder_epoch_1_L1_nonorm_layer_22.pth +3 -0
  18. weights_480/autoencoder_epoch_1_L1_nonorm_layer_23.pth +3 -0
  19. weights_480/autoencoder_epoch_1_L1_nonorm_layer_24.pth +3 -0
  20. weights_480/autoencoder_epoch_1_L1_nonorm_layer_25.pth +3 -0
  21. weights_480/autoencoder_epoch_1_L1_nonorm_layer_26.pth +3 -0
  22. weights_480/autoencoder_epoch_1_L1_nonorm_layer_27.pth +3 -0
  23. weights_480/autoencoder_epoch_1_L1_nonorm_layer_28.pth +3 -0
  24. weights_480/autoencoder_epoch_1_L1_nonorm_layer_29.pth +3 -0
  25. weights_480/autoencoder_epoch_1_L1_nonorm_layer_3.pth +3 -0
  26. weights_480/autoencoder_epoch_1_L1_nonorm_layer_30.pth +3 -0
  27. weights_480/autoencoder_epoch_1_L1_nonorm_layer_31.pth +3 -0
  28. weights_480/autoencoder_epoch_1_L1_nonorm_layer_32.pth +3 -0
  29. weights_480/autoencoder_epoch_1_L1_nonorm_layer_33.pth +3 -0
  30. weights_480/autoencoder_epoch_1_L1_nonorm_layer_34.pth +3 -0
  31. weights_480/autoencoder_epoch_1_L1_nonorm_layer_35.pth +3 -0
  32. weights_480/autoencoder_epoch_1_L1_nonorm_layer_36.pth +3 -0
  33. weights_480/autoencoder_epoch_1_L1_nonorm_layer_37.pth +3 -0
  34. weights_480/autoencoder_epoch_1_L1_nonorm_layer_38.pth +3 -0
  35. weights_480/autoencoder_epoch_1_L1_nonorm_layer_39.pth +3 -0
  36. weights_480/autoencoder_epoch_1_L1_nonorm_layer_4.pth +3 -0
  37. weights_480/autoencoder_epoch_1_L1_nonorm_layer_5.pth +3 -0
  38. weights_480/autoencoder_epoch_1_L1_nonorm_layer_6.pth +3 -0
  39. weights_480/autoencoder_epoch_1_L1_nonorm_layer_7.pth +3 -0
  40. weights_480/autoencoder_epoch_1_L1_nonorm_layer_8.pth +3 -0
  41. weights_480/autoencoder_epoch_1_L1_nonorm_layer_9.pth +3 -0
modeling_llama.py ADDED
@@ -0,0 +1,1451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 480
341
+ self.ae_v = AutoEncoder(input_dim, hidden_dim)#.cuda()
342
+
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
+ kv_seq_len = key_states.shape[-2]
419
+ if past_key_value is not None:
420
+ if self.layer_idx is None:
421
+ raise ValueError(
422
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
423
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
424
+ "with a layer index."
425
+ )
426
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
427
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
428
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
429
+
430
+ if past_key_value is not None:
431
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
432
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
433
+
434
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
435
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
436
+
437
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
438
+
439
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
440
+ raise ValueError(
441
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
442
+ f" {attn_weights.size()}"
443
+ )
444
+
445
+ if attention_mask is not None:
446
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
447
+ raise ValueError(
448
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
449
+ )
450
+ attn_weights = attn_weights + attention_mask
451
+
452
+ # upcast attention to fp32
453
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
454
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
455
+
456
+ # import pdb; pdb.set_trace()
457
+ if attn_weights.shape[2]>576:
458
+ # print("loading ... ")
459
+ #print(value_states.shape)
460
+ self.ae_v.load_state_dict(torch.load("weights_480/"+"autoencoder_epoch_1_L1_1280_nonorm_layer_"+str(self.layer_idx)+".pth", map_location='cuda'))
461
+ value_states_v = value_states[:,:,35:35+576,:]
462
+ value_states_v = value_states_v.permute(0, 2, 1, 3)
463
+ value_states_v=value_states_v.reshape(value_states_v.shape[0],value_states_v.shape[1],5120)
464
+ # import pdb; pdb.set_trace()
465
+ value_states_v = self.ae_v(value_states_v)
466
+ value_states_v = value_states_v.reshape(value_states_v.shape[0],value_states_v.shape[1], 40, 128)
467
+ value_states_v = value_states_v.permute(0, 2, 1, 3)
468
+ value_states[:,:,35:35+576,:] = value_states_v
469
+
470
+ attn_output = torch.matmul(attn_weights, value_states)
471
+
472
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
473
+ raise ValueError(
474
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
475
+ f" {attn_output.size()}"
476
+ )
477
+
478
+ attn_output = attn_output.transpose(1, 2).contiguous()
479
+
480
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
481
+
482
+ if self.config.pretraining_tp > 1:
483
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
484
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
485
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
486
+ else:
487
+ attn_output = self.o_proj(attn_output)
488
+
489
+ if not output_attentions:
490
+ attn_weights = None
491
+
492
+ return attn_output, attn_weights, past_key_value
493
+
494
+
495
+ class LlamaFlashAttention2(LlamaAttention):
496
+ """
497
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
498
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
499
+ flash attention and deal with padding tokens in case the input contains any of them.
500
+ """
501
+
502
+ def __init__(self, *args, **kwargs):
503
+ super().__init__(*args, **kwargs)
504
+
505
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
506
+ # 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.
507
+ # 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).
508
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
509
+
510
+ def forward(
511
+ self,
512
+ hidden_states: torch.Tensor,
513
+ attention_mask: Optional[torch.LongTensor] = None,
514
+ position_ids: Optional[torch.LongTensor] = None,
515
+ past_key_value: Optional[Cache] = None,
516
+ output_attentions: bool = False,
517
+ use_cache: bool = False,
518
+ **kwargs,
519
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
520
+ # LlamaFlashAttention2 attention does not support output_attentions
521
+ if "padding_mask" in kwargs:
522
+ warnings.warn(
523
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
524
+ )
525
+
526
+ # overwrite attention_mask with padding_mask
527
+ attention_mask = kwargs.pop("padding_mask")
528
+
529
+ output_attentions = False
530
+
531
+ bsz, q_len, _ = hidden_states.size()
532
+
533
+ query_states = self.q_proj(hidden_states)
534
+ key_states = self.k_proj(hidden_states)
535
+ value_states = self.v_proj(hidden_states)
536
+
537
+ # Flash attention requires the input to have the shape
538
+ # batch_size x seq_length x head_dim x hidden_dim
539
+ # therefore we just need to keep the original shape
540
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
541
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
542
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
543
+
544
+ kv_seq_len = key_states.shape[-2]
545
+ if past_key_value is not None:
546
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
547
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
548
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
549
+
550
+ if past_key_value is not None:
551
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
552
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
553
+
554
+ # 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
555
+ # to be able to avoid many of these transpose/reshape/view.
556
+ query_states = query_states.transpose(1, 2)
557
+ key_states = key_states.transpose(1, 2)
558
+ value_states = value_states.transpose(1, 2)
559
+
560
+ dropout_rate = self.attention_dropout if self.training else 0.0
561
+
562
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
563
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
564
+ # cast them back in the correct dtype just to be sure everything works as expected.
565
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
566
+ # in fp32. (LlamaRMSNorm handles it correctly)
567
+
568
+ input_dtype = query_states.dtype
569
+ if input_dtype == torch.float32:
570
+ # Handle the case where the model is quantized
571
+ if hasattr(self.config, "_pre_quantization_dtype"):
572
+ target_dtype = self.config._pre_quantization_dtype
573
+ else:
574
+ target_dtype = self.q_proj.weight.dtype
575
+
576
+ logger.warning_once(
577
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
578
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
579
+ f" {target_dtype}."
580
+ )
581
+
582
+ query_states = query_states.to(target_dtype)
583
+ key_states = key_states.to(target_dtype)
584
+ value_states = value_states.to(target_dtype)
585
+
586
+ attn_output = self._flash_attention_forward(
587
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
588
+ )
589
+
590
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
591
+ attn_output = self.o_proj(attn_output)
592
+
593
+ if not output_attentions:
594
+ attn_weights = None
595
+
596
+ return attn_output, attn_weights, past_key_value
597
+
598
+ def _flash_attention_forward(
599
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
600
+ ):
601
+ """
602
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
603
+ first unpad the input, then computes the attention scores and pad the final attention scores.
604
+
605
+ Args:
606
+ query_states (`torch.Tensor`):
607
+ Input query states to be passed to Flash Attention API
608
+ key_states (`torch.Tensor`):
609
+ Input key states to be passed to Flash Attention API
610
+ value_states (`torch.Tensor`):
611
+ Input value states to be passed to Flash Attention API
612
+ attention_mask (`torch.Tensor`):
613
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
614
+ position of padding tokens and 1 for the position of non-padding tokens.
615
+ dropout (`int`, *optional*):
616
+ Attention dropout
617
+ softmax_scale (`float`, *optional*):
618
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
619
+ """
620
+ if not self._flash_attn_uses_top_left_mask:
621
+ causal = self.is_causal
622
+ else:
623
+ # 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__.
624
+ causal = self.is_causal and query_length != 1
625
+
626
+ # Contains at least one padding token in the sequence
627
+ if attention_mask is not None:
628
+ batch_size = query_states.shape[0]
629
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
630
+ query_states, key_states, value_states, attention_mask, query_length
631
+ )
632
+
633
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
634
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
635
+
636
+ attn_output_unpad = flash_attn_varlen_func(
637
+ query_states,
638
+ key_states,
639
+ value_states,
640
+ cu_seqlens_q=cu_seqlens_q,
641
+ cu_seqlens_k=cu_seqlens_k,
642
+ max_seqlen_q=max_seqlen_in_batch_q,
643
+ max_seqlen_k=max_seqlen_in_batch_k,
644
+ dropout_p=dropout,
645
+ softmax_scale=softmax_scale,
646
+ causal=causal,
647
+ )
648
+
649
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
650
+ else:
651
+ attn_output = flash_attn_func(
652
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
653
+ )
654
+
655
+ return attn_output
656
+
657
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
658
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
659
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
660
+
661
+ key_layer = index_first_axis(
662
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
663
+ )
664
+ value_layer = index_first_axis(
665
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
666
+ )
667
+ if query_length == kv_seq_len:
668
+ query_layer = index_first_axis(
669
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
670
+ )
671
+ cu_seqlens_q = cu_seqlens_k
672
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
673
+ indices_q = indices_k
674
+ elif query_length == 1:
675
+ max_seqlen_in_batch_q = 1
676
+ cu_seqlens_q = torch.arange(
677
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
678
+ ) # There is a memcpy here, that is very bad.
679
+ indices_q = cu_seqlens_q[:-1]
680
+ query_layer = query_layer.squeeze(1)
681
+ else:
682
+ # The -q_len: slice assumes left padding.
683
+ attention_mask = attention_mask[:, -query_length:]
684
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
685
+
686
+ return (
687
+ query_layer,
688
+ key_layer,
689
+ value_layer,
690
+ indices_q,
691
+ (cu_seqlens_q, cu_seqlens_k),
692
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
693
+ )
694
+
695
+
696
+ class LlamaSdpaAttention(LlamaAttention):
697
+ """
698
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
699
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
700
+ SDPA API.
701
+ """
702
+
703
+ # Adapted from LlamaAttention.forward
704
+ def forward(
705
+ self,
706
+ hidden_states: torch.Tensor,
707
+ attention_mask: Optional[torch.Tensor] = None,
708
+ position_ids: Optional[torch.LongTensor] = None,
709
+ past_key_value: Optional[Cache] = None,
710
+ output_attentions: bool = False,
711
+ use_cache: bool = False,
712
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
713
+ if output_attentions:
714
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
715
+ logger.warning_once(
716
+ "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, "
717
+ '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.'
718
+ )
719
+ return super().forward(
720
+ hidden_states=hidden_states,
721
+ attention_mask=attention_mask,
722
+ position_ids=position_ids,
723
+ past_key_value=past_key_value,
724
+ output_attentions=output_attentions,
725
+ use_cache=use_cache,
726
+ )
727
+
728
+ bsz, q_len, _ = hidden_states.size()
729
+
730
+ query_states = self.q_proj(hidden_states)
731
+ key_states = self.k_proj(hidden_states)
732
+ value_states = self.v_proj(hidden_states)
733
+
734
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
735
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
736
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
737
+
738
+ kv_seq_len = key_states.shape[-2]
739
+ if past_key_value is not None:
740
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
741
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
742
+
743
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
744
+
745
+ if past_key_value is not None:
746
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
747
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
748
+
749
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
750
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
751
+
752
+ if attention_mask is not None:
753
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
754
+ raise ValueError(
755
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
756
+ )
757
+
758
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
759
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
760
+ if query_states.device.type == "cuda" and attention_mask is not None:
761
+ query_states = query_states.contiguous()
762
+ key_states = key_states.contiguous()
763
+ value_states = value_states.contiguous()
764
+
765
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
766
+ query_states,
767
+ key_states,
768
+ value_states,
769
+ attn_mask=attention_mask,
770
+ dropout_p=self.attention_dropout if self.training else 0.0,
771
+ # 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.
772
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
773
+ )
774
+
775
+ attn_output = attn_output.transpose(1, 2).contiguous()
776
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
777
+
778
+ attn_output = self.o_proj(attn_output)
779
+
780
+ return attn_output, None, past_key_value
781
+
782
+
783
+ LLAMA_ATTENTION_CLASSES = {
784
+ "eager": LlamaAttention,
785
+ "flash_attention_2": LlamaFlashAttention2,
786
+ "sdpa": LlamaSdpaAttention,
787
+ }
788
+
789
+
790
+ class LlamaDecoderLayer(nn.Module):
791
+ def __init__(self, config: LlamaConfig, layer_idx: int):
792
+ super().__init__()
793
+ self.hidden_size = config.hidden_size
794
+ config._attn_implementation="eager"
795
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
796
+
797
+ self.mlp = LlamaMLP(config)
798
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
799
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
800
+
801
+ def forward(
802
+ self,
803
+ hidden_states: torch.Tensor,
804
+ attention_mask: Optional[torch.Tensor] = None,
805
+ position_ids: Optional[torch.LongTensor] = None,
806
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
807
+ output_attentions: Optional[bool] = False,
808
+ use_cache: Optional[bool] = False,
809
+ **kwargs,
810
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
811
+ """
812
+ Args:
813
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
814
+ attention_mask (`torch.FloatTensor`, *optional*):
815
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
816
+ query_sequence_length, key_sequence_length)` if default attention is used.
817
+ output_attentions (`bool`, *optional*):
818
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
819
+ returned tensors for more detail.
820
+ use_cache (`bool`, *optional*):
821
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
822
+ (see `past_key_values`).
823
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
824
+ """
825
+ if "padding_mask" in kwargs:
826
+ warnings.warn(
827
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
828
+ )
829
+
830
+ residual = hidden_states
831
+
832
+ hidden_states = self.input_layernorm(hidden_states)
833
+
834
+ # Self Attention
835
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
836
+ hidden_states=hidden_states,
837
+ attention_mask=attention_mask,
838
+ position_ids=position_ids,
839
+ past_key_value=past_key_value,
840
+ output_attentions=output_attentions,
841
+ use_cache=use_cache,
842
+ **kwargs,
843
+ )
844
+ hidden_states = residual + hidden_states
845
+
846
+ # Fully Connected
847
+ residual = hidden_states
848
+ hidden_states = self.post_attention_layernorm(hidden_states)
849
+ hidden_states = self.mlp(hidden_states)
850
+ hidden_states = residual + hidden_states
851
+
852
+ outputs = (hidden_states,)
853
+
854
+ if output_attentions:
855
+ outputs += (self_attn_weights,)
856
+
857
+ if use_cache:
858
+ outputs += (present_key_value,)
859
+
860
+ return outputs
861
+
862
+
863
+ LLAMA_START_DOCSTRING = r"""
864
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
865
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
866
+ etc.)
867
+
868
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
869
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
870
+ and behavior.
871
+
872
+ Parameters:
873
+ config ([`LlamaConfig`]):
874
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
875
+ load the weights associated with the model, only the configuration. Check out the
876
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
877
+ """
878
+
879
+
880
+ @add_start_docstrings(
881
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
882
+ LLAMA_START_DOCSTRING,
883
+ )
884
+ class LlamaPreTrainedModel(PreTrainedModel):
885
+ config_class = LlamaConfig
886
+ base_model_prefix = "model"
887
+ supports_gradient_checkpointing = True
888
+ _no_split_modules = ["LlamaDecoderLayer"]
889
+ _skip_keys_device_placement = "past_key_values"
890
+ _supports_flash_attn_2 = True
891
+ _supports_sdpa = True
892
+ _supports_cache_class = True
893
+
894
+ def _init_weights(self, module):
895
+ std = self.config.initializer_range
896
+ if isinstance(module, nn.Linear):
897
+ module.weight.data.normal_(mean=0.0, std=std)
898
+ if module.bias is not None:
899
+ module.bias.data.zero_()
900
+ elif isinstance(module, nn.Embedding):
901
+ module.weight.data.normal_(mean=0.0, std=std)
902
+ if module.padding_idx is not None:
903
+ module.weight.data[module.padding_idx].zero_()
904
+
905
+
906
+ LLAMA_INPUTS_DOCSTRING = r"""
907
+ Args:
908
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
909
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
910
+ it.
911
+
912
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
913
+ [`PreTrainedTokenizer.__call__`] for details.
914
+
915
+ [What are input IDs?](../glossary#input-ids)
916
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
917
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
918
+
919
+ - 1 for tokens that are **not masked**,
920
+ - 0 for tokens that are **masked**.
921
+
922
+ [What are attention masks?](../glossary#attention-mask)
923
+
924
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
925
+ [`PreTrainedTokenizer.__call__`] for details.
926
+
927
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
928
+ `past_key_values`).
929
+
930
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
931
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
932
+ information on the default strategy.
933
+
934
+ - 1 indicates the head is **not masked**,
935
+ - 0 indicates the head is **masked**.
936
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
937
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
938
+ config.n_positions - 1]`.
939
+
940
+ [What are position IDs?](../glossary#position-ids)
941
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
942
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
943
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
944
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
945
+
946
+ Two formats are allowed:
947
+ - a [`~cache_utils.Cache`] instance;
948
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
949
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
950
+ cache format.
951
+
952
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
953
+ legacy cache format will be returned.
954
+
955
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
956
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
957
+ of shape `(batch_size, sequence_length)`.
958
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
959
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
960
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
961
+ model's internal embedding lookup matrix.
962
+ use_cache (`bool`, *optional*):
963
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
964
+ `past_key_values`).
965
+ output_attentions (`bool`, *optional*):
966
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
967
+ tensors for more detail.
968
+ output_hidden_states (`bool`, *optional*):
969
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
970
+ more detail.
971
+ return_dict (`bool`, *optional*):
972
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
973
+ """
974
+
975
+
976
+ @add_start_docstrings(
977
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
978
+ LLAMA_START_DOCSTRING,
979
+ )
980
+ class LlamaModel(LlamaPreTrainedModel):
981
+ """
982
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
983
+
984
+ Args:
985
+ config: LlamaConfig
986
+ """
987
+
988
+ def __init__(self, config: LlamaConfig):
989
+ super().__init__(config)
990
+ self.padding_idx = config.pad_token_id
991
+ self.vocab_size = config.vocab_size
992
+
993
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
994
+ self.layers = nn.ModuleList(
995
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
996
+ )
997
+ self._use_sdpa = config._attn_implementation == "sdpa"
998
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
999
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1000
+
1001
+ self.gradient_checkpointing = False
1002
+ # Initialize weights and apply final processing
1003
+ self.post_init()
1004
+
1005
+ def get_input_embeddings(self):
1006
+ return self.embed_tokens
1007
+
1008
+ def set_input_embeddings(self, value):
1009
+ self.embed_tokens = value
1010
+
1011
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1012
+ def forward(
1013
+ self,
1014
+ input_ids: torch.LongTensor = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ use_cache: Optional[bool] = None,
1020
+ output_attentions: Optional[bool] = None,
1021
+ output_hidden_states: Optional[bool] = None,
1022
+ return_dict: Optional[bool] = None,
1023
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1024
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1025
+ output_hidden_states = (
1026
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1027
+ )
1028
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1029
+
1030
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1031
+
1032
+ # retrieve input_ids and inputs_embeds
1033
+ if input_ids is not None and inputs_embeds is not None:
1034
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1035
+ elif input_ids is not None:
1036
+ batch_size, seq_length = input_ids.shape[:2]
1037
+ elif inputs_embeds is not None:
1038
+ batch_size, seq_length = inputs_embeds.shape[:2]
1039
+ else:
1040
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1041
+
1042
+ if self.gradient_checkpointing and self.training:
1043
+ if use_cache:
1044
+ logger.warning_once(
1045
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1046
+ )
1047
+ use_cache = False
1048
+
1049
+ past_key_values_length = 0
1050
+ if use_cache:
1051
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1052
+ if use_legacy_cache:
1053
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1054
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1055
+
1056
+ if position_ids is None:
1057
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1058
+ position_ids = torch.arange(
1059
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1060
+ )
1061
+ position_ids = position_ids.unsqueeze(0)
1062
+
1063
+ if inputs_embeds is None:
1064
+ inputs_embeds = self.embed_tokens(input_ids)
1065
+
1066
+ if self._use_flash_attention_2:
1067
+ # 2d mask is passed through the layers
1068
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1069
+ elif self._use_sdpa and not output_attentions:
1070
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1071
+ # the manual implementation that requires a 4D causal mask in all cases.
1072
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1073
+ attention_mask,
1074
+ (batch_size, seq_length),
1075
+ inputs_embeds,
1076
+ past_key_values_length,
1077
+ )
1078
+ else:
1079
+ # 4d mask is passed through the layers
1080
+ attention_mask = _prepare_4d_causal_attention_mask(
1081
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1082
+ )
1083
+
1084
+ # embed positions
1085
+ hidden_states = inputs_embeds
1086
+
1087
+ # decoder layers
1088
+ all_hidden_states = () if output_hidden_states else None
1089
+ all_self_attns = () if output_attentions else None
1090
+ next_decoder_cache = None
1091
+
1092
+ for decoder_layer in self.layers:
1093
+ if output_hidden_states:
1094
+ all_hidden_states += (hidden_states,)
1095
+
1096
+ if self.gradient_checkpointing and self.training:
1097
+ layer_outputs = self._gradient_checkpointing_func(
1098
+ decoder_layer.__call__,
1099
+ hidden_states,
1100
+ attention_mask,
1101
+ position_ids,
1102
+ past_key_values,
1103
+ output_attentions,
1104
+ use_cache,
1105
+ )
1106
+ else:
1107
+ layer_outputs = decoder_layer(
1108
+ hidden_states,
1109
+ attention_mask=attention_mask,
1110
+ position_ids=position_ids,
1111
+ past_key_value=past_key_values,
1112
+ output_attentions=output_attentions,
1113
+ use_cache=use_cache,
1114
+ )
1115
+
1116
+ hidden_states = layer_outputs[0]
1117
+
1118
+ if use_cache:
1119
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1120
+
1121
+ if output_attentions:
1122
+ all_self_attns += (layer_outputs[1],)
1123
+
1124
+ hidden_states = self.norm(hidden_states)
1125
+
1126
+ # add hidden states from the last decoder layer
1127
+ if output_hidden_states:
1128
+ all_hidden_states += (hidden_states,)
1129
+
1130
+ next_cache = None
1131
+ if use_cache:
1132
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1133
+ if not return_dict:
1134
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1135
+ return BaseModelOutputWithPast(
1136
+ last_hidden_state=hidden_states,
1137
+ past_key_values=next_cache,
1138
+ hidden_states=all_hidden_states,
1139
+ attentions=all_self_attns,
1140
+ )
1141
+
1142
+
1143
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1144
+ _tied_weights_keys = ["lm_head.weight"]
1145
+
1146
+ def __init__(self, config):
1147
+ super().__init__(config)
1148
+ self.model = LlamaModel(config)
1149
+ self.vocab_size = config.vocab_size
1150
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1151
+
1152
+ # Initialize weights and apply final processing
1153
+ self.post_init()
1154
+
1155
+ def get_input_embeddings(self):
1156
+ return self.model.embed_tokens
1157
+
1158
+ def set_input_embeddings(self, value):
1159
+ self.model.embed_tokens = value
1160
+
1161
+ def get_output_embeddings(self):
1162
+ return self.lm_head
1163
+
1164
+ def set_output_embeddings(self, new_embeddings):
1165
+ self.lm_head = new_embeddings
1166
+
1167
+ def set_decoder(self, decoder):
1168
+ self.model = decoder
1169
+
1170
+ def get_decoder(self):
1171
+ return self.model
1172
+
1173
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1174
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1175
+ def forward(
1176
+ self,
1177
+ input_ids: torch.LongTensor = None,
1178
+ attention_mask: Optional[torch.Tensor] = None,
1179
+ position_ids: Optional[torch.LongTensor] = None,
1180
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1181
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1182
+ labels: Optional[torch.LongTensor] = None,
1183
+ use_cache: Optional[bool] = None,
1184
+ output_attentions: Optional[bool] = None,
1185
+ output_hidden_states: Optional[bool] = None,
1186
+ return_dict: Optional[bool] = None,
1187
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1188
+ r"""
1189
+ Args:
1190
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1191
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1192
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1193
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1194
+
1195
+ Returns:
1196
+
1197
+ Example:
1198
+
1199
+ ```python
1200
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1201
+
1202
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1203
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1204
+
1205
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1206
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1207
+
1208
+ >>> # Generate
1209
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1210
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1211
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1212
+ ```"""
1213
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1214
+ output_hidden_states = (
1215
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1216
+ )
1217
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1218
+
1219
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1220
+ outputs = self.model(
1221
+ input_ids=input_ids,
1222
+ attention_mask=attention_mask,
1223
+ position_ids=position_ids,
1224
+ past_key_values=past_key_values,
1225
+ inputs_embeds=inputs_embeds,
1226
+ use_cache=use_cache,
1227
+ output_attentions=output_attentions,
1228
+ output_hidden_states=output_hidden_states,
1229
+ return_dict=return_dict,
1230
+ )
1231
+
1232
+ hidden_states = outputs[0]
1233
+ if self.config.pretraining_tp > 1:
1234
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1235
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1236
+ logits = torch.cat(logits, dim=-1)
1237
+ else:
1238
+ logits = self.lm_head(hidden_states)
1239
+ logits = logits.float()
1240
+
1241
+ loss = None
1242
+ if labels is not None:
1243
+ # Shift so that tokens < n predict n
1244
+ shift_logits = logits[..., :-1, :].contiguous()
1245
+ shift_labels = labels[..., 1:].contiguous()
1246
+ # Flatten the tokens
1247
+ loss_fct = CrossEntropyLoss()
1248
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1249
+ shift_labels = shift_labels.view(-1)
1250
+ # Enable model parallelism
1251
+ shift_labels = shift_labels.to(shift_logits.device)
1252
+ loss = loss_fct(shift_logits, shift_labels)
1253
+
1254
+ if not return_dict:
1255
+ output = (logits,) + outputs[1:]
1256
+ return (loss,) + output if loss is not None else output
1257
+
1258
+ return CausalLMOutputWithPast(
1259
+ loss=loss,
1260
+ logits=logits,
1261
+ past_key_values=outputs.past_key_values,
1262
+ hidden_states=outputs.hidden_states,
1263
+ attentions=outputs.attentions,
1264
+ )
1265
+
1266
+ def prepare_inputs_for_generation(
1267
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1268
+ ):
1269
+ if past_key_values is not None:
1270
+ if isinstance(past_key_values, Cache):
1271
+ cache_length = past_key_values.get_seq_length()
1272
+ past_length = past_key_values.seen_tokens
1273
+ max_cache_length = past_key_values.get_max_length()
1274
+ else:
1275
+ cache_length = past_length = past_key_values[0][0].shape[2]
1276
+ max_cache_length = None
1277
+
1278
+ # Keep only the unprocessed tokens:
1279
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1280
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1281
+ # input)
1282
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1283
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1284
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1285
+ # input_ids based on the past_length.
1286
+ elif past_length < input_ids.shape[1]:
1287
+ input_ids = input_ids[:, past_length:]
1288
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1289
+
1290
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1291
+ if (
1292
+ max_cache_length is not None
1293
+ and attention_mask is not None
1294
+ and cache_length + input_ids.shape[1] > max_cache_length
1295
+ ):
1296
+ attention_mask = attention_mask[:, -max_cache_length:]
1297
+
1298
+ position_ids = kwargs.get("position_ids", None)
1299
+ if attention_mask is not None and position_ids is None:
1300
+ # create position_ids on the fly for batch generation
1301
+ position_ids = attention_mask.long().cumsum(-1) - 1
1302
+ position_ids.masked_fill_(attention_mask == 0, 1)
1303
+ if past_key_values:
1304
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1305
+
1306
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1307
+ if inputs_embeds is not None and past_key_values is None:
1308
+ model_inputs = {"inputs_embeds": inputs_embeds}
1309
+ else:
1310
+ model_inputs = {"input_ids": input_ids}
1311
+
1312
+ model_inputs.update(
1313
+ {
1314
+ "position_ids": position_ids,
1315
+ "past_key_values": past_key_values,
1316
+ "use_cache": kwargs.get("use_cache"),
1317
+ "attention_mask": attention_mask,
1318
+ }
1319
+ )
1320
+ return model_inputs
1321
+
1322
+ @staticmethod
1323
+ def _reorder_cache(past_key_values, beam_idx):
1324
+ reordered_past = ()
1325
+ for layer_past in past_key_values:
1326
+ reordered_past += (
1327
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1328
+ )
1329
+ return reordered_past
1330
+
1331
+
1332
+ @add_start_docstrings(
1333
+ """
1334
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1335
+
1336
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1337
+ (e.g. GPT-2) do.
1338
+
1339
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1340
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1341
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1342
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1343
+ each row of the batch).
1344
+ """,
1345
+ LLAMA_START_DOCSTRING,
1346
+ )
1347
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1348
+ def __init__(self, config):
1349
+ super().__init__(config)
1350
+ self.num_labels = config.num_labels
1351
+ self.model = LlamaModel(config)
1352
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1353
+
1354
+ # Initialize weights and apply final processing
1355
+ self.post_init()
1356
+
1357
+ def get_input_embeddings(self):
1358
+ return self.model.embed_tokens
1359
+
1360
+ def set_input_embeddings(self, value):
1361
+ self.model.embed_tokens = value
1362
+
1363
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1364
+ def forward(
1365
+ self,
1366
+ input_ids: torch.LongTensor = None,
1367
+ attention_mask: Optional[torch.Tensor] = None,
1368
+ position_ids: Optional[torch.LongTensor] = None,
1369
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1370
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1371
+ labels: Optional[torch.LongTensor] = None,
1372
+ use_cache: Optional[bool] = None,
1373
+ output_attentions: Optional[bool] = None,
1374
+ output_hidden_states: Optional[bool] = None,
1375
+ return_dict: Optional[bool] = None,
1376
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1377
+ r"""
1378
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1379
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1380
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1381
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1382
+ """
1383
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1384
+
1385
+ transformer_outputs = self.model(
1386
+ input_ids,
1387
+ attention_mask=attention_mask,
1388
+ position_ids=position_ids,
1389
+ past_key_values=past_key_values,
1390
+ inputs_embeds=inputs_embeds,
1391
+ use_cache=use_cache,
1392
+ output_attentions=output_attentions,
1393
+ output_hidden_states=output_hidden_states,
1394
+ return_dict=return_dict,
1395
+ )
1396
+ hidden_states = transformer_outputs[0]
1397
+ logits = self.score(hidden_states)
1398
+
1399
+ if input_ids is not None:
1400
+ batch_size = input_ids.shape[0]
1401
+ else:
1402
+ batch_size = inputs_embeds.shape[0]
1403
+
1404
+ if self.config.pad_token_id is None and batch_size != 1:
1405
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1406
+ if self.config.pad_token_id is None:
1407
+ sequence_lengths = -1
1408
+ else:
1409
+ if input_ids is not None:
1410
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1411
+ logits.device
1412
+ )
1413
+ else:
1414
+ sequence_lengths = -1
1415
+
1416
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1417
+
1418
+ loss = None
1419
+ if labels is not None:
1420
+ labels = labels.to(logits.device)
1421
+ if self.config.problem_type is None:
1422
+ if self.num_labels == 1:
1423
+ self.config.problem_type = "regression"
1424
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1425
+ self.config.problem_type = "single_label_classification"
1426
+ else:
1427
+ self.config.problem_type = "multi_label_classification"
1428
+
1429
+ if self.config.problem_type == "regression":
1430
+ loss_fct = MSELoss()
1431
+ if self.num_labels == 1:
1432
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1433
+ else:
1434
+ loss = loss_fct(pooled_logits, labels)
1435
+ elif self.config.problem_type == "single_label_classification":
1436
+ loss_fct = CrossEntropyLoss()
1437
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1438
+ elif self.config.problem_type == "multi_label_classification":
1439
+ loss_fct = BCEWithLogitsLoss()
1440
+ loss = loss_fct(pooled_logits, labels)
1441
+ if not return_dict:
1442
+ output = (pooled_logits,) + transformer_outputs[1:]
1443
+ return ((loss,) + output) if loss is not None else output
1444
+
1445
+ return SequenceClassifierOutputWithPast(
1446
+ loss=loss,
1447
+ logits=pooled_logits,
1448
+ past_key_values=transformer_outputs.past_key_values,
1449
+ hidden_states=transformer_outputs.hidden_states,
1450
+ attentions=transformer_outputs.attentions,
1451
+ )
weights_480/autoencoder_epoch_1_L1_nonorm_layer_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:62f6119d167487dc3499774a2ce11ad27a6ebcda9d8a7e7a46259a5721ec18e6
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8afec2359d4c84537685ac26eda3e8b0d5ebdd742fb74e7ae34f9c2ff24f908
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_10.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9dfbc1ed88456cad5bf3b1f0fbe65dd9762669e7acf8761f5068bdac84f5ffd7
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_11.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1222adf5043219dc6cc213d3b5e5a600ae10fbcb8d7dfac6059554df48905d99
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_12.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:11a17253cff1a441dc9ca2208ade87341247f944183a71bc312dbb61b7f4c0d0
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_13.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f02b8675388392b87c4458816ea7a881daa4b7f8b3c936006192529941bfe335
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_14.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6030afd955c02b692d1b1a3be97bc99bd0d597d7cbb1f26c62697245c28fcc2e
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_15.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6042d293f6ce75a8e91ab2543ba111a337adfd00163abf7e0bc19ff7921fc6c0
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_16.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8712cf883b4f360eb3a02702bf5c4452c4a0ad1e5a23261f01a029526af6790e
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_17.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3edde039d903a07d4cf172b021b7a9b2a4206eb38e49b9ac542f4f06a1b17426
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_18.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b44cd654981494d80b42a91f0b1ddc0dd947d0cec81744f975b8559420fcdef4
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_19.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1391b5f4678c73258cbc99b657ccf7a3df8c348d4cda02c8f478f9fe1ee2ed0b
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d9a47439616872760cf9dc875ddb5f83b147d0b679b922b4bc07968a3f4998b3
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_20.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d6ba03c14c1042b8861ddefbc4c870f407eacf91ce66139fdb9837dd11b5200
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_21.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35b25fc0c23c90ba78b35fca6815d4bbeb18b298e1ef7b93ce8b917b0ee6785b
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_22.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c06b005b9c7ab062c68654e7fe3d7ec9f1c3dfc76a7f58ec0314e12a0f4227f7
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_23.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77e2abca59d597e68202ede853f175194f6f76bb6bc68948222a00004f776636
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_24.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ab9d628626c1d815ded03030ea5f217b9a254be6b99e962210cf9cc77a83cf96
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_25.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9669d03b6d5493588be1d33747ac82190bcd05e621e44cb6bbd40210441533b7
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_26.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df4282ef7c4ea29519929172d24f0989860c0d28dc3e070260ecf4ac3baa40f2
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_27.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f8afc98ce23024c8aee0c9005818c51413a50618826abb351143ca8e6fc5505
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_28.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3c489b09b8a53ff34214f2c929d9dae89b4375f4a233b07871147d59bd830a8
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_29.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:327487a81e45fc21ce8dd90e7777c3dea0848c64b5e45ce91472781e51a3c41f
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:37e5f7d59c6dd2a74c9805d7cd39cfc052f247762daca948cd1e76c63f616258
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_30.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df6238c042edd0e01a5c341981772f5e2d52e07b849d4da5c7d66871c012d873
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_31.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:032129e723327b30c1ebba05bbc79d29fc3f85d9f6e130ab82d02899e22210f6
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_32.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:206b930c1486e6643a94e4bfc5fae7f0080814695346537e4cc2a5fed7fda476
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_33.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ff28eac7413f02bcd97bc447090f733fcb3d14da298ec03c580d22a0839d8764
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_34.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:263445b51e502b6585ac89eb7b645e1fa76580d4622974f45aee4bdbbc7565e3
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_35.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:19c0070d3c3ea9b288c80680b281b61a041c9a32c9e692a9eaa81ca909008128
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_36.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28ee84cff2485079ab770646e3ff07f88c345cd5a532d2644a499856f644877f
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_37.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:17e58e2f576baae621a1581d40ac491e504346f98416b10157a5139ae841fc24
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_38.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0f1ee30117a4dbb5ef2661e310a612cde5de056408347d7f736c34bf474a18ea
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_39.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:041242cc725abfd33cb40e8b8ff0a767eef0e9e9b4bf5cbef0637a8ae5317ea2
3
+ size 19671897
weights_480/autoencoder_epoch_1_L1_nonorm_layer_4.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d66b37bc2640a979d89f6fc9bb7155f1193d6282922bd0f21f8ff5ed97d51a9a
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_5.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83bd58f1dd7ff2a4324522ec76b706606f03a0fbafbd7634507c1fdb36424c59
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_6.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5854e6970ea61400e638d54be95057600ce5487101ab29ea56a95161b57ecbb5
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_7.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd621d39b76d07181502dced3b166d1fc2d6bf07e6709ec660ac3b03890af80d
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_8.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bdd134ccc36544b2c266abff21eecc953d701d78cbc69ce8e5a3b3f62d2a7b78
3
+ size 19671886
weights_480/autoencoder_epoch_1_L1_nonorm_layer_9.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55eaae1411665b2a641fcc73b779533b9e29e53ac8e4fd48c348c654f4b6d22c
3
+ size 19671886