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.
Files changed (394) hide show
  1. benchmarks/benchmark_batched_envs.py +104 -0
  2. benchmarks/conftest.py +91 -0
  3. benchmarks/ecosystem/gym_env_throughput.py +321 -0
  4. benchmarks/ecosystem/vmas_rllib_vs_torchrl_sampling_performance.py +231 -0
  5. benchmarks/requirements.txt +7 -0
  6. benchmarks/storage/benchmark_sample_latency_over_rpc.py +193 -0
  7. benchmarks/test_collectors_benchmark.py +240 -0
  8. benchmarks/test_compressed_storage_benchmark.py +145 -0
  9. benchmarks/test_envs_benchmark.py +133 -0
  10. benchmarks/test_llm.py +101 -0
  11. benchmarks/test_non_tensor_env_benchmark.py +70 -0
  12. benchmarks/test_objectives_benchmarks.py +1199 -0
  13. benchmarks/test_replaybuffer_benchmark.py +254 -0
  14. sota-check/README.md +35 -0
  15. sota-implementations/README.md +142 -0
  16. sota-implementations/a2c/README.md +39 -0
  17. sota-implementations/a2c/a2c_atari.py +291 -0
  18. sota-implementations/a2c/a2c_mujoco.py +273 -0
  19. sota-implementations/a2c/utils_atari.py +240 -0
  20. sota-implementations/a2c/utils_mujoco.py +160 -0
  21. sota-implementations/bandits/README.md +7 -0
  22. sota-implementations/bandits/dqn.py +126 -0
  23. sota-implementations/cql/cql_offline.py +198 -0
  24. sota-implementations/cql/cql_online.py +249 -0
  25. sota-implementations/cql/discrete_cql_offline.py +180 -0
  26. sota-implementations/cql/discrete_cql_online.py +227 -0
  27. sota-implementations/cql/utils.py +471 -0
  28. sota-implementations/crossq/crossq.py +271 -0
  29. sota-implementations/crossq/utils.py +320 -0
  30. sota-implementations/ddpg/ddpg.py +231 -0
  31. sota-implementations/ddpg/utils.py +325 -0
  32. sota-implementations/decision_transformer/dt.py +163 -0
  33. sota-implementations/decision_transformer/lamb.py +167 -0
  34. sota-implementations/decision_transformer/online_dt.py +178 -0
  35. sota-implementations/decision_transformer/utils.py +562 -0
  36. sota-implementations/discrete_sac/discrete_sac.py +243 -0
  37. sota-implementations/discrete_sac/utils.py +324 -0
  38. sota-implementations/dqn/README.md +30 -0
  39. sota-implementations/dqn/dqn_atari.py +272 -0
  40. sota-implementations/dqn/dqn_cartpole.py +236 -0
  41. sota-implementations/dqn/utils_atari.py +132 -0
  42. sota-implementations/dqn/utils_cartpole.py +90 -0
  43. sota-implementations/dreamer/README.md +129 -0
  44. sota-implementations/dreamer/dreamer.py +586 -0
  45. sota-implementations/dreamer/dreamer_utils.py +1107 -0
  46. sota-implementations/expert-iteration/README.md +352 -0
  47. sota-implementations/expert-iteration/ei_utils.py +770 -0
  48. sota-implementations/expert-iteration/expert-iteration-async.py +512 -0
  49. sota-implementations/expert-iteration/expert-iteration-sync.py +508 -0
  50. sota-implementations/expert-iteration/requirements_gsm8k.txt +13 -0
  51. sota-implementations/expert-iteration/requirements_ifeval.txt +16 -0
  52. sota-implementations/gail/gail.py +327 -0
  53. sota-implementations/gail/gail_utils.py +68 -0
  54. sota-implementations/gail/ppo_utils.py +157 -0
  55. sota-implementations/grpo/README.md +273 -0
  56. sota-implementations/grpo/grpo-async.py +437 -0
  57. sota-implementations/grpo/grpo-sync.py +435 -0
  58. sota-implementations/grpo/grpo_utils.py +843 -0
  59. sota-implementations/grpo/requirements_gsm8k.txt +11 -0
  60. sota-implementations/grpo/requirements_ifeval.txt +16 -0
  61. sota-implementations/impala/README.md +33 -0
  62. sota-implementations/impala/impala_multi_node_ray.py +292 -0
  63. sota-implementations/impala/impala_multi_node_submitit.py +284 -0
  64. sota-implementations/impala/impala_single_node.py +261 -0
  65. sota-implementations/impala/utils.py +184 -0
  66. sota-implementations/iql/discrete_iql.py +230 -0
  67. sota-implementations/iql/iql_offline.py +164 -0
  68. sota-implementations/iql/iql_online.py +225 -0
  69. sota-implementations/iql/utils.py +437 -0
  70. sota-implementations/multiagent/README.md +74 -0
  71. sota-implementations/multiagent/iql.py +237 -0
  72. sota-implementations/multiagent/maddpg_iddpg.py +266 -0
  73. sota-implementations/multiagent/mappo_ippo.py +267 -0
  74. sota-implementations/multiagent/qmix_vdn.py +271 -0
  75. sota-implementations/multiagent/sac.py +337 -0
  76. sota-implementations/multiagent/utils/__init__.py +4 -0
  77. sota-implementations/multiagent/utils/logging.py +151 -0
  78. sota-implementations/multiagent/utils/utils.py +43 -0
  79. sota-implementations/ppo/README.md +29 -0
  80. sota-implementations/ppo/ppo_atari.py +305 -0
  81. sota-implementations/ppo/ppo_mujoco.py +293 -0
  82. sota-implementations/ppo/utils_atari.py +238 -0
  83. sota-implementations/ppo/utils_mujoco.py +152 -0
  84. sota-implementations/ppo_trainer/train.py +21 -0
  85. sota-implementations/redq/README.md +7 -0
  86. sota-implementations/redq/redq.py +199 -0
  87. sota-implementations/redq/utils.py +1060 -0
  88. sota-implementations/sac/sac-async.py +266 -0
  89. sota-implementations/sac/sac.py +239 -0
  90. sota-implementations/sac/utils.py +381 -0
  91. sota-implementations/sac_trainer/train.py +16 -0
  92. sota-implementations/td3/td3.py +254 -0
  93. sota-implementations/td3/utils.py +319 -0
  94. sota-implementations/td3_bc/td3_bc.py +177 -0
  95. sota-implementations/td3_bc/utils.py +251 -0
  96. torchrl/__init__.py +144 -0
  97. torchrl/_extension.py +74 -0
  98. torchrl/_torchrl.cpython-314-aarch64-linux-gnu.so +0 -0
  99. torchrl/_utils.py +1431 -0
  100. torchrl/collectors/__init__.py +48 -0
  101. torchrl/collectors/_base.py +1058 -0
  102. torchrl/collectors/_constants.py +88 -0
  103. torchrl/collectors/_multi_async.py +324 -0
  104. torchrl/collectors/_multi_base.py +1805 -0
  105. torchrl/collectors/_multi_sync.py +464 -0
  106. torchrl/collectors/_runner.py +581 -0
  107. torchrl/collectors/_single.py +2009 -0
  108. torchrl/collectors/_single_async.py +259 -0
  109. torchrl/collectors/collectors.py +62 -0
  110. torchrl/collectors/distributed/__init__.py +32 -0
  111. torchrl/collectors/distributed/default_configs.py +133 -0
  112. torchrl/collectors/distributed/generic.py +1306 -0
  113. torchrl/collectors/distributed/ray.py +1092 -0
  114. torchrl/collectors/distributed/rpc.py +1006 -0
  115. torchrl/collectors/distributed/sync.py +731 -0
  116. torchrl/collectors/distributed/utils.py +160 -0
  117. torchrl/collectors/llm/__init__.py +10 -0
  118. torchrl/collectors/llm/base.py +494 -0
  119. torchrl/collectors/llm/ray_collector.py +275 -0
  120. torchrl/collectors/llm/utils.py +36 -0
  121. torchrl/collectors/llm/weight_update/__init__.py +10 -0
  122. torchrl/collectors/llm/weight_update/vllm.py +348 -0
  123. torchrl/collectors/llm/weight_update/vllm_v2.py +311 -0
  124. torchrl/collectors/utils.py +433 -0
  125. torchrl/collectors/weight_update.py +591 -0
  126. torchrl/csrc/numpy_utils.h +38 -0
  127. torchrl/csrc/pybind.cpp +27 -0
  128. torchrl/csrc/segment_tree.h +458 -0
  129. torchrl/csrc/torch_utils.h +34 -0
  130. torchrl/csrc/utils.cpp +48 -0
  131. torchrl/csrc/utils.h +31 -0
  132. torchrl/data/__init__.py +187 -0
  133. torchrl/data/datasets/__init__.py +58 -0
  134. torchrl/data/datasets/atari_dqn.py +878 -0
  135. torchrl/data/datasets/common.py +281 -0
  136. torchrl/data/datasets/d4rl.py +489 -0
  137. torchrl/data/datasets/d4rl_infos.py +187 -0
  138. torchrl/data/datasets/gen_dgrl.py +375 -0
  139. torchrl/data/datasets/minari_data.py +643 -0
  140. torchrl/data/datasets/openml.py +177 -0
  141. torchrl/data/datasets/openx.py +798 -0
  142. torchrl/data/datasets/roboset.py +363 -0
  143. torchrl/data/datasets/utils.py +11 -0
  144. torchrl/data/datasets/vd4rl.py +432 -0
  145. torchrl/data/llm/__init__.py +34 -0
  146. torchrl/data/llm/dataset.py +491 -0
  147. torchrl/data/llm/history.py +1378 -0
  148. torchrl/data/llm/prompt.py +198 -0
  149. torchrl/data/llm/reward.py +225 -0
  150. torchrl/data/llm/topk.py +186 -0
  151. torchrl/data/llm/utils.py +543 -0
  152. torchrl/data/map/__init__.py +21 -0
  153. torchrl/data/map/hash.py +185 -0
  154. torchrl/data/map/query.py +204 -0
  155. torchrl/data/map/tdstorage.py +363 -0
  156. torchrl/data/map/tree.py +1434 -0
  157. torchrl/data/map/utils.py +103 -0
  158. torchrl/data/postprocs/__init__.py +8 -0
  159. torchrl/data/postprocs/postprocs.py +391 -0
  160. torchrl/data/replay_buffers/__init__.py +99 -0
  161. torchrl/data/replay_buffers/checkpointers.py +622 -0
  162. torchrl/data/replay_buffers/ray_buffer.py +292 -0
  163. torchrl/data/replay_buffers/replay_buffers.py +2376 -0
  164. torchrl/data/replay_buffers/samplers.py +2578 -0
  165. torchrl/data/replay_buffers/scheduler.py +265 -0
  166. torchrl/data/replay_buffers/storages.py +2412 -0
  167. torchrl/data/replay_buffers/utils.py +1042 -0
  168. torchrl/data/replay_buffers/writers.py +781 -0
  169. torchrl/data/tensor_specs.py +7101 -0
  170. torchrl/data/utils.py +334 -0
  171. torchrl/envs/__init__.py +265 -0
  172. torchrl/envs/async_envs.py +1105 -0
  173. torchrl/envs/batched_envs.py +3093 -0
  174. torchrl/envs/common.py +4241 -0
  175. torchrl/envs/custom/__init__.py +11 -0
  176. torchrl/envs/custom/chess.py +617 -0
  177. torchrl/envs/custom/llm.py +214 -0
  178. torchrl/envs/custom/pendulum.py +401 -0
  179. torchrl/envs/custom/san_moves.txt +29274 -0
  180. torchrl/envs/custom/tictactoeenv.py +288 -0
  181. torchrl/envs/env_creator.py +263 -0
  182. torchrl/envs/gym_like.py +752 -0
  183. torchrl/envs/libs/__init__.py +68 -0
  184. torchrl/envs/libs/_gym_utils.py +326 -0
  185. torchrl/envs/libs/brax.py +846 -0
  186. torchrl/envs/libs/dm_control.py +544 -0
  187. torchrl/envs/libs/envpool.py +447 -0
  188. torchrl/envs/libs/gym.py +2239 -0
  189. torchrl/envs/libs/habitat.py +138 -0
  190. torchrl/envs/libs/isaac_lab.py +87 -0
  191. torchrl/envs/libs/isaacgym.py +203 -0
  192. torchrl/envs/libs/jax_utils.py +166 -0
  193. torchrl/envs/libs/jumanji.py +963 -0
  194. torchrl/envs/libs/meltingpot.py +599 -0
  195. torchrl/envs/libs/openml.py +153 -0
  196. torchrl/envs/libs/openspiel.py +652 -0
  197. torchrl/envs/libs/pettingzoo.py +1042 -0
  198. torchrl/envs/libs/procgen.py +351 -0
  199. torchrl/envs/libs/robohive.py +429 -0
  200. torchrl/envs/libs/smacv2.py +645 -0
  201. torchrl/envs/libs/unity_mlagents.py +891 -0
  202. torchrl/envs/libs/utils.py +147 -0
  203. torchrl/envs/libs/vmas.py +813 -0
  204. torchrl/envs/llm/__init__.py +63 -0
  205. torchrl/envs/llm/chat.py +730 -0
  206. torchrl/envs/llm/datasets/README.md +4 -0
  207. torchrl/envs/llm/datasets/__init__.py +17 -0
  208. torchrl/envs/llm/datasets/gsm8k.py +353 -0
  209. torchrl/envs/llm/datasets/ifeval.py +274 -0
  210. torchrl/envs/llm/envs.py +789 -0
  211. torchrl/envs/llm/libs/README.md +3 -0
  212. torchrl/envs/llm/libs/__init__.py +8 -0
  213. torchrl/envs/llm/libs/mlgym.py +869 -0
  214. torchrl/envs/llm/reward/__init__.py +10 -0
  215. torchrl/envs/llm/reward/gsm8k.py +324 -0
  216. torchrl/envs/llm/reward/ifeval/README.md +13 -0
  217. torchrl/envs/llm/reward/ifeval/__init__.py +10 -0
  218. torchrl/envs/llm/reward/ifeval/_instructions.py +1667 -0
  219. torchrl/envs/llm/reward/ifeval/_instructions_main.py +131 -0
  220. torchrl/envs/llm/reward/ifeval/_instructions_registry.py +100 -0
  221. torchrl/envs/llm/reward/ifeval/_instructions_util.py +1677 -0
  222. torchrl/envs/llm/reward/ifeval/_scorer.py +454 -0
  223. torchrl/envs/llm/transforms/__init__.py +55 -0
  224. torchrl/envs/llm/transforms/browser.py +292 -0
  225. torchrl/envs/llm/transforms/dataloading.py +859 -0
  226. torchrl/envs/llm/transforms/format.py +73 -0
  227. torchrl/envs/llm/transforms/kl.py +1544 -0
  228. torchrl/envs/llm/transforms/policy_version.py +189 -0
  229. torchrl/envs/llm/transforms/reason.py +323 -0
  230. torchrl/envs/llm/transforms/tokenizer.py +321 -0
  231. torchrl/envs/llm/transforms/tools.py +1955 -0
  232. torchrl/envs/model_based/__init__.py +9 -0
  233. torchrl/envs/model_based/common.py +180 -0
  234. torchrl/envs/model_based/dreamer.py +112 -0
  235. torchrl/envs/transforms/__init__.py +147 -0
  236. torchrl/envs/transforms/functional.py +48 -0
  237. torchrl/envs/transforms/gym_transforms.py +203 -0
  238. torchrl/envs/transforms/module.py +341 -0
  239. torchrl/envs/transforms/r3m.py +372 -0
  240. torchrl/envs/transforms/ray_service.py +663 -0
  241. torchrl/envs/transforms/rb_transforms.py +214 -0
  242. torchrl/envs/transforms/transforms.py +11835 -0
  243. torchrl/envs/transforms/utils.py +94 -0
  244. torchrl/envs/transforms/vc1.py +307 -0
  245. torchrl/envs/transforms/vecnorm.py +845 -0
  246. torchrl/envs/transforms/vip.py +407 -0
  247. torchrl/envs/utils.py +1718 -0
  248. torchrl/envs/vec_envs.py +11 -0
  249. torchrl/modules/__init__.py +206 -0
  250. torchrl/modules/distributions/__init__.py +73 -0
  251. torchrl/modules/distributions/continuous.py +830 -0
  252. torchrl/modules/distributions/discrete.py +908 -0
  253. torchrl/modules/distributions/truncated_normal.py +187 -0
  254. torchrl/modules/distributions/utils.py +233 -0
  255. torchrl/modules/llm/__init__.py +62 -0
  256. torchrl/modules/llm/backends/__init__.py +65 -0
  257. torchrl/modules/llm/backends/vllm/__init__.py +94 -0
  258. torchrl/modules/llm/backends/vllm/_models.py +46 -0
  259. torchrl/modules/llm/backends/vllm/base.py +72 -0
  260. torchrl/modules/llm/backends/vllm/vllm_async.py +2075 -0
  261. torchrl/modules/llm/backends/vllm/vllm_plugin.py +22 -0
  262. torchrl/modules/llm/backends/vllm/vllm_sync.py +446 -0
  263. torchrl/modules/llm/backends/vllm/vllm_utils.py +129 -0
  264. torchrl/modules/llm/policies/__init__.py +28 -0
  265. torchrl/modules/llm/policies/common.py +1809 -0
  266. torchrl/modules/llm/policies/transformers_wrapper.py +2756 -0
  267. torchrl/modules/llm/policies/vllm_wrapper.py +2241 -0
  268. torchrl/modules/llm/utils.py +23 -0
  269. torchrl/modules/mcts/__init__.py +21 -0
  270. torchrl/modules/mcts/scores.py +579 -0
  271. torchrl/modules/models/__init__.py +86 -0
  272. torchrl/modules/models/batchrenorm.py +119 -0
  273. torchrl/modules/models/decision_transformer.py +179 -0
  274. torchrl/modules/models/exploration.py +731 -0
  275. torchrl/modules/models/llm.py +156 -0
  276. torchrl/modules/models/model_based.py +596 -0
  277. torchrl/modules/models/models.py +1712 -0
  278. torchrl/modules/models/multiagent.py +1067 -0
  279. torchrl/modules/models/recipes/impala.py +185 -0
  280. torchrl/modules/models/utils.py +162 -0
  281. torchrl/modules/planners/__init__.py +10 -0
  282. torchrl/modules/planners/cem.py +228 -0
  283. torchrl/modules/planners/common.py +73 -0
  284. torchrl/modules/planners/mppi.py +265 -0
  285. torchrl/modules/tensordict_module/__init__.py +89 -0
  286. torchrl/modules/tensordict_module/actors.py +2457 -0
  287. torchrl/modules/tensordict_module/common.py +529 -0
  288. torchrl/modules/tensordict_module/exploration.py +814 -0
  289. torchrl/modules/tensordict_module/probabilistic.py +321 -0
  290. torchrl/modules/tensordict_module/rnn.py +1639 -0
  291. torchrl/modules/tensordict_module/sequence.py +132 -0
  292. torchrl/modules/tensordict_module/world_models.py +34 -0
  293. torchrl/modules/utils/__init__.py +38 -0
  294. torchrl/modules/utils/mappings.py +9 -0
  295. torchrl/modules/utils/utils.py +89 -0
  296. torchrl/objectives/__init__.py +78 -0
  297. torchrl/objectives/a2c.py +659 -0
  298. torchrl/objectives/common.py +753 -0
  299. torchrl/objectives/cql.py +1346 -0
  300. torchrl/objectives/crossq.py +710 -0
  301. torchrl/objectives/ddpg.py +453 -0
  302. torchrl/objectives/decision_transformer.py +371 -0
  303. torchrl/objectives/deprecated.py +516 -0
  304. torchrl/objectives/dqn.py +683 -0
  305. torchrl/objectives/dreamer.py +488 -0
  306. torchrl/objectives/functional.py +48 -0
  307. torchrl/objectives/gail.py +258 -0
  308. torchrl/objectives/iql.py +996 -0
  309. torchrl/objectives/llm/__init__.py +30 -0
  310. torchrl/objectives/llm/grpo.py +846 -0
  311. torchrl/objectives/llm/sft.py +482 -0
  312. torchrl/objectives/multiagent/__init__.py +8 -0
  313. torchrl/objectives/multiagent/qmixer.py +396 -0
  314. torchrl/objectives/ppo.py +1669 -0
  315. torchrl/objectives/redq.py +683 -0
  316. torchrl/objectives/reinforce.py +530 -0
  317. torchrl/objectives/sac.py +1580 -0
  318. torchrl/objectives/td3.py +570 -0
  319. torchrl/objectives/td3_bc.py +625 -0
  320. torchrl/objectives/utils.py +782 -0
  321. torchrl/objectives/value/__init__.py +28 -0
  322. torchrl/objectives/value/advantages.py +1956 -0
  323. torchrl/objectives/value/functional.py +1459 -0
  324. torchrl/objectives/value/utils.py +360 -0
  325. torchrl/record/__init__.py +17 -0
  326. torchrl/record/loggers/__init__.py +23 -0
  327. torchrl/record/loggers/common.py +48 -0
  328. torchrl/record/loggers/csv.py +226 -0
  329. torchrl/record/loggers/mlflow.py +142 -0
  330. torchrl/record/loggers/tensorboard.py +139 -0
  331. torchrl/record/loggers/trackio.py +163 -0
  332. torchrl/record/loggers/utils.py +78 -0
  333. torchrl/record/loggers/wandb.py +214 -0
  334. torchrl/record/recorder.py +554 -0
  335. torchrl/services/__init__.py +79 -0
  336. torchrl/services/base.py +109 -0
  337. torchrl/services/ray_service.py +453 -0
  338. torchrl/testing/__init__.py +107 -0
  339. torchrl/testing/assertions.py +179 -0
  340. torchrl/testing/dist_utils.py +122 -0
  341. torchrl/testing/env_creators.py +227 -0
  342. torchrl/testing/env_helper.py +35 -0
  343. torchrl/testing/gym_helpers.py +156 -0
  344. torchrl/testing/llm_mocks.py +119 -0
  345. torchrl/testing/mocking_classes.py +2720 -0
  346. torchrl/testing/modules.py +295 -0
  347. torchrl/testing/mp_helpers.py +15 -0
  348. torchrl/testing/ray_helpers.py +293 -0
  349. torchrl/testing/utils.py +190 -0
  350. torchrl/trainers/__init__.py +42 -0
  351. torchrl/trainers/algorithms/__init__.py +11 -0
  352. torchrl/trainers/algorithms/configs/__init__.py +705 -0
  353. torchrl/trainers/algorithms/configs/collectors.py +216 -0
  354. torchrl/trainers/algorithms/configs/common.py +41 -0
  355. torchrl/trainers/algorithms/configs/data.py +308 -0
  356. torchrl/trainers/algorithms/configs/envs.py +104 -0
  357. torchrl/trainers/algorithms/configs/envs_libs.py +361 -0
  358. torchrl/trainers/algorithms/configs/logging.py +80 -0
  359. torchrl/trainers/algorithms/configs/modules.py +570 -0
  360. torchrl/trainers/algorithms/configs/objectives.py +177 -0
  361. torchrl/trainers/algorithms/configs/trainers.py +340 -0
  362. torchrl/trainers/algorithms/configs/transforms.py +955 -0
  363. torchrl/trainers/algorithms/configs/utils.py +252 -0
  364. torchrl/trainers/algorithms/configs/weight_sync_schemes.py +191 -0
  365. torchrl/trainers/algorithms/configs/weight_update.py +159 -0
  366. torchrl/trainers/algorithms/ppo.py +373 -0
  367. torchrl/trainers/algorithms/sac.py +308 -0
  368. torchrl/trainers/helpers/__init__.py +40 -0
  369. torchrl/trainers/helpers/collectors.py +416 -0
  370. torchrl/trainers/helpers/envs.py +573 -0
  371. torchrl/trainers/helpers/logger.py +33 -0
  372. torchrl/trainers/helpers/losses.py +132 -0
  373. torchrl/trainers/helpers/models.py +658 -0
  374. torchrl/trainers/helpers/replay_buffer.py +59 -0
  375. torchrl/trainers/helpers/trainers.py +301 -0
  376. torchrl/trainers/trainers.py +2052 -0
  377. torchrl/weight_update/__init__.py +33 -0
  378. torchrl/weight_update/_distributed.py +749 -0
  379. torchrl/weight_update/_mp.py +624 -0
  380. torchrl/weight_update/_noupdate.py +102 -0
  381. torchrl/weight_update/_ray.py +1032 -0
  382. torchrl/weight_update/_rpc.py +284 -0
  383. torchrl/weight_update/_shared.py +891 -0
  384. torchrl/weight_update/llm/__init__.py +32 -0
  385. torchrl/weight_update/llm/vllm_double_buffer.py +370 -0
  386. torchrl/weight_update/llm/vllm_nccl.py +710 -0
  387. torchrl/weight_update/utils.py +73 -0
  388. torchrl/weight_update/weight_sync_schemes.py +1244 -0
  389. torchrl-0.11.0.dist-info/METADATA +1308 -0
  390. torchrl-0.11.0.dist-info/RECORD +394 -0
  391. torchrl-0.11.0.dist-info/WHEEL +5 -0
  392. torchrl-0.11.0.dist-info/entry_points.txt +2 -0
  393. torchrl-0.11.0.dist-info/licenses/LICENSE +21 -0
  394. torchrl-0.11.0.dist-info/top_level.txt +7 -0
