-
Notifications
You must be signed in to change notification settings - Fork 20
/
train_teacher.py
executable file
·346 lines (305 loc) · 10.4 KB
/
train_teacher.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
import argparse
import numpy as np
import torch
import torch.optim as optim
from pathlib import Path
from models import Model
from dataloader import load_data
from utils import (
get_logger,
get_evaluator,
set_seed,
get_training_config,
check_writable,
compute_min_cut_loss,
graph_split,
feature_prop,
)
from train_and_eval import run_transductive, run_inductive
def get_args():
parser = argparse.ArgumentParser(description="PyTorch DGL implementation")
parser.add_argument("--device", type=int, default=-1, help="CUDA device, -1 means CPU")
parser.add_argument("--seed", type=int, default=0, help="Random seed")
parser.add_argument(
"--log_level",
type=int,
default=20,
help="Logger levels for run {10: DEBUG, 20: INFO, 30: WARNING}",
)
parser.add_argument(
"--console_log",
action="store_true",
help="Set to True to display log info in console",
)
parser.add_argument(
"--output_path", type=str, default="outputs", help="Path to save outputs"
)
parser.add_argument(
"--num_exp", type=int, default=1, help="Repeat how many experiments"
)
parser.add_argument(
"--exp_setting",
type=str,
default="tran",
help="Experiment setting, one of [tran, ind]",
)
parser.add_argument(
"--eval_interval", type=int, default=1, help="Evaluate once per how many epochs"
)
parser.add_argument(
"--save_results",
action="store_true",
help="Set to True to save the loss curves, trained model, and min-cut loss for the transductive setting",
)
"""Dataset"""
parser.add_argument("--dataset", type=str, default="cora", help="Dataset")
parser.add_argument("--data_path", type=str, default="./data", help="Path to data")
parser.add_argument(
"--labelrate_train",
type=int,
default=20,
help="How many labeled data per class as train set",
)
parser.add_argument(
"--labelrate_val",
type=int,
default=30,
help="How many labeled data per class in valid set",
)
parser.add_argument(
"--split_idx",
type=int,
default=0,
help="For Non-Homo datasets only, one of [0,1,2,3,4]",
)
"""Model"""
parser.add_argument(
"--model_config_path",
type=str,
default="./train.conf.yaml",
help="Path to model configeration",
)
parser.add_argument("--teacher", type=str, default="SAGE", help="Teacher model")
parser.add_argument(
"--num_layers", type=int, default=2, help="Model number of layers"
)
parser.add_argument(
"--hidden_dim", type=int, default=128, help="Model hidden layer dimensions"
)
parser.add_argument("--dropout_ratio", type=float, default=0)
parser.add_argument(
"--norm_type", type=str, default="none", help="One of [none, batch, layer]"
)
"""SAGE Specific"""
parser.add_argument("--batch_size", type=int, default=512)
parser.add_argument(
"--fan_out",
type=str,
default="5,5",
help="Number of samples for each layer in SAGE. Length = num_layers",
)
parser.add_argument(
"--num_workers", type=int, default=0, help="Number of workers for sampler"
)
"""Optimization"""
parser.add_argument("--learning_rate", type=float, default=0.01)
parser.add_argument("--weight_decay", type=float, default=0.0005)
parser.add_argument(
"--max_epoch", type=int, default=500, help="Evaluate once per how many epochs"
)
parser.add_argument(
"--patience",
type=int,
default=50,
help="Early stop is the score on validation set does not improve for how many epochs",
)
"""Ablation"""
parser.add_argument(
"--feature_noise",
type=float,
default=0,
help="add white noise to features for analysis, value in [0, 1] for noise level",
)
parser.add_argument(
"--split_rate",
type=float,
default=0.2,
help="Rate for graph split, see comment of graph_split for more details",
)
parser.add_argument(
"--compute_min_cut",
action="store_true",
help="Set to True to compute and store the min-cut loss",
)
parser.add_argument(
"--feature_aug_k",
type=int,
default=0,
help="Augment node futures by aggregating feature_aug_k-hop neighbor features",
)
args = parser.parse_args()
return args
def run(args):
"""
Returns:
score_lst: a list of evaluation results on test set.
len(score_lst) = 1 for the transductive setting.
len(score_lst) = 2 for the inductive/production setting.
"""
""" Set seed, device, and logger """
set_seed(args.seed)
if torch.cuda.is_available() and args.device >= 0:
device = torch.device("cuda:" + str(args.device))
else:
device = "cpu"
if args.feature_noise != 0 and args.seed == 0:
args.output_path = Path.cwd().joinpath(
args.output_path, "noisy_features", f"noise_{args.feature_noise}"
)
if args.feature_aug_k > 0 and args.seed == 0:
args.output_path = Path.cwd().joinpath(
args.output_path, "aug_features", f"aug_hop_{args.feature_aug_k}"
)
args.teacher = f"GA{args.feature_aug_k}{args.teacher}"
if args.exp_setting == "tran":
output_dir = Path.cwd().joinpath(
args.output_path,
"transductive",
args.dataset,
args.teacher,
f"seed_{args.seed}",
)
elif args.exp_setting == "ind":
output_dir = Path.cwd().joinpath(
args.output_path,
"inductive",
f"split_rate_{args.split_rate}",
args.dataset,
args.teacher,
f"seed_{args.seed}",
)
else:
raise ValueError(f"Unknown experiment setting! {args.exp_setting}")
args.output_dir = output_dir
check_writable(output_dir, overwrite=False)
logger = get_logger(output_dir.joinpath("log"), args.console_log, args.log_level)
logger.info(f"output_dir: {output_dir}")
""" Load data """
g, labels, idx_train, idx_val, idx_test = load_data(
args.dataset,
args.data_path,
split_idx=args.split_idx,
seed=args.seed,
labelrate_train=args.labelrate_train,
labelrate_val=args.labelrate_val,
)
logger.info(f"Total {g.number_of_nodes()} nodes.")
logger.info(f"Total {g.number_of_edges()} edges.")
feats = g.ndata["feat"]
args.feat_dim = g.ndata["feat"].shape[1]
args.label_dim = labels.int().max().item() + 1
if 0 < args.feature_noise <= 1:
feats = (
1 - args.feature_noise
) * feats + args.feature_noise * torch.randn_like(feats)
""" Model config """
conf = {}
if args.model_config_path is not None:
conf = get_training_config(args.model_config_path, args.teacher, args.dataset)
conf = dict(args.__dict__, **conf)
conf["device"] = device
logger.info(f"conf: {conf}")
""" Model init """
model = Model(conf)
optimizer = optim.Adam(
model.parameters(), lr=conf["learning_rate"], weight_decay=conf["weight_decay"]
)
criterion = torch.nn.NLLLoss()
evaluator = get_evaluator(conf["dataset"])
""" Data split and run """
loss_and_score = []
if args.exp_setting == "tran":
indices = (idx_train, idx_val, idx_test)
# propagate node feature
if args.feature_aug_k > 0:
feats = feature_prop(feats, g, args.feature_aug_k)
out, score_val, score_test = run_transductive(
conf,
model,
g,
feats,
labels,
indices,
criterion,
evaluator,
optimizer,
logger,
loss_and_score,
)
score_lst = [score_test]
elif args.exp_setting == "ind":
indices = graph_split(idx_train, idx_val, idx_test, args.split_rate, args.seed)
# propagate node feature. The propagation for the observed graph only happens within the subgraph obs_g
if args.feature_aug_k > 0:
idx_obs = indices[3]
obs_g = g.subgraph(idx_obs)
obs_feats = feature_prop(feats[idx_obs], obs_g, args.feature_aug_k)
feats = feature_prop(feats, g, args.feature_aug_k)
feats[idx_obs] = obs_feats
out, score_val, score_test_tran, score_test_ind = run_inductive(
conf,
model,
g,
feats,
labels,
indices,
criterion,
evaluator,
optimizer,
logger,
loss_and_score,
)
score_lst = [score_test_tran, score_test_ind]
logger.info(
f"num_layers: {conf['num_layers']}. hidden_dim: {conf['hidden_dim']}. dropout_ratio: {conf['dropout_ratio']}"
)
logger.info(f"# params {sum(p.numel() for p in model.parameters())}")
""" Saving teacher outputs """
out_np = out.detach().cpu().numpy()
np.savez(output_dir.joinpath("out"), out_np)
""" Saving loss curve and model """
if args.save_results:
# Loss curves
loss_and_score = np.array(loss_and_score)
np.savez(output_dir.joinpath("loss_and_score"), loss_and_score)
# Model
torch.save(model.state_dict(), output_dir.joinpath("model.pth"))
""" Saving min-cut loss """
if args.exp_setting == "tran" and args.compute_min_cut:
min_cut = compute_min_cut_loss(g, out)
with open(output_dir.parent.joinpath("min_cut_loss"), "a+") as f:
f.write(f"{min_cut :.4f}\n")
return score_lst
def repeat_run(args):
scores = []
for seed in range(args.num_exp):
args.seed = seed
scores.append(run(args))
scores_np = np.array(scores)
return scores_np.mean(axis=0), scores_np.std(axis=0)
def main():
args = get_args()
if args.num_exp == 1:
score = run(args)
score_str = "".join([f"{s : .4f}\t" for s in score])
elif args.num_exp > 1:
score_mean, score_std = repeat_run(args)
score_str = "".join(
[f"{s : .4f}\t" for s in score_mean] + [f"{s : .4f}\t" for s in score_std]
)
with open(args.output_dir.parent.joinpath("exp_results"), "a+") as f:
f.write(f"{score_str}\n")
# for collecting aggregated results
print(score_str)
if __name__ == "__main__":
main()