forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_libs.py
4010 lines (3626 loc) · 139 KB
/
test_libs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import functools
import gc
import importlib.util
_has_isaac = importlib.util.find_spec("isaacgym") is not None
if _has_isaac:
# isaac gym asks to be imported before torch...
import isaacgym # noqa
import isaacgymenvs # noqa
from torchrl.envs.libs.isaacgym import IsaacGymEnv
import argparse
import importlib
import os
import time
from contextlib import nullcontext
from pathlib import Path
from sys import platform
from typing import Optional, Union
import numpy as np
import pytest
import torch
from _utils_internal import (
_make_multithreaded_env,
CARTPOLE_VERSIONED,
get_available_devices,
get_default_devices,
HALFCHEETAH_VERSIONED,
PENDULUM_VERSIONED,
PONG_VERSIONED,
rand_reset,
rollout_consistency_assertion,
)
from packaging import version
from tensordict import (
assert_allclose_td,
is_tensor_collection,
LazyStackedTensorDict,
TensorDict,
)
from tensordict.nn import (
ProbabilisticTensorDictModule,
TensorDictModule,
TensorDictSequential,
)
from torch import nn
from torchrl._utils import implement_for, logger as torchrl_logger
from torchrl.collectors.collectors import SyncDataCollector
from torchrl.data import (
Binary,
Bounded,
Categorical,
Composite,
MultiCategorical,
MultiOneHot,
OneHot,
ReplayBuffer,
ReplayBufferEnsemble,
Unbounded,
UnboundedDiscreteTensorSpec,
)
from torchrl.data.datasets.atari_dqn import AtariDQNExperienceReplay
from torchrl.data.datasets.d4rl import D4RLExperienceReplay
from torchrl.data.datasets.gen_dgrl import GenDGRLExperienceReplay
from torchrl.data.datasets.minari_data import MinariExperienceReplay
from torchrl.data.datasets.openml import OpenMLExperienceReplay
from torchrl.data.datasets.openx import OpenXExperienceReplay
from torchrl.data.datasets.roboset import RobosetExperienceReplay
from torchrl.data.datasets.vd4rl import VD4RLExperienceReplay
from torchrl.data.replay_buffers import SamplerWithoutReplacement
from torchrl.data.utils import CloudpickleWrapper
from torchrl.envs import (
CatTensors,
Compose,
DoubleToFloat,
EnvBase,
EnvCreator,
RemoveEmptySpecs,
RenameTransform,
)
from torchrl.envs.batched_envs import SerialEnv
from torchrl.envs.libs.brax import _has_brax, BraxEnv, BraxWrapper
from torchrl.envs.libs.dm_control import _has_dmc, DMControlEnv, DMControlWrapper
from torchrl.envs.libs.envpool import _has_envpool, MultiThreadedEnvWrapper
from torchrl.envs.libs.gym import (
_gym_to_torchrl_spec_transform,
_has_gym,
_is_from_pixels,
_torchrl_to_gym_spec_transform,
gym_backend,
GymEnv,
GymWrapper,
MOGymEnv,
MOGymWrapper,
set_gym_backend,
)
from torchrl.envs.libs.habitat import _has_habitat, HabitatEnv
from torchrl.envs.libs.jumanji import _has_jumanji, JumanjiEnv
from torchrl.envs.libs.meltingpot import MeltingpotEnv, MeltingpotWrapper
from torchrl.envs.libs.openml import OpenMLEnv
from torchrl.envs.libs.openspiel import _has_pyspiel, OpenSpielEnv, OpenSpielWrapper
from torchrl.envs.libs.pettingzoo import _has_pettingzoo, PettingZooEnv
from torchrl.envs.libs.robohive import _has_robohive, RoboHiveEnv
from torchrl.envs.libs.smacv2 import _has_smacv2, SMACv2Env
from torchrl.envs.libs.vmas import _has_vmas, VmasEnv, VmasWrapper
from torchrl.envs.transforms import ActionMask, TransformedEnv
from torchrl.envs.utils import (
check_env_specs,
ExplorationType,
MarlGroupMapType,
RandomPolicy,
)
from torchrl.modules import (
ActorCriticOperator,
MaskedCategorical,
MLP,
SafeModule,
ValueOperator,
)
_has_d4rl = importlib.util.find_spec("d4rl") is not None
_has_mo = importlib.util.find_spec("mo_gymnasium") is not None
_has_sklearn = importlib.util.find_spec("sklearn") is not None
_has_gym_robotics = importlib.util.find_spec("gymnasium_robotics") is not None
_has_minari = importlib.util.find_spec("minari") is not None
_has_gymnasium = importlib.util.find_spec("gymnasium") is not None
_has_gym_regular = importlib.util.find_spec("gym") is not None
if _has_gymnasium:
set_gym_backend("gymnasium").set()
import gymnasium
assert gym_backend() is gymnasium
elif _has_gym:
set_gym_backend("gym").set()
import gym
assert gym_backend() is gym
_has_meltingpot = importlib.util.find_spec("meltingpot") is not None
_has_minigrid = importlib.util.find_spec("minigrid") is not None
@pytest.fixture(scope="session", autouse=True)
def maybe_init_minigrid():
if _has_minigrid and _has_gymnasium:
import minigrid
minigrid.register_minigrid_envs()
def get_gym_pixel_wrapper():
try:
# works whenever gym_version > version.parse("0.19")
PixelObservationWrapper = gym_backend(
"wrappers.pixel_observation"
).PixelObservationWrapper
except Exception as err:
from torchrl.envs.libs.utils import (
GymPixelObservationWrapper as PixelObservationWrapper,
)
return PixelObservationWrapper
if _has_gym:
try:
from gymnasium import __version__ as gym_version
gym_version = version.parse(gym_version)
except ModuleNotFoundError:
from gym import __version__ as gym_version
gym_version = version.parse(gym_version)
if _has_dmc:
from dm_control import suite
from dm_control.suite.wrappers import pixels
if _has_vmas:
import vmas
if _has_envpool:
import envpool
_has_pytree = True
try:
from torch.utils._pytree import tree_flatten, tree_map
except ImportError:
_has_pytree = False
IS_OSX = platform == "darwin"
RTOL = 1e-1
ATOL = 1e-1
@pytest.mark.skipif(not _has_gym, reason="no gym library found")
class TestGym:
class DummyEnv(EnvBase):
def __init__(self, arg1, *, arg2, **kwargs):
super().__init__(**kwargs)
assert arg1 == 1
assert arg2 == 2
self.observation_spec = Composite(
observation=Unbounded((*self.batch_size, 3)),
other=Composite(
another_other=Unbounded((*self.batch_size, 3)),
shape=self.batch_size,
),
shape=self.batch_size,
)
self.action_spec = Unbounded((*self.batch_size, 3))
self.done_spec = Categorical(2, (*self.batch_size, 1), dtype=torch.bool)
self.full_done_spec["truncated"] = self.full_done_spec["terminated"].clone()
def _reset(self, tensordict):
return self.observation_spec.rand()
def _step(self, tensordict):
action = tensordict.get("action")
return TensorDict(
{
"observation": action.clone(),
"other": {"another_other": torch.zeros_like(action)},
"reward": action.sum(-1, True),
"done": ~action.any(-1, True),
"terminated": ~action.any(-1, True),
"truncated": torch.zeros((*self.batch_size, 1), dtype=torch.bool),
},
batch_size=[],
)
def _set_seed(self, seed):
return seed + 1
@implement_for("gym", None, "0.18")
def _make_spec(self, batch_size, cat, cat_shape, multicat, multicat_shape):
return Composite(
a=Unbounded(shape=(*batch_size, 1)),
b=Composite(c=cat(5, shape=cat_shape, dtype=torch.int64), shape=batch_size),
d=cat(5, shape=cat_shape, dtype=torch.int64),
e=multicat([2, 3], shape=(*batch_size, multicat_shape), dtype=torch.int64),
f=Bounded(-3, 4, shape=(*batch_size, 1)),
# g=UnboundedDiscreteTensorSpec(shape=(*batch_size, 1), dtype=torch.long),
h=Binary(n=5, shape=(*batch_size, 5)),
shape=batch_size,
)
@implement_for("gym", "0.18", None)
def _make_spec( # noqa: F811
self, batch_size, cat, cat_shape, multicat, multicat_shape
):
return Composite(
a=Unbounded(shape=(*batch_size, 1)),
b=Composite(c=cat(5, shape=cat_shape, dtype=torch.int64), shape=batch_size),
d=cat(5, shape=cat_shape, dtype=torch.int64),
e=multicat([2, 3], shape=(*batch_size, multicat_shape), dtype=torch.int64),
f=Bounded(-3, 4, shape=(*batch_size, 1)),
g=UnboundedDiscreteTensorSpec(shape=(*batch_size, 1), dtype=torch.long),
h=Binary(n=5, shape=(*batch_size, 5)),
shape=batch_size,
)
@implement_for("gymnasium")
def _make_spec( # noqa: F811
self, batch_size, cat, cat_shape, multicat, multicat_shape
):
return Composite(
a=Unbounded(shape=(*batch_size, 1)),
b=Composite(c=cat(5, shape=cat_shape, dtype=torch.int64), shape=batch_size),
d=cat(5, shape=cat_shape, dtype=torch.int64),
e=multicat([2, 3], shape=(*batch_size, multicat_shape), dtype=torch.int64),
f=Bounded(-3, 4, shape=(*batch_size, 1)),
g=UnboundedDiscreteTensorSpec(shape=(*batch_size, 1), dtype=torch.long),
h=Binary(n=5, shape=(*batch_size, 5)),
shape=batch_size,
)
@pytest.mark.parametrize("categorical", [True, False])
def test_gym_spec_cast(self, categorical):
batch_size = [3, 4]
cat = Categorical if categorical else OneHot
cat_shape = batch_size if categorical else (*batch_size, 5)
multicat = MultiCategorical if categorical else MultiOneHot
multicat_shape = 2 if categorical else 5
spec = self._make_spec(batch_size, cat, cat_shape, multicat, multicat_shape)
recon = _gym_to_torchrl_spec_transform(
_torchrl_to_gym_spec_transform(
spec, categorical_action_encoding=categorical
),
categorical_action_encoding=categorical,
batch_size=batch_size,
)
for (key0, spec0), (key1, spec1) in zip(
spec.items(True, True), recon.items(True, True)
):
assert spec0 == spec1, (key0, key1, spec0, spec1)
assert spec == recon
assert recon.shape == spec.shape
@pytest.mark.parametrize("order", ["tuple_seq"])
@implement_for("gym")
def test_gym_spec_cast_tuple_sequential(self, order):
torchrl_logger.info("Sequence not available in gym")
return
# @pytest.mark.parametrize("order", ["seq_tuple", "tuple_seq"])
@pytest.mark.parametrize("order", ["tuple_seq"])
@implement_for("gymnasium")
def test_gym_spec_cast_tuple_sequential(self, order): # noqa: F811
with set_gym_backend("gymnasium"):
if order == "seq_tuple":
# Requires nested tensors to be created along dim=1, disabling
space = gym_backend("spaces").Dict(
feature=gym_backend("spaces").Sequence(
gym_backend("spaces").Tuple(
(
gym_backend("spaces").Box(-1, 1, shape=(2, 2)),
gym_backend("spaces").Box(-1, 1, shape=(1, 2)),
)
),
stack=True,
)
)
elif order == "tuple_seq":
space = gym_backend("spaces").Dict(
feature=gym_backend("spaces").Tuple(
(
gym_backend("spaces").Sequence(
gym_backend("spaces").Box(-1, 1, shape=(2, 2)),
stack=True,
),
gym_backend("spaces").Sequence(
gym_backend("spaces").Box(-1, 1, shape=(1, 2)),
stack=True,
),
),
)
)
else:
raise NotImplementedError
sample = space.sample()
partial_tree_map = functools.partial(
tree_map, is_leaf=lambda x: isinstance(x, (tuple, torch.Tensor))
)
def stack_tuples(item):
if isinstance(item, tuple):
try:
return torch.stack(
[partial_tree_map(stack_tuples, x) for x in item]
)
except RuntimeError:
item = [partial_tree_map(stack_tuples, x) for x in item]
try:
return torch.nested.nested_tensor(item)
except RuntimeError:
return tuple(item)
return torch.as_tensor(item)
sample_pt = partial_tree_map(stack_tuples, sample)
# sample_pt = torch.utils._pytree.tree_map(lambda x: torch.stack(list(x)), sample_pt, is_leaf=lambda x: isinstance(x, tuple))
spec = _gym_to_torchrl_spec_transform(space)
rand = spec.rand()
assert spec.contains(rand), (rand, spec)
assert spec.contains(sample_pt), (rand, sample_pt)
space_recon = _torchrl_to_gym_spec_transform(spec)
assert space_recon == space, (space_recon, space)
rand_numpy = rand.numpy()
assert space.contains(rand_numpy)
_BACKENDS = [None]
if _has_gymnasium:
_BACKENDS += ["gymnasium"]
if _has_gym_regular:
_BACKENDS += ["gym"]
@pytest.mark.skipif(not _has_pytree, reason="pytree needed for torchrl_to_gym test")
@pytest.mark.parametrize("backend", _BACKENDS)
@pytest.mark.parametrize("numpy", [True, False])
def test_torchrl_to_gym(self, backend, numpy):
from torchrl.envs.libs.gym import gym_backend, set_gym_backend
gb = gym_backend()
try:
EnvBase.register_gym(
f"Dummy-{numpy}-{backend}-v0",
entry_point=self.DummyEnv,
to_numpy=numpy,
backend=backend,
arg1=1,
arg2=2,
)
with set_gym_backend(backend) if backend is not None else nullcontext():
envgym = gym_backend().make(f"Dummy-{numpy}-{backend}-v0")
envgym.reset()
obs, *_ = envgym.step(envgym.action_space.sample())
assert "observation" in obs
assert "other" in obs
if numpy:
assert all(
isinstance(val, np.ndarray) for val in tree_flatten(obs)[0]
)
else:
assert all(
isinstance(val, torch.Tensor) for val in tree_flatten(obs)[0]
)
# with a transform
transform = Compose(
CatTensors(["observation", ("other", "another_other")]),
RemoveEmptySpecs(),
)
envgym = gym_backend().make(
f"Dummy-{numpy}-{backend}-v0",
transform=transform,
)
envgym.reset()
obs, *_ = envgym.step(envgym.action_space.sample())
assert "observation_other" not in obs
assert "observation" not in obs
assert "other" not in obs
if numpy:
assert all(
isinstance(val, np.ndarray) for val in tree_flatten(obs)[0]
)
else:
assert all(
isinstance(val, torch.Tensor) for val in tree_flatten(obs)[0]
)
# register with transform
transform = Compose(
CatTensors(["observation", ("other", "another_other")]),
RemoveEmptySpecs(),
)
EnvBase.register_gym(
f"Dummy-{numpy}-{backend}-transform-v0",
entry_point=self.DummyEnv,
backend=backend,
to_numpy=numpy,
arg1=1,
arg2=2,
transform=transform,
)
with set_gym_backend(backend) if backend is not None else nullcontext():
envgym = gym_backend().make(f"Dummy-{numpy}-{backend}-transform-v0")
envgym.reset()
obs, *_ = envgym.step(envgym.action_space.sample())
assert "observation_other" not in obs
assert "observation" not in obs
assert "other" not in obs
if numpy:
assert all(
isinstance(val, np.ndarray) for val in tree_flatten(obs)[0]
)
else:
assert all(
isinstance(val, torch.Tensor) for val in tree_flatten(obs)[0]
)
# register with transform
EnvBase.register_gym(
f"Dummy-{numpy}-{backend}-noarg-v0",
entry_point=self.DummyEnv,
backend=backend,
to_numpy=numpy,
)
with set_gym_backend(backend) if backend is not None else nullcontext():
with pytest.raises(AssertionError):
envgym = gym_backend().make(
f"Dummy-{numpy}-{backend}-noarg-v0", arg1=None, arg2=None
)
envgym = gym_backend().make(
f"Dummy-{numpy}-{backend}-noarg-v0", arg1=1, arg2=2
)
# Get info dict
gym_info_at_reset = version.parse(
gym_backend().__version__
) >= version.parse("0.26.0")
with set_gym_backend(backend) if backend is not None else nullcontext():
envgym = gym_backend().make(
f"Dummy-{numpy}-{backend}-noarg-v0",
arg1=1,
arg2=2,
info_keys=("other",),
)
if gym_info_at_reset:
out, info = envgym.reset()
if numpy:
assert all(
isinstance(val, np.ndarray)
for val in tree_flatten((obs, info))[0]
)
else:
assert all(
isinstance(val, torch.Tensor)
for val in tree_flatten((obs, info))[0]
)
else:
out = envgym.reset()
info = {}
if numpy:
assert all(
isinstance(val, np.ndarray)
for val in tree_flatten((obs, info))[0]
)
else:
assert all(
isinstance(val, torch.Tensor)
for val in tree_flatten((obs, info))[0]
)
assert "observation" in out
assert "other" not in out
if gym_info_at_reset:
assert "other" in info
out, *_, info = envgym.step(envgym.action_space.sample())
assert "observation" in out
assert "other" not in out
assert "other" in info
if numpy:
assert all(
isinstance(val, np.ndarray)
for val in tree_flatten((obs, info))[0]
)
else:
assert all(
isinstance(val, torch.Tensor)
for val in tree_flatten((obs, info))[0]
)
EnvBase.register_gym(
f"Dummy-{numpy}-{backend}-info-v0",
entry_point=self.DummyEnv,
backend=backend,
to_numpy=numpy,
info_keys=("other",),
)
with set_gym_backend(backend) if backend is not None else nullcontext():
envgym = gym_backend().make(
f"Dummy-{numpy}-{backend}-info-v0", arg1=1, arg2=2
)
if gym_info_at_reset:
out, info = envgym.reset()
if numpy:
assert all(
isinstance(val, np.ndarray)
for val in tree_flatten((obs, info))[0]
)
else:
assert all(
isinstance(val, torch.Tensor)
for val in tree_flatten((obs, info))[0]
)
else:
out = envgym.reset()
info = {}
if numpy:
assert all(
isinstance(val, np.ndarray)
for val in tree_flatten((obs, info))[0]
)
else:
assert all(
isinstance(val, torch.Tensor)
for val in tree_flatten((obs, info))[0]
)
assert "observation" in out
assert "other" not in out
if gym_info_at_reset:
assert "other" in info
out, *_, info = envgym.step(envgym.action_space.sample())
assert "observation" in out
assert "other" not in out
assert "other" in info
if numpy:
assert all(
isinstance(val, np.ndarray)
for val in tree_flatten((obs, info))[0]
)
else:
assert all(
isinstance(val, torch.Tensor)
for val in tree_flatten((obs, info))[0]
)
finally:
set_gym_backend(gb).set()
@pytest.mark.parametrize(
"env_name",
[
HALFCHEETAH_VERSIONED(),
PONG_VERSIONED(),
# PENDULUM_VERSIONED,
],
)
@pytest.mark.parametrize("frame_skip", [1, 3])
@pytest.mark.parametrize(
"from_pixels,pixels_only",
[
[True, True],
[True, False],
[False, False],
],
)
def test_gym(self, env_name, frame_skip, from_pixels, pixels_only):
if env_name == PONG_VERSIONED() and not from_pixels:
# raise pytest.skip("already pixel")
# we don't skip because that would raise an exception
return
elif (
env_name != PONG_VERSIONED()
and from_pixels
and torch.cuda.device_count() < 1
):
raise pytest.skip("no cuda device")
def non_null_obs(batched_td):
if from_pixels:
pix_norm = batched_td.get("pixels").flatten(-3, -1).float().norm(dim=-1)
pix_norm_next = (
batched_td.get(("next", "pixels"))
.flatten(-3, -1)
.float()
.norm(dim=-1)
)
idx = (pix_norm > 1) & (pix_norm_next > 1)
# eliminate batch size: all idx must be True (otherwise one could be filled with 0s)
while idx.ndim > 1:
idx = idx.all(0)
idx = idx.nonzero().squeeze(-1)
assert idx.numel(), "Did not find pixels with norm > 1"
return idx
return slice(None)
tdreset = []
tdrollout = []
final_seed = []
for _ in range(2):
env0 = GymEnv(
env_name,
frame_skip=frame_skip,
from_pixels=from_pixels,
pixels_only=pixels_only,
)
torch.manual_seed(0)
np.random.seed(0)
final_seed.append(env0.set_seed(0))
tdreset.append(env0.reset())
rollout = env0.rollout(max_steps=50)
tdrollout.append(rollout)
assert env0.from_pixels is from_pixels
env0.close()
env_type = type(env0._env)
assert_allclose_td(*tdreset, rtol=RTOL, atol=ATOL)
tdrollout = torch.stack(tdrollout, 0)
# custom filtering of non-null obs: mujoco rendering sometimes fails
# and renders black images. To counter this in the tests, we select
# tensordicts with all non-null observations
idx = non_null_obs(tdrollout)
assert_allclose_td(
tdrollout[0][..., idx], tdrollout[1][..., idx], rtol=RTOL, atol=ATOL
)
final_seed0, final_seed1 = final_seed
assert final_seed0 == final_seed1
if env_name == PONG_VERSIONED():
base_env = gym_backend().make(env_name, frameskip=frame_skip)
frame_skip = 1
else:
base_env = _make_gym_environment(env_name)
if from_pixels and not _is_from_pixels(base_env):
PixelObservationWrapper = get_gym_pixel_wrapper()
base_env = PixelObservationWrapper(base_env, pixels_only=pixels_only)
assert type(base_env) is env_type
# Compare GymEnv output with GymWrapper output
env1 = GymWrapper(base_env, frame_skip=frame_skip)
assert env0.get_library_name(env0._env) == env1.get_library_name(env1._env)
# check that we didn't do more wrapping
assert type(env0._env) == type(env1._env) # noqa: E721
assert env0.output_spec == env1.output_spec
assert env0.input_spec == env1.input_spec
del env0
torch.manual_seed(0)
np.random.seed(0)
final_seed2 = env1.set_seed(0)
tdreset2 = env1.reset()
rollout2 = env1.rollout(max_steps=50)
assert env1.from_pixels is from_pixels
env1.close()
del env1, base_env
assert_allclose_td(tdreset[0], tdreset2, rtol=RTOL, atol=ATOL)
assert final_seed0 == final_seed2
# same magic trick for mujoco as above
tdrollout = torch.stack([tdrollout[0], rollout2], 0)
idx = non_null_obs(tdrollout)
assert_allclose_td(
tdrollout[0][..., idx], tdrollout[1][..., idx], rtol=RTOL, atol=ATOL
)
@pytest.mark.parametrize(
"env_name",
[
PONG_VERSIONED(),
# PENDULUM_VERSIONED,
HALFCHEETAH_VERSIONED(),
],
)
@pytest.mark.parametrize("frame_skip", [1, 3])
@pytest.mark.parametrize(
"from_pixels,pixels_only",
[
[False, False],
[True, True],
[True, False],
],
)
def test_gym_fake_td(self, env_name, frame_skip, from_pixels, pixels_only):
if env_name == PONG_VERSIONED() and not from_pixels:
# raise pytest.skip("already pixel")
return
elif (
env_name != PONG_VERSIONED()
and from_pixels
and (not torch.has_cuda or not torch.cuda.device_count())
):
raise pytest.skip("no cuda device")
env = GymEnv(
env_name,
frame_skip=frame_skip,
from_pixels=from_pixels,
pixels_only=pixels_only,
)
check_env_specs(env)
@pytest.mark.parametrize("frame_skip", [1, 3])
@pytest.mark.parametrize(
"from_pixels,pixels_only",
[
[False, False],
[True, True],
[True, False],
],
)
@pytest.mark.parametrize("wrapper", [True, False])
def test_mo(self, frame_skip, from_pixels, pixels_only, wrapper):
if importlib.util.find_spec("gymnasium") is not None and not _has_mo:
raise pytest.skip("mo-gym not found")
else:
# avoid skipping, which we consider as errors in the gym CI
return
def make_env():
import mo_gymnasium
if wrapper:
return MOGymWrapper(
mo_gymnasium.make("minecart-v0"),
frame_skip=frame_skip,
from_pixels=from_pixels,
pixels_only=pixels_only,
)
else:
return MOGymEnv(
"minecart-v0",
frame_skip=frame_skip,
from_pixels=from_pixels,
pixels_only=pixels_only,
)
env = make_env()
check_env_specs(env)
env = SerialEnv(2, make_env)
check_env_specs(env)
def test_info_reader_mario(self):
try:
import gym_super_mario_bros as mario_gym
except ImportError as err:
try:
gym = gym_backend()
# with 0.26 we must have installed gym_super_mario_bros
# Since we capture the skips as errors, we raise a skip in this case
# Otherwise, we just return
gym_version = version.parse(gym.__version__)
if version.parse(
"0.26.0"
) <= gym_version and gym_version < version.parse("0.27"):
raise pytest.skip(f"no super mario bros: error=\n{err}")
except ImportError:
pass
return
gb = gym_backend()
try:
with set_gym_backend("gym"):
env = mario_gym.make("SuperMarioBros-v0")
env = GymWrapper(env)
check_env_specs(env)
def info_reader(info, tensordict):
assert isinstance(info, dict) # failed before bugfix
env.info_dict_reader = info_reader
check_env_specs(env)
finally:
set_gym_backend(gb).set()
@implement_for("gymnasium")
def test_one_hot_and_categorical(self):
# tests that one-hot and categorical work ok when an integer is expected as action
cliff_walking = GymEnv("CliffWalking-v0", categorical_action_encoding=True)
cliff_walking.rollout(10)
check_env_specs(cliff_walking)
cliff_walking = GymEnv("CliffWalking-v0", categorical_action_encoding=False)
cliff_walking.rollout(10)
check_env_specs(cliff_walking)
@implement_for("gym")
def test_one_hot_and_categorical(self): # noqa: F811
# we do not skip (bc we may want to make sure nothing is skipped)
# but CliffWalking-v0 in earlier Gym versions uses np.bool, which
# was deprecated after np 1.20, and we don't want to install multiple np
# versions.
return
@implement_for("gymnasium")
@pytest.mark.parametrize(
"envname",
["HalfCheetah-v4", "CartPole-v1", "ALE/Pong-v5"]
+ (["FetchReach-v2"] if _has_gym_robotics else []),
)
@pytest.mark.flaky(reruns=5, reruns_delay=1)
def test_vecenvs_wrapper(self, envname):
import gymnasium
# we can't use parametrize with implement_for
env = GymWrapper(
gymnasium.vector.SyncVectorEnv(
2 * [lambda envname=envname: gymnasium.make(envname)]
)
)
assert env.batch_size == torch.Size([2])
check_env_specs(env)
env = GymWrapper(
gymnasium.vector.AsyncVectorEnv(
2 * [lambda envname=envname: gymnasium.make(envname)]
)
)
assert env.batch_size == torch.Size([2])
check_env_specs(env)
@implement_for("gymnasium")
# this env has Dict-based observation which is a nice thing to test
@pytest.mark.parametrize(
"envname",
["HalfCheetah-v4", "CartPole-v1", "ALE/Pong-v5"]
+ (["FetchReach-v2"] if _has_gym_robotics else []),
)
@pytest.mark.flaky(reruns=5, reruns_delay=1)
def test_vecenvs_env(self, envname):
gb = gym_backend()
try:
with set_gym_backend("gymnasium"):
env = GymEnv(envname, num_envs=2, from_pixels=False)
env.set_seed(0)
assert env.get_library_name(env._env) == "gymnasium"
# rollouts can be executed without decorator
check_env_specs(env)
rollout = env.rollout(100, break_when_any_done=False)
for obs_key in env.observation_spec.keys(True, True):
rollout_consistency_assertion(
rollout,
done_key="done",
observation_key=obs_key,
done_strict="CartPole" in envname,
)
env.close()
del env
finally:
set_gym_backend(gb).set()
@implement_for("gym", "0.18")
@pytest.mark.parametrize(
"envname",
["CartPole-v1", "HalfCheetah-v4"],
)
@pytest.mark.flaky(reruns=5, reruns_delay=1)
def test_vecenvs_wrapper(self, envname): # noqa: F811
gym = gym_backend()
# we can't use parametrize with implement_for
for envname in ["CartPole-v1", "HalfCheetah-v4"]:
env = GymWrapper(
gym.vector.SyncVectorEnv(
2 * [lambda envname=envname: gym.make(envname)]
)
)
assert env.batch_size == torch.Size([2])
check_env_specs(env)
env = GymWrapper(
gym.vector.AsyncVectorEnv(
2 * [lambda envname=envname: gym.make(envname)]
)
)
assert env.batch_size == torch.Size([2])
check_env_specs(env)
env.close()
del env
@implement_for("gym", "0.18")
@pytest.mark.parametrize(
"envname",
["cp", "hc"],
)
@pytest.mark.flaky(reruns=5, reruns_delay=1)
def test_vecenvs_env(self, envname): # noqa: F811
gb = gym_backend()
try:
with set_gym_backend("gym"):
if envname == "hc":
envname = HALFCHEETAH_VERSIONED()
else:
envname = CARTPOLE_VERSIONED()
env = GymEnv(envname, num_envs=2, from_pixels=False)
env.set_seed(0)
assert env.get_library_name(env._env) == "gym"
# rollouts can be executed without decorator
check_env_specs(env)
rollout = env.rollout(100, break_when_any_done=False)
for obs_key in env.observation_spec.keys(True, True):
rollout_consistency_assertion(
rollout,
done_key="done",
observation_key=obs_key,
done_strict="CartPole" in envname,
)
env.close()
del env
if envname != "CartPole-v1":
with set_gym_backend("gym"):
env = GymEnv(envname, num_envs=2, from_pixels=True)
env.set_seed(0)
# rollouts can be executed without decorator
check_env_specs(env)
env.close()
del env
finally:
set_gym_backend(gb).set()
@implement_for("gym", None, "0.18")
@pytest.mark.parametrize(
"envname",
["CartPole-v1", "HalfCheetah-v4"],
)
def test_vecenvs_wrapper(self, envname): # noqa: F811
# skipping tests for older versions of gym
...
@implement_for("gym", None, "0.18")
@pytest.mark.parametrize(
"envname",
["CartPole-v1", "HalfCheetah-v4"],
)
def test_vecenvs_env(self, envname): # noqa: F811
# skipping tests for older versions of gym
...