forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_specs.py
3808 lines (3389 loc) · 133 KB
/
test_specs.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 (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import contextlib
import warnings
import numpy as np
import pytest
import torch
import torchrl.data.tensor_specs
from _utils_internal import get_available_devices, get_default_devices, set_global_var
from scipy.stats import chisquare
from tensordict import LazyStackedTensorDict, TensorDict, TensorDictBase
from tensordict.utils import _unravel_key_to_tuple
from torchrl._utils import _make_ordinal_device
from torchrl.data.tensor_specs import (
_keys_to_empty_composite_spec,
Binary,
BinaryDiscreteTensorSpec,
Bounded,
BoundedTensorSpec,
Categorical,
Composite,
CompositeSpec,
ContinuousBox,
DiscreteTensorSpec,
MultiCategorical,
MultiDiscreteTensorSpec,
MultiOneHot,
MultiOneHotDiscreteTensorSpec,
NonTensor,
NonTensorSpec,
OneHot,
OneHotDiscreteTensorSpec,
StackedComposite,
TensorSpec,
Unbounded,
UnboundedContinuous,
UnboundedContinuousTensorSpec,
UnboundedDiscrete,
UnboundedDiscreteTensorSpec,
)
from torchrl.data.utils import check_no_exclusive_keys, consolidate_spec
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.float64, None])
def test_bounded(dtype):
torch.manual_seed(0)
np.random.seed(0)
for _ in range(100):
bounds = torch.randn(2).sort()[0]
ts = Bounded(bounds[0].item(), bounds[1].item(), torch.Size((1,)), dtype=dtype)
_dtype = dtype
if dtype is None:
_dtype = torch.get_default_dtype()
r = ts.rand()
assert ts.is_in(r)
assert r.dtype is _dtype
ts.is_in(ts.encode(bounds.mean()))
ts.is_in(ts.encode(bounds.mean().item()))
assert (ts.encode(ts.to_numpy(r)) == r).all()
@pytest.mark.parametrize("cls", [OneHot, Categorical])
def test_discrete(cls):
torch.manual_seed(0)
np.random.seed(0)
ts = cls(10)
for _ in range(100):
r = ts.rand()
ts.to_numpy(r)
ts.encode(torch.tensor([5]))
ts.encode(torch.tensor(5).numpy())
ts.encode(9)
with pytest.raises(AssertionError), set_global_var(
torchrl.data.tensor_specs, "_CHECK_SPEC_ENCODE", True
):
ts.encode(torch.tensor([11])) # out of bounds
assert not torchrl.data.tensor_specs._CHECK_SPEC_ENCODE
assert ts.is_in(r)
assert (ts.encode(ts.to_numpy(r)) == r).all()
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.float64, None])
def test_unbounded(dtype):
torch.manual_seed(0)
np.random.seed(0)
ts = Unbounded(dtype=dtype)
if dtype is None:
dtype = torch.get_default_dtype()
for _ in range(100):
r = ts.rand()
ts.to_numpy(r)
assert ts.is_in(r)
assert r.dtype is dtype
assert (ts.encode(ts.to_numpy(r)) == r).all()
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.float64, None])
@pytest.mark.parametrize("shape", [[], torch.Size([3])])
def test_ndbounded(dtype, shape):
torch.manual_seed(0)
np.random.seed(0)
for _ in range(100):
lb = torch.rand(10) - 1
ub = torch.rand(10) + 1
ts = Bounded(lb, ub, dtype=dtype)
_dtype = dtype
if dtype is None:
_dtype = torch.get_default_dtype()
r = ts.rand(shape)
assert r.dtype is _dtype
assert r.shape == torch.Size([*shape, 10])
assert (r >= lb.to(dtype)).all() and (
r <= ub.to(dtype)
).all(), f"{r[r <= lb] - lb.expand_as(r)[r <= lb]} -- {r[r >= ub] - ub.expand_as(r)[r >= ub]} "
ts.to_numpy(r)
assert ts.is_in(r)
ts.encode(lb + torch.rand(10) * (ub - lb))
ts.encode((lb + torch.rand(10) * (ub - lb)).numpy())
if not shape:
assert (ts.encode(ts.to_numpy(r)) == r).all()
else:
with pytest.raises(RuntimeError, match="Shape mismatch"):
ts.encode(ts.to_numpy(r))
assert (ts.expand(*shape, *ts.shape).encode(ts.to_numpy(r)) == r).all()
with pytest.raises(AssertionError), set_global_var(
torchrl.data.tensor_specs, "_CHECK_SPEC_ENCODE", True
):
ts.encode(torch.rand(10) + 3) # out of bounds
with pytest.raises(AssertionError), set_global_var(
torchrl.data.tensor_specs, "_CHECK_SPEC_ENCODE", True
):
ts.to_numpy(torch.rand(10) + 3) # out of bounds
assert not torchrl.data.tensor_specs._CHECK_SPEC_ENCODE
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.float64, None])
@pytest.mark.parametrize("n", range(3, 10))
@pytest.mark.parametrize(
"shape",
[
[],
torch.Size(
[
3,
]
),
],
)
def test_ndunbounded(dtype, n, shape):
torch.manual_seed(0)
np.random.seed(0)
ts = Unbounded(
shape=[
n,
],
dtype=dtype,
)
if dtype is None:
dtype = torch.get_default_dtype()
for _ in range(100):
r = ts.rand(shape)
assert r.shape == torch.Size(
[
*shape,
n,
]
)
ts.to_numpy(r)
assert ts.is_in(r)
assert r.dtype is dtype
if not shape:
assert (ts.encode(ts.to_numpy(r)) == r).all()
else:
with pytest.raises(RuntimeError, match="Shape mismatch"):
ts.encode(ts.to_numpy(r))
assert (ts.expand(*shape, *ts.shape).encode(ts.to_numpy(r)) == r).all()
@pytest.mark.parametrize("n", range(3, 10))
@pytest.mark.parametrize(
"shape",
[
[],
torch.Size(
[
3,
]
),
],
)
def test_binary(n, shape):
torch.manual_seed(0)
np.random.seed(0)
ts = Binary(n)
for _ in range(100):
r = ts.rand(shape)
assert r.shape == torch.Size(
[
*shape,
n,
]
)
assert ts.is_in(r)
assert ((r == 0) | (r == 1)).all()
if not shape:
assert (ts.encode(ts.to_numpy(r)) == r).all()
else:
with pytest.raises(RuntimeError, match="Shape mismatch"):
ts.encode(ts.to_numpy(r))
assert (ts.expand(*shape, *ts.shape).encode(ts.to_numpy(r)) == r).all()
@pytest.mark.parametrize(
"ns",
[
[
5,
],
[5, 2, 3],
[4, 4, 1],
],
)
@pytest.mark.parametrize(
"shape",
[
[],
torch.Size(
[
3,
]
),
],
)
def test_mult_onehot(shape, ns):
torch.manual_seed(0)
np.random.seed(0)
ts = MultiOneHot(nvec=ns)
for _ in range(100):
r = ts.rand(shape)
assert r.shape == torch.Size(
[
*shape,
sum(ns),
]
)
assert ts.is_in(r)
assert ((r == 0) | (r == 1)).all()
rsplit = r.split(ns, dim=-1)
for _r, _n in zip(rsplit, ns):
assert (_r.sum(-1) == 1).all()
assert _r.shape[-1] == _n
categorical = ts.to_categorical(r)
assert not ts.is_in(categorical)
# assert (ts.encode(categorical) == r).all()
if not shape:
assert (ts.encode(categorical) == r).all()
else:
with pytest.raises(RuntimeError, match="is invalid for input of size"):
ts.encode(categorical)
assert (ts.expand(*shape, *ts.shape).encode(categorical) == r).all()
@pytest.mark.parametrize(
"ns",
[
5,
[5, 2, 3],
[4, 5, 1, 3],
[[1, 2], [3, 4]],
[[[2, 4], [3, 5]], [[4, 5], [2, 3]], [[2, 3], [3, 2]]],
],
)
@pytest.mark.parametrize("shape", [None, [], torch.Size([3]), torch.Size([4, 5])])
@pytest.mark.parametrize("dtype", [torch.float, torch.int, torch.long])
def test_multi_discrete(shape, ns, dtype):
torch.manual_seed(0)
np.random.seed(0)
ts = MultiCategorical(ns, dtype=dtype)
_real_shape = shape if shape is not None else []
nvec_shape = torch.tensor(ns).size()
for _ in range(100):
r = ts.rand(shape)
assert r.shape == torch.Size(
[
*_real_shape,
*nvec_shape,
]
), (r.shape, ns, shape, _real_shape, nvec_shape)
assert ts.is_in(r), (r, r.shape, ns)
rand = torch.rand(
torch.Size(
[
*_real_shape,
*nvec_shape,
]
)
)
projection = ts._project(rand)
assert rand.shape == projection.shape
assert ts.is_in(projection)
if projection.ndim < 1:
projection.fill_(-1)
else:
projection[..., 0] = -1
assert not ts.is_in(projection)
@pytest.mark.parametrize("n", [1, 4, 7, 99])
@pytest.mark.parametrize("device", get_default_devices())
@pytest.mark.parametrize("shape", [None, [], [1], [1, 2]])
def test_discrete_conversion(n, device, shape):
categorical = Categorical(n, device=device, shape=shape)
shape_one_hot = [n] if not shape else [*shape, n]
one_hot = OneHot(n, device=device, shape=shape_one_hot)
assert categorical != one_hot
assert categorical.to_one_hot_spec() == one_hot
assert one_hot.to_categorical_spec() == categorical
categorical_recon = one_hot.to_categorical(one_hot.rand(shape))
assert categorical.is_in(categorical_recon), (categorical, categorical_recon)
one_hot_recon = categorical.to_one_hot(categorical.rand(shape))
assert one_hot.is_in(one_hot_recon), (one_hot, one_hot_recon)
@pytest.mark.parametrize("ns", [[5], [5, 2, 3], [4, 5, 1, 3]])
@pytest.mark.parametrize("shape", [torch.Size([3]), torch.Size([4, 5])])
@pytest.mark.parametrize("device", get_default_devices())
def test_multi_discrete_conversion(ns, shape, device):
categorical = MultiCategorical(ns, device=device)
one_hot = MultiOneHot(ns, device=device)
assert categorical != one_hot
assert categorical.to_one_hot_spec() == one_hot
assert one_hot.to_categorical_spec() == categorical
categorical_recon = one_hot.to_categorical(one_hot.rand(shape))
assert categorical.is_in(categorical_recon), (categorical, categorical_recon)
one_hot_recon = categorical.to_one_hot(categorical.rand(shape))
assert one_hot.is_in(one_hot_recon), (one_hot, one_hot_recon)
@pytest.mark.parametrize("is_complete", [True, False])
@pytest.mark.parametrize("device", [None, *get_default_devices()])
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.float64, None])
@pytest.mark.parametrize("shape", [(), (2, 3)])
class TestComposite:
@staticmethod
def _composite_spec(shape, is_complete=True, device=None, dtype=None):
torch.manual_seed(0)
np.random.seed(0)
return Composite(
obs=Bounded(
torch.zeros(*shape, 3, 32, 32),
torch.ones(*shape, 3, 32, 32),
dtype=dtype,
device=device,
),
act=Unbounded(
(
*shape,
7,
),
dtype=dtype,
device=device,
)
if is_complete
else None,
shape=shape,
device=device,
)
def test_getitem(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
assert isinstance(ts["obs"], Bounded)
if is_complete:
assert isinstance(ts["act"], Unbounded)
else:
assert ts["act"] is None
with pytest.raises(KeyError):
_ = ts["UNK"]
def test_setitem_forbidden_keys(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
for key in {"shape", "device", "dtype", "space"}:
with pytest.raises(AttributeError, match="cannot be set"):
ts[key] = 42
@pytest.mark.parametrize("dest", get_available_devices())
def test_setitem_matches_device(self, shape, is_complete, device, dtype, dest):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["good"] = Unbounded(shape=shape, device=device, dtype=dtype)
cm = (
contextlib.nullcontext()
if (device == dest) or (device is None)
else pytest.raises(
RuntimeError, match="All devices of Composite must match"
)
)
with cm:
# auto-casting is introduced since v0.3
ts["bad"] = Unbounded(shape=shape, device=dest, dtype=dtype)
assert ts.device == device
assert ts["good"].device == (
device if device is not None else torch.zeros(()).device
)
assert ts["bad"].device == (device if device is not None else dest)
def test_del(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
assert "obs" in ts.keys()
assert "act" in ts.keys()
del ts["obs"]
assert "obs" not in ts.keys()
assert "act" in ts.keys()
def test_encode(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
if dtype is None:
dtype = torch.get_default_dtype()
for _ in range(100):
r = ts.rand()
raw_vals = {"obs": r["obs"].cpu().numpy()}
if is_complete:
raw_vals["act"] = r["act"].cpu().numpy()
encoded_vals = ts.encode(raw_vals)
assert encoded_vals["obs"].dtype == dtype
assert (encoded_vals["obs"] == r["obs"]).all()
if is_complete:
assert encoded_vals["act"].dtype == dtype
assert (encoded_vals["act"] == r["act"]).all()
def test_is_in(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
for _ in range(100):
r = ts.rand()
assert ts.is_in(r)
def test_to_numpy(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
for _ in range(100):
r = ts.rand()
for key, value in ts.to_numpy(r).items():
spec = ts[key]
assert (spec.to_numpy(r[key]) == value).all()
@pytest.mark.parametrize("shape_other", [[], [5]])
def test_project(self, shape, is_complete, device, dtype, shape_other):
ts = self._composite_spec(shape, is_complete, device, dtype)
# Using normal distribution to get out of bounds
shape = (*shape_other, *shape)
tensors = {"obs": torch.randn(*shape, 3, 32, 32, dtype=dtype, device=device)}
if is_complete:
tensors["act"] = torch.randn(*shape, 7, dtype=dtype, device=device)
out_of_bounds_td = TensorDict(tensors, batch_size=shape)
assert not ts.is_in(out_of_bounds_td)
ts.project(out_of_bounds_td)
assert ts.is_in(out_of_bounds_td)
assert out_of_bounds_td.shape == torch.Size(shape)
@pytest.mark.parametrize("shape_other", [[], [3]])
def test_rand(self, shape, is_complete, device, dtype, shape_other):
ts = self._composite_spec(shape, is_complete, device, dtype)
if dtype is None:
dtype = torch.get_default_dtype()
shape = (*shape_other, *shape)
rand_td = ts.rand(shape_other)
assert rand_td.shape == torch.Size(shape)
assert rand_td.get("obs").shape == torch.Size([*shape, 3, 32, 32])
assert rand_td.get("obs").dtype == dtype
if is_complete:
assert rand_td.get("act").shape == torch.Size([*shape, 7])
assert rand_td.get("act").dtype == dtype
def test_repr(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
output = repr(ts)
assert output.startswith("Composite")
assert "obs: " in output
assert "act: " in output
def test_device_cast_with_dtype_fails(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
with pytest.raises(ValueError, match="Only device casting is allowed"):
ts.to(torch.float16)
@pytest.mark.parametrize("dest", get_available_devices())
def test_device_cast(self, shape, is_complete, device, dtype, dest):
# Note: trivial test in case there is only one device available.
ts = self._composite_spec(shape, is_complete, device, dtype)
ts.rand()
td_to = ts.to(dest)
cast_r = td_to.rand()
assert td_to.device == dest
assert cast_r["obs"].device == dest
if is_complete:
assert cast_r["act"].device == dest
def test_type_check(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
rand_td = ts.rand()
ts.type_check(rand_td)
ts.type_check(rand_td["obs"], "obs")
if is_complete:
ts.type_check(rand_td["act"], "act")
def test_nested_composite_spec(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
assert set(ts.keys()) == {
"obs",
"act",
"nested_cp",
}
assert set(ts.keys(include_nested=True)) == {
"obs",
"act",
"nested_cp",
("nested_cp", "obs"),
("nested_cp", "act"),
}
assert set(ts.keys(include_nested=True, leaves_only=True)) == {
"obs",
"act",
("nested_cp", "obs"),
("nested_cp", "act"),
}
assert set(ts.keys(leaves_only=True)) == {
"obs",
"act",
}
td = ts.rand()
assert isinstance(td["nested_cp"], TensorDictBase)
keys = list(td.keys())
for key in keys:
if key != "nested_cp":
assert key in td["nested_cp"].keys()
def test_nested_composite_spec_index(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"]["nested_cp"] = self._composite_spec(
shape, is_complete, device, dtype
)
assert ts["nested_cp"]["nested_cp"] is ts["nested_cp", "nested_cp"]
assert (
ts["nested_cp"]["nested_cp"]["obs"] is ts["nested_cp", "nested_cp", "obs"]
)
def test_nested_composite_spec_rand(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"]["nested_cp"] = self._composite_spec(
shape, is_complete, device, dtype
)
r = ts.rand()
assert (r["nested_cp", "nested_cp", "obs"] >= 0).all()
def test_nested_composite_spec_zero(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"]["nested_cp"] = self._composite_spec(
shape, is_complete, device, dtype
)
r = ts.zero()
assert (r["nested_cp", "nested_cp", "obs"] == 0).all()
def test_nested_composite_spec_setitem(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"]["nested_cp"] = self._composite_spec(
shape, is_complete, device, dtype
)
ts["nested_cp", "nested_cp", "obs"] = None
assert (
ts["nested_cp"]["nested_cp"]["obs"] is ts["nested_cp", "nested_cp", "obs"]
)
assert ts["nested_cp"]["nested_cp"]["obs"] is None
ts["nested_cp", "another", "obs"] = None
def test_nested_composite_spec_delitem(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"]["nested_cp"] = self._composite_spec(
shape, is_complete, device, dtype
)
del ts["nested_cp", "nested_cp", "obs"]
assert ("nested_cp", "nested_cp", "obs") not in ts.keys(True, True)
def test_nested_composite_spec_update(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
td2 = Composite(new=None)
ts.update(td2)
assert set(ts.keys(include_nested=True)) == {
"obs",
"act",
"nested_cp",
("nested_cp", "obs"),
("nested_cp", "act"),
"new",
}
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
td2 = Composite(nested_cp=Composite(new=None).to(device))
ts.update(td2)
assert set(ts.keys(include_nested=True)) == {
"obs",
"act",
"nested_cp",
("nested_cp", "obs"),
("nested_cp", "act"),
("nested_cp", "new"),
}
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
td2 = Composite(nested_cp=Composite(act=None).to(device))
ts.update(td2)
assert set(ts.keys(include_nested=True)) == {
"obs",
"act",
"nested_cp",
("nested_cp", "obs"),
("nested_cp", "act"),
}
assert ts["nested_cp"]["act"] is None
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested_cp"] = self._composite_spec(shape, is_complete, device, dtype)
td2 = Composite(
nested_cp=Composite(act=None, shape=shape).to(device), shape=shape
)
ts.update(td2)
td2 = Composite(
nested_cp=Composite(
act=Unbounded(shape=shape, device=device),
shape=shape,
),
shape=shape,
)
ts.update(td2)
assert set(ts.keys(include_nested=True)) == {
"obs",
"act",
"nested_cp",
("nested_cp", "obs"),
("nested_cp", "act"),
}
assert ts["nested_cp"]["act"] is not None
def test_change_batch_size(self, shape, is_complete, device, dtype):
ts = self._composite_spec(shape, is_complete, device, dtype)
ts["nested"] = Composite(
leaf=Unbounded(shape, device=device),
shape=shape,
device=device,
)
ts = ts.expand(3, *shape)
assert ts["nested"].shape == (3, *shape)
assert ts["nested", "leaf"].shape == (3, *shape)
ts.shape = ()
# this does not change
assert ts["nested"].shape == (3, *shape)
assert ts.shape == ()
ts["nested"].shape = ()
ts.shape = (3,)
assert ts.shape == (3,)
assert ts["nested"].shape == (3,)
@pytest.mark.parametrize("shape", [(), (2, 3)])
@pytest.mark.parametrize("device", get_default_devices())
def test_create_composite_nested(shape, device):
d = [
{("a", "b"): Unbounded(shape=shape, device=device)},
{"a": {"b": Unbounded(shape=shape, device=device)}},
]
for _d in d:
c = Composite(_d, shape=shape)
assert isinstance(c["a", "b"], Unbounded)
assert c["a"].shape == torch.Size(shape)
assert c.device is None # device not explicitly passed
assert c["a"].device is None # device not explicitly passed
assert c["a", "b"].device == device
c = c.to(device)
assert c.device == device
assert c["a"].device == device
@pytest.mark.parametrize("recurse", [True, False])
def test_lock(recurse):
shape = [3, 4, 5]
spec = Composite(
a=Composite(b=Composite(shape=shape[:3], device="cpu"), shape=shape[:2]),
shape=shape[:1],
)
spec["a"] = spec["a"].clone()
spec["a", "b"] = spec["a", "b"].clone()
assert not spec.locked
spec.lock_(recurse=recurse)
assert spec.locked
with pytest.raises(RuntimeError, match="Cannot modify a locked Composite."):
spec["a"] = spec["a"].clone()
with pytest.raises(RuntimeError, match="Cannot modify a locked Composite."):
spec.set("a", spec["a"].clone())
if recurse:
assert spec["a"].locked
with pytest.raises(RuntimeError, match="Cannot modify a locked Composite."):
spec["a"].set("b", spec["a", "b"].clone())
with pytest.raises(RuntimeError, match="Cannot modify a locked Composite."):
spec["a", "b"] = spec["a", "b"].clone()
else:
assert not spec["a"].locked
spec["a", "b"] = spec["a", "b"].clone()
spec["a"].set("b", spec["a", "b"].clone())
spec.unlock_(recurse=recurse)
spec["a"] = spec["a"].clone()
spec["a", "b"] = spec["a", "b"].clone()
spec["a"].set("b", spec["a", "b"].clone())
def test_keys_to_empty_composite_spec():
keys = [("key1", "out"), ("key1", "in"), "key2", ("key1", "subkey1", "subkey2")]
composite = _keys_to_empty_composite_spec(keys)
assert set(composite.keys(True, True)) == set(keys)
class TestEquality:
"""Tests spec comparison."""
@staticmethod
def _ts_make_all_fields_equal(ts_to, ts_from):
ts_to.shape = ts_from.shape
ts_to.space = ts_from.space
ts_to.device = ts_from.device
ts_to.dtype = ts_from.dtype
ts_to.domain = ts_from.domain
return ts_to
def test_equality_bounded(self):
minimum = 10
maximum = 100
device = "cpu"
dtype = torch.float16
ts = Bounded(minimum, maximum, torch.Size((1,)), device, dtype)
ts_same = Bounded(minimum, maximum, torch.Size((1,)), device, dtype)
assert ts == ts_same
ts_other = Bounded(minimum + 1, maximum, torch.Size((1,)), device, dtype)
assert ts != ts_other
ts_other = Bounded(minimum, maximum + 1, torch.Size((1,)), device, dtype)
assert ts != ts_other
if torch.cuda.device_count():
ts_other = Bounded(minimum, maximum, torch.Size((1,)), "cuda:0", dtype)
assert ts != ts_other
ts_other = Bounded(minimum, maximum, torch.Size((1,)), device, torch.float64)
assert ts != ts_other
ts_other = TestEquality._ts_make_all_fields_equal(
Unbounded(device=device, dtype=dtype), ts
)
assert ts != ts_other
def test_equality_onehot(self):
n = 5
device = "cpu"
dtype = torch.float16
use_register = False
ts = OneHot(n=n, device=device, dtype=dtype, use_register=use_register)
ts_same = OneHot(n=n, device=device, dtype=dtype, use_register=use_register)
assert ts == ts_same
ts_other = OneHot(
n=n + 1, device=device, dtype=dtype, use_register=use_register
)
assert ts != ts_other
if torch.cuda.device_count():
ts_other = OneHot(
n=n, device="cuda:0", dtype=dtype, use_register=use_register
)
assert ts != ts_other
ts_other = OneHot(
n=n, device=device, dtype=torch.float64, use_register=use_register
)
assert ts != ts_other
ts_other = OneHot(
n=n, device=device, dtype=dtype, use_register=not use_register
)
assert ts != ts_other
ts_other = TestEquality._ts_make_all_fields_equal(
Unbounded(device=device, dtype=dtype), ts
)
assert ts != ts_other
def test_equality_unbounded(self):
device = "cpu"
dtype = torch.float16
ts = Unbounded(device=device, dtype=dtype)
ts_same = Unbounded(device=device, dtype=dtype)
assert ts == ts_same
if torch.cuda.device_count():
ts_other = Unbounded(device="cuda:0", dtype=dtype)
assert ts != ts_other
ts_other = Unbounded(device=device, dtype=torch.float64)
assert ts != ts_other
ts_other = TestEquality._ts_make_all_fields_equal(
Bounded(0, 1, torch.Size((1,)), device, dtype), ts
)
ts_other.space = ContinuousBox(
ts_other.space.low * 0, ts_other.space.high * 0 + 1
)
assert ts.space != ts_other.space, (ts.space, ts_other.space)
assert ts != ts_other
def test_equality_ndbounded(self):
minimum = np.arange(12).reshape((3, 4))
maximum = minimum + 100
device = "cpu"
dtype = torch.float16
ts = Bounded(low=minimum, high=maximum, device=device, dtype=dtype)
ts_same = Bounded(low=minimum, high=maximum, device=device, dtype=dtype)
assert ts == ts_same
ts_other = Bounded(low=minimum + 1, high=maximum, device=device, dtype=dtype)
assert ts != ts_other
ts_other = Bounded(low=minimum, high=maximum + 1, device=device, dtype=dtype)
assert ts != ts_other
if torch.cuda.device_count():
ts_other = Bounded(low=minimum, high=maximum, device="cuda:0", dtype=dtype)
assert ts != ts_other
ts_other = Bounded(
low=minimum, high=maximum, device=device, dtype=torch.float64
)
assert ts != ts_other
ts_other = TestEquality._ts_make_all_fields_equal(
Unbounded(device=device, dtype=dtype), ts
)
assert ts != ts_other
def test_equality_discrete(self):
n = 5
shape = torch.Size([1])
device = "cpu"
dtype = torch.float16
ts = Categorical(n=n, shape=shape, device=device, dtype=dtype)
ts_same = Categorical(n=n, shape=shape, device=device, dtype=dtype)
assert ts == ts_same
ts_other = Categorical(n=n + 1, shape=shape, device=device, dtype=dtype)
assert ts != ts_other
if torch.cuda.device_count():
ts_other = Categorical(n=n, shape=shape, device="cuda:0", dtype=dtype)
assert ts != ts_other
ts_other = Categorical(n=n, shape=shape, device=device, dtype=torch.float64)
assert ts != ts_other
ts_other = Categorical(
n=n, shape=torch.Size([2]), device=device, dtype=torch.float64
)
assert ts != ts_other
ts_other = TestEquality._ts_make_all_fields_equal(
Unbounded(device=device, dtype=dtype), ts
)
assert ts != ts_other
@pytest.mark.parametrize(
"shape",
[
3,
torch.Size([4]),
torch.Size([5, 6]),
],
)
def test_equality_ndunbounded(self, shape):
device = "cpu"
dtype = torch.float16
ts = Unbounded(shape=shape, device=device, dtype=dtype)
ts_same = Unbounded(shape=shape, device=device, dtype=dtype)
assert ts == ts_same
other_shape = 13 if isinstance(shape, int) else torch.Size(np.array(shape) + 10)
ts_other = Unbounded(shape=other_shape, device=device, dtype=dtype)
assert ts != ts_other
if torch.cuda.device_count():
ts_other = Unbounded(shape=shape, device="cuda:0", dtype=dtype)
assert ts != ts_other
ts_other = Unbounded(shape=shape, device=device, dtype=torch.float64)
assert ts != ts_other
ts_other = TestEquality._ts_make_all_fields_equal(
Bounded(0, 1, torch.Size((1,)), device, dtype), ts
)
# Unbounded and bounded without space are technically the same
assert ts == ts_other
def test_equality_binary(self):
n = 5
device = "cpu"
dtype = torch.float16
ts = Binary(n=n, device=device, dtype=dtype)
ts_same = Binary(n=n, device=device, dtype=dtype)
assert ts == ts_same
ts_other = Binary(n=n + 5, device=device, dtype=dtype)
assert ts != ts_other
if torch.cuda.device_count():
ts_other = Binary(n=n, device="cuda:0", dtype=dtype)
assert ts != ts_other
ts_other = Binary(n=n, device=device, dtype=torch.float64)
assert ts != ts_other
ts_other = TestEquality._ts_make_all_fields_equal(
Bounded(0, 1, torch.Size((1,)), device, dtype), ts
)
assert ts != ts_other
@pytest.mark.parametrize("nvec", [[3], [3, 4], [3, 4, 5]])
def test_equality_multi_onehot(self, nvec):
device = "cpu"
dtype = torch.float16
ts = MultiOneHot(nvec=nvec, device=device, dtype=dtype)
ts_same = MultiOneHot(nvec=nvec, device=device, dtype=dtype)
assert ts == ts_same
other_nvec = np.array(nvec) + 3
ts_other = MultiOneHot(nvec=other_nvec, device=device, dtype=dtype)
assert ts != ts_other
other_nvec = [12]
ts_other = MultiOneHot(nvec=other_nvec, device=device, dtype=dtype)
assert ts != ts_other
other_nvec = [12, 13]
ts_other = MultiOneHot(nvec=other_nvec, device=device, dtype=dtype)
assert ts != ts_other
if torch.cuda.device_count():
ts_other = MultiOneHot(nvec=nvec, device="cuda:0", dtype=dtype)