-
Notifications
You must be signed in to change notification settings - Fork 3
/
train_exp073.py
1259 lines (970 loc) · 40.4 KB
/
train_exp073.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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from transformers import get_linear_schedule_with_warmup, \
get_cosine_schedule_with_warmup, \
get_polynomial_decay_schedule_with_warmup, get_constant_schedule_with_warmup
def get_scheduler(optimizer, config, num_train_steps):
if config.scheduler.type == 'constant_schedule_with_warmup':
scheduler = get_constant_schedule_with_warmup(
optimizer,
num_warmup_steps=config.scheduler.constant_schedule_with_warmup.n_warmup_steps
)
elif config.scheduler.type == 'linear_schedule_with_warmup':
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=config.scheduler.linear_schedule_with_warmup.n_warmup_steps,
num_training_steps=num_train_steps
)
elif config.scheduler.type == 'cosine_schedule_with_warmup':
scheduler = get_cosine_schedule_with_warmup(
optimizer,
num_warmup_steps=config.scheduler.cosine_schedule_with_warmup.n_warmup_steps,
num_cycles=config.scheduler.cosine_schedule_with_warmup.n_cycles,
num_training_steps=num_train_steps,
)
elif config.scheduler.type == 'polynomial_decay_schedule_with_warmup':
scheduler = get_polynomial_decay_schedule_with_warmup(
optimizer,
num_warmup_steps=config.scheduler.polynomial_decay_schedule_with_warmup.n_warmup_steps,
num_training_steps=num_train_steps,
power=config.scheduler.polynomial_decay_schedule_with_warmup.power,
lr_end=config.scheduler.polynomial_decay_schedule_with_warmup.min_lr
)
else:
raise ValueError(f'Unknown scheduler: {config.scheduler.scheduler_type}')
return scheduler
# File: src/training/scheduler.py
from collections import defaultdict
from typing import Dict
from tqdm.auto import tqdm
class PRFScore:
"""A precision / recall / F score."""
def __init__(
self,
*,
tp: int = 0,
fp: int = 0,
fn: int = 0,
) -> None:
self.tp = tp
self.fp = fp
self.fn = fn
def __len__(self) -> int:
return self.tp + self.fp + self.fn
def __iadd__(self, other): # in-place add
self.tp += other.tp
self.fp += other.fp
self.fn += other.fn
return self
def __add__(self, other):
return PRFScore(
tp=self.tp + other.tp, fp=self.fp + other.fp, fn=self.fn + other.fn
)
def score_set(self, cand: set, gold: set) -> None:
self.tp += len(cand.intersection(gold))
self.fp += len(cand - gold)
self.fn += len(gold - cand)
@property
def precision(self) -> float:
return self.tp / (self.tp + self.fp + 1e-100)
@property
def recall(self) -> float:
return self.tp / (self.tp + self.fn + 1e-100)
@property
def f1(self) -> float:
p = self.precision
r = self.recall
return 2 * ((p * r) / (p + r + 1e-100))
@property
def f5(self) -> float:
beta = 5
p = self.precision
r = self.recall
fbeta = (1+(beta**2))*p*r / ((beta**2)*p + r + 1e-100)
return fbeta
def to_dict(self) -> Dict[str, float]:
return {"p": self.precision, "r": self.recall, "f5": self.f5}
def compute_fbeta(valid_df, pred_df):
references = {(row.document, row.token, row.label) for row in valid_df.itertuples()}
predictions = {(row.document, row.token, row.label) for row in pred_df.itertuples()}
score_per_type = defaultdict(PRFScore)
references = set(references)
for ex in predictions:
pred_type = ex[-1] # (document, token, label)
if pred_type != 'O':
pred_type = pred_type[2:] # avoid B- and I- prefix
if pred_type not in score_per_type:
score_per_type[pred_type] = PRFScore()
if ex in references:
score_per_type[pred_type].tp += 1
references.remove(ex)
else:
score_per_type[pred_type].fp += 1
for doc, tok, ref_type in references:
if ref_type != 'O':
ref_type = ref_type[2:] # avoid B- and I- prefix
if ref_type not in score_per_type:
score_per_type[ref_type] = PRFScore()
score_per_type[ref_type].fn += 1
totals = PRFScore()
for prf in score_per_type.values():
totals += prf
results = {
"precision": totals.precision,
"recall": totals.recall,
"fbeta": totals.f5,
"ents_per_type": {k: v.to_dict() for k, v in score_per_type.items() if k!= 'O'},
}
return results
def compute_metrics(p, id2label, valid_ds, valid_df, threshold=0.9):
"""
Compute the LB metric (lb) and other auxiliary metrics
"""
predictions, labels = p
pred_df = parse_predictions(predictions, id2label, valid_ds, threshold=threshold)
all_labels = ['B-EMAIL', 'B-ID_NUM', 'B-NAME_STUDENT', 'B-PHONE_NUM', 'B-STREET_ADDRESS', 'B-URL_PERSONAL', 'B-USERNAME', 'I-ID_NUM', 'I-NAME_STUDENT', 'I-PHONE_NUM', 'I-STREET_ADDRESS', 'I-URL_PERSONAL', 'O']
keep = []
for label in tqdm(pred_df.label.values):
if label not in all_labels:
keep.append(False)
else:
keep.append(True)
pred_df = pred_df[keep]
fbeta_post = compute_fbeta(valid_df, pred_df)
pred_df = parse_predictions(predictions, id2label, valid_ds, threshold=0)
fbeta = compute_fbeta(valid_df, pred_df)
fbeta_best = max(fbeta_post['fbeta'], fbeta['fbeta'])
return {'fbeta': fbeta['fbeta'], 'fbeta_best': fbeta_best, 'fbeta_post': fbeta_post['fbeta']}
def pii_fbeta_score(pred_df, gt_df, beta=5):
"""
Parameters:
- pred_df (DataFrame): DataFrame containing predicted PII labels.
- gt_df (DataFrame): DataFrame containing ground truth PII labels.
- beta (float): The beta parameter for the F-beta score, controlling the trade-off between precision and recall.
Returns:
- float: Micro F-beta score.
"""
df = pred_df.merge(gt_df, how="outer", on=["document", "token"], suffixes=("_pred", "_gt"))
df["cm"] = ""
df.loc[df.label_gt.isna(), "cm"] = "FP"
df.loc[df.label_pred.isna(), "cm"] = "FN"
df.loc[(df.label_gt.notna() & df.label_pred.notna()) & (df.label_gt != df.label_pred), "cm"] = "FNFP" # CHANGED
df.loc[
(df.label_pred.notna()) & (df.label_gt.notna()) & (df.label_gt == df.label_pred), "cm"
] = "TP"
FP = (df["cm"].isin({"FP", "FNFP"})).sum()
FN = (df["cm"].isin({"FN", "FNFP"})).sum()
TP = (df["cm"] == "TP").sum()
s_micro = (1+(beta**2))*TP/(((1+(beta**2))*TP) + ((beta**2)*FN) + FP)
#### some changes to check wandb versioning
return s_micro
# File: src/training/metrics.py
import torch
import os
import torch
import random
import numpy as np
import pandas as pd
from tqdm.auto import tqdm
from copy import deepcopy
def seed_everything(seed=42):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
def get_valid_steps(num_train_steps, n_evaluations):
eval_steps = num_train_steps // n_evaluations
eval_steps = [eval_steps * i for i in range(1, n_evaluations + 1)]
return eval_steps
def parse_predictions(predictions, id2label, ds, threshold=0.9):
pred_softmax = np.exp(predictions) / np.sum(np.exp(predictions), axis = 2).reshape(predictions.shape[0],predictions.shape[1],1)
preds = predictions.argmax(-1)
preds_without_O = pred_softmax[:,:,:12].argmax(-1)
O_preds = pred_softmax[:,:,12]
preds_final = np.where(O_preds < threshold, preds_without_O , preds)
pairs = []
document, token, label, token_str = [], [], [], []
for p, token_map, offsets, tokens, doc, indices in zip(preds_final, ds["token_map"], ds["offset_mapping"], ds["tokens"], ds["document"], ds["token_indices"]):
for token_pred, (start_idx, end_idx) in zip(p, offsets):
label_pred = id2label[token_pred]
if start_idx + end_idx == 0: continue
if token_map[start_idx] == -1:
start_idx += 1
# ignore "\n\n"
while start_idx < len(token_map) and tokens[token_map[start_idx]].isspace():
start_idx += 1
if start_idx >= len(token_map): break
original_token_id = token_map[start_idx]
token_id = indices[original_token_id]
# ignore "O" predictions and whitespace preds
if label_pred != "O" and token_id != -1:
pair=(doc, token_id)
if pair not in pairs:
document.append(doc)
token.append(token_id)
label.append(label_pred)
token_str.append(tokens[original_token_id])
pairs.append(pair)
df = pd.DataFrame({
# "eval_row": row,
"document": document,
"token": token,
"label": label,
"token_str": token_str
})
df = df.drop_duplicates(['document', 'token', 'label', 'token_str']).reset_index(drop=True)
df["row_id"] = list(range(len(df)))
return df
# File: src/training/utils.py
# import torch
import torch.nn as nn
from types import SimpleNamespace
import numpy as np
import gc
from tqdm import tqdm
import torch
import random
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def batch_to_device(batch):
for k, v in batch.items():
if type(v) == dict:
for _k, _v in v.items():
if len(v) == 1:
v = v[0].unsqueeze(0)
v[_k] = _v.to(device)
batch[k] = v
else:
if len(v) == 1:
v = v[0].unsqueeze(0)
batch[k] = v.to(device)
return batch
class Trainer:
def __init__(
self,
model: nn.Module,
config: SimpleNamespace,
train_dataloader: torch.utils.data.DataLoader=None,
valid_dataloader: torch.utils.data.DataLoader=None,
optimizer: torch.optim.Optimizer=None,
scheduler: torch.optim.lr_scheduler=None,
eval_steps=None,
callbacks=None,
) -> None:
self.model = model
self.optimizer = optimizer
self.scheduler = scheduler
self.config = config
self.train_dataloader = train_dataloader
self.valid_dataloader = valid_dataloader
self.scaler = torch.cuda.amp.GradScaler(enabled=self.config.training.apex)
self.eval_steps = eval_steps
self.callbacks = callbacks
def validate(self):
self.model.eval()
self.callbacks.on_valid_epoch_start()
predictions = []
target = []
for step, inputs in enumerate(self.valid_dataloader):
inputs = batch_to_device(inputs)
with torch.no_grad():
with torch.cuda.amp.autocast():
y_pred, loss = self.model(inputs)
y_pred = torch.sigmoid(y_pred)
predictions.append(y_pred.detach().to('cpu').numpy())
target.append(inputs['labels'].cpu().numpy())
self.callbacks.on_valid_step_end(loss)
predictions = np.concatenate(predictions)
target = np.concatenate(target)
return predictions, target
def predict(self, test_loader):
predictions = []
self.model.eval()
self.model.to(device)
for inputs in tqdm(test_loader, total=len(test_loader)):
inputs = batch_to_device(inputs)
with torch.no_grad():
with torch.cuda.amp.autocast():
y_preds, _ = self.model(inputs)
y_preds = torch.sigmoid(y_preds)
predictions.append(y_preds.detach().to('cpu').numpy())
predictions = np.concatenate(predictions)
return predictions
def get_embeddings(self, test_loader):
predictions = []
self.model.eval()
self.model.to(device)
for inputs in tqdm(test_loader, total=len(test_loader)):
inputs = batch_to_device(inputs)
with torch.no_grad():
with torch.cuda.amp.autocast():
outputs = self.model.backbone(inputs['input_ids'], inputs['attention_mask'])
embeddings = self.model.pooling(inputs, outputs)
predictions.append(embeddings.detach().to('cpu').numpy())
predictions = np.concatenate(predictions)
return predictions
def train(self):
self.model.to(device)
self.callbacks.on_training_start()
for epoch in range(self.config.training.epochs):
self.model.train()
self.callbacks.on_train_epoch_start()
for step, inputs in enumerate(self.train_dataloader):
inputs = batch_to_device(inputs)
if self.config.training.apex:
with torch.cuda.amp.autocast():
y_pred, loss = self.model(inputs)
raw_loss = loss.item()
self.scaler.scale(loss).backward()
self.scaler.unscale_(self.optimizer)
grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(),
self.config.training.max_grad_norm)
self.scaler.step(self.optimizer)
self.scaler.update()
else:
y_pred, loss, skip = self.model(inputs)
raw_loss = loss.item()
loss.backward()
grad_norm = torch.nn.utils.clip_grad_norm_(self.model.parameters(),
self.config.training.max_grad_norm)
self.optimizer.step()
self.optimizer.zero_grad()
self.scheduler.step()
learning_rates = self.scheduler.get_last_lr()
self.callbacks.on_train_step_end(raw_loss, grad_norm, learning_rates)
if (step + 1) in self.eval_steps:
predictions, target = self.validate()
self.model.train()
self.callbacks.on_valid_epoch_end(target, predictions)
score_improved = self.callbacks.get('MetricsHandler').is_valid_score_improved()
if score_improved:
self.save_best_model(predictions)
self.callbacks.on_train_epoch_end()
self.save_checkpoint()
torch.cuda.empty_cache()
gc.collect()
return None
def save_best_model(self, predictions):
torch.save(
{
'model': self.model.state_dict(),
'predictions': predictions
},
self.config.best_model_path
)
def save_checkpoint(self):
torch.save(
{
'model': self.model.state_dict()
},
self.config.checkpoint_path
)
# File: src/training/trainer.py
from transformers import AutoConfig, AutoModelForTokenClassification, AutoModel
from transformers.modeling_outputs import TokenClassifierOutput
from transformers.models.deberta.modeling_deberta import DebertaPreTrainedModel, DebertaModel
import torch
import torch.nn as nn
class CustomModel(DebertaPreTrainedModel):
def __init__(self, config, model_path='microsoft/deberta-v3-large'):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.deberta = AutoModel.from_pretrained(model_path, config=config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
self.bilstm = nn.LSTM(config.hidden_size, (config.hidden_size) // 2, num_layers=2, dropout=config.hidden_dropout_prob, batch_first=True,
bidirectional=True)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.deberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
lstm_output, hc = self.bilstm(sequence_output)
logits = self.classifier(lstm_output)
loss = None
if labels is not None:
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
)
def freeze(module):
for parameter in module.parameters():
parameter.requires_grad = False
def get_model(config, model_path, id2label, label2id):
all_labels = list(label2id.keys())
backbone_config = AutoConfig.from_pretrained(model_path)
backbone_config.hidden_dropout = config.model.dropout
backbone_config.hidden_dropout_prob = config.model.dropout
backbone_config.attention_dropout = config.model.dropout
backbone_config.attention_probs_dropout_prob = config.model.dropout
backbone_config.num_labels = len(all_labels)
backbone_config.id2label = id2label
backbone_config.label2id = label2id
if config.model.lstm:
print('LSTM')
model = CustomModel(
backbone_config,
model_path,
)
else:
model = AutoModelForTokenClassification.from_pretrained(
model_path,
config=backbone_config,
ignore_mismatched_sizes=True
)
if config.model.freeze_embeddings:
freeze(model.deberta.embeddings)
if config.model.freeze_n_layers > 0:
freeze(model.deberta.encoder.layer[:config.model.freeze_n_layers])
return model
# File: src/training/model.py
import torch.nn as nn
def get_criterion(config):
return nn.BCEWithLogitsLoss(reduction='mean')
# File: src/training/criterion.py
from transformers import AdamW
import math
def get_parameters_groups(n_layers, n_groups):
layers = [f'backbone.encoder.layer.{n_layers - i - 1}.' for i in range(n_layers)]
step = math.ceil(n_layers / n_groups)
groups = []
for i in range(0, n_layers, step):
if i + step >= n_layers - 1:
group = layers[i:]
groups.append(group)
break
else:
group = layers[i:i + step]
groups.append(group)
return groups
def get_grouped_llrd_parameters(model,
encoder_lr,
decoder_lr,
embeddings_lr,
lr_mult_factor,
weight_decay,
n_groups):
opt_parameters = []
named_parameters = list(model.named_parameters())
no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"]
n_layers = model.backbone_config.num_hidden_layers
parameters_groups = get_parameters_groups(n_layers, n_groups)
for _, (name, params) in enumerate(named_parameters):
wd = 0.0 if any(p in name for p in no_decay) else weight_decay
if name.startswith("backbone.encoder"):
lr = encoder_lr
for i, group in enumerate(parameters_groups):
lr = encoder_lr * (lr_mult_factor ** (i + 1)) if any(p in name for p in group) else lr
opt_parameters.append({"params": params,
"weight_decay": wd,
"lr": lr})
if name.startswith("backbone.embeddings"):
lr = embeddings_lr
opt_parameters.append({"params": params,
"weight_decay": wd,
"lr": lr})
if name.startswith("bigram_type_embeddings"):
lr = embeddings_lr
opt_parameters.append({"params": params,
"weight_decay": wd,
"lr": lr})
if name.startswith("fc") or name.startswith('backbone.pooler') or name.startswith('pool') or name.startswith('pooling'):
lr = decoder_lr
opt_parameters.append({"params": params,
"weight_decay": wd,
"lr": lr})
return opt_parameters
def get_optimizer_params(model, encoder_lr, decoder_lr, weight_decay=0.0):
no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"]
optimizer_parameters = [
{'params': [p for n, p in model.backbone.named_parameters() if not any(nd in n for nd in no_decay)],
'lr': encoder_lr, 'weight_decay': weight_decay},
{'params': [p for n, p in model.backbone.named_parameters() if any(nd in n for nd in no_decay)],
'lr': encoder_lr, 'weight_decay': 0.0},
{'params': [p for n, p in model.named_parameters() if ("backbone" not in n) and ("backbone_prompt" not in n)],
'lr': decoder_lr, 'weight_decay': 0.0},
]
return optimizer_parameters
def get_optimizer(model, config):
if config.optimizer.group_lr_multiplier == 1:
optimizer_parameters = get_optimizer_params(model,
config.optimizer.encoder_lr,
config.optimizer.decoder_lr,
weight_decay=config.optimizer.weight_decay)
else:
optimizer_parameters = get_grouped_llrd_parameters(model,
encoder_lr=config.optimizer.encoder_lr,
decoder_lr=config.optimizer.decoder_lr,
embeddings_lr=config.optimizer.embeddings_lr,
lr_mult_factor=config.optimizer.group_lr_multiplier,
weight_decay=config.optimizer.weight_decay,
n_groups=config.optimizer.n_groups)
optimizer = AdamW(optimizer_parameters,
lr=config.optimizer.encoder_lr,
eps=config.optimizer.eps,
betas=[config.optimizer.beta1, config.optimizer.beta2])
return optimizer
# File: src/training/optimizer.py
import json
import pandas as pd
def get_reference_df(raw_df):
ref_df = raw_df[['document', 'tokens', 'labels']].copy()
ref_df = ref_df.explode(['tokens', 'labels']).reset_index(drop=True).rename(columns={'tokens': 'token', 'labels': 'label'})
ref_df['token_str'] = ref_df['token'].copy()
ref_df['token'] = ref_df.groupby('document').cumcount()
reference_df = ref_df[ref_df['label'] != 'O'].copy()
reference_df = reference_df.reset_index().rename(columns={'index': 'row_id'})
reference_df = reference_df[['row_id', 'document', 'token', 'label', 'token_str']].copy()
return reference_df
def split_rows(df, max_length, doc_stride):
new_df = []
for _, row in df.iterrows():
tokens = row['tokens']
if len(tokens) > max_length:
start = 0
while start < len(tokens):
remaining_tokens = len(tokens) - start
if remaining_tokens < max_length and start != 0:
start = max(0, len(tokens) - max_length)
end = min(start + max_length, len(tokens))
new_row = {}
new_row['document'] = row['document']
new_row['source'] = row['source']
new_row['valid'] = row['valid']
new_row['tokens'] = tokens[start:end]
new_row['trailing_whitespace'] = row['trailing_whitespace'][start:end]
new_row['labels'] = row['labels'][start:end]
new_row['token_indices'] = list(range(start, end))
new_row['full_text'] = rebuild_text(new_row['tokens'], new_row['trailing_whitespace'])
new_df.append(new_row)
if remaining_tokens >= max_length:
start += doc_stride
else:
break
else:
new_row = {
'document': row['document'],
'valid': row['valid'],
'tokens': row['tokens'],
'trailing_whitespace': row['trailing_whitespace'],
'labels': row['labels'],
'token_indices': row['token_indices'],
'full_text': row['full_text'],
'source': row['source'],
}
new_df.append(new_row)
return pd.DataFrame(new_df)
def add_token_indices(doc_tokens):
token_indices = list(range(len(doc_tokens)))
return token_indices
def rebuild_text(tokens, trailing_whitespace):
text = ''
for token, ws in zip(tokens, trailing_whitespace):
ws = " " if ws == True else ""
text += token + ws
return text
# File: src/data/utils.py
import numpy as np
import pandas as pd
from datasets import Dataset
import numpy as np
import torch
from copy import deepcopy
def tokenize(example, tokenizer, max_length, label2id):
text = []
token_map = []
labels = []
idx = 0
for t, l, ws in zip(
example["tokens"], example["provided_labels"], example["trailing_whitespace"]
):
text.append(t)
token_map.extend([idx]*len(t))
labels.extend([l] * len(t))
if ws:
text.append(" ")
labels.append("O")
token_map.append(-1)
idx += 1
tokenized = tokenizer("".join(text), return_offsets_mapping=True, max_length=max_length, truncation=True)
labels = np.array(labels)
text = "".join(text)
token_labels = []
for start_idx, end_idx in tokenized.offset_mapping:
if start_idx == 0 and end_idx == 0:
token_labels.append(label2id["O"])
continue
if text[start_idx].isspace():
start_idx += 1
while start_idx >= len(labels):
start_idx -= 1
token_labels.append(label2id[labels[start_idx]])
length = len(tokenized.input_ids)
return {**tokenized, "labels": token_labels, "length": length, "token_map": token_map,}
class CustomDataset(torch.utils.data.Dataset):
def __init__(self, data, tokenizer, max_length, label2id):
self.data = data
self.max_length = max_length
self.tokenizer = tokenizer
self.label2id = label2id
def __len__(self):
return len(self.data)
def __getitem__(self, item):
row = self.data.iloc[item]
sample = {
'full_text': row.full_text, 'document': row.document,
'trailing_whitespace': row.trailing_whitespace, 'token_indices': row.token_indices
}
tokens = deepcopy(row.tokens)
labels = row.labels
if np.random.uniform() > 0.5:
for i in range(1, len(tokens)):
if labels[i-1] == 'B-NAME_STUDENT' and labels[i] == 'I-NAME_STUDENT':
tokens[i-1], tokens[i] = tokens[i], tokens[i-1]
sample['tokens'] = tokens
sample['provided_labels'] = labels
tokenized = tokenize(sample, self.tokenizer, self.max_length, self.label2id)
sample.update(tokenized)
return sample
def create_dataset(data, tokenizer, max_length, label2id):
ds = Dataset.from_dict({
"full_text": data.full_text.tolist(),
"document": data.document.tolist(),
"tokens": data.tokens.tolist(),
"trailing_whitespace": data.trailing_whitespace.tolist(),
"provided_labels": data.labels.tolist(),
"token_indices": data.token_indices.tolist(),
})
ds = ds.map(tokenize, fn_kwargs={"tokenizer": tokenizer, "label2id": label2id, "max_length": max_length}, num_proc=4)
return ds
# File: src/data/dataset.py
from types import SimpleNamespace
def dictionary_to_namespace(data):
if type(data) is list:
return list(map(dictionary_to_namespace, data))
elif type(data) is dict:
sns = SimpleNamespace()
for key, value in data.items():
setattr(sns, key, dictionary_to_namespace(value))
return sns
else:
return data
def namespace_to_dictionary(data):
dictionary = vars(data)
for k, v in dictionary.items():
if type(v) is SimpleNamespace:
v = namespace_to_dictionary(v)
dictionary[k] = v
return dictionary
# File: src/environment/utils.py
from argparse import ArgumentParser
import argparse
from types import SimpleNamespace
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def get_default_args():
args = SimpleNamespace()
args.debug = False
args.fold = 0
args.exp_name = 'test'
return vars(args)
def is_notebook() -> bool:
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False
def get_args():
its_notebook = is_notebook()
if its_notebook:
args = get_default_args()
else:
args = get_input_args()
return args
# File: src/environment/arguments.py
import yaml
import copy
from pathlib import Path
def load_config(filepath):
with open(filepath, 'rb') as file:
data = yaml.safe_load(file)
# data = dictionary_to_namespace(data)
return data
def save_config(config, path):
config_out = copy.deepcopy(config)
config_out.tokenizer = None
config_out = namespace_to_dictionary(config_out)
for key, value in config_out.items():
if type(value) == type(Path()):
config_out[key] = str(value)
with open(path, 'w') as file:
yaml.dump(config_out, file, default_flow_style=False)
def concat_configs(
args,
config,
filepaths
):
config.update(args)
config.update(filepaths)
config = dictionary_to_namespace(config)
if config.debug:
config.exp_name = 'test'
config.logger.use_wandb = False
config.dataset.train_batch_size = 2
config.dataset.valid_batch_size = 2
config.run_name = f'{config.exp_name}_{config.job_type}_{config.seed}_{config.fold}' # config.exp_name + f'_fold{config.fold}'
config.run_id = config.run_name
return config
# File: src/environment/config.py
import yaml
from pathlib import Path
import os
import shutil
def load_filepaths(filepath):
with open(filepath, 'rb') as file:
data = yaml.safe_load(file)