-
Notifications
You must be signed in to change notification settings - Fork 41
/
trainer_motsp_no_transfer.py
executable file
·411 lines (307 loc) · 14.3 KB
/
trainer_motsp_no_transfer.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""Defines the main trainer model for combinatorial problems
Each task must define the following functions:
* mask_fn: can be None
* update_fn: can be None
* reward_fn: specifies the quality of found solutions
* render_fn: Specifies how to plot found solutions. Can be None
"""
import os
import time
import argparse
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from model import DRL4TSP, Encoder
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#device = torch.device('cpu')
class StateCritic(nn.Module):
"""Estimates the problem complexity.
This is a basic module that just looks at the log-probabilities predicted by
the encoder + decoder, and returns an estimate of complexity
"""
def __init__(self, static_size, dynamic_size, hidden_size):
super(StateCritic, self).__init__()
self.static_encoder = Encoder(static_size, hidden_size)
self.dynamic_encoder = Encoder(dynamic_size, hidden_size)
# Define the encoder & decoder models
self.fc1 = nn.Conv1d(hidden_size * 2, 20, kernel_size=1)
self.fc2 = nn.Conv1d(20, 20, kernel_size=1)
self.fc3 = nn.Conv1d(20, 1, kernel_size=1)
for p in self.parameters():
if len(p.shape) > 1:
nn.init.xavier_uniform_(p)
def forward(self, static, dynamic):
# Use the probabilities of visiting each
static_hidden = self.static_encoder(static)
dynamic_hidden = self.dynamic_encoder(dynamic)
hidden = torch.cat((static_hidden, dynamic_hidden), 1)
output = F.relu(self.fc1(hidden))
output = F.relu(self.fc2(output))
output = self.fc3(output).sum(dim=2)
return output
class Critic(nn.Module):
"""Estimates the problem complexity.
This is a basic module that just looks at the log-probabilities predicted by
the encoder + decoder, and returns an estimate of complexity
"""
def __init__(self, hidden_size):
super(Critic, self).__init__()
# Define the encoder & decoder models
self.fc1 = nn.Conv1d(1, hidden_size, kernel_size=1)
self.fc2 = nn.Conv1d(hidden_size, 20, kernel_size=1)
self.fc3 = nn.Conv1d(20, 1, kernel_size=1)
for p in self.parameters():
if len(p.shape) > 1:
nn.init.xavier_uniform_(p)
def forward(self, input):
output = F.relu(self.fc1(input.unsqueeze(1)))
output = F.relu(self.fc2(output)).squeeze(2)
output = self.fc3(output).sum(dim=2)
return output
def validate(data_loader, actor, reward_fn, w1, w2, render_fn=None, save_dir='.',
num_plot=5):
"""Used to monitor progress on a validation set & optionally plot solution."""
actor.eval()
if not os.path.exists(save_dir):
os.makedirs(save_dir)
rewards = []
obj1s = []
obj2s = []
for batch_idx, batch in enumerate(data_loader):
static, dynamic, x0 = batch
static = static.to(device)
dynamic = dynamic.to(device)
x0 = x0.to(device) if len(x0) > 0 else None
with torch.no_grad():
tour_indices, _ = actor.forward(static, dynamic, x0)
reward, obj1, obj2 = reward_fn(static, tour_indices, w1, w2)
rewards.append(torch.mean(reward.detach()).item())
obj1s.append(torch.mean(obj1.detach()).item())
obj2s.append(torch.mean(obj2.detach()).item())
if render_fn is not None and batch_idx < num_plot:
name = 'batch%d_%2.4f.png'%(batch_idx, torch.mean(reward.detach()).item())
path = os.path.join(save_dir, name)
render_fn(static, tour_indices, path)
actor.train()
return np.mean(rewards), np.mean(obj1s), np.mean(obj2s)
def train(actor, critic, w1, w2, task, num_nodes, train_data, valid_data, reward_fn,
render_fn, batch_size, actor_lr, critic_lr, max_grad_norm,
**kwargs):
"""Constructs the main actor & critic networks, and performs all training."""
now = '%s' % datetime.datetime.now().time()
now = now.replace(':', '_')
bname = "_4static"
save_dir = os.path.join(task+bname, '%d' % num_nodes, 'w_%2.2f_%2.2f' % (w1, w2), now)
checkpoint_dir = os.path.join(save_dir, 'checkpoints')
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
actor_optim = optim.Adam(actor.parameters(), lr=actor_lr)
critic_optim = optim.Adam(critic.parameters(), lr=critic_lr)
train_loader = DataLoader(train_data, batch_size, True, num_workers=0)
valid_loader = DataLoader(valid_data, batch_size, False, num_workers=0)
best_params = None
best_reward = np.inf
for epoch in range(5):
print("epoch %d start:"% epoch)
actor.train()
critic.train()
times, losses, rewards, critic_rewards = [], [], [], []
obj1s, obj2s = [], []
epoch_start = time.time()
start = epoch_start
for batch_idx, batch in enumerate(train_loader):
static, dynamic, x0 = batch
static = static.to(device)
dynamic = dynamic.to(device)
x0 = x0.to(device) if len(x0) > 0 else None
# Full forward pass through the dataset
tour_indices, tour_logp = actor(static, dynamic, x0)
# Sum the log probabilities for each city in the tour
reward, obj1, obj2 = reward_fn(static, tour_indices, w1, w2)
# Query the critic for an estimate of the reward
critic_est = critic(static, dynamic).view(-1)
advantage = (reward - critic_est)
actor_loss = torch.mean(advantage.detach() * tour_logp.sum(dim=1))
critic_loss = torch.mean(advantage ** 2)
actor_optim.zero_grad()
actor_loss.backward()
torch.nn.utils.clip_grad_norm_(actor.parameters(), max_grad_norm)
actor_optim.step()
critic_optim.zero_grad()
critic_loss.backward()
torch.nn.utils.clip_grad_norm_(critic.parameters(), max_grad_norm)
critic_optim.step()
critic_rewards.append(torch.mean(critic_est.detach()).item())
rewards.append(torch.mean(reward.detach()).item())
losses.append(torch.mean(actor_loss.detach()).item())
obj1s.append(torch.mean(obj1.detach()).item())
obj2s.append(torch.mean(obj2.detach()).item())
if (batch_idx + 1) % 200 == 0:
print("\n")
end = time.time()
times.append(end - start)
start = end
mean_loss = np.mean(losses[-100:])
mean_reward = np.mean(rewards[-100:])
mean_obj1 = np.mean(obj1s[-100:])
mean_obj2 = np.mean(obj2s[-100:])
print(' Batch %d/%d, reward: %2.3f, obj1: %2.3f, obj2: %2.3f, loss: %2.4f, took: %2.4fs' %
(batch_idx, len(train_loader), mean_reward, mean_obj1, mean_obj2, mean_loss,
times[-1]))
mean_loss = np.mean(losses)
mean_reward = np.mean(rewards)
# Save the weights
epoch_dir = os.path.join(checkpoint_dir, '%s' % epoch)
if not os.path.exists(epoch_dir):
os.makedirs(epoch_dir)
save_path = os.path.join(epoch_dir, 'actor.pt')
torch.save(actor.state_dict(), save_path)
save_path = os.path.join(epoch_dir, 'critic.pt')
torch.save(critic.state_dict(), save_path)
# Save rendering of validation set tours
valid_dir = os.path.join(save_dir, '%s' % epoch)
print("begin valid")
s = time.time()
mean_valid, mean_obj1_valid, mean_obj2_valid = validate(valid_loader, actor, reward_fn, w1, w2, render_fn,
valid_dir, num_plot=5)
print("valid end time: %2.4f" % (time.time()-s) )
# Save best model parameters
if mean_valid < best_reward:
best_reward = mean_valid
# save_path = os.path.join(save_dir, 'actor.pt')
# torch.save(actor.state_dict(), save_path)
#
# save_path = os.path.join(save_dir, 'critic.pt')
# torch.save(critic.state_dict(), save_path)
# 存在w_1_0主文件夹下,多存一份,用来transfer to next w
main_dir = os.path.join(task+bname, '%d' % num_nodes, 'w_%2.2f_%2.2f' % (w1, w2))
save_path = os.path.join(main_dir, 'actor.pt')
torch.save(actor.state_dict(), save_path)
save_path = os.path.join(main_dir, 'critic.pt')
torch.save(critic.state_dict(), save_path)
print('Mean epoch loss/reward: %2.4f, %2.4f, %2.4f, obj1_valid: %2.3f, obj2_valid: %2.3f. took: %2.4fs '\
'(%2.4fs / 100 batches)\n' % \
(mean_loss, mean_reward, mean_valid, mean_obj1_valid, mean_obj2_valid, time.time() - epoch_start,
np.mean(times)))
def train_tsp(args, w1=1, w2=0, checkpoint = None):
# Goals from paper:
# TSP20, 3.97
# TSP50, 6.08
# TSP100, 8.44
from tasks import motsp
from tasks.motsp import TSPDataset
STATIC_SIZE = 4 # (x, y)
DYNAMIC_SIZE = 1 # dummy for compatibility
train_data = TSPDataset(args.num_nodes, args.train_size, args.seed)
valid_data = TSPDataset(args.num_nodes, args.valid_size, args.seed + 1)
update_fn = None
actor = DRL4TSP(STATIC_SIZE,
DYNAMIC_SIZE,
args.hidden_size,
update_fn,
motsp.update_mask,
args.num_layers,
args.dropout).to(device)
critic = StateCritic(STATIC_SIZE, DYNAMIC_SIZE, args.hidden_size).to(device)
kwargs = vars(args)
kwargs['train_data'] = train_data
kwargs['valid_data'] = valid_data
kwargs['reward_fn'] = motsp.reward
kwargs['render_fn'] = motsp.render
if checkpoint:
path = os.path.join(checkpoint, 'actor.pt')
actor.load_state_dict(torch.load(path, device))
# actor.static_encoder.state_dict().get("conv.weight").size()
path = os.path.join(checkpoint, 'critic.pt')
critic.load_state_dict(torch.load(path, device))
if not args.test:
train(actor, critic, w1, w2, **kwargs)
test_data = TSPDataset(args.num_nodes, args.valid_size, args.seed + 2)
test_dir = 'test'
test_loader = DataLoader(test_data, args.valid_size, False, num_workers=0)
out = validate(test_loader, actor, motsp.reward, w1, w2, motsp.render, test_dir, num_plot=5)
print('w1=%2.2f,w2=%2.2f. Average tour length: ' % (w1, w2), out)
def train_vrp(args):
# Goals from paper:
# VRP10, Capacity 20: 4.84 (Greedy)
# VRP20, Capacity 30: 6.59 (Greedy)
# VRP50, Capacity 40: 11.39 (Greedy)
# VRP100, Capacity 50: 17.23 (Greedy)
from tasks import vrp
from tasks.vrp import VehicleRoutingDataset
# Determines the maximum amount of load for a vehicle based on num nodes
LOAD_DICT = {10: 20, 20: 30, 50: 40, 100: 50}
MAX_DEMAND = 9
STATIC_SIZE = 2 # (x, y)
DYNAMIC_SIZE = 2 # (load, demand)
max_load = LOAD_DICT[args.num_nodes]
train_data = VehicleRoutingDataset(args.train_size,
args.num_nodes,
max_load,
MAX_DEMAND,
args.seed)
valid_data = VehicleRoutingDataset(args.valid_size,
args.num_nodes,
max_load,
MAX_DEMAND,
args.seed + 1)
actor = DRL4TSP(STATIC_SIZE,
DYNAMIC_SIZE,
args.hidden_size,
train_data.update_dynamic,
train_data.update_mask,
args.num_layers,
args.dropout).to(device)
critic = StateCritic(STATIC_SIZE, DYNAMIC_SIZE, args.hidden_size).to(device)
kwargs = vars(args)
kwargs['train_data'] = train_data
kwargs['valid_data'] = valid_data
kwargs['reward_fn'] = vrp.reward
kwargs['render_fn'] = vrp.render
if args.checkpoint:
path = os.path.join(args.checkpoint, 'actor.pt')
actor.load_state_dict(torch.load(path, device))
path = os.path.join(args.checkpoint, 'critic.pt')
critic.load_state_dict(torch.load(path, device))
if not args.test:
train(actor, critic, **kwargs)
test_data = VehicleRoutingDataset(args.valid_size,
args.num_nodes,
max_load,
MAX_DEMAND,
args.seed + 2)
test_dir = 'test'
test_loader = DataLoader(test_data, args.batch_size, False, num_workers=0)
out = validate(test_loader, actor, vrp.reward, vrp.render, test_dir, num_plot=5)
print('Average tour length: ', out)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Combinatorial Optimization')
parser.add_argument('--seed', default=12345, type=int)
# parser.add_argument('--checkpoint', default="tsp/20/w_1_0/20_06_30.888074")
parser.add_argument('--test', action='store_true', default=False)
parser.add_argument('--task', default='tsp')
parser.add_argument('--nodes', dest='num_nodes', default=40, type=int)
parser.add_argument('--actor_lr', default=5e-4, type=float)
parser.add_argument('--critic_lr', default=5e-4, type=float)
parser.add_argument('--max_grad_norm', default=2., type=float)
parser.add_argument('--batch_size', default=200, type=int)
parser.add_argument('--hidden', dest='hidden_size', default=128, type=int)
parser.add_argument('--dropout', default=0.1, type=float)
parser.add_argument('--layers', dest='num_layers', default=1, type=int)
parser.add_argument('--train-size',default=500000, type=int)
parser.add_argument('--valid-size', default=1000, type=int)
args = parser.parse_args()
# Trained without transfer
if args.task == 'tsp':
w2_list = np.arange(101)/100
for i in range(0,101):
print("Current w:%2.2f/%2.2f"% (1-w2_list[i], w2_list[i]))
train_tsp(args, 1-w2_list[i], w2_list[i], None)
elif args.task == 'vrp':
train_vrp(args)
else:
raise ValueError('Task <%s> not understood'%args.task)