-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
251 lines (213 loc) · 8 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
# System imports
import os
import sys
from pprint import pprint as pp
from time import time as tt
import inspect
# External imports
import matplotlib.pyplot as plt
import matplotlib.colors
from sklearn.decomposition import PCA
from sklearn.metrics import auc
import numpy as np
import pandas as pd
import seaborn as sns
import torch
from torch_geometric.data import Data
from torch_geometric.data import DataLoader
import argparse
from itertools import permutations
from itertools import chain
import trackml.dataset
import ipywidgets as widgets
from ipywidgets import interact, interact_manual
# Pick up local packages
sys.path.append("..")
# Local imports
from prepare import select_hits
from toy_utils import *
from models import *
from trainers import *
# Get rid of RuntimeWarnings, gross
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
import wandb
device = "cuda" if torch.cuda.is_available() else "cpu"
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser("train.py")
add_arg = parser.add_argument
add_arg("config", nargs="?", default="configs/hello.yaml")
add_arg("--hidden-dim", type=int, default=None, help="Hidden layer dimension size")
add_arg(
"--n-graph-iters", type=int, default=None, help="Number of graph iterations"
)
add_arg(
"--emb-dim",
type=int,
default=None,
help="Number of spatial embedding dimensions",
)
add_arg(
"--emb-hidden",
type=int,
default=None,
help="Number of embedding hidden dimensions",
)
add_arg("--nb-layer", type=int, default=None, help="Number of embedding layers")
add_arg("--r-val", type=float, default=None, help="Radius of graph construction")
add_arg("--r-train", type=float, default=None, help="Radius of embedding training")
add_arg("--margin", type=float, default=None, help="Radius of hinge loss")
add_arg("--lr-1", type=float, default=None, help="Embedding loss learning rate")
add_arg("--lr-2", type=float, default=None, help="AGNN loss learning rate")
add_arg("--lr-3", type=float, default=None, help="Weight balance learning rate")
add_arg("--weight", type=float, default=None, help="Positive weight in AGNN")
add_arg("--train-size", type=int, default=None, help="Number of train population")
add_arg("--val-size", type=int, default=None, help="Number of validate population")
add_arg("--pt-cut", type=float, default=None, help="Cutoff for momentum")
add_arg("--adjacent", type=bool, default=False, help="Enforce adjacent layers?")
return parser.parse_args()
def save_model(epoch, model, optimizer, scheduler, running_loss, config, PATH):
torch.save(
{
"epoch": epoch,
"model_state_dict": model.state_dict(),
"optimizer_state_dict": optimizer.state_dict(),
"scheduler_state_dict": scheduler.state_dict(),
"loss": running_loss,
"config": config,
},
os.path.join("model_comparisons/", PATH),
)
def main(args):
with open(args.config) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
# Dataset processing
pt_cut = config["selection"]["pt_min"]
train_number = config["selection"]["train_number"]
test_number = config["selection"]["test_number"]
load_dir = config["input_dir"]
model_dir = config["model_dir"]
# Construct experiment name
group = str(pt_cut) + "pt_cut"
if endcaps:
group += "_endcaps"
print("Running experiment group:", group)
train_path = os.path.join(load_dir, group, str(train_number) + "_events_train")
test_path = os.path.join(load_dir, group, str(test_number) + "_events_test")
train_dataset = torch.load(train_path)
test_dataset = torch.load(test_path)
train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=1, shuffle=True)
# Model config
m_configs = config["model"]
model = EmbeddingToAGNN(**m_configs).to(device)
# multi_loss = MultiNoiseLoss(n_losses=2).to(device)
m_configs.update(config["training"])
m_configs.update(config["selection"])
wandb.init(group=group, config=m_configs)
wandb.run.save()
print(wandb.run.name)
model_name = wandb.run.name
wandb.watch(model, log="all")
# Optimizer config
# optimizer = torch.optim.AdamW([
# {'params': model.emb_network.parameters()},
# {'params': chain(model.node_network.parameters(), model.edge_network.parameters(), model.input_network.parameters())},
# {'params': multi_loss.noise_params}],
# lr = 0.001, weight_decay=1e-3, amsgrad=True)
# Scheduler config
# lambda1 = lambda ep: 1 / (args.lr_1**(ep//10))
# lambda2 = lambda ep: 1 / (args.lr_2**(ep//30))
# lambda3 = lambda ep: 1 / (args.lr_3**(ep//10))
# scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=[lambda1, lambda2, lambda3])
optimizer = torch.optim.AdamW(
model.parameters(),
lr=m_configs["lr"],
weight_decay=m_configs["weight_decay"],
amsgrad=True,
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer, factor=m_configs["factor"], patience=m_configs["patience"]
)
# Training loop
for epoch in range(30):
tic = tt()
model.train()
if args.adjacent:
edge_acc, cluster_pur, train_loss = balanced_adjacent_train(
model, train_loader, optimizer, multi_loss, m_configs
)
else:
edge_acc, cluster_pur, train_loss = balanced_train(
model, train_loader, optimizer, multi_loss, m_configs
)
# print("Training loss:", train_loss)
model.eval()
if args.adjacent:
with torch.no_grad():
(
edge_acc,
edge_pur,
edge_eff,
cluster_pur,
cluster_eff,
val_loss,
av_nhood_size,
) = evaluate_adjacent(model, test_loader, multi_loss, m_configs)
else:
with torch.no_grad():
(
edge_acc,
edge_pur,
edge_eff,
cluster_pur,
cluster_eff,
val_loss,
av_nhood_size,
) = evaluate(model, test_loader, multi_loss, m_configs)
scheduler.step()
wandb.log(
{
"val_loss": val_loss,
"train_loss": train_loss,
"edge_acc": edge_acc,
"edge_pur": edge_pur,
"edge_eff": edge_eff,
"cluster_pur": cluster_pur,
"cluster_eff": cluster_eff,
"lr": scheduler._last_lr[0],
"combined_performance": edge_eff * cluster_eff * edge_pur + cluster_pur,
"combined_efficiency": edge_eff * cluster_eff * edge_pur,
"noise_1": multi_loss.noise_params[0].item(),
"noise_2": multi_loss.noise_params[1].item(),
"av_nhood_size": av_nhood_size,
}
)
save_model(
epoch,
model,
optimizer,
scheduler,
cluster_eff,
m_configs,
"EmbeddingToAGNN/" + model_name + ".tar",
)
print(
"Epoch: {}, Edge Accuracy: {:.4f}, Edge Purity: {:.4f}, Edge Efficiency: {:.4f}, Cluster Purity: {:.4f}, Cluster Efficiency: {:.4f}, Loss: {:.4f}, LR: {} in time {}".format(
epoch,
edge_acc,
edge_pur,
edge_eff,
cluster_pur,
cluster_eff,
val_loss,
scheduler._last_lr,
tt() - tic,
)
)
if __name__ == "__main__":
# Parse the command line
args = parse_args()
# print(args)
main(args)