forked from juho-lee/set_transformer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
151 lines (135 loc) · 4.8 KB
/
run.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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import pickle
import os
import argparse
import logging
import time
from tqdm import tqdm
import matplotlib.pyplot as plt
from models import SetTransformer, DeepSet
from mixture_of_mvns import MixtureOfMVNs
from mvn_diag import MultivariateNormalDiag
parser = argparse.ArgumentParser()
parser.add_argument('--mode', type=str, default='train')
parser.add_argument('--num_bench', type=int, default=100)
parser.add_argument('--net', type=str, default='set_transformer')
parser.add_argument('--B', type=int, default=10)
parser.add_argument('--N_min', type=int, default=300)
parser.add_argument('--N_max', type=int, default=600)
parser.add_argument('--K', type=int, default=4)
parser.add_argument('--gpu', type=str, default='0')
parser.add_argument('--lr', type=float, default=1e-3)
parser.add_argument('--run_name', type=str, default='trial')
parser.add_argument('--num_steps', type=int, default=50000)
parser.add_argument('--test_freq', type=int, default=200)
parser.add_argument('--save_freq', type=int, default=400)
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
B = args.B
N_min = args.N_min
N_max = args.N_max
K = args.K
D = 2
mvn = MultivariateNormalDiag(D)
mog = MixtureOfMVNs(mvn)
dim_output = 2*D
if args.net == 'set_transformer':
net = SetTransformer(D, K, dim_output).cuda()
elif args.net == 'deepset':
net = DeepSet(D, K, dim_output).cuda()
else:
raise ValueError('Invalid net {}'.format(args.net))
benchfile = os.path.join('benchmark', 'mog_{:d}.pkl'.format(K))
def generate_benchmark():
if not os.path.isdir('benchmark'):
os.makedirs('benchmark')
N_list = np.random.randint(N_min, N_max, args.num_bench)
data = []
ll = 0.
for N in tqdm(N_list):
X, labels, pi, params = mog.sample(B, N, K, return_gt=True)
ll += mog.log_prob(X, pi, params).item()
data.append(X)
bench = [data, ll/args.num_bench]
torch.save(bench, benchfile)
save_dir = os.path.join('results', args.net, args.run_name)
def train():
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
if not os.path.isfile(benchfile):
generate_benchmark()
bench = torch.load(benchfile)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(args.run_name)
logger.addHandler(logging.FileHandler(
os.path.join(save_dir,
'train_'+time.strftime('%Y%m%d-%H%M')+'.log'),
mode='w'))
logger.info(str(args) + '\n')
optimizer = optim.Adam(net.parameters(), lr=args.lr)
tick = time.time()
for t in range(1, args.num_steps+1):
if t == int(0.5*args.num_steps):
optimizer.param_groups[0]['lr'] *= 0.1
net.train()
optimizer.zero_grad()
N = np.random.randint(N_min, N_max)
X = mog.sample(B, N, K)
ll = mog.log_prob(X, *mvn.parse(net(X)))
loss = -ll
loss.backward()
optimizer.step()
if t % args.test_freq == 0:
line = 'step {}, lr {:.3e}, '.format(
t, optimizer.param_groups[0]['lr'])
line += test(bench, verbose=False)
line += ' ({:.3f} secs)'.format(time.time()-tick)
tick = time.time()
logger.info(line)
if t % args.save_freq == 0:
torch.save({'state_dict':net.state_dict()},
os.path.join(save_dir, 'model.tar'))
torch.save({'state_dict':net.state_dict()},
os.path.join(save_dir, 'model.tar'))
def test(bench, verbose=True):
net.eval()
data, oracle_ll = bench
avg_ll = 0.
for X in data:
X = X.cuda()
avg_ll += mog.log_prob(X, *mvn.parse(net(X))).item()
avg_ll /= len(data)
line = 'test ll {:.4f} (oracle {:.4f})'.format(avg_ll, oracle_ll)
if verbose:
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(args.run_name)
logger.addHandler(logging.FileHandler(
os.path.join(save_dir, 'test.log'), mode='w'))
logger.info(line)
return line
def plot():
net.eval()
X = mog.sample(B, np.random.randint(N_min, N_max), K)
pi, params = mvn.parse(net(X))
ll, labels = mog.log_prob(X, pi, params, return_labels=True)
fig, axes = plt.subplots(2, B//2, figsize=(7*B//5,5))
mog.plot(X, labels, params, axes)
plt.show()
if __name__ == '__main__':
if args.mode == 'bench':
generate_benchmark()
elif args.mode == 'train':
train()
elif args.mode == 'test':
bench = torch.load(benchfile)
ckpt = torch.load(os.path.join(save_dir, 'model.tar'))
net.load_state_dict(ckpt['state_dict'])
test(bench)
elif args.mode == 'plot':
ckpt = torch.load(os.path.join(save_dir, 'model.tar'))
net.load_state_dict(ckpt['state_dict'])
plot()