-
Notifications
You must be signed in to change notification settings - Fork 361
/
Copy pathtest_cost.py
16677 lines (15352 loc) · 596 KB
/
test_cost.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 argparse
import contextlib
import functools
import importlib.util
import itertools
import operator
import os
import sys
import warnings
from copy import deepcopy
from dataclasses import asdict, dataclass
import numpy as np
import pytest
import torch
from packaging import version, version as pack_version
from tensordict import assert_allclose_td, TensorDict, TensorDictBase
from tensordict._C import unravel_keys
from tensordict.nn import (
composite_lp_aggregate,
CompositeDistribution,
InteractionType,
NormalParamExtractor,
ProbabilisticTensorDictModule,
ProbabilisticTensorDictModule as ProbMod,
ProbabilisticTensorDictSequential,
ProbabilisticTensorDictSequential as ProbSeq,
set_composite_lp_aggregate,
TensorDictModule,
TensorDictModule as Mod,
TensorDictSequential,
TensorDictSequential as Seq,
WrapModule,
)
from tensordict.nn.distributions.composite import _add_suffix
from tensordict.nn.utils import Buffer
from tensordict.utils import unravel_key
from torch import autograd, nn
from torchrl._utils import _standardize
from torchrl.data import Bounded, Categorical, Composite, MultiOneHot, OneHot, Unbounded
from torchrl.data.postprocs.postprocs import MultiStep
from torchrl.envs import EnvBase
from torchrl.envs.model_based.dreamer import DreamerEnv
from torchrl.envs.transforms import TensorDictPrimer, TransformedEnv
from torchrl.envs.utils import exploration_type, ExplorationType, set_exploration_type
from torchrl.modules import (
DistributionalQValueActor,
OneHotCategorical,
QValueActor,
recurrent_mode,
SafeSequential,
WorldModelWrapper,
)
from torchrl.modules.distributions.continuous import TanhDelta, TanhNormal
from torchrl.modules.models import QMixer
from torchrl.modules.models.model_based import (
DreamerActor,
ObsDecoder,
ObsEncoder,
RSSMPosterior,
RSSMPrior,
RSSMRollout,
)
from torchrl.modules.models.models import MLP
from torchrl.modules.tensordict_module.actors import (
Actor,
ActorCriticOperator,
ActorValueOperator,
ProbabilisticActor,
QValueModule,
ValueOperator,
)
from torchrl.objectives import (
A2CLoss,
ClipPPOLoss,
CQLLoss,
CrossQLoss,
DDPGLoss,
DiscreteCQLLoss,
DiscreteIQLLoss,
DiscreteSACLoss,
DistributionalDQNLoss,
DQNLoss,
DreamerActorLoss,
DreamerModelLoss,
DreamerValueLoss,
DTLoss,
GAILLoss,
IQLLoss,
KLPENPPOLoss,
OnlineDTLoss,
PPOLoss,
QMixerLoss,
SACLoss,
TD3BCLoss,
TD3Loss,
)
from torchrl.objectives.common import add_random_module, LossModule
from torchrl.objectives.deprecated import DoubleREDQLoss_deprecated, REDQLoss_deprecated
from torchrl.objectives.redq import REDQLoss
from torchrl.objectives.reinforce import ReinforceLoss
from torchrl.objectives.utils import (
_vmap_func,
HardUpdate,
hold_out_net,
SoftUpdate,
ValueEstimators,
)
from torchrl.objectives.value.advantages import (
GAE,
TD1Estimator,
TDLambdaEstimator,
VTrace,
)
from torchrl.objectives.value.functional import (
_transpose_time,
generalized_advantage_estimate,
reward2go,
td0_advantage_estimate,
td1_advantage_estimate,
td_lambda_advantage_estimate,
vec_generalized_advantage_estimate,
vec_td1_advantage_estimate,
vec_td_lambda_advantage_estimate,
vtrace_advantage_estimate,
)
from torchrl.objectives.value.utils import (
_custom_conv1d,
_get_num_per_traj,
_get_num_per_traj_init,
_inv_pad_sequence,
_make_gammas_tensor,
_split_and_pad_sequence,
)
if os.getenv("PYTORCH_TEST_FBCODE"):
from pytorch.rl.test._utils_internal import ( # noqa
_call_value_nets,
dtype_fixture,
get_available_devices,
get_default_devices,
)
from pytorch.rl.test.mocking_classes import ContinuousActionConvMockEnv
else:
from _utils_internal import ( # noqa
_call_value_nets,
dtype_fixture,
get_available_devices,
get_default_devices,
)
from mocking_classes import ContinuousActionConvMockEnv
_has_functorch = True
try:
import functorch as ft # noqa
make_functional_with_buffers = ft.make_functional_with_buffers
FUNCTORCH_ERR = ""
except ImportError as err:
_has_functorch = False
FUNCTORCH_ERR = str(err)
_has_transformers = bool(importlib.util.find_spec("transformers"))
TORCH_VERSION = version.parse(version.parse(torch.__version__).base_version)
IS_WINDOWS = sys.platform == "win32"
# Capture all warnings
pytestmark = [
pytest.mark.filterwarnings("error"),
pytest.mark.filterwarnings(
"ignore:The current behavior of MLP when not providing `num_cells` is that the number"
),
pytest.mark.filterwarnings(
"ignore:dep_util is Deprecated. Use functions from setuptools instead"
),
pytest.mark.filterwarnings(
"ignore:The PyTorch API of nested tensors is in prototype"
),
]
class _check_td_steady:
def __init__(self, td):
self.td_clone = td.clone()
self.td = td
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
assert (
self.td.select(*self.td_clone.keys()) == self.td_clone
).all(), "Some keys have been modified in the tensordict!"
def get_devices():
devices = [torch.device("cpu")]
for i in range(torch.cuda.device_count()):
devices += [torch.device(f"cuda:{i}")]
return devices
class MARLEnv(EnvBase):
def __init__(self):
batch = self.batch = (3,)
super().__init__(batch_size=batch)
self.n_agents = n_agents = (4,)
self.obs_feat = obs_feat = (5,)
self.full_observation_spec = Composite(
agents=Composite(
observation=Unbounded(batch + n_agents + obs_feat),
shape=batch + n_agents,
),
shape=batch,
)
self.full_done_spec = Composite(
done=Unbounded(batch + (1,), dtype=torch.bool),
terminated=Unbounded(batch + (1,), dtype=torch.bool),
truncated=Unbounded(batch + (1,), dtype=torch.bool),
shape=batch,
)
self.act_feat_dirich = act_feat_dirich = (10, 2)
self.act_feat_categ = act_feat_categ = (7,)
self.full_action_spec = Composite(
agents=Composite(
dirich=Unbounded(batch + n_agents + act_feat_dirich),
categ=Unbounded(batch + n_agents + act_feat_categ),
shape=batch + n_agents,
),
shape=batch,
)
self.full_reward_spec = Composite(
agents=Composite(
reward=Unbounded(batch + n_agents + (1,)), shape=batch + n_agents
),
shape=batch,
)
@classmethod
def make_composite_dist(cls):
dist_cstr = functools.partial(
CompositeDistribution,
distribution_map={
(
"agents",
"dirich",
): lambda concentration: torch.distributions.Independent(
torch.distributions.Dirichlet(concentration), 1
),
("agents", "categ"): torch.distributions.Categorical,
},
)
return ProbabilisticTensorDictModule(
in_keys=["params"],
out_keys=[("agents", "dirich"), ("agents", "categ")],
distribution_class=dist_cstr,
return_log_prob=True,
)
def _step(
self,
tensordict: TensorDictBase,
) -> TensorDictBase:
...
def _reset(self, tensordic):
...
def _set_seed(self, seed: int | None) -> None:
...
class LossModuleTestBase:
@pytest.fixture(scope="class", autouse=True)
def _composite_log_prob(self):
setter = set_composite_lp_aggregate(False)
setter.set()
yield
setter.unset()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
assert hasattr(
cls, "test_reset_parameters_recursive"
), "Please add a test_reset_parameters_recursive test for this class"
def _flatten_in_keys(self, in_keys):
return [
in_key if isinstance(in_key, str) else "_".join(list(unravel_keys(in_key)))
for in_key in in_keys
]
def tensordict_keys_test(self, loss_fn, default_keys, td_est=None):
self.tensordict_keys_unknown_key_test(loss_fn)
self.tensordict_keys_default_values_test(loss_fn, default_keys)
self.tensordict_set_keys_test(loss_fn, default_keys)
def tensordict_keys_unknown_key_test(self, loss_fn):
"""Test that exception is raised if an unknown key is set via .set_keys()"""
test_fn = deepcopy(loss_fn)
with pytest.raises(ValueError):
test_fn.set_keys(unknown_key="test2")
def tensordict_keys_default_values_test(self, loss_fn, default_keys):
test_fn = deepcopy(loss_fn)
for key, value in default_keys.items():
assert getattr(test_fn.tensor_keys, key) == value
def tensordict_set_keys_test(self, loss_fn, default_keys):
"""Test setting of tensordict keys via .set_keys()"""
test_fn = deepcopy(loss_fn)
new_key = "test1"
for key, _ in default_keys.items():
test_fn.set_keys(**{key: new_key})
assert getattr(test_fn.tensor_keys, key) == new_key
test_fn = deepcopy(loss_fn)
test_fn.set_keys(**{key: new_key for key, _ in default_keys.items()})
for key, _ in default_keys.items():
assert getattr(test_fn.tensor_keys, key) == new_key
def set_advantage_keys_through_loss_test(
self, loss_fn, td_est, loss_advantage_key_mapping
):
key_mapping = loss_advantage_key_mapping
test_fn = deepcopy(loss_fn)
new_keys = {}
for loss_key, (_, new_key) in key_mapping.items():
new_keys[loss_key] = new_key
test_fn.set_keys(**new_keys)
test_fn.make_value_estimator(td_est)
for _, (advantage_key, new_key) in key_mapping.items():
assert (
getattr(test_fn.value_estimator.tensor_keys, advantage_key) == new_key
)
@classmethod
def reset_parameters_recursive_test(cls, loss_fn):
def get_params(loss_fn):
for key, item in loss_fn.__dict__.items():
if isinstance(item, nn.Module):
module_name = key
params_name = f"{module_name}_params"
target_name = f"target_{module_name}_params"
params = loss_fn._modules.get(params_name, None)
target = loss_fn._modules.get(target_name, None)
if params is not None:
yield params_name, params._param_td
else:
for subparam_name, subparam in loss_fn.named_parameters():
if module_name in subparam_name:
yield subparam_name, subparam
if target is not None:
yield target_name, target
old_params = {}
for param_name, param in get_params(loss_fn):
with torch.no_grad():
# Change the parameter to ensure that reset will change it again
param += 1000
old_params[param_name] = param.clone()
loss_fn.reset_parameters_recursive()
for param_name, param in get_params(loss_fn):
old_param = old_params[param_name]
assert (param != old_param).any()
@pytest.mark.parametrize("device", get_default_devices())
@pytest.mark.parametrize("vmap_randomness", (None, "different", "same", "error"))
@pytest.mark.parametrize("dropout", (0.0, 0.1))
def test_loss_vmap_random(device, vmap_randomness, dropout):
class VmapTestLoss(LossModule):
model: TensorDictModule
model_params: TensorDict
target_model_params: TensorDict
def __init__(self):
super().__init__()
layers = [nn.Linear(4, 4), nn.ReLU()]
if dropout > 0.0:
layers.append(nn.Dropout(dropout))
layers.append(nn.Linear(4, 4))
net = nn.Sequential(*layers).to(device)
model = TensorDictModule(net, in_keys=["obs"], out_keys=["action"])
self.convert_to_functional(model, "model", expand_dim=4)
self._make_vmap()
def _make_vmap(self):
self.vmap_model = _vmap_func(
self.model,
(None, 0),
randomness=(
"error" if vmap_randomness == "error" else self.vmap_randomness
),
)
def forward(self, td):
out = self.vmap_model(td, self.model_params)
return {"loss": out["action"].mean()}
loss_module = VmapTestLoss()
td = TensorDict({"obs": torch.randn(3, 4).to(device)}, [3])
# If user sets vmap randomness to a specific value
if vmap_randomness in ("different", "same") and dropout > 0.0:
loss_module.set_vmap_randomness(vmap_randomness)
# Fail case
elif vmap_randomness == "error" and dropout > 0.0:
with pytest.raises(
RuntimeError,
match="vmap: called random operation while in randomness error mode",
):
loss_module(td)["loss"]
return
loss_module(td)["loss"]
class TestDQN(LossModuleTestBase):
seed = 0
def _create_mock_actor(
self,
action_spec_type,
batch=2,
obs_dim=3,
action_dim=4,
device="cpu",
is_nn_module=False,
action_value_key=None,
):
# Actor
if action_spec_type == "one_hot":
action_spec = OneHot(action_dim)
elif action_spec_type == "categorical":
action_spec = Categorical(action_dim)
# elif action_spec_type == "nd_bounded":
# action_spec = BoundedTensorSpec(
# -torch.ones(action_dim), torch.ones(action_dim), (action_dim,)
# )
else:
raise ValueError(f"Wrong {action_spec_type}")
module = nn.Linear(obs_dim, action_dim)
if is_nn_module:
return module.to(device)
actor = QValueActor(
spec=Composite(
{
"action": action_spec,
(
"action_value" if action_value_key is None else action_value_key
): None,
"chosen_action_value": None,
},
shape=[],
),
action_space=action_spec_type,
module=module,
action_value_key=action_value_key,
).to(device)
return actor
def _create_mock_distributional_actor(
self,
action_spec_type,
batch=2,
obs_dim=3,
action_dim=4,
atoms=5,
vmin=1,
vmax=5,
is_nn_module=False,
action_value_key="action_value",
):
# Actor
var_nums = None
if action_spec_type == "mult_one_hot":
action_spec = MultiOneHot([action_dim // 2, action_dim // 2])
var_nums = action_spec.nvec
elif action_spec_type == "one_hot":
action_spec = OneHot(action_dim)
elif action_spec_type == "categorical":
action_spec = Categorical(action_dim)
else:
raise ValueError(f"Wrong {action_spec_type}")
support = torch.linspace(vmin, vmax, atoms, dtype=torch.float)
module = MLP(obs_dim, (atoms, action_dim))
# TODO: Fails tests with
# TypeError: __init__() missing 1 required keyword-only argument: 'support'
# DistributionalQValueActor initializer expects additional inputs.
# if is_nn_module:
# return module
actor = DistributionalQValueActor(
spec=Composite(
{
"action": action_spec,
action_value_key: None,
},
shape=[],
),
module=module,
support=support,
action_space=action_spec_type,
var_nums=var_nums,
action_value_key=action_value_key,
)
return actor
def _create_mock_data_dqn(
self,
action_spec_type,
batch=2,
obs_dim=3,
action_dim=4,
atoms=None,
device="cpu",
action_key="action",
action_value_key="action_value",
):
# create a tensordict
obs = torch.randn(batch, obs_dim)
next_obs = torch.randn(batch, obs_dim)
if atoms:
action_value = torch.randn(batch, atoms, action_dim).softmax(-2)
action = (
action_value[..., 0, :] == action_value[..., 0, :].max(-1, True)[0]
).to(torch.long)
else:
action_value = torch.randn(batch, action_dim)
action = (action_value == action_value.max(-1, True)[0]).to(torch.long)
if action_spec_type == "categorical":
action_value = torch.max(action_value, -1, keepdim=True)[0]
action = torch.argmax(action, -1, keepdim=False)
reward = torch.randn(batch, 1)
done = torch.zeros(batch, 1, dtype=torch.bool)
terminated = torch.zeros(batch, 1, dtype=torch.bool)
td = TensorDict(
batch_size=(batch,),
source={
"observation": obs,
"next": {
"observation": next_obs,
"done": done,
"terminated": terminated,
"reward": reward,
},
action_key: action,
action_value_key: action_value,
},
device=device,
)
return td
def _create_seq_mock_data_dqn(
self,
action_spec_type,
batch=2,
T=4,
obs_dim=3,
action_dim=4,
atoms=None,
device="cpu",
):
# create a tensordict
total_obs = torch.randn(batch, T + 1, obs_dim, device=device)
obs = total_obs[:, :T]
next_obs = total_obs[:, 1:]
if atoms:
action_value = torch.randn(
batch, T, atoms, action_dim, device=device
).softmax(-2)
action = (
action_value[..., 0, :] == action_value[..., 0, :].max(-1, True)[0]
).to(torch.long)
else:
action_value = torch.randn(batch, T, action_dim, device=device)
action = (action_value == action_value.max(-1, True)[0]).to(torch.long)
# action_value = action_value.unsqueeze(-1)
reward = torch.randn(batch, T, 1, device=device)
done = torch.zeros(batch, T, 1, dtype=torch.bool, device=device)
terminated = torch.zeros(batch, T, 1, dtype=torch.bool, device=device)
mask = ~torch.zeros(batch, T, dtype=torch.bool, device=device)
if action_spec_type == "categorical":
action_value = torch.max(action_value, -1, keepdim=True)[0]
action = torch.argmax(action, -1, keepdim=False)
action = action.masked_fill_(~mask, 0.0)
else:
action = action.masked_fill_(~mask.unsqueeze(-1), 0.0)
td = TensorDict(
batch_size=(batch, T),
source={
"observation": obs.masked_fill_(~mask.unsqueeze(-1), 0.0),
"next": {
"observation": next_obs.masked_fill_(~mask.unsqueeze(-1), 0.0),
"done": done,
"terminated": terminated,
"reward": reward.masked_fill_(~mask.unsqueeze(-1), 0.0),
},
"collector": {"mask": mask},
"action": action,
"action_value": action_value.masked_fill_(~mask.unsqueeze(-1), 0.0),
},
names=[None, "time"],
)
return td
def test_reset_parameters_recursive(self):
actor = self._create_mock_actor(action_spec_type="one_hot")
loss_fn = DQNLoss(actor)
self.reset_parameters_recursive_test(loss_fn)
@pytest.mark.parametrize(
"delay_value,double_dqn", ([False, False], [True, False], [True, True])
)
@pytest.mark.parametrize("device", get_default_devices())
@pytest.mark.parametrize("action_spec_type", ("one_hot", "categorical"))
@pytest.mark.parametrize("td_est", list(ValueEstimators) + [None])
def test_dqn(self, delay_value, double_dqn, device, action_spec_type, td_est):
torch.manual_seed(self.seed)
actor = self._create_mock_actor(
action_spec_type=action_spec_type, device=device
)
td = self._create_mock_data_dqn(
action_spec_type=action_spec_type, device=device
)
loss_fn = DQNLoss(
actor,
loss_function="l2",
delay_value=delay_value,
double_dqn=double_dqn,
)
if td_est in (ValueEstimators.GAE, ValueEstimators.VTrace):
with pytest.raises(NotImplementedError):
loss_fn.make_value_estimator(td_est)
return
if td_est is not None:
loss_fn.make_value_estimator(td_est)
with (
pytest.warns(UserWarning, match="No target network updater has been")
if delay_value
else contextlib.nullcontext()
), _check_td_steady(td):
loss = loss_fn(td)
if delay_value:
# remove warning
SoftUpdate(loss_fn, eps=0.5)
assert loss_fn.tensor_keys.priority in td.keys()
sum([item for name, item in loss.items() if name.startswith("loss")]).backward()
assert torch.nn.utils.clip_grad.clip_grad_norm_(actor.parameters(), 1.0) > 0.0
# Check param update effect on targets
target_value = loss_fn.target_value_network_params.clone()
for p in loss_fn.parameters():
if p.requires_grad:
p.data += torch.randn_like(p)
target_value2 = loss_fn.target_value_network_params.clone()
if loss_fn.delay_value:
assert_allclose_td(target_value, target_value2)
else:
assert not (target_value == target_value2).any()
# check that policy is updated after parameter update
parameters = [p.clone() for p in actor.parameters()]
for p in loss_fn.parameters():
p.data += torch.randn_like(p)
assert all((p1 != p2).all() for p1, p2 in zip(parameters, actor.parameters()))
@pytest.mark.parametrize("delay_value", (False, True))
@pytest.mark.parametrize("device", get_default_devices())
@pytest.mark.parametrize("action_spec_type", ("one_hot", "categorical"))
def test_dqn_state_dict(self, delay_value, device, action_spec_type):
torch.manual_seed(self.seed)
actor = self._create_mock_actor(
action_spec_type=action_spec_type, device=device
)
loss_fn = DQNLoss(actor, loss_function="l2", delay_value=delay_value)
sd = loss_fn.state_dict()
loss_fn2 = DQNLoss(actor, loss_function="l2", delay_value=delay_value)
loss_fn2.load_state_dict(sd)
@pytest.mark.parametrize("n", range(1, 4))
@pytest.mark.parametrize("delay_value", (False, True))
@pytest.mark.parametrize("device", get_default_devices())
@pytest.mark.parametrize("action_spec_type", ("one_hot", "categorical"))
def test_dqn_batcher(self, n, delay_value, device, action_spec_type, gamma=0.9):
torch.manual_seed(self.seed)
actor = self._create_mock_actor(
action_spec_type=action_spec_type, device=device
)
td = self._create_seq_mock_data_dqn(
action_spec_type=action_spec_type, device=device
)
loss_fn = DQNLoss(actor, loss_function="l2", delay_value=delay_value)
ms = MultiStep(gamma=gamma, n_steps=n).to(device)
ms_td = ms(td.clone())
with (
pytest.warns(UserWarning, match="No target network updater has been")
if delay_value
else contextlib.nullcontext()
), _check_td_steady(ms_td):
loss_ms = loss_fn(ms_td)
assert loss_fn.tensor_keys.priority in ms_td.keys()
if delay_value:
# remove warning
SoftUpdate(loss_fn, eps=0.5)
with torch.no_grad():
loss = loss_fn(td)
if n == 1:
assert_allclose_td(td, ms_td.select(*td.keys(True, True)))
_loss = sum(
[item for name, item in loss.items() if name.startswith("loss")]
)
_loss_ms = sum(
[item for name, item in loss_ms.items() if name.startswith("loss")]
)
assert (
abs(_loss - _loss_ms) < 1e-3
), f"found abs(loss-loss_ms) = {abs(loss - loss_ms):4.5f} for n=0"
else:
with pytest.raises(AssertionError):
assert_allclose_td(loss, loss_ms)
sum(
[item for name, item in loss_ms.items() if name.startswith("loss")]
).backward()
assert torch.nn.utils.clip_grad.clip_grad_norm_(actor.parameters(), 1.0) > 0.0
# Check param update effect on targets
target_value = loss_fn.target_value_network_params.clone()
for p in loss_fn.parameters():
if p.requires_grad:
p.data += torch.randn_like(p)
target_value2 = loss_fn.target_value_network_params.clone()
if loss_fn.delay_value:
assert_allclose_td(target_value, target_value2)
else:
assert not (target_value == target_value2).any()
# check that policy is updated after parameter update
parameters = [p.clone() for p in actor.parameters()]
for p in loss_fn.parameters():
p.data += torch.randn_like(p)
assert all((p1 != p2).all() for p1, p2 in zip(parameters, actor.parameters()))
@pytest.mark.parametrize(
"td_est", [ValueEstimators.TD1, ValueEstimators.TD0, ValueEstimators.TDLambda]
)
def test_dqn_tensordict_keys(self, td_est):
torch.manual_seed(self.seed)
action_spec_type = "one_hot"
actor = self._create_mock_actor(action_spec_type=action_spec_type)
loss_fn = DQNLoss(actor, delay_value=True)
default_keys = {
"advantage": "advantage",
"value_target": "value_target",
"value": "chosen_action_value",
"priority": "td_error",
"action_value": "action_value",
"action": "action",
"reward": "reward",
"done": "done",
"terminated": "terminated",
}
self.tensordict_keys_test(loss_fn, default_keys=default_keys)
loss_fn = DQNLoss(actor, delay_value=True)
key_mapping = {
"advantage": ("advantage", "advantage_2"),
"value_target": ("value_target", ("value_target", "nested")),
"reward": ("reward", "reward_test"),
"done": ("done", ("done", "test")),
"terminated": ("terminated", ("terminated", "test")),
}
self.set_advantage_keys_through_loss_test(loss_fn, td_est, key_mapping)
actor = self._create_mock_actor(
action_spec_type=action_spec_type, action_value_key="chosen_action_value_2"
)
loss_fn = DQNLoss(actor, delay_value=True)
key_mapping = {
"value": ("value", "chosen_action_value_2"),
}
self.set_advantage_keys_through_loss_test(loss_fn, td_est, key_mapping)
@pytest.mark.parametrize("action_spec_type", ("categorical", "one_hot"))
@pytest.mark.parametrize(
"td_est", [ValueEstimators.TD1, ValueEstimators.TD0, ValueEstimators.TDLambda]
)
def test_dqn_tensordict_run(self, action_spec_type, td_est):
torch.manual_seed(self.seed)
tensor_keys = {
"action_value": "action_value_test",
"action": "action_test",
"priority": "priority_test",
}
actor = self._create_mock_actor(
action_spec_type=action_spec_type,
action_value_key=tensor_keys["action_value"],
)
td = self._create_mock_data_dqn(
action_spec_type=action_spec_type,
action_key=tensor_keys["action"],
action_value_key=tensor_keys["action_value"],
)
loss_fn = DQNLoss(actor, loss_function="l2", delay_value=True)
loss_fn.set_keys(**tensor_keys)
if td_est is not None:
loss_fn.make_value_estimator(td_est)
SoftUpdate(loss_fn, eps=0.5)
with _check_td_steady(td):
_ = loss_fn(td)
assert loss_fn.tensor_keys.priority in td.keys()
@pytest.mark.parametrize("atoms", range(4, 10))
@pytest.mark.parametrize("delay_value", (False, True))
@pytest.mark.parametrize("device", get_devices())
@pytest.mark.parametrize(
"action_spec_type", ("mult_one_hot", "one_hot", "categorical")
)
@pytest.mark.parametrize("td_est", list(ValueEstimators) + [None])
def test_distributional_dqn(
self, atoms, delay_value, device, action_spec_type, td_est, gamma=0.9
):
torch.manual_seed(self.seed)
actor = self._create_mock_distributional_actor(
action_spec_type=action_spec_type, atoms=atoms
).to(device)
td = self._create_mock_data_dqn(
action_spec_type=action_spec_type, atoms=atoms
).to(device)
loss_fn = DistributionalDQNLoss(
actor,
gamma=gamma,
delay_value=delay_value,
)
if td_est not in (None, ValueEstimators.TD0):
with pytest.raises(NotImplementedError):
loss_fn.make_value_estimator(td_est)
return
elif td_est is not None:
loss_fn.make_value_estimator(td_est)
with _check_td_steady(td), (
pytest.warns(
UserWarning,
match="No target network updater has been associated with this loss module",
)
if delay_value
else contextlib.nullcontext()
):
loss = loss_fn(td)
assert loss_fn.tensor_keys.priority in td.keys()
sum([item for name, item in loss.items() if name.startswith("loss")]).backward()
assert torch.nn.utils.clip_grad.clip_grad_norm_(actor.parameters(), 1.0) > 0.0
if delay_value:
# remove warning
SoftUpdate(loss_fn, eps=0.5)
# Check param update effect on targets
target_value = loss_fn.target_value_network_params.clone()
for p in loss_fn.parameters():
if p.requires_grad:
p.data += torch.randn_like(p)
target_value2 = loss_fn.target_value_network_params.clone()
if loss_fn.delay_value:
assert_allclose_td(target_value, target_value2)
else:
for key, val in target_value.flatten_keys(",").items():
if "support" in key:
continue
assert not (val == target_value2[tuple(key.split(","))]).any(), key
# check that policy is updated after parameter update
parameters = [p.clone() for p in actor.parameters()]
for p in loss_fn.parameters():
p.data += torch.randn_like(p)
assert all((p1 != p2).all() for p1, p2 in zip(parameters, actor.parameters()))
@pytest.mark.parametrize("observation_key", ["observation", "observation2"])
@pytest.mark.parametrize("reward_key", ["reward", "reward2"])
@pytest.mark.parametrize("done_key", ["done", "done2"])
@pytest.mark.parametrize("terminated_key", ["terminated", "terminated2"])
def test_dqn_notensordict(
self, observation_key, reward_key, done_key, terminated_key
):
n_obs = 3
n_action = 4
action_spec = OneHot(n_action)
module = nn.Linear(n_obs, n_action) # a simple value model
actor = QValueActor(
spec=action_spec,
action_space="one_hot",
module=module,
in_keys=[observation_key],
)
dqn_loss = DQNLoss(actor, delay_value=True)
dqn_loss.set_keys(reward=reward_key, done=done_key, terminated=terminated_key)
# define data
observation = torch.randn(n_obs)
next_observation = torch.randn(n_obs)
action = action_spec.rand()
next_reward = torch.randn(1)
next_done = torch.zeros(1, dtype=torch.bool)
next_terminated = torch.zeros(1, dtype=torch.bool)
kwargs = {
observation_key: observation,
f"next_{observation_key}": next_observation,
f"next_{reward_key}": next_reward,
f"next_{done_key}": next_done,
f"next_{terminated_key}": next_terminated,
"action": action,
}
td = TensorDict(kwargs, []).unflatten_keys("_")
# Disable warning
SoftUpdate(dqn_loss, eps=0.5)
loss_val = dqn_loss(**kwargs)
loss_val_td = dqn_loss(td)
torch.testing.assert_close(loss_val_td.get("loss"), loss_val)
def test_distributional_dqn_tensordict_keys(self):
torch.manual_seed(self.seed)
action_spec_type = "one_hot"
atoms = 2
gamma = 0.9
actor = self._create_mock_distributional_actor(
action_spec_type=action_spec_type, atoms=atoms
)
loss_fn = DistributionalDQNLoss(actor, gamma=gamma, delay_value=True)
default_keys = {
"priority": "td_error",
"action_value": "action_value",
"action": "action",
"reward": "reward",
"done": "done",
"terminated": "terminated",
"steps_to_next_obs": "steps_to_next_obs",
}
self.tensordict_keys_test(loss_fn, default_keys=default_keys)
@pytest.mark.parametrize("action_spec_type", ("categorical", "one_hot"))
@pytest.mark.parametrize("td_est", [ValueEstimators.TD0])
def test_distributional_dqn_tensordict_run(self, action_spec_type, td_est):
torch.manual_seed(self.seed)
atoms = 4
tensor_keys = {
"action_value": "action_value_test",
"action": "action_test",
"priority": "priority_test",
}
actor = self._create_mock_distributional_actor(
action_spec_type=action_spec_type,
atoms=atoms,
action_value_key=tensor_keys["action_value"],