forked from pytorch/rl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollectors.py
2173 lines (1941 loc) · 93.2 KB
/
collectors.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 _pickle
import abc
import inspect
import os
import queue
import sys
import time
import warnings
from collections import OrderedDict
from copy import deepcopy
from multiprocessing import connection, queues
from multiprocessing.managers import SyncManager
from textwrap import indent
from typing import Any, Callable, Dict, Iterator, Optional, Sequence, Tuple, Union
import numpy as np
import torch
import torch.nn as nn
from tensordict.nn import TensorDictModule, TensorDictModuleBase
from tensordict.tensordict import TensorDict, TensorDictBase
from torch import multiprocessing as mp
from torch.utils.data import IterableDataset
from torchrl._utils import (
_check_for_faulty_process,
accept_remote_rref_udf_invocation,
prod,
RL_WARNINGS,
VERBOSE,
)
from torchrl.collectors.utils import split_trajectories
from torchrl.data.tensor_specs import TensorSpec
from torchrl.data.utils import CloudpickleWrapper, DEVICE_TYPING
from torchrl.envs.common import EnvBase
from torchrl.envs.transforms import StepCounter, TransformedEnv
from torchrl.envs.utils import (
_convert_exploration_type,
ExplorationType,
set_exploration_type,
step_mdp,
)
from torchrl.envs.vec_env import _BatchedEnv
_TIMEOUT = 1.0
_MIN_TIMEOUT = 1e-3 # should be several orders of magnitude inferior wrt time spent collecting a trajectory
_MAX_IDLE_COUNT = int(os.environ.get("MAX_IDLE_COUNT", 1000))
DEFAULT_EXPLORATION_TYPE: ExplorationType = ExplorationType.RANDOM
_is_osx = sys.platform.startswith("darwin")
class RandomPolicy:
"""A random policy for data collectors.
This is a wrapper around the action_spec.rand method.
Args:
action_spec: TensorSpec object describing the action specs
Examples:
>>> from tensordict import TensorDict
>>> from torchrl.data.tensor_specs import BoundedTensorSpec
>>> action_spec = BoundedTensorSpec(-torch.ones(3), torch.ones(3))
>>> actor = RandomPolicy(spec=action_spec)
>>> td = actor(TensorDict(batch_size=[])) # selects a random action in the cube [-1; 1]
"""
def __init__(self, action_spec: TensorSpec):
self.action_spec = action_spec
def __call__(self, td: TensorDictBase) -> TensorDictBase:
return td.set("action", self.action_spec.rand())
class _Interruptor:
"""A class for managing the collection state of a process.
This class provides methods to start and stop collection, and to check
whether collection has been stopped. The collection state is protected
by a lock to ensure thread-safety.
"""
# interrupter vs interruptor: google trends seems to indicate that "or" is more
# widely used than "er" even if my IDE complains about that...
def __init__(self):
self._collect = True
self._lock = mp.Lock()
def start_collection(self):
with self._lock:
self._collect = True
def stop_collection(self):
with self._lock:
self._collect = False
def collection_stopped(self):
with self._lock:
return self._collect is False
class _InterruptorManager(SyncManager):
"""A custom SyncManager for managing the collection state of a process.
This class extends the SyncManager class and allows to share an Interruptor object
between processes.
"""
pass
_InterruptorManager.register("_Interruptor", _Interruptor)
def recursive_map_to_cpu(dictionary: OrderedDict) -> OrderedDict:
"""Maps the tensors to CPU through a nested dictionary."""
return OrderedDict(
**{
k: recursive_map_to_cpu(item)
if isinstance(item, OrderedDict)
else item.cpu()
if isinstance(item, torch.Tensor)
else item
for k, item in dictionary.items()
}
)
def _policy_is_tensordict_compatible(policy: nn.Module):
sig = inspect.signature(policy.forward)
if isinstance(policy, TensorDictModuleBase):
return True
if (
len(sig.parameters) == 1
and hasattr(policy, "in_keys")
and hasattr(policy, "out_keys")
):
warnings.warn(
"Passing a policy that is not a TensorDictModuleBase subclass but has in_keys and out_keys "
"will soon be deprecated. We'd like to motivate our users to inherit from this class (which "
"has very few restrictions) to make the experience smoother.",
category=DeprecationWarning,
)
# if the policy is a TensorDictModule or takes a single argument and defines
# in_keys and out_keys then we assume it can already deal with TensorDict input
# to forward and we return True
return True
elif not hasattr(policy, "in_keys") and not hasattr(policy, "out_keys"):
# if it's not a TensorDictModule, and in_keys and out_keys are not defined then
# we assume no TensorDict compatibility and will try to wrap it.
return False
# if in_keys or out_keys were defined but policy is not a TensorDictModule or
# accepts multiple arguments then it's likely the user is trying to do something
# that will have undetermined behaviour, we raise an error
raise TypeError(
"Received a policy that defines in_keys or out_keys and also expects multiple "
"arguments to policy.forward. If the policy is compatible with TensorDict, it "
"should take a single argument of type TensorDict to policy.forward and define "
"both in_keys and out_keys. Alternatively, policy.forward can accept "
"arbitrarily many tensor inputs and leave in_keys and out_keys undefined and "
"TorchRL will attempt to automatically wrap the policy with a TensorDictModule."
)
class DataCollectorBase(IterableDataset, metaclass=abc.ABCMeta):
"""Base class for data collectors."""
_iterator = None
def _get_policy_and_device(
self,
policy: Optional[
Union[
TensorDictModule,
Callable[[TensorDictBase], TensorDictBase],
]
] = None,
device: Optional[DEVICE_TYPING] = None,
observation_spec: TensorSpec = None,
) -> Tuple[TensorDictModule, torch.device, Union[None, Callable[[], dict]]]:
"""Util method to get a policy and its device given the collector __init__ inputs.
From a policy and a device, assigns the self.device attribute to
the desired device and maps the policy onto it or (if the device is
ommitted) assigns the self.device attribute to the policy device.
Args:
create_env_fn (Callable or list of callables): an env creator
function (or a list of creators)
create_env_kwargs (dictionary): kwargs for the env creator
policy (TensorDictModule, optional): a policy to be used
device (int, str or torch.device, optional): device where to place
the policy
observation_spec (TensorSpec, optional): spec of the observations
"""
if policy is None:
if not hasattr(self, "env") or self.env is None:
raise ValueError(
"env must be provided to _get_policy_and_device if policy is None"
)
policy = RandomPolicy(self.env.action_spec)
elif isinstance(policy, nn.Module):
# TODO: revisit these checks when we have determined whether arbitrary
# callables should be supported as policies.
if not _policy_is_tensordict_compatible(policy):
# policy is a nn.Module that doesn't operate on tensordicts directly
# so we attempt to auto-wrap policy with TensorDictModule
if observation_spec is None:
raise ValueError(
"Unable to read observation_spec from the environment. This is "
"required to check compatibility of the environment and policy "
"since the policy is a nn.Module that operates on tensors "
"rather than a TensorDictModule or a nn.Module that accepts a "
"TensorDict as input and defines in_keys and out_keys."
)
try:
# signature modified by make_functional
sig = policy.forward.__signature__
except AttributeError:
sig = inspect.signature(policy.forward)
required_params = {
str(k)
for k, p in sig.parameters.items()
if p.default is inspect._empty
}
next_observation = {
key: value for key, value in observation_spec.rand().items()
}
# we check if all the mandatory params are there
if not required_params.difference(set(next_observation)):
in_keys = [str(k) for k in sig.parameters if k in next_observation]
out_keys = ["action"]
output = policy(**next_observation)
if isinstance(output, tuple):
out_keys.extend(f"output{i+1}" for i in range(len(output) - 1))
policy = TensorDictModule(
policy, in_keys=in_keys, out_keys=out_keys
)
else:
raise TypeError(
f"""Arguments to policy.forward are incompatible with entries in
env.observation_spec (got incongruent signatures: fun signature is {set(sig.parameters)} vs specs {set(next_observation)}).
If you want TorchRL to automatically wrap your policy with a TensorDictModule
then the arguments to policy.forward must correspond one-to-one with entries
in env.observation_spec that are prefixed with 'next_'. For more complex
behaviour and more control you can consider writing your own TensorDictModule.
"""
)
try:
policy_device = next(policy.parameters()).device
except: # noqa
policy_device = (
torch.device(device) if device is not None else torch.device("cpu")
)
device = torch.device(device) if device is not None else policy_device
get_weights_fn = None
if policy_device != device:
param_and_buf = dict(policy.named_parameters())
param_and_buf.update(dict(policy.named_buffers()))
def get_weights_fn(param_and_buf=param_and_buf):
return TensorDict(param_and_buf, []).apply(lambda x: x.data)
policy_cast = deepcopy(policy).requires_grad_(False).to(device)
# here things may break bc policy.to("cuda") gives us weights on cuda:0 (same
# but different)
try:
device = next(policy_cast.parameters()).device
except StopIteration: # noqa
pass
else:
policy_cast = policy
return policy_cast, device, get_weights_fn
def update_policy_weights_(
self, policy_weights: Optional[TensorDictBase] = None
) -> None:
"""Updates the policy weights if the policy of the data collector and the trained policy live on different devices.
Args:
policy_weights (TensorDictBase, optional): if provided, a TensorDict containing
the weights of the policy to be used for the udpdate.
"""
if policy_weights is not None:
self.policy_weights.apply(lambda x: x.data).update_(policy_weights)
elif self.get_weights_fn is not None:
self.policy_weights.apply(lambda x: x.data).update_(self.get_weights_fn())
def __iter__(self) -> Iterator[TensorDictBase]:
return self.iterator()
def next(self):
try:
if self._iterator is None:
self._iterator = iter(self)
out = next(self._iterator)
# if any, we don't want the device ref to be passed in distributed settings
out.clear_device_()
return out
except StopIteration:
return None
@abc.abstractmethod
def shutdown(self):
raise NotImplementedError
@abc.abstractmethod
def iterator(self) -> Iterator[TensorDictBase]:
raise NotImplementedError
@abc.abstractmethod
def set_seed(self, seed: int, static_seed: bool = False) -> int:
raise NotImplementedError
@abc.abstractmethod
def state_dict(self) -> OrderedDict:
raise NotImplementedError
@abc.abstractmethod
def load_state_dict(self, state_dict: OrderedDict) -> None:
raise NotImplementedError
def __repr__(self) -> str:
string = f"{self.__class__.__name__}()"
return string
@accept_remote_rref_udf_invocation
class SyncDataCollector(DataCollectorBase):
"""Generic data collector for RL problems. Requires an environment constructor and a policy.
Args:
create_env_fn (Callable): a callable that returns an instance of
:class:`~torchrl.envs.EnvBase` class.
policy (Callable): Policy to be executed in the environment.
Must accept :class:`tensordict.tensordict.TensorDictBase` object as input.
If ``None`` is provided, the policy used will be a
:class:`~torchrl.collectors.RandomPolicy` instance with the environment
``action_spec``.
frames_per_batch (int): A keyword-only argument representing the total
number of elements in a batch.
total_frames (int): A keyword-only argument representing the total
number of frames returned by the collector
during its lifespan. If the ``total_frames`` is not divisible by
``frames_per_batch``, an exception is raised.
Endless collectors can be created by passing ``total_frames=-1``.
device (int, str or torch.device, optional): The device on which the
policy will be placed.
If it differs from the input policy device, the
:meth:`~.update_policy_weights_` method should be queried
at appropriate times during the training loop to accommodate for
the lag between parameter configuration at various times.
Defaults to ``None`` (i.e. policy is kept on its original device).
storing_device (int, str or torch.device, optional): The device on which
the output :class:`tensordict.TensorDict` will be stored. For long
trajectories, it may be necessary to store the data on a different
device than the one where the policy and env are executed.
Defaults to ``"cpu"``.
create_env_kwargs (dict, optional): Dictionary of kwargs for
``create_env_fn``.
max_frames_per_traj (int, optional): Maximum steps per trajectory.
Note that a trajectory can span over multiple batches (unless
``reset_at_each_iter`` is set to ``True``, see below).
Once a trajectory reaches ``n_steps``, the environment is reset.
If the environment wraps multiple environments together, the number
of steps is tracked for each environment independently. Negative
values are allowed, in which case this argument is ignored.
Defaults to ``-1`` (i.e. no maximum number of steps).
init_random_frames (int, optional): Number of frames for which the
policy is ignored before it is called. This feature is mainly
intended to be used in offline/model-based settings, where a
batch of random trajectories can be used to initialize training.
Defaults to ``-1`` (i.e. no random frames).
reset_at_each_iter (bool, optional): Whether environments should be reset
at the beginning of a batch collection.
Defaults to ``False``.
postproc (Callable, optional): A post-processing transform, such as
a :class:`~torchrl.envs.Transform` or a :class:`~torchrl.data.postprocs.MultiStep`
instance.
Defaults to ``None``.
split_trajs (bool, optional): Boolean indicating whether the resulting
TensorDict should be split according to the trajectories.
See :func:`~torchrl.collectors.utils.split_trajectories` for more
information.
Defaults to ``False``.
exploration_type (ExplorationType, optional): interaction mode to be used when
collecting data. Must be one of ``ExplorationType.RANDOM``, ``ExplorationType.MODE`` or
``ExplorationType.MEAN``.
Defaults to ``ExplorationType.RANDOM``
return_same_td (bool, optional): if ``True``, the same TensorDict
will be returned at each iteration, with its values
updated. This feature should be used cautiously: if the same
tensordict is added to a replay buffer for instance,
the whole content of the buffer will be identical.
Default is False.
interruptor (_Interruptor, optional):
An _Interruptor object that can be used from outside the class to control rollout collection.
The _Interruptor class has methods ´start_collection´ and ´stop_collection´, which allow to implement
strategies such as preeptively stopping rollout collection.
Default is ``False``.
reset_when_done (bool, optional): if ``True`` (default), an environment
that return a ``True`` value in its ``"done"`` or ``"truncated"``
entry will be reset at the corresponding indices.
Examples:
>>> from torchrl.envs.libs.gym import GymEnv
>>> from tensordict.nn import TensorDictModule
>>> from torch import nn
>>> env_maker = lambda: GymEnv("Pendulum-v1", device="cpu")
>>> policy = TensorDictModule(nn.Linear(3, 1), in_keys=["observation"], out_keys=["action"])
>>> collector = SyncDataCollector(
... create_env_fn=env_maker,
... policy=policy,
... total_frames=2000,
... max_frames_per_traj=50,
... frames_per_batch=200,
... init_random_frames=-1,
... reset_at_each_iter=False,
... device="cpu",
... storing_device="cpu",
... )
>>> for i, data in enumerate(collector):
... if i == 2:
... print(data)
... break
TensorDict(
fields={
action: Tensor(shape=torch.Size([4, 50, 1]), device=cpu, dtype=torch.float32, is_shared=False),
collector: TensorDict(
fields={
step_count: Tensor(shape=torch.Size([4, 50]), device=cpu, dtype=torch.int64, is_shared=False),
"traj_ids: Tensor(shape=torch.Size([4, 50]), device=cpu, dtype=torch.int64, is_shared=False)},
batch_size=torch.Size([4, 50]),
device=cpu,
is_shared=False),
done: Tensor(shape=torch.Size([4, 50, 1]), device=cpu, dtype=torch.bool, is_shared=False),
mask: Tensor(shape=torch.Size([4, 50]), device=cpu, dtype=torch.bool, is_shared=False),
next: TensorDict(
fields={
observation: Tensor(shape=torch.Size([4, 50, 3]), device=cpu, dtype=torch.float32, is_shared=False)},
batch_size=torch.Size([4, 50]),
device=cpu,
is_shared=False),
observation: Tensor(shape=torch.Size([4, 50, 3]), device=cpu, dtype=torch.float32, is_shared=False),
reward: Tensor(shape=torch.Size([4, 50, 1]), device=cpu, dtype=torch.float32, is_shared=False)},
batch_size=torch.Size([4, 50]),
device=cpu,
is_shared=False)
>>> del collector
The collector delivers batches of data that are marked with a ``"time"``
dimension.
Examples:
>>> assert data.names[-1] == "time"
"""
def __init__(
self,
create_env_fn: Union[
EnvBase, "EnvCreator", Sequence[Callable[[], EnvBase]] # noqa: F821
], # noqa: F821
policy: Optional[
Union[
TensorDictModule,
Callable[[TensorDictBase], TensorDictBase],
]
],
*,
frames_per_batch: int,
total_frames: int,
device: DEVICE_TYPING = None,
storing_device: DEVICE_TYPING = None,
create_env_kwargs: Optional[dict] = None,
max_frames_per_traj: int = -1,
init_random_frames: int = -1,
reset_at_each_iter: bool = False,
postproc: Optional[Callable[[TensorDictBase], TensorDictBase]] = None,
split_trajs: Optional[bool] = None,
exploration_type: ExplorationType = DEFAULT_EXPLORATION_TYPE,
exploration_mode=None,
return_same_td: bool = False,
reset_when_done: bool = True,
interruptor=None,
):
self.closed = True
exploration_type = _convert_exploration_type(
exploration_mode=exploration_mode, exploration_type=exploration_type
)
if create_env_kwargs is None:
create_env_kwargs = {}
if not isinstance(create_env_fn, EnvBase):
env = create_env_fn(**create_env_kwargs)
else:
env = create_env_fn
if create_env_kwargs:
if not isinstance(env, _BatchedEnv):
raise RuntimeError(
"kwargs were passed to SyncDataCollector but they can't be set "
f"on environment of type {type(create_env_fn)}."
)
env.update_kwargs(create_env_kwargs)
if storing_device is None:
if device is not None:
storing_device = device
elif policy is not None:
try:
policy_device = next(policy.parameters()).device
except (AttributeError, StopIteration):
policy_device = torch.device("cpu")
storing_device = policy_device
else:
storing_device = torch.device("cpu")
self.storing_device = torch.device(storing_device)
self.env: EnvBase = env
self.closed = False
self.reset_when_done = reset_when_done
self.n_env = self.env.batch_size.numel()
(self.policy, self.device, self.get_weights_fn,) = self._get_policy_and_device(
policy=policy,
device=device,
observation_spec=self.env.observation_spec,
)
if isinstance(self.policy, nn.Module):
self.policy_weights = TensorDict(dict(self.policy.named_parameters()), [])
self.policy_weights.update(
TensorDict(dict(self.policy.named_buffers()), [])
)
else:
self.policy_weights = TensorDict({}, [])
print("sending env to device", self.device)
self.env: EnvBase = self.env.to(self.device)
self.max_frames_per_traj = max_frames_per_traj
if self.max_frames_per_traj > 0:
# let's check that there is no StepCounter yet
for key in self.env.output_spec.keys(True, True):
if isinstance(key, str):
key = (key,)
if "truncated" in key:
raise ValueError(
"A 'truncated' key is already present in the environment "
"and the 'max_frames_per_traj' argument may conflict with "
"a 'StepCounter' that has already been set. "
"Possible solutions: Set max_frames_per_traj to 0 or "
"remove the StepCounter limit from the environment transforms."
)
env = self.env = TransformedEnv(
self.env, StepCounter(max_steps=self.max_frames_per_traj)
)
if total_frames is None or total_frames < 0:
total_frames = float("inf")
else:
remainder = total_frames % frames_per_batch
if remainder != 0 and RL_WARNINGS:
warnings.warn(
f"total_frames ({total_frames}) is not exactly divisible by frames_per_batch ({frames_per_batch})."
f"This means {frames_per_batch - remainder} additional frames will be collected."
"To silence this message, set the environment variable RL_WARNINGS to False."
)
self.total_frames = total_frames
self.reset_at_each_iter = reset_at_each_iter
self.init_random_frames = init_random_frames
self.postproc = postproc
if self.postproc is not None and hasattr(self.postproc, "to"):
self.postproc.to(self.storing_device)
if frames_per_batch % self.n_env != 0 and RL_WARNINGS:
warnings.warn(
f"frames_per_batch {frames_per_batch} is not exactly divisible by the number of batched environments {self.n_env}, "
f" this results in more frames_per_batch per iteration that requested."
"To silence this message, set the environment variable RL_WARNINGS to False."
)
self.requested_frames_per_batch = frames_per_batch
self.frames_per_batch = -(-frames_per_batch // self.n_env)
self.exploration_type = (
exploration_type if exploration_type else DEFAULT_EXPLORATION_TYPE
)
self.return_same_td = return_same_td
self._tensordict = env.reset()
traj_ids = torch.arange(self.n_env, device=env.device).view(self.env.batch_size)
self._tensordict.set(
("collector", "traj_ids"),
traj_ids,
)
with torch.no_grad():
self._tensordict_out = env.fake_tensordict()
if (
hasattr(self.policy, "spec")
and self.policy.spec is not None
and all(
v is not None for v in self.policy.spec.values(True, True)
) # if a spec is None, we don't know anything about it
# and set(self.policy.spec.keys(True, True)) == set(self.policy.out_keys)
and any(
key not in self._tensordict_out.keys(isinstance(key, tuple))
for key in self.policy.spec.keys(True, True)
)
):
# if policy spec is non-empty, all the values are not None and the keys
# match the out_keys we assume the user has given all relevant information
# the policy could have more keys than the env:
policy_spec = self.policy.spec
if policy_spec.ndim < self._tensordict_out.ndim:
policy_spec = policy_spec.expand(self._tensordict_out.shape)
for key, spec in policy_spec.items(True, True):
if key in self._tensordict_out.keys(isinstance(key, tuple)):
continue
self._tensordict_out.set(key, spec.zero())
self._tensordict_out = (
self._tensordict_out.unsqueeze(-1)
.expand(*env.batch_size, self.frames_per_batch)
.clone()
)
elif (
hasattr(self.policy, "spec")
and self.policy.spec is not None
and all(v is not None for v in self.policy.spec.values(True, True))
and all(
key in self._tensordict_out.keys(isinstance(key, tuple))
for key in self.policy.spec.keys(True, True)
)
):
# reach this if the policy has specs and they match with the fake tensordict
self._tensordict_out = (
self._tensordict_out.unsqueeze(-1)
.expand(*env.batch_size, self.frames_per_batch)
.clone()
)
else:
# otherwise, we perform a small number of steps with the policy to
# determine the relevant keys with which to pre-populate _tensordict_out.
# This is the safest thing to do if the spec has None fields or if there is
# no spec at all.
# See #505 for additional context.
with torch.no_grad():
self._tensordict_out = self._tensordict_out.to(self.device)
self._tensordict_out = self.policy(self._tensordict_out).unsqueeze(-1)
self._tensordict_out = (
self._tensordict_out.expand(*env.batch_size, self.frames_per_batch)
.clone()
.zero_()
)
# in addition to outputs of the policy, we add traj_ids and step_count to
# _tensordict_out which will be collected during rollout
self._tensordict_out = self._tensordict_out.to(self.storing_device)
self._tensordict_out.set(
("collector", "traj_ids"),
torch.zeros(
*self._tensordict_out.batch_size,
dtype=torch.int64,
device=self.storing_device,
),
)
self._tensordict_out.refine_names(..., "time")
if split_trajs is None:
split_trajs = False
elif not self.reset_when_done and split_trajs:
raise RuntimeError(
"Cannot split trajectories when reset_when_done is False."
)
self.split_trajs = split_trajs
self._exclude_private_keys = True
self.interruptor = interruptor
# for RPC
def next(self):
return super().next()
# for RPC
def update_policy_weights_(
self, policy_weights: Optional[TensorDictBase] = None
) -> None:
super().update_policy_weights_(policy_weights)
def set_seed(self, seed: int, static_seed: bool = False) -> int:
"""Sets the seeds of the environments stored in the DataCollector.
Args:
seed (int): integer representing the seed to be used for the environment.
static_seed(bool, optional): if ``True``, the seed is not incremented.
Defaults to False
Returns:
Output seed. This is useful when more than one environment is contained in the DataCollector, as the
seed will be incremented for each of these. The resulting seed is the seed of the last environment.
Examples:
>>> from torchrl.envs import ParallelEnv
>>> from torchrl.envs.libs.gym import GymEnv
>>> env_fn = lambda: GymEnv("Pendulum-v1")
>>> env_fn_parallel = ParallelEnv(6, env_fn)
>>> collector = SyncDataCollector(env_fn_parallel)
>>> out_seed = collector.set_seed(1) # out_seed = 6
"""
return self.env.set_seed(seed, static_seed=static_seed)
def iterator(self) -> Iterator[TensorDictBase]:
"""Iterates through the DataCollector.
Yields: TensorDictBase objects containing (chunks of) trajectories
"""
total_frames = self.total_frames
i = -1
self._frames = 0
while True:
i += 1
self._iter = i
tensordict_out = self.rollout()
self._frames += tensordict_out.numel()
if self._frames >= total_frames:
self.env.close()
if self.split_trajs:
tensordict_out = split_trajectories(tensordict_out, prefix="collector")
if self.postproc is not None:
tensordict_out = self.postproc(tensordict_out)
if self._exclude_private_keys:
excluded_keys = [
key for key in tensordict_out.keys() if key.startswith("_")
]
tensordict_out = tensordict_out.exclude(*excluded_keys, inplace=True)
if self.return_same_td:
# This is used with multiprocessed collectors to use the buffers
# stored in the tensordict.
yield tensordict_out
else:
# we must clone the values, as the tensordict is updated in-place.
# otherwise the following code may break:
# >>> for i, data in enumerate(collector):
# >>> if i == 0:
# >>> data0 = data
# >>> elif i == 1:
# >>> data1 = data
# >>> else:
# >>> break
# >>> assert data0["done"] is not data1["done"]
yield tensordict_out.clone()
if self._frames >= self.total_frames:
break
def _step_and_maybe_reset(self) -> None:
done = self._tensordict.get(("next", "done"))
truncated = self._tensordict.get(("next", "truncated"), None)
traj_ids = self._tensordict.get(("collector", "traj_ids"))
self._tensordict = step_mdp(self._tensordict)
if not self.reset_when_done:
return
done_or_terminated = (
(done | truncated) if truncated is not None else done.clone()
)
if done_or_terminated.any():
# collectors do not support passing other tensors than `"_reset"`
# to `reset()`.
_reset = done_or_terminated
td_reset = self._tensordict.select().set("_reset", _reset)
td_reset = self.env.reset(td_reset)
traj_done_or_terminated = done_or_terminated.sum(
tuple(range(self._tensordict.batch_dims, done_or_terminated.ndim)),
dtype=torch.bool,
)
if td_reset.batch_dims:
self._tensordict.get_sub_tensordict(traj_done_or_terminated).update(
td_reset[traj_done_or_terminated], inplace=True
)
else:
self._tensordict.update(td_reset, inplace=True)
done = self._tensordict.get("done")
if done.any():
raise RuntimeError(
f"Env {self.env} was done after reset on specified '_reset' dimensions. This is (currently) not allowed."
)
traj_ids[traj_done_or_terminated] = traj_ids.max() + torch.arange(
1, traj_done_or_terminated.sum() + 1, device=traj_ids.device
)
self._tensordict.set_(
("collector", "traj_ids"), traj_ids
) # no ops if they already match
@torch.no_grad()
def rollout(self) -> TensorDictBase:
"""Computes a rollout in the environment using the provided policy.
Returns:
TensorDictBase containing the computed rollout.
"""
if self.reset_at_each_iter:
self._tensordict.update(self.env.reset(), inplace=True)
# self._tensordict.fill_(("collector", "step_count"), 0)
self._tensordict_out.fill_(("collector", "traj_ids"), -1)
with set_exploration_type(self.exploration_type):
for j in range(self.frames_per_batch):
if self._frames < self.init_random_frames:
self.env.rand_step(self._tensordict)
else:
self.policy(self._tensordict)
self.env.step(self._tensordict)
# we must clone all the values, since the step / traj_id updates are done in-place
try:
self._tensordict_out[..., j] = self._tensordict
except RuntimeError:
# unlock the output tensordict to allow for new keys to be written
# these will be missed during the sync but at least we won't get an error during the update
is_shared = self._tensordict_out.is_shared()
self._tensordict_out.unlock_()
self._tensordict_out[..., j] = self._tensordict
if is_shared:
self._tensordict_out.share_memory_()
else:
self._tensordict_out.lock()
self._step_and_maybe_reset()
if (
self.interruptor is not None
and self.interruptor.collection_stopped()
):
break
return self._tensordict_out
def reset(self, index=None, **kwargs) -> None:
"""Resets the environments to a new initial state."""
# metadata
md = self._tensordict["collector"].clone()
if index is not None:
# check that the env supports partial reset
if prod(self.env.batch_size) == 0:
raise RuntimeError("resetting unique env with index is not permitted.")
_reset = torch.zeros(
self.env.done_spec.shape,
dtype=torch.bool,
device=self.env.device,
)
_reset[index] = 1
self._tensordict[index].zero_()
self._tensordict["_reset"] = _reset
else:
_reset = None
self._tensordict.zero_()
self._tensordict.update(self.env.reset(**kwargs))
md["traj_ids"] = md["traj_ids"] - md["traj_ids"].min()
self._tensordict["collector"] = md
def shutdown(self) -> None:
"""Shuts down all workers and/or closes the local environment."""
if not self.closed:
self.closed = True
del self._tensordict, self._tensordict_out
if not self.env.is_closed:
self.env.close()
del self.env
return
def __del__(self):
try:
self.shutdown()
except Exception:
# an AttributeError will typically be raised if the collector is deleted when the program ends.
# In the future, insignificant changes to the close method may change the error type.
# We excplicitely assume that any error raised during closure in
# __del__ will not affect the program.
pass
def state_dict(self) -> OrderedDict:
"""Returns the local state_dict of the data collector (environment and policy).
Returns:
an ordered dictionary with fields :obj:`"policy_state_dict"` and
`"env_state_dict"`.
"""
if isinstance(self.env, TransformedEnv):
env_state_dict = self.env.transform.state_dict()
elif isinstance(self.env, _BatchedEnv):
env_state_dict = self.env.state_dict()
else:
env_state_dict = OrderedDict()
if hasattr(self.policy, "state_dict"):
policy_state_dict = self.policy.state_dict()
state_dict = OrderedDict(
policy_state_dict=policy_state_dict,
env_state_dict=env_state_dict,
)
else:
state_dict = OrderedDict(env_state_dict=env_state_dict)
return state_dict
def load_state_dict(self, state_dict: OrderedDict, **kwargs) -> None:
"""Loads a state_dict on the environment and policy.
Args:
state_dict (OrderedDict): ordered dictionary containing the fields
`"policy_state_dict"` and :obj:`"env_state_dict"`.
"""
strict = kwargs.get("strict", True)
if strict or "env_state_dict" in state_dict:
self.env.load_state_dict(state_dict["env_state_dict"], **kwargs)
if strict or "policy_state_dict" in state_dict:
self.policy.load_state_dict(state_dict["policy_state_dict"], **kwargs)
def __repr__(self) -> str:
env_str = indent(f"env={self.env}", 4 * " ")
policy_str = indent(f"policy={self.policy}", 4 * " ")
td_out_str = indent(f"td_out={self._tensordict_out}", 4 * " ")
string = (
f"{self.__class__.__name__}("
f"\n{env_str},"
f"\n{policy_str},"
f"\n{td_out_str},"
f"\nexploration={self.exploration_type})"
)
return string
class _MultiDataCollector(DataCollectorBase):
"""Runs a given number of DataCollectors on separate processes.
Args:
create_env_fn (List[Callabled]): list of Callables, each returning an
instance of :class:`~torchrl.envs.EnvBase`.
policy (Callable, optional): Instance of TensorDictModule class.
Must accept TensorDictBase object as input.
If ``None`` is provided, the policy used will be a
:class:`RandomPolicy` instance with the environment
``action_spec``.
frames_per_batch (int): A keyword-only argument representing the
total number of elements in a batch.
total_frames (int): A keyword-only argument representing the
total number of frames returned by the collector
during its lifespan. If the ``total_frames`` is not divisible by
``frames_per_batch``, an exception is raised.
Endless collectors can be created by passing ``total_frames=-1``.
device (int, str, torch.device or sequence of such, optional):
The device on which the policy will be placed.
If it differs from the input policy device, the
:meth:`~.update_policy_weights_` method should be queried
at appropriate times during the training loop to accommodate for
the lag between parameter configuration at various times.
If necessary, a list of devices can be passed in which case each
element will correspond to the designated device of a sub-collector.
Defaults to ``None`` (i.e. policy is kept on its original device).
storing_device (int, str, torch.device or sequence of such, optional):
The device on which the output :class:`tensordict.TensorDict` will
be stored. For long trajectories, it may be necessary to store the
data on a different device than the one where the policy and env
are executed.
If necessary, a list of devices can be passed in which case each
element will correspond to the designated storing device of a
sub-collector.
Defaults to ``"cpu"``.
create_env_kwargs (dict, optional): A dictionary with the
keyword arguments used to create an environment. If a list is
provided, each of its elements will be assigned to a sub-collector.
max_frames_per_traj (int, optional): Maximum steps per trajectory.
Note that a trajectory can span over multiple batches (unless
``reset_at_each_iter`` is set to ``True``, see below).
Once a trajectory reaches ``n_steps``, the environment is reset.
If the environment wraps multiple environments together, the number
of steps is tracked for each environment independently. Negative
values are allowed, in which case this argument is ignored.