qnguyen3 commited on
Commit
66bd4d0
1 Parent(s): 5da9f9f

Upload modelling_RW.py

Browse files
Files changed (1) hide show
  1. modelling_RW.py +1124 -0
modelling_RW.py ADDED
@@ -0,0 +1,1124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # port of models described in RW
2
+ # We use the bloom model as a starting point for these model.
3
+ # Please refer to the bloom models for usage instructions.
4
+
5
+ import math
6
+ import warnings
7
+ from typing import Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.utils.checkpoint
11
+ from torch import nn
12
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, LayerNorm, MSELoss
13
+ from torch.nn import functional as F
14
+
15
+ from transformers.modeling_outputs import (
16
+ BaseModelOutputWithPastAndCrossAttentions,
17
+ CausalLMOutputWithCrossAttentions,
18
+ QuestionAnsweringModelOutput,
19
+ SequenceClassifierOutputWithPast,
20
+ TokenClassifierOutput,
21
+ )
22
+ from transformers.modeling_utils import PreTrainedModel
23
+ from transformers.utils import logging
24
+ from .configuration_RW import RWConfig
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ # NOTE(Hesslow): Unfortunately we did not fuse matmul and bias during training, this means that there's one additional quantization to bfloat16 between the operations.
29
+ # In order not to degrade the quality of our HF-port, we keep these characteristics in the final model.
30
+ class Linear(nn.Linear):
31
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
32
+ ret = input @ self.weight.T
33
+ if self.bias is None:
34
+ return ret
35
+ else:
36
+ return ret + self.bias
37
+
38
+
39
+ from einops import rearrange
40
+
41
+ # rotary pos emb helpers (torch.jit.script does not seem to support staticmethod...)
42
+ def rotate_half(x):
43
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
44
+ return torch.cat((-x2, x1), dim=x1.ndim - 1) # dim=-1 triggers a bug in torch < 1.8.0
45
+
46
+
47
+ class RotaryEmbedding(torch.nn.Module):
48
+ """Implementation of RotaryEmbedding from GPT-NeoX.
49
+ This implementation is design to operate on queries and keys that are compatible with
50
+ [batch_size, n_heads_per_partition, seq_len, head_dim] (e.g. MinGPTAttention format).
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ config,
56
+ base=10000,
57
+ ):
58
+ head_dim = config.head_dim
59
+ self.use_cache = config.use_cache
60
+ super().__init__()
61
+ inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
62
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
63
+ self.head_dim = head_dim
64
+ self.seq_len_cached = None
65
+ self.batch_size_cached = None
66
+ self.cos_cached: torch.Tensor | None = None
67
+ self.sin_cached: torch.Tensor | None = None
68
+
69
+ def cos_sin(
70
+ self,
71
+ seq_len: int,
72
+ device="cuda",
73
+ dtype=torch.bfloat16,
74
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
75
+ if not self.use_cache:
76
+ t = torch.arange(seq_len, device=device).type_as(self.inv_freq)
77
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
78
+ emb = torch.cat((freqs, freqs), dim=-1).to(device)
79
+
80
+ if dtype in [torch.float16, torch.bfloat16]:
81
+ emb = emb.float()
82
+
83
+ cos_cached = emb.cos()[None, :, :]
84
+ sin_cached = emb.sin()[None, :, :]
85
+
86
+ cos_cached = cos_cached.type(dtype)
87
+ sin_cached = sin_cached.type(dtype)
88
+
89
+ return cos_cached, sin_cached
90
+ elif seq_len != self.seq_len_cached or not self.use_cache:
91
+ self.seq_len_cached = seq_len
92
+ t = torch.arange(seq_len, device=device).type_as(self.inv_freq)
93
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
94
+ emb = torch.cat((freqs, freqs), dim=-1).to(device)
95
+
96
+ if dtype in [torch.float16, torch.bfloat16]:
97
+ emb = emb.float()
98
+
99
+ self.cos_cached = emb.cos()[None, :, :]
100
+ self.sin_cached = emb.sin()[None, :, :]
101
+
102
+ self.cos_cached = self.cos_cached.type(dtype)
103
+ self.sin_cached = self.sin_cached.type(dtype)
104
+
105
+ return self.cos_cached, self.sin_cached
106
+ return self.cos_cached, self.sin_cached
107
+
108
+ def forward(self, q, k):
109
+ batch, seq_len, head_dim = q.shape
110
+ cos, sin = self.cos_sin(seq_len, q.device, q.dtype)
111
+ return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
112
+
113
+
114
+ def _make_causal_mask(
115
+ input_ids_shape: torch.Size, device: torch.device, past_key_values_length: int
116
+ ) -> torch.BoolTensor:
117
+ batch_size, target_length = input_ids_shape
118
+ mask = torch.empty((target_length, target_length + past_key_values_length), dtype=torch.bool, device=device)
119
+ # ONNX doesn't support `torch.Tensor.triu` properly, thus we use this workaround
120
+ seq_ids = torch.arange(target_length, device=device)
121
+ mask[:, past_key_values_length:] = seq_ids[:, None] < seq_ids[None, :]
122
+
123
+ if past_key_values_length > 0:
124
+ mask[:, :past_key_values_length] = False
125
+
126
+ expanded_mask = mask[None, None, :, :].expand(batch_size, 1, target_length, target_length + past_key_values_length)
127
+ return expanded_mask
128
+
129
+
130
+ def _expand_mask(mask: torch.Tensor, tgt_length: int) -> torch.BoolTensor:
131
+ batch_size, src_length = mask.shape
132
+ tgt_length = tgt_length if tgt_length is not None else src_length
133
+
134
+ expanded_mask = ~(mask[:, None, None, :].to(torch.bool))
135
+ return expanded_mask.expand(batch_size, 1, tgt_length, src_length)
136
+
137
+
138
+ def build_alibi_tensor(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
139
+ batch_size, seq_length = attention_mask.shape
140
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
141
+ base = torch.tensor(
142
+ 2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
143
+ )
144
+ powers = torch.arange(1, 1 + closest_power_of_2, device=attention_mask.device, dtype=torch.int32)
145
+ slopes = torch.pow(base, powers)
146
+
147
+ if closest_power_of_2 != num_heads:
148
+ extra_base = torch.tensor(
149
+ 2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=attention_mask.device, dtype=torch.float32
150
+ )
151
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
152
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=attention_mask.device, dtype=torch.int32)
153
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
154
+
155
+ # Note: alibi will added to the attention bias that will be applied to the query, key product of attention
156
+ # => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
157
+ # => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
158
+ # => the query_length dimension will then be broadcasted correctly
159
+ # This is more or less identical to T5's relative position bias:
160
+ # https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
161
+ arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :]
162
+ alibi = slopes[..., None].bfloat16() * arange_tensor
163
+ return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
164
+
165
+
166
+ def dropout_add(x: torch.Tensor, residual: torch.Tensor, prob: float, training: bool) -> torch.Tensor:
167
+ out = F.dropout(x, p=prob, training=training)
168
+ out = residual + out
169
+ return out
170
+
171
+
172
+ class Attention(nn.Module):
173
+ def __init__(self, config: RWConfig):
174
+ super().__init__()
175
+
176
+ self.hidden_size = config.hidden_size
177
+ self.num_heads = config.n_head
178
+ self.head_dim = self.hidden_size // self.num_heads
179
+ self.split_size = self.hidden_size
180
+ self.hidden_dropout = config.hidden_dropout
181
+
182
+ if self.head_dim * self.num_heads != self.hidden_size:
183
+ raise ValueError(
184
+ f"`hidden_size` must be divisible by num_heads (got `hidden_size`: {self.hidden_size} and `num_heads`:"
185
+ f" {self.num_heads})."
186
+ )
187
+
188
+ self.maybe_rotary = RotaryEmbedding(config) if config.rotary else lambda q, k: (q, k)
189
+
190
+ # Layer-wise attention scaling
191
+ self.inv_norm_factor = 1.0 / math.sqrt(self.head_dim)
192
+ self.beta = self.inv_norm_factor
193
+
194
+ self.query_key_value = Linear(
195
+ self.hidden_size,
196
+ (config.n_head_kv * 2 + config.n_head) * self.head_dim,
197
+ bias=config.bias,
198
+ )
199
+ self.dense = Linear(self.hidden_size, self.hidden_size, bias=config.bias)
200
+ self.attention_dropout = nn.Dropout(config.attention_dropout)
201
+ self.num_kv = config.n_head_kv
202
+
203
+ def _split_heads(self, fused_qkv: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
204
+ """
205
+ Split the last dimension into (num_heads, head_dim), results share same memory
206
+ storage as `fused_qkv`
207
+
208
+ Args:
209
+ fused_qkv (`torch.tensor`, *required*): [batch_size, seq_length, num_heads * 3 * head_dim]
210
+
211
+ Returns:
212
+ query: [batch_size, seq_length, num_heads, head_dim]
213
+ key: [batch_size, seq_length, num_heads, head_dim]
214
+ value: [batch_size, seq_length, num_heads, head_dim]
215
+ """
216
+ batch, seq_len, _ = fused_qkv.shape
217
+ qkv = fused_qkv.view(batch, seq_len, -1, self.num_heads // self.num_kv + 2, 64)
218
+ q = qkv[:, :, :, :-2]
219
+ k = qkv[:, :, :, [-2]]
220
+ v = qkv[:, :, :, [-1]]
221
+ k = torch.broadcast_to(k, q.shape)
222
+ v = torch.broadcast_to(v, q.shape)
223
+
224
+ q, k, v = [
225
+ rearrange(
226
+ x,
227
+ "batch seq_len group num_heads head_dim ->\
228
+ batch seq_len (group num_heads) head_dim",
229
+ head_dim=self.head_dim,
230
+ )
231
+ for x in [q, k, v]
232
+ ]
233
+ return q, k, v
234
+
235
+ def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
236
+ """
237
+ Merge heads together over the last dimenstion
238
+
239
+ Args:
240
+ x: (`torch.tensor`, *required*): [batch_size * num_heads, seq_length, head_dim]
241
+
242
+ Returns:
243
+ torch.tensor: [batch_size, seq_length, num_heads * head_dim]
244
+ """
245
+ # What we want to achieve is:
246
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads * head_dim
247
+ batch_size_and_num_heads, seq_length, _ = x.shape
248
+ batch_size = batch_size_and_num_heads // self.num_heads
249
+
250
+ # First view to decompose the batch size
251
+ # batch_size * num_heads, seq_length, head_dim -> batch_size, num_heads, seq_length, head_dim
252
+ x = x.view(batch_size, self.num_heads, seq_length, self.head_dim)
253
+
254
+ # batch_size, num_heads, seq_length, head_dim -> batch_size, seq_length, num_heads, head_dim
255
+ x = x.permute(0, 2, 1, 3)
256
+
257
+ # batch_size, seq_length, num_heads, head_dim -> batch_size, seq_length, num_heads * head_dim
258
+ return x.reshape(batch_size, seq_length, self.num_heads * self.head_dim)
259
+
260
+ def forward(
261
+ self,
262
+ hidden_states: torch.Tensor,
263
+ alibi: torch.Tensor,
264
+ attention_mask: torch.Tensor,
265
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
266
+ head_mask: Optional[torch.Tensor] = None,
267
+ use_cache: bool = False,
268
+ output_attentions: bool = False,
269
+ ):
270
+ fused_qkv = self.query_key_value(hidden_states) # [batch_size, seq_length, 3 x hidden_size]
271
+
272
+ # 3 x [batch_size, seq_length, num_heads, head_dim]
273
+ (query_layer, key_layer, value_layer) = self._split_heads(fused_qkv)
274
+
275
+ batch_size, q_length, _, _ = query_layer.shape
276
+
277
+ query_layer = query_layer.transpose(1, 2).reshape(batch_size * self.num_heads, q_length, self.head_dim)
278
+ key_layer = key_layer.transpose(1, 2).reshape(
279
+ batch_size * self.num_heads,
280
+ q_length,
281
+ self.head_dim,
282
+ )
283
+ value_layer = value_layer.transpose(1, 2).reshape(batch_size * self.num_heads, q_length, self.head_dim)
284
+
285
+ query_layer, key_layer = self.maybe_rotary(query_layer, key_layer)
286
+
287
+ if layer_past is not None:
288
+ past_key, past_value = layer_past
289
+ # concatenate along seq_length dimension:
290
+ # - key: [batch_size * self.num_heads, head_dim, kv_length]
291
+ # - value: [batch_size * self.num_heads, kv_length, head_dim]
292
+ key_layer = torch.cat((past_key, key_layer), dim=1)
293
+ value_layer = torch.cat((past_value, value_layer), dim=1)
294
+
295
+ _, kv_length, _ = key_layer.shape
296
+
297
+ if use_cache is True:
298
+ present = (key_layer, value_layer)
299
+ else:
300
+ present = None
301
+
302
+ if alibi is None:
303
+ query_layer_ = query_layer.reshape(batch_size, self.num_heads, -1, self.head_dim)
304
+ key_layer_ = key_layer.reshape(batch_size, self.num_heads, -1, self.head_dim)
305
+ value_layer_ = value_layer.reshape(batch_size, self.num_heads, -1, self.head_dim)
306
+
307
+ attn_output = F.scaled_dot_product_attention(
308
+ query_layer_, key_layer_, value_layer_, None, 0.0, is_causal=True
309
+ )
310
+
311
+ x = attn_output.view(batch_size, self.num_heads, q_length, self.head_dim)
312
+ x = x.permute(0, 2, 1, 3)
313
+ attn_output = x.reshape(batch_size, q_length, self.num_heads * self.head_dim)
314
+
315
+ output_tensor = self.dense(attn_output)
316
+
317
+ outputs = (output_tensor, present)
318
+ assert not output_attentions # not supported.
319
+ return outputs
320
+ else:
321
+ attention_mask_float = (attention_mask * 1.0).masked_fill(attention_mask, -1e9).to(torch.bfloat16)
322
+ matmul_result = query_layer @ key_layer.transpose(-1, -2)
323
+
324
+ # change view to [batch_size, num_heads, q_length, kv_length]
325
+ attention_scores = matmul_result.view(batch_size, self.num_heads, q_length, kv_length)
326
+
327
+ # cast attention scores to fp32, compute scaled softmax and cast back to initial dtype - [batch_size, num_heads, q_length, kv_length]
328
+ input_dtype = attention_scores.dtype
329
+ # `float16` has a minimum value of -65504.0, whereas `bfloat16` and `float32` have a minimum value of `-3.4e+38`
330
+ if input_dtype == torch.float16 or input_dtype == torch.bfloat16:
331
+ attention_scores = attention_scores.to(torch.float32)
332
+ # attn_weights = torch.masked_fill(attention_scores, attention_mask, torch.finfo(attention_scores.dtype).min)
333
+ attention_probs = F.softmax(
334
+ (attention_scores + alibi.view(batch_size, self.num_heads, 1, -1)) * self.inv_norm_factor
335
+ + attention_mask_float,
336
+ dim=-1,
337
+ dtype=hidden_states.dtype,
338
+ )
339
+ # [batch_size, num_heads, q_length, kv_length]
340
+ attention_probs = self.attention_dropout(attention_probs)
341
+
342
+ if head_mask is not None:
343
+ attention_probs = attention_probs * head_mask
344
+
345
+ # change view [batch_size x num_heads, q_length, kv_length]
346
+ attention_probs_reshaped = attention_probs.view(batch_size * self.num_heads, q_length, kv_length)
347
+
348
+ # matmul: [batch_size * num_heads, q_length, head_dim]
349
+ context_layer = attention_probs_reshaped @ value_layer
350
+
351
+ # change view [batch_size, num_heads, q_length, head_dim]
352
+ context_layer = self._merge_heads(context_layer)
353
+
354
+ output_tensor = self.dense(context_layer)
355
+
356
+ outputs = (output_tensor, present)
357
+ if output_attentions:
358
+ outputs += (attention_probs,)
359
+
360
+ return outputs
361
+
362
+
363
+ class MLP(nn.Module):
364
+ def __init__(self, config: RWConfig):
365
+ super().__init__()
366
+ hidden_size = config.hidden_size
367
+
368
+ self.dense_h_to_4h = Linear(hidden_size, 4 * hidden_size, bias=config.bias)
369
+ self.act = nn.GELU()
370
+ self.dense_4h_to_h = Linear(4 * hidden_size, hidden_size, bias=config.bias)
371
+ self.hidden_dropout = config.hidden_dropout
372
+
373
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
374
+ x = self.act(self.dense_h_to_4h(x))
375
+ x = self.dense_4h_to_h(x)
376
+ return x
377
+
378
+
379
+ class DecoderLayer(nn.Module):
380
+ def __init__(self, config: RWConfig):
381
+ super().__init__()
382
+ hidden_size = config.hidden_size
383
+
384
+ self.ln_attn = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
385
+ self.ln_mlp = LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
386
+
387
+ self.num_heads = config.n_head
388
+ self.self_attention = Attention(config)
389
+
390
+ self.mlp = MLP(config)
391
+
392
+ self.apply_residual_connection_post_layernorm = config.apply_residual_connection_post_layernorm
393
+ self.hidden_dropout = config.hidden_dropout
394
+
395
+ self.config = config
396
+
397
+ def forward(
398
+ self,
399
+ hidden_states: torch.Tensor,
400
+ alibi: torch.Tensor,
401
+ attention_mask: torch.Tensor,
402
+ layer_past: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
403
+ head_mask: Optional[torch.Tensor] = None,
404
+ use_cache: bool = False,
405
+ output_attentions: bool = False,
406
+ ):
407
+
408
+ ln_attn = self.ln_attn(hidden_states)
409
+ ln_mlp = self.ln_mlp(hidden_states)
410
+
411
+ residual = hidden_states
412
+
413
+ # Self attention.
414
+ attn_outputs = self.self_attention(
415
+ ln_attn,
416
+ layer_past=layer_past,
417
+ attention_mask=attention_mask,
418
+ alibi=alibi,
419
+ head_mask=head_mask,
420
+ use_cache=use_cache,
421
+ output_attentions=output_attentions,
422
+ )
423
+
424
+ attention_output = attn_outputs[0]
425
+
426
+ outputs = attn_outputs[1:]
427
+
428
+ # MLP.
429
+ mlp_output = self.mlp(ln_mlp)
430
+
431
+ output = dropout_add(
432
+ mlp_output + attention_output, residual, self.config.hidden_dropout, training=self.training
433
+ )
434
+
435
+ if use_cache:
436
+ outputs = (output,) + outputs
437
+ else:
438
+ outputs = (output,) + outputs[1:]
439
+
440
+ return outputs # hidden_states, present, attentions
441
+
442
+
443
+ class RWPreTrainedModel(PreTrainedModel):
444
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
445
+ """
446
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
447
+ models.
448
+ """
449
+
450
+ config_class = RWConfig
451
+ base_model_prefix = "transformer"
452
+ supports_gradient_checkpointing = True
453
+ _no_split_modules = ["DecoderLayer"]
454
+
455
+ def __init__(self, *inputs, **kwargs):
456
+ super().__init__(*inputs, **kwargs)
457
+
458
+ def _init_weights(self, module: nn.Module):
459
+ """Initialize the weights."""
460
+ if isinstance(module, nn.Linear) or isinstance(module, Linear):
461
+ # Slightly different from the TF version which uses truncated_normal for initialization
462
+ # cf https://github.com/pytorch/pytorch/pull/5617
463
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
464
+ if module.bias is not None:
465
+ module.bias.data.zero_()
466
+ elif isinstance(module, nn.Embedding):
467
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
468
+ if module.padding_idx is not None:
469
+ module.weight.data[module.padding_idx].zero_()
470
+ elif isinstance(module, LayerNorm):
471
+ module.bias.data.zero_()
472
+ module.weight.data.fill_(1.0)
473
+
474
+ def _set_gradient_checkpointing(self, module: nn.Module, value: bool = False):
475
+ if isinstance(module, RWModel):
476
+ module.gradient_checkpointing = value
477
+
478
+ @staticmethod
479
+ def _convert_to_standard_cache(
480
+ past_key_value: Tuple[Tuple[torch.Tensor, torch.Tensor]], batch_size: int
481
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
482
+ """
483
+ Standardizes the format of the cache so as to match most implementations, i.e. to tuple(tuple([batch_size,
484
+ num_heads, ...]))
485
+ """
486
+ batch_size_times_num_heads, head_dim, seq_length = past_key_value[0][0].shape
487
+ num_heads = batch_size_times_num_heads // batch_size
488
+ # key: [batch_size * num_heads, head_dim, seq_length] -> [batch_size, num_heads, head_dim, seq_length]
489
+ # value: [batch_size * num_heads, seq_length, head_dim] -> [batch_size, num_heads, seq_length, head_dim]
490
+ return tuple(
491
+ (
492
+ layer_past[0].view(batch_size, num_heads, head_dim, seq_length),
493
+ layer_past[1].view(batch_size, num_heads, seq_length, head_dim),
494
+ )
495
+ for layer_past in past_key_value
496
+ )
497
+
498
+ @staticmethod
499
+ def _convert_to_rw_cache(
500
+ past_key_value: Tuple[Tuple[torch.Tensor, torch.Tensor]]
501
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor]]:
502
+ batch_size, num_heads, head_dim, seq_length = past_key_value[0][0].shape
503
+ batch_size_times_num_heads = batch_size * num_heads
504
+ # key: [batch_size, num_heads, head_dim, seq_length] -> [batch_size * num_heads, head_dim, seq_length]
505
+ # value: [batch_size, num_heads, seq_length, head_dim] -> [batch_size * num_heads, seq_length, head_dim]
506
+ return tuple(
507
+ (
508
+ layer_past[0].view(batch_size_times_num_heads, head_dim, seq_length),
509
+ layer_past[1].view(batch_size_times_num_heads, seq_length, head_dim),
510
+ )
511
+ for layer_past in past_key_value
512
+ )
513
+
514
+
515
+ class RWModel(RWPreTrainedModel):
516
+ def __init__(self, config: RWConfig):
517
+ super().__init__(config)
518
+
519
+ self.embed_dim = config.hidden_size
520
+ self.num_heads = config.n_head
521
+ self.alibi = config.alibi
522
+
523
+ # Embedding + LN Embedding
524
+ self.word_embeddings = nn.Embedding(config.vocab_size, self.embed_dim)
525
+
526
+ # Transformer blocks
527
+ self.h = nn.ModuleList([DecoderLayer(config) for _ in range(config.num_hidden_layers)])
528
+
529
+ # Final Layer Norm
530
+ self.ln_f = LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
531
+
532
+ self.gradient_checkpointing = False
533
+
534
+ # Initialize weights and apply final processing
535
+ self.post_init()
536
+
537
+ def get_input_embeddings(self):
538
+ return self.word_embeddings
539
+
540
+ def _prepare_attn_mask(
541
+ self, attention_mask: torch.Tensor, input_shape: Tuple[int, int], past_key_values_length: int
542
+ ) -> torch.BoolTensor:
543
+ # create causal mask
544
+ # [batch_size, seq_length] -> [batch_size, 1, tgt_length, src_length]
545
+ combined_attention_mask = None
546
+ device = attention_mask.device
547
+ _, src_length = input_shape
548
+
549
+ if src_length > 1:
550
+ combined_attention_mask = _make_causal_mask(
551
+ input_shape, device=device, past_key_values_length=past_key_values_length
552
+ )
553
+
554
+ # [batch_size, seq_length] -> [batch_size, 1, tgt_length, src_length]
555
+ expanded_attn_mask = _expand_mask(attention_mask, tgt_length=src_length)
556
+ combined_attention_mask = (
557
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
558
+ )
559
+
560
+ return combined_attention_mask
561
+
562
+ def set_input_embeddings(self, new_embeddings: torch.Tensor):
563
+ self.word_embeddings = new_embeddings
564
+
565
+ def forward(
566
+ self,
567
+ input_ids: Optional[torch.LongTensor] = None,
568
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ head_mask: Optional[torch.LongTensor] = None,
571
+ inputs_embeds: Optional[torch.LongTensor] = None,
572
+ use_cache: Optional[bool] = None,
573
+ output_attentions: Optional[bool] = None,
574
+ output_hidden_states: Optional[bool] = None,
575
+ return_dict: Optional[bool] = None,
576
+ **deprecated_arguments,
577
+ ) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
578
+ if deprecated_arguments.pop("position_ids", False) is not False:
579
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
580
+ warnings.warn(
581
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
582
+ " passing `position_ids`.",
583
+ FutureWarning,
584
+ )
585
+ if len(deprecated_arguments) > 0:
586
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
587
+
588
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
589
+ output_hidden_states = (
590
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
591
+ )
592
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
593
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
594
+
595
+ if input_ids is not None and inputs_embeds is not None:
596
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
597
+ elif input_ids is not None:
598
+ batch_size, seq_length = input_ids.shape
599
+ elif inputs_embeds is not None:
600
+ batch_size, seq_length, _ = inputs_embeds.shape
601
+ else:
602
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
603
+
604
+ if past_key_values is None:
605
+ past_key_values = tuple([None] * len(self.h))
606
+
607
+ # Prepare head mask if needed
608
+ # 1.0 in head_mask indicate we keep the head
609
+ # attention_probs has shape batch_size x num_heads x N x N
610
+ # head_mask has shape n_layer x batch x num_heads x N x N
611
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
612
+
613
+ if inputs_embeds is None:
614
+ inputs_embeds = self.word_embeddings(input_ids)
615
+
616
+ hidden_states = inputs_embeds
617
+
618
+ presents = () if use_cache else None
619
+ all_self_attentions = () if output_attentions else None
620
+ all_hidden_states = () if output_hidden_states else None
621
+
622
+ # Compute alibi tensor: check build_alibi_tensor documentation
623
+ seq_length_with_past = seq_length
624
+ past_key_values_length = 0
625
+ if past_key_values[0] is not None:
626
+ past_key_values_length = past_key_values[0][0].shape[2]
627
+ seq_length_with_past = seq_length_with_past + past_key_values_length
628
+ if attention_mask is None:
629
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
630
+ else:
631
+ attention_mask = attention_mask.to(hidden_states.device)
632
+
633
+ if self.alibi:
634
+ alibi = build_alibi_tensor(attention_mask, self.num_heads, dtype=hidden_states.dtype)
635
+ else:
636
+ alibi = None
637
+
638
+ causal_mask = self._prepare_attn_mask(
639
+ attention_mask,
640
+ input_shape=(batch_size, seq_length),
641
+ past_key_values_length=past_key_values_length,
642
+ )
643
+
644
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
645
+
646
+ if output_hidden_states:
647
+ all_hidden_states = all_hidden_states + (hidden_states,)
648
+
649
+ if self.gradient_checkpointing and self.training:
650
+
651
+ if use_cache:
652
+ logger.warning(
653
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
654
+ )
655
+ use_cache = False
656
+
657
+ def create_custom_forward(module):
658
+ def custom_forward(*inputs):
659
+ # None for past_key_value
660
+ return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
661
+
662
+ return custom_forward
663
+
664
+ outputs = torch.utils.checkpoint.checkpoint(
665
+ create_custom_forward(block),
666
+ hidden_states,
667
+ alibi,
668
+ causal_mask,
669
+ head_mask[i],
670
+ )
671
+ else:
672
+ outputs = block(
673
+ hidden_states,
674
+ layer_past=layer_past,
675
+ attention_mask=causal_mask,
676
+ head_mask=head_mask[i],
677
+ use_cache=use_cache,
678
+ output_attentions=output_attentions,
679
+ alibi=alibi,
680
+ )
681
+
682
+ hidden_states = outputs[0]
683
+ if use_cache is True:
684
+ presents = presents + (outputs[1],)
685
+
686
+ if output_attentions:
687
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
688
+
689
+ # Add last hidden state
690
+ hidden_states = self.ln_f(hidden_states)
691
+
692
+ if output_hidden_states:
693
+ all_hidden_states = all_hidden_states + (hidden_states,)
694
+
695
+ if not return_dict:
696
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
697
+
698
+ return BaseModelOutputWithPastAndCrossAttentions(
699
+ last_hidden_state=hidden_states,
700
+ past_key_values=presents,
701
+ hidden_states=all_hidden_states,
702
+ attentions=all_self_attentions,
703
+ )
704
+
705
+
706
+ class RWForCausalLM(RWPreTrainedModel):
707
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
708
+
709
+ def __init__(self, config: RWConfig):
710
+ super().__init__(config)
711
+ self.transformer = RWModel(config)
712
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
713
+
714
+ # Initialize weights and apply final processing
715
+ self.post_init()
716
+
717
+ def get_output_embeddings(self):
718
+ return self.lm_head
719
+
720
+ def set_output_embeddings(self, new_embeddings: torch.Tensor):
721
+ self.lm_head = new_embeddings
722
+
723
+ def prepare_inputs_for_generation(
724
+ self,
725
+ input_ids: torch.LongTensor,
726
+ past: Optional[torch.Tensor] = None,
727
+ attention_mask: Optional[torch.Tensor] = None,
728
+ **kwargs,
729
+ ) -> dict:
730
+ # only last token for input_ids if past is not None
731
+ if past:
732
+ input_ids = input_ids[:, -1].unsqueeze(-1)
733
+
734
+ # the cache may be in the stardard format (e.g. in contrastive search), convert to our's format if needed
735
+ if past[0][0].shape[0] == input_ids.shape[0]:
736
+ past = self._convert_to_rw_cache(past)
737
+
738
+ return {
739
+ "input_ids": input_ids,
740
+ "past_key_values": past,
741
+ "use_cache": kwargs.get("use_cache"),
742
+ "attention_mask": attention_mask,
743
+ }
744
+
745
+ def forward(
746
+ self,
747
+ input_ids: Optional[torch.LongTensor] = None,
748
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
749
+ attention_mask: Optional[torch.Tensor] = None,
750
+ head_mask: Optional[torch.Tensor] = None,
751
+ inputs_embeds: Optional[torch.Tensor] = None,
752
+ labels: Optional[torch.Tensor] = None,
753
+ use_cache: Optional[bool] = None,
754
+ output_attentions: Optional[bool] = None,
755
+ output_hidden_states: Optional[bool] = None,
756
+ return_dict: Optional[bool] = None,
757
+ **deprecated_arguments,
758
+ ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
759
+ r"""
760
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
761
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
762
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
763
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
764
+ """
765
+ if deprecated_arguments.pop("position_ids", False) is not False:
766
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
767
+ warnings.warn(
768
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
769
+ " passing `position_ids`.",
770
+ FutureWarning,
771
+ )
772
+ if len(deprecated_arguments) > 0:
773
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
774
+
775
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
776
+
777
+ transformer_outputs = self.transformer(
778
+ input_ids,
779
+ past_key_values=past_key_values,
780
+ attention_mask=attention_mask,
781
+ head_mask=head_mask,
782
+ inputs_embeds=inputs_embeds,
783
+ use_cache=use_cache,
784
+ output_attentions=output_attentions,
785
+ output_hidden_states=output_hidden_states,
786
+ return_dict=return_dict,
787
+ )
788
+ hidden_states = transformer_outputs[0]
789
+
790
+ lm_logits = self.lm_head(hidden_states)
791
+
792
+ loss = None
793
+ if labels is not None:
794
+ # Shift so that tokens < n predict n
795
+ shift_logits = lm_logits[..., :-1, :].contiguous()
796
+ shift_labels = labels[..., 1:].contiguous()
797
+ batch_size, seq_length, vocab_size = shift_logits.shape
798
+ # Flatten the tokens
799
+ loss_fct = CrossEntropyLoss()
800
+ loss = loss_fct(
801
+ shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length)
802
+ )
803
+
804
+ if not return_dict:
805
+ output = (lm_logits,) + transformer_outputs[1:]
806
+ return ((loss,) + output) if loss is not None else output
807
+
808
+ return CausalLMOutputWithCrossAttentions(
809
+ loss=loss,
810
+ logits=lm_logits,
811
+ past_key_values=transformer_outputs.past_key_values,
812
+ hidden_states=transformer_outputs.hidden_states,
813
+ attentions=transformer_outputs.attentions,
814
+ )
815
+
816
+ def _reorder_cache(
817
+ self, past: Tuple[Tuple[torch.Tensor, torch.Tensor], ...], beam_idx: torch.LongTensor
818
+ ) -> Tuple[Tuple[torch.Tensor, torch.Tensor], ...]:
819
+ """
820
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
821
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
822
+ beam_idx at every generation step.
823
+
824
+ Output shares the same memory storage as `past`.
825
+ """
826
+ standardized_past = self._convert_to_standard_cache(past, batch_size=len(beam_idx))
827
+
828
+ # Get a copy of `beam_idx` on all the devices where we need those indices.
829
+ device_to_beam_idx = {
830
+ past_state.device: beam_idx.to(past_state.device) for layer_past in past for past_state in layer_past
831
+ }
832
+ reordered_past = tuple(
833
+ (
834
+ layer_past[0].index_select(0, device_to_beam_idx[layer_past[0].device]),
835
+ layer_past[1].index_select(0, device_to_beam_idx[layer_past[0].device]),
836
+ )
837
+ for layer_past in standardized_past
838
+ )
839
+ return self._convert_to_rw_cache(reordered_past)
840
+
841
+
842
+ class RWForSequenceClassification(RWPreTrainedModel):
843
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
844
+
845
+ def __init__(self, config: RWConfig):
846
+ super().__init__(config)
847
+ self.num_labels = config.num_labels
848
+ self.transformer = RWModel(config)
849
+ self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False)
850
+
851
+ # Initialize weights and apply final processing
852
+ self.post_init()
853
+
854
+ def forward(
855
+ self,
856
+ input_ids: Optional[torch.LongTensor] = None,
857
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
858
+ attention_mask: Optional[torch.Tensor] = None,
859
+ head_mask: Optional[torch.Tensor] = None,
860
+ inputs_embeds: Optional[torch.Tensor] = None,
861
+ labels: Optional[torch.Tensor] = None,
862
+ use_cache: Optional[bool] = None,
863
+ output_attentions: Optional[bool] = None,
864
+ output_hidden_states: Optional[bool] = None,
865
+ return_dict: Optional[bool] = None,
866
+ **deprecated_arguments,
867
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
868
+ r"""
869
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
870
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
871
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
872
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
873
+ """
874
+ if deprecated_arguments.pop("position_ids", False) is not False:
875
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
876
+ warnings.warn(
877
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
878
+ " passing `position_ids`.",
879
+ FutureWarning,
880
+ )
881
+ if len(deprecated_arguments) > 0:
882
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
883
+
884
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
885
+
886
+ transformer_outputs = self.transformer(
887
+ input_ids,
888
+ past_key_values=past_key_values,
889
+ attention_mask=attention_mask,
890
+ head_mask=head_mask,
891
+ inputs_embeds=inputs_embeds,
892
+ use_cache=use_cache,
893
+ output_attentions=output_attentions,
894
+ output_hidden_states=output_hidden_states,
895
+ return_dict=return_dict,
896
+ )
897
+
898
+ hidden_states = transformer_outputs[0]
899
+ logits = self.score(hidden_states)
900
+
901
+ if input_ids is not None:
902
+ batch_size = input_ids.shape[0]
903
+ else:
904
+ batch_size = inputs_embeds.shape[0]
905
+
906
+ if self.config.pad_token_id is None and batch_size != 1:
907
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
908
+ if self.config.pad_token_id is None:
909
+ sequence_lengths = -1
910
+ else:
911
+ if input_ids is not None:
912
+ sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(dim=-1) - 1
913
+ else:
914
+ sequence_lengths = -1
915
+ logger.warning(
916
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
917
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
918
+ )
919
+
920
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
921
+
922
+ loss = None
923
+ if labels is not None:
924
+ if self.config.problem_type is None:
925
+ if self.num_labels == 1:
926
+ self.config.problem_type = "regression"
927
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
928
+ self.config.problem_type = "single_label_classification"
929
+ else:
930
+ self.config.problem_type = "multi_label_classification"
931
+
932
+ if self.config.problem_type == "regression":
933
+ loss_fct = MSELoss()
934
+ if self.num_labels == 1:
935
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
936
+ else:
937
+ loss = loss_fct(pooled_logits, labels)
938
+ elif self.config.problem_type == "single_label_classification":
939
+ loss_fct = CrossEntropyLoss()
940
+ loss = loss_fct(pooled_logits, labels)
941
+ elif self.config.problem_type == "multi_label_classification":
942
+ loss_fct = BCEWithLogitsLoss()
943
+ loss = loss_fct(pooled_logits, labels)
944
+ if not return_dict:
945
+ output = (pooled_logits,) + transformer_outputs[1:]
946
+ return ((loss,) + output) if loss is not None else output
947
+
948
+ return SequenceClassifierOutputWithPast(
949
+ loss=loss,
950
+ logits=pooled_logits,
951
+ past_key_values=transformer_outputs.past_key_values,
952
+ hidden_states=transformer_outputs.hidden_states,
953
+ attentions=transformer_outputs.attentions,
954
+ )
955
+
956
+
957
+ class RWForTokenClassification(RWPreTrainedModel):
958
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
959
+
960
+ def __init__(self, config: RWConfig):
961
+ super().__init__(config)
962
+ self.num_labels = config.num_labels
963
+
964
+ self.transformer = RWModel(config)
965
+ if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
966
+ classifier_dropout = config.classifier_dropout
967
+ elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
968
+ classifier_dropout = config.hidden_dropout
969
+ else:
970
+ classifier_dropout = 0.1
971
+ self.dropout = nn.Dropout(classifier_dropout)
972
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
973
+
974
+ # Initialize weights and apply final processing
975
+ self.post_init()
976
+
977
+ def forward(
978
+ self,
979
+ input_ids: Optional[torch.LongTensor] = None,
980
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor, torch.Tensor], ...]] = None,
981
+ attention_mask: Optional[torch.Tensor] = None,
982
+ head_mask: Optional[torch.Tensor] = None,
983
+ inputs_embeds: Optional[torch.Tensor] = None,
984
+ labels: Optional[torch.Tensor] = None,
985
+ use_cache: Optional[bool] = None,
986
+ output_attentions: Optional[bool] = None,
987
+ output_hidden_states: Optional[bool] = None,
988
+ return_dict: Optional[bool] = None,
989
+ **deprecated_arguments,
990
+ ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
991
+ r"""
992
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
993
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
994
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
995
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
996
+ """
997
+ if deprecated_arguments.pop("position_ids", False) is not False:
998
+ # `position_ids` could have been `torch.Tensor` or `None` so defaulting pop to `False` allows to detect if users were passing explicitly `None`
999
+ warnings.warn(
1000
+ "`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. You can safely ignore"
1001
+ " passing `position_ids`.",
1002
+ FutureWarning,
1003
+ )
1004
+ if len(deprecated_arguments) > 0:
1005
+ raise ValueError(f"Got unexpected arguments: {deprecated_arguments}")
1006
+
1007
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1008
+
1009
+ transformer_outputs = self.transformer(
1010
+ input_ids,
1011
+ past_key_values=past_key_values,
1012
+ attention_mask=attention_mask,
1013
+ head_mask=head_mask,
1014
+ inputs_embeds=inputs_embeds,
1015
+ use_cache=use_cache,
1016
+ output_attentions=output_attentions,
1017
+ output_hidden_states=output_hidden_states,
1018
+ return_dict=return_dict,
1019
+ )
1020
+
1021
+ hidden_states = transformer_outputs[0]
1022
+ hidden_states = self.dropout(hidden_states)
1023
+ logits = self.classifier(hidden_states)
1024
+
1025
+ loss = None
1026
+ if labels is not None:
1027
+ batch_size, seq_length = labels.shape
1028
+ loss_fct = CrossEntropyLoss()
1029
+ loss = loss_fct(logits.view(batch_size * seq_length, self.num_labels), labels.view(batch_size * seq_length))
1030
+
1031
+ if not return_dict:
1032
+ output = (logits,) + transformer_outputs[2:]
1033
+ return ((loss,) + output) if loss is not None else output
1034
+
1035
+ return TokenClassifierOutput(
1036
+ loss=loss,
1037
+ logits=logits,
1038
+ hidden_states=transformer_outputs.hidden_states,
1039
+ attentions=transformer_outputs.attentions,
1040
+ )
1041
+
1042
+
1043
+ class RWForQuestionAnswering(RWPreTrainedModel):
1044
+ _keys_to_ignore_on_load_missing = [r"h.*.self_attention.scale_mask_softmax.causal_mask", r"lm_head.weight"]
1045
+
1046
+ def __init__(self, config):
1047
+ super().__init__(config)
1048
+ self.transformer = RWModel(config)
1049
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1050
+
1051
+ # Initialize weights and apply final processing
1052
+ self.post_init()
1053
+
1054
+ def forward(
1055
+ self,
1056
+ input_ids: Optional[torch.LongTensor] = None,
1057
+ attention_mask: Optional[torch.FloatTensor] = None,
1058
+ position_ids: Optional[torch.LongTensor] = None,
1059
+ head_mask: Optional[torch.FloatTensor] = None,
1060
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1061
+ start_positions: Optional[torch.LongTensor] = None,
1062
+ end_positions: Optional[torch.LongTensor] = None,
1063
+ output_attentions: Optional[bool] = None,
1064
+ output_hidden_states: Optional[bool] = None,
1065
+ return_dict: Optional[bool] = None,
1066
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1067
+ r"""
1068
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1069
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1070
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1071
+ are not taken into account for computing the loss.
1072
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1073
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1074
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1075
+ are not taken into account for computing the loss.
1076
+ """
1077
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1078
+
1079
+ outputs = self.transformer(
1080
+ input_ids,
1081
+ attention_mask=attention_mask,
1082
+ position_ids=position_ids,
1083
+ head_mask=head_mask,
1084
+ inputs_embeds=inputs_embeds,
1085
+ output_attentions=output_attentions,
1086
+ output_hidden_states=output_hidden_states,
1087
+ return_dict=return_dict,
1088
+ )
1089
+
1090
+ sequence_output = outputs[0]
1091
+
1092
+ logits = self.qa_outputs(sequence_output)
1093
+ start_logits, end_logits = logits.split(1, dim=-1)
1094
+ start_logits = start_logits.squeeze(-1).contiguous()
1095
+ end_logits = end_logits.squeeze(-1).contiguous()
1096
+
1097
+ total_loss = None
1098
+ if start_positions is not None and end_positions is not None:
1099
+ # If we are on multi-GPU, split add a dimension
1100
+ if len(start_positions.size()) > 1:
1101
+ start_positions = start_positions.squeeze(-1)
1102
+ if len(end_positions.size()) > 1:
1103
+ end_positions = end_positions.squeeze(-1)
1104
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1105
+ ignored_index = start_logits.size(1)
1106
+ start_positions = start_positions.clamp(0, ignored_index)
1107
+ end_positions = end_positions.clamp(0, ignored_index)
1108
+
1109
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1110
+ start_loss = loss_fct(start_logits, start_positions)
1111
+ end_loss = loss_fct(end_logits, end_positions)
1112
+ total_loss = (start_loss + end_loss) / 2
1113
+
1114
+ if not return_dict:
1115
+ output = (start_logits, end_logits) + outputs[2:]
1116
+ return ((total_loss,) + output) if total_loss is not None else output
1117
+
1118
+ return QuestionAnsweringModelOutput(
1119
+ loss=total_loss,
1120
+ start_logits=start_logits,
1121
+ end_logits=end_logits,
1122
+ hidden_states=outputs.hidden_states,
1123
+ attentions=outputs.attentions,
1124
+ )