-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathcommon_utils.py
2123 lines (1949 loc) · 133 KB
/
common_utils.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
# -*- coding: utf-8 -*-
# Copyright 2021 National Institute of Information and Communication Technology (Raj Dabre)
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
# The above copyright notice and this permission notice shall
# be included in all copies or substantial portions of the
# Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## Basic imports
import os
import argparse
import time
import sys
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
##
## Huggingface imports
import transformers
from transformers import AutoTokenizer, MBartTokenizer, MBart50Tokenizer, BartTokenizer
from transformers import MBartForConditionalGeneration, MBartConfig, get_linear_schedule_with_warmup
from transformers import AdamW
from torch.optim import Optimizer
##
## Pytorch imports
import torch
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel
import torch.multiprocessing as mp
import torch.distributed as dist
from torch.optim import Adam
import torch.nn.functional as F
##
## Our imports
from common_utils import *
##
## Other imports
import random
from typing import Iterable, Tuple
import numpy as np
import math
import sacrebleu
from rouge_score import rouge_scorer
import functools
import matplotlib.pyplot as plt # drawing heat map of attention weights
from matplotlib import rcParams
import matplotlib.colors as mcolors
rcParams['font.sans-serif'] = ['Source Han Sans TW',
'sans-serif',
"FreeSerif" # fc-list :lang=hi family
]
from copy import deepcopy
##
## Seed setting here
torch.manual_seed(621311)
##
class AdamWScale(Optimizer): ### Taken from nanot5 library (https://github.com/PiotrNawrot/nanoT5)
"""
This AdamW implementation is copied from Huggingface.
We modified it with Adagrad scaling by rms of a weight tensor
Implements Adam algorithm with weight decay fix as introduced in [Decoupled Weight Decay
Regularization](https://arxiv.org/abs/1711.05101).
Parameters:
params (`Iterable[nn.parameter.Parameter]`):
Iterable of parameters to optimize or dictionaries defining parameter groups.
lr (`float`, *optional*, defaults to 1e-3):
The learning rate to use.
betas (`Tuple[float,float]`, *optional*, defaults to (0.9, 0.999)):
Adam's betas parameters (b1, b2).
eps (`float`, *optional*, defaults to 1e-6):
Adam's epsilon for numerical stability.
weight_decay (`float`, *optional*, defaults to 0):
Decoupled weight decay to apply.
correct_bias (`bool`, *optional*, defaults to `True`):
Whether or not to correct bias in Adam (for instance, in Bert TF repository they use `False`).
no_deprecation_warning (`bool`, *optional*, defaults to `False`):
A flag used to disable the deprecation warning (set to `True` to disable the warning).
"""
def __init__(
self,
params: Iterable[nn.parameter.Parameter],
lr: float = 1e-3,
betas: Tuple[float, float] = (0.9, 0.999),
eps: float = 1e-6,
weight_decay: float = 0.0,
correct_bias: bool = True,
):
if lr < 0.0:
raise ValueError(f"Invalid learning rate: {lr} - should be >= 0.0")
if not 0.0 <= betas[0] < 1.0:
raise ValueError(f"Invalid beta parameter: {betas[0]} - should be in [0.0, 1.0)")
if not 0.0 <= betas[1] < 1.0:
raise ValueError(f"Invalid beta parameter: {betas[1]} - should be in [0.0, 1.0)")
if not 0.0 <= eps:
raise ValueError(f"Invalid epsilon value: {eps} - should be >= 0.0")
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, correct_bias=correct_bias)
super().__init__(params, defaults)
@staticmethod
def _rms(tensor):
return tensor.norm(2) / (tensor.numel() ** 0.5)
def step(self, closure=None):
"""
Performs a single optimization step.
Arguments:
closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad.data
if grad.is_sparse:
raise RuntimeError("Adam does not support sparse gradients, please consider SparseAdam instead")
state = self.state[p]
beta1, beta2 = group["betas"]
# State initialization
if len(state) == 0:
state["step"] = 0
# Exponential moving average of gradient values
state["exp_avg"] = torch.zeros_like(p.data)
# Exponential moving average of squared gradient values
state["exp_avg_sq"] = torch.zeros_like(p.data)
exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]
state["step"] += 1
# Decay the first and second moment running average coefficient
# In-place operations to update the averages at the same time
exp_avg.mul_(beta1).add_(grad, alpha=(1.0 - beta1))
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2)
denom = exp_avg_sq.sqrt().add_(group["eps"])
step_size = group["lr"]
if group["correct_bias"]: # No bias correction for Bert
bias_correction1 = 1.0 - beta1 ** state["step"]
bias_correction2 = 1.0 - beta2 ** state["step"]
step_size = step_size * math.sqrt(bias_correction2) / bias_correction1
# /Adapt Step from Adafactor
step_size = step_size * max(1e-3, self._rms(p.data))
# /Adapt Step from Adafactor
p.data.addcdiv_(exp_avg, denom, value=-step_size)
# Just adding the square of the weights to the loss function is *not*
# the correct way of using L2 regularization/weight decay with Adam,
# since that will interact with the m and v parameters in strange ways.
#
# Instead we want to decay the weights in a manner that doesn't interact
# with the m/v parameters. This is equivalent to adding the square
# of the weights to the loss with plain (non-momentum) SGD.
# Add weight decay at the end (fixed version)
if group["weight_decay"] > 0.0:
p.data.add_(p.data, alpha=(-group["lr"] * group["weight_decay"]))
return loss
class EWC(object):
def __init__(self, model, dataset, gpu, label_smoothing, ignore_index=None):
self.model = model
self.dataset = dataset
self.params = {n: p for n, p in self.model.named_parameters() if p.requires_grad}
self._means = {}
self.gpu = gpu
self.label_smoothing = label_smoothing
self.ignore_index = ignore_index
self._precision_matrices = self._diag_fisher()
for n, p in deepcopy(self.params).items():
self._means[n] = torch.tensor(p.detach().cpu().numpy()).to(gpu)
self._means[n].requires_grad = False
def _diag_fisher(self):
precision_matrices = {}
for n, p in deepcopy(self.params).items():
p.data.zero_()
precision_matrices[n] = torch.tensor(p.detach().cpu().numpy()).to(self.gpu)
self.model.eval()
num_samples = 0
for input_ids, input_masks, decoder_input_ids, labels in self.dataset:
self.model.zero_grad(set_to_none=True)
input_ids = input_ids.to(self.gpu)
input_masks = input_masks.to(self.gpu)
decoder_input_ids = decoder_input_ids.to(self.gpu)
labels = labels.to(self.gpu)
num_samples += input_ids.size(0)
output = self.model(input_ids=input_ids, attention_mask=input_masks ,decoder_input_ids=decoder_input_ids)
lprobs = torch.nn.functional.log_softmax(output.logits, dim=-1) ## Softmax tempering of logits if needed.
loss = label_smoothed_nll_loss(lprobs, labels, self.label_smoothing, self.ignore_index)
loss.backward()
loss.detach()
for n, p in self.model.named_parameters():
if p.requires_grad:
precision_matrices[n].data += p.grad.data ** 2
for n, p in self.model.named_parameters():
if p.requires_grad:
precision_matrices[n].data = precision_matrices[n].data / num_samples
precision_matrices = {n: p for n, p in precision_matrices.items()}
for n, p in precision_matrices.items():
precision_matrices[n].requires_grad = False
self.model.zero_grad(set_to_none=True)
self.model.train()
return precision_matrices
def penalty(self, model):
loss = 0
for n, p in model.named_parameters():
if p.requires_grad:
_loss = self._precision_matrices[n] * (p - self._means[n]) ** 2
loss += _loss.sum()
return loss
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None):
"""From fairseq. This returns the label smoothed cross entropy loss."""
if target.dim() == lprobs.dim() - 1:
target = target.unsqueeze(-1)
nll_loss = -lprobs.gather(dim=-1, index=target)
smooth_loss = -lprobs.sum(dim=-1, keepdim=True)
if ignore_index is not None:
pad_mask = target.eq(ignore_index)
nll_loss.masked_fill_(pad_mask, 0.0)
smooth_loss.masked_fill_(pad_mask, 0.0)
denominator = (1.0 - 1.0*pad_mask)
denominator = denominator.sum()
else:
nll_loss = nll_loss.squeeze(-1)
smooth_loss = smooth_loss.squeeze(-1)
denominator = 1.0
if ignore_index is not None:
nll_loss = nll_loss.sum()
smooth_loss = smooth_loss.sum()
else:
nll_loss = nll_loss.mean()
smooth_loss = smooth_loss.mean()
eps_i = epsilon / lprobs.size(-1)
loss = (1.0 - epsilon) * nll_loss + eps_i * smooth_loss
loss = loss/denominator
return loss
def prune_weights(model_weight_dict, prune_ratio):
"""Prunes the weights of the model.
Args:
model_weight_dict: The weights of the model.
prune_ratio: The ratio of the weights to be pruned.
Returns:
The pruned weights which will be used to initialize the model.
Logic:
1. For each key in the model_weight_dict, get the weight tensor and flatten it.
2. Sort the weight tensor in ascending order and get the indices of the top prune_ratio*len(weight_tensor) elements.
3. Set the weights to zero at the indices obtained in step 2."""
if prune_ratio <= 0:
return model_weight_dict
print("Pruning weights. Pruning percent: {}%".format(prune_ratio*100))
for key in model_weight_dict:
weight_tensor = model_weight_dict[key]
weight_tensor = weight_tensor.view(-1)
weight_tensor = weight_tensor.cpu().numpy()
indices = np.argsort(weight_tensor)
indices = indices[:int(prune_ratio*len(weight_tensor))]
weight_tensor[indices] = 0
weight_tensor = torch.from_numpy(weight_tensor)
print("Pruned percentage: {}%".format(torch.sum(weight_tensor == 0)/len(weight_tensor)*100))
weight_tensor = weight_tensor.view_as(model_weight_dict[key])
model_weight_dict[key] = weight_tensor
return model_weight_dict
def lmap(f, x):
"""list(map(f, x)). Converts a map into a list containing (key,value) pairs."""
return list(map(f, x))
def compute_distillation_losses(child_mod_compute, parent_mod_compute, target, ignore_index, args):
"""Implemented by me. This is based on distill bert, distill mbart etc. This method is run when the 'distillation' argument is passed.
There are 3 types of distillation losses for now: cross_entropy, hidden_layer_regression and attention_distillation.
cross_entropy: This minimizes the cross entropy loss between the parent distribution and the child distribution. Essentially this is different from regular cross entropy loss in the following way. Regular cross entropy is -(label(Y)*log(p_child(Y/X))) whereas this distillation loss is -(p_parent(Y/X)*log(p_child(Y/X))). We expect that the child will mimic the parent distribution.
hidden_layer_regression: Here we choose parent to child layer mappings and minimize the hidden layer differences via the L2 (regression) loss. Simply put, for the encoder and decoder, for each layer mapping, we compute (child_hidden_representation-parent_hidden_representation)**2.
attention_distillation: This is a rather recent approach where we compute cross entropy loss between the attention distributions of the parent (as a label) and the child. The loss is -(parent_layer_x_attention*log(child_layer_x_attention))."""
distillation_losses_to_compute = args.distillation_styles.split(",")
all_distillation_losses = []
if target.dim() == child_mod_compute.logits.dim() - 1:
target = target.unsqueeze(-1)
pad_mask = target.eq(ignore_index)
for distillation_loss_to_compute in distillation_losses_to_compute:
if distillation_loss_to_compute == "cross_entropy":
parent_logits = parent_mod_compute.logits
parent_lprobs = torch.nn.functional.log_softmax(parent_logits/args.distillation_temperature, dim=-1)
child_logits = child_mod_compute.logits
child_lprobs = torch.nn.functional.log_softmax(child_logits/args.distillation_temperature, dim=-1)
parent_softmax = torch.exp(parent_lprobs)
distillation_cross_entropy = parent_softmax*child_lprobs
distillation_cross_entropy.masked_fill_(pad_mask, 0.0)
distillation_cross_entropy = distillation_cross_entropy.sum(dim=-1)
distillation_cross_entropy = distillation_cross_entropy.mean() * args.distillation_temperature**2
all_distillation_losses.append(distillation_cross_entropy)
if distillation_loss_to_compute == "hidden_layer_regression":
all_regression_losses = []
for layer_mapping in args.distillation_layer_mapping.strip().split(","):
parent_layer_idx, child_layer_idx = layer_mapping.split("-")
parent_layer_idx, child_layer_idx = int(parent_layer_idx)-1, int(child_layer_idx)-1
parent_encoder_layer_state = parent_mod_compute.encoder_hidden_states[parent_layer_idx]
child_encoder_layer_state = child_mod_compute.encoder_hidden_states[child_layer_idx]
encoder_l2_loss = (parent_encoder_layer_state-child_encoder_layer_state)**2
encoder_l2_loss.masked_fill_(pad_mask, 0.0)
encoder_l2_loss = encoder_l2_loss.sum(dim=-1).mean()
parent_decoder_layer_state = parent_mod_compute.decoder_hidden_states[parent_layer_idx]
child_decoder_layer_state = child_mod_compute.decoder_hidden_states[child_layer_idx]
decoder_l2_loss = (parent_decoder_layer_state-child_decoder_layer_state)**2
decoder_l2_loss.masked_fill_(pad_mask, 0.0)
decoder_l2_loss = decoder_l2_loss.sum(dim=-1).mean()
all_regression_losses.append(encoder_l2_loss)
all_regression_losses.append(decoder_l2_loss)
regression_loss = torch.mean(torch.stack(all_regression_losses), dim=0)
all_distillation_losses.append(-regression_loss) ## We will take a negative later so this minus sign here is to negate its effect. We want to minimize the L2 loss after all.
if distillation_loss_to_compute == "attention_distillation":
all_attention_distillation_losses = []
for layer_mapping in args.distillation_layer_mapping.strip().split(","):
parent_layer_idx, child_layer_idx = layer_mapping.split("-")
parent_layer_idx, child_layer_idx = int(parent_layer_idx)-1, int(child_layer_idx)-1
parent_encoder_self_attention = parent_mod_compute.encoder_attentions[parent_layer_idx]
child_encoder_self_attention = child_mod_compute.encoder_attentions[child_layer_idx]
# deal with padding here. We will need to access the source token padding information.
encoder_sa_loss = parent_encoder_self_attention*torch.log(child_encoder_self_attention.masked_fill_(child_encoder_self_attention.eq(0.0), 1e-10))
encoder_l2_loss = encoder_l2_loss.sum(dim=-1).mean()
parent_decoder_self_attention = parent_mod_compute.decoder_attentions[parent_layer_idx]
child_decoder_self_attention = child_mod_compute.decoder_attentions[child_layer_idx]
decoder_sa_loss = parent_decoder_self_attention*torch.log(child_decoder_self_attention.masked_fill_(child_decoder_self_attention.eq(0.0), 1e-10))
decoder_sa_loss = decoder_sa_loss.sum(dim=-1).mean()
parent_decoder_cross_attention = parent_mod_compute.cross_attentions[parent_layer_idx]
child_decoder_cross_attention = child_mod_compute.cross_attentions[child_layer_idx]
decoder_ca_loss = parent_decoder_cross_attention*torch.log(child_decoder_cross_attention.masked_fill_(child_decoder_cross_attention.eq(0.0), 1e-10))
decoder_ca_loss = decoder_ca_loss.sum(dim=-1).mean()
all_attention_distillation_losses.append(encoder_sa_loss)
all_attention_distillation_losses.append(decoder_sa_loss)
all_attention_distillation_losses.append(decoder_ca_loss)
all_attention_distillation_losses = torch.mean(torch.stack(all_attention_distillation_losses), dim=0)
all_distillation_losses.append(all_attention_distillation_losses)
return -torch.mean(torch.stack(all_distillation_losses), dim=0)
def remap_layers(model, idx, args, rank): ### Cut this code into half.
"""This method is used to remap the layers from a pretrained model to the current model. The remapping info comes in the form of 2-1,... which means, map the second layer of the pretrained model to the first layer of the current model."""
print("Remapping layers from parent to child.")
model_copy = model.copy()
if args.remap_encoder != "":
keys_to_consider = [key for key in model.keys() if ".encoder.layers" in key]
keys_to_keep = set() ## Keys to keep in the model dict once remapping is done as we assume that the user always specifies ALL desired target model keys to be remapped.
for mapping in args.remap_encoder.split(","):
slayer, tlayer = mapping.split("-")
slayer = str(int(slayer)-1) # Zero indexing
tlayer = str(int(tlayer)-1) # Zero indexing
keys_to_keep.add(slayer) ## Key remapped so it should not be deleted
for key in keys_to_consider:
key = key.strip().split(".")
key_copy = list(key)
if key[idx] == slayer:
if rank == 0:
print("Remapping", key)
key_copy[idx] =tlayer
key = ".".join(key)
key_copy = ".".join(key_copy)
model[key] = model_copy[key_copy]
for key in keys_to_consider: ## Purge all unspecified keys.
key = key.strip().split(".")
if key[idx] not in keys_to_keep:
key = ".".join(key)
if rank == 0:
print("Deleting", key)
del model[key]
if args.remap_decoder != "":
keys_to_consider = [key for key in model.keys() if ".decoder.layers" in key]
keys_to_keep = set() ## Keys to keep in the model dict once remapping is done as we assume that the user always specifies ALL desired target model keys to be remapped.
for mapping in args.remap_encoder.split(","):
slayer, tlayer = mapping.split("-")
slayer = str(int(slayer)-1) # Zero indexing
tlayer = str(int(tlayer)-1) # Zero indexing
keys_to_keep.add(slayer) ## Key remapped so it should not be deleted
for key in keys_to_consider:
key = key.strip().split(".")
key_copy = list(key)
if key[idx] == slayer:
if rank == 0:
print("Remapping", key)
key_copy[idx] =tlayer
key = ".".join(key)
key_copy = ".".join(key_copy)
model[key] = model_copy[key_copy]
for key in keys_to_consider: ## Purge all unspecified keys.
key = key.strip().split(".")
if key[idx] not in keys_to_keep:
key = ".".join(key)
if rank == 0:
print("Deleting", key)
del model[key]
if rank == 0:
print("Final model dictionary after remapping is:", model.keys())
return model
def remap_embeddings(our_model_dict, model_to_load_dict, args):
"""This method will consider two tokenizers, one for the pretrained model and one for the current model. It will then remap the embeddings. When we remapt embeddings we not only remap input embeddings to the encoder and decoder but also the lm head parameters which is a kind of embedding consisting of a weight matrix and biases. Note that embed positions remapping makes no sense."""
if args.pretrained_tokenizer_name_or_path is None:
return model_to_load_dict
tok = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path, do_lower_case=False, use_fast=False, keep_accents=True).get_vocab()
tok_pre = AutoTokenizer.from_pretrained(args.pretrained_tokenizer_name_or_path, do_lower_case=False, use_fast=False, keep_accents=True).get_vocab()
for token in tok:
tok_idx = tok[token]
if token in tok_pre:
pre_tok_idx = tok_pre[token]
our_model_dict["module.model.shared.weight"][tok_idx] = model_to_load_dict["module.model.shared.weight"][pre_tok_idx]
our_model_dict["module.model.encoder.embed_tokens.weight"][tok_idx] = model_to_load_dict["module.model.encoder.embed_tokens.weight"][pre_tok_idx]
our_model_dict["module.model.decoder.embed_tokens.weight"][tok_idx] = model_to_load_dict["module.model.decoder.embed_tokens.weight"][pre_tok_idx]
our_model_dict["module.lm_head.weight"][tok_idx] = model_to_load_dict["module.lm_head.weight"][pre_tok_idx]
our_model_dict["module.final_logits_bias"][tok_idx] = model_to_load_dict["module.final_logits_bias"][pre_tok_idx]
model_to_load_dict["module.model.shared.weight"] = our_model_dict["module.model.shared.weight"]
model_to_load_dict["module.model.encoder.embed_tokens.weight"] = our_model_dict["module.model.encoder.embed_tokens.weight"]
model_to_load_dict["module.model.decoder.embed_tokens.weight"] = our_model_dict["module.model.decoder.embed_tokens.weight"]
model_to_load_dict["module.lm_head.weight"] = our_model_dict["module.lm_head.weight"]
model_to_load_dict["module.final_logits_bias"] = our_model_dict["module.final_logits_bias"]
return model_to_load_dict
def remap_embeddings_eliminate_components_and_eliminate_mismatches(our_model_dict, model_to_load_dict, args):
"""This method first remaps embeddings from pretrained to current model and then eliminates mismatched layers between the pretrained model and the current model. A mismatch is when the size of the pretrained parameter is not the same as the parameter of the current model."""
print("Remapping embeddings.")
model_to_load_dict = remap_embeddings(our_model_dict, model_to_load_dict, args)
if args.eliminate_encoder_before_initialization:
print("Eliminating encoder from the model to load")
for load_model_key in model_to_load_dict:
if "encoder" in load_model_key:
del model_to_load_dict[load_model_key]
if args.eliminate_decoder_before_initialization:
print("Eliminating decoder from the model to load")
for load_model_key in model_to_load_dict:
if "decoder" in load_model_key:
del model_to_load_dict[load_model_key]
if args.eliminate_embeddings_before_initialization:
print("Eliminating embeddings from the model to load")
for load_model_key in model_to_load_dict:
if "embed" in load_model_key:
del model_to_load_dict[load_model_key]
print("Eliminating matched params with mismatched sizes from the initial model.")
for our_model_key in our_model_dict:
if our_model_key in model_to_load_dict:
if our_model_dict[our_model_key].size() != model_to_load_dict[our_model_key].size():
print("Eliminating", our_model_key)
del model_to_load_dict[our_model_key]
return model_to_load_dict
def init_weights(module, in_features, out_features):
"""Method to initialize model weights. Not used for now but might be used in the future. Tries to mimic t2t initialization.
TODO: Incorporate this into the flow so as to give users an option to do their own initialization."""
if isinstance(module, nn.Linear):
init_std = (3.0/(in_features+out_features))**(0.5)
module.weight.data.normal_(mean=0.0, std=init_std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
init_std = (3.0/(out_features))**(0.5)
module.weight.data.normal_(mean=0.0, std=init_std)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
def shard_files_mono(files, tokenizer, args):
"""This method shards files into N parts containing the same number of lines. Each shard will go to a different GPU which may even be located on another machine. This method is run when the 'shard_files' argument is passed."""
print("Sharding files into", args.world_size, "parts")
for lang, file_details in files:
infile = open(file_details[0]).readlines() if args.num_domains_for_domain_classifier > 1 else open(file_details).readlines()
num_lines = len(infile)
lines_per_shard = math.ceil(num_lines/args.world_size)
print("For language:",lang," the total number of lines are:", num_lines, "and number of lines per shard are:", lines_per_shard)
for shard_id in range(args.world_size):
outfile = open(file_details[0]+"."+"%02d" % shard_id, "w") if args.num_domains_for_domain_classifier > 1 else open(file_details+"."+"%02d" % shard_id, "w")
for line in infile[shard_id*lines_per_shard:(shard_id+1)*lines_per_shard]:
if args.sliding_window_shard: ## This is for sliding window sharding. Now note that each shard wont contain the same number of lines. This is because we are sliding the window. But thats not going to change our overall story.
if args.sliding_sharding_delimiter == " ": ## Handle this case specially.
line = line.strip()
line_tok = tokenizer(line, add_special_tokens=False).input_ids
num_blocks = math.ceil(len(line_tok)/args.hard_truncate_length)
for block_id in range(num_blocks): # Extract the block, detokenize it and write it to the file.
block = line_tok[block_id*args.hard_truncate_length:(block_id+1)*args.hard_truncate_length]
block = tokenizer.decode(block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
outfile.write(block+"\n")
else: # First split the line based on the args.sliding_sharding_delimiter and then tokenize each constituent. Keep adding tokens until you reach the hard truncate length. Then write the block to the file.
line = line.strip()
line_split = line.split(args.sliding_sharding_delimiter)
block = []
for sub_line in line_split:
sub_line_tok = tokenizer(sub_line, add_special_tokens=False).input_ids
if (len(block) + len(sub_line_tok)) > args.hard_truncate_length:
if len(block) > 0:
block = tokenizer.decode(block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
outfile.write(block+"\n")
block = []
else:
pass
block.extend(sub_line_tok)
if len(block) > 0:
block = tokenizer.decode(block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
outfile.write(block+"\n")
else:
outfile.write(line)
outfile.flush()
outfile.close()
print("File for language", lang, "has been sharded.")
sys.stdout.flush()
def shard_files_mono_lm(files, args):
"""This method shards files into N parts containing the same number of lines. Each shard will go to a different GPU which may even be located on another machine. This method is run when the 'shard_files' argument is passed."""
print("Sharding files into", args.world_size, "parts")
for lang in files:
infile = open(files[lang]).readlines()
num_lines = len(infile)
lines_per_shard = math.ceil(num_lines/args.world_size)
print("For language:",lang," the total number of lines are:", num_lines, "and number of lines per shard are:", lines_per_shard)
for shard_id in range(args.world_size):
outfile = open(files[lang]+"."+"%02d" % shard_id, "w")
for line in infile[shard_id*lines_per_shard:(shard_id+1)*lines_per_shard]:
outfile.write(line)
outfile.flush()
outfile.close()
print("File for language", lang, "has been sharded.")
sys.stdout.flush()
def shard_files_bi(files, tokenizer, args, additional_tokenizer=None):
"""This method shards files into N parts containing the same number of lines. Each shard will go to a different GPU which may even be located on another machine. This method is run when the 'shard_files' argument is passed."""
print("Sharding files into", args.world_size, "parts")
if args.sliding_window_shard and args.sliding_sharding_delimiter == " ":
print("Sliding window sharding with a space delimiter with parallel corpora is not a good idea. You have chosen violence. Now you must live with it.")
elif args.sliding_window_shard and args.sliding_sharding_delimiter != " ":
print("Sliding window sharding with a non-space delimiter with parallel corpora will make sense only if the number of delimiter separated sentences per pair of lines read are equal. Be careful.")
if additional_tokenizer is None:
additional_tokenizer = tokenizer
for pair, file_details in files:
infile = list(zip(open(file_details[0]).readlines(), open(file_details[1]).readlines()))
num_lines = len(infile)
lines_per_shard = math.ceil(num_lines/args.world_size)
print("For language pair:",pair," the total number of lines are:", num_lines, "and number of lines per shard are:", lines_per_shard)
for shard_id in range(args.world_size):
srcoutfile = open(file_details[0]+"."+"%02d" % shard_id, "w")
tgtoutfile = open(file_details[1]+"."+"%02d" % shard_id, "w")
for src_line, tgt_line in infile[shard_id*lines_per_shard:(shard_id+1)*lines_per_shard]:
if args.sliding_window_shard: ## This is for sliding window sharding. Now note that each shard wont contain the same number of lines. This is because we are sliding the window. But thats not going to change our overall story.
if args.sliding_sharding_delimiter == " ": ## Handle this case specially. For a parallel corpus setting, this will be bad. Very very bad. Dont use this EVER.
src_line = src_line.strip()
tgt_line = tgt_line.strip()
src_line_tok = tokenizer(src_line, add_special_tokens=False).input_ids
tgt_line_tok = additional_tokenizer(tgt_line, add_special_tokens=False).input_ids
num_blocks = math.ceil(len(src_line_tok)/args.hard_truncate_length)
for block_id in range(num_blocks): # Extract the block, detokenize it and write it to the file. Assuming that the number of delimiter separated sentences per line is the same for both the files.
src_block = src_line_tok[block_id*args.hard_truncate_length:(block_id+1)*args.hard_truncate_length]
tgt_block = tgt_line_tok[block_id*args.hard_truncate_length:(block_id+1)*args.hard_truncate_length]
src_block = tokenizer.decode(src_block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
tgt_block = additional_tokenizer.decode(tgt_block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
srcoutfile.write(src_block+"\n")
tgtoutfile.write(tgt_block+"\n")
else: # First split the line based on the args.sliding_sharding_delimiter and then tokenize each constituent. Keep adding tokens until you reach the hard truncate length. Then write the block to the file. Use this only if you are sure that the number of delimiter separated sentences per line is the same for both the files.
src_line = src_line.strip()
tgt_line = tgt_line.strip()
src_line_split = src_line.split(args.sliding_sharding_delimiter)
tgt_line_split = tgt_line.split(args.sliding_sharding_delimiter)
src_block = []
tgt_block = []
for src_sub_line, tgt_sub_line in zip(src_line_split, tgt_line_split):
src_sub_line_tok = tokenizer(src_sub_line, add_special_tokens=False).input_ids
tgt_sub_line_tok = additional_tokenizer(tgt_sub_line, add_special_tokens=False).input_ids
if (len(src_block) + len(src_sub_line_tok)) > args.hard_truncate_length: ## Assuming that source and target have the same number of delimiter separated sentences per line.
if len(src_block) > 0:
src_block = tokenizer.decode(src_block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
srcoutfile.write(src_block+"\n")
src_block = []
tgt_block = additional_tokenizer.decode(tgt_block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
tgtoutfile.write(tgt_block+"\n")
tgt_block = []
else:
pass
src_block.extend(src_sub_line_tok)
tgt_block.extend(tgt_sub_line_tok)
if len(src_block) > 0:
src_block = tokenizer.decode(src_block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
srcoutfile.write(src_block+"\n")
tgt_block = additional_tokenizer.decode(tgt_block, skip_special_tokens=True, clean_up_tokenization_spaces=False)
tgtoutfile.write(tgt_block+"\n")
else:
srcoutfile.write(src_line)
tgtoutfile.write(tgt_line)
srcoutfile.flush()
srcoutfile.close()
tgtoutfile.flush()
tgtoutfile.close()
print("File for language pair", pair, "has been sharded.")
sys.stdout.flush()
def get_sacrebleu(refs, hyp):
"""Returns sacrebleu score. Sacrebleu is a reliable implementation for computing corpus level BLEU scores."""
bleu = sacrebleu.corpus_bleu(hyp, refs)
return bleu.score
def get_bucket_indexed_indefinite_corpus_yielder_mono(corpus, lang, bucket_intervals, sorted_batching, tokenizer):
# First we split the corpus into buckets. Each number in the bucket_intervals list is the upper bound of the bucket. The last bucket is the rest of the corpus.
# We create a dictionary where the key is the bucket id and the value is the yielder for that bucket.
corpus_split_by_length = {l: [] for l in bucket_intervals}
for line in corpus:
tokenized_sentence = tokenizer(line.strip(), add_special_tokens=False).input_ids
line_length = len(tokenized_sentence)
for bucket_id in range(len(bucket_intervals)-1):
if line_length >= bucket_intervals[bucket_id] and line_length < bucket_intervals[bucket_id+1]:
corpus_split_by_length[bucket_intervals[bucket_id]].append(line)
break
if line_length >= bucket_intervals[-1]:
corpus_split_by_length[bucket_intervals[-1]].append(line)
# Print bucket sizes
bucket_distributions = []
for bucket_id in corpus_split_by_length:
curr_bucket_size = len(corpus_split_by_length[bucket_id])
print("For language", lang, "the number of lines in bucket", bucket_id, "is", curr_bucket_size)
bucket_distributions.append(curr_bucket_size)
total_lines = sum(bucket_distributions)
bucket_distributions = [x/total_lines for x in bucket_distributions]
# Now we create a yielder for each bucket.
bucket_yielders = {}
for bucket_id in corpus_split_by_length:
if len(corpus_split_by_length[bucket_id]) > 0:
bucket_yielders[bucket_id] = yield_corpus_indefinitely_mono(corpus_split_by_length[bucket_id], lang, sorted_batching, bucketed_batching=True, bucket_id=bucket_id, tokenizer=tokenizer)
return bucket_yielders, bucket_distributions
def yield_corpus_indefinitely_mono(corpus, lang, sorted_batching, bucketed_batching=False, bucket_id=None, tokenizer=None):
"""This shuffles the corpus or corpus shard at the beginning of each epoch and returns sentences indefinitely."""
epoch_counter = 0
num_lines = len(corpus)
num_sentences_before_sort = 20000
num_sorted_segments = (num_lines // num_sentences_before_sort) + 1
try:
while True:
if bucketed_batching:
print("Shuffling bucket!")
else:
print("Shuffling corpus!")
sys.stdout.flush()
random.shuffle(corpus) ## Add bucketing logic here
if sorted_batching:
for curr_segment_id in range(num_sorted_segments):
curr_segment = corpus[curr_segment_id*num_sentences_before_sort:(curr_segment_id+1)*num_sentences_before_sort]
for src_line in sorted(curr_segment, key=lambda x: len(tokenizer(x.strip(), add_special_tokens=False).input_ids)):
yield src_line
else:
for src_line in corpus:
yield src_line
epoch_counter += 1
if bucketed_batching:
print("Finished round", epoch_counter, "for bucket:", bucket_id, "for language:", lang)
else:
print("Finished epoch", epoch_counter, "for language:", lang)
except Exception as e:
print(e)
print("Catastrophic data gen failure")
return None
def get_bucket_indexed_indefinite_corpus_yielder_bi(corpus, lang, bucket_intervals, sorted_batching, tokenizer, tgt_tokenizer):
# First we split the corpus into buckets. Each number in the bucket_intervals list is the upper bound of the bucket. The last bucket is the rest of the corpus.
# We create a dictionary where the key is the bucket id and the value is the yielder for that bucket.
corpus_split_by_length = {l: [] for l in bucket_intervals}
for src_line, tgt_line in corpus:
tgt_line_tok = tgt_tokenizer(tgt_line.strip(), add_special_tokens=False).input_ids
src_line_tok = tokenizer(src_line.strip(), add_special_tokens=False).input_ids
tgt_line_length = len(tgt_line_tok)
src_line_length = len(src_line_tok)
average_line_length = (tgt_line_length + src_line_length) / 2 ## Hopefully this leads to a compromise between the two.
# We will index the bucket by the target line length.
for bucket_id in range(len(bucket_intervals)-1):
if average_line_length >= bucket_intervals[bucket_id] and average_line_length < bucket_intervals[bucket_id+1]:
corpus_split_by_length[bucket_intervals[bucket_id]].append((src_line, tgt_line))
break
if average_line_length >= bucket_intervals[-1]:
corpus_split_by_length[bucket_intervals[-1]].append((src_line, tgt_line))
# Print bucket sizes
bucket_distributions = []
for bucket_id in corpus_split_by_length:
curr_bucket_size = len(corpus_split_by_length[bucket_id])
print("For language", lang, "the number of lines in bucket", bucket_id, "is", curr_bucket_size)
bucket_distributions.append(curr_bucket_size)
total_lines = sum(bucket_distributions)
bucket_distributions = [x/total_lines for x in bucket_distributions]
# Now we create a yielder for each bucket.
bucket_yielders = {}
for bucket_id in corpus_split_by_length:
if len(corpus_split_by_length[bucket_id]) > 0:
bucket_yielders[bucket_id] = yield_corpus_indefinitely_bi(corpus_split_by_length[bucket_id], lang, sorted_batching, bucketed_batching=True, bucket_id=bucket_id, tokenizer=tokenizer, tgt_tokenizer=tgt_tokenizer)
return bucket_yielders, bucket_distributions
def yield_corpus_indefinitely_bi(corpus, language, sorted_batching, bucketed_batching=False, bucket_id=None, tokenizer=None, tgt_tokenizer=None):
"""This shuffles the corpus at the beginning of each epoch and returns sentences indefinitely."""
epoch_counter = 0
num_lines = len(corpus)
num_sentences_before_sort = 20000
num_sorted_segments = (num_lines // num_sentences_before_sort) + 1
while True:
if bucketed_batching:
print("Shuffling bucket ID:", bucket_id, "for language:", language)
else:
print("Shuffling corpus:", language)
random.shuffle(corpus)
sys.stdout.flush()
if sorted_batching:
for curr_segment_id in range(num_sorted_segments):
curr_segment = corpus[curr_segment_id*num_sentences_before_sort:(curr_segment_id+1)*num_sentences_before_sort]
for src_line, tgt_line in sorted(curr_segment, key=lambda x: (len(tokenizer(x[0].strip(), add_special_tokens=False).input_ids) + len(tgt_tokenizer(x[1].strip(), add_special_tokens=False).input_ids)) / 2):
yield src_line, tgt_line
else:
for src_line, tgt_line in corpus:
yield src_line, tgt_line
epoch_counter += 1
if bucketed_batching:
print("Finished round", epoch_counter, "for bucket:", bucket_id, "for language:", language)
else:
print("Finished epoch", epoch_counter, "for language:", language)
return None, None ## We should never reach this point.
def sub_sample_and_permute_document(sentence, document_level_sentence_delimiter, max_length):
"""Here we start at a particular random index and select the rest of the sentences. This is to make sure that we dont always see only the initial part of each document all the time."""
sentence_split = sentence.split(" "+document_level_sentence_delimiter+" ")
length_histogram = []
current_length = 0
for sent in sentence_split:
current_length += len(sent.split(" "))
length_histogram.append(current_length)
len_space_sentence_split = length_histogram[-1]
if len_space_sentence_split > max_length:
max_token_idx = len_space_sentence_split - max_length
for idx, token_idx in enumerate(length_histogram):
max_last_sentence_idx = idx
if token_idx > max_token_idx:
break
else:
max_last_sentence_idx = 0
start_idx = random.randint(0, max_last_sentence_idx)
sentence_split = sentence_split[start_idx:]
sentence = " ".join(sentence_split)
sent_len = len(sentence.split(" "))
sentence_split_shuffled = random.sample(sentence_split, len(sentence_split))
sentence_split_shuffled = " ".join(sentence_split_shuffled)
sentence_split_shuffled = sentence_split_shuffled.split(" ")
return sentence_split_shuffled, sentence, sent_len
def generate_ul2_input_and_output(split_sentence, args, current_ul2_denoising_style = None):
"""Generates the input and output for the UL2 objective model."""
# Randomly select a denoising style
denoising_style = random.choice(args.denoising_styles) if current_ul2_denoising_style is None else current_ul2_denoising_style
max_retries = args.max_masking_retries
curr_retries = 0
if denoising_style == "R":
original_sentence_length = len(split_sentence)
masked_so_far = 0
spans = []
max_to_mask = int(args.ul2_r_max_to_mask * original_sentence_length)
# While 15% of the tokens are not masked, do the following.
while True:
# Choose an index at random.
possible_spans = [np.random.normal(s, args.ul2_r_spans_std) for s in args.ul2_r_spans_mean]
# Choose a span length at random.
span_length = int(random.choice(possible_spans))
# If the span length is greater than the length of the sentence, then choose a new span length.
if span_length > len(split_sentence) or span_length == 0:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
# Else extract the span and replace it with a mask token.
else:
random_idx = random.randint(0, len(split_sentence)-span_length)
span = split_sentence[random_idx:random_idx+span_length]
# if the mask token is already present, then choose a new span.
if "[MASK]" in span:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
spans.append((random_idx, span, span_length))
split_sentence[random_idx:random_idx+span_length] = ["[MASK]"] * span_length
masked_so_far += len(span)
if masked_so_far >= max_to_mask:
break
# Concatenate the spans to form the output. Use <s> as the separator.
output_sentence = ""
for _, span, _ in sorted(spans, key=lambda x: x[0]):
output_sentence += " ".join(span) + " <s> "
output_sentence = output_sentence.strip()
# Concatenate the tokens to form the input.
for pos, _, span_length in sorted(spans, key=lambda x: x[0], reverse=True):
split_sentence[pos: pos + span_length] = ["[MASK]"]
input_sentence = " ".join(split_sentence)
# Prepend the input with the denoising style.
if args.ignore_paradigm_token:
pass
else:
input_sentence = "<R> " + input_sentence
elif denoising_style == "S":
# Choose an index uniformly between beginning and end of sentence subject to maximum and minimum masking percentage.
random_idx = random.randint(int(args.ul2_s_min_prefix_to_keep * len(split_sentence)), int(args.ul2_s_max_prefix_to_keep * len(split_sentence)))
# Extract extract the span from the index to the end of the sentence.
span = split_sentence[random_idx:]
# Replace the span with a mask token.
split_sentence[random_idx:] = ["[MASK]"]
# Concatenate the tokens to form the input.
input_sentence = " ".join(split_sentence)
# Concatenate the span to form the output. Use <s> as the separator.
output_sentence = " ".join(span)
# Prepend the input with the denoising style.
if args.ignore_paradigm_token:
pass
else:
input_sentence = "<S> " + input_sentence
elif denoising_style == "X":
original_sentence_length = len(split_sentence)
masked_so_far = 0
spans = []
# Choose a subtype of X denoising style.
X_denoising_style = random.choice(args.x_denoising_styles)
if X_denoising_style == "LL": # Same as R denoising style but with span lengths with mean of 64 and standard deviation of 1.
max_to_mask = int(args.ul2_x_ll_max_to_mask * original_sentence_length)
while True:
span_length = int(np.random.normal(args.ul2_x_ll_span_mean, args.ul2_x_ll_span_std))
if span_length > len(split_sentence) or span_length == 0:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
else:
random_idx = random.randint(0, len(split_sentence)-span_length)
span = split_sentence[random_idx:random_idx+span_length]
if "[MASK]" in span:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
spans.append((random_idx, span, span_length))
split_sentence[random_idx:random_idx+span_length] = ["[MASK]"] * span_length
masked_so_far += len(span)
if masked_so_far >= max_to_mask:
break
elif X_denoising_style == "LH": # Same as above but with masking limit of 0.5.
max_to_mask = int(args.ul2_x_lh_max_to_mask * original_sentence_length)
while True:
span_length = int(np.random.normal(args.ul2_x_lh_span_mean, args.ul2_x_lh_span_std))
if span_length > len(split_sentence) or span_length == 0:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
else:
random_idx = random.randint(0, len(split_sentence)-span_length)
span = split_sentence[random_idx:random_idx+span_length]
if "[MASK]" in span:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
spans.append((random_idx, span, span_length))
split_sentence[random_idx:random_idx+span_length] = ["[MASK]"] * span_length
masked_so_far += len(span)
if masked_so_far >= max_to_mask:
break
elif X_denoising_style == "SH": # Same as R denoising style but with masking limit of 0.5.
max_to_mask = int(args.ul2_x_sh_max_to_mask * original_sentence_length)
while True:
possible_spans = [np.random.normal(s, args.ul2_x_sh_spans_std) for s in args.ul2_x_sh_spans_mean]
# Choose a span length at random.
span_length = int(random.choice(possible_spans))
# If the span length is greater than the length of the sentence, then choose a new span length.
if span_length > len(split_sentence) or span_length == 0:
if curr_retries >= max_retries:
break
continue
# Else extract the span and replace it with a mask token.
else:
random_idx = random.randint(0, len(split_sentence)-span_length)
span = split_sentence[random_idx:random_idx+span_length]
# if the mask token is already present, then choose a new span.
if "[MASK]" in span:
if curr_retries >= max_retries:
break
continue
spans.append((random_idx, span, span_length))
split_sentence[random_idx:random_idx+span_length] = ["[MASK]"] * span_length
masked_so_far += len(span)
if masked_so_far >= max_to_mask:
break
# Concatenate the spans to form the output. Use <s> as the separator.
output_sentence = ""
for _, span, _ in sorted(spans, key=lambda x: x[0]):
output_sentence += " ".join(span) + " <s> "
output_sentence = output_sentence.strip()
# Concatenate the tokens to form the input.
for pos, _, span_length in sorted(spans, key=lambda x: x[0], reverse=True):
split_sentence[pos: pos + span_length] = ["[MASK]"]
input_sentence = " ".join(split_sentence)
# Prepend the input with the denoising style.
if args.ignore_paradigm_token:
pass
else:
input_sentence = "<X> " + input_sentence
return input_sentence, output_sentence
def generate_mbart_or_mt5_input_and_output(split_sentence, original_sentence, mask_percent, mask_tok, args):
original_sentence_length = len(split_sentence)
masked_so_far = 0
spans = []
max_to_mask = int(mask_percent * original_sentence_length)
max_retries = args.max_masking_retries
curr_retries = 0
# While X% of the tokens are not masked, do the following.
while True:
# Choose an index at random.
span_length = np.random.poisson(args.token_masking_lambda)
# If the span length is greater than the length of the sentence, then choose a new span length.
if span_length > len(split_sentence) or span_length == 0:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
# Else extract the span and replace it with a mask token.
else:
random_idx = random.randint(0, len(split_sentence)-span_length)
span = split_sentence[random_idx:random_idx+span_length]
# if the mask token is already present, then choose a new span.
if mask_tok in span:
curr_retries += 1
if curr_retries >= max_retries:
break
continue
spans.append((random_idx, span, span_length))
split_sentence[random_idx:random_idx+span_length] = [mask_tok] * span_length
masked_so_far += len(span)
if masked_so_far >= max_to_mask:
break
# Concatenate the spans to form the output. Use <s> as the separator.
output_sentence = ""
for _, span, _ in sorted(spans, key=lambda x: x[0]):
output_sentence += " ".join(span) + " <s> "
output_sentence = output_sentence.strip()
# Concatenate the tokens to form the input.
for pos, _, span_length in sorted(spans, key=lambda x: x[0], reverse=True):
split_sentence[pos: pos + span_length] = [mask_tok]