This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
test_torch_agent.py
1067 lines (968 loc) · 41.4 KB
/
test_torch_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
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Unit tests for TorchAgent.
"""
import os
import unittest
from parlai.core.agents import create_agent_from_shared
from parlai.utils.testing import tempdir
from parlai.utils.misc import Message
SKIP_TESTS = False
try:
from parlai.core.torch_agent import Output
from parlai.agents.test_agents.test_agents import MockTorchAgent, MockDict
import torch
except ImportError:
SKIP_TESTS = True
def get_agent(**kwargs):
r"""
Return opt-initialized agent.
:param kwargs: any kwargs you want to set using parser.set_params(\*\*kwargs)
"""
if 'no_cuda' not in kwargs:
kwargs['no_cuda'] = True
from parlai.core.params import ParlaiParser
parser = ParlaiParser()
MockTorchAgent.add_cmdline_args(parser, partial_opt=None)
parser.set_params(**kwargs)
opt = parser.parse_args([])
return MockTorchAgent(opt)
@unittest.skipIf(SKIP_TESTS, "Torch not installed.")
class TestTorchAgent(unittest.TestCase):
"""
Basic tests on the util functions in TorchAgent.
"""
def test_mock(self):
"""
Just make sure we can instantiate a mock agent.
"""
agent = get_agent()
self.assertTrue(isinstance(agent.dict, MockDict))
def test_share(self):
"""
Make sure share works and shares dictionary.
"""
agent = get_agent()
shared = agent.share()
self.assertTrue('dict' in shared)
def test__vectorize_text(self):
"""
Test _vectorize_text and its different options.
"""
agent = get_agent()
text = "I'm sorry, Dave"
# test add_start and add_end
vec = agent._vectorize_text(text, add_start=False, add_end=False)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [1, 2, 3])
vec = agent._vectorize_text(text, add_start=True, add_end=False)
self.assertEqual(len(vec), 4)
self.assertEqual(vec.tolist(), [MockDict.BEG_IDX, 1, 2, 3])
vec = agent._vectorize_text(text, add_start=False, add_end=True)
self.assertEqual(len(vec), 4)
self.assertEqual(vec.tolist(), [1, 2, 3, MockDict.END_IDX])
vec = agent._vectorize_text(text, add_start=True, add_end=True)
self.assertEqual(len(vec), 5)
self.assertEqual(vec.tolist(), [MockDict.BEG_IDX, 1, 2, 3, MockDict.END_IDX])
# now do it again with truncation=3
vec = agent._vectorize_text(text, add_start=False, add_end=False, truncate=3)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [1, 2, 3])
vec = agent._vectorize_text(text, add_start=True, add_end=False, truncate=3)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [1, 2, 3])
vec = agent._vectorize_text(text, add_start=False, add_end=True, truncate=3)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [2, 3, MockDict.END_IDX])
vec = agent._vectorize_text(text, add_start=True, add_end=True, truncate=3)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [2, 3, MockDict.END_IDX])
# now do it again with truncation=2
vec = agent._vectorize_text(text, add_start=False, add_end=False, truncate=2)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [2, 3])
vec = agent._vectorize_text(text, add_start=True, add_end=False, truncate=2)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [2, 3])
vec = agent._vectorize_text(text, add_start=False, add_end=True, truncate=2)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [3, MockDict.END_IDX])
vec = agent._vectorize_text(text, add_start=True, add_end=True, truncate=2)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [3, MockDict.END_IDX])
# now do it again with truncation=2, don't truncate_left
vec = agent._vectorize_text(
text, add_start=False, add_end=False, truncate=2, truncate_left=False
)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [1, 2])
vec = agent._vectorize_text(
text, add_start=True, add_end=False, truncate=2, truncate_left=False
)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [MockDict.BEG_IDX, 1])
vec = agent._vectorize_text(
text, add_start=False, add_end=True, truncate=2, truncate_left=False
)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [1, 2])
vec = agent._vectorize_text(
text, add_start=True, add_end=True, truncate=2, truncate_left=False
)
self.assertEqual(len(vec), 2)
self.assertEqual(vec.tolist(), [MockDict.BEG_IDX, 1])
# now do it again with truncation=3, don't truncate_left
vec = agent._vectorize_text(
text, add_start=False, add_end=False, truncate=3, truncate_left=False
)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [1, 2, 3])
vec = agent._vectorize_text(
text, add_start=True, add_end=False, truncate=3, truncate_left=False
)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [MockDict.BEG_IDX, 1, 2])
vec = agent._vectorize_text(
text, add_start=False, add_end=True, truncate=3, truncate_left=False
)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [1, 2, 3])
vec = agent._vectorize_text(
text, add_start=True, add_end=True, truncate=3, truncate_left=False
)
self.assertEqual(len(vec), 3)
self.assertEqual(vec.tolist(), [MockDict.BEG_IDX, 1, 2])
def test__check_truncate(self):
"""
Make sure we are truncating when needed.
"""
agent = get_agent()
inp = torch.LongTensor([1, 2, 3])
self.assertEqual(agent._check_truncate(inp, None).tolist(), [1, 2, 3])
self.assertEqual(agent._check_truncate(inp, 4).tolist(), [1, 2, 3])
self.assertEqual(agent._check_truncate(inp, 3).tolist(), [1, 2, 3])
self.assertEqual(agent._check_truncate(inp, 2).tolist(), [1, 2])
self.assertEqual(agent._check_truncate(inp, 1).tolist(), [1])
self.assertEqual(agent._check_truncate(inp, 0).tolist(), [])
def test_vectorize(self):
"""
Test the vectorization of observations.
Make sure they do not recompute results, and respect the different param
options.
"""
agent = get_agent()
obs_labs = Message(
{'text': 'No. Try not.', 'labels': ['Do.', 'Do not.'], 'episode_done': True}
)
obs_elabs = Message(
{
'text': 'No. Try not.',
'eval_labels': ['Do.', 'Do not.'],
'episode_done': True,
}
)
for obs in (obs_labs, obs_elabs):
lab_key = 'labels' if 'labels' in obs else 'eval_labels'
lab_vec = lab_key + '_vec'
lab_chc = lab_key + '_choice'
inp = obs.copy()
# test add_start=True, add_end=True
agent.history.reset()
agent.history.update_history(inp)
out = agent.vectorize(inp, agent.history, add_start=True, add_end=True)
self.assertEqual(out['text_vec'].tolist(), [1, 2, 3])
# note that label could be either label above
self.assertEqual(out[lab_vec][0].item(), MockDict.BEG_IDX)
self.assertEqual(out[lab_vec][1].item(), 1)
self.assertEqual(out[lab_vec][-1].item(), MockDict.END_IDX)
self.assertEqual(out[lab_chc][:2], 'Do')
# test add_start=True, add_end=False
inp = obs.copy()
out = agent.vectorize(inp, agent.history, add_start=True, add_end=False)
self.assertEqual(out['text_vec'].tolist(), [1, 2, 3])
# note that label could be either label above
self.assertEqual(out[lab_vec][0].item(), MockDict.BEG_IDX)
self.assertNotEqual(out[lab_vec][-1].item(), MockDict.END_IDX)
self.assertEqual(out[lab_chc][:2], 'Do')
# test add_start=False, add_end=True
inp = obs.copy()
out = agent.vectorize(inp, agent.history, add_start=False, add_end=True)
self.assertEqual(out['text_vec'].tolist(), [1, 2, 3])
# note that label could be either label above
self.assertNotEqual(out[lab_vec][0].item(), MockDict.BEG_IDX)
self.assertEqual(out[lab_vec][-1].item(), MockDict.END_IDX)
self.assertEqual(out[lab_chc][:2], 'Do')
# test add_start=False, add_end=False
inp = obs.copy()
out = agent.vectorize(inp, agent.history, add_start=False, add_end=False)
self.assertEqual(out['text_vec'].tolist(), [1, 2, 3])
# note that label could be either label above
self.assertNotEqual(out[lab_vec][0].item(), MockDict.BEG_IDX)
self.assertNotEqual(out[lab_vec][-1].item(), MockDict.END_IDX)
self.assertEqual(out[lab_chc][:2], 'Do')
# test caching of tensors
out_again = agent.vectorize(out, agent.history)
# should have cached result from before
self.assertIs(out['text_vec'], out_again['text_vec'])
self.assertEqual(out['text_vec'].tolist(), [1, 2, 3])
# next: should truncate cached result
prev_vec = out['text_vec']
out_again = agent.vectorize(out, agent.history, text_truncate=1)
self.assertIsNot(prev_vec, out_again['text_vec'])
self.assertEqual(out['text_vec'].tolist(), [3])
# test split_lines
agent = get_agent(split_lines=True)
obs = Message(
{
'text': 'Hello.\nMy name is Inogo Montoya.\n'
'You killed my father.\nPrepare to die.',
'episode_done': True,
}
)
agent.history.update_history(obs)
vecs = agent.history.get_history_vec_list()
self.assertEqual(vecs, [[1], [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3]])
# check cache
out_again = agent.vectorize(obs, agent.history)
vecs = agent.history.get_history_vec_list()
self.assertEqual(vecs, [[1], [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3]])
def test_batchify(self):
"""
Make sure the batchify function sets up the right fields.
"""
agent = get_agent(rank_candidates=True)
obs_labs = [
Message(
{
'text': 'It\'s only a flesh wound.',
'labels': ['Yield!'],
'episode_done': True,
}
),
Message(
{
'text': 'The needs of the many outweigh...',
'labels': ['The needs of the few.'],
'episode_done': True,
}
),
Message(
{
'text': 'Hello there.',
'labels': ['General Kenobi.'],
'episode_done': True,
}
),
]
obs_elabs = [
Message(
{
'text': 'It\'s only a flesh wound.',
'eval_labels': ['Yield!'],
'episode_done': True,
}
),
Message(
{
'text': 'The needs of the many outweigh...',
'eval_labels': ['The needs of the few.'],
'episode_done': True,
}
),
Message(
{
'text': 'Hello there.',
'eval_labels': ['General Kenobi.'],
'episode_done': True,
}
),
]
for obs_batch in (obs_labs, obs_elabs):
lab_key = 'labels' if 'labels' in obs_batch[0] else 'eval_labels'
# nothing has been vectorized yet so should be empty
batch = agent.batchify(obs_batch)
self.assertIsNone(batch.text_vec)
self.assertIsNone(batch.text_lengths)
self.assertIsNone(batch.label_vec)
self.assertIsNone(batch.label_lengths)
self.assertIsNone(batch.labels)
self.assertIsNone(batch.candidates)
self.assertIsNone(batch.candidate_vecs)
self.assertIsNone(batch.image)
obs_vecs = []
for o in obs_batch:
agent.history.reset()
agent.history.update_history(o)
obs_vecs.append(
agent.vectorize(o, agent.history, add_start=False, add_end=False)
)
# is_valid should map to nothing
def is_valid(obs):
return False
agent.is_valid = is_valid
batch = agent.batchify(obs_batch)
self.assertIsNone(batch.text_vec)
self.assertIsNone(batch.text_lengths)
self.assertIsNone(batch.label_vec)
self.assertIsNone(batch.label_lengths)
self.assertIsNone(batch.labels)
self.assertIsNone(batch.candidates)
self.assertIsNone(batch.candidate_vecs)
self.assertIsNone(batch.image)
# is_valid should check for text_vec
def is_valid(obs):
return 'text_vec' in obs
agent.is_valid = is_valid
batch = agent.batchify(obs_vecs)
# which fields were filled vs should be empty?
self.assertIsNotNone(batch.text_vec)
self.assertIsNotNone(batch.text_lengths)
self.assertIsNotNone(batch.label_vec)
self.assertIsNotNone(batch.label_lengths)
self.assertIsNotNone(batch.labels)
self.assertIsNone(batch.candidates)
self.assertIsNone(batch.candidate_vecs)
self.assertIsNone(batch.image)
# contents of certain fields:
self.assertEqual(
batch.text_vec.tolist(),
[[1, 2, 3, 4, 5, 0], [1, 2, 3, 4, 5, 6], [1, 2, 0, 0, 0, 0]],
)
self.assertEqual(batch.text_lengths, [5, 6, 2])
self.assertEqual(
batch.label_vec.tolist(),
[[1, 0, 0, 0, 0], [1, 2, 3, 4, 5], [1, 2, 0, 0, 0]],
)
self.assertEqual(batch.label_lengths, [1, 5, 2])
self.assertEqual(batch.labels, [o[lab_key][0] for o in obs_batch])
self.assertEqual(list(batch.valid_indices), [0, 1, 2])
# now sort the batch, make sure fields are in sorted order
batch = agent.batchify(obs_vecs, sort=True)
self.assertEqual(
batch.text_vec.tolist(),
[[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 0], [1, 2, 0, 0, 0, 0]],
)
self.assertEqual(batch.text_lengths, [6, 5, 2])
self.assertEqual(
batch.label_vec.tolist(),
[[1, 2, 3, 4, 5], [1, 0, 0, 0, 0], [1, 2, 0, 0, 0]],
)
self.assertEqual(batch.label_lengths, [5, 1, 2])
labs = [o[lab_key][0] for o in obs_batch]
self.assertEqual(batch.labels, [labs[i] for i in [1, 0, 2]])
self.assertEqual(list(batch.valid_indices), [1, 0, 2])
# now sort just on ys
new_vecs = [vecs.copy() for vecs in obs_vecs]
for vec in new_vecs:
vec.pop('text')
vec.pop('text_vec')
def is_valid(obs):
return 'labels_vec' in obs or 'eval_labels_vec' in obs
agent.is_valid = is_valid
batch = agent.batchify(new_vecs, sort=True)
self.assertIsNone(batch.text_vec)
self.assertIsNone(batch.text_lengths)
self.assertIsNotNone(batch.label_vec)
self.assertIsNotNone(batch.label_lengths)
self.assertEqual(
batch.label_vec.tolist(),
[[1, 2, 3, 4, 5], [1, 2, 0, 0, 0], [1, 0, 0, 0, 0]],
)
self.assertEqual(batch.label_lengths, [5, 2, 1])
labs = [o[lab_key][0] for o in new_vecs]
self.assertEqual(batch.labels, [labs[i] for i in [1, 2, 0]])
self.assertEqual(list(batch.valid_indices), [1, 2, 0])
# test is_valid
def is_valid(obs):
return 'text_vec' in obs and len(obs['text_vec']) < 3
agent.is_valid = is_valid
batch = agent.batchify(obs_vecs)
self.assertEqual(batch.text_vec.tolist(), [[1, 2]])
self.assertEqual(batch.text_lengths, [2])
self.assertEqual(batch.label_vec.tolist(), [[1, 2]])
self.assertEqual(batch.label_lengths, [2])
self.assertEqual(batch.labels, obs_batch[2][lab_key])
self.assertEqual(list(batch.valid_indices), [2])
agent.history.reset()
obs_cands = [
agent.vectorize(
Message({'label_candidates': ['A', 'B', 'C']}), agent.history
),
agent.vectorize(
Message({'label_candidates': ['1', '2', '5', '3', 'Sir']}),
agent.history,
),
agent.vectorize(
Message({'label_candidates': ['Do', 'Re', 'Mi']}), agent.history
),
agent.vectorize(
Message({'label_candidates': ['Fa', 'So', 'La', 'Ti']}), agent.history
),
]
# is_valid should check for label candidates vecs
def is_valid(obs):
return 'label_candidates_vecs' in obs
agent.is_valid = is_valid
batch = agent.batchify(obs_cands)
self.assertTrue(agent.rank_candidates, 'Agent not set up to rank.')
self.assertIsNone(batch.text_vec)
self.assertIsNone(batch.text_lengths)
self.assertIsNone(batch.label_vec)
self.assertIsNone(batch.label_lengths)
self.assertIsNone(batch.labels)
self.assertIsNotNone(batch.valid_indices)
self.assertIsNotNone(batch.candidates)
self.assertIsNotNone(batch.candidate_vecs)
self.assertEqual(list(batch.valid_indices), [0, 1, 2, 3])
self.assertEqual(batch.candidates, [o['label_candidates'] for o in obs_cands])
self.assertEqual(len(batch.candidate_vecs), len(obs_cands))
for i, cs in enumerate(batch.candidate_vecs):
self.assertEqual(len(cs), len(obs_cands[i]['label_candidates']))
def test_match_batch(self):
"""
Make sure predictions are correctly aligned when available.
"""
agent = get_agent()
# first try empty outputs
reply = agent.match_batch([{}, {}, {}], [0, 1, 2], Output())
self.assertEqual([{}, {}, {}], reply)
reply = agent.match_batch([{}, {}, {}], [0, 1, 2], None)
self.assertEqual([{}, {}, {}], reply)
# try text in order
reply = agent.match_batch(
[{}, {}, {}], [0, 1, 2], Output(['E.T.', 'Phone', 'Home'])
)
self.assertEqual([{'text': 'E.T.'}, {'text': 'Phone'}, {'text': 'Home'}], reply)
# try text out of order
reply = agent.match_batch(
[{}, {}, {}], [2, 0, 1], Output(['Home', 'E.T.', 'Phone'])
)
self.assertEqual([{'text': 'E.T.'}, {'text': 'Phone'}, {'text': 'Home'}], reply)
# try text_candidates in order
reply = agent.match_batch(
[{}, {}],
[0, 1],
Output(
None,
[
['More human than human.', 'Less human than human'],
['Just walk into Mordor', 'Just QWOP into Mordor.'],
],
),
)
self.assertEqual(
reply[0]['text_candidates'],
['More human than human.', 'Less human than human'],
)
self.assertEqual(
reply[1]['text_candidates'],
['Just walk into Mordor', 'Just QWOP into Mordor.'],
)
# try text_candidates out of order
reply = agent.match_batch(
[{}, {}],
[1, 0],
Output(
None,
[
['More human than human.', 'Less human than human'],
['Just walk into Mordor', 'Just QWOP into Mordor.'],
],
),
)
self.assertEqual(
reply[0]['text_candidates'],
['Just walk into Mordor', 'Just QWOP into Mordor.'],
)
self.assertEqual(
reply[1]['text_candidates'],
['More human than human.', 'Less human than human'],
)
# try both text and text_candidates in order
reply = agent.match_batch(
[{}, {}],
[0, 1],
Output(
['You shall be avenged...', 'Man creates dinosaurs...'],
[
['By Grabthar’s hammer.', 'By the suns of Worvan.'],
['Dinosaurs eat man.', 'Woman inherits the earth.'],
],
),
)
self.assertEqual(reply[0]['text'], 'You shall be avenged...')
self.assertEqual(
reply[0]['text_candidates'],
['By Grabthar’s hammer.', 'By the suns of Worvan.'],
)
self.assertEqual(reply[1]['text'], 'Man creates dinosaurs...')
self.assertEqual(
reply[1]['text_candidates'],
['Dinosaurs eat man.', 'Woman inherits the earth.'],
)
# try both text and text_candidates out of order
reply = agent.match_batch(
[{}, {}],
[1, 0],
Output(
['You shall be avenged...', 'Man creates dinosaurs...'],
[
['By Grabthar’s hammer.', 'By the suns of Worvan.'],
['Dinosaurs eat man.', 'Woman inherits the earth.'],
],
),
)
self.assertEqual(reply[0]['text'], 'Man creates dinosaurs...')
self.assertEqual(
reply[0]['text_candidates'],
['Dinosaurs eat man.', 'Woman inherits the earth.'],
)
self.assertEqual(reply[1]['text'], 'You shall be avenged...')
self.assertEqual(
reply[1]['text_candidates'],
['By Grabthar’s hammer.', 'By the suns of Worvan.'],
)
def test__add_person_tokens(self):
"""
Make sure person tokens are added to the write place in text.
"""
agent = get_agent()
text = (
"I've seen things you people wouldn't believe.\n"
"Attack ships on fire off the shoulder of Orion.\n"
"I watched C-beams glitter in the dark near the Tannhauser gate.\n"
"All those moments will be lost in time, like tears in rain."
)
prefix = 'PRE'
out = agent.history._add_person_tokens(text, prefix, add_after_newln=False)
self.assertEqual(out, prefix + ' ' + text)
out = agent.history._add_person_tokens(text, prefix, add_after_newln=True)
idx = text.rfind('\n') + 1
self.assertEqual(out, text[:idx] + prefix + ' ' + text[idx:])
def test_history(self):
"""
Test different dialog history settings.
"""
# try with unlimited history
agent = get_agent(history_size=-1)
obs = {'text': 'I am Groot.', 'labels': ['I am Groot?'], 'episode_done': False}
# first exchange
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.')
# second exchange, no reply
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.\nI am Groot.')
# include reply
agent.history.add_reply('I am Groot?')
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.\nI am Groot.\nI am Groot?\nI am Groot.')
# on reset should be same as first exchange
agent.history.reset()
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.')
# now try with history size = 1
agent = get_agent(history_size=1)
# first exchange
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.')
# second exchange should change nothing
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.')
# third exchange with reply should change nothing
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.')
# now if we add the reply, we should only have the reply left
agent.history.add_reply(obs['labels'][0])
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot?')
# now try with history size = 2
agent = get_agent(history_size=2)
# first exchange
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.')
# second exchange with reply should contain reply
agent.history.add_reply('I am Groot?')
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot?\nI am Groot.')
# now try with history size = 3
agent = get_agent(history_size=3)
# first exchange
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.')
# second exchange with reply should contain reply and input
agent.history.add_reply('I am Groot?')
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.\nI am Groot?\nI am Groot.')
# now test add_person_tokens
agent = get_agent(history_size=3, person_tokens=True)
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, '{} I am Groot.'.format(agent.P1_TOKEN))
# second exchange, history should still contain the tokens
agent.history.add_reply('I am Groot?')
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(
text,
'{} I am Groot.\n{} I am Groot?\n{} I am Groot.'.format(
agent.P1_TOKEN, agent.P2_TOKEN, agent.P1_TOKEN
),
)
# now add add_p1_after_newln
agent = get_agent(history_size=3, person_tokens=True, add_p1_after_newln=True)
ctx_obs = obs.copy() # context then utterance in this text field
ctx_obs['text'] = 'Groot is Groot.\nI am Groot.'
agent.history.update_history(ctx_obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'Groot is Groot.\n{} I am Groot.'.format(agent.P1_TOKEN))
# second exchange, history should still contain context text
agent.history.add_reply('I am Groot?')
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(
text,
'Groot is Groot.\n{} I am Groot.\n{} I am Groot?\n{} I am Groot.'.format(
agent.P1_TOKEN, agent.P2_TOKEN, agent.P1_TOKEN
),
)
# test history vecs
agent.history.reset()
agent.history.update_history(obs)
vec = agent.history.get_history_vec()
self.assertEqual(vec, [2001, 1, 2, 3])
# test history vec list
agent.history.update_history(obs)
vecs = agent.history.get_history_vec_list()
self.assertEqual(vecs, [[2001, 1, 2, 3], [2001, 1, 2, 3]])
# test clearing history
agent.history.reset()
text = agent.history.get_history_str()
self.assertIsNone(text)
vecs = agent.history.get_history_vec_list()
self.assertEqual(vecs, [])
# test delimiter
agent = get_agent(history_size=-1, delimiter=' Groot! ')
agent.history.update_history(obs)
agent.history.update_history(obs)
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot. Groot! I am Groot.')
# test global_end_token, this will append a selected token to the end
# of history block
agent = get_agent(history_add_global_end_token='end')
agent.history.reset()
agent.history.update_history(obs)
vec = agent.history.get_history_vec()
self.assertEqual(vec, [1, 2, 3, MockDict.END_IDX])
# test temp history
agent = get_agent(
history_size=-1, include_temp_history=True, delimiter='__delim__'
)
agent.history.reset()
agent.history.update_history(obs, temp_history=' temp history')
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot. temp history')
vec = agent.history.get_history_vec()
self.assertEqual(vec, [1, 2, 3, 1, 2])
agent.history.update_history(obs, temp_history=' temp history')
text = agent.history.get_history_str()
self.assertEqual(text, 'I am Groot.__delim__I am Groot. temp history')
vecs = agent.history.get_history_vec_list()
self.assertEqual(vecs, [[1, 2, 3], [1, 2, 3]])
vec = agent.history.get_history_vec()
self.assertEqual(vec, [1, 2, 3, 1, 1, 2, 3, 1, 2])
def test_reversed_history(self):
agent = get_agent(history_reversed=True)
agent.history.reset()
agent.history.update_history({'text': 'hello i am stephen'})
agent.history.update_history({'text': 'i am bob'})
assert agent.history.get_history_str() == 'hello i am stephen\ni am bob'
agent.history.reset()
agent.history.update_history(
{'text': 'your persona: filler\nhello i am stephen'}
)
agent.history.update_history({'text': 'i am bob'})
assert (
agent.history.get_history_str()
== 'your persona: filler\nhello i am stephen\ni am bob'
)
def test_observe(self):
"""
Make sure agent stores and returns observation.
"""
agent = get_agent()
# text could be none
obs = {'text': None, 'episode_done': True}
out = agent.observe(obs.copy())
self.assertIsNotNone(out)
# make sure we throw an exception for having an episode done without a reset
obs = {'text': "I'll be back.", 'labels': ["I'm back."], 'episode_done': True}
with self.assertRaises(RuntimeError):
agent.observe(obs.copy())
# okay, let's do it properly now
agent.reset()
obs = {'text': "I'll be back.", 'labels': ["I'm back."], 'episode_done': True}
out = agent.observe(obs.copy())
self.assertIsNotNone(out)
self.assertIsNotNone(agent.observation)
self.assertEqual(out['text'], "I'll be back.")
# now try with episode not done
agent = get_agent()
obs['episode_done'] = False
out = agent.observe(obs.copy())
self.assertIsNotNone(out)
self.assertIsNotNone(agent.observation)
self.assertEqual(out['text'], "I'll be back.")
# should remember history
agent.act()
out = agent.observe(obs.copy())
self.assertEqual(out['full_text'], "I'll be back.\nI'm back.\nI'll be back.")
def test_batch_act(self):
"""
Make sure batch act calls the right step.
"""
agent = get_agent()
obs_labs = [
Message(
{
'text': "It's only a flesh wound.",
'labels': ['Yield!'],
'episode_done': True,
}
),
Message(
{
'text': 'The needs of the many outweigh...',
'labels': ['The needs of the few.'],
'episode_done': True,
}
),
Message(
{
'text': 'Hello there.',
'labels': ['General Kenobi.'],
'episode_done': True,
}
),
]
obs_labs_vecs = []
for o in obs_labs:
agent.history.reset()
agent.history.update_history(o)
obs_labs_vecs.append(agent.vectorize(o, agent.history))
reply = agent.batch_act(obs_labs_vecs)
for i in range(len(obs_labs_vecs)):
self.assertEqual(reply[i]['text'], 'Training {}!'.format(i))
obs_elabs = [
Message(
{
'text': "It's only a flesh wound.",
'eval_labels': ['Yield!'],
'episode_done': True,
}
),
Message(
{
'text': 'The needs of the many outweigh...',
'eval_labels': ['The needs of the few.'],
'episode_done': True,
}
),
Message(
{
'text': 'Hello there.',
'eval_labels': ['General Kenobi.'],
'episode_done': True,
}
),
]
obs_elabs_vecs = []
for o in obs_elabs:
agent.history.reset()
agent.history.update_history(o)
obs_elabs_vecs.append(agent.vectorize(o, agent.history))
reply = agent.batch_act(obs_elabs_vecs)
for i in range(len(obs_elabs_vecs)):
self.assertIn('Evaluating {}'.format(i), reply[i]['text'])
def test_interactive_mode(self):
"""
Test if conversation history is destroyed in MTurk mode.
"""
# both manually setting bs to 1 and interactive mode true
agent = get_agent(batchsize=1, interactive_mode=True)
agent.observe(Message({'text': 'foo', 'episode_done': True}))
response = agent.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
shared = create_agent_from_shared(agent.share())
shared.observe(Message({'text': 'bar', 'episode_done': True}))
response = shared.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
# now just bs 1
agent = get_agent(batchsize=1, interactive_mode=False)
agent.observe(Message({'text': 'foo', 'episode_done': True}))
response = agent.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
shared = create_agent_from_shared(agent.share())
shared.observe(Message({'text': 'bar', 'episode_done': True}))
response = shared.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
# now just interactive
shared = create_agent_from_shared(agent.share())
agent.observe(Message({'text': 'foo', 'episode_done': True}))
response = agent.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
shared = create_agent_from_shared(agent.share())
shared.observe(Message({'text': 'bar', 'episode_done': True}))
response = shared.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
# finally, actively attempt to sabotage
agent = get_agent(batchsize=16, interactive_mode=False)
agent.observe(Message({'text': 'foo', 'episode_done': True}))
response = agent.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
shared = create_agent_from_shared(agent.share())
shared.observe(Message({'text': 'bar', 'episode_done': True}))
response = shared.act()
self.assertIn(
'Evaluating 0', response['text'], 'Incorrect output in single act()'
)
def test_use_reply(self):
"""
Check that self-observe is correctly acting on labels.
"""
# default is hybrid label-model, which uses the label if it's available, and
# otherwise the label
# first check if there is a label available
agent = get_agent()
obs = Message({'text': 'Call', 'labels': ['Response'], 'episode_done': False})
agent.observe(obs)
_ = agent.act()
self.assertEqual(agent.history.get_history_str(), 'Call\nResponse')
# check if there is no label
agent.reset()
obs = Message({'text': 'Call', 'episode_done': False})
agent.observe(obs)
_ = agent.act()
self.assertEqual(
agent.history.get_history_str(), 'Call\nEvaluating 0 (responding to Call)!'
)
# now some of the other possible values of --use-reply
# --use-reply model. even if there is a label, we should see the model's out
agent = get_agent(use_reply='model')
obs = Message({'text': 'Call', 'labels': ['Response'], 'episode_done': False})
agent.observe(obs)
_ = agent.act()
self.assertEqual(agent.history.get_history_str(), 'Call\nTraining 0!')
# --use-reply none doesn't hear itself
agent = get_agent(use_reply='none')
obs = Message({'text': 'Call', 'labels': ['Response'], 'episode_done': False})
agent.observe(obs)
agent.act()
self.assertEqual(agent.history.get_history_str(), 'Call')
def test_mturk_racehistory(self):
"""
Emulate a setting where batch_act misappropriately handles mturk.
"""
agent = get_agent(batchsize=16, interactive_mode=True, echo=True)
share1 = create_agent_from_shared(agent.share())
share1.observe(Message({'text': 'thread1-msg1', 'episode_done': False}))
share2 = create_agent_from_shared(agent.share())
share2.observe(Message({'text': 'thread2-msg1', 'episode_done': False}))
share1.act()
share2.act()
share1.observe(Message({'text': 'thread1-msg2', 'episode_done': False}))
share2.observe(Message({'text': 'thread2-msg2', 'episode_done': False}))
share2.act()
share1.act()
share2.observe(Message({'text': 'thread2-msg3', 'episode_done': False}))
share1.observe(Message({'text': 'thread1-msg3', 'episode_done': False}))
self.assertNotIn('thread1-msg1', share2.history.get_history_str())
self.assertNotIn('thread2-msg1', share1.history.get_history_str())