-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrainer.py
72 lines (59 loc) · 1.81 KB
/
trainer.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
import os
import pytorch_lightning as pl
from pytorch_lightning.callbacks import (
EarlyStopping,
LearningRateMonitor,
ModelCheckpoint,
)
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.plugins import DDPPlugin
import torch
from model import compute_metrics
# Seed
pl.seed_everything(42, workers=True)
def build_trainer(args):
# Get folder name
name = f"{args.model_name}_{args.data_name}"
# Callbacks
enable_checkpointing = "test" not in args.mode
if enable_checkpointing:
callbacks = []
callbacks += [
ModelCheckpoint(
filename="best", monitor=args.monitor, mode="min", save_last=True
)
]
callbacks += [
EarlyStopping(
monitor=args.monitor,
mode="min",
min_delta=1e-3,
patience=5,
strict=True,
)
]
if args.lr == 0:
args.lr = None
else:
callbacks += [LearningRateMonitor()]
logger = TensorBoardLogger(save_dir="checkpoints", name=name)
else:
callbacks = None
logger = False
n_gpus = torch.cuda.device_count()
return pl.Trainer.from_argparse_args(
args,
accelerator="ddp" if n_gpus > 1 else None,
check_val_every_n_epoch=1,
gpus=n_gpus,
plugins=DDPPlugin(find_unused_parameters=False) if n_gpus > 1 else None,
default_root_dir="checkpoints",
max_epochs=args.max_epochs,
accumulate_grad_batches=args.accumulate_grad_batches,
val_check_interval=args.val_check_interval,
callbacks=callbacks,
logger=logger,
log_every_n_steps=1,
fast_dev_run=args.fast_dev_run,
enable_checkpointing=enable_checkpointing,
)