-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
algorithm_config.py
5487 lines (5022 loc) · 266 KB
/
algorithm_config.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 dataclasses
from enum import Enum
import inspect
import logging
import math
import sys
from typing import (
Any,
Callable,
Collection,
Dict,
List,
Optional,
Tuple,
Type,
TYPE_CHECKING,
Union,
)
import gymnasium as gym
import tree
from packaging import version
import ray
from ray.rllib.algorithms.callbacks import DefaultCallbacks
from ray.rllib.core import DEFAULT_MODULE_ID
from ray.rllib.core.columns import Columns
from ray.rllib.core.rl_module import validate_module_id
from ray.rllib.core.rl_module.default_model_config import DefaultModelConfig
from ray.rllib.core.rl_module.multi_rl_module import MultiRLModuleSpec
from ray.rllib.core.rl_module.rl_module import RLModuleSpec
from ray.rllib.env import INPUT_ENV_SPACES
from ray.rllib.env.env_context import EnvContext
from ray.rllib.env.multi_agent_env import MultiAgentEnv
from ray.rllib.env.wrappers.atari_wrappers import is_atari
from ray.rllib.evaluation.collectors.sample_collector import SampleCollector
from ray.rllib.evaluation.collectors.simple_list_collector import SimpleListCollector
from ray.rllib.models import MODEL_DEFAULTS
from ray.rllib.offline.input_reader import InputReader
from ray.rllib.offline.io_context import IOContext
from ray.rllib.policy.policy import Policy, PolicySpec
from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID
from ray.rllib.utils import deep_update, merge_dicts
from ray.rllib.utils.annotations import (
OldAPIStack,
OverrideToImplementCustomLogic_CallToSuperRecommended,
)
from ray.rllib.utils.deprecation import (
DEPRECATED_VALUE,
Deprecated,
deprecation_warning,
)
from ray.rllib.utils.framework import try_import_tf, try_import_torch
from ray.rllib.utils.from_config import NotProvided, from_config
from ray.rllib.utils.schedules.scheduler import Scheduler
from ray.rllib.utils.serialization import (
NOT_SERIALIZABLE,
deserialize_type,
serialize_type,
)
from ray.rllib.utils.test_utils import check
from ray.rllib.utils.torch_utils import TORCH_COMPILE_REQUIRED_VERSION
from ray.rllib.utils.typing import (
AgentID,
AlgorithmConfigDict,
EnvConfigDict,
EnvType,
LearningRateOrSchedule,
ModuleID,
MultiAgentPolicyConfigDict,
PartialAlgorithmConfigDict,
PolicyID,
ResultDict,
RLModuleSpecType,
SampleBatchType,
)
from ray.tune.logger import Logger
from ray.tune.registry import get_trainable_cls
from ray.tune.result import TRIAL_INFO
from ray.tune.tune import _Config
Space = gym.Space
"""TODO(jungong, sven): in "offline_data" we can potentially unify all input types
under input and input_config keys. E.g.
input: sample
input_config {
env: CartPole-v1
}
or:
input: json_reader
input_config {
path: /tmp/
}
or:
input: dataset
input_config {
format: parquet
path: /tmp/
}
"""
if TYPE_CHECKING:
from ray.rllib.algorithms.algorithm import Algorithm
from ray.rllib.connectors.connector_v2 import ConnectorV2
from ray.rllib.core.learner import Learner
from ray.rllib.core.learner.learner_group import LearnerGroup
from ray.rllib.core.rl_module.rl_module import RLModule
from ray.rllib.utils.typing import EpisodeType
logger = logging.getLogger(__name__)
def _check_rl_module_spec(module_spec: RLModuleSpecType) -> None:
if not isinstance(module_spec, (RLModuleSpec, MultiRLModuleSpec)):
raise ValueError(
"rl_module_spec must be an instance of "
"RLModuleSpec or MultiRLModuleSpec."
f"Got {type(module_spec)} instead."
)
class AlgorithmConfig(_Config):
"""A RLlib AlgorithmConfig builds an RLlib Algorithm from a given configuration.
.. testcode::
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.algorithms.callbacks import MemoryTrackingCallbacks
# Construct a generic config object, specifying values within different
# sub-categories, e.g. "training".
config = (PPOConfig().training(gamma=0.9, lr=0.01)
.environment(env="CartPole-v1")
.resources(num_gpus=0)
.env_runners(num_env_runners=0)
.callbacks(MemoryTrackingCallbacks)
)
# A config object can be used to construct the respective Algorithm.
rllib_algo = config.build()
.. testcode::
from ray.rllib.algorithms.ppo import PPOConfig
from ray import tune
# In combination with a tune.grid_search:
config = PPOConfig()
config.training(lr=tune.grid_search([0.01, 0.001]))
# Use `to_dict()` method to get the legacy plain python config dict
# for usage with `tune.Tuner().fit()`.
tune.Tuner("PPO", param_space=config.to_dict())
"""
@staticmethod
def DEFAULT_AGENT_TO_MODULE_MAPPING_FN(agent_id, episode):
# The default agent ID to module ID mapping function to use in the multi-agent
# case if None is provided.
# Map any agent ID to "default_policy".
return DEFAULT_MODULE_ID
# TODO (sven): Deprecate in new API stack.
@staticmethod
def DEFAULT_POLICY_MAPPING_FN(aid, episode, worker, **kwargs):
# The default policy mapping function to use if None provided.
# Map any agent ID to "default_policy".
return DEFAULT_POLICY_ID
@classmethod
def from_dict(cls, config_dict: dict) -> "AlgorithmConfig":
"""Creates an AlgorithmConfig from a legacy python config dict.
.. testcode::
from ray.rllib.algorithms.ppo.ppo import PPOConfig
# pass a RLlib config dict
ppo_config = PPOConfig.from_dict({})
ppo = ppo_config.build(env="Pendulum-v1")
Args:
config_dict: The legacy formatted python config dict for some algorithm.
Returns:
A new AlgorithmConfig object that matches the given python config dict.
"""
# Create a default config object of this class.
config_obj = cls()
# Remove `_is_frozen` flag from config dict in case the AlgorithmConfig that
# the dict was derived from was already frozen (we don't want to copy the
# frozenness).
config_dict.pop("_is_frozen", None)
config_obj.update_from_dict(config_dict)
return config_obj
@classmethod
def overrides(cls, **kwargs):
"""Generates and validates a set of config key/value pairs (passed via kwargs).
Validation whether given config keys are valid is done immediately upon
construction (by comparing against the properties of a default AlgorithmConfig
object of this class).
Allows combination with a full AlgorithmConfig object to yield a new
AlgorithmConfig object.
Used anywhere, we would like to enable the user to only define a few config
settings that would change with respect to some main config, e.g. in multi-agent
setups and evaluation configs.
.. testcode::
from ray.rllib.algorithms.ppo import PPOConfig
from ray.rllib.policy.policy import PolicySpec
config = (
PPOConfig()
.multi_agent(
policies={
"pol0": PolicySpec(config=PPOConfig.overrides(lambda_=0.95))
},
)
)
.. testcode::
from ray.rllib.algorithms.algorithm_config import AlgorithmConfig
from ray.rllib.algorithms.ppo import PPOConfig
config = (
PPOConfig()
.evaluation(
evaluation_num_env_runners=1,
evaluation_interval=1,
evaluation_config=AlgorithmConfig.overrides(explore=False),
)
)
Returns:
A dict mapping valid config property-names to values.
Raises:
KeyError: In case a non-existing property name (kwargs key) is being
passed in. Valid property names are taken from a default
AlgorithmConfig object of `cls`.
"""
default_config = cls()
config_overrides = {}
for key, value in kwargs.items():
if not hasattr(default_config, key):
raise KeyError(
f"Invalid property name {key} for config class {cls.__name__}!"
)
# Allow things like "lambda" as well.
key = cls._translate_special_keys(key, warn_deprecated=True)
config_overrides[key] = value
return config_overrides
def __init__(self, algo_class: Optional[type] = None):
"""Initializes an AlgorithmConfig instance.
Args:
algo_class: An optional Algorithm class that this config class belongs to.
Used (if provided) to build a respective Algorithm instance from this
config.
"""
# Define all settings and their default values.
# Define the default RLlib Algorithm class that this AlgorithmConfig is applied
# to.
self.algo_class = algo_class
# `self.python_environment()`
self.extra_python_environs_for_driver = {}
self.extra_python_environs_for_worker = {}
# `self.resources()`
self.placement_strategy = "PACK"
self.num_gpus = 0 # @OldAPIStack
self._fake_gpus = False # @OldAPIStack
self.num_cpus_for_main_process = 1
# `self.framework()`
self.framework_str = "torch"
self.eager_tracing = True
self.eager_max_retraces = 20
self.tf_session_args = {
# note: overridden by `local_tf_session_args`
"intra_op_parallelism_threads": 2,
"inter_op_parallelism_threads": 2,
"gpu_options": {
"allow_growth": True,
},
"log_device_placement": False,
"device_count": {"CPU": 1},
# Required by multi-GPU (num_gpus > 1).
"allow_soft_placement": True,
}
self.local_tf_session_args = {
# Allow a higher level of parallelism by default, but not unlimited
# since that can cause crashes with many concurrent drivers.
"intra_op_parallelism_threads": 8,
"inter_op_parallelism_threads": 8,
}
# Torch compile settings
self.torch_compile_learner = False
self.torch_compile_learner_what_to_compile = (
TorchCompileWhatToCompile.FORWARD_TRAIN
)
# AOT Eager is a dummy backend and doesn't result in speedups.
self.torch_compile_learner_dynamo_backend = (
"aot_eager" if sys.platform == "darwin" else "inductor"
)
self.torch_compile_learner_dynamo_mode = None
self.torch_compile_worker = False
# AOT Eager is a dummy backend and doesn't result in speedups.
self.torch_compile_worker_dynamo_backend = (
"aot_eager" if sys.platform == "darwin" else "onnxrt"
)
self.torch_compile_worker_dynamo_mode = None
# Default kwargs for `torch.nn.parallel.DistributedDataParallel`.
self.torch_ddp_kwargs = {}
# Default setting for skipping `nan` gradient updates.
self.torch_skip_nan_gradients = False
# `self.api_stack()`
self.enable_rl_module_and_learner = False
self.enable_env_runner_and_connector_v2 = False
# `self.environment()`
self.env = None
self.env_config = {}
self.observation_space = None
self.action_space = None
self.clip_rewards = None
self.normalize_actions = True
self.clip_actions = False
self._is_atari = None
self.disable_env_checking = False
# Deprecated settings:
self.env_task_fn = None
self.render_env = False
self.action_mask_key = "action_mask"
# `self.env_runners()`
self.env_runner_cls = None
self.num_env_runners = 0
self.num_envs_per_env_runner = 1
self.num_cpus_per_env_runner = 1
self.num_gpus_per_env_runner = 0
self.custom_resources_per_env_runner = {}
self.validate_env_runners_after_construction = True
self.max_requests_in_flight_per_env_runner = 1
self.sample_timeout_s = 60.0
self.create_env_on_local_worker = False
self._env_to_module_connector = None
self.add_default_connectors_to_env_to_module_pipeline = True
self._module_to_env_connector = None
self.add_default_connectors_to_module_to_env_pipeline = True
self.episode_lookback_horizon = 1
# TODO (sven): Rename into `sample_timesteps` (or `sample_duration`
# and `sample_duration_unit` (replacing batch_mode), like we do it
# in the evaluation config).
self.rollout_fragment_length = 200
# TODO (sven): Rename into `sample_mode`.
self.batch_mode = "truncate_episodes"
self.compress_observations = False
# @OldAPIStack
self.remote_worker_envs = False
self.remote_env_batch_wait_ms = 0
self.enable_tf1_exec_eagerly = False
self.sample_collector = SimpleListCollector
self.preprocessor_pref = "deepmind"
self.observation_filter = "NoFilter"
self.update_worker_filter_stats = True
self.use_worker_filter_stats = True
self.sampler_perf_stats_ema_coef = None
# `self.learners()`
self.num_learners = 0
self.num_gpus_per_learner = 0
self.num_cpus_per_learner = 1
self.local_gpu_idx = 0
# `self.training()`
self.gamma = 0.99
self.lr = 0.001
self.grad_clip = None
self.grad_clip_by = "global_norm"
# Simple logic for now: If None, use `train_batch_size`.
self.train_batch_size_per_learner = None
self.train_batch_size = 32 # @OldAPIStack
# These setting have been adopted from the original PPO batch settings:
# num_sgd_iter, minibatch_size, and shuffle_sequences.
self.num_epochs = 1
self.minibatch_size = None
self.shuffle_batch_per_epoch = False
# TODO (sven): Unsolved problem with RLModules sometimes requiring settings from
# the main AlgorithmConfig. We should not require the user to provide those
# settings in both, the AlgorithmConfig (as property) AND the model config
# dict. We should generally move to a world, in which there exists an
# AlgorithmConfig that a) has-a user provided model config object and b)
# is given a chance to compile a final model config (dict or object) that is
# then passed into the RLModule/Catalog. This design would then match our
# "compilation" pattern, where we compile automatically those settings that
# should NOT be touched by the user.
# In case, an Algorithm already uses the above described pattern (and has
# `self.model` as a @property, ignore AttributeError (for trying to set this
# property).
try:
self.model = copy.deepcopy(MODEL_DEFAULTS)
except AttributeError:
pass
self._learner_connector = None
self.add_default_connectors_to_learner_pipeline = True
self.learner_config_dict = {}
self.optimizer = {} # @OldAPIStack
self._learner_class = None
# `self.callbacks()`
self.callbacks_class = DefaultCallbacks
# `self.explore()`
self.explore = True
# This is not compatible with RLModules, which have a method
# `forward_exploration` to specify custom exploration behavior.
self.exploration_config = {}
# `self.multi_agent()`
# TODO (sven): Prepare multi-agent setup for logging each agent's and each
# RLModule's steps taken thus far (and passing this information into the
# EnvRunner metrics and the RLModule's forward pass). Thereby, deprecate the
# `count_steps_by` config setting AND - at the same time - allow users to
# specify the batch size unit instead (agent- vs env steps).
self.count_steps_by = "env_steps"
# self.agent_to_module_mapping_fn = self.DEFAULT_AGENT_TO_MODULE_MAPPING_FN
# Soon to be Deprecated.
self.policies = {DEFAULT_POLICY_ID: PolicySpec()}
self.policy_map_capacity = 100
self.policy_mapping_fn = self.DEFAULT_POLICY_MAPPING_FN
self.policies_to_train = None
self.policy_states_are_swappable = False
self.observation_fn = None
# `self.offline_data()`
self.input_ = "sampler"
self.input_read_method = "read_parquet"
self.input_read_method_kwargs = {}
self.input_read_schema = {}
self.input_read_episodes = False
self.input_read_sample_batches = False
self.input_read_batch_size = None
self.input_filesystem = None
self.input_filesystem_kwargs = {}
self.input_compress_columns = [Columns.OBS, Columns.NEXT_OBS]
self.input_spaces_jsonable = True
self.materialize_data = False
self.materialize_mapped_data = True
self.map_batches_kwargs = {}
self.iter_batches_kwargs = {}
self.prelearner_class = None
self.prelearner_buffer_class = None
self.prelearner_buffer_kwargs = {}
self.prelearner_module_synch_period = 10
self.dataset_num_iters_per_learner = None
self.input_config = {}
self.actions_in_input_normalized = False
self.postprocess_inputs = False
self.shuffle_buffer_size = 0
self.output = None
self.output_config = {}
self.output_compress_columns = [Columns.OBS, Columns.NEXT_OBS]
self.output_max_file_size = 64 * 1024 * 1024
self.output_max_rows_per_file = None
self.output_write_method = "write_parquet"
self.output_write_method_kwargs = {}
self.output_filesystem = None
self.output_filesystem_kwargs = {}
self.output_write_episodes = True
self.offline_sampling = False
# `self.evaluation()`
self.evaluation_interval = None
self.evaluation_duration = 10
self.evaluation_duration_unit = "episodes"
self.evaluation_sample_timeout_s = 120.0
self.evaluation_parallel_to_training = False
self.evaluation_force_reset_envs_before_iteration = True
self.evaluation_config = None
self.off_policy_estimation_methods = {}
self.ope_split_batch_by_episode = True
self.evaluation_num_env_runners = 0
self.custom_evaluation_function = None
# TODO: Set this flag still in the config or - much better - in the
# RolloutWorker as a property.
self.in_evaluation = False
# TODO (sven): Deprecate this setting (it's not user-accessible right now any
# way). Replace by logic within `training_step` to merge and broadcast the
# EnvRunner (connector) states.
self.sync_filters_on_rollout_workers_timeout_s = 10.0
# `self.reporting()`
self.keep_per_episode_custom_metrics = False
self.metrics_episode_collection_timeout_s = 60.0
self.metrics_num_episodes_for_smoothing = 100
self.min_time_s_per_iteration = None
self.min_train_timesteps_per_iteration = 0
self.min_sample_timesteps_per_iteration = 0
self.log_gradients = True
# `self.checkpointing()`
self.export_native_model_files = False
self.checkpoint_trainable_policies_only = False
# `self.debugging()`
self.logger_creator = None
self.logger_config = None
self.log_level = "WARN"
self.log_sys_usage = True
self.fake_sampler = False
self.seed = None
# TODO (sven): Remove these settings again in the future. We only need them
# to debug a quite complex, production memory leak, possibly related to
# evaluation in parallel (when `training_step` is getting called inside a
# thread). It's also possible that the leak is not caused by RLlib itself,
# but by Ray core, but we need more data to narrow this down.
self._run_training_always_in_thread = False
self._evaluation_parallel_to_training_wo_thread = False
# `self.fault_tolerance()`
self.restart_failed_env_runners = True
self.ignore_env_runner_failures = False
# By default, restart failed worker a thousand times.
# This should be enough to handle normal transient failures.
# This also prevents infinite number of restarts in case the worker or env has
# a bug.
self.max_num_env_runner_restarts = 1000
# Small delay between worker restarts. In case EnvRunners or eval EnvRunners
# have remote dependencies, this delay can be adjusted to make sure we don't
# flood them with re-connection requests, and allow them enough time to recover.
# This delay also gives Ray time to stream back error logging and exceptions.
self.delay_between_env_runner_restarts_s = 60.0
self.restart_failed_sub_environments = False
self.num_consecutive_env_runner_failures_tolerance = 100
self.env_runner_health_probe_timeout_s = 30.0
self.env_runner_restore_timeout_s = 1800.0
# `self.rl_module()`
self._model_config = {}
self._rl_module_spec = None
# Helper to keep track of the original exploration config when dis-/enabling
# rl modules.
self.__prior_exploration_config = None
# Module ID specific config overrides.
self.algorithm_config_overrides_per_module = {}
# Cached, actual AlgorithmConfig objects derived from
# `self.algorithm_config_overrides_per_module`.
self._per_module_overrides: Dict[ModuleID, "AlgorithmConfig"] = {}
# `self.experimental()`
self._torch_grad_scaler_class = None
self._torch_lr_scheduler_classes = None
self._tf_policy_handles_more_than_one_loss = False
self._disable_preprocessor_api = False
self._disable_action_flattening = False
self._disable_initialize_loss_from_dummy_batch = False
self._dont_auto_sync_env_runner_states = False
# Has this config object been frozen (cannot alter its attributes anymore).
self._is_frozen = False
# TODO: Remove, once all deprecation_warning calls upon using these keys
# have been removed.
# === Deprecated keys ===
self.enable_connectors = DEPRECATED_VALUE
self.simple_optimizer = DEPRECATED_VALUE
self.monitor = DEPRECATED_VALUE
self.evaluation_num_episodes = DEPRECATED_VALUE
self.metrics_smoothing_episodes = DEPRECATED_VALUE
self.timesteps_per_iteration = DEPRECATED_VALUE
self.min_iter_time_s = DEPRECATED_VALUE
self.collect_metrics_timeout = DEPRECATED_VALUE
self.min_time_s_per_reporting = DEPRECATED_VALUE
self.min_train_timesteps_per_reporting = DEPRECATED_VALUE
self.min_sample_timesteps_per_reporting = DEPRECATED_VALUE
self.input_evaluation = DEPRECATED_VALUE
self.policy_map_cache = DEPRECATED_VALUE
self.worker_cls = DEPRECATED_VALUE
self.synchronize_filters = DEPRECATED_VALUE
self.enable_async_evaluation = DEPRECATED_VALUE
self.custom_async_evaluation_function = DEPRECATED_VALUE
self._enable_rl_module_api = DEPRECATED_VALUE
self.auto_wrap_old_gym_envs = DEPRECATED_VALUE
self.always_attach_evaluation_results = DEPRECATED_VALUE
# The following values have moved because of the new ReplayBuffer API
self.buffer_size = DEPRECATED_VALUE
self.prioritized_replay = DEPRECATED_VALUE
self.learning_starts = DEPRECATED_VALUE
self.replay_batch_size = DEPRECATED_VALUE
# -1 = DEPRECATED_VALUE is a valid value for replay_sequence_length
self.replay_sequence_length = None
self.replay_mode = DEPRECATED_VALUE
self.prioritized_replay_alpha = DEPRECATED_VALUE
self.prioritized_replay_beta = DEPRECATED_VALUE
self.prioritized_replay_eps = DEPRECATED_VALUE
self.min_time_s_per_reporting = DEPRECATED_VALUE
self.min_train_timesteps_per_reporting = DEPRECATED_VALUE
self.min_sample_timesteps_per_reporting = DEPRECATED_VALUE
self._disable_execution_plan_api = DEPRECATED_VALUE
def to_dict(self) -> AlgorithmConfigDict:
"""Converts all settings into a legacy config dict for backward compatibility.
Returns:
A complete AlgorithmConfigDict, usable in backward-compatible Tune/RLlib
use cases.
"""
config = copy.deepcopy(vars(self))
config.pop("algo_class")
config.pop("_is_frozen")
# Worst naming convention ever: NEVER EVER use reserved key-words...
if "lambda_" in config:
assert hasattr(self, "lambda_")
config["lambda"] = getattr(self, "lambda_")
config.pop("lambda_")
if "input_" in config:
assert hasattr(self, "input_")
config["input"] = getattr(self, "input_")
config.pop("input_")
# Convert `policies` (PolicySpecs?) into dict.
# Convert policies dict such that each policy ID maps to a old-style.
# 4-tuple: class, obs-, and action space, config.
if "policies" in config and isinstance(config["policies"], dict):
policies_dict = {}
for policy_id, policy_spec in config.pop("policies").items():
if isinstance(policy_spec, PolicySpec):
policies_dict[policy_id] = policy_spec.get_state()
else:
policies_dict[policy_id] = policy_spec
config["policies"] = policies_dict
# Switch out deprecated vs new config keys.
config["callbacks"] = config.pop("callbacks_class", DefaultCallbacks)
config["create_env_on_driver"] = config.pop("create_env_on_local_worker", 1)
config["custom_eval_function"] = config.pop("custom_evaluation_function", None)
config["framework"] = config.pop("framework_str", None)
# Simplify: Remove all deprecated keys that have as value `DEPRECATED_VALUE`.
# These would be useless in the returned dict anyways.
for dep_k in [
"monitor",
"evaluation_num_episodes",
"metrics_smoothing_episodes",
"timesteps_per_iteration",
"min_iter_time_s",
"collect_metrics_timeout",
"buffer_size",
"prioritized_replay",
"learning_starts",
"replay_batch_size",
"replay_mode",
"prioritized_replay_alpha",
"prioritized_replay_beta",
"prioritized_replay_eps",
"min_time_s_per_reporting",
"min_train_timesteps_per_reporting",
"min_sample_timesteps_per_reporting",
"input_evaluation",
"_enable_new_api_stack",
]:
if config.get(dep_k) == DEPRECATED_VALUE:
config.pop(dep_k, None)
return config
def update_from_dict(
self,
config_dict: PartialAlgorithmConfigDict,
) -> "AlgorithmConfig":
"""Modifies this AlgorithmConfig via the provided python config dict.
Warns if `config_dict` contains deprecated keys.
Silently sets even properties of `self` that do NOT exist. This way, this method
may be used to configure custom Policies which do not have their own specific
AlgorithmConfig classes, e.g.
`ray.rllib.examples.policy.random_policy::RandomPolicy`.
Args:
config_dict: The old-style python config dict (PartialAlgorithmConfigDict)
to use for overriding some properties defined in there.
Returns:
This updated AlgorithmConfig object.
"""
eval_call = {}
# We deal with this special key before all others because it may influence
# stuff like "exploration_config".
# Namely, we want to re-instantiate the exploration config this config had
# inside `self.experimental()` before potentially overwriting it in the
# following.
enable_new_api_stack = config_dict.get(
"_enable_new_api_stack",
config_dict.get(
"enable_rl_module_and_learner",
config_dict.get("enable_env_runner_and_connector_v2"),
),
)
if enable_new_api_stack is not None:
self.api_stack(
enable_rl_module_and_learner=enable_new_api_stack,
enable_env_runner_and_connector_v2=enable_new_api_stack,
)
# Modify our properties one by one.
for key, value in config_dict.items():
key = self._translate_special_keys(key, warn_deprecated=False)
# Ray Tune saves additional data under this magic keyword.
# This should not get treated as AlgorithmConfig field.
if key == TRIAL_INFO:
continue
if key in ["_enable_new_api_stack"]:
# We've dealt with this above.
continue
# Set our multi-agent settings.
elif key == "multiagent":
kwargs = {
k: value[k]
for k in [
"policies",
"policy_map_capacity",
"policy_mapping_fn",
"policies_to_train",
"policy_states_are_swappable",
"observation_fn",
"count_steps_by",
]
if k in value
}
self.multi_agent(**kwargs)
# Some keys specify config sub-dicts and therefore should go through the
# correct methods to properly `.update()` those from given config dict
# (to not lose any sub-keys).
elif key == "callbacks_class" and value != NOT_SERIALIZABLE:
# For backward compatibility reasons, only resolve possible
# classpath if value is a str type.
if isinstance(value, str):
value = deserialize_type(value, error=True)
self.callbacks(callbacks_class=value)
elif key == "env_config":
self.environment(env_config=value)
elif key.startswith("evaluation_"):
eval_call[key] = value
elif key == "exploration_config":
if enable_new_api_stack:
self.exploration_config = value
continue
if isinstance(value, dict) and "type" in value:
value["type"] = deserialize_type(value["type"])
self.env_runners(exploration_config=value)
elif key == "model":
# Resolve possible classpath.
if isinstance(value, dict) and value.get("custom_model"):
value["custom_model"] = deserialize_type(value["custom_model"])
self.training(**{key: value})
elif key == "optimizer":
self.training(**{key: value})
elif key == "replay_buffer_config":
if isinstance(value, dict) and "type" in value:
value["type"] = deserialize_type(value["type"])
self.training(**{key: value})
elif key == "sample_collector":
# Resolve possible classpath.
value = deserialize_type(value)
self.env_runners(sample_collector=value)
# Set the property named `key` to `value`.
else:
setattr(self, key, value)
self.evaluation(**eval_call)
return self
def get_state(self) -> Dict[str, Any]:
"""Returns a dict state that can be pickled.
Returns:
A dictionary containing all attributes of the instance.
"""
state = self.__dict__.copy()
state["class"] = type(self)
state.pop("algo_class")
state.pop("_is_frozen")
state = {k: v for k, v in state.items() if v != DEPRECATED_VALUE}
# Convert `policies` (PolicySpecs?) into dict.
# Convert policies dict such that each policy ID maps to a old-style.
# 4-tuple: class, obs-, and action space, config.
# TODO (simon, sven): Remove when deprecating old stack.
if "policies" in state and isinstance(state["policies"], dict):
policies_dict = {}
for policy_id, policy_spec in state.pop("policies").items():
if isinstance(policy_spec, PolicySpec):
policies_dict[policy_id] = policy_spec.get_state()
else:
policies_dict[policy_id] = policy_spec
state["policies"] = policies_dict
# state = self._serialize_dict(state)
return state
@classmethod
def from_state(cls, state: Dict[str, Any]) -> "AlgorithmConfig":
"""Returns an instance constructed from the state.
Args:
cls: An `AlgorithmConfig` class.
state: A dictionary containing the state of an `AlgorithmConfig`.
See `AlgorithmConfig.get_state` for creating a state.
Returns:
An `AlgorithmConfig` instance with attributes from the `state`.
"""
ctor = state["class"]
config = ctor()
config.__dict__.update(state)
return config
# TODO(sven): We might want to have a `deserialize` method as well. Right now,
# simply using the from_dict() API works in this same (deserializing) manner,
# whether the dict used is actually code-free (already serialized) or not
# (i.e. a classic RLlib config dict with e.g. "callbacks" key still pointing to
# a class).
def serialize(self) -> Dict[str, Any]:
"""Returns a mapping from str to JSON'able values representing this config.
The resulting values don't have any code in them.
Classes (such as `callbacks_class`) are converted to their full
classpath, e.g. `ray.rllib.algorithms.callbacks.DefaultCallbacks`.
Actual code such as lambda functions ware written as their source
code (str) plus any closure information for properly restoring the
code inside the AlgorithmConfig object made from the returned dict data.
Dataclass objects get converted to dicts.
Returns:
A dict mapping from str to JSON'able values.
"""
config = self.to_dict()
return self._serialize_dict(config)
def copy(self, copy_frozen: Optional[bool] = None) -> "AlgorithmConfig":
"""Creates a deep copy of this config and (un)freezes if necessary.
Args:
copy_frozen: Whether the created deep copy is frozen or not. If None,
keep the same frozen status that `self` currently has.
Returns:
A deep copy of `self` that is (un)frozen.
"""
cp = copy.deepcopy(self)
if copy_frozen is True:
cp.freeze()
elif copy_frozen is False:
cp._is_frozen = False
if isinstance(cp.evaluation_config, AlgorithmConfig):
cp.evaluation_config._is_frozen = False
return cp
def freeze(self) -> None:
"""Freezes this config object, such that no attributes can be set anymore.
Algorithms should use this method to make sure that their config objects
remain read-only after this.
"""
if self._is_frozen:
return
self._is_frozen = True
# Also freeze underlying eval config, if applicable.
if isinstance(self.evaluation_config, AlgorithmConfig):
self.evaluation_config.freeze()
# TODO: Flip out all set/dict/list values into frozen versions
# of themselves? This way, users won't even be able to alter those values
# directly anymore.
@OverrideToImplementCustomLogic_CallToSuperRecommended
def validate(self) -> None:
"""Validates all values in this config."""
# Check framework specific settings.
self._validate_framework_settings()
# Check resources specific settings.
self._validate_resources_settings()
# Check multi-agent specific settings.
self._validate_multi_agent_settings()
# Check input specific settings.
self._validate_input_settings()
# Check evaluation specific settings.
self._validate_evaluation_settings()
# Check offline specific settings (new API stack).
self._validate_offline_settings()
# Check new API stack specific settings.
self._validate_new_api_stack_settings()
# Check to-be-deprecated settings (however that are still in use).
self._validate_to_be_deprecated_settings()
def build(
self,
env: Optional[Union[str, EnvType]] = None,
logger_creator: Optional[Callable[[], Logger]] = None,
use_copy: bool = True,
) -> "Algorithm":
"""Builds an Algorithm from this AlgorithmConfig (or a copy thereof).
Args:
env: Name of the environment to use (e.g. a gym-registered str),
a full class path (e.g.
"ray.rllib.examples.envs.classes.random_env.RandomEnv"), or an Env
class directly. Note that this arg can also be specified via
the "env" key in `config`.
logger_creator: Callable that creates a ray.tune.Logger
object. If unspecified, a default logger is created.
use_copy: Whether to deepcopy `self` and pass the copy to the Algorithm
(instead of `self`) as config. This is useful in case you would like to
recycle the same AlgorithmConfig over and over, e.g. in a test case, in
which we loop over different DL-frameworks.
Returns:
A ray.rllib.algorithms.algorithm.Algorithm object.
"""
if env is not None:
self.env = env
if self.evaluation_config is not None:
self.evaluation_config["env"] = env
if logger_creator is not None:
self.logger_creator = logger_creator
algo_class = self.algo_class
if isinstance(self.algo_class, str):
algo_class = get_trainable_cls(self.algo_class)
return algo_class(
config=self if not use_copy else copy.deepcopy(self),
logger_creator=self.logger_creator,
)
def build_env_to_module_connector(self, env):
from ray.rllib.connectors.env_to_module import (
AddObservationsFromEpisodesToBatch,
AddStatesFromEpisodesToBatch,
AgentToModuleMapping,
BatchIndividualItems,
EnvToModulePipeline,
NumpyToTensor,
)
custom_connectors = []
# Create an env-to-module connector pipeline (including RLlib's default
# env->module connector piece) and return it.
if self._env_to_module_connector is not None:
val_ = self._env_to_module_connector(env)
from ray.rllib.connectors.connector_v2 import ConnectorV2
# ConnectorV2 (piece or pipeline).
if isinstance(val_, ConnectorV2):
custom_connectors = [val_]
# Sequence of individual ConnectorV2 pieces.
elif isinstance(val_, (list, tuple)):
custom_connectors = list(val_)
# Unsupported return value.
else:
raise ValueError(
"`AlgorithmConfig.env_runners(env_to_module_connector=..)` must "
"return a ConnectorV2 object or a list thereof (to be added to a "
f"pipeline)! Your function returned {val_}."
)
obs_space = getattr(env, "single_observation_space", env.observation_space)
if obs_space is None and self.is_multi_agent():
obs_space = gym.spaces.Dict(
{
aid: env.get_observation_space(aid)
for aid in env.unwrapped.possible_agents
}