forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transforms.py
2928 lines (2487 loc) · 106 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 copy
from textwrap import indent
from typing import Any, List, Optional, OrderedDict, Sequence, Tuple, Union
import torch
from tensordict.tensordict import TensorDict, TensorDictBase
from tensordict.utils import expand_as_right
from torch import nn, Tensor
from torchrl.data.tensor_specs import (
BinaryDiscreteTensorSpec,
BoundedTensorSpec,
CompositeSpec,
ContinuousBox,
DEVICE_TYPING,
TensorSpec,
UnboundedContinuousTensorSpec,
UnboundedDiscreteTensorSpec,
)
from torchrl.envs.common import EnvBase, make_tensordict
from torchrl.envs.transforms import functional as F
from torchrl.envs.transforms.utils import check_finite
from torchrl.envs.utils import step_mdp
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
IMAGE_KEYS = ["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 in_key, out_key in zip(self.in_keys, self.out_keys):
if in_key in observation_spec.keys():
d[out_key] = function(self, observation_spec[in_key])
return CompositeSpec(d, shape=observation_spec.shape)
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,
in_keys: Sequence[str],
out_keys: Optional[Sequence[str]] = None,
in_keys_inv: Optional[Sequence[str]] = None,
out_keys_inv: Optional[Sequence[str]] = None,
):
super().__init__()
if isinstance(in_keys, str):
in_keys = [in_keys]
self.in_keys = in_keys
if out_keys is None:
out_keys = copy(self.in_keys)
self.out_keys = out_keys
if in_keys_inv is None:
in_keys_inv = []
self.in_keys_inv = in_keys_inv
if out_keys_inv is None:
out_keys_inv = copy(self.in_keys_inv)
self.out_keys_inv = out_keys_inv
self.__dict__["_container"] = None
self.__dict__["_parent"] = None
def reset(self, tensordict: TensorDictBase) -> TensorDictBase:
"""Resets a tranform if it is stateful."""
return tensordict
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."""
for in_key, out_key in zip(self.in_keys, self.out_keys):
if in_key in tensordict.keys(include_nested=True):
observation = self._apply_transform(tensordict.get(in_key))
tensordict.set(
out_key,
observation,
)
return tensordict
def forward(self, tensordict: TensorDictBase) -> TensorDictBase:
tensordict = self._call(tensordict)
return tensordict
# raise NotImplementedError("""`Transform.forward` is currently not implemented (reserved for usage beyond envs). Use `Transform._step` instead.""")
def _step(self, tensordict: TensorDictBase) -> TensorDictBase:
# placeholder when we'll move to tensordict['next']
# tensordict["next"] = self._call(tensordict.get("next"))
out = self._call(tensordict)
# print(out, tensordict, out is tensordict, (out==tensordict).all())
return out
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:
for in_key, out_key in zip(self.in_keys_inv, self.out_keys_inv):
if in_key in tensordict.keys(include_nested=True):
observation = self._inv_apply_transform(tensordict.get(in_key))
tensordict.set(
out_key,
observation,
)
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.in_keys})"
def set_container(self, container: Union[Transform, EnvBase]) -> None:
if self.__dict__["_container"] is not None:
raise AttributeError(
f"parent of transform {type(self)} already set. "
"Call `transform.clone()` to get a similar transform with no parent set."
)
self.__dict__["_container"] = container
def reset_parent(self) -> None:
self.__dict__["_container"] = None
self.__dict__["_parent"] = None
def clone(self):
self_copy = copy(self)
self_copy.reset_parent()
return self_copy
@property
def parent(self) -> Optional[EnvBase]:
if self.__dict__.get("_parent", None) is None:
if "_container" not in self.__dict__:
raise AttributeError("transform parent uninitialized")
container = self.__dict__["_container"]
if container is None:
return container
out = None
if not isinstance(container, EnvBase):
# if it's not an env, it should be a Compose transform
if not isinstance(container, Compose):
raise ValueError(
"A transform parent must be either another Compose transform or an environment object."
)
compose = container
if compose.__dict__["_container"]:
# the parent of the compose must be a TransformedEnv
compose_parent = TransformedEnv(
compose.__dict__["_container"].base_env
)
if compose_parent.transform is not compose:
comp_parent_trans = compose_parent.transform.clone()
else:
comp_parent_trans = None
out = TransformedEnv(
compose_parent.base_env,
transform=comp_parent_trans,
)
for orig_trans in compose.transforms:
if orig_trans is self:
break
transform = orig_trans.clone()
transform.reset_parent()
out.append_transform(transform)
elif isinstance(container, TransformedEnv):
out = TransformedEnv(container.base_env)
else:
raise ValueError(f"container is of type {type(container)}")
self.__dict__["_parent"] = out
return self.__dict__["_parent"]
def empty_cache(self):
self.__dict__["_parent"] = None
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,
):
self._transform = None
device = kwargs.pop("device", None)
if device is not None:
env = env.to(device)
else:
device = env.device
super().__init__(device=None, **kwargs)
if isinstance(env, TransformedEnv):
self._set_env(env.base_env, device)
if type(transform) is not Compose:
# we don't use isinstance as some transforms may be subclassed from
# Compose but with other features that we don't want to loose.
transform = [transform]
else:
for t in transform:
t.reset_parent()
env_transform = env.transform
if type(env_transform) is not Compose:
env_transform.reset_parent()
env_transform = [env_transform]
else:
for t in env_transform:
t.reset_parent()
transform = Compose(*env_transform, *transform).to(device)
else:
self._set_env(env, device)
if transform is None:
transform = Compose()
else:
transform = transform.to(device)
self.transform = transform
self._last_obs = None
self.cache_specs = cache_specs
self.__dict__["_reward_spec"] = None
self.__dict__["_input_spec"] = None
self.__dict__["_observation_spec"] = None
self.batch_size = self.base_env.batch_size
def _set_env(self, env: EnvBase, device) -> None:
if device != env.device:
env = env.to(device)
self.base_env = env
# updates need not be inplace, as transforms may modify values out-place
self.base_env._inplace_update = False
@property
def transform(self) -> Transform:
return self._transform
@transform.setter
def transform(self, transform: Transform):
if not isinstance(transform, Transform):
raise ValueError(
f"""Expected a transform of type torchrl.envs.transforms.Transform,
but got an object of type {type(transform)}."""
)
prev_transform = self.transform
if prev_transform is not None:
prev_transform.empty_cache()
prev_transform.__dict__["_container"] = None
transform.set_container(self)
transform.eval()
self._transform = transform
@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(
self.base_env.observation_spec.clone()
)
if self.cache_specs:
self.__dict__["_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(
self.base_env.input_spec.clone()
)
if self.cache_specs:
self.__dict__["_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(
self.base_env.reward_spec.clone()
)
if self.cache_specs:
self.__dict__["_reward_spec"] = reward_spec
else:
reward_spec = self._reward_spec
return reward_spec
def _step(self, tensordict: TensorDictBase) -> TensorDictBase:
tensordict = tensordict.clone(False)
tensordict_in = self.transform.inv(tensordict)
tensordict_out = self.base_env._step(tensordict_in)
tensordict_out = (
tensordict_out.update( # update the output with the original tensordict
tensordict.exclude(
*tensordict_out.keys()
) # exclude the newly written keys
)
)
next_tensordict = self.transform._step(tensordict_out)
# tensordict_out.update(next_tensordict, inplace=False)
return next_tensordict
def set_seed(
self, seed: Optional[int] = None, static_seed: bool = False
) -> Optional[int]:
"""Set the seeds of the environment."""
return self.base_env.set_seed(seed, static_seed=static_seed)
def _set_seed(self, seed: Optional[int]):
"""This method is not used in transformed envs."""
pass
def _reset(self, tensordict: Optional[TensorDictBase] = None, **kwargs):
if tensordict is not None:
tensordict = tensordict.clone(recurse=False)
out_tensordict = self.base_env.reset(tensordict=tensordict, **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 close(self):
self.base_env.close()
self.is_closed = True
def empty_cache(self):
self.__dict__["_observation_spec"] = None
self.__dict__["_input_spec"] = None
self.__dict__["_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
prev_transform.reset_parent()
self.transform = Compose()
self.transform.append(prev_transform)
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):
compose = Compose(self.transform.clone())
self.transform = compose # parent set automatically
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.__dict__["_input_spec"] = None
self.__dict__["_observation_spec"] = None
self.__dict__["_reward_spec"] = None
def to(self, device: DEVICE_TYPING) -> TransformedEnv:
self.base_env.to(device)
self.transform.to(device)
if self.cache_specs:
self.__dict__["_input_spec"] = None
self.__dict__["_observation_spec"] = None
self.__dict__["_reward_spec"] = None
return self
def __setattr__(self, key, value):
propobj = getattr(self.__class__, key, None)
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."""
def __init__(
self,
in_keys: Optional[Sequence[str]] = None,
out_keys: Optional[Sequence[str]] = None,
):
if in_keys is None:
in_keys = [
"observation",
"pixels",
"observation_state",
]
super(ObservationTransform, self).__init__(in_keys=in_keys, out_keys=out_keys)
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)
"""
def __init__(self, *transforms: Transform):
super().__init__(in_keys=[])
self.transforms = nn.ModuleList(transforms)
for t in self.transforms:
t.set_container(self)
def forward(self, tensordict: TensorDictBase) -> TensorDictBase:
for t in self.transforms:
tensordict = t(tensordict)
return tensordict
def _step(self, tensordict: TensorDictBase) -> TensorDictBase:
for t in self.transforms:
tensordict = t._step(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_container(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_container(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}"
)
# empty cache of all transforms to reset parents and specs
self.empty_cache()
if index < 0:
index = index + len(self.transforms)
transform.eval()
self.transforms.insert(index, transform)
transform.set_container(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 * ' ')})"
def empty_cache(self):
for t in self.transforms:
t.empty_cache()
super().empty_cache()
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(in_keys=["pixels"])
>>> ri = torch.randint(0, 255, (1,1,10,11,3), dtype=torch.uint8)
>>> td = TensorDict(
... {"pixels": ri},
... [1, 1])
>>> _ = transform(td)
>>> obs = td.get("pixels")
>>> print(obs.shape, obs.dtype)
torch.Size([1, 1, 3, 10, 11]) torch.float32
"""
def __init__(
self,
unsqueeze: bool = False,
dtype: Optional[torch.device] = None,
in_keys: Optional[Sequence[str]] = None,
out_keys: Optional[Sequence[str]] = None,
):
if in_keys is None:
in_keys = IMAGE_KEYS # default
super().__init__(in_keys=in_keys, out_keys=out_keys)
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(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.
"""
def __init__(
self,
clamp_min: float = None,
clamp_max: float = None,
in_keys: Optional[Sequence[str]] = None,
out_keys: Optional[Sequence[str]] = None,
):
if in_keys is None:
in_keys = ["reward"]
super().__init__(in_keys=in_keys, out_keys=out_keys)
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,
shape=reward_spec.shape,
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.in_keys})"
)
class BinarizeReward(Transform):
"""Maps the reward to a binary value (0 or 1) if the reward is null or non-null, respectively."""
def __init__(
self,
in_keys: Optional[Sequence[str]] = None,
out_keys: Optional[Sequence[str]] = None,
):
if in_keys is None:
in_keys = ["reward"]
super().__init__(in_keys=in_keys, out_keys=out_keys)
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, shape=reward_spec.shape
)
class Resize(ObservationTransform):
"""Resizes an pixel observation.
Args:
w (int): resulting width
h (int): resulting height
interpolation (str): interpolation method
"""
def __init__(
self,
w: int,
h: int,
interpolation: str = "bilinear",
in_keys: Optional[Sequence[str]] = None,
out_keys: 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 in_keys is None:
in_keys = IMAGE_KEYS # default
super().__init__(in_keys=in_keys, out_keys=out_keys)
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:
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.in_keys})"
)
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).
"""
def __init__(
self,
w: int,
h: int = None,
in_keys: Optional[Sequence[str]] = None,
):
if in_keys is None:
in_keys = IMAGE_KEYS # default
super().__init__(in_keys=in_keys)
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.in_keys
else _obs_spec
for key, _obs_spec in observation_spec._specs.items()
},
shape=observation_spec.shape,
)