torchrl 0.11.0__cp314-cp314-macosx_11_0_arm64.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 (395) 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/.dylibs/libc++.1.0.dylib +0 -0
  97. torchrl/__init__.py +144 -0
  98. torchrl/_extension.py +74 -0
  99. torchrl/_torchrl.cpython-314-darwin.so +0 -0
  100. torchrl/_utils.py +1431 -0
  101. torchrl/collectors/__init__.py +48 -0
  102. torchrl/collectors/_base.py +1058 -0
  103. torchrl/collectors/_constants.py +88 -0
  104. torchrl/collectors/_multi_async.py +324 -0
  105. torchrl/collectors/_multi_base.py +1805 -0
  106. torchrl/collectors/_multi_sync.py +464 -0
  107. torchrl/collectors/_runner.py +581 -0
  108. torchrl/collectors/_single.py +2009 -0
  109. torchrl/collectors/_single_async.py +259 -0
  110. torchrl/collectors/collectors.py +62 -0
  111. torchrl/collectors/distributed/__init__.py +32 -0
  112. torchrl/collectors/distributed/default_configs.py +133 -0
  113. torchrl/collectors/distributed/generic.py +1306 -0
  114. torchrl/collectors/distributed/ray.py +1092 -0
  115. torchrl/collectors/distributed/rpc.py +1006 -0
  116. torchrl/collectors/distributed/sync.py +731 -0
  117. torchrl/collectors/distributed/utils.py +160 -0
  118. torchrl/collectors/llm/__init__.py +10 -0
  119. torchrl/collectors/llm/base.py +494 -0
  120. torchrl/collectors/llm/ray_collector.py +275 -0
  121. torchrl/collectors/llm/utils.py +36 -0
  122. torchrl/collectors/llm/weight_update/__init__.py +10 -0
  123. torchrl/collectors/llm/weight_update/vllm.py +348 -0
  124. torchrl/collectors/llm/weight_update/vllm_v2.py +311 -0
  125. torchrl/collectors/utils.py +433 -0
  126. torchrl/collectors/weight_update.py +591 -0
  127. torchrl/csrc/numpy_utils.h +38 -0
  128. torchrl/csrc/pybind.cpp +27 -0
  129. torchrl/csrc/segment_tree.h +458 -0
  130. torchrl/csrc/torch_utils.h +34 -0
  131. torchrl/csrc/utils.cpp +48 -0
  132. torchrl/csrc/utils.h +31 -0
  133. torchrl/data/__init__.py +187 -0
  134. torchrl/data/datasets/__init__.py +58 -0
  135. torchrl/data/datasets/atari_dqn.py +878 -0
  136. torchrl/data/datasets/common.py +281 -0
  137. torchrl/data/datasets/d4rl.py +489 -0
  138. torchrl/data/datasets/d4rl_infos.py +187 -0
  139. torchrl/data/datasets/gen_dgrl.py +375 -0
  140. torchrl/data/datasets/minari_data.py +643 -0
  141. torchrl/data/datasets/openml.py +177 -0
  142. torchrl/data/datasets/openx.py +798 -0
  143. torchrl/data/datasets/roboset.py +363 -0
  144. torchrl/data/datasets/utils.py +11 -0
  145. torchrl/data/datasets/vd4rl.py +432 -0
  146. torchrl/data/llm/__init__.py +34 -0
  147. torchrl/data/llm/dataset.py +491 -0
  148. torchrl/data/llm/history.py +1378 -0
  149. torchrl/data/llm/prompt.py +198 -0
  150. torchrl/data/llm/reward.py +225 -0
  151. torchrl/data/llm/topk.py +186 -0
  152. torchrl/data/llm/utils.py +543 -0
  153. torchrl/data/map/__init__.py +21 -0
  154. torchrl/data/map/hash.py +185 -0
  155. torchrl/data/map/query.py +204 -0
  156. torchrl/data/map/tdstorage.py +363 -0
  157. torchrl/data/map/tree.py +1434 -0
  158. torchrl/data/map/utils.py +103 -0
  159. torchrl/data/postprocs/__init__.py +8 -0
  160. torchrl/data/postprocs/postprocs.py +391 -0
  161. torchrl/data/replay_buffers/__init__.py +99 -0
  162. torchrl/data/replay_buffers/checkpointers.py +622 -0
  163. torchrl/data/replay_buffers/ray_buffer.py +292 -0
  164. torchrl/data/replay_buffers/replay_buffers.py +2376 -0
  165. torchrl/data/replay_buffers/samplers.py +2578 -0
  166. torchrl/data/replay_buffers/scheduler.py +265 -0
  167. torchrl/data/replay_buffers/storages.py +2412 -0
  168. torchrl/data/replay_buffers/utils.py +1042 -0
  169. torchrl/data/replay_buffers/writers.py +781 -0
  170. torchrl/data/tensor_specs.py +7101 -0
  171. torchrl/data/utils.py +334 -0
  172. torchrl/envs/__init__.py +265 -0
  173. torchrl/envs/async_envs.py +1105 -0
  174. torchrl/envs/batched_envs.py +3093 -0
  175. torchrl/envs/common.py +4241 -0
  176. torchrl/envs/custom/__init__.py +11 -0
  177. torchrl/envs/custom/chess.py +617 -0
  178. torchrl/envs/custom/llm.py +214 -0
  179. torchrl/envs/custom/pendulum.py +401 -0
  180. torchrl/envs/custom/san_moves.txt +29274 -0
  181. torchrl/envs/custom/tictactoeenv.py +288 -0
  182. torchrl/envs/env_creator.py +263 -0
  183. torchrl/envs/gym_like.py +752 -0
  184. torchrl/envs/libs/__init__.py +68 -0
  185. torchrl/envs/libs/_gym_utils.py +326 -0
  186. torchrl/envs/libs/brax.py +846 -0
  187. torchrl/envs/libs/dm_control.py +544 -0
  188. torchrl/envs/libs/envpool.py +447 -0
  189. torchrl/envs/libs/gym.py +2239 -0
  190. torchrl/envs/libs/habitat.py +138 -0
  191. torchrl/envs/libs/isaac_lab.py +87 -0
  192. torchrl/envs/libs/isaacgym.py +203 -0
  193. torchrl/envs/libs/jax_utils.py +166 -0
  194. torchrl/envs/libs/jumanji.py +963 -0
  195. torchrl/envs/libs/meltingpot.py +599 -0
  196. torchrl/envs/libs/openml.py +153 -0
  197. torchrl/envs/libs/openspiel.py +652 -0
  198. torchrl/envs/libs/pettingzoo.py +1042 -0
  199. torchrl/envs/libs/procgen.py +351 -0
  200. torchrl/envs/libs/robohive.py +429 -0
  201. torchrl/envs/libs/smacv2.py +645 -0
  202. torchrl/envs/libs/unity_mlagents.py +891 -0
  203. torchrl/envs/libs/utils.py +147 -0
  204. torchrl/envs/libs/vmas.py +813 -0
  205. torchrl/envs/llm/__init__.py +63 -0
  206. torchrl/envs/llm/chat.py +730 -0
  207. torchrl/envs/llm/datasets/README.md +4 -0
  208. torchrl/envs/llm/datasets/__init__.py +17 -0
  209. torchrl/envs/llm/datasets/gsm8k.py +353 -0
  210. torchrl/envs/llm/datasets/ifeval.py +274 -0
  211. torchrl/envs/llm/envs.py +789 -0
  212. torchrl/envs/llm/libs/README.md +3 -0
  213. torchrl/envs/llm/libs/__init__.py +8 -0
  214. torchrl/envs/llm/libs/mlgym.py +869 -0
  215. torchrl/envs/llm/reward/__init__.py +10 -0
  216. torchrl/envs/llm/reward/gsm8k.py +324 -0
  217. torchrl/envs/llm/reward/ifeval/README.md +13 -0
  218. torchrl/envs/llm/reward/ifeval/__init__.py +10 -0
  219. torchrl/envs/llm/reward/ifeval/_instructions.py +1667 -0
  220. torchrl/envs/llm/reward/ifeval/_instructions_main.py +131 -0
  221. torchrl/envs/llm/reward/ifeval/_instructions_registry.py +100 -0
  222. torchrl/envs/llm/reward/ifeval/_instructions_util.py +1677 -0
  223. torchrl/envs/llm/reward/ifeval/_scorer.py +454 -0
  224. torchrl/envs/llm/transforms/__init__.py +55 -0
  225. torchrl/envs/llm/transforms/browser.py +292 -0
  226. torchrl/envs/llm/transforms/dataloading.py +859 -0
  227. torchrl/envs/llm/transforms/format.py +73 -0
  228. torchrl/envs/llm/transforms/kl.py +1544 -0
  229. torchrl/envs/llm/transforms/policy_version.py +189 -0
  230. torchrl/envs/llm/transforms/reason.py +323 -0
  231. torchrl/envs/llm/transforms/tokenizer.py +321 -0
  232. torchrl/envs/llm/transforms/tools.py +1955 -0
  233. torchrl/envs/model_based/__init__.py +9 -0
  234. torchrl/envs/model_based/common.py +180 -0
  235. torchrl/envs/model_based/dreamer.py +112 -0
  236. torchrl/envs/transforms/__init__.py +147 -0
  237. torchrl/envs/transforms/functional.py +48 -0
  238. torchrl/envs/transforms/gym_transforms.py +203 -0
  239. torchrl/envs/transforms/module.py +341 -0
  240. torchrl/envs/transforms/r3m.py +372 -0
  241. torchrl/envs/transforms/ray_service.py +663 -0
  242. torchrl/envs/transforms/rb_transforms.py +214 -0
  243. torchrl/envs/transforms/transforms.py +11835 -0
  244. torchrl/envs/transforms/utils.py +94 -0
  245. torchrl/envs/transforms/vc1.py +307 -0
  246. torchrl/envs/transforms/vecnorm.py +845 -0
  247. torchrl/envs/transforms/vip.py +407 -0
  248. torchrl/envs/utils.py +1718 -0
  249. torchrl/envs/vec_envs.py +11 -0
  250. torchrl/modules/__init__.py +206 -0
  251. torchrl/modules/distributions/__init__.py +73 -0
  252. torchrl/modules/distributions/continuous.py +830 -0
  253. torchrl/modules/distributions/discrete.py +908 -0
  254. torchrl/modules/distributions/truncated_normal.py +187 -0
  255. torchrl/modules/distributions/utils.py +233 -0
  256. torchrl/modules/llm/__init__.py +62 -0
  257. torchrl/modules/llm/backends/__init__.py +65 -0
  258. torchrl/modules/llm/backends/vllm/__init__.py +94 -0
  259. torchrl/modules/llm/backends/vllm/_models.py +46 -0
  260. torchrl/modules/llm/backends/vllm/base.py +72 -0
  261. torchrl/modules/llm/backends/vllm/vllm_async.py +2075 -0
  262. torchrl/modules/llm/backends/vllm/vllm_plugin.py +22 -0
  263. torchrl/modules/llm/backends/vllm/vllm_sync.py +446 -0
  264. torchrl/modules/llm/backends/vllm/vllm_utils.py +129 -0
  265. torchrl/modules/llm/policies/__init__.py +28 -0
  266. torchrl/modules/llm/policies/common.py +1809 -0
  267. torchrl/modules/llm/policies/transformers_wrapper.py +2756 -0
  268. torchrl/modules/llm/policies/vllm_wrapper.py +2241 -0
  269. torchrl/modules/llm/utils.py +23 -0
  270. torchrl/modules/mcts/__init__.py +21 -0
  271. torchrl/modules/mcts/scores.py +579 -0
  272. torchrl/modules/models/__init__.py +86 -0
  273. torchrl/modules/models/batchrenorm.py +119 -0
  274. torchrl/modules/models/decision_transformer.py +179 -0
  275. torchrl/modules/models/exploration.py +731 -0
  276. torchrl/modules/models/llm.py +156 -0
  277. torchrl/modules/models/model_based.py +596 -0
  278. torchrl/modules/models/models.py +1712 -0
  279. torchrl/modules/models/multiagent.py +1067 -0
  280. torchrl/modules/models/recipes/impala.py +185 -0
  281. torchrl/modules/models/utils.py +162 -0
  282. torchrl/modules/planners/__init__.py +10 -0
  283. torchrl/modules/planners/cem.py +228 -0
  284. torchrl/modules/planners/common.py +73 -0
  285. torchrl/modules/planners/mppi.py +265 -0
  286. torchrl/modules/tensordict_module/__init__.py +89 -0
  287. torchrl/modules/tensordict_module/actors.py +2457 -0
  288. torchrl/modules/tensordict_module/common.py +529 -0
  289. torchrl/modules/tensordict_module/exploration.py +814 -0
  290. torchrl/modules/tensordict_module/probabilistic.py +321 -0
  291. torchrl/modules/tensordict_module/rnn.py +1639 -0
  292. torchrl/modules/tensordict_module/sequence.py +132 -0
  293. torchrl/modules/tensordict_module/world_models.py +34 -0
  294. torchrl/modules/utils/__init__.py +38 -0
  295. torchrl/modules/utils/mappings.py +9 -0
  296. torchrl/modules/utils/utils.py +89 -0
  297. torchrl/objectives/__init__.py +78 -0
  298. torchrl/objectives/a2c.py +659 -0
  299. torchrl/objectives/common.py +753 -0
  300. torchrl/objectives/cql.py +1346 -0
  301. torchrl/objectives/crossq.py +710 -0
  302. torchrl/objectives/ddpg.py +453 -0
  303. torchrl/objectives/decision_transformer.py +371 -0
  304. torchrl/objectives/deprecated.py +516 -0
  305. torchrl/objectives/dqn.py +683 -0
  306. torchrl/objectives/dreamer.py +488 -0
  307. torchrl/objectives/functional.py +48 -0
  308. torchrl/objectives/gail.py +258 -0
  309. torchrl/objectives/iql.py +996 -0
  310. torchrl/objectives/llm/__init__.py +30 -0
  311. torchrl/objectives/llm/grpo.py +846 -0
  312. torchrl/objectives/llm/sft.py +482 -0
  313. torchrl/objectives/multiagent/__init__.py +8 -0
  314. torchrl/objectives/multiagent/qmixer.py +396 -0
  315. torchrl/objectives/ppo.py +1669 -0
  316. torchrl/objectives/redq.py +683 -0
  317. torchrl/objectives/reinforce.py +530 -0
  318. torchrl/objectives/sac.py +1580 -0
  319. torchrl/objectives/td3.py +570 -0
  320. torchrl/objectives/td3_bc.py +625 -0
  321. torchrl/objectives/utils.py +782 -0
  322. torchrl/objectives/value/__init__.py +28 -0
  323. torchrl/objectives/value/advantages.py +1956 -0
  324. torchrl/objectives/value/functional.py +1459 -0
  325. torchrl/objectives/value/utils.py +360 -0
  326. torchrl/record/__init__.py +17 -0
  327. torchrl/record/loggers/__init__.py +23 -0
  328. torchrl/record/loggers/common.py +48 -0
  329. torchrl/record/loggers/csv.py +226 -0
  330. torchrl/record/loggers/mlflow.py +142 -0
  331. torchrl/record/loggers/tensorboard.py +139 -0
  332. torchrl/record/loggers/trackio.py +163 -0
  333. torchrl/record/loggers/utils.py +78 -0
  334. torchrl/record/loggers/wandb.py +214 -0
  335. torchrl/record/recorder.py +554 -0
  336. torchrl/services/__init__.py +79 -0
  337. torchrl/services/base.py +109 -0
  338. torchrl/services/ray_service.py +453 -0
  339. torchrl/testing/__init__.py +107 -0
  340. torchrl/testing/assertions.py +179 -0
  341. torchrl/testing/dist_utils.py +122 -0
  342. torchrl/testing/env_creators.py +227 -0
  343. torchrl/testing/env_helper.py +35 -0
  344. torchrl/testing/gym_helpers.py +156 -0
  345. torchrl/testing/llm_mocks.py +119 -0
  346. torchrl/testing/mocking_classes.py +2720 -0
  347. torchrl/testing/modules.py +295 -0
  348. torchrl/testing/mp_helpers.py +15 -0
  349. torchrl/testing/ray_helpers.py +293 -0
  350. torchrl/testing/utils.py +190 -0
  351. torchrl/trainers/__init__.py +42 -0
  352. torchrl/trainers/algorithms/__init__.py +11 -0
  353. torchrl/trainers/algorithms/configs/__init__.py +705 -0
  354. torchrl/trainers/algorithms/configs/collectors.py +216 -0
  355. torchrl/trainers/algorithms/configs/common.py +41 -0
  356. torchrl/trainers/algorithms/configs/data.py +308 -0
  357. torchrl/trainers/algorithms/configs/envs.py +104 -0
  358. torchrl/trainers/algorithms/configs/envs_libs.py +361 -0
  359. torchrl/trainers/algorithms/configs/logging.py +80 -0
  360. torchrl/trainers/algorithms/configs/modules.py +570 -0
  361. torchrl/trainers/algorithms/configs/objectives.py +177 -0
  362. torchrl/trainers/algorithms/configs/trainers.py +340 -0
  363. torchrl/trainers/algorithms/configs/transforms.py +955 -0
  364. torchrl/trainers/algorithms/configs/utils.py +252 -0
  365. torchrl/trainers/algorithms/configs/weight_sync_schemes.py +191 -0
  366. torchrl/trainers/algorithms/configs/weight_update.py +159 -0
  367. torchrl/trainers/algorithms/ppo.py +373 -0
  368. torchrl/trainers/algorithms/sac.py +308 -0
  369. torchrl/trainers/helpers/__init__.py +40 -0
  370. torchrl/trainers/helpers/collectors.py +416 -0
  371. torchrl/trainers/helpers/envs.py +573 -0
  372. torchrl/trainers/helpers/logger.py +33 -0
  373. torchrl/trainers/helpers/losses.py +132 -0
  374. torchrl/trainers/helpers/models.py +658 -0
  375. torchrl/trainers/helpers/replay_buffer.py +59 -0
  376. torchrl/trainers/helpers/trainers.py +301 -0
  377. torchrl/trainers/trainers.py +2052 -0
  378. torchrl/weight_update/__init__.py +33 -0
  379. torchrl/weight_update/_distributed.py +749 -0
  380. torchrl/weight_update/_mp.py +624 -0
  381. torchrl/weight_update/_noupdate.py +102 -0
  382. torchrl/weight_update/_ray.py +1032 -0
  383. torchrl/weight_update/_rpc.py +284 -0
  384. torchrl/weight_update/_shared.py +891 -0
  385. torchrl/weight_update/llm/__init__.py +32 -0
  386. torchrl/weight_update/llm/vllm_double_buffer.py +370 -0
  387. torchrl/weight_update/llm/vllm_nccl.py +710 -0
  388. torchrl/weight_update/utils.py +73 -0
  389. torchrl/weight_update/weight_sync_schemes.py +1244 -0
  390. torchrl-0.11.0.dist-info/METADATA +1308 -0
  391. torchrl-0.11.0.dist-info/RECORD +395 -0
  392. torchrl-0.11.0.dist-info/WHEEL +5 -0
  393. torchrl-0.11.0.dist-info/entry_points.txt +2 -0
  394. torchrl-0.11.0.dist-info/licenses/LICENSE +21 -0
  395. torchrl-0.11.0.dist-info/top_level.txt +7 -0