@@ -0,0 +1,859 @@
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
+ from __future__ import annotations
6
+
7
+ import warnings
8
+ from collections import deque
9
+ from collections.abc import Callable, Iterable, Mapping
10
+
11
+ from typing import Any, Literal, TypeVar
12
+
13
+ import torch
14
+ from tensordict import is_tensor_collection, lazy_stack, TensorDict, TensorDictBase
15
+
16
+ from torchrl.data.tensor_specs import Composite, DEVICE_TYPING, TensorSpec
17
+ from torchrl.envs.common import EnvBase
18
+ from torchrl.envs.transforms import TensorDictPrimer, Transform
19
+
20
+ # Import ray service components
21
+ from torchrl.envs.transforms.ray_service import (
22
+ _map_input_output_device,
23
+ _RayServiceMetaClass,
24
+ RayTransform,
25
+ )
26
+ from torchrl.envs.utils import make_composite_from_td
27
+
28
+ T = TypeVar("T")
29
+
30
+
31
+ def as_nested_tensor(list_of_tensordicts: list[TensorDictBase]) -> TensorDictBase:
32
+ """Stacks a list of tensordicts into a single tensordict with nested tensors.
33
+
34
+ Args:
35
+ list_of_tensordicts (list[TensorDictBase]): A list of tensordicts to stack.
36
+
37
+ Returns:
38
+ TensorDictBase: A tensordict with nested tensors.
39
+
40
+ """
41
+
42
+ def _as_nested_tensor(*list_of_tensors):
43
+ return torch.nested.as_nested_tensor(list_of_tensors, layout=torch.jagged)
44
+
45
+ batch_size = list(list_of_tensordicts[0].shape)
46
+ batch_size.insert(0, len(list_of_tensordicts))
47
+ result: TensorDictBase = list_of_tensordicts[0].apply( # type: ignore[assignment]
48
+ _as_nested_tensor, *list_of_tensordicts[1:], batch_size=batch_size
49
+ )
50
+ return result
51
+
52
+
53
+ def as_padded_tensor(
54
+ list_of_tensordicts: list[TensorDictBase], dim=0, stack_dim: int = 0
55
+ ) -> TensorDictBase:
56
+ """Stacks a list of tensordicts into a single tensordict with padded tensors.
57
+
58
+ Args:
59
+ list_of_tensordicts (list[[TensorDictBase]]): A list of tensordicts to stack.
60
+ dim (int, optional): The dimension along which to pad. Defaults to 0.
61
+ stack_dim (int, optional): The dimension along which to stack. Defaults to 0.
62
+
63
+ Returns:
64
+ TensorDictBase: A tensordict with padded tensors.
65
+ """
66
+
67
+ def _stack_tensors(*list_of_tensors):
68
+ if dim < 0:
69
+ raise ValueError("dim must be >= 0")
70
+ max_length = max([t.size(dim) for t in list_of_tensors])
71
+
72
+ def pad_tensor(tensor):
73
+ padding_length = max_length - tensor.size(dim)
74
+ shape = [
75
+ s if i != dim else padding_length for i, s in enumerate(tensor.shape)
76
+ ]
77
+ return torch.cat((tensor.new_zeros(shape), tensor), dim=dim)
78
+
79
+ return torch.stack([pad_tensor(t) for t in list_of_tensors], dim=stack_dim)
80
+
81
+ batch_size = list(list_of_tensordicts[0].shape)
82
+ batch_size.insert(dim, len(list_of_tensordicts))
83
+ result: TensorDictBase = list_of_tensordicts[0].apply( # type: ignore[assignment]
84
+ _stack_tensors, *list_of_tensordicts[1:], batch_size=batch_size
85
+ )
86
+ return result
87
+
88
+
89
+ class RayDataLoadingPrimer(RayTransform):
90
+ """A :class:`~torchrl.envs.llm.transforms.dataloading.DataLoadingPrimer` that creates a single actor that can be shared by multiple environments.
91
+
92
+ This class creates a Ray remote actor from DataLoadingPrimer that can be shared across multiple workers.
93
+ All method calls are delegated to the remote actor, ensuring that multiple environments iterate over
94
+ the same shared dataloader.
95
+
96
+ Keyword Args:
97
+ dataloader: A dataloader object to be used directly. Ray will handle serialization.
98
+ dataloader_factory: A callable that returns a dataloader. This allows for explicit
99
+ resource control and avoids serialization issues.
100
+ num_cpus (int, optional): Number of CPUs to allocate to the Ray actor.
101
+ Defaults to the dataloader's num_workers if available, otherwise 1.
102
+ num_gpus (int, optional): Number of GPUs to allocate to the Ray actor. Defaults to 0.
103
+ actor_name (str, optional): Name of the Ray actor to use. If provided, the actor will be reused if it already exists.
104
+ **kwargs: Additional keyword arguments to pass to DataLoadingPrimer.
105
+
106
+ Note:
107
+ Exactly one of `dataloader` or `dataloader_factory` must be provided.
108
+
109
+ Examples:
110
+ >>> # Option 1: Using a dataloader factory for explicit resource control
111
+ >>> def create_dataloader():
112
+ ... return torch.utils.data.DataLoader(dataset, batch_size=32, num_workers=4)
113
+ >>> primer1 = RayDataLoadingPrimer(dataloader_factory=create_dataloader, num_cpus=4)
114
+ >>> primer2 = RayDataLoadingPrimer(dataloader_factory=create_dataloader, num_cpus=4) # Same shared actor
115
+
116
+ >>> # Option 2: Pass dataloader directly (Ray handles serialization)
117
+ >>> dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, num_workers=4)
118
+ >>> primer1 = RayDataLoadingPrimer(dataloader=dataloader) # num_cpus=4 inferred from num_workers
119
+ >>> primer2 = RayDataLoadingPrimer(dataloader=dataloader) # Same shared actor
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ *,
125
+ dataloader=None,
126
+ dataloader_factory=None,
127
+ num_cpus=None,
128
+ num_gpus=0,
129
+ device: DEVICE_TYPING | None = None,
130
+ actor_name: str | None = None,
131
+ **kwargs,
132
+ ):
133
+ # Validate arguments: exactly one of dataloader or dataloader_factory must be provided
134
+ if dataloader is not None and dataloader_factory is not None:
135
+ raise ValueError(
136
+ "Cannot provide both 'dataloader' and 'dataloader_factory'. Choose one."
137
+ )
138
+ if dataloader is None and dataloader_factory is None:
139
+ raise ValueError(
140
+ "Must provide exactly one of 'dataloader' or 'dataloader_factory'."
141
+ )
142
+
143
+ # Infer num_cpus from dataloader if not specified
144
+ if num_cpus is None:
145
+ if dataloader is not None:
146
+ num_cpus = getattr(dataloader, "num_workers", 1)
147
+ elif dataloader_factory is not None:
148
+ temp_dataloader = dataloader_factory()
149
+ num_cpus = getattr(temp_dataloader, "num_workers", 1)
150
+ del temp_dataloader
151
+ else:
152
+ num_cpus = 1
153
+
154
+ if num_cpus == 0:
155
+ num_cpus = 1
156
+
157
+ # Handle device setup for primers
158
+ primers = kwargs.get("primers", None)
159
+ if hasattr(primers, "device") and primers.device is not None:
160
+ if device is not None and device != primers.device:
161
+ raise ValueError(
162
+ "Device mismatch between primers and device. "
163
+ "Use the device argument to set the device."
164
+ )
165
+ device = primers.device
166
+ if hasattr(primers, "cpu"):
167
+ primers = primers.cpu()
168
+ elif hasattr(primers, "to"):
169
+ primers = primers.to("cpu")
170
+ if primers is not None:
171
+ kwargs["primers"] = primers
172
+
173
+ # Store creation parameters for actor creation
174
+ self._dataloader = dataloader
175
+ self._dataloader_factory = dataloader_factory
176
+ self._creation_kwargs = kwargs
177
+
178
+ # Call parent constructor
179
+ super().__init__(
180
+ num_cpus=num_cpus,
181
+ num_gpus=num_gpus,
182
+ device=device,
183
+ actor_name=actor_name,
184
+ **kwargs,
185
+ )
186
+
187
+ # Actor initialization is handled by the parent RayTransform class
188
+
189
+ def _create_actor(self, **kwargs):
190
+ """Create the remote DataLoadingPrimer actor."""
191
+ # Create the remote DataLoadingPrimer with resource specifications
192
+ RemoteDataLoadingPrimer = self._ray.remote(
193
+ num_cpus=self._num_cpus, num_gpus=self._num_gpus
194
+ )(DataLoadingPrimer)
195
+
196
+ if self._actor_name is not None:
197
+ RemoteDataLoadingPrimer = RemoteDataLoadingPrimer.options(
198
+ name=self._actor_name
199
+ )
200
+
201
+ # Create the shared actor, passing factory or dataloader as appropriate
202
+ if self._dataloader_factory is not None:
203
+ actor = RemoteDataLoadingPrimer.remote(
204
+ dataloader_factory=self._dataloader_factory, **self._creation_kwargs
205
+ )
206
+ else:
207
+ actor = RemoteDataLoadingPrimer.remote(
208
+ dataloader=self._dataloader, **self._creation_kwargs
209
+ )
210
+
211
+ return actor
212
+
213
+ @property
214
+ def dataloader(self):
215
+ """Get dataloader property."""
216
+ raise NotImplementedError(
217
+ "dataloader is not implemented for RayDataLoadingPrimer"
218
+ )
219
+
220
+ @property
221
+ def endless_dataloader(self):
222
+ """Get endless_dataloader property."""
223
+ raise NotImplementedError(
224
+ "endless_dataloader is not implemented for RayDataLoadingPrimer"
225
+ )
226
+
227
+ def __repr__(self):
228
+ """String representation."""
229
+ try:
230
+ if hasattr(self, "_actor") and self._actor is not None:
231
+ return self._ray.get(self._actor.__repr__.remote())
232
+ else:
233
+ return "RayDataLoadingPrimer(actor=None)"
234
+ except Exception:
235
+ return f"RayDataLoadingPrimer(actor={getattr(self, '_actor', 'None')})"
236
+
237
+ @property
238
+ def stack_method(self):
239
+ """Get stack_method property."""
240
+ raise NotImplementedError(
241
+ "stack_method is not implemented for RayDataLoadingPrimer"
242
+ )
243
+
244
+ @property
245
+ def repeats(self):
246
+ """Get repeats property."""
247
+ return self._ray.get(self._actor.__getattribute__.remote("repeats"))
248
+
249
+ @property
250
+ def data_keys(self):
251
+ """Get data_keys property."""
252
+ return self._ray.get(self._actor.__getattribute__.remote("data_keys"))
253
+
254
+ @property
255
+ def primers(self):
256
+ """Get primers property."""
257
+ return self._ray.get(self._actor.__getattribute__.remote("primers"))
258
+
259
+ @primers.setter
260
+ def primers(self, value: TensorSpec):
261
+ """Set primers property."""
262
+ self._ray.get(self._actor._set_attr.remote("primers", value))
263
+
264
+ # TensorDictPrimer methods
265
+ def init(self, tensordict: TensorDictBase | None):
266
+ """Initialize."""
267
+ return self._ray.get(self._actor.init.remote(tensordict))
268
+
269
+ def reset_dataloader(self):
270
+ """Reset the dataloader."""
271
+ return self._delegate_method_call("reset_dataloader")
272
+
273
+ @_map_input_output_device
274
+ def _load_from_dataloader(
275
+ self, reset: torch.Tensor | None = None
276
+ ) -> TensorDictBase:
277
+ """Load data from the dataloader."""
278
+ result = self._delegate_method_call("_load_from_dataloader", reset)
279
+
280
+ # Ensure proper batch dimensions: if result is scalar (ndim=0), unsqueeze to add batch dim
281
+ # This matches the behavior in the original DataLoadingPrimer._load_from_dataloader
282
+ if hasattr(result, "ndim") and not result.ndim:
283
+ result = result.unsqueeze(0)
284
+
285
+ return result
286
+
287
+ @property
288
+ def primers(self):
289
+ """Get primers property."""
290
+ return self._delegate_property_get("primers")
291
+
292
+ @primers.setter
293
+ def primers(self, value: TensorSpec):
294
+ """Set primers property."""
295
+ self._delegate_property_set("primers", value)
296
+
297
+ @_map_input_output_device
298
+ def _reset_func(
299
+ self, tensordict: TensorDictBase | None, tensordict_reset: TensorDictBase | None
300
+ ) -> TensorDictBase | None:
301
+ """Reset function."""
302
+ result = super()._reset_func(tensordict, tensordict_reset)
303
+
304
+ # Handle batch size expansion locally since remote actor lacks parent context
305
+ # This mimics the batch expansion logic from TensorDictPrimer._reset_func
306
+ if (
307
+ self.parent
308
+ and self.parent.batch_locked
309
+ and hasattr(result, "apply") # Check if it's a TensorDict-like object
310
+ ):
311
+ # Ensure result has proper batch dimensions to match parent
312
+ expected_batch_size = self.parent.batch_size
313
+ if result.batch_size != expected_batch_size:
314
+ # Expand result to match expected batch size
315
+ result = result.expand(expected_batch_size)
316
+
317
+ return result
318
+
319
+ # Additional methods and properties are handled by the parent RayTransform class
320
+
321
+
322
+ class DataLoadingPrimer(TensorDictPrimer, metaclass=_RayServiceMetaClass):
323
+ """A primer that loads data from a dataloader and converts it into a tensordict using ``stack_method``.
324
+
325
+ Args:
326
+ dataloader (Iterable[Dict[str, Any]]): The dataloader to load data from.
327
+ During collection, we will attempt to convert it into a tensordict using :func:`~tensordict.from_dict` or a
328
+ similar function.
329
+ It is assumed that the elements retrieved from the dataloader come in batches along the first dimension
330
+ of every tensor, unless `dataloader.batch_size=0`.
331
+ The dataloader must yield mappable data structures (e.g., dictionaries).
332
+ If a dataloader_factory is provided, it will be used to create a fresh dataloader and this argument can be
333
+ omitted.
334
+
335
+ Keyword Args:
336
+ primers (Composite | None, optional): The primers to use for each key in the dataloader. Defaults to None.
337
+ stack_method (Callable[[Any], Any] | Literal["as_nested_tensor", "as_padded_tensor"], optional): The method to
338
+ use for stacking the data. Defaults to ``maybe_dense_stack``.
339
+ repeats (int, optional): How many times the same sample needs to appear successively. This can be useful in
340
+ situations like GRPO where a single prompt is used multiple times to estimate the advantage using Monte-Carlo
341
+ samples (rather than an advantage module).
342
+ batch_size (int, torch.Size or None): the batch-size of the data delivered by the transform.
343
+ This is somewhat unrelated to the batch-size of the dataloader, in the sense that this number may or may
344
+ not match the DL's batch size.
345
+ If left empty, the batch-size is inferred from `dataloader.batch_size` if that attribute exists. If not,
346
+ an empty batch-size will be used (`torch.Size([])`).
347
+
348
+ .. note:: The batch-size of the Primer must match the batch-size of the parent environment (typically a
349
+ wrapper around :class:`~torchrl.envs.LLMEnv`).
350
+
351
+ group_repeats (bool, optional): if ``True``, the batch-size is multiplied by the number of repeats such that
352
+ all repeats are grouped in a single batch collected from the buffer. Defaults to ``False``.
353
+ dataloader_factory (Callable[[], Iterable[dict[str, Any]]], optional): A callable that returns a dataloader.
354
+ This allows for explicit resource control and avoids serialization issues.
355
+ use_ray_service (bool, optional): if ``True``, returns a :class:`RayDataLoadingPrimer` instance instead,
356
+ which creates a Ray actor for shared dataloader access across multiple environments.
357
+ Defaults to ``False``.
358
+
359
+ Attributes:
360
+ dataloader (Iterable[Any]): The dataloader to load data from.
361
+ endless_dataloader (Iterable[Any]): An endless iterator over the dataloader.
362
+ stack_method (Callable[[Any], Any]): The method to use for stacking the data.
363
+
364
+ .. seealso:: :class:`~torchrl.envs.LLMEnv` and :class:`~torchrl.envs.LLMEnv.from_dataloader`.
365
+
366
+ Examples:
367
+ Using the regular DataLoadingPrimer:
368
+
369
+ >>> dataloader = torch.utils.data.DataLoader(dataset, batch_size=32)
370
+ >>> primer = DataLoadingPrimer(dataloader=dataloader) # Regular implementation
371
+
372
+ Using the Ray-based implementation for shared dataloader access:
373
+
374
+ >>> primer = DataLoadingPrimer(dataloader=dataloader, use_ray_service=True) # Returns RayDataLoadingPrimer
375
+ >>> # Multiple environments can now share the same dataloader through the Ray actor
376
+
377
+ Example of a dataloader yielding strings:
378
+ >>> import random
379
+ >>> import string
380
+ >>> import tensordict as td
381
+ >>> import torch
382
+ >>> from tensordict import TensorDict
383
+ >>> from torchrl.data import Unbounded
384
+ >>> from torchrl.envs import DataLoadingPrimer, LLMEnv
385
+ >>> td.set_capture_non_tensor_stack(False).set()
386
+ >>> class DummyDataLoader:
387
+ ... '''A dummy dataloader that generates random strings.'''
388
+ ... def __init__(self, batch_size: int = 0):
389
+ ... self.batch_size = batch_size
390
+ ... def generate_random_string(self, length: int = 10) -. str:
391
+ ... '''Generate a random string of a given length.'''
392
+ ... return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
393
+ ... def __iter__(self):
394
+ ... return self
395
+ ... def __next__(self):
396
+ ... if self.batch_size == 0:
397
+ ... return self.generate_random_string()
398
+ ... else:
399
+ ... return [self.generate_random_string() for _ in range(self.batch_size)]
400
+ >>> # Create an LLM environment with string-to-string input/output.
401
+ >>> env = LLMEnv(from_text=True)
402
+ >>> # Append a DataLoadingPrimer to the environment.
403
+ >>> env = env.append_transform(
404
+ >>> DataLoadingPrimer(
405
+ >>> dataloader=DummyDataLoader(),
406
+ >>> example_data="a string!",
407
+ >>> )
408
+ >>> )
409
+ >>> # Test the environment.
410
+ >>> print(env.rand_action(TensorDict()))
411
+ TensorDict(
412
+ fields={
413
+ action: NonTensorData(data=a string, batch_size=torch.Size([]), device=None)},
414
+ batch_size=torch.Size([]),
415
+ device=None,
416
+ is_shared=False)
417
+ >>> print(env.rollout(3))
418
+ TensorDict(
419
+ fields={
420
+ action: NonTensorStack(
421
+ ['a string', 'a string', 'a string'],
422
+ batch_size=torch.Size([3]),
423
+ device=None),
424
+ done: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
425
+ next: TensorDict(
426
+ fields={
427
+ done: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
428
+ observation: NonTensorStack(
429
+ ['zxwvupirska string', 'zxwvupirska stringa string...,
430
+ batch_size=torch.Size([3]),
431
+ device=None),
432
+ terminated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
433
+ truncated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
434
+ batch_size=torch.Size([3]),
435
+ device=None,
436
+ is_shared=False),
437
+ observation: NonTensorStack(
438
+ ['zxwvupirsk', 'zxwvupirska string', 'zxwvupirska ...,
439
+ batch_size=torch.Size([3]),
440
+ device=None),
441
+ terminated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
442
+ truncated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
443
+ batch_size=torch.Size([3]),
444
+ device=None,
445
+ is_shared=False)
446
+ >>> # Roll out the environment with a specific initial state.
447
+ >>> init_state = env.reset(TensorDict(batch_size=[3]))
448
+ >>> print(env.rollout(3, auto_reset=False, tensordict=init_state))
449
+ TensorDict(
450
+ fields={
451
+ action: NonTensorStack(
452
+ [['a string', 'a string', 'a string'], ['a string'...,
453
+ batch_size=torch.Size([3, 3]),
454
+ device=None),
455
+ done: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
456
+ next: TensorDict(
457
+ fields={
458
+ done: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
459
+ observation: NonTensorStack(
460
+ [[array(['nngcmflsana string', 'vrrbnhzpmga string...,
461
+ batch_size=torch.Size([3, 3]),
462
+ device=None),
463
+ terminated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
464
+ truncated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
465
+ batch_size=torch.Size([3, 3]),
466
+ device=None,
467
+ is_shared=False),
468
+ observation: NonTensorStack(
469
+ [['nngcmflsan', array(['nngcmflsana string', 'vrrb...,
470
+ batch_size=torch.Size([3, 3]),
471
+ device=None),
472
+ terminated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
473
+ truncated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
474
+ batch_size=torch.Size([3, 3]),
475
+ device=None,
476
+ is_shared=False)
477
+
478
+ Example of dataloader yielding tensors:
479
+ >>> import random
480
+ >>> import string
481
+ >>>
482
+ >>> import tensordict as td
483
+ >>> import torch
484
+ >>> from tensordict import TensorDict
485
+ >>> from torchrl.data import Unbounded
486
+ >>> from torchrl.envs import DataLoadingPrimer, LLMEnv
487
+ >>>
488
+ >>> td.set_capture_non_tensor_stack(False).set()
489
+ >>>
490
+ >>>
491
+ >>> class DummyTensorDataLoader:
492
+ ... '''A dummy dataloader that generates tensors of random int64 values.'''
493
+ ...
494
+ ... def __init__(self, batch_size: int = 0, max_length: int = 10, padding: bool = False):
495
+ ... '''
496
+ ... Args:
497
+ ... batch_size (int, optional): The batch size of the generated tensors. Defaults to 0.
498
+ ... max_length (int, optional): The maximum length of the generated tensors. Defaults to 10.
499
+ ... padding (bool, optional): Whether to pad the tensors to the maximum length. Defaults to `False`.
500
+ ... '''
501
+ ... self.batch_size = batch_size
502
+ ... self.max_length = max_length
503
+ ... self.padding = padding
504
+ ...
505
+ ... def generate_random_tensor(self) -. torch.Tensor:
506
+ ... '''Generate a tensor of random int64 values.'''
507
+ ... length = random.randint(1, self.max_length)
508
+ ... return torch.tensor([random.randint(0, 100) for _ in range(length)], dtype=torch.int64)
509
+ ...
510
+ ... def pad_tensor(self, tensor: torch.Tensor) -. torch.Tensor:
511
+ ... '''Pad a tensor to the maximum length.'''
512
+ ... padding_length = self.max_length - len(tensor)
513
+ ... return torch.cat((torch.zeros(padding_length, dtype=torch.int64), tensor))
514
+ ...
515
+ ... def __iter__(self):
516
+ ... return self
517
+ ...
518
+ ... def __next__(self):
519
+ ... if self.batch_size == 0:
520
+ ... tensor = self.generate_random_tensor()
521
+ ... return self.pad_tensor(tensor) if self.padding else tensor
522
+ ... else:
523
+ ... tensors = [self.generate_random_tensor() for _ in range(self.batch_size)]
524
+ ... if self.padding:
525
+ ... tensors = [self.pad_tensor(tensor) for tensor in tensors]
526
+ ... return torch.stack(tensors)
527
+ ... else:
528
+ ... return tensors
529
+ >>>
530
+ >>> # Create an LLM environment with non-string input/output and append a DataLoadingPrimer.
531
+ >>> env = LLMEnv(from_text=False)
532
+ >>> env = env.append_transform(
533
+ >>> DataLoadingPrimer(
534
+ >>> dataloader=DummyTensorDataLoader(),
535
+ >>> data_specs=[Unbounded(shape=(-1,), dtype=torch.int64)],
536
+ >>> )
537
+ >>> )
538
+ >>> print(env.rand_action(TensorDict()))
539
+ TensorDict(
540
+ fields={
541
+ action: Tensor(shape=torch.Size([1]), device=cpu, dtype=torch.int64, is_shared=False)},
542
+ batch_size=torch.Size([]),
543
+ device=None,
544
+ is_shared=False)
545
+ >>> print(env.rollout(3))
546
+ LazyStackedTensorDict(
547
+ fields={
548
+ action: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.int64, is_shared=False),
549
+ done: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
550
+ next: LazyStackedTensorDict(
551
+ fields={
552
+ done: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
553
+ observation: Tensor(shape=torch.Size([3, -1]), device=cpu, dtype=torch.int64, is_shared=False),
554
+ terminated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
555
+ truncated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
556
+ exclusive_fields={
557
+ },
558
+ batch_size=torch.Size([3]),
559
+ device=None,
560
+ is_shared=False,
561
+ stack_dim=0),
562
+ observation: Tensor(shape=torch.Size([3, -1]), device=cpu, dtype=torch.int64, is_shared=False),
563
+ terminated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
564
+ truncated: Tensor(shape=torch.Size([3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
565
+ exclusive_fields={
566
+ },
567
+ batch_size=torch.Size([3]),
568
+ device=None,
569
+ is_shared=False,
570
+ stack_dim=0)
571
+ >>> # Create an LLM environment with padded tensor input/output and append a DataLoadingPrimer.
572
+ >>> env = LLMEnv(from_text=False)
573
+ >>> env = env.append_transform(
574
+ >>> DataLoadingPrimer(
575
+ >>> dataloader=DummyTensorDataLoader(padding=True),
576
+ >>> data_specs=[Unbounded(shape=(-1,), dtype=torch.int64)],
577
+ >>> stack_method="as_padded_tensor",
578
+ >>> )
579
+ >>> )
580
+ >>> print(env.rollout(3, auto_reset=False, tensordict=env.reset(TensorDict(batch_size=[3]))))
581
+ LazyStackedTensorDict(
582
+ fields={
583
+ action: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.int64, is_shared=False),
584
+ done: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
585
+ next: LazyStackedTensorDict(
586
+ fields={
587
+ done: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
588
+ observation: Tensor(shape=torch.Size([3, 3, -1]), device=cpu, dtype=torch.int64, is_shared=False),
589
+ terminated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
590
+ truncated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
591
+ exclusive_fields={
592
+ },
593
+ batch_size=torch.Size([3, 3]),
594
+ device=None,
595
+ is_shared=False,
596
+ stack_dim=1),
597
+ observation: Tensor(shape=torch.Size([3, 3, -1]), device=cpu, dtype=torch.int64, is_shared=False),
598
+ terminated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False),
599
+ truncated: Tensor(shape=torch.Size([3, 3, 1]), device=cpu, dtype=torch.bool, is_shared=False)},
600
+ exclusive_fields={
601
+ },
602
+ batch_size=torch.Size([3, 3]),
603
+ device=None,
604
+ is_shared=False,
605
+ stack_dim=1)
606
+
607
+ """
608
+
609
+ _RayServiceClass = RayDataLoadingPrimer
610
+
611
+ def __init__(
612
+ self,
613
+ dataloader: Iterable[dict[str, Any]] | None = None,
614
+ *,
615
+ dataloader_factory: Callable[[], Iterable[dict[str, Any]]] | None = None,
616
+ primers: Composite | None = None,
617
+ stack_method: Callable[[Any], Any]
618
+ | Literal["as_nested_tensor", "as_padded_tensor"]
619
+ | None = None,
620
+ batch_size: int | torch.Size | None = None,
621
+ repeats: int | None = None,
622
+ device: torch.device | None = None,
623
+ group_repeats: bool = False,
624
+ use_ray_service: bool = False,
625
+ ):
626
+ # Validate arguments: exactly one of dataloader or dataloader_factory must be provided
627
+ if dataloader is not None and dataloader_factory is not None:
628
+ raise ValueError(
629
+ "Cannot provide both 'dataloader' and 'dataloader_factory'. Choose one."
630
+ )
631
+ if dataloader is None and dataloader_factory is None:
632
+ raise ValueError(
633
+ "Must provide exactly one of 'dataloader' or 'dataloader_factory'."
634
+ )
635
+
636
+ # Initialize dataloader from factory if provided
637
+ if dataloader_factory is not None:
638
+ self.dataloader = dataloader_factory()
639
+ self.dataloader_factory = dataloader_factory
640
+ else:
641
+ self.dataloader = dataloader
642
+ self.dataloader_factory = None
643
+
644
+ if repeats is None:
645
+ repeats = 0
646
+ self.repeats = repeats
647
+
648
+ # Determine batch-size
649
+ # We must distinguish the batch-size of the DL and the batch size of the transform.
650
+ # We may want more or less elements than the DL and the logic is slightly different so we
651
+ # allow to recompose batches on the fly. If the DL has a batch-size, every element will be
652
+ # unbound and stored in a queue. Otherwise, we get as many elements from the DL to fulfill
653
+ # the required batch-size.
654
+ #
655
+ # If the batch-size is passed, we will stack as many elements as necessary to fulfill this.
656
+ # If not, we try to get it from the dataloader. Contrary to the dataloader, we will always
657
+ # deliver the same batch-size (we create an infinite dataloader and reset when it's done),
658
+ # whereas DLs with drop_last=False may return batches of different sizes.
659
+ #
660
+ # If the batch size passed to the transform is empty (torch.Size(())) or 0, we will consider that
661
+ # the batch-size is determined on-the-fly.
662
+ #
663
+ # A batch-size of 0 in the dataloader means no batch-size.
664
+ #
665
+ # If needed, the various repeats can be grouped in a single batch through group_repeats.
666
+ #
667
+ # If auto_batch_size is on, we call auto_batch_size=True when doing TensorDict.from_dict:
668
+ # That way we get a tensordict of the right batch-size.
669
+ # If the dataloader has no batch-size, we're not sure that we can determine the batch-size
670
+ # automatically so we will consider that each element in the DL has a batch-size of 0 (ie,
671
+ # a single non-batched element is returned at a time).
672
+
673
+ if batch_size is None:
674
+ batch_size = getattr(dataloader, "batch_size", torch.Size([]))
675
+ if batch_size == 0:
676
+ batch_size = torch.Size(())
677
+ if not isinstance(batch_size, (list, tuple)):
678
+ if isinstance(batch_size, int):
679
+ batch_size_tuple = (batch_size,)
680
+ elif isinstance(batch_size, torch.Size):
681
+ batch_size_tuple = tuple(batch_size)
682
+ else:
683
+ batch_size_tuple = (batch_size,)
684
+ else:
685
+ batch_size_tuple = batch_size
686
+ batch_size = torch.Size(batch_size_tuple)
687
+ auto_batch_size = getattr(dataloader, "batch_size", 1) != 0
688
+
689
+ if len(batch_size) > 1:
690
+ raise ValueError(
691
+ f"batch_size can only be 0 or 1D, got batch_size={batch_size}."
692
+ )
693
+
694
+ # We deliver all the repeats in the same batch
695
+ if repeats and group_repeats:
696
+ if batch_size == torch.Size([]):
697
+ batch_size = torch.Size((repeats,))
698
+ else:
699
+ batch_size = torch.Size([batch_size[0] * repeats])
700
+
701
+ self._queue = deque()
702
+ self.auto_batch_size = auto_batch_size
703
+ self.batch_size = batch_size
704
+ self.endless_dataloader = self._endless_iter(self.dataloader)
705
+
706
+ if stack_method is None:
707
+ stack_method = lazy_stack
708
+ elif stack_method == "as_nested_tensor":
709
+ stack_method = as_nested_tensor
710
+ elif stack_method == "as_padded_tensor":
711
+ stack_method = as_padded_tensor
712
+ elif not callable(stack_method):
713
+ raise ValueError(f"Unknown stack_method={stack_method}")
714
+ self.stack_method = stack_method
715
+
716
+ if primers is None:
717
+ # We can get the primer from the dataloader itself
718
+ data = self._load_from_dataloader()
719
+ primers = make_composite_from_td(
720
+ data, dynamic_shape=True, unsqueeze_null_shapes=False
721
+ )
722
+ if batch_size:
723
+ primers = primers.expand(batch_size)
724
+ self._queue.insert(0, data)
725
+ self.data_keys = list(primers.keys(True, True))
726
+ else:
727
+ self.data_keys = list(primers.keys(True, True))
728
+
729
+ super().__init__(
730
+ primers=primers,
731
+ default_value=self._load_from_dataloader,
732
+ reset_key=None,
733
+ expand_specs=None,
734
+ single_default_value=True,
735
+ call_before_env_reset=True,
736
+ device=device,
737
+ )
738
+ self._reset_key = "_reset"
739
+
740
+ def reset_dataloader(self):
741
+ """Reset the dataloader.
742
+
743
+ This is useful when the dataloader is not infinite and we want to reset it.
744
+ If a dataloader_factory was provided, it will be used to create a fresh dataloader.
745
+
746
+ Returns:
747
+ self: The transform itself.
748
+ """
749
+ self._queue.clear()
750
+ if self.dataloader_factory is not None:
751
+ # Create a fresh dataloader from the factory
752
+ self.dataloader = self.dataloader_factory()
753
+ self.endless_dataloader = self._endless_iter(self.dataloader)
754
+ return self
755
+
756
+ @classmethod
757
+ def _endless_iter(self, obj):
758
+ while True:
759
+ yield from obj
760
+
761
+ _device: torch.device | None = None
762
+
763
+ @property
764
+ def device(self) -> torch.device | None:
765
+ if self._device is None:
766
+ primers = getattr(self, "primers", None)
767
+ if primers is not None:
768
+ device = self.primers.device
769
+ else:
770
+ parent = getattr(self, "parent", None)
771
+ if parent is not None:
772
+ device = getattr(parent, "device", None)
773
+ else:
774
+ device = None
775
+ self._device = device
776
+ return self._device
777
+
778
+ @device.setter
779
+ def device(self, device: torch.device | None):
780
+ self._device = device
781
+
782
+ def _load_from_dataloader(
783
+ self, reset: torch.Tensor | None = None
784
+ ) -> TensorDictBase:
785
+ """Loads a single element from the dataloader, or alternatively from the buffer.
786
+
787
+ If `reset` is passed, then one element per reset will be loaded.
788
+ """
789
+ device = self.device
790
+
791
+ if reset is not None:
792
+ if not reset.any():
793
+ raise RuntimeError("reset must have at least one True value.")
794
+ if reset.ndim > 0:
795
+ loaded = [
796
+ self._load_from_dataloader().to(device) for _ in range(reset.sum())
797
+ ]
798
+ return self.stack_method(loaded)
799
+
800
+ if len(self._queue) > 0:
801
+ result = self._queue.popleft()
802
+ if result.device != device:
803
+ result = result.to(device)
804
+ return result
805
+
806
+ data = next(self.endless_dataloader)
807
+ # Some heuristic here:
808
+ # if data is a map, assume its keys match the keys in spec
809
+ # TODO: one could rename the keys too
810
+ if is_tensor_collection(data):
811
+ out = data
812
+ elif isinstance(data, Mapping):
813
+ out = TensorDict.from_dict(
814
+ data,
815
+ auto_batch_size=self.auto_batch_size,
816
+ batch_dims=int(bool(self.auto_batch_size or self.batch_size)),
817
+ device=device,
818
+ )
819
+ else:
820
+ raise TypeError(
821
+ "Data loader must return a mapping that can be automatically cast to a tensordict. Check that you have "
822
+ "the appropriate collate_fn in your dataloader to do so."
823
+ )
824
+ if not out.ndim:
825
+ out = out.unsqueeze(0)
826
+ self._queue.extend(
827
+ [d for d in out.unbind(0) for _ in range(max(1, self.repeats))]
828
+ )
829
+ out = self._queue.popleft()
830
+ return out
831
+
832
+ def set_container(self, container: Transform | EnvBase) -> None:
833
+ result = super().set_container(container)
834
+ # Check batch size
835
+ parent = getattr(self, "parent", None)
836
+ if (
837
+ self.batch_size is not None
838
+ and parent is not None
839
+ and parent.batch_size != self.batch_size
840
+ ):
841
+ warnings.warn(
842
+ f"The parent env has a different batch size than the {type(self).__name__} transform."
843
+ )
844
+ return result
845
+
846
+ def _update_primers_batch_size(self, parent_batch_size):
847
+ """Update the primers to match the parent's batch size.
848
+
849
+ This method is called remotely to ensure the remote actor's primers
850
+ have the correct batch dimensions.
851
+ """
852
+ if hasattr(self.primers, "expand"):
853
+ # Expand primers to match the parent batch size
854
+ if self.primers.shape != parent_batch_size:
855
+ self.primers = self.primers.expand(parent_batch_size)
856
+
857
+ def __repr__(self) -> str:
858
+ class_name = self.__class__.__name__
859
+ return f"{class_name}(primers={self.primers}, dataloader={self.dataloader})"