forked from ray-project/ray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollout_worker.py
2072 lines (1794 loc) · 82 KB
/
rollout_worker.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
import copy
import importlib.util
import logging
import os
import platform
import threading
from collections import defaultdict
from types import FunctionType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Container,
Dict,
List,
Optional,
Set,
Tuple,
Type,
Union,
)
import numpy as np
import tree # pip install dm_tree
from gymnasium.spaces import Discrete, MultiDiscrete, Space
import ray
from ray import ObjectRef
from ray import cloudpickle as pickle
from ray.rllib.connectors.util import (
create_connectors_for_policy,
maybe_get_filters_for_syncing,
)
from ray.rllib.core.rl_module.rl_module import SingleAgentRLModuleSpec
from ray.rllib.env.base_env import BaseEnv, convert_to_base_env
from ray.rllib.env.env_context import EnvContext
from ray.rllib.env.env_runner import EnvRunner
from ray.rllib.env.external_multi_agent_env import ExternalMultiAgentEnv
from ray.rllib.env.multi_agent_env import MultiAgentEnv
from ray.rllib.env.wrappers.atari_wrappers import is_atari, wrap_deepmind
from ray.rllib.evaluation.metrics import RolloutMetrics
from ray.rllib.evaluation.sampler import SyncSampler
from ray.rllib.models import ModelCatalog
from ray.rllib.models.preprocessors import Preprocessor
from ray.rllib.offline import (
D4RLReader,
DatasetReader,
DatasetWriter,
InputReader,
IOContext,
JsonReader,
JsonWriter,
MixedInput,
NoopOutput,
OutputWriter,
ShuffledInput,
)
from ray.rllib.policy.policy import Policy, PolicySpec
from ray.rllib.policy.policy_map import PolicyMap
from ray.rllib.policy.sample_batch import (
DEFAULT_POLICY_ID,
MultiAgentBatch,
concat_samples,
convert_ma_batch_to_sample_batch,
)
from ray.rllib.policy.torch_policy import TorchPolicy
from ray.rllib.policy.torch_policy_v2 import TorchPolicyV2
from ray.rllib.utils import check_env, force_list
from ray.rllib.utils.annotations import DeveloperAPI, override
from ray.rllib.utils.debug import summarize, update_global_seed_if_necessary
from ray.rllib.utils.deprecation import DEPRECATED_VALUE, deprecation_warning
from ray.rllib.utils.error import ERR_MSG_NO_GPUS, HOWTO_CHANGE_CONFIG
from ray.rllib.utils.filter import Filter, NoFilter, get_filter
from ray.rllib.utils.framework import try_import_tf, try_import_torch
from ray.rllib.utils.from_config import from_config
from ray.rllib.utils.policy import create_policy_for_framework, validate_policy_id
from ray.rllib.utils.sgd import do_minibatch_sgd
from ray.rllib.utils.tf_run_builder import _TFRunBuilder
from ray.rllib.utils.tf_utils import get_gpu_devices as get_tf_gpu_devices
from ray.rllib.utils.tf_utils import get_tf_eager_cls_if_necessary
from ray.rllib.utils.typing import (
AgentID,
EnvCreator,
EnvType,
ModelGradients,
ModelWeights,
MultiAgentPolicyConfigDict,
PartialAlgorithmConfigDict,
PolicyID,
PolicyState,
SampleBatchType,
T,
)
from ray.tune.registry import registry_contains_input, registry_get_input
from ray.util.annotations import PublicAPI
from ray.util.debug import disable_log_once_globally, enable_periodic_logging, log_once
from ray.util.iter import ParallelIteratorWorker
if TYPE_CHECKING:
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
from ray.rllib.algorithms.callbacks import DefaultCallbacks # noqa
from ray.rllib.evaluation.episode import Episode
tf1, tf, tfv = try_import_tf()
torch, _ = try_import_torch()
logger = logging.getLogger(__name__)
# Handle to the current rollout worker, which will be set to the most recently
# created RolloutWorker in this process. This can be helpful to access in
# custom env or policy classes for debugging or advanced use cases.
_global_worker: Optional["RolloutWorker"] = None
@DeveloperAPI
def get_global_worker() -> "RolloutWorker":
"""Returns a handle to the active rollout worker in this process."""
global _global_worker
return _global_worker
def _update_env_seed_if_necessary(
env: EnvType, seed: int, worker_idx: int, vector_idx: int
):
"""Set a deterministic random seed on environment.
NOTE: this may not work with remote environments (issue #18154).
"""
if seed is None:
return
# A single RL job is unlikely to have more than 10K
# rollout workers.
max_num_envs_per_workers: int = 1000
assert (
worker_idx < max_num_envs_per_workers
), "Too many envs per worker. Random seeds may collide."
computed_seed: int = worker_idx * max_num_envs_per_workers + vector_idx + seed
# Gymnasium.env.
# This will silently fail for most Farama-foundation gymnasium environments.
# (they do nothing and return None per default)
if not hasattr(env, "reset"):
if log_once("env_has_no_reset_method"):
logger.info(f"Env {env} doesn't have a `reset()` method. Cannot seed.")
else:
try:
env.reset(seed=computed_seed)
except Exception:
logger.info(
f"Env {env} doesn't support setting a seed via its `reset()` "
"method! Implement this method as `reset(self, *, seed=None, "
"options=None)` for it to abide to the correct API. Cannot seed."
)
@DeveloperAPI
class RolloutWorker(ParallelIteratorWorker, EnvRunner):
"""Common experience collection class.
This class wraps a policy instance and an environment class to
collect experiences from the environment. You can create many replicas of
this class as Ray actors to scale RL training.
This class supports vectorized and multi-agent policy evaluation (e.g.,
VectorEnv, MultiAgentEnv, etc.)
.. testcode::
:skipif: True
# Create a rollout worker and using it to collect experiences.
import gymnasium as gym
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
worker = RolloutWorker(
env_creator=lambda _: gym.make("CartPole-v1"),
default_policy_class=PPOTF1Policy)
print(worker.sample())
# Creating a multi-agent rollout worker
from gymnasium.spaces import Discrete, Box
import random
MultiAgentTrafficGrid = ...
worker = RolloutWorker(
env_creator=lambda _: MultiAgentTrafficGrid(num_cars=25),
config=AlgorithmConfig().multi_agent(
policies={
# Use an ensemble of two policies for car agents
"car_policy1":
(PGTFPolicy, Box(...), Discrete(...),
AlgorithmConfig.overrides(gamma=0.99)),
"car_policy2":
(PGTFPolicy, Box(...), Discrete(...),
AlgorithmConfig.overrides(gamma=0.95)),
# Use a single shared policy for all traffic lights
"traffic_light_policy":
(PGTFPolicy, Box(...), Discrete(...), {}),
},
policy_mapping_fn=(
lambda agent_id, episode, **kwargs:
random.choice(["car_policy1", "car_policy2"])
if agent_id.startswith("car_") else "traffic_light_policy"),
),
)
print(worker.sample())
.. testoutput::
SampleBatch({
"obs": [[...]], "actions": [[...]], "rewards": [[...]],
"terminateds": [[...]], "truncateds": [[...]], "new_obs": [[...]]}
)
MultiAgentBatch({
"car_policy1": SampleBatch(...),
"car_policy2": SampleBatch(...),
"traffic_light_policy": SampleBatch(...)}
)
"""
def __init__(
self,
*,
env_creator: EnvCreator,
validate_env: Optional[Callable[[EnvType, EnvContext], None]] = None,
config: Optional["AlgorithmConfig"] = None,
worker_index: int = 0,
num_workers: Optional[int] = None,
recreated_worker: bool = False,
log_dir: Optional[str] = None,
spaces: Optional[Dict[PolicyID, Tuple[Space, Space]]] = None,
default_policy_class: Optional[Type[Policy]] = None,
dataset_shards: Optional[List[ray.data.Dataset]] = None,
# Deprecated: This is all specified in `config` anyways.
tf_session_creator=DEPRECATED_VALUE, # Use config.tf_session_options instead.
):
"""Initializes a RolloutWorker instance.
Args:
env_creator: Function that returns a gym.Env given an EnvContext
wrapped configuration.
validate_env: Optional callable to validate the generated
environment (only on worker=0).
worker_index: For remote workers, this should be set to a
non-zero and unique value. This index is passed to created envs
through EnvContext so that envs can be configured per worker.
recreated_worker: Whether this worker is a recreated one. Workers are
recreated by an Algorithm (via WorkerSet) in case
`recreate_failed_workers=True` and one of the original workers (or an
already recreated one) has failed. They don't differ from original
workers other than the value of this flag (`self.recreated_worker`).
log_dir: Directory where logs can be placed.
spaces: An optional space dict mapping policy IDs
to (obs_space, action_space)-tuples. This is used in case no
Env is created on this RolloutWorker.
"""
# Deprecated args.
if tf_session_creator != DEPRECATED_VALUE:
deprecation_warning(
old="RolloutWorker(.., tf_session_creator=.., ..)",
new="config.framework(tf_session_args={..}); "
"RolloutWorker(config=config, ..)",
error=True,
)
self._original_kwargs: dict = locals().copy()
del self._original_kwargs["self"]
global _global_worker
_global_worker = self
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
# Default config needed?
if config is None or isinstance(config, dict):
config = AlgorithmConfig().update_from_dict(config or {})
# Freeze config, so no one else can alter it from here on.
config.freeze()
# Set extra python env variables before calling super constructor.
if config.extra_python_environs_for_driver and worker_index == 0:
for key, value in config.extra_python_environs_for_driver.items():
os.environ[key] = str(value)
elif config.extra_python_environs_for_worker and worker_index > 0:
for key, value in config.extra_python_environs_for_worker.items():
os.environ[key] = str(value)
def gen_rollouts():
while True:
yield self.sample()
ParallelIteratorWorker.__init__(self, gen_rollouts, False)
EnvRunner.__init__(self, config=config)
self.num_workers = (
num_workers if num_workers is not None else self.config.num_rollout_workers
)
# In case we are reading from distributed datasets, store the shards here
# and pick our shard by our worker-index.
self._ds_shards = dataset_shards
self.worker_index: int = worker_index
# Lock to be able to lock this entire worker
# (via `self.lock()` and `self.unlock()`).
# This might be crucial to prevent a race condition in case
# `config.policy_states_are_swappable=True` and you are using an Algorithm
# with a learner thread. In this case, the thread might update a policy
# that is being swapped (during the update) by the Algorithm's
# training_step's `RolloutWorker.get_weights()` call (to sync back the
# new weights to all remote workers).
self._lock = threading.Lock()
if (
tf1
and (config.framework_str == "tf2" or config.enable_tf1_exec_eagerly)
# This eager check is necessary for certain all-framework tests
# that use tf's eager_mode() context generator.
and not tf1.executing_eagerly()
):
tf1.enable_eager_execution()
if self.config.log_level:
logging.getLogger("ray.rllib").setLevel(self.config.log_level)
if self.worker_index > 1:
disable_log_once_globally() # only need 1 worker to log
elif self.config.log_level == "DEBUG":
enable_periodic_logging()
env_context = EnvContext(
self.config.env_config,
worker_index=self.worker_index,
vector_index=0,
num_workers=self.num_workers,
remote=self.config.remote_worker_envs,
recreated_worker=recreated_worker,
)
self.env_context = env_context
self.config: AlgorithmConfig = config
self.callbacks: DefaultCallbacks = self.config.callbacks_class()
self.recreated_worker: bool = recreated_worker
# Setup current policy_mapping_fn. Start with the one from the config, which
# might be None in older checkpoints (nowadays AlgorithmConfig has a proper
# default for this); Need to cover this situation via the backup lambda here.
self.policy_mapping_fn = (
lambda agent_id, episode, worker, **kw: DEFAULT_POLICY_ID
)
self.set_policy_mapping_fn(self.config.policy_mapping_fn)
self.env_creator: EnvCreator = env_creator
# Resolve possible auto-fragment length.
configured_rollout_fragment_length = self.config.get_rollout_fragment_length(
worker_index=self.worker_index
)
self.total_rollout_fragment_length: int = (
configured_rollout_fragment_length * self.config.num_envs_per_worker
)
self.preprocessing_enabled: bool = not config._disable_preprocessor_api
self.last_batch: Optional[SampleBatchType] = None
self.global_vars: dict = {
# TODO(sven): Make this per-policy!
"timestep": 0,
# Counter for performed gradient updates per policy in `self.policy_map`.
# Allows for compiling metrics on the off-policy'ness of an update given
# that the number of gradient updates of the sampling policies are known
# to the learner (and can be compared to the learner version of the same
# policy).
"num_grad_updates_per_policy": defaultdict(int),
}
# If seed is provided, add worker index to it and 10k iff evaluation worker.
self.seed = (
None
if self.config.seed is None
else self.config.seed
+ self.worker_index
+ self.config.in_evaluation * 10000
)
# Update the global seed for numpy/random/tf-eager/torch if we are not
# the local worker, otherwise, this was already done in the Algorithm
# object itself.
if self.worker_index > 0:
update_global_seed_if_necessary(self.config.framework_str, self.seed)
# A single environment provided by the user (via config.env). This may
# also remain None.
# 1) Create the env using the user provided env_creator. This may
# return a gym.Env (incl. MultiAgentEnv), an already vectorized
# VectorEnv, BaseEnv, ExternalEnv, or an ActorHandle (remote env).
# 2) Wrap - if applicable - with Atari/rendering wrappers.
# 3) Seed the env, if necessary.
# 4) Vectorize the existing single env by creating more clones of
# this env and wrapping it with the RLlib BaseEnv class.
self.env = self.make_sub_env_fn = None
# Create a (single) env for this worker.
if not (
self.worker_index == 0
and self.num_workers > 0
and not self.config.create_env_on_local_worker
):
# Run the `env_creator` function passing the EnvContext.
self.env = env_creator(copy.deepcopy(self.env_context))
clip_rewards = self.config.clip_rewards
if self.env is not None:
# Validate environment (general validation function).
if not self.config.disable_env_checking:
check_env(self.env, self.config)
# Custom validation function given, typically a function attribute of the
# Algorithm.
if validate_env is not None:
validate_env(self.env, self.env_context)
# We can't auto-wrap a BaseEnv.
if isinstance(self.env, (BaseEnv, ray.actor.ActorHandle)):
def wrap(env):
return env
# Atari type env and "deepmind" preprocessor pref.
elif is_atari(self.env) and self.config.preprocessor_pref == "deepmind":
# Deepmind wrappers already handle all preprocessing.
self.preprocessing_enabled = False
# If clip_rewards not explicitly set to False, switch it
# on here (clip between -1.0 and 1.0).
if self.config.clip_rewards is None:
clip_rewards = True
# Framestacking is used.
use_framestack = self.config.model.get("framestack") is True
def wrap(env):
env = wrap_deepmind(
env,
dim=self.config.model.get("dim"),
framestack=use_framestack,
noframeskip=self.config.env_config.get("frameskip", 0) == 1,
)
return env
elif self.config.preprocessor_pref is None:
# Only turn off preprocessing
self.preprocessing_enabled = False
def wrap(env):
return env
else:
def wrap(env):
return env
# Wrap env through the correct wrapper.
self.env: EnvType = wrap(self.env)
# Ideally, we would use the same make_sub_env() function below
# to create self.env, but wrap(env) and self.env has a cyclic
# dependency on each other right now, so we would settle on
# duplicating the random seed setting logic for now.
_update_env_seed_if_necessary(self.env, self.seed, self.worker_index, 0)
# Call custom callback function `on_sub_environment_created`.
self.callbacks.on_sub_environment_created(
worker=self,
sub_environment=self.env,
env_context=self.env_context,
)
self.make_sub_env_fn = self._get_make_sub_env_fn(
env_creator, env_context, validate_env, wrap, self.seed
)
self.spaces = spaces
self.default_policy_class = default_policy_class
self.policy_dict, self.is_policy_to_train = self.config.get_multi_agent_setup(
env=self.env,
spaces=self.spaces,
default_policy_class=self.default_policy_class,
)
self.policy_map: Optional[PolicyMap] = None
# TODO(jungong) : clean up after non-connector env_runner is fully deprecated.
self.preprocessors: Dict[PolicyID, Preprocessor] = None
# Check available number of GPUs.
num_gpus = (
self.config.num_gpus
if self.worker_index == 0
else self.config.num_gpus_per_worker
)
# This is only for the old API where local_worker was responsible for learning
if not self.config._enable_new_api_stack:
# Error if we don't find enough GPUs.
if (
ray.is_initialized()
and ray._private.worker._mode() != ray._private.worker.LOCAL_MODE
and not config._fake_gpus
):
devices = []
if self.config.framework_str in ["tf2", "tf"]:
devices = get_tf_gpu_devices()
elif self.config.framework_str == "torch":
devices = list(range(torch.cuda.device_count()))
if len(devices) < num_gpus:
raise RuntimeError(
ERR_MSG_NO_GPUS.format(len(devices), devices)
+ HOWTO_CHANGE_CONFIG
)
# Warn, if running in local-mode and actual GPUs (not faked) are
# requested.
elif (
ray.is_initialized()
and ray._private.worker._mode() == ray._private.worker.LOCAL_MODE
and num_gpus > 0
and not self.config._fake_gpus
):
logger.warning(
"You are running ray with `local_mode=True`, but have "
f"configured {num_gpus} GPUs to be used! In local mode, "
f"Policies are placed on the CPU and the `num_gpus` setting "
f"is ignored."
)
self.filters: Dict[PolicyID, Filter] = defaultdict(NoFilter)
# if RLModule API is enabled, marl_module_spec holds the specs of the RLModules
self.marl_module_spec = None
self._update_policy_map(policy_dict=self.policy_dict)
# Update Policy's view requirements from Model, only if Policy directly
# inherited from base `Policy` class. At this point here, the Policy
# must have it's Model (if any) defined and ready to output an initial
# state.
for pol in self.policy_map.values():
if not pol._model_init_state_automatically_added and not pol.config.get(
"_enable_new_api_stack", False
):
pol._update_model_view_requirements_from_init_state()
self.multiagent: bool = set(self.policy_map.keys()) != {DEFAULT_POLICY_ID}
if self.multiagent and self.env is not None:
if not isinstance(
self.env,
(BaseEnv, ExternalMultiAgentEnv, MultiAgentEnv, ray.actor.ActorHandle),
):
raise ValueError(
f"Have multiple policies {self.policy_map}, but the "
f"env {self.env} is not a subclass of BaseEnv, "
f"MultiAgentEnv, ActorHandle, or ExternalMultiAgentEnv!"
)
if self.worker_index == 0:
logger.info("Built filter map: {}".format(self.filters))
# This RolloutWorker has no env.
if self.env is None:
self.async_env = None
# Use a custom env-vectorizer and call it providing self.env.
elif "custom_vector_env" in self.config:
self.async_env = self.config.custom_vector_env(self.env)
# Default: Vectorize self.env via the make_sub_env function. This adds
# further clones of self.env and creates a RLlib BaseEnv (which is
# vectorized under the hood).
else:
# Always use vector env for consistency even if num_envs_per_worker=1.
self.async_env: BaseEnv = convert_to_base_env(
self.env,
make_env=self.make_sub_env_fn,
num_envs=self.config.num_envs_per_worker,
remote_envs=self.config.remote_worker_envs,
remote_env_batch_wait_ms=self.config.remote_env_batch_wait_ms,
worker=self,
restart_failed_sub_environments=(
self.config.restart_failed_sub_environments
),
)
# `truncate_episodes`: Allow a batch to contain more than one episode
# (fragments) and always make the batch `rollout_fragment_length`
# long.
rollout_fragment_length_for_sampler = configured_rollout_fragment_length
if self.config.batch_mode == "truncate_episodes":
pack = True
# `complete_episodes`: Never cut episodes and sampler will return
# exactly one (complete) episode per poll.
else:
assert self.config.batch_mode == "complete_episodes"
rollout_fragment_length_for_sampler = float("inf")
pack = False
# Create the IOContext for this worker.
self.io_context: IOContext = IOContext(
log_dir, self.config, self.worker_index, self
)
render = False
if self.config.render_env is True and (
self.num_workers == 0 or self.worker_index == 1
):
render = True
if self.env is None:
self.sampler = None
else:
self.sampler = SyncSampler(
worker=self,
env=self.async_env,
clip_rewards=clip_rewards,
rollout_fragment_length=rollout_fragment_length_for_sampler,
count_steps_by=self.config.count_steps_by,
callbacks=self.callbacks,
multiple_episodes_in_batch=pack,
normalize_actions=self.config.normalize_actions,
clip_actions=self.config.clip_actions,
observation_fn=self.config.observation_fn,
sample_collector_class=self.config.sample_collector,
render=render,
)
self.input_reader: InputReader = self._get_input_creator_from_config()(
self.io_context
)
self.output_writer: OutputWriter = self._get_output_creator_from_config()(
self.io_context
)
# The current weights sequence number (version). May remain None for when
# not tracking weights versions.
self.weights_seq_no: Optional[int] = None
logger.debug(
"Created rollout worker with env {} ({}), policies {}".format(
self.async_env, self.env, self.policy_map
)
)
@override(EnvRunner)
def assert_healthy(self):
is_healthy = self.policy_map and self.input_reader and self.output_writer
assert is_healthy, (
f"RolloutWorker {self} (idx={self.worker_index}; "
f"num_workers={self.num_workers}) not healthy!"
)
@override(EnvRunner)
def sample(self, **kwargs) -> SampleBatchType:
"""Returns a batch of experience sampled from this worker.
This method must be implemented by subclasses.
Returns:
A columnar batch of experiences (e.g., tensors) or a MultiAgentBatch.
.. testcode::
:skipif: True
import gymnasium as gym
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
worker = RolloutWorker(
env_creator=lambda _: gym.make("CartPole-v1"),
default_policy_class=PPOTF1Policy,
config=AlgorithmConfig(),
)
print(worker.sample())
.. testoutput::
SampleBatch({"obs": [...], "action": [...], ...})
"""
if self.config.fake_sampler and self.last_batch is not None:
return self.last_batch
elif self.input_reader is None:
raise ValueError(
"RolloutWorker has no `input_reader` object! "
"Cannot call `sample()`. You can try setting "
"`create_env_on_driver` to True."
)
if log_once("sample_start"):
logger.info(
"Generating sample batch of size {}".format(
self.total_rollout_fragment_length
)
)
batches = [self.input_reader.next()]
steps_so_far = (
batches[0].count
if self.config.count_steps_by == "env_steps"
else batches[0].agent_steps()
)
# In truncate_episodes mode, never pull more than 1 batch per env.
# This avoids over-running the target batch size.
if (
self.config.batch_mode == "truncate_episodes"
and not self.config.offline_sampling
):
max_batches = self.config.num_envs_per_worker
else:
max_batches = float("inf")
while steps_so_far < self.total_rollout_fragment_length and (
len(batches) < max_batches
):
batch = self.input_reader.next()
steps_so_far += (
batch.count
if self.config.count_steps_by == "env_steps"
else batch.agent_steps()
)
batches.append(batch)
batch = concat_samples(batches)
self.callbacks.on_sample_end(worker=self, samples=batch)
# Always do writes prior to compression for consistency and to allow
# for better compression inside the writer.
self.output_writer.write(batch)
if log_once("sample_end"):
logger.info("Completed sample batch:\n\n{}\n".format(summarize(batch)))
if self.config.compress_observations:
batch.compress(bulk=self.config.compress_observations == "bulk")
if self.config.fake_sampler:
self.last_batch = batch
return batch
@ray.method(num_returns=2)
def sample_with_count(self) -> Tuple[SampleBatchType, int]:
"""Same as sample() but returns the count as a separate value.
Returns:
A columnar batch of experiences (e.g., tensors) and the
size of the collected batch.
.. testcode::
:skipif: True
import gymnasium as gym
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
worker = RolloutWorker(
env_creator=lambda _: gym.make("CartPole-v1"),
default_policy_class=PPOTFPolicy)
print(worker.sample_with_count())
.. testoutput::
(SampleBatch({"obs": [...], "action": [...], ...}), 3)
"""
batch = self.sample()
return batch, batch.count
def learn_on_batch(self, samples: SampleBatchType) -> Dict:
"""Update policies based on the given batch.
This is the equivalent to apply_gradients(compute_gradients(samples)),
but can be optimized to avoid pulling gradients into CPU memory.
Args:
samples: The SampleBatch or MultiAgentBatch to learn on.
Returns:
Dictionary of extra metadata from compute_gradients().
.. testcode::
:skipif: True
import gymnasium as gym
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
worker = RolloutWorker(
env_creator=lambda _: gym.make("CartPole-v1"),
default_policy_class=PPOTF1Policy)
batch = worker.sample()
info = worker.learn_on_batch(samples)
"""
if log_once("learn_on_batch"):
logger.info(
"Training on concatenated sample batches:\n\n{}\n".format(
summarize(samples)
)
)
info_out = {}
if isinstance(samples, MultiAgentBatch):
builders = {}
to_fetch = {}
for pid, batch in samples.policy_batches.items():
if self.is_policy_to_train is not None and not self.is_policy_to_train(
pid, samples
):
continue
# Decompress SampleBatch, in case some columns are compressed.
batch.decompress_if_needed()
policy = self.policy_map[pid]
tf_session = policy.get_session()
if tf_session and hasattr(policy, "_build_learn_on_batch"):
builders[pid] = _TFRunBuilder(tf_session, "learn_on_batch")
to_fetch[pid] = policy._build_learn_on_batch(builders[pid], batch)
else:
info_out[pid] = policy.learn_on_batch(batch)
info_out.update({pid: builders[pid].get(v) for pid, v in to_fetch.items()})
else:
if self.is_policy_to_train is None or self.is_policy_to_train(
DEFAULT_POLICY_ID, samples
):
info_out.update(
{
DEFAULT_POLICY_ID: self.policy_map[
DEFAULT_POLICY_ID
].learn_on_batch(samples)
}
)
if log_once("learn_out"):
logger.debug("Training out:\n\n{}\n".format(summarize(info_out)))
return info_out
def sample_and_learn(
self,
expected_batch_size: int,
num_sgd_iter: int,
sgd_minibatch_size: str,
standardize_fields: List[str],
) -> Tuple[dict, int]:
"""Sample and batch and learn on it.
This is typically used in combination with distributed allreduce.
Args:
expected_batch_size: Expected number of samples to learn on.
num_sgd_iter: Number of SGD iterations.
sgd_minibatch_size: SGD minibatch size.
standardize_fields: List of sample fields to normalize.
Returns:
A tuple consisting of a dictionary of extra metadata returned from
the policies' `learn_on_batch()` and the number of samples
learned on.
"""
batch = self.sample()
assert batch.count == expected_batch_size, (
"Batch size possibly out of sync between workers, expected:",
expected_batch_size,
"got:",
batch.count,
)
logger.info(
"Executing distributed minibatch SGD "
"with epoch size {}, minibatch size {}".format(
batch.count, sgd_minibatch_size
)
)
info = do_minibatch_sgd(
batch,
self.policy_map,
self,
num_sgd_iter,
sgd_minibatch_size,
standardize_fields,
)
return info, batch.count
def compute_gradients(
self,
samples: SampleBatchType,
single_agent: bool = None,
) -> Tuple[ModelGradients, dict]:
"""Returns a gradient computed w.r.t the specified samples.
Uses the Policy's/ies' compute_gradients method(s) to perform the
calculations. Skips policies that are not trainable as per
`self.is_policy_to_train()`.
Args:
samples: The SampleBatch or MultiAgentBatch to compute gradients
for using this worker's trainable policies.
Returns:
In the single-agent case, a tuple consisting of ModelGradients and
info dict of the worker's policy.
In the multi-agent case, a tuple consisting of a dict mapping
PolicyID to ModelGradients and a dict mapping PolicyID to extra
metadata info.
Note that the first return value (grads) can be applied as is to a
compatible worker using the worker's `apply_gradients()` method.
.. testcode::
:skipif: True
import gymnasium as gym
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
worker = RolloutWorker(
env_creator=lambda _: gym.make("CartPole-v1"),
default_policy_class=PPOTF1Policy)
batch = worker.sample()
grads, info = worker.compute_gradients(samples)
"""
if log_once("compute_gradients"):
logger.info("Compute gradients on:\n\n{}\n".format(summarize(samples)))
if single_agent is True:
samples = convert_ma_batch_to_sample_batch(samples)
grad_out, info_out = self.policy_map[DEFAULT_POLICY_ID].compute_gradients(
samples
)
info_out["batch_count"] = samples.count
return grad_out, info_out
# Treat everything as is multi-agent.
samples = samples.as_multi_agent()
# Calculate gradients for all policies.
grad_out, info_out = {}, {}
if self.config.framework_str == "tf":
for pid, batch in samples.policy_batches.items():
if self.is_policy_to_train is not None and not self.is_policy_to_train(
pid, samples
):
continue
policy = self.policy_map[pid]
builder = _TFRunBuilder(policy.get_session(), "compute_gradients")
grad_out[pid], info_out[pid] = policy._build_compute_gradients(
builder, batch
)
grad_out = {k: builder.get(v) for k, v in grad_out.items()}
info_out = {k: builder.get(v) for k, v in info_out.items()}
else:
for pid, batch in samples.policy_batches.items():
if self.is_policy_to_train is not None and not self.is_policy_to_train(
pid, samples
):
continue
grad_out[pid], info_out[pid] = self.policy_map[pid].compute_gradients(
batch
)
info_out["batch_count"] = samples.count
if log_once("grad_out"):
logger.info("Compute grad info:\n\n{}\n".format(summarize(info_out)))
return grad_out, info_out
def apply_gradients(
self,
grads: Union[ModelGradients, Dict[PolicyID, ModelGradients]],
) -> None:
"""Applies the given gradients to this worker's models.
Uses the Policy's/ies' apply_gradients method(s) to perform the
operations.
Args:
grads: Single ModelGradients (single-agent case) or a dict
mapping PolicyIDs to the respective model gradients
structs.
.. testcode::
:skipif: True
import gymnasium as gym
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.algorithms.ppo.ppo_tf_policy import PPOTF1Policy
worker = RolloutWorker(
env_creator=lambda _: gym.make("CartPole-v1"),
default_policy_class=PPOTF1Policy)
samples = worker.sample()
grads, info = worker.compute_gradients(samples)
worker.apply_gradients(grads)
"""
if log_once("apply_gradients"):
logger.info("Apply gradients:\n\n{}\n".format(summarize(grads)))
# Grads is a dict (mapping PolicyIDs to ModelGradients).
# Multi-agent case.
if isinstance(grads, dict):
for pid, g in grads.items():
if self.is_policy_to_train is None or self.is_policy_to_train(
pid, None
):
self.policy_map[pid].apply_gradients(g)
# Grads is a ModelGradients type. Single-agent case.
elif self.is_policy_to_train is None or self.is_policy_to_train(
DEFAULT_POLICY_ID, None
):
self.policy_map[DEFAULT_POLICY_ID].apply_gradients(grads)