forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tensor_specs.py
2015 lines (1728 loc) · 70.4 KB
/
tensor_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.
from __future__ import annotations
import abc
import warnings
from copy import deepcopy
from dataclasses import dataclass
from textwrap import indent
from typing import (
Any,
Dict,
ItemsView,
KeysView,
List,
Optional,
Sequence,
Tuple,
Union,
ValuesView,
)
import numpy as np
import torch
from tensordict.tensordict import TensorDict, TensorDictBase
from torchrl._utils import get_binary_env_var
_CHECK_IMAGES = get_binary_env_var("CHECK_IMAGES")
DEVICE_TYPING = Union[torch.device, str, int]
INDEX_TYPING = Union[int, torch.Tensor, np.ndarray, slice, List]
# By default, we do not check that an obs is in the domain. THis should be done when validating the env beforehand
_CHECK_SPEC_ENCODE = get_binary_env_var("CHECK_SPEC_ENCODE")
_DEFAULT_SHAPE = torch.Size((1,))
DEVICE_ERR_MSG = "device of empty CompositeSpec is not defined."
def _default_dtype_and_device(
dtype: Union[None, torch.dtype],
device: Union[None, str, int, torch.device],
) -> Tuple[torch.dtype, torch.device]:
if dtype is None:
dtype = torch.get_default_dtype()
if device is None:
device = torch.device("cpu")
device = torch.device(device)
return dtype, device
class invertible_dict(dict):
"""An invertible dictionary.
Examples:
>>> my_dict = invertible_dict(a=3, b=2)
>>> inv_dict = my_dict.invert()
>>> assert {2, 3} == set(inv_dict.keys())
"""
def __init__(self, *args, inv_dict=None, **kwargs):
if inv_dict is None:
inv_dict = {}
super().__init__(*args, **kwargs)
self.inv_dict = inv_dict
def __setitem__(self, k, v):
if v in self.inv_dict or k in self:
raise Exception("overwriting in invertible_dict is not permitted")
self.inv_dict[v] = k
return super().__setitem__(k, v)
def update(self, d):
raise NotImplementedError
def invert(self):
d = invertible_dict()
for k, value in self.items():
d[value] = k
return d
def inverse(self):
return self.inv_dict
class Box:
"""A box of values."""
def __iter__(self):
raise NotImplementedError
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> ContinuousBox:
raise NotImplementedError
def __repr__(self):
return f"{self.__class__.__name__}()"
def clone(self) -> DiscreteBox:
return deepcopy(self)
@dataclass(repr=False)
class ContinuousBox(Box):
"""A continuous box of values, in between a minimum and a maximum."""
_minimum: torch.Tensor
_maximum: torch.Tensor
device: torch.device = None
# We store the tensors on CPU to avoid overloading CUDA with tensors that are rarely used.
@property
def minimum(self):
return self._minimum.to(self.device)
@property
def maximum(self):
return self._maximum.to(self.device)
@minimum.setter
def minimum(self, value):
self.device = value.device
self._minimum = value.cpu()
@maximum.setter
def maximum(self, value):
self.device = value.device
self._maximum = value.cpu()
def __post_init__(self):
self.minimum = self.minimum.clone()
self.maximum = self.maximum.clone()
def __iter__(self):
yield self.minimum
yield self.maximum
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> ContinuousBox:
return self.__class__(self.minimum.to(dest), self.maximum.to(dest))
def clone(self) -> ContinuousBox:
return self.__class__(self.minimum.clone(), self.maximum.clone())
def __repr__(self):
min_str = f"minimum=Tensor(shape={self.minimum.shape}, device={self.minimum.device}, dtype={self.minimum.dtype}, contiguous={self.maximum.is_contiguous()})"
max_str = f"maximum=Tensor(shape={self.maximum.shape}, device={self.maximum.device}, dtype={self.maximum.dtype}, contiguous={self.maximum.is_contiguous()})"
return f"{self.__class__.__name__}({min_str}, {max_str})"
def __eq__(self, other):
return (
type(self) == type(other)
and self.minimum.dtype == other.minimum.dtype
and self.maximum.dtype == other.maximum.dtype
and torch.equal(self.minimum, other.minimum)
and torch.equal(self.maximum, other.maximum)
)
@dataclass(repr=False)
class DiscreteBox(Box):
"""A box of discrete values."""
n: int
register = invertible_dict()
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> DiscreteBox:
return deepcopy(self)
def __repr__(self):
return f"{self.__class__.__name__}(n={self.n})"
@dataclass(repr=False)
class BoxList(Box):
"""A box of discrete values."""
boxes: List
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> BoxList:
return BoxList([box.to(dest) for box in self.boxes])
def __iter__(self):
for elt in self.boxes:
yield elt
def __repr__(self):
return f"{self.__class__.__name__}(boxes={self.boxes})"
def __len__(self):
return len(self.boxes)
@staticmethod
def from_nvec(nvec: torch.Tensor):
if nvec.ndim == 0:
return DiscreteBox(nvec.item())
else:
return BoxList([BoxList.from_nvec(n) for n in nvec.unbind(-1)])
@dataclass(repr=False)
class BinaryBox(Box):
"""A box of n binary values."""
n: int
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> ContinuousBox:
return deepcopy(self)
def __repr__(self):
return f"{self.__class__.__name__}(n={self.n})"
@dataclass(repr=False)
class TensorSpec:
"""Parent class of the tensor meta-data containers for observation, actions and rewards.
Args:
shape (torch.Size): size of the tensor
space (Box): Box instance describing what kind of values can be
expected
device (torch.device): device of the tensor
dtype (torch.dtype): dtype of the tensor
"""
shape: torch.Size
space: Union[None, Box]
device: torch.device = torch.device("cpu")
dtype: torch.dtype = torch.float
domain: str = ""
def encode(self, val: Union[np.ndarray, torch.Tensor]) -> torch.Tensor:
"""Encodes a value given the specified spec, and return the corresponding tensor.
Args:
val (np.ndarray or torch.Tensor): value to be encoded as tensor.
Returns:
torch.Tensor matching the required tensor specs.
"""
if not isinstance(val, torch.Tensor):
if isinstance(val, list):
if len(val) == 1:
# gym used to return lists of images since 0.26.0
# We convert these lists in np.array or take the first element
# if there is just one.
# See https://github.com/pytorch/rl/pull/403/commits/73d77d033152c61d96126ccd10a2817fecd285a1
val = val[0]
else:
val = np.array(val)
if _CHECK_IMAGES and val.dtype is np.dtype("uint8"):
# images can become noisy during training. if the CHECK_IMAGES
# env variable is True, we check that no more than half of the
# pixels are black or white.
v = (val == 0) | (val == 255)
v = v.sum() / v.size
assert v < 0.5, f"numpy: {val.shape}"
if isinstance(val, np.ndarray) and not all(
stride > 0 for stride in val.strides
):
val = val.copy()
val = torch.tensor(val, dtype=self.dtype, device=self.device)
if val.shape[-len(self.shape) :] != self.shape:
# option 1: add a singleton dim at the end
if (
val.shape[-len(self.shape) :] == self.shape[:-1]
and self.shape[-1] == 1
):
val = val.unsqueeze(-1)
else:
raise RuntimeError(
f"Shape mismatch: the value has shape {val.shape} which "
f"is incompatible with the spec shape {self.shape}."
)
if _CHECK_SPEC_ENCODE:
self.assert_is_in(val)
return val
def __setattr__(self, key, value):
if key == "shape":
value = torch.Size(value)
super().__setattr__(key, value)
def to_numpy(self, val: torch.Tensor, safe: bool = True) -> np.ndarray:
"""Returns the np.ndarray correspondent of an input tensor.
Args:
val (torch.Tensor): tensor to be transformed_in to numpy
safe (bool): boolean value indicating whether a check should be
performed on the value against the domain of the spec.
Returns:
a np.ndarray
"""
if safe:
self.assert_is_in(val)
return val.detach().cpu().numpy()
@property
def ndim(self):
return self.ndimension()
def ndimension(self):
return len(self.shape)
@abc.abstractmethod
def index(self, index: INDEX_TYPING, tensor_to_index: torch.Tensor) -> torch.Tensor:
"""Indexes the input tensor.
Args:
index (int, torch.Tensor, slice or list): index of the tensor
tensor_to_index: tensor to be indexed
Returns:
indexed tensor
"""
raise NotImplementedError
@abc.abstractmethod
def expand(self, *shape):
"""Returns a new Spec with the extended shape.
Args:
*shape (tuple or iterable of int): the new shape of the Spec. Must comply with the current shape:
its length must be at least as long as the current shape length,
and its last values must be complient too; ie they can only differ
from it if the current dimension is a singleton.
"""
raise NotImplementedError
def _project(self, val: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@abc.abstractmethod
def is_in(self, val: torch.Tensor) -> bool:
"""If the value :obj:`val` is in the box defined by the TensorSpec, returns True, otherwise False.
Args:
val (torch.Tensor): value to be checked
Returns:
boolean indicating if values belongs to the TensorSpec box
"""
raise NotImplementedError
def project(self, val: torch.Tensor) -> torch.Tensor:
"""If the input tensor is not in the TensorSpec box, it maps it back to it given some heuristic.
Args:
val (torch.Tensor): tensor to be mapped to the box.
Returns:
a torch.Tensor belonging to the TensorSpec box.
"""
if not self.is_in(val):
return self._project(val)
return val
def assert_is_in(self, value: torch.Tensor) -> None:
"""Asserts whether a tensor belongs to the box, and raises an exception otherwise.
Args:
value (torch.Tensor): value to be checked.
"""
if not self.is_in(value):
raise AssertionError(
f"Encoding failed because value is not in space. "
f"Consider calling project(val) first. value was = {value} "
f"and spec was {self}."
)
def type_check(self, value: torch.Tensor, key: str = None) -> None:
"""Checks the input value dtype against the TensorSpec dtype and raises an exception if they don't match.
Args:
value (torch.Tensor): tensor whose dtype has to be checked
key (str, optional): if the TensorSpec has keys, the value
dtype will be checked against the spec pointed by the
indicated key.
"""
if value.dtype is not self.dtype:
raise TypeError(
f"value.dtype={value.dtype} but"
f" {self.__class__.__name__}.dtype={self.dtype}"
)
@abc.abstractmethod
def rand(self, shape=None) -> torch.Tensor:
"""Returns a random tensor in the box. The sampling will be uniform unless the box is unbounded.
Args:
shape (torch.Size): shape of the random tensor
Returns:
a random tensor sampled in the TensorSpec box.
"""
raise NotImplementedError
def zero(self, shape=None) -> torch.Tensor:
"""Returns a zero-filled tensor in the box.
Args:
shape (torch.Size): shape of the zero-tensor
Returns:
a zero-filled tensor sampled in the TensorSpec box.
"""
if shape is None:
shape = torch.Size([])
return torch.zeros((*shape, *self.shape), dtype=self.dtype, device=self.device)
@abc.abstractmethod
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> "TensorSpec":
raise NotImplementedError
@abc.abstractmethod
def clone(self) -> "TensorSpec":
raise NotImplementedError
def __repr__(self):
shape_str = "shape=" + str(self.shape)
space_str = "space=" + str(self.space)
device_str = "device=" + str(self.device)
dtype_str = "dtype=" + str(self.dtype)
domain_str = "domain=" + str(self.domain)
sub_string = ", ".join(
[shape_str, space_str, device_str, dtype_str, domain_str]
)
string = f"{self.__class__.__name__}(\n {sub_string})"
return string
@dataclass(repr=False)
class OneHotDiscreteTensorSpec(TensorSpec):
"""A unidimensional, one-hot discrete tensor spec.
By default, TorchRL assumes that categorical variables are encoded as
one-hot encodings of the variable. This allows for simple indexing of
tensors, e.g.
>>> batch, size = 3, 4
>>> action_value = torch.arange(batch*size)
>>> action_value = action_value.view(batch, size).to(torch.float)
>>> action = (action_value == action_value.max(-1,
... keepdim=True)[0]).to(torch.long)
>>> chosen_action_value = (action * action_value).sum(-1)
>>> print(chosen_action_value)
tensor([ 3., 7., 11.])
Args:
n (int): number of possible outcomes.
shape (torch.Size, optional): total shape of the sampled tensors.
If provided, the last dimension must match n.
device (str, int or torch.device, optional): device of the tensors.
dtype (str or torch.dtype, optional): dtype of the tensors.
user_register (bool): experimental feature. If True, every integer
will be mapped onto a binary vector in the order in which they
appear. This feature is designed for environment with no
a-priori definition of the number of possible outcomes (e.g.
discrete outcomes are sampled from an arbitrary set, whose
elements will be mapped in a register to a series of unique
one-hot binary vectors).
"""
shape: torch.Size
space: DiscreteBox
device: torch.device = torch.device("cpu")
dtype: torch.dtype = torch.float
domain: str = ""
def __init__(
self,
n: int,
shape: Optional[torch.Size] = None,
device: Optional[DEVICE_TYPING] = None,
dtype: Optional[Union[str, torch.dtype]] = torch.long,
use_register: bool = False,
):
dtype, device = _default_dtype_and_device(dtype, device)
self.use_register = use_register
space = DiscreteBox(
n,
)
if shape is None:
shape = torch.Size((space.n,))
else:
shape = torch.Size(shape)
if not len(shape) or shape[-1] != space.n:
raise ValueError(
f"The last value of the shape must match n for transform of type {self.__class__}. "
f"Got n={space.n} and shape={shape}."
)
super().__init__(shape, space, device, dtype, "discrete")
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> CompositeSpec:
if isinstance(dest, torch.dtype):
dest_dtype = dest
dest_device = self.device
else:
dest_dtype = self.dtype
dest_device = torch.device(dest)
return self.__class__(
n=self.space.n,
shape=self.shape,
device=dest_device,
dtype=dest_dtype,
use_register=self.use_register,
)
def clone(self) -> CompositeSpec:
return self.__class__(
n=self.space.n,
shape=self.shape,
device=self.device,
dtype=self.dtype,
use_register=self.use_register,
)
def expand(self, *shape):
if len(shape) == 1 and isinstance(shape[0], (tuple, list, torch.Size)):
shape = shape[0]
if any(val < 0 for val in shape):
raise ValueError(
f"{self.__class__.__name__}.extend does not support negative shapes."
)
if any(s1 != s2 and s2 != 1 for s1, s2 in zip(shape[-self.ndim :], self.shape)):
raise ValueError(
f"The last {self.ndim} of the extended shape must match the"
f"shape of the CompositeSpec in CompositeSpec.extend."
)
return self.__class__(
n=shape[-1], shape=shape, device=self.device, dtype=self.dtype
)
def rand(self, shape=None) -> torch.Tensor:
if shape is None:
shape = self.shape[:-1]
else:
shape = torch.Size([*shape, *self.shape[:-1]])
return torch.nn.functional.gumbel_softmax(
torch.rand(torch.Size([*shape, self.space.n]), device=self.device),
hard=True,
dim=-1,
).to(torch.long)
def encode(
self,
val: Union[np.ndarray, torch.Tensor],
space: Optional[DiscreteBox] = None,
) -> torch.Tensor:
if not isinstance(val, torch.Tensor):
val = torch.tensor(val, dtype=self.dtype, device=self.device)
if space is None:
space = self.space
if self.use_register:
if val not in space.register:
space.register[val] = len(space.register)
val = space.register[val]
if (val >= space.n).any():
raise AssertionError("Value must be less than action space.")
val = torch.nn.functional.one_hot(val.long(), space.n)
return val
def to_numpy(self, val: torch.Tensor, safe: bool = True) -> np.ndarray:
if safe:
if not isinstance(val, torch.Tensor):
raise NotImplementedError
self.assert_is_in(val)
val = val.argmax(-1).cpu().numpy()
if self.use_register:
inv_reg = self.space.register.inverse()
vals = []
for _v in val.view(-1):
vals.append(inv_reg[int(_v)])
return np.array(vals).reshape(tuple(val.shape))
return val
def index(self, index: INDEX_TYPING, tensor_to_index: torch.Tensor) -> torch.Tensor:
if not isinstance(index, torch.Tensor):
raise ValueError(
f"Only tensors are allowed for indexing using "
f"{self.__class__.__name__}.index(...)"
)
index = index.nonzero().squeeze()
index = index.expand(*tensor_to_index.shape[:-1], index.shape[-1])
return tensor_to_index.gather(-1, index)
def _project(self, val: torch.Tensor) -> torch.Tensor:
# idx = val.sum(-1) != 1
out = torch.nn.functional.gumbel_softmax(val.to(torch.float))
out = (out == out.max(dim=-1, keepdim=True)[0]).to(torch.long)
return out
def is_in(self, val: torch.Tensor) -> bool:
return (val.sum(-1) == 1).all()
def __eq__(self, other):
return (
type(self) == type(other)
and self.shape == other.shape
and self.space == other.space
and self.device == other.device
and self.dtype == other.dtype
and self.domain == other.domain
and self.use_register == other.use_register
)
def to_categorical(self) -> DiscreteTensorSpec:
return DiscreteTensorSpec(
self.space.n, device=self.device, dtype=self.dtype, shape=self.shape[:-1]
)
@dataclass(repr=False)
class BoundedTensorSpec(TensorSpec):
"""A bounded continuous tensor spec.
Args:
minimum (np.ndarray, torch.Tensor or number): lower bound of the box.
maximum (np.ndarray, torch.Tensor or number): upper bound of the box.
device (str, int or torch.device, optional): device of the tensors.
dtype (str or torch.dtype, optional): dtype of the tensors.
"""
def __init__(
self,
minimum: Union[float, torch.Tensor, np.ndarray],
maximum: Union[float, torch.Tensor, np.ndarray],
shape: Optional[Union[torch.Size, int]] = None,
device: Optional[DEVICE_TYPING] = None,
dtype: Optional[Union[torch.dtype, str]] = None,
):
dtype, device = _default_dtype_and_device(dtype, device)
if dtype is None:
dtype = torch.get_default_dtype()
if device is None:
device = torch._get_default_device()
if not isinstance(minimum, torch.Tensor):
minimum = torch.tensor(minimum, dtype=dtype, device=device)
if not isinstance(maximum, torch.Tensor):
maximum = torch.tensor(maximum, dtype=dtype, device=device)
if maximum.device != device:
maximum = maximum.to(device)
if minimum.device != device:
minimum = minimum.to(device)
if dtype is not None and minimum.dtype is not dtype:
minimum = minimum.to(dtype)
if dtype is not None and maximum.dtype is not dtype:
maximum = maximum.to(dtype)
err_msg = (
"BoundedTensorSpec requires the shape to be explicitely (via "
"the shape argument) or implicitely defined (via either the "
"minimum or the maximum or both). If the maximum and/or the "
"minimum have a non-singleton shape, they must match the "
"provided shape if this one is set explicitely."
)
if shape is not None and not isinstance(shape, torch.Size):
if isinstance(shape, int):
shape = torch.Size([shape])
else:
shape = torch.Size(list(shape))
if maximum.ndimension():
if shape is not None and shape != maximum.shape:
raise RuntimeError(err_msg)
shape = maximum.shape
minimum = minimum.expand(*shape).clone()
elif minimum.ndimension():
if shape is not None and shape != minimum.shape:
raise RuntimeError(err_msg)
shape = minimum.shape
maximum = maximum.expand(*shape).clone()
elif shape is None:
raise RuntimeError(err_msg)
else:
minimum = minimum.expand(*shape).clone()
maximum = maximum.expand(*shape).clone()
if minimum.numel() > maximum.numel():
maximum = maximum.expand_as(minimum).clone()
elif maximum.numel() > minimum.numel():
minimum = minimum.expand_as(maximum).clone()
if shape is None:
shape = minimum.shape
else:
if isinstance(shape, float):
shape = torch.Size([shape])
elif not isinstance(shape, torch.Size):
shape = torch.Size(shape)
shape_err_msg = (
f"minimum and shape mismatch, got {minimum.shape} and {shape}"
)
if len(minimum.shape) != len(shape):
raise RuntimeError(shape_err_msg)
if not all(_s == _sa for _s, _sa in zip(shape, minimum.shape)):
raise RuntimeError(shape_err_msg)
self.shape = shape
super().__init__(
shape, ContinuousBox(minimum, maximum), device, dtype, "continuous"
)
def expand(self, *shape):
if len(shape) == 1 and isinstance(shape[0], (tuple, list, torch.Size)):
shape = shape[0]
if any(val < 0 for val in shape):
raise ValueError(
f"{self.__class__.__name__}.extend does not support negative shapes."
)
if any(s1 != s2 and s2 != 1 for s1, s2 in zip(shape[-self.ndim :], self.shape)):
raise ValueError(
f"The last {self.ndim} of the extended shape must match the"
f"shape of the CompositeSpec in CompositeSpec.extend."
)
return self.__class__(
minimum=self.space.minimum.expand(shape).clone(),
maximum=self.space.maximum.expand(shape).clone(),
shape=shape,
device=self.device,
dtype=self.dtype,
)
def rand(self, shape=None) -> torch.Tensor:
if shape is None:
shape = torch.Size([])
a, b = self.space
if self.dtype in (torch.float, torch.double, torch.half):
shape = [*shape, *self.shape]
out = (
torch.zeros(shape, dtype=self.dtype, device=self.device).uniform_()
* (b - a)
+ a
)
if (out > b).any():
out[out > b] = b.expand_as(out)[out > b]
if (out < a).any():
out[out < a] = a.expand_as(out)[out < a]
return out
else:
if self.space.maximum.dtype == torch.bool:
maxi = self.space.maximum.int()
else:
maxi = self.space.maximum
if self.space.minimum.dtype == torch.bool:
mini = self.space.minimum.int()
else:
mini = self.space.minimum
interval = maxi - mini
r = torch.rand(torch.Size([*shape, *self.shape]), device=interval.device)
r = interval * r
r = self.space.minimum + r
r = r.to(self.dtype).to(self.device)
return r
def _project(self, val: torch.Tensor) -> torch.Tensor:
minimum = self.space.minimum.to(val.device)
maximum = self.space.maximum.to(val.device)
try:
val = val.clamp_(minimum.item(), maximum.item())
except ValueError:
minimum = minimum.expand_as(val)
maximum = maximum.expand_as(val)
val[val < minimum] = minimum[val < minimum]
val[val > maximum] = maximum[val > maximum]
except RuntimeError:
minimum = minimum.expand_as(val)
maximum = maximum.expand_as(val)
val[val < minimum] = minimum[val < minimum]
val[val > maximum] = maximum[val > maximum]
return val
def is_in(self, val: torch.Tensor) -> bool:
try:
return (val >= self.space.minimum.to(val.device)).all() and (
val <= self.space.maximum.to(val.device)
).all()
except RuntimeError as err:
if "The size of tensor a" in str(err):
warnings.warn(f"Got a shape mismatch: {str(err)}")
return False
raise err
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> CompositeSpec:
if isinstance(dest, torch.dtype):
dest_dtype = dest
dest_device = self.device
else:
dest_dtype = self.dtype
dest_device = torch.device(dest)
return self.__class__(
minimum=self.space.minimum.to(dest),
maximum=self.space.maximum.to(dest),
shape=self.shape,
device=dest_device,
dtype=dest_dtype,
)
def clone(self) -> CompositeSpec:
return self.__class__(
minimum=self.space.minimum.clone(),
maximum=self.space.maximum.clone(),
shape=self.shape,
device=self.device,
dtype=self.dtype,
)
@dataclass(repr=False)
class UnboundedContinuousTensorSpec(TensorSpec):
"""An unbounded continuous tensor spec.
Args:
device (str, int or torch.device, optional): device of the tensors.
dtype (str or torch.dtype, optional): dtype of the tensors
(should be an floating point dtype such as float, double etc.)
"""
def __init__(
self,
shape: Union[torch.Size, int] = _DEFAULT_SHAPE,
device: Optional[DEVICE_TYPING] = None,
dtype: Optional[Union[str, torch.dtype]] = None,
):
if isinstance(shape, int):
shape = torch.Size([shape])
dtype, device = _default_dtype_and_device(dtype, device)
box = (
ContinuousBox(torch.tensor(-np.inf), torch.tensor(np.inf))
if shape == _DEFAULT_SHAPE
else None
)
super().__init__(
shape=shape,
space=box,
device=device,
dtype=dtype,
domain="continuous",
)
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> CompositeSpec:
if isinstance(dest, torch.dtype):
dest_dtype = dest
dest_device = self.device
else:
dest_dtype = self.dtype
dest_device = torch.device(dest)
return self.__class__(shape=self.shape, device=dest_device, dtype=dest_dtype)
def clone(self) -> CompositeSpec:
return self.__class__(shape=self.shape, device=self.device, dtype=self.dtype)
def rand(self, shape=None) -> torch.Tensor:
if shape is None:
shape = torch.Size([])
shape = [*shape, *self.shape]
return torch.randn(shape, device=self.device, dtype=self.dtype)
def is_in(self, val: torch.Tensor) -> bool:
return True
def expand(self, *shape):
if len(shape) == 1 and isinstance(shape[0], (tuple, list, torch.Size)):
shape = shape[0]
if any(val < 0 for val in shape):
raise ValueError(
f"{self.__class__.__name__}.extend does not support negative shapes."
)
if any(s1 != s2 and s2 != 1 for s1, s2 in zip(shape[-self.ndim :], self.shape)):
raise ValueError(
f"The last {self.ndim} of the extended shape must match the"
f"shape of the CompositeSpec in CompositeSpec.extend."
)
return self.__class__(shape=shape, device=self.device, dtype=self.dtype)
@dataclass(repr=False)
class UnboundedDiscreteTensorSpec(TensorSpec):
"""An unbounded discrete tensor spec.
Args:
device (str, int or torch.device, optional): device of the tensors.
dtype (str or torch.dtype, optional): dtype of the tensors
(should be an integer dtype such as long, uint8 etc.)
"""
def __init__(
self,
shape: Union[torch.Size, int] = _DEFAULT_SHAPE,
device: Optional[DEVICE_TYPING] = None,
dtype: Optional[Union[str, torch.dtype]] = None,
):
if isinstance(shape, int):
shape = torch.Size([shape])
dtype, device = _default_dtype_and_device(dtype, device)
if dtype == torch.bool:
min_value = False
max_value = True
else:
if dtype.is_floating_point:
min_value = torch.finfo(dtype).min
max_value = torch.finfo(dtype).max
else:
min_value = torch.iinfo(dtype).min
max_value = torch.iinfo(dtype).max
space = ContinuousBox(
torch.full(shape, min_value, device=device),
torch.full(shape, max_value, device=device),
)
super().__init__(
shape=shape,
space=space,
device=device,
dtype=dtype,
domain="continuous",
)
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> CompositeSpec:
if isinstance(dest, torch.dtype):
dest_dtype = dest
dest_device = self.device
else:
dest_dtype = self.dtype
dest_device = torch.device(dest)
return self.__class__(shape=self.shape, device=dest_device, dtype=dest_dtype)
def clone(self) -> CompositeSpec:
return self.__class__(shape=self.shape, device=self.device, dtype=self.dtype)
def rand(self, shape=None) -> torch.Tensor:
if shape is None:
shape = torch.Size([])
interval = self.space.maximum - self.space.minimum
r = torch.rand(torch.Size([*shape, *interval.shape]), device=interval.device)
r = r * interval
r = self.space.minimum + r
r = r.to(self.dtype)
return r.to(self.device)
def is_in(self, val: torch.Tensor) -> bool:
return True
def expand(self, *shape):
if len(shape) == 1 and isinstance(shape[0], (tuple, list, torch.Size)):
shape = shape[0]
if any(val < 0 for val in shape):
raise ValueError(
f"{self.__class__.__name__}.extend does not support negative shapes."
)
if any(s1 != s2 and s2 != 1 for s1, s2 in zip(shape[-self.ndim :], self.shape)):
raise ValueError(
f"The last {self.ndim} of the extended shape must match the"
f"shape of the CompositeSpec in CompositeSpec.extend."
)
return self.__class__(shape=shape, device=self.device, dtype=self.dtype)
@dataclass(repr=False)
class BinaryDiscreteTensorSpec(TensorSpec):
"""A binary discrete tensor spec.
Args:
n (int): length of the binary vector.
shape (torch.Size, optional): total shape of the sampled tensors.
If provided, the last dimension must match n.
device (str, int or torch.device, optional): device of the tensors.
dtype (str or torch.dtype, optional): dtype of the tensors. Defaults to torch.long.
Examples:
>>> spec = BinaryDiscreteTensorSpec(n=4, shape=(5, 4), device="cpu", dtype=torch.bool)
>>> print(spec.zero())
"""
shape: torch.Size