onkarpandit-g42 commited on
Commit
0cb2bdc
1 Parent(s): cb1ad09

Upload modeling_jais.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_jais.py +1600 -0
modeling_jais.py ADDED
@@ -0,0 +1,1600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The OpenAI Team Authors and HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ # Copyright 2023 Cerebras Systems.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ PyTorch JAIS model."""
18
+
19
+ import math
20
+ import os
21
+ import warnings
22
+ from typing import Optional, Tuple, Union
23
+
24
+ import torch
25
+ from torch import Tensor, nn
26
+ from torch.cuda.amp import autocast
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from transformers.modeling_utils import PreTrainedModel
38
+ from transformers.pytorch_utils import Conv1D, find_pruneable_heads_and_indices, prune_conv1d_layer
39
+ from transformers.utils import (
40
+ add_code_sample_docstrings,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ )
45
+ from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
46
+ from .configuration_jais import JAISConfig
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+ _CHECKPOINT_FOR_DOC = "core42/jais-13b"
52
+ _CONFIG_FOR_DOC = "JAISConfig"
53
+
54
+
55
+ class SwiGLUActivation(nn.Module):
56
+ def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
57
+ return x1 * nn.functional.silu(x2)
58
+
59
+
60
+ class AlibiPositionEmbeddingLayer(nn.Module):
61
+ def __init__(self, num_heads, alibi_scaling=None):
62
+ super(AlibiPositionEmbeddingLayer, self).__init__()
63
+
64
+ self.num_heads = num_heads
65
+ self.alibi_scaling = alibi_scaling
66
+ slopes = torch.tensor(AlibiPositionEmbeddingLayer._get_alibi_slopes(num_heads)).unsqueeze(-1)
67
+ self.slopes = nn.parameter.Parameter(slopes, requires_grad=False)
68
+
69
+ def forward(
70
+ self,
71
+ seq_length,
72
+ key_length,
73
+ cached_qk_len,
74
+ ):
75
+ context_position = torch.arange(
76
+ cached_qk_len, cached_qk_len + seq_length, device=self.slopes.device
77
+ )[:, None]
78
+ memory_position = torch.arange(
79
+ key_length + cached_qk_len, device=self.slopes.device
80
+ )[None, :]
81
+ relative_position = memory_position - context_position
82
+ relative_position = torch.abs(relative_position).unsqueeze(0).expand(self.num_heads, -1, -1)
83
+
84
+ if self.alibi_scaling is None:
85
+ scale = 1.0
86
+ elif self.alibi_scaling.get("factor") is not None:
87
+ scale = self.alibi_scaling["factor"]
88
+ elif relative_position.shape[-1] > self.alibi_scaling["train_seq_len"]:
89
+ scale = relative_position.shape[-1] / self.alibi_scaling["train_seq_len"]
90
+ else:
91
+ scale = 1.0
92
+
93
+ alibi = (self.slopes / -scale).unsqueeze(1) * relative_position
94
+ return alibi
95
+
96
+ @staticmethod
97
+ def _get_alibi_slopes(n):
98
+ def get_slopes_power_of_2(n):
99
+ start = 2 ** (-(2 ** -(math.log2(n) - 3)))
100
+ ratio = start
101
+ return [start * ratio**i for i in range(n)]
102
+
103
+ if math.log2(n).is_integer():
104
+ return get_slopes_power_of_2(
105
+ n
106
+ ) # In the paper, we only train models that have 2^a heads for some a. This function has
107
+ else: # some good properties that only occur when the input is a power of 2. To maintain that even
108
+ closest_power_of_2 = 2 ** math.floor(
109
+ math.log2(n)
110
+ ) # when the number of heads is not a power of 2, we use this workaround.
111
+ return (
112
+ get_slopes_power_of_2(closest_power_of_2)
113
+ + AlibiPositionEmbeddingLayer._get_alibi_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2]
114
+ )
115
+
116
+
117
+ def load_tf_weights_in_jais(model, config, jais_checkpoint_path):
118
+ """Load tf checkpoints in a pytorch model"""
119
+ try:
120
+ import re
121
+
122
+ import tensorflow as tf
123
+ except ImportError:
124
+ logger.error(
125
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
126
+ "https://www.tensorflow.org/install/ for installation instructions."
127
+ )
128
+ raise
129
+ tf_path = os.path.abspath(jais_checkpoint_path)
130
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
131
+ # Load weights from TF model
132
+ init_vars = tf.train.list_variables(tf_path)
133
+ names = []
134
+ arrays = []
135
+ for name, shape in init_vars:
136
+ logger.info(f"Loading TF weight {name} with shape {shape}")
137
+ array = tf.train.load_variable(tf_path, name)
138
+ names.append(name)
139
+ arrays.append(array.squeeze())
140
+
141
+ for name, array in zip(names, arrays):
142
+ name = name[6:] # skip "model/"
143
+ name = name.split("/")
144
+ pointer = model
145
+ for m_name in name:
146
+ if re.fullmatch(r"[A-Za-z]+\d+", m_name):
147
+ scope_names = re.split(r"(\d+)", m_name)
148
+ else:
149
+ scope_names = [m_name]
150
+ if scope_names[0] == "w" or scope_names[0] == "g":
151
+ pointer = getattr(pointer, "weight")
152
+ elif scope_names[0] == "b":
153
+ pointer = getattr(pointer, "bias")
154
+ elif scope_names[0] == "wpe" or scope_names[0] == "wte":
155
+ pointer = getattr(pointer, scope_names[0])
156
+ pointer = getattr(pointer, "weight")
157
+ else:
158
+ pointer = getattr(pointer, scope_names[0])
159
+ if len(scope_names) >= 2:
160
+ num = int(scope_names[1])
161
+ pointer = pointer[num]
162
+ try:
163
+ assert (
164
+ pointer.shape == array.shape
165
+ ), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
166
+ except AssertionError as e:
167
+ e.args += (pointer.shape, array.shape)
168
+ raise
169
+ logger.info(f"Initialize PyTorch weight {name}")
170
+ pointer.data = torch.from_numpy(array)
171
+ return model
172
+
173
+
174
+ class JAISAttention(nn.Module):
175
+ def __init__(self, config, is_cross_attention=False, layer_idx=None):
176
+ super().__init__()
177
+
178
+ max_positions = config.max_position_embeddings
179
+ self.register_buffer(
180
+ "bias",
181
+ torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
182
+ 1, 1, max_positions, max_positions
183
+ ),
184
+ persistent=False,
185
+ )
186
+ self.register_buffer("masked_bias", torch.tensor(-1e4), persistent=False)
187
+
188
+ self.embed_dim = config.hidden_size
189
+ self.num_heads = config.num_attention_heads
190
+ self.head_dim = self.embed_dim // self.num_heads
191
+ self.split_size = self.embed_dim
192
+ if self.head_dim * self.num_heads != self.embed_dim:
193
+ raise ValueError(
194
+ f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
195
+ f" {self.num_heads})."
196
+ )
197
+
198
+ self.scale_attn_weights = config.scale_attn_weights
199
+ self.is_cross_attention = is_cross_attention
200
+
201
+ # Layer-wise attention scaling, reordering, and upcasting
202
+ self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
203
+ self.layer_idx = layer_idx
204
+ self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
205
+
206
+ if self.is_cross_attention:
207
+ self.c_attn = Conv1D(2 * self.embed_dim, self.embed_dim)
208
+ self.q_attn = Conv1D(self.embed_dim, self.embed_dim)
209
+ else:
210
+ self.c_attn = Conv1D(3 * self.embed_dim, self.embed_dim)
211
+ self.c_proj = Conv1D(self.embed_dim, self.embed_dim)
212
+
213
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
214
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
215
+
216
+ self.pruned_heads = set()
217
+
218
+ self.attn_scale_power = 1.0 if config.mup_scale_qk_dot_by_d else 0.5
219
+
220
+ def prune_heads(self, heads):
221
+ if len(heads) == 0:
222
+ return
223
+ heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
224
+ index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
225
+
226
+ # Prune conv1d layers
227
+ self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
228
+ self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
229
+
230
+ # Update hyper params
231
+ self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
232
+ self.num_heads = self.num_heads - len(heads)
233
+ self.pruned_heads = self.pruned_heads.union(heads)
234
+
235
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
236
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
237
+
238
+ if self.scale_attn_weights:
239
+ attn_weights = attn_weights / torch.full(
240
+ [], value.size(-1) ** self.attn_scale_power, dtype=attn_weights.dtype, device=attn_weights.device
241
+ )
242
+
243
+ # Layer-wise attention scaling
244
+ if self.scale_attn_by_inverse_layer_idx:
245
+ attn_weights = attn_weights / float(self.layer_idx + 1)
246
+
247
+ if not self.is_cross_attention:
248
+ # if only "normal" attention layer implements causal mask
249
+ query_length, key_length = query.size(-2), key.size(-2)
250
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
251
+ mask_value = torch.finfo(attn_weights.dtype).min
252
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
253
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
254
+ mask_value = torch.full([], mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
255
+ attn_weights = torch.where(causal_mask, attn_weights.to(attn_weights.dtype), mask_value)
256
+
257
+ if attention_mask is not None:
258
+ # Apply the attention mask
259
+ attn_weights = attn_weights + attention_mask
260
+
261
+ if position_bias is not None:
262
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
263
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
264
+
265
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
266
+ attn_weights = attn_weights.type(value.dtype)
267
+ attn_weights = self.attn_dropout(attn_weights)
268
+
269
+ # Mask heads if we want to
270
+ if head_mask is not None:
271
+ attn_weights = attn_weights * head_mask
272
+
273
+ attn_output = torch.matmul(attn_weights, value)
274
+
275
+ return attn_output, attn_weights
276
+
277
+ def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None, position_bias=None):
278
+ # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
279
+ bsz, num_heads, q_seq_len, dk = query.size()
280
+ _, _, k_seq_len, _ = key.size()
281
+
282
+ # Preallocate attn_weights for `baddbmm`
283
+ attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
284
+
285
+ # Compute Scale Factor
286
+ scale_factor = 1.0
287
+ if self.scale_attn_weights:
288
+ scale_factor /= float(value.size(-1)) ** self.attn_scale_power
289
+
290
+ if self.scale_attn_by_inverse_layer_idx:
291
+ scale_factor /= float(self.layer_idx + 1)
292
+
293
+ # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
294
+ with autocast(enabled=False):
295
+ q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
296
+ attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
297
+ attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
298
+
299
+ if not self.is_cross_attention:
300
+ # if only "normal" attention layer implements causal mask
301
+ query_length, key_length = query.size(-2), key.size(-2)
302
+ causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length]
303
+ mask_value = torch.finfo(attn_weights.dtype).min
304
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
305
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
306
+ mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
307
+ attn_weights = torch.where(causal_mask, attn_weights, mask_value)
308
+
309
+ if attention_mask is not None:
310
+ # Apply the attention mask
311
+ attn_weights = attn_weights + attention_mask
312
+
313
+ if position_bias is not None:
314
+ attn_weights += position_bias.type_as(attn_weights).unsqueeze(0)
315
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
316
+
317
+ # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
318
+ if attn_weights.dtype != torch.float32:
319
+ raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
320
+ attn_weights = attn_weights.type(value.dtype)
321
+ attn_weights = self.attn_dropout(attn_weights)
322
+
323
+ # Mask heads if we want to
324
+ if head_mask is not None:
325
+ attn_weights = attn_weights * head_mask
326
+
327
+ attn_output = torch.matmul(attn_weights, value)
328
+
329
+ return attn_output, attn_weights
330
+
331
+ def _split_heads(self, tensor, num_heads, attn_head_size):
332
+ """
333
+ Splits hidden_size dim into attn_head_size and num_heads
334
+ """
335
+ new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
336
+ tensor = tensor.view(new_shape)
337
+ return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
338
+
339
+ def _merge_heads(self, tensor, num_heads, attn_head_size):
340
+ """
341
+ Merges attn_head_size dim and num_attn_heads dim into hidden_size
342
+ """
343
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
344
+ new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
345
+ return tensor.view(new_shape)
346
+
347
+ def forward(
348
+ self,
349
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
350
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
351
+ attention_mask: Optional[torch.FloatTensor] = None,
352
+ head_mask: Optional[torch.FloatTensor] = None,
353
+ encoder_hidden_states: Optional[torch.Tensor] = None,
354
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
355
+ use_cache: Optional[bool] = False,
356
+ output_attentions: Optional[bool] = False,
357
+ position_bias: Optional[torch.FloatTensor] = None,
358
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]], ...]:
359
+ if encoder_hidden_states is not None:
360
+ if not hasattr(self, "q_attn"):
361
+ raise ValueError(
362
+ "If class is used as cross attention, the weights `q_attn` have to be defined. "
363
+ "Please make sure to instantiate class with `JAISAttention(..., is_cross_attention=True)`."
364
+ )
365
+
366
+ query = self.q_attn(hidden_states)
367
+ key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
368
+ attention_mask = encoder_attention_mask
369
+ else:
370
+ query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
371
+
372
+ query = self._split_heads(query, self.num_heads, self.head_dim)
373
+ key = self._split_heads(key, self.num_heads, self.head_dim)
374
+ value = self._split_heads(value, self.num_heads, self.head_dim)
375
+
376
+ if layer_past is not None:
377
+ past_key, past_value = layer_past
378
+ key = torch.cat((past_key, key), dim=-2)
379
+ value = torch.cat((past_value, value), dim=-2)
380
+
381
+ if use_cache is True:
382
+ present = (key, value)
383
+ else:
384
+ present = None
385
+
386
+ if self.reorder_and_upcast_attn:
387
+ attn_output, attn_weights = self._upcast_and_reordered_attn(
388
+ query, key, value, attention_mask, head_mask, position_bias
389
+ )
390
+ else:
391
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask, position_bias)
392
+
393
+ attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
394
+ attn_output = self.c_proj(attn_output)
395
+ attn_output = self.resid_dropout(attn_output)
396
+
397
+ outputs = (attn_output, present)
398
+ if output_attentions:
399
+ outputs += (attn_weights,)
400
+
401
+ return outputs # a, present, (attentions)
402
+
403
+
404
+ class JAISMLP(nn.Module):
405
+ def __init__(self, intermediate_size, config):
406
+ super().__init__()
407
+ embed_dim = config.hidden_size
408
+ self.swiglu = config.activation_function == "swiglu"
409
+ self.c_fc = Conv1D(intermediate_size, embed_dim)
410
+ self.c_fc2 = Conv1D(intermediate_size, embed_dim) if self.swiglu else None
411
+ self.c_proj = Conv1D(embed_dim, intermediate_size)
412
+ self.act = SwiGLUActivation() if self.swiglu else ACT2FN[config.activation_function]
413
+ self.dropout = nn.Dropout(config.resid_pdrop)
414
+
415
+ def forward(self, hidden_states: Optional[Tuple[torch.FloatTensor]]) -> torch.FloatTensor:
416
+ if self.swiglu:
417
+ hidden_states2 = self.c_fc2(hidden_states)
418
+ hidden_states = self.c_fc(hidden_states)
419
+ hidden_states = self.act(hidden_states, hidden_states2) if self.swiglu else self.act(hidden_states)
420
+ hidden_states = self.c_proj(hidden_states)
421
+ hidden_states = self.dropout(hidden_states)
422
+ return hidden_states
423
+
424
+
425
+ class JAISBlock(nn.Module):
426
+ def __init__(self, config, layer_idx=None):
427
+ super().__init__()
428
+ hidden_size = config.hidden_size
429
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
430
+
431
+ self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
432
+ self.attn = JAISAttention(config, layer_idx=layer_idx)
433
+ self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
434
+
435
+ if config.add_cross_attention:
436
+ self.crossattention = JAISAttention(config, is_cross_attention=True, layer_idx=layer_idx)
437
+ self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
438
+
439
+ self.mlp = JAISMLP(inner_dim, config)
440
+
441
+ def forward(
442
+ self,
443
+ hidden_states: Optional[Tuple[torch.FloatTensor]],
444
+ layer_past: Optional[Tuple[torch.Tensor]] = None,
445
+ attention_mask: Optional[torch.FloatTensor] = None,
446
+ head_mask: Optional[torch.FloatTensor] = None,
447
+ encoder_hidden_states: Optional[torch.Tensor] = None,
448
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
449
+ use_cache: Optional[bool] = False,
450
+ output_attentions: Optional[bool] = False,
451
+ position_bias: Optional[torch.FloatTensor] = None,
452
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
453
+ residual = hidden_states
454
+ hidden_states = self.ln_1(hidden_states)
455
+ attn_outputs = self.attn(
456
+ hidden_states,
457
+ layer_past=layer_past,
458
+ attention_mask=attention_mask,
459
+ head_mask=head_mask,
460
+ use_cache=use_cache,
461
+ output_attentions=output_attentions,
462
+ position_bias=position_bias,
463
+ )
464
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
465
+ outputs = attn_outputs[1:]
466
+ # residual connection
467
+ hidden_states = attn_output + residual
468
+
469
+ if encoder_hidden_states is not None:
470
+ # add one self-attention block for cross-attention
471
+ if not hasattr(self, "crossattention"):
472
+ raise ValueError(
473
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
474
+ "cross-attention layers by setting `config.add_cross_attention=True`"
475
+ )
476
+ residual = hidden_states
477
+ hidden_states = self.ln_cross_attn(hidden_states)
478
+ cross_attn_outputs = self.crossattention(
479
+ hidden_states,
480
+ attention_mask=attention_mask,
481
+ head_mask=head_mask,
482
+ encoder_hidden_states=encoder_hidden_states,
483
+ encoder_attention_mask=encoder_attention_mask,
484
+ output_attentions=output_attentions,
485
+ position_bias=position_bias,
486
+ )
487
+ attn_output = cross_attn_outputs[0]
488
+ # residual connection
489
+ hidden_states = residual + attn_output
490
+ outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
491
+
492
+ residual = hidden_states
493
+ hidden_states = self.ln_2(hidden_states)
494
+ feed_forward_hidden_states = self.mlp(hidden_states)
495
+ # residual connection
496
+ hidden_states = residual + feed_forward_hidden_states
497
+
498
+ if use_cache:
499
+ outputs = (hidden_states,) + outputs
500
+ else:
501
+ outputs = (hidden_states,) + outputs[1:]
502
+
503
+ return outputs # hidden_states, present, (attentions, cross_attentions)
504
+
505
+
506
+ class JAISPreTrainedModel(PreTrainedModel):
507
+ """
508
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
509
+ models.
510
+ """
511
+
512
+ config_class = JAISConfig
513
+ load_tf_weights = load_tf_weights_in_jais
514
+ base_model_prefix = "transformer"
515
+ is_parallelizable = True
516
+ supports_gradient_checkpointing = True
517
+ _no_split_modules = ["JAISBlock"]
518
+ _skip_keys_device_placement = "past_key_values"
519
+
520
+ def __init__(self, *inputs, **kwargs):
521
+ super().__init__(*inputs, **kwargs)
522
+
523
+ def _init_weights(self, module):
524
+ """Initialize the weights."""
525
+ mup_init_scale = math.sqrt(self.config.mup_width_scale)
526
+ if isinstance(module, (nn.Linear, Conv1D)):
527
+ # Slightly different from the TF version which uses truncated_normal for initialization
528
+ # cf https://github.com/pytorch/pytorch/pull/5617
529
+ module.weight.data.normal_(mean=0.0, std=(self.config.initializer_range * mup_init_scale))
530
+ if module.bias is not None:
531
+ module.bias.data.zero_()
532
+ elif isinstance(module, nn.Embedding):
533
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
534
+ if module.padding_idx is not None:
535
+ module.weight.data[module.padding_idx].zero_()
536
+ elif isinstance(module, nn.LayerNorm):
537
+ module.bias.data.zero_()
538
+ module.weight.data.fill_(1.0)
539
+
540
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
541
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
542
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
543
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
544
+ #
545
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
546
+ for name, p in module.named_parameters():
547
+ if name == "c_proj.weight":
548
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
549
+ stddev = self.config.initializer_range * mup_init_scale / math.sqrt(2 * self.config.n_layer)
550
+ p.data.normal_(mean=0.0, std=stddev)
551
+
552
+ def _set_gradient_checkpointing(self, module, value=False):
553
+ if isinstance(module, JAISModel):
554
+ module.gradient_checkpointing = value
555
+
556
+ def get_mup_param_groups(self, lr, weight_decay=0.0, decoupled_wd=True):
557
+ """
558
+ Returns list of dicts defining parameter groups for muP:
559
+ group 0: most model params get scaled learning rate and weight decay.
560
+ group 1: embedding layer gets non-scaled learning rate and weight decay.
561
+ group 2: normalization layers and biases get non-scaled learning rate only.
562
+
563
+ The output can be passed to Adam-base optimizers
564
+ e.g.
565
+ param_groups = model.get_mup_param_groups(lr=1e-3, weight_decay=0.1)
566
+ torch.optim.AdamW(param_groups, betas=(0.9, 0.95), eps=1e-8)
567
+ """
568
+ norm_modules = (
569
+ torch.nn.LayerNorm,
570
+ torch.nn.BatchNorm1d,
571
+ torch.nn.BatchNorm2d,
572
+ torch.nn.BatchNorm3d,
573
+ torch.nn.InstanceNorm1d,
574
+ torch.nn.InstanceNorm2d,
575
+ torch.nn.InstanceNorm3d,
576
+ torch.nn.GroupNorm,
577
+ torch.nn.SyncBatchNorm,
578
+ torch.nn.LocalResponseNorm,
579
+ )
580
+
581
+ def get_group_index(param_name):
582
+ for name, module in self.named_modules():
583
+ if name in param_name:
584
+ if isinstance(module, norm_modules):
585
+ return 2
586
+ elif isinstance(module, torch.nn.Embedding):
587
+ return 1
588
+ return 0
589
+
590
+ width_scale = self.config.mup_width_scale
591
+ new_param_groups = []
592
+ new_param_groups.append({"params": [], "lr": lr * width_scale, "weight_decay": weight_decay})
593
+ if not decoupled_wd:
594
+ new_param_groups[0]["weight_decay"] /= width_scale
595
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": weight_decay})
596
+ new_param_groups.append({"params": [], "lr": lr, "weight_decay": 0.0})
597
+
598
+ for name, param in self.named_parameters():
599
+ if not param.requires_grad:
600
+ continue
601
+
602
+ if name.endswith("bias"):
603
+ new_param_groups[2]["params"].append(param)
604
+ else:
605
+ new_param_groups[get_group_index(name)]["params"].append(param)
606
+
607
+ for idx, param_group in enumerate(new_param_groups):
608
+ if len(param_group["params"]) == 0:
609
+ del new_param_groups[idx]
610
+
611
+ return new_param_groups
612
+
613
+
614
+ JAIS_START_DOCSTRING = r"""
615
+
616
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
617
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
618
+ etc.)
619
+
620
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
621
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
622
+ and behavior.
623
+
624
+ Parameters:
625
+ config ([`JAISConfig`]): Model configuration class with all the parameters of the model.
626
+ Initializing with a config file does not load the weights associated with the model, only the
627
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
628
+ """
629
+
630
+ JAIS_INPUTS_DOCSTRING = r"""
631
+ Args:
632
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
633
+ `input_ids_length` = `sequence_length` if `past_key_values` is `None` else
634
+ `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input
635
+ sequence tokens in the vocabulary.
636
+
637
+ If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
638
+ `input_ids`.
639
+
640
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
641
+ [`PreTrainedTokenizer.__call__`] for details.
642
+
643
+ [What are input IDs?](../glossary#input-ids)
644
+ past_key_values (`Tuple[Tuple[torch.Tensor]]` of length `config.n_layers`):
645
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
646
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
647
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
648
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
649
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
650
+
651
+ - 1 for tokens that are **not masked**,
652
+ - 0 for tokens that are **masked**.
653
+
654
+ If `past_key_values` is used, `attention_mask` needs to contain the masking strategy that was used for
655
+ `past_key_values`. In other words, the `attention_mask` always has to have the length:
656
+ `len(past_key_values) + len(input_ids)`
657
+
658
+ [What are attention masks?](../glossary#attention-mask)
659
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
660
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
661
+ 1]`:
662
+
663
+ - 0 corresponds to a *sentence A* token,
664
+ - 1 corresponds to a *sentence B* token.
665
+
666
+ [What are token type IDs?](../glossary#token-type-ids)
667
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
668
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
669
+ config.max_position_embeddings - 1]`.
670
+
671
+ [What are position IDs?](../glossary#position-ids)
672
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
673
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
674
+
675
+ - 1 indicates the head is **not masked**,
676
+ - 0 indicates the head is **masked**.
677
+
678
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
679
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
680
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
681
+ model's internal embedding lookup matrix.
682
+
683
+ If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
684
+ `past_key_values`).
685
+ use_cache (`bool`, *optional*):
686
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
687
+ `past_key_values`).
688
+ output_attentions (`bool`, *optional*):
689
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
690
+ tensors for more detail.
691
+ output_hidden_states (`bool`, *optional*):
692
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
693
+ more detail.
694
+ return_dict (`bool`, *optional*):
695
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
696
+ """
697
+ PARALLELIZE_DOCSTRING = r"""
698
+ This is an experimental feature and is a subject to change at a moment's notice.
699
+
700
+ Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
701
+ it will evenly distribute blocks across all devices.
702
+
703
+ Args:
704
+ device_map (`Dict[int, list]`, optional, defaults to None):
705
+ A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
706
+ automatically mapped to the first device (for esoteric reasons). That means that the first device should
707
+ have fewer attention modules mapped to it than other devices. For reference, the gpt2 models have the
708
+ following number of attention modules:
709
+
710
+ - gpt2: 12
711
+ - gpt2-medium: 24
712
+ - gpt2-large: 36
713
+ - gpt2-xl: 48
714
+
715
+ Example:
716
+
717
+ ```python
718
+ # Here is an example of a device map on a machine with 4 GPUs using gpt2-xl, which has a total of 48 attention modules:
719
+ model = GPT2LMHeadModel.from_pretrained("gpt2-xl")
720
+ device_map = {
721
+ 0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
722
+ 1: [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
723
+ 2: [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34],
724
+ 3: [35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47],
725
+ }
726
+ model.parallelize(device_map)
727
+ ```
728
+ """
729
+ DEPARALLELIZE_DOCSTRING = r"""
730
+ Moves the model to cpu from a model parallel state.
731
+
732
+ Example:
733
+
734
+ ```python
735
+ # On a 4 GPU machine with gpt2-large:
736
+ model = GPT2LMHeadModel.from_pretrained("gpt2-large")
737
+ device_map = {
738
+ 0: [0, 1, 2, 3, 4, 5, 6, 7],
739
+ 1: [8, 9, 10, 11, 12, 13, 14, 15],
740
+ 2: [16, 17, 18, 19, 20, 21, 22, 23],
741
+ 3: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35],
742
+ }
743
+ model.parallelize(device_map) # Splits the model across several devices
744
+ model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
745
+ ```
746
+ """
747
+
748
+
749
+ @add_start_docstrings(
750
+ "The bare JAIS Model transformer outputting raw hidden-states without any specific head on top.",
751
+ JAIS_START_DOCSTRING,
752
+ )
753
+ class JAISModel(JAISPreTrainedModel):
754
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
755
+ _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
756
+
757
+ def __init__(self, config):
758
+ super().__init__(config)
759
+
760
+ self.embed_dim = config.hidden_size
761
+
762
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
763
+ self.wpe = (
764
+ nn.Embedding(config.max_position_embeddings, self.embed_dim)
765
+ if config.position_embedding_type != "alibi"
766
+ else None
767
+ )
768
+ self.embeddings_scale = config.mup_embeddings_scale
769
+
770
+ self.drop = nn.Dropout(config.embd_pdrop)
771
+ self.h = nn.ModuleList([JAISBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
772
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
773
+
774
+ self.relative_pe = (
775
+ AlibiPositionEmbeddingLayer(config.num_attention_heads, config.alibi_scaling)
776
+ if config.position_embedding_type == "alibi"
777
+ else None
778
+ )
779
+
780
+ # Model parallel
781
+ self.model_parallel = False
782
+ self.device_map = None
783
+ self.gradient_checkpointing = False
784
+
785
+ # Initialize weights and apply final processing
786
+ self.post_init()
787
+
788
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
789
+ def parallelize(self, device_map=None):
790
+ # Check validity of device_map
791
+ warnings.warn(
792
+ "`JAISModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load your"
793
+ " model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
794
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'h.0': 0, 'h.1': 1,"
795
+ " ...}",
796
+ FutureWarning,
797
+ )
798
+ self.device_map = (
799
+ get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
800
+ )
801
+ assert_device_map(self.device_map, len(self.h))
802
+ self.model_parallel = True
803
+ self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
804
+ self.last_device = "cuda:" + str(max(self.device_map.keys()))
805
+ self.wte = self.wte.to(self.first_device)
806
+ if self.wpe is not None:
807
+ self.wpe = self.wpe.to(self.first_device)
808
+ # Load onto devices
809
+ for k, v in self.device_map.items():
810
+ for block in v:
811
+ cuda_device = "cuda:" + str(k)
812
+ self.h[block] = self.h[block].to(cuda_device)
813
+ # ln_f to last
814
+ self.ln_f = self.ln_f.to(self.last_device)
815
+
816
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
817
+ def deparallelize(self):
818
+ warnings.warn(
819
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
820
+ FutureWarning,
821
+ )
822
+ self.model_parallel = False
823
+ self.device_map = None
824
+ self.first_device = "cpu"
825
+ self.last_device = "cpu"
826
+ self.wte = self.wte.to("cpu")
827
+ if self.wpe is not None:
828
+ self.wpe = self.wpe.to("cpu")
829
+ for index in range(len(self.h)):
830
+ self.h[index] = self.h[index].to("cpu")
831
+ self.ln_f = self.ln_f.to("cpu")
832
+ torch.cuda.empty_cache()
833
+
834
+ def get_input_embeddings(self):
835
+ return self.wte
836
+
837
+ def set_input_embeddings(self, new_embeddings):
838
+ self.wte = new_embeddings
839
+
840
+ def _prune_heads(self, heads_to_prune):
841
+ """
842
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
843
+ """
844
+ for layer, heads in heads_to_prune.items():
845
+ self.h[layer].attn.prune_heads(heads)
846
+
847
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
848
+ @add_code_sample_docstrings(
849
+ checkpoint=_CHECKPOINT_FOR_DOC,
850
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
851
+ config_class=_CONFIG_FOR_DOC,
852
+ )
853
+ def forward(
854
+ self,
855
+ input_ids: Optional[torch.LongTensor] = None,
856
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
857
+ attention_mask: Optional[torch.FloatTensor] = None,
858
+ token_type_ids: Optional[torch.LongTensor] = None,
859
+ position_ids: Optional[torch.LongTensor] = None,
860
+ head_mask: Optional[torch.FloatTensor] = None,
861
+ inputs_embeds: Optional[torch.FloatTensor] = None,
862
+ encoder_hidden_states: Optional[torch.Tensor] = None,
863
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
864
+ use_cache: Optional[bool] = None,
865
+ output_attentions: Optional[bool] = None,
866
+ output_hidden_states: Optional[bool] = None,
867
+ return_dict: Optional[bool] = None,
868
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
869
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
870
+ output_hidden_states = (
871
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
872
+ )
873
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
874
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
875
+
876
+ if input_ids is not None and inputs_embeds is not None:
877
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
878
+ elif input_ids is not None:
879
+ input_shape = input_ids.size()
880
+ input_ids = input_ids.view(-1, input_shape[-1])
881
+ batch_size = input_ids.shape[0]
882
+ elif inputs_embeds is not None:
883
+ input_shape = inputs_embeds.size()[:-1]
884
+ batch_size = inputs_embeds.shape[0]
885
+ else:
886
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
887
+
888
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
889
+
890
+ if token_type_ids is not None:
891
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
892
+ if position_ids is not None:
893
+ position_ids = position_ids.view(-1, input_shape[-1])
894
+
895
+ if past_key_values is None:
896
+ past_length = 0
897
+ past_key_values = tuple([None] * len(self.h))
898
+ else:
899
+ past_length = past_key_values[0][0].size(-2)
900
+ if position_ids is None:
901
+ position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
902
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
903
+
904
+ # JAISAttention mask.
905
+ if attention_mask is not None:
906
+ if batch_size <= 0:
907
+ raise ValueError("batch_size has to be defined and > 0")
908
+ attention_mask = attention_mask.view(batch_size, -1)
909
+ # We create a 3D attention mask from a 2D tensor mask.
910
+ # Sizes are [batch_size, 1, 1, to_seq_length]
911
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
912
+ # this attention mask is more simple than the triangular masking of causal attention
913
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
914
+ attention_mask = attention_mask[:, None, None, :]
915
+
916
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
917
+ # masked positions, this operation will create a tensor which is 0.0 for
918
+ # positions we want to attend and the dtype's smallest value for masked positions.
919
+ # Since we are adding it to the raw scores before the softmax, this is
920
+ # effectively the same as removing these entirely.
921
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
922
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
923
+
924
+ # If a 2D or 3D attention mask is provided for the cross-attention
925
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
926
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
927
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
928
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
929
+ if encoder_attention_mask is None:
930
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
931
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
932
+ else:
933
+ encoder_attention_mask = None
934
+
935
+ # Prepare head mask if needed
936
+ # 1.0 in head_mask indicate we keep the head
937
+ # attention_probs has shape bsz x n_heads x N x N
938
+ # head_mask has shape n_layer x batch x n_heads x N x N
939
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
940
+
941
+ if inputs_embeds is None:
942
+ inputs_embeds = self.wte(input_ids)
943
+ if self.wpe is not None:
944
+ position_embeds = self.wpe(position_ids)
945
+ hidden_states = inputs_embeds + position_embeds
946
+ else:
947
+ hidden_states = inputs_embeds
948
+ hidden_states *= torch.tensor(
949
+ float(self.embeddings_scale), dtype=hidden_states.dtype, device=hidden_states.device
950
+ )
951
+
952
+ if token_type_ids is not None:
953
+ token_type_embeds = self.wte(token_type_ids)
954
+ hidden_states = hidden_states + token_type_embeds
955
+
956
+ hidden_states = self.drop(hidden_states)
957
+
958
+ if self.relative_pe is not None:
959
+ length = input_ids.shape[1]
960
+ cached_kv_length = 0
961
+ cached_kv = past_key_values[0]
962
+ if cached_kv is not None:
963
+ cached_kv_length = cached_kv[0].shape[-2]
964
+ position_bias = self.relative_pe(length, length, cached_kv_length)
965
+ else:
966
+ position_bias = None
967
+
968
+ output_shape = input_shape + (hidden_states.size(-1),)
969
+
970
+ if self.gradient_checkpointing and self.training:
971
+ if use_cache:
972
+ logger.warning_once(
973
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
974
+ )
975
+ use_cache = False
976
+
977
+ presents = () if use_cache else None
978
+ all_self_attentions = () if output_attentions else None
979
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
980
+ all_hidden_states = () if output_hidden_states else None
981
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
982
+ # Model parallel
983
+ if self.model_parallel:
984
+ torch.cuda.set_device(hidden_states.device)
985
+ # Ensure layer_past is on same device as hidden_states (might not be correct)
986
+ if layer_past is not None:
987
+ layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
988
+ # Ensure that attention_mask is always on the same device as hidden_states
989
+ if attention_mask is not None:
990
+ attention_mask = attention_mask.to(hidden_states.device)
991
+ if isinstance(head_mask, torch.Tensor):
992
+ head_mask = head_mask.to(hidden_states.device)
993
+ if output_hidden_states:
994
+ all_hidden_states = all_hidden_states + (hidden_states,)
995
+
996
+ if self.gradient_checkpointing and self.training:
997
+
998
+ def create_custom_forward(module):
999
+ def custom_forward(*inputs):
1000
+ # None for past_key_value
1001
+ return module(*inputs, use_cache, output_attentions)
1002
+
1003
+ return custom_forward
1004
+
1005
+ outputs = torch.utils.checkpoint.checkpoint(
1006
+ create_custom_forward(block),
1007
+ hidden_states,
1008
+ None,
1009
+ attention_mask,
1010
+ head_mask[i],
1011
+ encoder_hidden_states,
1012
+ encoder_attention_mask,
1013
+ )
1014
+ else:
1015
+ outputs = block(
1016
+ hidden_states,
1017
+ layer_past=layer_past,
1018
+ attention_mask=attention_mask,
1019
+ head_mask=head_mask[i],
1020
+ encoder_hidden_states=encoder_hidden_states,
1021
+ encoder_attention_mask=encoder_attention_mask,
1022
+ use_cache=use_cache,
1023
+ output_attentions=output_attentions,
1024
+ position_bias=position_bias,
1025
+ )
1026
+
1027
+ hidden_states = outputs[0]
1028
+ if use_cache is True:
1029
+ presents = presents + (outputs[1],)
1030
+
1031
+ if output_attentions:
1032
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
1033
+ if self.config.add_cross_attention:
1034
+ all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
1035
+
1036
+ # Model Parallel: If it's the last layer for that device, put things on the next device
1037
+ if self.model_parallel:
1038
+ for k, v in self.device_map.items():
1039
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
1040
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
1041
+
1042
+ hidden_states = self.ln_f(hidden_states)
1043
+
1044
+ hidden_states = hidden_states.view(output_shape)
1045
+ # Add last hidden state
1046
+ if output_hidden_states:
1047
+ all_hidden_states = all_hidden_states + (hidden_states,)
1048
+
1049
+ if not return_dict:
1050
+ return tuple(
1051
+ v
1052
+ for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
1053
+ if v is not None
1054
+ )
1055
+
1056
+ return BaseModelOutputWithPastAndCrossAttentions(
1057
+ last_hidden_state=hidden_states,
1058
+ past_key_values=presents,
1059
+ hidden_states=all_hidden_states,
1060
+ attentions=all_self_attentions,
1061
+ cross_attentions=all_cross_attentions,
1062
+ )
1063
+
1064
+
1065
+ @add_start_docstrings(
1066
+ """
1067
+ The JAIS Model transformer with a language modeling head on top (linear layer with weights tied to the input
1068
+ embeddings).
1069
+ """,
1070
+ JAIS_START_DOCSTRING,
1071
+ )
1072
+ class JAISLMHeadModel(JAISPreTrainedModel):
1073
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1074
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias"]
1075
+
1076
+ def __init__(self, config):
1077
+ super().__init__(config)
1078
+ self.transformer = JAISModel(config)
1079
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1080
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1081
+
1082
+ # Model parallel
1083
+ self.model_parallel = False
1084
+ self.device_map = None
1085
+
1086
+ # Initialize weights and apply final processing
1087
+ self.post_init()
1088
+
1089
+ @add_start_docstrings(PARALLELIZE_DOCSTRING)
1090
+ def parallelize(self, device_map=None):
1091
+ warnings.warn(
1092
+ "`JAISLMHeadModel.parallelize` is deprecated and will be removed in v5 of Transformers, you should load"
1093
+ " your model with `device_map='balanced'` in the call to `from_pretrained`. You can also provide your own"
1094
+ " `device_map` but it needs to be a dictionary module_name to device, so for instance {'transformer.h.0':"
1095
+ " 0, 'transformer.h.1': 1, ...}",
1096
+ FutureWarning,
1097
+ )
1098
+ self.device_map = (
1099
+ get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1100
+ if device_map is None
1101
+ else device_map
1102
+ )
1103
+ assert_device_map(self.device_map, len(self.transformer.h))
1104
+ self.transformer.parallelize(self.device_map)
1105
+ self.lm_head = self.lm_head.to(self.transformer.first_device)
1106
+ self.model_parallel = True
1107
+
1108
+ @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1109
+ def deparallelize(self):
1110
+ warnings.warn(
1111
+ "Like `parallelize`, `deparallelize` is deprecated and will be removed in v5 of Transformers.",
1112
+ FutureWarning,
1113
+ )
1114
+ self.transformer.deparallelize()
1115
+ self.transformer = self.transformer.to("cpu")
1116
+ self.lm_head = self.lm_head.to("cpu")
1117
+ self.model_parallel = False
1118
+ torch.cuda.empty_cache()
1119
+
1120
+ def get_output_embeddings(self):
1121
+ return self.lm_head
1122
+
1123
+ def set_output_embeddings(self, new_embeddings):
1124
+ self.lm_head = new_embeddings
1125
+
1126
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
1127
+ token_type_ids = kwargs.get("token_type_ids", None)
1128
+ # only last token for inputs_ids if past is defined in kwargs
1129
+ if past_key_values:
1130
+ input_ids = input_ids[:, -1].unsqueeze(-1)
1131
+ if token_type_ids is not None:
1132
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1133
+
1134
+ attention_mask = kwargs.get("attention_mask", None)
1135
+ position_ids = kwargs.get("position_ids", None)
1136
+
1137
+ if attention_mask is not None and position_ids is None:
1138
+ # create position_ids on the fly for batch generation
1139
+ position_ids = attention_mask.long().cumsum(-1) - 1
1140
+ position_ids.masked_fill_(attention_mask == 0, 1)
1141
+ if past_key_values:
1142
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1143
+ else:
1144
+ position_ids = None
1145
+
1146
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1147
+ if inputs_embeds is not None and past_key_values is None:
1148
+ model_inputs = {"inputs_embeds": inputs_embeds}
1149
+ else:
1150
+ model_inputs = {"input_ids": input_ids}
1151
+
1152
+ model_inputs.update(
1153
+ {
1154
+ "past_key_values": past_key_values,
1155
+ "use_cache": kwargs.get("use_cache"),
1156
+ "position_ids": position_ids,
1157
+ "attention_mask": attention_mask,
1158
+ "token_type_ids": token_type_ids,
1159
+ }
1160
+ )
1161
+ return model_inputs
1162
+
1163
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
1164
+ @add_code_sample_docstrings(
1165
+ checkpoint=_CHECKPOINT_FOR_DOC,
1166
+ output_type=CausalLMOutputWithCrossAttentions,
1167
+ config_class=_CONFIG_FOR_DOC,
1168
+ )
1169
+ def forward(
1170
+ self,
1171
+ input_ids: Optional[torch.LongTensor] = None,
1172
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1173
+ attention_mask: Optional[torch.FloatTensor] = None,
1174
+ token_type_ids: Optional[torch.LongTensor] = None,
1175
+ position_ids: Optional[torch.LongTensor] = None,
1176
+ head_mask: Optional[torch.FloatTensor] = None,
1177
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1178
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1179
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1180
+ labels: Optional[torch.LongTensor] = None,
1181
+ use_cache: Optional[bool] = None,
1182
+ output_attentions: Optional[bool] = None,
1183
+ output_hidden_states: Optional[bool] = None,
1184
+ return_dict: Optional[bool] = None,
1185
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1186
+ r"""
1187
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1188
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1189
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1190
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1191
+ """
1192
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1193
+
1194
+ transformer_outputs = self.transformer(
1195
+ input_ids,
1196
+ past_key_values=past_key_values,
1197
+ attention_mask=attention_mask,
1198
+ token_type_ids=token_type_ids,
1199
+ position_ids=position_ids,
1200
+ head_mask=head_mask,
1201
+ inputs_embeds=inputs_embeds,
1202
+ encoder_hidden_states=encoder_hidden_states,
1203
+ encoder_attention_mask=encoder_attention_mask,
1204
+ use_cache=use_cache,
1205
+ output_attentions=output_attentions,
1206
+ output_hidden_states=output_hidden_states,
1207
+ return_dict=return_dict,
1208
+ )
1209
+ hidden_states = transformer_outputs[0]
1210
+
1211
+ # Set device for model parallelism
1212
+ if self.model_parallel:
1213
+ torch.cuda.set_device(self.transformer.first_device)
1214
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
1215
+
1216
+ lm_logits = self.lm_head(hidden_states)
1217
+ lm_logits *= torch.tensor(float(self.output_logits_scale), dtype=lm_logits.dtype, device=lm_logits.device)
1218
+
1219
+ loss = None
1220
+ if labels is not None:
1221
+ # move labels to correct device to enable model parallelism
1222
+ labels = labels.to(lm_logits.device)
1223
+ # Shift so that tokens < n predict n
1224
+ shift_logits = lm_logits[..., :-1, :].contiguous()
1225
+ shift_labels = labels[..., 1:].contiguous()
1226
+ # Flatten the tokens
1227
+ loss_fct = CrossEntropyLoss()
1228
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1229
+
1230
+ if not return_dict:
1231
+ output = (lm_logits,) + transformer_outputs[1:]
1232
+ return ((loss,) + output) if loss is not None else output
1233
+
1234
+ return CausalLMOutputWithCrossAttentions(
1235
+ loss=loss,
1236
+ logits=lm_logits,
1237
+ past_key_values=transformer_outputs.past_key_values,
1238
+ hidden_states=transformer_outputs.hidden_states,
1239
+ attentions=transformer_outputs.attentions,
1240
+ cross_attentions=transformer_outputs.cross_attentions,
1241
+ )
1242
+
1243
+ @staticmethod
1244
+ def _reorder_cache(
1245
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
1246
+ ) -> Tuple[Tuple[torch.Tensor]]:
1247
+ """
1248
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
1249
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
1250
+ beam_idx at every generation step.
1251
+ """
1252
+ return tuple(
1253
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1254
+ for layer_past in past_key_values
1255
+ )
1256
+
1257
+
1258
+ @add_start_docstrings(
1259
+ """
1260
+ The JAIS Model transformer with a sequence classification head on top (linear layer).
1261
+
1262
+ [`JAISForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1263
+ (e.g. GPT-1) do.
1264
+
1265
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1266
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1267
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1268
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1269
+ each row of the batch).
1270
+ """,
1271
+ JAIS_START_DOCSTRING,
1272
+ )
1273
+ class JAISForSequenceClassification(JAISPreTrainedModel):
1274
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1275
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head.weight"]
1276
+
1277
+ def __init__(self, config):
1278
+ super().__init__(config)
1279
+ self.num_labels = config.num_labels
1280
+ self.transformer = JAISModel(config)
1281
+ self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1282
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1283
+
1284
+ # Model parallel
1285
+ self.model_parallel = False
1286
+ self.device_map = None
1287
+
1288
+ # Initialize weights and apply final processing
1289
+ self.post_init()
1290
+
1291
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
1292
+ @add_code_sample_docstrings(
1293
+ checkpoint="microsoft/DialogRPT-updown",
1294
+ output_type=SequenceClassifierOutputWithPast,
1295
+ config_class=_CONFIG_FOR_DOC,
1296
+ )
1297
+ def forward(
1298
+ self,
1299
+ input_ids: Optional[torch.LongTensor] = None,
1300
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1301
+ attention_mask: Optional[torch.FloatTensor] = None,
1302
+ token_type_ids: Optional[torch.LongTensor] = None,
1303
+ position_ids: Optional[torch.LongTensor] = None,
1304
+ head_mask: Optional[torch.FloatTensor] = None,
1305
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1306
+ labels: Optional[torch.LongTensor] = None,
1307
+ use_cache: Optional[bool] = None,
1308
+ output_attentions: Optional[bool] = None,
1309
+ output_hidden_states: Optional[bool] = None,
1310
+ return_dict: Optional[bool] = None,
1311
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1312
+ r"""
1313
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1314
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1315
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1316
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1317
+ """
1318
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1319
+
1320
+ transformer_outputs = self.transformer(
1321
+ input_ids,
1322
+ past_key_values=past_key_values,
1323
+ attention_mask=attention_mask,
1324
+ token_type_ids=token_type_ids,
1325
+ position_ids=position_ids,
1326
+ head_mask=head_mask,
1327
+ inputs_embeds=inputs_embeds,
1328
+ use_cache=use_cache,
1329
+ output_attentions=output_attentions,
1330
+ output_hidden_states=output_hidden_states,
1331
+ return_dict=return_dict,
1332
+ )
1333
+ hidden_states = transformer_outputs[0]
1334
+ logits = self.score(hidden_states)
1335
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1336
+
1337
+ if input_ids is not None:
1338
+ batch_size, sequence_length = input_ids.shape[:2]
1339
+ else:
1340
+ batch_size, sequence_length = inputs_embeds.shape[:2]
1341
+
1342
+ assert (
1343
+ self.config.pad_token_id is not None or batch_size == 1
1344
+ ), "Cannot handle batch sizes > 1 if no padding token is defined."
1345
+ if self.config.pad_token_id is None:
1346
+ sequence_lengths = -1
1347
+ else:
1348
+ if input_ids is not None:
1349
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1350
+ else:
1351
+ sequence_lengths = -1
1352
+ logger.warning(
1353
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1354
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1355
+ )
1356
+
1357
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1358
+
1359
+ loss = None
1360
+ if labels is not None:
1361
+ if self.config.problem_type is None:
1362
+ if self.num_labels == 1:
1363
+ self.config.problem_type = "regression"
1364
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1365
+ self.config.problem_type = "single_label_classification"
1366
+ else:
1367
+ self.config.problem_type = "multi_label_classification"
1368
+
1369
+ if self.config.problem_type == "regression":
1370
+ loss_fct = MSELoss()
1371
+ if self.num_labels == 1:
1372
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1373
+ else:
1374
+ loss = loss_fct(pooled_logits, labels)
1375
+ elif self.config.problem_type == "single_label_classification":
1376
+ loss_fct = CrossEntropyLoss()
1377
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1378
+ elif self.config.problem_type == "multi_label_classification":
1379
+ loss_fct = BCEWithLogitsLoss()
1380
+ loss = loss_fct(pooled_logits, labels)
1381
+ if not return_dict:
1382
+ output = (pooled_logits,) + transformer_outputs[1:]
1383
+ return ((loss,) + output) if loss is not None else output
1384
+
1385
+ return SequenceClassifierOutputWithPast(
1386
+ loss=loss,
1387
+ logits=pooled_logits,
1388
+ past_key_values=transformer_outputs.past_key_values,
1389
+ hidden_states=transformer_outputs.hidden_states,
1390
+ attentions=transformer_outputs.attentions,
1391
+ )
1392
+
1393
+
1394
+ @add_start_docstrings(
1395
+ """
1396
+ JAIS Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1397
+ Named-Entity-Recognition (NER) tasks.
1398
+ """,
1399
+ JAIS_START_DOCSTRING,
1400
+ )
1401
+ class JAISForTokenClassification(JAISPreTrainedModel):
1402
+ def __init__(self, config):
1403
+ super().__init__(config)
1404
+ self.num_labels = config.num_labels
1405
+
1406
+ self.transformer = JAISModel(config)
1407
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1408
+ classifier_dropout = config.classifier_dropout
1409
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1410
+ classifier_dropout = config.hidden_dropout
1411
+ else:
1412
+ classifier_dropout = 0.1
1413
+ self.dropout = nn.Dropout(classifier_dropout)
1414
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1415
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1416
+
1417
+ # Model parallel
1418
+ self.model_parallel = False
1419
+ self.device_map = None
1420
+
1421
+ # Initialize weights and apply final processing
1422
+ self.post_init()
1423
+
1424
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING)
1425
+ # fmt: off
1426
+ @add_code_sample_docstrings(
1427
+ checkpoint="brad1141/gpt2-finetuned-comp2",
1428
+ output_type=TokenClassifierOutput,
1429
+ config_class=_CONFIG_FOR_DOC,
1430
+ expected_loss=0.25,
1431
+ expected_output=["Lead", "Lead", "Lead", "Position", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead", "Lead"],
1432
+ )
1433
+ # fmt: on
1434
+ def forward(
1435
+ self,
1436
+ input_ids: Optional[torch.LongTensor] = None,
1437
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
1438
+ attention_mask: Optional[torch.FloatTensor] = None,
1439
+ token_type_ids: Optional[torch.LongTensor] = None,
1440
+ position_ids: Optional[torch.LongTensor] = None,
1441
+ head_mask: Optional[torch.FloatTensor] = None,
1442
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1443
+ labels: Optional[torch.LongTensor] = None,
1444
+ use_cache: Optional[bool] = None,
1445
+ output_attentions: Optional[bool] = None,
1446
+ output_hidden_states: Optional[bool] = None,
1447
+ return_dict: Optional[bool] = None,
1448
+ ) -> Union[Tuple, TokenClassifierOutput]:
1449
+ r"""
1450
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1451
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1452
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1453
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1454
+ """
1455
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1456
+
1457
+ transformer_outputs = self.transformer(
1458
+ input_ids,
1459
+ past_key_values=past_key_values,
1460
+ attention_mask=attention_mask,
1461
+ token_type_ids=token_type_ids,
1462
+ position_ids=position_ids,
1463
+ head_mask=head_mask,
1464
+ inputs_embeds=inputs_embeds,
1465
+ use_cache=use_cache,
1466
+ output_attentions=output_attentions,
1467
+ output_hidden_states=output_hidden_states,
1468
+ return_dict=return_dict,
1469
+ )
1470
+
1471
+ hidden_states = transformer_outputs[0]
1472
+ hidden_states = self.dropout(hidden_states)
1473
+ logits = self.classifier(hidden_states)
1474
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1475
+
1476
+ loss = None
1477
+ if labels is not None:
1478
+ labels = labels.to(logits.device)
1479
+ loss_fct = CrossEntropyLoss()
1480
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1481
+
1482
+ if not return_dict:
1483
+ output = (logits,) + transformer_outputs[2:]
1484
+ return ((loss,) + output) if loss is not None else output
1485
+
1486
+ return TokenClassifierOutput(
1487
+ loss=loss,
1488
+ logits=logits,
1489
+ hidden_states=transformer_outputs.hidden_states,
1490
+ attentions=transformer_outputs.attentions,
1491
+ )
1492
+
1493
+
1494
+ @add_start_docstrings(
1495
+ """
1496
+ The JAIS Model transformer with a span classification head on top for extractive question-answering tasks like
1497
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1498
+ """,
1499
+ JAIS_START_DOCSTRING,
1500
+ )
1501
+ class JAISForQuestionAnswering(JAISPreTrainedModel):
1502
+ _keys_to_ignore_on_load_unexpected = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"]
1503
+ _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"h\.\d+\.attn\.bias", r"lm_head.weight"]
1504
+
1505
+ def __init__(self, config):
1506
+ super().__init__(config)
1507
+ self.num_labels = config.num_labels
1508
+ self.transformer = JAISModel(config)
1509
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1510
+ self.output_logits_scale = config.mup_output_alpha * config.mup_width_scale
1511
+
1512
+ # Model parallel
1513
+ self.model_parallel = False
1514
+ self.device_map = None
1515
+ self.gradient_checkpointing = False
1516
+
1517
+ # Initialize weights and apply final processing
1518
+ self.post_init()
1519
+
1520
+ @add_start_docstrings_to_model_forward(JAIS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1521
+ @add_code_sample_docstrings(
1522
+ checkpoint=_CHECKPOINT_FOR_DOC,
1523
+ output_type=QuestionAnsweringModelOutput,
1524
+ config_class=_CONFIG_FOR_DOC,
1525
+ real_checkpoint=_CHECKPOINT_FOR_DOC,
1526
+ )
1527
+ def forward(
1528
+ self,
1529
+ input_ids: Optional[torch.LongTensor] = None,
1530
+ attention_mask: Optional[torch.FloatTensor] = None,
1531
+ token_type_ids: Optional[torch.LongTensor] = None,
1532
+ position_ids: Optional[torch.LongTensor] = None,
1533
+ head_mask: Optional[torch.FloatTensor] = None,
1534
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1535
+ start_positions: Optional[torch.LongTensor] = None,
1536
+ end_positions: Optional[torch.LongTensor] = None,
1537
+ output_attentions: Optional[bool] = None,
1538
+ output_hidden_states: Optional[bool] = None,
1539
+ return_dict: Optional[bool] = None,
1540
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1541
+ r"""
1542
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1543
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1544
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1545
+ are not taken into account for computing the loss.
1546
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1547
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1548
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1549
+ are not taken into account for computing the loss.
1550
+ """
1551
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1552
+
1553
+ outputs = self.transformer(
1554
+ input_ids,
1555
+ attention_mask=attention_mask,
1556
+ token_type_ids=token_type_ids,
1557
+ position_ids=position_ids,
1558
+ head_mask=head_mask,
1559
+ inputs_embeds=inputs_embeds,
1560
+ output_attentions=output_attentions,
1561
+ output_hidden_states=output_hidden_states,
1562
+ return_dict=return_dict,
1563
+ )
1564
+
1565
+ sequence_output = outputs[0]
1566
+
1567
+ logits = self.qa_outputs(sequence_output)
1568
+ logits *= torch.tensor(float(self.output_logits_scale), dtype=logits.dtype, device=logits.device)
1569
+ start_logits, end_logits = logits.split(1, dim=-1)
1570
+ start_logits = start_logits.squeeze(-1).contiguous()
1571
+ end_logits = end_logits.squeeze(-1).contiguous()
1572
+
1573
+ total_loss = None
1574
+ if start_positions is not None and end_positions is not None:
1575
+ # If we are on multi-GPU, split add a dimension
1576
+ if len(start_positions.size()) > 1:
1577
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1578
+ if len(end_positions.size()) > 1:
1579
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1580
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1581
+ ignored_index = start_logits.size(1)
1582
+ start_positions = start_positions.clamp(0, ignored_index)
1583
+ end_positions = end_positions.clamp(0, ignored_index)
1584
+
1585
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1586
+ start_loss = loss_fct(start_logits, start_positions)
1587
+ end_loss = loss_fct(end_logits, end_positions)
1588
+ total_loss = (start_loss + end_loss) / 2
1589
+
1590
+ if not return_dict:
1591
+ output = (start_logits, end_logits) + outputs[2:]
1592
+ return ((total_loss,) + output) if total_loss is not None else output
1593
+
1594
+ return QuestionAnsweringModelOutput(
1595
+ loss=total_loss,
1596
+ start_logits=start_logits,
1597
+ end_logits=end_logits,
1598
+ hidden_states=outputs.hidden_states,
1599
+ attentions=outputs.attentions,
1600
+ )