-
Notifications
You must be signed in to change notification settings - Fork 0
/
policy.py
441 lines (378 loc) · 18.4 KB
/
policy.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# -*- coding: utf-8 -*-
"""
@author: ryuichi takanobu
@modified: anubhav sachan
"""
import os
import logging
import torch
import torch.nn as nn
from torch import optim
from utils import to_device
from evaluator import MultiWozEvaluator, DSTCSGDSEvaluator
from torch.utils.tensorboard import SummaryWriter
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class MultiDiscretePolicy(nn.Module):
def __init__(self, cfg, character='sys'):
super(MultiDiscretePolicy, self).__init__()
if character == 'sys':
self.net = nn.Sequential(nn.Linear(cfg.s_dim, cfg.h_dim),
nn.ReLU(),
nn.Linear(cfg.h_dim, 1024),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(1024, 2048),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(2048, 3072),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(3072, 4096),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(4096, 5120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(5120, 7120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(7120, 9120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(9120, 5120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(5120, 4052),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(4052, 3072),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(3072, 2048),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(2048, 2048),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(2048, 1000),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(1000, 500),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(500, 256),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(256, cfg.h_dim),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(cfg.h_dim, cfg.h_dim),
nn.ReLU(),
nn.Linear(cfg.h_dim, cfg.a_dim))
elif character == 'usr':
self.net = nn.Sequential(nn.Linear(cfg.s_dim_usr, cfg.h_dim),
nn.ReLU(),
nn.Linear(cfg.h_dim, 1024),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(1024, 2048),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(2048, 3072),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(3072, 4096),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(4096, 5120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(5120, 5120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(5120, 6100),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(6100, 8120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(8120, 9120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(9120, 5120),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(5120, 3072),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(3072, 2048),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(2048, 2048),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(2048, 1000),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(1000, 500),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(500, 256),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(256, cfg.h_dim),
nn.ReLU(),
nn.Dropout(cfg.dp),
nn.Linear(cfg.h_dim, cfg.h_dim),
nn.ReLU(),
nn.Linear(cfg.h_dim, cfg.a_dim_usr))
else:
raise NotImplementedError('Unknown character {}'.format(character))
def forward(self, s):
# [b, s_dim] => [b, a_dim]
a_weights = self.net(s)
return a_weights
def select_action(self, s, sample=True):
"""
:param s: [s_dim]
:return: [a_dim]
"""
# forward to get action probs
# [s_dim] => [a_dim]
a_weights = self.forward(s)
a_probs = torch.sigmoid(a_weights)
# [a_dim] => [a_dim, 2]
a_probs = a_probs.unsqueeze(1)
a_probs = torch.cat([1-a_probs, a_probs], 1)
# [a_dim, 2] => [a_dim]
a = a_probs.multinomial(1).squeeze(1) if sample else a_probs.argmax(1)
return a
def batch_select_action(self, s, sample=False):
"""
:param s: [b, s_dim]
:return: [b, a_dim]
"""
# forward to get action probs
# [b, s_dim] => [b, a_dim]
a_weights = self.forward(s)
a_probs = torch.sigmoid(a_weights)
# [b, a_dim] => [b, a_dim, 2]
a_probs = a_probs.unsqueeze(2)
a_probs = torch.cat([1-a_probs, a_probs], 2)
# [b, a_dim, 2] => [b*a_dim, 2] => [b*a_dim, 1] => [b*a_dim] => [b, a_dim]
a = a_probs.reshape(-1, 2).multinomial(1).squeeze(1).reshape(a_weights.shape) if sample else a_probs.argmax(2)
return a
def get_log_prob(self, s, a):
"""
:param s: [b, s_dim]
:param a: [b, a_dim]
:return: [b, 1]
"""
# forward to get action probs
# [b, s_dim] => [b, a_dim]
a_weights = self.forward(s)
a_probs = torch.sigmoid(a_weights)
# [b, a_dim] => [b, a_dim, 2]
a_probs = a_probs.unsqueeze(-1)
a_probs = torch.cat([1-a_probs, a_probs], -1)
# [b, a_dim, 2] => [b, a_dim]
trg_a_probs = a_probs.gather(-1, a.unsqueeze(-1)).squeeze(-1)
log_prob = torch.log(trg_a_probs)
return log_prob.sum(-1, keepdim=True)
class Policy(object):
def __init__(self, env_cls, args, manager, cfg, process_num, character, pre=False, infer=False):
"""
:param env_cls: env class or function, not instance, as we need to create several instance in class.
:param args:
:param manager:
:param cfg:
:param process_num: process number
:param character: user or system
:param pre: set to pretrain mode
:param infer: set to test mode
"""
self.process_num = process_num
self.character = character
# initialize envs for each process
self.env_list = []
for _ in range(process_num):
self.env_list.append(env_cls())
# construct policy and value network
self.policy = MultiDiscretePolicy(cfg, character).to(device=DEVICE)
if pre:
self.print_per_batch = args.print_per_batch
from dbquery import DBQuery
db = DBQuery(args.data_dir, cfg)
self.data_train = manager.create_dataset_policy('train', args.batchsz, cfg, db, character)
self.data_valid = manager.create_dataset_policy('valid', args.batchsz, cfg, db, character)
self.data_test = manager.create_dataset_policy('test', args.batchsz, cfg, db, character)
if character == 'sys':
pos_weight = args.policy_weight_sys * torch.ones([cfg.a_dim]).to(device=DEVICE)
elif character == 'usr':
pos_weight = args.policy_weight_usr * torch.ones([cfg.a_dim_usr]).to(device=DEVICE)
else:
raise Exception('Unknown character')
self.multi_entropy_loss = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
else:
self.evaluator = MultiWozEvaluator(args.data_dir)
self.save_dir = args.save_dir + '/' + character if pre else args.save_dir
self.save_per_epoch = args.save_per_epoch
self.optim_batchsz = args.batchsz
self.policy.eval()
self.gamma = args.gamma
self.policy_optim = optim.RMSprop(self.policy.parameters(), lr=args.lr_policy, weight_decay=args.weight_decay)
self.writer = SummaryWriter()
def policy_loop(self, data):
s, target_a = to_device(data)
a_weights = self.policy(s)
loss_a = self.multi_entropy_loss(a_weights, target_a)
return loss_a
def imitating(self, epoch):
"""
pretrain the policy by simple imitation learning (behavioral cloning)
"""
self.policy.train()
a_loss = 0.
for i, data in enumerate(self.data_train):
self.policy_optim.zero_grad()
loss_a = self.policy_loop(data)
a_loss += loss_a.item()
loss_a.backward()
self.policy_optim.step()
if (i+1) % self.print_per_batch == 0:
a_loss /= self.print_per_batch
logging.debug('<<dialog policy {}>> epoch {}, iter {}, loss_a:{}'.format(self.character, epoch, i, a_loss))
a_loss = 0.
if (epoch+1) % self.save_per_epoch == 0:
self.save(self.save_dir, epoch)
self.policy.eval()
def imit_test(self, epoch, best):
"""
provide an unbiased evaluation of the policy fit on the training dataset
"""
a_loss = 0.
for i, data in enumerate(self.data_valid):
loss_a = self.policy_loop(data)
a_loss += loss_a.item()
a_loss /= len(self.data_valid)
logging.debug('<<dialog policy {}>> validation, epoch {}, loss_a:{}'.format(self.character, epoch, a_loss))
if a_loss < best:
logging.info('<<dialog policy {}>> best model saved'.format(self.character))
best = a_loss
self.save(self.save_dir, 'best')
a_loss = 0.
for i, data in enumerate(self.data_test):
loss_a = self.policy_loop(data)
a_loss += loss_a.item()
a_loss /= len(self.data_test)
logging.debug('<<dialog policy {}>> test, epoch {}, loss_a:{}'.format(self.character, epoch, a_loss))
self.writer.add_scalar('pretrain/dialogue_policy_{}/test'.format(self.character), a_loss, epoch)
return best
def save(self, directory, epoch):
if not os.path.exists(directory):
os.makedirs(directory)
torch.save(self.policy.state_dict(), directory + '/' + str(epoch) + '_pol.mdl')
logging.info('<<dialog policy {}>> epoch {}: saved network to mdl'.format(self.character, epoch))
def load(self, filename):
policy_mdl = filename + '_pol.mdl'
if os.path.exists(policy_mdl):
self.policy.load_state_dict(torch.load(policy_mdl))
logging.info('<<dialog policy {}>> loaded checkpoint from file: {}'.format(self.character, policy_mdl))
class DSTCPolicy(object):
def __init__(self, env_cls, args, manager, cfg, process_num, character, pre=False, infer=False):
"""
:param env_cls: env class or function, not instance, as we need to create several instance in class.
:param args:
:param manager:
:param cfg:
:param process_num: process number
:param character: user or system
:param pre: set to pretrain mode
:param infer: set to test mode
"""
self.process_num = process_num
self.character = character
# initialize envs for each process
self.env_list = []
for _ in range(process_num):
self.env_list.append(env_cls())
# construct policy and value network
self.policy = MultiDiscretePolicy(cfg, character).to(device=DEVICE)
if pre:
self.print_per_batch = args.print_per_batch
self.data_train = manager.create_dataset_policy('train', args.batchsz, cfg, character)
self.data_valid = manager.create_dataset_policy('valid', args.batchsz, cfg, character)
self.data_test = manager.create_dataset_policy('test', args.batchsz, cfg, character)
if character == 'sys':
pos_weight = args.policy_weight_sys * torch.ones([cfg.a_dim]).to(device=DEVICE)
elif character == 'usr':
pos_weight = args.policy_weight_usr * torch.ones([cfg.a_dim_usr]).to(device=DEVICE)
else:
raise Exception('Unknown character')
self.multi_entropy_loss = nn.BCEWithLogitsLoss(pos_weight=pos_weight)
else:
self.evaluator = DSTCSGDSEvaluator(args.data_dir)
self.save_dir = args.save_dir + '/' + character if pre else args.save_dir
self.save_per_epoch = args.save_per_epoch
self.optim_batchsz = args.batchsz
self.policy.eval()
self.gamma = args.gamma
self.policy_optim = optim.RMSprop(self.policy.parameters(), lr=args.lr_policy, weight_decay=args.weight_decay)
self.writer = SummaryWriter()
def policy_loop(self, data):
s, target_a = to_device(data)
a_weights = self.policy(s)
loss_a = self.multi_entropy_loss(a_weights, target_a)
return loss_a
def imitating(self, epoch):
"""
pretrain the policy by simple imitation learning (behavioral cloning)
"""
self.policy.train()
a_loss = 0.
for i, data in enumerate(self.data_train):
self.policy_optim.zero_grad()
loss_a = self.policy_loop(data)
a_loss += loss_a.item()
loss_a.backward()
self.policy_optim.step()
if (i+1) % self.print_per_batch == 0:
a_loss /= self.print_per_batch
logging.debug('<<dialog policy {}>> epoch {}, iter {}/{}, loss_a:{}'.format(self.character, epoch, i, len(self.data_train), a_loss))
a_loss = 0.
if (epoch+1) % self.save_per_epoch == 0:
print('saving model at epoch: ' + str(epoch) + '.')
self.save(self.save_dir, epoch)
self.policy.eval()
def imit_test(self, epoch, best):
"""
provide an unbiased evaluation of the policy fit on the training dataset
"""
a_loss = 0.
for i, data in enumerate(self.data_valid):
loss_a = self.policy_loop(data)
a_loss += loss_a.item()
a_loss /= len(self.data_valid)
logging.debug('<<dialog policy {}>> validation, epoch {}, loss_a:{}'.format(self.character, epoch, a_loss))
if a_loss < best:
logging.info('<<dialog policy {}>> best model saved'.format(self.character))
best = a_loss
self.save(self.save_dir, 'best')
a_loss = 0.
for i, data in enumerate(self.data_test):
loss_a = self.policy_loop(data)
a_loss += loss_a.item()
a_loss /= len(self.data_test)
logging.debug('<<dialog policy {}>> test, epoch {}, loss_a:{}'.format(self.character, epoch, a_loss))
self.writer.add_scalar('pretrain/dialogue_policy_{}/test'.format(self.character), a_loss, epoch)
return best
def save(self, directory, epoch):
if not os.path.exists(directory):
os.makedirs(directory)
torch.save(self.policy.state_dict(), directory + '/' + str(epoch) + '_pol.mdl')
logging.info('<<dialog policy {}>> epoch {}: saved network to mdl'.format(self.character, epoch))
def load(self, filename):
policy_mdl = filename + '_pol.mdl'
if os.path.exists(policy_mdl):
self.policy.load_state_dict(torch.load(policy_mdl))
logging.info('<<dialog policy {}>> loaded checkpoint from file: {}'.format(self.character, policy_mdl))