-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain_model3.py
More file actions
274 lines (217 loc) · 7.79 KB
/
train_model3.py
File metadata and controls
274 lines (217 loc) · 7.79 KB
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
from model import *
import torch
import gzip
import pickle
import os
import random
from alive_progress import alive_bar
random.seed(0)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
ident = "lp"
# ident = "lp_20_20"
# ident = "lp_15_15"
ident = "lp_75_75"
# ident = "lp_500_500"
ident = "CA_20_20"
ident = "CA_50_50"
# ident = "CA_300_300"
# ident = "IS_10"
ident = "IS_500"
ident = "IS_1000"
ident = "IS_50"
# ident = "lp_75_75_60.0"
ident = "lp_50_50_600.0"
ident = "lp_500_500_600.0"
ident = "lp_10000_10000_5.0"
ident = "IS_10000"
ident = "lp_1000_1000_600.0"
ident = "lp_5000_5000_20.0"
ident = "lp_500_500_600.0"
ident = "maxflow_2000_2000_600.0"
ident = "maxflow_600_600_600.0"
# ident = "maxflow_1000_1000_600.0"
eps=0.2
nfeat = 5
model_type = 'dchannel'
lrate = 1e-3
conts=False
# lrate = 1e-4
# conts=False
# lrate = 1e-5
# conts=True
idf = f"data_{ident}"
nfeat = 5
other='x0'+model_type
if nfeat!=1:
other += f'_feat{nfeat}'
if eps!=0.2:
other += f'_ep{eps}'
flist_train = os.listdir(f'./{idf}/train')
flist_valid = os.listdir(f'./{idf}/valid')[:100]
best_loss = 1e+20
mdl = framework_model1dim(4,64,nfeat,model_type).to(device)
parm_num = count_parameters(mdl)
print(f'Number of parameters:: {parm_num}')
# mdl = framework_model3(2,2,64,4)
last_epoch=0
if not os.path.isdir('./model'):
os.mkdir('./model')
elif os.path.exists(f"./model/best_model3_{ident}{other}.mdl") and conts:
checkpoint = torch.load(f"./model/best_model3_{ident}{other}.mdl")
mdl.load_state_dict(checkpoint['model'])
if 'nepoch' in checkpoint:
last_epoch=checkpoint['nepoch']
best_loss=checkpoint['best_loss']
print(f'Last best val loss gen: {best_loss}')
print('Model Loaded')
loss_func = torch.nn.MSELoss()
optimizer = torch.optim.Adam(mdl.parameters(), lr=lrate)
max_epoch = 10000
if not os.path.isdir('./logs'):
os.mkdir('./logs')
flog = open(f'./logs/train_log_fixed_mu_{ident}{other}.log','w')
for epoch in range(last_epoch, max_epoch):
avg_loss=[0,0,0]
random.shuffle(flist_train)
with alive_bar(len(flist_train),title=f"Model3 Training Epoch:{epoch} task:{ident}") as bar:
for fnm in flist_train:
# train
# reading
f = gzip.open(f'./data_{ident}/train/{fnm}','rb')
# A,v,c,sol,dual,obj = pickle.load(f)
tar = pickle.load(f)
A = tar[0].to(device)
# v = tar[1]
# c = tar[2]
sol = tar[3]
dual = tar[4]
obj = tar[5]
if len(tar)>=9:
cost = torch.as_tensor(tar[7])
minA = torch.as_tensor(tar[8])
if not torch.is_tensor(A):
A = torch.as_tensor(A,dtype=torch.float32).to(device)
amx = None
if A.is_sparse:
amx = torch.max(A.values())
else:
amx = torch.max(A)
m = A.shape[0]
mu = 1/eps * torch.log(m*amx/eps)
# x = torch.as_tensor(v,dtype=torch.float32)
# y = torch.as_tensor(c,dtype=torch.float32)
x_gt = torch.as_tensor(sol,dtype=torch.float32).to(device)
y_gt = torch.as_tensor(dual,dtype=torch.float32).to(device)
f.close()
# apply gradient
optimizer.zero_grad()
n = A.shape[1]
# x = torch.ones((n,1))
x = torch.zeros((n,1)).to(device)
y = torch.zeros((m,1)).to(device)
x,y = mdl(A,x,y,mu)
# check if need to restore val
# if len(tar)>=9:
# x = x/minA
# for i in range(x.shape[0]):
# x[i] = x[i]/cost[i]
# for name,param in mdl.named_parameters():
# if param.requires_grad and 't2' in name:
# print(name)
# print(param)
# # print(x)
# # print(fnm, mu)
# quit()
x_gt = x_gt.unsqueeze(-1)
loss_x = loss_func(x, x_gt)
# print(x.min(),x.max())
# print(x_gt.min(),x_gt.max())
# input()
avg_loss[0] += loss_x.item()
if len(tar)>=9:
print(loss_x.item(),torch.sum(x).item()/minA.item(),obj)
else:
print(loss_x.item(),torch.sum(x).item(),obj)
# loss_y = loss_func(y, y_gt)
# avg_loss[1] += loss_y.item()
# loss = loss_x+loss_y
loss = loss_x
# avg_loss[2] += loss.item()
loss.backward()
optimizer.step()
bar()
avg_loss[0] /= round(len(flist_train),2)
avg_loss[1] /= round(len(flist_train),2)
avg_loss[2] /= round(len(flist_train),2)
# print(f'Epoch {epoch} Train:::: primal loss:{avg_loss[0]}, dual loss:{avg_loss[1]}, total loss:{avg_loss[2]}')
print(f'Epoch {epoch} Train:::: primal loss:{avg_loss[0]}')
st = f'Epoch {epoch}::::{avg_loss[0]} '
flog.write(st)
optimizer.zero_grad()
avg_loss=[0,0,0]
with torch.no_grad():
with alive_bar(len(flist_valid),title=f"Valid Epoch:{epoch}") as bar:
for fnm in flist_valid:
# valid
# reading
f = gzip.open(f'./data_{ident}/valid/{fnm}','rb')
# A,v,c,sol,dual,obj = pickle.load(f)
tar = pickle.load(f)
A = tar[0].to(device)
# v = tar[1]
# c = tar[2]
sol = tar[3]
dual = tar[4]
obj = tar[5]
if len(tar)>=9:
cost = tar[7]
minA = tar[8]
A = torch.as_tensor(A,dtype=torch.float32).to(device)
amx = None
if A.is_sparse:
amx = torch.max(A.values())
else:
amx = torch.max(A)
m = A.shape[0]
mu = 1/eps * torch.log(m*amx/eps)
# x = torch.as_tensor(v,dtype=torch.float32)
# y = torch.as_tensor(c,dtype=torch.float32)
x_gt = torch.as_tensor(sol,dtype=torch.float32).to(device)
y_gt = torch.as_tensor(dual,dtype=torch.float32).to(device)
f.close()
# obtain loss
n = A.shape[1]
# x = torch.ones((n,1))
x = torch.zeros((n,1)).to(device)
y = torch.zeros((m,1)).to(device)
x_gt = x_gt.unsqueeze(-1)
x,y = mdl(A,x,y,mu)
# check if need to restore val
# if len(tar)>=9:
# x = x/minA
# for i in range(x.shape[0]):
# x[i] = x[i]/cost[i]
loss_x = loss_func(x, x_gt)
avg_loss[0] += loss_x.item()
# loss_y = loss_func(y, y_gt)
# avg_loss[1] += loss_y.item()
# loss = loss_x+loss_y
# avg_loss[2] += loss.item()
bar()
avg_loss[0] /= round(len(flist_valid),2)
avg_loss[1] /= round(len(flist_valid),2)
avg_loss[2] /= round(len(flist_valid),2)
# print(f'Epoch {epoch} Valid:::: primal loss:{avg_loss[0]}, dual loss:{avg_loss[1]}, total loss:{avg_loss[2]}')
print(f'Epoch {epoch} Valid:::: primal loss:{avg_loss[0]}')
st = f'{avg_loss[0]}\n'
flog.write(st)
if best_loss > avg_loss[0]:
best_loss = avg_loss[0]
state={'model':mdl.state_dict(),'optimizer':optimizer.state_dict(),'best_loss':best_loss,'nepoch':epoch}
torch.save(state,f'./model/best_model3_{ident}{other}.mdl')
st =f'Saving new best model with valid loss: {best_loss}\n'
flog.write(st)
print(f'Saving new best model with valid loss: {best_loss}')
flog.flush()
flog.close()