-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
Copy pathalgorithm.py
4476 lines (4020 loc) · 190 KB
/
algorithm.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
from collections import defaultdict
import concurrent
import copy
from datetime import datetime
import functools
import gymnasium as gym
import importlib
import importlib.metadata
import json
import logging
import numpy as np
import os
from packaging import version
import pathlib
import pyarrow.fs
import re
import tempfile
import time
from typing import (
Any,
Callable,
Collection,
DefaultDict,
Dict,
List,
Optional,
Set,
Tuple,
Type,
TYPE_CHECKING,
Union,
)
import tree # pip install dm_tree
import ray
from ray.tune.result import TRAINING_ITERATION
from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag
from ray.actor import ActorHandle
from ray.tune import Checkpoint
import ray.cloudpickle as pickle
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
from ray.rllib.algorithms.registry import ALGORITHMS_CLASS_TO_NAME as ALL_ALGORITHMS
from ray.rllib.algorithms.utils import (
AggregatorActor,
_get_env_runner_bundles,
_get_offline_eval_runner_bundles,
_get_learner_bundles,
_get_main_process_bundle,
)
from ray.rllib.callbacks.utils import make_callback
from ray.rllib.connectors.agent.obs_preproc import ObsPreprocessorConnector
from ray.rllib.connectors.connector_pipeline_v2 import ConnectorPipelineV2
from ray.rllib.core import (
COMPONENT_ENV_RUNNER,
COMPONENT_ENV_TO_MODULE_CONNECTOR,
COMPONENT_EVAL_ENV_RUNNER,
COMPONENT_LEARNER,
COMPONENT_LEARNER_GROUP,
COMPONENT_METRICS_LOGGER,
COMPONENT_MODULE_TO_ENV_CONNECTOR,
COMPONENT_RL_MODULE,
DEFAULT_MODULE_ID,
)
from ray.rllib.core.columns import Columns
from ray.rllib.core.rl_module.multi_rl_module import (
MultiRLModule,
MultiRLModuleSpec,
)
from ray.rllib.core.rl_module import validate_module_id
from ray.rllib.core.rl_module.rl_module import RLModule, RLModuleSpec
from ray.rllib.env import INPUT_ENV_SPACES
from ray.rllib.env.env_context import EnvContext
from ray.rllib.env.env_runner import EnvRunner
from ray.rllib.env.env_runner_group import EnvRunnerGroup
from ray.rllib.env.utils import _gym_env_creator
from ray.rllib.evaluation.metrics import (
collect_episodes,
summarize_episodes,
)
from ray.rllib.execution.rollout_ops import synchronous_parallel_sample
from ray.rllib.offline import get_dataset_and_shards
from ray.rllib.offline.estimators import (
OffPolicyEstimator,
ImportanceSampling,
WeightedImportanceSampling,
DirectMethod,
DoublyRobust,
)
from ray.rllib.offline.offline_evaluator import OfflineEvaluator
from ray.rllib.policy.policy import Policy, PolicySpec
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, SampleBatch
from ray.rllib.utils import deep_update, FilterManager, force_list
from ray.rllib.utils.actor_manager import FaultTolerantActorManager, RemoteCallResults
from ray.rllib.utils.annotations import (
DeveloperAPI,
ExperimentalAPI,
OldAPIStack,
override,
OverrideToImplementCustomLogic,
OverrideToImplementCustomLogic_CallToSuperRecommended,
PublicAPI,
)
from ray.rllib.utils.checkpoints import (
Checkpointable,
CHECKPOINT_VERSION,
CHECKPOINT_VERSION_LEARNER_AND_ENV_RUNNER,
get_checkpoint_info,
try_import_msgpack,
)
from ray.rllib.utils.debug import update_global_seed_if_necessary
from ray.rllib.utils.deprecation import (
DEPRECATED_VALUE,
Deprecated,
deprecation_warning,
)
from ray.rllib.utils.error import ERR_MSG_INVALID_ENV_DESCRIPTOR, EnvError
from ray.rllib.utils.framework import try_import_tf
from ray.rllib.utils.from_config import from_config
from ray.rllib.utils.metrics import (
AGGREGATOR_ACTOR_RESULTS,
ALL_MODULES,
DATASET_NUM_ITERS_EVALUATED,
ENV_RUNNER_RESULTS,
ENV_RUNNER_SAMPLING_TIMER,
EPISODE_LEN_MEAN,
EPISODE_RETURN_MEAN,
EVALUATION_ITERATION_TIMER,
EVALUATION_RESULTS,
FAULT_TOLERANCE_STATS,
LEARNER_RESULTS,
LEARNER_UPDATE_TIMER,
NUM_AGENT_STEPS_SAMPLED,
NUM_AGENT_STEPS_SAMPLED_LIFETIME,
NUM_AGENT_STEPS_SAMPLED_THIS_ITER,
NUM_AGENT_STEPS_TRAINED,
NUM_AGENT_STEPS_TRAINED_LIFETIME,
NUM_ENV_STEPS_SAMPLED,
NUM_ENV_STEPS_SAMPLED_LIFETIME,
NUM_ENV_STEPS_SAMPLED_THIS_ITER,
NUM_ENV_STEPS_SAMPLED_FOR_EVALUATION_THIS_ITER,
NUM_ENV_STEPS_TRAINED,
NUM_ENV_STEPS_TRAINED_LIFETIME,
NUM_EPISODES,
NUM_EPISODES_LIFETIME,
NUM_TRAINING_STEP_CALLS_PER_ITERATION,
OFFLINE_EVAL_RUNNER_RESULTS,
OFFLINE_EVALUATION_ITERATION_TIMER,
RESTORE_ENV_RUNNERS_TIMER,
RESTORE_EVAL_ENV_RUNNERS_TIMER,
RESTORE_OFFLINE_EVAL_RUNNERS_TIMER,
SYNCH_ENV_CONNECTOR_STATES_TIMER,
SYNCH_EVAL_ENV_CONNECTOR_STATES_TIMER,
SYNCH_WORKER_WEIGHTS_TIMER,
TIMERS,
TRAINING_ITERATION_TIMER,
TRAINING_STEP_TIMER,
STEPS_TRAINED_THIS_ITER_COUNTER,
)
from ray.rllib.utils.metrics.learner_info import LEARNER_INFO
from ray.rllib.utils.metrics.metrics_logger import MetricsLogger
from ray.rllib.utils.metrics.stats import Stats
from ray.rllib.utils.replay_buffers import MultiAgentReplayBuffer, ReplayBuffer
from ray.rllib.utils.runners.runner_group import RunnerGroup
from ray.rllib.utils.serialization import deserialize_type, NOT_SERIALIZABLE
from ray.rllib.utils.spaces import space_utils
from ray.rllib.utils.typing import (
AgentConnectorDataType,
AgentID,
AgentToModuleMappingFn,
AlgorithmConfigDict,
EnvCreator,
EnvInfoDict,
EnvType,
EpisodeID,
ModuleID,
PartialAlgorithmConfigDict,
PolicyID,
PolicyState,
ResultDict,
SampleBatchType,
ShouldModuleBeUpdatedFn,
StateDict,
TensorStructType,
TensorType,
)
from ray.train.constants import DEFAULT_STORAGE_PATH
from ray.tune.execution.placement_groups import PlacementGroupFactory
from ray.tune.experiment.trial import ExportFormat
from ray.tune.logger import Logger, UnifiedLogger
from ray.tune.registry import ENV_CREATOR, _global_registry
from ray.tune.resources import Resources
from ray.tune.trainable import Trainable
from ray.util import log_once
from ray.util.timer import _Timer
from ray.tune.registry import get_trainable_cls
if TYPE_CHECKING:
from ray.rllib.core.learner.learner_group import LearnerGroup
from ray.rllib.offline.offline_data import OfflineData
tf1, tf, tfv = try_import_tf()
logger = logging.getLogger(__name__)
@PublicAPI
class Algorithm(Checkpointable, Trainable):
"""An RLlib algorithm responsible for training one or more neural network models.
You can write your own Algorithm classes by sub-classing from `Algorithm`
or any of its built-in subclasses.
Override the `training_step` method to implement your own algorithm logic.
Find the various built-in `training_step()` methods for different algorithms in
their respective [algo name].py files, for example:
`ray.rllib.algorithms.dqn.dqn.py` or `ray.rllib.algorithms.impala.impala.py`.
The most important API methods an Algorithm exposes are `train()` for running a
single training iteration, `evaluate()` for running a single round of evaluation,
`save_to_path()` for creating a checkpoint, and `restore_from_path()` for loading a
state from an existing checkpoint.
"""
#: The AlgorithmConfig instance of the Algorithm.
config: Optional[AlgorithmConfig] = None
#: The MetricsLogger instance of the Algorithm. RLlib uses this to log
#: metrics from within the `training_step()` method. Users can use it to log
#: metrics from within their custom Algorithm-based callbacks.
metrics: Optional[MetricsLogger] = None
#: The `EnvRunnerGroup` of the Algorithm. An `EnvRunnerGroup` is
#: composed of a single local `EnvRunner` (see: `self.env_runner`), serving as
#: the reference copy of the models to be trained and optionally one or more
#: remote `EnvRunners` used to generate training samples from the RL
#: environment, in parallel. EnvRunnerGroup is fault-tolerant and elastic. It
#: tracks health states for all the managed remote EnvRunner actors. As a
#: result, Algorithm should never access the underlying actor handles directly.
#: Instead, always access them via all the foreach APIs with assigned IDs of
#: the underlying EnvRunners.
env_runner_group: Optional[EnvRunnerGroup] = None
#: A special EnvRunnerGroup only used for evaluation, not to
#: collect training samples.
eval_env_runner_group: Optional[EnvRunnerGroup] = None
#: The `LearnerGroup` instance of the Algorithm, managing either
#: one local `Learner` or one or more remote `Learner` actors. Responsible for
#: updating the models from RL environment (episode) data.
learner_group: Optional["LearnerGroup"] = None
#: An optional OfflineData instance, used for offline RL.
offline_data: Optional["OfflineData"] = None
# Whether to allow unknown top-level config keys.
_allow_unknown_configs = False
# List of top-level keys with value=dict, for which new sub-keys are
# allowed to be added to the value dict.
_allow_unknown_subkeys = [
"tf_session_args",
"local_tf_session_args",
"env_config",
"model",
"optimizer",
"custom_resources_per_env_runner",
"custom_resources_per_worker",
"evaluation_config",
"exploration_config",
"replay_buffer_config",
"extra_python_environs_for_worker",
"input_config",
"output_config",
]
# List of top level keys with value=dict, for which we always override the
# entire value (dict), iff the "type" key in that value dict changes.
_override_all_subkeys_if_type_changes = [
"exploration_config",
"replay_buffer_config",
]
# List of keys that are always fully overridden if present in any dict or sub-dict
_override_all_key_list = ["off_policy_estimation_methods", "policies"]
_progress_metrics = (
f"{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}",
f"{EVALUATION_RESULTS}/{ENV_RUNNER_RESULTS}/{EPISODE_RETURN_MEAN}",
f"{NUM_ENV_STEPS_SAMPLED_LIFETIME}",
f"{NUM_ENV_STEPS_TRAINED_LIFETIME}",
f"{NUM_EPISODES_LIFETIME}",
f"{ENV_RUNNER_RESULTS}/{EPISODE_LEN_MEAN}",
)
# Backward compatibility with old checkpoint system (now through the
# `Checkpointable` API).
METADATA_FILE_NAME = "rllib_checkpoint.json"
STATE_FILE_NAME = "algorithm_state"
@classmethod
@override(Checkpointable)
def from_checkpoint(
cls,
path: Union[str, Checkpoint],
filesystem: Optional["pyarrow.fs.FileSystem"] = None,
*,
# @OldAPIStack
policy_ids: Optional[Collection[PolicyID]] = None,
policy_mapping_fn: Optional[Callable[[AgentID, EpisodeID], PolicyID]] = None,
policies_to_train: Optional[
Union[
Collection[PolicyID],
Callable[[PolicyID, Optional[SampleBatchType]], bool],
]
] = None,
# deprecated args
checkpoint=DEPRECATED_VALUE,
**kwargs,
) -> "Algorithm":
"""Creates a new algorithm instance from a given checkpoint.
Args:
path: The path (str) to the checkpoint directory to use or a Ray Train
Checkpoint instance to restore from.
filesystem: PyArrow FileSystem to use to access data at the `path`. If not
specified, this is inferred from the URI scheme of `path`.
policy_ids: Optional list of PolicyIDs to recover. This allows users to
restore an Algorithm with only a subset of the originally present
Policies.
policy_mapping_fn: An optional (updated) policy mapping function to use from
here on.
policies_to_train: An optional list of policy IDs to be trained or a
callable taking PolicyID and SampleBatchType and returning a bool
(trainable or not?). If None, will keep the existing setup in place.
Policies, whose IDs are not in the list (or for which the callable
returns False) will not be updated.
Returns:
The instantiated Algorithm.
"""
if checkpoint != DEPRECATED_VALUE:
deprecation_warning(
old="Algorithm.from_checkpoint(checkpoint=...)",
new="Algorithm.from_checkpoint(path=...)",
error=True,
)
checkpoint_info = get_checkpoint_info(path)
# New API stack -> Use Checkpointable's default implementation.
if checkpoint_info["checkpoint_version"] >= version.Version("2.0"):
# `path` is a Checkpoint instance: Translate to directory and continue.
if isinstance(path, Checkpoint):
path = path.to_directory()
return super().from_checkpoint(path, filesystem=filesystem, **kwargs)
# Not possible for (v0.1) (algo class and config information missing
# or very hard to retrieve).
elif checkpoint_info["checkpoint_version"] == version.Version("0.1"):
raise ValueError(
"Cannot restore a v0 checkpoint using `Algorithm.from_checkpoint()`!"
"In this case, do the following:\n"
"1) Create a new Algorithm object using your original config.\n"
"2) Call the `restore()` method of this algo object passing it"
" your checkpoint dir or AIR Checkpoint object."
)
elif checkpoint_info["checkpoint_version"] < version.Version("1.0"):
raise ValueError(
"`checkpoint_info['checkpoint_version']` in `Algorithm.from_checkpoint"
"()` must be 1.0 or later! You are using a checkpoint with "
f"version v{checkpoint_info['checkpoint_version']}."
)
# This is a msgpack checkpoint.
if checkpoint_info["format"] == "msgpack":
# User did not provide unserializable function with this call
# (`policy_mapping_fn`). Note that if `policies_to_train` is None, it
# defaults to training all policies (so it's ok to not provide this here).
if policy_mapping_fn is None:
# Only DEFAULT_POLICY_ID present in this algorithm, provide default
# implementations of these two functions.
if checkpoint_info["policy_ids"] == {DEFAULT_POLICY_ID}:
policy_mapping_fn = AlgorithmConfig.DEFAULT_POLICY_MAPPING_FN
# Provide meaningful error message.
else:
raise ValueError(
"You are trying to restore a multi-agent algorithm from a "
"`msgpack` formatted checkpoint, which do NOT store the "
"`policy_mapping_fn` or `policies_to_train` "
"functions! Make sure that when using the "
"`Algorithm.from_checkpoint()` utility, you also pass the "
"args: `policy_mapping_fn` and `policies_to_train` with your "
"call. You might leave `policies_to_train=None` in case "
"you would like to train all policies anyways."
)
state = Algorithm._checkpoint_info_to_algorithm_state(
checkpoint_info=checkpoint_info,
policy_ids=policy_ids,
policy_mapping_fn=policy_mapping_fn,
policies_to_train=policies_to_train,
)
return Algorithm.from_state(state)
@PublicAPI
def __init__(
self,
config: Optional[AlgorithmConfig] = None,
env=None, # deprecated arg
logger_creator: Optional[Callable[[], Logger]] = None,
**kwargs,
):
"""Initializes an Algorithm instance.
Args:
config: Algorithm-specific configuration object.
logger_creator: Callable that creates a ray.tune.Logger
object. If unspecified, a default logger is created.
**kwargs: Arguments passed to the Trainable base class.
"""
# Translate possible dict into an AlgorithmConfig object, as well as,
# resolving generic config objects into specific ones (e.g. passing
# an `AlgorithmConfig` super-class instance into a PPO constructor,
# which normally would expect a PPOConfig object).
if isinstance(config, dict):
default_config = self.get_default_config()
# `self.get_default_config()` also returned a dict ->
# Last resort: Create core AlgorithmConfig from merged dicts.
if isinstance(default_config, dict):
if "class" in config:
AlgorithmConfig.from_state(config)
else:
config = AlgorithmConfig.from_dict(
config_dict=self.merge_algorithm_configs(
default_config, config, True
)
)
# Default config is an AlgorithmConfig -> update its properties
# from the given config dict.
else:
if isinstance(config, dict) and "class" in config:
config = default_config.from_state(config)
else:
config = default_config.update_from_dict(config)
else:
default_config = self.get_default_config()
# Given AlgorithmConfig is not of the same type as the default config:
# This could be the case e.g. if the user is building an algo from a
# generic AlgorithmConfig() object.
if not isinstance(config, type(default_config)):
config = default_config.update_from_dict(config.to_dict())
else:
config = default_config.from_state(config.get_state())
# In case this algo is using a generic config (with no algo_class set), set it
# here.
if config.algo_class is None:
config.algo_class = type(self)
if env is not None:
deprecation_warning(
old=f"algo = Algorithm(env='{env}', ...)",
new=f"algo = AlgorithmConfig().environment('{env}').build()",
error=False,
)
config.environment(env)
# Validate and freeze our AlgorithmConfig object (no more changes possible).
config.validate()
config.freeze()
# Convert `env` provided in config into a concrete env creator callable, which
# takes an EnvContext (config dict) as arg and returning an RLlib supported Env
# type (e.g. a gym.Env).
self._env_id, self.env_creator = self._get_env_id_and_creator(
config.env, config
)
env_descr = (
self._env_id.__name__ if isinstance(self._env_id, type) else self._env_id
)
# Placeholder for a local replay buffer instance.
self.local_replay_buffer = None
# Placeholder for our LearnerGroup responsible for updating the RLModule(s).
self.learner_group: Optional["LearnerGroup"] = None
# The Algorithm's `MetricsLogger` object to collect stats from all its
# components (including timers, counters and other stats in its own
# `training_step()` and other methods) as well as custom callbacks.
self.metrics = MetricsLogger()
# Create a default logger creator if no logger_creator is specified
if logger_creator is None:
# Default logdir prefix containing the agent's name and the
# env id.
timestr = datetime.today().strftime("%Y-%m-%d_%H-%M-%S")
env_descr_for_dir = re.sub("[/\\\\]", "-", str(env_descr))
logdir_prefix = f"{type(self).__name__}_{env_descr_for_dir}_{timestr}"
if not os.path.exists(DEFAULT_STORAGE_PATH):
# Possible race condition if dir is created several times on
# rollout workers
os.makedirs(DEFAULT_STORAGE_PATH, exist_ok=True)
logdir = tempfile.mkdtemp(prefix=logdir_prefix, dir=DEFAULT_STORAGE_PATH)
# Allow users to more precisely configure the created logger
# via "logger_config.type".
if config.logger_config and "type" in config.logger_config:
def default_logger_creator(config):
"""Creates a custom logger with the default prefix."""
cfg = config["logger_config"].copy()
cls = cfg.pop("type")
# Provide default for logdir, in case the user does
# not specify this in the "logger_config" dict.
logdir_ = cfg.pop("logdir", logdir)
return from_config(cls=cls, _args=[cfg], logdir=logdir_)
# If no `type` given, use tune's UnifiedLogger as last resort.
else:
def default_logger_creator(config):
"""Creates a Unified logger with the default prefix."""
return UnifiedLogger(config, logdir, loggers=None)
logger_creator = default_logger_creator
# Metrics-related properties.
self._timers = defaultdict(_Timer)
self._counters = defaultdict(int)
self._episode_history = []
self._episodes_to_be_collected = []
# The fully qualified AlgorithmConfig used for evaluation
# (or None if evaluation not setup).
self.evaluation_config: Optional[AlgorithmConfig] = None
# Evaluation EnvRunnerGroup and metrics last returned by `self.evaluate()`.
self.eval_env_runner_group: Optional[EnvRunnerGroup] = None
super().__init__(
config=config,
logger_creator=logger_creator,
**kwargs,
)
@OverrideToImplementCustomLogic
@classmethod
def get_default_config(cls) -> AlgorithmConfig:
return AlgorithmConfig()
@OverrideToImplementCustomLogic
def _remote_worker_ids_for_metrics(self) -> List[int]:
"""Returns a list of remote worker IDs to fetch metrics from.
Specific Algorithm implementations can override this method to
use a subset of the workers for metrics collection.
Returns:
List of remote worker IDs to fetch metrics from.
"""
return self.env_runner_group.healthy_worker_ids()
@OverrideToImplementCustomLogic_CallToSuperRecommended
@override(Trainable)
def setup(self, config: AlgorithmConfig) -> None:
# Setup our config: Merge the user-supplied config dict (which could
# be a partial config dict) with the class' default.
if not isinstance(config, AlgorithmConfig):
assert isinstance(config, PartialAlgorithmConfigDict)
config_obj = self.get_default_config()
if not isinstance(config_obj, AlgorithmConfig):
assert isinstance(config, PartialAlgorithmConfigDict)
config_obj = AlgorithmConfig().from_dict(config_obj)
config_obj.update_from_dict(config)
config_obj.env = self._env_id
self.config = config_obj
# Set Algorithm's seed after we have - if necessary - enabled
# tf eager-execution.
update_global_seed_if_necessary(self.config.framework_str, self.config.seed)
self._record_usage(self.config)
# Create the callbacks object.
if self.config.enable_env_runner_and_connector_v2:
self.callbacks = [cls() for cls in force_list(self.config.callbacks_class)]
else:
self.callbacks = self.config.callbacks_class()
if self.config.log_level in ["WARN", "ERROR"]:
logger.info(
f"Current log_level is {self.config.log_level}. For more information, "
"set 'log_level': 'INFO' / 'DEBUG' or use the -v and "
"-vv flags."
)
if self.config.log_level:
logging.getLogger("ray.rllib").setLevel(self.config.log_level)
# Create local replay buffer if necessary.
self.local_replay_buffer = self._create_local_replay_buffer_if_necessary(
self.config
)
# Create a dict, mapping ActorHandles to sets of open remote
# requests (object refs). This way, we keep track, of which actors
# inside this Algorithm (e.g. a remote EnvRunner) have
# already been sent how many (e.g. `sample()`) requests.
self.remote_requests_in_flight: DefaultDict[
ActorHandle, Set[ray.ObjectRef]
] = defaultdict(set)
self.env_runner_group: Optional[EnvRunnerGroup] = None
# In case there is no local EnvRunner anymore, we need to handle connector
# pipelines directly here.
self.spaces: Optional[Dict] = None
self.env_to_module_connector: Optional[ConnectorPipelineV2] = None
self.module_to_env_connector: Optional[ConnectorPipelineV2] = None
# Offline RL settings.
input_evaluation = self.config.get("input_evaluation")
if input_evaluation is not None and input_evaluation is not DEPRECATED_VALUE:
ope_dict = {str(ope): {"type": ope} for ope in input_evaluation}
deprecation_warning(
old="config.input_evaluation={}".format(input_evaluation),
new="config.evaluation(evaluation_config=config.overrides("
f"off_policy_estimation_methods={ope_dict}"
"))",
error=True,
help="Running OPE during training is not recommended.",
)
self.config.off_policy_estimation_methods = ope_dict
# If an input path is available and we are on the new API stack generate
# an `OfflineData` instance.
if self.config.is_offline:
from ray.rllib.offline.offline_data import OfflineData
# Use either user-provided `OfflineData` class or RLlib's default.
offline_data_class = self.config.offline_data_class or OfflineData
# Build the `OfflineData` class.
self.offline_data = offline_data_class(self.config)
# Otherwise set the attribute to `None`.
else:
self.offline_data = None
if not self.offline_data:
# Create a set of env runner actors via a EnvRunnerGroup.
self.env_runner_group = EnvRunnerGroup(
env_creator=self.env_creator,
validate_env=self.validate_env,
default_policy_class=self.get_default_policy_class(self.config),
config=self.config,
# New API stack: User decides whether to create local env runner.
# Old API stack: Always create local EnvRunner.
local_env_runner=(
True
if not self.config.enable_env_runner_and_connector_v2
else self.config.create_local_env_runner
),
logdir=self.logdir,
tune_trial_id=self.trial_id,
)
# Compile, validate, and freeze an evaluation config.
self.evaluation_config = self.config.get_evaluation_config_object()
self.evaluation_config.validate()
self.evaluation_config.freeze()
# Evaluation EnvRunnerGroup setup.
# User would like to setup a separate evaluation worker set.
# Note: We skip EnvRunnerGroup creation if we need to do offline evaluation.
if self._should_create_evaluation_env_runners(self.evaluation_config):
_, env_creator = self._get_env_id_and_creator(
self.evaluation_config.env, self.evaluation_config
)
# Create a separate evaluation worker set for evaluation.
# If evaluation_num_env_runners=0, use the evaluation set's local
# worker for evaluation, otherwise, use its remote workers
# (parallelized evaluation).
self.eval_env_runner_group: EnvRunnerGroup = EnvRunnerGroup(
env_creator=env_creator,
validate_env=None,
default_policy_class=self.get_default_policy_class(self.config),
config=self.evaluation_config,
logdir=self.logdir,
tune_trial_id=self.trial_id,
# New API stack: User decides whether to create local env runner.
# Old API stack: Always create local EnvRunner.
local_env_runner=(
True
if not self.evaluation_config.enable_env_runner_and_connector_v2
else self.evaluation_config.create_local_env_runner
),
pg_offset=self.config.num_env_runners,
)
if self.env_runner_group:
self.spaces = self.env_runner_group.get_spaces()
elif self.eval_env_runner_group:
self.spaces = self.eval_env_runner_group.get_spaces()
if self.env_runner is None and self.spaces is not None:
self.env_to_module_connector = self.config.build_env_to_module_connector(
spaces=self.spaces
)
self.module_to_env_connector = self.config.build_module_to_env_connector(
spaces=self.spaces
)
self.evaluation_dataset = None
if (
self.evaluation_config.off_policy_estimation_methods
and not self.evaluation_config.ope_split_batch_by_episode
):
# the num worker is set to 0 to avoid creating shards. The dataset will not
# be repartioned to num_workers blocks.
logger.info("Creating evaluation dataset ...")
self.evaluation_dataset, _ = get_dataset_and_shards(
self.evaluation_config, num_workers=0
)
logger.info("Evaluation dataset created")
self.reward_estimators: Dict[str, OffPolicyEstimator] = {}
ope_types = {
"is": ImportanceSampling,
"wis": WeightedImportanceSampling,
"dm": DirectMethod,
"dr": DoublyRobust,
}
for name, method_config in self.config.off_policy_estimation_methods.items():
method_type = method_config.pop("type")
if method_type in ope_types:
deprecation_warning(
old=method_type,
new=str(ope_types[method_type]),
error=True,
)
method_type = ope_types[method_type]
elif isinstance(method_type, str):
logger.log(0, "Trying to import from string: " + method_type)
mod, obj = method_type.rsplit(".", 1)
mod = importlib.import_module(mod)
method_type = getattr(mod, obj)
if isinstance(method_type, type) and issubclass(
method_type, OfflineEvaluator
):
# TODO(kourosh) : Add an integration test for all these
# offline evaluators.
policy = self.get_policy()
if issubclass(method_type, OffPolicyEstimator):
method_config["gamma"] = self.config.gamma
self.reward_estimators[name] = method_type(policy, **method_config)
else:
raise ValueError(
f"Unknown off_policy_estimation type: {method_type}! Must be "
"either a class path or a sub-class of ray.rllib."
"offline.offline_evaluator::OfflineEvaluator"
)
# TODO (Rohan138): Refactor this and remove deprecated methods
# Need to add back method_type in case Algorithm is restored from checkpoint
method_config["type"] = method_type
if self.config.enable_rl_module_and_learner:
spaces = {
INPUT_ENV_SPACES: (
self.config.observation_space,
self.config.action_space,
)
}
if self.env_runner_group:
spaces.update(self.spaces)
elif self.eval_env_runner_group:
spaces.update(self.eval_env_runner_group.get_spaces())
else:
spaces.update(
{
DEFAULT_MODULE_ID: (
self.config.observation_space,
self.config.action_space,
),
}
)
module_spec: MultiRLModuleSpec = self.config.get_multi_rl_module_spec(
spaces=spaces,
inference_only=False,
)
self.learner_group = self.config.build_learner_group(
rl_module_spec=module_spec
)
# Check if there are modules to load from the `module_spec`.
rl_module_ckpt_dirs = {}
multi_rl_module_ckpt_dir = module_spec.load_state_path
modules_to_load = module_spec.modules_to_load
for module_id, sub_module_spec in module_spec.rl_module_specs.items():
if sub_module_spec.load_state_path:
rl_module_ckpt_dirs[module_id] = sub_module_spec.load_state_path
if multi_rl_module_ckpt_dir or rl_module_ckpt_dirs:
self.learner_group.load_module_state(
multi_rl_module_ckpt_dir=multi_rl_module_ckpt_dir,
modules_to_load=modules_to_load,
rl_module_ckpt_dirs=rl_module_ckpt_dirs,
)
# Sync the weights from the learner group to the EnvRunners.
rl_module_state = self.learner_group.get_state(
components=COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE,
inference_only=True,
)[COMPONENT_LEARNER]
if self.env_runner_group:
self.env_runner_group.sync_env_runner_states(
config=self.config,
env_steps_sampled=self.metrics.peek(
(ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0
),
rl_module_state=rl_module_state,
env_to_module=self.env_to_module_connector,
module_to_env=self.module_to_env_connector,
)
elif self.eval_env_runner_group:
self.eval_env_runner_group.sync_env_runner_states(
config=self.evaluation_config,
env_steps_sampled=self.metrics.peek(
(ENV_RUNNER_RESULTS, NUM_ENV_STEPS_SAMPLED_LIFETIME), default=0
),
rl_module_state=rl_module_state,
env_to_module=self.env_to_module_connector,
module_to_env=self.module_to_env_connector,
)
# TODO (simon): Update modules in DataWorkers.
if self.offline_data:
# If the learners are remote we need to provide specific
# information and the learner's actor handles.
if self.learner_group.is_remote:
# If learners run on different nodes, locality hints help
# to use the nearest learner in the workers that do the
# data preprocessing.
learner_node_ids = self.learner_group.foreach_learner(
lambda _: ray.get_runtime_context().get_node_id()
)
self.offline_data.locality_hints = [
node_id.get() for node_id in learner_node_ids
]
# Provide the actor handles for the learners for module
# updating during preprocessing.
self.offline_data.learner_handles = self.learner_group._workers
# Otherwise we can simply pass in the local learner.
else:
self.offline_data.learner_handles = [self.learner_group._learner]
# TODO (simon, sven): Replace these set-some-object's-attributes-
# directly? We should find some solution for this in the future, an API,
# or setting these in the OfflineData constructor?
# Provide the module_spec. Note, in the remote case this is needed
# because the learner module cannot be copied, but must be built.
self.offline_data.module_spec = module_spec
# Provide the `OfflineData` instance with space information. It might
# need it for reading recorded experiences.
self.offline_data.spaces = spaces
if self._should_create_offline_evaluation_runners(self.evaluation_config):
from ray.rllib.offline.offline_evaluation_runner_group import (
OfflineEvaluationRunnerGroup,
)
# If no inference-only `RLModule` should be used in offline evaluation,
# get the complete learner module.
if not self.evaluation_config.offline_eval_rl_module_inference_only:
rl_module_state = self.learner_group.get_state(
components=COMPONENT_LEARNER + "/" + COMPONENT_RL_MODULE,
inference_only=False,
)[COMPONENT_LEARNER]
# Create the offline evaluation runner group.
self.offline_eval_runner_group: OfflineEvaluationRunnerGroup = OfflineEvaluationRunnerGroup(
config=self.evaluation_config,
# Do not create a local runner such that the dataset can be split.
local_runner=False,
# Provide the `RLModule`'s state for the `OfflinePreLearner`s.
module_state=rl_module_state[COMPONENT_RL_MODULE],
module_spec=module_spec,
# Note, even if no environment is run, the `MultiRLModule` needs
# spaces to construct the policy network.
spaces=spaces,
)
# Create an Aggregator actor set, if necessary.
self._aggregator_actor_manager = None
if self.config.enable_rl_module_and_learner and (
self.config.num_aggregator_actors_per_learner > 0
):
rl_module_spec = self.config.get_multi_rl_module_spec(
spaces=self.spaces,
inference_only=False,
)
agg_cls = ray.remote(
num_cpus=1,
# TODO (sven): Activate this when Ray has figured out GPU pre-loading.
# num_gpus=0.01 if self.config.num_gpus_per_learner > 0 else 0,
max_restarts=-1,
)(AggregatorActor)
self._aggregator_actor_manager = FaultTolerantActorManager(
[
agg_cls.remote(self.config, rl_module_spec)
for _ in range(
(self.config.num_learners or 1)
* self.config.num_aggregator_actors_per_learner
)
],
max_remote_requests_in_flight_per_actor=(
self.config.max_requests_in_flight_per_aggregator_actor
),
)
# Get the devices of each learner.
learner_locations = list(
enumerate(
self.learner_group.foreach_learner(
func=lambda _learner: (_learner.node, _learner.device),
)
)
)
# Get the devices of each AggregatorActor.
aggregator_locations = list(
enumerate(
self._aggregator_actor_manager.foreach_actor(
func=lambda actor: (actor._node, actor._device)
)
)
)
self._aggregator_actor_to_learner = {}
for agg_idx, aggregator_location in aggregator_locations:
aggregator_location = aggregator_location.get()
for learner_idx, learner_location in learner_locations:
# TODO (sven): Activate full comparison (including device) when Ray
# has figured out GPU pre-loading.
if learner_location.get()[0] == aggregator_location[0]:
# Round-robin, in case all Learners are on same device/node.
learner_locations = learner_locations[1:] + [
learner_locations[0]
]
self._aggregator_actor_to_learner[agg_idx] = learner_idx
break
if agg_idx not in self._aggregator_actor_to_learner:
raise RuntimeError(
"No Learner worker found that matches aggregation worker "
f"#{agg_idx}'s node ({aggregator_location[0]}) and device "
f"({aggregator_location[1]})! The Learner workers' locations "
f"are {learner_locations}."
)
# Make sure, each Learner index is mapped to from at least one
# AggregatorActor.
if not all(
learner_idx in self._aggregator_actor_to_learner.values()
for learner_idx in range(self.config.num_learners or 1)
):
raise RuntimeError(
"Some Learner indices are not mapped to from any AggregatorActors! "
"Final AggregatorActor idx -> Learner idx mapping is: "
f"{self._aggregator_actor_to_learner}"
)
# Run `on_algorithm_init` callback after initialization is done.
make_callback(
"on_algorithm_init",
self.callbacks,
self.config.callbacks_on_algorithm_init,
kwargs=dict(
algorithm=self,
metrics_logger=self.metrics,
),
)
@OverrideToImplementCustomLogic
@classmethod
def get_default_policy_class(
cls,
config: AlgorithmConfig,
) -> Optional[Type[Policy]]:
"""Returns a default Policy class to use, given a config.
This class will be used by an Algorithm in case
the policy class is not provided by the user in any single- or
multi-agent PolicySpec.
Note: This method is ignored when the RLModule API is enabled.
"""
return None
@override(Trainable)
def step(self) -> ResultDict:
"""Implements the main `Algorithm.train()` logic.
Takes n attempts to perform a single training step. Thereby
catches RayErrors resulting from worker failures. After n attempts,
fails gracefully.
Override this method in your Algorithm sub-classes if you would like to
handle worker failures yourself.
Otherwise, override only `training_step()` to implement the core
algorithm logic.