singleheart commited on
Commit
a809ab8
·
verified ·
1 Parent(s): 4d97bf3

Upload modeling_axk1.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_axk1.py +1833 -0
modeling_axk1.py ADDED
@@ -0,0 +1,1833 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 A.X K1 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
+
21
+ """ PyTorch A.X K1 model."""
22
+
23
+ import math
24
+ import warnings
25
+ from typing import List, Optional, Tuple, Union
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import (
35
+ _prepare_4d_causal_attention_mask,
36
+ )
37
+ from transformers.modeling_outputs import (
38
+ BaseModelOutputWithPast,
39
+ CausalLMOutputWithPast,
40
+ SequenceClassifierOutputWithPast,
41
+ )
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers.pytorch_utils import (
44
+ ALL_LAYERNORM_LAYERS,
45
+ is_torch_greater_or_equal_than_2_1,
46
+ )
47
+ from transformers.utils import (
48
+ add_start_docstrings,
49
+ add_start_docstrings_to_model_forward,
50
+ is_flash_attn_2_available,
51
+ is_flash_attn_greater_or_equal_2_10,
52
+ logging,
53
+ replace_return_docstrings,
54
+ )
55
+ from transformers.utils.import_utils import is_torch_fx_available
56
+ from .configuration_axk1 import AXK1Config
57
+ import torch.distributed as dist
58
+ import numpy as np
59
+
60
+ if is_flash_attn_2_available():
61
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
62
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
63
+
64
+
65
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
66
+ # It means that the function will not be traced through and simply appear as a node in the graph.
67
+ if is_torch_fx_available():
68
+ if not is_torch_greater_or_equal_than_2_1:
69
+ import torch.fx
70
+
71
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
72
+
73
+
74
+ logger = logging.get_logger(__name__)
75
+
76
+ _CONFIG_FOR_DOC = "AXK1Config"
77
+
78
+
79
+ def _get_unpad_data(attention_mask):
80
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
81
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
82
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
83
+ cu_seqlens = F.pad(
84
+ torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)
85
+ )
86
+ return (
87
+ indices,
88
+ cu_seqlens,
89
+ max_seqlen_in_batch,
90
+ )
91
+
92
+
93
+ class AXK1RMSNorm(nn.Module):
94
+ def __init__(self, hidden_size, eps=1e-6):
95
+ """
96
+ AXK1RMSNorm is equivalent to T5LayerNorm
97
+ """
98
+ super().__init__()
99
+ self.weight = nn.Parameter(torch.ones(hidden_size))
100
+ self.variance_epsilon = eps
101
+
102
+ def forward(self, hidden_states):
103
+ input_dtype = hidden_states.dtype
104
+ hidden_states = hidden_states.to(torch.float32)
105
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
106
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
107
+ return self.weight * hidden_states.to(input_dtype)
108
+
109
+
110
+ ALL_LAYERNORM_LAYERS.append(AXK1RMSNorm)
111
+
112
+
113
+ class AXK1RotaryEmbedding(nn.Module):
114
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
115
+ super().__init__()
116
+
117
+ self.dim = dim
118
+ self.max_position_embeddings = max_position_embeddings
119
+ self.base = base
120
+ inv_freq = 1.0 / (
121
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
122
+ )
123
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
124
+
125
+ # Build here to make `torch.jit.trace` work.
126
+ self._set_cos_sin_cache(
127
+ seq_len=max_position_embeddings,
128
+ device=self.inv_freq.device,
129
+ dtype=torch.get_default_dtype(),
130
+ )
131
+ self.max_seq_len_cached = None
132
+
133
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
134
+ self.max_seq_len_cached = seq_len
135
+ t = torch.arange(
136
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
137
+ )
138
+
139
+ freqs = torch.outer(t, self.inv_freq.to(t.device))
140
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
141
+ emb = torch.cat((freqs, freqs), dim=-1)
142
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
143
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
144
+
145
+ def forward(self, x, seq_len=None):
146
+ # x: [bs, num_attention_heads, seq_len, head_size]
147
+ if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached:
148
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
149
+
150
+ return (
151
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
152
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
153
+ )
154
+
155
+
156
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->AXK1
157
+ class AXK1LinearScalingRotaryEmbedding(AXK1RotaryEmbedding):
158
+ """AXK1RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
159
+
160
+ def __init__(
161
+ self,
162
+ dim,
163
+ max_position_embeddings=2048,
164
+ base=10000,
165
+ device=None,
166
+ scaling_factor=1.0,
167
+ ):
168
+ self.scaling_factor = scaling_factor
169
+ super().__init__(dim, max_position_embeddings, base, device)
170
+
171
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
172
+ self.max_seq_len_cached = seq_len
173
+ t = torch.arange(
174
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
175
+ )
176
+ t = t / self.scaling_factor
177
+
178
+ freqs = torch.outer(t, self.inv_freq)
179
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
180
+ emb = torch.cat((freqs, freqs), dim=-1)
181
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
182
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
183
+
184
+
185
+ # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->AXK1
186
+ class AXK1DynamicNTKScalingRotaryEmbedding(AXK1RotaryEmbedding):
187
+ """AXK1RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
188
+
189
+ def __init__(
190
+ self,
191
+ dim,
192
+ max_position_embeddings=2048,
193
+ base=10000,
194
+ device=None,
195
+ scaling_factor=1.0,
196
+ ):
197
+ self.scaling_factor = scaling_factor
198
+ super().__init__(dim, max_position_embeddings, base, device)
199
+
200
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
201
+ self.max_seq_len_cached = seq_len
202
+
203
+ if seq_len > self.max_position_embeddings:
204
+ base = self.base * (
205
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
206
+ - (self.scaling_factor - 1)
207
+ ) ** (self.dim / (self.dim - 2))
208
+ inv_freq = 1.0 / (
209
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
210
+ )
211
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
212
+
213
+ t = torch.arange(
214
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
215
+ )
216
+
217
+ freqs = torch.outer(t, self.inv_freq)
218
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
219
+ emb = torch.cat((freqs, freqs), dim=-1)
220
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
221
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
222
+
223
+
224
+ # Inverse dim formula to find dim based on number of rotations
225
+ def yarn_find_correction_dim(
226
+ num_rotations, dim, base=10000, max_position_embeddings=2048
227
+ ):
228
+ return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (
229
+ 2 * math.log(base)
230
+ )
231
+
232
+
233
+ # Find dim range bounds based on rotations
234
+ def yarn_find_correction_range(
235
+ low_rot, high_rot, dim, base=10000, max_position_embeddings=2048
236
+ ):
237
+ low = math.floor(
238
+ yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings)
239
+ )
240
+ high = math.ceil(
241
+ yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings)
242
+ )
243
+ return max(low, 0), min(high, dim - 1) # Clamp values just in case
244
+
245
+
246
+ def yarn_get_mscale(scale=1, mscale=1):
247
+ if scale <= 1:
248
+ return 1.0
249
+ return 0.1 * mscale * math.log(scale) + 1.0
250
+
251
+
252
+ def yarn_linear_ramp_mask(min, max, dim):
253
+ if min == max:
254
+ max += 0.001 # Prevent singularity
255
+
256
+ linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
257
+ ramp_func = torch.clamp(linear_func, 0, 1)
258
+ return ramp_func
259
+
260
+
261
+ class AXK1YarnRotaryEmbedding(AXK1RotaryEmbedding):
262
+
263
+ def __init__(
264
+ self,
265
+ dim,
266
+ max_position_embeddings=2048,
267
+ base=10000,
268
+ device=None,
269
+ scaling_factor=1.0,
270
+ original_max_position_embeddings=4096,
271
+ beta_fast=32,
272
+ beta_slow=1,
273
+ mscale=1,
274
+ mscale_all_dim=0,
275
+ ):
276
+ self.scaling_factor = scaling_factor
277
+ self.original_max_position_embeddings = original_max_position_embeddings
278
+ self.beta_fast = beta_fast
279
+ self.beta_slow = beta_slow
280
+ self.mscale = mscale
281
+ self.mscale_all_dim = mscale_all_dim
282
+ super().__init__(dim, max_position_embeddings, base, device)
283
+
284
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
285
+ self.max_seq_len_cached = seq_len
286
+ dim = self.dim
287
+
288
+ freq_extra = 1.0 / (
289
+ self.base
290
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
291
+ )
292
+ freq_inter = 1.0 / (
293
+ self.scaling_factor
294
+ * self.base
295
+ ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim)
296
+ )
297
+
298
+ low, high = yarn_find_correction_range(
299
+ self.beta_fast,
300
+ self.beta_slow,
301
+ dim,
302
+ self.base,
303
+ self.original_max_position_embeddings,
304
+ )
305
+ inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to(
306
+ device=device, dtype=torch.float32
307
+ )
308
+ inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask
309
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
310
+
311
+ t = torch.arange(seq_len, device=device, dtype=torch.float32)
312
+
313
+ freqs = torch.outer(t, inv_freq)
314
+
315
+ _mscale = float(
316
+ yarn_get_mscale(self.scaling_factor, self.mscale)
317
+ / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim)
318
+ )
319
+
320
+ emb = torch.cat((freqs, freqs), dim=-1)
321
+ self.register_buffer(
322
+ "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False
323
+ )
324
+ self.register_buffer(
325
+ "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False
326
+ )
327
+
328
+
329
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
330
+ def rotate_half(x):
331
+ """Rotates half the hidden dims of the input."""
332
+ x1 = x[..., : x.shape[-1] // 2]
333
+ x2 = x[..., x.shape[-1] // 2 :]
334
+ return torch.cat((-x2, x1), dim=-1)
335
+
336
+
337
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
338
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
339
+ """Applies Rotary Position Embedding to the query and key tensors.
340
+ Args:
341
+ q (`torch.Tensor`): The query tensor.
342
+ k (`torch.Tensor`): The key tensor.
343
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
344
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
345
+ position_ids (`torch.Tensor`):
346
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
347
+ used to pass offsetted position ids when working with a KV-cache.
348
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
349
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
350
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
351
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
352
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
353
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
354
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
355
+ Returns:
356
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
357
+ """
358
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
359
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
360
+
361
+ b, h, s, d = q.shape
362
+ q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
363
+
364
+ b, h, s, d = k.shape
365
+ k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
366
+
367
+ q_embed = (q * cos) + (rotate_half(q) * sin)
368
+ k_embed = (k * cos) + (rotate_half(k) * sin)
369
+ return q_embed, k_embed
370
+
371
+
372
+ class AXK1MLP(nn.Module):
373
+ def __init__(self, config, hidden_size=None, intermediate_size=None):
374
+ super().__init__()
375
+ self.config = config
376
+ self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
377
+ self.intermediate_size = (
378
+ config.intermediate_size if intermediate_size is None else intermediate_size
379
+ )
380
+
381
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
382
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
383
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
384
+ self.act_fn = ACT2FN[config.hidden_act]
385
+
386
+ def forward(self, x):
387
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
388
+ return down_proj
389
+
390
+
391
+ class MoEGate(nn.Module):
392
+ def __init__(self, config):
393
+ super().__init__()
394
+ self.config = config
395
+ self.top_k = config.num_experts_per_tok
396
+ self.n_routed_experts = config.n_routed_experts
397
+ self.routed_scaling_factor = config.routed_scaling_factor
398
+ self.scoring_func = config.scoring_func
399
+ self.topk_method = config.topk_method
400
+ self.n_group = config.n_group
401
+ self.topk_group = config.topk_group
402
+
403
+ # topk selection algorithm
404
+ self.norm_topk_prob = config.norm_topk_prob
405
+ self.gating_dim = config.hidden_size
406
+ self.weight = nn.Parameter(
407
+ torch.empty((self.n_routed_experts, self.gating_dim))
408
+ )
409
+ if self.topk_method == "noaux_tc":
410
+ self.e_score_correction_bias = nn.Parameter(
411
+ torch.empty((self.n_routed_experts))
412
+ )
413
+ self.reset_parameters()
414
+
415
+ def reset_parameters(self) -> None:
416
+ import torch.nn.init as init
417
+
418
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
419
+
420
+ def forward(self, hidden_states):
421
+ bsz, seq_len, h = hidden_states.shape
422
+ ### compute gating score
423
+ hidden_states = hidden_states.view(-1, h)
424
+ logits = F.linear(
425
+ hidden_states.type(torch.float32), self.weight.type(torch.float32), None
426
+ )
427
+ if self.scoring_func == "sigmoid":
428
+ scores = logits.sigmoid()
429
+ else:
430
+ raise NotImplementedError(
431
+ f"insupportable scoring function for MoE gating: {self.scoring_func}"
432
+ )
433
+
434
+ ### select top-k experts
435
+ if self.topk_method == "noaux_tc":
436
+ assert not self.training
437
+ scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0)
438
+ group_scores = (
439
+ scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1)
440
+ ) # [n, n_group]
441
+ group_idx = torch.topk(
442
+ group_scores, k=self.topk_group, dim=-1, sorted=False
443
+ )[
444
+ 1
445
+ ] # [n, top_k_group]
446
+ group_mask = torch.zeros_like(group_scores) # [n, n_group]
447
+ group_mask.scatter_(1, group_idx, 1) # [n, n_group]
448
+ score_mask = (
449
+ group_mask.unsqueeze(-1)
450
+ .expand(
451
+ bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group
452
+ )
453
+ .reshape(bsz * seq_len, -1)
454
+ ) # [n, e]
455
+ tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) # [n, e]
456
+ _, topk_idx = torch.topk(
457
+ tmp_scores, k=self.top_k, dim=-1, sorted=False
458
+ )
459
+ topk_weight = scores.gather(1, topk_idx)
460
+ else:
461
+ raise NotImplementedError(
462
+ f"insupportable TopK function for MoE gating: {self.topk_method}"
463
+ )
464
+
465
+ ### norm gate to sum 1
466
+ if self.top_k > 1 and self.norm_topk_prob:
467
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
468
+ topk_weight = topk_weight / denominator
469
+ topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor
470
+
471
+ return topk_idx, topk_weight
472
+
473
+ class AXK1MoE(nn.Module):
474
+ """
475
+ A mixed expert module containing shared experts.
476
+ """
477
+
478
+ def __init__(self, config):
479
+ super().__init__()
480
+ self.config = config
481
+ self.num_experts_per_tok = config.num_experts_per_tok
482
+
483
+ if hasattr(config, "ep_size") and config.ep_size > 1:
484
+ assert config.ep_size == dist.get_world_size()
485
+ self.ep_size = config.ep_size
486
+ self.experts_per_rank = config.n_routed_experts // config.ep_size
487
+ self.ep_rank = dist.get_rank()
488
+ self.experts = nn.ModuleList(
489
+ [
490
+ (
491
+ AXK1MLP(
492
+ config, intermediate_size=config.moe_intermediate_size
493
+ )
494
+ if i >= self.ep_rank * self.experts_per_rank
495
+ and i < (self.ep_rank + 1) * self.experts_per_rank
496
+ else None
497
+ )
498
+ for i in range(config.n_routed_experts)
499
+ ]
500
+ )
501
+ else:
502
+ self.ep_size = 1
503
+ self.experts_per_rank = config.n_routed_experts
504
+ self.ep_rank = 0
505
+ self.experts = nn.ModuleList(
506
+ [
507
+ AXK1MLP(
508
+ config, intermediate_size=config.moe_intermediate_size
509
+ )
510
+ for i in range(config.n_routed_experts)
511
+ ]
512
+ )
513
+ self.gate = MoEGate(config)
514
+ if config.n_shared_experts is not None:
515
+ intermediate_size = config.moe_intermediate_size * config.n_shared_experts
516
+ self.shared_experts = AXK1MLP(
517
+ config=config, intermediate_size=intermediate_size
518
+ )
519
+
520
+ def forward(self, hidden_states):
521
+ identity = hidden_states
522
+ orig_shape = hidden_states.shape
523
+ topk_idx, topk_weight = self.gate(hidden_states)
524
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
525
+ flat_topk_idx = topk_idx.view(-1)
526
+ if not self.training:
527
+ y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape)
528
+ if self.config.n_shared_experts is not None:
529
+ y = y + self.shared_experts(identity)
530
+ return y
531
+
532
+ @torch.no_grad()
533
+ def moe_infer(self, x, topk_ids, topk_weight):
534
+ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts)))
535
+ cnts.scatter_(1, topk_ids, 1)
536
+ tokens_per_expert = cnts.sum(dim=0)
537
+ idxs = topk_ids.view(-1).argsort()
538
+ sorted_tokens = x[idxs // topk_ids.shape[1]]
539
+ sorted_tokens_shape = sorted_tokens.shape
540
+ if self.ep_size > 1:
541
+ tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1)
542
+ tokens_per_expert_group = tokens_per_expert.new_empty(
543
+ tokens_per_expert.shape[0]
544
+ )
545
+ dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert)
546
+ output_splits = (
547
+ tokens_per_expert_group.view(self.ep_size, -1)
548
+ .sum(1)
549
+ .cpu()
550
+ .numpy()
551
+ .tolist()
552
+ )
553
+ gathered_tokens = sorted_tokens.new_empty(
554
+ tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1]
555
+ )
556
+ input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist()
557
+ dist.all_to_all(
558
+ list(gathered_tokens.split(output_splits)),
559
+ list(sorted_tokens.split(input_split_sizes)),
560
+ )
561
+ tokens_per_expert_post_gather = tokens_per_expert_group.view(
562
+ self.ep_size, self.experts_per_rank
563
+ ).sum(dim=0)
564
+ gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32)
565
+ s = 0
566
+ for i, k in enumerate(tokens_per_expert_group.cpu().numpy()):
567
+ gatherd_idxs[s : s + k] = i % self.experts_per_rank
568
+ s += k
569
+ gatherd_idxs = gatherd_idxs.argsort()
570
+ sorted_tokens = gathered_tokens[gatherd_idxs]
571
+ tokens_per_expert = tokens_per_expert_post_gather
572
+ tokens_per_expert = tokens_per_expert.cpu().numpy()
573
+
574
+ outputs = []
575
+ start_idx = 0
576
+ for i, num_tokens in enumerate(tokens_per_expert):
577
+ end_idx = start_idx + num_tokens
578
+ if num_tokens == 0:
579
+ continue
580
+ expert = self.experts[i + self.ep_rank * self.experts_per_rank]
581
+ tokens_for_this_expert = sorted_tokens[start_idx:end_idx]
582
+ expert_out = expert(tokens_for_this_expert)
583
+ outputs.append(expert_out)
584
+ start_idx = end_idx
585
+
586
+ outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0)
587
+ if self.ep_size > 1:
588
+ new_x = torch.empty_like(outs)
589
+ new_x[gatherd_idxs] = outs
590
+ gathered_tokens = new_x.new_empty(*sorted_tokens_shape)
591
+ dist.all_to_all(
592
+ list(gathered_tokens.split(input_split_sizes)),
593
+ list(new_x.split(output_splits)),
594
+ )
595
+ outs = gathered_tokens
596
+
597
+ new_x = torch.empty_like(outs)
598
+ new_x[idxs] = outs
599
+ final_out = (
600
+ new_x.view(*topk_ids.shape, -1)
601
+ .type(topk_weight.dtype)
602
+ .mul_(topk_weight.unsqueeze(dim=-1))
603
+ .sum(dim=1)
604
+ .type(new_x.dtype)
605
+ )
606
+ return final_out
607
+
608
+
609
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
610
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
611
+ """
612
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
613
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
614
+ """
615
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
616
+ if n_rep == 1:
617
+ return hidden_states
618
+ hidden_states = hidden_states[:, :, None, :, :].expand(
619
+ batch, num_key_value_heads, n_rep, slen, head_dim
620
+ )
621
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
622
+
623
+
624
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->AXK1
625
+ class AXK1Attention(nn.Module):
626
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
627
+
628
+ def __init__(self, config: AXK1Config, layer_idx: Optional[int] = None):
629
+ super().__init__()
630
+ self.config = config
631
+ self.layer_idx = layer_idx
632
+ if layer_idx is None:
633
+ logger.warning_once(
634
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
635
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
636
+ "when creating this class."
637
+ )
638
+
639
+ self.attention_dropout = config.attention_dropout
640
+ self.hidden_size = config.hidden_size
641
+ self.num_heads = config.num_attention_heads
642
+
643
+ self.max_position_embeddings = config.max_position_embeddings
644
+ self.rope_theta = config.rope_theta
645
+ self.q_lora_rank = config.q_lora_rank
646
+ self.qk_rope_head_dim = config.qk_rope_head_dim
647
+ self.kv_lora_rank = config.kv_lora_rank
648
+ self.v_head_dim = config.v_head_dim
649
+ self.qk_nope_head_dim = config.qk_nope_head_dim
650
+ self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
651
+
652
+ self.is_causal = True
653
+
654
+ if self.q_lora_rank is None:
655
+ self.q_proj = nn.Linear(
656
+ self.hidden_size, self.num_heads * self.q_head_dim, bias=False
657
+ )
658
+ else:
659
+ self.q_a_proj = nn.Linear(
660
+ self.hidden_size, config.q_lora_rank, bias=config.attention_bias
661
+ )
662
+ self.q_a_layernorm = AXK1RMSNorm(config.q_lora_rank)
663
+ self.q_b_proj = nn.Linear(
664
+ config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False
665
+ )
666
+
667
+ self.kv_a_proj_with_mqa = nn.Linear(
668
+ self.hidden_size,
669
+ config.kv_lora_rank + config.qk_rope_head_dim,
670
+ bias=config.attention_bias,
671
+ )
672
+ self.kv_a_layernorm = AXK1RMSNorm(config.kv_lora_rank)
673
+ self.kv_b_proj = nn.Linear(
674
+ config.kv_lora_rank,
675
+ self.num_heads
676
+ * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim),
677
+ bias=False,
678
+ )
679
+
680
+ self.o_proj = nn.Linear(
681
+ self.num_heads * self.v_head_dim,
682
+ self.hidden_size,
683
+ bias=config.attention_bias,
684
+ )
685
+ self._init_rope()
686
+
687
+ self.softmax_scale = self.q_head_dim ** (-0.5)
688
+ if self.config.rope_scaling is not None:
689
+ mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
690
+ scaling_factor = self.config.rope_scaling["factor"]
691
+ if mscale_all_dim:
692
+ mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
693
+ self.softmax_scale = self.softmax_scale * mscale * mscale
694
+
695
+ def _init_rope(self):
696
+ if self.config.rope_scaling is None:
697
+ self.rotary_emb = AXK1RotaryEmbedding(
698
+ self.qk_rope_head_dim,
699
+ max_position_embeddings=self.max_position_embeddings,
700
+ base=self.rope_theta,
701
+ )
702
+ else:
703
+ scaling_type = self.config.rope_scaling["type"]
704
+ scaling_factor = self.config.rope_scaling["factor"]
705
+ if scaling_type == "linear":
706
+ self.rotary_emb = AXK1LinearScalingRotaryEmbedding(
707
+ self.qk_rope_head_dim,
708
+ max_position_embeddings=self.max_position_embeddings,
709
+ scaling_factor=scaling_factor,
710
+ base=self.rope_theta,
711
+ )
712
+ elif scaling_type == "dynamic":
713
+ self.rotary_emb = AXK1DynamicNTKScalingRotaryEmbedding(
714
+ self.qk_rope_head_dim,
715
+ max_position_embeddings=self.max_position_embeddings,
716
+ scaling_factor=scaling_factor,
717
+ base=self.rope_theta,
718
+ )
719
+ elif scaling_type == "yarn":
720
+ kwargs = {
721
+ key: self.config.rope_scaling[key]
722
+ for key in [
723
+ "original_max_position_embeddings",
724
+ "beta_fast",
725
+ "beta_slow",
726
+ "mscale",
727
+ "mscale_all_dim",
728
+ ]
729
+ if key in self.config.rope_scaling
730
+ }
731
+ self.rotary_emb = AXK1YarnRotaryEmbedding(
732
+ self.qk_rope_head_dim,
733
+ max_position_embeddings=self.max_position_embeddings,
734
+ scaling_factor=scaling_factor,
735
+ base=self.rope_theta,
736
+ **kwargs,
737
+ )
738
+ else:
739
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
740
+
741
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
742
+ return (
743
+ tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim)
744
+ .transpose(1, 2)
745
+ .contiguous()
746
+ )
747
+
748
+ def forward(
749
+ self,
750
+ hidden_states: torch.Tensor,
751
+ attention_mask: Optional[torch.Tensor] = None,
752
+ position_ids: Optional[torch.LongTensor] = None,
753
+ past_key_value: Optional[Cache] = None,
754
+ output_attentions: bool = False,
755
+ use_cache: bool = False,
756
+ **kwargs,
757
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
758
+ if "padding_mask" in kwargs:
759
+ warnings.warn(
760
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
761
+ )
762
+ bsz, q_len, _ = hidden_states.size()
763
+
764
+ if self.q_lora_rank is None:
765
+ q = self.q_proj(hidden_states)
766
+ else:
767
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
768
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
769
+ q_nope, q_pe = torch.split(
770
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
771
+ )
772
+
773
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
774
+ compressed_kv, k_pe = torch.split(
775
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
776
+ )
777
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
778
+ kv = (
779
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
780
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
781
+ .transpose(1, 2)
782
+ )
783
+
784
+ k_nope, value_states = torch.split(
785
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
786
+ )
787
+ kv_seq_len = value_states.shape[-2]
788
+ if past_key_value is not None:
789
+ if self.layer_idx is None:
790
+ raise ValueError(
791
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
792
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
793
+ "with a layer index."
794
+ )
795
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
796
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
797
+
798
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
799
+
800
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
801
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
802
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
803
+
804
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
805
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
806
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
807
+ if past_key_value is not None:
808
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
809
+ key_states, value_states = past_key_value.update(
810
+ key_states, value_states, self.layer_idx, cache_kwargs
811
+ )
812
+
813
+ attn_weights = (
814
+ torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale
815
+ )
816
+
817
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
818
+ raise ValueError(
819
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
820
+ f" {attn_weights.size()}"
821
+ )
822
+ assert attention_mask is not None
823
+ if attention_mask is not None:
824
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
825
+ raise ValueError(
826
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
827
+ )
828
+ attn_weights = attn_weights + attention_mask
829
+
830
+ # upcast attention to fp32
831
+ attn_weights = nn.functional.softmax(
832
+ attn_weights, dim=-1, dtype=torch.float32
833
+ ).to(query_states.dtype)
834
+ attn_weights = nn.functional.dropout(
835
+ attn_weights, p=self.attention_dropout, training=self.training
836
+ )
837
+ attn_output = torch.matmul(attn_weights, value_states)
838
+
839
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim):
840
+ raise ValueError(
841
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is"
842
+ f" {attn_output.size()}"
843
+ )
844
+
845
+ attn_output = attn_output.transpose(1, 2).contiguous()
846
+
847
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim)
848
+
849
+ attn_output = self.o_proj(attn_output)
850
+
851
+ if not output_attentions:
852
+ attn_weights = None
853
+
854
+ return attn_output, attn_weights, past_key_value
855
+
856
+
857
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->AXK1
858
+ class AXK1FlashAttention2(AXK1Attention):
859
+ """
860
+ AXK1 flash attention module. This module inherits from `AXK1Attention` as the weights of the module stays
861
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
862
+ flash attention and deal with padding tokens in case the input contains any of them.
863
+ """
864
+
865
+ def __init__(self, *args, **kwargs):
866
+ super().__init__(*args, **kwargs)
867
+
868
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
869
+ # 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.
870
+ # 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).
871
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
872
+
873
+ def forward(
874
+ self,
875
+ hidden_states: torch.Tensor,
876
+ attention_mask: Optional[torch.LongTensor] = None,
877
+ position_ids: Optional[torch.LongTensor] = None,
878
+ past_key_value: Optional[Cache] = None,
879
+ output_attentions: bool = False,
880
+ use_cache: bool = False,
881
+ **kwargs,
882
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
883
+ # AXK1FlashAttention2 attention does not support output_attentions
884
+ if "padding_mask" in kwargs:
885
+ warnings.warn(
886
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
887
+ )
888
+
889
+ # overwrite attention_mask with padding_mask
890
+ attention_mask = kwargs.pop("padding_mask")
891
+
892
+ output_attentions = False
893
+
894
+ bsz, q_len, _ = hidden_states.size()
895
+
896
+ if self.q_lora_rank is None:
897
+ q = self.q_proj(hidden_states)
898
+ else:
899
+ q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
900
+ q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2)
901
+ q_nope, q_pe = torch.split(
902
+ q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1
903
+ )
904
+
905
+ # Flash attention requires the input to have the shape
906
+ # batch_size x seq_length x head_dim x hidden_dim
907
+ # therefore we just need to keep the original shape
908
+ compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
909
+ compressed_kv, k_pe = torch.split(
910
+ compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1
911
+ )
912
+ k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2)
913
+ kv = (
914
+ self.kv_b_proj(self.kv_a_layernorm(compressed_kv))
915
+ .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim)
916
+ .transpose(1, 2)
917
+ )
918
+
919
+ k_nope, value_states = torch.split(
920
+ kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1
921
+ )
922
+ kv_seq_len = value_states.shape[-2]
923
+
924
+ kv_seq_len = value_states.shape[-2]
925
+ if past_key_value is not None:
926
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
927
+
928
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
929
+ q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids)
930
+
931
+ query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
932
+ query_states[:, :, :, : self.qk_nope_head_dim] = q_nope
933
+ query_states[:, :, :, self.qk_nope_head_dim :] = q_pe
934
+
935
+ key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim)
936
+ key_states[:, :, :, : self.qk_nope_head_dim] = k_nope
937
+ key_states[:, :, :, self.qk_nope_head_dim :] = k_pe
938
+
939
+ if self.q_head_dim != self.v_head_dim:
940
+ value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim])
941
+
942
+ if past_key_value is not None:
943
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
944
+ key_states, value_states = past_key_value.update(
945
+ key_states, value_states, self.layer_idx, cache_kwargs
946
+ )
947
+
948
+ # 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
949
+ # to be able to avoid many of these transpose/reshape/view.
950
+ query_states = query_states.transpose(1, 2)
951
+ key_states = key_states.transpose(1, 2)
952
+ value_states = value_states.transpose(1, 2)
953
+
954
+ dropout_rate = self.attention_dropout if self.training else 0.0
955
+
956
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
957
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
958
+ # cast them back in the correct dtype just to be sure everything works as expected.
959
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
960
+ # in fp32. (AXK1RMSNorm handles it correctly)
961
+
962
+ input_dtype = query_states.dtype
963
+ if input_dtype == torch.float32:
964
+ # Handle the case where the model is quantized
965
+ if hasattr(self.config, "_pre_quantization_dtype"):
966
+ target_dtype = self.config._pre_quantization_dtype
967
+ elif torch.is_autocast_enabled():
968
+ target_dtype = torch.get_autocast_gpu_dtype()
969
+ else:
970
+ target_dtype = (
971
+ self.q_proj.weight.dtype
972
+ if self.q_lora_rank is None
973
+ else self.q_a_proj.weight.dtype
974
+ )
975
+
976
+ logger.warning_once(
977
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
978
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
979
+ f" {target_dtype}."
980
+ )
981
+
982
+ query_states = query_states.to(target_dtype)
983
+ key_states = key_states.to(target_dtype)
984
+ value_states = value_states.to(target_dtype)
985
+
986
+ attn_output = self._flash_attention_forward(
987
+ query_states,
988
+ key_states,
989
+ value_states,
990
+ attention_mask,
991
+ q_len,
992
+ dropout=dropout_rate,
993
+ softmax_scale=self.softmax_scale,
994
+ )
995
+ if self.q_head_dim != self.v_head_dim:
996
+ attn_output = attn_output[:, :, :, : self.v_head_dim]
997
+
998
+ attn_output = attn_output.reshape(
999
+ bsz, q_len, self.num_heads * self.v_head_dim
1000
+ ).contiguous()
1001
+ attn_output = self.o_proj(attn_output)
1002
+
1003
+ if not output_attentions:
1004
+ attn_weights = None
1005
+
1006
+ return attn_output, attn_weights, past_key_value
1007
+
1008
+ def _flash_attention_forward(
1009
+ self,
1010
+ query_states,
1011
+ key_states,
1012
+ value_states,
1013
+ attention_mask,
1014
+ query_length,
1015
+ dropout=0.0,
1016
+ softmax_scale=None,
1017
+ ):
1018
+ """
1019
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
1020
+ first unpad the input, then computes the attention scores and pad the final attention scores.
1021
+ Args:
1022
+ query_states (`torch.Tensor`):
1023
+ Input query states to be passed to Flash Attention API
1024
+ key_states (`torch.Tensor`):
1025
+ Input key states to be passed to Flash Attention API
1026
+ value_states (`torch.Tensor`):
1027
+ Input value states to be passed to Flash Attention API
1028
+ attention_mask (`torch.Tensor`):
1029
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
1030
+ position of padding tokens and 1 for the position of non-padding tokens.
1031
+ dropout (`int`, *optional*):
1032
+ Attention dropout
1033
+ softmax_scale (`float`, *optional*):
1034
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
1035
+ """
1036
+ if not self._flash_attn_uses_top_left_mask:
1037
+ causal = self.is_causal
1038
+ else:
1039
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in AXK1FlashAttention2 __init__.
1040
+ causal = self.is_causal and query_length != 1
1041
+
1042
+ # Contains at least one padding token in the sequence
1043
+ if attention_mask is not None:
1044
+ batch_size = query_states.shape[0]
1045
+ (
1046
+ query_states,
1047
+ key_states,
1048
+ value_states,
1049
+ indices_q,
1050
+ cu_seq_lens,
1051
+ max_seq_lens,
1052
+ ) = self._upad_input(
1053
+ query_states, key_states, value_states, attention_mask, query_length
1054
+ )
1055
+
1056
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
1057
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
1058
+
1059
+ attn_output_unpad = flash_attn_varlen_func(
1060
+ query_states,
1061
+ key_states,
1062
+ value_states,
1063
+ cu_seqlens_q=cu_seqlens_q,
1064
+ cu_seqlens_k=cu_seqlens_k,
1065
+ max_seqlen_q=max_seqlen_in_batch_q,
1066
+ max_seqlen_k=max_seqlen_in_batch_k,
1067
+ dropout_p=dropout,
1068
+ softmax_scale=softmax_scale,
1069
+ causal=causal,
1070
+ )
1071
+
1072
+ attn_output = pad_input(
1073
+ attn_output_unpad, indices_q, batch_size, query_length
1074
+ )
1075
+ else:
1076
+ attn_output = flash_attn_func(
1077
+ query_states,
1078
+ key_states,
1079
+ value_states,
1080
+ dropout,
1081
+ softmax_scale=softmax_scale,
1082
+ causal=causal,
1083
+ )
1084
+
1085
+ return attn_output
1086
+
1087
+ def _upad_input(
1088
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
1089
+ ):
1090
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
1091
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
1092
+
1093
+ key_layer = index_first_axis(
1094
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1095
+ indices_k,
1096
+ )
1097
+ value_layer = index_first_axis(
1098
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
1099
+ indices_k,
1100
+ )
1101
+ if query_length == kv_seq_len:
1102
+ query_layer = index_first_axis(
1103
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
1104
+ indices_k,
1105
+ )
1106
+ cu_seqlens_q = cu_seqlens_k
1107
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
1108
+ indices_q = indices_k
1109
+ elif query_length == 1:
1110
+ max_seqlen_in_batch_q = 1
1111
+ cu_seqlens_q = torch.arange(
1112
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
1113
+ ) # There is a memcpy here, that is very bad.
1114
+ indices_q = cu_seqlens_q[:-1]
1115
+ query_layer = query_layer.squeeze(1)
1116
+ else:
1117
+ # The -q_len: slice assumes left padding.
1118
+ attention_mask = attention_mask[:, -query_length:]
1119
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
1120
+ query_layer, attention_mask
1121
+ )
1122
+
1123
+ return (
1124
+ query_layer,
1125
+ key_layer,
1126
+ value_layer,
1127
+ indices_q,
1128
+ (cu_seqlens_q, cu_seqlens_k),
1129
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
1130
+ )
1131
+
1132
+
1133
+ ATTENTION_CLASSES = {
1134
+ "eager": AXK1Attention,
1135
+ "flash_attention_2": AXK1FlashAttention2,
1136
+ }
1137
+
1138
+
1139
+ class AXK1DecoderLayer(nn.Module):
1140
+ def __init__(self, config: AXK1Config, layer_idx: int):
1141
+ super().__init__()
1142
+ self.hidden_size = config.hidden_size
1143
+
1144
+ self.self_attn = ATTENTION_CLASSES[config._attn_implementation](
1145
+ config=config, layer_idx=layer_idx
1146
+ )
1147
+ self.config = config
1148
+ self.layer_idx = layer_idx
1149
+
1150
+ self.mlp = (
1151
+ AXK1MoE(config)
1152
+ if (
1153
+ config.n_routed_experts is not None
1154
+ and layer_idx >= config.first_k_dense_replace
1155
+ and layer_idx % config.moe_layer_freq == 0
1156
+ )
1157
+ else AXK1MLP(config)
1158
+ )
1159
+ self.input_layernorm = AXK1RMSNorm(
1160
+ config.hidden_size, eps=config.rms_norm_eps
1161
+ )
1162
+ self.post_attention_layernorm = AXK1RMSNorm(
1163
+ config.hidden_size, eps=config.rms_norm_eps
1164
+ )
1165
+ self.post_mlp_layernorm = AXK1RMSNorm(
1166
+ config.hidden_size, eps=config.rms_norm_eps
1167
+ )
1168
+
1169
+ def forward(
1170
+ self,
1171
+ hidden_states: torch.Tensor,
1172
+ attention_mask: Optional[torch.Tensor] = None,
1173
+ position_ids: Optional[torch.LongTensor] = None,
1174
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1175
+ output_attentions: Optional[bool] = False,
1176
+ use_cache: Optional[bool] = False,
1177
+ **kwargs,
1178
+ ) -> Tuple[
1179
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
1180
+ ]:
1181
+ """
1182
+ Args:
1183
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1184
+ attention_mask (`torch.FloatTensor`, *optional*):
1185
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1186
+ query_sequence_length, key_sequence_length)` if default attention is used.
1187
+ output_attentions (`bool`, *optional*):
1188
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1189
+ returned tensors for more detail.
1190
+ use_cache (`bool`, *optional*):
1191
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1192
+ (see `past_key_values`).
1193
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1194
+ """
1195
+ if "padding_mask" in kwargs:
1196
+ warnings.warn(
1197
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
1198
+ )
1199
+ residual = hidden_states
1200
+
1201
+ hidden_states = self.input_layernorm(hidden_states)
1202
+
1203
+ # Self Attention
1204
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
1205
+ hidden_states=hidden_states,
1206
+ attention_mask=attention_mask,
1207
+ position_ids=position_ids,
1208
+ past_key_value=past_key_value,
1209
+ output_attentions=output_attentions,
1210
+ use_cache=use_cache,
1211
+ **kwargs,
1212
+ )
1213
+ hidden_states = residual + hidden_states
1214
+
1215
+ # Fully Connected
1216
+ residual = hidden_states
1217
+ hidden_states = self.post_attention_layernorm(hidden_states)
1218
+ hidden_states = self.mlp(hidden_states)
1219
+ if (
1220
+ self.config.n_routed_experts is not None
1221
+ and self.layer_idx >= self.config.first_k_dense_replace
1222
+ and self.layer_idx % self.config.moe_layer_freq == 0
1223
+ ):
1224
+ hidden_states = self.post_mlp_layernorm(hidden_states)
1225
+ hidden_states = residual + hidden_states
1226
+
1227
+ outputs = (hidden_states,)
1228
+
1229
+ if output_attentions:
1230
+ outputs += (self_attn_weights,)
1231
+
1232
+ if use_cache:
1233
+ outputs += (present_key_value,)
1234
+
1235
+ return outputs
1236
+
1237
+
1238
+ AXK1_START_DOCSTRING = r"""
1239
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1240
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1241
+ etc.)
1242
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1243
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1244
+ and behavior.
1245
+ Parameters:
1246
+ config ([`AXK1Config`]):
1247
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1248
+ load the weights associated with the model, only the configuration. Check out the
1249
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1250
+ """
1251
+
1252
+
1253
+ @add_start_docstrings(
1254
+ "The bare AXK1 Model outputting raw hidden-states without any specific head on top.",
1255
+ AXK1_START_DOCSTRING,
1256
+ )
1257
+ class AXK1PreTrainedModel(PreTrainedModel):
1258
+ config_class = AXK1Config
1259
+ base_model_prefix = "model"
1260
+ supports_gradient_checkpointing = True
1261
+ _no_split_modules = ["AXK1DecoderLayer"]
1262
+ _skip_keys_device_placement = "past_key_values"
1263
+ _supports_flash_attn_2 = True
1264
+ _supports_cache_class = True
1265
+
1266
+ def _init_weights(self, module):
1267
+ std = self.config.initializer_range
1268
+ if isinstance(module, nn.Linear):
1269
+ module.weight.data.normal_(mean=0.0, std=std)
1270
+ if module.bias is not None:
1271
+ module.bias.data.zero_()
1272
+ elif isinstance(module, nn.Embedding):
1273
+ module.weight.data.normal_(mean=0.0, std=std)
1274
+ if module.padding_idx is not None:
1275
+ module.weight.data[module.padding_idx].zero_()
1276
+
1277
+
1278
+ AXK1_INPUTS_DOCSTRING = r"""
1279
+ Args:
1280
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1281
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1282
+ it.
1283
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1284
+ [`PreTrainedTokenizer.__call__`] for details.
1285
+ [What are input IDs?](../glossary#input-ids)
1286
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1287
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1288
+ - 1 for tokens that are **not masked**,
1289
+ - 0 for tokens that are **masked**.
1290
+ [What are attention masks?](../glossary#attention-mask)
1291
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1292
+ [`PreTrainedTokenizer.__call__`] for details.
1293
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1294
+ `past_key_values`).
1295
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1296
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1297
+ information on the default strategy.
1298
+ - 1 indicates the head is **not masked**,
1299
+ - 0 indicates the head is **masked**.
1300
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1301
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1302
+ config.n_positions - 1]`.
1303
+ [What are position IDs?](../glossary#position-ids)
1304
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1305
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1306
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1307
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1308
+ Two formats are allowed:
1309
+ - a [`~cache_utils.Cache`] instance;
1310
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1311
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1312
+ cache format.
1313
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1314
+ legacy cache format will be returned.
1315
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1316
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1317
+ of shape `(batch_size, sequence_length)`.
1318
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1319
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1320
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1321
+ model's internal embedding lookup matrix.
1322
+ use_cache (`bool`, *optional*):
1323
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1324
+ `past_key_values`).
1325
+ output_attentions (`bool`, *optional*):
1326
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1327
+ tensors for more detail.
1328
+ output_hidden_states (`bool`, *optional*):
1329
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1330
+ more detail.
1331
+ return_dict (`bool`, *optional*):
1332
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1333
+ """
1334
+
1335
+
1336
+ @add_start_docstrings(
1337
+ "The bare AXK1 Model outputting raw hidden-states without any specific head on top.",
1338
+ AXK1_START_DOCSTRING,
1339
+ )
1340
+ class AXK1Model(AXK1PreTrainedModel):
1341
+ """
1342
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`AXK1DecoderLayer`]
1343
+ Args:
1344
+ config: AXK1Config
1345
+ """
1346
+
1347
+ def __init__(self, config: AXK1Config):
1348
+ super().__init__(config)
1349
+ self.padding_idx = config.pad_token_id
1350
+ self.vocab_size = config.vocab_size
1351
+
1352
+ self.embed_tokens = nn.Embedding(
1353
+ config.vocab_size, config.hidden_size, self.padding_idx
1354
+ )
1355
+ self.layers = nn.ModuleList(
1356
+ [
1357
+ AXK1DecoderLayer(config, layer_idx)
1358
+ for layer_idx in range(config.num_hidden_layers)
1359
+ ]
1360
+ )
1361
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1362
+ self.norm = AXK1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1363
+
1364
+ self.gradient_checkpointing = False
1365
+ # Initialize weights and apply final processing
1366
+ self.post_init()
1367
+
1368
+ def get_input_embeddings(self):
1369
+ return self.embed_tokens
1370
+
1371
+ def set_input_embeddings(self, value):
1372
+ self.embed_tokens = value
1373
+
1374
+ @add_start_docstrings_to_model_forward(AXK1_INPUTS_DOCSTRING)
1375
+ def forward(
1376
+ self,
1377
+ input_ids: torch.LongTensor = None,
1378
+ attention_mask: Optional[torch.Tensor] = None,
1379
+ position_ids: Optional[torch.LongTensor] = None,
1380
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1381
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1382
+ use_cache: Optional[bool] = None,
1383
+ output_attentions: Optional[bool] = None,
1384
+ output_hidden_states: Optional[bool] = None,
1385
+ return_dict: Optional[bool] = None,
1386
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1387
+ output_attentions = (
1388
+ output_attentions
1389
+ if output_attentions is not None
1390
+ else self.config.output_attentions
1391
+ )
1392
+ output_hidden_states = (
1393
+ output_hidden_states
1394
+ if output_hidden_states is not None
1395
+ else self.config.output_hidden_states
1396
+ )
1397
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1398
+
1399
+ return_dict = (
1400
+ return_dict if return_dict is not None else self.config.use_return_dict
1401
+ )
1402
+
1403
+ # retrieve input_ids and inputs_embeds
1404
+ if input_ids is not None and inputs_embeds is not None:
1405
+ raise ValueError(
1406
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1407
+ )
1408
+ elif input_ids is not None:
1409
+ batch_size, seq_length = input_ids.shape[:2]
1410
+ elif inputs_embeds is not None:
1411
+ batch_size, seq_length = inputs_embeds.shape[:2]
1412
+ else:
1413
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1414
+
1415
+ past_key_values_length = 0
1416
+ if use_cache:
1417
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1418
+ if use_legacy_cache:
1419
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1420
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1421
+
1422
+ if position_ids is None:
1423
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1424
+ position_ids = torch.arange(
1425
+ past_key_values_length,
1426
+ seq_length + past_key_values_length,
1427
+ dtype=torch.long,
1428
+ device=device,
1429
+ )
1430
+ position_ids = position_ids.unsqueeze(0)
1431
+
1432
+ if inputs_embeds is None:
1433
+ inputs_embeds = self.embed_tokens(input_ids)
1434
+
1435
+ if self._use_flash_attention_2:
1436
+ # 2d mask is passed through the layers
1437
+ attention_mask = (
1438
+ attention_mask
1439
+ if (attention_mask is not None and 0 in attention_mask)
1440
+ else None
1441
+ )
1442
+ else:
1443
+ # 4d mask is passed through the layers
1444
+ attention_mask = _prepare_4d_causal_attention_mask(
1445
+ attention_mask,
1446
+ (batch_size, seq_length),
1447
+ inputs_embeds,
1448
+ past_key_values_length,
1449
+ )
1450
+
1451
+ # embed positions
1452
+ hidden_states = inputs_embeds
1453
+
1454
+ # decoder layers
1455
+ all_hidden_states = () if output_hidden_states else None
1456
+ all_self_attns = () if output_attentions else None
1457
+ next_decoder_cache = None
1458
+
1459
+ for decoder_layer in self.layers:
1460
+ if output_hidden_states:
1461
+ all_hidden_states += (hidden_states,)
1462
+
1463
+ layer_outputs = decoder_layer(
1464
+ hidden_states,
1465
+ attention_mask=attention_mask,
1466
+ position_ids=position_ids,
1467
+ past_key_value=past_key_values,
1468
+ output_attentions=output_attentions,
1469
+ use_cache=use_cache,
1470
+ )
1471
+
1472
+ hidden_states = layer_outputs[0]
1473
+
1474
+ if use_cache:
1475
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1476
+
1477
+ if output_attentions:
1478
+ all_self_attns += (layer_outputs[1],)
1479
+
1480
+ hidden_states = self.norm(hidden_states)
1481
+
1482
+ # add hidden states from the last decoder layer
1483
+ if output_hidden_states:
1484
+ all_hidden_states += (hidden_states,)
1485
+
1486
+ next_cache = None
1487
+ if use_cache:
1488
+ next_cache = (
1489
+ next_decoder_cache.to_legacy_cache()
1490
+ if use_legacy_cache
1491
+ else next_decoder_cache
1492
+ )
1493
+ if not return_dict:
1494
+ return tuple(
1495
+ v
1496
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1497
+ if v is not None
1498
+ )
1499
+ return BaseModelOutputWithPast(
1500
+ last_hidden_state=hidden_states,
1501
+ past_key_values=next_cache,
1502
+ hidden_states=all_hidden_states,
1503
+ attentions=all_self_attns,
1504
+ )
1505
+
1506
+
1507
+ class AXK1ForCausalLM(AXK1PreTrainedModel):
1508
+ _tied_weights_keys = ["lm_head.weight"]
1509
+
1510
+ def __init__(self, config):
1511
+ super().__init__(config)
1512
+ self.model = AXK1Model(config)
1513
+ self.vocab_size = config.vocab_size
1514
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1515
+
1516
+ # Initialize weights and apply final processing
1517
+ self.post_init()
1518
+
1519
+ def get_input_embeddings(self):
1520
+ return self.model.embed_tokens
1521
+
1522
+ def set_input_embeddings(self, value):
1523
+ self.model.embed_tokens = value
1524
+
1525
+ def get_output_embeddings(self):
1526
+ return self.lm_head
1527
+
1528
+ def set_output_embeddings(self, new_embeddings):
1529
+ self.lm_head = new_embeddings
1530
+
1531
+ def set_decoder(self, decoder):
1532
+ self.model = decoder
1533
+
1534
+ def get_decoder(self):
1535
+ return self.model
1536
+
1537
+ @add_start_docstrings_to_model_forward(AXK1_INPUTS_DOCSTRING)
1538
+ @replace_return_docstrings(
1539
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1540
+ )
1541
+ def forward(
1542
+ self,
1543
+ input_ids: torch.LongTensor = None,
1544
+ attention_mask: Optional[torch.Tensor] = None,
1545
+ position_ids: Optional[torch.LongTensor] = None,
1546
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1547
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1548
+ labels: Optional[torch.LongTensor] = None,
1549
+ use_cache: Optional[bool] = None,
1550
+ output_attentions: Optional[bool] = None,
1551
+ output_hidden_states: Optional[bool] = None,
1552
+ return_dict: Optional[bool] = None,
1553
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1554
+ r"""
1555
+ Args:
1556
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1557
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers.,
1558
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1559
+ (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`.
1560
+ Returns:
1561
+ Example:
1562
+ ```python
1563
+ >>> from transformers import AutoTokenizer, AXK1ForCausalLM
1564
+ >>> model = AXK1ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1565
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1566
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1567
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1568
+ >>> # Generate
1569
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1570
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1571
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1572
+ ```"""
1573
+ output_attentions = (
1574
+ output_attentions
1575
+ if output_attentions is not None
1576
+ else self.config.output_attentions
1577
+ )
1578
+ output_hidden_states = (
1579
+ output_hidden_states
1580
+ if output_hidden_states is not None
1581
+ else self.config.output_hidden_states
1582
+ )
1583
+ return_dict = (
1584
+ return_dict if return_dict is not None else self.config.use_return_dict
1585
+ )
1586
+
1587
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1588
+ outputs = self.model(
1589
+ input_ids=input_ids,
1590
+ attention_mask=attention_mask,
1591
+ position_ids=position_ids,
1592
+ past_key_values=past_key_values,
1593
+ inputs_embeds=inputs_embeds,
1594
+ use_cache=use_cache,
1595
+ output_attentions=output_attentions,
1596
+ output_hidden_states=output_hidden_states,
1597
+ return_dict=return_dict,
1598
+ )
1599
+
1600
+ hidden_states = outputs[0]
1601
+ logits = self.lm_head(hidden_states)
1602
+ logits = logits.float()
1603
+
1604
+ loss = None
1605
+ if labels is not None:
1606
+ # Shift so that tokens < n predict n
1607
+ shift_logits = logits[..., :-1, :].contiguous()
1608
+ shift_labels = labels[..., 1:].contiguous()
1609
+ # Flatten the tokens
1610
+ loss_fct = CrossEntropyLoss()
1611
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1612
+ shift_labels = shift_labels.view(-1)
1613
+ # Enable model parallelism
1614
+ shift_labels = shift_labels.to(shift_logits.device)
1615
+ loss = loss_fct(shift_logits, shift_labels)
1616
+
1617
+ if not return_dict:
1618
+ output = (logits,) + outputs[1:]
1619
+ return (loss,) + output if loss is not None else output
1620
+
1621
+ return CausalLMOutputWithPast(
1622
+ loss=loss,
1623
+ logits=logits,
1624
+ past_key_values=outputs.past_key_values,
1625
+ hidden_states=outputs.hidden_states,
1626
+ attentions=outputs.attentions,
1627
+ )
1628
+
1629
+ def prepare_inputs_for_generation(
1630
+ self,
1631
+ input_ids,
1632
+ past_key_values=None,
1633
+ attention_mask=None,
1634
+ inputs_embeds=None,
1635
+ **kwargs,
1636
+ ):
1637
+ if past_key_values is not None:
1638
+ if isinstance(past_key_values, Cache):
1639
+ cache_length = past_key_values.get_seq_length()
1640
+ past_length = past_key_values.seen_tokens
1641
+ max_cache_length = past_key_values.get_max_length()
1642
+ else:
1643
+ cache_length = past_length = past_key_values[0][0].shape[2]
1644
+ max_cache_length = None
1645
+
1646
+ # Keep only the unprocessed tokens:
1647
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1648
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1649
+ # input)
1650
+ if (
1651
+ attention_mask is not None
1652
+ and attention_mask.shape[1] > input_ids.shape[1]
1653
+ ):
1654
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1655
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1656
+ # input_ids based on the past_length.
1657
+ elif past_length < input_ids.shape[1]:
1658
+ input_ids = input_ids[:, past_length:]
1659
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1660
+
1661
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1662
+ if (
1663
+ max_cache_length is not None
1664
+ and attention_mask is not None
1665
+ and cache_length + input_ids.shape[1] > max_cache_length
1666
+ ):
1667
+ attention_mask = attention_mask[:, -max_cache_length:]
1668
+
1669
+ position_ids = kwargs.get("position_ids", None)
1670
+ if attention_mask is not None and position_ids is None:
1671
+ # create position_ids on the fly for batch generation
1672
+ position_ids = attention_mask.long().cumsum(-1) - 1
1673
+ position_ids.masked_fill_(attention_mask == 0, 1)
1674
+ if past_key_values:
1675
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1676
+
1677
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1678
+ if inputs_embeds is not None and past_key_values is None:
1679
+ model_inputs = {"inputs_embeds": inputs_embeds}
1680
+ else:
1681
+ model_inputs = {"input_ids": input_ids}
1682
+
1683
+ model_inputs.update(
1684
+ {
1685
+ "position_ids": position_ids,
1686
+ "past_key_values": past_key_values,
1687
+ "use_cache": kwargs.get("use_cache"),
1688
+ "attention_mask": attention_mask,
1689
+ }
1690
+ )
1691
+ return model_inputs
1692
+
1693
+ @staticmethod
1694
+ def _reorder_cache(past_key_values, beam_idx):
1695
+ reordered_past = ()
1696
+ for layer_past in past_key_values:
1697
+ reordered_past += (
1698
+ tuple(
1699
+ past_state.index_select(0, beam_idx.to(past_state.device))
1700
+ for past_state in layer_past
1701
+ ),
1702
+ )
1703
+ return reordered_past
1704
+
1705
+
1706
+ @add_start_docstrings(
1707
+ """
1708
+ The AXK1 Model transformer with a sequence classification head on top (linear layer).
1709
+ [`AXK1ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1710
+ (e.g. GPT-2) do.
1711
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1712
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1713
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1714
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1715
+ each row of the batch).
1716
+ """,
1717
+ AXK1_START_DOCSTRING,
1718
+ )
1719
+ class AXK1ForSequenceClassification(AXK1PreTrainedModel):
1720
+ def __init__(self, config):
1721
+ super().__init__(config)
1722
+ self.num_labels = config.num_labels
1723
+ self.model = AXK1Model(config)
1724
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1725
+
1726
+ # Initialize weights and apply final processing
1727
+ self.post_init()
1728
+
1729
+ def get_input_embeddings(self):
1730
+ return self.model.embed_tokens
1731
+
1732
+ def set_input_embeddings(self, value):
1733
+ self.model.embed_tokens = value
1734
+
1735
+ @add_start_docstrings_to_model_forward(AXK1_INPUTS_DOCSTRING)
1736
+ def forward(
1737
+ self,
1738
+ input_ids: torch.LongTensor = None,
1739
+ attention_mask: Optional[torch.Tensor] = None,
1740
+ position_ids: Optional[torch.LongTensor] = None,
1741
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1742
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1743
+ labels: Optional[torch.LongTensor] = None,
1744
+ use_cache: Optional[bool] = None,
1745
+ output_attentions: Optional[bool] = None,
1746
+ output_hidden_states: Optional[bool] = None,
1747
+ return_dict: Optional[bool] = None,
1748
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1749
+ r"""
1750
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1751
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers.,
1752
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1753
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1754
+ """
1755
+ return_dict = (
1756
+ return_dict if return_dict is not None else self.config.use_return_dict
1757
+ )
1758
+
1759
+ transformer_outputs = self.model(
1760
+ input_ids,
1761
+ attention_mask=attention_mask,
1762
+ position_ids=position_ids,
1763
+ past_key_values=past_key_values,
1764
+ inputs_embeds=inputs_embeds,
1765
+ use_cache=use_cache,
1766
+ output_attentions=output_attentions,
1767
+ output_hidden_states=output_hidden_states,
1768
+ return_dict=return_dict,
1769
+ )
1770
+ hidden_states = transformer_outputs[0]
1771
+ logits = self.score(hidden_states)
1772
+
1773
+ if input_ids is not None:
1774
+ batch_size = input_ids.shape[0]
1775
+ else:
1776
+ batch_size = inputs_embeds.shape[0]
1777
+
1778
+ if self.config.pad_token_id is None and batch_size != 1:
1779
+ raise ValueError(
1780
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1781
+ )
1782
+ if self.config.pad_token_id is None:
1783
+ sequence_lengths = -1
1784
+ else:
1785
+ if input_ids is not None:
1786
+ sequence_lengths = (
1787
+ torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1788
+ ).to(logits.device)
1789
+ else:
1790
+ sequence_lengths = -1
1791
+
1792
+ pooled_logits = logits[
1793
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1794
+ ]
1795
+
1796
+ loss = None
1797
+ if labels is not None:
1798
+ labels = labels.to(logits.device)
1799
+ if self.config.problem_type is None:
1800
+ if self.num_labels == 1:
1801
+ self.config.problem_type = "regression"
1802
+ elif self.num_labels > 1 and (
1803
+ labels.dtype == torch.long or labels.dtype == torch.int
1804
+ ):
1805
+ self.config.problem_type = "single_label_classification"
1806
+ else:
1807
+ self.config.problem_type = "multi_label_classification"
1808
+
1809
+ if self.config.problem_type == "regression":
1810
+ loss_fct = MSELoss()
1811
+ if self.num_labels == 1:
1812
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1813
+ else:
1814
+ loss = loss_fct(pooled_logits, labels)
1815
+ elif self.config.problem_type == "single_label_classification":
1816
+ loss_fct = CrossEntropyLoss()
1817
+ loss = loss_fct(
1818
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1819
+ )
1820
+ elif self.config.problem_type == "multi_label_classification":
1821
+ loss_fct = BCEWithLogitsLoss()
1822
+ loss = loss_fct(pooled_logits, labels)
1823
+ if not return_dict:
1824
+ output = (pooled_logits,) + transformer_outputs[1:]
1825
+ return ((loss,) + output) if loss is not None else output
1826
+
1827
+ return SequenceClassifierOutputWithPast(
1828
+ loss=loss,
1829
+ logits=pooled_logits,
1830
+ past_key_values=transformer_outputs.past_key_values,
1831
+ hidden_states=transformer_outputs.hidden_states,
1832
+ attentions=transformer_outputs.attentions,
1833
+ )