-
Notifications
You must be signed in to change notification settings - Fork 0
/
modeling_quantile_regression.py
608 lines (523 loc) · 26.8 KB
/
modeling_quantile_regression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import math
import torch
import torch.nn as nn
from transformers.models.bert import BertPreTrainedModel, BertModel
from transformers.models.opt import OPTPreTrainedModel, OPTModel
from transformers.models.gpt_neox import GPTNeoXPreTrainedModel, GPTNeoXModel
from transformers.modeling_outputs import SequenceClassifierOutput, SequenceClassifierOutputWithPast, TokenClassifierOutput
import scipy.stats
def l1_loss_fn(score, target, ignore_index=-100):
mask = (target == ignore_index)
out = torch.nn.functional.l1_loss(score, target=target, reduction="none")
return out[~mask]
def mse_loss_fn(score, target, ignore_index=-100):
mask = (target == ignore_index)
out = torch.nn.functional.mse_loss(score, target, reduction="none")
return out[~mask]
def gaussian_loss_fn(score, target, eps=1e-4, quantile=None, kl_weight=0.0, return_kl=False, ignore_index=-100):
mask = (target == ignore_index)
# little different from the rest, score is Nx2, quantile is ignored, this is just a negative log likelihood of a Gaussian distribution
assert (
score.ndim == 2 and score.shape[-1] == 2
), "score has the wrong shape, expected Nx2 input but got {}".format(score.shape)
assert (
target.ndim == 1
), "target has the wrong shape, expected 1-d vector, got {}".format(target.shape)
mu = score[:, 0]
var = score[:, 1]
assert (
mu.shape == var.shape and mu.shape == target.shape
), "mean, std and target have non-compatible shapes, got {} {} {}".format(
mu.shape, var.shape, target.shape
)
var = var.clone()
with torch.no_grad():
var.clamp_(min=eps)
loss = 0.5 * torch.log(var) + 0.5 * (target - mu) ** 2 / (var) + 0.5 * math.log(2 * math.pi)
assert target.shape == loss.shape, "loss should be a 1-d vector got {}".format(
loss.shape
)
kl = 0.5 * (-torch.log(var) + var + mu ** 2 - 1)
if kl_weight > 0:
loss += kl_weight * kl
if return_kl:
return loss, kl
return loss[~mask]
def pinball_loss_fn(score, target, quantiles, ignore_index=-100):
mask = (target == ignore_index)
assert (
score.ndim == 2
), "score has the wrong shape, expected 2d input but got {}".format(score.shape)
assert (
target.ndim == 1
), "target has the wrong shape, expected 1-d vector, got {}".format(target.shape)
target = target.reshape([-1, 1])
delta_score = target - score
loss = torch.maximum(delta_score * quantiles, delta_score * (quantiles - 1.0))
return loss[~mask, :]
def mse_pinball_loss_fn(score, target, quantiles, pinball_reduction="sum", ignore_index=-100):
mask = (target == ignore_index)
num_quantiles = quantiles.shape[0]
assert (
score.ndim == 2
), "score has the wrong shape, expected 2d input but got {}".format(score.shape)
assert (
score.shape[-1] == num_quantiles + 1
), f"score shape does not match with number of quantiles, score is {score.shape} but number of quantiles is {num_quantiles}"
assert (
target.ndim == 1
), "target has the wrong shape, expected 1-d vector, got {}".format(target.shape)
regression_loss = torch.nn.functional.mse_loss(score[:, 0], target, reduction="none")[~mask]
pinball_loss = pinball_loss_fn(score[:, 1:], target, quantiles, ignore_index=ignore_index)
if pinball_reduction == "sum":
pinball_loss = pinball_loss.sum(-1)
elif pinball_reduction == "mean":
pinball_loss = pinball_loss.mean(-1)
loss = regression_loss + pinball_loss
return loss
def gaussian_pinball_loss_fn(score, target, eps=1e-4, quantile=None, ignore_index=-100):
# little different from the rest, score is Nx2, quantile is ignored, this is just a negative log likelihood of a Gaussian distribution
assert (
score.ndim == 2 and score.shape[-1] == 2
), "score has the wrong shape, expected Nx2 input but got {}".format(score.shape)
assert (
target.ndim == 1
), "target has the wrong shape, expected 1-d vector, got {}".format(target.shape)
gaussian_loss = gaussian_loss_fn(score, target, ignore_index=ignore_index)
pinball_loss = pinball_loss_fn(score[:, [0]], target, torch.FloatTensor([0.5]).to(score.device), ignore_index=ignore_index).sum(-1) + pinball_loss_fn(score[:, [0]] + torch.sqrt(score[:, [1]]), target, torch.FloatTensor([1-scipy.stats.norm.sf(1)], ignore_index=ignore_index).to(score.device)).sum(-1)
loss = gaussian_loss + pinball_loss
return loss
class BertForQuantileRegression(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if self.config.regression_type == "regression":
self.num_labels = 1
elif self.config.regression_type == "gaussian_regression":
self.num_labels = 2
self.kl_weight = 0.0
if self.config.kl_weight > 0:
self.kl_weight = self.config.kl_weight
self.var_nonlin = torch.nn.functional.softplus
elif self.config.regression_type == "iqr_regression":
self.num_labels = len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "mse_pinball_regression":
self.num_labels = 1 + len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "gaussian_pinball_regression":
self.num_labels = 2
self.var_nonlin = torch.nn.functional.softplus
else:
self.num_labels = self.config.num_labels
self.config = config
self.bert = BertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, self.num_labels)
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
if self.config.regression_type == "gaussian_regression":
logits[:, 1] = self.var_nonlin(logits[:, 1].clone())
elif self.config.regression_type == "gaussian_pinball_regression":
logits[:, 1] = self.var_nonlin(logits[:, 1].clone())
loss = None
if labels is not None:
if self.config.regression_type == "regression":
loss_fct = torch.nn.MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.regression_type == "gaussian_regression":
loss_fct = gaussian_loss_fn
loss = loss_fct(logits, labels, kl_weight=self.kl_weight).mean()
elif self.config.regression_type == "iqr_regression":
loss_fct = pinball_loss_fn
loss = loss_fct(logits, labels, quantiles=torch.FloatTensor(self.quantiles).to(logits.device)).mean()
elif self.config.regression_type == "mse_pinball_regression":
loss_fct = mse_pinball_loss_fn
loss = loss_fct(logits, labels, quantiles=torch.FloatTensor(self.quantiles).to(logits.device)).mean()
elif self.config.regression_type == "gaussian_pinball_regression":
loss_fct = gaussian_pinball_loss_fn
loss = loss_fct(logits, labels).mean()
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class OPTForQuantileRegression(OPTPreTrainedModel):
def __init__(self, config):
config.dropout = 0.0
super().__init__(config)
if self.config.regression_type == "regression":
self.num_labels = 1
elif self.config.regression_type == "gaussian_regression":
self.num_labels = 2
self.kl_weight = 0.0
if self.config.kl_weight > 0:
self.kl_weight = self.config.kl_weight
self.var_nonlin = torch.nn.functional.softplus
elif self.config.regression_type == "iqr_regression":
self.num_labels = len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "mse_pinball_regression":
self.num_labels = 1 + len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "gaussian_pinball_regression":
self.num_labels = 2
self.var_nonlin = torch.nn.functional.softplus
else:
self.num_labels = self.config.num_labels
self.config = config
self.model = OPTModel(config)
self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False)
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
transformer_outputs = self.model(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = transformer_outputs[0]
logits = self.score(hidden_states)
if input_ids is not None:
batch_size, sequence_length = input_ids.shape[:2]
else:
batch_size, sequence_length = inputs_embeds.shape[:2]
if self.config.pad_token_id is None:
sequence_lengths = -1
else:
if input_ids is not None:
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
sequence_lengths = sequence_lengths % input_ids.shape[-1]
sequence_lengths = sequence_lengths.to(logits.device)
else:
sequence_lengths = -1
logger.warning(
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
)
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
if self.config.regression_type == "gaussian_regression":
pooled_logits[:, 1] = self.var_nonlin(pooled_logits[:, 1].clone())
elif self.config.regression_type == "gaussian_pinball_regression":
pooled_logits[:, 1] = self.var_nonlin(pooled_logits[:, 1].clone())
loss = None
if labels is not None:
if self.config.regression_type == "regression":
loss_fct = torch.nn.MSELoss()
if self.num_labels == 1:
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(pooled_logits, labels)
elif self.config.regression_type == "gaussian_regression":
loss_fct = gaussian_loss_fn
loss = loss_fct(pooled_logits, labels, kl_weight=self.kl_weight).mean()
elif self.config.regression_type == "iqr_regression":
loss_fct = pinball_loss_fn
loss = loss_fct(pooled_logits, labels, quantiles=torch.FloatTensor(self.quantiles).to(pooled_logits.device)).mean()
elif self.config.regression_type == "mse_pinball_regression":
loss_fct = mse_pinball_loss_fn
loss = loss_fct(pooled_logits, labels, quantiles=torch.FloatTensor(self.quantiles).to(pooled_logits.device)).mean()
elif self.config.regression_type == "gaussian_pinball_regression":
loss_fct = gaussian_pinball_loss_fn
loss = loss_fct(pooled_logits, labels).mean()
if not return_dict:
output = (pooled_logits,) + transformer_outputs[1:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutputWithPast(
loss=loss,
logits=pooled_logits,
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
def get_input_embeddings(self):
return self.model.decoder.embed_tokens
def set_input_embeddings(self, value):
self.model.decoder.embed_tokens = value
class GPTNeoXForQuantileRegression(GPTNeoXPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if self.config.regression_type == "regression":
self.num_labels = 1
elif self.config.regression_type == "gaussian_regression":
self.num_labels = 2
self.kl_weight = 0.0
if self.config.kl_weight > 0:
self.kl_weight = self.config.kl_weight
self.var_nonlin = torch.nn.functional.softplus
elif self.config.regression_type == "iqr_regression":
self.num_labels = len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "mse_pinball_regression":
self.num_labels = 1 + len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "gaussian_pinball_regression":
self.num_labels = 2
self.var_nonlin = torch.nn.functional.softplus
else:
self.num_labels = self.config.num_labels
self.config = config
self.gpt_neox = GPTNeoXModel(config)
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.FloatTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.gpt_neox(
input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = outputs[0]
logits = self.score(hidden_states)
if input_ids is not None:
batch_size, sequence_length = input_ids.shape[:2]
else:
batch_size, sequence_length = inputs_embeds.shape[:2]
if self.config.pad_token_id is None and batch_size != 1:
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
if self.config.pad_token_id is None:
sequence_lengths = -1
else:
if input_ids is not None:
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
sequence_lengths = sequence_lengths % input_ids.shape[-1]
sequence_lengths = sequence_lengths.to(logits.device)
else:
sequence_lengths = -1
logger.warning(
f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
)
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
if self.config.regression_type == "gaussian_regression":
pooled_logits[:, 1] = self.var_nonlin(pooled_logits[:, 1].clone())
elif self.config.regression_type == "gaussian_pinball_regression":
pooled_logits[:, 1] = self.var_nonlin(pooled_logits[:, 1].clone())
loss = None
if labels is not None:
labels = labels.to(pooled_logits.device)
if self.config.regression_type == "regression":
loss_fct = torch.nn.MSELoss()
if self.num_labels == 1:
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(pooled_logits, labels)
elif self.config.regression_type == "gaussian_regression":
loss_fct = gaussian_loss_fn
loss = loss_fct(pooled_logits, labels, kl_weight=self.kl_weight).mean()
elif self.config.regression_type == "iqr_regression":
loss_fct = pinball_loss_fn
loss = loss_fct(pooled_logits, labels, quantiles=torch.FloatTensor(self.quantiles).to(pooled_logits.device)).mean()
elif self.config.regression_type == "mse_pinball_regression":
loss_fct = mse_pinball_loss_fn
loss = loss_fct(pooled_logits, labels, quantiles=torch.FloatTensor(self.quantiles).to(pooled_logits.device)).mean()
elif self.config.regression_type == "gaussian_pinball_regression":
loss_fct = gaussian_pinball_loss_fn
loss = loss_fct(pooled_logits, labels).mean()
if not return_dict:
output = (pooled_logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutputWithPast(
loss=loss,
logits=pooled_logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class GPTNeoXForTokenQuantileRegression(GPTNeoXPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if self.config.regression_type == "regression":
self.num_labels = 1
elif self.config.regression_type == "gaussian_regression":
self.num_labels = 2
self.kl_weight = 0.0
if self.config.kl_weight > 0:
self.kl_weight = self.config.kl_weight
self.var_nonlin = torch.nn.functional.softplus
elif self.config.regression_type == "iqr_regression":
self.num_labels = len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "mse_pinball_regression":
self.num_labels = 1 + len(self.config.quantiles)
self.quantiles = self.config.quantiles
elif self.config.regression_type == "gaussian_pinball_regression":
self.num_labels = 2
self.var_nonlin = torch.nn.functional.softplus
else:
self.num_labels = self.config.num_labels
self.config = config
self.gpt_neox = GPTNeoXModel(config)
self.dropout = nn.Dropout(config.classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
head_mask: Optional[torch.FloatTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, TokenClassifierOutput]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.gpt_neox(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = outputs[0]
hidden_states = self.dropout(hidden_states)
logits = self.classifier(hidden_states)
if self.config.regression_type == "gaussian_regression":
logits[..., 1] = self.var_nonlin(logits[..., 1].clone())
elif self.config.regression_type == "gaussian_pinball_regression":
logits[..., 1] = self.var_nonlin(logits[..., 1].clone())
loss = None
if labels is not None:
labels = labels.to(logits.device)
shift_logits = logits[:, 1:, :].contiguous()
labels = labels[:, :-1].contiguous()
if self.config.regression_type == "regression":
loss_fct = mse_loss_fn
loss = loss_fct(shift_logits.view(-1), labels.view(-1)).mean()
elif self.config.regression_type == "gaussian_regression":
loss_fct = gaussian_loss_fn
loss = loss_fct(shift_logits.view(-1, self.num_labels), labels.view(-1), kl_weight=self.kl_weight).mean()
elif self.config.regression_type == "iqr_regression":
loss_fct = pinball_loss_fn
loss = loss_fct(shift_logits.view(-1, self.num_labels), labels.view(-1), quantiles=torch.FloatTensor(self.quantiles).to(logits.device)).mean()
elif self.config.regression_type == "mse_pinball_regression":
loss_fct = mse_pinball_loss_fn
loss = loss_fct(shift_logits.view(-1, self.num_labels), labels.view(-1), quantiles=torch.FloatTensor(self.quantiles).to(logits.device)).mean()
elif self.config.regression_type == "gaussian_pinball_regression":
loss_fct = gaussian_pinball_loss_fn
loss = loss_fct(shift_logits.view(-1, self.num_labels), labels.view(-1)).mean()
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)