-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbase_classes.py
621 lines (525 loc) · 17.2 KB
/
base_classes.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
609
610
611
612
613
614
615
616
617
618
619
620
621
"""
This module builds base trainer for all pre & downstream tasks.
Author: wangning([email protected])
Date : 2022/12/8 2:43 PM
"""
import copy
import os
import shutil
import numpy as np
import abc
import os.path as osp
from sklearn.metrics import (
accuracy_score,
precision_score,
recall_score,
f1_score,
matthews_corrcoef,
roc_auc_score
)
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle.fluid.reader import DataLoader, BatchSampler
from paddlenlp.data import Stack
from paddlenlp.transformers import ErnieForMaskedLM
# ===================== Common Modules =====================
class MlpProjector(nn.Layer):
"""MLP projection head.
"""
def __init__(self, n_in, output_size=128):
"""
Args:
n_in:
output_size:
"""
super(MlpProjector, self).__init__()
self.dense = nn.Linear(n_in, output_size)
self.activation = nn.ReLU()
self.projection = nn.Linear(output_size, output_size)
self.n_out = output_size
def forward(self, embeddings):
"""
Args:
embeddings:
Returns:
"""
x = self.dense(embeddings)
x = self.activation(x)
x = self.projection(x)
return x
class IndicatorClassifier(nn.Layer):
"""This class indicate coarse class after token [IND].
"""
def __init__(self, model_name_or_path):
"""
Args:
model_name_or_path:
"""
super(IndicatorClassifier, self).__init__()
self.indicator = ErnieForMaskedLM.from_pretrained(model_name_or_path)
def forward(self,
input_ids,
masked_positions):
"""
Args:
input_ids:
masked_positions:
Returns:
"""
with paddle.no_grad():
outputs = self.indicator(
input_ids, masked_positions=masked_positions)
return outputs
class MajorityVoter(nn.Layer):
"""Stack top k logits.
"""
def __init__(self):
"""
"""
super(MajorityVoter, self).__init__()
def forward(self, k_logits, topk_probs):
"""
Forward function.
Args:
k_logits:
topk_probs:
Returns:
"""
ensemble_logits = paddle.einsum('ijk,ij->ik', k_logits, topk_probs)
return ensemble_logits
# ===================== Base Classes =====================
class BaseTrainer(object):
"""Base trainer
"""
def __init__(self,
args,
tokenizer,
model,
pretrained_model=None,
indicator=None,
ensemble=None,
train_dataset=None,
eval_dataset=None,
data_collator=None,
loss_fn=None,
optimizer=None,
compute_metrics=None,
visual_writer=None):
"""init function
Args:
args: training args
tokenizer: convert sequence to ids
model: downstream task model
pretrained_model: pretrained model
indicator: indicator classifier
ensemble: ensemble model
train_dataset: dataset for training
eval_dataset: dataset for evaluation
data_collator: data collator
loss_fn: loss function
optimizer: optimizer for training
compute_metrics: metrics function
visual_writer: visualdl writer
Returns:
None
"""
self.args = args
self.tokenizer = tokenizer
self.model = model
self.pretrained_model = pretrained_model
self.indicator = indicator
self.ensemble = ensemble
self.train_dataset = train_dataset
self.eval_dataset = eval_dataset
self.data_collator = data_collator
self.loss_fn = loss_fn
self.optimizer = optimizer
self.compute_metrics = compute_metrics
# default name_pbar is the first metric
self.name_pbar = self.compute_metrics.metrics[0]
self.visual_writer = visual_writer
self.max_metric = 0.
self.max_model_dir = ""
# init dataloaders
self._prepare_dataloaders()
def _get_dataloader(self, dataset, sampler):
"""get dataloader, private function
Args:
dataset: dataset to be loaded
sampler: data sampler
Returns:
paddle.io.Dataloader: data loader
"""
return DataLoader(
dataset,
batch_sampler=sampler,
collate_fn=self.data_collator,
num_workers=self.args.dataloader_num_workers,
)
def _get_sampler(self, dataset):
"""get data sampler, private function
Args:
dataset: dataset to be loaded
Returns:
paddle.io.BatchSampler: data sampler
"""
return BatchSampler(dataset=dataset,
shuffle=True,
batch_size=self.args.batch_size,
drop_last=self.args.dataloader_drop_last)
def _prepare_dataloaders(self):
"""prepare dataloaders, private function
Returns:
None
"""
if self.train_dataset:
train_sampler = self._get_sampler(self.train_dataset)
self.train_dataloader = self._get_dataloader(
self.train_dataset, train_sampler)
if self.eval_dataset:
eval_sampler = self._get_sampler(self.eval_dataset)
self.eval_dataloader = self._get_dataloader(
self.eval_dataset, eval_sampler)
def save_model(self, metrics_dataset, epoch):
"""
Save model after epoch training in save_dir.
Args:
metrics_dataset: metrics of dataset
epoch: training epoch number
Returns:
None
"""
if metrics_dataset[self.name_pbar] > self.max_metric:
self.max_metric = metrics_dataset[self.name_pbar]
if os.path.exists(self.max_model_dir):
print("Remove old max model dir:", self.max_model_dir)
shutil.rmtree(self.max_model_dir)
self.max_model_dir = osp.join(
self.args.output, "epoch_" + str(epoch))
os.makedirs(self.max_model_dir)
save_model_path = osp.join(
self.max_model_dir, "model_state.pdparams")
paddle.save(self.model.state_dict(), save_model_path)
print("Model saved at:", save_model_path)
def get_input_ids_ind_topk(self, input_ids, seq_lens, indicator):
"""Get top k input ids with indications and return them.
Args:
input_ids: (B, L)
seq_lens: (B) or (B, Ch)
indicator:
Returns:
(token ids, probabilities)
"""
input_ids = paddle.unsqueeze(input_ids, axis=0)
(B, max_seq_len) = input_ids.shape
token_to_idx = self.tokenizer.vocab.token_to_idx
ind_id = token_to_idx[self.tokenizer.ind_token]
sep_id = token_to_idx[self.tokenizer.sep_token]
is_cross = (seq_lens <= max_seq_len - 2) # remove [SEP] & [LABEL] token
ind_positions = paddle.where(
is_cross, x=seq_lens - 1, y=max_seq_len - 3)
label_positions = ind_positions + 1
sep_positions = ind_positions + 2
for b in range(B):
input_ids[b, ind_positions[b]] = ind_id
input_ids[b, sep_positions[b]] = sep_id
masked_positions = copy.deepcopy(label_positions)
for i in range(1, B):
masked_positions[i] += i * max_seq_len
with paddle.no_grad():
ind_logtis = indicator(input_ids=input_ids,
masked_positions=masked_positions)
ind_logits = ind_logtis.detach() # [B, vocab_size]
# remove special tokens and bases (A, T, C, G)
ind_logits[:, :7] = float('-inf')
ind_logits[:, 35:] = float('-inf')
ind_probs = F.softmax(ind_logits, axis=-1)
# (B, k), (B)
topk_probs, topk_ind_ids = paddle.topk(
ind_probs, self.args.top_k, axis=-1, largest=True)
# (B*Ch, k, max_seq_len)
input_ids_inds = paddle.tile(input_ids.unsqueeze(
axis=1), repeat_times=(1, self.args.top_k, 1))
for b in range(B):
input_ids_inds[b, :, label_positions[b]] = paddle.t(topk_ind_ids[b])
# tested, add it has more accuracy
topk_probs = topk_probs / paddle.sum(topk_probs, axis=1, keepdim=True)
return input_ids_inds, topk_probs, topk_ind_ids
def train(self, epoch):
"""
Args:
epoch: training epoch
Returns:
None
"""
raise NotImplementedError("Must implement train method.")
def eval(self, epoch):
"""
Args:
epoch: eval epoch
Returns:
None
"""
raise NotImplementedError("Must implement eval method.")
class BaseCollator(object):
"""Data collator that will dynamically pad the inputs to the longest sequence in the batch and process them.
"""
def __init__(self):
"""
"""
self.stack_fn = Stack()
def __call__(self, data):
"""
Args:
data: instance for stack
Returns:
dict for trainer
"""
raise NotImplementedError("Must implement __call__ method.")
class BaseInstance(object):
"""A single instance for data collator.
"""
def __init__(self):
"""
"""
pass
def __call__(self):
"""
Returns:
class properties
"""
return vars(self).items()
class BaseMetrics(abc.ABC):
"""Base class for functional tasks metrics
"""
def __init__(self, metrics):
"""
Args:
metrics: names in list
"""
self.metrics = [x.lower() for x in metrics]
@abc.abstractmethod
def __call__(self, outputs, labels):
"""
Args:
kwargs: required args of model (dict)
Returns:
metrics in dict
"""
preds = paddle.argmax(outputs, axis=-1)
preds = paddle.cast(preds, 'int32')
preds = preds.numpy()
labels = paddle.cast(labels, 'int32')
labels = labels.numpy()
res = {}
for name in self.metrics:
func = getattr(self, name)
if func:
if func == self.auc:
# given two neural outputs, calculate their logits
# and then calculate auc
logits = F.sigmoid(outputs).cpu().numpy()
m = func(logits, labels)
else:
m = func(preds, labels)
res[name] = m
else:
raise NotImplementedError
return res
@staticmethod
def accuracy(preds, labels):
"""
All args have same shapes.
Args:
preds: predictions of model, (batch_size, 1)
labels: ground truth, (batch_size, 1)
Returns:
accuracy
"""
return accuracy_score(labels, preds)
@staticmethod
def precision(preds, labels):
"""
All args have same shapes.
Args:
preds: predictions of model, (batch_size, 1)
labels: ground truth, (batch_size, 1)
Returns:
precision
"""
return precision_score(labels, preds, average='macro')
@staticmethod
def recall(preds, labels):
"""
All args have same shapes.
Args:
preds: predictions of model, (batch_size, 1)
labels: ground truth, (batch_size, 1)
Returns:
precision
"""
return recall_score(labels, preds, average='macro')
@staticmethod
def f1s(preds, labels):
"""
All args have same shapes.
Args:
preds: predictions of model, (batch_size, 1)
labels: ground truth, (batch_size, 1)
Returns:
precision
"""
return f1_score(labels, preds, average='macro')
@staticmethod
def mcc(preds, labels):
"""
All args have same shapes.
Args:
preds: predictions of model, (batch_size, 1)
labels: ground truth, (batch_size, 1)
Returns:
precision
"""
return matthews_corrcoef(labels, preds)
@staticmethod
def auc(preds, labels):
"""
All args have same shapes.
Args:
preds: predictions of model, (batch_size, 1)
labels: ground truth, (batch_size, 1)
Returns:
precision
"""
labels += 1
preds = preds[:, 1]
return roc_auc_score(labels, preds)
class BaseStructMetrics(abc.ABC):
"""Base class for evaluation metrics
"""
def __init__(self, metrics):
"""
Args:
metrics: names in list
"""
self.metrics = [x.lower() for x in metrics]
@abc.abstractmethod
def __call__(self, **kwargs):
"""
Args:
kwargs: required args of model (dict)
Returns:
metrics in dict
"""
raise NotImplementedError("Must implement __call__ method.")
@staticmethod
def accuracy(logits, labels, mask=None):
"""
All args have same shapes.
Args:
logits: predictions of model, (batch_size, *)
labels: ground truth, (batch_size, *)
mask: valid sequence length masking, (batch_size, *)
Returns:
accuracy
"""
if mask is not None:
tp = np.sum(np.logical_and(np.logical_and(
np.equal(labels, 1), np.equal(logits, 1)), mask))
tn = np.sum(np.logical_and(np.logical_and(
np.equal(labels, 0), np.equal(logits, 0)), mask))
return (tp + tn) / np.sum(np.equal(mask, 1))
else:
tp = np.sum(np.logical_and(
np.equal(labels, 1), np.equal(logits, 1)))
tn = np.sum(np.logical_and(
np.equal(labels, 0), np.equal(logits, 0)), )
return (tp + tn) / labels.shape[0]
@staticmethod
def precision(logits, labels, mask=None):
"""
All args have same shapes.
Args:
logits: predictions of model, (batch_size, *)
labels: ground truth, (batch_size, *)
mask: valid sequence length masking, (batch_size, *)
Returns:
precision
"""
if mask is not None:
tp = np.sum(np.logical_and(np.logical_and(
np.equal(labels, 1), np.equal(logits, 1)), mask))
fp = np.sum(np.logical_and(np.logical_and(
np.equal(labels, 0), np.equal(logits, 1)), mask))
else:
tp = np.sum(np.logical_and(
np.equal(labels, 1), np.equal(logits, 1)))
fp = np.sum(np.logical_and(
np.equal(labels, 0), np.equal(logits, 1)), )
return tp / (tp + fp)
@staticmethod
def recall(logits, labels, mask=None):
"""
All args have same shapes.
Args:
logits: predictions of model, (batch_size, *)
labels: ground truth, (batch_size, *)
mask: valid sequence length masking, (batch_size, *)
Returns:
recall
"""
if mask is not None:
tp = np.sum(np.logical_and(np.logical_and(
np.equal(labels, 1), np.equal(logits, 1)), mask))
fn = np.sum(np.logical_and(np.logical_and(
np.equal(labels, 1), np.equal(logits, 0)), mask))
else:
tp = np.sum(np.logical_and(
np.equal(labels, 1), np.equal(logits, 1)))
fn = np.sum(np.logical_and(
np.equal(labels, 1), np.equal(logits, 0)), )
return tp / (tp + fn)
def f1s(self, logits, labels, mask=None):
"""
All args have same shapes.
Args:
logits: predictions of model, (batch_size, *)
labels: ground truth, (batch_size, *)
mask: valid sequence length masking, (batch_size, *)
Returns:
f1s
"""
p = self.precision(logits, labels, mask)
r = self.recall(logits, labels, mask)
metric = 2 * p * r / (p + r)
return metric
class FuncMetrics(object):
"""Metrics for classification
"""
def __init__(self, metrics):
"""
Args:
metrics: names in string
"""
self.metrics = [x.lower() for x in metrics]
def __call__(self, outputs, labels):
"""
Args:
outputs: output of model
labels: ground truth of data
Returns:
metrics in dict
"""
preds = paddle.concat(outputs, axis=0)
labels = paddle.concat(labels, axis=0)
res = {}
for name in self.metrics:
func = getattr(self, name)
if func:
m = func(preds, labels)
res[name] = m
else:
raise NotImplementedError(
"Metric {} is not implemented.".format(name))
return res