forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1631 lines (1457 loc) · 66.8 KB
/
utils.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 contextlib
import functools
import importlib.util
import inspect
import os
import re
import warnings
from enum import Enum
from typing import Any, Dict, List, Union
import tensordict.base
import torch
from tensordict import (
is_tensor_collection,
LazyStackedTensorDict,
NonTensorData,
NonTensorStack,
TensorDict,
TensorDictBase,
unravel_key,
)
from tensordict.base import _is_leaf_nontensor
from tensordict.nn import TensorDictModule, TensorDictModuleBase
from tensordict.nn.probabilistic import ( # noqa
# Note: the `set_interaction_mode` and their associated arg `default_interaction_mode` are being deprecated!
# Please use the `set_/interaction_type` ones above with the InteractionType enum instead.
# See more details: https://github.com/pytorch/rl/issues/1016
interaction_mode as exploration_mode,
interaction_type as exploration_type,
InteractionType as ExplorationType,
set_interaction_mode as set_exploration_mode,
set_interaction_type as set_exploration_type,
)
from tensordict.utils import is_non_tensor, NestedKey
from torch import nn as nn
from torch.utils._pytree import tree_map
from torchrl._utils import _replace_last, _rng_decorator, logger as torchrl_logger
from torchrl.data.tensor_specs import (
Composite,
NO_DEFAULT_RL as NO_DEFAULT,
TensorSpec,
Unbounded,
)
from torchrl.data.utils import check_no_exclusive_keys
__all__ = [
"exploration_mode",
"exploration_type",
"set_exploration_mode",
"set_exploration_type",
"ExplorationType",
"check_env_specs",
"step_mdp",
"make_composite_from_td",
"MarlGroupMapType",
"check_marl_grouping",
]
ACTION_MASK_ERROR = RuntimeError(
"An out-of-bounds actions has been provided to an env with an 'action_mask' output."
" If you are using a custom policy, make sure to take the action mask into account when computing the output."
" If you are using a default policy, please add the torchrl.envs.transforms.ActionMask transform to your environment."
"If you are using a ParallelEnv or another batched inventor, "
"make sure to add the transform to the ParallelEnv (and not to the sub-environments)."
" For more info on using action masks, see the docs at: "
"https://pytorch.org/rl/reference/envs.html#environments-with-masked-actions"
)
def _convert_exploration_type(*, exploration_mode, exploration_type):
if exploration_mode is not None:
return ExplorationType.from_str(exploration_mode)
return exploration_type
class _classproperty(property):
def __get__(self, cls, owner):
return classmethod(self.fget).__get__(None, owner)()
class _StepMDP:
"""Stateful version of step_mdp.
Precomputes the list of keys to include and exclude during a call to step_mdp
to reduce runtime.
"""
def __init__(
self,
env,
*,
keep_other: bool = True,
exclude_reward: bool = True,
exclude_done: bool = False,
exclude_action: bool = True,
):
action_keys = env.action_keys
done_keys = env.done_keys
reward_keys = env.reward_keys
observation_keys = env.full_observation_spec.keys(True, True)
state_keys = env.full_state_spec.keys(True, True)
self.action_keys = [unravel_key(key) for key in action_keys]
self.done_keys = [unravel_key(key) for key in done_keys]
self.observation_keys = list(observation_keys)
self.state_keys = list(state_keys)
self.reward_keys = [unravel_key(key) for key in reward_keys]
self.reward_keys_filt = list(set(self.reward_keys) - set(self.state_keys))
excluded = set()
if exclude_reward:
# If a reward is also a state, it must be in the input
excluded = excluded.union(self.reward_keys_filt)
if exclude_done:
excluded = excluded.union(self.done_keys)
if exclude_action:
excluded = excluded.union(self.action_keys)
self.excluded = [unravel_key(key) for key in excluded]
self.keep_other = keep_other
self.exclude_action = exclude_action
self.exclude_from_root = ["next", *self.done_keys]
self.keys_from_next = list(self.observation_keys)
if not exclude_reward:
self.keys_from_next += self.reward_keys
else:
self.keys_from_next += [
reward_key
for reward_key in self.reward_keys
if reward_key in self.state_keys
]
if not exclude_done:
self.keys_from_next += self.done_keys
self.keys_from_root = []
if not exclude_action:
self.keys_from_root += self.action_keys
else:
self.exclude_from_root += self.action_keys
if keep_other:
self.keys_from_root += self.state_keys
else:
self.exclude_from_root += self.state_keys
reset_keys = {_replace_last(key, "_reset") for key in self.done_keys}
self.exclude_from_root += list(reset_keys)
self.exclude_from_root += self.reward_keys_filt
self.exclude_from_root = self._repr_key_list_as_tree(self.exclude_from_root)
self.keys_from_root = self._repr_key_list_as_tree(self.keys_from_root)
self.keys_from_next = self._repr_key_list_as_tree(self.keys_from_next)
self.validated = None
# Model based envs can have missing keys
# TODO: do we want to always allow this? check_env_specs should catch these or downstream ops
self._allow_absent_keys = True
def validate(self, tensordict):
if self.validated:
return True
if self.validated is None:
# check that the key set of the tensordict matches what is expected
expected = (
self.state_keys
+ self.action_keys
+ self.done_keys
+ self.observation_keys
+ [unravel_key(("next", key)) for key in self.observation_keys]
+ [unravel_key(("next", key)) for key in self.done_keys]
+ [unravel_key(("next", key)) for key in self.reward_keys]
)
def _is_reset(key: NestedKey):
if isinstance(key, str):
return key == "_reset"
return key[-1] == "_reset"
actual = {
key
for key in tensordict.keys(True, True, is_leaf=_is_leaf_nontensor)
if not _is_reset(key)
}
expected = set(expected)
self.validated = expected.intersection(actual) == expected
if not self.validated:
warnings.warn(
"The expected key set and actual key set differ. "
"This will work but with a slower throughput than "
"when the specs match exactly the actual key set "
"in the data. "
f"{{Expected keys}}-{{Actual keys}}={set(expected) - actual}, \n"
f"{{Actual keys}}-{{Expected keys}}={actual- set(expected)}."
)
return self.validated
@staticmethod
def _repr_key_list_as_tree(key_list):
"""Represents the keys as a tree to facilitate iteration."""
if not key_list:
return {}
key_dict = {key: torch.zeros(()) for key in key_list}
td = TensorDict(key_dict, batch_size=torch.Size([]))
return tree_map(lambda x: None, td.to_dict())
@classmethod
def _grab_and_place(
cls,
nested_key_dict: dict,
data_in: TensorDictBase,
data_out: TensorDictBase,
_allow_absent_keys: bool,
):
for key, subdict in nested_key_dict.items():
val = data_in._get_str(key, NO_DEFAULT)
if subdict is not None:
val_out = data_out._get_str(key, None)
if val_out is None:
val_out = val.empty()
if isinstance(val, LazyStackedTensorDict):
val = LazyStackedTensorDict(
*(
cls._grab_and_place(
subdict,
_val,
_val_out,
_allow_absent_keys=_allow_absent_keys,
)
for (_val, _val_out) in zip(
val.unbind(val.stack_dim),
val_out.unbind(val_out.stack_dim),
)
),
stack_dim=val.stack_dim,
)
else:
val = cls._grab_and_place(
subdict, val, val_out, _allow_absent_keys=_allow_absent_keys
)
if val is NO_DEFAULT:
if not _allow_absent_keys:
raise KeyError(f"key {key} not found.")
else:
if is_non_tensor(val):
val = val.clone()
data_out._set_str(
key, val, validated=True, inplace=False, non_blocking=False
)
return data_out
@classmethod
def _exclude(
cls, nested_key_dict: dict, data_in: TensorDictBase, out: TensorDictBase | None
) -> None:
"""Copies the entries if they're not part of the list of keys to exclude."""
if isinstance(data_in, LazyStackedTensorDict):
if out is None:
out = data_in.empty()
for td, td_out in zip(data_in.tensordicts, out.tensordicts):
cls._exclude(nested_key_dict, td, td_out)
return out
has_set = False
for key, value in data_in.items(is_leaf=_is_leaf_nontensor):
subdict = nested_key_dict.get(key, NO_DEFAULT)
if subdict is NO_DEFAULT:
value = value.copy() if is_tensor_collection(value) else value
if not has_set and out is None:
out = data_in.empty()
out._set_str(key, value, validated=True, inplace=False)
has_set = True
elif subdict is not None:
value = cls._exclude(subdict, value, None)
if value is not None:
if not has_set and out is None:
out = data_in.empty()
out._set_str(key, value, validated=True, inplace=False)
has_set = True
if has_set:
return out
def __call__(self, tensordict):
if isinstance(tensordict, LazyStackedTensorDict):
out = LazyStackedTensorDict.lazy_stack(
[self.__call__(td) for td in tensordict.tensordicts],
tensordict.stack_dim,
)
return out
next_td = tensordict._get_str("next", None)
if self.validate(tensordict):
if self.keep_other:
out = self._exclude(self.exclude_from_root, tensordict, out=None)
else:
out = next_td.empty()
self._grab_and_place(
self.keys_from_root,
tensordict,
out,
_allow_absent_keys=self._allow_absent_keys,
)
if isinstance(next_td, LazyStackedTensorDict):
if not isinstance(out, LazyStackedTensorDict):
out = LazyStackedTensorDict(
*out.unbind(next_td.stack_dim), stack_dim=next_td.stack_dim
)
for _next_td, _out in zip(next_td.tensordicts, out.tensordicts):
self._grab_and_place(
self.keys_from_next,
_next_td,
_out,
_allow_absent_keys=self._allow_absent_keys,
)
else:
self._grab_and_place(
self.keys_from_next,
next_td,
out,
_allow_absent_keys=self._allow_absent_keys,
)
return out
else:
out = next_td.empty()
total_key = ()
if self.keep_other:
for key in tensordict.keys():
if key != "next":
_set(tensordict, out, key, total_key, self.excluded)
elif not self.exclude_action:
for action_key in self.action_keys:
_set_single_key(tensordict, out, action_key)
for key in next_td.keys():
_set(next_td, out, key, total_key, self.excluded)
return out
def step_mdp(
tensordict: TensorDictBase,
next_tensordict: TensorDictBase = None,
keep_other: bool = True,
exclude_reward: bool = True,
exclude_done: bool = False,
exclude_action: bool = True,
reward_keys: Union[NestedKey, List[NestedKey]] = "reward",
done_keys: Union[NestedKey, List[NestedKey]] = "done",
action_keys: Union[NestedKey, List[NestedKey]] = "action",
) -> TensorDictBase:
"""Creates a new tensordict that reflects a step in time of the input tensordict.
Given a tensordict retrieved after a step, returns the :obj:`"next"` indexed-tensordict.
The arguments allow for a precise control over what should be kept and what
should be copied from the ``"next"`` entry. The default behavior is:
move the observation entries, reward and done states to the root, exclude
the current action and keep all extra keys (non-action, non-done, non-reward).
Args:
tensordict (TensorDictBase): tensordict with keys to be renamed
next_tensordict (TensorDictBase, optional): destination tensordict
keep_other (bool, optional): if ``True``, all keys that do not start with :obj:`'next_'` will be kept.
Default is ``True``.
exclude_reward (bool, optional): if ``True``, the :obj:`"reward"` key will be discarded
from the resulting tensordict. If ``False``, it will be copied (and replaced)
from the ``"next"`` entry (if present).
Default is ``True``.
exclude_done (bool, optional): if ``True``, the :obj:`"done"` key will be discarded
from the resulting tensordict. If ``False``, it will be copied (and replaced)
from the ``"next"`` entry (if present).
Default is ``False``.
exclude_action (bool, optional): if ``True``, the :obj:`"action"` key will
be discarded from the resulting tensordict. If ``False``, it will
be kept in the root tensordict (since it should not be present in
the ``"next"`` entry).
Default is ``True``.
reward_keys (NestedKey or list of NestedKey, optional): the keys where the reward is written. Defaults
to "reward".
done_keys (NestedKey or list of NestedKey, optional): the keys where the done is written. Defaults
to "done".
action_keys (NestedKey or list of NestedKey, optional): the keys where the action is written. Defaults
to "action".
Returns:
A new tensordict (or next_tensordict) containing the tensors of the t+1 step.
Examples:
This funtion allows for this kind of loop to be used:
>>> from tensordict import TensorDict
>>> import torch
>>> td = TensorDict({
... "done": torch.zeros((), dtype=torch.bool),
... "reward": torch.zeros(()),
... "extra": torch.zeros(()),
... "next": TensorDict({
... "done": torch.zeros((), dtype=torch.bool),
... "reward": torch.zeros(()),
... "obs": torch.zeros(()),
... }, []),
... "obs": torch.zeros(()),
... "action": torch.zeros(()),
... }, [])
>>> print(step_mdp(td))
TensorDict(
fields={
done: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.bool, is_shared=False),
extra: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False),
obs: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)},
batch_size=torch.Size([]),
device=None,
is_shared=False)
>>> print(step_mdp(td, exclude_done=True)) # "done" is dropped
TensorDict(
fields={
extra: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False),
obs: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)},
batch_size=torch.Size([]),
device=None,
is_shared=False)
>>> print(step_mdp(td, exclude_reward=False)) # "reward" is kept
TensorDict(
fields={
done: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.bool, is_shared=False),
extra: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False),
obs: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False),
reward: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)},
batch_size=torch.Size([]),
device=None,
is_shared=False)
>>> print(step_mdp(td, exclude_action=False)) # "action" persists at the root
TensorDict(
fields={
action: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False),
done: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.bool, is_shared=False),
extra: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False),
obs: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)},
batch_size=torch.Size([]),
device=None,
is_shared=False)
>>> print(step_mdp(td, keep_other=False)) # "extra" is missing
TensorDict(
fields={
done: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.bool, is_shared=False),
obs: Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, is_shared=False)},
batch_size=torch.Size([]),
device=None,
is_shared=False)
.. warning:: This function will not work properly if the reward key is also part of the input key when
the reward keys are excluded. This is why the :class:`~torchrl.envs.RewardSum` transform registers
the episode reward in the observation and not the reward spec by default.
When using the fast, cached version of this function (``_StepMDP``), this issue should not
be observed.
"""
if isinstance(tensordict, LazyStackedTensorDict):
if next_tensordict is not None:
next_tensordicts = next_tensordict.unbind(tensordict.stack_dim)
else:
next_tensordicts = [None] * len(tensordict.tensordicts)
out = LazyStackedTensorDict.lazy_stack(
[
step_mdp(
td,
next_tensordict=ntd,
keep_other=keep_other,
exclude_reward=exclude_reward,
exclude_done=exclude_done,
exclude_action=exclude_action,
reward_keys=reward_keys,
done_keys=done_keys,
action_keys=action_keys,
)
for td, ntd in zip(tensordict.tensordicts, next_tensordicts)
],
tensordict.stack_dim,
)
if next_tensordict is not None:
next_tensordict.update(out)
return next_tensordict
return out
if not isinstance(action_keys, list):
action_keys = [action_keys]
if not isinstance(done_keys, list):
done_keys = [done_keys]
if not isinstance(reward_keys, list):
reward_keys = [reward_keys]
excluded = set()
if exclude_reward:
excluded = excluded.union(reward_keys)
if exclude_done:
excluded = excluded.union(done_keys)
if exclude_action:
excluded = excluded.union(action_keys)
next_td = tensordict.get("next")
out = next_td.empty()
total_key = ()
if keep_other:
for key in tensordict.keys():
if key != "next":
_set(tensordict, out, key, total_key, excluded)
elif not exclude_action:
for action_key in action_keys:
_set_single_key(tensordict, out, action_key)
for key in next_td.keys():
_set(next_td, out, key, total_key, excluded)
if next_tensordict is not None:
return next_tensordict.update(out)
else:
return out
def _set_single_key(
source: TensorDictBase,
dest: TensorDictBase,
key: str | tuple,
clone: bool = False,
device=None,
):
# key should be already unraveled
if isinstance(key, str):
key = (key,)
for k in key:
try:
val = source._get_str(k, None)
if is_tensor_collection(val):
new_val = dest._get_str(k, None)
if new_val is None:
new_val = val.empty()
dest._set_str(
k, new_val, inplace=False, validated=True, non_blocking=False
)
source = val
dest = new_val
else:
if device is not None and val.device != device:
val = val.to(device, non_blocking=True)
elif clone:
val = val.clone()
dest._set_str(k, val, inplace=False, validated=True, non_blocking=False)
# This is a temporary solution to understand if a key is heterogeneous
# while not having performance impact when the exception is not raised
except RuntimeError as err:
if re.match(r"Found more than one unique shape in the tensors", str(err)):
# this is a het key
for s_td, d_td in zip(source.tensordicts, dest.tensordicts):
_set_single_key(s_td, d_td, k, clone=clone, device=device)
break
else:
raise err
def _set(source, dest, key, total_key, excluded):
total_key = total_key + (key,)
non_empty = False
if unravel_key(total_key) not in excluded:
try:
val = source.get(key)
if is_tensor_collection(val) and not isinstance(
val, (NonTensorData, NonTensorStack)
):
# if val is a tensordict we need to copy the structure
new_val = dest.get(key, None)
if new_val is None:
new_val = val.empty()
non_empty_local = False
for subkey in val.keys():
non_empty_local = (
_set(val, new_val, subkey, total_key, excluded)
or non_empty_local
)
if non_empty_local:
# dest.set(key, new_val)
dest._set_str(
key, new_val, inplace=False, validated=True, non_blocking=False
)
non_empty = non_empty_local
else:
non_empty = True
# dest.set(key, val)
dest._set_str(
key, val, inplace=False, validated=True, non_blocking=False
)
# This is a temporary solution to understand if a key is heterogeneous
# while not having performance impact when the exception is not raised
except RuntimeError as err:
if re.match(r"Found more than one unique shape in the tensors", str(err)):
# this is a het key
non_empty_local = False
for s_td, d_td in zip(source.tensordicts, dest.tensordicts):
non_empty_local = (
_set(s_td, d_td, key, total_key, excluded) or non_empty_local
)
non_empty = non_empty_local
else:
raise err
return non_empty
def get_available_libraries():
"""Returns all the supported libraries."""
return SUPPORTED_LIBRARIES
def _check_gym():
"""Returns True if the gym library is installed."""
return importlib.util.find_spec("gym") is not None
def _check_gym_atari():
"""Returns True if the gym library is installed and atari envs can be found."""
if not _check_gym():
return False
return importlib.util.find_spec("atari-py") is not None
def _check_mario():
"""Returns True if the "gym-super-mario-bros" library is installed."""
return importlib.util.find_spec("gym-super-mario-bros") is not None
def _check_dmcontrol():
"""Returns True if the "dm-control" library is installed."""
return importlib.util.find_spec("dm_control") is not None
def _check_dmlab():
"""Returns True if the "deepmind-lab" library is installed."""
return importlib.util.find_spec("deepmind_lab") is not None
SUPPORTED_LIBRARIES = {
"gym": _check_gym(), # OpenAI
"gym[atari]": _check_gym_atari(), #
"dm_control": _check_dmcontrol(),
"habitat": None,
"gym-super-mario-bros": _check_mario(),
# "vizdoom": None, # gym based, https://github.com/mwydmuch/ViZDoom
# "openspiel": None, # DM, https://github.com/deepmind/open_spiel
# "pysc2": None, # DM, https://github.com/deepmind/pysc2
# "deepmind_lab": _check_dmlab(),
# DM, https://github.com/deepmind/lab, https://github.com/deepmind/lab/tree/master/python/pip_package
# "serpent.ai": None, # https://github.com/SerpentAI/SerpentAI
# "gfootball": None, # 2.8k G, https://github.com/google-research/football
# DM, https://github.com/deepmind/dm_control
# FB, https://github.com/facebookresearch/habitat-sim
# "meta-world": None, # https://github.com/rlworkgroup/metaworld
# "minerl": None, # https://github.com/minerllabs/minerl
# "multi-agent-emergence-environments": None,
# OpenAI, https://github.com/openai/multi-agent-emergence-environments
# "procgen": None, # OpenAI, https://github.com/openai/procgen
# "pybullet": None, # https://github.com/benelot/pybullet-gym
# "realworld_rl_suite": None,
# G, https://github.com/google-research/realworldrl_suite
# "rlcard": None, # https://github.com/datamllab/rlcard
# "screeps": None, # https://github.com/screeps/screeps
# "ml-agents": None,
}
def _per_level_env_check(data0, data1, check_dtype):
"""Checks shape and dtype of two tensordicts, accounting for lazy stacks."""
if isinstance(data0, LazyStackedTensorDict):
for _data0, _data1 in zip(data0.tensordicts, data1.unbind(data0.stack_dim)):
_per_level_env_check(_data0, _data1, check_dtype=check_dtype)
return
if isinstance(data1, LazyStackedTensorDict):
for _data0, _data1 in zip(data0.unbind(data1.stack_dim), data1.tensordicts):
_per_level_env_check(_data0, _data1, check_dtype=check_dtype)
return
else:
keys0 = set(data0.keys())
keys1 = set(data1.keys())
if keys0 != keys1:
raise AssertionError(f"Keys mismatch: {keys0} vs {keys1}")
for key in keys0:
_data0 = data0[key]
_data1 = data1[key]
if _data0.shape != _data1.shape:
raise AssertionError(
f"The shapes of the real and fake tensordict don't match for key {key}. "
f"Got fake={_data0.shape} and real={_data1.shape}."
)
if isinstance(_data0, TensorDictBase):
_per_level_env_check(_data0, _data1, check_dtype=check_dtype)
else:
if check_dtype and (_data0.dtype != _data1.dtype):
raise AssertionError(
f"The dtypes of the real and fake tensordict don't match for key {key}. "
f"Got fake={_data0.dtype} and real={_data1.dtype}."
)
def check_env_specs(
env, return_contiguous=True, check_dtype=True, seed: int | None = None
):
"""Tests an environment specs against the results of short rollout.
This test function should be used as a sanity check for an env wrapped with
torchrl's EnvBase subclasses: any discrepancy between the expected data and
the data collected should raise an assertion error.
A broken environment spec will likely make it impossible to use parallel
environments.
Args:
env (EnvBase): the env for which the specs have to be checked against data.
return_contiguous (bool, optional): if ``True``, the random rollout will be called with
return_contiguous=True. This will fail in some cases (e.g. heterogeneous shapes
of inputs/outputs). Defaults to True.
check_dtype (bool, optional): if False, dtype checks will be skipped.
Defaults to True.
seed (int, optional): for reproducibility, a seed can be set.
The seed will be set in pytorch temporarily, then the RNG state will
be reverted to what it was before. For the env, we set the seed but since
setting the rng state back to what is was isn't a feature of most environment,
we leave it to the user to accomplish that.
Defaults to ``None``.
Caution: this function resets the env seed. It should be used "offline" to
check that an env is adequately constructed, but it may affect the seeding
of an experiment and as such should be kept out of training scripts.
"""
if seed is not None:
device = (
env.device if env.device is not None and env.device.type == "cuda" else None
)
with _rng_decorator(seed, device=device):
env.set_seed(seed)
return check_env_specs(
env, return_contiguous=return_contiguous, check_dtype=check_dtype
)
fake_tensordict = env.fake_tensordict()
real_tensordict = env.rollout(3, return_contiguous=return_contiguous)
if return_contiguous:
fake_tensordict = fake_tensordict.unsqueeze(real_tensordict.batch_dims - 1)
fake_tensordict = fake_tensordict.expand(*real_tensordict.shape)
else:
fake_tensordict = LazyStackedTensorDict.lazy_stack(
[fake_tensordict.clone() for _ in range(3)], -1
)
# eliminate empty containers
fake_tensordict_select = fake_tensordict.select(
*fake_tensordict.keys(True, True, is_leaf=tensordict.base._default_is_leaf)
)
real_tensordict_select = real_tensordict.select(
*real_tensordict.keys(True, True, is_leaf=tensordict.base._default_is_leaf)
)
# check keys
fake_tensordict_keys = set(
fake_tensordict.keys(True, True, is_leaf=tensordict.base._is_leaf_nontensor)
)
real_tensordict_keys = set(
real_tensordict.keys(True, True, is_leaf=tensordict.base._is_leaf_nontensor)
)
if fake_tensordict_keys != real_tensordict_keys:
raise AssertionError(
f"""The keys of the specs and data do not match:
- List of keys present in real but not in fake: {real_tensordict_keys-fake_tensordict_keys},
- List of keys present in fake but not in real: {fake_tensordict_keys-real_tensordict_keys}.
"""
)
zeroing_err_msg = (
"zeroing the two tensordicts did not make them identical. "
"Check for discrepancies:\nFake=\n{fake_tensordict}\nReal=\n{real_tensordict}"
)
from torchrl.envs.common import _has_dynamic_specs
if _has_dynamic_specs(env.specs):
for real, fake in zip(real_tensordict.unbind(-1), fake_tensordict.unbind(-1)):
fake = fake.apply(lambda x, y: x.expand_as(y), real)
if (torch.zeros_like(real) != torch.zeros_like(fake)).any():
raise AssertionError(zeroing_err_msg)
# Checks shapes and eventually dtypes of keys at all nesting levels
_per_level_env_check(fake, real, check_dtype=check_dtype)
else:
if (
torch.zeros_like(fake_tensordict_select)
!= torch.zeros_like(real_tensordict_select)
).any():
raise AssertionError(zeroing_err_msg)
# Checks shapes and eventually dtypes of keys at all nesting levels
_per_level_env_check(
fake_tensordict_select, real_tensordict_select, check_dtype=check_dtype
)
# Check specs
last_td = real_tensordict[..., -1]
last_td = env.rand_action(last_td)
full_action_spec = env.input_spec["full_action_spec"]
full_state_spec = env.input_spec["full_state_spec"]
full_observation_spec = env.output_spec["full_observation_spec"]
full_reward_spec = env.output_spec["full_reward_spec"]
full_done_spec = env.output_spec["full_done_spec"]
for name, spec in (
("action", full_action_spec),
("state", full_state_spec),
("done", full_done_spec),
("obs", full_observation_spec),
):
if not check_no_exclusive_keys(spec):
raise AssertionError(
"It appears you are using some LazyStackedCompositeSpecs with exclusive keys "
"(keys present in some but not all of the stacked specs). To use such heterogeneous specs, "
"you will need to first pass your stack through `torchrl.data.consolidate_spec`."
)
if spec is None:
spec = Composite(shape=env.batch_size, device=env.device)
td = last_td.select(*spec.keys(True, True), strict=True)
if not spec.contains(td):
raise AssertionError(
f"spec check failed at root for spec {name}={spec} and data {td}."
)
for name, spec in (
("reward", full_reward_spec),
("done", full_done_spec),
("obs", full_observation_spec),
):
if spec is None:
spec = Composite(shape=env.batch_size, device=env.device)
td = last_td.get("next").select(*spec.keys(True, True), strict=True)
if not spec.contains(td):
raise AssertionError(
f"spec check failed at root for spec {name}={spec} and data {td}."
)
torchrl_logger.info("check_env_specs succeeded!")
def _selective_unsqueeze(tensor: torch.Tensor, batch_size: torch.Size, dim: int = -1):
shape_len = len(tensor.shape)
if shape_len < len(batch_size):
raise RuntimeError(
f"Tensor has less dims than batch_size. shape:{tensor.shape}, batch_size: {batch_size}"
)
if tensor.shape[: len(batch_size)] != batch_size:
raise RuntimeError(
f"Tensor does not have given batch_size. shape:{tensor.shape}, batch_size: {batch_size}"
)
if shape_len == len(batch_size):
return tensor.unsqueeze(dim=dim)
return tensor
def _sort_keys(element):
if isinstance(element, tuple):
element = unravel_key(element)
return "_-|-_".join(element)
return element
def make_composite_from_td(data, unsqueeze_null_shapes: bool = True):
"""Creates a Composite instance from a tensordict, assuming all values are unbounded.
Args:
data (tensordict.TensorDict): a tensordict to be mapped onto a Composite.
unsqueeze_null_shapes (bool, optional): if ``True``, every empty shape will be
unsqueezed to (1,). Defaults to ``True``.
Examples:
>>> from tensordict import TensorDict
>>> data = TensorDict({
... "obs": torch.randn(3),
... "action": torch.zeros(2, dtype=torch.int),
... "next": {"obs": torch.randn(3), "reward": torch.randn(1)}
... }, [])
>>> spec = make_composite_from_td(data)
>>> print(spec)
Composite(
obs: UnboundedContinuous(
shape=torch.Size([3]), space=None, device=cpu, dtype=torch.float32, domain=continuous),
action: UnboundedContinuous(
shape=torch.Size([2]), space=None, device=cpu, dtype=torch.int32, domain=continuous),
next: Composite(
obs: UnboundedContinuous(
shape=torch.Size([3]), space=None, device=cpu, dtype=torch.float32, domain=continuous),
reward: UnboundedContinuous(
shape=torch.Size([1]), space=ContinuousBox(low=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, contiguous=True), high=Tensor(shape=torch.Size([]), device=cpu, dtype=torch.float32, contiguous=True)), device=cpu, dtype=torch.float32, domain=continuous), device=cpu, shape=torch.Size([])), device=cpu, shape=torch.Size([]))
>>> assert (spec.zero() == data.zero_()).all()
"""
# custom funtion to convert a tensordict in a similar spec structure
# of unbounded values.
composite = Composite(
{
key: make_composite_from_td(tensor)
if isinstance(tensor, TensorDictBase)
else Unbounded(
dtype=tensor.dtype,
device=tensor.device,
shape=tensor.shape
if tensor.shape or not unsqueeze_null_shapes
else [1],
)
for key, tensor in data.items()
},
shape=data.shape,
)
return composite
@contextlib.contextmanager
def clear_mpi_env_vars():
"""Clears the MPI of environment variables.
`from mpi4py import MPI` will call `MPI_Init` by default.
If the child process has MPI environment variables, MPI will think that the child process
is an MPI process just like the parent and do bad things such as hang.
This context manager is a hacky way to clear those environment variables
temporarily such as when we are starting multiprocessing Processes.
Yields:
Yields for the context manager
"""
removed_environment = {}
for k, v in list(os.environ.items()):
for prefix in ["OMPI_", "PMI_"]:
if k.startswith(prefix):
removed_environment[k] = v
del os.environ[k]
try:
yield
finally:
os.environ.update(removed_environment)
class MarlGroupMapType(Enum):
"""Marl Group Map Type.
As a feature of torchrl multiagent, you are able to control the grouping of agents in your environment.
You can group agents together (stacking their tensors) to leverage vectorization when passing them through the same
neural network. You can split agents in different groups where they are heterogenous or should be processed by
different neural networks. To group, you just need to pass a ``group_map`` at env constructiuon time.
Otherwise, you can choose one of the premade grouping strategies from this class.
- With ``group_map=MarlGroupMapType.ALL_IN_ONE_GROUP`` and
agents ``["agent_0", "agent_1", "agent_2", "agent_3"]``,
the tensordicts coming and going from your environment will look
something like:
>>> print(env.rand_action(env.reset()))
TensorDict(
fields={
agents: TensorDict(
fields={
action: Tensor(shape=torch.Size([4, 9]), device=cpu, dtype=torch.int64, is_shared=False),
done: Tensor(shape=torch.Size([4, 1]), device=cpu, dtype=torch.bool, is_shared=False),
observation: Tensor(shape=torch.Size([4, 3, 3, 2]), device=cpu, dtype=torch.int8, is_shared=False)},
batch_size=torch.Size([4]))},
batch_size=torch.Size([]))
>>> print(env.group_map)
{"agents": ["agent_0", "agent_1", "agent_2", "agent_3]}
- With ``group_map=MarlGroupMapType.ONE_GROUP_PER_AGENT`` and
agents ``["agent_0", "agent_1", "agent_2", "agent_3"]``,
the tensordicts coming and going from your environment will look
something like:
>>> print(env.rand_action(env.reset()))
TensorDict(
fields={
agent_0: TensorDict(
fields={
action: Tensor(shape=torch.Size([9]), device=cpu, dtype=torch.int64, is_shared=False),
done: Tensor(shape=torch.Size([1]), device=cpu, dtype=torch.bool, is_shared=False),
observation: Tensor(shape=torch.Size([3, 3, 2]), device=cpu, dtype=torch.int8, is_shared=False)},
batch_size=torch.Size([]))},
agent_1: TensorDict(
fields={
action: Tensor(shape=torch.Size([9]), device=cpu, dtype=torch.int64, is_shared=False),
done: Tensor(shape=torch.Size([1]), device=cpu, dtype=torch.bool, is_shared=False),
observation: Tensor(shape=torch.Size([3, 3, 2]), device=cpu, dtype=torch.int8, is_shared=False)},
batch_size=torch.Size([]))},
agent_2: TensorDict(
fields={
action: Tensor(shape=torch.Size([9]), device=cpu, dtype=torch.int64, is_shared=False),
done: Tensor(shape=torch.Size([1]), device=cpu, dtype=torch.bool, is_shared=False),
observation: Tensor(shape=torch.Size([3, 3, 2]), device=cpu, dtype=torch.int8, is_shared=False)},
batch_size=torch.Size([]))},