This repository has been archived by the owner on Aug 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathagent.py
2338 lines (1860 loc) · 92.2 KB
/
agent.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import sys
from collections import defaultdict
import numpy as np
import torch
from torch import optim, autograd
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import utils
from dialog import DialogLogger
import vis
import domain
from engines import Criterion
import math
from collections import Counter
class Agent(object):
""" Agent's interface. """
def feed_context(self, ctx):
pass
def read(self, inpt):
pass
def write(self):
pass
def choose(self):
pass
def update(self, agree, reward, partner_choice):
pass
class RnnAgent(Agent):
def __init__(self, model, args, name='Alice', allow_no_agreement=True, train=False, diverse=False):
super(RnnAgent, self).__init__()
self.model = model
self.model.eval()
self.args = args
self.name = name
self.human = False
self.domain = domain.get_domain(args.domain)
self.allow_no_agreement = allow_no_agreement
self.sel_model = utils.load_model(args.selection_model_file)
self.sel_model.eval()
def _encode(self, inpt, dictionary):
encoded = torch.Tensor(dictionary.w2i(inpt)).long().unsqueeze(1)
return encoded
def _decode(self, out, dictionary):
return dictionary.i2w(out.data.squeeze(1).cpu())
def feed_context(self, context):
self.lang_hs = []
self.sents = []
self.words = []
self.context = context
self.ctx = self._encode(context, self.model.context_dict)
self.ctx_h = self.model.forward_context(Variable(self.ctx))
self.lang_h = self.model.zero_h(1, self.model.args.nhid_lang)
def feed_partner_context(self, partner_context):
pass
def update(self, agree, reward, choice=None, partner_choice=None,
partner_input=None, max_partner_reward=None):
pass
def read(self, inpt):
self.sents.append(Variable(self._encode(['THEM:'] + inpt, self.model.word_dict)))
inpt = self._encode(inpt, self.model.word_dict)
lang_hs, self.lang_h = self.model.read(Variable(inpt), self.lang_h, self.ctx_h)
self.lang_hs.append(lang_hs.squeeze(1))
self.words.append(self.model.word2var('THEM:').unsqueeze(0))
self.words.append(Variable(inpt))
assert (torch.cat(self.words).size(0) == torch.cat(self.lang_hs).size(0))
def write(self, max_words=100):
acts, outs, self.lang_h, lang_hs = self.model.write(self.lang_h, self.ctx_h,
max_words, self.args.temperature)
self.lang_hs.append(lang_hs)
self.words.append(self.model.word2var('YOU:').unsqueeze(0))
self.words.append(outs)
self.sents.append(torch.cat([self.model.word2var('YOU:').unsqueeze(1), outs], 0))
assert (torch.cat(self.words).size(0) == torch.cat(self.lang_hs).size(0))
return self._decode(outs, self.model.word_dict)
def _make_idxs(self, sents):
lens, rev_idxs, hid_idxs = [], [], []
for sent in sents:
assert sent.size(1) == 1
# remove last hidden state
ln = torch.Tensor(1).fill_(sent.size(0) - 1).long()
lens.append(ln)
idx = torch.Tensor(sent.size(0), 1, 1).fill_(-1).long()
for j in range(idx.size(0)):
idx[j][0][0] = j if j >= sent.size(0) else sent.size(0) - j - 1
rev_idxs.append(Variable(idx))
hid_idxs.append(Variable(ln.view(1, 1, 1)))
return lens, rev_idxs, hid_idxs
def _choose(self, sample=False):
sents = self.sents[:-1]
lens, rev_idxs, hid_idxs = self._make_idxs(sents)
sel_out = self.sel_model.forward(sents, lens, rev_idxs, hid_idxs, Variable(self.ctx))
choices = self.domain.generate_choices(self.context, with_disagreement=True)
choices_logits = []
for i in range(self.domain.selection_length()):
idxs = [self.sel_model.item_dict.get_idx(c[i]) for c in choices]
idxs = Variable(torch.Tensor(idxs).long())
choices_logits.append(torch.gather(sel_out[i], 0, idxs).unsqueeze(1))
choice_logit = torch.sum(torch.cat(choices_logits, 1), 1, keepdim=True).squeeze(1)
choice_logit = choice_logit.sub(choice_logit.max(0)[0].item())
prob = F.softmax(choice_logit, dim=0)
if sample:
idx = prob.multinomial(1).detach()
logprob = F.log_softmax(choice_logit, dim=0).gather(0, idx)
else:
_, idx = prob.max(0, keepdim=True)
logprob = None
p_agree = prob[idx.item()]
# Pick only your choice
return choices[idx.item()][:self.domain.selection_length()], logprob, p_agree.item()
def choose(self):
choice, _, _ = self._choose()
return choice
class HierarchicalAgent(RnnAgent):
def __init__(self, model, args, name='Alice'):
super(HierarchicalAgent, self).__init__(model, args, name)
self.vis = False
def feed_context(self, context):
self.lang_hs = []
self.sents = []
self.context = context
self.ctx = self._encode(context, dictionary=self.model.context_dict)
self.ctx_h = self.model.forward_context(Variable(self.ctx)).squeeze(0)
self.strat_h = self.model.zero_h(1, self.model.args.nhid_strat).squeeze(0)
self.lang_h = self.model.zero_h(1, self.model.args.nhid_lang).squeeze(0)
self.lang_attn = self.model.zero_h(1, self.model.args.nhid_lang).squeeze(0)
def read(self, inpt):
inpt = ['THEM:'] + inpt
inpt = Variable(self._encode(inpt, self.model.word_dict))
self.sents.append(inpt)
self.strat_h, self.lang_h, lang_hs, self.lang_attn, attn_p = self.model.read(
inpt, self.strat_h, self.lang_h, self.ctx_h, self.lang_attn)
self.lang_hs.append(lang_hs)
if self.vis:
vis.plot_attn(self._decode(inpt, self.model.word_dict), attn_p)
def write(self):
_, outs, self.strat_h, self.lang_h, lang_hs, self.lang_attn, attn_p = self.model.write(
self.strat_h, self.lang_h, self.ctx_h, self.lang_attn, 100, self.args.temperature)
self.lang_hs.append(lang_hs)
self.sents.append(outs)
# remove 'YOU:'
if self.vis:
vis.plot_attn(self._decode(outs, self.model.word_dict), attn_p)
outs = outs.narrow(0, 1, outs.size(0) - 1)
return self._decode(outs, self.model.word_dict)
def _make_idxs(self):
lens, hid_idxs, rev_idxs = [], [], []
for sent in self.sents:
assert sent.size(1) == 1
ln = torch.Tensor(1).fill_(sent.size(0) - 1).long()
lens.append(ln)
hid_idxs.append(Variable(ln.view(1, 1, 1)))
idx = torch.Tensor(sent.size(0), 1, 1).fill_(-1).long()
for j in range(idx.size(0)):
idx[j][0][0] = sent.size(0) - j - 1
rev_idxs.append(Variable(idx))
return lens, hid_idxs, rev_idxs
def _make_choice_logits(self):
if len(self.sents) == 0:
return Variable(torch.Tensor(1, self.model.output_length * len(self.model.item_dict)).fill_(0))
inpt_embs = self.model.forward_embedding(self.sents)
lens, hid_idxs, rev_idxs = self._make_idxs()
logits, attn_p = self.model.forward_selection(
inpt_embs, self.lang_hs, lens,
self.strat_h.unsqueeze(1), self.ctx_h.unsqueeze(1),
rev_idxs, hid_idxs)
if self.vis:
sent_p, word_ps = attn_p
for sent, word_p in zip(self.sents, word_ps):
vis.plot_attn(self._decode(sent, self.model.word_dict), word_p)
vis.plot_attn(['%d' % i for i in range(len(word_ps))], sent_p)
return logits
def _choose(self, sample=False, logits=None):
if not logits:
logits = self._make_choice_logits()
logits = logits.view(self.domain.selection_length(), -1)
choices = self.domain.generate_choices(self.context)
choices_logits = []
for i in range(self.domain.selection_length()):
idxs = [self.model.item_dict.get_idx(c[i]) for c in choices]
idxs = Variable(torch.Tensor(idxs).long())
choices_logits.append(torch.gather(logits[i].squeeze(0), 0, idxs).unsqueeze(1))
choice_logit = torch.sum(torch.cat(choices_logits, 1), 1).squeeze(1)
choice_logit = choice_logit.sub(choice_logit.max(1, keepdim=True).data[0])
prob = F.softmax(choice_logit)
if sample:
idx = prob.multinomial().detach()
logprob = F.log_softmax(choice_logit).gather(0, idx)
else:
_, idx = prob.max(0, keepdim=True)
logprob = None
p_agree = prob[idx.data[0]].data[0]
# Pick only your choice
return choices[idx.data[0]][:self.domain.selection_length()], logprob, p_agree
class RnnRolloutAgent(RnnAgent):
def __init__(self, model, args, name='Alice', train=False):
super(RnnRolloutAgent, self).__init__(model, args, name)
self.ncandidate = 5
self.nrollout = 3
self.rollout_len = 100
def write(self, max_words):
best_score = -1
res = None
for _ in range(self.ncandidate):
_, move, move_lang_h, move_lang_hs = self.model.write(
self.lang_h, self.ctx_h, 100, self.args.temperature)
is_selection = len(move) == 1 and \
self.model.word_dict.get_word(move.data[0][0]) == '<selection>'
score = 0
for _ in range(self.nrollout):
combined_lang_hs = self.lang_hs + [move_lang_hs]
combined_words = self.words + [self.model.word2var('YOU:'), move]
if not is_selection:
# Complete the conversation with rollout_length samples
_, rollout, _, rollout_lang_hs = self.model.write(
move_lang_h, self.ctx_h, self.rollout_len, self.args.temperature,
stop_tokens=['<selection>'], resume=True)
combined_lang_hs += [rollout_lang_hs]
combined_words += [rollout]
# Choose items
rollout_score = None
combined_lang_hs = torch.cat(combined_lang_hs)
combined_words = torch.cat(combined_words)
rollout_choice, _, p_agree = self._choose(combined_lang_hs, combined_words, sample=False)
rollout_score = self.domain.score(self.context, rollout_choice)
score += p_agree * rollout_score
# Take the candidate with the max expected reward
if score > best_score:
res = (move, move_lang_h, move_lang_hs)
best_score = score
outs, lang_h, lang_hs = res
self.lang_h = lang_h
self.lang_hs.append(lang_hs)
self.words.append(self.model.word2var('YOU:'))
self.words.append(outs)
return self._decode(outs, self.model.word_dict)
class StrategyAgent(HierarchicalAgent):
def __init__(self, model, args, name='Alice', train=False, diverse=False):
super(StrategyAgent, self).__init__(model, args, name)
self.sel_model = utils.load_model(args.selection_model_file)
self.sel_model.eval()
def feed_context(self, context):
self.lang_hs = []
self.sents = []
self.sents2 = []
self.context = context
self.ctx = self._encode(context, dictionary=self.model.context_dict)
self.ctx_h = self.model.forward_context(Variable(self.ctx))
self.sent_attn_h = self.model.zero_h(1, 2 * self.model.args.nhid_attn)
self.lang_h = self.model.zero_h(1, self.model.args.nhid_lang)
self.strat_h = self.model.zero_h(1, self.model.args.nhid_strat)
self.strat_hs = []
#self.sel_h = self.model.zero_h(1, self.model.selection_size)
#self.future_h, self.next_strat_h = self.model.future_strat(self.strat_h, self.model.future_strat.zero_h(1))
def feed_partner_context(self, partner_context):
self.partner_context = partner_context
self_partner_ctx = self._encode(partner_context, dictionary=self.model.context_dict)
def _make_idxs2(self, sents):
lens, rev_idxs, hid_idxs = [], [], []
for sent in sents:
assert sent.size(1) == 1
# remove last hidden state
ln = torch.Tensor(1).fill_(sent.size(0) - 1).long()
lens.append(ln)
idx = torch.Tensor(sent.size(0), 1, 1).fill_(-1).long()
for j in range(idx.size(0)):
idx[j][0][0] = j if j >= sent.size(0) else sent.size(0) - j - 1
rev_idxs.append(Variable(idx))
hid_idxs.append(Variable(ln.view(1, 1, 1)))
return lens, rev_idxs, hid_idxs
def _choose2(self, sample=False):
sents = self.sents2[:-1]
lens, rev_idxs, hid_idxs = self._make_idxs2(sents)
sel_out = self.sel_model.forward(sents, lens, rev_idxs, hid_idxs, Variable(self.ctx))
choices = self.domain.generate_choices(self.context, with_disagreement=True)
choices_logits = []
for i in range(self.domain.selection_length()):
idxs = [self.sel_model.item_dict.get_idx(c[i]) for c in choices]
idxs = Variable(torch.Tensor(idxs).long())
choices_logits.append(torch.gather(sel_out[i], 0, idxs).unsqueeze(1))
choice_logit = torch.sum(torch.cat(choices_logits, 1), 1, keepdim=True).squeeze(1)
choice_logit = choice_logit.sub(choice_logit.max(0)[0].data[0])
prob = F.softmax(choice_logit)
if sample:
idx = prob.multinomial().detach()
logprob = F.log_softmax(choice_logit).gather(0, idx)
else:
_, idx = prob.max(0, keepdim=True)
logprob = None
p_agree = prob[idx.data[0]]
# Pick only your choice
return choices[idx.data[0]][:self.domain.selection_length()], logprob, p_agree.data[0]
def choose(self):
choice, _, _ = self._choose2()
return choice
def update_attention(self):
# recompute lang_attn_h
if self.sents[-1][0].data[0] == self.model.word_dict.word2idx['<selection>']:
return
lens, rev_idxs, hid_idxs = self._make_idxs(self.sents, self.lang_hs)
(self.sent_attn_h, sent_attn_p), (word_attn_hs, word_attn_ps) = self.model.attn(
self.strat_h, self.lang_hs, lens, rev_idxs, hid_idxs)
if self.vis:
sents = [self._decode(sent, self.model.word_dict) for sent in self.sents]
#vis.plot_attn(sents, sent_attn_p, word_attn_ps)
#import pdb; pdb.set_trace()
def update_strategy(self):
# update current strategy
self.strat_h = self.model.strategy(self.strat_h, self.sent_attn_h, self.lang_h, self.ctx_h)
self.strat_hs.append(self.strat_h)
# update future strategy
#self.next_strat_h, self.future_h = self.model.future_strat(self.strat_h, self.future_h)
#self.plot_strategy()
#self.plot_partner_context()
#import pdb; pdb.set_trace()
def plot_strategy(self):
choices = self.domain.generate_choices(self.context)
def get_prob(logits, attn_p):
choices_logits = []
for i in range(self.domain.selection_length()):
idxs = [self.model.item_dict.get_idx(c[i]) for c in choices]
idxs = Variable(torch.Tensor(idxs).long())
choices_logits.append(torch.gather(logits[i].squeeze(0), 0, idxs).unsqueeze(1))
if vis:
p = F.softmax(logits)
labels = ['%s' % s for s in self.model.item_dict.idx2word]
#for i in range(3):
# vis.plot_distribution(p[i], labels, 'Item%d' % i)
choice_logit = torch.sum(torch.cat(choices_logits, 1), 1, keepdim=True).squeeze(1)
choice_logit = choice_logit.sub(choice_logit.max(0)[0].data[0])
return F.softmax(choice_logit), attn_p
actual_prob, attn_p = get_prob(*self.model.forward_selection(self.strat_hs, self.ctx_h))
next_actual_prob, next_attn_p = get_prob(*self.model.forward_selection(self.strat_hs + [self.next_strat_h], self.ctx_h))
#predicted_prob = get_prob(self.sel_h.view(self.domain.selection_length(), -1))
labels = []
for choice in choices:
if choice[0] == '<no_agreement>':
labels.append('no_agree')
elif choice[0] == '<disconnect>':
labels.append('discon')
else:
you = [str(self.domain.parse_choice(c)[1]) for c in choice[:3]]
them = [str(self.domain.parse_choice(c)[1]) for c in choice[3:]]
labels.append('(%s)' % (','.join(you)))
title = 'Your input %s' % (' '.join(['%s=(%s:%s)' % (DialogLogger.CODE2ITEM[i][1],
self.context[2 * i + 0], self.context[2 * i + 1]) \
for i in range(len(self.context) // 2)]))
if self.vis:
vis.plot_distribution(actual_prob, labels, 'Actual: ' + title)
vis.plot_distribution(next_actual_prob, labels, 'Next Actual: ' + title)
if attn_p.size(1) > 1:
labels = ['%d' % i for i in range(attn_p.size(1))]
#vis.plot_distribution(attn_p.squeeze(0), labels, 'Strategy Attention')
#vis.plot_distribution(predicted_prob, labels, 'Predicted: ' + title)
#score_out = F.softmax(self.model.forward_score(self.strat_hs, self.ctx_h))
#labels = ['_%d' % i for i in range(11)]
#vis.plot_distribution(score_out.squeeze(0), labels, 'Score')
def plot_partner_context(self):
logits = self.model.forward_partner_context(self.strat_hs)
prob = F.softmax(logits)
n = len(self.partner_context) // 2
title = 'Partner input: %s' % (' '.join(['%s=(%s:%s)' % (
DialogLogger.CODE2ITEM[i][1],
self.partner_context[2 * i + 0],
self.partner_context[2 * i + 1]) for i in range(n)]))
legend = [DialogLogger.CODE2ITEM[i][1] for i in range(n)]
rownames = self.model.context_dict.idx2word
prob = prob.transpose(0, 1).contiguous()
if self.vis:
vis.plot_context(prob, rownames, title, legend)
def read(self, inpt):
# update strategy
self.update_strategy()
if self.vis:
import pdb; pdb.set_trace()
self.sents.append(Variable(self._encode(inpt, self.model.word_dict)))
# prepend 'THEM:'
inpt = ['THEM:'] + inpt
inpt = Variable(self._encode(inpt, self.model.word_dict))
self.sents2.append(inpt)
# read up the sentence
lang_hs, self.lang_h = self.model.read(inpt, self.strat_h)
# store hidden states and the sentence
self.lang_hs.append(lang_hs)
# update attention
self.update_attention()
def write(self, max_words=100):
self.update_strategy()
if self.vis:
import pdb; pdb.set_trace()
# generate new sentence
_, outs, lang_hs, self.lang_h, topks = self.model.write(
self.strat_h, max_words, self.args.temperature)
if self.vis:
if outs.size(0) > 1:
starts = ['YOU:'] + self.model.word_dict.i2w(outs.narrow(0, 0, outs.size(0) - 1).data[:, 0])
for i in range(len(starts)):
start = starts[i]
prob, words = topks[i]
words = self.model.word_dict.i2w(words.data)
words = ['%s_' % w for w in words]
vis.plot_distribution(prob, words, start)
self.sents2.append(torch.cat([self.model.word2var('YOU:').unsqueeze(1), outs], 0))
self.sents.append(outs)
outs = self._decode(outs, self.model.word_dict)
#inpt = ['YOU:'] + outs
#inpt = Variable(self._encode(outs, self.model.word_dict))
#lang_hs, self.lang_h = self.model.read(inpt, self.strat_h)
self.lang_hs.append(lang_hs)
self.update_attention()
return outs
# store lang_hs and outs
self.lang_hs.append(lang_hs)
self.sents.append(outs)
self.update_attention()
# if self.vis:
# vis.plot_attn(self._decode(outs, self.model.word_dict), attn_p)
# decode to English
return self._decode(outs, self.model.word_dict)
def _make_idxs(self, sents, lang_hs):
lens, rev_idxs, hid_idxs = [], [], []
for sent, lang_hs in zip(sents, lang_hs):
assert sent.size(1) == 1
# remove last hidden state
ln = torch.Tensor(1).fill_(sent.size(0)).long()
lens.append(ln)
idx = torch.Tensor(lang_hs.size(0) , 1, 1).fill_(-1).long()
for j in range(idx.size(0)):
idx[j][0][0] = j if j >= sent.size(0) else sent.size(0) - j - 1
rev_idxs.append(Variable(idx))
hid_idxs.append(None)
return lens, rev_idxs, hid_idxs
def _choose(self, strat_hs, sample=False):
logits, _ = self.model.forward_selection(strat_hs, self.ctx_h)
logits = logits.view(self.domain.selection_length(), -1)
choices = self.domain.generate_choices(self.context)
choices_logits = []
for i in range(self.domain.selection_length()):
idxs = [self.model.item_dict.get_idx(c[i]) for c in choices]
idxs = Variable(torch.Tensor(idxs).long())
choices_logits.append(torch.gather(logits[i].squeeze(0), 0, idxs).unsqueeze(1))
choice_logit = torch.sum(torch.cat(choices_logits, 1), 1, keepdim=True).squeeze(1)
choice_logit = choice_logit.sub(choice_logit.max(0)[0].data[0])
prob = F.softmax(choice_logit)
if sample:
idx = prob.multinomial().detach()
logprob = F.log_softmax(choice_logit).gather(0, idx)
else:
_, idx = prob.max(0, keepdim=True)
logprob = None
p_agree = prob[idx.data[0]].data[0]
# Pick only your choice
return choices[idx.data[0]][:self.domain.selection_length()], logprob, p_agree
class StrategyRolloutAgent(StrategyAgent):
def __init__(self, models, args, name='Alice'):
model, forward_model = models
super(StrategyRolloutAgent, self).__init__(model, args, name)
self.ncandidate = 10
self.nrollout = 10
self.rollout_len = 5
self.forward_model = forward_model
self.forward_model.eval()
def feed_context(self, context):
super(StrategyRolloutAgent, self).feed_context(context)
self.forward_h = self.forward_model.zero_h(1, self.forward_model.hidden_size).squeeze(0)
def update_strategy(self):
super(StrategyRolloutAgent, self).update_strategy()
forward_inpt = torch.cat([self.strat_h, self.ctx_h], 1)
self.forward_h = self.forward_model.step(forward_inpt, self.forward_h)
def write(self):
self.update_strategy()
best_score = -1
res = None
for _ in range(self.ncandidate):
_, move, move_lang_hs, move_lang_h = self.model.write(
self.strat_h, 100, self.args.temperature)
is_selection = len(move) == 1 and \
self.model.word_dict.get_word(move.data[0][0]) == '<selection>'
all_lang_hs = self.lang_hs + [move_lang_hs]
all_sents = self.sents + [move]
lens, rev_idxs, hid_idxs = self._make_idxs(all_sents, all_lang_hs)
(attn_h, _), _ = self.model.attn(self.strat_h, all_lang_hs, lens, rev_idxs, hid_idxs)
move_strat_h = self.model.strategy(self.strat_h, attn_h, move_lang_h, self.ctx_h)
forward_h = self.forward_h.expand(self.nrollout, self.forward_h.size(1))
strat_h = move_strat_h.expand(self.nrollout, self.move_strat_h.size(1))
ctx_h = self.ctx_h.expand(self.nrollout, self.ctx_h.size(1))
for i in range(self.rollout_len):
forward_inpt = torch.cat([strat_h, ctx_h], 1)
forward_h = self.forward_model.step(forward_inpt, forward_h)
strat_h = forward_h
total_score = 0
for _ in range(self.nrollout):
forward_h = self.forward_h
strat_h = move_strat_h
gamma = 1
for i in range(self.rollout_len):
forward_inpt = torch.cat([strat_h, self.ctx_h], 1)
forward_h = self.forward_model.step(forward_inpt, forward_h)
strat_h = forward_h
choice, _, agree_prob = self._choose([strat_h])
score = self.domain.score(self.context, choice)
total_score += gamma * agree_prob * score
gamma *= 0.99
if total_score > best_score:
best_score = total_score
res = (move, move_lang_hs, move_lang_h)
out, lang_hs, self.lang_h = res
self.lang_hs.append(lang_hs)
self.sents.append(out)
self.update_attention()
return self._decode(out, self.model.word_dict)
class RnnRolloutAgent2(RnnAgent):
def __init__(self, model, args, name='Alice', force_unique_candidates=False, sample_selection=False,
allow_no_agreement=True, train=False):
super(RnnRolloutAgent, self).__init__(model, args, name, allow_no_agreement=allow_no_agreement)
self.ncandidate = 10 #args.rollout_candidates
self.nrollout = 16 #args.rollout_bsz
self.rollout_len = 100
self.max_attempts = 100
self.force_unique_candidates = force_unique_candidates
self.sample_selection = sample_selection
def update(self, agree, reward, choice=None, partner_choice=None, partner_input=None):
pass
def write(self, max_words):
best_score = -9999
res = None
i = 0
uniq = set()
while i < self.ncandidate or (best_score < -99990 and i < 100):
i += 1
move_string = None
attempts = 0
while attempts < self.max_attempts and (not move_string or move_string in uniq or not self.force_unique_candidates):
_, move, move_lang_h, move_lang_hs = self.model.write(
self.lang_h, self.ctx_h, min(max_words, 100), self.args.temperature, first_turn = len(self.words) == 0
)
move_string = ' '.join(self._decode(move, self.model.word_dict))
attempts += 1
if attempts == self.max_attempts:
break
uniq.add(move_string)
is_selection = len(move) == 1 and \
self.model.word_dict.get_word(move.data[0][0]) == '<selection>'
score = 0
for _ in range(self.nrollout):
combined_lang_hs = self.lang_hs + [move_lang_hs]
combined_words = self.words + [self.model.word2var('YOU:'), move]
if not is_selection and max_words - len(move) > 1:
# Complete the conversation with rollout_length samples
_, rollout, _, rollout_lang_hs = self.model.write(
move_lang_h, self.ctx_h, max_words - len(move), self.args.temperature,
stop_tokens=['<selection>'], resume=True)
combined_lang_hs += [rollout_lang_hs]
combined_words += [rollout]
# Choose items
combined_lang_hs = torch.cat(combined_lang_hs)
combined_words = torch.cat(combined_words)
rollout_choice, _, p_agree = self._choose(combined_lang_hs, combined_words, sample=self.sample_selection)
rollout_score = self.domain.score(self.context, rollout_choice)
if not self.sample_selection:
rollout_score = rollout_score * p_agree
score += rollout_score
# Take the candidate with the max expected reward
if score > best_score:
res = (move, move_lang_h, move_lang_hs)
best_score = score
outs, lang_h, lang_hs = res
self.lang_h = lang_h
self.lang_hs.append(lang_hs)
self.words.append(self.model.word2var('YOU:'))
self.words.append(outs)
return self._decode(outs, self.model.word_dict)
class BatchedRolloutAgent(RnnRolloutAgent):
def __init__(self, model, args, name='Alice'):
super(BatchedRolloutAgent, self).__init__(model, args, name)
self.eos = self.model.word_dict.get_idx('<eos>')
self.eod = self.model.word_dict.get_idx('<selection>')
def _find(self, seq, tokens):
n = seq.size(0)
for i in range(n):
if seq[i] in tokens:
return i
return n
def write(self):
batch_outs, batch_lang_hs = self.model.write_batch(
self.args.rollout_bsz, self.lang_h, self.ctx_h, self.args.temperature)
counts, scores, states = defaultdict(float), defaultdict(int), defaultdict(list)
for i in range(self.args.rollout_bsz):
outs = batch_outs.narrow(1, i, 1).squeeze(1).data.cpu()
lang_hs = batch_lang_hs.narrow(1, i, 1).squeeze(1)
# Find the end of the dialogue
eod_pos = self._find(outs, [self.eod])
if eod_pos == outs.size(0):
# Unfinished dialogue, don't count this
continue
# Find end of the first utterance
first_turn_length = self._find(outs, [self.eos, self.eod]) + 1
move = outs.narrow(0, 0, first_turn_length)
sent = ' '.join(self.model.word_dict.i2w(move.numpy()))
sent_lang_hs = lang_hs.narrow(0, 0, first_turn_length + 1)
lang_h = lang_hs.narrow(0, first_turn_length + 1, 1).unsqueeze(0)
dialog_lang_hs = lang_hs.narrow(0, 0, eod_pos + 1)
dialog_words = Variable(outs.narrow(0, 0, eod_pos + 1).cuda())
choice, _, p_agree = self._choose(
torch.cat(self.lang_hs + [dialog_lang_hs]),
torch.cat(self.words + [dialog_words]).squeeze().unsqueeze(1), sample=False)
# Group by the first utterance
counts[sent] += 1
scores[sent] += self.domain.score(self.context, choice) * p_agree
states[sent] = (lang_h, sent_lang_hs, move)
for threshold in range(self.args.rollout_count_threshold, -1, -1):
cands = [k for k in counts if counts[k] >= threshold]
if cands:
sent = max(cands, key=lambda k: scores[k] / counts[k])
lang_h, sent_lang_hs, move = states[sent]
self.lang_h = lang_h
self.lang_hs.append(sent_lang_hs)
self.words.append(self.model.word2var('YOU:'))
self.words.append(Variable(move.cuda()))
assert (torch.cat(self.words).size()[0] == torch.cat(self.lang_hs).size()[0])
return sent.split(' ')
class RlAgent(RnnAgent):
def __init__(self, model, args, name='Alice', train=False):
self.train = train
super(RlAgent, self).__init__(model, args, name=name)
self.opt = optim.RMSprop(
self.model.parameters(),
lr=args.rl_lr,
momentum=self.args.momentum)
self.all_rewards = []
if self.args.visual:
self.model_plot = vis.ModulePlot(self.model, plot_weight=False, plot_grad=True)
self.agree_plot = vis.Plot(['agree',], 'agree', 'agree')
self.reward_plot = vis.Plot(
['reward', 'partner_reward'], 'reward', 'reward')
self.loss_plot = vis.Plot(['loss',], 'loss', 'loss')
self.agree_reward_plot = vis.Plot(
['reward', 'partner_reward'], 'agree_reward', 'agree_reward')
self.t = 0
def feed_context(self, ctx):
super(RlAgent, self).feed_context(ctx)
self.logprobs = []
def write(self, max_words):
logprobs, outs, self.lang_h, lang_hs = self.model.write(self.lang_h, self.ctx_h,
100, self.args.temperature)
self.logprobs.extend(logprobs)
self.lang_hs.append(lang_hs)
self.words.append(self.model.word2var('YOU:'))
self.words.append(outs)
assert (torch.cat(self.words).size()[0] == torch.cat(self.lang_hs).size()[0])
return self._decode(outs, self.model.word_dict)
def choose(self):
if self.args.eps < np.random.rand():
choice, _, _ = self._choose(sample=False)
else:
choice, logprob, _ = self._choose(sample=True)
self.logprobs.append(logprob)
return choice
def update(self, agree, reward, choice=None, partner_choice=None, partner_input=None, partner_reward=None):
if not self.train:
return
self.t += 1
if len(self.logprobs) == 0:
return
reward_agree = reward
partner_reward_agree = partner_reward
reward = reward if agree else 0
partner_reward = partner_reward if agree else 0
diff = reward - partner_reward
self.all_rewards.append(diff)
#self.all_rewards.append(reward)
r = (diff - np.mean(self.all_rewards)) / max(1e-4, np.std(self.all_rewards))
g = Variable(torch.zeros(1, 1).fill_(r))
rewards = []
for _ in self.logprobs:
rewards.insert(0, g)
g = g * self.args.gamma
loss = 0
for lp, r in zip(self.logprobs, rewards):
loss -= lp * r
self.opt.zero_grad()
loss.backward()
nn.utils.clip_grad_norm(self.model.parameters(), self.args.rl_clip)
if self.args.visual and self.t % 10 == 0:
self.model_plot.update(self.t)
self.agree_plot.update('agree', self.t, int(agree))
self.reward_plot.update('reward', self.t, reward)
self.reward_plot.update('partner_reward', self.t, partner_reward)
self.agree_reward_plot.update('reward', self.t, reward_agree)
self.agree_reward_plot.update('partner_reward', self.t, partner_reward_agree)
self.loss_plot.update('loss', self.t, loss.data[0][0])
self.opt.step()
class OnlineAgent(RnnRolloutAgent):
def __init__(self, model, args, name='Alice'):
super(OnlineAgent, self).__init__(model, args, name, force_unique_candidates=True, sample_selection=True,
allow_no_agreement=False)
self.eos = self.model.word_dict.get_idx('<eos>')
self.eod = self.model.word_dict.get_idx('<selection>')
self.t = 0
self.opt = optim.SGD(
self.model.parameters(),
lr=self.args.lr, #TODO
momentum=self.args.momentum,
nesterov=(self.args.nesterov and self.args.momentum > 0))
self.crit = Criterion(self.model.word_dict)
self.sel_crit = Criterion(
self.model.item_dict, bad_toks=['<disconnect>', '<disagree>'])
self.last_choice = None
self.sum_sel_out = None
self.loss = 0
self.lm_loss = 0
self.choice_to_dialogue = dict()
self.choices = set()
self.agrees = 0
self.reward = 0
self.agreed_deal_to_dialogue = dict()
self.no_agreements = 0
def update(self, agree, reward, choice=None, partner_choice=None, partner_input=None):
self.t += 1
if choice[0] == '<no_agreement>':
self.no_agreements += 1
agree = True #FIXME
assert(agree == (choice == partner_choice[3:] + partner_choice[:3]))
data = torch.cat(self.words)
words = self._decode(data, self.model.word_dict)
self.choices.add(str(choice))
if choice[0] != '<no_agreement>':
# Disagree - adjudicate compromise
# Compromise is the deal with the best minimum score, where each component agrees with at least one agent
best_choice = None
best_score = -99999
for c in self.domain.generate_choices(self.context):
match = True
for i in range(0, len(c)):
j = (3 + i) % 6
if c[i] != choice[i] and c[i] != partner_choice[j]:
match = False
break
if match:
score1 = self.domain.score(self.context, c)
score2 = self.domain.score(partner_input, c[3:] + c[:3])
score = min(score1, score2)
if score > best_score or (score == best_score and words[0] == 'YOU:'):
best_choice = c
best_score = score
choice = best_choice
partner_choice = best_choice[3:] + best_choice[:3]
words_inverse = [('THEM:' if x == 'YOU:' else 'YOU:' if x == 'THEM:' else x) for x in words]
if agree:
self.agrees += 1
self.reward += reward
if self.t % 100 == 0:
print ("Unique choices: ", len(self.choices))
print ("Agreements: ", self.agrees)
print ("No agreements: ", self.no_agreements)
print ("Reward: ", self.reward)
print ("Total uniq agreed: ", len(self.agreed_deal_to_dialogue))
self.choices = set()
self.reward = 0
self.agrees = 0
self.no_agreements = 0
def insert(map, key, value):
if not key in map:
map[key] = []
map[key].append(value)
if choice[:3] == partner_choice[3:] and choice[0] != '<no_agreement>':
insert(self.agreed_deal_to_dialogue, str(choice), (words, choice))
insert(self.agreed_deal_to_dialogue, str(partner_choice), (words_inverse, partner_choice))
if self.t % self.args.bsz == 0:
# Train selection classifier
# Take last N instances of each agreed deal
deal_element_count = Counter()
dialogue_to_deal = []
for deal in self.agreed_deal_to_dialogue:
deals_and_dialogues = self.agreed_deal_to_dialogue[deal]
for (words, tgt_deal) in deals_and_dialogues[-10:]:
for i in range(0, len(tgt_deal)):
deal_element_count[(i, tgt_deal[i])] += 1
dialogue_to_deal.append((words, tgt_deal))
loss = None
loss_unweighted = 0
num = 0
# Classify deals
for words, deal in dialogue_to_deal:
sel_outs = self.model.forward_selection(Variable(self._encode(words, self.model.word_dict), requires_grad=False), None, None)
for (i, deal_element) in enumerate(deal):
weight = 1 / deal_element_count[(i, deal_element)]
sel_out = sel_outs[i]
sel_tgt = Variable(torch.Tensor(self.model.item_dict.w2i([deal_element])).contiguous().view(-1).long(), volatile=False)
example_loss = self.sel_crit(sel_out.unsqueeze(0), sel_tgt)
#print (sel_out)
#print (sel_tgt)
#print (example_loss)
num += 1
loss_unweighted += example_loss
#print ("loss", loss, "ex", example_loss, "weight", weight)
loss = loss + example_loss * weight if loss is not None else example_loss * weight