-
Notifications
You must be signed in to change notification settings - Fork 767
/
Copy pathpreprocessors_test.py
2104 lines (1911 loc) · 71.2 KB
/
preprocessors_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021 The T5 Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for from t5.preprocessors."""
import functools
from absl.testing import absltest
import gin
import seqio
from seqio import test_utils
from t5.data import preprocessors as prep
import tensorflow.compat.v2 as tf
tf.compat.v1.enable_eager_execution()
mock = absltest.mock
assert_dataset = test_utils.assert_dataset
class PreprocessorsTest(tf.test.TestCase):
def test_regular_noise_mask(self):
length = 800
span_length = 2
noise_density = 0.25
noise_mask = prep.regular_noise_mask(
length=length,
noise_density=noise_density,
seeds=[(0, 1), (2, 3)],
min_span_length=span_length,
max_span_length=span_length)
num_masked = tf.reduce_sum(tf.cast(noise_mask, tf.int32))
self.assertEqual(self.evaluate(num_masked), length * noise_density)
def test_random_prefix_noise_mask(self):
for _ in range(100):
length = 10
noise_density = 0.5
noise_mask = prep.random_prefix_noise_mask(
length=length,
noise_density=noise_density,
seeds=[(0, 1)])
first = noise_mask[0]
last = noise_mask[-1]
self.assertTrue(self.evaluate(first))
self.assertFalse(self.evaluate(last))
def test_random_spans_helper(self):
input_length = 64
noise_density = 0.20
mean_noise_span_lengths = [2.0, 1.0]
expected_outputs = [(70, 22), (63, 27)]
for mean_length, expected_output in zip(mean_noise_span_lengths,
expected_outputs):
output = prep.random_spans_helper(input_length, noise_density,
mean_length, 1, 1)
self.assertAllEqual(output, expected_output)
def test_random_spans_noise_mask(self):
length = 32
noise_density = 0.25
mean_noise_span_length = 2.0
# there should be 4 noise spans with a total length of 8.
noise_mask = prep.random_spans_noise_mask(
length, noise_density, [(1, 2), (3, 4)], mean_noise_span_length)
output = self.evaluate(tf.cast(noise_mask, tf.int32))
expected_output = [
0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1]
self.assertAllEqual(output, expected_output)
def test_noise_token_to_sentinel(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [999, 999, 12, 13, 999, 15]
output = self.evaluate(prep.noise_token_to_sentinel(
tokens, noise_mask, vocabulary, ()))
self.assertAllEqual(output, expected_output)
def test_noise_span_to_sentinel(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [999, 12, 13, 999, 15]
output = self.evaluate(prep.noise_span_to_sentinel(
tokens, noise_mask, vocabulary, ()))
self.assertAllEqual(output, expected_output)
def test_nonnoise_span_to_sentinel(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [10, 11, 999, 14, 999]
output = self.evaluate(prep.nonnoise_span_to_sentinel(
tokens, noise_mask, vocabulary, ()))
self.assertAllEqual(output, expected_output)
def test_noise_span_to_unique_sentinel(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [999, 12, 13, 998, 15]
output = self.evaluate(prep.noise_span_to_unique_sentinel(
tokens, noise_mask, vocabulary, ()))
self.assertAllEqual(output, expected_output)
def test_drop_noise_tokens(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [12, 13, 15]
output = self.evaluate(prep.drop_noise_tokens(
tokens, noise_mask, vocabulary, ()))
self.assertAllEqual(output, expected_output)
def test_drop_nonnoise_tokens(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [10, 11, 14]
output = self.evaluate(prep.drop_nonnoise_tokens(
tokens, noise_mask, vocabulary, ()))
self.assertAllEqual(output, expected_output)
def test_permute_noise_tokens(self):
tf.random.set_seed(55)
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [10, 14, 12, 13, 11, 15]
output = self.evaluate(prep.permute_noise_tokens(
tokens, noise_mask, vocabulary, [(0, 1)]))
self.assertAllEqual(output, expected_output)
tf.random.set_seed(None)
def test_noise_token_to_gathered_token(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [13, 14, 12, 13, 10, 15]
output = self.evaluate(prep.noise_token_to_gathered_token(
tokens, noise_mask, vocabulary, [(55, 56)]))
self.assertAllEqual(output, expected_output)
def test_noise_token_to_random_token(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant([10, 11, 12, 13, 14, 15])
noise_mask = tf.constant([True, True, False, False, True, False])
expected_output = [961, 553, 12, 13, 60, 15]
output = self.evaluate(prep.noise_token_to_random_token(
tokens, noise_mask, vocabulary, seeds=[(55, 56)]))
self.assertAllEqual(output, expected_output)
def test_noise_token_to_random_token_or_sentinel(self):
vocabulary = test_utils.MockVocabulary({'foo': [10]}, vocab_size=1000)
tokens = tf.constant(list(range(10)))
noise_mask = tf.constant(
[True, True, False, False, True, False, True, True, True, True])
expected_output = [999, 348, 2, 3, 108, 5, 999, 999, 999, 999]
output = self.evaluate(prep.noise_token_to_random_token_or_sentinel(
tokens, noise_mask, vocabulary,
seeds=[(55, 56), (57, 58)], random_prob=0.2))
self.assertAllEqual(output, expected_output)
def test_translate(self):
og_dataset = tf.data.Dataset.from_tensor_slices(
{'en': ['That is good.'], 'de': ['Das ist gut.']}
)
dataset = prep.translate(og_dataset, 'en', 'de')
assert_dataset(
dataset,
{
'inputs': 'translate English to German: That is good.',
'targets': 'Das ist gut.',
}
)
def test_summarize(self):
og_dataset = tf.data.Dataset.from_tensor_slices(
{'article': ['An article.'], 'highlights': ['A summary.']}
)
dataset = prep.summarize(og_dataset, 'article', 'highlights')
assert_dataset(
dataset,
{'inputs': 'summarize: An article.', 'targets': 'A summary.'},
)
def assertStringEqual(self, a, b):
self.assertTrue(tf.equal(a, b), '%s != %s' % (a, b))
def test_pad_punctuation(self):
self.assertStringEqual(
' " This is a string with " punctuation ( 1845 - 1986 ) " . ',
prep._pad_punctuation(
'"This is a string with "punctuation (1845-1986) ".'))
def test_span_answer(self):
self.assertStringEqual(
'start: 2 end: 3',
prep._span_answer(tf.constant('Called the Denver Broncos.'),
tf.constant('Denver Broncos')))
# Not found.
self.assertStringEqual(
'',
prep._span_answer(tf.constant('Called the Denver Broncos.'),
tf.constant('Denver Bronscos')))
def test_squad(self):
og_dataset = tf.data.Dataset.from_tensors({
'id': 'testid',
'context': 'Some context.',
'question': 'A question?',
'answers': {
'text': ['The answer.', 'Another answer.'],
}
})
dataset = prep.squad(og_dataset)
assert_dataset(
dataset, {
'id': 'testid',
'inputs': 'question: A question ? context: Some context . ',
'targets': 'The answer . ',
'context': 'Some context . ',
'question': 'A question ? ',
'answers': ['The answer . ', 'Another answer . '],
})
def test_pad_nonspaced_languages(self):
dataset = tf.data.Dataset.from_tensor_slices(
{'text': ['Hello there. 你好吗?']})
dataset = prep.pad_nonspaced_languages(dataset)
assert_dataset(
dataset,
{
'text': 'Hello there. 你 好 吗 ?',
})
def test_triviaqa(self):
answers = ['key', 'keys']
contexts = [
'The answer to all questions is the key.',
'The answer to all questions are the keys.'
]
og_dataset = tf.data.Dataset.from_tensors(
{
'question': 'What is the answer?',
'entity_pages': {
'wiki_context': contexts
},
'answer': {
'normalized_aliases': answers,
'normalized_value': 'key'
}
}
)
dataset = prep.trivia_qa(og_dataset)
assert_dataset(dataset, [{
'inputs':
'question: What is the answer ? context: The answer to all questions is the key . ',
'targets':
'key'
}, {
'inputs':
'question: What is the answer ? context: The answer to all questions are the keys . ',
'targets':
'key'
}, {
'inputs':
'question: What is the answer ? context: The answer to all questions are the keys . ',
'targets':
'keys'
}])
def test_squad_span_space_tokenized(self):
answers = ['the answer', 'answer']
d = tf.data.Dataset.from_tensors(
{
'id': 'a',
'context': 'context with the answer.',
'question': 'Say what?',
'answers': {
'text': answers,
},
},)
og_dataset = d.concatenate(
tf.data.Dataset.from_tensors(
{ # Filter this out because answer is not in context.
'id': 'b',
'context': 'context without answers.',
'question': 'Say what?',
'answers': {
'text': answers,
}
}))
dataset = prep.squad_span_space_tokenized(og_dataset)
assert_dataset(
dataset, {
'id':
'a',
'inputs':
'question: Say what ? context: context with the answer . ',
'targets':
'start: 2 end: 3',
'context':
'context with the answer . ',
'question':
'Say what ? ',
'answers':
answers,
})
def test_glue(self):
test_idx = 10
input_data = {
'q1': 'How so?',
'q2': 'Why not?',
'q3': 'Who?',
'idx': test_idx,
'label': 0,
}
og_dataset = tf.data.Dataset.from_tensors(input_data)
benchmark_name = 'qqp'
label_names = ['not_duplicate', 'duplicate']
dataset = prep.glue(og_dataset, benchmark_name, label_names)
assert_dataset(
dataset,
{
'inputs': 'qqp q1: How so? q2: Why not? q3: Who?',
'targets': 'not_duplicate',
'idx': test_idx,
},
)
# Test `feature_names` argument.
dataset = prep.glue(
og_dataset, benchmark_name, label_names, feature_names=['q3', 'q1'])
assert_dataset(
dataset,
{
'inputs': 'qqp q3: Who? q1: How so?',
'targets': 'not_duplicate',
'idx': test_idx,
},
)
# Test target is <unk> when label is -1
input_data['label'] = -1
og_dataset = tf.data.Dataset.from_tensors(input_data)
dataset = prep.glue(og_dataset, benchmark_name, label_names)
assert_dataset(
dataset,
{
'inputs': 'qqp q1: How so? q2: Why not? q3: Who?',
'targets': '<unk>',
'idx': test_idx,
},
)
# Test id_key argument
input_data = {
'q1': 'How so?',
'q2': 'Why not?',
'q3': 'Who?',
'uid': test_idx,
'label': 0,
}
og_dataset = tf.data.Dataset.from_tensors(input_data)
dataset = prep.glue(og_dataset, benchmark_name, label_names,
feature_names=['q1', 'q2', 'q3'], id_key='uid')
assert_dataset(
dataset,
{
'inputs': 'qqp q1: How so? q2: Why not? q3: Who?',
'targets': 'not_duplicate',
'idx': test_idx,
},
)
def test_multirc(self):
og_dataset = tf.data.Dataset.from_tensors({
'paragraph':
'<b>Sent 1: </b>Once upon a time, there was a squirrel named Joey.<br><b>Sent 2: </b>Joey loved to go outside and play with his cousin Jimmy.',
'question':
'Why was Joey surprised the morning he woke up for breakfast?',
'answer':
'There was only pie to eat',
'label': 1,
'idx': {
'paragraph': 5,
'question': 1,
'answer': 3
}
})
dataset = prep.glue(
og_dataset,
'multirc',
label_names=['False', 'True'],
feature_names=('question', 'answer', 'paragraph'),
)
assert_dataset(
dataset,
{
'inputs':
'multirc question: Why was Joey surprised the morning he woke up for breakfast? answer: There was only pie to eat paragraph: Sent 1: Once upon a time, there was a squirrel named Joey. Sent 2: Joey loved to go outside and play with his cousin Jimmy.',
'targets': 'True',
'idx/paragraph': 5,
'idx/question': 1,
'idx/answer': 3,
},
)
def test_stsb(self):
test_idx = 10
og_dataset = tf.data.Dataset.from_tensors(
{
'sentence1': ['Big news.'],
'sentence2': ['No idea.'],
'label': [2.8],
'idx': test_idx,
},
)
dataset = prep.stsb(og_dataset)
assert_dataset(
dataset,
{
'inputs': 'stsb sentence1: Big news. sentence2: No idea.',
'targets': '2.8',
'idx': test_idx,
},
)
# Test when floating point label is not in [0., 0.2, ..., 4.8, 5.0]
og_dataset = tf.data.Dataset.from_tensor_slices(
{
'sentence1': ['Big news.'],
'sentence2': ['No idea.'],
'label': [1.66],
'idx': [test_idx],
}
)
dataset = prep.stsb(og_dataset)
assert_dataset(
dataset,
{
'inputs': 'stsb sentence1: Big news. sentence2: No idea.',
'targets': '1.6',
'idx': test_idx,
},
)
def test_multi_translate(self):
languages = ['en', 'de', 'fr']
translations = ['That is good.', 'Das ist gut.', 'Ca c\'est bon.']
og_dataset = tf.data.Dataset.from_tensors(
{'translations': {'language': languages, 'translation': translations}}
)
dataset = prep.multi_translate(og_dataset, 'en', 'de')
assert_dataset(
dataset,
{
'inputs': 'translate English to German: That is good.',
'targets': 'Das ist gut.',
}
)
# Test that it skips over the whole (single-entry) dataset when we ask for
# a language which is not in the language list
dataset = prep.multi_translate(og_dataset, 'en', 'sk')
assert_dataset(dataset, [])
def test_fill_in_the_blank(self):
num_tries = 1000
original = 'This is a long test with lots of words to see if it works ok.'
dataset = tf.data.Dataset.from_tensor_slices(
{'text': [original] * num_tries})
dataset = prep.fill_in_the_blank(dataset)
for data in test_utils.dataset_as_text(dataset):
# Remove the prefix from the start of the input string
self.assertTrue(data['inputs'].startswith('fill: '))
inp = data['inputs'].replace('fill: ', '')
# Split output into chunks according to X locations.
out_split = data['targets'].split('X')
# Make sure that there is at least one blank
self.assertGreater(len(out_split), 1)
# Remove leading/trailing whitespace and any empty chunks
out_split = [o.strip() for o in out_split if o]
# Replace 'X' with entries from out_split by popping from the front
reconstructed = ''.join(
[i if i != 'X' else out_split.pop(0) for i in inp])
self.assertEqual(reconstructed, original)
def test_fill_in_the_blank_sized(self):
def _validate_data(data, valid_bins, og_length=15):
# Remove the prefix from the start of the input string
self.assertTrue(data['inputs'].startswith('fill: '))
inp = data['inputs'].replace('fill: ', '')
# Split input into chunks according to blank locations.
inp_split = inp.split('_')
# Make sure that there is exactly one blank (could be at beginning/end).
self.assertLen(inp_split, 3)
# Make sure reconstruction is accurate.
reconstructed = ''.join([inp_split[0], data['targets']] + inp_split[2:])
self.assertEqual(reconstructed, original)
# Make sure blank size is correctly chosen.
blank_bin = int(inp_split[1])
self.assertIn(blank_bin, valid_bins)
blank_size = len(data['targets'].split())
self.assertGreaterEqual(blank_size, min(og_length, valid_bins[0]))
self.assertLessEqual(blank_size, valid_bins[-1])
return blank_size, blank_bin
num_tries = 250
original = 'This is a long test with lots of words to see if it works ok.'
dataset = tf.data.Dataset.from_tensor_slices(
{'text': [original] * num_tries})
dataset = prep.fill_in_the_blank_sized(dataset, [1, 4])
num_outputs = 0
for data in test_utils.dataset_as_text(dataset):
blank_size, blank_bin = _validate_data(data, [1, 4])
if blank_size <= 2:
self.assertEqual(blank_bin, 1)
else:
self.assertEqual(blank_bin, 4)
num_outputs += 1
self.assertEqual(num_tries, num_outputs)
# Check case where bin size is larger than text.
dataset = tf.data.Dataset.from_tensor_slices(
{'text': [original] * num_tries})
dataset = prep.fill_in_the_blank_sized(dataset, [1024])
self.assertEmpty(list(test_utils.dataset_as_text(dataset)))
def test_random_split_text(self):
num_tries = 10
original = '%s' % list(range(100))
dataset = tf.data.Dataset.from_tensor_slices(
{'text': [original] * num_tries})
dataset = prep.random_split_text(dataset)
out = []
for data in test_utils.dataset_as_text(dataset):
out.append(data['text'])
reconstructed = ' '.join(out)
ref = ' '.join([original] * num_tries)
self.assertEqual(reconstructed, ref)
def test_split_tokens(self):
original = list(range(2, 102))
og_dataset = tf.data.Dataset.from_tensors({'targets': original})
# Verify splits with no max segments.
def _verify_split(length, n_expected_outputs):
ds = prep.split_tokens(
og_dataset, unused_vocabulary=None, max_tokens_per_segment=length)
outputs = list(test_utils.dataset_as_text(ds))
self.assertLen(outputs, n_expected_outputs)
reconstructed = []
for ex in outputs[:-1]:
t = ex['targets']
self.assertLen(t, length)
reconstructed.extend(t)
final_t = outputs[-1]['targets']
self.assertLessEqual(len(final_t), length)
reconstructed.extend(final_t)
self.assertEqual(reconstructed, original)
_verify_split(25, 4)
_verify_split(30, 4)
_verify_split(100, 1)
_verify_split(1000, 1)
def test_split_tokens_rank2(self):
original = list([i, 2 * i] for i in range(2, 102))
og_dataset = tf.data.Dataset.from_tensors({'targets': original})
# Verify splits with no max segments.
def _verify_split(length, n_expected_outputs):
ds = prep.split_tokens(
og_dataset, unused_vocabulary=None, max_tokens_per_segment=length)
outputs = list(test_utils.dataset_as_text(ds))
self.assertLen(outputs, n_expected_outputs)
reconstructed = []
for ex in outputs[:-1]:
t = ex['targets']
self.assertLen(t, length)
reconstructed.extend(t)
final_t = outputs[-1]['targets']
self.assertLessEqual(len(final_t), length)
reconstructed.extend(final_t)
self.assertAllEqual(reconstructed, original)
_verify_split(25, 4)
_verify_split(30, 4)
_verify_split(100, 1)
_verify_split(1000, 1)
def test_split_padding_tokens(self):
original = [0] * 100
og_dataset = tf.data.Dataset.from_tensors({'targets': original})
# Verify splits with no max segments.
def _verify_split(length, n_expected_outputs):
ds = prep.split_tokens(
og_dataset, unused_vocabulary=None, max_tokens_per_segment=length)
outputs = list(test_utils.dataset_as_text(ds))
self.assertLen(outputs, n_expected_outputs)
reconstructed = []
for ex in outputs[:-1]:
t = ex['targets']
self.assertLen(t, length)
reconstructed.extend(t)
final_t = outputs[-1]['targets']
self.assertLessEqual(len(final_t), length)
reconstructed.extend(final_t)
self.assertEqual(reconstructed, original)
_verify_split(25, 4)
_verify_split(30, 4)
_verify_split(100, 1)
_verify_split(1000, 1)
def test_split_tokens_additional_features_passthrough(self):
original = list(range(2, 102))
original_aux = list(range(4, 104))
original_aux2d = list([i, 2 * i] for i in range(6, 106))
original_passthrough = list(range(20))
og_dataset = tf.data.Dataset.from_tensors({
'targets': original,
'aux': original_aux,
'aux2d': original_aux2d,
'passthrough': original_passthrough
})
# Verify splits with no max segments.
def _verify_split(length, n_expected_outputs):
ds = prep.split_tokens(
og_dataset, unused_vocabulary=None, max_tokens_per_segment=length,
additional_feature_keys=['aux', 'aux2d'],
passthrough_feature_keys=['passthrough'])
outputs = list(test_utils.dataset_as_text(ds))
self.assertLen(outputs, n_expected_outputs)
reconstructed = []
reconstructed_aux = []
reconstructed_aux2d = []
for ex in outputs[:-1]:
t = ex['targets']
self.assertLen(t, length)
reconstructed.extend(t)
a = ex['aux']
self.assertLen(a, length)
reconstructed_aux.extend(a)
a2d = ex['aux2d']
self.assertLen(a2d, length)
reconstructed_aux2d.extend(a2d)
final_t = outputs[-1]['targets']
self.assertLessEqual(len(final_t), length)
reconstructed.extend(final_t)
self.assertEqual(reconstructed, original)
final_a = outputs[-1]['aux']
self.assertLessEqual(len(final_a), length)
reconstructed_aux.extend(final_a)
self.assertEqual(reconstructed_aux, original_aux)
final_a2d = outputs[-1]['aux2d']
self.assertLessEqual(len(final_a2d), length)
reconstructed_aux2d.extend(final_a2d)
self.assertAllEqual(reconstructed_aux2d, original_aux2d)
for ex in outputs:
self.assertAllEqual(original_passthrough, ex['passthrough'])
_verify_split(25, 4)
_verify_split(30, 4)
_verify_split(100, 1)
_verify_split(1000, 1)
def test_split_tokens_additional_features_passthrough_rank0(self):
original = list(range(2, 102))
original_aux = list(range(4, 104))
original_passthrough = 1234
og_dataset = tf.data.Dataset.from_tensors({
'targets': original,
'aux': original_aux,
'passthrough': original_passthrough
})
# Verify splits with no max segments.
def _verify_split(length, n_expected_outputs):
ds = prep.split_tokens(
og_dataset, unused_vocabulary=None, max_tokens_per_segment=length,
additional_feature_keys=['aux'],
passthrough_feature_keys=['passthrough'])
outputs = list(test_utils.dataset_as_text(ds))
self.assertLen(outputs, n_expected_outputs)
reconstructed = []
reconstructed_aux = []
for ex in outputs[:-1]:
t = ex['targets']
self.assertLen(t, length)
reconstructed.extend(t)
a = ex['aux']
self.assertLen(a, length)
reconstructed_aux.extend(a)
final_t = outputs[-1]['targets']
self.assertLessEqual(len(final_t), length)
reconstructed.extend(final_t)
self.assertEqual(reconstructed, original)
final_a = outputs[-1]['aux']
self.assertLessEqual(len(final_a), length)
reconstructed_aux.extend(final_a)
self.assertEqual(reconstructed_aux, original_aux)
for ex in outputs:
self.assertAllEqual(original_passthrough, ex['passthrough'])
_verify_split(25, 4)
_verify_split(30, 4)
_verify_split(100, 1)
_verify_split(1000, 1)
def test_split_tokens_to_targets_length(self):
original = list(range(2, 102))
og_dataset = tf.data.Dataset.from_tensors({'targets': original})
sequence_length = {'targets': 4}
eos_features = {
'targets': seqio.Feature(
vocabulary=seqio.PassThroughVocabulary(102),
add_eos=True)
}
no_eos_features = {
'targets': seqio.Feature(
vocabulary=seqio.PassThroughVocabulary(102),
add_eos=False)
}
ds = prep.split_tokens_to_targets_length(
og_dataset,
sequence_length=sequence_length,
output_features=eos_features)
eos_outputs = list(ds.as_numpy_iterator())
# Outputs should be length 3 to leave room for adding EOS.
self.assertLen(eos_outputs[0]['targets'], 3)
ds = prep.split_tokens_to_targets_length(
og_dataset,
sequence_length=sequence_length,
output_features=no_eos_features)
no_eos_outputs = list(ds.as_numpy_iterator())
self.assertLen(no_eos_outputs[0]['targets'], 4)
def test_trim_tokens_at_front(self):
sequence_length = {'inputs': 4}
inputs = tf.data.Dataset.from_tensors(
{'inputs': tf.constant([10, 11, 12, 13, 14, 15])})
output = prep.trim_tokens_at_front(inputs, sequence_length=sequence_length)
expected_output = [{'inputs': tf.constant([13, 14, 15])}]
test_utils.assert_dataset(output, expected_output)
def test_split_text_to_words(self):
og_dataset = tf.data.Dataset.from_tensor_slices({
'text': [
'Here\'s a sentence. Here is another; it has a semicolon.',
'I\'m 2-words.',
'There_are_no_spaces_here_so_technically_this_is_one_word.',
'',
]
})
dataset = prep.split_text_to_words(og_dataset)
test_utils.assert_dataset(dataset, [
{
'words': ['Here\'s', 'a', 'sentence.', 'Here', 'is', 'another;',
'it', 'has', 'a', 'semicolon.',],
'text': 'Here\'s a sentence. Here is another; it has a semicolon.'
},
{
'words': ['I\'m', '2-words.'],
'text': 'I\'m 2-words.'
},
])
def test_definite_pronoun_resolution_simple(self):
# Test where the pronoun is in the middle of the sentence. Also test the
# case where the string pronoun is a substring of another word in the
# sentence.
og_dataset = tf.data.Dataset.from_tensors({
'sentence': 'Mitchell asked Tom if he could lend some money.',
'pronoun': 'he',
'candidates': ['Mitchell', 'Tom'],
'label': 1,
})
dataset = prep.definite_pronoun_resolution_simple(og_dataset)
assert_dataset(
dataset, {
'inputs':
'wsc: Mitchell asked Tom if *he* could lend some money.',
'targets':
'Tom',
})
# Test multiple word pronouns. The Definite Pronoun Resolution Dataset is
# weird.
og_dataset = tf.data.Dataset.from_tensors({
'sentence':
'Bill beat Tom at Scrabble because that newbie had all the luck.',
'pronoun':
'that newbie',
'candidates': ['Bill', 'Tom'],
'label':
0,
})
dataset = prep.definite_pronoun_resolution_simple(og_dataset)
assert_dataset(
dataset, {
'inputs':
'wsc: Bill beat Tom at Scrabble because *that newbie* had all the luck.',
'targets':
'Bill',
})
# Test pronoun at end of sentence.
og_dataset = tf.data.Dataset.from_tensors({
'sentence':
'Carl borrowed a book from Richard, but the book was unreadable to him.',
'pronoun':
'him',
'candidates': ['Carl', 'Richard'],
'label':
0,
})
dataset = prep.definite_pronoun_resolution_simple(og_dataset)
assert_dataset(
dataset, {
'inputs':
'wsc: Carl borrowed a book from Richard, but the book was unreadable to *him*.',
'targets':
'Carl',
})
def test_wsc_simple(self):
og_dataset = tf.data.Dataset.from_tensors({
'text': 'Mitchell asked Tom if he could lend some money.',
'span1_text': 'Tom',
'span2_text': 'he',
'span2_index': 4,
'idx': 1,
})
dataset = prep.wsc_simple(og_dataset, correct_referent_only=False)
assert_dataset(
dataset, {
'inputs': 'wsc: Mitchell asked Tom if *he* could lend some money.',
'targets': 'Tom',
'label': 0,
'idx': 1,
})
# Test including only examples with the correct referent.
og_dataset = tf.data.Dataset.from_tensor_slices({
'text': [
'Mitchell asked Tom if he could lend some money.',
'Mitchell asked Tom if he could lend some money.',
],
'span1_text': [
'Tom',
'Mitchell',
],
'span2_text': [
'he',
'he',
],
'span2_index': [4, 4],
'label': [1, 0],
'idx': [1, 2]
})
dataset = prep.wsc_simple(og_dataset, correct_referent_only=True)
assert_dataset(dataset, [{
'inputs': 'wsc: Mitchell asked Tom if *he* could lend some money.',
'targets': 'Tom',
'label': True,
'idx': 1,
}])
def test_wnli_simple(self):
og_dataset = tf.data.Dataset.from_tensor_slices({
'sentence1': [
'Lily spoke to Donna breaking her silence.',
'The fish ate the worm. It was tasty.',
'Edward dropped adhesive tape onto his window sill, and when he pulled the tape off, some of the glue was stuck on it.',
"Al stole Bob's wallet and car, and then he was driving it really fast to get away.",
],
'sentence2': [
"Lily spoke to Donna breaking Donna's silence.",
'The worm was tasty.',
'Some of the glue was stuck on the window sill.',
'He was driving the car really fast to get away.',
],
'idx': [1, 2, 3, 4],
'label': [1, 0, 0, 1],
})
dataset = prep.wnli_simple(og_dataset)
assert_dataset(dataset, [
{
'inputs': 'wsc: Lily spoke to Donna breaking *her* silence.',
'targets': 'Donna',
'premise': 'Lily spoke to Donna breaking her silence.',
'hypothesis': "Lily spoke to Donna breaking Donna's silence.",
'label': 1,
'idx': 1,
},
{
'inputs': 'wsc: The fish ate the worm. *It* was tasty.',
'targets': 'The worm',
'premise': 'The fish ate the worm. It was tasty.',
'hypothesis': 'The worm was tasty.',
'label': 0,
'idx': 2,
},
{
'inputs':
'wsc: Edward dropped adhesive tape onto his window sill, and when he pulled the tape off, some of the glue was stuck on *it* .',
'targets':
'the window sill',
'premise':
'Edward dropped adhesive tape onto his window sill, and when he pulled the tape off, some of the glue was stuck on it.',
'hypothesis':
'Some of the glue was stuck on the window sill.',
'label':
0,
'idx':
3,
},
{
'inputs':
"wsc: Al stole Bob's wallet and car, and then he was driving *it* really fast to get away.",
'targets':
'the car',
'premise':
"Al stole Bob's wallet and car, and then he was driving it really fast to get away.",
'hypothesis':
'He was driving the car really fast to get away.',
'label':
1,
'idx':
4,
},
])
def test_next_sentence_prediction(self):
og_dataset = tf.data.Dataset.from_tensor_slices({
'text': [
'This is the first sentence. This is the second sentence.',
'This is the third sentence. This is the fourth sentence.',
]
})
# Test neighboring sentences.
dataset = prep.next_sentence_prediction(
og_dataset, label_sentences=False, p_neighbors=1, buffer_size=1)
assert_dataset(
dataset,
[
{
'inputs':
'nsp: This is the first sentence. This is the second sentence.',
'targets':
'next',
},
{
'inputs':
'nsp: This is the third sentence. This is the fourth sentence.',
'targets':
'next',
},
],
)
# Test non-neighboring sentences.
dataset = prep.next_sentence_prediction(