forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_helpers.py
1072 lines (953 loc) · 36.4 KB
/
test_helpers.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 argparse
import dataclasses
from time import sleep
import pytest
import torch
from _utils_internal import generate_seeds, get_available_devices
from torchrl._utils import timeit
try:
from hydra import compose, initialize
from hydra.core.config_store import ConfigStore
_has_hydra = True
except ImportError:
_has_hydra = False
from mocking_classes import (
ContinuousActionConvMockEnvNumpy,
ContinuousActionVecMockEnv,
DiscreteActionConvMockEnvNumpy,
DiscreteActionVecMockEnv,
MockSerialEnv,
)
from packaging import version
from torchrl.data import CompositeSpec, NdBoundedTensorSpec
from torchrl.envs.libs.gym import _has_gym
from torchrl.envs.transforms import ObservationNorm
from torchrl.envs.transforms.transforms import (
_has_tv,
FlattenObservation,
TransformedEnv,
)
from torchrl.envs.utils import set_exploration_mode
from torchrl.modules.tensordict_module.common import _has_functorch
from torchrl.trainers.helpers import transformed_env_constructor
from torchrl.trainers.helpers.envs import (
EnvConfig,
initialize_observation_norm_transforms,
retrieve_observation_norms_state_dict,
)
from torchrl.trainers.helpers.losses import A2CLossConfig, make_a2c_loss
from torchrl.trainers.helpers.models import (
A2CModelConfig,
DDPGModelConfig,
DiscreteModelConfig,
DreamerConfig,
make_a2c_model,
make_ddpg_actor,
make_dqn_actor,
make_dreamer,
make_ppo_model,
make_redq_model,
make_sac_model,
PPOModelConfig,
REDQModelConfig,
SACModelConfig,
)
TORCH_VERSION = version.parse(torch.__version__)
if TORCH_VERSION < version.parse("1.12.0"):
UNSQUEEZE_SINGLETON = True
else:
UNSQUEEZE_SINGLETON = False
## these tests aren't truly unitary but setting up a fake env for the
# purpose of building a model with args is a lot of unstable scaffoldings
# with unclear benefits
@pytest.fixture
def dreamer_constructor_fixture():
import os
# we hack the env constructor
import sys
sys.path.append(os.path.dirname(__file__) + "/../examples/dreamer/")
from dreamer_utils import transformed_env_constructor
yield transformed_env_constructor
sys.path.pop()
def _assert_keys_match(td, expeceted_keys):
td_keys = list(td.keys())
d = set(td_keys) - set(expeceted_keys)
assert len(d) == 0, f"{d} is in tensordict but unexpected: {td.keys()}"
d = set(expeceted_keys) - set(td_keys)
assert len(d) == 0, f"{d} is expected but not in tensordict: {td.keys()}"
assert len(td_keys) == len(expeceted_keys)
@pytest.mark.skipif(not _has_gym, reason="No gym library found")
@pytest.mark.skipif(not _has_tv, reason="No torchvision library found")
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("noisy", [(), ("noisy=True",)])
@pytest.mark.parametrize("distributional", [(), ("distributional=True",)])
@pytest.mark.parametrize("from_pixels", [(), ("from_pixels=True", "catframes=4")])
@pytest.mark.parametrize(
"categorical_action_encoding",
[("categorical_action_encoding=True",), ("categorical_action_encoding=False",)],
)
def test_dqn_maker(
device, noisy, distributional, from_pixels, categorical_action_encoding
):
flags = list(noisy + distributional + from_pixels + categorical_action_encoding) + [
"env_name=CartPole-v1"
]
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
DiscreteModelConfig,
)
for config_field in dataclasses.fields(config_cls)
]
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
env_maker = (
DiscreteActionConvMockEnvNumpy if from_pixels else DiscreteActionVecMockEnv
)
env_maker = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
stats={"loc": 0.0, "scale": 1.0},
)
proof_environment = env_maker(
categorical_action_encoding=cfg.categorical_action_encoding,
)
actor = make_dqn_actor(proof_environment, cfg, device)
td = proof_environment.reset().to(device)
if UNSQUEEZE_SINGLETON and not td.ndimension():
# Linear and conv used to break for non-batched data
actor(td.unsqueeze(0))
else:
actor(td)
expected_keys = ["done", "action", "action_value"]
if from_pixels:
expected_keys += ["pixels", "pixels_orig"]
else:
expected_keys += ["observation_orig", "observation_vector"]
if not distributional:
expected_keys += ["chosen_action_value"]
try:
_assert_keys_match(td, expected_keys)
except AssertionError:
proof_environment.close()
raise
proof_environment.close()
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.skipif(not _has_gym, reason="No gym library found")
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("from_pixels", [("from_pixels=True", "catframes=4"), ()])
@pytest.mark.parametrize("gsde", [(), ("gSDE=True",)])
@pytest.mark.parametrize("exploration", ["random", "mode"])
def test_ddpg_maker(device, from_pixels, gsde, exploration):
if not gsde and exploration != "random":
pytest.skip("no need to test this setting")
device = torch.device("cpu")
flags = list(from_pixels + gsde)
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
DDPGModelConfig,
)
for config_field in dataclasses.fields(config_cls)
]
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
env_maker = (
ContinuousActionConvMockEnvNumpy
if from_pixels
else ContinuousActionVecMockEnv
)
env_maker = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
stats={"loc": 0.0, "scale": 1.0},
)
proof_environment = env_maker()
actor, value = make_ddpg_actor(proof_environment, device=device, cfg=cfg)
td = proof_environment.reset().to(device)
with set_exploration_mode(exploration):
if UNSQUEEZE_SINGLETON and not td.ndimension():
# Linear and conv used to break for non-batched data
actor(td.unsqueeze(0))
else:
actor(td)
expected_keys = ["done", "action", "param"]
if from_pixels:
expected_keys += ["pixels", "hidden", "pixels_orig"]
else:
expected_keys += ["observation_vector", "observation_orig"]
if cfg.gSDE:
expected_keys += ["scale", "loc", "_eps_gSDE"]
try:
_assert_keys_match(td, expected_keys)
except AssertionError:
proof_environment.close()
raise
if cfg.gSDE:
tsf_loc = actor.module[0].module[-1].module.transform(td.get("loc"))
if exploration == "random":
with pytest.raises(AssertionError):
torch.testing.assert_close(td.get("action"), tsf_loc)
else:
torch.testing.assert_close(td.get("action"), tsf_loc)
if UNSQUEEZE_SINGLETON and not td.ndimension():
# Linear and conv used to break for non-batched data
value(td.unsqueeze(0))
else:
value(td)
expected_keys += ["state_action_value"]
try:
_assert_keys_match(td, expected_keys)
except AssertionError:
proof_environment.close()
raise
proof_environment.close()
del proof_environment
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.skipif(not _has_gym, reason="No gym library found")
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("from_pixels", [(), ("from_pixels=True", "catframes=4")])
@pytest.mark.parametrize("gsde", [(), ("gSDE=True",)])
@pytest.mark.parametrize("shared_mapping", [(), ("shared_mapping=True",)])
@pytest.mark.parametrize("exploration", ["random", "mode"])
@pytest.mark.parametrize("action_space", ["discrete", "continuous"])
def test_ppo_maker(
device, from_pixels, shared_mapping, gsde, exploration, action_space
):
if not gsde and exploration != "random":
pytest.skip("no need to test this setting")
flags = list(from_pixels + shared_mapping + gsde)
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
PPOModelConfig,
)
for config_field in dataclasses.fields(config_cls)
]
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
# if gsde and from_pixels:
# pytest.skip("gsde and from_pixels are incompatible")
if from_pixels:
if action_space == "continuous":
env_maker = ContinuousActionConvMockEnvNumpy
else:
env_maker = DiscreteActionConvMockEnvNumpy
else:
if action_space == "continuous":
env_maker = ContinuousActionVecMockEnv
else:
env_maker = DiscreteActionVecMockEnv
env_maker = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
stats={"loc": 0.0, "scale": 1.0},
)
proof_environment = env_maker()
if cfg.from_pixels and not cfg.shared_mapping:
with pytest.raises(
RuntimeError,
match="PPO learnt from pixels require the shared_mapping to be set to True",
):
actor_value = make_ppo_model(
proof_environment,
device=device,
cfg=cfg,
)
return
if action_space == "discrete" and cfg.gSDE:
with pytest.raises(
RuntimeError,
match="cannot use gSDE with discrete actions",
):
actor_value = make_a2c_model(
proof_environment,
device=device,
cfg=cfg,
)
return
actor_value = make_ppo_model(
proof_environment,
device=device,
cfg=cfg,
)
actor = actor_value.get_policy_operator()
expected_keys = [
"done",
"pixels" if len(from_pixels) else "observation_vector",
"pixels_orig" if len(from_pixels) else "observation_orig",
"action",
"sample_log_prob",
]
if action_space == "continuous":
expected_keys += ["loc", "scale"]
else:
expected_keys += ["logits"]
if shared_mapping:
expected_keys += ["hidden"]
if len(gsde):
expected_keys += ["_eps_gSDE"]
td = proof_environment.reset().to(device)
td_clone = td.clone()
with set_exploration_mode(exploration):
if UNSQUEEZE_SINGLETON and not td_clone.ndimension():
# Linear and conv used to break for non-batched data
actor(td_clone.unsqueeze(0))
else:
actor(td_clone)
try:
_assert_keys_match(td_clone, expected_keys)
except AssertionError:
proof_environment.close()
raise
if cfg.gSDE:
if cfg.shared_mapping:
tsf_loc = actor[-2].module[-1].module.transform(td_clone.get("loc"))
else:
tsf_loc = (
actor.module[0].module[-1].module.transform(td_clone.get("loc"))
)
if exploration == "random":
with pytest.raises(AssertionError):
torch.testing.assert_close(td_clone.get("action"), tsf_loc)
else:
torch.testing.assert_close(td_clone.get("action"), tsf_loc)
value = actor_value.get_value_operator()
expected_keys = [
"done",
"pixels" if len(from_pixels) else "observation_vector",
"pixels_orig" if len(from_pixels) else "observation_orig",
"state_value",
]
if shared_mapping:
expected_keys += ["hidden"]
if len(gsde):
expected_keys += ["_eps_gSDE"]
td_clone = td.clone()
if UNSQUEEZE_SINGLETON and not td_clone.ndimension():
# Linear and conv used to break for non-batched data
value(td_clone.unsqueeze(0))
else:
value(td_clone)
try:
_assert_keys_match(td_clone, expected_keys)
except AssertionError:
proof_environment.close()
raise
proof_environment.close()
del proof_environment
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.skipif(not _has_gym, reason="No gym library found")
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("from_pixels", [(), ("from_pixels=True", "catframes=4")])
@pytest.mark.parametrize("gsde", [(), ("gSDE=True",)])
@pytest.mark.parametrize("shared_mapping", [(), ("shared_mapping=True",)])
@pytest.mark.parametrize("exploration", ["random", "mode"])
@pytest.mark.parametrize("action_space", ["discrete", "continuous"])
def test_a2c_maker(
device, from_pixels, shared_mapping, gsde, exploration, action_space
):
if not gsde and exploration != "random":
pytest.skip("no need to test this setting")
flags = list(from_pixels + shared_mapping + gsde)
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
A2CLossConfig,
A2CModelConfig,
)
for config_field in dataclasses.fields(config_cls)
]
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
# if gsde and from_pixels:
# pytest.skip("gsde and from_pixels are incompatible")
if from_pixels:
if action_space == "continuous":
env_maker = ContinuousActionConvMockEnvNumpy
else:
env_maker = DiscreteActionConvMockEnvNumpy
else:
if action_space == "continuous":
env_maker = ContinuousActionVecMockEnv
else:
env_maker = DiscreteActionVecMockEnv
env_maker = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
stats={"loc": 0.0, "scale": 1.0},
)
proof_environment = env_maker()
if cfg.from_pixels and not cfg.shared_mapping:
with pytest.raises(
RuntimeError,
match="A2C learnt from pixels require the shared_mapping to be set to True",
):
actor_value = make_a2c_model(
proof_environment,
device=device,
cfg=cfg,
)
return
if action_space == "discrete" and cfg.gSDE:
with pytest.raises(
RuntimeError,
match="cannot use gSDE with discrete actions",
):
actor_value = make_a2c_model(
proof_environment,
device=device,
cfg=cfg,
)
return
actor_value = make_a2c_model(
proof_environment,
device=device,
cfg=cfg,
)
actor = actor_value.get_policy_operator()
expected_keys = [
"done",
"pixels" if len(from_pixels) else "observation_vector",
"pixels_orig" if len(from_pixels) else "observation_orig",
"action",
"sample_log_prob",
]
if action_space == "continuous":
expected_keys += ["loc", "scale"]
else:
expected_keys += ["logits"]
if shared_mapping:
expected_keys += ["hidden"]
if len(gsde):
expected_keys += ["_eps_gSDE"]
td = proof_environment.reset().to(device)
td_clone = td.clone()
with set_exploration_mode(exploration):
if UNSQUEEZE_SINGLETON and not td_clone.ndimension():
# Linear and conv used to break for non-batched data
actor(td_clone.unsqueeze(0))
else:
actor(td_clone)
try:
_assert_keys_match(td_clone, expected_keys)
except AssertionError:
proof_environment.close()
raise
if cfg.gSDE:
if cfg.shared_mapping:
tsf_loc = actor[-2].module[-1].module.transform(td_clone.get("loc"))
else:
tsf_loc = (
actor.module[0].module[-1].module.transform(td_clone.get("loc"))
)
if exploration == "random":
with pytest.raises(AssertionError):
torch.testing.assert_close(td_clone.get("action"), tsf_loc)
else:
torch.testing.assert_close(td_clone.get("action"), tsf_loc)
value = actor_value.get_value_operator()
expected_keys = [
"done",
"pixels" if len(from_pixels) else "observation_vector",
"pixels_orig" if len(from_pixels) else "observation_orig",
"state_value",
]
if shared_mapping:
expected_keys += ["hidden"]
if len(gsde):
expected_keys += ["_eps_gSDE"]
td_clone = td.clone()
if UNSQUEEZE_SINGLETON and not td_clone.ndimension():
# Linear and conv used to break for non-batched data
value(td_clone.unsqueeze(0))
else:
value(td_clone)
try:
_assert_keys_match(td_clone, expected_keys)
except AssertionError:
proof_environment.close()
raise
proof_environment.close()
del proof_environment
loss_fn = make_a2c_loss(actor_value, cfg)
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.skipif(not _has_gym, reason="No gym library found")
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("gsde", [(), ("gSDE=True",)])
@pytest.mark.parametrize("from_pixels", [()])
@pytest.mark.parametrize("tanh_loc", [(), ("tanh_loc=True",)])
@pytest.mark.parametrize("exploration", ["random", "mode"])
def test_sac_make(device, gsde, tanh_loc, from_pixels, exploration):
if not gsde and exploration != "random":
pytest.skip("no need to test this setting")
flags = list(gsde + tanh_loc + from_pixels)
if gsde and from_pixels:
pytest.skip("gsde and from_pixels are incompatible")
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
SACModelConfig,
)
for config_field in dataclasses.fields(config_cls)
]
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
if from_pixels:
cfg.catframes = 4
env_maker = (
ContinuousActionConvMockEnvNumpy
if from_pixels
else ContinuousActionVecMockEnv
)
env_maker = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
stats={"loc": 0.0, "scale": 1.0},
)
proof_environment = env_maker()
model = make_sac_model(
proof_environment,
device=device,
cfg=cfg,
)
actor, qvalue, value = model
td = proof_environment.reset().to(device)
td_clone = td.clone()
with set_exploration_mode(exploration):
if UNSQUEEZE_SINGLETON and not td_clone.ndimension():
# Linear and conv used to break for non-batched data
actor(td_clone.unsqueeze(0))
else:
actor(td_clone)
expected_keys = [
"done",
"pixels" if len(from_pixels) else "observation_vector",
"pixels_orig" if len(from_pixels) else "observation_orig",
"action",
"loc",
"scale",
]
if len(gsde):
expected_keys += ["_eps_gSDE"]
if cfg.gSDE:
tsf_loc = actor.module[0].module[-1].module.transform(td_clone.get("loc"))
if exploration == "random":
with pytest.raises(AssertionError):
torch.testing.assert_close(td_clone.get("action"), tsf_loc)
else:
torch.testing.assert_close(td_clone.get("action"), tsf_loc)
try:
_assert_keys_match(td_clone, expected_keys)
except AssertionError:
proof_environment.close()
raise
if UNSQUEEZE_SINGLETON and not td_clone.ndimension():
# Linear and conv used to break for non-batched data
qvalue(td_clone.unsqueeze(0))
else:
qvalue(td_clone)
expected_keys = [
"done",
"observation_vector",
"observation_orig",
"action",
"state_action_value",
"loc",
"scale",
]
if len(gsde):
expected_keys += ["_eps_gSDE"]
try:
_assert_keys_match(td_clone, expected_keys)
except AssertionError:
proof_environment.close()
raise
if UNSQUEEZE_SINGLETON and not td.ndimension():
# Linear and conv used to break for non-batched data
value(td.unsqueeze(0))
else:
value(td)
expected_keys = [
"done",
"observation_vector",
"observation_orig",
"state_value",
]
if len(gsde):
expected_keys += ["_eps_gSDE"]
try:
_assert_keys_match(td, expected_keys)
except AssertionError:
proof_environment.close()
raise
proof_environment.close()
del proof_environment
@pytest.mark.skipif(not _has_functorch, reason="functorch not installed")
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.skipif(not _has_gym, reason="No gym library found")
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("from_pixels", [(), ("from_pixels=True", "catframes=4")])
@pytest.mark.parametrize("gsde", [(), ("gSDE=True",)])
@pytest.mark.parametrize("exploration", ["random", "mode"])
def test_redq_make(device, from_pixels, gsde, exploration):
if not gsde and exploration != "random":
pytest.skip("no need to test this setting")
flags = list(from_pixels + gsde)
if gsde and from_pixels:
pytest.skip("gsde and from_pixels are incompatible")
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
REDQModelConfig,
)
for config_field in dataclasses.fields(config_cls)
]
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
env_maker = (
ContinuousActionConvMockEnvNumpy
if from_pixels
else ContinuousActionVecMockEnv
)
env_maker = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
stats={"loc": 0.0, "scale": 1.0},
)
proof_environment = env_maker()
model = make_redq_model(
proof_environment,
device=device,
cfg=cfg,
)
actor, qvalue = model
td = proof_environment.reset().to(device)
with set_exploration_mode(exploration):
actor(td)
expected_keys = [
"done",
"action",
"sample_log_prob",
"loc",
"scale",
]
if len(gsde):
expected_keys += ["_eps_gSDE"]
if from_pixels:
expected_keys += ["hidden", "pixels", "pixels_orig"]
else:
expected_keys += ["observation_vector", "observation_orig"]
try:
_assert_keys_match(td, expected_keys)
except AssertionError:
proof_environment.close()
raise
if cfg.gSDE:
tsf_loc = actor.module[0].module[-1].module.transform(td.get("loc"))
if exploration == "random":
with pytest.raises(AssertionError):
torch.testing.assert_close(td.get("action"), tsf_loc)
else:
torch.testing.assert_close(td.get("action"), tsf_loc)
qvalue(td)
expected_keys = [
"done",
"action",
"sample_log_prob",
"state_action_value",
"loc",
"scale",
]
if len(gsde):
expected_keys += ["_eps_gSDE"]
if from_pixels:
expected_keys += ["hidden", "pixels", "pixels_orig"]
else:
expected_keys += ["observation_vector", "observation_orig"]
try:
_assert_keys_match(td, expected_keys)
except AssertionError:
proof_environment.close()
raise
proof_environment.close()
del proof_environment
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.skipif(not _has_gym, reason="No gym library found")
@pytest.mark.skipif(
version.parse(torch.__version__) < version.parse("1.11.0"),
reason="""Dreamer works with batches of null to 2 dimensions. Torch < 1.11
requires one-dimensional batches (for RNN and Conv nets for instance). If you'd like
to see torch < 1.11 supported for dreamer, please submit an issue.""",
)
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("tanh_loc", [(), ("tanh_loc=True",)])
@pytest.mark.parametrize("exploration", ["random", "mode"])
def test_dreamer_make(device, tanh_loc, exploration, dreamer_constructor_fixture):
transformed_env_constructor = dreamer_constructor_fixture
flags = ["from_pixels=True", "catframes=1"]
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
DreamerConfig,
)
for config_field in dataclasses.fields(config_cls)
]
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
env_maker = ContinuousActionConvMockEnvNumpy
env_maker = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
stats={"loc": 0.0, "scale": 1.0},
)
proof_environment = env_maker().to(device)
model = make_dreamer(
proof_environment=proof_environment,
device=device,
cfg=cfg,
)
world_model, model_based_env, actor_model, value_model, policy = model
out = world_model(proof_environment.rollout(3))
expected_keys = {
"action",
"belief",
"done",
("next", "belief"),
("next", "encoded_latents"),
("next", "pixels"),
("next", "pixels_orig"),
("next", "posterior_mean"),
("next", "posterior_std"),
("next", "prior_mean"),
("next", "prior_std"),
("next", "state"),
"pixels",
"pixels_orig",
"reward",
"state",
("next", "reco_pixels"),
"next",
}
assert set(out.keys(True)) == expected_keys
simulated_data = model_based_env.rollout(3)
expected_keys = {
"action",
"belief",
"done",
("next", "belief"),
("next", "state"),
("next", "pixels"),
("next", "pixels_orig"),
"pixels_orig",
"pixels",
"reward",
"state",
"next",
}
assert expected_keys == set(simulated_data.keys(True))
simulated_action = actor_model(model_based_env.reset())
real_action = actor_model(proof_environment.reset())
simulated_policy_action = policy(model_based_env.reset())
real_policy_action = policy(proof_environment.reset())
assert "action" in simulated_action.keys()
assert "action" in real_action.keys()
assert "action" in simulated_policy_action.keys()
assert "action" in real_policy_action.keys()
value_td = value_model(proof_environment.reset())
assert "state_value" in value_td.keys()
@pytest.mark.parametrize("initial_seed", range(5))
def test_seed_generator(initial_seed):
num_seeds = 100
# Check unique seed generation
if initial_seed == 0:
with pytest.raises(ValueError):
generate_seeds(initial_seed - 1, num_seeds)
return
else:
seeds0 = generate_seeds(initial_seed - 1, num_seeds)
seeds1 = generate_seeds(initial_seed, num_seeds)
assert len(seeds1) == num_seeds
assert len(seeds1) == len(set(seeds1))
assert len(set(seeds0).intersection(set(seeds1))) == 0
# Check deterministic seed generation
seeds0 = generate_seeds(initial_seed, num_seeds)
seeds1 = generate_seeds(initial_seed, num_seeds)
assert seeds0 == seeds1
def test_timeit():
n1 = 500
w1 = 1e-4
n2 = 200
w2 = 1e-4
w3 = 1e-4
# warmup
for _ in range(10):
sleep(w1)
for _ in range(n1):
with timeit("event1"):
sleep(w1)
sleep(w3)
for _ in range(n2):
with timeit("event2"):
sleep(w2)
val1 = timeit._REG["event1"]
val2 = timeit._REG["event2"]
assert abs(val1[0] - w1) < 1e-2
assert abs(val1[1] - n1 * w1) < 1
assert val1[2] == n1
assert abs(val2[0] - w2) < 1e-2
assert abs(val2[1] - n2 * w2) < 1
assert val2[2] == n2
@pytest.mark.skipif(not _has_hydra, reason="No hydra library found")
@pytest.mark.parametrize("from_pixels", [(), ("from_pixels=True", "catframes=4")])
def test_transformed_env_constructor_with_state_dict(from_pixels):
config_fields = [
(config_field.name, config_field.type, config_field)
for config_cls in (
EnvConfig,
DreamerConfig,
)
for config_field in dataclasses.fields(config_cls)
]
flags = list(from_pixels)
Config = dataclasses.make_dataclass(cls_name="Config", fields=config_fields)
cs = ConfigStore.instance()
cs.store(name="config", node=Config)
with initialize(version_base=None, config_path=None):
cfg = compose(config_name="config", overrides=flags)
env_maker = (
ContinuousActionConvMockEnvNumpy
if from_pixels
else ContinuousActionVecMockEnv
)
t_env = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
)()
idx, state_dict = retrieve_observation_norms_state_dict(t_env)[0]
obs_transform = transformed_env_constructor(
cfg,
use_env_creator=False,
custom_env_maker=env_maker,
obs_norm_state_dict=state_dict,
)().transform[idx]
torch.testing.assert_close(obs_transform.state_dict(), state_dict)
@pytest.mark.parametrize("device", get_available_devices())
@pytest.mark.parametrize("keys", [None, ["observation", "observation_orig"]])
@pytest.mark.parametrize("composed", [True, False])
@pytest.mark.parametrize("initialized", [True, False])
def test_initialize_stats_from_observation_norms(device, keys, composed, initialized):
obs_spec, stat_key = None, None
if keys:
obs_spec = CompositeSpec(
**{
key: NdBoundedTensorSpec(maximum=1, minimum=1, shape=torch.Size([1]))
for key in keys
}
)
stat_key = keys[0]
env = ContinuousActionVecMockEnv(
device=device,
observation_spec=obs_spec,
action_spec=NdBoundedTensorSpec(
minimum=1, maximum=2, shape=torch.Size((1,))