-
Notifications
You must be signed in to change notification settings - Fork 10
/
train.py
858 lines (750 loc) · 27.1 KB
/
train.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
import os
import sys
import csv
import argparse
import logging
import torch
import accelerate
from torch import nn as nn
from torch.utils.data import DataLoader
from torch.utils.flop_counter import FlopCounterMode
from triton.testing import do_bench
from accelerate.logging import get_logger
from safetensors.torch import load_file
from logging.handlers import RotatingFileHandler
from tqdm import tqdm
from aria.config import load_model_config
from aria.model import ModelConfig, TransformerLM
from aria.tokenizer import (
Tokenizer,
AbsTokenizer,
RelTokenizer,
SeparatedAbsTokenizer,
)
from aria.data.datasets import (
TrainingDataset,
PretrainingDataset,
FinetuningDataset,
)
from aria.utils import _load_weight
# ----- USAGE -----
#
# This script is meant to be run using the huggingface accelerate cli, see:
#
# https://huggingface.co/docs/accelerate/basic_tutorials/launch
# https://huggingface.co/docs/accelerate/package_reference/cli
#
# For example usage you could run the pre-training script with:
#
# accelerate launch [arguments] aria/train.py train \
# small \
# data/train \
# data/val \
# -epochs 10 \
# -bs 32 \
# -workers 8
#
# You could resume a run from an accelerate checkpoint with:
#
# accelerate launch [arguments] aria/train.py resume \
# small \
# data/train \
# data/val \
# -cdir models/epoch5_step0 \
# -rstep 0 \
# -repoch 5 \
# -epochs 5 \
# -bs 32 \
# -workers 8
# TODO:
# - Test that everything works on a distributed setup
def setup_logger(project_dir: str):
# Get logger and reset all handlers
logger = logging.getLogger(__name__)
for h in logger.handlers[:]:
logger.removeHandler(h)
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
"[%(asctime)s] %(name)s: [%(levelname)s] %(message)s",
)
fh = RotatingFileHandler(
os.path.join(project_dir, "logs.txt"), backupCount=5, maxBytes=1024**3
)
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
logger.addHandler(ch)
return get_logger(__name__) # using accelerate.logging.get_logger()
def get_tokenizer_name(
train_data_path: str,
val_data_path: str,
):
"""This will throw an error if there is a tokenizer mismatch"""
train_config = TrainingDataset.get_config_from_path(train_data_path)
val_config = TrainingDataset.get_config_from_path(val_data_path)
assert (
train_config["tokenizer_name"] == val_config["tokenizer_name"]
), "Dataset tokenizers don't match"
return train_config["tokenizer_name"]
def setup_project_dir(project_dir: str | None):
if not project_dir:
# Create project directory
if not os.path.isdir("./experiments"):
os.mkdir("./experiments")
project_dirs = [
_dir
for _dir in os.listdir("./experiments")
if os.path.isdir(os.path.join("experiments", _dir))
]
ind = 0
while True:
if str(ind) not in project_dirs:
break
else:
ind += 1
project_dir_abs = os.path.abspath(os.path.join("experiments", str(ind)))
assert not os.path.isdir(project_dir_abs)
os.mkdir(project_dir_abs)
elif project_dir:
# Run checks on project directory
if os.path.isdir(project_dir):
assert (
len(os.listdir(project_dir)) == 0
), "Provided project directory is not empty"
project_dir_abs = os.path.abspath(project_dir)
elif os.path.isfile(project_dir):
raise FileExistsError(
"The provided path points toward an existing file"
)
else:
try:
os.mkdir(project_dir)
except Exception as e:
raise e(f"Failed to create project directory at {project_dir}")
project_dir_abs = os.path.abspath(project_dir)
os.mkdir(os.path.join(project_dir_abs, "checkpoints"))
return project_dir_abs
def _get_optim(
lr: float,
model: nn.Module,
num_epochs: int,
steps_per_epoch: int,
warmup: int = 100,
end_ratio: int = 0.1,
):
optimizer = torch.optim.AdamW(
model.parameters(),
lr=lr,
weight_decay=0.01,
betas=(0.9, 0.95),
eps=1e-5,
)
warmup_lrs = torch.optim.lr_scheduler.LinearLR(
optimizer,
start_factor=0.000001,
end_factor=1,
total_iters=warmup,
)
linear_decay_lrs = torch.optim.lr_scheduler.LinearLR(
optimizer,
start_factor=1,
end_factor=end_ratio,
total_iters=(num_epochs * steps_per_epoch) - warmup,
)
lr_scheduler = torch.optim.lr_scheduler.SequentialLR(
optimizer,
schedulers=[warmup_lrs, linear_decay_lrs],
milestones=[warmup],
)
return optimizer, lr_scheduler
def get_optim(
model: nn.Module,
num_epochs: int,
steps_per_epoch: int,
):
LR = 3e-5
END_RATIO = 0.1
WARMUP_STEPS = 1000
return _get_optim(
lr=LR,
model=model,
num_epochs=num_epochs,
steps_per_epoch=steps_per_epoch,
warmup=WARMUP_STEPS,
end_ratio=END_RATIO,
)
def get_dataloaders(
train_data_dir: str,
val_data_dir: str,
tokenizer: Tokenizer,
batch_size: int,
num_workers: int,
init_epoch: int | None = None,
apply_aug: bool = True,
finetune: bool = False,
):
logger = logging.getLogger(__name__)
if finetune == False:
train_dataset = PretrainingDataset(
dir_path=train_data_dir,
tokenizer=tokenizer,
)
val_dataset = PretrainingDataset(
dir_path=val_data_dir,
tokenizer=tokenizer,
)
elif finetune == True:
train_dataset = FinetuningDataset(
dir_path=train_data_dir,
tokenizer=tokenizer,
)
val_dataset = FinetuningDataset(
dir_path=val_data_dir,
tokenizer=tokenizer,
)
else:
raise ValueError
if init_epoch:
if init_epoch > train_dataset.num_epochs:
logger.warning(
f"Provided init_epoch is larger than the number of epoch files "
f"located in {train_data_dir}. The default behaviour in this case "
f"is to load the epochs in a cyclic fashion."
)
train_dataset.init_epoch(idx=init_epoch)
assert (
val_dataset.num_epochs == 1
), "val-data directory should only contain one epoch"
if apply_aug:
train_dataset.set_transform(tokenizer.export_data_aug())
train_dataloader = DataLoader(
train_dataset,
batch_size=batch_size,
num_workers=num_workers,
shuffle=True,
)
val_dataloader = DataLoader(
val_dataset,
batch_size=batch_size,
num_workers=num_workers,
shuffle=False,
)
return train_dataloader, val_dataloader
def rolling_average(prev_avg: float, x_n: float, n: int):
# Returns rolling average without needing to recalculate
if n == 0:
return x_n
else:
return ((prev_avg * (n - 1)) / n) + (x_n / n)
def _train(
epochs: int,
accelerator: accelerate.Accelerator,
model: TransformerLM,
train_dataloader: DataLoader,
val_dataloader: DataLoader,
optimizer: torch.optim.Optimizer,
scheduler: torch.optim.lr_scheduler.LRScheduler = None,
steps_per_checkpoint: int | None = None,
resume_step: int | None = None,
resume_epoch: int | None = None,
project_dir: str | None = None,
):
def profile_flops(dataloader: DataLoader):
def _bench():
for batch in dataloader:
src, tgt = batch # (b_sz, s_len), (b_sz, s_len, v_sz)
logits = model(src) # (b_sz, s_len, v_sz)
logits = logits.transpose(1, 2)
loss = loss_fn(logits, tgt)
# Backwards step - omit optimizer.step()
accelerator.backward(loss)
optimizer.zero_grad()
break
flop_counter = FlopCounterMode(display=False)
logger.info(
f"Model has "
f"{'{:,}'.format(sum(p.numel() for p in model.parameters() if p.requires_grad))} "
"parameters"
)
# logger.info("Profiling FLOP")
# _bench()
# with flop_counter:
# _bench()
# total_flop = sum(flop_counter.get_flop_counts()["Global"].values())
# logger.info(f"Forwards & backwards FLOP: {total_flop / 1e12} TF")
def make_checkpoint(_accelerator, _epoch: int, _step: int):
checkpoint_dir = os.path.join(
project_dir,
"checkpoints",
f"epoch{_epoch}_step{_step}",
)
logger.info(
f"EPOCH {_epoch}/{epochs + start_epoch}: Saving checkpoint - {checkpoint_dir}"
)
_accelerator.save_state(checkpoint_dir)
# This is all slightly messy as train_loop and val_loop make use of the
# variables in the wider scope. Perhaps refactor this at some point.
def train_loop(dataloader: DataLoader, _epoch: int, _resume_step: int = 0):
avg_train_loss = 0
trailing_loss = 0
loss_buffer = []
try:
lr_for_print = "{:.2e}".format(scheduler.get_last_lr()[0])
except Exception:
pass
else:
lr_for_print = "{:.2e}".format(optimizer.param_groups[-1]["lr"])
model.train()
for __step, batch in (
pbar := tqdm(
enumerate(dataloader),
total=len(dataloader) + _resume_step,
initial=_resume_step,
leave=False,
)
):
step = __step + _resume_step + 1
src, tgt, mask = batch # (b_sz, s_len), (b_sz, s_len, v_sz)
logits = model(src) # (b_sz, s_len, v_sz)
logits = logits.transpose(1, 2) # Transpose for CrossEntropyLoss
loss = loss_fn(logits, tgt)
loss = loss * mask
loss = loss[loss != 0.0].mean() # != 0.0 here is important
# Calculate statistics
loss_buffer.append(loss.item())
if len(loss_buffer) > TRAILING_LOSS_STEPS:
loss_buffer.pop(0)
trailing_loss = sum(loss_buffer) / len(loss_buffer)
avg_train_loss = rolling_average(
avg_train_loss, loss.item(), __step
)
# Logging
logger.debug(
f"EPOCH {_epoch} STEP {step}: "
f"lr={lr_for_print}, "
f"loss={round(loss.item(), 4)}, "
f"trailing_loss={round(trailing_loss, 4)}, "
f"average_loss={round(avg_train_loss, 4)}"
)
if accelerator.is_main_process:
loss_writer.writerow([_epoch, step, loss.item()])
pbar.set_postfix_str(
f"lr={lr_for_print}, "
f"loss={round(loss.item(), 4)}, "
f"trailing={round(trailing_loss, 4)}"
)
# Backwards step
accelerator.backward(loss)
optimizer.step()
optimizer.zero_grad()
if scheduler:
scheduler.step()
lr_for_print = "{:.2e}".format(scheduler.get_last_lr()[0])
if steps_per_checkpoint:
if step % steps_per_checkpoint == 0:
make_checkpoint(
_accelerator=accelerator,
_epoch=_epoch,
_step=step,
)
logger.info(
f"EPOCH {_epoch}/{epochs + start_epoch}: Finished training - "
f"average_loss={round(avg_train_loss, 4)}"
)
return avg_train_loss
def val_loop(dataloader, _epoch: int):
avg_val_loss = 0
model.eval()
for step, batch in (
pbar := tqdm(
enumerate(dataloader),
total=len(dataloader),
leave=False,
)
):
src, tgt, mask = batch # (b_sz, s_len), (b_sz, s_len, v_sz)
with torch.no_grad():
logits = model(src) # (b_sz, s_len, v_sz)
logits = logits.transpose(1, 2) # Transpose for CrossEntropyLoss
loss = loss_fn(logits, tgt)
loss = loss * mask
loss = loss[loss != 0.0].mean()
# Logging
avg_val_loss = rolling_average(avg_val_loss, loss.item(), step)
pbar.set_postfix_str(f"average_loss={round(avg_val_loss, 4)}")
# EPOCH
logger.info(
f"EPOCH {_epoch}/{epochs + start_epoch}: Finished evaluation - "
f"average_loss={round(avg_val_loss, 4)}"
)
return avg_val_loss
if steps_per_checkpoint:
assert (
steps_per_checkpoint > 1
), "Invalid checkpoint mode value (too small)"
TRAILING_LOSS_STEPS = 200
PAD_ID = train_dataloader.dataset.tokenizer.pad_id
logger = get_logger(__name__) # Accelerate logger
loss_fn = nn.CrossEntropyLoss(ignore_index=PAD_ID, reduction="none")
profile_flops(dataloader=train_dataloader)
if accelerator.is_main_process:
loss_csv = open(os.path.join(project_dir, "loss.csv"), "w")
loss_writer = csv.writer(loss_csv)
loss_writer.writerow(["epoch", "step", "loss"])
epoch_csv = open(os.path.join(project_dir, "epoch.csv"), "w")
epoch_writer = csv.writer(epoch_csv)
epoch_writer.writerow(["epoch", "avg_train_loss", "avg_val_loss"])
if resume_epoch is not None:
start_epoch = resume_epoch + 1
else:
start_epoch = 0
if resume_step is not None:
assert resume_epoch is not None, "Must provide resume epoch"
logger.info(
f"Resuming training from step {resume_step} - logging as EPOCH {resume_epoch}"
)
skipped_dataloader = accelerator.skip_first_batches(
dataloader=train_dataloader,
num_batches=resume_step,
)
avg_train_loss = train_loop(
dataloader=skipped_dataloader,
_epoch=resume_epoch,
_resume_step=resume_step,
)
avg_val_loss = val_loop(dataloader=val_dataloader, _epoch=resume_epoch)
if accelerator.is_main_process:
epoch_writer.writerow([resume_epoch, avg_train_loss, avg_val_loss])
epoch_csv.flush()
make_checkpoint(
_accelerator=accelerator, _epoch=start_epoch, _step=0
)
for epoch in range(start_epoch, epochs + start_epoch):
train_dataloader.dataset.init_epoch(epoch)
avg_train_loss = train_loop(dataloader=train_dataloader, _epoch=epoch)
avg_val_loss = val_loop(dataloader=val_dataloader, _epoch=epoch)
if accelerator.is_main_process:
epoch_writer.writerow([epoch, avg_train_loss, avg_val_loss])
epoch_csv.flush()
make_checkpoint(_accelerator=accelerator, _epoch=epoch + 1, _step=0)
logging.shutdown()
if accelerator.is_main_process:
loss_csv.close()
epoch_csv.close()
# NOTE: Any differences observed when resuming training are most likely the
# result of randomness inherent to the data-augmentation. I'm currently unsure
# how to register and restore this random state during checkpointing.
def resume_train(
model_name: str,
train_data_path: str,
val_data_path: str,
num_workers: int,
batch_size: int,
epochs: int,
checkpoint_dir: str,
resume_epoch: int,
resume_step: int,
steps_per_checkpoint: int | None = None,
project_dir: str = None,
):
# Validate inputs
assert 0 < num_workers <= 128, "Too many workers"
assert epochs > 0, "Invalid number of epochs"
assert batch_size > 0, "Invalid batch size"
assert torch.cuda.is_available() is True, "CUDA not available"
assert os.path.isdir(checkpoint_dir), f"No dir at {checkpoint_dir}"
assert os.path.isdir(train_data_path), f"No dir found at {train_data_path}"
assert os.path.isdir(val_data_path), f"No dir found at {val_data_path}"
tokenizer_name = get_tokenizer_name(train_data_path, val_data_path)
if tokenizer_name == "abs":
tokenizer = AbsTokenizer(return_tensors=True)
elif tokenizer_name == "separated_abs":
tokenizer = SeparatedAbsTokenizer(return_tensors=True)
elif tokenizer_name == "rel":
tokenizer = RelTokenizer(return_tensors=True)
else:
raise Exception("Invalid tokenizer name")
# TODO: Add support for verifying the resume_step and epoch, keep these
# save these variables as part of the state during checkpointing
accelerator = accelerate.Accelerator(project_dir=project_dir)
if accelerator.is_main_process:
project_dir = setup_project_dir(project_dir)
logger = setup_logger(project_dir)
logger = get_logger(__name__)
logger.info(f"Using project directory {project_dir} ")
logger.warning(
"Please insure that the training config and resume step are set "
"correctly, the script does not currently check that this is the case. "
"If the previous checkpoint was saved at step n, then resume_step "
"should be n. If there is a mismatch between the batch size then the "
"script will resume at the wrong step. It is also important that the "
"same distributed setup is used for training."
)
logger.info(
f"Using training config: "
f"model_name={model_name}, "
f"epochs={epochs}, "
f"batch_size={batch_size}, "
f"num_workers={num_workers}, "
f"checkpoint_dir={checkpoint_dir}, "
f"resume_step={resume_step}, "
f"resume_epoch={resume_epoch}"
)
if steps_per_checkpoint:
logger.info(f"Creating checkpoints every {steps_per_checkpoint}")
# Init model
model_config = ModelConfig(**load_model_config(model_name))
model_config.set_vocab_size(tokenizer.vocab_size)
model = TransformerLM(model_config)
train_dataloader, val_dataloader = get_dataloaders(
train_data_dir=train_data_path,
val_data_dir=val_data_path,
tokenizer=tokenizer,
init_epoch=resume_epoch,
batch_size=batch_size,
num_workers=num_workers,
apply_aug=True,
)
optimizer, scheduler = get_optim(
model,
num_epochs=epochs,
steps_per_epoch=len(train_dataloader),
)
(
model,
train_dataloader,
val_dataloader,
optimizer,
scheduler,
) = accelerator.prepare(
model,
train_dataloader,
val_dataloader,
optimizer,
scheduler,
)
try:
accelerator.load_state(checkpoint_dir)
except Exception as e:
raise Exception(
f"Failed to load checkpoint: {e}\n"
"This could be due to a mismatch between the tokenizer used "
"to build the pre-training and fine-tuning datasets"
)
logger.info(f"Loaded checkpoint at {checkpoint_dir}")
logger.info("Starting train job")
_train(
epochs=epochs,
accelerator=accelerator,
model=model,
train_dataloader=train_dataloader,
val_dataloader=val_dataloader,
optimizer=optimizer,
scheduler=scheduler,
steps_per_checkpoint=steps_per_checkpoint,
resume_step=resume_step,
resume_epoch=resume_epoch,
project_dir=project_dir,
)
def train(
model_name: str,
train_data_path: str,
val_data_path: str,
num_workers: int,
batch_size: int,
epochs: int,
checkpoint_path: str | None = None,
steps_per_checkpoint: int | None = None,
project_dir: str = None,
):
# Validate inputs
assert 0 < num_workers <= 128, "Too many workers"
assert epochs > 0, "Invalid number of epochs"
assert batch_size > 0, "Invalid batch size"
assert torch.cuda.is_available() is True, "CUDA not available"
assert os.path.isdir(train_data_path), f"No dir found at {train_data_path}"
assert os.path.isdir(val_data_path), f"No dir found at {val_data_path}"
tokenizer_name = get_tokenizer_name(train_data_path, val_data_path)
if tokenizer_name == "abs":
tokenizer = AbsTokenizer(return_tensors=True)
elif tokenizer_name == "separated_abs":
tokenizer = SeparatedAbsTokenizer(return_tensors=True)
elif tokenizer_name == "rel":
tokenizer = RelTokenizer(return_tensors=True)
else:
raise Exception("Invalid tokenizer name")
accelerator = accelerate.Accelerator(project_dir=project_dir)
if accelerator.is_main_process:
project_dir = setup_project_dir(project_dir)
logger = setup_logger(project_dir)
logger = get_logger(__name__)
logger.info(f"Using project directory {project_dir}")
logger.info(
f"Using training config: "
f"model_name={model_name}, "
f"checkpoint_path={checkpoint_path}, "
if checkpoint_path
else ""
f"epochs={epochs}, "
f"batch_size={batch_size}, "
f"num_workers={num_workers}"
)
# Init model
model_config = ModelConfig(**load_model_config(model_name))
model_config.set_vocab_size(tokenizer.vocab_size)
model = TransformerLM(model_config)
logger.info(f"Loaded model with config: {load_model_config(model_name)}")
if checkpoint_path:
try:
model.load_state_dict(_load_weight(checkpoint_path))
except Exception as e:
raise Exception(
f"Failed to load checkpoint: {e}\n"
"This could be due to a mismatch between the tokenizer used "
"to build the pre-training and fine-tuning datasets"
)
logger.info(f"Loaded finetune checkpoint located at: {checkpoint_path}")
train_dataloader, val_dataloader = get_dataloaders(
train_data_dir=train_data_path,
val_data_dir=val_data_path,
tokenizer=tokenizer,
batch_size=batch_size,
num_workers=num_workers,
apply_aug=True,
finetune=True if checkpoint_path is not None else False,
)
optimizer, scheduler = get_optim(
model,
num_epochs=epochs,
steps_per_epoch=len(train_dataloader),
)
(
model,
train_dataloader,
val_dataloader,
optimizer,
scheduler,
) = accelerator.prepare(
model,
train_dataloader,
val_dataloader,
optimizer,
scheduler,
)
logger.info(f"Starting {'finetune' if checkpoint_path else 'pretrain'} job")
_train(
epochs=epochs,
accelerator=accelerator,
model=model,
train_dataloader=train_dataloader,
val_dataloader=val_dataloader,
optimizer=optimizer,
scheduler=scheduler,
steps_per_checkpoint=steps_per_checkpoint,
project_dir=project_dir,
)
def convert_cp_from_safetensors(checkpoint_path: str, save_path: str):
d = load_file(checkpoint_path)
key = list(d.keys())[0]
gap = len(key.split(".")[0])
d = {s[gap + 1 :]: v for s, v in d.items()}
torch.save(d, save_path)
def convert_cp_from_accelerate(
model_name: str, tokenizer_name: str, checkpoint_dir: str, save_path: str
):
def _load_state_dict(_tokenizer: Tokenizer):
model_config = ModelConfig(**load_model_config(model_name))
model_config.set_vocab_size(_tokenizer.vocab_size)
model = TransformerLM(model_config)
model = accelerator.prepare(model)
accelerator.load_state(checkpoint_dir)
return model.state_dict()
accelerator = accelerate.Accelerator()
# Try both
if tokenizer_name == "abs":
state_dict = _load_state_dict(_tokenizer=AbsTokenizer())
elif tokenizer_name == "rel":
state_dict = _load_state_dict(_tokenizer=RelTokenizer())
else:
print("Invalid choice of tokenizer")
torch.save(state_dict, save_path)
def parse_resume_args():
argp = argparse.ArgumentParser(prog="python aria/train.py resume")
argp.add_argument("model", help="name of model config file")
argp.add_argument("train_data", help="path to train data")
argp.add_argument("val_data", help="path to val data")
argp.add_argument("-cdir", help="checkpoint dir", type=str, required=True)
argp.add_argument("-rstep", help="resume step", type=int, required=True)
argp.add_argument("-repoch", help="resume epoch", type=int, required=True)
argp.add_argument("-epochs", help="train epochs", type=int, required=True)
argp.add_argument("-bs", help="batch size", type=int, default=32)
argp.add_argument("-workers", help="number workers", type=int, default=1)
argp.add_argument("-pdir", help="project dir", type=str, required=False)
argp.add_argument(
"-spc", help="steps per checkpoint", type=int, required=False
)
return argp.parse_args(sys.argv[2:])
def parse_train_args():
argp = argparse.ArgumentParser(prog="python aria/train.py train")
argp.add_argument("model", help="name of model config file")
argp.add_argument("train_data", help="path to train dir")
argp.add_argument("val_data", help="path to val dir")
argp.add_argument(
"-cp", help="path to checkpoint", required=False, default=None
)
argp.add_argument("-epochs", help="train epochs", type=int, required=True)
argp.add_argument("-bs", help="batch size", type=int, default=32)
argp.add_argument("-workers", help="number workers", type=int, default=1)
argp.add_argument("-pdir", help="project dir", type=str, required=False)
argp.add_argument(
"-spc", help="steps per checkpoint", type=int, required=False
)
return argp.parse_args(sys.argv[2:])
if __name__ == "__main__":
parser = argparse.ArgumentParser(
usage="python aria/train.py <command> [<args>]"
)
parser.add_argument(
"mode", help="training function", choices=("train", "resume")
)
args = parser.parse_args(sys.argv[1:2])
if not hasattr(args, "mode"):
parser.print_help()
print("Unrecognized command")
exit(1)
elif args.mode == "train":
train_args = parse_train_args()
train(
model_name=train_args.model,
train_data_path=train_args.train_data,
val_data_path=train_args.val_data,
num_workers=train_args.workers,
batch_size=train_args.bs,
epochs=train_args.epochs,
checkpoint_path=train_args.cp,
steps_per_checkpoint=train_args.spc,
project_dir=train_args.pdir,
)
elif args.mode == "resume":
resume_args = parse_resume_args()
resume_train(
model_name=resume_args.model,
train_data_path=resume_args.train_data,
val_data_path=resume_args.val_data,
num_workers=resume_args.workers,
batch_size=resume_args.bs,
epochs=resume_args.epochs,
checkpoint_dir=resume_args.cdir,
resume_step=resume_args.rstep,
resume_epoch=resume_args.repoch,
steps_per_checkpoint=resume_args.spc,
project_dir=resume_args.pdir,
)
else:
print("Unrecognized command")
parser.print_help()
exit(1)