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,1306 @@
|
|
|
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
|
+
r"""Generic distributed data-collector using torch.distributed backend."""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import socket
|
|
11
|
+
import warnings
|
|
12
|
+
from collections import OrderedDict
|
|
13
|
+
from collections.abc import Callable, Sequence
|
|
14
|
+
from copy import copy, deepcopy
|
|
15
|
+
from datetime import timedelta
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import torch.cuda
|
|
19
|
+
from tensordict import TensorDict, TensorDictBase
|
|
20
|
+
from tensordict.nn import TensorDictModuleBase
|
|
21
|
+
from torch import nn
|
|
22
|
+
from torchrl._utils import (
|
|
23
|
+
_get_mp_ctx,
|
|
24
|
+
_ProcessNoWarn,
|
|
25
|
+
logger as torchrl_logger,
|
|
26
|
+
VERBOSE,
|
|
27
|
+
)
|
|
28
|
+
from torchrl.collectors._base import _LegacyCollectorMeta, BaseCollector
|
|
29
|
+
from torchrl.collectors._constants import DEFAULT_EXPLORATION_TYPE
|
|
30
|
+
from torchrl.collectors._multi_async import MultiAsyncCollector
|
|
31
|
+
from torchrl.collectors._multi_base import MultiCollector
|
|
32
|
+
from torchrl.collectors._multi_sync import MultiSyncCollector
|
|
33
|
+
from torchrl.collectors._single import Collector
|
|
34
|
+
from torchrl.collectors.distributed.default_configs import (
|
|
35
|
+
_create_tcpstore_with_retry,
|
|
36
|
+
DEFAULT_SLURM_CONF,
|
|
37
|
+
MAX_TIME_TO_CONNECT,
|
|
38
|
+
TCP_PORT,
|
|
39
|
+
)
|
|
40
|
+
from torchrl.collectors.utils import _cast, _NON_NN_POLICY_WEIGHTS, split_trajectories
|
|
41
|
+
from torchrl.collectors.weight_update import WeightUpdaterBase
|
|
42
|
+
from torchrl.data.utils import CloudpickleWrapper
|
|
43
|
+
from torchrl.envs.common import EnvBase
|
|
44
|
+
from torchrl.envs.env_creator import EnvCreator
|
|
45
|
+
from torchrl.weight_update import DistributedWeightSyncScheme
|
|
46
|
+
from torchrl.weight_update.weight_sync_schemes import WeightSyncScheme
|
|
47
|
+
|
|
48
|
+
SUBMITIT_ERR = None
|
|
49
|
+
try:
|
|
50
|
+
import submitit
|
|
51
|
+
|
|
52
|
+
_has_submitit = True
|
|
53
|
+
except ModuleNotFoundError as err:
|
|
54
|
+
_has_submitit = False
|
|
55
|
+
SUBMITIT_ERR = err
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _node_init_dist(rank, world_size, backend, rank0_ip, tcpport, verbose):
|
|
59
|
+
os.environ["MASTER_ADDR"] = str(rank0_ip)
|
|
60
|
+
os.environ["MASTER_PORT"] = str(tcpport)
|
|
61
|
+
|
|
62
|
+
if verbose:
|
|
63
|
+
torchrl_logger.debug(
|
|
64
|
+
f"Rank0 IP address: '{rank0_ip}' \ttcp port: '{tcpport}', backend={backend}."
|
|
65
|
+
)
|
|
66
|
+
torchrl_logger.debug(
|
|
67
|
+
f"RANK {rank} with world_size {world_size} -- launching distributed"
|
|
68
|
+
)
|
|
69
|
+
torch.distributed.init_process_group(
|
|
70
|
+
backend,
|
|
71
|
+
rank=rank,
|
|
72
|
+
world_size=world_size,
|
|
73
|
+
timeout=timedelta(MAX_TIME_TO_CONNECT),
|
|
74
|
+
init_method=f"tcp://{rank0_ip}:{tcpport}",
|
|
75
|
+
)
|
|
76
|
+
if verbose:
|
|
77
|
+
torchrl_logger.debug(f"Connected!\nRANK {rank} -- creating store")
|
|
78
|
+
|
|
79
|
+
# Receive actual store port from master via broadcast (master may have used retry)
|
|
80
|
+
store_port_tensor = torch.zeros(1, dtype=torch.int64)
|
|
81
|
+
torch.distributed.broadcast(store_port_tensor, src=0)
|
|
82
|
+
actual_store_port = int(store_port_tensor.item())
|
|
83
|
+
if verbose:
|
|
84
|
+
torchrl_logger.debug(
|
|
85
|
+
f"RANK {rank} -- received store port {actual_store_port} from master"
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# The store carries instructions for the node
|
|
89
|
+
_store = torch.distributed.TCPStore(
|
|
90
|
+
host_name=rank0_ip,
|
|
91
|
+
port=actual_store_port,
|
|
92
|
+
world_size=world_size,
|
|
93
|
+
is_master=False,
|
|
94
|
+
timeout=timedelta(10),
|
|
95
|
+
)
|
|
96
|
+
return _store
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _distributed_init_delayed(
|
|
100
|
+
rank,
|
|
101
|
+
backend,
|
|
102
|
+
rank0_ip,
|
|
103
|
+
tcpport,
|
|
104
|
+
world_size,
|
|
105
|
+
verbose=False,
|
|
106
|
+
):
|
|
107
|
+
"""Initializer for contexts where jobs cannot be launched from main node.
|
|
108
|
+
|
|
109
|
+
This function will wait for the main worker to send the launch command.
|
|
110
|
+
"""
|
|
111
|
+
_store = _node_init_dist(rank, world_size, backend, rank0_ip, tcpport, verbose)
|
|
112
|
+
# wait...
|
|
113
|
+
objects = [
|
|
114
|
+
None,
|
|
115
|
+
] * world_size
|
|
116
|
+
output_list = [None]
|
|
117
|
+
torch.distributed.scatter_object_list(output_list, objects, src=0)
|
|
118
|
+
output = output_list[0]
|
|
119
|
+
sync = output["sync"]
|
|
120
|
+
collector_class = output["collector_class"]
|
|
121
|
+
num_workers = output["num_workers"]
|
|
122
|
+
env_make = output["env_make"]
|
|
123
|
+
policy = output["policy"]
|
|
124
|
+
frames_per_batch = output["frames_per_batch"]
|
|
125
|
+
collector_kwargs = output["collector_kwargs"]
|
|
126
|
+
_run_collector(
|
|
127
|
+
_store=_store,
|
|
128
|
+
sync=sync,
|
|
129
|
+
collector_class=collector_class,
|
|
130
|
+
num_workers=num_workers,
|
|
131
|
+
env_make=env_make,
|
|
132
|
+
policy=policy,
|
|
133
|
+
frames_per_batch=frames_per_batch,
|
|
134
|
+
collector_kwargs=collector_kwargs,
|
|
135
|
+
verbose=verbose,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _distributed_init_collection_node(
|
|
140
|
+
*,
|
|
141
|
+
rank,
|
|
142
|
+
rank0_ip,
|
|
143
|
+
tcpport,
|
|
144
|
+
sync,
|
|
145
|
+
world_size,
|
|
146
|
+
backend,
|
|
147
|
+
collector_class,
|
|
148
|
+
num_workers,
|
|
149
|
+
env_make,
|
|
150
|
+
policy,
|
|
151
|
+
policy_factory,
|
|
152
|
+
frames_per_batch,
|
|
153
|
+
collector_kwargs,
|
|
154
|
+
weight_sync_schemes,
|
|
155
|
+
verbose=True,
|
|
156
|
+
):
|
|
157
|
+
_store = _node_init_dist(rank, world_size, backend, rank0_ip, tcpport, verbose)
|
|
158
|
+
_run_collector(
|
|
159
|
+
_store=_store,
|
|
160
|
+
sync=sync,
|
|
161
|
+
collector_class=collector_class,
|
|
162
|
+
num_workers=num_workers,
|
|
163
|
+
env_make=env_make,
|
|
164
|
+
policy=policy,
|
|
165
|
+
policy_factory=policy_factory,
|
|
166
|
+
frames_per_batch=frames_per_batch,
|
|
167
|
+
weight_sync_schemes=weight_sync_schemes,
|
|
168
|
+
collector_kwargs=collector_kwargs,
|
|
169
|
+
verbose=verbose,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _run_collector(
|
|
174
|
+
*,
|
|
175
|
+
_store,
|
|
176
|
+
sync,
|
|
177
|
+
collector_class,
|
|
178
|
+
num_workers,
|
|
179
|
+
env_make,
|
|
180
|
+
policy,
|
|
181
|
+
policy_factory,
|
|
182
|
+
frames_per_batch,
|
|
183
|
+
collector_kwargs,
|
|
184
|
+
weight_sync_schemes: dict[str, DistributedWeightSyncScheme],
|
|
185
|
+
verbose=True,
|
|
186
|
+
):
|
|
187
|
+
rank = torch.distributed.get_rank()
|
|
188
|
+
if verbose:
|
|
189
|
+
torchrl_logger.debug(
|
|
190
|
+
f"RANK {rank} -- creating collector of type {collector_class}"
|
|
191
|
+
)
|
|
192
|
+
if not issubclass(collector_class, Collector):
|
|
193
|
+
env_make = [env_make] * num_workers
|
|
194
|
+
else:
|
|
195
|
+
collector_kwargs["return_same_td"] = True
|
|
196
|
+
if num_workers != 1:
|
|
197
|
+
raise RuntimeError(
|
|
198
|
+
"Collector and subclasses can only support a single environment."
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
if issubclass(collector_class, MultiCollector) and (
|
|
202
|
+
(not isinstance(policy_factory, Sequence) and policy_factory is not None)
|
|
203
|
+
or (isinstance(policy_factory, Sequence) and any(policy_factory))
|
|
204
|
+
):
|
|
205
|
+
# We build an intermediate policy to get the weights from for weight updates. This is slow
|
|
206
|
+
# (main -> dist worker -> mp worker), but in some cases there is no alternative
|
|
207
|
+
policy = (
|
|
208
|
+
policy_factory[0]()
|
|
209
|
+
if isinstance(policy_factory, Sequence)
|
|
210
|
+
else policy_factory()
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
if isinstance(policy, nn.Module):
|
|
214
|
+
policy_weights = TensorDict.from_module(policy)
|
|
215
|
+
policy_weights = policy_weights.data.apply(_cast, policy_weights).lock_()
|
|
216
|
+
else:
|
|
217
|
+
if collector_kwargs.get("weight_updater") is None and (
|
|
218
|
+
policy_factory is None
|
|
219
|
+
or (isinstance(policy_factory, Sequence) and not any(policy_factory))
|
|
220
|
+
):
|
|
221
|
+
warnings.warn(_NON_NN_POLICY_WEIGHTS)
|
|
222
|
+
policy_weights = TensorDict(lock=True)
|
|
223
|
+
|
|
224
|
+
# NOTE:
|
|
225
|
+
# - `weight_sync_schemes` here are the *distributed* schemes used to send
|
|
226
|
+
# weights from the main process to this node.
|
|
227
|
+
# - Inner multi-process collectors (e.g., MultiSyncCollector) should
|
|
228
|
+
# manage their own local weight sync schemes (SharedMem / MP) for their
|
|
229
|
+
# sub-workers.
|
|
230
|
+
# Therefore, we do NOT pass `weight_sync_schemes` down into
|
|
231
|
+
# `collector_class` so that it can set up its own local schemes.
|
|
232
|
+
collector = collector_class(
|
|
233
|
+
env_make,
|
|
234
|
+
policy=policy,
|
|
235
|
+
policy_factory=policy_factory,
|
|
236
|
+
frames_per_batch=frames_per_batch,
|
|
237
|
+
total_frames=-1,
|
|
238
|
+
split_trajs=False,
|
|
239
|
+
**collector_kwargs,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
if weight_sync_schemes is not None:
|
|
243
|
+
for model_id, scheme in weight_sync_schemes.items():
|
|
244
|
+
# Provide both collector context and distributed store / rank so the
|
|
245
|
+
# scheme can wire its transport correctly.
|
|
246
|
+
scheme.init_on_receiver(
|
|
247
|
+
model_id=model_id,
|
|
248
|
+
context=collector,
|
|
249
|
+
# store=_store,
|
|
250
|
+
worker_idx=rank,
|
|
251
|
+
)
|
|
252
|
+
scheme.connect()
|
|
253
|
+
|
|
254
|
+
total_frames = 0
|
|
255
|
+
while True:
|
|
256
|
+
if verbose:
|
|
257
|
+
torchrl_logger.debug(f"RANK {rank} -- waiting for instructions")
|
|
258
|
+
instruction = _store.get(f"NODE_{rank}_in")
|
|
259
|
+
if verbose:
|
|
260
|
+
torchrl_logger.debug(f"RANK {rank} -- new instruction: {instruction}")
|
|
261
|
+
_store.delete_key(f"NODE_{rank}_in")
|
|
262
|
+
if instruction == b"continue":
|
|
263
|
+
_store.set(f"NODE_{rank}_status", b"busy")
|
|
264
|
+
if verbose:
|
|
265
|
+
torchrl_logger.debug(f"RANK {rank} -- collecting new data")
|
|
266
|
+
data = collector.next()
|
|
267
|
+
total_frames += data.numel()
|
|
268
|
+
if verbose:
|
|
269
|
+
torchrl_logger.debug(
|
|
270
|
+
f"RANK {rank} -- got data, total frames = {total_frames}"
|
|
271
|
+
)
|
|
272
|
+
torchrl_logger.debug(
|
|
273
|
+
f"RANK {rank} -- sending TensorDict payload to rank 0"
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
if _store.get("TRAINER_status") == b"alive":
|
|
277
|
+
data.isend(dst=0)
|
|
278
|
+
if verbose:
|
|
279
|
+
torchrl_logger.debug(f"RANK {rank} -- setting to 'done'")
|
|
280
|
+
if not sync:
|
|
281
|
+
_store.set(f"NODE_{rank}_status", b"done")
|
|
282
|
+
if verbose:
|
|
283
|
+
torchrl_logger.debug(f"RANK {rank} -- set to 'done'")
|
|
284
|
+
|
|
285
|
+
elif instruction == b"shutdown":
|
|
286
|
+
if verbose:
|
|
287
|
+
torchrl_logger.debug(f"RANK {rank} -- shutting down")
|
|
288
|
+
# Shutdown weight sync schemes first (stops background threads)
|
|
289
|
+
if weight_sync_schemes is not None:
|
|
290
|
+
for scheme in weight_sync_schemes.values():
|
|
291
|
+
try:
|
|
292
|
+
scheme.shutdown()
|
|
293
|
+
except Exception:
|
|
294
|
+
pass
|
|
295
|
+
try:
|
|
296
|
+
collector.shutdown()
|
|
297
|
+
except Exception:
|
|
298
|
+
pass
|
|
299
|
+
_store.set(f"NODE_{rank}_out", b"down")
|
|
300
|
+
break
|
|
301
|
+
|
|
302
|
+
elif instruction == b"update_weights":
|
|
303
|
+
if verbose:
|
|
304
|
+
torchrl_logger.debug(f"RANK {rank} -- updating weights")
|
|
305
|
+
|
|
306
|
+
if weight_sync_schemes is not None:
|
|
307
|
+
if verbose:
|
|
308
|
+
torchrl_logger.debug(
|
|
309
|
+
f"RANK {rank} -- using weight sync schemes for update"
|
|
310
|
+
)
|
|
311
|
+
# Receive fresh weights from the main process for each model.
|
|
312
|
+
# scheme.receive() handles both applying weights locally and
|
|
313
|
+
# cascading to sub-collectors via context.update_policy_weights_().
|
|
314
|
+
for model_id, scheme in weight_sync_schemes.items():
|
|
315
|
+
if verbose:
|
|
316
|
+
torchrl_logger.debug(
|
|
317
|
+
f"RANK {rank} -- receiving weights for model '{model_id}'"
|
|
318
|
+
)
|
|
319
|
+
scheme.receive()
|
|
320
|
+
if verbose:
|
|
321
|
+
torchrl_logger.debug(
|
|
322
|
+
f"RANK {rank} -- received and cascaded weights for model '{model_id}'"
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
# Acknowledgment is handled by the transport (send_ack in the
|
|
326
|
+
# WeightReceiver), so we can continue without touching the
|
|
327
|
+
# TCPStore here.
|
|
328
|
+
continue
|
|
329
|
+
if sync:
|
|
330
|
+
policy_weights.recv(0)
|
|
331
|
+
else:
|
|
332
|
+
# without further arguments, irecv blocks until weights have
|
|
333
|
+
# been updated
|
|
334
|
+
policy_weights.irecv(0)
|
|
335
|
+
# the policy has been updated: we can simply update the weights
|
|
336
|
+
collector.update_policy_weights_(policy_weights=policy_weights)
|
|
337
|
+
_store.set(f"NODE_{rank}_out", b"updated")
|
|
338
|
+
elif instruction.startswith(b"seeding"):
|
|
339
|
+
seed = int(instruction.split(b"seeding_"))
|
|
340
|
+
new_seed = collector.set_seed(seed)
|
|
341
|
+
_store.set(f"NODE_{rank}_out", b"seeded")
|
|
342
|
+
_store.set(f"NODE_{rank}_seed", str(new_seed).encode("utf-8"))
|
|
343
|
+
else:
|
|
344
|
+
raise RuntimeError(f"Instruction {instruction} is not recognised")
|
|
345
|
+
if not collector.closed:
|
|
346
|
+
collector.shutdown()
|
|
347
|
+
del collector
|
|
348
|
+
return
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
class DistributedCollector(BaseCollector):
|
|
352
|
+
"""A distributed data collector with torch.distributed backend.
|
|
353
|
+
|
|
354
|
+
Supports sync and async data collection.
|
|
355
|
+
|
|
356
|
+
Args:
|
|
357
|
+
create_env_fn (Callable or List[Callabled]): list of Callables, each returning an
|
|
358
|
+
instance of :class:`~torchrl.envs.EnvBase`.
|
|
359
|
+
policy (Callable): Policy to be executed in the environment.
|
|
360
|
+
Must accept :class:`tensordict.tensordict.TensorDictBase` object as input.
|
|
361
|
+
If ``None`` is provided, the policy used will be a
|
|
362
|
+
:class:`~torchrl.collectors.RandomPolicy` instance with the environment
|
|
363
|
+
``action_spec``.
|
|
364
|
+
Accepted policies are usually subclasses of :class:`~tensordict.nn.TensorDictModuleBase`.
|
|
365
|
+
This is the recommended usage of the collector.
|
|
366
|
+
Other callables are accepted too:
|
|
367
|
+
If the policy is not a ``TensorDictModuleBase`` (e.g., a regular :class:`~torch.nn.Module`
|
|
368
|
+
instances) it will be wrapped in a `nn.Module` first.
|
|
369
|
+
Then, the collector will try to assess if these
|
|
370
|
+
modules require wrapping in a :class:`~tensordict.nn.TensorDictModule` or not.
|
|
371
|
+
|
|
372
|
+
- If the policy forward signature matches any of ``forward(self, tensordict)``,
|
|
373
|
+
``forward(self, td)`` or ``forward(self, <anything>: TensorDictBase)`` (or
|
|
374
|
+
any typing with a single argument typed as a subclass of ``TensorDictBase``)
|
|
375
|
+
then the policy won't be wrapped in a :class:`~tensordict.nn.TensorDictModule`.
|
|
376
|
+
|
|
377
|
+
- 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)``.
|
|
378
|
+
|
|
379
|
+
.. note:: If the policy needs to be passed as a policy factory (e.g., in case it mustn't be serialized /
|
|
380
|
+
pickled directly), the ``policy_factory`` should be used instead.
|
|
381
|
+
|
|
382
|
+
Keyword Args:
|
|
383
|
+
policy_factory (Callable[[], Callable], list of Callable[[], Callable], optional): a callable
|
|
384
|
+
(or list of callables) that returns a policy instance. This is exclusive with the `policy` argument.
|
|
385
|
+
|
|
386
|
+
.. note:: `policy_factory` comes in handy whenever the policy cannot be serialized.
|
|
387
|
+
|
|
388
|
+
frames_per_batch (int): A keyword-only argument representing the total
|
|
389
|
+
number of elements in a batch.
|
|
390
|
+
total_frames (int): A keyword-only argument representing the total
|
|
391
|
+
number of frames returned by the collector
|
|
392
|
+
during its lifespan. If the ``total_frames`` is not divisible by
|
|
393
|
+
``frames_per_batch``, an exception is raised.
|
|
394
|
+
Endless collectors can be created by passing ``total_frames=-1``.
|
|
395
|
+
Defaults to ``-1`` (endless collector).
|
|
396
|
+
device (int, str or torch.device, optional): The generic device of the
|
|
397
|
+
collector. The ``device`` args fills any non-specified device: if
|
|
398
|
+
``device`` is not ``None`` and any of ``storing_device``, ``policy_device`` or
|
|
399
|
+
``env_device`` is not specified, its value will be set to ``device``.
|
|
400
|
+
Defaults to ``None`` (No default device).
|
|
401
|
+
Lists of devices are supported.
|
|
402
|
+
storing_device (int, str or torch.device, optional): The *remote* device on which
|
|
403
|
+
the output :class:`~tensordict.TensorDict` will be stored.
|
|
404
|
+
If ``device`` is passed and ``storing_device`` is ``None``, it will
|
|
405
|
+
default to the value indicated by ``device``.
|
|
406
|
+
For long trajectories, it may be necessary to store the data on a different
|
|
407
|
+
device than the one where the policy and env are executed.
|
|
408
|
+
Defaults to ``None`` (the output tensordict isn't on a specific device,
|
|
409
|
+
leaf tensors sit on the device where they were created).
|
|
410
|
+
Lists of devices are supported.
|
|
411
|
+
env_device (int, str or torch.device, optional): The *remote* device on which
|
|
412
|
+
the environment should be cast (or executed if that functionality is
|
|
413
|
+
supported). If not specified and the env has a non-``None`` device,
|
|
414
|
+
``env_device`` will default to that value. If ``device`` is passed
|
|
415
|
+
and ``env_device=None``, it will default to ``device``. If the value
|
|
416
|
+
as such specified of ``env_device`` differs from ``policy_device``
|
|
417
|
+
and one of them is not ``None``, the data will be cast to ``env_device``
|
|
418
|
+
before being passed to the env (i.e., passing different devices to
|
|
419
|
+
policy and env is supported). Defaults to ``None``.
|
|
420
|
+
Lists of devices are supported.
|
|
421
|
+
policy_device (int, str or torch.device, optional): The *remote* device on which
|
|
422
|
+
the policy should be cast.
|
|
423
|
+
If ``device`` is passed and ``policy_device=None``, it will default
|
|
424
|
+
to ``device``. If the value as such specified of ``policy_device``
|
|
425
|
+
differs from ``env_device`` and one of them is not ``None``,
|
|
426
|
+
the data will be cast to ``policy_device`` before being passed to
|
|
427
|
+
the policy (i.e., passing different devices to policy and env is
|
|
428
|
+
supported). Defaults to ``None``.
|
|
429
|
+
Lists of devices are supported.
|
|
430
|
+
max_frames_per_traj (int, optional): Maximum steps per trajectory.
|
|
431
|
+
Note that a trajectory can span across multiple batches (unless
|
|
432
|
+
``reset_at_each_iter`` is set to ``True``, see below).
|
|
433
|
+
Once a trajectory reaches ``n_steps``, the environment is reset.
|
|
434
|
+
If the environment wraps multiple environments together, the number
|
|
435
|
+
of steps is tracked for each environment independently. Negative
|
|
436
|
+
values are allowed, in which case this argument is ignored.
|
|
437
|
+
Defaults to ``None`` (i.e., no maximum number of steps).
|
|
438
|
+
init_random_frames (int, optional): Number of frames for which the
|
|
439
|
+
policy is ignored before it is called. This feature is mainly
|
|
440
|
+
intended to be used in offline/model-based settings, where a
|
|
441
|
+
batch of random trajectories can be used to initialize training.
|
|
442
|
+
If provided, it will be rounded up to the closest multiple of frames_per_batch.
|
|
443
|
+
Defaults to ``None`` (i.e. no random frames).
|
|
444
|
+
reset_at_each_iter (bool, optional): Whether environments should be reset
|
|
445
|
+
at the beginning of a batch collection.
|
|
446
|
+
Defaults to ``False``.
|
|
447
|
+
postproc (Callable, optional): A post-processing transform, such as
|
|
448
|
+
a :class:`~torchrl.envs.Transform` or a :class:`~torchrl.data.postprocs.MultiStep`
|
|
449
|
+
instance.
|
|
450
|
+
Defaults to ``None``.
|
|
451
|
+
split_trajs (bool, optional): Boolean indicating whether the resulting
|
|
452
|
+
TensorDict should be split according to the trajectories.
|
|
453
|
+
See :func:`~torchrl.collectors.utils.split_trajectories` for more
|
|
454
|
+
information.
|
|
455
|
+
Defaults to ``False``.
|
|
456
|
+
exploration_type (ExplorationType, optional): interaction mode to be used when
|
|
457
|
+
collecting data. Must be one of ``torchrl.envs.utils.ExplorationType.DETERMINISTIC``,
|
|
458
|
+
``torchrl.envs.utils.ExplorationType.RANDOM``, ``torchrl.envs.utils.ExplorationType.MODE``
|
|
459
|
+
or ``torchrl.envs.utils.ExplorationType.MEAN``.
|
|
460
|
+
collector_class (Type or str, optional): a collector class for the remote node. Can be
|
|
461
|
+
:class:`~torchrl.collectors.Collector`,
|
|
462
|
+
:class:`~torchrl.collectors.MultiSyncCollector`,
|
|
463
|
+
:class:`~torchrl.collectors.MultiAsyncCollector`
|
|
464
|
+
or a derived class of these. The strings "single", "sync" and
|
|
465
|
+
"async" correspond to respective class.
|
|
466
|
+
Defaults to :class:`~torchrl.collectors.Collector`.
|
|
467
|
+
collector_kwargs (dict or list, optional): a dictionary of parameters to be passed to the
|
|
468
|
+
remote data-collector. If a list is provided, each element will
|
|
469
|
+
correspond to an individual set of keyword arguments for the
|
|
470
|
+
dedicated collector.
|
|
471
|
+
num_workers_per_collector (int, optional): the number of copies of the
|
|
472
|
+
env constructor that is to be used on the remote nodes.
|
|
473
|
+
Defaults to 1 (a single env per collector).
|
|
474
|
+
On a single worker node all the sub-workers will be
|
|
475
|
+
executing the same environment. If different environments need to
|
|
476
|
+
be executed, they should be dispatched across worker nodes, not
|
|
477
|
+
subnodes.
|
|
478
|
+
sync (bool, optional): if ``True``, the resulting tensordict is a stack of all the
|
|
479
|
+
tensordicts collected on each node. If ``False`` (default), each
|
|
480
|
+
tensordict results from a separate node in a "first-ready,
|
|
481
|
+
first-served" fashion.
|
|
482
|
+
slurm_kwargs (dict): a dictionary of parameters to be passed to the
|
|
483
|
+
submitit executor.
|
|
484
|
+
backend (str, optional): must a string "<distributed_backed>" where
|
|
485
|
+
<distributed_backed> is one of ``"gloo"``, ``"mpi"``, ``"nccl"`` or ``"ucc"``. See
|
|
486
|
+
the torch.distributed documentation for more information.
|
|
487
|
+
Defaults to ``"gloo"``.
|
|
488
|
+
update_after_each_batch (bool, optional): if ``True``, the weights will
|
|
489
|
+
be updated after each collection. For ``sync=True``, this means that
|
|
490
|
+
all workers will see their weights updated. For ``sync=False``,
|
|
491
|
+
only the worker from which the data has been gathered will be
|
|
492
|
+
updated.
|
|
493
|
+
Defaults to ``False``, ie. updates have to be executed manually
|
|
494
|
+
through
|
|
495
|
+
:meth:`~torchrl.collectors.distributed.DistributedDataCollector.update_policy_weights_`.
|
|
496
|
+
max_weight_update_interval (int, optional): the maximum number of
|
|
497
|
+
batches that can be collected before the policy weights of a worker
|
|
498
|
+
is updated.
|
|
499
|
+
For sync collections, this parameter is overwritten by ``update_after_each_batch``.
|
|
500
|
+
For async collections, it may be that one worker has not seen its
|
|
501
|
+
parameters being updated for a certain time even if ``update_after_each_batch``
|
|
502
|
+
is turned on.
|
|
503
|
+
Defaults to -1 (no forced update).
|
|
504
|
+
launcher (str, optional): how jobs should be launched.
|
|
505
|
+
Can be one of "submitit" or "mp" for multiprocessing.
|
|
506
|
+
Use "submitit_delayed" if your cluster does not support spawning
|
|
507
|
+
jobs from existing jobs.
|
|
508
|
+
The former can launch jobs across multiple nodes, whilst the latter will only
|
|
509
|
+
launch jobs on a single machine. "submitit" requires the homonymous
|
|
510
|
+
library to be installed.
|
|
511
|
+
To find more about submitit, visit
|
|
512
|
+
https://github.com/facebookincubator/submitit and check our examples
|
|
513
|
+
to learn more.
|
|
514
|
+
Defaults to ``"submitit"``.
|
|
515
|
+
tcp_port (int, optional): the TCP port to be used. Defaults to 10003.
|
|
516
|
+
weight_updater (WeightUpdaterBase or constructor, optional): An instance of :class:`~torchrl.collectors.WeightUpdaterBase`
|
|
517
|
+
or its subclass, responsible for updating the policy weights on distributed inference workers.
|
|
518
|
+
If not provided, a :class:`~torchrl.collectors.distributed.DistributedWeightUpdater` will be used by
|
|
519
|
+
default, which handles weight synchronization across distributed workers.
|
|
520
|
+
Consider using a constructor if the updater needs to be serialized.
|
|
521
|
+
weight_sync_schemes (dict[str, WeightSyncScheme], optional): Dictionary of weight sync schemes for
|
|
522
|
+
SENDING weights to distributed worker collectors. Keys are model identifiers (e.g., "policy")
|
|
523
|
+
and values are WeightSyncScheme instances configured to send weights via torch.distributed.
|
|
524
|
+
If not provided, a :class:`~torchrl.weight_update.DistributedWeightSyncScheme` will be used by default.
|
|
525
|
+
This is for propagating weights from the main process to distributed workers.
|
|
526
|
+
weight_recv_schemes (dict[str, WeightSyncScheme], optional): Dictionary of weight sync schemes for
|
|
527
|
+
RECEIVING weights from a parent process or training loop. Keys are model identifiers (e.g., "policy")
|
|
528
|
+
and values are WeightSyncScheme instances configured to receive weights.
|
|
529
|
+
This is typically used when DistributedDataCollector is itself a worker in a larger distributed setup.
|
|
530
|
+
Defaults to ``None``.
|
|
531
|
+
|
|
532
|
+
"""
|
|
533
|
+
|
|
534
|
+
_VERBOSE = VERBOSE # for debugging
|
|
535
|
+
|
|
536
|
+
def __init__(
|
|
537
|
+
self,
|
|
538
|
+
create_env_fn,
|
|
539
|
+
policy: Callable[[TensorDictBase], TensorDictBase] | None = None,
|
|
540
|
+
*,
|
|
541
|
+
policy_factory: Callable[[], Callable]
|
|
542
|
+
| list[Callable[[] | Callable]]
|
|
543
|
+
| None = None,
|
|
544
|
+
frames_per_batch: int,
|
|
545
|
+
total_frames: int = -1,
|
|
546
|
+
device: torch.device | list[torch.device] | None = None,
|
|
547
|
+
storing_device: torch.device | list[torch.device] | None = None,
|
|
548
|
+
env_device: torch.device | list[torch.device] | None = None,
|
|
549
|
+
policy_device: torch.device | list[torch.device] | None = None,
|
|
550
|
+
max_frames_per_traj: int = -1,
|
|
551
|
+
init_random_frames: int = -1,
|
|
552
|
+
reset_at_each_iter: bool = False,
|
|
553
|
+
postproc: Callable | None = None,
|
|
554
|
+
split_trajs: bool = False,
|
|
555
|
+
exploration_type: ExporationType = DEFAULT_EXPLORATION_TYPE, # noqa
|
|
556
|
+
collector_class: type = Collector,
|
|
557
|
+
collector_kwargs: dict[str, Any] | None = None,
|
|
558
|
+
num_workers_per_collector: int = 1,
|
|
559
|
+
sync: bool = False,
|
|
560
|
+
slurm_kwargs: dict[str, Any] | None = None,
|
|
561
|
+
backend: str = "gloo",
|
|
562
|
+
update_after_each_batch: bool = False,
|
|
563
|
+
max_weight_update_interval: int = -1,
|
|
564
|
+
update_interval: int | None = None,
|
|
565
|
+
launcher: str = "submitit",
|
|
566
|
+
tcp_port: int | None = None,
|
|
567
|
+
weight_updater: WeightUpdaterBase
|
|
568
|
+
| Callable[[], WeightUpdaterBase]
|
|
569
|
+
| None = None,
|
|
570
|
+
weight_sync_schemes: dict[str, WeightSyncScheme] | None = None,
|
|
571
|
+
weight_recv_schemes: dict[str, WeightSyncScheme] | None = None,
|
|
572
|
+
):
|
|
573
|
+
|
|
574
|
+
if self._VERBOSE:
|
|
575
|
+
torchrl_logger.setLevel("DEBUG")
|
|
576
|
+
|
|
577
|
+
if collector_class == "async":
|
|
578
|
+
collector_class = MultiAsyncCollector
|
|
579
|
+
elif collector_class == "sync":
|
|
580
|
+
collector_class = MultiSyncCollector
|
|
581
|
+
elif collector_class == "single":
|
|
582
|
+
collector_class = Collector
|
|
583
|
+
self.collector_class = collector_class
|
|
584
|
+
self.env_constructors = create_env_fn
|
|
585
|
+
if not isinstance(policy_factory, Sequence):
|
|
586
|
+
policy_factory = [policy_factory for _ in range(len(self.env_constructors))]
|
|
587
|
+
self.policy_factory = policy_factory
|
|
588
|
+
if isinstance(policy, nn.Module):
|
|
589
|
+
policy_weights = TensorDict.from_module(policy)
|
|
590
|
+
policy_weights = policy_weights.data.lock_()
|
|
591
|
+
elif any(policy_factory):
|
|
592
|
+
policy_weights = None
|
|
593
|
+
else:
|
|
594
|
+
if not any(policy_factory):
|
|
595
|
+
warnings.warn(_NON_NN_POLICY_WEIGHTS)
|
|
596
|
+
policy_weights = TensorDict(lock=True)
|
|
597
|
+
self.policy = policy
|
|
598
|
+
self._policy_to_send = policy if not any(policy_factory) else None
|
|
599
|
+
self.policy_weights = policy_weights
|
|
600
|
+
self.num_workers = len(create_env_fn)
|
|
601
|
+
self.frames_per_batch = frames_per_batch
|
|
602
|
+
self.requested_frames_per_batch = frames_per_batch
|
|
603
|
+
|
|
604
|
+
self.device = device
|
|
605
|
+
self.storing_device = storing_device
|
|
606
|
+
self.env_device = env_device
|
|
607
|
+
self.policy_device = policy_device
|
|
608
|
+
|
|
609
|
+
# make private to avoid changes from users during collection
|
|
610
|
+
self._sync = sync
|
|
611
|
+
self.update_after_each_batch = update_after_each_batch
|
|
612
|
+
self.max_weight_update_interval = max_weight_update_interval
|
|
613
|
+
if update_interval is not None and update_interval < 1:
|
|
614
|
+
raise ValueError(
|
|
615
|
+
"`update_interval` must be >= 1 when provided. "
|
|
616
|
+
f"Got update_interval={update_interval}."
|
|
617
|
+
)
|
|
618
|
+
self.update_interval = update_interval
|
|
619
|
+
if self.update_after_each_batch and self.max_weight_update_interval > -1:
|
|
620
|
+
raise RuntimeError(
|
|
621
|
+
"Got conflicting update instructions: `update_after_each_batch` "
|
|
622
|
+
"`max_weight_update_interval` are incompatible."
|
|
623
|
+
)
|
|
624
|
+
self.launcher = launcher
|
|
625
|
+
self._batches_since_weight_update = [0 for _ in range(self.num_workers)]
|
|
626
|
+
if tcp_port is None:
|
|
627
|
+
self.tcp_port = os.environ.get("TCP_PORT", TCP_PORT)
|
|
628
|
+
else:
|
|
629
|
+
self.tcp_port = str(tcp_port)
|
|
630
|
+
|
|
631
|
+
if self._sync:
|
|
632
|
+
if self.frames_per_batch % self.num_workers != 0:
|
|
633
|
+
raise RuntimeError(
|
|
634
|
+
f"Cannot dispatch {self.frames_per_batch} frames across {self.num_workers}. "
|
|
635
|
+
f"Consider using a number of frames per batch that is divisible by the number of workers."
|
|
636
|
+
)
|
|
637
|
+
self._frames_per_batch_corrected = self.frames_per_batch // self.num_workers
|
|
638
|
+
else:
|
|
639
|
+
self._frames_per_batch_corrected = self.frames_per_batch
|
|
640
|
+
|
|
641
|
+
self.num_workers_per_collector = num_workers_per_collector
|
|
642
|
+
self.total_frames = total_frames
|
|
643
|
+
self.slurm_kwargs = copy(DEFAULT_SLURM_CONF)
|
|
644
|
+
if slurm_kwargs is not None:
|
|
645
|
+
self.slurm_kwargs.update(slurm_kwargs)
|
|
646
|
+
collector_kwargs = collector_kwargs if collector_kwargs is not None else {}
|
|
647
|
+
self.collector_kwargs = (
|
|
648
|
+
deepcopy(collector_kwargs)
|
|
649
|
+
if isinstance(collector_kwargs, (list, tuple))
|
|
650
|
+
else [copy(collector_kwargs) for _ in range(self.num_workers)]
|
|
651
|
+
)
|
|
652
|
+
|
|
653
|
+
# update collector kwargs
|
|
654
|
+
for i, collector_kwarg in enumerate(self.collector_kwargs):
|
|
655
|
+
collector_kwarg["max_frames_per_traj"] = max_frames_per_traj
|
|
656
|
+
collector_kwarg["init_random_frames"] = (
|
|
657
|
+
init_random_frames // self.num_workers
|
|
658
|
+
)
|
|
659
|
+
if not self._sync and init_random_frames > 0:
|
|
660
|
+
warnings.warn(
|
|
661
|
+
"async distributed data collection with init_random_frames > 0 "
|
|
662
|
+
"may have unforeseen consequences as we do not control that once "
|
|
663
|
+
"non-random data is being collected all nodes are returning non-random data. "
|
|
664
|
+
"If this is a feature that you feel should be fixed, please raise an issue on "
|
|
665
|
+
"torchrl's repo."
|
|
666
|
+
)
|
|
667
|
+
collector_kwarg["reset_at_each_iter"] = reset_at_each_iter
|
|
668
|
+
collector_kwarg["exploration_type"] = exploration_type
|
|
669
|
+
collector_kwarg["device"] = self.device[i]
|
|
670
|
+
collector_kwarg["storing_device"] = self.storing_device[i]
|
|
671
|
+
collector_kwarg["env_device"] = self.env_device[i]
|
|
672
|
+
collector_kwarg["policy_device"] = self.policy_device[i]
|
|
673
|
+
|
|
674
|
+
self.postproc = postproc
|
|
675
|
+
self.split_trajs = split_trajs
|
|
676
|
+
|
|
677
|
+
self.backend = backend
|
|
678
|
+
|
|
679
|
+
# Set up weight synchronization - prefer new schemes over legacy updater
|
|
680
|
+
if weight_updater is None and weight_sync_schemes is None:
|
|
681
|
+
# Default to Distributed weight sync scheme for distributed collectors
|
|
682
|
+
from torchrl.weight_update import DistributedWeightSyncScheme
|
|
683
|
+
|
|
684
|
+
weight_sync_schemes = {
|
|
685
|
+
"policy": DistributedWeightSyncScheme(backend=backend, sync=self._sync)
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
if weight_sync_schemes is not None:
|
|
689
|
+
torchrl_logger.debug("RANK 0 -- Using weight sync schemes")
|
|
690
|
+
# Use new weight synchronization system
|
|
691
|
+
self._weight_sync_schemes = weight_sync_schemes
|
|
692
|
+
self.weight_updater = None
|
|
693
|
+
else:
|
|
694
|
+
torchrl_logger.debug("RANK 0 -- Using weight updater")
|
|
695
|
+
# Fall back to legacy weight updater system
|
|
696
|
+
if weight_updater is None:
|
|
697
|
+
weight_updater = DistributedWeightUpdater(
|
|
698
|
+
store=self._store,
|
|
699
|
+
policy_weights=self.policy_weights,
|
|
700
|
+
num_workers=self.num_workers,
|
|
701
|
+
sync=self._sync,
|
|
702
|
+
)
|
|
703
|
+
self.weight_updater = weight_updater
|
|
704
|
+
self._weight_sync_schemes = None
|
|
705
|
+
|
|
706
|
+
if self._weight_sync_schemes is not None:
|
|
707
|
+
# Initialize schemes on the sender (main process) side now that
|
|
708
|
+
# worker processes and the store have been created.
|
|
709
|
+
for model_id, scheme in self._weight_sync_schemes.items():
|
|
710
|
+
scheme.init_on_sender(
|
|
711
|
+
num_workers=self.num_workers, context=self, model_id=model_id
|
|
712
|
+
)
|
|
713
|
+
|
|
714
|
+
self._init_workers()
|
|
715
|
+
|
|
716
|
+
# Set up weight receivers if provided
|
|
717
|
+
if weight_recv_schemes is not None:
|
|
718
|
+
self.register_scheme_receiver(weight_recv_schemes)
|
|
719
|
+
|
|
720
|
+
self._make_container()
|
|
721
|
+
if self._weight_sync_schemes is not None:
|
|
722
|
+
for scheme in self._weight_sync_schemes.values():
|
|
723
|
+
scheme.connect()
|
|
724
|
+
|
|
725
|
+
@property
|
|
726
|
+
def device(self) -> list[torch.device]:
|
|
727
|
+
return self._device
|
|
728
|
+
|
|
729
|
+
@property
|
|
730
|
+
def storing_device(self) -> list[torch.device]:
|
|
731
|
+
return self._storing_device
|
|
732
|
+
|
|
733
|
+
@property
|
|
734
|
+
def env_device(self) -> list[torch.device]:
|
|
735
|
+
return self._env_device
|
|
736
|
+
|
|
737
|
+
@property
|
|
738
|
+
def policy_device(self) -> list[torch.device]:
|
|
739
|
+
return self._policy_device
|
|
740
|
+
|
|
741
|
+
@device.setter
|
|
742
|
+
def device(self, value):
|
|
743
|
+
if isinstance(value, (tuple, list)):
|
|
744
|
+
if len(value) != self.num_workers:
|
|
745
|
+
raise RuntimeError(
|
|
746
|
+
"The number of devices passed to the collector must match the number of workers."
|
|
747
|
+
)
|
|
748
|
+
self._device = value
|
|
749
|
+
else:
|
|
750
|
+
self._device = [value] * self.num_workers
|
|
751
|
+
|
|
752
|
+
@storing_device.setter
|
|
753
|
+
def storing_device(self, value):
|
|
754
|
+
if isinstance(value, (tuple, list)):
|
|
755
|
+
if len(value) != self.num_workers:
|
|
756
|
+
raise RuntimeError(
|
|
757
|
+
"The number of devices passed to the collector must match the number of workers."
|
|
758
|
+
)
|
|
759
|
+
self._storing_device = value
|
|
760
|
+
else:
|
|
761
|
+
self._storing_device = [value] * self.num_workers
|
|
762
|
+
|
|
763
|
+
@env_device.setter
|
|
764
|
+
def env_device(self, value):
|
|
765
|
+
if isinstance(value, (tuple, list)):
|
|
766
|
+
if len(value) != self.num_workers:
|
|
767
|
+
raise RuntimeError(
|
|
768
|
+
"The number of devices passed to the collector must match the number of workers."
|
|
769
|
+
)
|
|
770
|
+
self._env_device = value
|
|
771
|
+
else:
|
|
772
|
+
self._env_device = [value] * self.num_workers
|
|
773
|
+
|
|
774
|
+
@policy_device.setter
|
|
775
|
+
def policy_device(self, value):
|
|
776
|
+
if isinstance(value, (tuple, list)):
|
|
777
|
+
if len(value) != self.num_workers:
|
|
778
|
+
raise RuntimeError(
|
|
779
|
+
"The number of devices passed to the collector must match the number of workers."
|
|
780
|
+
)
|
|
781
|
+
self._policy_device = value
|
|
782
|
+
else:
|
|
783
|
+
self._policy_device = [value] * self.num_workers
|
|
784
|
+
|
|
785
|
+
def _init_master_dist(
|
|
786
|
+
self,
|
|
787
|
+
world_size,
|
|
788
|
+
backend,
|
|
789
|
+
):
|
|
790
|
+
torchrl_logger.debug(
|
|
791
|
+
f"RANK 0 -- launching main node with tcp port '{self.tcp_port}' and "
|
|
792
|
+
f"IP '{self.IPAddr}'. rank: 0, world_size: {world_size}, backend={backend}."
|
|
793
|
+
)
|
|
794
|
+
os.environ["MASTER_ADDR"] = str(self.IPAddr)
|
|
795
|
+
os.environ["MASTER_PORT"] = str(self.tcp_port)
|
|
796
|
+
|
|
797
|
+
TCP_PORT = self.tcp_port
|
|
798
|
+
torch.distributed.init_process_group(
|
|
799
|
+
backend,
|
|
800
|
+
rank=0,
|
|
801
|
+
world_size=world_size,
|
|
802
|
+
timeout=timedelta(MAX_TIME_TO_CONNECT),
|
|
803
|
+
init_method=f"tcp://{self.IPAddr}:{TCP_PORT}",
|
|
804
|
+
)
|
|
805
|
+
torchrl_logger.debug("RANK 0 -- main initiated! Launching store...")
|
|
806
|
+
# Use retry logic to handle port conflicts
|
|
807
|
+
self._store, self._store_port = _create_tcpstore_with_retry(
|
|
808
|
+
host_name=self.IPAddr,
|
|
809
|
+
port=int(TCP_PORT) + 1,
|
|
810
|
+
world_size=self.num_workers + 1,
|
|
811
|
+
is_master=True,
|
|
812
|
+
timeout=10.0,
|
|
813
|
+
wait_for_workers=False, # Don't wait - we need to broadcast port first
|
|
814
|
+
)
|
|
815
|
+
torchrl_logger.debug(
|
|
816
|
+
f"RANK 0 -- store created on port {self._store_port}. Broadcasting to workers..."
|
|
817
|
+
)
|
|
818
|
+
# Broadcast actual store port to all workers
|
|
819
|
+
store_port_tensor = torch.tensor([self._store_port], dtype=torch.int64)
|
|
820
|
+
torch.distributed.broadcast(store_port_tensor, src=0)
|
|
821
|
+
torchrl_logger.debug("RANK 0 -- done. Setting status to 'alive'")
|
|
822
|
+
self._store.set("TRAINER_status", b"alive")
|
|
823
|
+
|
|
824
|
+
def _make_container(self):
|
|
825
|
+
torchrl_logger.debug("RANK 0 -- making container")
|
|
826
|
+
env_constructor = self.env_constructors[0]
|
|
827
|
+
kwargs = self.collector_kwargs[
|
|
828
|
+
0
|
|
829
|
+
].copy() # Create a copy to avoid modifying the original
|
|
830
|
+
# Mirror the Collector configuration used on the workers so
|
|
831
|
+
# that the dummy batch structure matches what remote ranks will send.
|
|
832
|
+
# _run_collector always sets return_same_td=True for Collector,
|
|
833
|
+
# so we must do the same here to ensure structural consistency.
|
|
834
|
+
kwargs["return_same_td"] = True
|
|
835
|
+
pseudo_collector = Collector(
|
|
836
|
+
env_constructor,
|
|
837
|
+
policy=self.policy if not self.policy_factory[0] else None,
|
|
838
|
+
policy_factory=self.policy_factory[0],
|
|
839
|
+
frames_per_batch=self._frames_per_batch_corrected,
|
|
840
|
+
total_frames=-1,
|
|
841
|
+
split_trajs=False,
|
|
842
|
+
**kwargs,
|
|
843
|
+
)
|
|
844
|
+
for _data in pseudo_collector:
|
|
845
|
+
break
|
|
846
|
+
torchrl_logger.debug(f"RANK 0 -- got dummy batch: {_data}")
|
|
847
|
+
torchrl_logger.debug("RANK 0 -- expanding...")
|
|
848
|
+
self._tensordict_out = (
|
|
849
|
+
_data.expand((self.num_workers, *_data.shape)).clone().to_lazystack(0)
|
|
850
|
+
)
|
|
851
|
+
torchrl_logger.debug(
|
|
852
|
+
f"RANK 0 -- expanded recv buffer spec: {self._tensordict_out}"
|
|
853
|
+
)
|
|
854
|
+
torchrl_logger.debug("RANK 0 -- locking")
|
|
855
|
+
if self._sync:
|
|
856
|
+
self._tensordict_out.lock_()
|
|
857
|
+
self._tensordict_out_unbind = self._tensordict_out.unbind(0)
|
|
858
|
+
for td in self._tensordict_out_unbind:
|
|
859
|
+
td.lock_()
|
|
860
|
+
else:
|
|
861
|
+
self._tensordict_out = self._tensordict_out.unbind(0)
|
|
862
|
+
for td in self._tensordict_out:
|
|
863
|
+
td.lock_()
|
|
864
|
+
torchrl_logger.debug("RANK 0 -- storage created:")
|
|
865
|
+
torchrl_logger.debug("RANK 0 -- shutting down...")
|
|
866
|
+
pseudo_collector.shutdown()
|
|
867
|
+
torchrl_logger.debug("RANK 0 -- dummy collector shut down!")
|
|
868
|
+
del pseudo_collector
|
|
869
|
+
|
|
870
|
+
def _init_worker_dist_submitit(self, executor, i):
|
|
871
|
+
env_make = self.env_constructors[i]
|
|
872
|
+
if not isinstance(env_make, (EnvBase, EnvCreator)):
|
|
873
|
+
env_make = CloudpickleWrapper(env_make)
|
|
874
|
+
TCP_PORT = self.tcp_port
|
|
875
|
+
job = executor.submit(
|
|
876
|
+
_distributed_init_collection_node,
|
|
877
|
+
rank=i + 1,
|
|
878
|
+
rank0_ip=self.IPAddr,
|
|
879
|
+
tcpport=int(TCP_PORT),
|
|
880
|
+
sync=self._sync,
|
|
881
|
+
world_size=self.num_workers + 1,
|
|
882
|
+
backend=self.backend,
|
|
883
|
+
collector_class=self.collector_class,
|
|
884
|
+
num_workers=self.num_workers_per_collector,
|
|
885
|
+
env_make=env_make,
|
|
886
|
+
policy=self._policy_to_send,
|
|
887
|
+
policy_factory=self.policy_factory[i],
|
|
888
|
+
frames_per_batch=self._frames_per_batch_corrected,
|
|
889
|
+
weight_sync_schemes=self._weight_sync_schemes,
|
|
890
|
+
collector_kwargs=self.collector_kwargs[i],
|
|
891
|
+
verbose=self._VERBOSE,
|
|
892
|
+
)
|
|
893
|
+
return job
|
|
894
|
+
|
|
895
|
+
def _init_worker_dist_submitit_delayed(self):
|
|
896
|
+
def get_env_make(i):
|
|
897
|
+
env_make = self.env_constructors[i]
|
|
898
|
+
if not isinstance(env_make, (EnvBase, EnvCreator)):
|
|
899
|
+
env_make = CloudpickleWrapper(env_make)
|
|
900
|
+
return env_make
|
|
901
|
+
|
|
902
|
+
self._init_master_dist(self.num_workers + 1, self.backend)
|
|
903
|
+
objects = [
|
|
904
|
+
{
|
|
905
|
+
"sync": self._sync,
|
|
906
|
+
"collector_class": self.collector_class,
|
|
907
|
+
"num_workers": self.num_workers_per_collector,
|
|
908
|
+
"env_make": get_env_make(i),
|
|
909
|
+
"policy": self.policy,
|
|
910
|
+
"policy_factory": self.policy_factory[i],
|
|
911
|
+
"frames_per_batch": self._frames_per_batch_corrected,
|
|
912
|
+
"collector_kwargs": self.collector_kwargs[i],
|
|
913
|
+
}
|
|
914
|
+
for i in range(self.num_workers)
|
|
915
|
+
]
|
|
916
|
+
objects = [None] + objects
|
|
917
|
+
torch.distributed.scatter_object_list([None], objects, src=0)
|
|
918
|
+
|
|
919
|
+
def _init_worker_dist_mp(self, i):
|
|
920
|
+
env_make = self.env_constructors[i]
|
|
921
|
+
if not isinstance(env_make, (EnvBase, EnvCreator)):
|
|
922
|
+
env_make = CloudpickleWrapper(env_make)
|
|
923
|
+
TCP_PORT = self.tcp_port
|
|
924
|
+
job = _ProcessNoWarn(
|
|
925
|
+
target=_distributed_init_collection_node,
|
|
926
|
+
_start_method=_get_mp_ctx().get_start_method(),
|
|
927
|
+
kwargs=dict( # noqa: C408
|
|
928
|
+
rank=i + 1,
|
|
929
|
+
rank0_ip=self.IPAddr,
|
|
930
|
+
tcpport=int(TCP_PORT),
|
|
931
|
+
sync=self._sync,
|
|
932
|
+
world_size=self.num_workers + 1,
|
|
933
|
+
backend=self.backend,
|
|
934
|
+
collector_class=self.collector_class,
|
|
935
|
+
num_workers=self.num_workers_per_collector,
|
|
936
|
+
env_make=env_make,
|
|
937
|
+
policy=self._policy_to_send,
|
|
938
|
+
policy_factory=self.policy_factory[i],
|
|
939
|
+
frames_per_batch=self._frames_per_batch_corrected,
|
|
940
|
+
collector_kwargs=self.collector_kwargs[i],
|
|
941
|
+
weight_sync_schemes=self._weight_sync_schemes,
|
|
942
|
+
verbose=self._VERBOSE,
|
|
943
|
+
),
|
|
944
|
+
)
|
|
945
|
+
job.start()
|
|
946
|
+
return job
|
|
947
|
+
|
|
948
|
+
def _init_workers(self):
|
|
949
|
+
|
|
950
|
+
if self.launcher != "mp":
|
|
951
|
+
hostname = socket.gethostname()
|
|
952
|
+
IPAddr = socket.gethostbyname(hostname)
|
|
953
|
+
else:
|
|
954
|
+
IPAddr = "localhost"
|
|
955
|
+
torchrl_logger.debug(f"RANK 0 -- Server IP address: {IPAddr}")
|
|
956
|
+
self.IPAddr = IPAddr
|
|
957
|
+
os.environ["MASTER_ADDR"] = str(self.IPAddr)
|
|
958
|
+
os.environ["MASTER_PORT"] = str(self.tcp_port)
|
|
959
|
+
|
|
960
|
+
self.jobs = []
|
|
961
|
+
if self.launcher == "submitit":
|
|
962
|
+
if not _has_submitit:
|
|
963
|
+
raise ImportError("submitit not found.") from SUBMITIT_ERR
|
|
964
|
+
executor = submitit.AutoExecutor(folder="log_test")
|
|
965
|
+
executor.update_parameters(**self.slurm_kwargs)
|
|
966
|
+
if self.launcher == "submitit_delayed":
|
|
967
|
+
self._init_worker_dist_submitit_delayed()
|
|
968
|
+
else:
|
|
969
|
+
for i in range(self.num_workers):
|
|
970
|
+
torchrl_logger.debug("RANK 0 -- Submitting job")
|
|
971
|
+
if self.launcher == "submitit":
|
|
972
|
+
job = self._init_worker_dist_submitit(
|
|
973
|
+
executor,
|
|
974
|
+
i,
|
|
975
|
+
)
|
|
976
|
+
torchrl_logger.debug(
|
|
977
|
+
f"RANK 0 -- job id {job.job_id}"
|
|
978
|
+
) # ID of your job
|
|
979
|
+
elif self.launcher == "mp":
|
|
980
|
+
job = self._init_worker_dist_mp(
|
|
981
|
+
i,
|
|
982
|
+
)
|
|
983
|
+
torchrl_logger.debug("RANK 0 -- job launched")
|
|
984
|
+
self.jobs.append(job)
|
|
985
|
+
self._init_master_dist(self.num_workers + 1, self.backend)
|
|
986
|
+
|
|
987
|
+
def iterator(self):
|
|
988
|
+
yield from self._iterator_dist()
|
|
989
|
+
|
|
990
|
+
def _iterator_dist(self):
|
|
991
|
+
torchrl_logger.debug("RANK 0 -- iterating...")
|
|
992
|
+
|
|
993
|
+
total_frames = 0
|
|
994
|
+
num_batches_yielded = 0
|
|
995
|
+
if not self._sync:
|
|
996
|
+
for rank in range(1, self.num_workers + 1):
|
|
997
|
+
torchrl_logger.debug(f"RANK 0 -- sending 'continue' to {rank}")
|
|
998
|
+
self._store.set(f"NODE_{rank}_in", b"continue")
|
|
999
|
+
trackers = []
|
|
1000
|
+
for i in range(self.num_workers):
|
|
1001
|
+
rank = i + 1
|
|
1002
|
+
torchrl_logger.debug(f"RANK 0 -- receiving {rank=}")
|
|
1003
|
+
trackers.append(
|
|
1004
|
+
self._tensordict_out[i].irecv(src=rank, return_premature=True)
|
|
1005
|
+
)
|
|
1006
|
+
torchrl_logger.debug(f"RANK 0 -- trackers: {trackers}")
|
|
1007
|
+
|
|
1008
|
+
while total_frames < self.total_frames:
|
|
1009
|
+
if self._sync:
|
|
1010
|
+
data, total_frames = self._next_sync(total_frames)
|
|
1011
|
+
else:
|
|
1012
|
+
data, total_frames, ready_worker_idx = self._next_async(
|
|
1013
|
+
total_frames, trackers
|
|
1014
|
+
)
|
|
1015
|
+
|
|
1016
|
+
if self.split_trajs:
|
|
1017
|
+
data = split_trajectories(data)
|
|
1018
|
+
if self.postproc is not None:
|
|
1019
|
+
data = self.postproc(data)
|
|
1020
|
+
yield data
|
|
1021
|
+
num_batches_yielded += 1
|
|
1022
|
+
has_more = total_frames < self.total_frames
|
|
1023
|
+
|
|
1024
|
+
# Automatic weight update hook: update_interval controls how often we
|
|
1025
|
+
# propagate weights through the registered weight sync schemes.
|
|
1026
|
+
#
|
|
1027
|
+
# Important: for async collection, we do this *after* yielding the batch
|
|
1028
|
+
# (so the user can mutate policy weights) but *before* letting the worker
|
|
1029
|
+
# continue, to ensure the next batch reflects the new weights.
|
|
1030
|
+
if (
|
|
1031
|
+
has_more
|
|
1032
|
+
and self.update_interval is not None
|
|
1033
|
+
and self._weight_sync_schemes is not None
|
|
1034
|
+
and num_batches_yielded % self.update_interval == 0
|
|
1035
|
+
):
|
|
1036
|
+
if self._sync:
|
|
1037
|
+
# Sync case: all workers will proceed next, update everyone.
|
|
1038
|
+
for scheme in self._weight_sync_schemes.values():
|
|
1039
|
+
scheme.send()
|
|
1040
|
+
else:
|
|
1041
|
+
# Async case: only release the worker that just produced data.
|
|
1042
|
+
for scheme in self._weight_sync_schemes.values():
|
|
1043
|
+
scheme.send(worker_ids=ready_worker_idx)
|
|
1044
|
+
|
|
1045
|
+
if (not self._sync) and has_more:
|
|
1046
|
+
# Release the worker that produced the last batch and restart its
|
|
1047
|
+
# receive tracker *after* any weight update has been propagated.
|
|
1048
|
+
rank = ready_worker_idx + 1
|
|
1049
|
+
torchrl_logger.debug(f"RANK 0 -- sending 'continue' to {rank}")
|
|
1050
|
+
self._store.set(f"NODE_{rank}_in", b"continue")
|
|
1051
|
+
trackers[ready_worker_idx] = self._tensordict_out[
|
|
1052
|
+
ready_worker_idx
|
|
1053
|
+
].irecv(src=rank, return_premature=True)
|
|
1054
|
+
|
|
1055
|
+
if self.max_weight_update_interval > -1:
|
|
1056
|
+
for j in range(self.num_workers):
|
|
1057
|
+
rank = j + 1
|
|
1058
|
+
if (
|
|
1059
|
+
self._batches_since_weight_update[j]
|
|
1060
|
+
> self.max_weight_update_interval
|
|
1061
|
+
):
|
|
1062
|
+
torchrl_logger.debug(f"RANK 0 -- updating weights for {rank=}")
|
|
1063
|
+
self.update_policy_weights_(
|
|
1064
|
+
policy_weights=None, worker_ids=rank
|
|
1065
|
+
)
|
|
1066
|
+
|
|
1067
|
+
for i in range(self.num_workers):
|
|
1068
|
+
rank = i + 1
|
|
1069
|
+
torchrl_logger.debug(f"RANK 0 -- shutting down rank {rank}.")
|
|
1070
|
+
self._store.set(f"NODE_{rank}_in", b"shutdown")
|
|
1071
|
+
|
|
1072
|
+
def _next_sync(self, total_frames):
|
|
1073
|
+
# in the 'sync' case we should update before collecting the data
|
|
1074
|
+
if self.update_after_each_batch:
|
|
1075
|
+
torchrl_logger.debug(
|
|
1076
|
+
f"RANK 0 -- updating weights for {total_frames=} in _next_sync."
|
|
1077
|
+
)
|
|
1078
|
+
self.update_policy_weights_()
|
|
1079
|
+
else:
|
|
1080
|
+
for j in range(self.num_workers):
|
|
1081
|
+
self._batches_since_weight_update[j] += 1
|
|
1082
|
+
|
|
1083
|
+
if total_frames < self.total_frames:
|
|
1084
|
+
for rank in range(1, self.num_workers + 1):
|
|
1085
|
+
torchrl_logger.debug(f"RANK 0 -- sending 'continue' to {rank}")
|
|
1086
|
+
self._store.set(f"NODE_{rank}_in", b"continue")
|
|
1087
|
+
trackers = []
|
|
1088
|
+
for i in range(self.num_workers):
|
|
1089
|
+
rank = i + 1
|
|
1090
|
+
torchrl_logger.debug(f"RANK 0 -- receiving {rank=} in _next_sync.")
|
|
1091
|
+
trackers.append(
|
|
1092
|
+
self._tensordict_out_unbind[i].irecv(src=rank, return_premature=True)
|
|
1093
|
+
)
|
|
1094
|
+
for tracker in trackers:
|
|
1095
|
+
for _tracker in tracker:
|
|
1096
|
+
_tracker.wait()
|
|
1097
|
+
data = self._tensordict_out.clone()
|
|
1098
|
+
traj_ids = data.get(("collector", "traj_ids"), None)
|
|
1099
|
+
if traj_ids is not None:
|
|
1100
|
+
for i in range(1, self.num_workers):
|
|
1101
|
+
traj_ids[i] += traj_ids[i - 1].max()
|
|
1102
|
+
data.set_(("collector", "traj_ids"), traj_ids)
|
|
1103
|
+
total_frames += data.numel()
|
|
1104
|
+
return data, total_frames
|
|
1105
|
+
|
|
1106
|
+
def _next_async(self, total_frames, trackers):
|
|
1107
|
+
data = None
|
|
1108
|
+
ready_worker_idx = None
|
|
1109
|
+
while data is None:
|
|
1110
|
+
for i in range(self.num_workers):
|
|
1111
|
+
rank = i + 1
|
|
1112
|
+
torchrl_logger.debug(f"RANK 0 -- checking {rank=} in _next_async.")
|
|
1113
|
+
if self._store.get(f"NODE_{rank}_status") == b"done":
|
|
1114
|
+
torchrl_logger.debug(f"RANK 0 -- receiving {rank=} in _next_async.")
|
|
1115
|
+
for _tracker in trackers[i]:
|
|
1116
|
+
_tracker.wait()
|
|
1117
|
+
torchrl_logger.debug(f"RANK 0 -- received {rank=} in _next_async.")
|
|
1118
|
+
data = self._tensordict_out[i].clone()
|
|
1119
|
+
if self.update_after_each_batch:
|
|
1120
|
+
torchrl_logger.debug(
|
|
1121
|
+
f"RANK 0 -- updating weights for {rank=} in _next_async."
|
|
1122
|
+
)
|
|
1123
|
+
self.update_policy_weights_(worker_ids=rank)
|
|
1124
|
+
total_frames += data.numel()
|
|
1125
|
+
ready_worker_idx = i
|
|
1126
|
+
for j in range(self.num_workers):
|
|
1127
|
+
self._batches_since_weight_update[j] += j != i
|
|
1128
|
+
break
|
|
1129
|
+
if ready_worker_idx is None:
|
|
1130
|
+
raise RuntimeError(
|
|
1131
|
+
"Failed to find a ready worker in async collection loop."
|
|
1132
|
+
)
|
|
1133
|
+
return data, total_frames, ready_worker_idx
|
|
1134
|
+
|
|
1135
|
+
def set_seed(self, seed: int, static_seed: bool = False) -> int:
|
|
1136
|
+
for i in range(self.num_workers):
|
|
1137
|
+
rank = i + 1
|
|
1138
|
+
self._store.set(f"NODE_{rank}_in", f"seeding_{seed}".encode())
|
|
1139
|
+
status = self._store.get(f"NODE_{rank}_out")
|
|
1140
|
+
if status != b"updated":
|
|
1141
|
+
raise RuntimeError(f"Expected 'seeded' but got status {status}.")
|
|
1142
|
+
self._store.delete_key(f"NODE_{rank}_out")
|
|
1143
|
+
new_seed = self._store.get(f"NODE_{rank}_seed")
|
|
1144
|
+
self._store.delete_key(f"NODE_{rank}_seed")
|
|
1145
|
+
seed = int(new_seed)
|
|
1146
|
+
return seed
|
|
1147
|
+
|
|
1148
|
+
def state_dict(self) -> OrderedDict:
|
|
1149
|
+
raise NotImplementedError
|
|
1150
|
+
|
|
1151
|
+
def load_state_dict(self, state_dict: OrderedDict) -> None:
|
|
1152
|
+
raise NotImplementedError
|
|
1153
|
+
|
|
1154
|
+
def shutdown(self, timeout: float | None = None) -> None:
|
|
1155
|
+
# Prevent double shutdown
|
|
1156
|
+
if getattr(self, "_shutdown", False):
|
|
1157
|
+
return
|
|
1158
|
+
self._shutdown = True
|
|
1159
|
+
|
|
1160
|
+
self._store.set("TRAINER_status", b"shutdown")
|
|
1161
|
+
for i in range(self.num_workers):
|
|
1162
|
+
rank = i + 1
|
|
1163
|
+
torchrl_logger.debug(f"shutting down node with rank={rank}")
|
|
1164
|
+
self._store.set(f"NODE_{rank}_in", b"shutdown")
|
|
1165
|
+
for i in range(self.num_workers):
|
|
1166
|
+
rank = i + 1
|
|
1167
|
+
torchrl_logger.debug(f"getting status of node {rank}")
|
|
1168
|
+
status = self._store.get(f"NODE_{rank}_out")
|
|
1169
|
+
if status != b"down":
|
|
1170
|
+
raise RuntimeError(f"Expected 'down' but got status {status}.")
|
|
1171
|
+
self._store.delete_key(f"NODE_{rank}_out")
|
|
1172
|
+
for i in range(self.num_workers):
|
|
1173
|
+
if self.launcher == "mp":
|
|
1174
|
+
if not self.jobs[i].is_alive():
|
|
1175
|
+
continue
|
|
1176
|
+
self.jobs[i].join(timeout=10)
|
|
1177
|
+
elif self.launcher == "submitit":
|
|
1178
|
+
self.jobs[i].result()
|
|
1179
|
+
elif self.launcher == "submitit_delayed":
|
|
1180
|
+
pass
|
|
1181
|
+
|
|
1182
|
+
# Clean up weight sync schemes AFTER workers have exited
|
|
1183
|
+
# (workers have their own scheme instances that they clean up)
|
|
1184
|
+
if self._weight_sync_schemes is not None:
|
|
1185
|
+
torchrl_logger.debug("shutting down weight sync schemes")
|
|
1186
|
+
for scheme in self._weight_sync_schemes.values():
|
|
1187
|
+
try:
|
|
1188
|
+
scheme.shutdown()
|
|
1189
|
+
except Exception as e:
|
|
1190
|
+
torchrl_logger.warning(
|
|
1191
|
+
f"Error shutting down weight sync scheme: {e}"
|
|
1192
|
+
)
|
|
1193
|
+
self._weight_sync_schemes = None
|
|
1194
|
+
|
|
1195
|
+
# Destroy torch.distributed process group
|
|
1196
|
+
if torch.distributed.is_initialized():
|
|
1197
|
+
torchrl_logger.debug("destroying process group")
|
|
1198
|
+
torch.distributed.destroy_process_group()
|
|
1199
|
+
|
|
1200
|
+
torchrl_logger.debug("collector shut down")
|
|
1201
|
+
|
|
1202
|
+
|
|
1203
|
+
class DistributedWeightUpdater(WeightUpdaterBase):
|
|
1204
|
+
"""A remote weight updater for synchronizing policy weights across distributed workers.
|
|
1205
|
+
|
|
1206
|
+
.. warning::
|
|
1207
|
+
This class has been deprecated in favor of the :class:`~torchrl.weight_update.DistributedWeightSyncScheme`
|
|
1208
|
+
API.
|
|
1209
|
+
|
|
1210
|
+
The `DistributedWeightUpdater` class provides a mechanism for updating the weights
|
|
1211
|
+
of a policy across distributed inference workers. It is designed to work with the
|
|
1212
|
+
:class:`~torchrl.collectors.distributed.DistributedDataCollector` to ensure that each worker receives the latest policy weights.
|
|
1213
|
+
This class is typically used in distributed data collection scenarios where multiple workers
|
|
1214
|
+
need to be kept in sync with the central policy weights.
|
|
1215
|
+
|
|
1216
|
+
Args:
|
|
1217
|
+
store (dict[str, str]): A dictionary-like store used for communication between the server
|
|
1218
|
+
and the distributed workers.
|
|
1219
|
+
policy_weights (TensorDictBase): The current weights of the policy that need to be distributed
|
|
1220
|
+
to the workers.
|
|
1221
|
+
num_workers (int): The number of distributed workers that will receive the updated policy weights.
|
|
1222
|
+
sync (bool): if ``True``, the sync happens synchronously (the server waits for the worker to have completed
|
|
1223
|
+
the update to restart the run).
|
|
1224
|
+
|
|
1225
|
+
Methods:
|
|
1226
|
+
update_weights: Updates the weights on specified or all distributed workers.
|
|
1227
|
+
all_worker_ids: Returns a list of all worker identifiers (not implemented in this class).
|
|
1228
|
+
_sync_weights_with_worker: Synchronizes the server weights with a specific worker (not implemented).
|
|
1229
|
+
_get_server_weights: Retrieves the latest weights from the server (not implemented).
|
|
1230
|
+
_maybe_map_weights: Optionally maps server weights before distribution (not implemented).
|
|
1231
|
+
|
|
1232
|
+
.. note::
|
|
1233
|
+
This class assumes that the server weights can be directly applied to the distributed workers
|
|
1234
|
+
without any additional processing. If your use case requires more complex weight mapping or
|
|
1235
|
+
synchronization logic, consider extending `WeightUpdaterBase` with a custom implementation.
|
|
1236
|
+
|
|
1237
|
+
Raises:
|
|
1238
|
+
RuntimeError: If the worker rank is less than 1 or if the status returned by the store is not "updated".
|
|
1239
|
+
|
|
1240
|
+
.. seealso:: :class:`~torchrl.collectors.WeightUpdaterBase` and
|
|
1241
|
+
:class:`~torchrl.collectors.distributed.DistributedDataCollector`.
|
|
1242
|
+
|
|
1243
|
+
"""
|
|
1244
|
+
|
|
1245
|
+
_VERBOSE = False
|
|
1246
|
+
|
|
1247
|
+
def __init__(
|
|
1248
|
+
self,
|
|
1249
|
+
store: dict[str, str],
|
|
1250
|
+
policy_weights: TensorDictBase,
|
|
1251
|
+
num_workers: int,
|
|
1252
|
+
sync: bool,
|
|
1253
|
+
):
|
|
1254
|
+
self._store = store
|
|
1255
|
+
self.policy_weights = policy_weights
|
|
1256
|
+
self.num_workers = num_workers
|
|
1257
|
+
self._sync = sync
|
|
1258
|
+
self._batches_since_weight_update = [0 for _ in range(self.num_workers)]
|
|
1259
|
+
|
|
1260
|
+
def _sync_weights_with_worker(
|
|
1261
|
+
self, worker_id: int | torch.device, server_weights: TensorDictBase
|
|
1262
|
+
) -> TensorDictBase:
|
|
1263
|
+
raise NotImplementedError
|
|
1264
|
+
|
|
1265
|
+
def _get_server_weights(self) -> TensorDictBase:
|
|
1266
|
+
raise NotImplementedError
|
|
1267
|
+
|
|
1268
|
+
def _maybe_map_weights(self, server_weights: TensorDictBase) -> TensorDictBase:
|
|
1269
|
+
raise NotImplementedError
|
|
1270
|
+
|
|
1271
|
+
def all_worker_ids(self) -> list[int] | list[torch.device]:
|
|
1272
|
+
raise NotImplementedError
|
|
1273
|
+
|
|
1274
|
+
def _push_weights(
|
|
1275
|
+
self,
|
|
1276
|
+
policy_or_weights: TensorDictModuleBase | TensorDictBase | dict | None = None,
|
|
1277
|
+
worker_ids: torch.device | int | list[int] | list[torch.device] | None = None,
|
|
1278
|
+
):
|
|
1279
|
+
worker_rank = worker_ids
|
|
1280
|
+
if isinstance(worker_ids, int):
|
|
1281
|
+
if worker_rank is not None and worker_rank < 1:
|
|
1282
|
+
raise RuntimeError("worker_rank must be greater than 1")
|
|
1283
|
+
worker_rank = [worker_rank - 1]
|
|
1284
|
+
workers = range(self.num_workers) if worker_rank is None else worker_rank
|
|
1285
|
+
weights = (
|
|
1286
|
+
self.policy_weights if policy_or_weights is None else policy_or_weights
|
|
1287
|
+
)
|
|
1288
|
+
for i in workers:
|
|
1289
|
+
rank = i + 1
|
|
1290
|
+
torchrl_logger.debug(f"updating weights of {rank}")
|
|
1291
|
+
self._store.set(f"NODE_{rank}_in", b"update_weights")
|
|
1292
|
+
if self._sync:
|
|
1293
|
+
weights.send(rank)
|
|
1294
|
+
else:
|
|
1295
|
+
weights.isend(rank)
|
|
1296
|
+
self._batches_since_weight_update[i] = 0
|
|
1297
|
+
status = self._store.get(f"NODE_{rank}_out")
|
|
1298
|
+
if status != b"updated":
|
|
1299
|
+
raise RuntimeError(f"Expected 'updated' but got status {status}.")
|
|
1300
|
+
self._store.delete_key(f"NODE_{rank}_out")
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
class DistributedDataCollector(DistributedCollector, metaclass=_LegacyCollectorMeta):
|
|
1304
|
+
"""Deprecated version of :class:`~torchrl.collectors.distributed.DistributedCollector`."""
|
|
1305
|
+
|
|
1306
|
+
...
|