pheinisch commited on
Commit
6ade49b
1 Parent(s): e1eb1a0

Upload HGTrainer.py

Browse files
Files changed (1) hide show
  1. HGTrainer.py +432 -0
HGTrainer.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, Optional, Tuple, Literal
3
+
4
+ import torch
5
+ import numpy
6
+
7
+ from transformers import Trainer, PreTrainedModel, RobertaForSequenceClassification, BatchEncoding, RobertaConfig, \
8
+ EvalPrediction
9
+ from transformers.modeling_outputs import SequenceClassifierOutput, BaseModelOutput
10
+ from loguru import logger
11
+
12
+
13
+ def val_nov_loss(is_val: torch.Tensor, should_val: torch.Tensor, is_nov: torch.Tensor, should_nov: torch.Tensor,
14
+ weights: Optional[torch.Tensor] = None, reduce: bool = True) -> torch.Tensor:
15
+ if weights is None:
16
+ weights = torch.ones_like(should_val)
17
+ logger.debug("No weights-vector - assume, all {} samples should count equally", weights.size())
18
+
19
+ loss_validity = torch.pow(is_val - torch.where(torch.isnan(should_val), is_val, should_val), 2)
20
+ loss_novelty = torch.pow(is_nov - torch.where(torch.isnan(should_nov), is_nov, should_nov), 2)
21
+
22
+ logger.trace("loss_validity: {} / loss_novelty: {}", loss_validity, loss_novelty)
23
+
24
+ loss = (.5 * (loss_validity * loss_novelty) + .5 * loss_validity + .5 * loss_novelty) * weights
25
+
26
+ return torch.mean(loss) if reduce else loss
27
+
28
+
29
+ def val_nov_metric(eval_data: EvalPrediction) -> Dict[str, float]:
30
+ if isinstance(eval_data.predictions, Tuple) and isinstance(eval_data.label_ids, Tuple) \
31
+ or min(len(eval_data.predictions), len(eval_data.label_ids)) >= 2:
32
+ logger.trace("Format is as processable ({}: {})", type(eval_data.predictions), len(eval_data.predictions))
33
+ if len(eval_data.predictions) != 2:
34
+ logger.debug("We expect 2 tuples, but get {}: {}", len(eval_data.predictions), eval_data.predictions)
35
+
36
+ is_validity = eval_data.predictions[-2]
37
+ should_validity = eval_data.label_ids[-2]
38
+ is_novelty = eval_data.predictions[-1]
39
+ should_novelty = eval_data.label_ids[-1]
40
+
41
+ return _val_nov_metric(is_validity=is_validity, should_validity=should_validity,
42
+ is_novelty=is_novelty, should_novelty=should_novelty)
43
+ else:
44
+ logger.warning("This metric can't return all metrics properly, "
45
+ "because validity and novelty are not distinguishable")
46
+
47
+ return {
48
+ "size": numpy.size(eval_data.label_ids),
49
+ "mse_validity": numpy.mean((eval_data.predictions-eval_data.label_ids) ** 2),
50
+ "mse_novelty": numpy.mean((eval_data.predictions-eval_data.label_ids) ** 2),
51
+ "error_validity": numpy.mean(numpy.abs(eval_data.predictions-eval_data.label_ids)),
52
+ "error_novelty": numpy.mean(numpy.abs(eval_data.predictions-eval_data.label_ids)),
53
+ "approximately_hits_validity": -1,
54
+ "approximately_hits_novelty": -1,
55
+ "exact_hits_validity": -1,
56
+ "exact_hits_novelty": -1,
57
+ "approximately_hits": numpy.count_nonzero(
58
+ numpy.where(numpy.abs(eval_data.predictions-eval_data.label_ids) < .2, 1, 0)
59
+ ) / numpy.size(eval_data.predictions),
60
+ "exact_hits": numpy.count_nonzero(
61
+ numpy.where(numpy.abs(eval_data.predictions-eval_data.label_ids) < .05, 1, 0)
62
+ ) / numpy.size(eval_data.predictions),
63
+ "accuracy_validity": -1,
64
+ "accuracy_novelty": -1,
65
+ "accuracy": -1,
66
+ "f1_validity": -1,
67
+ "f1_novelty": -1,
68
+ "f1_macro": -1,
69
+ "never_predicted_classes": 4
70
+ }
71
+
72
+
73
+ def _val_nov_metric(is_validity: numpy.ndarray, should_validity: numpy.ndarray,
74
+ is_novelty: numpy.ndarray, should_novelty: numpy.ndarray) -> Dict[str, float]:
75
+ ret = {
76
+ "size": numpy.size(is_validity),
77
+ "mse_validity": numpy.mean((is_validity - should_validity) ** 2),
78
+ "mse_novelty": numpy.mean((is_novelty - should_novelty) ** 2),
79
+ "error_validity": numpy.mean(numpy.abs(is_validity - should_validity)),
80
+ "error_novelty": numpy.mean(numpy.abs(is_novelty - should_novelty)),
81
+ "approximately_hits_validity": numpy.sum(
82
+ numpy.where(numpy.abs(is_validity - should_validity) < .2, 1, 0)) / numpy.size(is_validity),
83
+ "approximately_hits_novelty": numpy.sum(
84
+ numpy.where(numpy.abs(is_novelty - should_novelty) < .2, 1, 0)) / numpy.size(is_novelty),
85
+ "exact_hits_validity": numpy.sum(
86
+ numpy.where(numpy.abs(is_validity - should_validity) < .05, 1, 0)) / numpy.size(is_validity),
87
+ "exact_hits_novelty": numpy.sum(
88
+ numpy.where(numpy.abs(is_novelty - should_novelty) < .05, 1, 0)) / numpy.size(is_novelty),
89
+ "approximately_hits": numpy.sum(
90
+ numpy.where(numpy.abs(is_validity - should_validity) + numpy.abs(is_novelty - should_novelty) < .25, 1, 0)
91
+ ) / numpy.size(is_validity),
92
+ "exact_hits": numpy.sum(
93
+ numpy.where(numpy.abs(is_validity - should_validity) + numpy.abs(is_novelty - should_novelty) < .05, 1, 0)
94
+ ) / numpy.size(is_validity),
95
+ "accuracy_validity": numpy.sum(numpy.where(
96
+ numpy.any(numpy.stack([
97
+ numpy.all(numpy.stack([is_validity >= .5, should_validity >= .5]), axis=0),
98
+ numpy.all(numpy.stack([is_validity < .5, should_validity < .5]), axis=0)
99
+ ]), axis=0),
100
+ 1, 0
101
+ )) / numpy.size(is_validity),
102
+ "accuracy_novelty": numpy.sum(numpy.where(
103
+ numpy.any(numpy.stack([
104
+ numpy.all(numpy.stack([is_novelty >= .5, should_novelty >= .5]), axis=0),
105
+ numpy.all(numpy.stack([is_novelty < .5, should_novelty < .5]), axis=0)
106
+ ]), axis=0),
107
+ 1, 0
108
+ )) / numpy.size(is_validity),
109
+ "accuracy": numpy.sum(numpy.where(
110
+ numpy.any(numpy.stack([
111
+ numpy.all(numpy.stack([is_validity >= .5, should_validity >= .5, is_novelty >= .5, should_novelty >= .5]),
112
+ axis=0),
113
+ numpy.all(numpy.stack([is_validity >= .5, should_validity >= .5, is_novelty < .5, should_novelty < .5]),
114
+ axis=0),
115
+ numpy.all(numpy.stack([is_validity < .5, should_validity < .5, is_novelty >= .5, should_novelty >= .5]),
116
+ axis=0),
117
+ numpy.all(numpy.stack([is_validity < .5, should_validity < .5, is_novelty < .5, should_novelty < .5]),
118
+ axis=0)
119
+ ]), axis=0),
120
+ 1, 0
121
+ )) / numpy.size(is_validity),
122
+ "never_predicted_classes": sum(
123
+ [int(numpy.all(numpy.abs(is_validity-validity) < .5) and numpy.all(numpy.abs(is_novelty-novelty) < .5))
124
+ for validity, novelty in [(1, 1), (1, 0), (0, 1), (0, 0)]]
125
+ )
126
+ }
127
+
128
+ ret_base_help = {
129
+ "true_positive_validity": numpy.sum(numpy.where(
130
+ numpy.all(numpy.stack([is_validity >= .5, should_validity >= .5]), axis=0),
131
+ 1, 0)),
132
+ "true_negative_validity": numpy.sum(numpy.where(
133
+ numpy.all(numpy.stack([is_validity < .5, should_validity < .5]), axis=0),
134
+ 1, 0)),
135
+ "true_positive_novelty": numpy.sum(numpy.where(
136
+ numpy.all(numpy.stack([is_novelty >= .5, should_novelty >= .5]), axis=0),
137
+ 1, 0)),
138
+ "true_negative_novelty": numpy.sum(numpy.where(
139
+ numpy.all(numpy.stack([is_novelty < .5, should_novelty < .5]), axis=0),
140
+ 1, 0)),
141
+ "true_positive_valid_novel": numpy.sum(numpy.where(
142
+ numpy.all(numpy.stack([is_validity >= .5, is_novelty >= .5,
143
+ should_validity >= .5, should_novelty >= .5]), axis=0),
144
+ 1, 0)),
145
+ "true_positive_nonvalid_novel": numpy.sum(numpy.where(
146
+ numpy.all(numpy.stack([is_validity < .5, is_novelty >= .5,
147
+ should_validity < .5, should_novelty >= .5]), axis=0),
148
+ 1, 0)),
149
+ "true_positive_valid_nonnovel": numpy.sum(numpy.where(
150
+ numpy.all(numpy.stack([is_validity >= .5, is_novelty < .5,
151
+ should_validity >= .5, should_novelty < .5]), axis=0),
152
+ 1, 0)),
153
+ "true_positive_nonvalid_nonnovel": numpy.sum(numpy.where(
154
+ numpy.all(numpy.stack([is_validity < .5, is_novelty < .5,
155
+ should_validity < .5, should_novelty < .5]), axis=0),
156
+ 1, 0)),
157
+ "classified_positive_validity": numpy.sum(numpy.where(is_validity >= .5, 1, 0)),
158
+ "classified_negative_validity": numpy.sum(numpy.where(is_validity < .5, 1, 0)),
159
+ "classified_positive_novelty": numpy.sum(numpy.where(is_novelty >= .5, 1, 0)),
160
+ "classified_negative_novelty": numpy.sum(numpy.where(is_novelty < .5, 1, 0)),
161
+ "classified_positive_valid_novel": numpy.sum(numpy.where(
162
+ numpy.all(numpy.stack([is_validity >= .5, is_novelty >= .5]), axis=0),
163
+ 1, 0)),
164
+ "classified_positive_nonvalid_novel": numpy.sum(numpy.where(
165
+ numpy.all(numpy.stack([is_validity < .5, is_novelty >= .5]), axis=0),
166
+ 1, 0)),
167
+ "classified_positive_valid_nonnovel": numpy.sum(numpy.where(
168
+ numpy.all(numpy.stack([is_validity >= .5, is_novelty < .5]), axis=0),
169
+ 1, 0)),
170
+ "classified_positive_nonvalid_nonnovel": numpy.sum(numpy.where(
171
+ numpy.all(numpy.stack([is_validity < .5, is_novelty < .5]), axis=0),
172
+ 1, 0)),
173
+ "indeed_positive_validity": numpy.sum(numpy.where(should_validity >= .5, 1, 0)),
174
+ "indeed_negative_validity": numpy.sum(numpy.where(should_validity < .5, 1, 0)),
175
+ "indeed_positive_novelty": numpy.sum(numpy.where(should_novelty >= .5, 1, 0)),
176
+ "indeed_negative_novelty": numpy.sum(numpy.where(should_novelty < .5, 1, 0)),
177
+ "indeed_positive_valid_novel": numpy.sum(numpy.where(
178
+ numpy.all(numpy.stack([should_validity >= .5, should_novelty >= .5]), axis=0),
179
+ 1, 0)),
180
+ "indeed_positive_nonvalid_novel": numpy.sum(numpy.where(
181
+ numpy.all(numpy.stack([should_validity < .5, should_novelty >= .5]), axis=0),
182
+ 1, 0)),
183
+ "indeed_positive_valid_nonnovel": numpy.sum(numpy.where(
184
+ numpy.all(numpy.stack([should_validity >= .5, should_novelty < .5]), axis=0),
185
+ 1, 0)),
186
+ "indeed_positive_nonvalid_nonnovel": numpy.sum(numpy.where(
187
+ numpy.all(numpy.stack([should_validity < .5, should_novelty < .5]), axis=0),
188
+ 1, 0)),
189
+ }
190
+
191
+ ret_help = {
192
+ "precision_validity": ret_base_help["true_positive_validity"] /
193
+ max(1, ret_base_help["classified_positive_validity"]),
194
+ "precision_novelty": ret_base_help["true_positive_novelty"] /
195
+ max(1, ret_base_help["classified_positive_novelty"]),
196
+ "recall_validity": ret_base_help["true_positive_validity"] /
197
+ max(1, ret_base_help["indeed_positive_validity"]),
198
+ "recall_novelty": ret_base_help["true_positive_novelty"] /
199
+ max(1, ret_base_help["indeed_positive_novelty"]),
200
+ "precision_val_neg": ret_base_help["true_negative_validity"] /
201
+ max(1, ret_base_help["classified_negative_validity"]),
202
+ "precision_nov_neg": ret_base_help["true_negative_novelty"] /
203
+ max(1, ret_base_help["classified_negative_novelty"]),
204
+ "recall_val_neg": ret_base_help["true_negative_validity"] /
205
+ max(1, ret_base_help["indeed_negative_validity"]),
206
+ "recall_nov_neg": ret_base_help["true_negative_novelty"] /
207
+ max(1, ret_base_help["indeed_negative_novelty"]),
208
+ "precision_valid_novel": ret_base_help["true_positive_valid_novel"] /
209
+ max(1, ret_base_help["classified_positive_valid_novel"]),
210
+ "precision_valid_nonnovel": ret_base_help["true_positive_valid_nonnovel"] /
211
+ max(1, ret_base_help["classified_positive_valid_nonnovel"]),
212
+ "precision_nonvalid_novel": ret_base_help["true_positive_nonvalid_novel"] /
213
+ max(1, ret_base_help["classified_positive_nonvalid_novel"]),
214
+ "precision_nonvalid_nonnovel": ret_base_help["true_positive_nonvalid_nonnovel"] /
215
+ max(1, ret_base_help["classified_positive_nonvalid_nonnovel"]),
216
+ "recall_valid_novel": ret_base_help["true_positive_valid_novel"] /
217
+ max(1, ret_base_help["indeed_positive_valid_novel"]),
218
+ "recall_valid_nonnovel": ret_base_help["true_positive_valid_nonnovel"] /
219
+ max(1, ret_base_help["indeed_positive_valid_nonnovel"]),
220
+ "recall_nonvalid_novel": ret_base_help["true_positive_nonvalid_novel"] /
221
+ max(1, ret_base_help["indeed_positive_nonvalid_novel"]),
222
+ "recall_nonvalid_nonnovel": ret_base_help["true_positive_nonvalid_nonnovel"] /
223
+ max(1, ret_base_help["indeed_positive_nonvalid_nonnovel"])
224
+ }
225
+
226
+ ret.update({
227
+ "f1_validity": 2 * ret_help["precision_validity"] * ret_help["recall_validity"] /
228
+ max(1e-4, ret_help["precision_validity"] + ret_help["recall_validity"]),
229
+ "f1_novelty": 2 * ret_help["precision_novelty"] * ret_help["recall_novelty"] /
230
+ max(1e-4, ret_help["precision_novelty"] + ret_help["recall_novelty"]),
231
+ "f1_val_neg": 2 * ret_help["precision_val_neg"] * ret_help["recall_val_neg"] /
232
+ max(1e-4, ret_help["precision_val_neg"] + ret_help["recall_val_neg"]),
233
+ "f1_nov_neg": 2 * ret_help["precision_nov_neg"] * ret_help["recall_nov_neg"] /
234
+ max(1e-4, ret_help["precision_nov_neg"] + ret_help["recall_nov_neg"]),
235
+ "f1_valid_novel": 2 * ret_help["precision_valid_novel"] * ret_help["recall_valid_novel"] /
236
+ max(1e-4, ret_help["precision_valid_novel"] + ret_help["recall_valid_novel"]),
237
+ "f1_valid_nonnovel": 2 * ret_help["precision_valid_nonnovel"] * ret_help["recall_valid_nonnovel"] /
238
+ max(1e-4, ret_help["precision_valid_nonnovel"] + ret_help["recall_valid_nonnovel"]),
239
+ "f1_nonvalid_novel": 2 * ret_help["precision_nonvalid_novel"] * ret_help["recall_nonvalid_novel"] /
240
+ max(1e-4, ret_help["precision_nonvalid_novel"] + ret_help["recall_nonvalid_novel"]),
241
+ "f1_nonvalid_nonnovel": 2 * ret_help["precision_nonvalid_nonnovel"] * ret_help["recall_nonvalid_nonnovel"] /
242
+ max(1e-4, ret_help["precision_nonvalid_nonnovel"] + ret_help["recall_nonvalid_nonnovel"])
243
+ })
244
+
245
+ ret.update({
246
+ "f1_val_macro": (ret["f1_validity"] + ret["f1_val_neg"])/2,
247
+ "f1_nov_macro": (ret["f1_novelty"] + ret["f1_nov_neg"])/2,
248
+ "f1_macro": (ret["f1_valid_novel"]+ret["f1_valid_nonnovel"]+ret["f1_nonvalid_novel"]+ret["f1_nonvalid_nonnovel"])/4
249
+ })
250
+
251
+ logger.info("Clean the metric-dict before returning: {}",
252
+ " / ".join(map(lambda key: "{}: {}".format(key, ret.pop(key)),
253
+ ["approximately_hits_validity", "approximately_hits_novelty", "exact_hits_validity",
254
+ "exact_hits_novelty", "size"])))
255
+
256
+ return ret
257
+
258
+
259
+ # noinspection PyMethodMayBeStatic
260
+ class ValNovTrainer(Trainer):
261
+ def compute_loss(self, model: PreTrainedModel, inputs: Dict[str, torch.Tensor], return_outputs=False):
262
+ try:
263
+ validity = inputs.pop("validity")
264
+ novelty = inputs.pop("novelty")
265
+ weights = inputs.pop("weight")
266
+ logger.trace("The batch contain following validity-scores ({}), novelty-scores ({}) and weights ({})",
267
+ validity, novelty, weights)
268
+
269
+ outputs = model(**inputs)
270
+
271
+ if isinstance(outputs, ValNovOutput) and outputs.loss is not None:
272
+ logger.debug("The loss was already computed: {}", outputs.loss)
273
+ return (outputs.loss, outputs) if return_outputs else outputs.loss
274
+
275
+ if isinstance(outputs, ValNovOutput):
276
+ is_val = outputs.validity
277
+ is_nov = outputs.novelty
278
+ else:
279
+ logger.warning("The output of you model {} is a {}, bit should be a ValNovOutput",
280
+ model.name_or_path, type(outputs))
281
+ is_val = outputs[0] if isinstance(outputs, Tuple) and len(outputs) >= 2 else outputs
282
+ is_nov = outputs[1] if isinstance(outputs, Tuple) and len(outputs) >= 2 else outputs
283
+
284
+ loss = val_nov_loss(is_val=is_val, is_nov=is_nov,
285
+ should_val=validity, should_nov=novelty,
286
+ weights=weights)
287
+
288
+ return (loss, outputs) if return_outputs else loss
289
+ except KeyError:
290
+ logger.opt(exception=True).error("Something in your configuration / plugged model is false")
291
+
292
+ return (torch.zeros((0,), dtype=torch.float), model(**inputs)) if return_outputs \
293
+ else torch.zeros((0,), dtype=torch.float)
294
+
295
+
296
+ @dataclass
297
+ class ValNovOutput(SequenceClassifierOutput):
298
+ validity: torch.FloatTensor = None
299
+ novelty: torch.FloatTensor = None
300
+
301
+
302
+ class ValNovRegressor(torch.nn.Module):
303
+ def __init__(self, transformer: PreTrainedModel,
304
+ loss: Literal["ignore", "compute", "compute and reduce"] = "ignore"):
305
+ super(ValNovRegressor, self).__init__()
306
+
307
+ self.transformer = transformer
308
+ try:
309
+ self.regression_layer_validity = torch.nn.Linear(in_features=transformer.config.hidden_size, out_features=1)
310
+ self.regression_layer_novelty = torch.nn.Linear(in_features=transformer.config.hidden_size, out_features=1)
311
+ except AttributeError:
312
+ logger.opt(exception=True).warning("No hidden-size... please use a XXXForMaskedLM-Model!")
313
+ self.regression_layer_validity = torch.nn.LazyLinear(out_features=1)
314
+ self.regression_layer_novelty = torch.nn.LazyLinear(out_features=1)
315
+
316
+ self.sigmoid = torch.nn.Sigmoid()
317
+ if loss == "ignore":
318
+ logger.info("torch-Module without an additional loss computation during the forward-pass - "
319
+ "has to be done explicitly in the training loop!")
320
+ self.loss = loss
321
+
322
+ logger.success("Successfully created {}", self)
323
+
324
+ def forward(self, x: BatchEncoding) -> ValNovOutput:
325
+ transformer_cls: BaseModelOutput = self.transformer(input_ids=x["input_ids"],
326
+ attention_mask=x["attention_mask"],
327
+ token_type_ids=x["token_type_ids"],
328
+ return_dict=True)
329
+
330
+ cls_logits = transformer_cls.last_hidden_state[0]
331
+
332
+ validity_logits = self.regression_layer_validity(cls_logits)
333
+ novelty_logits = self.regression_layer_novelty(cls_logits)
334
+
335
+ return ValNovOutput(
336
+ logits=torch.stack([validity_logits, novelty_logits]),
337
+ loss=val_nov_loss(is_val=self.sigmoid(validity_logits),
338
+ is_nov=self.sigmoid(novelty_logits),
339
+ should_val=x["validity"],
340
+ should_nov=x["novelty"],
341
+ weights=x.get("weight", None),
342
+ reduce=self.loss == "compute and reduce"
343
+ ) if self.loss != "ignore" and "validity" in x and "novelty" in x else None,
344
+ hidden_states=transformer_cls.hidden_states,
345
+ attentions=transformer_cls.attentions,
346
+ validity=self.sigmoid(validity_logits),
347
+ novelty=self.sigmoid(novelty_logits)
348
+ )
349
+
350
+ def __str__(self) -> str:
351
+ return "() --> ({} --> validity/ {} --> novelty)".format(self.transformer.name_or_path,
352
+ self.regression_layer_validity,
353
+ self.regression_layer_novelty)
354
+
355
+
356
+ class RobertaForValNovRegression(RobertaForSequenceClassification):
357
+ def __init__(self, *model_args, **model_kwargs):
358
+ config = RobertaForValNovRegression.get_config()
359
+
360
+ configs = [arg for arg in model_args if isinstance(arg, RobertaConfig)]
361
+ if len(configs) >= 1:
362
+ logger.warning("Found already {} config {}... extend it", len(configs), configs[0])
363
+ model_args = [arg for arg in model_args if not isinstance(arg, RobertaConfig)]
364
+ config = configs[0]
365
+ config.num_labels = 2
366
+ config.id2label = {
367
+ 0: "validity",
368
+ 1: "novelty"
369
+ }
370
+ config.return_dict = True
371
+
372
+ super().__init__(config=config, *model_args, **model_kwargs)
373
+
374
+ self.loss = "compute"
375
+ self.sigmoid = torch.nn.Sigmoid()
376
+
377
+ @classmethod
378
+ def get_config(cls) -> RobertaConfig:
379
+ config = RobertaConfig()
380
+ config.finetuning_task = "Validity-Novelty-Prediction"
381
+ config.num_labels = 2
382
+ config.id2label = {
383
+ 0: "validity",
384
+ 1: "novelty"
385
+ }
386
+ config.return_dict = True
387
+
388
+ return config
389
+
390
+ def forward(self, **kwargs):
391
+ logger.trace("Found {} forward-params", len(kwargs))
392
+ if "labels" in kwargs:
393
+ labels = kwargs.pop("labels")
394
+ logger.warning("Found a disturbing param in forward-function: labels ({})", labels)
395
+ if "return_dict" in kwargs:
396
+ return_dict = kwargs.pop("return_dict")
397
+ logger.warning("Found a disturbing param in forward-function: return_dict ({})", return_dict)
398
+
399
+ should_validity = None
400
+ if "validity" in kwargs:
401
+ should_validity = kwargs.pop("validity")
402
+ logger.trace("Found a target validity-vector: {}", should_validity)
403
+
404
+ should_novelty = None
405
+ if "novelty" in kwargs:
406
+ should_novelty = kwargs.pop("novelty")
407
+ logger.trace("Found a target novelty-vector: {}", should_novelty)
408
+
409
+ weights = None
410
+ if "weight" in kwargs:
411
+ weights = kwargs.pop("weight")
412
+ logger.trace("Found a sample-weights-vector: {}", weights)
413
+
414
+ out: SequenceClassifierOutput = super().forward(**kwargs)
415
+ is_validity = self.sigmoid(out.logits[:, 0])
416
+ is_novelty = self.sigmoid(out.logits[:, 1])
417
+
418
+ return ValNovOutput(
419
+ attentions=out.attentions,
420
+ hidden_states=out.hidden_states,
421
+ logits=out.logits,
422
+ loss=val_nov_loss(
423
+ is_val=is_validity,
424
+ is_nov=is_novelty,
425
+ should_val=should_validity,
426
+ should_nov=should_novelty,
427
+ weights=weights,
428
+ reduce=self.loss == "compute and reduce"
429
+ ) if self.loss != "ignore" and should_validity is not None and should_novelty is not None else None,
430
+ validity=is_validity,
431
+ novelty=is_novelty
432
+ )