@@ -0,0 +1,1667 @@
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
+ # Original LICENSE:
7
+ # Copyright 2024 The Google Research Authors.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """Library of instructions.
21
+
22
+ Modification from original script:
23
+
24
+ - typos;
25
+ - docstrings formatting;
26
+ - type annotations;
27
+ - removing assertions;
28
+ - torchrl_logger instead of logging
29
+
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import collections
35
+ import json
36
+ import random
37
+ import re
38
+ import string
39
+ from collections.abc import Sequence
40
+ from typing import Any, Literal, Optional, Union
41
+
42
+ from torchrl._utils import logger as torchrl_logger
43
+
44
+ from ._instructions_util import (
45
+ count_sentences,
46
+ count_words,
47
+ generate_keywords,
48
+ LANGUAGE_CODES,
49
+ nltk,
50
+ split_into_sentences,
51
+ )
52
+
53
+
54
+ _InstructionArgsDtype = Optional[dict[str, Union[int, str, Sequence[str]]]]
55
+
56
+ _LANGUAGES = LANGUAGE_CODES
57
+
58
+ # The relational operation for comparison.
59
+ _COMPARISON_RELATION = ("less than", "at least")
60
+
61
+ # The maximum number of sentences.
62
+ _MAX_NUM_SENTENCES = 20
63
+
64
+ # The number of placeholders.
65
+ _NUM_PLACEHOLDERS = 4
66
+
67
+ # The number of bullet lists.
68
+ _NUM_BULLETS = 5
69
+
70
+ # The options of constrained response.
71
+ _CONSTRAINED_RESPONSE_OPTIONS = (
72
+ "My answer is yes.",
73
+ "My answer is no.",
74
+ "My answer is maybe.",
75
+ )
76
+
77
+ # The options of starter keywords.
78
+ _STARTER_OPTIONS = (
79
+ "I would say",
80
+ "My answer is",
81
+ "I believe",
82
+ "In my opinion",
83
+ "I think",
84
+ "I reckon",
85
+ "I feel",
86
+ "From my perspective",
87
+ "As I see it",
88
+ "According to me",
89
+ "As far as I'm concerned",
90
+ "To my understanding",
91
+ "In my view",
92
+ "My take on it is",
93
+ "As per my perception",
94
+ )
95
+
96
+ # The options of ending keywords.
97
+ # TODO(jeffreyzhou) add more ending options
98
+ _ENDING_OPTIONS = ("Any other questions?", "Is there anything else I can help with?")
99
+
100
+ # The number of highlighted sections.
101
+ _NUM_HIGHLIGHTED_SECTIONS = 4
102
+
103
+ # The section spliter.
104
+ _SECTION_SPLITER = ("Section", "SECTION")
105
+
106
+ # The number of sections.
107
+ _NUM_SECTIONS = 5
108
+
109
+ # The number of paragraphs.
110
+ _NUM_PARAGRAPHS = 5
111
+
112
+ # The postscript marker.
113
+ _POSTSCRIPT_MARKER = ("P.S.", "P.P.S")
114
+
115
+ # The number of keywords.
116
+ _NUM_KEYWORDS = 2
117
+
118
+ # The occurrences of a single keyword.
119
+ _KEYWORD_FREQUENCY = 3
120
+
121
+ # The occurrences of a single letter.
122
+ _LETTER_FREQUENCY = 10
123
+
124
+ # The occurrences of words with all capital letters.
125
+ _ALL_CAPITAL_WORD_FREQUENCY = 20
126
+
127
+ # The number of words in the response.
128
+ _NUM_WORDS_LOWER_LIMIT = 100
129
+ _NUM_WORDS_UPPER_LIMIT = 500
130
+
131
+
132
+ class Instruction:
133
+ """An instruction template."""
134
+
135
+ def __init__(self, instruction_id):
136
+ self.id = instruction_id
137
+
138
+ def build_description(self, **kwargs):
139
+ raise NotImplementedError("`build_description` not implemented.")
140
+
141
+ def get_instruction_args(self) -> dict[str, Any] | None:
142
+ raise NotImplementedError("`get_instruction_args` not implemented.")
143
+
144
+ def get_instruction_args_keys(self) -> list[str]:
145
+ raise NotImplementedError("`get_instruction_args_keys` not implemented.")
146
+
147
+ def check_following(self, value: str) -> bool:
148
+ raise NotImplementedError("`check_following` not implemented.")
149
+
150
+
151
+ class ResponseLanguageChecker(Instruction):
152
+ """Check the language of the entire response."""
153
+
154
+ def build_description(self, *, language: str | None = None):
155
+ """Build the instruction description.
156
+
157
+ Args:
158
+ language (str): A string representing the expected language of the response. The
159
+ language has to comply to the 97 types defined in
160
+ `langid.py` (https://pypi.org/project/langid/1.1.5/), which follows
161
+ ISO 639-1 codes (https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes);
162
+ for example, `en` for English, `zh` for Chinese, `fr` for French.
163
+ If `None`, the language will be sampled from the list of languages.
164
+
165
+ Returns:
166
+ A string representing the instruction description.
167
+ """
168
+ self._language = language
169
+ if self._language is None:
170
+ self._language = random.choice(list(_LANGUAGES.keys()))
171
+ # TODO(tianjianlu): opens the description generation to more choices.
172
+ self._description_pattern = (
173
+ "Your ENTIRE response should be in {language} language, no other "
174
+ + "language is allowed."
175
+ )
176
+ return self._description_pattern.format(language=_LANGUAGES[self._language])
177
+
178
+ def get_instruction_args(self) -> dict[str, Any] | None:
179
+ """Returns the keyword args of `build_description`."""
180
+ return {"language": self._language}
181
+
182
+ def get_instruction_args_keys(self) -> list[str]:
183
+ """Returns the args keys of `build_description`."""
184
+ return ["language"]
185
+
186
+ def check_following(self, value: str) -> bool:
187
+ """Check if the language of the entire response follows the instruction.
188
+
189
+ Args:
190
+ value (str): A string representing the response.
191
+
192
+ Returns:
193
+ `True` if the language of `value` follows instruction; otherwise False.
194
+ """
195
+ import langdetect
196
+
197
+ try:
198
+ return langdetect.detect(value) == self._language
199
+ except (langdetect.LangDetectException, ImportError) as e:
200
+ # Count as instruction is followed.
201
+ torchrl_logger.error(
202
+ "Unable to detect language for text %s due to %s", value, e
203
+ ) # refex: disable=pytotw.037
204
+ return True
205
+
206
+
207
+ class NumberOfSentences(Instruction):
208
+ """Check the number of sentences."""
209
+
210
+ def build_description(
211
+ self, *, num_sentences: int | None = None, relation: str | None = None
212
+ ):
213
+ """Build the instruction description.
214
+
215
+ Args:
216
+ num_sentences (int, optional): An integer specifying the number of sentences as a
217
+ threshold. If `None`, the number of sentences will be randomly generated with a maximum
218
+ value determined by `_MAX_NUM_SENTENCES` (`20` by default).
219
+ relation (str, optional): A string in (`less than`, `at least`), defining the relational
220
+ operator for comparison.
221
+ Two relational comparisons are supported for now:
222
+ if 'less than', the actual number of sentences < the threshold;
223
+ if 'at least', the actual number of sentences >= the threshold.
224
+ If `None`, the relation is sampled randomly.
225
+
226
+ Returns:
227
+ A string representing the instruction description.
228
+
229
+ """
230
+ # The number of sentences as a threshold for comparison.
231
+ self._num_sentences_threshold = num_sentences
232
+ if self._num_sentences_threshold is None or self._num_sentences_threshold < 0:
233
+ self._num_sentences_threshold = random.randint(1, _MAX_NUM_SENTENCES)
234
+
235
+ if relation is None:
236
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
237
+ elif relation not in _COMPARISON_RELATION:
238
+ raise ValueError(
239
+ "The supported relation for comparison must be in "
240
+ f"{_COMPARISON_RELATION}, but {relation} is given."
241
+ )
242
+ else:
243
+ self._comparison_relation = relation
244
+
245
+ self._description_pattern = (
246
+ "Your response should contain {relation} {num_sentences} sentences."
247
+ )
248
+ return self._description_pattern.format(
249
+ relation=self._comparison_relation,
250
+ num_sentences=self._num_sentences_threshold,
251
+ )
252
+
253
+ def get_instruction_args(self) -> dict[str, Any] | None:
254
+ """Returns the keyword args of `build_description`."""
255
+ return {
256
+ "num_sentences": self._num_sentences_threshold,
257
+ "relation": self._comparison_relation,
258
+ }
259
+
260
+ def get_instruction_args_keys(self) -> list[str]:
261
+ """Returns the args keys of `build_description`."""
262
+ return ["num_sentences", "relation"]
263
+
264
+ def check_following(self, value: str) -> bool:
265
+ """Check if the number of sentences follows the instruction.
266
+
267
+ Args:
268
+ value (str): A string representing the response.
269
+
270
+ Returns:
271
+ `True` if the response follows the instruction.
272
+
273
+ Raise:
274
+ ValueError if the string in `instruction_args` is not in
275
+ `["less_than", "at_least"]`.
276
+ """
277
+ num_sentences = count_sentences(value)
278
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
279
+ return num_sentences < self._num_sentences_threshold
280
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
281
+ return (
282
+ num_sentences >= self._num_sentences_threshold
283
+ ) # pytype: disable=bad-return-type
284
+
285
+
286
+ class PlaceholderChecker(Instruction):
287
+ """Check the placeholders in template writing."""
288
+
289
+ def build_description(self, *, num_placeholders: int | None = None):
290
+ """Build the instruction description.
291
+
292
+ Args:
293
+ num_placeholders (int): An integer denoting the minimum number of
294
+ placeholders required in the response. If `None`, the number of
295
+ placeholders will be randomly generated with a maximum value determined
296
+ by `_NUM_PLACEHOLDERS` (`4` by default).
297
+
298
+ Returns:
299
+ A string representing the instruction description.
300
+ """
301
+ self._num_placeholders = num_placeholders
302
+ if self._num_placeholders is None or self._num_placeholders < 0:
303
+ self._num_placeholders = random.randint(1, _NUM_PLACEHOLDERS)
304
+ self._description_pattern = (
305
+ "The response must contain at least {num_placeholders} placeholders "
306
+ + "represented by square brackets, such as [address]."
307
+ )
308
+ return self._description_pattern.format(num_placeholders=self._num_placeholders)
309
+
310
+ def get_instruction_args(self) -> dict[str, Any] | None:
311
+ """Returns the keyword args of `build_description`."""
312
+ return {"num_placeholders": self._num_placeholders}
313
+
314
+ def get_instruction_args_keys(self) -> list[str]:
315
+ """Returns the args keys of `build_description`."""
316
+ return ["num_placeholders"]
317
+
318
+ def check_following(self, value: str) -> bool:
319
+ """Check if the number of placeholders follows the instruction.
320
+
321
+ Args:
322
+ value (str): A string representing the response.
323
+
324
+ Returns:
325
+ `True` if the actual number of placeholders in the response is greater than
326
+ or equal to `num_placeholders`; otherwise, `False`.
327
+ """
328
+ placeholders = re.findall(r"\[.*?\]", value)
329
+ num_placeholders = len(placeholders)
330
+ return num_placeholders >= self._num_placeholders
331
+
332
+
333
+ class BulletListChecker(Instruction):
334
+ """Checks the bullet list in the prompt."""
335
+
336
+ def build_description(self, *, num_bullets: int | None = None):
337
+ """Build the instruction description.
338
+
339
+ Args:
340
+ num_bullets: An integer specifying the exact number of bullet lists
341
+ that is required to appear in the response. Default is `None`.
342
+ If `None`, the number of bullet lists will be randomly generated with
343
+ a maximum value determined by `_NUM_BULLETS` (`5` by default).
344
+
345
+ Returns:
346
+ A string representing the instruction description.
347
+ """
348
+ self._num_bullets = num_bullets
349
+ if self._num_bullets is None or self._num_bullets < 0:
350
+ self._num_bullets = random.randint(1, _NUM_BULLETS)
351
+ self._description_pattern = (
352
+ "Your answer must contain exactly {num_bullets} bullet points. "
353
+ + "Use the markdown bullet points such as:\n"
354
+ + "* This is point 1. \n"
355
+ + "* This is point 2"
356
+ )
357
+ return self._description_pattern.format(num_bullets=self._num_bullets)
358
+
359
+ def get_instruction_args(self) -> dict[str, Any] | None:
360
+ """Returns the keyword args of `build_description`."""
361
+ return {"num_bullets": self._num_bullets}
362
+
363
+ def get_instruction_args_keys(self) -> list[str]:
364
+ """Returns the args keys of `build_description`."""
365
+ return ["num_bullets"]
366
+
367
+ def check_following(self, value: str) -> bool:
368
+ r"""Check if the number of bullet lists meets the requirement.
369
+
370
+ Args:
371
+ value (str): A string representing the response. The response is expected to
372
+ contain some bullet lists that start with `\*`.
373
+
374
+ Returns:
375
+ True if the actual number of bullet lists in the response meets the
376
+ requirement.
377
+ """
378
+ bullet_lists = re.findall(r"^\s*\*[^\*].*$", value, flags=re.MULTILINE)
379
+ bullet_lists_2 = re.findall(r"^\s*-.*$", value, flags=re.MULTILINE)
380
+ num_bullet_lists = len(bullet_lists) + len(bullet_lists_2)
381
+ return num_bullet_lists == self._num_bullets
382
+
383
+
384
+ class ConstrainedResponseChecker(Instruction):
385
+ """Checks the constrained response."""
386
+
387
+ def build_description(self) -> str:
388
+ """Build the instruction description."""
389
+ # A sequence of string(s) representing the options of the expected response.
390
+ self._constrained_responses = _CONSTRAINED_RESPONSE_OPTIONS
391
+ self._description_pattern = (
392
+ "Answer with one of the following options: {response_options}"
393
+ )
394
+ return self._description_pattern.format(
395
+ response_options=self._constrained_responses
396
+ )
397
+
398
+ def get_instruction_args(self) -> dict[str, Any] | None:
399
+ """Returns the keyword args of `build_description`."""
400
+ return None
401
+
402
+ def get_instruction_args_keys(self) -> list[str]:
403
+ """Returns the args keys of `build_description`."""
404
+ return []
405
+
406
+ def check_following(self, value: str) -> bool:
407
+ """Checks if the response matches the constrained options.
408
+
409
+ Args:
410
+ value (str): A string representing the response.
411
+
412
+ Returns:
413
+ True if the actual response contains one of the options in the constrained
414
+ responses; otherwise False.
415
+ """
416
+ value = value.strip()
417
+ for constrained_response in self._constrained_responses:
418
+ if constrained_response in value:
419
+ return True
420
+ return False
421
+
422
+
423
+ class ConstrainedStartChecker(Instruction):
424
+ """Checks the response start."""
425
+
426
+ def build_description(self, *, starter=None):
427
+ """Build the instruction description.
428
+
429
+ Args:
430
+ starter: A string representing the keyword that the response should start
431
+ with.
432
+
433
+ Returns:
434
+ A string representing the instruction description.
435
+ """
436
+ self._starter = starter.strip() if isinstance(starter, str) else starter
437
+ if self._starter is None:
438
+ self._starter = random.choice(_STARTER_OPTIONS)
439
+ self._description_pattern = (
440
+ "During the conversation, when it is your turn, "
441
+ + "please always start with {starter}"
442
+ )
443
+ return self._description_pattern.format(starter=self._starter)
444
+
445
+ def get_instruction_args(self) -> dict[str, str]:
446
+ """Returns the keyword args of `build_description`."""
447
+ return {"starter": self._starter}
448
+
449
+ def get_instruction_args_keys(self) -> list[str]:
450
+ """Returns the args keys of `build_description`."""
451
+ return ["starter"]
452
+
453
+ def check_following(self, value: str) -> bool:
454
+ """Checks if the response starts with the constrained keyword or phrase.
455
+
456
+ Args:
457
+ value (str): A string representing the response.
458
+
459
+ Returns:
460
+ `True` if the response starts with the given phrase or keyword that is
461
+ contained in `instruction_args`; otherwise, `False`.
462
+ """
463
+ response_pattern = r"^\s*" + self._starter + r".*$"
464
+ response_with_constrained_start = re.search(
465
+ response_pattern, value, flags=re.MULTILINE
466
+ )
467
+ return bool(response_with_constrained_start)
468
+
469
+
470
+ class HighlightSectionChecker(Instruction):
471
+ """Checks the highlighted section."""
472
+
473
+ def build_description(self, *, num_highlights: int | None = None) -> str:
474
+ """Build the instruction description.
475
+
476
+ Args:
477
+ num_highlights (int, optional): An integer specifying the minimum number of highlighted
478
+ sections. If `None`, the number of highlighted sections will be generated with a
479
+ maximum of `_NUM_HIGHLIGHTED_SECTIONS` (defaults to `4`).
480
+
481
+ Returns:
482
+ A string representing the instruction description.
483
+ """
484
+ self._num_highlights = num_highlights
485
+ if self._num_highlights is None or self._num_highlights < 0:
486
+ self._num_highlights = random.randint(1, _NUM_HIGHLIGHTED_SECTIONS)
487
+
488
+ self._description_pattern = (
489
+ "Highlight at least {num_highlights} sections in your answer with "
490
+ + "markdown, i.e. *highlighted section*."
491
+ )
492
+
493
+ return self._description_pattern.format(num_highlights=self._num_highlights)
494
+
495
+ def get_instruction_args(self) -> dict[str, int]:
496
+ """Returns the keyword args of `build_description`."""
497
+ return {"num_highlights": self._num_highlights}
498
+
499
+ def get_instruction_args_keys(self) -> list[str]:
500
+ """Returns the args keys of `build_description`."""
501
+ return ["num_highlights"]
502
+
503
+ def check_following(self, value: str) -> bool:
504
+ """Checks if the number of highlighted sections meets the requirement.
505
+
506
+ Args:
507
+ value (str): A string representing the response. The response is expected to
508
+ contain highlighted sections in the format of *highlighted*.
509
+
510
+ Returns:
511
+ True if the actual number of highlighted sections in the format of
512
+ *highlighed sections* meets the minimum requirement; otherwise False.
513
+ """
514
+ num_highlights = 0
515
+ highlights = re.findall(r"\*[^\n\*]*\*", value)
516
+ double_highlights = re.findall(r"\*\*[^\n\*]*\*\*", value)
517
+ for highlight in highlights:
518
+ if highlight.strip("*").strip():
519
+ num_highlights += 1
520
+ for highlight in double_highlights:
521
+ if highlight.removeprefix("**").removesuffix("**").strip():
522
+ num_highlights += 1
523
+
524
+ return num_highlights >= self._num_highlights
525
+
526
+
527
+ class SectionChecker(Instruction):
528
+ """Checks the sections."""
529
+
530
+ def build_description(self, *, section_spliter=None, num_sections=None):
531
+ """Build the instruction description.
532
+
533
+ Args:
534
+ section_spliter: A string represents the section spliter keyword that
535
+ marks a new section, i.e., `Section` or `SECTION`.
536
+ num_sections: An integer specifying the number of sections.
537
+
538
+ Returns:
539
+ A string representing the instruction description.
540
+ """
541
+ self._section_spliter = (
542
+ section_spliter.strip()
543
+ if isinstance(section_spliter, str)
544
+ else section_spliter
545
+ )
546
+ if self._section_spliter is None:
547
+ self._section_spliter = random.choice(_SECTION_SPLITER)
548
+
549
+ self._num_sections = num_sections
550
+ if self._num_sections is None or self._num_sections < 0:
551
+ self._num_sections = random.randint(1, _NUM_SECTIONS)
552
+
553
+ self._description_pattern = (
554
+ "Your response must have {num_sections} sections. Mark the beginning "
555
+ + "of each section with {section_spliter} X, such as:\n"
556
+ + "{section_spliter} 1\n"
557
+ + "[content of section 1]\n"
558
+ + "{section_spliter} 2\n"
559
+ + "[content of section 2]"
560
+ )
561
+
562
+ return self._description_pattern.format(
563
+ num_sections=self._num_sections, section_spliter=self._section_spliter
564
+ )
565
+
566
+ def get_instruction_args(self) -> dict[str, Any]:
567
+ """Returns the keyword args of `build_description`."""
568
+ return {
569
+ "section_spliter": self._section_spliter,
570
+ "num_sections": self._num_sections,
571
+ }
572
+
573
+ def get_instruction_args_keys(self) -> list[str]:
574
+ """Returns the args keys of `build_description`."""
575
+ return ["section_spliter", "num_sections"]
576
+
577
+ def check_following(self, value: str) -> bool:
578
+ """Checks the response contains multiple sections.
579
+
580
+ Args:
581
+ value (str): A string representing the response. The response is expected
582
+ to contain multiple sections (number of sections is greater than 1).
583
+ A new section starts with `Section 1`, where the number denotes the
584
+ section index.
585
+
586
+ Returns:
587
+ `True` if the number of sections in the response is greater than or equal to
588
+ the minimum number of sections; otherwise, `False`.
589
+ """
590
+ section_splitter_patten = r"\s?" + self._section_spliter + r"\s?\d+\s?"
591
+ sections = re.split(section_splitter_patten, value)
592
+ num_sections = len(sections) - 1
593
+ return num_sections >= self._num_sections
594
+
595
+
596
+ class ParagraphChecker(Instruction):
597
+ """Checks the paragraphs."""
598
+
599
+ def build_description(self, *, num_paragraphs: int | None = None) -> str:
600
+ """Build the instruction description.
601
+
602
+ Args:
603
+ num_paragraphs (int): An integer specifying the number of paragraphs.
604
+ If `None`, the number of paragraphs is automatically generated with a maximum
605
+ value of `_NUM_PARAGRAPHS` (defaults to `5`).
606
+
607
+ Returns:
608
+ A string representing the instruction description.
609
+ """
610
+ self._num_paragraphs = num_paragraphs
611
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
612
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
613
+
614
+ self._description_pattern = (
615
+ "There should be {num_paragraphs} paragraphs. "
616
+ + "Paragraphs are separated with the markdown divider: ***"
617
+ )
618
+
619
+ return self._description_pattern.format(num_paragraphs=self._num_paragraphs)
620
+
621
+ def get_instruction_args(self) -> dict[str, Any]:
622
+ """Returns the keyword args of `build_description`."""
623
+ return {"num_paragraphs": self._num_paragraphs}
624
+
625
+ def get_instruction_args_keys(self) -> list[str]:
626
+ """Returns the args keys of `build_description`."""
627
+ return ["num_paragraphs"]
628
+
629
+ def check_following(self, value: str) -> bool:
630
+ """Checks the response contains required number of paragraphs.
631
+
632
+ Args:
633
+ value (str): A string representing the response. The response may contain
634
+ paragraphs that are separated by the markdown divider: `***`.
635
+
636
+ Returns:
637
+ `True` if the actual number of paragraphs is the same as required;
638
+ otherwise, `False`.
639
+ """
640
+ paragraphs = re.split(r"\s?\*\*\*\s?", value)
641
+ num_paragraphs = len(paragraphs)
642
+
643
+ for index, paragraph in enumerate(paragraphs):
644
+ if not paragraph.strip():
645
+ if index == 0 or index == len(paragraphs) - 1:
646
+ num_paragraphs -= 1
647
+ else:
648
+ return False
649
+
650
+ return num_paragraphs == self._num_paragraphs
651
+
652
+
653
+ class PostscriptChecker(Instruction):
654
+ """Checks the postscript."""
655
+
656
+ def build_description(self, *, postscript_marker: str | None = None):
657
+ """Build the instruction description.
658
+
659
+ Args:
660
+ postscript_marker (str, optional): A string containing the keyword that marks the start
661
+ of the postscript section. If `None`, the postscript marker is automatically
662
+ generated within `("P.S.", "P.P.S")`.
663
+
664
+ Returns:
665
+ A string representing the instruction description.
666
+ """
667
+ self._postscript_marker = (
668
+ postscript_marker.strip()
669
+ if isinstance(postscript_marker, str)
670
+ else postscript_marker
671
+ )
672
+ if self._postscript_marker is None:
673
+ self._postscript_marker = random.choice(_POSTSCRIPT_MARKER)
674
+
675
+ self._description_pattern = (
676
+ "At the end of your response, please explicitly add a postscript "
677
+ + "starting with {postscript}"
678
+ )
679
+
680
+ return self._description_pattern.format(postscript=self._postscript_marker)
681
+
682
+ def get_instruction_args(self) -> dict[str, Any]:
683
+ """Returns the keyword args of `build_description`."""
684
+ return {"postscript_marker": self._postscript_marker}
685
+
686
+ def get_instruction_args_keys(self) -> list[str]:
687
+ """Returns the args keys of `build_description`."""
688
+ return ["postscript_marker"]
689
+
690
+ def check_following(self, value: str) -> bool:
691
+ """Checks if the response follows the postscript format.
692
+
693
+ Args:
694
+ value (str): A string representing the response. The response is expected to
695
+ contain a postscript section.
696
+
697
+ Returns:
698
+ True if the response contains a postscript section starting with
699
+ the keyword containing in the `instruction_args`; otherwise False.
700
+ """
701
+ value = value.lower()
702
+ if self._postscript_marker == "P.P.S":
703
+ postscript_pattern = r"\s*p\.\s?p\.\s?s.*$"
704
+ elif self._postscript_marker == "P.S.":
705
+ postscript_pattern = r"\s*p\.\s?s\..*$"
706
+ else:
707
+ postscript_pattern = r"\s*" + self._postscript_marker.lower() + r".*$"
708
+ postscript = re.findall(postscript_pattern, value, flags=re.MULTILINE)
709
+ return True if postscript else False
710
+
711
+
712
+ class RephraseChecker(Instruction):
713
+ """Checks the repharse."""
714
+
715
+ def build_description(self, *, original_message: str):
716
+ """Build the instruction description.
717
+
718
+ Args:
719
+ original_message (str): A string representing the original message. The
720
+ rephrased response should only change its words/sentences in between
721
+ its two asterisks, for example, *change me*. Both original and rephrased
722
+ messages should contain the changes in the form of *change me*.
723
+
724
+ Returns:
725
+ A string representing the instruction description.
726
+ """
727
+ if not self.is_change(original_message):
728
+ raise ValueError(
729
+ f"Message {original_message} does not contain changes "
730
+ "in the form of *change me*."
731
+ )
732
+
733
+ self._reference_without_change = original_message
734
+ self._description = (
735
+ "Rephrasing: Your rephrased response should only"
736
+ + "change the words/sentences in between two asterisks"
737
+ + "such as *change me*."
738
+ )
739
+ return self._description
740
+
741
+ def get_instruction_args(self) -> dict[str, Any]:
742
+ """Returns the keyword args of `build_description`."""
743
+ return {"original_message": self._reference_without_change}
744
+
745
+ def get_instruction_args_keys(self) -> list[str]:
746
+ """Returns the args keys of `build_description`."""
747
+ return ["original_message"]
748
+
749
+ def check_following(self, value: str) -> bool:
750
+ r"""Checks if the rephrasing follows the instruction.
751
+
752
+ Args:
753
+ value (str): A string representing the response, which is expected to rephras
754
+ the string of `instruction_args`.
755
+
756
+ Returns:
757
+ `True` if `value` and `instruction_args` only differ by the words/sentences
758
+ in between two asterisks such as *change me*; otherwise, `False`.
759
+ """
760
+ if not self.is_change(value):
761
+ raise ValueError(
762
+ f"value {value} does not contain " "changes in the form of *change me*."
763
+ )
764
+
765
+ response_without_changes = self.strip_changes(value)
766
+ reference_without_changes = self.strip_changes(self._reference_without_change)
767
+
768
+ return response_without_changes == reference_without_changes
769
+
770
+ def is_change(self, response: str) -> bool:
771
+ """Check if there is change in the response in the form of *change me*."""
772
+ return re.search(r"\*.*\*", response)
773
+
774
+ def strip_changes(self, response: str):
775
+ """Strips off the changes."""
776
+ return re.sub(r"\*.*\*", "", response)
777
+
778
+
779
+ class KeywordChecker(Instruction):
780
+ """Check the exisitence of certain keywords."""
781
+
782
+ def build_description(self, *, keywords: Sequence[str] | None = None):
783
+ """Build the instruction description.
784
+
785
+ Args:
786
+ keywords (Sequence of str, optional): A sequence of strings representing the keywords that are
787
+ expected in the response. If `None`, the keywords are automatically
788
+ generated with a maximum of `_NUM_KEYWORDS` (defaults to `2`).
789
+
790
+ Returns:
791
+ A string representing the instruction description.
792
+ """
793
+ if not keywords:
794
+ self._keywords = generate_keywords(num_keywords=_NUM_KEYWORDS)
795
+ else:
796
+ self._keywords = keywords
797
+ self._keywords = sorted(self._keywords)
798
+
799
+ self._description_pattern = "Include keywords {keywords} in the response."
800
+
801
+ return self._description_pattern.format(keywords=self._keywords)
802
+
803
+ def get_instruction_args(self) -> dict[str, Any]:
804
+ """Returns the keyword args of `build_description`."""
805
+ return {"keywords": self._keywords}
806
+
807
+ def get_instruction_args_keys(self) -> list[str]:
808
+ """Returns the args keys of `build_description`."""
809
+ return ["keywords"]
810
+
811
+ def check_following(self, value: str) -> bool:
812
+ """Check if the response contain the expected keywords."""
813
+ for keyword in self._keywords:
814
+ if not re.search(keyword, value, flags=re.IGNORECASE):
815
+ return False
816
+ return True
817
+
818
+
819
+ class KeywordFrequencyChecker(Instruction):
820
+ """Check the keyword frequency."""
821
+
822
+ def build_description(
823
+ self,
824
+ *,
825
+ keyword: str | None = None,
826
+ frequency: int | None = None,
827
+ relation: Literal["less than", "at least"] | None = None,
828
+ ):
829
+ """Build the instruction description.
830
+
831
+ Args:
832
+ keyword (str, optional): A string representing a keyword that is expected in the response.
833
+ frequency (int, optional): An integer specifying the number of times `keyword` is expected
834
+ to appear in the response.
835
+ relation (str, optional): A string in (`'less than'`, `'at least'`), defining the relational
836
+ operator for comparison.
837
+ Two relational comparisons are supported for now:
838
+ if `'less than'`, the actual number of occurrences < frequency;
839
+ if `'at least'`, the actual number of occurrences >= frequency.
840
+
841
+ Returns:
842
+ A string representing the instruction description.
843
+ """
844
+ if not keyword:
845
+ self._keyword = generate_keywords(num_keywords=1)[0]
846
+ else:
847
+ self._keyword = keyword.strip()
848
+
849
+ self._frequency = frequency
850
+ if self._frequency is None or self._frequency < 0:
851
+ self._frequency = random.randint(1, _KEYWORD_FREQUENCY)
852
+
853
+ if relation is None:
854
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
855
+ elif relation not in _COMPARISON_RELATION:
856
+ raise ValueError(
857
+ "The supported relation for comparison must be in "
858
+ f"{_COMPARISON_RELATION}, but {relation} is given."
859
+ )
860
+ else:
861
+ self._comparison_relation = relation
862
+
863
+ self._description_pattern = (
864
+ "In your response, the word {keyword} should appear {relation} "
865
+ + "{frequency} times."
866
+ )
867
+
868
+ return self._description_pattern.format(
869
+ keyword=self._keyword,
870
+ relation=self._comparison_relation,
871
+ frequency=self._frequency,
872
+ )
873
+
874
+ def get_instruction_args(self) -> dict[str, Any]:
875
+ """Returns the keyword args of `build_description`."""
876
+ return {
877
+ "keyword": self._keyword,
878
+ "frequency": self._frequency,
879
+ "relation": self._comparison_relation,
880
+ }
881
+
882
+ def get_instruction_args_keys(self) -> list[str]:
883
+ """Returns the args keys of `build_description`."""
884
+ return ["keyword", "frequency", "relation"]
885
+
886
+ def check_following(self, value: str) -> bool:
887
+ """Checks if the response contain the keyword with required frequency."""
888
+ actual_occurrences = len(re.findall(self._keyword, value, flags=re.IGNORECASE))
889
+
890
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
891
+ return actual_occurrences < self._frequency
892
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
893
+ return (
894
+ actual_occurrences >= self._frequency
895
+ ) # pytype: disable=bad-return-type
896
+
897
+
898
+ class NumberOfWords(Instruction):
899
+ """Checks the number of words."""
900
+
901
+ def build_description(
902
+ self,
903
+ *,
904
+ num_words: int | None = None,
905
+ relation: Literal["less than", "at least"] | None = None,
906
+ ):
907
+ """Build the instruction description.
908
+
909
+ Args:
910
+ num_words (int, optional): An integer specifying the number of words contained in the
911
+ response.
912
+ relation (str, optional): A string in (`less than`, `at least`), defining the relational
913
+ operator for comparison.
914
+ Two relational comparisons are supported for now:
915
+ if 'less than', the actual number of words < num_words;
916
+ if 'at least', the actual number of words >= num_words.
917
+
918
+ Returns:
919
+ A string representing the instruction description.
920
+ """
921
+ self._num_words = num_words
922
+ if self._num_words is None or self._num_words < 0:
923
+ self._num_words = random.randint(
924
+ _NUM_WORDS_LOWER_LIMIT, _NUM_WORDS_UPPER_LIMIT
925
+ )
926
+
927
+ if relation is None:
928
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
929
+ elif relation not in _COMPARISON_RELATION:
930
+ raise ValueError(
931
+ "The supported relation for comparison must be in "
932
+ f"{_COMPARISON_RELATION}, but {relation} is given."
933
+ )
934
+ else:
935
+ self._comparison_relation = relation
936
+
937
+ self._description_pattern = "Answer with {relation} {num_words} words."
938
+
939
+ return self._description_pattern.format(
940
+ relation=self._comparison_relation, num_words=self._num_words
941
+ )
942
+
943
+ def get_instruction_args(self) -> dict[str, Any]:
944
+ """Returns the keyword args of `build_description`."""
945
+ return {"num_words": self._num_words, "relation": self._comparison_relation}
946
+
947
+ def get_instruction_args_keys(self) -> list[str]:
948
+ """Returns the args keys of `build_description`."""
949
+ return ["num_words", "relation"]
950
+
951
+ def check_following(self, value: str) -> bool:
952
+ """Checks if the response contains the expected number of words."""
953
+ num_words = count_words(value)
954
+
955
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
956
+ return num_words < self._num_words
957
+ elif self._comparison_relation == _COMPARISON_RELATION[1]:
958
+ return num_words >= self._num_words # pytype: disable=bad-return-type
959
+
960
+
961
+ class JsonFormat(Instruction):
962
+ """Check the Json format."""
963
+
964
+ def build_description(self) -> str:
965
+ self._description_pattern = (
966
+ "Entire output should be wrapped in JSON format. You can use markdown"
967
+ " ticks such as ```."
968
+ )
969
+ return self._description_pattern
970
+
971
+ def get_instruction_args(self) -> None:
972
+ """Returns the keyword args of `build_description`."""
973
+ return None
974
+
975
+ def get_instruction_args_keys(self) -> list[str]:
976
+ """Returns the args keys of `build_description`."""
977
+ return []
978
+
979
+ def check_following(self, value: str) -> bool:
980
+ value = (
981
+ value.strip()
982
+ .removeprefix("```json")
983
+ .removeprefix("```Json")
984
+ .removeprefix("```JSON")
985
+ .removeprefix("```")
986
+ .removesuffix("```")
987
+ .strip()
988
+ )
989
+ try:
990
+ json.loads(value)
991
+ except ValueError:
992
+ return False
993
+ return True
994
+
995
+
996
+ class ParagraphFirstWordCheck(Instruction):
997
+ """Check the paragraph and the first word of the nth paragraph."""
998
+
999
+ def build_description(
1000
+ self,
1001
+ num_paragraphs: int | None = None,
1002
+ nth_paragraph: int | None = None,
1003
+ first_word: str | None = None,
1004
+ ):
1005
+ r"""Build the instruction description.
1006
+
1007
+ Args:
1008
+ num_paragraphs (int, optional): An integer indicating the number of paragraphs expected
1009
+ in the response. A paragraph is a subset of the string that is
1010
+ expected to be separated by '\n\n'.
1011
+ nth_paragraph (int, optional): An integer indicating the paragraph number that we look at.
1012
+ Note that n starts from 1.
1013
+ first_word (str, optional): A string that represent the first word of the bth paragraph.
1014
+
1015
+ Returns:
1016
+ A string representing the instruction description.
1017
+ """
1018
+ self._num_paragraphs = num_paragraphs
1019
+ if self._num_paragraphs is None or self._num_paragraphs < 0:
1020
+ self._num_paragraphs = random.randint(1, _NUM_PARAGRAPHS)
1021
+
1022
+ self._nth_paragraph = nth_paragraph
1023
+ if (
1024
+ self._nth_paragraph is None
1025
+ or self._nth_paragraph <= 0
1026
+ or self._nth_paragraph > self._num_paragraphs
1027
+ ):
1028
+ self._nth_paragraph = random.randint(1, self._num_paragraphs + 1)
1029
+
1030
+ self._first_word = first_word
1031
+ if self._first_word is None:
1032
+ self._first_word = generate_keywords(num_keywords=1)[0]
1033
+ self._first_word = self._first_word.lower()
1034
+
1035
+ self._description_pattern = (
1036
+ "There should be {num_paragraphs} paragraphs. "
1037
+ + "Paragraphs and only paragraphs are separated with each other by two "
1038
+ + "new lines as if it was '\\n\\n' in python. "
1039
+ + "Paragraph {nth_paragraph} must start with word {first_word}."
1040
+ )
1041
+
1042
+ return self._description_pattern.format(
1043
+ num_paragraphs=self._num_paragraphs,
1044
+ nth_paragraph=self._nth_paragraph,
1045
+ first_word=self._first_word,
1046
+ )
1047
+
1048
+ def get_instruction_args(self) -> dict[str, Any]:
1049
+ """Returns the keyword args of `build_description`."""
1050
+ return {
1051
+ "num_paragraphs": self._num_paragraphs,
1052
+ "nth_paragraph": self._nth_paragraph,
1053
+ "first_word": self._first_word,
1054
+ }
1055
+
1056
+ def get_instruction_args_keys(self) -> list[str]:
1057
+ """Returns the args keys of `build_description`."""
1058
+ return ["num_paragraphs", "nth_paragraph", "first_word"]
1059
+
1060
+ def check_following(self, value: str) -> bool:
1061
+ """Checks for required number of paragraphs and correct first word.
1062
+
1063
+ Args:
1064
+ value (str): A string representing the response. The response may contain
1065
+ paragraphs that are separated by two new lines and the first word of
1066
+ the nth paragraph will have to match a specified word.
1067
+
1068
+ Returns:
1069
+ `True` if the number of paragraphs is the same as required and the first
1070
+ word of the specified paragraph is the same as required. Otherwise, `False`.
1071
+ """
1072
+ paragraphs = re.split(r"\n\n", value)
1073
+ num_paragraphs = len(paragraphs)
1074
+
1075
+ for paragraph in paragraphs:
1076
+ if not paragraph.strip():
1077
+ num_paragraphs -= 1
1078
+
1079
+ # check that index doesn't go out of bounds
1080
+ if self._nth_paragraph <= num_paragraphs:
1081
+ paragraph = paragraphs[self._nth_paragraph - 1].strip()
1082
+ if not paragraph:
1083
+ return False
1084
+ else:
1085
+ return False
1086
+
1087
+ first_word = ""
1088
+ punctuation = {".", ",", "?", "!", "'", '"'}
1089
+
1090
+ # get first word and remove punctuation
1091
+ word = paragraph.split()[0].strip()
1092
+ # TODO(jeffrey): make more complex?
1093
+ word = word.lstrip("'")
1094
+ word = word.lstrip('"')
1095
+
1096
+ for letter in word:
1097
+ if letter in punctuation:
1098
+ break
1099
+ first_word += letter.lower()
1100
+
1101
+ return num_paragraphs == self._num_paragraphs and first_word == self._first_word
1102
+
1103
+
1104
+ # TODO(jeffrey) add relation - at least/at most?
1105
+ class KeySentenceChecker(Instruction):
1106
+ """Check the existence of certain key sentences."""
1107
+
1108
+ def build_description(
1109
+ self,
1110
+ key_sentences: Sequence[str] | None = None,
1111
+ num_sentences: int | None = None,
1112
+ ):
1113
+ """Build the instruction description.
1114
+
1115
+ Args:
1116
+ key_sentences (Sequence[str], optional): A sequences of strings representing the key sentences that
1117
+ are expected in the response.
1118
+ num_sentences (int, optional): The number of key sentences that are expected to be seen in
1119
+ the response.
1120
+
1121
+ Returns:
1122
+ A string representing the instruction description.
1123
+ """
1124
+ if not key_sentences:
1125
+ # TODO(jeffrey) make a generate sentences function? wonderwords package
1126
+ self._key_sentences = {"For now, this is fine."}
1127
+ else:
1128
+ self._key_sentences = key_sentences
1129
+
1130
+ if not num_sentences:
1131
+ self._num_sentences = random.randint(1, len(self._key_sentences))
1132
+ else:
1133
+ self._num_sentences = num_sentences
1134
+
1135
+ self._description_pattern = (
1136
+ "Include {num_sentences} of the following sentences {key_sentences}"
1137
+ )
1138
+
1139
+ return self._description_pattern.format(
1140
+ num_sentences=self._num_sentences, key_sentences=self._key_sentences
1141
+ )
1142
+
1143
+ def get_instruction_args(self) -> dict[str, Any]:
1144
+ """Returns the keyword args of `build_description`."""
1145
+ return {
1146
+ "num_sentences": self._num_sentences,
1147
+ "key_sentences": list(self._key_sentences),
1148
+ }
1149
+
1150
+ def get_instruction_args_keys(self) -> list[str]:
1151
+ """Returns the args keys of `build_description`."""
1152
+ return ["num_sentences", "key_sentences"]
1153
+
1154
+ def check_following(self, value: str) -> bool:
1155
+ """Checks if the response contains the expected key sentences."""
1156
+ count = 0
1157
+ sentences = split_into_sentences(value)
1158
+ for sentence in self._key_sentences:
1159
+ if sentence in sentences:
1160
+ count += 1
1161
+
1162
+ return count == self._num_sentences
1163
+
1164
+
1165
+ class ForbiddenWords(Instruction):
1166
+ """Checks that specified words are not used in response."""
1167
+
1168
+ def build_description(self, forbidden_words: Sequence[str] | None = None):
1169
+ """Build the instruction description.
1170
+
1171
+ Args:
1172
+ forbidden_words (Sequence[str], optional): A sequences of strings respresenting words that are not
1173
+ allowed in the response.
1174
+
1175
+ Returns:
1176
+ A string representing the instruction description.
1177
+ """
1178
+ if not forbidden_words:
1179
+ self._forbidden_words = generate_keywords(num_keywords=_NUM_KEYWORDS)
1180
+ else:
1181
+ self._forbidden_words = list(set(forbidden_words))
1182
+ self._forbidden_words = sorted(self._forbidden_words)
1183
+ self._description_pattern = (
1184
+ "Do not include keywords {forbidden_words} in the response."
1185
+ )
1186
+
1187
+ return self._description_pattern.format(forbidden_words=self._forbidden_words)
1188
+
1189
+ def get_instruction_args(self) -> dict[str, Any]:
1190
+ """Returns the keyword args of `build_description`."""
1191
+ return {"forbidden_words": self._forbidden_words}
1192
+
1193
+ def get_instruction_args_keys(self) -> list[str]:
1194
+ """Returns the args keys of `build_description`."""
1195
+ return ["forbidden_words"]
1196
+
1197
+ def check_following(self, value: str) -> bool:
1198
+ """Check if the response does not contain the expected keywords."""
1199
+ for word in self._forbidden_words:
1200
+ if re.search(r"\b" + word + r"\b", value, flags=re.IGNORECASE):
1201
+ return False
1202
+ return True
1203
+
1204
+
1205
+ class RephraseParagraph(Instruction):
1206
+ """Checks that the paragraph is rephrased."""
1207
+
1208
+ def build_description(self, *, original_paragraph: str, low: int, high: int) -> str:
1209
+ """Builds the instruction description.
1210
+
1211
+ Args:
1212
+ original_paragraph (str): A string presenting the original paragraph. The
1213
+ rephrases response should have between low-high words in common.
1214
+ low (int): An integer presenting the lower bound of similar words.
1215
+ high (int): An integer representing the upper bound of similar words.
1216
+
1217
+ Returns:
1218
+ A string representing the instruction description.
1219
+ """
1220
+ # TODO(jeffrey) make more encompassing
1221
+ self._original_paragraph = original_paragraph
1222
+ self._low = low
1223
+ self._high = high
1224
+
1225
+ self._description = (
1226
+ "Rephrase the following paragraph: "
1227
+ + "{original_paragraph}\nYour response should have "
1228
+ + "between {low} and {high} of the same words. "
1229
+ + "Words are the same if and only if all of the "
1230
+ + "letters, ignoring cases, are the same. For "
1231
+ + "example, 'run' is the same as 'Run' but different "
1232
+ + "to 'ran'."
1233
+ )
1234
+
1235
+ return self._description.format(
1236
+ original_paragraph=original_paragraph, low=self._low, high=self._high
1237
+ )
1238
+
1239
+ def get_instruction_args(self) -> dict[str, Any]:
1240
+ """Returns the keyword args of `build_description`."""
1241
+ return {
1242
+ "original_paragraph": self._original_paragraph,
1243
+ "low": self._low,
1244
+ "high": self._high,
1245
+ }
1246
+
1247
+ def get_instruction_args_keys(self) -> list[str]:
1248
+ """Returns the args keys of `build_description`."""
1249
+ return ["original_paragraph", "low", "high"]
1250
+
1251
+ def check_following(self, value: str) -> bool:
1252
+ val_words = re.findall(r"\w+", value.lower())
1253
+ original_words = re.findall(r"\w+", self._original_paragraph.lower())
1254
+ similar_words = 0
1255
+
1256
+ dict_val = collections.Counter(val_words)
1257
+ dict_original = collections.Counter(original_words)
1258
+
1259
+ for word in dict_original:
1260
+ similar_words += min(dict_original[word], dict_val[word])
1261
+
1262
+ return similar_words >= self._low and similar_words <= self._high
1263
+
1264
+
1265
+ class TwoResponsesChecker(Instruction):
1266
+ """Check that two responses were given."""
1267
+
1268
+ def build_description(self) -> str:
1269
+ """Build the instruction description."""
1270
+ self._description_pattern = (
1271
+ "Give two different responses. Responses and only responses should"
1272
+ " be separated by 6 asterisk symbols: ******."
1273
+ )
1274
+ return self._description_pattern
1275
+
1276
+ def get_instruction_args(self) -> dict[str, Any] | None:
1277
+ """Returns the keyword args of `build_description`."""
1278
+ return None
1279
+
1280
+ def get_instruction_args_keys(self) -> list[str]:
1281
+ """Returns the args keys of `build_description`."""
1282
+ return []
1283
+
1284
+ def check_following(self, value: str) -> bool:
1285
+ """Checks if the response has two different answers.
1286
+
1287
+ Args:
1288
+ value (str): A string representing the response.
1289
+
1290
+ Returns:
1291
+ `True` if two responses are detected and false otherwise.
1292
+ """
1293
+ valid_responses = []
1294
+ responses = value.split("******")
1295
+ for index, response in enumerate(responses):
1296
+ if not response.strip():
1297
+ if index != 0 and index != len(responses) - 1:
1298
+ return False
1299
+ else:
1300
+ valid_responses.append(response)
1301
+ return (
1302
+ len(valid_responses) == 2
1303
+ and valid_responses[0].strip() != valid_responses[1].strip()
1304
+ )
1305
+
1306
+
1307
+ class RepeatPromptThenAnswer(Instruction):
1308
+ """Checks that Prompt is first repeated then answered."""
1309
+
1310
+ def build_description(self, *, prompt_to_repeat: str | None = None) -> str:
1311
+ """Build the instruction description.
1312
+
1313
+ Args:
1314
+ prompt_to_repeat: The prompt that is meant to be repeated.
1315
+
1316
+ Returns:
1317
+ A string representing the instruction description.
1318
+ """
1319
+ if not prompt_to_repeat:
1320
+ raise ValueError("prompt_to_repeat must be set.")
1321
+ else:
1322
+ self._prompt_to_repeat = prompt_to_repeat
1323
+ self._description_pattern = (
1324
+ "First repeat the request word for word without change,"
1325
+ " then give your answer (1. do not say any words or characters"
1326
+ " before repeating the request; 2. the request you need to repeat"
1327
+ " does not include this sentence)"
1328
+ )
1329
+ return self._description_pattern
1330
+
1331
+ def get_instruction_args(self) -> dict[str, Any]:
1332
+ return {"prompt_to_repeat": self._prompt_to_repeat}
1333
+
1334
+ def get_instruction_args_keys(self) -> list[str]:
1335
+ """Returns the args keys of `build_description`."""
1336
+ return ["prompt_to_repeat"]
1337
+
1338
+ def check_following(self, value: str) -> bool:
1339
+ if value.strip().lower().startswith(self._prompt_to_repeat.strip().lower()):
1340
+ return True
1341
+ return False
1342
+
1343
+
1344
+ class EndChecker(Instruction):
1345
+ """Checks that the prompt ends with a given phrase."""
1346
+
1347
+ def build_description(self, *, end_phrase: str | None = None):
1348
+ """Build the instruction description.
1349
+
1350
+ Args:
1351
+ end_phrase (str): A string representing the phrase the response should end with.
1352
+
1353
+ Returns:
1354
+ A string representing the instruction description.
1355
+ """
1356
+ self._end_phrase = (
1357
+ end_phrase.strip() if isinstance(end_phrase, str) else end_phrase
1358
+ )
1359
+ if self._end_phrase is None:
1360
+ self._end_phrase = random.choice(_ENDING_OPTIONS)
1361
+ self._description_pattern = (
1362
+ "Finish your response with this exact phrase {ender}. "
1363
+ "No other words should follow this phrase."
1364
+ )
1365
+ return self._description_pattern.format(ender=self._end_phrase)
1366
+
1367
+ def get_instruction_args(self) -> dict[str, Any]:
1368
+ return {"end_phrase": self._end_phrase}
1369
+
1370
+ def get_instruction_args_keys(self) -> list[str]:
1371
+ """Returns the args keys of `build_description`."""
1372
+ return ["end_phrase"]
1373
+
1374
+ def check_following(self, value: str) -> bool:
1375
+ """Checks if the response ends with the expected phrase."""
1376
+ value = value.strip().strip('"').lower()
1377
+ self._end_phrase = self._end_phrase.strip().lower()
1378
+ return value.endswith(self._end_phrase)
1379
+
1380
+
1381
+ class TitleChecker(Instruction):
1382
+ """Checks the response for a title."""
1383
+
1384
+ def build_description(self) -> str:
1385
+ """Build the instruction description."""
1386
+ self._description_pattern = (
1387
+ "Your answer must contain a title, wrapped in double angular brackets,"
1388
+ " such as <<poem of joy>>."
1389
+ )
1390
+ return self._description_pattern
1391
+
1392
+ def get_instruction_args(self) -> dict[str, Any] | None:
1393
+ return None
1394
+
1395
+ def get_instruction_args_keys(self) -> list[str]:
1396
+ """Returns the args keys of `build_description`."""
1397
+ return []
1398
+
1399
+ def check_following(self, value: str) -> bool:
1400
+ """Checks if the response contains a title."""
1401
+ pattern = r"<<[^\n]+>>"
1402
+ re_pattern = re.compile(pattern)
1403
+ titles = re.findall(re_pattern, value)
1404
+
1405
+ for title in titles:
1406
+ if title.lstrip("<").rstrip(">").strip():
1407
+ return True
1408
+ return False
1409
+
1410
+
1411
+ class LetterFrequencyChecker(Instruction):
1412
+ """Checks letter frequency."""
1413
+
1414
+ def build_description(
1415
+ self,
1416
+ *,
1417
+ letter: str | None = None,
1418
+ let_frequency: int | None = None,
1419
+ let_relation: Literal["less than", "at least"] | None = None,
1420
+ ) -> str:
1421
+ """Build the instruction description.
1422
+
1423
+ Args:
1424
+ letter (str, optional): A string representing a letter that is expected in the response.
1425
+ let_frequency (int, optional): An integer specifying the number of times `keyword` is
1426
+ expected to appear in the response.
1427
+ let_relation: A string in (`"less than"`, `"at least"`), defining the
1428
+ relational operator for comparison. Two relational comparisons are
1429
+ supported for now; if 'less than', the actual number of
1430
+ occurrences < frequency; if 'at least', the actual number of
1431
+ occurrences >= frequency.
1432
+
1433
+ Returns:
1434
+ A string representing the instruction description.
1435
+ """
1436
+ if (
1437
+ not letter
1438
+ or len(letter) > 1
1439
+ or ord(letter.lower()) < 97
1440
+ or ord(letter.lower()) > 122
1441
+ ):
1442
+ self._letter = random.choice(list(string.ascii_letters))
1443
+ else:
1444
+ self._letter = letter.strip()
1445
+ self._letter = self._letter.lower()
1446
+
1447
+ self._frequency = let_frequency
1448
+ if self._frequency is None or self._frequency < 0:
1449
+ self._frequency = random.randint(1, _LETTER_FREQUENCY)
1450
+
1451
+ if let_relation is None:
1452
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1453
+ elif let_relation not in _COMPARISON_RELATION:
1454
+ raise ValueError(
1455
+ "The supported relation for comparison must be in "
1456
+ f"{_COMPARISON_RELATION}, but {let_relation} is given."
1457
+ )
1458
+ else:
1459
+ self._comparison_relation = let_relation
1460
+
1461
+ self._description_pattern = (
1462
+ "In your response, the letter {letter} should appear {let_relation}"
1463
+ " {let_frequency} times."
1464
+ )
1465
+
1466
+ return self._description_pattern.format(
1467
+ letter=self._letter,
1468
+ let_frequency=self._frequency,
1469
+ let_relation=self._comparison_relation,
1470
+ )
1471
+
1472
+ def get_instruction_args(self) -> dict[str, Any]:
1473
+ """Returns the keyword args of build description."""
1474
+ return {
1475
+ "letter": self._letter,
1476
+ "let_frequency": self._frequency,
1477
+ "let_relation": self._comparison_relation,
1478
+ }
1479
+
1480
+ def get_instruction_args_keys(self) -> list[str]:
1481
+ """Returns the args keys of `build_description`."""
1482
+ return ["letter", "let_frequency", "let_relation"]
1483
+
1484
+ def check_following(self, value: str) -> bool:
1485
+ """Checks that the response contains the letter at the right frequency."""
1486
+ value = value.lower()
1487
+ letters = collections.Counter(value)
1488
+
1489
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1490
+ return letters[self._letter] < self._frequency
1491
+ else:
1492
+ return letters[self._letter] >= self._frequency
1493
+
1494
+
1495
+ class CapitalLettersEnglishChecker(Instruction):
1496
+ """Checks that the response is in english and is in all capital letters."""
1497
+
1498
+ def build_description(self) -> str:
1499
+ """Build the instruction description."""
1500
+ self._description_pattern = (
1501
+ "Your entire response should be in English, and in all capital letters."
1502
+ )
1503
+ return self._description_pattern
1504
+
1505
+ def get_instruction_args(self) -> dict[str, Any] | None:
1506
+ return None
1507
+
1508
+ def get_instruction_args_keys(self) -> list[str]:
1509
+ """Returns the args keys of `build_description`."""
1510
+ return []
1511
+
1512
+ def check_following(self, value: str) -> bool:
1513
+ """Checks that the response is in English and in all capital letters."""
1514
+ import langdetect
1515
+
1516
+ try:
1517
+ return value.isupper() and langdetect.detect(value) == "en"
1518
+ except (langdetect.LangDetectException, ImportError) as e:
1519
+ # Count as instruction is followed.
1520
+ torchrl_logger.error(
1521
+ "Unable to detect language for text %s due to %s", value, e
1522
+ ) # refex: disable=pytotw.037
1523
+ return True
1524
+
1525
+
1526
+ class LowercaseLettersEnglishChecker(Instruction):
1527
+ """Checks that the response is in english and is in all lowercase letters."""
1528
+
1529
+ def build_description(self) -> str:
1530
+ """Build the instruction description."""
1531
+ self._description_pattern = (
1532
+ "Your entire response should be in English, and in all lowercase"
1533
+ " letters. No capital letters are allowed."
1534
+ )
1535
+ return self._description_pattern
1536
+
1537
+ def get_instruction_args(self) -> dict[str, Any] | None:
1538
+ return None
1539
+
1540
+ def get_instruction_args_keys(self) -> list[str]:
1541
+ """Returns the args keys of `build_description`."""
1542
+ return []
1543
+
1544
+ def check_following(self, value: str) -> bool:
1545
+ """Checks that the response is in English and in all lowercase letters."""
1546
+ import langdetect
1547
+
1548
+ try:
1549
+ return value.islower() and langdetect.detect(value) == "en"
1550
+ except (langdetect.LangDetectException, ImportError) as e:
1551
+ # Count as instruction is followed.
1552
+ torchrl_logger.error(
1553
+ "Unable to detect language for text %s due to %s", value, e
1554
+ ) # refex: disable=pytotw.037
1555
+ return True
1556
+
1557
+
1558
+ class CommaChecker(Instruction):
1559
+ """Checks the response for no commas."""
1560
+
1561
+ def build_description(self) -> str:
1562
+ """Build the instruction description."""
1563
+ self._description_pattern = (
1564
+ "In your entire response, refrain from the use of any commas."
1565
+ )
1566
+ return self._description_pattern
1567
+
1568
+ def get_instruction_args(self) -> dict[str, Any] | None:
1569
+ return None
1570
+
1571
+ def get_instruction_args_keys(self) -> list[str]:
1572
+ """Returns the args keys of `build_description`."""
1573
+ return []
1574
+
1575
+ def check_following(self, value: str) -> bool:
1576
+ """Checks that the response does not contain commas."""
1577
+ return not re.search(r"\,", value)
1578
+
1579
+
1580
+ class CapitalWordFrequencyChecker(Instruction):
1581
+ """Checks frequency of words with all capital letters."""
1582
+
1583
+ def build_description(
1584
+ self,
1585
+ capital_frequency: int | None = None,
1586
+ capital_relation: Literal["at least", "at most"] | None = None,
1587
+ ) -> str:
1588
+ """Build the instruction description.
1589
+
1590
+ Args:
1591
+ capital_frequency: An integer that represents the number of words that
1592
+ should be in all capital letters.
1593
+ capital_relation: A string that is 'at least' or 'at most' that refers to
1594
+ the frequency.
1595
+
1596
+ Returns:
1597
+ A string representing the instruction description.
1598
+ """
1599
+ self._frequency = capital_frequency
1600
+ if self._frequency is None:
1601
+ self._frequency = random.randint(1, _ALL_CAPITAL_WORD_FREQUENCY)
1602
+
1603
+ self._comparison_relation = capital_relation
1604
+ if capital_relation is None:
1605
+ self._comparison_relation = random.choice(_COMPARISON_RELATION)
1606
+ elif capital_relation not in _COMPARISON_RELATION:
1607
+ raise ValueError(
1608
+ "The supported relation for comparison must be in "
1609
+ f"{_COMPARISON_RELATION}, but {capital_relation} is given."
1610
+ )
1611
+
1612
+ self._description_pattern = (
1613
+ "In your response, words with all capital letters should appear"
1614
+ " {relation} {frequency} times."
1615
+ )
1616
+
1617
+ return self._description_pattern.format(
1618
+ frequency=self._frequency, relation=self._comparison_relation
1619
+ )
1620
+
1621
+ def get_instruction_args(self) -> dict[str, Any]:
1622
+ """Returns the keyword args of build description."""
1623
+ return {
1624
+ "capital_frequency": self._frequency,
1625
+ "capital_relation": self._comparison_relation,
1626
+ }
1627
+
1628
+ def get_instruction_args_keys(self) -> list[str]:
1629
+ """Returns the args keys of `build_description`."""
1630
+ return ["capital_frequency", "capital_relation"]
1631
+
1632
+ def check_following(self, value: str) -> bool:
1633
+ """Checks the frequency of words with all capital letters."""
1634
+ # Hyphenated words will count as one word
1635
+ words = nltk.word_tokenize(value)
1636
+ capital_words = [word for word in words if word.isupper()]
1637
+
1638
+ capital_words = len(capital_words)
1639
+
1640
+ if self._comparison_relation == _COMPARISON_RELATION[0]:
1641
+ return capital_words < self._frequency
1642
+ else:
1643
+ return capital_words >= self._frequency
1644
+
1645
+
1646
+ class QuotationChecker(Instruction):
1647
+ """Checks response is wrapped with double quotation marks."""
1648
+
1649
+ def build_description(self) -> str:
1650
+ """Build the instruction description."""
1651
+ self._description_pattern = (
1652
+ "Wrap your entire response with double quotation marks."
1653
+ )
1654
+ return self._description_pattern
1655
+
1656
+ def get_instruction_args(self) -> dict[str, Any] | None:
1657
+ """Returns the keyword args of build description."""
1658
+ return None
1659
+
1660
+ def get_instruction_args_keys(self) -> list[str]:
1661
+ """Returns the args keys of `build_description`."""
1662
+ return []
1663
+
1664
+ def check_following(self, value: str) -> bool:
1665
+ """Checks if the response is wrapped with double quotation marks."""
1666
+ value = value.strip()
1667
+ return len(value) > 1 and value[0] == '"' and value[-1] == '"'