/
train.py
110 lines (94 loc) · 2.59 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
import random
from collections import defaultdict
import numpy as np
import torch
import torch_geometric
from sacred import Experiment
from sacred.observers import FileStorageObserver
from tqdm import trange
from datasets import load_temporal_data
from model.tgne import TGNE
ex = Experiment("tgne")
ex.observers.append(FileStorageObserver.create("my_runs"))
def set_seed(seed):
print("Setting seed to", seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch_geometric.seed_everything(seed)
@ex.config
def config():
dataset = "toy"
seed = 42
dim = 2
prior_scale_init = None
prior_scale = 1.0
n_ticks = 15
n_epochs = 200
lr_z = 0.1
lr_bias = 0.001
cuda = False
batch_size = None
@ex.automain
def train(
dataset,
dim,
prior_scale_init,
prior_scale,
n_ticks,
n_epochs,
lr_z,
lr_bias,
cuda,
batch_size,
):
temporal_data = load_temporal_data(dataset)
set_seed(42)
save = True
import sys
if "-d" in sys.argv or "--debug" in sys.argv:
print("Debug mode")
n_epochs = 1
save = False
tgne = TGNE(
n_nodes=temporal_data.num_nodes,
n_ticks=n_ticks,
dim=dim,
prior_scale=prior_scale,
prior_scale_init=prior_scale if prior_scale_init is None else prior_scale_init,
cuda=cuda,
lr_bias=lr_bias,
lr_z=lr_z,
)
train_data = temporal_data
train_loader = torch.utils.data.DataLoader(
train_data,
batch_size=len(train_data) if not batch_size else batch_size,
collate_fn=train_data.collate,
)
steps = trange(n_epochs)
losses = []
grads = defaultdict(list)
for step in steps:
for batch in train_loader:
batch_logs = tgne.training_step(batch)
loss = batch_logs["loss"]
for param_name, grad in batch_logs["grads"].items():
grads[param_name].append(grad)
losses.append(batch_logs["loss"])
steps.set_description("loss: {:.4f}".format(loss))
ex.log_scalar("loss", loss, step)
for param_name, grad in batch_logs["grads"].items():
ex.log_scalar(f"grad_{param_name}", grad, step)
out = {
"state_dict": tgne.state_dict(),
"losses": losses,
"grads": grads,
}
if save:
fname = f"tgne_{dataset}_{n_epochs}.ckpt"
outpath = f"output/{fname}"
torch.save(out, outpath)
# This will copy and paste the trained model to the run-specific folder
ex.add_artifact(outpath, name=fname)