BAAI
/

hyxmmm commited on
Commit
d0204b5
1 Parent(s): ff6fe45

Upload modeling_aquiladense.py with huggingface_hub

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