-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
69 lines (53 loc) · 1.65 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
from pathlib import Path
import lightning as L
from lightning.pytorch.callbacks import Callback, EarlyStopping, ModelCheckpoint
from data import DataConfig, GraphDataModule
from model import GNNConfig, GNNModule
FilePath = str | Path
def init_trainer(
savedir: FilePath, early_stopping: bool = False, **kwargs
) -> L.Trainer:
monitor = "val_loss"
callbacks: list[Callback] = [
ModelCheckpoint(
monitor=monitor,
filename="{epoch}_{val_loss:.3f}",
save_last=False,
save_top_k=1,
mode="min",
every_n_epochs=1,
)
]
if early_stopping:
callbacks.append(
EarlyStopping(
monitor=monitor,
min_delta=0.01,
patience=5,
stopping_threshold=0.1,
divergence_threshold=1.0,
)
)
max_epochs = 250
else:
max_epochs = 150
trainer = L.Trainer(
max_epochs=max_epochs,
callbacks=callbacks,
accelerator="auto",
devices="auto",
# precision="16-true",
num_sanity_val_steps=0,
default_root_dir=savedir,
**kwargs
)
return trainer
def train(
trainer: L.Trainer, data_config: DataConfig, model_config: GNNConfig
) -> dict[str, float]:
datamodule = GraphDataModule(data_config)
model = GNNModule(model_config, datamodule.data.metadata())
trainer.fit(model, datamodule=datamodule)
test_results: dict[str, float] = trainer.test(model, datamodule=datamodule)[0] # type: ignore
test_results["n_parameters"] = model.num_parameters()
return test_results