-
Notifications
You must be signed in to change notification settings - Fork 2
/
train_mlm.py
1833 lines (1634 loc) · 67.2 KB
/
train_mlm.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
#!/usr/bin/env python
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# taken and modified from https://github.com/huggingface/transformers/blob/master/examples/pytorch/language-modeling/run_mlm_no_trainer.py
import argparse
import logging
import math
import os
import random
from torch._C import layout
import wandb
import plotly.express as px
from datetime import datetime
from collections import defaultdict, OrderedDict as OD
import loss
import numpy as np
import datasets
import torch
from datasets import load_dataset, load_metric
from torch.utils.data.dataloader import DataLoader
from tqdm.auto import tqdm
import torch.nn as nn
import transformers
from transformers import (
CONFIG_MAPPING,
AdamW,
AutoTokenizer,
DataCollatorForLanguageModeling,
SchedulerType,
get_scheduler,
set_seed,
)
from operator import attrgetter
from utils.module_proxy_wrapper import ModuleProxyWrapper
from accelerate import Accelerator, DistributedDataParallelKwargs, DistributedType
from sampling import (
Sampler,
get_supertransformer_config,
show_random_elements,
show_args,
)
from collections import defaultdict
from custom_layers import custom_bert, custom_mobile_bert
import plotly.graph_objects as go
from more_itertools import unique_everseen
from utils import (
count_parameters,
check_path,
get_current_datetime,
read_json,
calculate_params_from_config,
millify,
)
from loss import *
import transformers
from transformers.models.bert.modeling_bert import BertForMaskedLM
from torchinfo import summary
logger = logging.getLogger(__name__)
def validate_subtransformer(
model,
eval_dataloader,
accelerator,
len_eval_dataset,
per_device_eval_batch_size,
pad_to_max_length,
):
metric = load_metric("custom_metrics/mlm_accuracy.py")
def get_labels(predictions, references):
# Transform predictions and references tensos to numpy arrays
if accelerator.device.type == "cpu":
y_pred = predictions.detach().clone().numpy()
y_true = references.detach().clone().numpy()
else:
y_pred = predictions.detach().cpu().clone().numpy()
y_true = references.detach().cpu().clone().numpy()
# Remove ignored index (special tokens)
true_predictions = [
[str(p) for (p, l) in zip(pred, gold_label) if l != -100]
for pred, gold_label in zip(y_pred, y_true)
]
true_labels = [
[str(l) for (p, l) in zip(pred, gold_label) if l != -100]
for pred, gold_label in zip(y_pred, y_true)
]
return true_predictions, true_labels
losses = []
progress_bar = tqdm(
range(0, len(eval_dataloader)),
disable=not accelerator.is_local_main_process,
)
model.eval()
for step, batch in enumerate(eval_dataloader):
# We could avoid this line since we set the accelerator with `device_placement=True`.
with torch.no_grad():
outputs = model(**batch)
loss = outputs.loss
losses.append(accelerator.gather(loss.repeat(per_device_eval_batch_size)))
predictions = outputs.logits.argmax(dim=-1)
labels = batch["labels"]
if (
not pad_to_max_length
): # necessary to pad predictions and labels for being gathered
predictions = accelerator.pad_across_processes(
predictions, dim=1, pad_index=-100
)
labels = accelerator.pad_across_processes(labels, dim=1, pad_index=-100)
predictions_gathered = accelerator.gather(predictions)
labels_gathered = accelerator.gather(labels)
preds, refs = get_labels(predictions_gathered, labels_gathered)
metric.add_batch(
predictions=preds,
references=refs,
) # predictions and preferences are expected to be a nested list of labels, not label_ids
progress_bar.update(1)
losses = torch.cat(losses)
losses = losses[:len_eval_dataset]
eval_metric = metric.compute()
try:
val_loss = torch.mean(losses)
perplexity = math.exp(torch.mean(losses))
except OverflowError:
perplexity = float("inf")
eval_metric["val_loss"] = val_loss
eval_metric["perplexity"] = perplexity
return eval_metric
def parse_args():
parser = argparse.ArgumentParser(
description="Pretrain/Finetune a transformers model on a Masked Language Modeling task"
)
parser.add_argument(
"--dataset_name",
type=str,
default=None,
help="The name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--dataset_config_name",
type=str,
default=None,
help="The configuration name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--train_file",
type=str,
default=None,
help="A csv or a json file containing the training data.",
)
parser.add_argument(
"--validation_file",
type=str,
default=None,
help="A csv or a json file containing the validation data.",
)
parser.add_argument(
"--validation_split_percentage",
default=5,
help="The percentage of the train set used as validation set in case there's no validation split",
)
parser.add_argument(
"--pad_to_max_length",
action="store_true",
help="If passed, pad all samples to `max_length`. Otherwise, dynamic padding is used.",
)
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to pretrained model or model identifier from huggingface.co/models.",
)
parser.add_argument(
"--config_name",
type=str,
default=None,
help="Pretrained config name or path if not the same as model_name",
)
parser.add_argument(
"--tokenizer_name",
type=str,
default=None,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--use_slow_tokenizer",
action="store_true",
help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
)
parser.add_argument(
"--per_device_train_batch_size",
type=int,
default=8,
help="Batch size (per device) for the training dataloader.",
)
parser.add_argument(
"--per_device_eval_batch_size",
type=int,
default=8,
help="Batch size (per device) for the evaluation dataloader.",
)
parser.add_argument(
"--learning_rate",
type=float,
default=7e-4,
help="Initial learning rate (after the potential warmup period) to use.",
)
parser.add_argument(
"--weight_decay", type=float, default=0.01, help="Weight decay to use."
)
parser.add_argument(
"--num_train_epochs",
type=int,
default=3,
help="Total number of training epochs to perform.",
)
parser.add_argument(
"--max_train_steps",
type=int,
default=None,
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
)
parser.add_argument(
"--gradient_accumulation_steps",
type=int,
default=1,
help="Number of updates steps to accumulate before performing a backward/update pass.",
)
parser.add_argument(
"--lr_scheduler_type",
type=SchedulerType,
default="linear",
help="The scheduler type to use.",
choices=[
"linear",
"cosine",
"cosine_with_restarts",
"polynomial",
"constant",
"constant_with_warmup",
],
)
parser.add_argument(
"--num_warmup_steps",
type=int,
default=10000,
help="Number of steps for the warmup in the lr scheduler.",
)
parser.add_argument(
"--output_dir",
type=str,
default="checkpoints",
help="Where to store the final model.",
)
parser.add_argument(
"--seed", type=int, default=42, help="A seed for reproducible training."
)
parser.add_argument(
"--model_type",
type=str,
default=None,
help="Model type to use if training from scratch.",
)
parser.add_argument(
"--logging_steps",
type=int,
default=100,
help="Log every X updates steps.",
)
parser.add_argument(
"--max_seq_length",
type=int,
default=None,
help="The maximum total input sequence length after tokenization. Sequences longer than this will be truncated.",
)
parser.add_argument(
"--line_by_line",
type=bool,
default=True,
help="""
Whether distinct lines of text in the dataset are to be handled as
distinct sequences. This is deafult for bert/electra models and should
be set to False for gpt/gpt2 type models""",
)
parser.add_argument(
"--preprocessing_num_workers",
type=int,
default=8,
help="The number of processes to use for the preprocessing.",
)
parser.add_argument(
"--overwrite_cache",
type=bool,
default=False,
help="Overwrite the cached training and evaluation sets",
)
parser.add_argument(
"--mlm_probability",
type=float,
default=0.15,
help="Ratio of tokens to mask for masked language modeling loss",
)
# args we add
parser.add_argument(
"--early_stopping_patience",
default=5,
type=int,
help="Patience for early stopping to stop training if val_acc doesnt converge",
)
parser.add_argument(
"--layer_drop_prob",
default=0.0,
type=float,
help="Probability to drop layers",
)
# parser.add_argument(
# "--limit_subtransformer_choices",
# default=0,
# type=int,
# help="If set to 1, it will limit the hidden_size and number of encoder layers of the subtransformer choices",
# )
parser.add_argument(
"--eval_random_subtransformers",
default=1,
type=int,
help="If set to 1, this will evaluate 25 random subtransformers after every training epoch when training a supertransformer",
)
parser.add_argument(
"--train_subtransformers_from_scratch",
default=0,
type=int,
help="""
If set to 1, this will train 25 random subtransformers from scratch.
By default, it is set to False (0) and we train a supertransformer and finetune subtransformers
""",
)
parser.add_argument(
"--fp16", type=int, default=1, help="If set to 1, will use FP16 training."
)
parser.add_argument(
"--mixing",
type=str,
required=True,
help=f"specifies how to mix the tokens in bertlayers",
choices=["attention", "gmlp", "fnet", "mobilebert", "bert-bottleneck"],
)
parser.add_argument(
"--resume_from_checkpoint_dir",
type=str,
default=None,
help=f"directory that contains checkpoints, optimizer, scheduler to resume training",
)
parser.add_argument(
"--tiny_attn",
type=int,
default=0,
help=f"Choose this if you need Tiny Attention Module along-with gMLP dense block",
)
parser.add_argument(
"--num_subtransformers_monitor",
type=int,
default=25,
help=f"Choose the number of subtransformers whose performance you wish to monitor",
)
parser.add_argument(
"--c4_dir",
type=str,
default=None,
help=f"The directory path for C4",
)
parser.add_argument(
"--tokenized_c4_dir",
type=str,
default=None,
help=f"The directory path for tokenized C4",
)
parser.add_argument(
"--sampling_type",
type=str,
default="random",
help=f"The sampling type for super-transformer",
choices=["none", "naive_params", "biased_params", "random"],
)
parser.add_argument(
"--sampling_rule",
type=str,
default="none",
help=f"The sampling rule for sampling super-transformers",
choices=["none", "sandwich"],
)
parser.add_argument(
"--pop_size",
type=int,
default=1,
help=f"Number of random subtransformers to sample at each step",
)
parser.add_argument(
"--k_sampling",
type=int,
default=1,
help=f"The step frequency of sampling a sub-transformers",
)
parser.add_argument(
"--magic_sampling_random_walk_prob",
type=float,
default=None,
help=f"""
whether to use magic sampling and do a random walk (sampling a subtransformer by changing some of previous
subtransformer's parameters(hidden size, number of layers, etc.)
""",
)
parser.add_argument(
"--magic_sampling_per_layer_change_prob",
type=float,
default=None,
help=f"""
if using magic sampling, this is the probability of changing some layers parameters (its width) given the previous sampled subtransformer
""",
)
parser.add_argument(
"--inplace_distillation",
type=int,
default=0,
help=f"Whether to use inplace distillation",
)
parser.add_argument(
"--kd_ratio",
type=float,
default=1,
help=f"Sensitizes the amount of KD-loss that needs to be added with existing loss",
)
parser.add_argument(
"--layerwise_distillation",
type=int,
default=0,
help=f"Conditional layerwise attention and feature map transfer for in-place distillation",
)
parser.add_argument(
"--alpha_divergence",
type=int,
default=0,
help=f"Enable Alpha Divergence KL loss",
)
parser.add_argument(
"--alpha_min",
type=float,
default=-1.0,
help=f"Alpha min value",
)
parser.add_argument(
"--alpha_max",
type=float,
default=1.0,
help=f"Alpha max value",
)
parser.add_argument(
"--beta_clip",
type=float,
default=5.0,
help=f"The clip value for alpha divergence",
)
parser.add_argument(
"--subtransformer_config_path",
type=str,
default=None,
help=f"The path to a subtransformer configration",
)
parser.add_argument(
"--rewire",
type=int,
default=0,
help=f"Whether to rewire model",
)
# parser.add_argument(
# "--presampled_subtransformers_order",
# type=str,
# default=None,
# help=f"The order in which presampled subtransformers should be sorted",
# choices=["ascending", "descending"],
# )
parser.add_argument(
"--rewired_model_checkpoint_dir",
type=str,
default=None,
help=f"Path to rewired model checkpoint",
)
parser.add_argument(
"--additional_random_softmaxing",
action="store_true",
help=f"if true then random softmax layers will be softmaxed in addition to the last layer, except that there will be a random walk when it comes to choosing the layer to softmax",
)
parser.add_argument(
"--random_layer_selection_probability",
type=float,
default=0.10,
help="What is the probability of choosing a random layer instead of choosing an intermediate layer.",
)
parser.add_argument(
"--wandb_suffix",
type=str,
default=None,
help=f"suffix for wandb",
)
parser.add_argument(
"--target_perplexity",
type=float,
default=None,
help=f"perplexity to stop further pretraining",
)
parser.add_argument(
"--wandb_entity",
type=str,
required=True,
help=f"wandb entity",
)
parser.add_argument(
"--wandb_project",
type=str,
default="super-pretraining",
help=f"wandb project",
)
# parser.add_argument(
# "--max_grad_norm", default=1.0, type=float, help="Max gradient norm."
# )
args = parser.parse_args()
if args.subtransformer_config_path is None:
args.model_name_or_path = "bert-base-cased"
# Sanity checks
if args.layerwise_distillation:
assert args.inplace_distillation
if args.alpha_divergence:
assert args.inplace_distillation
if args.inplace_distillation == 1:
assert (
args.sampling_rule == "sandwich"
), "Sampling rule needs to be sandwich if using inplace distillation"
if (
args.dataset_name is None
and args.train_file is None
and args.validation_file is None
and args.c4_dir is None
and args.tokenized_c4_dir is None
):
raise ValueError("Need either a dataset name or a training/validation file.")
else:
if args.train_file is not None:
extension = args.train_file.split(".")[-1]
assert extension in [
"csv",
"json",
"txt",
], "`train_file` should be a csv, json or txt file."
if args.validation_file is not None:
extension = args.validation_file.split(".")[-1]
assert extension in [
"csv",
"json",
"txt",
], "`validation_file` should be a csv, json or txt file."
if args.tiny_attn == 1:
assert args.mixing == "gmlp", "Tiny Attention can work only in GMLP setup"
if args.sampling_type == "none":
# if we are not sampling, dont test random subtransformers every n epochs
args.eval_random_subtransformers = False
if args.c4_dir is not None:
check_path(args.c4_dir)
# c4_train_dir = os.path.join(args.c4_dir, "train")
# c4_val_dir = os.path.join(args.c4_dir, "val")
# check_path(c4_train_dir)
# check_path(c4_val_dir)
args.dataset_name = "c4_realnews"
# args.c4_train_dir = c4_train_dir
# args.c4_val_dir = c4_val_dir
if args.tokenized_c4_dir is not None:
check_path(args.tokenized_c4_dir)
args.dataset_name = "c4_realnews"
if args.resume_from_checkpoint_dir is not None:
args.optim_scheduler_states_path = os.path.join(
args.resume_from_checkpoint_dir, "optimizer_scheduler.pt"
)
check_path(args.resume_from_checkpoint_dir)
check_path(args.optim_scheduler_states_path)
model_path = os.path.join(args.resume_from_checkpoint_dir, "pytorch_model.bin")
check_path(model_path)
# overwrite on the same directory
args.output_dir = args.resume_from_checkpoint_dir
if args.target_perplexity is not None:
assert (
args.subtransformer_config_path is not None
), "Need to provide subtransformer config path to use this option"
assert args.k_sampling > 0
if args.subtransformer_config_path:
check_path(args.subtransformer_config_path)
assert (
args.sampling_type == "none"
), "sampling_type is not supported when providing custom_subtransformer_config"
assert (
args.eval_random_subtransformers == 0
), "no need to evaluate random subtransformers when a custom_subtransformer_config is provided"
assert (
args.layer_drop_prob == 0.0
), "layer_drop_prob is not needed when providing custom_subtransformer_config"
if args.rewire:
assert (
args.rewired_model_checkpoint_dir is not None
), "Rewired model checkpoint path cannot be None if rewire is set to True"
check_path(args.rewired_model_checkpoint_dir)
if args.resume_from_checkpoint_dir is not None:
args.resume_from_checkpoint_dir = args.rewired_model_checkpoint_dir
## Temporary Assert until rewiring support is providied for all other BERT variants
assert args.mixing == "bert-bottleneck"
if (
args.magic_sampling_random_walk_prob is not None
or args.magic_sampling_per_layer_change_prob is not None
):
assert (
args.magic_sampling_per_layer_change_prob is not None
), "magic_sampling_per_layer_change_prob cannot be None if magic_sampling_random_walk_prob is not None"
assert (
args.magic_sampling_random_walk_prob is not None
), "magic_sampling_random_walk_prob cannot be None if magic_sampling_per_layer_change_prob is not None"
assert (
args.magic_sampling_random_walk_prob > 0.0
and args.magic_sampling_random_walk_prob <= 1.0
), "magic_sampling_random_walk_prob should be between 0.0 and 1.0"
assert (
args.magic_sampling_per_layer_change_prob > 0.0
and args.magic_sampling_per_layer_change_prob <= 1.0
), "magic_sampling_per_layer_change_prob should be between 0.0 and 1.0"
return args
def main():
args = parse_args()
param = DistributedDataParallelKwargs(
find_unused_parameters=True, check_reduction=False
)
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
accelerator = Accelerator(fp16=args.fp16, kwargs_handlers=[param])
show_args(accelerator, args)
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
logger.info(accelerator.state)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(
logging.INFO if accelerator.is_local_main_process else logging.ERROR
)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
str_name = (
args.mixing + "_tiny_attn"
if args.tiny_attn == 1
else args.mixing + "_" + args.sampling_type + "_K=" + str(args.k_sampling)
)
str_name = "rewired_" + str_name if args.rewire else str_name
if args.inplace_distillation:
str_name += "_ip_distill"
if args.layerwise_distillation:
str_name += "_layerwise_distill"
if args.alpha_divergence:
str_name += "_alpha_div"
else:
str_name += "_pretraining"
if args.wandb_suffix is not None:
str_name += "_" + args.wandb_suffix
if accelerator.is_main_process:
wandb.init(
project=args.wandb_project,
entity=args.wandb_entity,
name=args.dataset_name.split("/")[-1].strip() + "_" + str_name,
)
if args.output_dir is not None and args.resume_from_checkpoint_dir is None:
dataset_name = args.dataset_name.split("/")[-1].strip()
args.output_dir += (
"/" + dataset_name + "_" + str_name + "_" + get_current_datetime()
)
args.optim_scheduler_states_path = os.path.join(
args.output_dir, "{}/optimizer_scheduler.pt"
)
os.makedirs(args.output_dir, exist_ok=True)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
#
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if args.tokenized_c4_dir is not None:
logger.info("Loading Tokenized C4 Dataset...")
tokenized_datasets = datasets.load_from_disk(args.tokenized_c4_dir)
elif args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
if args.dataset_name == "c4_realnews":
logger.info("Loading C4 Dataset...")
raw_datasets = datasets.load_from_disk(args.c4_dir)
# train_files = [
# os.path.join(args.c4_train_dir, file)
# for file in os.listdir(args.c4_train_dir)
# if file.endswith("json.gz")
# ]
# val_files = [
# os.path.join(args.c4_val_dir, file)
# for file in os.listdir(args.c4_val_dir)
# if file.endswith("json.gz")
# ]
# train_files = sorted(train_files)
# val_files = sorted(val_files)
# raw_datasets = load_dataset(
# "json", data_files={"train": train_files, "validation": val_files}
# )
else:
raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name)
if "validation" not in raw_datasets.keys():
raw_datasets["validation"] = load_dataset(
args.dataset_name,
args.dataset_config_name,
split=f"train[:{args.validation_split_percentage}%]",
)
raw_datasets["train"] = load_dataset(
args.dataset_name,
args.dataset_config_name,
split=f"train[{args.validation_split_percentage}%:]",
)
# limiting dataset for testing
# raw_datasets["train"] = raw_datasets["train"].select(range(100))
else:
data_files = {}
if args.train_file is not None:
data_files["train"] = args.train_file
if args.validation_file is not None:
data_files["validation"] = args.validation_file
extension = args.train_file.split(".")[-1]
if extension == "txt":
extension = "text"
raw_datasets = load_dataset(extension, data_files=data_files)
if args.subtransformer_config_path is None:
global_config = get_supertransformer_config(
args.model_name_or_path,
mixing=args.mixing,
additional_random_softmaxing=args.additional_random_softmaxing,
random_layer_selection_probability=args.random_layer_selection_probability,
)
else:
global_config = get_supertransformer_config(
"bert-base-cased",
mixing=args.mixing,
additional_random_softmaxing=args.additional_random_softmaxing,
random_layer_selection_probability=args.random_layer_selection_probability,
)
if args.tokenizer_name:
tokenizer = AutoTokenizer.from_pretrained(
args.tokenizer_name, use_fast=not args.use_slow_tokenizer
)
elif args.model_name_or_path:
if args.subtransformer_config_path is None:
tokenizer = AutoTokenizer.from_pretrained(
args.model_name_or_path, use_fast=not args.use_slow_tokenizer
)
else:
tokenizer = AutoTokenizer.from_pretrained(
"bert-base-cased", use_fast=not args.use_slow_tokenizer
)
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
)
# if args.model_name_or_path:
# model = AutoModelForMaskedLM.from_pretrained(
# args.model_name_or_path,
# from_tf=bool(".ckpt" in args.model_name_or_path),
# config=config,
# )
# else:
# logger.info("Training new model from scratch")
# model = AutoModelForMaskedLM.from_config(config)
# add max_seq_len or model_max_len to config
if args.max_seq_length:
global_config.max_seq_length = args.max_seq_length
else:
logger.warning(
f"The max_seq_length is not defined!! Setting it to max length in tokenizer"
)
global_config.max_seq_length = tokenizer.model_max_length
# overriding the hideen dropout inline with hyperparms in gmlp paper
global_config.hidden_dropout_prob = 0
if args.layerwise_distillation or args.additional_random_softmaxing:
# for attention transfer and feature transfer enable these.
global_config.output_attentions = True
global_config.output_hidden_states = True
global_config.alpha_divergence = args.alpha_divergence
if args.alpha_divergence:
global_config.alpha_min = args.alpha_min
global_config.alpha_max = args.alpha_max
global_config.beta_clip = args.beta_clip
global_config.rewire = args.rewire
global_config.layer_drop_prob = args.layer_drop_prob
if (
args.magic_sampling_per_layer_change_prob is not None
and args.magic_sampling_random_walk_prob is not None
):
global_config.magic_sampling_per_layer_change_prob = (
args.magic_sampling_per_layer_change_prob
)
global_config.magic_sampling_random_walk_prob = (
args.magic_sampling_random_walk_prob
)
if args.subtransformer_config_path is not None:
subtransformer_config = read_json(args.subtransformer_config_path)
for key, value in subtransformer_config.items():
# update global_config with attributes of subtransformer_config
setattr(global_config, key, value)
logger.info(
"=================================================================="
)
logger.info(
f"Number of parameters in custom config is {millify(calculate_params_from_config(global_config, scaling_laws=False, add_output_emb_layer=False))}"
)
logger.info(
"=================================================================="
)
# if check_path(args.model_name_or_path):
# model = custom_bert.BertForMaskedLM.from_pretrained(
# args.model_name_or_path, config=global_config
# )
# else:
# TODO: decouple mixing and mobilebert model declarato
if args.mixing == "mobilebert":
states = OD()
model = custom_mobile_bert.MobileBertForMaskedLM(config=global_config)
model2 = BertForMaskedLM.from_pretrained("bert-base-cased")
for key in model2.state_dict().keys():
_key = key.replace("bert.", "mobilebert.")
states[_key] = model2.state_dict()[key]
del model2
model.load_state_dict(states, strict=False)
del states
identity = torch.eye(global_config.true_hidden_size)
for key in model.state_dict().keys():
if (
"bottleneck.input.dense.weight" in key
or "output.bottleneck.dense.weight" in key
):
model.state_dict()[key].data.copy_(identity)
elif (
"bottleneck.output.dense.bias" in key
or "output.bottleneck.dense.bias" in key
):
model.state_dict()[key].data.zero_()
logger.info("MobileBert Initiliazed with bert-base")
elif args.mixing == "bert-bottleneck":
model = custom_bert.BertForMaskedLM.from_pretrained(
"bert-base-cased", config=global_config
)
identity = torch.eye(global_config.hidden_size)
for key in model.state_dict().keys():
if "input_bottleneck.weight" in key or "output_bottleneck.weight" in key:
model.state_dict()[key].data.copy_(identity)
elif "input_bottleneck.bias" in key or "output_bottleneck.bias" in key:
model.state_dict()[key].data.zero_()
logger.info("BERT-Bottleneck Initiliazed with BERT-base")
elif args.inplace_distillation or args.sampling_type == "none":
# initialize with pretrained model if we are using inplace distillation or if we are using no sampling
model = custom_bert.BertForMaskedLM.from_pretrained(
args.model_name_or_path, config=global_config
)
else:
model = custom_bert.BertForMaskedLM(global_config)