torchrl 0.11.0__cp314-cp314-manylinux_2_28_aarch64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- benchmarks/benchmark_batched_envs.py +104 -0
- benchmarks/conftest.py +91 -0
- benchmarks/ecosystem/gym_env_throughput.py +321 -0
- benchmarks/ecosystem/vmas_rllib_vs_torchrl_sampling_performance.py +231 -0
- benchmarks/requirements.txt +7 -0
- benchmarks/storage/benchmark_sample_latency_over_rpc.py +193 -0
- benchmarks/test_collectors_benchmark.py +240 -0
- benchmarks/test_compressed_storage_benchmark.py +145 -0
- benchmarks/test_envs_benchmark.py +133 -0
- benchmarks/test_llm.py +101 -0
- benchmarks/test_non_tensor_env_benchmark.py +70 -0
- benchmarks/test_objectives_benchmarks.py +1199 -0
- benchmarks/test_replaybuffer_benchmark.py +254 -0
- sota-check/README.md +35 -0
- sota-implementations/README.md +142 -0
- sota-implementations/a2c/README.md +39 -0
- sota-implementations/a2c/a2c_atari.py +291 -0
- sota-implementations/a2c/a2c_mujoco.py +273 -0
- sota-implementations/a2c/utils_atari.py +240 -0
- sota-implementations/a2c/utils_mujoco.py +160 -0
- sota-implementations/bandits/README.md +7 -0
- sota-implementations/bandits/dqn.py +126 -0
- sota-implementations/cql/cql_offline.py +198 -0
- sota-implementations/cql/cql_online.py +249 -0
- sota-implementations/cql/discrete_cql_offline.py +180 -0
- sota-implementations/cql/discrete_cql_online.py +227 -0
- sota-implementations/cql/utils.py +471 -0
- sota-implementations/crossq/crossq.py +271 -0
- sota-implementations/crossq/utils.py +320 -0
- sota-implementations/ddpg/ddpg.py +231 -0
- sota-implementations/ddpg/utils.py +325 -0
- sota-implementations/decision_transformer/dt.py +163 -0
- sota-implementations/decision_transformer/lamb.py +167 -0
- sota-implementations/decision_transformer/online_dt.py +178 -0
- sota-implementations/decision_transformer/utils.py +562 -0
- sota-implementations/discrete_sac/discrete_sac.py +243 -0
- sota-implementations/discrete_sac/utils.py +324 -0
- sota-implementations/dqn/README.md +30 -0
- sota-implementations/dqn/dqn_atari.py +272 -0
- sota-implementations/dqn/dqn_cartpole.py +236 -0
- sota-implementations/dqn/utils_atari.py +132 -0
- sota-implementations/dqn/utils_cartpole.py +90 -0
- sota-implementations/dreamer/README.md +129 -0
- sota-implementations/dreamer/dreamer.py +586 -0
- sota-implementations/dreamer/dreamer_utils.py +1107 -0
- sota-implementations/expert-iteration/README.md +352 -0
- sota-implementations/expert-iteration/ei_utils.py +770 -0
- sota-implementations/expert-iteration/expert-iteration-async.py +512 -0
- sota-implementations/expert-iteration/expert-iteration-sync.py +508 -0
- sota-implementations/expert-iteration/requirements_gsm8k.txt +13 -0
- sota-implementations/expert-iteration/requirements_ifeval.txt +16 -0
- sota-implementations/gail/gail.py +327 -0
- sota-implementations/gail/gail_utils.py +68 -0
- sota-implementations/gail/ppo_utils.py +157 -0
- sota-implementations/grpo/README.md +273 -0
- sota-implementations/grpo/grpo-async.py +437 -0
- sota-implementations/grpo/grpo-sync.py +435 -0
- sota-implementations/grpo/grpo_utils.py +843 -0
- sota-implementations/grpo/requirements_gsm8k.txt +11 -0
- sota-implementations/grpo/requirements_ifeval.txt +16 -0
- sota-implementations/impala/README.md +33 -0
- sota-implementations/impala/impala_multi_node_ray.py +292 -0
- sota-implementations/impala/impala_multi_node_submitit.py +284 -0
- sota-implementations/impala/impala_single_node.py +261 -0
- sota-implementations/impala/utils.py +184 -0
- sota-implementations/iql/discrete_iql.py +230 -0
- sota-implementations/iql/iql_offline.py +164 -0
- sota-implementations/iql/iql_online.py +225 -0
- sota-implementations/iql/utils.py +437 -0
- sota-implementations/multiagent/README.md +74 -0
- sota-implementations/multiagent/iql.py +237 -0
- sota-implementations/multiagent/maddpg_iddpg.py +266 -0
- sota-implementations/multiagent/mappo_ippo.py +267 -0
- sota-implementations/multiagent/qmix_vdn.py +271 -0
- sota-implementations/multiagent/sac.py +337 -0
- sota-implementations/multiagent/utils/__init__.py +4 -0
- sota-implementations/multiagent/utils/logging.py +151 -0
- sota-implementations/multiagent/utils/utils.py +43 -0
- sota-implementations/ppo/README.md +29 -0
- sota-implementations/ppo/ppo_atari.py +305 -0
- sota-implementations/ppo/ppo_mujoco.py +293 -0
- sota-implementations/ppo/utils_atari.py +238 -0
- sota-implementations/ppo/utils_mujoco.py +152 -0
- sota-implementations/ppo_trainer/train.py +21 -0
- sota-implementations/redq/README.md +7 -0
- sota-implementations/redq/redq.py +199 -0
- sota-implementations/redq/utils.py +1060 -0
- sota-implementations/sac/sac-async.py +266 -0
- sota-implementations/sac/sac.py +239 -0
- sota-implementations/sac/utils.py +381 -0
- sota-implementations/sac_trainer/train.py +16 -0
- sota-implementations/td3/td3.py +254 -0
- sota-implementations/td3/utils.py +319 -0
- sota-implementations/td3_bc/td3_bc.py +177 -0
- sota-implementations/td3_bc/utils.py +251 -0
- torchrl/__init__.py +144 -0
- torchrl/_extension.py +74 -0
- torchrl/_torchrl.cpython-314-aarch64-linux-gnu.so +0 -0
- torchrl/_utils.py +1431 -0
- torchrl/collectors/__init__.py +48 -0
- torchrl/collectors/_base.py +1058 -0
- torchrl/collectors/_constants.py +88 -0
- torchrl/collectors/_multi_async.py +324 -0
- torchrl/collectors/_multi_base.py +1805 -0
- torchrl/collectors/_multi_sync.py +464 -0
- torchrl/collectors/_runner.py +581 -0
- torchrl/collectors/_single.py +2009 -0
- torchrl/collectors/_single_async.py +259 -0
- torchrl/collectors/collectors.py +62 -0
- torchrl/collectors/distributed/__init__.py +32 -0
- torchrl/collectors/distributed/default_configs.py +133 -0
- torchrl/collectors/distributed/generic.py +1306 -0
- torchrl/collectors/distributed/ray.py +1092 -0
- torchrl/collectors/distributed/rpc.py +1006 -0
- torchrl/collectors/distributed/sync.py +731 -0
- torchrl/collectors/distributed/utils.py +160 -0
- torchrl/collectors/llm/__init__.py +10 -0
- torchrl/collectors/llm/base.py +494 -0
- torchrl/collectors/llm/ray_collector.py +275 -0
- torchrl/collectors/llm/utils.py +36 -0
- torchrl/collectors/llm/weight_update/__init__.py +10 -0
- torchrl/collectors/llm/weight_update/vllm.py +348 -0
- torchrl/collectors/llm/weight_update/vllm_v2.py +311 -0
- torchrl/collectors/utils.py +433 -0
- torchrl/collectors/weight_update.py +591 -0
- torchrl/csrc/numpy_utils.h +38 -0
- torchrl/csrc/pybind.cpp +27 -0
- torchrl/csrc/segment_tree.h +458 -0
- torchrl/csrc/torch_utils.h +34 -0
- torchrl/csrc/utils.cpp +48 -0
- torchrl/csrc/utils.h +31 -0
- torchrl/data/__init__.py +187 -0
- torchrl/data/datasets/__init__.py +58 -0
- torchrl/data/datasets/atari_dqn.py +878 -0
- torchrl/data/datasets/common.py +281 -0
- torchrl/data/datasets/d4rl.py +489 -0
- torchrl/data/datasets/d4rl_infos.py +187 -0
- torchrl/data/datasets/gen_dgrl.py +375 -0
- torchrl/data/datasets/minari_data.py +643 -0
- torchrl/data/datasets/openml.py +177 -0
- torchrl/data/datasets/openx.py +798 -0
- torchrl/data/datasets/roboset.py +363 -0
- torchrl/data/datasets/utils.py +11 -0
- torchrl/data/datasets/vd4rl.py +432 -0
- torchrl/data/llm/__init__.py +34 -0
- torchrl/data/llm/dataset.py +491 -0
- torchrl/data/llm/history.py +1378 -0
- torchrl/data/llm/prompt.py +198 -0
- torchrl/data/llm/reward.py +225 -0
- torchrl/data/llm/topk.py +186 -0
- torchrl/data/llm/utils.py +543 -0
- torchrl/data/map/__init__.py +21 -0
- torchrl/data/map/hash.py +185 -0
- torchrl/data/map/query.py +204 -0
- torchrl/data/map/tdstorage.py +363 -0
- torchrl/data/map/tree.py +1434 -0
- torchrl/data/map/utils.py +103 -0
- torchrl/data/postprocs/__init__.py +8 -0
- torchrl/data/postprocs/postprocs.py +391 -0
- torchrl/data/replay_buffers/__init__.py +99 -0
- torchrl/data/replay_buffers/checkpointers.py +622 -0
- torchrl/data/replay_buffers/ray_buffer.py +292 -0
- torchrl/data/replay_buffers/replay_buffers.py +2376 -0
- torchrl/data/replay_buffers/samplers.py +2578 -0
- torchrl/data/replay_buffers/scheduler.py +265 -0
- torchrl/data/replay_buffers/storages.py +2412 -0
- torchrl/data/replay_buffers/utils.py +1042 -0
- torchrl/data/replay_buffers/writers.py +781 -0
- torchrl/data/tensor_specs.py +7101 -0
- torchrl/data/utils.py +334 -0
- torchrl/envs/__init__.py +265 -0
- torchrl/envs/async_envs.py +1105 -0
- torchrl/envs/batched_envs.py +3093 -0
- torchrl/envs/common.py +4241 -0
- torchrl/envs/custom/__init__.py +11 -0
- torchrl/envs/custom/chess.py +617 -0
- torchrl/envs/custom/llm.py +214 -0
- torchrl/envs/custom/pendulum.py +401 -0
- torchrl/envs/custom/san_moves.txt +29274 -0
- torchrl/envs/custom/tictactoeenv.py +288 -0
- torchrl/envs/env_creator.py +263 -0
- torchrl/envs/gym_like.py +752 -0
- torchrl/envs/libs/__init__.py +68 -0
- torchrl/envs/libs/_gym_utils.py +326 -0
- torchrl/envs/libs/brax.py +846 -0
- torchrl/envs/libs/dm_control.py +544 -0
- torchrl/envs/libs/envpool.py +447 -0
- torchrl/envs/libs/gym.py +2239 -0
- torchrl/envs/libs/habitat.py +138 -0
- torchrl/envs/libs/isaac_lab.py +87 -0
- torchrl/envs/libs/isaacgym.py +203 -0
- torchrl/envs/libs/jax_utils.py +166 -0
- torchrl/envs/libs/jumanji.py +963 -0
- torchrl/envs/libs/meltingpot.py +599 -0
- torchrl/envs/libs/openml.py +153 -0
- torchrl/envs/libs/openspiel.py +652 -0
- torchrl/envs/libs/pettingzoo.py +1042 -0
- torchrl/envs/libs/procgen.py +351 -0
- torchrl/envs/libs/robohive.py +429 -0
- torchrl/envs/libs/smacv2.py +645 -0
- torchrl/envs/libs/unity_mlagents.py +891 -0
- torchrl/envs/libs/utils.py +147 -0
- torchrl/envs/libs/vmas.py +813 -0
- torchrl/envs/llm/__init__.py +63 -0
- torchrl/envs/llm/chat.py +730 -0
- torchrl/envs/llm/datasets/README.md +4 -0
- torchrl/envs/llm/datasets/__init__.py +17 -0
- torchrl/envs/llm/datasets/gsm8k.py +353 -0
- torchrl/envs/llm/datasets/ifeval.py +274 -0
- torchrl/envs/llm/envs.py +789 -0
- torchrl/envs/llm/libs/README.md +3 -0
- torchrl/envs/llm/libs/__init__.py +8 -0
- torchrl/envs/llm/libs/mlgym.py +869 -0
- torchrl/envs/llm/reward/__init__.py +10 -0
- torchrl/envs/llm/reward/gsm8k.py +324 -0
- torchrl/envs/llm/reward/ifeval/README.md +13 -0
- torchrl/envs/llm/reward/ifeval/__init__.py +10 -0
- torchrl/envs/llm/reward/ifeval/_instructions.py +1667 -0
- torchrl/envs/llm/reward/ifeval/_instructions_main.py +131 -0
- torchrl/envs/llm/reward/ifeval/_instructions_registry.py +100 -0
- torchrl/envs/llm/reward/ifeval/_instructions_util.py +1677 -0
- torchrl/envs/llm/reward/ifeval/_scorer.py +454 -0
- torchrl/envs/llm/transforms/__init__.py +55 -0
- torchrl/envs/llm/transforms/browser.py +292 -0
- torchrl/envs/llm/transforms/dataloading.py +859 -0
- torchrl/envs/llm/transforms/format.py +73 -0
- torchrl/envs/llm/transforms/kl.py +1544 -0
- torchrl/envs/llm/transforms/policy_version.py +189 -0
- torchrl/envs/llm/transforms/reason.py +323 -0
- torchrl/envs/llm/transforms/tokenizer.py +321 -0
- torchrl/envs/llm/transforms/tools.py +1955 -0
- torchrl/envs/model_based/__init__.py +9 -0
- torchrl/envs/model_based/common.py +180 -0
- torchrl/envs/model_based/dreamer.py +112 -0
- torchrl/envs/transforms/__init__.py +147 -0
- torchrl/envs/transforms/functional.py +48 -0
- torchrl/envs/transforms/gym_transforms.py +203 -0
- torchrl/envs/transforms/module.py +341 -0
- torchrl/envs/transforms/r3m.py +372 -0
- torchrl/envs/transforms/ray_service.py +663 -0
- torchrl/envs/transforms/rb_transforms.py +214 -0
- torchrl/envs/transforms/transforms.py +11835 -0
- torchrl/envs/transforms/utils.py +94 -0
- torchrl/envs/transforms/vc1.py +307 -0
- torchrl/envs/transforms/vecnorm.py +845 -0
- torchrl/envs/transforms/vip.py +407 -0
- torchrl/envs/utils.py +1718 -0
- torchrl/envs/vec_envs.py +11 -0
- torchrl/modules/__init__.py +206 -0
- torchrl/modules/distributions/__init__.py +73 -0
- torchrl/modules/distributions/continuous.py +830 -0
- torchrl/modules/distributions/discrete.py +908 -0
- torchrl/modules/distributions/truncated_normal.py +187 -0
- torchrl/modules/distributions/utils.py +233 -0
- torchrl/modules/llm/__init__.py +62 -0
- torchrl/modules/llm/backends/__init__.py +65 -0
- torchrl/modules/llm/backends/vllm/__init__.py +94 -0
- torchrl/modules/llm/backends/vllm/_models.py +46 -0
- torchrl/modules/llm/backends/vllm/base.py +72 -0
- torchrl/modules/llm/backends/vllm/vllm_async.py +2075 -0
- torchrl/modules/llm/backends/vllm/vllm_plugin.py +22 -0
- torchrl/modules/llm/backends/vllm/vllm_sync.py +446 -0
- torchrl/modules/llm/backends/vllm/vllm_utils.py +129 -0
- torchrl/modules/llm/policies/__init__.py +28 -0
- torchrl/modules/llm/policies/common.py +1809 -0
- torchrl/modules/llm/policies/transformers_wrapper.py +2756 -0
- torchrl/modules/llm/policies/vllm_wrapper.py +2241 -0
- torchrl/modules/llm/utils.py +23 -0
- torchrl/modules/mcts/__init__.py +21 -0
- torchrl/modules/mcts/scores.py +579 -0
- torchrl/modules/models/__init__.py +86 -0
- torchrl/modules/models/batchrenorm.py +119 -0
- torchrl/modules/models/decision_transformer.py +179 -0
- torchrl/modules/models/exploration.py +731 -0
- torchrl/modules/models/llm.py +156 -0
- torchrl/modules/models/model_based.py +596 -0
- torchrl/modules/models/models.py +1712 -0
- torchrl/modules/models/multiagent.py +1067 -0
- torchrl/modules/models/recipes/impala.py +185 -0
- torchrl/modules/models/utils.py +162 -0
- torchrl/modules/planners/__init__.py +10 -0
- torchrl/modules/planners/cem.py +228 -0
- torchrl/modules/planners/common.py +73 -0
- torchrl/modules/planners/mppi.py +265 -0
- torchrl/modules/tensordict_module/__init__.py +89 -0
- torchrl/modules/tensordict_module/actors.py +2457 -0
- torchrl/modules/tensordict_module/common.py +529 -0
- torchrl/modules/tensordict_module/exploration.py +814 -0
- torchrl/modules/tensordict_module/probabilistic.py +321 -0
- torchrl/modules/tensordict_module/rnn.py +1639 -0
- torchrl/modules/tensordict_module/sequence.py +132 -0
- torchrl/modules/tensordict_module/world_models.py +34 -0
- torchrl/modules/utils/__init__.py +38 -0
- torchrl/modules/utils/mappings.py +9 -0
- torchrl/modules/utils/utils.py +89 -0
- torchrl/objectives/__init__.py +78 -0
- torchrl/objectives/a2c.py +659 -0
- torchrl/objectives/common.py +753 -0
- torchrl/objectives/cql.py +1346 -0
- torchrl/objectives/crossq.py +710 -0
- torchrl/objectives/ddpg.py +453 -0
- torchrl/objectives/decision_transformer.py +371 -0
- torchrl/objectives/deprecated.py +516 -0
- torchrl/objectives/dqn.py +683 -0
- torchrl/objectives/dreamer.py +488 -0
- torchrl/objectives/functional.py +48 -0
- torchrl/objectives/gail.py +258 -0
- torchrl/objectives/iql.py +996 -0
- torchrl/objectives/llm/__init__.py +30 -0
- torchrl/objectives/llm/grpo.py +846 -0
- torchrl/objectives/llm/sft.py +482 -0
- torchrl/objectives/multiagent/__init__.py +8 -0
- torchrl/objectives/multiagent/qmixer.py +396 -0
- torchrl/objectives/ppo.py +1669 -0
- torchrl/objectives/redq.py +683 -0
- torchrl/objectives/reinforce.py +530 -0
- torchrl/objectives/sac.py +1580 -0
- torchrl/objectives/td3.py +570 -0
- torchrl/objectives/td3_bc.py +625 -0
- torchrl/objectives/utils.py +782 -0
- torchrl/objectives/value/__init__.py +28 -0
- torchrl/objectives/value/advantages.py +1956 -0
- torchrl/objectives/value/functional.py +1459 -0
- torchrl/objectives/value/utils.py +360 -0
- torchrl/record/__init__.py +17 -0
- torchrl/record/loggers/__init__.py +23 -0
- torchrl/record/loggers/common.py +48 -0
- torchrl/record/loggers/csv.py +226 -0
- torchrl/record/loggers/mlflow.py +142 -0
- torchrl/record/loggers/tensorboard.py +139 -0
- torchrl/record/loggers/trackio.py +163 -0
- torchrl/record/loggers/utils.py +78 -0
- torchrl/record/loggers/wandb.py +214 -0
- torchrl/record/recorder.py +554 -0
- torchrl/services/__init__.py +79 -0
- torchrl/services/base.py +109 -0
- torchrl/services/ray_service.py +453 -0
- torchrl/testing/__init__.py +107 -0
- torchrl/testing/assertions.py +179 -0
- torchrl/testing/dist_utils.py +122 -0
- torchrl/testing/env_creators.py +227 -0
- torchrl/testing/env_helper.py +35 -0
- torchrl/testing/gym_helpers.py +156 -0
- torchrl/testing/llm_mocks.py +119 -0
- torchrl/testing/mocking_classes.py +2720 -0
- torchrl/testing/modules.py +295 -0
- torchrl/testing/mp_helpers.py +15 -0
- torchrl/testing/ray_helpers.py +293 -0
- torchrl/testing/utils.py +190 -0
- torchrl/trainers/__init__.py +42 -0
- torchrl/trainers/algorithms/__init__.py +11 -0
- torchrl/trainers/algorithms/configs/__init__.py +705 -0
- torchrl/trainers/algorithms/configs/collectors.py +216 -0
- torchrl/trainers/algorithms/configs/common.py +41 -0
- torchrl/trainers/algorithms/configs/data.py +308 -0
- torchrl/trainers/algorithms/configs/envs.py +104 -0
- torchrl/trainers/algorithms/configs/envs_libs.py +361 -0
- torchrl/trainers/algorithms/configs/logging.py +80 -0
- torchrl/trainers/algorithms/configs/modules.py +570 -0
- torchrl/trainers/algorithms/configs/objectives.py +177 -0
- torchrl/trainers/algorithms/configs/trainers.py +340 -0
- torchrl/trainers/algorithms/configs/transforms.py +955 -0
- torchrl/trainers/algorithms/configs/utils.py +252 -0
- torchrl/trainers/algorithms/configs/weight_sync_schemes.py +191 -0
- torchrl/trainers/algorithms/configs/weight_update.py +159 -0
- torchrl/trainers/algorithms/ppo.py +373 -0
- torchrl/trainers/algorithms/sac.py +308 -0
- torchrl/trainers/helpers/__init__.py +40 -0
- torchrl/trainers/helpers/collectors.py +416 -0
- torchrl/trainers/helpers/envs.py +573 -0
- torchrl/trainers/helpers/logger.py +33 -0
- torchrl/trainers/helpers/losses.py +132 -0
- torchrl/trainers/helpers/models.py +658 -0
- torchrl/trainers/helpers/replay_buffer.py +59 -0
- torchrl/trainers/helpers/trainers.py +301 -0
- torchrl/trainers/trainers.py +2052 -0
- torchrl/weight_update/__init__.py +33 -0
- torchrl/weight_update/_distributed.py +749 -0
- torchrl/weight_update/_mp.py +624 -0
- torchrl/weight_update/_noupdate.py +102 -0
- torchrl/weight_update/_ray.py +1032 -0
- torchrl/weight_update/_rpc.py +284 -0
- torchrl/weight_update/_shared.py +891 -0
- torchrl/weight_update/llm/__init__.py +32 -0
- torchrl/weight_update/llm/vllm_double_buffer.py +370 -0
- torchrl/weight_update/llm/vllm_nccl.py +710 -0
- torchrl/weight_update/utils.py +73 -0
- torchrl/weight_update/weight_sync_schemes.py +1244 -0
- torchrl-0.11.0.dist-info/METADATA +1308 -0
- torchrl-0.11.0.dist-info/RECORD +394 -0
- torchrl-0.11.0.dist-info/WHEEL +5 -0
- torchrl-0.11.0.dist-info/entry_points.txt +2 -0
- torchrl-0.11.0.dist-info/licenses/LICENSE +21 -0
- torchrl-0.11.0.dist-info/top_level.txt +7 -0
|
@@ -0,0 +1,1092 @@
|
|
|
1
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
|
+
#
|
|
3
|
+
# This source code is licensed under the MIT license found in the
|
|
4
|
+
# LICENSE file in the root directory of this source tree.
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import threading
|
|
9
|
+
import warnings
|
|
10
|
+
from collections import OrderedDict
|
|
11
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import torch
|
|
15
|
+
import torch.nn as nn
|
|
16
|
+
from tensordict import TensorDict, TensorDictBase
|
|
17
|
+
|
|
18
|
+
from torchrl._utils import as_remote, logger as torchrl_logger
|
|
19
|
+
from torchrl.collectors._base import BaseCollector
|
|
20
|
+
from torchrl.collectors._constants import DEFAULT_EXPLORATION_TYPE
|
|
21
|
+
from torchrl.collectors._multi_async import MultiAsyncCollector
|
|
22
|
+
from torchrl.collectors._multi_sync import MultiSyncCollector
|
|
23
|
+
from torchrl.collectors._single import Collector
|
|
24
|
+
from torchrl.collectors.utils import _NON_NN_POLICY_WEIGHTS, split_trajectories
|
|
25
|
+
from torchrl.collectors.weight_update import RayWeightUpdater, WeightUpdaterBase
|
|
26
|
+
from torchrl.data import ReplayBuffer
|
|
27
|
+
from torchrl.envs.common import EnvBase
|
|
28
|
+
from torchrl.envs.env_creator import EnvCreator
|
|
29
|
+
from torchrl.weight_update.weight_sync_schemes import WeightSyncScheme
|
|
30
|
+
|
|
31
|
+
RAY_ERR = None
|
|
32
|
+
try:
|
|
33
|
+
import ray
|
|
34
|
+
from ray._private.services import get_node_ip_address
|
|
35
|
+
|
|
36
|
+
_has_ray = True
|
|
37
|
+
except ImportError as err:
|
|
38
|
+
_has_ray = False
|
|
39
|
+
RAY_ERR = err
|
|
40
|
+
|
|
41
|
+
DEFAULT_RAY_INIT_CONFIG = {
|
|
42
|
+
"address": None,
|
|
43
|
+
"num_cpus": None,
|
|
44
|
+
"num_gpus": None,
|
|
45
|
+
"resources": None,
|
|
46
|
+
"object_store_memory": None,
|
|
47
|
+
"local_mode": False,
|
|
48
|
+
"ignore_reinit_error": False,
|
|
49
|
+
"include_dashboard": None,
|
|
50
|
+
"dashboard_host": "127.0.0.1",
|
|
51
|
+
"dashboard_port": None,
|
|
52
|
+
"job_config": None,
|
|
53
|
+
"configure_logging": True,
|
|
54
|
+
"logging_level": "info",
|
|
55
|
+
"logging_format": None,
|
|
56
|
+
"log_to_driver": True,
|
|
57
|
+
"namespace": None,
|
|
58
|
+
"runtime_env": None,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
DEFAULT_REMOTE_CLASS_CONFIG = {
|
|
62
|
+
"num_cpus": 1,
|
|
63
|
+
"num_gpus": 0.2 if torch.cuda.is_available() else None,
|
|
64
|
+
"memory": 2 * 1024**3,
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def print_remote_collector_info(self):
|
|
69
|
+
"""Prints some information about the remote collector."""
|
|
70
|
+
s = (
|
|
71
|
+
f"Created remote collector with in machine "
|
|
72
|
+
f"{get_node_ip_address()} using gpus {ray.get_gpu_ids()}"
|
|
73
|
+
)
|
|
74
|
+
# torchrl_logger.warning(s)
|
|
75
|
+
torchrl_logger.debug(s)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class RayCollector(BaseCollector):
|
|
79
|
+
"""Distributed data collector with `Ray <https://docs.ray.io/>`_ backend.
|
|
80
|
+
|
|
81
|
+
This Python class serves as a ray-based solution to instantiate and coordinate multiple
|
|
82
|
+
data collectors in a distributed cluster. Like TorchRL non-distributed collectors, this
|
|
83
|
+
collector is an iterable that yields TensorDicts until a target number of collected
|
|
84
|
+
frames is reached, but handles distributed data collection under the hood.
|
|
85
|
+
|
|
86
|
+
The class dictionary input parameter "ray_init_config" can be used to provide the kwargs to
|
|
87
|
+
call Ray initialization method ray.init(). If "ray_init_config" is not provided, the default
|
|
88
|
+
behavior is to autodetect an existing Ray cluster or start a new Ray instance locally if no
|
|
89
|
+
existing cluster is found. Refer to Ray documentation for advanced initialization kwargs.
|
|
90
|
+
|
|
91
|
+
Similarly, dictionary input parameter "remote_configs" can be used to specify the kwargs for
|
|
92
|
+
ray.remote() when called to create each remote collector actor, including collector compute
|
|
93
|
+
resources.The sum of all collector resources should be available in the cluster. Refer to Ray
|
|
94
|
+
documentation for advanced configuration of the ray.remote() method. Default kwargs are:
|
|
95
|
+
|
|
96
|
+
>>> kwargs = {
|
|
97
|
+
... "num_cpus": 1,
|
|
98
|
+
... "num_gpus": 0.2,
|
|
99
|
+
... "memory": 2 * 1024 ** 3,
|
|
100
|
+
... }
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
The coordination between collector instances can be specified as "synchronous" or "asynchronous".
|
|
104
|
+
In synchronous coordination, this class waits for all remote collectors to collect a rollout,
|
|
105
|
+
concatenates all rollouts into a single TensorDict instance and finally yields the concatenated
|
|
106
|
+
data. On the other hand, if the coordination is to be carried out asynchronously, this class
|
|
107
|
+
provides the rollouts as they become available from individual remote collectors.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
create_env_fn (Callable or List[Callabled]): list of Callables, each returning an
|
|
111
|
+
instance of :class:`~torchrl.envs.EnvBase`.
|
|
112
|
+
policy (Callable, optional): Policy to be executed in the environment.
|
|
113
|
+
Must accept :class:`tensordict.tensordict.TensorDictBase` object as input.
|
|
114
|
+
If ``None`` is provided, the policy used will be a
|
|
115
|
+
:class:`~torchrl.collectors.RandomPolicy` instance with the environment
|
|
116
|
+
``action_spec``.
|
|
117
|
+
Accepted policies are usually subclasses of :class:`~tensordict.nn.TensorDictModuleBase`.
|
|
118
|
+
This is the recommended usage of the collector.
|
|
119
|
+
Other callables are accepted too:
|
|
120
|
+
If the policy is not a ``TensorDictModuleBase`` (e.g., a regular :class:`~torch.nn.Module`
|
|
121
|
+
instances) it will be wrapped in a `nn.Module` first.
|
|
122
|
+
Then, the collector will try to assess if these
|
|
123
|
+
modules require wrapping in a :class:`~tensordict.nn.TensorDictModule` or not.
|
|
124
|
+
|
|
125
|
+
- If the policy forward signature matches any of ``forward(self, tensordict)``,
|
|
126
|
+
``forward(self, td)`` or ``forward(self, <anything>: TensorDictBase)`` (or
|
|
127
|
+
any typing with a single argument typed as a subclass of ``TensorDictBase``)
|
|
128
|
+
then the policy won't be wrapped in a :class:`~tensordict.nn.TensorDictModule`.
|
|
129
|
+
|
|
130
|
+
- In all other cases an attempt to wrap it will be undergone as such: ``TensorDictModule(policy, in_keys=env_obs_key, out_keys=env.action_keys)``.
|
|
131
|
+
|
|
132
|
+
.. note:: If the policy needs to be passed as a policy factory (e.g., in case it mustn't be serialized /
|
|
133
|
+
pickled directly), the ``policy_factory`` should be used instead.
|
|
134
|
+
|
|
135
|
+
Keyword Args:
|
|
136
|
+
policy_factory (Callable[[], Callable], list of Callable[[], Callable], optional): a callable
|
|
137
|
+
(or list of callables) that returns a policy instance. This is exclusive with the `policy` argument.
|
|
138
|
+
|
|
139
|
+
.. note:: `policy_factory` comes in handy whenever the policy cannot be serialized.
|
|
140
|
+
|
|
141
|
+
trust_policy (bool, optional): if ``True``, a non-TensorDictModule policy will be trusted to be
|
|
142
|
+
assumed to be compatible with the collector. This defaults to ``True`` for CudaGraphModules
|
|
143
|
+
and ``False`` otherwise.
|
|
144
|
+
frames_per_batch (int): A keyword-only argument representing the
|
|
145
|
+
total number of elements in a batch.
|
|
146
|
+
total_frames (int, Optional): lower bound of the total number of frames returned by the collector.
|
|
147
|
+
The iterator will stop once the total number of frames equates or exceeds the total number of
|
|
148
|
+
frames passed to the collector. Default value is -1, which mean no target total number of frames
|
|
149
|
+
(i.e. the collector will run indefinitely).
|
|
150
|
+
device (int, str or torch.device, optional): The generic device of the
|
|
151
|
+
collector. The ``device`` args fills any non-specified device: if
|
|
152
|
+
``device`` is not ``None`` and any of ``storing_device``, ``policy_device`` or
|
|
153
|
+
``env_device`` is not specified, its value will be set to ``device``.
|
|
154
|
+
Defaults to ``None`` (No default device).
|
|
155
|
+
Lists of devices are supported.
|
|
156
|
+
storing_device (int, str or torch.device, optional): The *remote* device on which
|
|
157
|
+
the output :class:`~tensordict.TensorDict` will be stored.
|
|
158
|
+
If ``device`` is passed and ``storing_device`` is ``None``, it will
|
|
159
|
+
default to the value indicated by ``device``.
|
|
160
|
+
For long trajectories, it may be necessary to store the data on a different
|
|
161
|
+
device than the one where the policy and env are executed.
|
|
162
|
+
Defaults to ``None`` (the output tensordict isn't on a specific device,
|
|
163
|
+
leaf tensors sit on the device where they were created).
|
|
164
|
+
Lists of devices are supported.
|
|
165
|
+
env_device (int, str or torch.device, optional): The *remote* device on which
|
|
166
|
+
the environment should be cast (or executed if that functionality is
|
|
167
|
+
supported). If not specified and the env has a non-``None`` device,
|
|
168
|
+
``env_device`` will default to that value. If ``device`` is passed
|
|
169
|
+
and ``env_device=None``, it will default to ``device``. If the value
|
|
170
|
+
as such specified of ``env_device`` differs from ``policy_device``
|
|
171
|
+
and one of them is not ``None``, the data will be cast to ``env_device``
|
|
172
|
+
before being passed to the env (i.e., passing different devices to
|
|
173
|
+
policy and env is supported). Defaults to ``None``.
|
|
174
|
+
Lists of devices are supported.
|
|
175
|
+
policy_device (int, str or torch.device, optional): The *remote* device on which
|
|
176
|
+
the policy should be cast.
|
|
177
|
+
If ``device`` is passed and ``policy_device=None``, it will default
|
|
178
|
+
to ``device``. If the value as such specified of ``policy_device``
|
|
179
|
+
differs from ``env_device`` and one of them is not ``None``,
|
|
180
|
+
the data will be cast to ``policy_device`` before being passed to
|
|
181
|
+
the policy (i.e., passing different devices to policy and env is
|
|
182
|
+
supported). Defaults to ``None``.
|
|
183
|
+
Lists of devices are supported.
|
|
184
|
+
create_env_kwargs (dict, optional): Dictionary of kwargs for
|
|
185
|
+
``create_env_fn``.
|
|
186
|
+
max_frames_per_traj (int, optional): Maximum steps per trajectory.
|
|
187
|
+
Note that a trajectory can span across multiple batches (unless
|
|
188
|
+
``reset_at_each_iter`` is set to ``True``, see below).
|
|
189
|
+
Once a trajectory reaches ``n_steps``, the environment is reset.
|
|
190
|
+
If the environment wraps multiple environments together, the number
|
|
191
|
+
of steps is tracked for each environment independently. Negative
|
|
192
|
+
values are allowed, in which case this argument is ignored.
|
|
193
|
+
Defaults to ``None`` (i.e., no maximum number of steps).
|
|
194
|
+
init_random_frames (int, optional): Number of frames for which the
|
|
195
|
+
policy is ignored before it is called. This feature is mainly
|
|
196
|
+
intended to be used in offline/model-based settings, where a
|
|
197
|
+
batch of random trajectories can be used to initialize training.
|
|
198
|
+
If provided, it will be rounded up to the closest multiple of frames_per_batch.
|
|
199
|
+
Defaults to ``None`` (i.e. no random frames).
|
|
200
|
+
reset_at_each_iter (bool, optional): Whether environments should be reset
|
|
201
|
+
at the beginning of a batch collection.
|
|
202
|
+
Defaults to ``False``.
|
|
203
|
+
postproc (Callable, optional): A post-processing transform, such as
|
|
204
|
+
a :class:`~torchrl.envs.Transform` or a :class:`~torchrl.data.postprocs.MultiStep`
|
|
205
|
+
instance.
|
|
206
|
+
Defaults to ``None``.
|
|
207
|
+
split_trajs (bool, optional): Boolean indicating whether the resulting
|
|
208
|
+
TensorDict should be split according to the trajectories.
|
|
209
|
+
See :func:`~torchrl.collectors.utils.split_trajectories` for more
|
|
210
|
+
information.
|
|
211
|
+
Defaults to ``False``.
|
|
212
|
+
exploration_type (ExplorationType, optional): interaction mode to be used when
|
|
213
|
+
collecting data. Must be one of ``torchrl.envs.utils.ExplorationType.DETERMINISTIC``,
|
|
214
|
+
``torchrl.envs.utils.ExplorationType.RANDOM``, ``torchrl.envs.utils.ExplorationType.MODE``
|
|
215
|
+
or ``torchrl.envs.utils.ExplorationType.MEAN``.
|
|
216
|
+
collector_class (Python class or constructor): a collector class to be remotely instantiated. Can be
|
|
217
|
+
:class:`~torchrl.collectors.Collector`,
|
|
218
|
+
:class:`~torchrl.collectors.MultiSyncCollector`,
|
|
219
|
+
:class:`~torchrl.collectors.MultiAsyncCollector`
|
|
220
|
+
or a derived class of these.
|
|
221
|
+
Defaults to :class:`~torchrl.collectors.Collector`.
|
|
222
|
+
collector_kwargs (dict or list, optional): a dictionary of parameters to be passed to the
|
|
223
|
+
remote data-collector. If a list is provided, each element will
|
|
224
|
+
correspond to an individual set of keyword arguments for the
|
|
225
|
+
dedicated collector.
|
|
226
|
+
num_workers_per_collector (int): the number of copies of the
|
|
227
|
+
env constructor that is to be used on the remote nodes.
|
|
228
|
+
Defaults to 1 (a single env per collector).
|
|
229
|
+
On a single worker node all the sub-workers will be
|
|
230
|
+
executing the same environment. If different environments need to
|
|
231
|
+
be executed, they should be dispatched across worker nodes, not
|
|
232
|
+
subnodes.
|
|
233
|
+
ray_init_config (dict, Optional): kwargs used to call ray.init().
|
|
234
|
+
remote_configs (list of dicts, Optional): ray resource specs for each remote collector.
|
|
235
|
+
A single dict can be provided as well, and will be used in all collectors.
|
|
236
|
+
num_collectors (int, Optional): total number of collectors to be instantiated.
|
|
237
|
+
sync (bool): if ``True``, the resulting tensordict is a stack of all the
|
|
238
|
+
tensordicts collected on each node. If ``False`` (default), each
|
|
239
|
+
tensordict results from a separate node in a "first-ready,
|
|
240
|
+
first-served" fashion.
|
|
241
|
+
update_after_each_batch (bool, optional): if ``True``, the weights will
|
|
242
|
+
be updated after each collection. For ``sync=True``, this means that
|
|
243
|
+
all workers will see their weights updated. For ``sync=False``,
|
|
244
|
+
only the worker from which the data has been gathered will be
|
|
245
|
+
updated.
|
|
246
|
+
This is equivalent to `max_weight_update_interval=0`.
|
|
247
|
+
Defaults to ``False``, i.e. updates have to be executed manually
|
|
248
|
+
through
|
|
249
|
+
:meth:`torchrl.collectors.DataCollector.update_policy_weights_`
|
|
250
|
+
max_weight_update_interval (int, optional): the maximum number of
|
|
251
|
+
batches that can be collected before the policy weights of a worker
|
|
252
|
+
is updated.
|
|
253
|
+
For sync collections, this parameter is overwritten by ``update_after_each_batch``.
|
|
254
|
+
For async collections, it may be that one worker has not seen its
|
|
255
|
+
parameters being updated for a certain time even if ``update_after_each_batch``
|
|
256
|
+
is turned on.
|
|
257
|
+
Defaults to -1 (no forced update).
|
|
258
|
+
replay_buffer (RayReplayBuffer, optional): if provided, the collector will not yield tensordicts
|
|
259
|
+
but populate the buffer instead. Defaults to ``None``.
|
|
260
|
+
|
|
261
|
+
.. note:: although it is not enfoced (to allow users to implement their own replay buffer class), a
|
|
262
|
+
:class:`~torchrl.data.RayReplayBuffer` instance should be used here.
|
|
263
|
+
weight_updater (WeightUpdaterBase or constructor, optional): (Deprecated) An instance of :class:`~torchrl.collectors.WeightUpdaterBase`
|
|
264
|
+
or its subclass, responsible for updating the policy weights on remote inference workers managed by Ray.
|
|
265
|
+
If not provided, a :class:`~torchrl.collectors.RayWeightUpdater` will be used by default, leveraging
|
|
266
|
+
Ray's distributed capabilities.
|
|
267
|
+
Consider using a constructor if the updater needs to be serialized.
|
|
268
|
+
weight_sync_schemes (dict[str, WeightSyncScheme], optional): Dictionary of weight sync schemes for
|
|
269
|
+
SENDING weights to remote collector workers. Keys are model identifiers (e.g., "policy")
|
|
270
|
+
and values are WeightSyncScheme instances configured to send weights via Ray.
|
|
271
|
+
This is the recommended way to configure weight synchronization for propagating weights
|
|
272
|
+
from the main process to remote collectors. If not provided,
|
|
273
|
+
defaults to ``{"policy": RayWeightSyncScheme()}``.
|
|
274
|
+
|
|
275
|
+
.. note:: Weight synchronization is lazily initialized. When using ``policy_factory``
|
|
276
|
+
without a central ``policy``, weight sync is deferred until the first call to
|
|
277
|
+
:meth:`~torchrl.collectors.DataCollector.update_policy_weights_` with actual weights.
|
|
278
|
+
This allows sub-collectors to each have their own independent policies created via
|
|
279
|
+
the factory. If you have a central policy and want to sync its weights to remote
|
|
280
|
+
collectors, call ``update_policy_weights_(policy)`` before starting iteration.
|
|
281
|
+
|
|
282
|
+
weight_recv_schemes (dict[str, WeightSyncScheme], optional): Dictionary of weight sync schemes for
|
|
283
|
+
RECEIVING weights from a parent process or training loop. Keys are model identifiers (e.g., "policy")
|
|
284
|
+
and values are WeightSyncScheme instances configured to receive weights.
|
|
285
|
+
This is typically used when RayCollector is itself a worker in a larger distributed setup.
|
|
286
|
+
Defaults to ``None``.
|
|
287
|
+
use_env_creator (bool, optional): if ``True``, the environment constructor functions will be wrapped
|
|
288
|
+
in :class:`~torchrl.envs.EnvCreator`. This is useful for multiprocessed settings where shared memory
|
|
289
|
+
needs to be managed, but Ray has its own object storage mechanism, so this is typically not needed.
|
|
290
|
+
Defaults to ``False``.
|
|
291
|
+
|
|
292
|
+
Examples:
|
|
293
|
+
>>> from torch import nn
|
|
294
|
+
>>> from tensordict.nn import TensorDictModule
|
|
295
|
+
>>> from torchrl.envs.libs.gym import GymEnv
|
|
296
|
+
>>> from torchrl.collectors import Collector
|
|
297
|
+
>>> from torchrl.collectors.distributed import RayCollector
|
|
298
|
+
>>> env_maker = lambda: GymEnv("Pendulum-v1", device="cpu")
|
|
299
|
+
>>> policy = TensorDictModule(nn.Linear(3, 1), in_keys=["observation"], out_keys=["action"])
|
|
300
|
+
>>> distributed_collector = RayCollector(
|
|
301
|
+
... create_env_fn=[env_maker],
|
|
302
|
+
... policy=policy,
|
|
303
|
+
... collector_class=Collector,
|
|
304
|
+
... max_frames_per_traj=50,
|
|
305
|
+
... init_random_frames=-1,
|
|
306
|
+
... reset_at_each_iter=-False,
|
|
307
|
+
... collector_kwargs={
|
|
308
|
+
... "device": "cpu",
|
|
309
|
+
... "storing_device": "cpu",
|
|
310
|
+
... },
|
|
311
|
+
... num_collectors=1,
|
|
312
|
+
... total_frames=10000,
|
|
313
|
+
... frames_per_batch=200,
|
|
314
|
+
... )
|
|
315
|
+
>>> for i, data in enumerate(collector):
|
|
316
|
+
... if i == 2:
|
|
317
|
+
... print(data)
|
|
318
|
+
... break
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
def __init__(
|
|
322
|
+
self,
|
|
323
|
+
create_env_fn: Callable | EnvBase | list[Callable] | list[EnvBase],
|
|
324
|
+
policy: Callable[[TensorDictBase], TensorDictBase] | None = None,
|
|
325
|
+
*,
|
|
326
|
+
policy_factory: Callable[[], Callable]
|
|
327
|
+
| list[Callable[[], Callable]]
|
|
328
|
+
| None = None,
|
|
329
|
+
trust_policy: bool | None = None,
|
|
330
|
+
frames_per_batch: int,
|
|
331
|
+
total_frames: int = -1,
|
|
332
|
+
device: torch.device | list[torch.device] | None = None,
|
|
333
|
+
storing_device: torch.device | list[torch.device] | None = None,
|
|
334
|
+
env_device: torch.device | list[torch.device] | None = None,
|
|
335
|
+
policy_device: torch.device | list[torch.device] | None = None,
|
|
336
|
+
max_frames_per_traj=-1,
|
|
337
|
+
init_random_frames=-1,
|
|
338
|
+
reset_at_each_iter=False,
|
|
339
|
+
postproc=None,
|
|
340
|
+
split_trajs=False,
|
|
341
|
+
exploration_type=DEFAULT_EXPLORATION_TYPE,
|
|
342
|
+
collector_class: Callable[[TensorDict], TensorDict] = Collector,
|
|
343
|
+
collector_kwargs: dict[str, Any] | list[dict] | None = None,
|
|
344
|
+
num_workers_per_collector: int = 1,
|
|
345
|
+
sync: bool = False,
|
|
346
|
+
ray_init_config: dict[str, Any] | None = None,
|
|
347
|
+
remote_configs: dict[str, Any] | list[dict[str, Any]] | None = None,
|
|
348
|
+
num_collectors: int | None = None,
|
|
349
|
+
update_after_each_batch: bool = False,
|
|
350
|
+
max_weight_update_interval: int = -1,
|
|
351
|
+
replay_buffer: ReplayBuffer | None = None,
|
|
352
|
+
weight_updater: WeightUpdaterBase
|
|
353
|
+
| Callable[[], WeightUpdaterBase]
|
|
354
|
+
| None = None,
|
|
355
|
+
weight_sync_schemes: dict[str, WeightSyncScheme] | None = None,
|
|
356
|
+
weight_recv_schemes: dict[str, WeightSyncScheme] | None = None,
|
|
357
|
+
use_env_creator: bool = False,
|
|
358
|
+
no_cuda_sync: bool | None = None,
|
|
359
|
+
):
|
|
360
|
+
self.frames_per_batch = frames_per_batch
|
|
361
|
+
if remote_configs is None:
|
|
362
|
+
remote_configs = DEFAULT_REMOTE_CLASS_CONFIG
|
|
363
|
+
|
|
364
|
+
if ray_init_config is None:
|
|
365
|
+
ray_init_config = DEFAULT_RAY_INIT_CONFIG
|
|
366
|
+
|
|
367
|
+
if collector_kwargs is None:
|
|
368
|
+
collector_kwargs = {}
|
|
369
|
+
if replay_buffer is not None:
|
|
370
|
+
if isinstance(collector_kwargs, dict):
|
|
371
|
+
collector_kwargs.setdefault("replay_buffer", replay_buffer)
|
|
372
|
+
else:
|
|
373
|
+
collector_kwargs = [
|
|
374
|
+
ck.setdefault("replay_buffer", replay_buffer)
|
|
375
|
+
for ck in collector_kwargs
|
|
376
|
+
]
|
|
377
|
+
|
|
378
|
+
# Make sure input parameters are consistent
|
|
379
|
+
def check_consistency_with_num_collectors(param, param_name, num_collectors):
|
|
380
|
+
"""Checks that if param is a list, it has length num_collectors."""
|
|
381
|
+
if isinstance(param, list):
|
|
382
|
+
if len(param) != num_collectors:
|
|
383
|
+
raise ValueError(
|
|
384
|
+
f"Inconsistent RayDistributedCollector parameters, {param_name} is a list of length "
|
|
385
|
+
f"{len(param)} but the specified number of collectors is {num_collectors}."
|
|
386
|
+
)
|
|
387
|
+
else:
|
|
388
|
+
param = [param] * num_collectors
|
|
389
|
+
return param
|
|
390
|
+
|
|
391
|
+
if num_collectors:
|
|
392
|
+
create_env_fn = check_consistency_with_num_collectors(
|
|
393
|
+
create_env_fn, "create_env_fn", num_collectors
|
|
394
|
+
)
|
|
395
|
+
collector_kwargs = check_consistency_with_num_collectors(
|
|
396
|
+
collector_kwargs, "collector_kwargs", num_collectors
|
|
397
|
+
)
|
|
398
|
+
remote_configs = check_consistency_with_num_collectors(
|
|
399
|
+
remote_configs, "remote_config", num_collectors
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
def check_list_length_consistency(*lists):
|
|
403
|
+
"""Checks that all input lists have the same length.
|
|
404
|
+
|
|
405
|
+
If any non-list input is given, it is converted to a list
|
|
406
|
+
of the same length as the others by repeating the same
|
|
407
|
+
element multiple times.
|
|
408
|
+
"""
|
|
409
|
+
lengths = set()
|
|
410
|
+
new_lists = []
|
|
411
|
+
for lst in lists:
|
|
412
|
+
if isinstance(lst, list):
|
|
413
|
+
lengths.add(len(lst))
|
|
414
|
+
new_lists.append(lst)
|
|
415
|
+
else:
|
|
416
|
+
new_lst = [lst] * max(lengths)
|
|
417
|
+
new_lists.append(new_lst)
|
|
418
|
+
lengths.add(len(new_lst))
|
|
419
|
+
if len(lengths) > 1:
|
|
420
|
+
raise ValueError(
|
|
421
|
+
"Inconsistent RayDistributedCollector parameters. create_env_fn, "
|
|
422
|
+
"collector_kwargs and remote_configs are lists of different length."
|
|
423
|
+
)
|
|
424
|
+
else:
|
|
425
|
+
return new_lists
|
|
426
|
+
|
|
427
|
+
out_lists = check_list_length_consistency(
|
|
428
|
+
create_env_fn, collector_kwargs, remote_configs
|
|
429
|
+
)
|
|
430
|
+
create_env_fn, collector_kwargs, remote_configs = out_lists
|
|
431
|
+
num_collectors = len(create_env_fn)
|
|
432
|
+
|
|
433
|
+
if use_env_creator:
|
|
434
|
+
for i in range(len(create_env_fn)):
|
|
435
|
+
if not isinstance(create_env_fn[i], (EnvBase, EnvCreator)):
|
|
436
|
+
create_env_fn[i] = EnvCreator(create_env_fn[i])
|
|
437
|
+
|
|
438
|
+
# If ray available, try to connect to an existing Ray cluster or start one and connect to it.
|
|
439
|
+
if not _has_ray:
|
|
440
|
+
raise RuntimeError(
|
|
441
|
+
"ray library not found, unable to create a DistributedCollector. "
|
|
442
|
+
) from RAY_ERR
|
|
443
|
+
if not ray.is_initialized():
|
|
444
|
+
ray.init(**ray_init_config)
|
|
445
|
+
if not ray.is_initialized():
|
|
446
|
+
raise RuntimeError("Ray could not be initialized.")
|
|
447
|
+
|
|
448
|
+
# Define collector_class, monkey patch it with as_remote and print_remote_collector_info methods
|
|
449
|
+
if collector_class == "async":
|
|
450
|
+
collector_class = MultiAsyncCollector
|
|
451
|
+
elif collector_class == "sync":
|
|
452
|
+
collector_class = MultiSyncCollector
|
|
453
|
+
elif collector_class == "single":
|
|
454
|
+
collector_class = Collector
|
|
455
|
+
elif not isinstance(collector_class, type) or not issubclass(
|
|
456
|
+
collector_class, BaseCollector
|
|
457
|
+
):
|
|
458
|
+
raise TypeError("The collector_class must be an instance of BaseCollector.")
|
|
459
|
+
if not hasattr(collector_class, "as_remote"):
|
|
460
|
+
collector_class.as_remote = as_remote
|
|
461
|
+
if not hasattr(collector_class, "print_remote_collector_info"):
|
|
462
|
+
collector_class.print_remote_collector_info = print_remote_collector_info
|
|
463
|
+
|
|
464
|
+
self.no_cuda_sync = no_cuda_sync
|
|
465
|
+
self.replay_buffer = replay_buffer
|
|
466
|
+
if not isinstance(policy_factory, Sequence):
|
|
467
|
+
policy_factory = [policy_factory] * len(create_env_fn)
|
|
468
|
+
self.policy_factory = policy_factory
|
|
469
|
+
self.policy = policy # Store policy for weight extraction
|
|
470
|
+
self.trust_policy = trust_policy
|
|
471
|
+
if isinstance(policy, nn.Module):
|
|
472
|
+
policy_weights = TensorDict.from_module(policy)
|
|
473
|
+
policy_weights = policy_weights.data.lock_()
|
|
474
|
+
else:
|
|
475
|
+
policy_weights = TensorDict(lock=True)
|
|
476
|
+
if weight_updater is None:
|
|
477
|
+
warnings.warn(_NON_NN_POLICY_WEIGHTS)
|
|
478
|
+
self.policy_weights = policy_weights
|
|
479
|
+
self.collector_class = collector_class
|
|
480
|
+
self.collected_frames = 0
|
|
481
|
+
self.split_trajs = split_trajs
|
|
482
|
+
self.total_frames = total_frames
|
|
483
|
+
self.num_collectors = num_collectors
|
|
484
|
+
|
|
485
|
+
self.update_after_each_batch = update_after_each_batch
|
|
486
|
+
self.max_weight_update_interval = max_weight_update_interval
|
|
487
|
+
|
|
488
|
+
self.collector_kwargs = (
|
|
489
|
+
collector_kwargs if collector_kwargs is not None else [{}]
|
|
490
|
+
)
|
|
491
|
+
self.device = device
|
|
492
|
+
self.storing_device = storing_device
|
|
493
|
+
self.env_device = env_device
|
|
494
|
+
self.policy_device = policy_device
|
|
495
|
+
self._batches_since_weight_update = [0 for _ in range(self.num_collectors)]
|
|
496
|
+
self._sync = sync
|
|
497
|
+
self._collection_thread = None
|
|
498
|
+
self._stop_event = threading.Event()
|
|
499
|
+
|
|
500
|
+
if self._sync:
|
|
501
|
+
if frames_per_batch % self.num_collectors != 0:
|
|
502
|
+
raise RuntimeError(
|
|
503
|
+
f"Cannot dispatch {frames_per_batch} frames across {self.num_collectors}. "
|
|
504
|
+
f"Consider using a number of frames per batch that is divisible by the number of workers."
|
|
505
|
+
)
|
|
506
|
+
self._frames_per_batch_corrected = frames_per_batch // self.num_collectors
|
|
507
|
+
else:
|
|
508
|
+
self._frames_per_batch_corrected = frames_per_batch
|
|
509
|
+
|
|
510
|
+
# update collector kwargs
|
|
511
|
+
for i, collector_kwarg in enumerate(self.collector_kwargs):
|
|
512
|
+
# Don't pass policy_factory if we have a policy - remote collectors need the policy object
|
|
513
|
+
# to be able to apply weight updates
|
|
514
|
+
if policy is None:
|
|
515
|
+
collector_kwarg["policy_factory"] = policy_factory[i]
|
|
516
|
+
collector_kwarg["max_frames_per_traj"] = max_frames_per_traj
|
|
517
|
+
collector_kwarg["init_random_frames"] = (
|
|
518
|
+
init_random_frames // self.num_collectors
|
|
519
|
+
)
|
|
520
|
+
if not self._sync and init_random_frames > 0:
|
|
521
|
+
warnings.warn(
|
|
522
|
+
"async distributed data collection with init_random_frames > 0 "
|
|
523
|
+
"may have unforeseen consequences as we do not control that once "
|
|
524
|
+
"non-random data is being collected all nodes are returning non-random data. "
|
|
525
|
+
"If this is a feature that you feel should be fixed, please raise an issue on "
|
|
526
|
+
"torchrl's repo."
|
|
527
|
+
)
|
|
528
|
+
collector_kwarg["reset_at_each_iter"] = reset_at_each_iter
|
|
529
|
+
collector_kwarg["exploration_type"] = exploration_type
|
|
530
|
+
collector_kwarg["split_trajs"] = False
|
|
531
|
+
collector_kwarg["frames_per_batch"] = self._frames_per_batch_corrected
|
|
532
|
+
collector_kwarg["device"] = self.device[i]
|
|
533
|
+
collector_kwarg["storing_device"] = self.storing_device[i]
|
|
534
|
+
collector_kwarg["env_device"] = self.env_device[i]
|
|
535
|
+
collector_kwarg["policy_device"] = self.policy_device[i]
|
|
536
|
+
if "trust_policy" not in collector_kwarg:
|
|
537
|
+
collector_kwarg["trust_policy"] = self.trust_policy
|
|
538
|
+
if "no_cuda_sync" not in collector_kwarg and self.no_cuda_sync is not None:
|
|
539
|
+
collector_kwarg["no_cuda_sync"] = no_cuda_sync
|
|
540
|
+
|
|
541
|
+
self.postproc = postproc
|
|
542
|
+
|
|
543
|
+
# Create remote instances of the collector class
|
|
544
|
+
self._remote_collectors = []
|
|
545
|
+
if self.num_collectors > 0:
|
|
546
|
+
self.add_collectors(
|
|
547
|
+
create_env_fn,
|
|
548
|
+
num_workers_per_collector,
|
|
549
|
+
policy,
|
|
550
|
+
collector_kwargs,
|
|
551
|
+
remote_configs,
|
|
552
|
+
)
|
|
553
|
+
# Set up weight synchronization - prefer new schemes over legacy updater
|
|
554
|
+
if weight_updater is None and weight_sync_schemes is None:
|
|
555
|
+
# Default to Ray weight sync scheme for Ray collectors
|
|
556
|
+
from torchrl.weight_update import RayWeightSyncScheme
|
|
557
|
+
|
|
558
|
+
weight_sync_schemes = {"policy": RayWeightSyncScheme()}
|
|
559
|
+
|
|
560
|
+
if weight_sync_schemes is not None:
|
|
561
|
+
torchrl_logger.debug("RayCollector: Using weight sync schemes")
|
|
562
|
+
# Use new weight synchronization system
|
|
563
|
+
self._weight_sync_schemes = weight_sync_schemes
|
|
564
|
+
|
|
565
|
+
# Initialize schemes on the sender (main process) side
|
|
566
|
+
# Pass remote collectors as the "workers" for Ray schemes
|
|
567
|
+
for model_id, scheme in self._weight_sync_schemes.items():
|
|
568
|
+
torchrl_logger.debug(
|
|
569
|
+
f"RayCollector: Initializing sender for model '{model_id}'"
|
|
570
|
+
)
|
|
571
|
+
scheme.init_on_sender(
|
|
572
|
+
model_id=model_id,
|
|
573
|
+
remote_collectors=self.remote_collectors,
|
|
574
|
+
model=self.policy if model_id == "policy" else None,
|
|
575
|
+
context=self,
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
# Set up receiver schemes on remote collectors
|
|
579
|
+
# This enables the remote collectors to receive weight updates
|
|
580
|
+
for remote_collector in self.remote_collectors:
|
|
581
|
+
torchrl_logger.debug(
|
|
582
|
+
f"RayCollector: Registering scheme receiver for remote collector {remote_collector}"
|
|
583
|
+
)
|
|
584
|
+
fut = remote_collector.register_scheme_receiver.remote(
|
|
585
|
+
self._weight_sync_schemes, synchronize_weights=False
|
|
586
|
+
)
|
|
587
|
+
ray.get(fut)
|
|
588
|
+
|
|
589
|
+
self.weight_updater = None # Don't use legacy system
|
|
590
|
+
else:
|
|
591
|
+
torchrl_logger.debug("RayCollector: Using legacy weight updater system")
|
|
592
|
+
# Fall back to legacy weight updater system
|
|
593
|
+
if weight_updater is None:
|
|
594
|
+
weight_updater = RayWeightUpdater(
|
|
595
|
+
policy_weights=policy_weights,
|
|
596
|
+
remote_collectors=self.remote_collectors,
|
|
597
|
+
max_interval=self.max_weight_update_interval,
|
|
598
|
+
)
|
|
599
|
+
self.weight_updater = weight_updater
|
|
600
|
+
self._weight_sync_schemes = None
|
|
601
|
+
|
|
602
|
+
# Always initialize this flag - legacy system doesn't need lazy init
|
|
603
|
+
# but we set it for consistency
|
|
604
|
+
self._weight_sync_initialized = False
|
|
605
|
+
|
|
606
|
+
# Set up weight receivers if provided
|
|
607
|
+
if weight_recv_schemes is not None:
|
|
608
|
+
torchrl_logger.debug("RayCollector: Setting up weight receivers...")
|
|
609
|
+
self.register_scheme_receiver(weight_recv_schemes)
|
|
610
|
+
|
|
611
|
+
if not self._weight_sync_initialized:
|
|
612
|
+
self._lazy_initialize_weight_sync()
|
|
613
|
+
|
|
614
|
+
# Print info of all remote workers (fire and forget - no need to wait)
|
|
615
|
+
for e in self.remote_collectors:
|
|
616
|
+
e.print_remote_collector_info.remote()
|
|
617
|
+
|
|
618
|
+
def _lazy_initialize_weight_sync(self) -> None:
|
|
619
|
+
"""Initialize weight synchronization lazily on first update_policy_weights_() call.
|
|
620
|
+
|
|
621
|
+
This method performs the initial weight synchronization that was deferred from __init__.
|
|
622
|
+
It must be called before collection begins if weights need to be synced from a central policy.
|
|
623
|
+
|
|
624
|
+
The synchronization is done here (not in __init__) because:
|
|
625
|
+
1. When using policy_factory, there may be no central policy to sync from
|
|
626
|
+
2. Users may want to train the policy first before syncing weights
|
|
627
|
+
3. Different sub-collectors may have different policies via policy_factory
|
|
628
|
+
"""
|
|
629
|
+
if self._weight_sync_initialized:
|
|
630
|
+
return
|
|
631
|
+
|
|
632
|
+
if self._weight_sync_schemes is None:
|
|
633
|
+
# Legacy weight updater system doesn't use lazy init
|
|
634
|
+
self._weight_sync_initialized = True
|
|
635
|
+
return
|
|
636
|
+
|
|
637
|
+
torchrl_logger.debug("RayCollector: Performing lazy weight synchronization")
|
|
638
|
+
|
|
639
|
+
# Cascade synchronize_weights to remote collectors
|
|
640
|
+
torchrl_logger.debug(
|
|
641
|
+
"RayCollector: Cascading synchronize_weights to remote collectors"
|
|
642
|
+
)
|
|
643
|
+
self._sync_futures = []
|
|
644
|
+
for remote_collector in self.remote_collectors:
|
|
645
|
+
for model_id in self._weight_sync_schemes:
|
|
646
|
+
self._sync_futures.append(
|
|
647
|
+
remote_collector.cascade_execute.remote(
|
|
648
|
+
f"_receiver_schemes['{model_id}'].connect"
|
|
649
|
+
)
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
# Synchronize weights for each scheme
|
|
653
|
+
for model_id, scheme in self._weight_sync_schemes.items():
|
|
654
|
+
torchrl_logger.debug(
|
|
655
|
+
f"RayCollector: Synchronizing weights for model '{model_id}'"
|
|
656
|
+
)
|
|
657
|
+
scheme.connect()
|
|
658
|
+
|
|
659
|
+
# Block sync
|
|
660
|
+
torchrl_logger.debug(
|
|
661
|
+
"RayCollector: Waiting for weight synchronization to finish"
|
|
662
|
+
)
|
|
663
|
+
ray.get(self._sync_futures)
|
|
664
|
+
self._weight_sync_initialized = True
|
|
665
|
+
torchrl_logger.debug("RayCollector: Weight synchronization complete")
|
|
666
|
+
|
|
667
|
+
def _weight_update_impl(
|
|
668
|
+
self,
|
|
669
|
+
policy_or_weights: TensorDictBase | nn.Module | dict | None = None,
|
|
670
|
+
*,
|
|
671
|
+
worker_ids: int | list[int] | torch.device | list[torch.device] | None = None,
|
|
672
|
+
model_id: str | None = None,
|
|
673
|
+
weights_dict: dict[str, Any] | None = None,
|
|
674
|
+
**kwargs,
|
|
675
|
+
) -> None:
|
|
676
|
+
"""Override to trigger lazy weight sync initialization on first call.
|
|
677
|
+
|
|
678
|
+
When using policy_factory without a central policy, weight synchronization
|
|
679
|
+
is deferred until this method is called with actual weights.
|
|
680
|
+
"""
|
|
681
|
+
# Trigger lazy initialization if not already done
|
|
682
|
+
if not self._weight_sync_initialized:
|
|
683
|
+
self._lazy_initialize_weight_sync()
|
|
684
|
+
|
|
685
|
+
# Call parent implementation
|
|
686
|
+
return super()._weight_update_impl(
|
|
687
|
+
policy_or_weights=policy_or_weights,
|
|
688
|
+
worker_ids=worker_ids,
|
|
689
|
+
model_id=model_id,
|
|
690
|
+
weights_dict=weights_dict,
|
|
691
|
+
**kwargs,
|
|
692
|
+
)
|
|
693
|
+
|
|
694
|
+
# def _send_weights_scheme(self, *, scheme, processed_weights, worker_ids, model_id):
|
|
695
|
+
# if not worker_ids:
|
|
696
|
+
# worker_ids = list(range(self.num_collectors))
|
|
697
|
+
# futures = []
|
|
698
|
+
# for worker_id in worker_ids:
|
|
699
|
+
# torchrl_logger.debug(f"RayCollector: Sending weights to remote worker {worker_id}")
|
|
700
|
+
# # Call irecv
|
|
701
|
+
# fut = self.remote_collectors[worker_id].cascade_execute.remote(f"_receiver_schemes['{model_id}'].receive")
|
|
702
|
+
# futures.append(fut)
|
|
703
|
+
# torchrl_logger.debug(f"RayCollector: calling isend")
|
|
704
|
+
# scheme.send(weights=processed_weights, worker_ids=worker_ids)
|
|
705
|
+
# torchrl_logger.debug(f"RayCollector: Waiting for {len(futures)} irecv calls to finish")
|
|
706
|
+
# ray.get(futures)
|
|
707
|
+
|
|
708
|
+
def _extract_weights_if_needed(self, weights: Any, model_id: str) -> Any:
|
|
709
|
+
"""Extract weights from a model if needed.
|
|
710
|
+
|
|
711
|
+
For Ray collectors, when weights is None and we have a weight sync scheme,
|
|
712
|
+
extract fresh weights from the tracked policy model.
|
|
713
|
+
"""
|
|
714
|
+
scheme = (
|
|
715
|
+
self._weight_sync_schemes.get(model_id)
|
|
716
|
+
if self._weight_sync_schemes
|
|
717
|
+
else None
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
if weights is None and scheme is not None:
|
|
721
|
+
# Extract fresh weights from the scheme's model
|
|
722
|
+
model = scheme.model
|
|
723
|
+
if model is not None:
|
|
724
|
+
from torchrl.weight_update.weight_sync_schemes import WeightStrategy
|
|
725
|
+
|
|
726
|
+
strategy = WeightStrategy(extract_as=scheme.strategy_str)
|
|
727
|
+
return strategy.extract_weights(model)
|
|
728
|
+
|
|
729
|
+
# Fall back to base class behavior
|
|
730
|
+
return super()._extract_weights_if_needed(weights, model_id)
|
|
731
|
+
|
|
732
|
+
@property
|
|
733
|
+
def num_workers(self):
|
|
734
|
+
return self.num_collectors
|
|
735
|
+
|
|
736
|
+
@property
|
|
737
|
+
def device(self) -> list[torch.device]:
|
|
738
|
+
return self._device
|
|
739
|
+
|
|
740
|
+
@property
|
|
741
|
+
def storing_device(self) -> list[torch.device]:
|
|
742
|
+
return self._storing_device
|
|
743
|
+
|
|
744
|
+
@property
|
|
745
|
+
def env_device(self) -> list[torch.device]:
|
|
746
|
+
return self._env_device
|
|
747
|
+
|
|
748
|
+
@property
|
|
749
|
+
def policy_device(self) -> list[torch.device]:
|
|
750
|
+
return self._policy_device
|
|
751
|
+
|
|
752
|
+
@device.setter
|
|
753
|
+
def device(self, value):
|
|
754
|
+
if isinstance(value, (tuple, list)):
|
|
755
|
+
self._device = value
|
|
756
|
+
else:
|
|
757
|
+
self._device = [value] * self.num_collectors
|
|
758
|
+
|
|
759
|
+
@storing_device.setter
|
|
760
|
+
def storing_device(self, value):
|
|
761
|
+
if isinstance(value, (tuple, list)):
|
|
762
|
+
self._storing_device = value
|
|
763
|
+
else:
|
|
764
|
+
self._storing_device = [value] * self.num_collectors
|
|
765
|
+
|
|
766
|
+
@env_device.setter
|
|
767
|
+
def env_device(self, value):
|
|
768
|
+
if isinstance(value, (tuple, list)):
|
|
769
|
+
self._env_device = value
|
|
770
|
+
else:
|
|
771
|
+
self._env_device = [value] * self.num_collectors
|
|
772
|
+
|
|
773
|
+
@policy_device.setter
|
|
774
|
+
def policy_device(self, value):
|
|
775
|
+
if isinstance(value, (tuple, list)):
|
|
776
|
+
self._policy_device = value
|
|
777
|
+
else:
|
|
778
|
+
self._policy_device = [value] * self.num_collectors
|
|
779
|
+
|
|
780
|
+
@staticmethod
|
|
781
|
+
def _make_collector(cls, *, env_maker, policy, other_params):
|
|
782
|
+
"""Create a single collector instance."""
|
|
783
|
+
if policy is not None:
|
|
784
|
+
other_params["policy"] = policy
|
|
785
|
+
collector = cls(
|
|
786
|
+
env_maker,
|
|
787
|
+
total_frames=-1,
|
|
788
|
+
**other_params,
|
|
789
|
+
)
|
|
790
|
+
return collector
|
|
791
|
+
|
|
792
|
+
def add_collectors(
|
|
793
|
+
self,
|
|
794
|
+
create_env_fn,
|
|
795
|
+
num_envs,
|
|
796
|
+
policy,
|
|
797
|
+
collector_kwargs,
|
|
798
|
+
remote_configs,
|
|
799
|
+
):
|
|
800
|
+
"""Creates and adds a number of remote collectors to the set."""
|
|
801
|
+
for i, (env_maker, other_params, remote_config) in enumerate(
|
|
802
|
+
zip(create_env_fn, collector_kwargs, remote_configs)
|
|
803
|
+
):
|
|
804
|
+
# Add worker_idx to params so remote collectors know their index
|
|
805
|
+
other_params = dict(other_params) # Make a copy to avoid mutating original
|
|
806
|
+
other_params["worker_idx"] = i
|
|
807
|
+
|
|
808
|
+
cls = self.collector_class.as_remote(remote_config).remote
|
|
809
|
+
collector = self._make_collector(
|
|
810
|
+
cls,
|
|
811
|
+
env_maker=[env_maker] * num_envs
|
|
812
|
+
if num_envs > 1
|
|
813
|
+
or (
|
|
814
|
+
isinstance(self.collector_class, type)
|
|
815
|
+
and not issubclass(self.collector_class, Collector)
|
|
816
|
+
)
|
|
817
|
+
else env_maker,
|
|
818
|
+
policy=policy,
|
|
819
|
+
other_params=other_params,
|
|
820
|
+
)
|
|
821
|
+
self._remote_collectors.append(collector)
|
|
822
|
+
|
|
823
|
+
def local_policy(self):
|
|
824
|
+
"""Returns local collector."""
|
|
825
|
+
return self._local_policy
|
|
826
|
+
|
|
827
|
+
@property
|
|
828
|
+
def remote_collectors(self):
|
|
829
|
+
"""Returns list of remote collectors."""
|
|
830
|
+
return self._remote_collectors
|
|
831
|
+
|
|
832
|
+
def stop_remote_collectors(self):
|
|
833
|
+
"""Stops all remote collectors."""
|
|
834
|
+
for _ in range(len(self._remote_collectors)):
|
|
835
|
+
collector = self.remote_collectors.pop()
|
|
836
|
+
# collector.__ray_terminate__.remote() # This will kill the actor but let pending tasks finish
|
|
837
|
+
ray.kill(
|
|
838
|
+
collector
|
|
839
|
+
) # This will interrupt any running tasks on the actor, causing them to fail immediately
|
|
840
|
+
|
|
841
|
+
def iterator(self):
|
|
842
|
+
# Warn if weight sync wasn't initialized before collection starts
|
|
843
|
+
if not self._weight_sync_initialized and self._weight_sync_schemes is not None:
|
|
844
|
+
warnings.warn(
|
|
845
|
+
"RayCollector iteration started before weight synchronization was initialized. "
|
|
846
|
+
"Call update_policy_weights_(policy_or_weights) before iterating to sync weights "
|
|
847
|
+
"from a central policy to remote collectors. If using policy_factory with "
|
|
848
|
+
"independent policies on each collector, you can ignore this warning.",
|
|
849
|
+
UserWarning,
|
|
850
|
+
stacklevel=2,
|
|
851
|
+
)
|
|
852
|
+
|
|
853
|
+
def proc(data):
|
|
854
|
+
# When using RayReplayBuffer, sub-collectors write directly to buffer
|
|
855
|
+
# and return None, so skip processing
|
|
856
|
+
if data is None:
|
|
857
|
+
return None
|
|
858
|
+
if self.split_trajs:
|
|
859
|
+
data = split_trajectories(data)
|
|
860
|
+
if self.postproc is not None:
|
|
861
|
+
data = self.postproc(data)
|
|
862
|
+
return data
|
|
863
|
+
|
|
864
|
+
if self._sync:
|
|
865
|
+
meth = self._sync_iterator
|
|
866
|
+
else:
|
|
867
|
+
meth = self._async_iterator
|
|
868
|
+
yield from (proc(data) for data in meth())
|
|
869
|
+
|
|
870
|
+
async def _asyncio_iterator(self):
|
|
871
|
+
def proc(data):
|
|
872
|
+
# When using RayReplayBuffer, sub-collectors write directly to buffer
|
|
873
|
+
# and return None, so skip processing
|
|
874
|
+
if data is None:
|
|
875
|
+
return None
|
|
876
|
+
if self.split_trajs:
|
|
877
|
+
data = split_trajectories(data)
|
|
878
|
+
if self.postproc is not None:
|
|
879
|
+
data = self.postproc(data)
|
|
880
|
+
return data
|
|
881
|
+
|
|
882
|
+
if self._sync:
|
|
883
|
+
for d in self._sync_iterator():
|
|
884
|
+
yield proc(d)
|
|
885
|
+
else:
|
|
886
|
+
for d in self._async_iterator():
|
|
887
|
+
yield proc(d)
|
|
888
|
+
|
|
889
|
+
def _sync_iterator(self) -> Iterator[TensorDictBase]:
|
|
890
|
+
"""Collects one data batch per remote collector in each iteration."""
|
|
891
|
+
while (
|
|
892
|
+
self.collected_frames < self.total_frames and not self._stop_event.is_set()
|
|
893
|
+
):
|
|
894
|
+
if self.update_after_each_batch or self.max_weight_update_interval > -1:
|
|
895
|
+
torchrl_logger.debug("Updating weights on all workers")
|
|
896
|
+
self.update_policy_weights_()
|
|
897
|
+
|
|
898
|
+
# Ask for batches to all remote workers.
|
|
899
|
+
pending_tasks = [e.next.remote() for e in self.remote_collectors]
|
|
900
|
+
|
|
901
|
+
# Wait for all rollouts
|
|
902
|
+
samples_ready = []
|
|
903
|
+
while len(samples_ready) < self.num_collectors:
|
|
904
|
+
samples_ready, samples_not_ready = ray.wait(
|
|
905
|
+
pending_tasks, num_returns=len(pending_tasks)
|
|
906
|
+
)
|
|
907
|
+
|
|
908
|
+
# Retrieve and concatenate Tensordicts
|
|
909
|
+
out_td = []
|
|
910
|
+
for r in pending_tasks:
|
|
911
|
+
rollouts = ray.get(r)
|
|
912
|
+
ray.internal.free(
|
|
913
|
+
r
|
|
914
|
+
) # should not be necessary, deleted automatically when ref count is down to 0
|
|
915
|
+
out_td.append(rollouts)
|
|
916
|
+
|
|
917
|
+
# Handle case where replay_buffer is used and rollouts are None
|
|
918
|
+
if out_td[0] is None:
|
|
919
|
+
# Sub-collectors are writing directly to RayReplayBuffer
|
|
920
|
+
# Track frames and yield None to signal completion
|
|
921
|
+
self.collected_frames += self.frames_per_batch
|
|
922
|
+
yield None
|
|
923
|
+
else:
|
|
924
|
+
# Normal case: concatenate and yield rollouts
|
|
925
|
+
if len(rollouts.batch_size):
|
|
926
|
+
out_td = torch.stack(out_td)
|
|
927
|
+
else:
|
|
928
|
+
out_td = torch.cat(out_td)
|
|
929
|
+
|
|
930
|
+
self.collected_frames += out_td.numel()
|
|
931
|
+
yield out_td
|
|
932
|
+
|
|
933
|
+
# Only auto-shutdown if not running in a background thread.
|
|
934
|
+
# When using replay buffer, users should explicitly manage shutdown order.
|
|
935
|
+
if self._collection_thread is None:
|
|
936
|
+
self.shutdown(shutdown_ray=False)
|
|
937
|
+
|
|
938
|
+
def _run_collection_loop(self):
|
|
939
|
+
"""Runs the collection loop in a background thread."""
|
|
940
|
+
try:
|
|
941
|
+
for _ in self.iterator():
|
|
942
|
+
if self._stop_event.is_set():
|
|
943
|
+
break
|
|
944
|
+
# When RayReplayBuffer is configured, sub-collectors write directly
|
|
945
|
+
# to the buffer and data will be None. Otherwise, data contains rollouts.
|
|
946
|
+
except Exception as e:
|
|
947
|
+
torchrl_logger.error(f"Error in collection thread: {e}")
|
|
948
|
+
raise
|
|
949
|
+
|
|
950
|
+
def start(self):
|
|
951
|
+
"""Starts the RayCollector in a background thread."""
|
|
952
|
+
if self.replay_buffer is None:
|
|
953
|
+
raise RuntimeError(
|
|
954
|
+
"Replay buffer must be defined for background execution."
|
|
955
|
+
)
|
|
956
|
+
if self._collection_thread is None or not self._collection_thread.is_alive():
|
|
957
|
+
self._stop_event.clear()
|
|
958
|
+
self._collection_thread = threading.Thread(
|
|
959
|
+
target=self._run_collection_loop, daemon=True
|
|
960
|
+
)
|
|
961
|
+
self._collection_thread.start()
|
|
962
|
+
|
|
963
|
+
async def async_shutdown(self, shutdown_ray: bool = False):
|
|
964
|
+
"""Finishes processes started by the collector during async execution.
|
|
965
|
+
|
|
966
|
+
Args:
|
|
967
|
+
shutdown_ray (bool): If True, also shutdown the Ray cluster. Defaults to False.
|
|
968
|
+
Note: Setting this to True will kill all Ray actors in the cluster, including
|
|
969
|
+
any replay buffers or other services. Only set to True if you're sure you want
|
|
970
|
+
to shut down the entire Ray cluster.
|
|
971
|
+
|
|
972
|
+
"""
|
|
973
|
+
self._stop_event.set()
|
|
974
|
+
if self._collection_thread is not None and self._collection_thread.is_alive():
|
|
975
|
+
self._collection_thread.join(timeout=5.0)
|
|
976
|
+
self.stop_remote_collectors()
|
|
977
|
+
if shutdown_ray:
|
|
978
|
+
ray.shutdown()
|
|
979
|
+
|
|
980
|
+
def _async_iterator(self) -> Iterator[TensorDictBase]:
|
|
981
|
+
"""Collects a data batch from a single remote collector in each iteration."""
|
|
982
|
+
pending_tasks = {}
|
|
983
|
+
for index, collector in enumerate(self.remote_collectors):
|
|
984
|
+
future = collector.next.remote()
|
|
985
|
+
pending_tasks[future] = index
|
|
986
|
+
|
|
987
|
+
while (
|
|
988
|
+
self.collected_frames < self.total_frames and not self._stop_event.is_set()
|
|
989
|
+
):
|
|
990
|
+
if not len(list(pending_tasks.keys())) == len(self.remote_collectors):
|
|
991
|
+
raise RuntimeError("Missing pending tasks, something went wrong")
|
|
992
|
+
|
|
993
|
+
# Wait for first worker to finish
|
|
994
|
+
wait_results = ray.wait(list(pending_tasks.keys()))
|
|
995
|
+
future = wait_results[0][0]
|
|
996
|
+
collector_index = pending_tasks.pop(future)
|
|
997
|
+
collector = self.remote_collectors[collector_index]
|
|
998
|
+
|
|
999
|
+
# Retrieve single rollouts
|
|
1000
|
+
out_td = ray.get(future)
|
|
1001
|
+
ray.internal.free(
|
|
1002
|
+
[future]
|
|
1003
|
+
) # should not be necessary, deleted automatically when ref count is down to 0
|
|
1004
|
+
|
|
1005
|
+
# Track collected frames - use frames_per_batch since out_td might be None
|
|
1006
|
+
# when using RayReplayBuffer (sub-collectors write directly to buffer)
|
|
1007
|
+
self.collected_frames += self.frames_per_batch
|
|
1008
|
+
|
|
1009
|
+
yield out_td
|
|
1010
|
+
|
|
1011
|
+
if self.update_after_each_batch or self.max_weight_update_interval > -1:
|
|
1012
|
+
torchrl_logger.debug(f"Updating weights on worker {collector_index}")
|
|
1013
|
+
self.update_policy_weights_(worker_ids=collector_index + 1)
|
|
1014
|
+
|
|
1015
|
+
# Schedule a new collection task
|
|
1016
|
+
future = collector.next.remote()
|
|
1017
|
+
pending_tasks[future] = collector_index
|
|
1018
|
+
|
|
1019
|
+
# Wait for the in-process collections tasks to finish.
|
|
1020
|
+
refs = list(pending_tasks.keys())
|
|
1021
|
+
ray.wait(refs, num_returns=len(refs))
|
|
1022
|
+
|
|
1023
|
+
# Cancel the in-process collections tasks
|
|
1024
|
+
# for ref in refs:
|
|
1025
|
+
# ray.cancel(
|
|
1026
|
+
# object_ref=ref,
|
|
1027
|
+
# force=False,
|
|
1028
|
+
# )
|
|
1029
|
+
if self._collection_thread is None:
|
|
1030
|
+
self.shutdown()
|
|
1031
|
+
|
|
1032
|
+
def set_seed(self, seed: int, static_seed: bool = False) -> list[int]:
|
|
1033
|
+
"""Calls parent method for each remote collector iteratively and returns final seed."""
|
|
1034
|
+
for collector in self.remote_collectors:
|
|
1035
|
+
seed = ray.get(object_refs=collector.set_seed.remote(seed, static_seed))
|
|
1036
|
+
return seed
|
|
1037
|
+
|
|
1038
|
+
def state_dict(self) -> list[OrderedDict]:
|
|
1039
|
+
"""Calls parent method for each remote collector and returns a list of results."""
|
|
1040
|
+
futures = [
|
|
1041
|
+
collector.state_dict.remote() for collector in self.remote_collectors
|
|
1042
|
+
]
|
|
1043
|
+
results = ray.get(object_refs=futures)
|
|
1044
|
+
return results
|
|
1045
|
+
|
|
1046
|
+
def load_state_dict(self, state_dict: OrderedDict | list[OrderedDict]) -> None:
|
|
1047
|
+
"""Calls parent method for each remote collector."""
|
|
1048
|
+
if isinstance(state_dict, OrderedDict):
|
|
1049
|
+
state_dicts = [state_dict]
|
|
1050
|
+
if len(state_dict) == 1:
|
|
1051
|
+
state_dicts = state_dict * len(self.remote_collectors)
|
|
1052
|
+
for collector, state_dict in zip(self.remote_collectors, state_dicts):
|
|
1053
|
+
collector.load_state_dict.remote(state_dict)
|
|
1054
|
+
|
|
1055
|
+
def shutdown(
|
|
1056
|
+
self, timeout: float | None = None, shutdown_ray: bool = False
|
|
1057
|
+
) -> None:
|
|
1058
|
+
"""Finishes processes started by the collector.
|
|
1059
|
+
|
|
1060
|
+
Args:
|
|
1061
|
+
timeout (float, optional): Timeout for stopping the collection thread.
|
|
1062
|
+
shutdown_ray (bool): If True, also shutdown the Ray cluster. Defaults to False.
|
|
1063
|
+
Note: Setting this to True will kill all Ray actors in the cluster, including
|
|
1064
|
+
any replay buffers or other services. Only set to True if you're sure you want
|
|
1065
|
+
to shut down the entire Ray cluster.
|
|
1066
|
+
|
|
1067
|
+
"""
|
|
1068
|
+
self._stop_event.set()
|
|
1069
|
+
if self._collection_thread is not None and self._collection_thread.is_alive():
|
|
1070
|
+
self._collection_thread.join(
|
|
1071
|
+
timeout=timeout if timeout is not None else 5.0
|
|
1072
|
+
)
|
|
1073
|
+
self.stop_remote_collectors()
|
|
1074
|
+
|
|
1075
|
+
# Clean up weight sync schemes AFTER workers have exited
|
|
1076
|
+
if getattr(self, "_weight_sync_schemes", None) is not None:
|
|
1077
|
+
torchrl_logger.debug("shutting down weight sync schemes")
|
|
1078
|
+
for scheme in self._weight_sync_schemes.values():
|
|
1079
|
+
try:
|
|
1080
|
+
scheme.shutdown()
|
|
1081
|
+
except Exception as e:
|
|
1082
|
+
torchrl_logger.warning(
|
|
1083
|
+
f"Error shutting down weight sync scheme: {e}"
|
|
1084
|
+
)
|
|
1085
|
+
self._weight_sync_schemes = None
|
|
1086
|
+
|
|
1087
|
+
if shutdown_ray:
|
|
1088
|
+
ray.shutdown()
|
|
1089
|
+
|
|
1090
|
+
def __repr__(self) -> str:
|
|
1091
|
+
string = f"{self.__class__.__name__}()"
|
|
1092
|
+
return string
|