forked from nyu-dl/MultimodalGame
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmodel_symmetric.py
3551 lines (3224 loc) · 192 KB
/
model_symmetric.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 copy
import functools
import logging
import pickle
import torch
from torch.autograd import Variable as _Variable
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from torch.nn.parameter import Parameter
import torchvision.datasets as dset
import torchvision.models as models
import torchvision.transforms as transforms
from torchvision.utils import save_image
from sklearn.metrics import confusion_matrix
from agents import Agent
from analyze_messages import convert_tensor_to_string
from dataset_loader import load_shapeworld_dataset
from community_util import sample_agents, build_train_matrix, build_eval_list, get_msg_pairs
from misc import build_mask
from misc import calculate_average_message
from misc import calculate_entropy, calculate_average_entropy, check_entropy
from misc import count_distinct_messages
from misc import read_log_load
from misc import recursively_set_device, torch_save, torch_load, torch_load_communities
from misc import FileLogger
from misc import VisdomLogger as Logger
from misc import xavier_normal
import gflags
FLAGS = gflags.FLAGS
SHAPES = ['circle', 'cross', 'ellipse', 'pentagon', 'rectangle', 'semicircle', 'square', 'triangle']
COLORS = ['blue', 'cyan', 'gray', 'green', 'magenta', 'red', 'yellow']
OOD_EXAMPLES = ['square_red', 'triangle_green', 'circle_blue', 'rectangle_yellow', 'cross_magenta', 'ellipse_cyan']
MAX_EXAMPLES_TO_SAVE = 200
def Variable(*args, **kwargs):
var = _Variable(*args, **kwargs)
if FLAGS.cuda:
var = var.cuda()
return var
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 store_exemplar_batch(data, data_type, logger, flogger):
'''Writes MAX_EXAMPLES_TO_SAVE examples in the data to file for debugging
data: dictionary containing data and results
data = {"masked_im_1": [],
"masked_im_2": [],
"msg_1": [],
"msg_2": [],
"p": [],
"target": [],
"caption": [],
"shapes": [],
"colors": [],
"texts": [],
}
data_type: flag giving the name of the data to be stored.
e.g. "correct", "incorrect"
'''
debuglogger.info(f'Num {data_type}: {len(data["masked_im_1"])}')
debuglogger.info("Writing exemplar batch to file...")
assert len(data["masked_im_1"]) == len(data["masked_im_2"]) == len(data["p"]) == len(data["caption"]) == len(data["shapes"]) == len(data["colors"]) == len(data["texts"])
num_examples = min(len(data["shapes"]), MAX_EXAMPLES_TO_SAVE)
path = FLAGS.log_path
prefix = FLAGS.experiment_name + "_" + data_type
if not os.path.exists(path + "/" + prefix):
os.makedirs(path + "/" + prefix)
# Save images
masked_im_1 = torch.stack(data["masked_im_1"][:num_examples], dim=0)
debuglogger.debug(f'Masked im 1: {type(masked_im_1)}')
debuglogger.debug(f'Masked im 1: {masked_im_1.size()}')
save_image(masked_im_1, path + '/' + prefix + '/im1.png', nrow=16, pad_value=0.5)
masked_im_2 = torch.stack(data["masked_im_2"][:num_examples], dim=0)
save_image(masked_im_2, path + '/' + prefix + '/im2.png', nrow=16, pad_value=0.5)
# Save other relevant info
keys = ['p', 'caption', 'shapes', 'colors']
for k in keys:
filename = path + '/' + prefix + '/' + k + '.txt'
with open(filename, "w") as wf:
for i in range(num_examples):
wf.write(f'Example {i+1}: {data[k][i]}\n')
# Write texts
filename = path + '/' + prefix + '/texts.txt'
with open(filename, "w") as wf:
for i in range(num_examples):
s = ""
for t in data["texts"][i]:
s += t + ", "
wf.write(f'Example {i+1}: {s}\n')
# Print average and std p
np_p = np.array(data["p"])
debuglogger.info(f'p: mean: {np.mean(np_p)} std: {np.std(np_p)}')
def calc_message_mean_and_std(m_store):
'''Calculate the mean and std deviation of messages per agent per shape, color and shape-color combination'''
for k in m_store:
msgs = m_store[k]["message"]
msgs = torch.stack(msgs, dim=0)
debuglogger.debug(f'Key: {k}, Count: {m_store[k]["count"]}, Messages: {msgs.size()}')
mean = torch.mean(msgs, dim=0).cpu()
std = torch.std(msgs, dim=0).cpu()
m_store[k]["mean"] = mean
m_store[k]["std"] = std
return m_store
def log_message_stats(message_stats, logger, flogger, data_type, epoch, step, i_batch):
''' Helper function to write the message stats to file and log them to stdout
Logs the mean and std deviation per set of messages per shape, per color and per shape-color for each message set.
Additionally logs the distances between the mean message for each agent type per shape, color and shape-color'''
debuglogger.info('Logging message stats')
shape_colors = []
for s in SHAPES:
for c in COLORS:
shape_colors.append(str(s) + "_" + str(c))
# log shape stats
for s in SHAPES:
num = 0
if s in message_stats[0]["shape"]:
num = message_stats[0]["shape"][s]["count"]
means = []
stds = []
for i, m in enumerate(message_stats):
if s in message_stats[i]["shape"]:
assert num == message_stats[i]["shape"][s]["count"]
m = message_stats[i]["shape"][s]["mean"]
st = message_stats[i]["shape"][s]["std"]
means.append(m)
stds.append(st)
dists = []
assert len(means) != 1
for i in range(len(means)):
for j in range(i + 1, len(means)):
d = torch.dist(means[i], means[j])
dists.append((i, j, d))
if i == len(means) - 2:
break
logger.log(key=data_type + ": " + s + " message stats: count: ", val=num, step=step)
for i in range(len(means)):
logger.log(key=data_type + ": " + s + " message stats: Agent " + str(i) + ": mean: ",
val=means[i], step=step)
logger.log(key=data_type + ": " + s + " message stats: Agent " + str(i) + ": std: ",
val=stds[i], step=step)
flogger.Log("Epoch: {} Step: {} Batch: {} {} message stats: shape {}: count: {}, agent {}: mean: {}, std: {}".format(
epoch, step, i_batch, data_type, s, num, i, means[i], stds[i]))
for i in range(len(dists)):
logger.log(key=data_type + ": " + s + " message stats: distances: [" + str(dists[i][0]) + ":" + str(dists[i][1]) + "]: ", val=dists[i][2], step=step)
flogger.Log("Epoch: {} Step: {} Batch: {} {} message stats: shape {}: dists: {}".format(epoch, step, i_batch, data_type, s, dists))
# log color stats
for s in COLORS:
num = 0
if s in message_stats[0]["color"]:
num = message_stats[0]["color"][s]["count"]
means = []
stds = []
for i, m in enumerate(message_stats):
if s in message_stats[i]["color"]:
assert num == message_stats[i]["color"][s]["count"]
m = message_stats[i]["color"][s]["mean"]
st = message_stats[i]["color"][s]["std"]
means.append(m)
stds.append(st)
dists = []
assert len(means) != 1
for i in range(len(means)):
for j in range(i + 1, len(means)):
d = torch.dist(means[i], means[j])
dists.append((i, j, d))
if i == len(means) - 2:
break
logger.log(key=data_type + ": " + s + " message stats: count: ", val=num, step=step)
for i in range(len(means)):
logger.log(key=data_type + ": " + s + " message stats: Agent " + str(i) + ": mean: ",
val=means[i], step=step)
logger.log(key=data_type + ": " + s + " message stats: Agent " + str(i) + ": std: ",
val=stds[i], step=step)
flogger.Log("Epoch: {} Step: {} Batch: {} {} message stats: color {}: count: {}, agent {}: mean: {}, std: {}".format(
epoch, step, i_batch, data_type, s, num, i, means[i], stds[i]))
for i in range(len(dists)):
logger.log(key=data_type + ": " + s + " message stats: distances: [" + str(dists[i][0]) + ":" + str(dists[i][1]) + "]: ", val=dists[i][2], step=step)
flogger.Log("Epoch: {} Step: {} Batch: {} {} message stats: color {}: dists: {}".format(epoch, step, i_batch, data_type, s, dists))
# log shape - color stats
for s in shape_colors:
num = 0
if s in message_stats[0]["shape_color"]:
num = message_stats[0]["shape_color"][s]["count"]
means = []
stds = []
for i, m in enumerate(message_stats):
if s in message_stats[i]["shape_color"]:
assert num == message_stats[i]["shape_color"][s]["count"]
m = message_stats[i]["shape_color"][s]["mean"]
st = message_stats[i]["shape_color"][s]["std"]
means.append(m)
stds.append(st)
dists = []
assert len(means) != 1
for i in range(len(means)):
for j in range(i + 1, len(means)):
d = torch.dist(means[i], means[j])
dists.append((i, j, d))
if i == len(means) - 2:
break
logger.log(key=data_type + ": " + s + " message stats: count: ", val=num, step=step)
for i in range(len(means)):
logger.log(key=data_type + ": " + s + " message stats: Agent " + str(i) + ": mean: ", val=means[i], step=step)
logger.log(key=data_type + ": " + s + " message stats: Agent " + str(i) + ": std: ", val=stds[i], step=step)
flogger.Log("Epoch: {} Step: {} Batch: {} {} message stats: shape_color {}: count: {}, agent {}: mean: {}, std: {}".format(epoch, step, i_batch, data_type, s, num, i, means[i], stds[i]))
for i in range(len(dists)):
logger.log(key=data_type + ": " + s + " message stats: distances: [" + str(dists[i][0]) + ":" + str(dists[i][1]) + "]: ", val=dists[i][2], step=step)
flogger.Log("Epoch: {} Step: {} Batch: {} {} message stats: shape_color {}: dists: {}".format(epoch, step, i_batch, data_type, s, dists))
path = FLAGS.log_path + "/" + FLAGS.experiment_name + "_" + data_type + "_message_stats.pkl"
pickle.dump(message_stats, open(path, "wb"))
debuglogger.info(f'Saved message stats to log file')
def run_analyze_messages(data, data_type, logger, flogger, epoch, step, i_batch):
'''Calculates the mean and std deviation per set of messages per shape, per color and per shape-color for each message set.
Additionally caculates the distances between the mean message for each agent type per shape, color and shape-color
data: dictionary containing log of data_type examples
data_type: flag explaining the type of data
e.g. "correct", "incorrect"
Each message list should have the same length and the shape and colors lists
Also saves the messages and analysis to file
'''
message_stats = []
messages = [data["msg_1"], data["msg_2"]]
shapes = data["shapes"]
colors = data["colors"]
for m_set in messages:
assert len(m_set) == len(shapes)
assert len(m_set) == len(colors)
d = {"shape": {},
"color": {},
"shape_color": {}
}
message_stats.append(d)
debuglogger.info(f'Messages: {len(messages[0])}, {len(messages[0][0])}')
for i, m_set in enumerate(messages):
s_store = message_stats[i]["shape"]
c_store = message_stats[i]["color"]
s_c_store = message_stats[i]["shape_color"]
# Collect all messages
j = 0
for m, s, c in zip(m_set, shapes, colors):
if s in s_store:
# Potentially multiple exchanges
for m_i in m:
s_store[s]["count"] += 1
s_store[s]["message"].append(m_i.data)
else:
s_store[s] = {}
s_store[s]["count"] = 1
s_store[s]["message"] = [m[0].data]
if len(m) > 1:
for m_i in m[1:]:
s_store[s]["count"] += 1
s_store[s]["message"].append(m_i.data)
if c in c_store:
# Potentially multiple exchanges
for m_i in m:
c_store[c]["count"] += 1
c_store[c]["message"].append(m_i.data)
else:
c_store[c] = {}
c_store[c]["count"] = 1
c_store[c]["message"] = [m[0].data]
if len(m) > 1:
for m_i in m[1:]:
c_store[c]["count"] += 1
c_store[c]["message"].append(m_i.data)
s_c = str(s) + "_" + str(c)
if s_c in s_c_store:
# Potentially multiple exchanges
for m_i in m:
s_c_store[s_c]["count"] += 1
s_c_store[s_c]["message"].append(m_i.data)
else:
s_c_store[s_c] = {}
s_c_store[s_c]["count"] = 1
s_c_store[s_c]["message"] = [m[0].data]
if len(m) > 1:
for m_i in m[1:]:
s_c_store[s_c]["count"] += 1
s_c_store[s_c]["message"].append(m_i.data)
if j == 5:
debuglogger.debug(f's_store: {s_store}')
debuglogger.debug(f'c_store: {c_store}')
debuglogger.debug(f's_c_store: {s_c_store}')
j += 1
# Calculate and log mean and std_dev
s_store = calc_message_mean_and_std(s_store)
c_store = calc_message_mean_and_std(c_store)
s_c_store = calc_message_mean_and_std(s_c_store)
log_message_stats(message_stats, logger, flogger, data_type, epoch, step, i_batch)
def add_data_point(batch, i, data_store, messages_1, messages_2, probs_1, probs_2):
'''Adds the relevant data from a batch to a data store to analyze later'''
# Storing images creates a huge slowdown and no need to store them
# data_store["masked_im_1"].append(batch["masked_im_1"][i])
# data_store["masked_im_2"].append(batch["masked_im_2"][i])
data_store["p"].append(batch["p"][i])
data_store["target"].append(batch["target"][i])
data_store["caption"].append(batch["caption_str"][i])
data_store["shapes"].append(batch["shapes"][i])
data_store["colors"].append(batch["colors"][i])
data_store["texts"].append(batch["texts_str"][i])
# Add messages, probs and entropy from each exchange
m_1 = [] # message
p_1 = [] # message probability
m_1_ent = [] # entropy per message
m_1_str = [] # message as a string
for exchange, prob in zip(messages_1, probs_1):
m = exchange[i].data.cpu()
p = prob[i].data.cpu()
m_1.append(m)
p_1.append(p)
m_1_ent.append(calculate_entropy(p))
m_1_str.append(convert_tensor_to_string(m))
data_store["msg_1"].append(m_1)
data_store["probs_1"].append(p_1)
data_store["msg_1_str"].append(m_1_str)
data_store["msg_1_ent"].append(m_1_ent)
m_2 = [] # message
p_2 = [] # message probability
m_2_ent = [] # entropy per message
m_2_str = [] # message as a string
for exchange, prob in zip(messages_2, probs_2):
m = exchange[i].data.cpu()
p = prob[i].data.cpu()
m_2.append(m)
p_2.append(p)
m_2_ent.append(calculate_entropy(p))
m_2_str.append(convert_tensor_to_string(m))
data_store["msg_2"].append(m_2)
data_store["probs_2"].append(p_2)
data_store["msg_2_str"].append(m_2_str)
data_store["msg_2_ent"].append(m_2_ent)
return data_store
def save_messages_and_stats(correct, incorrect, agent_tag):
'''Saves all messages and message probs between two agents, along with relevant tags such as the shape, color and caption, and whether the message was correct or incorrect
Data is stored as a list of dicts and pickled. Each dict corresponds to one exchange. The dicts have the following keys
- msg_1: message(s) sent from agent 1
- msg_2: message(s) sent from agent 2
- probs_1: message 1 probs
- probs_2: message 2 probs
- caption: the correct caption
- shape: the shape in the caption
- color: the color in the caption
- correct: boolean, whether both agents solved the task after communication
'''
message_data = []
num_correct = len(correct["caption"])
num_incorrect = len(incorrect["caption"])
for i in range(num_correct):
elem = {}
elem["caption"] = correct["caption"][i]
elem["msg_1"] = correct["msg_1"][i]
elem["msg_2"] = correct["msg_2"][i]
elem["probs_1"] = correct["probs_1"][i]
elem["probs_2"] = correct["probs_2"][i]
elem["shape"] = correct["shapes"][i]
elem["color"] = correct["colors"][i]
elem["correct"] = True
message_data.append(elem)
for i in range(num_incorrect):
elem = {}
elem["caption"] = incorrect["caption"][i]
elem["msg_1"] = incorrect["msg_1"][i]
elem["msg_2"] = incorrect["msg_2"][i]
elem["probs_1"] = incorrect["probs_1"][i]
elem["probs_2"] = incorrect["probs_2"][i]
elem["shape"] = incorrect["shapes"][i]
elem["color"] = incorrect["colors"][i]
elem["correct"] = False
message_data.append(elem)
debuglogger.info(f'Saving messages...')
debuglogger.info(f'{num_correct} correct, {num_incorrect} incorrect, {num_correct + num_incorrect} total')
path = FLAGS.log_path + "/" + FLAGS.experiment_name + "_" + agent_tag + "_message_stats.pkl"
pickle.dump(message_data, open(path, "wb"))
debuglogger.info(f'Messages saved')
def get_similarity(dataset_path, in_domain_eval, agent1, agent2, a1_group, a2_group, a1_idx, a2_idx, agent_codes_1, agent_codes_2, logger, flogger):
'''Computes the similarity between two language groups. Can also be used to compute self similarity
Args:
agent1: first agent
agent2: second agent
a1_group: which group agent 1 belongs to (1 or 2)
a2_group: which group agent 2 belongs to (1 or 2)
a1_idx: index of first agent in the codes of the agent's group
a2_idx: index of second agent in the codes of the agent's group
agent_codes_1: average codes for each shape and color (from correct, non blank answers) sent by agents in group 1 (one set for each agent)
agent_codes_2: average codes for each shape and color (from correct, non blank answers) sent by agents in group 2 (one set for each agent)
'''
# Log agent details
debuglogger.info(f'Getting similarity for agents: [{a1_idx}/{a2_idx}], group: [{a1_group}/{a2_group}], length codes: [{len(agent_codes_1)}/{len(agent_codes_2)}]')
# Keep track of labels
true_labels = []
pred_labels_1_nc = []
pred_labels_1_com = []
pred_labels_2_nc = []
pred_labels_2_com = []
# Keep track of number of correct observations
total = 0
total_correct_nc = 0
total_correct_com = 0
atleast1_correct_nc = 0
atleast1_correct_com = 0
# Keep track of score when messages are changed
test_language_similarity = {"total": 0, "correct": [], "agent_w_changed_msg": [], "shape": [], "color": [], "orig_shape": [], "orig_color": [], "originally_correct": []}
detail_language_similarity = []
# Load development images
if in_domain_eval:
eval_mode = "train"
debuglogger.info("Evaluating on in domain validation set")
else:
eval_mode = FLAGS.dataset_eval_mode
debuglogger.info("Evaluating on out of domain validation set")
dev_loader = load_shapeworld_dataset(dataset_path, FLAGS.glove_path, eval_mode, FLAGS.dataset_size_dev, FLAGS.dataset_type, FLAGS.dataset_name, FLAGS.batch_size_dev, FLAGS.random_seed, FLAGS.shuffle_dev, FLAGS.img_feat, FLAGS.cuda, truncate_final_batch=False)
_batch_counter = 0
for batch in dev_loader:
_batch_counter += 1
debuglogger.debug(f'Batch {_batch_counter}')
target = batch["target"]
im_feats_1 = batch["im_feats_1"]
im_feats_2 = batch["im_feats_2"]
p = batch["p"]
desc = Variable(batch["texts_vec"])
_batch_size = target.size(0)
true_labels.append(target.cpu().numpy().reshape(-1))
# GPU support
if FLAGS.cuda:
im_feats_1 = im_feats_1.cuda()
im_feats_2 = im_feats_2.cuda()
target = target.cuda()
desc = desc.cuda()
data = {"im_feats_1": im_feats_1,
"im_feats_2": im_feats_2,
"p": p}
exchange_args = dict()
exchange_args["data"] = data
exchange_args["target"] = target
exchange_args["desc"] = desc
exchange_args["train"] = False
exchange_args["break_early"] = not FLAGS.fixed_exchange
s, message_1, message_2, y_all, r = exchange(
agent1, agent2, exchange_args)
s_masks_1, s_feats_1, s_probs_1 = s[0]
s_masks_2, s_feats_2, s_probs_2 = s[1]
feats_1, probs_1 = message_1
feats_2, probs_2 = message_2
y_nc = y_all[0]
y = y_all[1]
# Mask loss if dynamic exchange length
if FLAGS.fixed_exchange:
binary_s_masks = None
binary_agent1_masks = None
binary_agent2_masks = None
bas_agent1_masks = None
bas_agent2_masks = None
y1_masks = None
y2_masks = None
outp_1 = y[0][-1]
outp_2 = y[1][-1]
else:
# TODO
pass
# Before communication predictions
# Obtain predictions, loss and stats agent 1
(dist_1_nc, maxdist_1_nc, argmax_1_nc, ent_1_nc, nll_loss_1_nc,
logs_1_nc) = get_classification_loss_and_stats(y_nc[0], target)
# Obtain predictions, loss and stats agent 2
(dist_2_nc, maxdist_2_nc, argmax_2_nc, ent_2_nc, nll_loss_2_nc,
logs_2_nc) = get_classification_loss_and_stats(y_nc[1], target)
# After communication predictions
# Obtain predictions, loss and stats agent 1
(dist_1, maxdist_1, argmax_1, ent_1, nll_loss_1_com,
logs_1) = get_classification_loss_and_stats(outp_1, target)
# Obtain predictions, loss and stats agent 2
(dist_2, maxdist_2, argmax_2, ent_2, nll_loss_2_com,
logs_2) = get_classification_loss_and_stats(outp_2, target)
# Store top 1 prediction for confusion matrix
pred_labels_1_nc.append(argmax_1_nc.cpu().numpy())
pred_labels_1_com.append(argmax_1.cpu().numpy())
pred_labels_2_nc.append(argmax_2_nc.cpu().numpy())
pred_labels_2_com.append(argmax_2.cpu().numpy())
# Calculate number of correct observations for different types
accuracy_1_nc, correct_1_nc, top_1_1_nc = calculate_accuracy(
dist_1_nc, target, FLAGS.batch_size_dev, FLAGS.top_k_dev)
accuracy_1, correct_1, top_1_1 = calculate_accuracy(
dist_1, target, FLAGS.batch_size_dev, FLAGS.top_k_dev)
accuracy_2_nc, correct_2_nc, top_1_2_nc = calculate_accuracy(
dist_2_nc, target, FLAGS.batch_size_dev, FLAGS.top_k_dev)
accuracy_2, correct_2, top_1_2 = calculate_accuracy(
dist_2, target, FLAGS.batch_size_dev, FLAGS.top_k_dev)
batch_correct_nc = correct_1_nc.float() + correct_2_nc.float()
batch_correct_com = correct_1.float() + correct_2.float()
batch_correct_top_1_nc = top_1_1_nc.float() + top_1_2_nc.float()
batch_correct_top_1_com = top_1_1.float() + top_1_2.float()
# Update accuracy counts
total += float(_batch_size)
total_correct_nc += (batch_correct_nc == 2).sum()
total_correct_com += (batch_correct_com == 2).sum()
atleast1_correct_nc += (batch_correct_nc > 0).sum()
atleast1_correct_com += (batch_correct_com > 0).sum()
# Get correct indices
correct_indices_nc = (batch_correct_nc == 2)
correct_indices_com = (batch_correct_com == 2)
# Test compositionality
for _ in range(_batch_size):
# Construct batch of size 1
data = {"im_feats_1": im_feats_1[_].unsqueeze(0),
"im_feats_2": im_feats_2[_].unsqueeze(0),
"p": p[_]}
exchange_args = dict()
exchange_args["data"] = data
exchange_args["desc"] = desc[_].unsqueeze(0)
exchange_args["train"] = False
exchange_args["break_early"] = not FLAGS.fixed_exchange
exchange_args["test_language_similarity"] = True
# Construct candidate example to change message to
debuglogger.info(f'Agent with sight: {batch["non_blank_partition"][_]}')
# Only select examples where one agent is blind
if batch['non_blank_partition'][_] != 0:
change_agent = batch['non_blank_partition'][_]
texts = batch["texts_str"][_]
s = batch["shapes"][_]
c = batch["colors"][_]
debuglogger.info(f'i: {_}, caption: {batch["caption_str"][_]}, original target: {target[_]}, Correct? {correct_1[_]}/{correct_2[_]}')
debuglogger.debug(f'i: {_}, texts: {texts}')
debuglogger.debug(f'i: {_}, texts_shapes: {batch["texts_shapes"][_]}')
debuglogger.debug(f'i: {_}, texts_colors: {batch["texts_colors"][_]}')
for _t, t in enumerate(texts):
# Only select examples that are different to the current target
if _t != target[_]:
st = batch["texts_shapes"][_][_t]
ct = batch["texts_colors"][_][_t]
# Only select examples where there is a different of either the shape or the color, not both
if (st == s and ct != c) or (st != s and ct == c):
exchange_args["target"] = _t
exchange_args["change_agent"] = change_agent
if ct != c:
exchange_args["subtract"] = c
exchange_args["add"] = ct
else:
exchange_args["subtract"] = s
exchange_args["add"] = st
# Discard examples which involve adding or subtracting "None" (no code for this)
if exchange_args["subtract"] is None or exchange_args["add"] is None:
debuglogger.info(f'Skipping example due to None add or subtract...')
continue
debuglogger.info(f'i: {_} t: {_t}, subtracting: {exchange_args["subtract"]}, adding: {exchange_args["add"]}, change agent: {exchange_args["change_agent"]}')
# Set up to play the game and store results for all permutations
example_stats = {'subtract': {'name': exchange_args["subtract"], 'total': 0, 'correct': 0},
'add': {'name': exchange_args["add"], 'total': 0, 'correct': 0},
'own_correct': 0,
'originally_correct': 0,
'correct_permutations': 0,
'total_permutations': 0,
'total_own_codes': 0}
# Fix who goes first for all permutations in an example
exchange_args["use_given_who_goes_first"] = True
if random.random() < 0.5:
exchange_args["given_who_goes_first"] = 1
else:
exchange_args["given_who_goes_first"] = 2
# Flip the change agent since the agents receiving the image feats will be flipped
change_agent = 1 if change_agent == 2 else 2
exchange_args["change_agent"] = change_agent
debuglogger.info(f'Given who goes first: {exchange_args["given_who_goes_first"]}, change agent: {exchange_args["change_agent"]}')
''' ==========================================================='''
# First play game with the change agent's own codes
own_codes_flag = True
debuglogger.debug(f'Playing game with own codes: {own_codes_flag}')
if change_agent == 1:
if a1_group == 1:
exchange_args["agent_subtract_dict"] = agent_codes_1[a1_idx]
exchange_args["agent_add_dict"] = agent_codes_1[a1_idx]
else:
exchange_args["agent_subtract_dict"] = agent_codes_2[a1_idx]
exchange_args["agent_add_dict"] = agent_codes_2[a1_idx]
else:
if a2_group == 1:
exchange_args["agent_subtract_dict"] = agent_codes_1[a2_idx]
exchange_args["agent_add_dict"] = agent_codes_1[a2_idx]
else:
exchange_args["agent_subtract_dict"] = agent_codes_2[a2_idx]
exchange_args["agent_add_dict"] = agent_codes_2[a2_idx]
# Play game, corrupting message
_s, message_1, message_2, y_all, r = exchange(
agent1, agent2, exchange_args)
s_masks_1, s_feats_1, s_probs_1 = _s[0]
s_masks_2, s_feats_2, s_probs_2 = _s[1]
feats_1, probs_1 = message_1
feats_2, probs_2 = message_2
y_nc = y_all[0]
y = y_all[1]
# We only care about after communication predictions when measuring the peformance
score = None
new_target = torch.zeros(1).fill_(_t).long()
debuglogger.debug(f'Old target: {target[_]}')
na, argmax_y1 = torch.max(y[0][-1], 1)
na, argmax_y2 = torch.max(y[1][-1], 1)
debuglogger.debug(f'y1 logits: {y[0][-1].data}, y2 logits: {y[1][-1].data}')
debuglogger.debug(f'y1: {argmax_y1.data[0]}, y2: {argmax_y2.data[0]}, new_target: {new_target[0]}')
if FLAGS.cuda:
new_target = new_target.cuda()
if change_agent == 1:
# Calculate score for agent 2
(dist_2_change, na, na, na, na, na) = get_classification_loss_and_stats(y[1][-1], new_target)
debuglogger.debug(f'dist: {dist_2_change.data}')
na, na, top_1_2_change = calculate_accuracy(
dist_2_change, new_target, 1, FLAGS.top_k_dev)
score = top_1_2_change
else:
# Calculate score for agent 1
(dist_1_change, na, na, na, na, na) = get_classification_loss_and_stats(y[0][-1], new_target)
debuglogger.debug(f'dist: {dist_1_change.data}')
na, na, top_1_1_change = calculate_accuracy(
dist_1_change, new_target, 1, FLAGS.top_k_dev)
score = top_1_1_change
debuglogger.debug(f'i: {_}_{_t}: New caption: {t}, new target: {_t}, change_agent: {change_agent}, correct: {score[0]}, originally correct: {correct_1[_]}/{correct_2[_]}')
# Store results
test_language_similarity["total"] += 1
test_language_similarity["orig_shape"].append(s)
test_language_similarity["orig_color"].append(c)
if score[0] == 1:
test_language_similarity["correct"].append(1)
else:
test_language_similarity["correct"].append(0)
if change_agent == 2:
# The other agent had their message changed
test_language_similarity["originally_correct"].append(correct_1[_])
test_language_similarity["agent_w_changed_msg"].append(1)
else:
test_language_similarity["originally_correct"].append(correct_2[_])
test_language_similarity["agent_w_changed_msg"].append(2)
if ct != c:
test_language_similarity["shape"].append(None)
test_language_similarity["color"].append(ct)
else:
test_language_similarity["shape"].append(st)
test_language_similarity["color"].append(None)
# Track detailed results
example_stats['total_permutations'] += 1
example_stats['subtract']["total"] += 1
example_stats['add']["total"] += 1
if score[0] == 1:
example_stats["subtract"]["correct"] += 1
example_stats["add"]["correct"] += 1
example_stats["correct_permutations"] += 1
if change_agent == 2:
example_stats['originally_correct'] = correct_1[_]
else:
example_stats['originally_correct'] = correct_2[_]
if own_codes_flag:
example_stats['total_own_codes'] += 1
if score[0] == 1:
example_stats['own_correct'] += 1
''' ==========================================================='''
# Now play the game with all permutations of codes
for _g1 in range(len(agent_codes_1)):
for _g2 in range(len(agent_codes_2)):
# Track if agent is playing with its own codes
own_codes_flag = False
if FLAGS.self_similarity and (change_agent == 1) and (_g1 == _g2 == a1_idx):
own_codes_flag = True
elif FLAGS.self_similarity and (change_agent == 2) and (_g1 == _g2 == a2_idx):
own_codes_flag = True
debuglogger.debug(f'Playing game with own codes: {own_codes_flag}')
''' ==========================================================='''
# First play game with codes from group 1 subtracting and code from group 2 adding
exchange_args["agent_subtract_dict"] = agent_codes_1[_g1]
exchange_args["agent_add_dict"] = agent_codes_2[_g2]
# Play game, corrupting message
_s, message_1, message_2, y_all, r = exchange(
agent1, agent2, exchange_args)
s_masks_1, s_feats_1, s_probs_1 = _s[0]
s_masks_2, s_feats_2, s_probs_2 = _s[1]
feats_1, probs_1 = message_1
feats_2, probs_2 = message_2
y_nc = y_all[0]
y = y_all[1]
# We only care about after communication predictions when measuring the peformance
score = None
new_target = torch.zeros(1).fill_(_t).long()
debuglogger.debug(f'Old target: {target[_]}')
na, argmax_y1 = torch.max(y[0][-1], 1)
na, argmax_y2 = torch.max(y[1][-1], 1)
debuglogger.debug(f'y1 logits: {y[0][-1].data}, y2 logits: {y[1][-1].data}')
debuglogger.debug(f'y1: {argmax_y1.data[0]}, y2: {argmax_y2.data[0]}, new_target: {new_target[0]}')
if FLAGS.cuda:
new_target = new_target.cuda()
if change_agent == 1:
# Calculate score for agent 2
(dist_2_change, na, na, na, na, na) = get_classification_loss_and_stats(y[1][-1], new_target)
debuglogger.debug(f'dist: {dist_2_change.data}')
na, na, top_1_2_change = calculate_accuracy(
dist_2_change, new_target, 1, FLAGS.top_k_dev)
score = top_1_2_change
else:
# Calculate score for agent 1
(dist_1_change, na, na, na, na, na) = get_classification_loss_and_stats(y[0][-1], new_target)
debuglogger.debug(f'dist: {dist_1_change.data}')
na, na, top_1_1_change = calculate_accuracy(
dist_1_change, new_target, 1, FLAGS.top_k_dev)
score = top_1_1_change
debuglogger.debug(f'i: {_}_{_t}: New caption: {t}, new target: {_t}, change_agent: {change_agent}, correct: {score[0]}, originally correct: {correct_1[_]}/{correct_2[_]}')
# Store results
test_language_similarity["total"] += 1
test_language_similarity["orig_shape"].append(s)
test_language_similarity["orig_color"].append(c)
if score[0] == 1:
test_language_similarity["correct"].append(1)
else:
test_language_similarity["correct"].append(0)
if change_agent == 2:
# The other agent had their message changed
test_language_similarity["originally_correct"].append(correct_1[_])
test_language_similarity["agent_w_changed_msg"].append(1)
else:
test_language_similarity["originally_correct"].append(correct_2[_])
test_language_similarity["agent_w_changed_msg"].append(2)
if ct != c:
test_language_similarity["shape"].append(None)
test_language_similarity["color"].append(ct)
else:
test_language_similarity["shape"].append(st)
test_language_similarity["color"].append(None)
# Track detailed results
example_stats['total_permutations'] += 1
example_stats['subtract']["total"] += 1
example_stats['add']["total"] += 1
if score[0] == 1:
example_stats["subtract"]["correct"] += 1
example_stats["add"]["correct"] += 1
example_stats["correct_permutations"] += 1
if change_agent == 2:
example_stats['originally_correct'] = correct_1[_]
else:
example_stats['originally_correct'] = correct_2[_]
if own_codes_flag:
example_stats['total_own_codes'] += 1
if score[0] == 1:
example_stats['own_correct'] += 1
''' ==========================================================='''
''' ==========================================================='''
debuglogger.debug(f'Playing game with own codes: {own_codes_flag}')
# Now play the game with the switched codes
exchange_args["agent_subtract_dict"] = agent_codes_2[_g2]
exchange_args["agent_add_dict"] = agent_codes_1[_g1]
# Play game, corrupting message
_s, message_1, message_2, y_all, r = exchange(
agent1, agent2, exchange_args)
s_masks_1, s_feats_1, s_probs_1 = _s[0]
s_masks_2, s_feats_2, s_probs_2 = _s[1]
feats_1, probs_1 = message_1
feats_2, probs_2 = message_2
y_nc = y_all[0]
y = y_all[1]
# We only care about after communication predictions when measuring the peformance
score = None
new_target = torch.zeros(1).fill_(_t).long()
debuglogger.debug(f'Old target: {target[_]}')
na, argmax_y1 = torch.max(y[0][-1], 1)
na, argmax_y2 = torch.max(y[1][-1], 1)
debuglogger.debug(f'y1 logits: {y[0][-1].data}, y2 logits: {y[1][-1].data}')
debuglogger.debug(f'y1: {argmax_y1.data[0]}, y2: {argmax_y2.data[0]}, new_target: {new_target[0]}')
if FLAGS.cuda:
new_target = new_target.cuda()
if change_agent == 1:
# Calculate score for agent 2
(dist_2_change, na, na, na, na, na) = get_classification_loss_and_stats(y[1][-1], new_target)
debuglogger.debug(f'dist: {dist_2_change.data}')
na, na, top_1_2_change = calculate_accuracy(
dist_2_change, new_target, 1, FLAGS.top_k_dev)
score = top_1_2_change
else:
# Calculate score for agent 1
(dist_1_change, na, na, na, na, na) = get_classification_loss_and_stats(y[0][-1], new_target)
debuglogger.debug(f'dist: {dist_1_change.data}')
na, na, top_1_1_change = calculate_accuracy(
dist_1_change, new_target, 1, FLAGS.top_k_dev)
score = top_1_1_change
debuglogger.debug(f'i: {_}_{_t}: New caption: {t}, new target: {_t}, change_agent: {change_agent}, correct: {score[0]}, originally correct: {correct_1[_]}/{correct_2[_]}')
# Store results
test_language_similarity["total"] += 1
test_language_similarity["orig_shape"].append(s)
test_language_similarity["orig_color"].append(c)
if score[0] == 1:
test_language_similarity["correct"].append(1)
else:
test_language_similarity["correct"].append(0)
if change_agent == 2:
# The other agent had their message changed
test_language_similarity["originally_correct"].append(correct_1[_])
test_language_similarity["agent_w_changed_msg"].append(1)
else:
test_language_similarity["originally_correct"].append(correct_2[_])
test_language_similarity["agent_w_changed_msg"].append(2)
if ct != c:
test_language_similarity["shape"].append(None)
test_language_similarity["color"].append(ct)
else:
test_language_similarity["shape"].append(st)
test_language_similarity["color"].append(None)
# Track detailed results
example_stats['total_permutations'] += 1
example_stats['subtract']["total"] += 1
example_stats['add']["total"] += 1
if score[0] == 1:
example_stats["subtract"]["correct"] += 1
example_stats["add"]["correct"] += 1
example_stats["correct_permutations"] += 1
if change_agent == 2:
example_stats['originally_correct'] = correct_1[_]
else:
example_stats['originally_correct'] = correct_2[_]
if own_codes_flag:
example_stats['total_own_codes'] += 1
if score[0] == 1:
example_stats['own_correct'] += 1
''' ==========================================================='''
debuglogger.info(f'Detailed stats: {example_stats}')
detail_language_similarity.append(example_stats)
debuglogger.info(f'Total msg changed: {test_language_similarity["total"]}, Correct: {sum(test_language_similarity["correct"])}')
debuglogger.info(f'Eval total size: {total}')
debuglogger.info(f'Eval total correct com: {total_correct_com}')
aggregate_stats = {}
detail_total = 0
detail_orig_correct = 0
detail_total_permutes_not_filtered = 0
detail_own_total_total = 0
detail_own_total = 0
detail_own_total_filt = 0
detail_own_correct = 0
permutes_total = 0
permutes_correct = 0
for elem in detail_language_similarity:
detail_total += 1
detail_total_permutes_not_filtered += elem['total_permutations']
detail_own_total_total += elem['total_own_codes']
if elem["originally_correct"]:
detail_orig_correct += 1
detail_own_total += elem['total_own_codes']
if elem['own_correct'] > 0:
detail_own_total_filt += elem['total_own_codes']
detail_own_correct += elem['own_correct']
permutes_total += elem['total_permutations']
permutes_correct += elem['correct_permutations']
if elem['subtract']['name'] not in aggregate_stats:
aggregate_stats[elem['subtract']['name']] = {'total': 0, 'correct': 0, 'own_correct': 0, 'own_total': 0}
aggregate_stats[elem['subtract']['name']]['total'] += elem['subtract']['total']
aggregate_stats[elem['subtract']['name']]['correct'] += elem['subtract']['correct']
aggregate_stats[elem['subtract']['name']]['own_total'] += elem['total_own_codes']
aggregate_stats[elem['subtract']['name']]['own_correct'] += elem['own_correct']
if elem['add']['name'] not in aggregate_stats:
aggregate_stats[elem['add']['name']] = {'total': 0, 'correct': 0, 'own_correct': 0, 'own_total': 0}
aggregate_stats[elem['add']['name']]['total'] += elem['add']['total']
aggregate_stats[elem['add']['name']]['correct'] += elem['add']['correct']
aggregate_stats[elem['add']['name']]['own_total'] += elem['total_own_codes']
aggregate_stats[elem['add']['name']]['own_correct'] += elem['own_correct']
transform = elem['subtract']['name'] + '_' + elem['add']['name']
if transform not in aggregate_stats:
aggregate_stats[transform] = {'total': 0, 'correct': 0, 'own_correct': 0, 'own_total': 0}
aggregate_stats[transform]['total'] += elem['subtract']['total']
aggregate_stats[transform]['correct'] += elem['subtract']['correct']
aggregate_stats[transform]['own_total'] += elem['total_own_codes']
aggregate_stats[transform]['own_correct'] += elem['own_correct']
# Log detailed stats results
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: Total examples: {detail_total}, orig correct: {detail_orig_correct}, % correct: {detail_orig_correct / detail_total}')
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: Total permutations: {detail_total_permutes_not_filtered}, own_codes: {detail_own_total_total}, % own {detail_own_total_total / detail_total_permutes_not_filtered}')
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: Total own codes: {detail_own_total}, correct own codes: {detail_own_correct}, % correct {detail_own_correct / detail_own_total}')
flogger.Log('Filtering for originally correct examples with at least one permutation with own codes correct...')
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: Permutations total: {permutes_total}, permutations correct: {permutes_correct}, % {permutes_correct / permutes_total}')
norm_total = permutes_total - detail_own_total_filt
norm_correct = permutes_correct - detail_own_correct
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: Normalized total: {norm_total} normalized correct: {norm_correct}, SIMILARITY: {norm_correct / norm_total}')
for key in aggregate_stats:
_total = aggregate_stats[key]['total']
_correct = aggregate_stats[key]['correct']
_own_total = aggregate_stats[key]['own_total']
_own_correct = aggregate_stats[key]['own_correct']
_normalized_total = _total - _own_total
_normalized_correct = _correct - _own_correct
if _total > 0:
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: {key}: total: {_total} correct: {_correct} %: {_correct / _total}')
if _normalized_total > 0:
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: {key}: normalized total: {_normalized_total} normalized correct: {_normalized_correct} SIMILARITY: {_normalized_correct / _normalized_total}')
else:
flogger.Log(f'Agents {a1_idx + 1},{a2_idx + 1}: {key}: normalized total: {_normalized_total} normalized correct: {_normalized_correct} SIMILARITY: {0}')
return test_language_similarity
def eval_dev(dataset_path, top_k, agent1, agent2, logger, flogger, epoch, step, i_batch, in_domain_eval=True, callback=None, store_examples=False, analyze_messages=True, save_messages=False, agent_tag="_", agent_dicts=None, agent_idxs=None, agent_groups=None):
"""
Function computing development accuracy and other metrics
"""
extra = dict()
correct_to_analyze = {"masked_im_1": [],
"masked_im_2": [],
"msg_1": [],
"msg_1_ent": [],
"msg_1_str": [],
"msg_2": [],
"msg_2_ent": [],
"msg_2_str": [],
"probs_1": [],
"probs_2": [],
"p": [],
"target": [],
"caption": [],
"shapes": [],
"colors": [],
"texts": [],
}