zwt123home123 commited on
Commit
469195c
·
verified ·
1 Parent(s): 9c8cfa3

Upload folder using huggingface_hub

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