-
Notifications
You must be signed in to change notification settings - Fork 21
/
model.py
1820 lines (1517 loc) · 70.8 KB
/
model.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
import os
import sys
import json
import time
import numpy as np
import random
import h5py
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable as _Variable
import torch.optim as optim
from torch.nn.parameter import Parameter
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from sklearn.metrics import confusion_matrix
from misc import recursively_set_device, torch_save, torch_load
from misc import VisdomLogger as Logger
from misc import FileLogger
from misc import read_log_load
from misc import load_hdf5
from misc import read_data
from misc import embed
from misc import cbow
from misc import xavier_normal
from misc import build_mask
from sparks import sparks
from binary_vectors import extract_binary
import gflags
FLAGS = gflags.FLAGS
def Variable(*args, **kwargs):
var = _Variable(*args, **kwargs)
if FLAGS.cuda:
var = var.cuda()
return var
class Sender(nn.Module):
"""Agent 1 Network: Sender
"""
def __init__(self, feature_type, feat_dim, h_dim, w_dim, bin_dim_out, use_binary,
use_attn, attn_dim, attn_extra_context, attn_context_dim):
super(Sender, self).__init__()
self.feature_type = feature_type
self.feat_dim = feat_dim
self.h_dim = h_dim
self.w_dim = w_dim
self.bin_dim_out = bin_dim_out
self.use_binary = use_binary
self.use_attn = use_attn
self.attn_dim = attn_dim
self.attn_extra_context = attn_extra_context
self.attn_context_dim = attn_context_dim
self.image_layer = nn.Linear(self.feat_dim, self.h_dim)
self.code_layer = nn.Linear(self.w_dim, self.h_dim)
self.code_bias = Parameter(torch.Tensor(self.bin_dim_out))
# Layer for binary vector
if FLAGS.sender_mix == "mou":
self.binary_layer = nn.Linear(self.h_dim * 4, self.bin_dim_out)
if FLAGS.ignore_code:
self.code_bias_mou = Parameter(torch.Tensor(self.bin_dim_out))
else:
self.binary_layer = nn.Linear(self.h_dim, self.bin_dim_out)
# self.binary_layer.bias.data.fill_(-2.)
if self.use_attn:
self.attn_W_x = nn.Linear(self.feat_dim, self.attn_dim)
self.attn_W_w = nn.Linear(self.w_dim, self.attn_dim)
self.attn_U = nn.Linear(self.attn_dim, 1)
if FLAGS.attn_extra_context:
self.attn_W_g = nn.Linear(self.attn_context_dim, self.attn_dim)
self.reset_parameters()
def reset_parameters(self):
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data.set_(xavier_normal(m.weight.data))
if m.bias is not None:
m.bias.data.zero_()
if hasattr(self, 'code_bias'):
self.code_bias.data.normal_()
def reset_state(self):
"""Initialize state for Sender.
The Sender is stateless in its decisions, but some computation
can be reused at each time step.
"""
# Cached computation.
self.h_x_attn_flat = None
self.h_g_flat = None
self.fn_x = None
# Used for debugging.
self.attn_scores = []
def attention_func(self, w, x, g):
batch_size, n_feats, channels = x.size()
h_w_attn = self.attn_W_w(w)
h_w_attn_broadcast = h_w_attn.contiguous().unsqueeze(
1).expand(batch_size, n_feats, self.attn_dim)
h_w_attn_flat = h_w_attn_broadcast.contiguous().view(
batch_size * n_feats, self.attn_dim)
if not self.h_x_attn_flat:
x_flat = x.contiguous().view(batch_size * n_feats, channels)
self.h_x_attn_flat = self.attn_W_x(x_flat)
if self.attn_extra_context:
if not self.h_g_flat:
h_g = self.attn_W_g(g)
hg_broadcast = h_g.contiguous().unsqueeze(
1).expand(batch_size, n_feats, self.attn_dim)
self.h_g_flat = hg_broadcast.contiguous().view(
batch_size * n_feats, self.attn_dim)
if self.attn_extra_context:
attn_U_inp = nn.Tanh()(h_w_attn_flat + self.h_x_attn_flat + self.h_g_flat)
else:
attn_U_inp = nn.Tanh()(h_w_attn_flat + self.h_x_attn_flat)
attn_scores_flat = self.attn_U(attn_U_inp)
return attn_scores_flat
def forward(self, x, w, g, t):
"""Respond to communication query.
Communication Response:
z_hat = U_z(U_x x + U_w w)
z = bernoulli(sig(z_hat)) or round(sig(z_hat))
Image Attention (https://arxiv.org/pdf/1502.03044.pdf):
\beta_i = U tanh(W_r z_r + W_x x_i [+ W_g g])
\alpha = 1 / |x| if t == 0
\alpha = softmax(\beta) otherwise
x = \sum_i \alpha x_i
Args:
x: Image features.
w: Communication query from Receiver.
g: (attention) Image features used as query in attention.
t: (attention) Timestep. Used to change attention equation in first iteration.
Output:
features: A binary (or continuous) message in response to Receiver's query.
feature_probs: If the message is binary, then these are probability of ``1`` for each bit
in the message.
"""
if self.use_attn:
batch_size, channels, height, width = x.size()
n_feats = height * width
x = x.view(batch_size, channels, n_feats)
x = x.transpose(1, 2)
attn_scores_flat = self.attention_func(w, x, g)
# attention scores
if t == 0:
attn_scores = Variable(torch.FloatTensor(
batch_size, n_feats).fill_(1), volatile=not self.training)
attn_scores = attn_scores / n_feats
else:
attn_scores = F.softmax(
attn_scores_flat.view(batch_size, n_feats))
# x = \sum_i a_i x_i
x_attn = torch.bmm(attn_scores.unsqueeze(1), x).squeeze()
# Cache values for inspection
self.attn_scores.append(attn_scores)
_x = x_attn
else:
_x = x
self.h_x = h_x = self.image_layer(_x)
if t == 0:
batch_size = x.size(0)
# Same first code for all batch items.
first_code = F.sigmoid(self.code_bias.view(1, -1))
h_w = self.code_layer(first_code).expand(batch_size, self.h_dim)
elif t > 0 and FLAGS.ignore_code and FLAGS.sender_mix == "mou":
batch_size = x.size(0)
# Same code for all batch items.
code_mou = F.sigmoid(self.code_bias_mou.view(1, -1))
h_w = self.code_layer(code_mou).expand(batch_size, self.h_dim)
else:
h_w = self.code_layer(w)
if FLAGS.ignore_code:
if FLAGS.sender_mix == "sum" or FLAGS.sender_mix == "prod":
features = self.binary_layer(F.tanh(h_x))
elif FLAGS.sender_mix == "mou":
features = self.binary_layer(
F.tanh(torch.cat([h_x, h_w, h_x - h_w, h_x * h_w], 1)))
else:
if FLAGS.sender_mix == "sum":
features = self.binary_layer(F.tanh(h_x + h_w))
elif FLAGS.sender_mix == "prod":
features = self.binary_layer(F.tanh(h_x * h_w))
elif FLAGS.sender_mix == "mou":
features = self.binary_layer(
F.tanh(torch.cat([h_x, h_w, h_x - h_w, h_x * h_w], 1)))
if self.use_binary:
probs = F.sigmoid(features)
if self.training:
probs_ = probs.data.cpu().numpy()
binary_features = Variable(torch.from_numpy(
(np.random.rand(*probs_.shape) < probs_).astype('float32')))
else:
binary_features = torch.round(probs).detach()
if probs.is_cuda:
binary_features = binary_features.cuda()
if FLAGS.flipout_sen is not None and (self.training or FLAGS.flipout_dev):
binary_features = flipout(binary_features, FLAGS.flipout_sen)
return binary_features, probs
else:
return features, None
class Receiver(nn.Module):
"""Agent 2 Network: Receiver
"""
def __init__(self, z_dim, desc_dim, hid_dim, out_dim, w_dim, s_dim, use_binary):
super(Receiver, self).__init__()
self.z_dim = z_dim
self.desc_dim = desc_dim
self.hid_dim = hid_dim
self.out_dim = out_dim
self.w_dim = w_dim
self.s_dim = s_dim
self.use_binary = use_binary
# RNN network
self.rnn = nn.GRUCell(self.z_dim, self.hid_dim)
# Network for Receiver communications
self.w_h = nn.Linear(self.hid_dim, self.hid_dim, bias=True)
self.w_d = nn.Linear(self.desc_dim, self.hid_dim, bias=False)
self.w = nn.Linear(self.hid_dim, self.w_dim)
# Network for Receiver predicitons
self.y1 = nn.Linear(self.hid_dim + self.desc_dim, self.hid_dim)
self.y2 = nn.Linear(self.hid_dim, self.out_dim)
# Network for Receiver decisions
self.s = nn.Linear(self.hid_dim, self.s_dim)
if FLAGS.desc_attn:
self.attn_dim = FLAGS.desc_attn_dim
self.d_d = nn.Linear(self.desc_dim, self.attn_dim)
self.d_h = nn.Linear(self.hid_dim, self.attn_dim)
self.d_attn = nn.Linear(self.attn_dim, 1)
self.reset_parameters()
def reset_parameters(self):
for m in self.modules():
if isinstance(m, nn.Linear):
m.weight.data.set_(xavier_normal(m.weight.data))
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.GRUCell):
for mm in m.parameters():
if mm.data.ndimension() == 2:
mm.data.set_(xavier_normal(mm.data))
elif mm.data.ndimension() == 1: # Bias
mm.data.zero_()
if hasattr(self, 'code_bias'):
self.code_bias.data.uniform_(-1, 1)
def reset_state(self):
"""Initialize state for Receiver.
The Receiver is stateful, keeping tracking of previous messages it
has sent and received.
"""
self.h_z = None
self.s_prob_prod = None
def initial_state(self, batch_size):
return Variable(torch.zeros(batch_size, self.hid_dim))
def forward(self, z, desc, desc_set=None, desc_set_lens=None):
"""Send communication query.
Update State:
h_z = rnn(z, h_z)
Predictions:
y_i = f_y(h_z, desc_i)
Communication Query:
desc = \sum_i y_i desc_i
w_hat = tanh(W_h h_z + W_d desc)
w = bernoulli(sig(w_hat)) or round(sig(w_hat))
STOP Bit:
s_hat = W_s h_z
s = bernoulli(sig(s_hat)) or round(sig(s_hat))
Args:
z: Communication response from Receiver.
desc: List of description vectors used in communication and predictions.
Output:
s, s_probs: A STOP bit and its associated probability, indicating whether the Receiver has decided to stop
or continue its conversation with the Sender.
w, w_probs: A binary (or continuous) message, which is a query incorporating the descriptions. If the
message is binary, then the probability of each bit in the message being ``1`` is included.
y: A prediction for each class described in the descriptions.
"""
# BatchSize x BinaryDim
batch_size, binary_dim = z.size()
# Initialize hidden state if necessary
if self.h_z is None:
self.h_z = self.initial_state(batch_size)
# Run z through RNN
self.h_z = self.rnn(z, self.h_z)
# Build input for prediction using descriptions
# size of inp_with_desc: B*D x (WV+h)
if FLAGS.desc_attn:
nwords, desc_dim = desc_set.size()
desc_set = Variable(desc_set) # NW x WV
# Broadcast and Flatten
desc_set_broadcast = desc_set.unsqueeze(0).expand(
batch_size, nwords, self.desc_dim) # B x NW x WV
# Broadcast and Flatten
dd = self.d_d(desc_set) # NW x A
dd_broadcast = dd.unsqueeze(0).expand(
batch_size, nwords, self.attn_dim) # B x NW x A
dd_flat = dd_broadcast.contiguous().view(
batch_size * nwords, self.attn_dim) # B*NW x A
# Broadcast and Flatten
dh = self.d_h(self.h_z) # B x A
dh_broadcast = dh.unsqueeze(1).expand(
batch_size, nwords, self.attn_dim) # B x NW x A
dh_flat = dh_broadcast.contiguous().view(
batch_size * nwords, self.attn_dim) # B*NW x A
# Get and Apply Attention Scores
d_attn = self.d_attn(F.tanh(dd_flat + dh_flat)
).view(batch_size, nwords) # B x NW
# Partitioned Scores
cumlen = 0
d_attn_scores = []
for idesc, ndesc in enumerate(desc_set_lens):
start = cumlen
end = cumlen + ndesc
cumlen = end
scores = F.softmax(d_attn[:, start:end]) # B x NW_i
d_attn_scores.append(scores)
self.d_attn_scores = d_attn_scores = torch.cat(
d_attn_scores, 1) # B x NW
# Attend
d_attn_broadcast = d_attn_scores.unsqueeze(
2).expand_as(desc_set_broadcast) # B x NW x WV
desc_set_weighted = desc_set_broadcast * d_attn_broadcast # B x NW x WV
# Partitioned Weighted Sum
cumlen = 0
weighted_desc = []
for idesc, ndesc in enumerate(desc_set_lens):
start = cumlen
end = cumlen + ndesc
cumlen = end
cbow = desc_set_weighted[:, start:end, :].sum(1) # B x 1 x WV
weighted_desc.append(cbow)
weighted_desc = torch.cat(weighted_desc, 1) # B x D x WV
# Build Input
nclasses = weighted_desc.size(1)
weighted_desc = weighted_desc.view(
batch_size * nclasses, self.desc_dim) # B*D x WV
h_z_broadcast = self.h_z.unsqueeze(1).expand(
batch_size, nclasses, self.hid_dim) # B x D x h
h_z_flat = h_z_broadcast.contiguous().view(
batch_size * nclasses, self.hid_dim) # B*D x h
inp_with_desc = torch.cat(
[weighted_desc, h_z_flat], 1) # B*D x (WV+h)
else:
inp_with_desc = build_inp(self.h_z, desc) # B*D x (WV+h)
s_score = self.s(self.h_z)
s_prob = F.sigmoid(s_score)
if self.training:
# Sample decisions
prob_ = s_prob.data.cpu().numpy()
s_binary = Variable(torch.from_numpy(
(np.random.rand(*prob_.shape) < prob_).astype('float32')))
else:
# Infer decisions
if not self.s_prob_prod or not FLAGS.s_prob_prod:
self.s_prob_prod = s_prob
else:
self.s_prob_prod = self.s_prob_prod * s_prob
s_binary = torch.round(self.s_prob_prod).detach()
if s_prob.is_cuda:
s_binary = s_binary.cuda()
# Obtain predictions
y = self.y1(inp_with_desc).clamp(min=0)
y = self.y2(y).view(batch_size, -1)
# Obtain communications
# size of y = batch_size x # descriptions
# size of desc = # descriptions x self.desc_dim
# size of wd_inp = batch_size x self.desc_dim
n_desc = y.size(1)
# Reweight descriptions based on current model confidence
y_scores = F.softmax(y).detach()
y_broadcast = y_scores.unsqueeze(2).expand(
batch_size, n_desc, self.desc_dim)
if FLAGS.desc_attn:
wd_inp = weighted_desc.view(batch_size, nclasses, self.desc_dim)
else:
wd_inp = desc.unsqueeze(0).expand(
batch_size, n_desc, self.desc_dim)
wd_inp = (y_broadcast * wd_inp).sum(1).squeeze(1)
# Hidden state for Receiver message
self.h_w = F.tanh(self.w_h(self.h_z) + self.w_d(wd_inp))
w_scores = self.w(self.h_w)
if self.use_binary:
w_probs = F.sigmoid(w_scores)
if self.training:
probs_ = w_probs.data.cpu().numpy()
w_binary = Variable(torch.from_numpy(
(np.random.rand(*probs_.shape) < probs_).astype('float32')))
else:
w_binary = torch.round(w_probs).detach()
if w_probs.is_cuda:
w_binary = w_binary.cuda()
w_feats = w_binary
if FLAGS.flipout_rec is not None and (self.training or FLAGS.flipout_dev):
w_feats = flipout(w_feats, FLAGS.flipout_rec)
if FLAGS.ignore_receiver:
w_feats = Variable(torch.zeros(w_feats.size()),
volatile=not self.training)
else:
w_feats = w_scores
w_probs = None
return (s_binary, s_prob), (w_feats, w_probs), y
class Baseline(nn.Module):
"""Baseline
"""
def __init__(self, hid_dim, x_dim, binary_dim, inp_dim):
super(Baseline, self).__init__()
self.x_dim = x_dim
self.binary_dim = binary_dim
self.inp_dim = inp_dim
self.hid_dim = hid_dim
# Additional layers on top of feature extractor
self.linear1 = nn.Linear(
x_dim + self.binary_dim + self.inp_dim, self.hid_dim)
self.linear2 = nn.Linear(self.hid_dim, 1)
def forward(self, x, binary, inp):
"""Estimate agent's loss based on the agent's input.
Args:
x: Image features.
binary: Communication message.
inp: Hidden state (used when agent is the Receiver).
Output:
score: An estimate of the agent's loss.
"""
features = []
if x is not None:
features.append(x)
if binary is not None:
features.append(binary)
if inp is not None:
features.append(inp)
features = torch.cat(features, 1)
hidden = self.linear1(features).clamp(min=0)
pred_score = self.linear2(hidden)
return pred_score
def build_inp(binary_features, descs):
"""Function preparing input for Receiver network
Args:
binary_features: List of communication vectors, length ``B``.
descs: List of description vectors, length ``D``.
Output:
b_cat_d: The cartesian product of binary features and descriptions, length ``B`` x ``D``.
"""
if descs is not None:
batch_size = binary_features.size(0)
num_desc, desc_dim = descs.size()
# Expand binary features.
binary_index = torch.from_numpy(
np.arange(batch_size).repeat(num_desc).astype(np.int32)).long()
if binary_features.is_cuda:
binary_index = binary_index.cuda()
binary_copied = torch.index_select(
binary_features, 0, Variable(binary_index))
# Expand descriptions.
desc_index = torch.from_numpy(np.concatenate(
[np.arange(num_desc)] * batch_size).astype(np.int32)).long()
if descs.is_cuda:
desc_index = desc_index.cuda()
desc_copied = torch.index_select(descs, 0, Variable(desc_index))
# Concat binary vector with description vectors
inp = torch.cat([binary_copied, desc_copied], 1)
return inp
else:
return binary_features
def flipout(binary, p):
"""
Args:
binary: Tensor of binary values.
p: Probability of flipping a binary value.
Output:
outp: Tensor with same size as `binary` where bits have been
flipped with probability `p`.
"""
mask = torch.FloatTensor(binary.size()).fill_(p).numpy()
mask = Variable(torch.from_numpy(
(np.random.rand(*mask.shape) < mask).astype('float32')))
outp = (binary - mask).abs()
return outp
def loglikelihood(log_prob, target):
"""
Args: log softmax scores (N, C) where N is the batch size
and C is the number of classes
Output: log likelihood (N)
"""
return log_prob.gather(1, target)
def eval_dev(dev_file, batch_size, epoch, shuffle, cuda, top_k,
sender, receiver, desc_dict, map_labels, file_name,
callback=None):
"""
Function computing development accuracy
"""
desc = desc_dict["desc"]
desc_set = desc_dict.get("desc_set", None)
desc_set_lens = desc_dict.get("desc_set_lens", None)
extra = dict()
# Keep track of conversation lengths
conversation_lengths = []
# Keep track of message diversity
hamming_sen = []
hamming_rec = []
# Keep track of labels
true_labels = []
pred_labels = []
# Keep track of number of correct observations
total = 0
correct = 0
# Load development images
dev_loader = load_hdf5(dev_file, batch_size, epoch, shuffle,
truncate_final_batch=True, map_labels=map_labels)
for batch in dev_loader:
# Extract images and targets
target = batch["target"]
data = batch[FLAGS.img_feat]
_batch_size = target.size(0)
true_labels.append(target.cpu().numpy().reshape(-1))
# GPU support
if cuda:
data = data.cuda()
target = target.cuda()
desc = desc.cuda()
exchange_args = dict()
exchange_args["data"] = data
if FLAGS.attn_extra_context:
exchange_args["data_context"] = batch[FLAGS.data_context]
exchange_args["target"] = target
exchange_args["desc"] = desc
exchange_args["desc_set"] = desc_set
exchange_args["desc_set_lens"] = desc_set_lens
exchange_args["train"] = False
exchange_args["break_early"] = not FLAGS.fixed_exchange
exchange_args["corrupt"] = FLAGS.bit_flip
exchange_args["corrupt_region"] = FLAGS.corrupt_region
s, sen_w, rec_w, y, bs, br = exchange(
sender, receiver, None, None, exchange_args)
s_masks, s_feats, s_probs = s
sen_feats, sen_probs = sen_w
rec_feats, rec_probs = rec_w
# Mask if dynamic exchange length
if FLAGS.fixed_exchange:
y_masks = None
else:
y_masks = [torch.min(1 - m1, m2)
for m1, m2 in zip(s_masks[1:], s_masks[:-1])]
outp, _ = get_rec_outp(y, y_masks)
# Obtain top k predictions
dist = F.log_softmax(outp)
top_k_ind = torch.from_numpy(
dist.data.cpu().numpy().argsort()[:, -top_k:]).long()
target = target.view(-1, 1).expand(_batch_size, top_k)
# Store top 1 prediction for confusion matrix
_, argmax = dist.data.max(1)
pred_labels.append(argmax.cpu().numpy())
# Update accuracy counts
total += float(batch_size)
correct += (top_k_ind == target.cpu()).sum()
# Keep track of conversation lengths
conversation_lengths += torch.cat(s_feats,
1).data.float().sum(1).view(-1).tolist()
# Keep track of message diversity
mean_hamming_rec = 0
mean_hamming_sen = 0
prev_rec = torch.FloatTensor(_batch_size, FLAGS.rec_w_dim).fill_(0)
prev_sen = torch.FloatTensor(_batch_size, FLAGS.rec_w_dim).fill_(0)
for msg in sen_feats:
mean_hamming_sen += (msg.data.cpu() - prev_sen).abs().sum(1).mean()
prev_sen = msg.data.cpu()
mean_hamming_sen = mean_hamming_sen / float(len(sen_feats))
for msg in rec_feats:
mean_hamming_rec += (msg.data.cpu() - prev_rec).abs().sum(1).mean()
prev_rec = msg.data.cpu()
mean_hamming_rec = mean_hamming_rec / float(len(rec_feats))
hamming_sen.append(mean_hamming_sen)
hamming_rec.append(mean_hamming_rec)
if callback is not None:
callback_dict = dict(
s_masks=s_masks,
s_feats=s_feats,
s_probs=s_probs,
sen_feats=sen_feats,
sen_probs=sen_probs,
rec_feats=rec_feats,
rec_probs=rec_probs,
y=y)
callback(sender, receiver, batch, callback_dict)
# Print confusion matrix
true_labels = np.concatenate(true_labels).reshape(-1)
pred_labels = np.concatenate(pred_labels).reshape(-1)
np.savetxt(FLAGS.conf_mat, confusion_matrix(
true_labels, pred_labels), delimiter=',', fmt='%d')
# Compute statistics
conversation_lengths = np.array(conversation_lengths)
hamming_sen = np.array(hamming_sen)
hamming_rec = np.array(hamming_rec)
extra['conversation_lengths_mean'] = conversation_lengths.mean()
extra['conversation_lengths_std'] = conversation_lengths.std()
extra['hamming_sen_mean'] = hamming_sen.mean()
extra['hamming_rec_mean'] = hamming_rec.mean()
# Return accuracy
return correct / total, extra
def exchange(sender, receiver, baseline_sen, baseline_rec, exchange_args):
"""Run a batched conversation between Sender and Receiver.
The Sender has only the image, and the Receiver has descriptions of each of the image's
possible classes and a history of each message it has sent and received.
The Receiver begins the conversation by sending a query of Os. The Sender inspects this query
and the image, then formulates a response. The Receiver inspects the response and its set of
descriptions, then formulates a new query. The conversation continues this way until it has
reached some predetermined length, or the Receiver has decided it has processed a sufficient
amount of information at which point it ignores all future conversation. When each Receiver
in the batch has received sufficient information, then the batched conversation may terminate
early.
Exchange Args:
data: Image features.
data_context: Optional additional image features that can be used as query in visual attention.
target: Class labels.
desc: List of description vectors.
train: Boolean value indicating training mode (True) or evaluation mode (False).
break_early: Boolean value. If True, then terminate batched conversation if all Receivers are satisfied.
Args:
sender: Agent 1. The Sender.
receiver: Agent 2. The Receiver.
baseline_sen: Baseline network for Sender.
baseline_rec: Baseline network for Receiver.
exchange_args: Other useful arguments.
Output:
s: All STOP bits. (Masks, Values, Probabilities)
sen_w: All sender messages. (Values, Probabilities)
rec_w: All receiver messages. (Values, Probabilities)
y: All predictions that were made.
bs: Estimated loss of sender.
br: Estimated loss of receiver.
"""
data = exchange_args["data"]
data_context = exchange_args.get("data_context", None)
target = exchange_args["target"]
desc = exchange_args["desc"]
desc_set = exchange_args.get("desc_set", None)
desc_set_lens = exchange_args.get("desc_set_lens", None)
train = exchange_args["train"]
break_early = exchange_args.get("break_early", False)
corrupt = exchange_args.get("corrupt", False)
corrupt_region = exchange_args.get("corrupt_region", None)
batch_size = data.size(0)
# Pad with one column of ones.
stop_mask = [Variable(torch.ones(batch_size, 1).byte())]
stop_feat = []
stop_prob = []
sen_feats = []
sen_probs = []
rec_feats = []
rec_probs = []
y = []
bs = []
br = []
w_binary = Variable(torch.FloatTensor(batch_size, sender.w_dim).fill_(
FLAGS.first_rec), volatile=not train)
if train:
sender.train()
receiver.train()
baseline_sen.train()
baseline_rec.train()
else:
sender.eval()
receiver.eval()
sender.reset_state() # only for debugging/performance
receiver.reset_state()
for i_exchange in range(FLAGS.max_exchange):
z_r = w_binary # rename variable to z_r which makes more sense
# Run data through Sender
if data_context is not None:
z_binary, z_probs = sender(Variable(data, volatile=not train), Variable(z_r.data, volatile=not train),
Variable(data_context, volatile=not train), i_exchange)
else:
z_binary, z_probs = sender(Variable(data, volatile=not train), Variable(z_r.data, volatile=not train),
None, i_exchange)
# Optionally corrupt Sender's message
if corrupt:
# Obtain mask
mask = Variable(build_mask(corrupt_region, sender.w_dim))
mask_broadcast = mask.view(1, sender.w_dim).expand_as(z_binary)
# Subtract the mask to change values, but need to get absolute value
# to set -1 values to 1 to essentially "flip" all the bits.
z_binary = (z_binary - mask_broadcast).abs()
# Generate input for Receiver
z_s = z_binary # rename variable to z_s which makes more sense
# Run batch through Receiver
(s_binary, s_prob), (w_binary, w_probs), outp = receiver(
Variable(z_s.data, volatile=not train), Variable(
desc.data, volatile=not train),
desc_set, desc_set_lens)
if train:
sen_h_x = sender.h_x
# Score from Baseline (Sender)
baseline_sen_scores = baseline_sen(
Variable(sen_h_x.data), Variable(z_r.data), None)
rec_h_z = receiver.h_z if receiver.h_z else receiver.initial_state(
batch_size)
# Score from Baseline (Receiver)
baseline_rec_scores = baseline_rec(
None, Variable(z_s.data), Variable(rec_h_z.data))
outp = outp.view(batch_size, -1)
# Obtain predictions
dist = F.log_softmax(outp)
maxdist, argmax = dist.data.max(1)
# Save for later
stop_mask.append(torch.min(stop_mask[-1], s_binary.byte()))
stop_feat.append(s_binary)
stop_prob.append(s_prob)
sen_feats.append(z_binary)
sen_probs.append(z_probs)
rec_feats.append(w_binary)
rec_probs.append(w_probs)
y.append(outp)
if train:
br.append(baseline_rec_scores)
bs.append(baseline_sen_scores)
# Terminate exchange if everyone is done conversing
if break_early and stop_mask[-1].float().sum().data[0] == 0:
break
# The final mask must always be zero.
stop_mask[-1].data.fill_(0)
s = (stop_mask, stop_feat, stop_prob)
sen_w = (sen_feats, sen_probs)
rec_w = (rec_feats, rec_probs)
return s, sen_w, rec_w, y, bs, br
def get_rec_outp(y, masks):
def negent(yy):
probs = F.softmax(yy)
return (torch.log(probs + 1e-8) * probs).sum(1).mean()
# TODO: This is wrong for the dynamic exchange, and we might want a "per example"
# entropy for either exchange (this version is mean across batch).
negentropy = map(negent, y)
if masks is not None:
batch_size = y[0].size(0)
exchange_steps = len(masks)
inp = torch.cat([yy.view(batch_size, 1, -1) for yy in y], 1)
mask = torch.cat(masks, 1).view(
batch_size, exchange_steps, 1).expand_as(inp)
outp = torch.masked_select(inp, mask.detach()).view(batch_size, -1)
if FLAGS.debug:
# Each mask index should have exactly 1 true value.
assert all([mm.data[0] == 1 for mm in torch.cat(masks, 1).sum(1)])
return outp, negentropy
else:
return y[-1], negentropy
def calculate_loss_binary(binary_features, binary_probs, logs, baseline_scores, entropy_penalty):
log_p_z = Variable(binary_features.data) * torch.log(binary_probs + 1e-8) + \
(1 - Variable(binary_features.data)) * \
torch.log(1 - binary_probs + 1e-8)
log_p_z = log_p_z.sum(1)
weight = Variable(logs.data) - \
Variable(baseline_scores.clone().detach().data)
if logs.size(0) > 1:
weight = weight / np.maximum(1., torch.std(weight.data))
loss = torch.mean(-1 * weight * log_p_z)
# Must do both sides of negent, otherwise is skewed towards 0.
initial_negent = (torch.log(binary_probs + 1e-8)
* binary_probs).sum(1).mean()
inverse_negent = (torch.log((1. - binary_probs) + 1e-8)
* (1. - binary_probs)).sum(1).mean()
negentropy = initial_negent + inverse_negent
if entropy_penalty is not None:
loss = (loss + entropy_penalty * negentropy)
return loss, negentropy
def multistep_loss_binary(binary_features, binary_probs, logs, baseline_scores, masks, entropy_penalty):
if masks is not None:
def mapped_fn(feat, prob, scores, mask, mask_sums):
if mask_sums == 0:
return Variable(torch.zeros(1))
feat_size = feat.size()
prob_size = prob.size()
logs_size = logs.size()
scores_size = scores.size()
feat = feat[mask.expand_as(feat)].view(-1, feat_size[1])
prob = prob[mask.expand_as(prob)].view(-1, prob_size[1])
_logs = logs[mask.expand_as(logs)].view(-1, logs_size[1])
scores = scores[mask.expand_as(scores)].view(-1, scores_size[1])
return calculate_loss_binary(feat, prob, _logs, scores, entropy_penalty)
_mask_sums = [m.float().sum().data[0] for m in masks]
if FLAGS.debug:
assert len(masks) > 0
assert len(masks) == len(binary_features)
assert len(masks) == len(binary_probs)
assert len(masks) == len(baseline_scores)
assert sum(_mask_sums) > 0
outp = map(mapped_fn, binary_features, binary_probs,
baseline_scores, masks, _mask_sums)
losses = [o[0] for o in outp]
entropies = [o[1] for o in outp]
_losses = [l * ms for l, ms in zip(losses, _mask_sums)]
loss = sum(_losses) / sum(_mask_sums)
else:
outp = map(lambda feat, prob, scores: calculate_loss_binary(feat, prob, logs, scores, entropy_penalty),
binary_features, binary_probs, baseline_scores)
losses = [o[0] for o in outp]
entropies = [o[1] for o in outp]
loss = sum(losses) / len(binary_features)
return loss, entropies
def calculate_loss_bas(baseline_scores, logs):
loss_bas = nn.MSELoss()(baseline_scores, Variable(logs.data))
return loss_bas
def multistep_loss_bas(baseline_scores, logs, masks):
if masks is not None:
losses = map(lambda scores, mask: calculate_loss_bas(
scores[mask].view(-1, 1), logs[mask].view(-1, 1)),
baseline_scores, masks)
_mask_sums = [m.sum().float() for m in masks]
_losses = [l * ms for l, ms in zip(losses, _mask_sums)]
loss = sum(_losses) / sum(_mask_sums)
else:
losses = map(lambda scores: calculate_loss_bas(scores, logs),
baseline_scores)
loss = sum(losses) / len(baseline_scores)
return loss
def bin_to_alpha(binary):
ret = []
interval = 5
offset = 65
for i in range(0, len(binary), interval):
val = int(binary[i:i + interval], 2)
ret.append(unichr(offset + val))
return " ".join(ret)