forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transforms.py
2247 lines (1876 loc) · 76.2 KB
/
transforms.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 Plobs_dictnc. 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 collections
import multiprocessing as mp
from copy import deepcopy, copy
from textwrap import indent
from typing import Any, List, Optional, OrderedDict, Sequence, Union
from warnings import warn
import torch
from torch import nn, Tensor
try:
from torchvision.transforms.functional import center_crop
from torchvision.transforms.functional_tensor import (
resize,
) # as of now resize is imported from torchvision
_has_tv = True
except ImportError:
_has_tv = False
from torchrl.data.tensor_specs import (
BoundedTensorSpec,
CompositeSpec,
ContinuousBox,
NdUnboundedContinuousTensorSpec,
TensorSpec,
UnboundedContinuousTensorSpec,
BinaryDiscreteTensorSpec,
DEVICE_TYPING,
)
from torchrl.data.tensordict.tensordict import TensorDictBase, TensorDict
from torchrl.envs.common import EnvBase, make_tensordict
from torchrl.envs.transforms import functional as F
from torchrl.envs.transforms.utils import FiniteTensor
from torchrl.envs.utils import step_mdp
__all__ = [
"Transform",
"TransformedEnv",
"RewardClipping",
"Resize",
"CenterCrop",
"GrayScale",
"Compose",
"ToTensorImage",
"ObservationNorm",
"FlattenObservation",
"UnsqueezeTransform",
"RewardScaling",
"ObservationTransform",
"CatFrames",
"FiniteTensorDictCheck",
"DoubleToFloat",
"CatTensors",
"NoopResetEnv",
"BinarizeReward",
"PinMemoryTransform",
"VecNorm",
"gSDENoise",
"TensorDictPrimer",
]
IMAGE_KEYS = ["next_pixels"]
_MAX_NOOPS_TRIALS = 10
def _apply_to_composite(function):
def new_fun(self, observation_spec):
if isinstance(observation_spec, CompositeSpec):
d = observation_spec._specs
for key_in, key_out in zip(self.keys_in, self.keys_out):
if key_in in observation_spec.keys():
d[key_out] = function(self, observation_spec[key_in])
return CompositeSpec(**d)
else:
return function(self, observation_spec)
return new_fun
class Transform(nn.Module):
"""Environment transform parent class.
In principle, a transform receives a tensordict as input and returns (
the same or another) tensordict as output, where a series of values have
been modified or created with a new key. When instantiating a new
transform, the keys that are to be read from are passed to the
constructor via the :obj:`keys` argument.
Transforms are to be combined with their target environments with the
TransformedEnv class, which takes as arguments an :obj:`EnvBase` instance
and a transform. If multiple transforms are to be used, they can be
concatenated using the :obj:`Compose` class.
A transform can be stateless or stateful (e.g. CatTransform). Because of
this, Transforms support the :obj:`reset` operation, which should reset the
transform to its initial state (such that successive trajectories are kept
independent).
Notably, :obj:`Transform` subclasses take care of transforming the affected
specs from an environment: when querying
`transformed_env.observation_spec`, the resulting objects will describe
the specs of the transformed_in tensors.
"""
invertible = False
def __init__(
self,
keys_in: Sequence[str],
keys_out: Optional[Sequence[str]] = None,
keys_inv_in: Optional[Sequence[str]] = None,
keys_inv_out: Optional[Sequence[str]] = None,
):
super().__init__()
self.keys_in = keys_in
if keys_out is None:
keys_out = copy(self.keys_in)
self.keys_out = keys_out
if keys_inv_in is None:
keys_inv_in = []
self.keys_inv_in = keys_inv_in
if keys_inv_out is None:
keys_inv_out = copy(self.keys_inv_in)
self.keys_inv_out = keys_inv_out
self.__dict__["_parent"] = None
def reset(self, tensordict: TensorDictBase) -> TensorDictBase:
"""Resets a tranform if it is stateful."""
return tensordict
def _check_inplace(self) -> None:
if not hasattr(self, "inplace"):
raise AttributeError(
f"Transform of class {self.__class__.__name__} has no "
f"attribute inplace, consider implementing it."
)
def init(self, tensordict) -> None:
pass
def _apply_transform(self, obs: torch.Tensor) -> None:
"""Applies the transform to a tensor.
This operation can be called multiple times (if multiples keys of the
tensordict match the keys of the transform).
"""
raise NotImplementedError
def _call(self, tensordict: TensorDictBase) -> TensorDictBase:
"""Reads the input tensordict, and for the selected keys, applies the transform."""
self._check_inplace()
for key_in, key_out in zip(self.keys_in, self.keys_out):
if key_in in tensordict.keys():
observation = self._apply_transform(tensordict.get(key_in))
tensordict.set(key_out, observation, inplace=self.inplace)
return tensordict
def forward(self, tensordict: TensorDictBase) -> TensorDictBase:
self._call(tensordict)
return tensordict
def _inv_apply_transform(self, obs: torch.Tensor) -> torch.Tensor:
if self.invertible:
raise NotImplementedError
else:
return obs
def _inv_call(self, tensordict: TensorDictBase) -> TensorDictBase:
self._check_inplace()
for key_in, key_out in zip(self.keys_inv_in, self.keys_inv_out):
if key_in in tensordict.keys():
observation = self._inv_apply_transform(tensordict.get(key_in))
tensordict.set(key_out, observation, inplace=self.inplace)
return tensordict
def inv(self, tensordict: TensorDictBase) -> TensorDictBase:
self._inv_call(tensordict)
return tensordict
def transform_input_spec(self, input_spec: TensorSpec) -> TensorSpec:
"""Transforms the input spec such that the resulting spec matches transform mapping.
Args:
input_spec (TensorSpec): spec before the transform
Returns:
expected spec after the transform
"""
return input_spec
def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec:
"""Transforms the observation spec such that the resulting spec matches transform mapping.
Args:
observation_spec (TensorSpec): spec before the transform
Returns:
expected spec after the transform
"""
return observation_spec
def transform_reward_spec(self, reward_spec: TensorSpec) -> TensorSpec:
"""Transforms the reward spec such that the resulting spec matches transform mapping.
Args:
reward_spec (TensorSpec): spec before the transform
Returns:
expected spec after the transform
"""
return reward_spec
def dump(self, **kwargs) -> None:
pass
def __repr__(self) -> str:
return f"{self.__class__.__name__}(keys={self.keys_in})"
def set_parent(self, parent: Union[Transform, EnvBase]) -> None:
self.__dict__["_parent"] = parent
@property
def parent(self) -> EnvBase:
if not hasattr(self, "_parent"):
raise AttributeError("transform parent uninitialized")
parent = self._parent
if parent is None:
return parent
if not isinstance(parent, EnvBase):
# if it's not an env, it should be a Compose transform
if not isinstance(parent, Compose):
raise ValueError(
"A transform parent must be either another Compose transform or an environment object."
)
out = TransformedEnv(
parent.parent.base_env,
)
for transform in parent.transforms:
if transform is self:
break
out.append_transform(transform)
elif isinstance(parent, TransformedEnv):
out = TransformedEnv(parent.base_env)
else:
raise ValueError(f"parent is of type {type(parent)}")
return out
def empty_cache(self):
if self.parent is not None:
self.parent.empty_cache()
class TransformedEnv(EnvBase):
"""A transformed_in environment.
Args:
env (EnvBase): original environment to be transformed_in.
transform (Transform, optional): transform to apply to the tensordict resulting
from :obj:`env.step(td)`. If none is provided, an empty Compose
placeholder in an eval mode is used.
cache_specs (bool, optional): if True, the specs will be cached once
and for all after the first call (i.e. the specs will be
transformed_in only once). If the transform changes during
training, the original spec transform may not be valid anymore,
in which case this value should be set to `False`. Default is
`True`.
Examples:
>>> env = GymEnv("Pendulum-v0")
>>> transform = RewardScaling(0.0, 1.0)
>>> transformed_env = TransformedEnv(env, transform)
"""
def __init__(
self,
env: EnvBase,
transform: Optional[Transform] = None,
cache_specs: bool = True,
**kwargs,
):
device = kwargs.pop("device", env.device)
env = env.to(device)
super().__init__(device=None, **kwargs)
self._set_env(env, device)
if transform is None:
transform = Compose()
transform.set_parent(self)
else:
transform = transform.to(device)
transform.eval()
self.transform = transform
self._last_obs = None
self.cache_specs = cache_specs
self._reward_spec = None
self._observation_spec = None
self.batch_size = self.base_env.batch_size
def _set_env(self, env: EnvBase, device) -> None:
self.base_env = env.to(device)
# updates need not be inplace, as transforms may modify values out-place
self.base_env._inplace_update = False
@property
def device(self) -> bool:
return self.base_env.device
@device.setter
def device(self, value):
raise RuntimeError("device is a read-only property")
@property
def batch_locked(self) -> bool:
return self.base_env.batch_locked
@batch_locked.setter
def batch_locked(self, value):
raise RuntimeError("batch_locked is a read-only property")
@property
def run_type_checks(self) -> bool:
return self.base_env.run_type_checks
@run_type_checks.setter
def run_type_checks(self, value):
raise RuntimeError(
"run_type_checks is a read-only property for TransformedEnvs"
)
@property
def _inplace_update(self):
return self.base_env._inplace_update
@property
def observation_spec(self) -> TensorSpec:
"""Observation spec of the transformed environment."""
if self._observation_spec is None or not self.cache_specs:
observation_spec = self.transform.transform_observation_spec(
deepcopy(self.base_env.observation_spec)
)
if self.cache_specs:
self._observation_spec = observation_spec
else:
observation_spec = self._observation_spec
return observation_spec
@property
def action_spec(self) -> TensorSpec:
"""Action spec of the transformed environment."""
return self.input_spec["action"]
@property
def input_spec(self) -> TensorSpec:
"""Action spec of the transformed environment."""
if self._input_spec is None or not self.cache_specs:
input_spec = self.transform.transform_input_spec(
deepcopy(self.base_env.input_spec)
)
if self.cache_specs:
self._input_spec = input_spec
else:
input_spec = self._input_spec
return input_spec
@property
def reward_spec(self) -> TensorSpec:
"""Reward spec of the transformed environment."""
if self._reward_spec is None or not self.cache_specs:
reward_spec = self.transform.transform_reward_spec(
deepcopy(self.base_env.reward_spec)
)
if self.cache_specs:
self._reward_spec = reward_spec
else:
reward_spec = self._reward_spec
return reward_spec
def _step(self, tensordict: TensorDictBase) -> TensorDictBase:
# selected_keys = [key for key in tensordict.keys() if "action" in key]
# tensordict_in = tensordict.select(*selected_keys).clone()
tensordict_in = self.transform.inv(tensordict.clone(recurse=False))
tensordict_out = self.base_env.step(tensordict_in)
# tensordict should already have been processed by the transforms
# for logging purposes
tensordict_out = self.transform(tensordict_out)
return tensordict_out
def set_seed(self, seed: int, static_seed: bool = False) -> int:
"""Set the seeds of the environment."""
return self.base_env.set_seed(seed, static_seed=static_seed)
def _reset(self, tensordict: Optional[TensorDictBase] = None, **kwargs):
out_tensordict = self.base_env.reset(execute_step=False, **kwargs)
out_tensordict = self.transform.reset(out_tensordict)
out_tensordict = self.transform(out_tensordict)
return out_tensordict
def state_dict(self) -> OrderedDict:
state_dict = self.transform.state_dict()
return state_dict
def load_state_dict(self, state_dict: OrderedDict, **kwargs) -> None:
self.transform.load_state_dict(state_dict, **kwargs)
def eval(self) -> TransformedEnv:
if "transform" in self.__dir__():
# when calling __init__, eval() is called but transforms are not set
# yet.
self.transform.eval()
return self
def train(self, mode: bool = True) -> TransformedEnv:
self.transform.train(mode)
return self
@property
def is_closed(self) -> bool:
return self.base_env.is_closed
@is_closed.setter
def is_closed(self, value: bool):
self.base_env.is_closed = value
def is_done_get_fn(self) -> bool:
if self._is_done is None:
return self.base_env.is_done
return self._is_done.all()
def is_done_set_fn(self, val: torch.Tensor) -> None:
self._is_done = val
is_done = property(is_done_get_fn, is_done_set_fn)
def close(self):
self.base_env.close()
self.is_closed = True
def empty_cache(self):
self._observation_spec = None
self._input_spec = None
self._reward_spec = None
def append_transform(self, transform: Transform) -> None:
self._erase_metadata()
if not isinstance(transform, Transform):
raise ValueError(
"TransformedEnv.append_transform expected a transform but received an object of "
f"type {type(transform)} instead."
)
transform = transform.to(self.device)
if not isinstance(self.transform, Compose):
prev_transform = self.transform
self.transform = Compose()
self.transform.append(prev_transform)
self.transform.set_parent(self)
self.transform.append(transform)
def insert_transform(self, index: int, transform: Transform) -> None:
if not isinstance(transform, Transform):
raise ValueError(
"TransformedEnv.insert_transform expected a transform but received an object of "
f"type {type(transform)} instead."
)
transform = transform.to(self.device)
if not isinstance(self.transform, Compose):
self.transform = Compose(self.transform)
self.transform.set_parent(self)
self.transform.insert(index, transform)
self._erase_metadata()
def __getattr__(self, attr: str) -> Any:
if attr in self.__dir__():
return super().__getattr__(
attr
) # make sure that appropriate exceptions are raised
elif attr.startswith("__"):
raise AttributeError(
"passing built-in private methods is "
f"not permitted with type {type(self)}. "
f"Got attribute {attr}."
)
elif "base_env" in self.__dir__():
base_env = self.__getattr__("base_env")
return getattr(base_env, attr)
raise AttributeError(
f"env not set in {self.__class__.__name__}, cannot access {attr}"
)
def __repr__(self) -> str:
env_str = indent(f"env={self.base_env}", 4 * " ")
t_str = indent(f"transform={self.transform}", 4 * " ")
return f"TransformedEnv(\n{env_str},\n{t_str})"
def _erase_metadata(self):
if self.cache_specs:
self._input_spec = None
self._observation_spec = None
self._reward_spec = None
def to(self, device: DEVICE_TYPING) -> TransformedEnv:
self.base_env.to(device)
self.transform.to(device)
self.is_done = self.is_done.to(device)
if self.cache_specs:
self._input_spec = None
self._observation_spec = None
self._reward_spec = None
return self
def __setattr__(self, key, value):
propobj = getattr(self.__class__, key, None)
if isinstance(value, Transform):
value.set_parent(self)
if isinstance(propobj, property):
ancestors = list(__class__.__mro__)[::-1]
while isinstance(propobj, property):
if propobj.fset is not None:
return propobj.fset(self, value)
propobj = getattr(ancestors.pop(), key, None)
else:
raise AttributeError(f"can't set attribute {key}")
else:
return super().__setattr__(key, value)
def __del__(self):
# we may delete a TransformedEnv that contains an env contained by another
# transformed env and that we don't want to close
pass
class ObservationTransform(Transform):
"""Abstract class for transformations of the observations."""
inplace = False
def __init__(
self,
keys_in: Optional[Sequence[str]] = None,
keys_out: Optional[Sequence[str]] = None,
):
if keys_in is None:
keys_in = [
"next_observation",
"next_pixels",
"next_observation_state",
]
super(ObservationTransform, self).__init__(keys_in=keys_in, keys_out=keys_out)
class Compose(Transform):
"""Composes a chain of transforms.
Examples:
>>> env = GymEnv("Pendulum-v0")
>>> transforms = [RewardScaling(1.0, 1.0), RewardClipping(-2.0, 2.0)]
>>> transforms = Compose(*transforms)
>>> transformed_env = TransformedEnv(env, transforms)
"""
inplace = False
def __init__(self, *transforms: Transform):
super().__init__(keys_in=[])
self.transforms = nn.ModuleList(transforms)
for t in self.transforms:
t.set_parent(self)
def _call(self, tensordict: TensorDictBase) -> TensorDictBase:
for t in self.transforms:
tensordict = t(tensordict)
return tensordict
def _inv_call(self, tensordict: TensorDictBase) -> TensorDictBase:
for t in self.transforms[::-1]:
tensordict = t.inv(tensordict)
return tensordict
def transform_input_spec(self, input_spec: TensorSpec) -> TensorSpec:
for t in self.transforms[::-1]:
input_spec = t.transform_input_spec(input_spec)
return input_spec
def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec:
for t in self.transforms:
observation_spec = t.transform_observation_spec(observation_spec)
return observation_spec
def transform_reward_spec(self, reward_spec: TensorSpec) -> TensorSpec:
for t in self.transforms:
reward_spec = t.transform_reward_spec(reward_spec)
return reward_spec
def __getitem__(self, item: Union[int, slice, List]) -> Union:
transform = self.transforms
transform = transform[item]
if not isinstance(transform, Transform):
out = Compose(*self.transforms[item])
out.set_parent(self.parent)
return out
return transform
def dump(self, **kwargs) -> None:
for t in self:
t.dump(**kwargs)
def reset(self, tensordict: TensorDictBase) -> TensorDictBase:
for t in self.transforms:
tensordict = t.reset(tensordict)
return tensordict
def init(self, tensordict: TensorDictBase) -> None:
for t in self.transforms:
t.init(tensordict)
def append(self, transform):
self.empty_cache()
if not isinstance(transform, Transform):
raise ValueError(
"Compose.append expected a transform but received an object of "
f"type {type(transform)} instead."
)
transform.eval()
self.transforms.append(transform)
transform.set_parent(self)
def insert(self, index: int, transform: Transform) -> None:
if not isinstance(transform, Transform):
raise ValueError(
"Compose.append expected a transform but received an object of "
f"type {type(transform)} instead."
)
if abs(index) > len(self.transforms):
raise ValueError(
f"Index expected to be between [-{len(self.transforms)}, {len(self.transforms)}] got index={index}"
)
self.empty_cache()
if index < 0:
index = index + len(self.transforms)
transform.eval()
self.transforms.insert(index, transform)
transform.set_parent(self)
def to(self, dest: Union[torch.dtype, DEVICE_TYPING]) -> Compose:
for t in self.transforms:
t.to(dest)
return super().to(dest)
def __iter__(self):
return iter(self.transforms)
def __len__(self):
return len(self.transforms)
def __repr__(self) -> str:
layers_str = ",\n".join(
[indent(str(trsf), 4 * " ") for trsf in self.transforms]
)
return f"{self.__class__.__name__}(\n{indent(layers_str, 4 * ' ')})"
class ToTensorImage(ObservationTransform):
"""Transforms a numpy-like image (3 x W x H) to a pytorch image (3 x W x H).
Transforms an observation image from a (... x W x H x 3) 0..255 uint8
tensor to a single/double precision floating point (3 x W x H) tensor
with values between 0 and 1.
Args:
unsqueeze (bool): if True, the observation tensor is unsqueezed
along the first dimension. default=False.
dtype (torch.dtype, optional): dtype to use for the resulting
observations.
Examples:
>>> transform = ToTensorImage(keys_in=["next_pixels"])
>>> ri = torch.randint(0, 255, (1,1,10,11,3), dtype=torch.uint8)
>>> td = TensorDict(
... {"next_pixels": ri},
... [1, 1])
>>> _ = transform(td)
>>> obs = td.get("next_pixels")
>>> print(obs.shape, obs.dtype)
torch.Size([1, 1, 3, 10, 11]) torch.float32
"""
inplace = False
def __init__(
self,
unsqueeze: bool = False,
dtype: Optional[torch.device] = None,
keys_in: Optional[Sequence[str]] = None,
keys_out: Optional[Sequence[str]] = None,
):
if keys_in is None:
keys_in = IMAGE_KEYS # default
super().__init__(keys_in=keys_in, keys_out=keys_out)
self.unsqueeze = unsqueeze
self.dtype = dtype if dtype is not None else torch.get_default_dtype()
def _apply_transform(self, observation: torch.FloatTensor) -> torch.Tensor:
observation = observation.div(255).to(self.dtype)
observation = observation.permute(
*list(range(observation.ndimension() - 3)), -1, -3, -2
)
if observation.ndimension() == 3 and self.unsqueeze:
observation = observation.unsqueeze(0)
return observation
@_apply_to_composite
def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec:
observation_spec = self._pixel_observation(deepcopy(observation_spec))
observation_spec.shape = torch.Size(
[
*observation_spec.shape[:-3],
observation_spec.shape[-1],
observation_spec.shape[-3],
observation_spec.shape[-2],
]
)
observation_spec.dtype = self.dtype
return observation_spec
def _pixel_observation(self, spec: TensorSpec) -> None:
if isinstance(spec.space, ContinuousBox):
spec.space.maximum = self._apply_transform(spec.space.maximum)
spec.space.minimum = self._apply_transform(spec.space.minimum)
return spec
class RewardClipping(Transform):
"""Clips the reward between `clamp_min` and `clamp_max`.
Args:
clip_min (scalar): minimum value of the resulting reward.
clip_max (scalar): maximum value of the resulting reward.
"""
inplace = True
def __init__(
self,
clamp_min: float = None,
clamp_max: float = None,
keys_in: Optional[Sequence[str]] = None,
keys_out: Optional[Sequence[str]] = None,
):
if keys_in is None:
keys_in = ["reward"]
super().__init__(keys_in=keys_in, keys_out=keys_out)
clamp_min_tensor = (
clamp_min if isinstance(clamp_min, Tensor) else torch.tensor(clamp_min)
)
clamp_max_tensor = (
clamp_max if isinstance(clamp_max, Tensor) else torch.tensor(clamp_max)
)
self.register_buffer("clamp_min", clamp_min_tensor)
self.register_buffer("clamp_max", clamp_max_tensor)
def _apply_transform(self, reward: torch.Tensor) -> torch.Tensor:
if self.clamp_max is not None and self.clamp_min is not None:
reward = reward.clamp_(self.clamp_min, self.clamp_max)
elif self.clamp_min is not None:
reward = reward.clamp_min_(self.clamp_min)
elif self.clamp_max is not None:
reward = reward.clamp_max_(self.clamp_max)
return reward
def transform_reward_spec(self, reward_spec: TensorSpec) -> TensorSpec:
if isinstance(reward_spec, UnboundedContinuousTensorSpec):
return BoundedTensorSpec(
self.clamp_min,
self.clamp_max,
device=reward_spec.device,
dtype=reward_spec.dtype,
)
else:
raise NotImplementedError(
f"{self.__class__.__name__}.transform_reward_spec not "
f"implemented for tensor spec of type"
f" {type(reward_spec).__name__}"
)
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}("
f"clamp_min={float(self.clamp_min):4.4f}, clamp_max"
f"={float(self.clamp_max):4.4f}, keys={self.keys_in})"
)
class BinarizeReward(Transform):
"""Maps the reward to a binary value (0 or 1) if the reward is null or non-null, respectively."""
inplace = True
def __init__(
self,
keys_in: Optional[Sequence[str]] = None,
keys_out: Optional[Sequence[str]] = None,
):
if keys_in is None:
keys_in = ["reward"]
super().__init__(keys_in=keys_in, keys_out=keys_out)
def _apply_transform(self, reward: torch.Tensor) -> torch.Tensor:
if not reward.shape or reward.shape[-1] != 1:
raise RuntimeError(
f"Reward shape last dimension must be singleton, got reward of shape {reward.shape}"
)
return (reward > 0.0).to(torch.long)
def transform_reward_spec(self, reward_spec: TensorSpec) -> TensorSpec:
return BinaryDiscreteTensorSpec(n=1, device=reward_spec.device)
class Resize(ObservationTransform):
"""Resizes an pixel observation.
Args:
w (int): resulting width
h (int): resulting height
interpolation (str): interpolation method
"""
inplace = False
def __init__(
self,
w: int,
h: int,
interpolation: str = "bilinear",
keys_in: Optional[Sequence[str]] = None,
keys_out: Optional[Sequence[str]] = None,
):
if not _has_tv:
raise ImportError(
"Torchvision not found. The Resize transform relies on "
"torchvision implementation. "
"Consider installing this dependency."
)
if keys_in is None:
keys_in = IMAGE_KEYS # default
super().__init__(keys_in=keys_in, keys_out=keys_out)
self.w = int(w)
self.h = int(h)
self.interpolation = interpolation
def _apply_transform(self, observation: torch.Tensor) -> torch.Tensor:
# flatten if necessary
if observation.shape[-2:] == torch.Size([self.w, self.h]):
return observation
ndim = observation.ndimension()
if ndim > 4:
sizes = observation.shape[:-3]
observation = torch.flatten(observation, 0, ndim - 4)
observation = resize(
observation, [self.w, self.h], interpolation=self.interpolation
)
if ndim > 4:
observation = observation.unflatten(0, sizes)
return observation
@_apply_to_composite
def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec:
observation_spec = deepcopy(observation_spec)
space = observation_spec.space
if isinstance(space, ContinuousBox):
space.minimum = self._apply_transform(space.minimum)
space.maximum = self._apply_transform(space.maximum)
observation_spec.shape = space.minimum.shape
else:
observation_spec.shape = self._apply_transform(
torch.zeros(observation_spec.shape)
).shape
return observation_spec
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}("
f"w={int(self.w)}, h={int(self.h)}, "
f"interpolation={self.interpolation}, keys={self.keys_in})"
)
class CenterCrop(ObservationTransform):
"""Crops the center of an image.
Args:
w (int): resulting width
h (int, optional): resulting height. If None, then w is used (square crop).
"""
inplace = False
def __init__(
self,
w: int,
h: int = None,
keys_in: Optional[Sequence[str]] = None,
):
if keys_in is None:
keys_in = IMAGE_KEYS # default
super().__init__(keys_in=keys_in)
self.w = w
self.h = h if h else w
def _apply_transform(self, observation: torch.Tensor) -> torch.Tensor:
observation = center_crop(observation, [self.w, self.h])
return observation
def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec:
if isinstance(observation_spec, CompositeSpec):
return CompositeSpec(
**{
key: self.transform_observation_spec(_obs_spec)
if key in self.keys_in
else _obs_spec
for key, _obs_spec in observation_spec._specs.items()
}
)
else:
_observation_spec = deepcopy(observation_spec)
space = _observation_spec.space
if isinstance(space, ContinuousBox):
space.minimum = self._apply_transform(space.minimum)
space.maximum = self._apply_transform(space.maximum)
_observation_spec.shape = space.minimum.shape
else:
_observation_spec.shape = self._apply_transform(
torch.zeros(_observation_spec.shape)
).shape
observation_spec = _observation_spec
return observation_spec
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}("
f"w={float(self.w):4.4f}, h={float(self.h):4.4f}, "
)
class FlattenObservation(ObservationTransform):
"""Flatten adjacent dimensions of a tensor.
Args:
first_dim (int, optional): first dimension of the dimensions to flatten.
Default is 0.
last_dim (int, optional): last dimension of the dimensions to flatten.
Default is -3.
"""
inplace = False
def __init__(
self,
first_dim: int = 0,
last_dim: int = -3,
keys_in: Optional[Sequence[str]] = None,
):
if keys_in is None:
keys_in = IMAGE_KEYS # default
super().__init__(keys_in=keys_in)
self.first_dim = first_dim
self.last_dim = last_dim
def _apply_transform(self, observation: torch.Tensor) -> torch.Tensor:
observation = torch.flatten(observation, self.first_dim, self.last_dim)
return observation
def set_parent(self, parent: Union[Transform, EnvBase]) -> None:
out = super().set_parent(parent)
observation_spec = self.parent.observation_spec