/
test_datablob.py
2372 lines (2105 loc) · 98.4 KB
/
test_datablob.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
"""
Test the scalarstop.datablob module
"""
import doctest
import itertools
import json
import os
import tempfile
import unittest
from typing import Any, Mapping, Optional, Union
import pandas as pd
import tensorflow as tf
import tensorflow.python as tfpy # pylint: disable=no-name-in-module
import scalarstop as sp
from scalarstop._constants import _DEFAULT_SAVE_LOAD_VERSION
from scalarstop._filesystem import rmtree
from tests.assertions import (
assert_datablob_dataframes_are_equal,
assert_datablob_metadata_from_filesystem,
assert_datablob_names_and_hyperparams_are_equal,
assert_datablobs_tfdatas_are_equal,
assert_dataframes_are_equal,
assert_directory,
assert_hyperparams_are_equal,
assert_hyperparams_flat_are_equal,
assert_tfdatas_are_equal,
tfdata_as_list,
tfdata_get_first_shape_len,
)
from tests.fixtures import MyDataBlob as MyDataBlob3
from tests.fixtures import (
MyModelTemplate,
MyShardableDataBlob,
MyShardableDistributedDataBlob,
)
# TODO(jamesmishra): Fix unit tests that have two conflicting definitions of "MyDataBlob". Remove "MyDataBlob3". # pylint: disable=line-too-long
def load_tests(loader, tests, ignore): # pylint: disable=unused-argument
"""Have the unittest loader also run doctests."""
tests.addTests(doctest.DocTestSuite(sp.datablob))
return tests
class MyDataBlob(sp.DataBlob):
"""A simple example of a DataBlob."""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams for MyDataBlob,"""
a: int = 1
b: str = "hi"
def __init__(self, *, hyperparams=None, secret: str = "no"):
"""Initialize."""
super().__init__(hyperparams=hyperparams)
self._secret = secret
def set_training(self):
"""Set the training tfdata."""
return tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5]).map(
lambda x: x * self.hyperparams.a
)
def set_validation(self):
"""Set the validation tfdata."""
return tf.data.Dataset.from_tensor_slices([6, 7, 8, 9, 10]).map(
lambda x: x * self.hyperparams.a
)
def set_test(self):
"""Set the test tfdata."""
return tf.data.Dataset.from_tensor_slices([11, 12, 13, 14, 15]).map(
lambda x: x * self.hyperparams.a
)
class MyDataBlobArbitraryRows(sp.DataBlob):
"""A DataBlob fixture where we can arbitrarily vary the number of rows."""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams for MyDataBlobArbitraryRows."""
num_training: int
num_validation: int
num_test: int
coefficient: int = 100
hyperparams: "MyDataBlobArbitraryRows.Hyperparams"
def _make_tfdata(self, num: int) -> tf.data.Dataset:
return tf.data.Dataset.range(num).map(
lambda x: x * self.hyperparams.coefficient
)
def set_training(self):
return self._make_tfdata(self.hyperparams.num_training)
def set_validation(self):
return self._make_tfdata(self.hyperparams.num_validation)
def set_test(self):
return self._make_tfdata(self.hyperparams.num_test)
class MyDataBlobForgotHyperparams(sp.ModelTemplate):
"""A DataBlob with a misconfigured hyperparams class."""
Hyperparams = None # type: ignore
class MyDataBlobRequiredHyperparams(sp.ModelTemplate):
"""A DataBlob where the hyperparams have no default values."""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams for MyDataBlobRequiredHyperparams."""
a: int
b: str
class DataBlobWillFailtoSave(MyDataBlob):
"""
A :py:class:`DataBlob` that will raise an exception if you try
to save it to disk.
"""
def save_hook(self, *, subtype, path) -> None: # pylint: disable=unused-argument
"""A custom save hook to simulate a failure."""
# First we check that we have made partial progress in saving
# this DataBlob.
this_dataset_path = os.path.dirname(os.path.dirname(path))
files = os.listdir(this_dataset_path)
assert len(files) == 1
assert files[0].startswith(self.name)
# Then we create an error that should force us to delete this partial progress.
raise RuntimeError("Simulated failure for testing purposes.")
class DataBlobWillCauseDirectoryNotEmpty(MyDataBlob):
"""
A :py:class:`DataBlob` designed to fail because a directory
is created at the exact path that we want to save our
:py:class:`DataBlob`.
"""
def save_hook(self, *, subtype, path) -> None:
"""
We create the destination directory while making the temporary
directory to simulate a race condition while persisting a
:py:class:`DataBlob`.
"""
if subtype == "training":
datablobs_directory = os.path.dirname(os.path.dirname(path))
this_dataset_path = os.path.join(datablobs_directory, self.name)
# We have to create a directory, and then put something inside
# the directory to make sure that we can't copy into the
# directory without triggering an error.
os.mkdir(this_dataset_path)
with open(
os.path.join(this_dataset_path, "training"), "w", encoding="utf-8"
):
pass
class DataBlobWillCauseNotADirectoryError(MyDataBlob):
"""
A :py:class:`DataBlob` designed to fail because a file
is created at the exact path that we want to save our
:py:class:`DataBlob`.
"""
def save_hook(self, *, subtype, path) -> None:
"""
We create the destination directory as a file, as another
way to simulate a race condition.
"""
if subtype == "training":
datablobs_directory = os.path.dirname(os.path.dirname(path))
this_dataset_path = os.path.join(datablobs_directory, self.name)
with open(os.path.join(this_dataset_path), "w", encoding="utf-8"):
pass
class DataBlobForCaching(sp.DataBlob):
"""
DataBlob that increments an internal state every time it is
iterated over.
The purpose of this is enable caching on this DataBlob and watch
the counter stop incrementing.
"""
count = 0
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams for DataBlobForCaching."""
a: int = 3
def __init__(self, hyperparams=None):
"""Initialize."""
super().__init__(hyperparams=hyperparams)
def _count(self, tensor):
"""Increment the counter for testing."""
self.count += 1
return tensor
def _set_tfdata(self):
"""Generate the tfdata for training, validation, and test."""
def outer_func(tensor: tf.Tensor) -> tf.Tensor:
return tf.py_function(self._count, inp=[tensor], Tout=tf.int32)
return tf.data.Dataset.from_tensor_slices([3, 2, 1]).map(outer_func)
def set_training(self):
"""Set the training tfdata."""
return self._set_tfdata()
def set_validation(self):
"""Set the validation tfdata."""
return self._set_tfdata()
def set_test(self):
"""Set the test tfdata."""
return self._set_tfdata()
class MyDataFrameDataBlob(sp.DataFrameDataBlob):
"""
An example of creating a :py:class:`DataBlob` with a
:py:class:`pandas.DataFrame`.
"""
@sp.dataclass
class Hyperparams(sp.HyperparamsType):
"""Hyperparams for :py:class:`MyDataFrameDataBlob`."""
a: int = 0
def __init__(self, hyperparams=None):
"""Initialize."""
super().__init__(hyperparams=hyperparams)
def set_dataframe(self):
"""Set the dataframe."""
return pd.DataFrame(dict(samples=[1, 2, 3], labels=[4, 5, 6]))
def transform(self, dataframe: pd.DataFrame):
"""Transform."""
return tf.data.Dataset.zip(
(
tf.data.Dataset.from_tensor_slices(dataframe[self.samples_column]),
tf.data.Dataset.from_tensor_slices(dataframe[self.labels_column]),
)
)
class MyAppendDataBlob(sp.AppendDataBlob):
"""Fixture for testing sp.AppendDataBlob."""
@sp.dataclass
class Hyperparams(sp.AppendHyperparamsType):
"""Hyperparams for MyAppendDataBlob."""
coefficient: int
hyperparams: "MyAppendDataBlob.Hyperparams"
def __init__(
self,
*,
parent: sp.DataBlob,
hyperparams: Optional[Union[Mapping[str, Any], sp.HyperparamsType]] = None,
secret2: str,
):
super().__init__(parent=parent, hyperparams=hyperparams)
self._secret2 = secret2
def _wrap_tfdata(self, tfdata: tf.data.Dataset) -> tf.data.Dataset:
return tfdata.map(
lambda row: row * self.hyperparams.coefficient,
)
class MyAppendDataBlobConflictA(sp.AppendDataBlob):
"""
An AppendDataBlob whose hyperparam `a` is intended to
conflict with MyDataBlob.
"""
@sp.dataclass
class Hyperparams(sp.AppendHyperparamsType):
"""Hyperparams for MyAppendDataBlobConflictA."""
a: int
c: int
d: int
hyperparams: "MyAppendDataBlobConflictA.Hyperparams"
def _wrap_tfdata(self, tfdata: tf.data.Dataset) -> tf.data.Dataset:
"""Multiply the input tf.data.Dataset by our `a` hyperparameter."""
return tfdata.map(lambda x: x * self.hyperparams.a)
class MyAppendDataBlobConflictB(sp.AppendDataBlob):
"""
An AppendDataBlob whose hyperparam `b` is intended to
conflict with MyDataBlob.
The hyperparam `c` is also meant to conflict with
MyAppendDataBlobConflictA.
"""
@sp.dataclass
class Hyperparams(sp.AppendHyperparamsType):
"""Hyperparams for MyAppendDataBlobConflictB."""
b: "str"
c: int
e: int
hyperparams: "MyAppendDataBlobConflictB.Hyperparams"
def _wrap_tfdata(self, tfdata: tf.data.Dataset) -> tf.data.Dataset:
"""Multiply the input tf.data.Dataset by our `c` hyperparameter."""
return tfdata.map(lambda x: x * self.hyperparams.c)
class MyAppendDataBlobNoHyperparams(sp.AppendDataBlob):
"""Fixture for testing sp.AppendDataBlob without hyperparams."""
def _wrap_tfdata(self, tfdata: tf.data.Dataset) -> tf.data.Dataset:
return tfdata.enumerate()
class DataBlobTestCase(unittest.TestCase):
"""Base class for unit tests involving DataBlobs."""
def assert_saved_metadata_json(self, blob, filename):
"""Check that the metadata.json has been properly saved to the filesystem."""
expected = dict(
name=blob.name,
group_name=blob.group_name,
hyperparams=sp.dataclasses.asdict(blob.hyperparams),
save_load_version=_DEFAULT_SAVE_LOAD_VERSION,
num_shards=1,
)
with open(filename, "r", encoding="utf-8") as fh:
actual = json.load(fh)
self.assertEqual(expected, actual)
def assert_saved_dataframe(self, blob, subtype, this_datablobs_directory):
"""Check that DataFrames have been properly saved to the filesystem."""
current_dataframe = getattr(blob, subtype + "_dataframe")
assert_directory(
os.path.join(this_datablobs_directory, subtype),
["dataframe.pickle.gz", "tfdata", "element_spec.pickle"],
)
# Check that the loaded dataframe is the same.
loaded_dataframe = pd.read_pickle(
os.path.join(this_datablobs_directory, subtype, "dataframe.pickle.gz")
)
assert_dataframes_are_equal(current_dataframe, loaded_dataframe)
def assertions_for_save(self, blob, datablobs_directory):
"""Assert that saving a DataBlob works."""
with self.assertRaises(FileExistsError):
blob.save(datablobs_directory)
self.assertTrue(os.path.exists(os.path.join(datablobs_directory, blob.name)))
self.assertTrue(blob.exists_in_datablobs_directory(datablobs_directory))
this_datablobs_directory = os.path.join(datablobs_directory, blob.name)
assert_directory(
this_datablobs_directory,
["training", "validation", "test", "metadata.json", "metadata.pickle"],
)
self.assert_saved_metadata_json(
blob, os.path.join(this_datablobs_directory, "metadata.json")
)
for subtype in ["training", "validation", "test"]:
with self.subTest(subtype):
# If the DataBlob has dataframes, check that they have been
# serialized too.
current_dataframe = getattr(blob, subtype + "_dataframe", None)
if current_dataframe is not None:
self.assert_saved_dataframe(blob, subtype, this_datablobs_directory)
else:
assert_directory(
os.path.join(this_datablobs_directory, subtype),
["tfdata", "element_spec.pickle"],
)
self.assertTrue(
os.path.exists(
os.path.join(this_datablobs_directory, subtype, "tfdata")
)
)
def assertions_for_batch_cache_save(self, blob, sequence, datablobs_directory):
"""
Assert that batching, caching, and saving doesn't change
names or hyperparams.
"""
first_name = blob.name
first_group_name = blob.group_name
first_hyperparams = blob.hyperparams
for method_name, kwargs in sequence:
blob = getattr(blob, method_name)(**kwargs)
self.assertEqual(blob.name, first_name)
self.assertEqual(blob.group_name, first_group_name)
assert_hyperparams_are_equal(blob.hyperparams, first_hyperparams)
self.assertions_for_save(blob, datablobs_directory)
class TestDataBlob(DataBlobTestCase):
"""Tests for DataBlob."""
def test_not_implemented(self):
"""
Test that :py:class:`DataBlob` methods are not implemented
until overridden.
"""
blob = sp.DataBlob()
not_implemented_methods = [
"set_training",
"set_validation",
"set_test",
]
for method_name in not_implemented_methods:
with self.subTest(method_name + "()"):
with self.assertRaises(sp.exceptions.IsNotImplemented):
getattr(blob, method_name)()
not_implemented_properties = [
"training",
"validation",
"test",
]
for property_name in not_implemented_properties:
with self.subTest(property_name):
with self.assertRaises(sp.exceptions.IsNotImplemented):
getattr(blob, property_name)
def test_names(self):
"""Test that all of the names are correct."""
blob1 = MyDataBlob(hyperparams=dict(a=1, b="hi"), secret="s1")
blob2 = MyDataBlob(hyperparams=dict(a=1, b="hi"), secret="s2")
blob3 = MyDataBlob(hyperparams=dict(a=1, b="bye"), secret="s3")
self.assertTrue(isinstance(blob1, sp.DataBlob))
self.assertTrue(isinstance(blob2, sp.DataBlob))
self.assertTrue(isinstance(blob3, sp.DataBlob))
self.assertEqual(blob1.name, "MyDataBlob-naro6iqyw9whazvkgp4w3qa2")
self.assertEqual(blob1.name, blob2.name)
self.assertEqual(blob3.name, "MyDataBlob-cmfhzgfa6z4gm43ntk1q2hbp")
self.assertEqual(blob1.group_name, "MyDataBlob")
self.assertEqual(blob1.group_name, blob2.group_name)
self.assertEqual(blob1.group_name, blob3.group_name)
def test_missing_hyperparams_class(self):
"""Test what happens when the hyperparams class itself is missing."""
with self.assertRaises(sp.exceptions.YouForgotTheHyperparams):
MyDataBlobForgotHyperparams()
def test_save_success(self):
"""Test that we can save a :py:class:`DataBlob`."""
with tempfile.TemporaryDirectory() as datablobs_directory:
blob = MyDataBlob(hyperparams=dict(a=1, b="hi"), secret="s1")
# Make sure that the DataBlob has not already been saved.
self.assertFalse(blob.exists_in_datablobs_directory(datablobs_directory))
# Save the DataBlob and check that it was successfully persisted
# to the filesystem.
blob.save(datablobs_directory)
self.assertTrue(blob.exists_in_datablobs_directory(datablobs_directory))
assert_datablob_metadata_from_filesystem(
blob, datablobs_directory=datablobs_directory
)
# Test that we raise an exception when the datablob already exists.
with self.assertRaises(sp.exceptions.FileExists):
blob.save(datablobs_directory)
# Test that we can suppress the exception that we just raised
blob.save(datablobs_directory, ignore_existing=True)
# Test that the saved data looks right.
self.assertions_for_save(blob, datablobs_directory)
# Check that serialized element spec is correct.
for subtype in ["training", "validation", "test"]:
tfdata = getattr(blob, subtype)
with open(
os.path.join(
datablobs_directory, blob.name, subtype, "element_spec.pickle"
),
"rb",
) as fh:
loaded_element_spec = sp.pickle.load(fh)
self.assertEqual(tfdata.element_spec, loaded_element_spec)
def test_save_catch_exception(self):
"""
Test that :py:meth:`DataBlob.save` deletes partially-saved
data if it fails.
"""
with tempfile.TemporaryDirectory() as datablobs_directory:
with self.assertRaises(RuntimeError):
DataBlobWillFailtoSave().save(datablobs_directory)
assert_directory(datablobs_directory, [])
def test_save_dataset_created_during_creation_1(self):
"""
Test what happens when the final :py:class:`DataBlob`
directory is created after we start (but do not finish)
saving our :py:class:`DataBlob`.
"""
with tempfile.TemporaryDirectory() as datablobs_directory:
with self.assertRaises(sp.exceptions.FileExistsDuringDataBlobCreation):
DataBlobWillCauseDirectoryNotEmpty().save(datablobs_directory)
def test_save_dataset_created_during_creation_2(self):
"""
Test what happpens when we create a file (not a directory)
at the location that we wanted to create the directory
to save our :py:class:`DataBlob`.
"""
with tempfile.TemporaryDirectory() as datablobs_directory:
with self.assertRaises(sp.exceptions.FileExistsDuringDataBlobCreation):
DataBlobWillCauseNotADirectoryError().save(datablobs_directory)
def test_from_exact_path(self):
"""Test that we can load a :py:class:`DataBlob` from the filesystem."""
with tempfile.TemporaryDirectory() as datablobs_directory:
blob = MyDataBlob(hyperparams=dict(a=1, b="hi"), secret="s1")
blob.save(datablobs_directory)
self.assertTrue(blob.exists_in_datablobs_directory(datablobs_directory))
assert_datablob_metadata_from_filesystem(
blob, datablobs_directory=datablobs_directory
)
loaded = sp.DataBlob.from_exact_path(
os.path.join(datablobs_directory, blob.name)
)
assert_datablob_names_and_hyperparams_are_equal(blob, loaded)
assert_datablobs_tfdatas_are_equal(blob, loaded)
def test_load_dataset_not_found_1(self):
"""
Test what happens when we try to load a nonexistent
:py:class:`DataBlob` from the filesystem.
"""
with self.assertRaises(sp.exceptions.DataBlobNotFound):
sp.DataBlob.from_exact_path("asdf")
def test_load_dataset_not_found_2(self):
"""
Test what happens when we delete a directory containing
a :py:class:`tf.data.Dataset` and the element spec.
"""
for deleted_subtype in ["training", "validation", "test"]:
with tempfile.TemporaryDirectory() as datablobs_directory:
blob = MyDataBlob(hyperparams=dict(a=1, b="hi"), secret="s1").save(
datablobs_directory
)
rmtree(os.path.join(datablobs_directory, blob.name, deleted_subtype))
loaded = sp.DataBlob.from_exact_path(
os.path.join(datablobs_directory, blob.name)
)
for loaded_subtype in ["training", "validation", "test"]:
with self.subTest(
f"deleted {deleted_subtype}, loaded {loaded_subtype}"
):
if deleted_subtype == loaded_subtype:
with self.assertRaises(
sp.exceptions.TensorFlowDatasetNotFound
):
getattr(loaded, loaded_subtype)
else:
getattr(loaded, loaded_subtype)
def test_load_dataset_not_found_3(self):
"""
Test what happens when we delete a directory containing a
:py:class:`tf.data.Dataset` but we don't delete the element spec.
"""
for deleted_subtype in ["training", "validation", "test"]:
with tempfile.TemporaryDirectory() as datablobs_directory:
blob = MyDataBlob(hyperparams=dict(a=1, b="hi"), secret="s1").save(
datablobs_directory
)
rmtree(
os.path.join(
datablobs_directory, blob.name, deleted_subtype, "tfdata"
)
)
loaded = sp.DataBlob.from_exact_path(
os.path.join(datablobs_directory, blob.name)
)
for loaded_subtype in ["training", "validation", "test"]:
with self.subTest(
f"deleted {deleted_subtype}, loaded {loaded_subtype}"
):
if deleted_subtype == loaded_subtype:
with self.assertRaises(
sp.exceptions.TensorFlowDatasetNotFound
):
getattr(loaded, loaded_subtype)
else:
getattr(loaded, loaded_subtype)
def test_cache_save_load_permutations(self):
"""Test loading the dataset after cache and or save."""
with tempfile.TemporaryDirectory() as datablobs_directory:
operations = dict(
cache={},
save=dict(datablobs_directory=datablobs_directory),
)
for idx, sequence in enumerate(itertools.permutations(operations.items())):
blob = MyDataBlob(hyperparams=dict(a=idx, b="hi"), secret="s1")
with self.subTest(sequence[0]):
self.assertions_for_batch_cache_save(
blob, sequence, datablobs_directory
)
loaded = blob.from_exact_path(
os.path.join(datablobs_directory, blob.name)
)
assert_datablob_names_and_hyperparams_are_equal(blob, loaded)
assert_datablobs_tfdatas_are_equal(blob, loaded)
def test_batch_cache_save_load_permutations(self):
"""Test loading the dataset after batch/cache/save."""
with tempfile.TemporaryDirectory() as datablobs_directory:
operations = dict(
batch=dict(batch_size=2),
cache={},
save=dict(datablobs_directory=datablobs_directory),
)
for idx, sequence in enumerate(itertools.permutations(operations.items())):
blob = MyDataBlob(hyperparams=dict(a=idx, b="hi"), secret="s1")
with self.subTest(sequence[0]):
self.assertions_for_batch_cache_save(
blob, sequence, datablobs_directory
)
loaded = blob.from_exact_path(
os.path.join(datablobs_directory, blob.name)
)
assert_datablob_names_and_hyperparams_are_equal(blob, loaded)
class Test_WrapDataBlob(DataBlobTestCase):
"""Test the :py:class:`_WrapDataBlob` class."""
def test_not_implemented(self):
"""
Test that :py:class:`_WrapDataBlob` methods are not
implemented until overridden.
"""
wrapped = sp.datablob._WrapDataBlob(
wraps=MyDataBlob(), training=True, validation=True, test=True
)
not_implemented_methods = [
"set_training",
"set_validation",
"set_test",
]
for method_name in not_implemented_methods:
with self.subTest(method_name + "()"):
with self.assertRaises(sp.exceptions.IsNotImplemented):
getattr(wrapped, method_name)()
not_implemented_properties = [
"training",
"validation",
"test",
]
for property_name in not_implemented_properties:
with self.subTest(property_name):
with self.assertRaises(sp.exceptions.IsNotImplemented):
getattr(wrapped, property_name)
def test_cache_wrapping(self):
"""
Test that `_WrapDataBlob.training` calls `parent.training` a
opposed to `parent.set_training()`.
"""
class _TrainingCalled(Exception):
"""Test that DataBlob.training is called."""
class _ValidationCalled(Exception):
"""Test that DataBlob.validation is called."""
class _TestCalled(Exception):
"""Test that DataBlob.test is called."""
class _Parent(MyDataBlob):
"""Parent class with instrumented training, validation, and test property() methods."""
@property
def training(self):
raise _TrainingCalled("training")
@property
def validation(self):
raise _ValidationCalled("validation")
@property
def test(self):
raise _TestCalled("test")
wrapped = sp.datablob._WrapDataBlob(
wraps=_Parent(),
training=True,
validation=True,
test=True,
)
with self.assertRaises(_TrainingCalled):
wrapped.training # pylint: disable=pointless-statement
with self.assertRaises(_ValidationCalled):
wrapped.validation # pylint: disable=pointless-statement
with self.assertRaises(_TestCalled):
wrapped.test # pylint: disable=pointless-statement
def test_disable_training_validation_test(self):
"""
Test that _WrapDataBlob can selectively disable the training, validation, and test suites.
"""
class _Wrapper(sp.datablob._WrapDataBlob):
def _wrap_tfdata(self, tfdata):
return tfdata.map(lambda x: x * 1000)
parent = MyDataBlob()
wrapped_training = _Wrapper(
wraps=parent,
training=True,
validation=False,
test=False,
)
expected_training = tf.data.Dataset.from_tensor_slices(
[1000, 2000, 3000, 4000, 5000]
)
assert_tfdatas_are_equal(expected_training, wrapped_training.training)
assert_tfdatas_are_equal(parent.validation, wrapped_training.validation)
assert_tfdatas_are_equal(parent.test, wrapped_training.test)
wrapped_validation = _Wrapper(
wraps=parent,
training=False,
validation=True,
test=False,
)
expected_validation = tf.data.Dataset.from_tensor_slices(
[6000, 7000, 8000, 9000, 10000]
)
assert_tfdatas_are_equal(parent.training, wrapped_validation.training)
assert_tfdatas_are_equal(expected_validation, wrapped_validation.validation)
assert_tfdatas_are_equal(parent.test, wrapped_validation.test)
wrapped_test = _Wrapper(
wraps=parent,
training=False,
validation=False,
test=True,
)
expected_test = tf.data.Dataset.from_tensor_slices(
[11000, 12000, 13000, 14000, 15000]
)
assert_tfdatas_are_equal(parent.training, wrapped_test.training)
assert_tfdatas_are_equal(parent.validation, wrapped_test.validation)
assert_tfdatas_are_equal(expected_test, wrapped_test.test)
class Test_BatchDataBlob(DataBlobTestCase):
"""Tests for _BatchDataBlob"""
def test_successs(self):
"""Test that _BatchDataBlob works."""
blob = MyDataBlob(hyperparams=dict(a=1, b="hi"), secret="s1")
batched = blob.batch(2)
self.assertTrue(isinstance(blob, sp.DataBlob))
self.assertTrue(isinstance(batched, sp.DataBlob))
self.assertEqual(blob.name, batched.name)
self.assertEqual(blob.group_name, batched.group_name)
self.assertEqual(blob.hyperparams, batched.hyperparams)
for subtype in ["training", "validation", "test"]:
with self.subTest(subtype):
lst = list(getattr(batched, subtype))
self.assertEqual(len(lst), 3)
self.assertEqual(lst[0].shape, (2,))
self.assertEqual(lst[1].shape, (2,))
self.assertEqual(lst[2].shape, (1,))
def test_batch_with_tensorflow_distribute(self):
"""Test batching with the default TensorFlow Distribute strategy."""
num_replicas = tf.distribute.get_strategy().num_replicas_in_sync
input_batch_size = 2
batched = MyDataBlob().batch(input_batch_size, with_tf_distribute=True)
self.assertEqual(num_replicas * input_batch_size, batched.batch_size)
def test_selectively_disabling_batch(self):
"""Test that training/validation/test=False disables batching."""
datablob = MyDataBlob()
self.assertEqual(tfdata_get_first_shape_len(datablob.training), 0)
self.assertEqual(tfdata_get_first_shape_len(datablob.validation), 0)
self.assertEqual(tfdata_get_first_shape_len(datablob.test), 0)
batched_training = datablob.batch(2, validation=False, test=False)
self.assertEqual(tfdata_get_first_shape_len(batched_training.training), 1)
self.assertEqual(tfdata_get_first_shape_len(batched_training.validation), 0)
self.assertEqual(tfdata_get_first_shape_len(batched_training.test), 0)
batched_training_and_val = batched_training.batch(2, test=False)
self.assertEqual(
tfdata_get_first_shape_len(batched_training_and_val.training), 2
)
self.assertEqual(
tfdata_get_first_shape_len(batched_training_and_val.validation), 1
)
self.assertEqual(tfdata_get_first_shape_len(batched_training_and_val.test), 0)
batched_val_and_test = batched_training_and_val.batch(2, training=False)
self.assertEqual(tfdata_get_first_shape_len(batched_val_and_test.training), 2)
self.assertEqual(tfdata_get_first_shape_len(batched_val_and_test.validation), 2)
self.assertEqual(tfdata_get_first_shape_len(batched_val_and_test.test), 1)
class Test_CacheDataBlob(DataBlobTestCase):
"""Tests for _CacheDataBlob."""
def test_success(self):
"""Test that in-memory caching works."""
for subtype in ["training", "validation", "test"]:
with self.subTest(subtype):
# Each iteration increments the count by 3 because the tf.data pipeline is
# not cached.
blob = DataBlobForCaching()
# We start at 0.
self.assertEqual(blob.count, 0)
# Generating the tf.data pipeline does not increment the count.
subtype_tf = getattr(blob, subtype)
self.assertEqual(blob.count, 0)
# Each time we iterate over the tf.data pipeline, the count
# value goes up by 3. The counter should stop incrementing
# once we begin caching the pipeline.
for _ in subtype_tf:
continue
self.assertEqual(blob.count, 3)
for _ in subtype_tf:
continue
self.assertEqual(blob.count, 6)
for _ in subtype_tf:
continue
self.assertEqual(blob.count, 9)
# Set up the cached pipeline and verify everything is the same.
cached = blob.cache()
self.assertEqual(blob.name, cached.name)
self.assertEqual(blob.group_name, cached.group_name)
self.assertEqual(blob.hyperparams, cached.hyperparams)
# The count is where we last left it.
self.assertEqual(cached.count, 9)
# Selecting a tf.data pipeline from our DataBlob does not trigger
# an iteration over the pipeline. This means that the count is still 9.
cached_subtype_tf = getattr(cached, subtype)
self.assertEqual(cached.count, 9)
# The first iteration over a cached tf.data pipeline will still
# increment the counter. This is because tf.data caching isn't complete
# until the next pass over the entire dataset.
for _ in cached_subtype_tf:
continue
self.assertEqual(cached.count, 12)
# Now that caching is complete, we expect the value to stay at 12.
for _ in cached_subtype_tf:
continue
self.assertEqual(cached.count, 12)
for _ in cached_subtype_tf:
continue
self.assertEqual(cached.count, 12)
def test_selectively_disable_caching(self):
"""Test that training=False disables caching on the training set, and so forth."""
cached = DataBlobForCaching().cache(
training=False, precache_validation=True, precache_test=True
)
# the count is 6 because precaching the validation and test sets incremented
# the counter.
self.assertEqual(cached.count, 6)
# The training set is not cached, so our count increments by another 3.
for _ in cached.training:
continue
self.assertEqual(cached.count, 9)
# The validation and test sets have been precached,
# so they will no longer increment the count.
for _ in cached.validation:
continue
self.assertEqual(cached.count, 9)
for _ in cached.test:
continue
self.assertEqual(cached.count, 9)
for _ in cached.validation:
continue
self.assertEqual(cached.count, 9)
for _ in cached.test:
continue
self.assertEqual(cached.count, 9)
# But because we have not cached the training set, the count
# will continue to increment every time we iterate over iut.
for _ in cached.training:
continue
self.assertEqual(cached.count, 12)
for _ in cached.training:
continue
self.assertEqual(cached.count, 15)
def test_precache_training(self):
"""Test CacheDataBlob precache_training=True."""
# Each iteration increments the count by 3 because the tf.data pipeline is not cached.
blob = DataBlobForCaching()
# We start at 0.
self.assertEqual(blob.count, 0)
# Generating the tf.data pipeline does not increment the count.
subtype_tf = getattr(blob, "training")
self.assertEqual(blob.count, 0)
# Each time we iterate over the tf.data pipeline, the count
# value goes up by 3. The counter should stop incrementing
# once we begin caching the pipeline.
for _ in subtype_tf:
continue
self.assertEqual(blob.count, 3)
for _ in subtype_tf:
continue
self.assertEqual(blob.count, 6)
for _ in subtype_tf:
continue
self.assertEqual(blob.count, 9)
# Set up the cached pipeline and verify everything is the same.
cached = blob.cache(
precache_training=True, precache_validation=False, precache_test=False
)
self.assertEqual(blob.name, cached.name)
self.assertEqual(blob.group_name, cached.group_name)
self.assertEqual(blob.hyperparams, cached.hyperparams)
# The count is where we last left it.
self.assertEqual(cached.count, 12)
# Selecting a tf.data pipeline from our DataBlob does not trigger
# an iteration over the pipeline. This means that the count is still 9.
cached_subtype_tf = getattr(cached, "training")
self.assertEqual(cached.count, 12)
# The first iteration over a cached tf.data pipeline will still
# increment the counter. This is because tf.data caching isn't complete
# until the next pass over the entire dataset.
for _ in cached_subtype_tf:
continue
self.assertEqual(cached.count, 12)
# Now that caching is complete, we expect the value to stay at 12.
for _ in cached_subtype_tf:
continue
self.assertEqual(cached.count, 12)
for _ in cached_subtype_tf:
continue
self.assertEqual(cached.count, 12)
def test_precache_all(self):
"""Test CacheDataBlob precache True for training/validation/test."""
# Each iteration increments the count by 3 because the tf.data pipeline is not cached.
blob = DataBlobForCaching()
self.assertEqual(blob.count, 0)
for subtype in ["training", "validation", "test"]:
subtype_tf = getattr(blob, subtype)
for _ in subtype_tf:
continue
for _ in subtype_tf: