SunSec commited on
Commit
e9f3767
·
verified ·
1 Parent(s): 4bac76a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +27 -0
  2. deep_search/DeepResearcher/.gitignore +174 -0
  3. deep_search/DeepResearcher/LICENSE +201 -0
  4. deep_search/DeepResearcher/Notice.txt +1 -0
  5. deep_search/DeepResearcher/README.md +127 -0
  6. deep_search/DeepResearcher/VERL_README.md +147 -0
  7. deep_search/DeepResearcher/evaluate.sh +51 -0
  8. deep_search/DeepResearcher/examples/data_preprocess/full_hh_rlhf.py +146 -0
  9. deep_search/DeepResearcher/examples/data_preprocess/geo3k.py +86 -0
  10. deep_search/DeepResearcher/examples/data_preprocess/gsm8k.py +94 -0
  11. deep_search/DeepResearcher/examples/data_preprocess/hellaswag.py +102 -0
  12. deep_search/DeepResearcher/examples/data_preprocess/math_dataset.py +91 -0
  13. deep_search/DeepResearcher/examples/grpo_trainer/run_deepseek7b_llm.sh +37 -0
  14. deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2-7b_seq_balance.sh +39 -0
  15. deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2_5_0_5b_seq_balance.sh +39 -0
  16. deep_search/DeepResearcher/examples/ray/tutorial.ipynb +958 -0
  17. deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-3b_seq_balance.sh +42 -0
  18. deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-7b_seq_balance.sh +42 -0
  19. deep_search/DeepResearcher/examples/rloo_trainer/run_qwen2-7b.sh +40 -0
  20. deep_search/DeepResearcher/examples/sft/gsm8k/run_deepseek_6b7.sh +29 -0
  21. deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_2b.sh +31 -0
  22. deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_7b.sh +27 -0
  23. deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_peft.sh +38 -0
  24. deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2.sh +32 -0
  25. deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2_liger.sh +32 -0
  26. deep_search/DeepResearcher/examples/split_placement/README.md +61 -0
  27. deep_search/DeepResearcher/examples/split_placement/config/ppo_trainer_split.yaml +171 -0
  28. deep_search/DeepResearcher/examples/split_placement/main_ppo_split.py +199 -0
  29. deep_search/DeepResearcher/examples/split_placement/run_deepseek7b_llm.sh +35 -0
  30. deep_search/DeepResearcher/examples/split_placement/split_monkey_patch.py +197 -0
  31. deep_search/DeepResearcher/pyproject.toml +86 -0
  32. deep_search/DeepResearcher/requirements.txt +64 -0
  33. deep_search/DeepResearcher/setup.py +77 -0
  34. deep_search/DeepResearcher/train_grpo.sh +51 -0
  35. deep_search/search_o1/eval/__pycache__/utils.cpython-310.pyc +0 -0
  36. deep_search/search_o1/eval/__pycache__/utils.cpython-39.pyc +0 -0
  37. deep_search/search_o1/eval/add_eval.py +207 -0
  38. deep_search/search_o1/eval/eval_seach_o1.py +93 -0
  39. deep_search/search_o1/eval/eval_seach_o1_with_output_len.py +202 -0
  40. deep_search/search_o1/eval/token_len.py +76 -0
  41. deep_search/search_o1/eval/topics_stats.py +140 -0
  42. deep_search/search_o1/eval/utils.py +450 -0
  43. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/gen.4.9,15:24.json +3 -0
  44. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/gen.4.9,3:34.info_extract.json +3 -0
  45. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_12.json +3 -0
  46. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_13.json +3 -0
  47. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_5.json +3 -0
  48. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_8.json +3 -0
  49. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_9.json +3 -0
  50. deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/combined_output_length_distribution.png +3 -0
.gitattributes CHANGED
@@ -2203,3 +2203,30 @@ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_
2203
  deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_1.json filter=lfs diff=lfs merge=lfs -text
2204
  deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_2.json filter=lfs diff=lfs merge=lfs -text
2205
  deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_4.json filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2203
  deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_1.json filter=lfs diff=lfs merge=lfs -text
2204
  deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_2.json filter=lfs diff=lfs merge=lfs -text
2205
  deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_4.json filter=lfs diff=lfs merge=lfs -text
2206
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_11.json filter=lfs diff=lfs merge=lfs -text
2207
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_6.json filter=lfs diff=lfs merge=lfs -text
2208
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_5.json filter=lfs diff=lfs merge=lfs -text
2209
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_3.json filter=lfs diff=lfs merge=lfs -text
2210
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/gen.4.9,15:24.json filter=lfs diff=lfs merge=lfs -text
2211
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_7.json filter=lfs diff=lfs merge=lfs -text
2212
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_13.json filter=lfs diff=lfs merge=lfs -text
2213
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_12.json filter=lfs diff=lfs merge=lfs -text
2214
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/gen.4.8,5:50.info_extract.json filter=lfs diff=lfs merge=lfs -text
2215
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_9.json filter=lfs diff=lfs merge=lfs -text
2216
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_10.json filter=lfs diff=lfs merge=lfs -text
2217
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_2.json filter=lfs diff=lfs merge=lfs -text
2218
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_11.json filter=lfs diff=lfs merge=lfs -text
2219
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_6.json filter=lfs diff=lfs merge=lfs -text
2220
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_4.json filter=lfs diff=lfs merge=lfs -text
2221
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_1.json filter=lfs diff=lfs merge=lfs -text
2222
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_3.json filter=lfs diff=lfs merge=lfs -text
2223
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_8.json filter=lfs diff=lfs merge=lfs -text
2224
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_7.json filter=lfs diff=lfs merge=lfs -text
2225
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/gen.4.9,3:34.info_extract.json filter=lfs diff=lfs merge=lfs -text
2226
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_5.json filter=lfs diff=lfs merge=lfs -text
2227
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/gen.4.9,15:24.json filter=lfs diff=lfs merge=lfs -text
2228
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_12.json filter=lfs diff=lfs merge=lfs -text
2229
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_13.json filter=lfs diff=lfs merge=lfs -text
2230
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_9.json filter=lfs diff=lfs merge=lfs -text
2231
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_8.json filter=lfs diff=lfs merge=lfs -text
2232
+ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_5.json filter=lfs diff=lfs merge=lfs -text
deep_search/DeepResearcher/.gitignore ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Ruff stuff:
171
+ .ruff_cache/
172
+
173
+ # PyPI configuration file
174
+ .pypirc
deep_search/DeepResearcher/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
deep_search/DeepResearcher/Notice.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ Copyright 2023-2024 Bytedance Ltd. and/or its affiliates
deep_search/DeepResearcher/README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DeepResearcher: Scaling Deep Research via Reinforcement Learning in Real-world Environments
2
+
3
+ ## 📝 Introduction
4
+
5
+ DeepResearcher is the first comprehensive framework for end-to-end training of LLM-based deep research agents through scaling reinforcement learning (RL) in real-world environments with authentic web search interactions. Our qualitative analysis reveals emergent **cognitive behaviors** from end-to-end RL training, including the ability to formulate plans, cross-validate information from multiple sources, engage in self-reflection to redirect research, and maintain honesty when unable to find definitive answers.
6
+
7
+
8
+
9
+ <p align="center">
10
+     <img src="images/case_1.png" id="framework-icon" style="display:inline-block; width:46.55%; margin-right:5px;">
11
+     <img src="images/case_2.png" id="framework-icon" style="display:inline-block; width:43.45%;">
12
+ </p>
13
+
14
+
15
+ ## 📋 Table of Contents
16
+
17
+ - [Introduction](#-introduction)
18
+ - [Model](#-Model)
19
+ - [Performance](#-performance)
20
+ - [Get started](#-get-started)
21
+ - [Acknowledgement](#-Acknowledgement)
22
+ - [Citation](#✍️-citation)
23
+
24
+
25
+
26
+
27
+ ## 🤖 Model
28
+ DeepResearcher is now available on huggingface-hub:
29
+ | Model Name | HF Checkpoint | Size |
30
+ | ---------- | ------------------------------------------------------------ | :------: |
31
+ | DeepResearcher-7b | [🤗 GAIR/DeepResearcher-7b](https://huggingface.co/GAIR/DeepResearcher-7b) | **7B**
32
+
33
+
34
+ ## 🏆 Performance
35
+
36
+ Extensive experiments on open-domain research tasks demonstrate that DeepResearcher achieves substantial improvements of up to 28.9 points over prompt engineering-based baselines and up to 7.2 points over RAG-based RL agents. Our qualitative analysis reveals emergent cognitive behaviors from end-to-end RL training, including the ability to formulate plans, cross-validate information from multiple sources, engage in self-reflection to redirect research, and maintain honesty when unable to find definitive answers. Our results highlight that end-to-end training in real-world web environments is not merely an implementation detail but a fundamental requirement for developing robust research capabilities aligned with real-world applications.
37
+
38
+ <p align="center"> <img src="images/performance.png" id="performance-icon"> </p>
39
+
40
+ <p align="center"> <img src="images/scaling.png" id="performance-icon"> </p>
41
+
42
+
43
+ ## 🚀 Get Started
44
+
45
+ ### Package Installation
46
+
47
+ To begin using this repo, you need to install the required dependencies. You can do this by running the following command:
48
+
49
+ ```bash
50
+ git clone https://github.com/GAIR-NLP/DeepResearcher.git
51
+ conda create -n deepresearcher python=3.10
52
+ conda activate deepresearcher
53
+ cd DeepResearcher
54
+ pip3 install torch==2.4.0 --index-url https://download.pytorch.org/whl/cu124
55
+ pip3 install flash-attn --no-build-isolation
56
+ cd verl
57
+ pip3 install -e .
58
+ cd ../
59
+ pip3 install -r requirements.txt
60
+ ```
61
+
62
+ ### Start ray before training and inference
63
+ We use ray to train model, befor start ray you should set ```PET_NODE_RANK``` first. (**This is compulsory even if you only have 1 node**).
64
+ Here is the code of the head node:
65
+ ```bash
66
+ export PET_NODE_RANK=0
67
+ ray start --head
68
+ ```
69
+
70
+ ### Run backend handler
71
+
72
+ Running the following command to launch the server handler:
73
+ 1. Modify ```serper_api_key``` or ```azure_bing_search_subscription_key``` & ```search_engine``` in ```./scrl/handler/config.yaml```
74
+ 2. Add ```qwen-plus``` api key in ```./scrl/handler/server_handler.py```
75
+ ```python
76
+ client = OpenAI(
77
+ api_key="sk-xxx",
78
+ base_url="xxxx"
79
+ )
80
+ ```
81
+ 3. Start server handler:
82
+ ```bash
83
+ python ./scrl/handler/server_handler.py
84
+ ```
85
+
86
+ After launching all server handlers, you can replace ```server_url_list``` in ```./scrl/handler/config.yaml``` in your training host node and then run:
87
+ ```bash
88
+ python ./scrl/handler/handler.py
89
+ ```
90
+ ### Training model
91
+
92
+ Using the following command to train the model:
93
+ ```bash
94
+ bash train_grpo.sh
95
+ ```
96
+
97
+ ### Evaluate
98
+ Using the following command to generate rollout:
99
+ ```bash
100
+ bash evaluate.sh
101
+ ```
102
+ You can find the rollout file in: ```./outputs/{project_name}/{experiment_name}/rollout/rollout_step_0.json```
103
+ You can rename and copy it into ```./evaluate/{experiment_name}_result.json```
104
+
105
+ Then, run the following command:
106
+ ```bash
107
+ python ./evaluate/cacluate_metrics.py {experiment_name}
108
+ ```
109
+ You can check the score in ```./evaluate/{experiment_name}_score.json```
110
+
111
+ ## 🙏 Acknowledgement
112
+
113
+ DeepResearcher is inspired by [Deepseek-R1](https://github.com/deepseek-ai/DeepSeek-R1) with its implementation based on [veRL](https://github.com/volcengine/verl) and [Search-r1](https://github.com/PeterGriffinJin/Search-R1). We deeply appreciate the contributions of these teams to open-source research and development.
114
+
115
+ ## ✍️ Citation
116
+
117
+ Please cite the repo if the model/code/conclusion in this repo are helpful to you.
118
+ ```
119
+ @misc{deepresearch,
120
+ author = {Zheng, Yuxiang and Fu, Dayuan and Hu, Xiangkun and Cai, Xiaojie and Ye, Lyumanshan and Lu, Pengrui and Liu, Pengfei},
121
+ title = {DeepResearcher: Scaling Deep Research via Reinforcement Learning in Real-world Environments},
122
+ year = {2025},
123
+ publisher = {GitHub},
124
+ journal = {GitHub repository},
125
+ howpublished = {\url{https://github.com/GAIR-NLP/DeepResearcher}},
126
+ }
127
+ ```
deep_search/DeepResearcher/VERL_README.md ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <h1 style="text-align: center;">verl: Volcano Engine Reinforcement Learning for LLM</h1>
2
+
3
+ verl is a flexible, efficient and production-ready RL training library for large language models (LLMs).
4
+
5
+ verl is the open-source version of **[HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2)** paper.
6
+
7
+ verl is flexible and easy to use with:
8
+
9
+ - **Easy extension of diverse RL algorithms**: The Hybrid programming model combines the strengths of single-controller and multi-controller paradigms to enable flexible representation and efficient execution of complex Post-Training dataflows. Allowing users to build RL dataflows in a few lines of code.
10
+
11
+ - **Seamless integration of existing LLM infra with modular APIs**: Decouples computation and data dependencies, enabling seamless integration with existing LLM frameworks, such as PyTorch FSDP, Megatron-LM and vLLM. Moreover, users can easily extend to other LLM training and inference frameworks.
12
+
13
+ - **Flexible device mapping**: Supports various placement of models onto different sets of GPUs for efficient resource utilization and scalability across different cluster sizes.
14
+
15
+ - Readily integration with popular HuggingFace models
16
+
17
+
18
+ verl is fast with:
19
+
20
+ - **State-of-the-art throughput**: By seamlessly integrating existing SOTA LLM training and inference frameworks, verl achieves high generation and training throughput.
21
+
22
+ - **Efficient actor model resharding with 3D-HybridEngine**: Eliminates memory redundancy and significantly reduces communication overhead during transitions between training and generation phases.
23
+
24
+ <p align="center">
25
+ | <a href="https://verl.readthedocs.io/en/latest/index.html"><b>Documentation</b></a> | <a href="https://arxiv.org/abs/2409.19256v2"><b>Paper</b></a> | <a href="https://join.slack.com/t/verlgroup/shared_invite/zt-2w5p9o4c3-yy0x2Q56s_VlGLsJ93A6vA"><b>Slack</b></a> | <a href="https://raw.githubusercontent.com/eric-haibin-lin/verl-community/refs/heads/main/WeChat.JPG"><b>Wechat</b></a> | <a href="https://x.com/verl_project"><b>Twitter</b></a>
26
+
27
+ <!-- <a href=""><b>Slides</b></a> | -->
28
+ </p>
29
+
30
+ ## News
31
+ - [2025/3] We will present verl(HybridFlow) at [EuroSys 2025](https://2025.eurosys.org/). See you in in Rotterdam!
32
+ - [2025/2] verl v0.2.0.post1 is released! See [release note](https://github.com/volcengine/verl/releases/) for details.
33
+ - [2025/2] We presented verl in the [Bytedance/NVIDIA/Anyscale Ray Meetup](https://lu.ma/ji7atxux). See you in San Jose!
34
+ - [2025/1] [Doubao-1.5-pro](https://team.doubao.com/zh/special/doubao_1_5_pro) is released with SOTA-level performance on LLM & VLM. The RL scaling preview model is trained using verl, reaching OpenAI O1-level performance on math benchmarks (70.0 pass@1 on AIME).
35
+ - [2024/12] The team presented <a href="https://neurips.cc/Expo/Conferences/2024/workshop/100677">Post-training LLMs: From Algorithms to Infrastructure</a> at NeurIPS 2024. [Slides](https://github.com/eric-haibin-lin/verl-data/tree/neurips) and [video](https://neurips.cc/Expo/Conferences/2024/workshop/100677) available.
36
+ - [2024/12] verl is presented at Ray Forward 2024. Slides available [here](https://github.com/eric-haibin-lin/verl-community/blob/main/slides/Ray_Forward_2024_%E5%B7%AB%E9%94%A1%E6%96%8C.pdf).
37
+ - [2024/10] verl is presented at Ray Summit. [Youtube video](https://www.youtube.com/watch?v=MrhMcXkXvJU&list=PLzTswPQNepXntmT8jr9WaNfqQ60QwW7-U&index=37) available.
38
+ - [2024/08] HybridFlow (verl) is accepted to EuroSys 2025.
39
+
40
+ ## Key Features
41
+
42
+ - **FSDP** and **Megatron-LM** for training.
43
+ - **vLLM** and **HF Transformers** for rollout generation, **SGLang** support coming soon.
44
+ - Compatible with Hugging Face Transformers.
45
+ - Supervised fine-tuning.
46
+ - Reinforcement learning with [PPO](examples/ppo_trainer/), [GRPO](examples/grpo_trainer/), [ReMax](examples/remax_trainer/), [Reinforce++](https://verl.readthedocs.io/en/latest/examples/config.html#algorithm), [RLOO](examples/rloo_trainer/), etc.
47
+ - Support model-based reward and function-based reward (verifiable reward)
48
+ - Support vision-language models (VLMs) and [multi-modal RL](examples/grpo_trainer/run_qwen2_5_vl-7b.sh)
49
+ - Flash attention 2, [sequence packing](examples/ppo_trainer/run_qwen2-7b_seq_balance.sh), [sequence parallelism](examples/ppo_trainer/run_deepseek7b_llm_sp2.sh) support via DeepSpeed Ulysses, [LoRA](examples/sft/gsm8k/run_qwen_05_peft.sh), [Liger-kernel](examples/sft/gsm8k/run_qwen_05_sp2_liger.sh).
50
+ - Scales up to 70B models and hundreds of GPUs.
51
+ - Experiment tracking with wandb, swanlab, mlflow and tensorboard.
52
+
53
+ ## Upcoming Features
54
+ - Reward model training
55
+ - DPO training
56
+ - DeepSeek integration with Megatron v0.11
57
+ - SGLang integration
58
+
59
+ ## Getting Started
60
+
61
+ **Quickstart:**
62
+ - [Installation](https://verl.readthedocs.io/en/latest/start/install.html)
63
+ - [Quickstart](https://verl.readthedocs.io/en/latest/start/quickstart.html)
64
+ - [Programming Guide](https://verl.readthedocs.io/en/latest/hybrid_flow.html)
65
+
66
+ **Running a PPO example step-by-step:**
67
+ - Data and Reward Preparation
68
+ - [Prepare Data for Post-Training](https://verl.readthedocs.io/en/latest/preparation/prepare_data.html)
69
+ - [Implement Reward Function for Dataset](https://verl.readthedocs.io/en/latest/preparation/reward_function.html)
70
+ - Understanding the PPO Example
71
+ - [PPO Example Architecture](https://verl.readthedocs.io/en/latest/examples/ppo_code_architecture.html)
72
+ - [Config Explanation](https://verl.readthedocs.io/en/latest/examples/config.html)
73
+ - [Run GSM8K Example](https://verl.readthedocs.io/en/latest/examples/gsm8k_example.html)
74
+
75
+ **Reproducible algorithm baselines:**
76
+ - [PPO, GRPO, ReMax](https://verl.readthedocs.io/en/latest/experiment/ppo.html)
77
+
78
+ **For code explanation and advance usage (extension):**
79
+ - PPO Trainer and Workers
80
+ - [PPO Ray Trainer](https://verl.readthedocs.io/en/latest/workers/ray_trainer.html)
81
+ - [PyTorch FSDP Backend](https://verl.readthedocs.io/en/latest/workers/fsdp_workers.html)
82
+ - [Megatron-LM Backend](https://verl.readthedocs.io/en/latest/index.html)
83
+ - Advance Usage and Extension
84
+ - [Ray API design tutorial](https://verl.readthedocs.io/en/latest/advance/placement.html)
85
+ - [Extend to Other RL(HF) algorithms](https://verl.readthedocs.io/en/latest/advance/dpo_extension.html)
86
+ - [Add Models with the FSDP Backend](https://verl.readthedocs.io/en/latest/advance/fsdp_extension.html)
87
+ - [Add Models with the Megatron-LM Backend](https://verl.readthedocs.io/en/latest/advance/megatron_extension.html)
88
+ - [Deployment using Separate GPU Resources](https://github.com/volcengine/verl/tree/main/examples/split_placement)
89
+
90
+ **Blogs from the community**
91
+ - [使用verl进行GRPO分布式强化学习训练最佳实践](https://www.volcengine.com/docs/6459/1463942)
92
+ - [HybridFlow veRL 原文浅析](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/readme.md)
93
+ - [最高提升20倍吞吐量!豆包大模型团队发布全新 RLHF 框架,现已开源!](https://team.doubao.com/en/blog/%E6%9C%80%E9%AB%98%E6%8F%90%E5%8D%8720%E5%80%8D%E5%90%9E%E5%90%90%E9%87%8F-%E8%B1%86%E5%8C%85%E5%A4%A7%E6%A8%A1%E5%9E%8B%E5%9B%A2%E9%98%9F%E5%8F%91%E5%B8%83%E5%85%A8%E6%96%B0-rlhf-%E6%A1%86%E6%9E%B6-%E7%8E%B0%E5%B7%B2%E5%BC%80%E6%BA%90)
94
+
95
+ Checkout this [Jupyter Notebook](https://github.com/volcengine/verl/tree/main/examples/ppo_trainer/verl_getting_started.ipynb) to get started with PPO training with a single 24GB L4 GPU (**FREE** GPU quota provided by [Lighting Studio](https://lightning.ai/hlin-verl/studios/verl-getting-started))!
96
+
97
+ ## Performance Tuning Guide
98
+ The performance is essential for on-policy RL algorithm. We write a detailed performance tuning guide to allow people tune the performance. See [here](https://verl.readthedocs.io/en/latest/perf/perf_tuning.html) for more details.
99
+
100
+ ## vLLM v0.7 integration preview
101
+ We have released a testing version of veRL that supports vLLM>=0.7.0. Please refer to [this document](https://github.com/volcengine/verl/blob/main/docs/README_vllm0.7.md) for installation guide and more information.
102
+
103
+ ## Citation and acknowledgement
104
+
105
+ If you find the project helpful, please cite:
106
+ - [HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2)
107
+ - [A Framework for Training Large Language Models for Code Generation via Proximal Policy Optimization](https://i.cs.hku.hk/~cwu/papers/gmsheng-NL2Code24.pdf)
108
+
109
+ ```tex
110
+ @article{sheng2024hybridflow,
111
+ title = {HybridFlow: A Flexible and Efficient RLHF Framework},
112
+ author = {Guangming Sheng and Chi Zhang and Zilingfeng Ye and Xibin Wu and Wang Zhang and Ru Zhang and Yanghua Peng and Haibin Lin and Chuan Wu},
113
+ year = {2024},
114
+ journal = {arXiv preprint arXiv: 2409.19256}
115
+ }
116
+ ```
117
+
118
+ verl is inspired by the design of Nemo-Aligner, Deepspeed-chat and OpenRLHF. The project is adopted and supported by Anyscale, Bytedance, LMSys.org, Shanghai AI Lab, Tsinghua University, UC Berkeley, UCLA, UIUC, University of Hong Kong, and many more.
119
+
120
+ ## Awesome work using verl
121
+ - [TinyZero](https://github.com/Jiayi-Pan/TinyZero): a reproduction of **DeepSeek R1 Zero** recipe for reasoning tasks
122
+ - [PRIME](https://github.com/PRIME-RL/PRIME): Process reinforcement through implicit rewards
123
+ - [RAGEN](https://github.com/ZihanWang314/ragen): a general-purpose reasoning **agent** training framework
124
+ - [Logic-RL](https://github.com/Unakar/Logic-RL): a reproduction of DeepSeek R1 Zero on 2K Tiny Logic Puzzle Dataset.
125
+ - [deepscaler](https://github.com/agentica-project/deepscaler): iterative context scaling with GRPO
126
+ - [critic-rl](https://github.com/HKUNLP/critic-rl): LLM critics for code generation
127
+ - [Easy-R1](https://github.com/hiyouga/EasyR1): **Multi-modal** RL training framework
128
+ - [self-rewarding-reasoning-LLM](https://arxiv.org/pdf/2502.19613): self-rewarding and correction with **generative reward models**
129
+ - [Search-R1](https://github.com/PeterGriffinJin/Search-R1): RL with reasoning and **searching (tool-call)** interleaved LLMs
130
+ - [Code-R1](https://github.com/ganler/code-r1): Reproducing R1 for **Code** with Reliable Rewards
131
+ - [DQO](https://arxiv.org/abs/2410.09302): Enhancing multi-Step reasoning abilities of language models through direct Q-function optimization
132
+ - [FIRE](https://arxiv.org/abs/2410.21236): Flaming-hot initiation with regular execution sampling for large language models
133
+ - [ReSearch](https://github.com/Agent-RL/ReSearch): Learning to **Re**ason with **Search** for LLMs via Reinforcement Learning
134
+
135
+ ## Contribution Guide
136
+ Contributions from the community are welcome! Please checkout our [roadmap](https://github.com/volcengine/verl/issues/22) and [release plan](https://github.com/volcengine/verl/issues/354).
137
+
138
+ ### Code formatting
139
+ We use yapf (Google style) to enforce strict code formatting when reviewing PRs. To reformat you code locally, make sure you installed **latest** `yapf`
140
+ ```bash
141
+ pip3 install yapf --upgrade
142
+ ```
143
+ Then, make sure you are at top level of verl repo and run
144
+ ```bash
145
+ bash scripts/format.sh
146
+ ```
147
+ We are HIRING! Send us an [email](mailto:haibin.lin@bytedance.com) if you are interested in internship/FTE opportunities in MLSys/LLM reasoning/multimodal alignment.
deep_search/DeepResearcher/evaluate.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ export VLLM_ATTENTION_BACKEND=XFORMERS
3
+ export project_name="project_name"
4
+ export experiment_name="experiment_name"
5
+
6
+
7
+ PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
8
+ data.train_files=./data/train.parquet \
9
+ data.val_files=./data/test.parquet \
10
+ data.train_batch_size=256 \
11
+ data.max_prompt_length=30767 \
12
+ data.max_response_length=2000 \
13
+ +data.max_model_len=32768 \
14
+ data.data_writing_file=./signal/data.json \
15
+ data.signal_writing_file=./signal/signal.json \
16
+ actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \
17
+ actor_rollout_ref.model.use_remove_padding=true \
18
+ actor_rollout_ref.actor.optim.lr=1e-6 \
19
+ actor_rollout_ref.actor.ppo_mini_batch_size=4096 \
20
+ actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=2 \
21
+ actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=2 \
22
+ actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
23
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
24
+ actor_rollout_ref.rollout.max_num_batched_tokens=32768 \
25
+ actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=2 \
26
+ actor_rollout_ref.actor.use_kl_loss=true \
27
+ actor_rollout_ref.actor.use_dynamic_bsz=true \
28
+ actor_rollout_ref.actor.fsdp_config.param_offload=true \
29
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
30
+ actor_rollout_ref.ref.fsdp_config.param_offload=true \
31
+ actor_rollout_ref.actor.ppo_max_token_len_per_gpu=12288 \
32
+ actor_rollout_ref.actor.ulysses_sequence_parallel_size=4 \
33
+ critic.optim.lr=1e-5 \
34
+ critic.model.path=Qwen/Qwen2.5-7B-Instruct \
35
+ critic.ppo_micro_batch_size_per_gpu=2 \
36
+ algorithm.kl_ctrl.kl_coef=0.001 \
37
+ trainer.logger=['console','wandb'] \
38
+ trainer.project_name=${project_name} \
39
+ trainer.experiment_name=${experiment_name} \
40
+ +trainer.val_before_train=true \
41
+ trainer.default_hdfs_dir=null \
42
+ trainer.n_gpus_per_node=8 \
43
+ trainer.nnodes=1 \
44
+ trainer.save_freq=1 \
45
+ trainer.test_freq=1 \
46
+ trainer.remove_previous_ckpt_in_save=false \
47
+ agent_grpo.n=16 \
48
+ max_turns=10 \
49
+ search_engine=online_search \
50
+ trainer.total_epochs=1 2>&1 | tee ./${project_name}_${experiment_name}.log
51
+
deep_search/DeepResearcher/examples/data_preprocess/full_hh_rlhf.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ - Preprocess data and split the training set into 75% for training RM and 25% for validting RM.
16
+ - All the training data is used to train SFT and RL.
17
+ - Both chosen and rejected is used to train SFT
18
+ """
19
+ import argparse
20
+ import os
21
+
22
+ import pandas as pd
23
+ from datasets import load_dataset
24
+
25
+ from tqdm.auto import tqdm
26
+
27
+ from verl.utils.fs import copy, makedirs
28
+
29
+
30
+ def generate_sft_dataset(target_hdfs_path_dir, local_dir='~/data/full_hh_rlh/sft'):
31
+ dataset = load_dataset('Dahoas/full-hh-rlhf')
32
+ output = {'prompt': [], 'response': []}
33
+ for data in tqdm(dataset['train']):
34
+ # add chosen
35
+ output['prompt'].append(data['prompt'])
36
+ output['response'].append(data['chosen'])
37
+
38
+ # add rejection
39
+ output['prompt'].append(data['prompt'])
40
+ output['response'].append(data['rejected'])
41
+
42
+ df = pd.DataFrame(output)
43
+
44
+ local_dir = os.path.expanduser(local_dir)
45
+ os.makedirs(local_dir, exist_ok=True)
46
+
47
+ local_path = os.path.join(local_dir, 'train.parquet')
48
+
49
+ df.to_parquet(path=local_path)
50
+
51
+ if target_hdfs_path_dir is not None:
52
+ hdfs_dir = target_hdfs_path_dir + '/' + 'train.parquet'
53
+ makedirs(hdfs_dir)
54
+
55
+ copy(local_path, hdfs_dir)
56
+
57
+
58
+ def generate_rm_dataset(target_hdfs_path_dir, local_dir='~/data/full_hh_rlh/rm'):
59
+ train_dataset = load_dataset('Dahoas/full-hh-rlhf', split='train[:75%]')
60
+ test_dataset = load_dataset('Dahoas/full-hh-rlhf', split='train[-25%:]')
61
+
62
+ local_dir = os.path.expanduser(local_dir)
63
+ os.makedirs(local_dir, exist_ok=True)
64
+
65
+ for dataset, name in zip([train_dataset, test_dataset], ['train', 'test']):
66
+ output = {'prompt': [], 'chosen': [], 'rejected': []}
67
+ for data in tqdm(dataset):
68
+ # add chosen
69
+ output['prompt'].append(data['prompt'])
70
+ output['chosen'].append(data['chosen'])
71
+ output['rejected'].append(data['rejected'])
72
+
73
+ df = pd.DataFrame(output)
74
+
75
+ local_path = os.path.join(local_dir, name + '.parquet')
76
+
77
+ df.to_parquet(path=local_path)
78
+
79
+ if target_hdfs_path_dir is not None:
80
+ hdfs_dir = target_hdfs_path_dir + '/' + name + '.parquet'
81
+ makedirs(hdfs_dir)
82
+
83
+ copy(local_path, hdfs_dir)
84
+
85
+
86
+ def generate_rl_dataset(target_hdfs_path_dir, local_dir='~/data/full_hh_rlhf/rl'):
87
+ dataset = load_dataset('Dahoas/full-hh-rlhf')
88
+ train_dataset = dataset['train']
89
+
90
+ data_source = 'Dahoas/full-hh-rlhf'
91
+
92
+ # add a row to each data item that represents a unique id
93
+ def make_map_fn(split):
94
+
95
+ def process_fn(example, idx):
96
+ prompt = example.pop('prompt')
97
+ response = example.pop('response')
98
+
99
+ data = {
100
+ "data_source": data_source,
101
+ "prompt": [{
102
+ "role": "user",
103
+ "content": prompt
104
+ }],
105
+ "ability": "alignment",
106
+ "reward_model": {
107
+ "style": "model",
108
+ "ground_truth": response # should not be used
109
+ },
110
+ "extra_info": {
111
+ 'split': split,
112
+ 'index': idx
113
+ }
114
+ }
115
+ return data
116
+
117
+ return process_fn
118
+
119
+ train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
120
+ local_dir = os.path.expanduser(local_dir)
121
+ local_path = os.path.join(local_dir, 'train.parquet')
122
+ train_dataset.to_parquet(local_path)
123
+
124
+ if target_hdfs_path_dir is not None:
125
+ hdfs_dir = target_hdfs_path_dir + '/' + 'train.parquet'
126
+ makedirs(hdfs_dir)
127
+
128
+ copy(local_path, hdfs_dir)
129
+
130
+
131
+ if __name__ == '__main__':
132
+ parser = argparse.ArgumentParser()
133
+ parser.add_argument('--split', type=str, choices=['sft', 'rm', 'rl'], required=True)
134
+ parser.add_argument('--local_dir', type=str, default='~/data/full_hh_rlhf')
135
+ parser.add_argument('--hdfs_dir', type=str, required=False, default=None)
136
+
137
+ args = parser.parse_args()
138
+
139
+ if args.split == 'sft':
140
+ generate_sft_dataset(args.hdfs_dir, os.path.join(args.local_dir, args.split))
141
+ elif args.split == 'rm':
142
+ generate_rm_dataset(args.hdfs_dir, os.path.join(args.local_dir, args.split))
143
+ elif args.split == 'rl':
144
+ generate_rl_dataset(args.hdfs_dir, os.path.join(args.local_dir, args.split))
145
+ else:
146
+ raise NotImplementedError
deep_search/DeepResearcher/examples/data_preprocess/geo3k.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Preprocess the Geometry3k dataset to parquet format
16
+ """
17
+
18
+ import os
19
+ import datasets
20
+
21
+ from verl.utils.hdfs_io import copy, makedirs
22
+ import argparse
23
+
24
+ if __name__ == '__main__':
25
+ parser = argparse.ArgumentParser()
26
+ parser.add_argument('--local_dir', default='~/data/geo3k')
27
+ parser.add_argument('--hdfs_dir', default=None)
28
+
29
+ args = parser.parse_args()
30
+
31
+ data_source = 'hiyouga/geometry3k'
32
+
33
+ dataset = datasets.load_dataset(data_source)
34
+
35
+ train_dataset = dataset['train']
36
+ test_dataset = dataset['test']
37
+
38
+ instruction_following = (
39
+ r'You FIRST think about the reasoning process as an internal monologue and then provide the final answer. '
40
+ r'The reasoning process MUST BE enclosed within <think> </think> tags. The final answer MUST BE put in \boxed{}.'
41
+ )
42
+
43
+ # add a row to each data item that represents a unique id
44
+ def make_map_fn(split):
45
+
46
+ def process_fn(example, idx):
47
+ problem = example.pop('problem')
48
+ prompt = problem + ' ' + instruction_following
49
+ answer = example.pop('answer')
50
+ images = example.pop('images')
51
+
52
+ data = {
53
+ "data_source": data_source,
54
+ "prompt": [{
55
+ "role": "user",
56
+ "content": prompt,
57
+ }],
58
+ "images": images,
59
+ "ability": "math",
60
+ "reward_model": {
61
+ "style": "rule",
62
+ "ground_truth": answer
63
+ },
64
+ "extra_info": {
65
+ 'split': split,
66
+ 'index': idx,
67
+ 'answer': answer,
68
+ "question": problem,
69
+ }
70
+ }
71
+ return data
72
+
73
+ return process_fn
74
+
75
+ train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True, num_proc=8)
76
+ test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True, num_proc=8)
77
+
78
+ local_dir = args.local_dir
79
+ hdfs_dir = args.hdfs_dir
80
+
81
+ train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
82
+ test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet'))
83
+
84
+ if hdfs_dir is not None:
85
+ makedirs(hdfs_dir)
86
+ copy(src=local_dir, dst=hdfs_dir)
deep_search/DeepResearcher/examples/data_preprocess/gsm8k.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Preprocess the GSM8k dataset to parquet format
16
+ """
17
+
18
+ import re
19
+ import os
20
+ import datasets
21
+
22
+ from verl.utils.hdfs_io import copy, makedirs
23
+ import argparse
24
+
25
+
26
+ def extract_solution(solution_str):
27
+ solution = re.search("#### (\\-?[0-9\\.\\,]+)", solution_str)
28
+ assert solution is not None
29
+ final_solution = solution.group(0)
30
+ final_solution = final_solution.split('#### ')[1].replace(',', '')
31
+ return final_solution
32
+
33
+
34
+ if __name__ == '__main__':
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument('--local_dir', default='~/data/gsm8k')
37
+ parser.add_argument('--hdfs_dir', default=None)
38
+
39
+ args = parser.parse_args()
40
+
41
+ data_source = 'openai/gsm8k'
42
+
43
+ dataset = datasets.load_dataset(data_source, 'main')
44
+
45
+ train_dataset = dataset['train']
46
+ test_dataset = dataset['test']
47
+
48
+ instruction_following = "Let's think step by step and output the final answer after \"####\"."
49
+
50
+ # add a row to each data item that represents a unique id
51
+ def make_map_fn(split):
52
+
53
+ def process_fn(example, idx):
54
+ question_raw = example.pop('question')
55
+
56
+ question = question_raw + ' ' + instruction_following
57
+
58
+ answer_raw = example.pop('answer')
59
+ solution = extract_solution(answer_raw)
60
+ data = {
61
+ "data_source": data_source,
62
+ "prompt": [{
63
+ "role": "user",
64
+ "content": question,
65
+ }],
66
+ "ability": "math",
67
+ "reward_model": {
68
+ "style": "rule",
69
+ "ground_truth": solution
70
+ },
71
+ "extra_info": {
72
+ 'split': split,
73
+ 'index': idx,
74
+ 'answer': answer_raw,
75
+ "question": question_raw,
76
+ }
77
+ }
78
+ return data
79
+
80
+ return process_fn
81
+
82
+ train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
83
+ test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True)
84
+
85
+ local_dir = args.local_dir
86
+ hdfs_dir = args.hdfs_dir
87
+
88
+ train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
89
+ test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet'))
90
+
91
+ if hdfs_dir is not None:
92
+ makedirs(hdfs_dir)
93
+
94
+ copy(src=local_dir, dst=hdfs_dir)
deep_search/DeepResearcher/examples/data_preprocess/hellaswag.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Preprocess Hellaswag dataset.
16
+
17
+ """
18
+
19
+ import re
20
+ import os
21
+ import datasets
22
+
23
+ from verl.utils.hdfs_io import copy, makedirs
24
+ import argparse
25
+
26
+
27
+ def preprocess(text):
28
+ text = text.strip()
29
+ # NOTE: Brackets are artifacts of the WikiHow dataset portion of HellaSwag.
30
+ text = text.replace(" [title]", ". ")
31
+ text = re.sub("\\[.*?\\]", "", text)
32
+ text = text.replace(" ", " ")
33
+ return text
34
+
35
+
36
+ if __name__ == '__main__':
37
+ parser = argparse.ArgumentParser()
38
+ parser.add_argument('--local_dir', default='/opt/tiger/hellaswag')
39
+ parser.add_argument('--hdfs_dir', default=None)
40
+
41
+ args = parser.parse_args()
42
+
43
+ data_source = 'Rowan/hellaswag'
44
+
45
+ dataset = datasets.load_dataset(data_source, trust_remote_code=True)
46
+
47
+ train_dataset = dataset['train']
48
+ val_dataset = dataset['validation']
49
+ test_dataset = dataset['test']
50
+
51
+ instruction = 'Please complete the following sentence.\n'
52
+
53
+ def make_map_fn(split):
54
+
55
+ def process_fn(doc, idx):
56
+ ctx = doc["ctx_a"] + " " + doc["ctx_b"].capitalize()
57
+ query = preprocess(doc["activity_label"] + ": " + ctx)
58
+ choices = [preprocess(ending) for ending in doc["endings"]]
59
+ gold = int(doc["label"])
60
+
61
+ data = {
62
+ "data_source": data_source,
63
+ "prompt": [{
64
+ "role": "user",
65
+ "content": query
66
+ }],
67
+ "ability": "nlp",
68
+ "reward_model": {
69
+ "style": "model",
70
+ "eval": "multiple_choice", # using loglikelihood
71
+ "ground_truth": gold,
72
+ "choices": choices
73
+ },
74
+ "extra_info": {
75
+ 'split': split,
76
+ 'index': idx
77
+ }
78
+ }
79
+ return data
80
+
81
+ return process_fn
82
+
83
+ # filter data that doesn't have a label
84
+ train_dataset = train_dataset.filter(lambda x: len(x['label']) > 0)
85
+ val_dataset = val_dataset.filter(lambda x: len(x['label']) > 0)
86
+ test_dataset = test_dataset.filter(lambda x: len(x['label']) > 0)
87
+
88
+ train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
89
+ val_dataset = val_dataset.map(function=make_map_fn('validation'), with_indices=True)
90
+ test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True)
91
+
92
+ local_dir = args.local_dir
93
+ hdfs_dir = args.hdfs_dir
94
+
95
+ train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
96
+ val_dataset.to_parquet(os.path.join(local_dir, 'validation.parquet'))
97
+ test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet'))
98
+
99
+ if hdfs_dir is not None:
100
+ makedirs(hdfs_dir)
101
+
102
+ copy(src=local_dir, dst=hdfs_dir)
deep_search/DeepResearcher/examples/data_preprocess/math_dataset.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Preprocess the GSM8k dataset to parquet format
16
+ """
17
+
18
+ import os
19
+ import datasets
20
+
21
+ from verl.utils.hdfs_io import copy, makedirs
22
+ import argparse
23
+
24
+ from verl.utils.reward_score.math import remove_boxed, last_boxed_only_string
25
+
26
+
27
+ def extract_solution(solution_str):
28
+ return remove_boxed(last_boxed_only_string(solution_str))
29
+
30
+
31
+ if __name__ == '__main__':
32
+ parser = argparse.ArgumentParser()
33
+ parser.add_argument('--local_dir', default='~/data/math')
34
+ parser.add_argument('--hdfs_dir', default=None)
35
+
36
+ args = parser.parse_args()
37
+
38
+ # 'lighteval/MATH' is no longer available on huggingface.
39
+ # Use mirror repo: DigitalLearningGmbH/MATH-lighteval
40
+ data_source = 'DigitalLearningGmbH/MATH-lighteval'
41
+ print(f"Loading the {data_source} dataset from huggingface...", flush=True)
42
+ dataset = datasets.load_dataset(data_source, trust_remote_code=True)
43
+
44
+ train_dataset = dataset['train']
45
+ test_dataset = dataset['test']
46
+
47
+ instruction_following = "Let's think step by step and output the final answer within \\boxed{}."
48
+
49
+ # add a row to each data item that represents a unique id
50
+ def make_map_fn(split):
51
+
52
+ def process_fn(example, idx):
53
+ question = example.pop('problem')
54
+
55
+ question = question + ' ' + instruction_following
56
+
57
+ answer = example.pop('solution')
58
+ solution = extract_solution(answer)
59
+ data = {
60
+ "data_source": data_source,
61
+ "prompt": [{
62
+ "role": "user",
63
+ "content": question
64
+ }],
65
+ "ability": "math",
66
+ "reward_model": {
67
+ "style": "rule",
68
+ "ground_truth": solution
69
+ },
70
+ "extra_info": {
71
+ 'split': split,
72
+ 'index': idx
73
+ }
74
+ }
75
+ return data
76
+
77
+ return process_fn
78
+
79
+ train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
80
+ test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True)
81
+
82
+ local_dir = args.local_dir
83
+ hdfs_dir = args.hdfs_dir
84
+
85
+ train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
86
+ test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet'))
87
+
88
+ if hdfs_dir is not None:
89
+ makedirs(hdfs_dir)
90
+
91
+ copy(src=local_dir, dst=hdfs_dir)
deep_search/DeepResearcher/examples/grpo_trainer/run_deepseek7b_llm.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ python3 -m verl.trainer.main_ppo \
4
+ algorithm.adv_estimator=grpo \
5
+ data.train_files=$HOME/data/gsm8k/train.parquet \
6
+ data.val_files=$HOME/data/gsm8k/test.parquet \
7
+ data.train_batch_size=1024 \
8
+ data.max_prompt_length=512 \
9
+ data.max_response_length=1024 \
10
+ actor_rollout_ref.model.path=deepseek-ai/deepseek-llm-7b-chat \
11
+ actor_rollout_ref.actor.optim.lr=1e-6 \
12
+ actor_rollout_ref.model.use_remove_padding=True \
13
+ actor_rollout_ref.actor.ppo_mini_batch_size=256 \
14
+ actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=80 \
15
+ actor_rollout_ref.actor.use_kl_loss=True \
16
+ actor_rollout_ref.actor.kl_loss_coef=0.001 \
17
+ actor_rollout_ref.actor.kl_loss_type=low_var_kl \
18
+ actor_rollout_ref.model.enable_gradient_checkpointing=True \
19
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
20
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
21
+ actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=160 \
22
+ actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
23
+ actor_rollout_ref.rollout.name=vllm \
24
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
25
+ actor_rollout_ref.rollout.n=5 \
26
+ actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=160 \
27
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
28
+ algorithm.kl_ctrl.kl_coef=0.001 \
29
+ trainer.critic_warmup=0 \
30
+ trainer.logger=['console'] \
31
+ trainer.project_name='verl_grpo_example_gsm8k' \
32
+ trainer.experiment_name='deepseek_llm_7b_function_rm' \
33
+ trainer.n_gpus_per_node=8 \
34
+ trainer.nnodes=1 \
35
+ trainer.save_freq=-1 \
36
+ trainer.test_freq=5 \
37
+ trainer.total_epochs=15 $@
deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2-7b_seq_balance.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ export VLLM_ATTENTION_BACKEND=XFORMERS
4
+
5
+ python3 -m verl.trainer.main_ppo \
6
+ algorithm.adv_estimator=grpo \
7
+ data.train_files=$HOME/data/gsm8k/train.parquet \
8
+ data.val_files=$HOME/data/gsm8k/test.parquet \
9
+ data.train_batch_size=1024 \
10
+ data.max_prompt_length=512 \
11
+ data.max_response_length=1024 \
12
+ actor_rollout_ref.model.path=Qwen/Qwen2-7B-Instruct \
13
+ actor_rollout_ref.actor.optim.lr=1e-6 \
14
+ actor_rollout_ref.model.use_remove_padding=True \
15
+ actor_rollout_ref.actor.ppo_mini_batch_size=256 \
16
+ actor_rollout_ref.actor.use_dynamic_bsz=True \
17
+ actor_rollout_ref.actor.ppo_max_token_len_per_gpu=24000 \
18
+ actor_rollout_ref.actor.use_kl_loss=True \
19
+ actor_rollout_ref.actor.kl_loss_coef=0.001 \
20
+ actor_rollout_ref.actor.kl_loss_type=low_var_kl \
21
+ actor_rollout_ref.model.enable_gradient_checkpointing=True \
22
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
23
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
24
+ actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
25
+ actor_rollout_ref.rollout.name=vllm \
26
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
27
+ actor_rollout_ref.rollout.n=5 \
28
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
29
+ algorithm.kl_ctrl.kl_coef=0.001 \
30
+ trainer.critic_warmup=0 \
31
+ trainer.logger=['console','wandb'] \
32
+ trainer.project_name='verl_grpo_example_gsm8k' \
33
+ trainer.experiment_name='qwen2_7b_function_rm_kl1e-3' \
34
+ +trainer.val_before_train=False \
35
+ trainer.n_gpus_per_node=8 \
36
+ trainer.nnodes=1 \
37
+ trainer.save_freq=-1 \
38
+ trainer.test_freq=5 \
39
+ trainer.total_epochs=15 $@
deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2_5_0_5b_seq_balance.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ export VLLM_ATTENTION_BACKEND=XFORMERS
4
+
5
+ python3 -m verl.trainer.main_ppo \
6
+ algorithm.adv_estimator=grpo \
7
+ data.train_files=./data/gsm8k/train.parquet \
8
+ data.val_files=./data/gsm8k/test.parquet \
9
+ data.train_batch_size=1024 \
10
+ data.max_prompt_length=512 \
11
+ data.max_response_length=1024 \
12
+ actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \
13
+ actor_rollout_ref.actor.optim.lr=1e-6 \
14
+ actor_rollout_ref.model.use_remove_padding=True \
15
+ actor_rollout_ref.actor.ppo_mini_batch_size=256 \
16
+ actor_rollout_ref.actor.use_dynamic_bsz=True \
17
+ actor_rollout_ref.actor.ppo_max_token_len_per_gpu=24000 \
18
+ actor_rollout_ref.actor.use_kl_loss=True \
19
+ actor_rollout_ref.actor.kl_loss_coef=0.001 \
20
+ actor_rollout_ref.actor.kl_loss_type=low_var_kl \
21
+ actor_rollout_ref.model.enable_gradient_checkpointing=True \
22
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
23
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
24
+ actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
25
+ actor_rollout_ref.rollout.name=vllm \
26
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
27
+ actor_rollout_ref.rollout.n=5 \
28
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
29
+ algorithm.kl_ctrl.kl_coef=0.001 \
30
+ trainer.critic_warmup=0 \
31
+ trainer.logger=['console','wandb'] \
32
+ trainer.project_name='verl_grpo_example_gsm8k' \
33
+ trainer.experiment_name='qwen2.5_0.5b_function_rm_kl1e-3' \
34
+ +trainer.val_before_train=False \
35
+ trainer.n_gpus_per_node=8 \
36
+ trainer.nnodes=1 \
37
+ trainer.save_freq=1 \
38
+ trainer.test_freq=1 \
39
+ trainer.total_epochs=1 $@
deep_search/DeepResearcher/examples/ray/tutorial.ipynb ADDED
@@ -0,0 +1,958 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "0ddc582b",
6
+ "metadata": {},
7
+ "source": [
8
+ "# VeRL Ray API Tutorial"
9
+ ]
10
+ },
11
+ {
12
+ "cell_type": "markdown",
13
+ "id": "71fe3b94",
14
+ "metadata": {},
15
+ "source": [
16
+ "## Chapter 1: Ray Basics"
17
+ ]
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "execution_count": 144,
22
+ "id": "1347d381",
23
+ "metadata": {
24
+ "tags": []
25
+ },
26
+ "outputs": [],
27
+ "source": [
28
+ "import os"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "execution_count": 145,
34
+ "id": "e75b9d44",
35
+ "metadata": {
36
+ "tags": []
37
+ },
38
+ "outputs": [],
39
+ "source": [
40
+ "import ray\n",
41
+ "import torch\n",
42
+ "import warnings\n",
43
+ "warnings.filterwarnings('ignore')"
44
+ ]
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "execution_count": 146,
49
+ "id": "2e90ae00",
50
+ "metadata": {
51
+ "tags": []
52
+ },
53
+ "outputs": [
54
+ {
55
+ "name": "stderr",
56
+ "output_type": "stream",
57
+ "text": [
58
+ "2024-11-01 17:27:19,132\tINFO worker.py:1752 -- Started a local Ray instance.\n"
59
+ ]
60
+ },
61
+ {
62
+ "data": {
63
+ "application/vnd.jupyter.widget-view+json": {
64
+ "model_id": "9cc9d2ccbdfb48918c8fd6cd13a0807a",
65
+ "version_major": 2,
66
+ "version_minor": 0
67
+ },
68
+ "text/html": [
69
+ "<div class=\"lm-Widget p-Widget lm-Panel p-Panel jp-Cell-outputWrapper\">\n",
70
+ " <div style=\"margin-left: 50px;display: flex;flex-direction: row;align-items: center\">\n",
71
+ " <div class=\"jp-RenderedHTMLCommon\" style=\"display: flex; flex-direction: row;\">\n",
72
+ " <svg viewBox=\"0 0 567 224\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\" style=\"height: 3em;\">\n",
73
+ " <g clip-path=\"url(#clip0_4338_178347)\">\n",
74
+ " <path d=\"M341.29 165.561H355.29L330.13 129.051C345.63 123.991 354.21 112.051 354.21 94.2307C354.21 71.3707 338.72 58.1807 311.88 58.1807H271V165.561H283.27V131.661H311.8C314.25 131.661 316.71 131.501 319.01 131.351L341.25 165.561H341.29ZM283.29 119.851V70.0007H311.82C331.3 70.0007 342.34 78.2907 342.34 94.5507C342.34 111.271 331.34 119.861 311.82 119.861L283.29 119.851ZM451.4 138.411L463.4 165.561H476.74L428.74 58.1807H416L367.83 165.561H380.83L392.83 138.411H451.4ZM446.19 126.601H398L422 72.1407L446.24 126.601H446.19ZM526.11 128.741L566.91 58.1807H554.35L519.99 114.181L485.17 58.1807H472.44L514.01 129.181V165.541H526.13V128.741H526.11Z\" fill=\"var(--jp-ui-font-color0)\"/>\n",
75
+ " <path d=\"M82.35 104.44C84.0187 97.8827 87.8248 92.0678 93.1671 87.9146C98.5094 83.7614 105.083 81.5067 111.85 81.5067C118.617 81.5067 125.191 83.7614 130.533 87.9146C135.875 92.0678 139.681 97.8827 141.35 104.44H163.75C164.476 101.562 165.622 98.8057 167.15 96.2605L127.45 56.5605C121.071 60.3522 113.526 61.6823 106.235 60.3005C98.9443 58.9187 92.4094 54.9203 87.8602 49.0574C83.3109 43.1946 81.0609 35.8714 81.5332 28.4656C82.0056 21.0599 85.1679 14.0819 90.4252 8.8446C95.6824 3.60726 102.672 0.471508 110.08 0.0272655C117.487 -0.416977 124.802 1.86091 130.647 6.4324C136.493 11.0039 140.467 17.5539 141.821 24.8501C143.175 32.1463 141.816 39.6859 138 46.0505L177.69 85.7505C182.31 82.9877 187.58 81.4995 192.962 81.4375C198.345 81.3755 203.648 82.742 208.33 85.3976C213.012 88.0532 216.907 91.9029 219.616 96.5544C222.326 101.206 223.753 106.492 223.753 111.875C223.753 117.258 222.326 122.545 219.616 127.197C216.907 131.848 213.012 135.698 208.33 138.353C203.648 141.009 198.345 142.375 192.962 142.313C187.58 142.251 182.31 140.763 177.69 138L138 177.7C141.808 184.071 143.155 191.614 141.79 198.91C140.424 206.205 136.44 212.75 130.585 217.313C124.731 221.875 117.412 224.141 110.004 223.683C102.596 223.226 95.6103 220.077 90.3621 214.828C85.1139 209.58 81.9647 202.595 81.5072 195.187C81.0497 187.779 83.3154 180.459 87.878 174.605C92.4405 168.751 98.9853 164.766 106.281 163.401C113.576 162.035 121.119 163.383 127.49 167.19L167.19 127.49C165.664 124.941 164.518 122.182 163.79 119.3H141.39C139.721 125.858 135.915 131.673 130.573 135.826C125.231 139.98 118.657 142.234 111.89 142.234C105.123 142.234 98.5494 139.98 93.2071 135.826C87.8648 131.673 84.0587 125.858 82.39 119.3H60C58.1878 126.495 53.8086 132.78 47.6863 136.971C41.5641 141.163 34.1211 142.972 26.7579 142.059C19.3947 141.146 12.6191 137.574 7.70605 132.014C2.79302 126.454 0.0813599 119.29 0.0813599 111.87C0.0813599 104.451 2.79302 97.2871 7.70605 91.7272C12.6191 86.1673 19.3947 82.5947 26.7579 81.6817C34.1211 80.7686 41.5641 82.5781 47.6863 86.7696C53.8086 90.9611 58.1878 97.2456 60 104.44H82.35ZM100.86 204.32C103.407 206.868 106.759 208.453 110.345 208.806C113.93 209.159 117.527 208.258 120.522 206.256C123.517 204.254 125.725 201.276 126.771 197.828C127.816 194.38 127.633 190.677 126.253 187.349C124.874 184.021 122.383 181.274 119.205 179.577C116.027 177.88 112.359 177.337 108.826 178.042C105.293 178.746 102.113 180.654 99.8291 183.44C97.5451 186.226 96.2979 189.718 96.3 193.32C96.2985 195.364 96.7006 197.388 97.4831 199.275C98.2656 201.163 99.4132 202.877 100.86 204.32ZM204.32 122.88C206.868 120.333 208.453 116.981 208.806 113.396C209.159 109.811 208.258 106.214 206.256 103.219C204.254 100.223 201.275 98.0151 197.827 96.97C194.38 95.9249 190.676 96.1077 187.348 97.4873C184.02 98.8669 181.274 101.358 179.577 104.536C177.879 107.714 177.337 111.382 178.041 114.915C178.746 118.448 180.653 121.627 183.439 123.911C186.226 126.195 189.717 127.443 193.32 127.44C195.364 127.443 197.388 127.042 199.275 126.259C201.163 125.476 202.878 124.328 204.32 122.88ZM122.88 19.4205C120.333 16.8729 116.981 15.2876 113.395 14.9347C109.81 14.5817 106.213 15.483 103.218 17.4849C100.223 19.4868 98.0146 22.4654 96.9696 25.9131C95.9245 29.3608 96.1073 33.0642 97.4869 36.3922C98.8665 39.7202 101.358 42.4668 104.535 44.1639C107.713 45.861 111.381 46.4036 114.914 45.6992C118.447 44.9949 121.627 43.0871 123.911 40.301C126.195 37.515 127.442 34.0231 127.44 30.4205C127.44 28.3772 127.038 26.3539 126.255 24.4664C125.473 22.5788 124.326 20.8642 122.88 19.4205ZM19.42 100.86C16.8725 103.408 15.2872 106.76 14.9342 110.345C14.5813 113.93 15.4826 117.527 17.4844 120.522C19.4863 123.518 22.4649 125.726 25.9127 126.771C29.3604 127.816 33.0638 127.633 36.3918 126.254C39.7198 124.874 42.4664 122.383 44.1635 119.205C45.8606 116.027 46.4032 112.359 45.6988 108.826C44.9944 105.293 43.0866 102.114 40.3006 99.8296C37.5145 97.5455 34.0227 96.2983 30.42 96.3005C26.2938 96.3018 22.337 97.9421 19.42 100.86ZM100.86 100.86C98.3125 103.408 96.7272 106.76 96.3742 110.345C96.0213 113.93 96.9226 117.527 98.9244 120.522C100.926 123.518 103.905 125.726 107.353 126.771C110.8 127.816 114.504 127.633 117.832 126.254C121.16 124.874 123.906 122.383 125.604 119.205C127.301 116.027 127.843 112.359 127.139 108.826C126.434 105.293 124.527 102.114 121.741 99.8296C118.955 97.5455 115.463 96.2983 111.86 96.3005C109.817 96.299 107.793 96.701 105.905 97.4835C104.018 98.2661 102.303 99.4136 100.86 100.86Z\" fill=\"#00AEEF\"/>\n",
76
+ " </g>\n",
77
+ " <defs>\n",
78
+ " <clipPath id=\"clip0_4338_178347\">\n",
79
+ " <rect width=\"566.93\" height=\"223.75\" fill=\"white\"/>\n",
80
+ " </clipPath>\n",
81
+ " </defs>\n",
82
+ " </svg>\n",
83
+ "</div>\n",
84
+ "\n",
85
+ " <table class=\"jp-RenderedHTMLCommon\" style=\"border-collapse: collapse;color: var(--jp-ui-font-color1);font-size: var(--jp-ui-font-size1);\">\n",
86
+ " <tr>\n",
87
+ " <td style=\"text-align: left\"><b>Python version:</b></td>\n",
88
+ " <td style=\"text-align: left\"><b>3.9.2</b></td>\n",
89
+ " </tr>\n",
90
+ " <tr>\n",
91
+ " <td style=\"text-align: left\"><b>Ray version:</b></td>\n",
92
+ " <td style=\"text-align: left\"><b>2.10.0</b></td>\n",
93
+ " </tr>\n",
94
+ " \n",
95
+ "</table>\n",
96
+ "\n",
97
+ " </div>\n",
98
+ "</div>\n"
99
+ ],
100
+ "text/plain": [
101
+ "RayContext(dashboard_url='', python_version='3.9.2', ray_version='2.10.0', ray_commit='09abba26b5bf2707639bb637c208d062a47b46f6')"
102
+ ]
103
+ },
104
+ "execution_count": 146,
105
+ "metadata": {},
106
+ "output_type": "execute_result"
107
+ },
108
+ {
109
+ "name": "stdout",
110
+ "output_type": "stream",
111
+ "text": [
112
+ "\u001b[36m(GPUAccumulator pid=224400)\u001b[0m rank 0, value: tensor([1.], device='cuda:0')\n",
113
+ "\u001b[36m(GPUAccumulator pid=225234)\u001b[0m rank 2, value: tensor([3.], device='cuda:0')\n",
114
+ "\u001b[36m(GPUAccumulator pid=225607)\u001b[0m rank 0, value: tensor([2.], device='cuda:0')\n",
115
+ "\u001b[36m(GPUAccumulator pid=226423)\u001b[0m rank 1, value: tensor([3.], device='cuda:0')\n",
116
+ "\u001b[36m(GPUAccumulator pid=226857)\u001b[0m rank 3, value: tensor([6.], device='cuda:0')\n",
117
+ "\u001b[36m(GPUAccumulatorDecorator pid=227475)\u001b[0m 10\n",
118
+ "\u001b[36m(GPUAccumulatorDecorator pid=227475)\u001b[0m rank 0, value: tensor([10.], device='cuda:0')\n",
119
+ "\u001b[36m(GPUAccumulatorDecorator pid=227655)\u001b[0m rank 1, value: tensor([11.], device='cuda:0')\n"
120
+ ]
121
+ }
122
+ ],
123
+ "source": [
124
+ "# Build a local ray cluster. The head node and worker node are on this machine\n",
125
+ "ray.init()"
126
+ ]
127
+ },
128
+ {
129
+ "cell_type": "markdown",
130
+ "id": "a127e4e4",
131
+ "metadata": {},
132
+ "source": [
133
+ "Implement an Accumulator class."
134
+ ]
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "execution_count": 147,
139
+ "id": "20e7b9a3",
140
+ "metadata": {
141
+ "tags": []
142
+ },
143
+ "outputs": [],
144
+ "source": [
145
+ "@ray.remote\n",
146
+ "class Accumulator:\n",
147
+ " def __init__(self):\n",
148
+ " self.value = 0\n",
149
+ " \n",
150
+ " def add(self, x):\n",
151
+ " self.value += x\n",
152
+ " \n",
153
+ " def get_value(self):\n",
154
+ " return self.value"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "execution_count": 148,
160
+ "id": "3b80098c",
161
+ "metadata": {
162
+ "tags": []
163
+ },
164
+ "outputs": [],
165
+ "source": [
166
+ "# Instantiate an accumulator. Accumulator can be viewed as a process, acting as an RPC service.\n",
167
+ "accumulator = Accumulator.remote()"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": 149,
173
+ "id": "b14b1009",
174
+ "metadata": {
175
+ "tags": []
176
+ },
177
+ "outputs": [
178
+ {
179
+ "name": "stdout",
180
+ "output_type": "stream",
181
+ "text": [
182
+ "0\n"
183
+ ]
184
+ }
185
+ ],
186
+ "source": [
187
+ "value_ref = accumulator.get_value.remote() # Check the current value. Note that this function returns immediately and does not actually wait for the remote execution to complete.\n",
188
+ "# Get the value\n",
189
+ "value = ray.get(value_ref)\n",
190
+ "print(value)"
191
+ ]
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "execution_count": 150,
196
+ "id": "513a84b3",
197
+ "metadata": {
198
+ "tags": []
199
+ },
200
+ "outputs": [
201
+ {
202
+ "name": "stdout",
203
+ "output_type": "stream",
204
+ "text": [
205
+ "10\n"
206
+ ]
207
+ }
208
+ ],
209
+ "source": [
210
+ "# Accumulate, then check the result.\n",
211
+ "accumulator.add.remote(10) # Similarly, the 'add' here will return immediately.\n",
212
+ "new_value = ray.get(accumulator.get_value.remote())\n",
213
+ "print(new_value)"
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "markdown",
218
+ "id": "3c332fe0",
219
+ "metadata": {},
220
+ "source": [
221
+ "## Chapter 2: Resource Pool and RayWorkerGroup\n",
222
+ "In the previous example, it was a simple single-process worker. \n",
223
+ "In this example, we implement a worker with a GPU and form a RayWorkerGroup. Within this RayWorkerGroup, we implement a simple operation of an accumulator."
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": 151,
229
+ "id": "04229afb",
230
+ "metadata": {
231
+ "tags": []
232
+ },
233
+ "outputs": [],
234
+ "source": [
235
+ "from verl.single_controller.ray.base import RayResourcePool, RayClassWithInitArgs, RayWorkerGroup, merge_resource_pool\n",
236
+ "from verl.single_controller.base import Worker"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "execution_count": 152,
242
+ "id": "0d0dbd58",
243
+ "metadata": {
244
+ "tags": []
245
+ },
246
+ "outputs": [],
247
+ "source": [
248
+ "resource_pool = RayResourcePool([4], use_gpu=True)"
249
+ ]
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "execution_count": 153,
254
+ "id": "68f6838a",
255
+ "metadata": {
256
+ "tags": []
257
+ },
258
+ "outputs": [],
259
+ "source": [
260
+ "@ray.remote\n",
261
+ "class GPUAccumulator(Worker):\n",
262
+ "\n",
263
+ " def __init__(self) -> None:\n",
264
+ " super().__init__()\n",
265
+ " # The initial value of each rank is the same as the rank\n",
266
+ " self.value = torch.zeros(size=(1,), device='cuda') + self.rank\n",
267
+ "\n",
268
+ " def add(self, x):\n",
269
+ " self.value += x\n",
270
+ " print(f'rank {self.rank}, value: {self.value}')\n",
271
+ " return self.value.cpu()\n"
272
+ ]
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "execution_count": 154,
277
+ "id": "23aad8fe",
278
+ "metadata": {
279
+ "tags": []
280
+ },
281
+ "outputs": [
282
+ {
283
+ "name": "stdout",
284
+ "output_type": "stream",
285
+ "text": [
286
+ "[tensor([1.]), tensor([2.]), tensor([3.]), tensor([4.])]\n"
287
+ ]
288
+ }
289
+ ],
290
+ "source": [
291
+ "# Each worker's initial value is its rank, and then each rank's value is incremented by 1, so the values obtained on each rank are [1, 2, 3, 4]\n",
292
+ "class_with_args = RayClassWithInitArgs(cls=GPUAccumulator)\n",
293
+ "worker_group = RayWorkerGroup(resource_pool, class_with_args)\n",
294
+ "print(worker_group.execute_all_sync('add', x=[1,1,1,1]))"
295
+ ]
296
+ },
297
+ {
298
+ "cell_type": "markdown",
299
+ "id": "e6705284",
300
+ "metadata": {},
301
+ "source": [
302
+ "The principle of parameter passing: The input parameter is a list of length world_size, where each element in the list is dispatched respectively to each worker in the RayWorkerGroup. \n",
303
+ "The return parameter is also a list, corresponding to the return value of each worker."
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "markdown",
308
+ "id": "d25c2412",
309
+ "metadata": {},
310
+ "source": [
311
+ "### GPU Resource Sharing"
312
+ ]
313
+ },
314
+ {
315
+ "cell_type": "markdown",
316
+ "id": "f74f6d24",
317
+ "metadata": {},
318
+ "source": [
319
+ "RayWorkerGroups mapped to the same resource pool share the GPU. In this example, we implement three resource pools: the first occupies 4 GPUs, the second also occupies 4 GPUs, and the last occupies all 8 GPUs. Among them, the first resource pool reuses the resource pool mentioned above."
320
+ ]
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "execution_count": 155,
325
+ "id": "49f9c06f",
326
+ "metadata": {
327
+ "tags": []
328
+ },
329
+ "outputs": [],
330
+ "source": [
331
+ "# Create a new resource pool and then merge the newly created resource pool with the previous one.\n",
332
+ "resource_pool_1 = RayResourcePool([4], use_gpu=True, name_prefix='a')\n",
333
+ "resource_pool_merge = merge_resource_pool(resource_pool, resource_pool_1)"
334
+ ]
335
+ },
336
+ {
337
+ "cell_type": "code",
338
+ "execution_count": 156,
339
+ "id": "05c2e305",
340
+ "metadata": {
341
+ "tags": []
342
+ },
343
+ "outputs": [],
344
+ "source": [
345
+ "# Establish a RayWorkerGroup on the newly created resource pool.\n",
346
+ "worker_group_1 = RayWorkerGroup(resource_pool_1, class_with_args)\n",
347
+ "worker_group_merge = RayWorkerGroup(resource_pool_merge, class_with_args)"
348
+ ]
349
+ },
350
+ {
351
+ "cell_type": "code",
352
+ "execution_count": 157,
353
+ "id": "6b9b13f4",
354
+ "metadata": {
355
+ "tags": []
356
+ },
357
+ "outputs": [
358
+ {
359
+ "name": "stdout",
360
+ "output_type": "stream",
361
+ "text": [
362
+ "[tensor([2.]), tensor([3.]), tensor([4.]), tensor([5.])]\n"
363
+ ]
364
+ }
365
+ ],
366
+ "source": [
367
+ "# Run 'add' on the second set of 4 GPUs; the result should be [2, 3, 4, 5].\n",
368
+ "output_1 = worker_group_1.execute_all_sync('add', x=[2,2,2,2])\n",
369
+ "print(output_1)"
370
+ ]
371
+ },
372
+ {
373
+ "cell_type": "code",
374
+ "execution_count": 158,
375
+ "id": "d856d030",
376
+ "metadata": {
377
+ "tags": []
378
+ },
379
+ "outputs": [
380
+ {
381
+ "name": "stdout",
382
+ "output_type": "stream",
383
+ "text": [
384
+ "[tensor([3.]), tensor([4.]), tensor([5.]), tensor([6.]), tensor([7.]), tensor([8.]), tensor([9.]), tensor([10.])]\n"
385
+ ]
386
+ }
387
+ ],
388
+ "source": [
389
+ "# Run 'add' on the merged set of 8 GPUs; the result should be [3, 4, 5, 6, 7, 8, 9, 10].\n",
390
+ "output_merge = worker_group_merge.execute_all_sync('add', x=[3,3,3,3,3,3,3,3])\n",
391
+ "print(output_merge)"
392
+ ]
393
+ },
394
+ {
395
+ "cell_type": "code",
396
+ "execution_count": 159,
397
+ "id": "33a4628c",
398
+ "metadata": {
399
+ "tags": []
400
+ },
401
+ "outputs": [
402
+ {
403
+ "name": "stdout",
404
+ "output_type": "stream",
405
+ "text": [
406
+ "4 4 8\n"
407
+ ]
408
+ }
409
+ ],
410
+ "source": [
411
+ "print(worker_group.world_size, worker_group_1.world_size, worker_group_merge.world_size)"
412
+ ]
413
+ },
414
+ {
415
+ "cell_type": "markdown",
416
+ "id": "3df19d13",
417
+ "metadata": {},
418
+ "source": [
419
+ "## Chapter 3: Data Dispatch, Execution and Collection"
420
+ ]
421
+ },
422
+ {
423
+ "cell_type": "markdown",
424
+ "id": "acb22d9d",
425
+ "metadata": {},
426
+ "source": [
427
+ "In the above example, we used the `execute_all_sync` function in the RayWorkerGroup to dispatch data from the driver to each worker. This is very inconvenient for coding. \n",
428
+ "In this chapter, we use the form of function decorators to allow RayWorkerGroup to directly call functions written in the Worker, and to greatly simplify parameter passing."
429
+ ]
430
+ },
431
+ {
432
+ "cell_type": "code",
433
+ "execution_count": 160,
434
+ "id": "35237432",
435
+ "metadata": {
436
+ "tags": []
437
+ },
438
+ "outputs": [],
439
+ "source": [
440
+ "from verl.single_controller.base.decorator import register, Dispatch, Execute"
441
+ ]
442
+ },
443
+ {
444
+ "cell_type": "code",
445
+ "execution_count": 161,
446
+ "id": "88b8ba3b",
447
+ "metadata": {
448
+ "tags": []
449
+ },
450
+ "outputs": [],
451
+ "source": [
452
+ "@ray.remote\n",
453
+ "class GPUAccumulatorDecorator(Worker):\n",
454
+ "\n",
455
+ " def __init__(self) -> None:\n",
456
+ " super().__init__()\n",
457
+ " # The initial value of each rank is the same as the rank\n",
458
+ " self.value = torch.zeros(size=(1,), device='cuda') + self.rank\n",
459
+ " \n",
460
+ " # map from a single input to all the worker\n",
461
+ " @register(Dispatch.ONE_TO_ALL)\n",
462
+ " def add(self, x):\n",
463
+ " print(x)\n",
464
+ " self.value = self.value + x\n",
465
+ " print(f'rank {self.rank}, value: {self.value}')\n",
466
+ " return self.value.cpu()"
467
+ ]
468
+ },
469
+ {
470
+ "cell_type": "code",
471
+ "execution_count": 162,
472
+ "id": "eddaa043",
473
+ "metadata": {
474
+ "tags": []
475
+ },
476
+ "outputs": [],
477
+ "source": [
478
+ "class_with_args = RayClassWithInitArgs(cls=GPUAccumulatorDecorator)\n",
479
+ "gpu_accumulator_decorator = RayWorkerGroup(resource_pool_merge, class_with_args)"
480
+ ]
481
+ },
482
+ {
483
+ "cell_type": "code",
484
+ "execution_count": 163,
485
+ "id": "10087c91",
486
+ "metadata": {
487
+ "tags": []
488
+ },
489
+ "outputs": [
490
+ {
491
+ "name": "stdout",
492
+ "output_type": "stream",
493
+ "text": [
494
+ "[tensor([10.]), tensor([11.]), tensor([12.]), tensor([13.]), tensor([14.]), tensor([15.]), tensor([16.]), tensor([17.])]\n"
495
+ ]
496
+ }
497
+ ],
498
+ "source": [
499
+ "# As we can see, 10 is automatically dispatched to each Worker in this RayWorkerGroup.\n",
500
+ "print(gpu_accumulator_decorator.add(x=10))"
501
+ ]
502
+ },
503
+ {
504
+ "cell_type": "markdown",
505
+ "id": "540ee6ad",
506
+ "metadata": {},
507
+ "source": [
508
+ "### Custom Dispatch, Collection\n",
509
+ "Users can customize `dispatch` and `collection` function. You only need to write the `dispatch_fn` and `collect_fn` functions yourself. We also support executing RPC only on rank_zero, with specific examples provided below."
510
+ ]
511
+ },
512
+ {
513
+ "cell_type": "code",
514
+ "execution_count": 164,
515
+ "id": "8e041270",
516
+ "metadata": {
517
+ "tags": []
518
+ },
519
+ "outputs": [],
520
+ "source": [
521
+ "from verl.single_controller.base.decorator import register, Dispatch, collect_all_to_all, Execute"
522
+ ]
523
+ },
524
+ {
525
+ "cell_type": "code",
526
+ "execution_count": 165,
527
+ "id": "43b5be31",
528
+ "metadata": {
529
+ "tags": []
530
+ },
531
+ "outputs": [],
532
+ "source": [
533
+ "def two_to_all_dispatch_fn(worker_group, *args, **kwargs):\n",
534
+ " \"\"\"\n",
535
+ " Assume the input is a list of 2. Duplicate the input interleaved and pass to each worker.\n",
536
+ " \"\"\"\n",
537
+ " for arg in args:\n",
538
+ " assert len(arg) == 2\n",
539
+ " for i in range(worker_group.world_size - 2):\n",
540
+ " arg.append(arg[i % 2])\n",
541
+ " for k, v in kwargs.items():\n",
542
+ " assert len(v) == 2\n",
543
+ " for i in range(worker_group.world_size - 2):\n",
544
+ " v.append(v[i % 2])\n",
545
+ " return args, kwargs\n",
546
+ "\n",
547
+ "\n",
548
+ "@ray.remote\n",
549
+ "class TestActor(Worker):\n",
550
+ " # TODO: pass *args and **kwargs is bug prone and not very convincing\n",
551
+ " def __init__(self, x) -> None:\n",
552
+ " super().__init__()\n",
553
+ " self._x = x\n",
554
+ "\n",
555
+ " def foo(self, y):\n",
556
+ " return self._x + y\n",
557
+ "\n",
558
+ " @register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.RANK_ZERO)\n",
559
+ " def foo_rank_zero(self, x, y):\n",
560
+ " return self._x + y + x\n",
561
+ "\n",
562
+ " @register(dispatch_mode={'dispatch_fn': two_to_all_dispatch_fn, 'collect_fn': collect_all_to_all})\n",
563
+ " def foo_custom(self, x, y):\n",
564
+ " return self._x + y + x"
565
+ ]
566
+ },
567
+ {
568
+ "cell_type": "code",
569
+ "execution_count": 166,
570
+ "id": "83ec6609",
571
+ "metadata": {
572
+ "tags": []
573
+ },
574
+ "outputs": [],
575
+ "source": [
576
+ "class_with_args = RayClassWithInitArgs(cls=TestActor, x=2)\n",
577
+ "worker_group = RayWorkerGroup(resource_pool, class_with_args)"
578
+ ]
579
+ },
580
+ {
581
+ "cell_type": "code",
582
+ "execution_count": 167,
583
+ "id": "62c58d8a",
584
+ "metadata": {
585
+ "tags": []
586
+ },
587
+ "outputs": [],
588
+ "source": [
589
+ "output_ref = worker_group.foo_custom(x=[1, 2], y=[5, 6])\n",
590
+ "assert output_ref == [8, 10, 8, 10]\n",
591
+ "\n",
592
+ "output_ref = worker_group.foo_rank_zero(x=1, y=2)\n",
593
+ "assert output_ref == 5"
594
+ ]
595
+ },
596
+ {
597
+ "cell_type": "code",
598
+ "execution_count": 168,
599
+ "id": "14689353",
600
+ "metadata": {
601
+ "tags": []
602
+ },
603
+ "outputs": [
604
+ {
605
+ "name": "stdout",
606
+ "output_type": "stream",
607
+ "text": [
608
+ "8\n"
609
+ ]
610
+ }
611
+ ],
612
+ "source": [
613
+ "print(gpu_accumulator_decorator.world_size)"
614
+ ]
615
+ },
616
+ {
617
+ "cell_type": "code",
618
+ "execution_count": 169,
619
+ "id": "2c80bbf4",
620
+ "metadata": {
621
+ "tags": []
622
+ },
623
+ "outputs": [],
624
+ "source": [
625
+ "# Shutdown ray cluster\n",
626
+ "ray.shutdown()"
627
+ ]
628
+ },
629
+ {
630
+ "cell_type": "markdown",
631
+ "id": "a5c8151c",
632
+ "metadata": {},
633
+ "source": [
634
+ "## Chapter 4: NVMegatronRayWorkerGroup"
635
+ ]
636
+ },
637
+ {
638
+ "cell_type": "markdown",
639
+ "id": "cd5680e9",
640
+ "metadata": {},
641
+ "source": [
642
+ "Due to the Ray issue, we can only support max_colocate_count=1 in RayResourcePool for now. \n",
643
+ "This means that each GPU can only have one process.\n",
644
+ "We can support max_colocate > 1 when applying this pull request: https://github.com/ray-project/ray/pull/44385"
645
+ ]
646
+ },
647
+ {
648
+ "cell_type": "markdown",
649
+ "id": "92724419",
650
+ "metadata": {},
651
+ "source": [
652
+ "Therefore, we need to restart the ray and initialize a new resource_pool to demonstrate the **NVMegatronRayWorkerGroup**"
653
+ ]
654
+ },
655
+ {
656
+ "cell_type": "code",
657
+ "execution_count": null,
658
+ "id": "9b038538",
659
+ "metadata": {
660
+ "tags": []
661
+ },
662
+ "outputs": [],
663
+ "source": [
664
+ "# Build a local ray cluster. The head node and worker node are on this machine\n",
665
+ "ray.init()"
666
+ ]
667
+ },
668
+ {
669
+ "cell_type": "markdown",
670
+ "id": "ebfd8798",
671
+ "metadata": {},
672
+ "source": [
673
+ "Finally, we implement a `NVMegatronRayWorkerGroup`, within which we create a Megatron and then run a tensor parallel (tp) split Llama mlp layer. Here, we use a complex dispatch mode, `Megatron_COMPUTE`. This dispatch mode assumes that user passes the data partitioned by DP dimension. The data is dispatched to all tp/pp ranks within the same dp group, and ultimately only collects output data from tp=0 and the last pp. In this way, for users that only write code on the driver, the Megatron behind the RPC becomes transparent."
674
+ ]
675
+ },
676
+ {
677
+ "cell_type": "code",
678
+ "execution_count": 171,
679
+ "id": "5a032154",
680
+ "metadata": {
681
+ "tags": []
682
+ },
683
+ "outputs": [
684
+ {
685
+ "name": "stdout",
686
+ "output_type": "stream",
687
+ "text": [
688
+ "/opt/tiger/Megatron-LM\n",
689
+ "/opt/tiger/Megatron-LM/megatron/__init__.py\n"
690
+ ]
691
+ }
692
+ ],
693
+ "source": [
694
+ "import os\n",
695
+ "import sys\n",
696
+ "import site\n",
697
+ "\n",
698
+ "\n",
699
+ "current_pythonpath = os.environ.get('PYTHONPATH', '')\n",
700
+ "\n",
701
+ "new_path = '/opt/tiger/Megatron-LM'\n",
702
+ "\n",
703
+ "if current_pythonpath:\n",
704
+ " new_pythonpath = f'{new_path}:{current_pythonpath}'\n",
705
+ "else:\n",
706
+ " new_pythonpath = new_path\n",
707
+ "\n",
708
+ "os.environ['PYTHONPATH'] = new_pythonpath\n",
709
+ "\n",
710
+ "print(new_path)\n",
711
+ "sys.path.append(new_path)\n",
712
+ "\n",
713
+ "import megatron\n",
714
+ "print(megatron.__file__)"
715
+ ]
716
+ },
717
+ {
718
+ "cell_type": "code",
719
+ "execution_count": 172,
720
+ "id": "8c84cd5a",
721
+ "metadata": {
722
+ "tags": []
723
+ },
724
+ "outputs": [],
725
+ "source": [
726
+ "from verl.single_controller.base.decorator import register, Dispatch, Execute\n",
727
+ "from verl.single_controller.ray.megatron import NVMegatronRayWorkerGroup\n",
728
+ "from verl.single_controller.base.megatron.worker import MegatronWorker\n",
729
+ "from verl.single_controller.ray.base import RayResourcePool, RayClassWithInitArgs, RayWorkerGroup\n",
730
+ "from omegaconf import OmegaConf\n",
731
+ "from megatron.core import parallel_state as mpu"
732
+ ]
733
+ },
734
+ {
735
+ "cell_type": "code",
736
+ "execution_count": 173,
737
+ "id": "1b1debcc",
738
+ "metadata": {
739
+ "tags": []
740
+ },
741
+ "outputs": [],
742
+ "source": [
743
+ "resource_pool = RayResourcePool([4], use_gpu=True, max_colocate_count=1)"
744
+ ]
745
+ },
746
+ {
747
+ "cell_type": "code",
748
+ "execution_count": 174,
749
+ "id": "bccbe081",
750
+ "metadata": {
751
+ "tags": []
752
+ },
753
+ "outputs": [],
754
+ "source": [
755
+ "@ray.remote\n",
756
+ "class MLPLayerWorker(MegatronWorker):\n",
757
+ " def __init__(self):\n",
758
+ " super().__init__()\n",
759
+ " rank = int(os.environ['LOCAL_RANK'])\n",
760
+ " torch.distributed.init_process_group(backend=\"nccl\")\n",
761
+ " torch.cuda.set_device(rank)\n",
762
+ "\n",
763
+ " mpu.initialize_model_parallel(\n",
764
+ " tensor_model_parallel_size=4,\n",
765
+ " pipeline_model_parallel_size=1,\n",
766
+ " virtual_pipeline_model_parallel_size=None,\n",
767
+ " pipeline_model_parallel_split_rank=None,\n",
768
+ " use_sharp=False,\n",
769
+ " context_parallel_size=1,\n",
770
+ " expert_model_parallel_size=1,\n",
771
+ " nccl_communicator_config_path=None,\n",
772
+ " )\n",
773
+ " from megatron.core import tensor_parallel\n",
774
+ " tensor_parallel.model_parallel_cuda_manual_seed(10)\n",
775
+ "\n",
776
+ "\n",
777
+ " @register(Dispatch.ONE_TO_ALL)\n",
778
+ " def init_model(self, config):\n",
779
+ " from omegaconf import OmegaConf\n",
780
+ " from verl.utils.megatron_utils import init_model_parallel_config\n",
781
+ " from verl.models.llama.megatron.layers import ParallelLlamaMLP\n",
782
+ " megatron_config = OmegaConf.create({\n",
783
+ " 'sequence_parallel': False,\n",
784
+ " 'param_dtype': 'fp32',\n",
785
+ " 'tensor_model_parallel_size': mpu.get_tensor_model_parallel_world_size(),\n",
786
+ " 'pipeline_model_parallel_rank': mpu.get_pipeline_model_parallel_rank(),\n",
787
+ " 'pipeline_model_parallel_size': mpu.get_pipeline_model_parallel_world_size(),\n",
788
+ " 'virtual_pipeline_model_parallel_rank': mpu.get_virtual_pipeline_model_parallel_rank(),\n",
789
+ " 'virtual_pipeline_model_parallel_size': mpu.get_virtual_pipeline_model_parallel_world_size()\n",
790
+ " })\n",
791
+ "\n",
792
+ " megatron_config = init_model_parallel_config(megatron_config)\n",
793
+ " self.parallel_layer = ParallelLlamaMLP(config=config, megatron_config=megatron_config)\n",
794
+ " \n",
795
+ " @register(Dispatch.ONE_TO_ALL)\n",
796
+ " def get_weights(self):\n",
797
+ " output = {}\n",
798
+ " for key, val in self.parallel_layer.named_parameters():\n",
799
+ " output[key] = val\n",
800
+ " return output\n",
801
+ " \n",
802
+ " @register(Dispatch.MEGATRON_COMPUTE)\n",
803
+ " def run_layer(self, x):\n",
804
+ " x = x.to('cuda')\n",
805
+ " y = self.parallel_layer(x)\n",
806
+ " return y"
807
+ ]
808
+ },
809
+ {
810
+ "cell_type": "code",
811
+ "execution_count": 175,
812
+ "id": "a655271d",
813
+ "metadata": {
814
+ "tags": []
815
+ },
816
+ "outputs": [],
817
+ "source": [
818
+ "layer_cls = RayClassWithInitArgs(cls=MLPLayerWorker)\n",
819
+ "layer_worker_group = NVMegatronRayWorkerGroup(resource_pool=resource_pool,\n",
820
+ " ray_cls_with_init=layer_cls,\n",
821
+ " )\n"
822
+ ]
823
+ },
824
+ {
825
+ "cell_type": "code",
826
+ "execution_count": 176,
827
+ "id": "f105ebee",
828
+ "metadata": {
829
+ "tags": []
830
+ },
831
+ "outputs": [
832
+ {
833
+ "name": "stdout",
834
+ "output_type": "stream",
835
+ "text": [
836
+ "4 4 1 1\n"
837
+ ]
838
+ }
839
+ ],
840
+ "source": [
841
+ "print(layer_worker_group.world_size, layer_worker_group.tp_size, layer_worker_group.pp_size, layer_worker_group.dp_size)"
842
+ ]
843
+ },
844
+ {
845
+ "cell_type": "code",
846
+ "execution_count": 177,
847
+ "id": "38655091",
848
+ "metadata": {
849
+ "tags": []
850
+ },
851
+ "outputs": [],
852
+ "source": [
853
+ "ffn_hidden_size = 11008\n",
854
+ "batch_size = 16\n",
855
+ "seq_len = 2048\n",
856
+ "hidden_size = 4096\n",
857
+ "\n",
858
+ "config = OmegaConf.create({\n",
859
+ " 'hidden_size': hidden_size,\n",
860
+ " 'intermediate_size': ffn_hidden_size,\n",
861
+ " 'hidden_act': 'silu',\n",
862
+ " 'pretraining_tp': 1,\n",
863
+ " 'tp': layer_worker_group.tp_size,\n",
864
+ "})"
865
+ ]
866
+ },
867
+ {
868
+ "cell_type": "code",
869
+ "execution_count": 178,
870
+ "id": "a026efca",
871
+ "metadata": {
872
+ "tags": []
873
+ },
874
+ "outputs": [],
875
+ "source": [
876
+ "x = torch.rand(size=(seq_len, batch_size, hidden_size), dtype=torch.float32)"
877
+ ]
878
+ },
879
+ {
880
+ "cell_type": "code",
881
+ "execution_count": 179,
882
+ "id": "f5fcaf13",
883
+ "metadata": {
884
+ "tags": []
885
+ },
886
+ "outputs": [
887
+ {
888
+ "data": {
889
+ "text/plain": [
890
+ "[None, None, None, None]"
891
+ ]
892
+ },
893
+ "execution_count": 179,
894
+ "metadata": {},
895
+ "output_type": "execute_result"
896
+ }
897
+ ],
898
+ "source": [
899
+ "layer_worker_group.init_model(config)"
900
+ ]
901
+ },
902
+ {
903
+ "cell_type": "code",
904
+ "execution_count": 180,
905
+ "id": "3f5cc9b4",
906
+ "metadata": {
907
+ "tags": []
908
+ },
909
+ "outputs": [
910
+ {
911
+ "name": "stdout",
912
+ "output_type": "stream",
913
+ "text": [
914
+ "torch.Size([2048, 16, 4096])\n"
915
+ ]
916
+ }
917
+ ],
918
+ "source": [
919
+ "output = layer_worker_group.run_layer([x]) # This must be a list of size 1, ensuring that the input equals the data parallel (dp).\n",
920
+ "print(output[0].shape)"
921
+ ]
922
+ },
923
+ {
924
+ "cell_type": "code",
925
+ "execution_count": 181,
926
+ "id": "49792210",
927
+ "metadata": {
928
+ "tags": []
929
+ },
930
+ "outputs": [],
931
+ "source": [
932
+ "# Shutdown ray cluster\n",
933
+ "ray.shutdown()"
934
+ ]
935
+ }
936
+ ],
937
+ "metadata": {
938
+ "kernelspec": {
939
+ "display_name": "Python 3 (ipykernel)",
940
+ "language": "python",
941
+ "name": "python3"
942
+ },
943
+ "language_info": {
944
+ "codemirror_mode": {
945
+ "name": "ipython",
946
+ "version": 3
947
+ },
948
+ "file_extension": ".py",
949
+ "mimetype": "text/x-python",
950
+ "name": "python",
951
+ "nbconvert_exporter": "python",
952
+ "pygments_lexer": "ipython3",
953
+ "version": "3.9.2"
954
+ }
955
+ },
956
+ "nbformat": 4,
957
+ "nbformat_minor": 5
958
+ }
deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-3b_seq_balance.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ export HF_DATASETS_OFFLINE=1
4
+ export TRANSFORMERS_OFFLINE=1
5
+
6
+ export VLLM_ATTENTION_BACKEND=XFORMERS
7
+
8
+ python3 -m verl.trainer.main_ppo \
9
+ algorithm.adv_estimator=remax \
10
+ data.train_files=$HOME/data/gsm8k/train.parquet \
11
+ data.val_files=$HOME/data/gsm8k/test.parquet \
12
+ data.train_batch_size=512 \
13
+ data.max_prompt_length=512 \
14
+ data.max_response_length=1024 \
15
+ actor_rollout_ref.model.path=Qwen/Qwen2.5-3B-Instruct \
16
+ actor_rollout_ref.actor.optim.lr=1e-6 \
17
+ actor_rollout_ref.model.use_remove_padding=True \
18
+ actor_rollout_ref.actor.ppo_mini_batch_size=128 \
19
+ actor_rollout_ref.actor.use_dynamic_bsz=True \
20
+ actor_rollout_ref.actor.ppo_max_token_len_per_gpu=30000 \
21
+ actor_rollout_ref.actor.use_kl_loss=True \
22
+ actor_rollout_ref.actor.kl_loss_coef=0.001 \
23
+ actor_rollout_ref.actor.kl_loss_type=low_var_kl \
24
+ actor_rollout_ref.model.enable_gradient_checkpointing=True \
25
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
26
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
27
+ actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
28
+ actor_rollout_ref.rollout.name=vllm \
29
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.8 \
30
+ actor_rollout_ref.rollout.n=4 \
31
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
32
+ algorithm.kl_ctrl.kl_coef=0.001 \
33
+ trainer.critic_warmup=0 \
34
+ trainer.logger=['console','wandb'] \
35
+ trainer.project_name='verl_remax_example_gsm8k' \
36
+ trainer.experiment_name='qwen2.5_3b_function_rm_kl1e-3' \
37
+ +trainer.val_before_train=False \
38
+ trainer.n_gpus_per_node=8 \
39
+ trainer.nnodes=1 \
40
+ trainer.save_freq=-1 \
41
+ trainer.test_freq=5 \
42
+ trainer.total_epochs=5 $@
deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-7b_seq_balance.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ export HF_DATASETS_OFFLINE=1
4
+ export TRANSFORMERS_OFFLINE=1
5
+
6
+ export VLLM_ATTENTION_BACKEND=XFORMERS
7
+
8
+ python3 -m verl.trainer.main_ppo \
9
+ algorithm.adv_estimator=remax \
10
+ data.train_files=$HOME/data/gsm8k/train.parquet \
11
+ data.val_files=$HOME/data/gsm8k/test.parquet \
12
+ data.train_batch_size=1024 \
13
+ data.max_prompt_length=512 \
14
+ data.max_response_length=1024 \
15
+ actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \
16
+ actor_rollout_ref.actor.optim.lr=1e-6 \
17
+ actor_rollout_ref.model.use_remove_padding=True \
18
+ actor_rollout_ref.actor.ppo_mini_batch_size=256 \
19
+ actor_rollout_ref.actor.use_dynamic_bsz=True \
20
+ actor_rollout_ref.actor.ppo_max_token_len_per_gpu=24000 \
21
+ actor_rollout_ref.actor.use_kl_loss=True \
22
+ actor_rollout_ref.actor.kl_loss_coef=0.001 \
23
+ actor_rollout_ref.actor.kl_loss_type=low_var_kl \
24
+ actor_rollout_ref.model.enable_gradient_checkpointing=True \
25
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
26
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
27
+ actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
28
+ actor_rollout_ref.rollout.name=vllm \
29
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.8 \
30
+ actor_rollout_ref.rollout.n=4 \
31
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
32
+ algorithm.kl_ctrl.kl_coef=0.001 \
33
+ trainer.critic_warmup=0 \
34
+ trainer.logger=['console','wandb'] \
35
+ trainer.project_name='verl_remax_example_gsm8k' \
36
+ trainer.experiment_name='qwen2.5_7b_function_rm_kl1e-3' \
37
+ +trainer.val_before_train=False \
38
+ trainer.n_gpus_per_node=8 \
39
+ trainer.nnodes=1 \
40
+ trainer.save_freq=-1 \
41
+ trainer.test_freq=5 \
42
+ trainer.total_epochs=10 $@
deep_search/DeepResearcher/examples/rloo_trainer/run_qwen2-7b.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ export VLLM_ATTENTION_BACKEND=XFORMERS
4
+
5
+ python3 -m verl.trainer.main_ppo \
6
+ algorithm.adv_estimator=rloo \
7
+ data.train_files=$HOME/data/gsm8k/train.parquet \
8
+ data.val_files=$HOME/data/gsm8k/test.parquet \
9
+ data.train_batch_size=1024 \
10
+ data.max_prompt_length=512 \
11
+ data.max_response_length=1024 \
12
+ actor_rollout_ref.model.path=Qwen/Qwen2-7B-Instruct \
13
+ actor_rollout_ref.actor.optim.lr=1e-6 \
14
+ actor_rollout_ref.model.use_remove_padding=True \
15
+ actor_rollout_ref.actor.ppo_mini_batch_size=256 \
16
+ actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=80 \
17
+ actor_rollout_ref.actor.use_kl_loss=True \
18
+ actor_rollout_ref.actor.kl_loss_coef=0.001 \
19
+ actor_rollout_ref.actor.kl_loss_type=low_var_kl \
20
+ actor_rollout_ref.model.enable_gradient_checkpointing=True \
21
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
22
+ actor_rollout_ref.actor.fsdp_config.grad_offload=False \
23
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
24
+ actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=160 \
25
+ actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
26
+ actor_rollout_ref.rollout.name=vllm \
27
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
28
+ actor_rollout_ref.rollout.n=5 \
29
+ actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=160 \
30
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
31
+ algorithm.kl_ctrl.kl_coef=0.001 \
32
+ trainer.critic_warmup=0 \
33
+ trainer.logger=['console','wandb'] \
34
+ trainer.project_name='verl_rloo_example_gsm8k' \
35
+ trainer.experiment_name='qwen2_7b_function_rm' \
36
+ trainer.n_gpus_per_node=8 \
37
+ trainer.nnodes=1 \
38
+ trainer.save_freq=-1 \
39
+ trainer.test_freq=5 \
40
+ trainer.total_epochs=15 $@
deep_search/DeepResearcher/examples/sft/gsm8k/run_deepseek_6b7.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ if [ "$#" -lt 2 ]; then
4
+ echo "Usage: run_deepseek_6b7.sh <nproc_per_node> <save_path> [other_configs...]"
5
+ exit 1
6
+ fi
7
+
8
+ nproc_per_node=$1
9
+ save_path=$2
10
+
11
+ # Shift the arguments so $@ refers to the rest
12
+ shift 2
13
+
14
+ torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \
15
+ -m verl.trainer.fsdp_sft_trainer \
16
+ data.train_files=$HOME/data/gsm8k/train.parquet \
17
+ data.val_files=$HOME/data/gsm8k/test.parquet \
18
+ data.prompt_key=extra_info \
19
+ data.response_key=extra_info \
20
+ +data.prompt_dict_keys=['question'] \
21
+ +data.response_dict_keys=['answer'] \
22
+ data.micro_batch_size_per_gpu=4 \
23
+ model.partial_pretrain=deepseek-ai/deepseek-coder-6.7b-instruct \
24
+ trainer.default_local_dir=$save_path \
25
+ trainer.project_name=gsm8k-sft \
26
+ trainer.experiment_name=gsm8k-sft-deepseek-coder-6.7b-instruct \
27
+ trainer.total_epochs=4 \
28
+ trainer.logger=['console','wandb'] \
29
+ trainer.default_hdfs_dir=null $@
deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_2b.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tested with 2 & 4 GPUs
2
+
3
+ set -x
4
+
5
+ if [ "$#" -lt 2 ]; then
6
+ echo "Usage: run_gemma_2b.sh <nproc_per_node> <save_path> [other_configs...]"
7
+ exit 1
8
+ fi
9
+
10
+ nproc_per_node=$1
11
+ save_path=$2
12
+
13
+ # Shift the arguments so $@ refers to the rest
14
+ shift 2
15
+
16
+ torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \
17
+ -m verl.trainer.fsdp_sft_trainer \
18
+ data.train_files=$HOME/data/gsm8k/train.parquet \
19
+ data.val_files=$HOME/data/gsm8k/test.parquet \
20
+ data.prompt_key=extra_info \
21
+ data.response_key=extra_info \
22
+ +data.prompt_dict_keys=['question'] \
23
+ +data.response_dict_keys=['answer'] \
24
+ data.micro_batch_size_per_gpu=4 \
25
+ model.partial_pretrain=google/gemma-2b-it \
26
+ trainer.default_local_dir=$save_path \
27
+ trainer.project_name=gsm8k-sft \
28
+ trainer.experiment_name=gsm8k-sft-gemma-2b-it \
29
+ trainer.total_epochs=2 \
30
+ trainer.logger=['console','wandb'] \
31
+ trainer.default_hdfs_dir=null $@
deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_7b.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ if [ "$#" -lt 2 ]; then
4
+ echo "Usage: run_gemma_7b.sh <nproc_per_node> <save_path> [other_configs...]"
5
+ exit 1
6
+ fi
7
+
8
+ nproc_per_node=$1
9
+ save_path=$2
10
+
11
+ # Shift the arguments so $@ refers to the rest
12
+ shift 2
13
+
14
+ torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \
15
+ -m verl.trainer.fsdp_sft_trainer \
16
+ data.train_files=$HOME/data/gsm8k/train.parquet \
17
+ data.val_files=$HOME/data/gsm8k/test.parquet \
18
+ data.prompt_key=prompt \
19
+ data.response_key=answer \
20
+ data.micro_batch_size_per_gpu=4 \
21
+ model.partial_pretrain=google/gemma-1.1-7b-it \
22
+ trainer.default_local_dir=$save_path \
23
+ trainer.project_name=gsm8k-sft \
24
+ trainer.experiment_name=gsm8k-sft-gemma-1.1-7b-it \
25
+ trainer.total_epochs=4 \
26
+ trainer.logger=['console','wandb'] \
27
+ trainer.default_hdfs_dir=null $@
deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_peft.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tested with 2 & 4 GPUs
2
+
3
+ set -x
4
+
5
+ if [ "$#" -lt 2 ]; then
6
+ echo "Usage: run_qwen_05_peft.sh <nproc_per_node> <save_path> [other_configs...]"
7
+ exit 1
8
+ fi
9
+
10
+ nproc_per_node=$1
11
+ save_path=$2
12
+
13
+ # Shift the arguments so $@ refers to the rest
14
+ shift 2
15
+
16
+ torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \
17
+ -m verl.trainer.fsdp_sft_trainer \
18
+ data.train_files=$HOME/data/gsm8k/train.parquet \
19
+ data.val_files=$HOME/data/gsm8k/test.parquet \
20
+ data.prompt_key=extra_info \
21
+ data.response_key=extra_info \
22
+ optim.lr=1e-4 \
23
+ +data.prompt_dict_keys=['question'] \
24
+ +data.response_dict_keys=['answer'] \
25
+ data.micro_batch_size_per_gpu=4 \
26
+ model.partial_pretrain=Qwen/Qwen2.5-0.5B-Instruct \
27
+ trainer.default_local_dir=$save_path \
28
+ trainer.project_name=gsm8k-sft \
29
+ trainer.experiment_name=gsm8k-sft-qwen-2.5-0.5b-instruct \
30
+ trainer.logger=['console'] \
31
+ trainer.total_epochs=1 \
32
+ trainer.default_hdfs_dir=null $@ \
33
+ model.lora_rank=32\
34
+ model.lora_alpha=16 \
35
+ model.target_modules=all-linear
36
+
37
+ # Or you can do this:
38
+ # model.target_modules=[q_proj,v_proj] \
deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ if [ "$#" -lt 2 ]; then
4
+ echo "Usage: run_qwen_05_sp2.sh <nproc_per_node> <save_path> [other_configs...]"
5
+ exit 1
6
+ fi
7
+
8
+ nproc_per_node=$1
9
+ save_path=$2
10
+
11
+ # Shift the arguments so $@ refers to the rest
12
+ shift 2
13
+
14
+ torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \
15
+ -m verl.trainer.fsdp_sft_trainer \
16
+ data.train_files=$HOME/data/gsm8k/train.parquet \
17
+ data.val_files=$HOME/data/gsm8k/test.parquet \
18
+ data.prompt_key=extra_info \
19
+ data.response_key=extra_info \
20
+ optim.lr=1e-4 \
21
+ +data.prompt_dict_keys=['question'] \
22
+ +data.response_dict_keys=['answer'] \
23
+ data.micro_batch_size=4 \
24
+ model.partial_pretrain=Qwen/Qwen2.5-0.5B-Instruct \
25
+ trainer.default_local_dir=$save_path \
26
+ trainer.project_name=gsm8k-sft \
27
+ trainer.experiment_name=gsm8k-sft-qwen-2.5-0.5b-instruct-sp2 \
28
+ trainer.logger=['console'] \
29
+ trainer.total_training_steps=1 \
30
+ trainer.default_hdfs_dir=null $@ \
31
+ ulysses_sequence_parallel_size=2 \
32
+ use_remove_padding=true
deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2_liger.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ if [ "$#" -lt 2 ]; then
4
+ echo "Usage: run_qwen_05_sp2.sh <nproc_per_node> <save_path> [other_configs...]"
5
+ exit 1
6
+ fi
7
+
8
+ nproc_per_node=$1
9
+ save_path=$2
10
+
11
+ # Shift the arguments so $@ refers to the rest
12
+ shift 2
13
+
14
+ torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \
15
+ -m verl.trainer.fsdp_sft_trainer \
16
+ data.train_files=$HOME/data/gsm8k/train.parquet \
17
+ data.val_files=$HOME/data/gsm8k/test.parquet \
18
+ data.prompt_key=extra_info \
19
+ data.response_key=extra_info \
20
+ optim.lr=1e-4 \
21
+ +data.prompt_dict_keys=['question'] \
22
+ +data.response_dict_keys=['answer'] \
23
+ data.micro_batch_size=4 \
24
+ model.partial_pretrain=Qwen/Qwen2.5-0.5B-Instruct \
25
+ model.use_liger=True \
26
+ trainer.default_local_dir=$save_path \
27
+ trainer.project_name=gsm8k-sft \
28
+ trainer.experiment_name=gsm8k-sft-qwen-2.5-0.5b-instruct-sp2-liger \
29
+ trainer.logger=['console'] \
30
+ trainer.default_hdfs_dir=null $@ \
31
+ ulysses_sequence_parallel_size=2 \
32
+ use_remove_padding=true
deep_search/DeepResearcher/examples/split_placement/README.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Split Placement Example
2
+ Here we introduce how to run the naive implementation of the split placement of PPO algorithm.
3
+ We will release the complete version of flexible placement in the near future.
4
+
5
+ For quickstart, you can only follow Step 2 to modify the code and then follow Step 4 to execute the split placement example.
6
+
7
+ ### Step 1: Placing the models to different GPUs
8
+ Specify the placement and resource allocation. In the example, we place the actor and reference in the first half of the GPUs while map the critic and reward model (if any) to the second half of the GPUs.
9
+ ```python
10
+ actor_rollout_ref_pool_id = 'actor_rollout_ref_pool'
11
+ critic_pool_id = 'critic_pool'
12
+ if config.trainer.nnodes // 2 == 0 and config.trainer.n_gpus_per_node // 2 > 0:
13
+ resource_pool_spec = {
14
+ actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes,
15
+ critic_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes,
16
+ }
17
+ else:
18
+ resource_pool_spec = {
19
+ actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2),
20
+ critic_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2),
21
+ }
22
+ print(f'resource_pool_spec: {resource_pool_spec}')
23
+ mapping = {
24
+ Role.ActorRollout: actor_rollout_ref_pool_id,
25
+ Role.Critic: critic_pool_id,
26
+ Role.RefPolicy: actor_rollout_ref_pool_id,
27
+ }
28
+ mapping[Role.RewardModel] = critic_pool_id
29
+ ```
30
+
31
+ ### Step 2: Make the models executed asynchronously
32
+ Based on the model placement, we need to make the models executed asynchronously.
33
+
34
+ To do so, you need to turn off the `blocking` flag (i.e., `blocking=False`) in our decorator of some model operations.
35
+ For example, we hope the actor update and critic update can be executed in parallel, then we need to make the following modification in `fsdp_workers.py`
36
+
37
+ ```
38
+ @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO, blocking=False)
39
+ def update_actor(self, data: DataProto):
40
+ ...
41
+
42
+ @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO, blocking=False)
43
+ def update_critic(self, data: DataProto):
44
+ ...
45
+ ```
46
+
47
+ We can also parallelize the computation of `ref_log_prob` and `values` and `rewards` in the split placement. For simplicity of the tutorial, we don't do this in this example.
48
+
49
+ ### Step 3: Execute these operation in parallel in the single controller process
50
+ To implement the parallel execution of the actor and critic update, the only thing we need to modify in the `ray_trainer.py` is to `get` the concurrent `futures` on the single controller process.
51
+
52
+ ```python
53
+ critic_output = critic_output.get()
54
+ actor_output = actor_output.get()
55
+ ```
56
+
57
+ ### Step 4: Run the split placement example
58
+
59
+ ```
60
+ bash run_deepseek7b_llm.sh
61
+ ```
deep_search/DeepResearcher/examples/split_placement/config/ppo_trainer_split.yaml ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ data:
2
+ tokenizer: null
3
+ train_files: ~/data/rlhf/gsm8k/train.parquet
4
+ val_files: ~/data/rlhf/gsm8k/test.parquet
5
+ prompt_key: prompt
6
+ max_prompt_length: 512
7
+ max_response_length: 512
8
+ train_batch_size: 1024
9
+ val_batch_size: null # DEPRECATED: Validation datasets are sent to inference engines as a whole batch, which will schedule the memory themselves
10
+ return_raw_input_ids: False # This should be set to true when the tokenizer between policy and rm differs
11
+ return_raw_chat: False
12
+ shuffle: True
13
+
14
+ actor_rollout_ref:
15
+ hybrid_engine: True
16
+ model:
17
+ path: ~/models/deepseek-llm-7b-chat
18
+ external_lib: null
19
+ override_config: { }
20
+ enable_gradient_checkpointing: True
21
+ use_remove_padding: False
22
+ actor:
23
+ strategy: fsdp # This is for backward-compatibility
24
+ ppo_mini_batch_size: 256
25
+ ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu
26
+ ppo_micro_batch_size_per_gpu: null
27
+ use_dynamic_bsz: False
28
+ ppo_max_token_len_per_gpu: 16384 # n * ${data.max_prompt_length} + ${data.max_response_length}
29
+ grad_clip: 1.0
30
+ clip_ratio: 0.2
31
+ entropy_coeff: 0.001
32
+ use_kl_loss: False # True for GRPO
33
+ kl_loss_coef: 0.001 # for grpo
34
+ kl_loss_type: low_var_kl # for grpo
35
+ ppo_epochs: 1
36
+ shuffle: False
37
+ ulysses_sequence_parallel_size: 1 # sp size
38
+ optim:
39
+ lr: 1e-6
40
+ lr_warmup_steps_ratio: 0. # the total steps will be injected during runtime
41
+ min_lr_ratio: null # only useful for warmup with cosine
42
+ warmup_style: constant # select from constant/cosine
43
+ total_training_steps: -1 # must be override by program
44
+ fsdp_config:
45
+ wrap_policy:
46
+ # transformer_layer_cls_to_wrap: None
47
+ min_num_params: 0
48
+ param_offload: False
49
+ optimizer_offload: False
50
+ fsdp_size: -1
51
+ ref:
52
+ fsdp_config:
53
+ param_offload: False
54
+ wrap_policy:
55
+ # transformer_layer_cls_to_wrap: None
56
+ min_num_params: 0
57
+ log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu
58
+ log_prob_micro_batch_size_per_gpu: null
59
+ log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}
60
+ log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}
61
+ ulysses_sequence_parallel_size: ${actor_rollout_ref.actor.ulysses_sequence_parallel_size} # sp size
62
+ rollout:
63
+ name: vllm
64
+ temperature: 1.0
65
+ top_k: -1 # 0 for hf rollout, -1 for vllm rollout
66
+ top_p: 1
67
+ prompt_length: ${data.max_prompt_length} # not use for opensource
68
+ response_length: ${data.max_response_length}
69
+ # for vllm rollout
70
+ dtype: bfloat16 # should align with FSDP
71
+ gpu_memory_utilization: 0.5
72
+ ignore_eos: False
73
+ enforce_eager: True
74
+ free_cache_engine: True
75
+ load_format: dummy_dtensor
76
+ tensor_model_parallel_size: 2
77
+ max_num_batched_tokens: 8192
78
+ max_num_seqs: 1024
79
+ log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu
80
+ log_prob_micro_batch_size_per_gpu: null
81
+ log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}
82
+ log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}
83
+ disable_log_stats: True
84
+ enable_chunked_prefill: True # could get higher throughput
85
+ # for hf rollout
86
+ do_sample: True
87
+ # number of responses (i.e. num sample times)
88
+ n: 1 # > 1 for grpo
89
+
90
+ critic:
91
+ strategy: fsdp
92
+ optim:
93
+ lr: 1e-5
94
+ lr_warmup_steps_ratio: 0. # the total steps will be injected during runtime
95
+ min_lr_ratio: null # only useful for warmup with cosine
96
+ warmup_style: constant # select from constant/cosine
97
+ total_training_steps: -1 # must be override by program
98
+ model:
99
+ path: ~/models/deepseek-llm-7b-chat
100
+ tokenizer_path: ${actor_rollout_ref.model.path}
101
+ override_config: { }
102
+ external_lib: ${actor_rollout_ref.model.external_lib}
103
+ enable_gradient_checkpointing: True
104
+ use_remove_padding: False
105
+ fsdp_config:
106
+ param_offload: False
107
+ optimizer_offload: False
108
+ wrap_policy:
109
+ # transformer_layer_cls_to_wrap: None
110
+ min_num_params: 0
111
+ fsdp_size: -1
112
+ ppo_mini_batch_size: ${actor_rollout_ref.actor.ppo_mini_batch_size}
113
+ ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu
114
+ ppo_micro_batch_size_per_gpu: null
115
+ forward_micro_batch_size: ${critic.ppo_micro_batch_size}
116
+ forward_micro_batch_size_per_gpu: ${critic.ppo_micro_batch_size_per_gpu}
117
+ use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}
118
+ ppo_max_token_len_per_gpu: 32768 # (${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}) * 2
119
+ forward_max_token_len_per_gpu: ${critic.ppo_max_token_len_per_gpu}
120
+ ulysses_sequence_parallel_size: 1 # sp size
121
+ ppo_epochs: ${actor_rollout_ref.actor.ppo_epochs}
122
+ shuffle: ${actor_rollout_ref.actor.shuffle}
123
+ grad_clip: 1.0
124
+ cliprange_value: 0.5
125
+
126
+ reward_model:
127
+ enable: False
128
+ strategy: fsdp
129
+ model:
130
+ input_tokenizer: ${actor_rollout_ref.model.path} # set this to null if the chat template is identical
131
+ path: ~/models/FsfairX-LLaMA3-RM-v0.1
132
+ external_lib: ${actor_rollout_ref.model.external_lib}
133
+ use_remove_padding: False
134
+ fsdp_config:
135
+ min_num_params: 0
136
+ param_offload: False
137
+ fsdp_size: -1
138
+ micro_batch_size: null # will be deprecated, use micro_batch_size_per_gpu
139
+ micro_batch_size_per_gpu: null # set a number
140
+ max_length: null
141
+ ulysses_sequence_parallel_size: 1 # sp size
142
+ use_dynamic_bsz: ${critic.use_dynamic_bsz}
143
+ forward_max_token_len_per_gpu: ${critic.forward_max_token_len_per_gpu}
144
+ reward_manager: naive
145
+
146
+ algorithm:
147
+ gamma: 1.0
148
+ lam: 1.0
149
+ adv_estimator: gae
150
+ kl_penalty: kl # how to estimate kl divergence
151
+ kl_ctrl:
152
+ type: fixed
153
+ kl_coef: 0.001
154
+
155
+ trainer:
156
+ total_epochs: 30
157
+ total_training_steps: null
158
+ project_name: verl_examples
159
+ experiment_name: gsm8k
160
+ logger: [ 'console', 'wandb' ]
161
+ val_generations_to_log_to_wandb: 0
162
+ nnodes: 1
163
+ n_gpus_per_node: 8
164
+ save_freq: -1
165
+ # auto: find the last ckpt to resume. If can't find, start from scratch
166
+ resume_mode: auto # or auto or resume_path if
167
+ resume_from_path: False
168
+ test_freq: -1
169
+ critic_warmup: 0
170
+ default_hdfs_dir: null
171
+ default_local_dir: checkpoints/${trainer.project_name}/${trainer.experiment_name}
deep_search/DeepResearcher/examples/split_placement/main_ppo_split.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Note that we don't combine the main with ray_trainer as ray_trainer is used by other main.
16
+ """
17
+
18
+ from verl import DataProto
19
+ import torch
20
+ from verl.utils.reward_score import gsm8k, math
21
+ from verl.trainer.ppo.ray_trainer import RayPPOTrainer
22
+
23
+
24
+ def _select_rm_score_fn(data_source):
25
+ if data_source == 'openai/gsm8k':
26
+ return gsm8k.compute_score
27
+ elif data_source == 'lighteval/MATH':
28
+ return math.compute_score
29
+ else:
30
+ raise NotImplementedError
31
+
32
+
33
+ class RewardManager():
34
+
35
+ def __init__(self, tokenizer, num_examine) -> None:
36
+ self.tokenizer = tokenizer
37
+ self.num_examine = num_examine # the number of batches of decoded responses to print to the console
38
+
39
+ def __call__(self, data: DataProto):
40
+ """We will expand this function gradually based on the available datasets"""
41
+
42
+ # If there is rm score, we directly return rm score. Otherwise, we compute via rm_score_fn
43
+ if 'rm_scores' in data.batch.keys():
44
+ return data.batch['rm_scores']
45
+
46
+ reward_tensor = torch.zeros_like(data.batch['responses'], dtype=torch.float32)
47
+
48
+ already_print_data_sources = {}
49
+
50
+ for i in range(len(data)):
51
+ data_item = data[i] # DataProtoItem
52
+
53
+ prompt_ids = data_item.batch['prompts']
54
+
55
+ prompt_length = prompt_ids.shape[-1]
56
+
57
+ valid_prompt_length = data_item.batch['attention_mask'][:prompt_length].sum()
58
+ valid_prompt_ids = prompt_ids[-valid_prompt_length:]
59
+
60
+ response_ids = data_item.batch['responses']
61
+ valid_response_length = data_item.batch['attention_mask'][prompt_length:].sum()
62
+ valid_response_ids = response_ids[:valid_response_length]
63
+
64
+ # decode
65
+ sequences = torch.cat((valid_prompt_ids, valid_response_ids))
66
+ sequences_str = self.tokenizer.decode(sequences)
67
+
68
+ ground_truth = data_item.non_tensor_batch['reward_model']['ground_truth']
69
+
70
+ # select rm_score
71
+ data_source = data_item.non_tensor_batch['data_source']
72
+ compute_score_fn = _select_rm_score_fn(data_source)
73
+
74
+ score = compute_score_fn(solution_str=sequences_str, ground_truth=ground_truth)
75
+ reward_tensor[i, valid_response_length - 1] = score
76
+
77
+ if data_source not in already_print_data_sources:
78
+ already_print_data_sources[data_source] = 0
79
+
80
+ if already_print_data_sources[data_source] < self.num_examine:
81
+ already_print_data_sources[data_source] += 1
82
+ print(sequences_str)
83
+
84
+ return reward_tensor
85
+
86
+
87
+ import ray
88
+ import hydra
89
+ from split_monkey_patch import fit
90
+
91
+
92
+ @hydra.main(config_path='config', config_name='ppo_trainer_split', version_base=None)
93
+ def main(config):
94
+ if not ray.is_initialized():
95
+ # this is for local ray cluster
96
+ ray.init(runtime_env={'env_vars': {'TOKENIZERS_PARALLELISM': 'true', 'NCCL_DEBUG': 'WARN'}})
97
+
98
+ ray.get(main_task.remote(config))
99
+
100
+
101
+ @ray.remote
102
+ def main_task(config):
103
+ from verl.utils.fs import copy_to_local
104
+ from transformers import AutoTokenizer
105
+
106
+ # print initial config
107
+ from pprint import pprint
108
+ from omegaconf import OmegaConf
109
+ pprint(OmegaConf.to_container(config, resolve=True)) # resolve=True will eval symbol values
110
+ OmegaConf.resolve(config)
111
+
112
+ # download the checkpoint from hdfs
113
+ local_path = copy_to_local(config.actor_rollout_ref.model.path)
114
+
115
+ # instantiate tokenizer
116
+ from verl.utils import hf_tokenizer
117
+ tokenizer = hf_tokenizer(local_path)
118
+
119
+ # define worker classes
120
+ if config.actor_rollout_ref.actor.strategy == 'fsdp':
121
+ assert config.actor_rollout_ref.actor.strategy == config.critic.strategy
122
+ from verl.workers.fsdp_workers import ActorRolloutRefWorker, CriticWorker
123
+ from verl.single_controller.ray import RayWorkerGroup
124
+ ray_worker_group_cls = RayWorkerGroup
125
+
126
+ elif config.actor_rollout_ref.actor.strategy == 'megatron':
127
+ assert config.actor_rollout_ref.actor.strategy == config.critic.strategy
128
+ from verl.workers.megatron_workers import ActorRolloutRefWorker, CriticWorker
129
+ from verl.single_controller.ray.megatron import NVMegatronRayWorkerGroup
130
+ ray_worker_group_cls = NVMegatronRayWorkerGroup
131
+
132
+ else:
133
+ raise NotImplementedError
134
+
135
+ from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role
136
+
137
+ role_worker_mapping = {
138
+ Role.ActorRollout: ray.remote(ActorRolloutRefWorker),
139
+ Role.Critic: ray.remote(CriticWorker),
140
+ Role.RefPolicy: ray.remote(ActorRolloutRefWorker)
141
+ }
142
+
143
+ # NOTE: initialze two resource pool
144
+ actor_rollout_ref_pool_id = 'actor_rollout_ref_pool'
145
+ critic_pool_id = 'critic_pool'
146
+ if config.trainer.nnodes // 2 == 0 and config.trainer.n_gpus_per_node // 2 > 0:
147
+ resource_pool_spec = {
148
+ actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes,
149
+ critic_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes,
150
+ }
151
+ else:
152
+ resource_pool_spec = {
153
+ actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2),
154
+ critic_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2),
155
+ }
156
+ print(f'resource_pool_spec: {resource_pool_spec}')
157
+ mapping = {
158
+ Role.ActorRollout: actor_rollout_ref_pool_id,
159
+ Role.Critic: critic_pool_id,
160
+ Role.RefPolicy: actor_rollout_ref_pool_id,
161
+ }
162
+
163
+ # we should adopt a multi-source reward function here
164
+ # - for rule-based rm, we directly call a reward score
165
+ # - for model-based rm, we call a model
166
+ # - for code related prompt, we send to a sandbox if there are test cases
167
+ # - finally, we combine all the rewards together
168
+ # - The reward type depends on the tag of the data
169
+ if config.reward_model.enable:
170
+ if config.reward_model.strategy == 'fsdp':
171
+ from verl.workers.fsdp_workers import RewardModelWorker
172
+ elif config.reward_model.strategy == 'megatron':
173
+ from verl.workers.megatron_workers import RewardModelWorker
174
+ else:
175
+ raise NotImplementedError
176
+ role_worker_mapping[Role.RewardModel] = ray.remote(RewardModelWorker)
177
+ mapping[Role.RewardModel] = critic_pool_id
178
+
179
+ reward_fn = RewardManager(tokenizer=tokenizer, num_examine=0)
180
+
181
+ # Note that we always use function-based RM for validation
182
+ val_reward_fn = RewardManager(tokenizer=tokenizer, num_examine=1)
183
+
184
+ resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=mapping)
185
+
186
+ RayPPOTrainer.fit = fit
187
+ trainer = RayPPOTrainer(config=config,
188
+ tokenizer=tokenizer,
189
+ role_worker_mapping=role_worker_mapping,
190
+ resource_pool_manager=resource_pool_manager,
191
+ ray_worker_group_cls=ray_worker_group_cls,
192
+ reward_fn=reward_fn,
193
+ val_reward_fn=val_reward_fn)
194
+ trainer.init_workers()
195
+ trainer.fit()
196
+
197
+
198
+ if __name__ == '__main__':
199
+ main()
deep_search/DeepResearcher/examples/split_placement/run_deepseek7b_llm.sh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ set -x
2
+
3
+ python3 main_ppo_split.py \
4
+ data.train_files=$HOME/data/gsm8k/train.parquet \
5
+ data.val_files=$HOME/data/gsm8k/test.parquet \
6
+ data.train_batch_size=1024 \
7
+ data.max_prompt_length=512 \
8
+ data.max_response_length=512 \
9
+ actor_rollout_ref.model.path=deepseek-ai/deepseek-llm-7b-chat \
10
+ actor_rollout_ref.actor.optim.lr=1e-6 \
11
+ actor_rollout_ref.actor.ppo_mini_batch_size=256 \
12
+ actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=8 \
13
+ actor_rollout_ref.actor.fsdp_config.param_offload=False \
14
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
15
+ actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=8 \
16
+ actor_rollout_ref.rollout.tensor_model_parallel_size=4 \
17
+ actor_rollout_ref.rollout.name=vllm \
18
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.4 \
19
+ actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=8 \
20
+ actor_rollout_ref.ref.fsdp_config.param_offload=True \
21
+ critic.optim.lr=1e-5 \
22
+ critic.model.path=deepseek-ai/deepseek-llm-7b-chat \
23
+ critic.model.enable_gradient_checkpointing=False \
24
+ critic.ppo_micro_batch_size_per_gpu=8 \
25
+ critic.model.fsdp_config.param_offload=False \
26
+ critic.model.fsdp_config.optimizer_offload=False \
27
+ algorithm.kl_ctrl.kl_coef=0.001 \
28
+ trainer.critic_warmup=0 \
29
+ trainer.logger=['console','wandb'] \
30
+ trainer.project_name='verl_example_gsm8k' \
31
+ trainer.experiment_name='deepseek_llm_7b_function_rm' \
32
+ trainer.n_gpus_per_node=8 \
33
+ trainer.nnodes=1 \
34
+ trainer.save_freq=-1 \
35
+ trainer.total_epochs=15 $@
deep_search/DeepResearcher/examples/split_placement/split_monkey_patch.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ An naive implementation of split placment example
16
+ """
17
+ from pprint import pprint
18
+ from verl import DataProto
19
+ from verl.trainer.ppo.ray_trainer import compute_advantage, apply_kl_penalty, reduce_metrics, compute_data_metrics, _timer, compute_timing_metrics, AdvantageEstimator
20
+ from copy import deepcopy
21
+ import numpy as np
22
+ import torch
23
+ import uuid
24
+
25
+
26
+ def fit(self):
27
+ """
28
+ The training loop of PPO.
29
+ The driver process only need to call the compute functions of the worker group through RPC to construct the PPO dataflow.
30
+ The light-weight advantage computation is done on the driver process.
31
+ """
32
+ from verl.utils.tracking import Tracking
33
+ from omegaconf import OmegaConf
34
+
35
+ logger = Tracking(project_name=self.config.trainer.project_name,
36
+ experiment_name=self.config.trainer.experiment_name,
37
+ default_backend=self.config.trainer.logger,
38
+ config=OmegaConf.to_container(self.config, resolve=True))
39
+
40
+ self.global_steps = 0
41
+
42
+ # load checkpoint before doing anything
43
+ self._load_checkpoint()
44
+
45
+ # perform validation before training
46
+ # currently, we only support validation using the reward_function.
47
+ if self.val_reward_fn is not None and self.config.trainer.get('val_before_train', True):
48
+ val_metrics = self._validate()
49
+ pprint(f'Initial validation metrics: {val_metrics}')
50
+ logger.log(data=val_metrics, step=self.global_steps)
51
+ if self.config.trainer.get('val_only', False):
52
+ return
53
+
54
+ # we start from step 1
55
+ self.global_steps += 1
56
+
57
+ for epoch in range(self.config.trainer.total_epochs):
58
+ for batch_dict in self.train_dataloader:
59
+ metrics = {}
60
+ timing_raw = {}
61
+
62
+ batch: DataProto = DataProto.from_single_dict(batch_dict)
63
+
64
+ # pop those keys for generation
65
+ gen_batch = batch.pop(batch_keys=['input_ids', 'attention_mask', 'position_ids'])
66
+
67
+ with _timer('step', timing_raw):
68
+ # generate a batch
69
+ with _timer('gen', timing_raw):
70
+ gen_batch_output = self.actor_rollout_wg.generate_sequences(gen_batch)
71
+
72
+ if self.config.algorithm.adv_estimator == AdvantageEstimator.REMAX:
73
+ with _timer('gen_max', timing_raw):
74
+ gen_baseline_batch = deepcopy(gen_batch)
75
+ gen_baseline_batch.meta_info['do_sample'] = False
76
+ gen_baseline_output = self.actor_rollout_wg.generate_sequences(gen_baseline_batch)
77
+
78
+ batch = batch.union(gen_baseline_output)
79
+ reward_baseline_tensor = self.reward_fn(batch)
80
+ reward_baseline_tensor = reward_baseline_tensor.sum(dim=-1)
81
+
82
+ batch.pop(batch_keys=list(gen_baseline_output.batch.keys()))
83
+
84
+ batch.batch['reward_baselines'] = reward_baseline_tensor
85
+
86
+ del gen_baseline_batch, gen_baseline_output
87
+
88
+ batch.non_tensor_batch['uid'] = np.array([str(uuid.uuid4()) for _ in range(len(batch.batch))],
89
+ dtype=object)
90
+ # repeat to align with repeated responses in rollout
91
+ batch = batch.repeat(repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True)
92
+ batch = batch.union(gen_batch_output)
93
+
94
+ # balance the number of valid tokens on each dp rank.
95
+ # Note that this breaks the order of data inside the batch.
96
+ # Please take care when you implement group based adv computation such as GRPO and rloo
97
+ self._balance_batch(batch, metrics=metrics)
98
+
99
+ # compute global_valid tokens
100
+ batch.meta_info['global_token_num'] = torch.sum(batch.batch['attention_mask'], dim=-1).tolist()
101
+
102
+ # recompute old_log_probs
103
+ with _timer('old_log_prob', timing_raw):
104
+ old_log_prob = self.actor_rollout_wg.compute_log_prob(batch)
105
+ batch = batch.union(old_log_prob)
106
+
107
+ if self.use_reference_policy:
108
+ # compute reference log_prob
109
+ with _timer('ref', timing_raw):
110
+ ref_log_prob = self.ref_policy_wg.compute_ref_log_prob(batch)
111
+ batch = batch.union(ref_log_prob)
112
+
113
+ # compute values
114
+ if self.use_critic:
115
+ with _timer('values', timing_raw):
116
+ values = self.critic_wg.compute_values(batch)
117
+ batch = batch.union(values)
118
+
119
+ with _timer('adv', timing_raw):
120
+ # compute scores. Support both model and function-based.
121
+ # We first compute the scores using reward model. Then, we call reward_fn to combine
122
+ # the results from reward model and rule-based results.
123
+ if self.use_rm:
124
+ # we first compute reward model score
125
+ reward_tensor = self.rm_wg.compute_rm_score(batch)
126
+ batch = batch.union(reward_tensor)
127
+
128
+ # we combine with rule-based rm
129
+ reward_tensor = self.reward_fn(batch)
130
+ batch.batch['token_level_scores'] = reward_tensor
131
+
132
+ # compute rewards. apply_kl_penalty if available
133
+ if not self.config.actor_rollout_ref.actor.get('use_kl_loss', False):
134
+ batch, kl_metrics = apply_kl_penalty(batch,
135
+ kl_ctrl=self.kl_ctrl,
136
+ kl_penalty=self.config.algorithm.kl_penalty)
137
+ metrics.update(kl_metrics)
138
+ else:
139
+ batch.batch['token_level_rewards'] = batch.batch['token_level_scores']
140
+
141
+ # compute advantages, executed on the driver process
142
+ batch = compute_advantage(batch,
143
+ adv_estimator=self.config.algorithm.adv_estimator,
144
+ gamma=self.config.algorithm.gamma,
145
+ lam=self.config.algorithm.lam,
146
+ num_repeat=self.config.actor_rollout_ref.rollout.n)
147
+
148
+ # update critic
149
+ if self.use_critic:
150
+ with _timer('update_critic_call', timing_raw):
151
+ critic_output = self.critic_wg.update_critic(batch)
152
+
153
+ # implement critic warmup
154
+ if self.config.trainer.critic_warmup <= self.global_steps:
155
+ # update actor
156
+ with _timer('update_actor_call', timing_raw):
157
+ actor_output = self.actor_rollout_wg.update_actor(batch)
158
+
159
+ # NOTE: make sure you set blocking=False in update_actor and update_crtic in the worker class
160
+ with _timer('update_actor_critic', timing_raw):
161
+ critic_output = critic_output.get()
162
+ critic_output_metrics = reduce_metrics(critic_output.meta_info['metrics'])
163
+ metrics.update(critic_output_metrics)
164
+
165
+ actor_output = actor_output.get()
166
+ actor_output_metrics = reduce_metrics(actor_output.meta_info['metrics'])
167
+ metrics.update(actor_output_metrics)
168
+
169
+ # validate
170
+ if self.val_reward_fn is not None and self.config.trainer.test_freq > 0 and \
171
+ self.global_steps % self.config.trainer.test_freq == 0:
172
+ with _timer('testing', timing_raw):
173
+ val_metrics: dict = self._validate()
174
+ metrics.update(val_metrics)
175
+
176
+ if self.config.trainer.save_freq > 0 and \
177
+ self.global_steps % self.config.trainer.save_freq == 0:
178
+ with _timer('save_checkpoint', timing_raw):
179
+ self._save_checkpoint()
180
+
181
+ # collect metrics
182
+ metrics.update(compute_data_metrics(batch=batch, use_critic=self.use_critic))
183
+ metrics.update(compute_timing_metrics(batch=batch, timing_raw=timing_raw))
184
+
185
+ # TODO: make a canonical logger that supports various backend
186
+ logger.log(data=metrics, step=self.global_steps)
187
+
188
+ self.global_steps += 1
189
+
190
+ if self.global_steps >= self.total_training_steps:
191
+
192
+ # perform validation after training
193
+ if self.val_reward_fn is not None:
194
+ val_metrics = self._validate()
195
+ pprint(f'Final validation metrics: {val_metrics}')
196
+ logger.log(data=val_metrics, step=self.global_steps)
197
+ return
deep_search/DeepResearcher/pyproject.toml ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -------------------------------
2
+ # build-system
3
+ # -------------------------------
4
+ [build-system]
5
+ requires = [
6
+ "setuptools>=61.0",
7
+ "wheel"
8
+ ]
9
+ build-backend = "setuptools.build_meta"
10
+
11
+ # -------------------------------
12
+ # project (PEP 621 metadata)
13
+ # -------------------------------
14
+ [project]
15
+ name = "verl"
16
+ # We'll mark the version as "dynamic" because it's read from the file "verl/version/version"
17
+ # (PEP 621 calls this "dynamic version").
18
+ # The actual version is specified in the [tool.setuptools.dynamic] section below.
19
+ dynamic = ["version"]
20
+
21
+ description = "verl: Volcano Engine Reinforcement Learning for LLM"
22
+ license = {file = "LICENSE"} # or "Apache-2.0", if you prefer an SPDX identifier
23
+ readme = {file = "README.md", content-type = "text/markdown"}
24
+ requires-python = ">=3.8"
25
+
26
+ authors = [
27
+ { name = "Bytedance - Seed - MLSys", email = "zhangchi.usc1992@bytedance.com" },
28
+ { name = "Bytedance - Seed - MLSys", email = "gmsheng@connect.hku.hk" },
29
+ ]
30
+
31
+ # Dependencies corresponding to install_requires in setup.py
32
+ dependencies = [
33
+ "accelerate",
34
+ "codetiming",
35
+ "datasets",
36
+ "dill",
37
+ "hydra-core",
38
+ "numpy",
39
+ "pandas",
40
+ "peft",
41
+ "pyarrow>=15.0.0",
42
+ "pybind11",
43
+ "pylatexenc",
44
+ "ray>=2.10",
45
+ "tensordict<0.6",
46
+ "torchdata",
47
+ "transformers",
48
+ "vllm<=0.6.3",
49
+ 'wandb',
50
+ ]
51
+
52
+ # Optional dependencies (extras_require in setup.py)
53
+ [project.optional-dependencies]
54
+ test = [
55
+ "pytest", "yapf", "py-spy",
56
+ ]
57
+ prime = ["pyext"]
58
+ gpu = ["liger-kernel", "flash-attn"]
59
+
60
+ # URLs
61
+ [project.urls]
62
+ Homepage = "https://github.com/volcengine/verl"
63
+
64
+ # -------------------------------
65
+ # tool.setuptools - Additional config
66
+ # -------------------------------
67
+ [tool.setuptools]
68
+ # True means `setuptools` will attempt to include all relevant files in package_data automatically.
69
+ # This corresponds to `include_package_data=True` in setup.py.
70
+ include-package-data = true
71
+
72
+ # We read the version from a file in 'verl/version/version'
73
+ [tool.setuptools.dynamic]
74
+ version = {file = "verl/version/version"}
75
+
76
+ # If you need to mimic `package_dir={'': '.'}`:
77
+ [tool.setuptools.package-dir]
78
+ "" = "."
79
+
80
+ # If you need to include specific non-Python data (like YAML files or version file):
81
+ # This is the rough equivalent of package_data={'': ['version/*'], 'verl': ['trainer/config/*.yaml']}
82
+ [tool.setuptools.package-data]
83
+ verl = [
84
+ "version/*",
85
+ "trainer/config/*.yaml"
86
+ ]
deep_search/DeepResearcher/requirements.txt ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # requirements.txt records the full set of dependencies for development
2
+ accelerate
3
+ codetiming
4
+ datasets
5
+ dill
6
+ flash-attn
7
+ hydra-core
8
+ liger-kernel
9
+ numpy
10
+ pandas
11
+ peft
12
+ pyarrow>=15.0.0
13
+ pybind11
14
+ pylatexenc
15
+ ray[data,train,tune,serve]
16
+ tensordict<0.6
17
+ torchdata
18
+ transformers
19
+ vllm<=0.6.3
20
+ wandb
21
+ pathvalidate
22
+ smolagents
23
+ mammoth
24
+ pdfminer
25
+ python-pptx
26
+ puremagic
27
+ pydub
28
+ SpeechRecognition
29
+ PyPDF2
30
+ youtube_transcript_api
31
+ serpapi
32
+ tqdm
33
+ pubchempy
34
+ Bio
35
+ scikit-learn
36
+ google_search_results
37
+ markdownify
38
+ numexpr
39
+ openai
40
+ openpyxl
41
+ python-dotenv
42
+ chess
43
+ sympy
44
+ xlrd
45
+ huggingface_hub
46
+ Requests
47
+ beautifulsoup4
48
+ Pillow
49
+ modelscope
50
+ html2text
51
+ pathvalidate
52
+ smolagents
53
+ pdfminer
54
+ mammoth
55
+ pdfminer.six
56
+ python-pptx
57
+ pydub
58
+ puremagic
59
+ SpeechRecognition
60
+ youtube_transcript_api
61
+ html2text
62
+ flask
63
+ psutil
64
+ pymongo
deep_search/DeepResearcher/setup.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # setup.py is the fallback installation script when pyproject.toml does not work
16
+ from setuptools import setup, find_packages
17
+ import os
18
+
19
+ version_folder = os.path.dirname(os.path.join(os.path.abspath(__file__)))
20
+
21
+ with open(os.path.join(version_folder, 'verl/version/version')) as f:
22
+ __version__ = f.read().strip()
23
+
24
+ install_requires = [
25
+ 'accelerate',
26
+ 'codetiming',
27
+ 'datasets',
28
+ 'dill',
29
+ 'hydra-core',
30
+ 'numpy',
31
+ 'pandas',
32
+ 'peft',
33
+ 'pyarrow>=15.0.0',
34
+ 'pybind11',
35
+ 'pylatexenc',
36
+ 'ray>=2.10',
37
+ 'tensordict<0.6',
38
+ 'torchdata',
39
+ 'transformers',
40
+ 'vllm<=0.6.3',
41
+ 'wandb',
42
+ ]
43
+
44
+ TEST_REQUIRES = ['pytest', 'yapf', 'py-spy']
45
+ PRIME_REQUIRES = ['pyext']
46
+ GEO_REQUIRES = ['mathruler']
47
+ GPU_REQUIRES = ['liger-kernel', 'flash-attn']
48
+
49
+ extras_require = {
50
+ 'test': TEST_REQUIRES,
51
+ 'prime': PRIME_REQUIRES,
52
+ 'geo': GEO_REQUIRES,
53
+ 'gpu': GPU_REQUIRES,
54
+ }
55
+
56
+ from pathlib import Path
57
+ this_directory = Path(__file__).parent
58
+ long_description = (this_directory / "README.md").read_text()
59
+
60
+ setup(
61
+ name='verl',
62
+ version=__version__,
63
+ package_dir={'': '.'},
64
+ packages=find_packages(where='.'),
65
+ url='https://github.com/volcengine/verl',
66
+ license='Apache 2.0',
67
+ author='Bytedance - Seed - MLSys',
68
+ author_email='zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk',
69
+ description='verl: Volcano Engine Reinforcement Learning for LLM',
70
+ install_requires=install_requires,
71
+ extras_require=extras_require,
72
+ package_data={'': ['version/*'],
73
+ 'verl': ['trainer/config/*.yaml'],},
74
+ include_package_data=True,
75
+ long_description=long_description,
76
+ long_description_content_type='text/markdown'
77
+ )
deep_search/DeepResearcher/train_grpo.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ export VLLM_ATTENTION_BACKEND=XFORMERS
3
+ export project_name="project_name"
4
+ export experiment_name="experiment_name"
5
+
6
+
7
+ PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
8
+ data.train_files=./data/train.parquet \
9
+ data.val_files=./data/dev.parquet \
10
+ data.train_batch_size=256 \
11
+ data.max_prompt_length=30767 \
12
+ data.max_response_length=2000 \
13
+ +data.max_model_len=32768 \
14
+ data.data_writing_file=./signal/data.json \
15
+ data.signal_writing_file=./signal/signal.json \
16
+ actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \
17
+ actor_rollout_ref.model.use_remove_padding=true \
18
+ actor_rollout_ref.actor.optim.lr=1e-6 \
19
+ actor_rollout_ref.actor.ppo_mini_batch_size=4096 \
20
+ actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=2 \
21
+ actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=2 \
22
+ actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
23
+ actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
24
+ actor_rollout_ref.rollout.max_num_batched_tokens=32768 \
25
+ actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=2 \
26
+ actor_rollout_ref.actor.use_kl_loss=true \
27
+ actor_rollout_ref.actor.use_dynamic_bsz=true \
28
+ actor_rollout_ref.actor.fsdp_config.param_offload=true \
29
+ actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
30
+ actor_rollout_ref.ref.fsdp_config.param_offload=true \
31
+ actor_rollout_ref.actor.ppo_max_token_len_per_gpu=12288 \
32
+ actor_rollout_ref.actor.ulysses_sequence_parallel_size=4 \
33
+ critic.optim.lr=1e-5 \
34
+ critic.model.path=Qwen/Qwen2.5-7B-Instruct \
35
+ critic.ppo_micro_batch_size_per_gpu=2 \
36
+ algorithm.kl_ctrl.kl_coef=0.001 \
37
+ trainer.logger=['console','wandb'] \
38
+ trainer.project_name=${project_name} \
39
+ trainer.experiment_name=${experiment_name} \
40
+ +trainer.val_before_train=false \
41
+ trainer.default_hdfs_dir=null \
42
+ trainer.n_gpus_per_node=8 \
43
+ trainer.nnodes=1 \
44
+ trainer.save_freq=1 \
45
+ trainer.test_freq=1 \
46
+ trainer.remove_previous_ckpt_in_save=false \
47
+ agent_grpo.n=16 \
48
+ max_turns=10 \
49
+ search_engine=online_search \
50
+ trainer.total_epochs=1 2>&1 | tee ./${project_name}_${experiment_name}.log
51
+
deep_search/search_o1/eval/__pycache__/utils.cpython-310.pyc ADDED
Binary file (15.6 kB). View file
 
deep_search/search_o1/eval/__pycache__/utils.cpython-39.pyc ADDED
Binary file (15.5 kB). View file
 
deep_search/search_o1/eval/add_eval.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ from utils import has_answer, EM_compute, F1_compute, AC_compute
4
+
5
+ import os
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ import torch
8
+ import numpy as np
9
+ import matplotlib.pyplot as plt
10
+ import seaborn as sns
11
+
12
+
13
+
14
+
15
+
16
+
17
+ def calculate_statistics(data):
18
+ return {
19
+ 'mean': np.mean(data),
20
+ 'std': np.std(data),
21
+ 'median': np.median(data),
22
+ 'min': np.min(data),
23
+ 'max': np.max(data),
24
+ '25th_percentile': np.percentile(data, 25),
25
+ '75th_percentile': np.percentile(data, 75),
26
+ }
27
+
28
+
29
+ def analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len):
30
+ all_outputs_len_stats = calculate_statistics(all_outputs_len)
31
+ retrieval_outputs_len_stats = calculate_statistics(retrieval_outputs_len)
32
+ no_retrieval_outputs_len_stats = calculate_statistics(no_retrieval_outputs_len)
33
+
34
+ # 打印统计数据
35
+ print("All outputs length statistics:", all_outputs_len_stats)
36
+ print("Retrieval outputs length statistics:", retrieval_outputs_len_stats)
37
+ print("No retrieval outputs length statistics:", no_retrieval_outputs_len_stats)
38
+
39
+ # 创建保存结果的目录
40
+ output_dir = output_len_analyse_path
41
+ if not os.path.exists(output_dir):
42
+ os.makedirs(output_dir)
43
+
44
+ # 绘制直方图并保存图像
45
+ plt.figure(figsize=(12, 8))
46
+
47
+ # 绘制所有输出长度的直方图
48
+ plt.subplot(2, 2, 1)
49
+ sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density')
50
+ plt.title('Distribution of All Outputs Length')
51
+ plt.xlabel('Length')
52
+ plt.ylabel('Density')
53
+ # plt.savefig(os.path.join(output_dir, 'all_outputs_length_distribution.png'))
54
+
55
+ # 绘制检索输出长度的直方图
56
+ plt.subplot(2, 2, 2)
57
+ sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density')
58
+ plt.title('Distribution of Retrieval Outputs Length')
59
+ plt.xlabel('Length')
60
+ plt.ylabel('Density')
61
+ # plt.savefig(os.path.join(output_dir, 'retrieval_outputs_length_distribution.png'))
62
+
63
+ # 绘制没有检索输出长度的直方图
64
+ plt.subplot(2, 2, 3)
65
+ sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density')
66
+ plt.title('Distribution of No Retrieval Outputs Length')
67
+ plt.xlabel('Length')
68
+ plt.ylabel('Density')
69
+ # plt.savefig(os.path.join(output_dir, 'no_retrieval_outputs_length_distribution.png'))
70
+
71
+ # 总体输出长度分布
72
+ plt.subplot(2, 2, 4)
73
+ sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density', alpha=0.5)
74
+ sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density', alpha=0.5)
75
+ sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density', alpha=0.5)
76
+ plt.title('Overall Distribution of Outputs Length')
77
+ plt.xlabel('Length')
78
+ plt.ylabel('Density')
79
+ plt.legend()
80
+ # plt.savefig(os.path.join(output_dir, 'overall_output_length_distribution.png'))
81
+
82
+ # 保存所有图像
83
+ plt.tight_layout()
84
+ plt.savefig(os.path.join(output_dir, 'combined_output_length_distribution.png'))
85
+
86
+ plt.show()
87
+
88
+ def has_run_retrieve(sample):
89
+ return bool (sample["search_count"])
90
+
91
+ def cal_has_answer(sample):
92
+ reason_has, search_has, analyses_has = 0, 0, 0
93
+ for info in sample["all_info"]:
94
+ for k, v in info.items():
95
+ if "reason" in k:
96
+ reason_has = max(reason_has, has_answer(sample['answer'], v))
97
+ elif "search" in k:
98
+ search_has = max(search_has, has_answer(sample['answer'], v))
99
+ elif "analyses" in k:
100
+ analyses_has = max(analyses_has, has_answer(sample['answer'], v))
101
+ return {'reason': reason_has, 'search': search_has, 'analyse': analyses_has}
102
+
103
+ def extract_answer(sample):
104
+ output = sample.get('output', '')
105
+ match = re.search(r'\\boxed\{(.*?)\}', output)
106
+ if match:
107
+ return match.group(1)
108
+ return output.rsplit('\n', 1)[-1]
109
+
110
+ def cal_metrics(sample):
111
+ res = {}
112
+ pred = extract_answer(sample)
113
+ for m, func in {
114
+ 'em': EM_compute,
115
+ 'ac': AC_compute,
116
+ 'f1': F1_compute,
117
+ }.items():
118
+ res[m] = func(sample['answer'], pred)
119
+ res.update(cal_has_answer(sample))
120
+ res['search_count'] = sample['search_count']
121
+ return res
122
+
123
+ def add_eval(model_path, data_path):
124
+
125
+ # model_path = "/opt/aps/workdir/sunshuang/search_o1/Qwen2.5-7B-Instruct"
126
+ # data_path = "/opt/aps/workdir/sunshuang/search_o1/output_eval/eval_hopotqa_dev_500_original_qwen_7b_inst/runs.baselines/hotpotqa.qwen2.5-7b.search_o1/turn_7.json"
127
+ output_len_analyse_path = os.path.dirname(data_path)
128
+
129
+ # model = AutoModelForCausalLM.from_pretrained(model_path).to(torch.bfloat16).to("cuda")
130
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
131
+
132
+ with open(data_path) as f:
133
+ results = json.load(f)
134
+
135
+ # 初始化累加器
136
+ total_metrics = {}
137
+ retrieval_true_metrics = {}
138
+ retrieval_false_metrics = {}
139
+ count_total = 0
140
+ count_retrieval_true = 0
141
+ count_retrieval_false = 0
142
+
143
+ # 计算平均长度
144
+ all_outputs_len = []
145
+ retrieval_outputs_len = []
146
+ no_retrieval_outputs_len = []
147
+
148
+ # 遍历每个样本并计算指标
149
+ for sample in results:
150
+ sample.update(sample["item"])
151
+ metrics = cal_metrics(sample)
152
+
153
+ output_ids = tokenizer(sample["output"], add_special_tokens=False)["input_ids"]
154
+ all_outputs_len.append(len(output_ids))
155
+
156
+ # 累加总的指标
157
+ for key, value in metrics.items():
158
+ total_metrics[key] = total_metrics.get(key, 0) + value
159
+
160
+ # 根据是否跑了检索进行分类累加
161
+ if has_run_retrieve(sample):
162
+ retrieval_outputs_len.append(len(output_ids))
163
+
164
+ for key, value in metrics.items():
165
+ retrieval_true_metrics[key] = retrieval_true_metrics.get(key, 0) + value
166
+ count_retrieval_true += 1
167
+ else:
168
+ no_retrieval_outputs_len.append(len(output_ids))
169
+ for key, value in metrics.items():
170
+ retrieval_false_metrics[key] = retrieval_false_metrics.get(key, 0) + value
171
+ count_retrieval_false += 1
172
+
173
+ count_total += 1
174
+
175
+ # 计算均值
176
+ mean_metrics = {key: value / count_total for key, value in total_metrics.items()}
177
+ mean_retrieval_true_metrics = {key: value / count_retrieval_true for key, value in retrieval_true_metrics.items()}
178
+ mean_retrieval_false_metrics = {key: value / count_retrieval_false for key, value in retrieval_false_metrics.items()}
179
+
180
+ mean_all_output_len = sum(all_outputs_len) / len(all_outputs_len)
181
+ mean_retrieval_outputs_len = sum(retrieval_outputs_len) / len(retrieval_outputs_len)
182
+ mean_no_retrieval_outputs_len = sum(no_retrieval_outputs_len) / len(no_retrieval_outputs_len)
183
+
184
+ analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len)
185
+
186
+ print(count_retrieval_false/count_total)
187
+ print(count_retrieval_true/count_total)
188
+
189
+ # 打印结果
190
+ print(f"model_path: {model_path}")
191
+ print(f"data_path: {data_path}")
192
+ print("Overall Mean Metrics:")
193
+ for key, value in mean_metrics.items():
194
+ print(f"{key}: {value}")
195
+ print(f"output_len: {mean_all_output_len}")
196
+
197
+ print("\nMean Metrics for Samples with Retrieval:")
198
+ for key, value in mean_retrieval_true_metrics.items():
199
+ print(f"{key}: {value}")
200
+ print(f"output_len: {mean_retrieval_outputs_len}")
201
+
202
+ print("\nMean Metrics for Samples without Retrieval:")
203
+ for key, value in mean_retrieval_false_metrics.items():
204
+ print(f"{key}: {value}")
205
+ print(f"output_len: {mean_no_retrieval_outputs_len}")
206
+
207
+ main()
deep_search/search_o1/eval/eval_seach_o1.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ from utils import has_answer, EM_compute, F1_compute, AC_compute
4
+
5
+
6
+ with open("/opt/aps/workdir/sunshuang/search_o1/output_eval/eval_hopotqa_dev_500_qwen_32b_original_tokenizer_inst_data_1217/runs.baselines/hotpotqa.qwen_32b_original_tokenizer_inst_data_1217.search_o1/turn_15.json") as f:
7
+ results = json.load(f)
8
+
9
+ def has_run_retrieve(sample):
10
+ return bool (sample["search_count"])
11
+
12
+ def cal_has_answer(sample):
13
+ reason_has, search_has, analyses_has = 0, 0, 0
14
+ for info in sample["all_info"]:
15
+ for k, v in info.items():
16
+ if "reason" in k:
17
+ reason_has = max(reason_has, has_answer(sample['answer'], v))
18
+ elif "search" in k:
19
+ search_has = max(search_has, has_answer(sample['answer'], v))
20
+ elif "analyses" in k:
21
+ analyses_has = max(analyses_has, has_answer(sample['answer'], v))
22
+ return {'reason': reason_has, 'search': search_has, 'analyse': analyses_has}
23
+
24
+ def extract_answer(sample):
25
+ output = sample.get('output', '')
26
+ match = re.search(r'\\boxed\{(.*?)\}', output)
27
+ if match:
28
+ return match.group(1)
29
+ return output.rsplit('\n', 1)[-1]
30
+
31
+ def cal_metrics(sample):
32
+ res = {}
33
+ pred = extract_answer(sample)
34
+ for m, func in {
35
+ 'em': EM_compute,
36
+ 'ac': AC_compute,
37
+ 'f1': F1_compute,
38
+ }.items():
39
+ res[m] = func(sample['answer'], pred)
40
+ res.update(cal_has_answer(sample))
41
+ res['search_count'] = sample['search_count']
42
+ return res
43
+
44
+ def main():
45
+ # 初始化累加器
46
+ total_metrics = {}
47
+ retrieval_true_metrics = {}
48
+ retrieval_false_metrics = {}
49
+ count_total = 0
50
+ count_retrieval_true = 0
51
+ count_retrieval_false = 0
52
+
53
+ # 遍历每个样本并计算指标
54
+ for sample in results:
55
+ sample.update(sample["item"])
56
+ metrics = cal_metrics(sample)
57
+
58
+ # 累加总的指标
59
+ for key, value in metrics.items():
60
+ total_metrics[key] = total_metrics.get(key, 0) + value
61
+
62
+ # 根据是否跑了检索进行分类累加
63
+ if has_run_retrieve(sample):
64
+ for key, value in metrics.items():
65
+ retrieval_true_metrics[key] = retrieval_true_metrics.get(key, 0) + value
66
+ count_retrieval_true += 1
67
+ else:
68
+ for key, value in metrics.items():
69
+ retrieval_false_metrics[key] = retrieval_false_metrics.get(key, 0) + value
70
+ count_retrieval_false += 1
71
+
72
+ count_total += 1
73
+
74
+ # 计算均值
75
+ mean_metrics = {key: value / count_total for key, value in total_metrics.items()}
76
+ mean_retrieval_true_metrics = {key: value / count_retrieval_true for key, value in retrieval_true_metrics.items()}
77
+ mean_retrieval_false_metrics = {key: value / count_retrieval_false for key, value in retrieval_false_metrics.items()}
78
+ print(count_retrieval_false/count_total)
79
+ print(count_retrieval_true/count_total)
80
+ # 打印结果
81
+ print("Overall Mean Metrics:")
82
+ for key, value in mean_metrics.items():
83
+ print(f"{key}: {value}")
84
+
85
+ print("\nMean Metrics for Samples with Retrieval:")
86
+ for key, value in mean_retrieval_true_metrics.items():
87
+ print(f"{key}: {value}")
88
+
89
+ print("\nMean Metrics for Samples without Retrieval:")
90
+ for key, value in mean_retrieval_false_metrics.items():
91
+ print(f"{key}: {value}")
92
+
93
+ main()
deep_search/search_o1/eval/eval_seach_o1_with_output_len.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ from utils import has_answer, EM_compute, F1_compute, AC_compute
4
+
5
+ import os
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ import torch
8
+ import numpy as np
9
+ import matplotlib.pyplot as plt
10
+ import seaborn as sns
11
+
12
+ model_path = "/opt/aps/workdir/sunshuang/search_o1/Qwen2.5-7B-Instruct"
13
+ data_path = "/opt/aps/workdir/sunshuang/search_o1/output_eval/eval_hopotqa_dev_500_original_qwen_7b_inst/runs.baselines/hotpotqa.qwen2.5-7b.search_o1/turn_7.json"
14
+ output_len_analyse_path = os.path.dirname(data_path)
15
+
16
+ # model = AutoModelForCausalLM.from_pretrained(model_path).to(torch.bfloat16).to("cuda")
17
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
18
+
19
+ with open(data_path) as f:
20
+ results = json.load(f)
21
+
22
+
23
+ def calculate_statistics(data):
24
+ return {
25
+ 'mean': np.mean(data),
26
+ 'std': np.std(data),
27
+ 'median': np.median(data),
28
+ 'min': np.min(data),
29
+ 'max': np.max(data),
30
+ '25th_percentile': np.percentile(data, 25),
31
+ '75th_percentile': np.percentile(data, 75),
32
+ }
33
+
34
+
35
+ def analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len):
36
+ all_outputs_len_stats = calculate_statistics(all_outputs_len)
37
+ retrieval_outputs_len_stats = calculate_statistics(retrieval_outputs_len)
38
+ no_retrieval_outputs_len_stats = calculate_statistics(no_retrieval_outputs_len)
39
+
40
+ # 打印统计数据
41
+ print("All outputs length statistics:", all_outputs_len_stats)
42
+ print("Retrieval outputs length statistics:", retrieval_outputs_len_stats)
43
+ print("No retrieval outputs length statistics:", no_retrieval_outputs_len_stats)
44
+
45
+ # 创建保存结果的目录
46
+ output_dir = output_len_analyse_path
47
+ if not os.path.exists(output_dir):
48
+ os.makedirs(output_dir)
49
+
50
+ # 绘制直方图并保存图像
51
+ plt.figure(figsize=(12, 8))
52
+
53
+ # 绘制所有输出长度的直方图
54
+ plt.subplot(2, 2, 1)
55
+ sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density')
56
+ plt.title('Distribution of All Outputs Length')
57
+ plt.xlabel('Length')
58
+ plt.ylabel('Density')
59
+ # plt.savefig(os.path.join(output_dir, 'all_outputs_length_distribution.png'))
60
+
61
+ # 绘制检索输出长度的直方图
62
+ plt.subplot(2, 2, 2)
63
+ sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density')
64
+ plt.title('Distribution of Retrieval Outputs Length')
65
+ plt.xlabel('Length')
66
+ plt.ylabel('Density')
67
+ # plt.savefig(os.path.join(output_dir, 'retrieval_outputs_length_distribution.png'))
68
+
69
+ # 绘制没有检索输出长度的直方图
70
+ plt.subplot(2, 2, 3)
71
+ sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density')
72
+ plt.title('Distribution of No Retrieval Outputs Length')
73
+ plt.xlabel('Length')
74
+ plt.ylabel('Density')
75
+ # plt.savefig(os.path.join(output_dir, 'no_retrieval_outputs_length_distribution.png'))
76
+
77
+ # 总体输出长度分布
78
+ plt.subplot(2, 2, 4)
79
+ sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density', alpha=0.5)
80
+ sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density', alpha=0.5)
81
+ sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density', alpha=0.5)
82
+ plt.title('Overall Distribution of Outputs Length')
83
+ plt.xlabel('Length')
84
+ plt.ylabel('Density')
85
+ plt.legend()
86
+ # plt.savefig(os.path.join(output_dir, 'overall_output_length_distribution.png'))
87
+
88
+ # 保存所有图像
89
+ plt.tight_layout()
90
+ plt.savefig(os.path.join(output_dir, 'combined_output_length_distribution.png'))
91
+
92
+ plt.show()
93
+
94
+ def has_run_retrieve(sample):
95
+ return bool (sample["search_count"])
96
+
97
+ def cal_has_answer(sample):
98
+ reason_has, search_has, analyses_has = 0, 0, 0
99
+ for info in sample["all_info"]:
100
+ for k, v in info.items():
101
+ if "reason" in k:
102
+ reason_has = max(reason_has, has_answer(sample['answer'], v))
103
+ elif "search" in k:
104
+ search_has = max(search_has, has_answer(sample['answer'], v))
105
+ elif "analyses" in k:
106
+ analyses_has = max(analyses_has, has_answer(sample['answer'], v))
107
+ return {'reason': reason_has, 'search': search_has, 'analyse': analyses_has}
108
+
109
+ def extract_answer(sample):
110
+ output = sample.get('output', '')
111
+ match = re.search(r'\\boxed\{(.*?)\}', output)
112
+ if match:
113
+ return match.group(1)
114
+ return output.rsplit('\n', 1)[-1]
115
+
116
+ def cal_metrics(sample):
117
+ res = {}
118
+ pred = extract_answer(sample)
119
+ for m, func in {
120
+ 'em': EM_compute,
121
+ 'ac': AC_compute,
122
+ 'f1': F1_compute,
123
+ }.items():
124
+ res[m] = func(sample['answer'], pred)
125
+ res.update(cal_has_answer(sample))
126
+ res['search_count'] = sample['search_count']
127
+ return res
128
+
129
+ def main():
130
+ # 初始化累加器
131
+ total_metrics = {}
132
+ retrieval_true_metrics = {}
133
+ retrieval_false_metrics = {}
134
+ count_total = 0
135
+ count_retrieval_true = 0
136
+ count_retrieval_false = 0
137
+
138
+ # 计算平均长度
139
+ all_outputs_len = []
140
+ retrieval_outputs_len = []
141
+ no_retrieval_outputs_len = []
142
+
143
+ # 遍历每个样本并计算指标
144
+ for sample in results:
145
+ sample.update(sample["item"])
146
+ metrics = cal_metrics(sample)
147
+
148
+ output_ids = tokenizer(sample["output"], add_special_tokens=False)["input_ids"]
149
+ all_outputs_len.append(len(output_ids))
150
+
151
+ # 累加总的指标
152
+ for key, value in metrics.items():
153
+ total_metrics[key] = total_metrics.get(key, 0) + value
154
+
155
+ # 根据是否跑了检索进行分类累加
156
+ if has_run_retrieve(sample):
157
+ retrieval_outputs_len.append(len(output_ids))
158
+
159
+ for key, value in metrics.items():
160
+ retrieval_true_metrics[key] = retrieval_true_metrics.get(key, 0) + value
161
+ count_retrieval_true += 1
162
+ else:
163
+ no_retrieval_outputs_len.append(len(output_ids))
164
+ for key, value in metrics.items():
165
+ retrieval_false_metrics[key] = retrieval_false_metrics.get(key, 0) + value
166
+ count_retrieval_false += 1
167
+
168
+ count_total += 1
169
+
170
+ # 计算均值
171
+ mean_metrics = {key: value / count_total for key, value in total_metrics.items()}
172
+ mean_retrieval_true_metrics = {key: value / count_retrieval_true for key, value in retrieval_true_metrics.items()}
173
+ mean_retrieval_false_metrics = {key: value / count_retrieval_false for key, value in retrieval_false_metrics.items()}
174
+
175
+ mean_all_output_len = sum(all_outputs_len) / len(all_outputs_len)
176
+ mean_retrieval_outputs_len = sum(retrieval_outputs_len) / len(retrieval_outputs_len)
177
+ mean_no_retrieval_outputs_len = sum(no_retrieval_outputs_len) / len(no_retrieval_outputs_len)
178
+
179
+ analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len)
180
+
181
+ print(count_retrieval_false/count_total)
182
+ print(count_retrieval_true/count_total)
183
+
184
+ # 打印结果
185
+ print(f"model_path: {model_path}")
186
+ print(f"data_path: {data_path}")
187
+ print("Overall Mean Metrics:")
188
+ for key, value in mean_metrics.items():
189
+ print(f"{key}: {value}")
190
+ print(f"output_len: {mean_all_output_len}")
191
+
192
+ print("\nMean Metrics for Samples with Retrieval:")
193
+ for key, value in mean_retrieval_true_metrics.items():
194
+ print(f"{key}: {value}")
195
+ print(f"output_len: {mean_retrieval_outputs_len}")
196
+
197
+ print("\nMean Metrics for Samples without Retrieval:")
198
+ for key, value in mean_retrieval_false_metrics.items():
199
+ print(f"{key}: {value}")
200
+ print(f"output_len: {mean_no_retrieval_outputs_len}")
201
+
202
+ main()
deep_search/search_o1/eval/token_len.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ from utils import has_answer, EM_compute, F1_compute, AC_compute
4
+
5
+ import os
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ import torch
8
+ import numpy as np
9
+ import matplotlib.pyplot as plt
10
+ import seaborn as sns
11
+ from tqdm import tqdm
12
+
13
+ def calculate_statistics(data):
14
+ return {
15
+ 'mean': np.mean(data),
16
+ 'std': np.std(data),
17
+ 'median': np.median(data),
18
+ 'min': np.min(data),
19
+ 'max': np.max(data),
20
+ '25th_percentile': np.percentile(data, 25),
21
+ '75th_percentile': np.percentile(data, 75),
22
+ }
23
+
24
+
25
+ def analyse_len(text_len):
26
+ text_len_stats = calculate_statistics(text_len)
27
+
28
+ # 打印统计数据
29
+ print("text length statistics:", text_len_stats)
30
+
31
+ # 创建保存结果的目录
32
+ output_dir = output_len_analyse_path
33
+ if not os.path.exists(output_dir):
34
+ os.makedirs(output_dir)
35
+
36
+ # 绘制直方图并保存图像
37
+ plt.figure(figsize=(12, 8))
38
+
39
+ # 绘制所有输出长度的直方图
40
+ sns.histplot(text_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density')
41
+ plt.title('Distribution of All texts Length')
42
+ plt.xlabel('Length')
43
+ plt.ylabel('Density')
44
+ plt.savefig(os.path.join(output_dir, 'text_len.png'))
45
+
46
+
47
+ def save_to_json(data, filename):
48
+ with open(filename, 'w', encoding='utf-8') as f:
49
+ json.dump(data, f, ensure_ascii=False, indent=4)
50
+ print(f"save to {filename}, data len: {len(data)}")
51
+ def load_json(file_path):
52
+ with open(file_path, "r", encoding="utf-8") as f:
53
+ data = json.load(f)
54
+ print(f"load from {file_path}, data len: {len(data)}")
55
+ return data
56
+
57
+
58
+
59
+ if __name__=="__main__":
60
+
61
+ file_path = "/opt/aps/workdir/sunshuang/search_o1/outputs_reason_two_model/eval_reason_two_model/qwen-instruct-32B/JOB9986:LR1e-5:BASEQwen2.5-32B-Instruct:TOKENDeepSeek-R1-Distill-Qwen-32:BSZ1:ACC8/38/musique/test.2.28,17:38.info_extract.json"
62
+ model_path = "/capacity/userdata/models/Qwen2.5-32B-Instruct"
63
+ output_len_analyse_path = os.path.dirname(file_path)
64
+ # file_output_path = "/opt/aps/workdir/sunshuang/search_o1/outputs_gen_data_hotpot_qa/runs.baselines/hotpotqa.deepseek-r1-distill-qwen-32.search_o1/batch_0_back/test.2.23,14:26.info_extract_remove_special.json"
65
+ data = load_json(file_path)
66
+
67
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
68
+
69
+ text_len = []
70
+ for item in tqdm(data):
71
+
72
+ text_ids = tokenizer(item["prompt"], add_special_tokens=False)["input_ids"]
73
+ text_len.append(len(text_ids))
74
+
75
+ analyse_len(text_len)
76
+
deep_search/search_o1/eval/topics_stats.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from collections import defaultdict
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+
7
+ def read_json(file_path):
8
+ """从 JSON 文件中读取数据"""
9
+ with open(file_path, "r", encoding="utf-8") as f:
10
+ data = json.load(f)
11
+ print(f"load from {file_path}, total item: {len(data)}")
12
+ return data
13
+
14
+ def read_jsonl(file_path):
15
+ """从 JSON Lines 文件中读取数据"""
16
+ data = []
17
+ with open(file_path, "r", encoding="utf-8") as f:
18
+ for line in f:
19
+ data.append(json.loads(line.strip()))
20
+ print(f"load from {file_path}, total item: {len(data)}")
21
+ return data
22
+
23
+
24
+ # 统计并绘制图表的函数
25
+ def topics_stats(file_original_path, file_turn_path, file_eval_path):
26
+ # 读取数据
27
+ data_original_question = read_json(file_original_path)
28
+ data_turn = read_json(file_turn_path)
29
+ data_eval = read_json(file_eval_path)
30
+
31
+ # 初始化统计字典
32
+ stats = defaultdict(lambda: {"count": 0, "search_count": 0, "acc": 0, "em": 0, "f1": 0})
33
+
34
+
35
+
36
+ # 遍历数据,按 topic 进行统计
37
+ for item_ori, item_turn, item_eval in zip(data_original_question, data_turn, data_eval):
38
+ assert item_ori["id"] == item_turn["item"]["id"] == item_eval["id"], "ID mismatch"
39
+ topic = item_ori["metadata"]["topic"]
40
+ search_count = item_turn["search_count"]
41
+ acc = item_eval["Metrics"]["acc"]
42
+ em = item_eval["Metrics"]["em"]
43
+ f1 = item_eval["Metrics"]["f1"]
44
+
45
+
46
+ stats[topic]["count"] += 1
47
+ stats[topic]["search_count"] += search_count
48
+ stats[topic]["acc"] += acc
49
+ stats[topic]["em"] += em
50
+ stats[topic]["f1"] += f1
51
+
52
+ # 不分topic,统计所有的
53
+ stats["all"]["count"] += 1
54
+ stats["all"]["search_count"] += search_count
55
+ stats["all"]["acc"] += acc
56
+ stats["all"]["em"] += em
57
+ stats["all"]["f1"] += f1
58
+
59
+ output_stats_txt_file = os.path.join(os.path.dirname(file_turn_path), "topics_stats.txt")
60
+
61
+ # 计算平均值
62
+ avg_stats = {}
63
+ for topic, values in stats.items():
64
+ count = values["count"]
65
+ avg_stats[topic] = {
66
+ "count": count,
67
+ "percentage": count / len(data_turn),
68
+ "search_count": values["search_count"] / count,
69
+ "acc": values["acc"] / count,
70
+ "em": values["em"] / count,
71
+ "f1": values["f1"] / count,
72
+ }
73
+
74
+ avg_stats = dict(sorted(avg_stats.items()))
75
+
76
+ # 输出统计数据
77
+ # print("Topic Statistics:")
78
+ # for topic, metrics in avg_stats.items():
79
+ # print(f"Topic: {topic}")
80
+ # print(f" Count: {metrics['count']}")
81
+ # print(f" Percentage: {metrics['percentage']:.2%}")
82
+ # print(f" Average Search Count: {metrics['search_count']:.2f}")
83
+ # print(f" Average Accuracy (acc): {metrics['acc']:.2f}")
84
+ # print(f" Average Exact Match (em): {metrics['em']:.2f}")
85
+ # print(f" Average F1 Score: {metrics['f1']:.2f}")
86
+
87
+ with open(output_stats_txt_file, "w", encoding="utf-8") as f:
88
+ f.write("Topic Statistics:\n")
89
+ for topic, metrics in avg_stats.items():
90
+ f.write(f"Topic: {topic}\n")
91
+ f.write(f" Count: {metrics['count']}\n")
92
+ f.write(f" Percentage: {metrics['percentage']:.2%}\n")
93
+ f.write(f" Average Search Count: {metrics['search_count']:.2f}\n")
94
+ f.write(f" Average Accuracy (acc): {metrics['acc']:.2f}\n")
95
+ f.write(f" Average Exact Match (em): {metrics['em']:.2f}\n")
96
+ f.write(f" Average F1 Score: {metrics['f1']:.2f}\n")
97
+ f.write("\n")
98
+ # 绘制图表
99
+ topics = list(avg_stats.keys())
100
+ search_counts = [metrics["search_count"] for metrics in avg_stats.values()]
101
+ accs = [metrics["acc"] for metrics in avg_stats.values()]
102
+ ems = [metrics["em"] for metrics in avg_stats.values()]
103
+ f1s = [metrics["f1"] for metrics in avg_stats.values()]
104
+ percentage = [metrics["percentage"] for metrics in avg_stats.values()]
105
+
106
+
107
+ x = np.arange(len(topics)) # 横坐标
108
+ width = 0.15 # 柱状图宽度
109
+
110
+ fig, ax = plt.subplots(figsize=(20, 12))
111
+ rects1 = ax.bar(x - 2.5 * width, search_counts, width, label="Search Count")
112
+ rects2 = ax.bar(x - 1.5 * width, accs, width, label="Accuracy (acc)")
113
+ rects3 = ax.bar(x - 0.5 * width, ems, width, label="Exact Match (em)")
114
+ rects4 = ax.bar(x + 0.5 * width, f1s, width, label="F1 Score")
115
+ rects5 = ax.bar(x + 1.5 * width, percentage, width, label="Percentage") # 新增的柱状图
116
+
117
+
118
+
119
+ # 添加标签和标题
120
+ ax.set_xlabel("Topics")
121
+ ax.set_ylabel("Average Values")
122
+ ax.set_title("Average Metrics by Topic")
123
+ ax.set_xticks(x)
124
+ ax.set_xticklabels(topics, rotation=45, ha="right")
125
+ ax.legend()
126
+
127
+ # 显示图表
128
+ plt.tight_layout()
129
+ plt.show()
130
+
131
+ figure_path = os.path.join(os.path.dirname(file_turn_path), "topics_stats.png")
132
+ plt.savefig(figure_path)
133
+ return avg_stats
134
+
135
+
136
+ file_original_path="/share/project/sunshuang/simpleqa_gen_data/data/simple_qa_test_set_format_with_metadata.json"
137
+ file_turn_path="/share/project/sunshuang/deep_research/search_o1/output/outputs_sum_all_webpage_simpleqa500_ckpt176/turn_12.json"
138
+ file_eval_path="/share/project/sunshuang/deep_research/search_o1/output/outputs_sum_all_webpage_simpleqa500_ckpt176/test.3.11,14:55.json"
139
+
140
+ avg_stats = topics_stats(file_original_path, file_turn_path, file_eval_path)
deep_search/search_o1/eval/utils.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ num2alpha = {
2
+ 'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'ten': '10', 'eleven': '11', 'twelve': '12', 'thirteen': '13', 'fourteen': '14', 'fifteen': '15', 'sixteen': '16', 'seventeen': '17', 'eighteen': '18', 'nineteen': '19', 'twenty': '20', 'thirty': '30', 'forty': '40', 'fifty': '50', 'sixty': '60', 'seventy': '70', 'eighty': '80', 'ninety': '90', 'hundred': '100',
3
+ '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen', '20': 'twenty', '30': 'thirty', '40': 'forty', '50': 'fifty', '60': 'sixty', '70': 'seventy', '80': 'eighty', '90': 'ninety', '100': 'hundred',
4
+ }
5
+ import argparse
6
+ import collections
7
+ import json
8
+ import copy
9
+ import os
10
+ import re
11
+ import logging
12
+ import string
13
+ from typing import List
14
+ import regex
15
+ import unicodedata
16
+ from tqdm import tqdm
17
+
18
+
19
+ logger = logging.getLogger()
20
+
21
+
22
+ class Tokens(object):
23
+ """A class to represent a list of tokenized text."""
24
+ TEXT = 0
25
+ TEXT_WS = 1
26
+ SPAN = 2
27
+ POS = 3
28
+ LEMMA = 4
29
+ NER = 5
30
+
31
+ def __init__(self, data, annotators, opts=None):
32
+ self.data = data
33
+ self.annotators = annotators
34
+ self.opts = opts or {}
35
+
36
+ def __len__(self):
37
+ """The number of tokens."""
38
+ return len(self.data)
39
+
40
+ def slice(self, i=None, j=None):
41
+ """Return a view of the list of tokens from [i, j)."""
42
+ new_tokens = copy.copy(self)
43
+ new_tokens.data = self.data[i: j]
44
+ return new_tokens
45
+
46
+ def untokenize(self):
47
+ """Returns the original text (with whitespace reinserted)."""
48
+ return ''.join([t[self.TEXT_WS] for t in self.data]).strip()
49
+
50
+ def words(self, uncased=False):
51
+ """Returns a list of the text of each token
52
+ Args:
53
+ uncased: lower cases text
54
+ """
55
+ if uncased:
56
+ return [t[self.TEXT].lower() for t in self.data]
57
+ else:
58
+ return [t[self.TEXT] for t in self.data]
59
+
60
+ def offsets(self):
61
+ """Returns a list of [start, end) character offsets of each token."""
62
+ return [t[self.SPAN] for t in self.data]
63
+
64
+ def pos(self):
65
+ """Returns a list of part-of-speech tags of each token.
66
+ Returns None if this annotation was not included.
67
+ """
68
+ if 'pos' not in self.annotators:
69
+ return None
70
+ return [t[self.POS] for t in self.data]
71
+
72
+ def lemmas(self):
73
+ """Returns a list of the lemmatized text of each token.
74
+ Returns None if this annotation was not included.
75
+ """
76
+ if 'lemma' not in self.annotators:
77
+ return None
78
+ return [t[self.LEMMA] for t in self.data]
79
+
80
+ def entities(self):
81
+ """Returns a list of named-entity-recognition tags of each token.
82
+ Returns None if this annotation was not included.
83
+ """
84
+ if 'ner' not in self.annotators:
85
+ return None
86
+ return [t[self.NER] for t in self.data]
87
+
88
+ def ngrams(self, n=1, uncased=False, filter_fn=None, as_strings=True):
89
+ """Returns a list of all ngrams from length 1 to n.
90
+ Args:
91
+ n: upper limit of ngram length
92
+ uncased: lower cases text
93
+ filter_fn: user function that takes in an ngram list and returns
94
+ True or False to keep or not keep the ngram
95
+ as_string: return the ngram as a string vs list
96
+ """
97
+
98
+ def _skip(gram):
99
+ if not filter_fn:
100
+ return False
101
+ return filter_fn(gram)
102
+
103
+ words = self.words(uncased)
104
+ ngrams = [(s, e + 1)
105
+ for s in range(len(words))
106
+ for e in range(s, min(s + n, len(words)))
107
+ if not _skip(words[s:e + 1])]
108
+
109
+ # Concatenate into strings
110
+ if as_strings:
111
+ ngrams = ['{}'.format(' '.join(words[s:e])) for (s, e) in ngrams]
112
+
113
+ return ngrams
114
+
115
+ def entity_groups(self):
116
+ """Group consecutive entity tokens with the same NER tag."""
117
+ entities = self.entities()
118
+ if not entities:
119
+ return None
120
+ non_ent = self.opts.get('non_ent', 'O')
121
+ groups = []
122
+ idx = 0
123
+ while idx < len(entities):
124
+ ner_tag = entities[idx]
125
+ # Check for entity tag
126
+ if ner_tag != non_ent:
127
+ # Chomp the sequence
128
+ start = idx
129
+ while (idx < len(entities) and entities[idx] == ner_tag):
130
+ idx += 1
131
+ groups.append((self.slice(start, idx).untokenize(), ner_tag))
132
+ else:
133
+ idx += 1
134
+ return groups
135
+
136
+
137
+ class Tokenizer(object):
138
+ """Base tokenizer class.
139
+ Tokenizers implement tokenize, which should return a Tokens class.
140
+ """
141
+
142
+ def tokenize(self, text):
143
+ raise NotImplementedError
144
+
145
+ def shutdown(self):
146
+ pass
147
+
148
+ def __del__(self):
149
+ self.shutdown()
150
+
151
+
152
+ class SimpleTokenizer(Tokenizer):
153
+ ALPHA_NUM = r'[\p{L}\p{N}\p{M}]+'
154
+ NON_WS = r'[^\p{Z}\p{C}]'
155
+
156
+ def __init__(self, **kwargs):
157
+ """
158
+ Args:
159
+ annotators: None or empty set (only tokenizes).
160
+ """
161
+ self._regexp = regex.compile(
162
+ '(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS),
163
+ flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE
164
+ )
165
+ if len(kwargs.get('annotators', {})) > 0:
166
+ logger.warning('%s only tokenizes! Skipping annotators: %s' %
167
+ (type(self).__name__, kwargs.get('annotators')))
168
+ self.annotators = set()
169
+
170
+ def tokenize(self, text):
171
+ data = []
172
+ matches = [m for m in self._regexp.finditer(text)]
173
+ for i in range(len(matches)):
174
+ # Get text
175
+ token = matches[i].group()
176
+
177
+ # Get whitespace
178
+ span = matches[i].span()
179
+ start_ws = span[0]
180
+ if i + 1 < len(matches):
181
+ end_ws = matches[i + 1].span()[0]
182
+ else:
183
+ end_ws = span[1]
184
+
185
+ # Format data
186
+ data.append((
187
+ token,
188
+ text[start_ws: end_ws],
189
+ span,
190
+ ))
191
+ return Tokens(data, self.annotators)
192
+
193
+ tokenizer = SimpleTokenizer()
194
+
195
+ def normalize_span(text):
196
+ text = unicodedata.normalize('NFD', text)
197
+ text = tokenizer.tokenize(text).words(uncased=False)
198
+ return ' '.join(text), len(text)
199
+
200
+ def has_answer(answers, text, match_type="string"):
201
+ # print(answers, text)
202
+ # input()
203
+ text = unicodedata.normalize('NFD', text)
204
+ if match_type == 'string':
205
+ text = tokenizer.tokenize(text).words(uncased=True)
206
+ for single_answer in answers:
207
+ single_answer = unicodedata.normalize('NFD', single_answer)
208
+ single_answer = tokenizer.tokenize(single_answer)
209
+ single_answer = single_answer.words(uncased=True)
210
+ for i in range(0, len(text) - len(single_answer) + 1):
211
+ if single_answer == text[i: i + len(single_answer)]:
212
+ return 1
213
+ return 0
214
+
215
+ import unicodedata
216
+
217
+ def fake_answer(answers, text, fake_ans, match_type="string"):
218
+ answers = might_right_answers(answers) + expand_answers(answers)
219
+ # Normalize the input text
220
+ text = unicodedata.normalize('NFD', text)
221
+ if match_type == 'string':
222
+ otext = tokenizer.tokenize(text).words(uncased=False)
223
+ oo = ' '.join(otext)
224
+ text = tokenizer.tokenize(text).words(uncased=True)
225
+ for single_answer in answers:
226
+ single_answer = unicodedata.normalize('NFD', single_answer)
227
+ single_answer = tokenizer.tokenize(single_answer)
228
+ single_answer = single_answer.words(uncased=True)
229
+ for i in range(0, len(text) - len(single_answer) + 1):
230
+ if single_answer == text[i: i + len(single_answer)]:
231
+ ss = ' '.join(otext[i: i + len(single_answer)])
232
+
233
+ oo = oo.replace(ss, fake_ans)
234
+ return clean_text(oo)
235
+
236
+ def clean_text(text):
237
+ # 定义一个正则表达式模式,用于去除标点符号后面的多余空格
238
+ # 这里定义了一些常见的英文标点符号
239
+ pattern_remove_trailing_spaces = r'([,.!?;:\(\)\[\]\{\}—–—])\s+'
240
+
241
+ # 定义一个正则表达式模式,用于去除标点符号前面的多余空格
242
+ pattern_remove_leading_spaces = r'\s+([,.!?;:\(\)\[\]\{\}—–—])'
243
+
244
+ # 定义一个正则表达式模式,确保标点符号前后至少保留一个空格
245
+ pattern_preserve_single_space = r'(\s*)([,.!?;:\(\)\[\]\{\}—–—])(\s*)'
246
+
247
+ # 去除标点符号后面的多余空格
248
+ cleaned_text = re.sub(pattern_remove_trailing_spaces, r'\1 ', text)
249
+
250
+ # 去除标点符号前面的多余空格
251
+ cleaned_text = re.sub(pattern_remove_leading_spaces, r' \1', cleaned_text)
252
+
253
+ # 确保标点符号前后至少保留一个空格
254
+ cleaned_text = re.sub(pattern_preserve_single_space, r' \2 ', cleaned_text)
255
+
256
+ # 去除首尾空白
257
+ cleaned_text = cleaned_text.strip()
258
+
259
+ # 最终去除连续的空格
260
+ cleaned_text = re.sub(r'\s+', ' ', cleaned_text)
261
+
262
+ return cleaned_text
263
+
264
+
265
+ def expand_answers(answers: List[str]):
266
+ copy_answers = answers.copy()
267
+ res = set(answers)
268
+ for single_answer in answers:
269
+ if normalize_answer(single_answer) != "":
270
+ res.add(normalize_answer(single_answer))
271
+ original_answer = single_answer
272
+ single_answer = unicodedata.normalize('NFD', single_answer)
273
+ single_answer = tokenizer.tokenize(single_answer)
274
+ single_answer = single_answer.words(uncased=True)
275
+ for idx, word in enumerate(single_answer):
276
+ if word in num2alpha.keys():
277
+ cnt = 0
278
+ for word_before in single_answer[:idx]:
279
+ if word in word_before:
280
+ cnt += 1
281
+ pos = 0
282
+ while pos < len(original_answer) - len(word) + 1:
283
+ if original_answer[pos:].startswith(word):
284
+ if cnt == 0:
285
+ res.add(original_answer[:pos] + num2alpha[word] + original_answer[pos+len(word):])
286
+ break
287
+ pos += len(word)
288
+ cnt -= 1
289
+ else:
290
+ pos += 1
291
+ for i in res:
292
+ if i.lower() not in [c.lower() for c in copy_answers] and i != "":
293
+ copy_answers.append(i)
294
+ return copy_answers
295
+
296
+ def might_right_answers(answers):
297
+ ans = set(answers)
298
+ res = set()
299
+ for single_answer in answers:
300
+ original_answer = single_answer
301
+ single_answer = unicodedata.normalize('NFD', single_answer)
302
+ single_answer = tokenizer.tokenize(single_answer)
303
+ single_answer = single_answer.words(uncased=True)
304
+ for idx, word in enumerate(single_answer):
305
+ for spand_len in range(1, len(single_answer)):
306
+ cand_fake_ans = " ".join(single_answer[:idx] + single_answer[idx + spand_len:])
307
+ if _remove_proj(normalize_answer(cand_fake_ans)).replace(" ","") != "":
308
+ res.add(cand_fake_ans)
309
+ return list(res - ans)
310
+
311
+ def _remove_proj(text):
312
+ text = re.sub(r"\b(in|on|at|by|with|for|of|to)\b", " ", text)
313
+ return text
314
+
315
+ def normalize_answer(s):
316
+ def remove_articles(text):
317
+ return re.sub(r"\b(a|an|the)\b", " ", text)
318
+
319
+ def white_space_fix(text):
320
+ return " ".join(text.split())
321
+
322
+ def remove_punc(text):
323
+ exclude = set(string.punctuation)
324
+ return "".join(ch for ch in text if ch not in exclude)
325
+
326
+ def lower(text):
327
+ return text.lower()
328
+
329
+ return white_space_fix(remove_articles(remove_punc(lower(s))))
330
+
331
+ def EM_compute(answer_list, prediction):
332
+ return max([int(normalize_answer(prediction) == normalize_answer(ground_truth)) for ground_truth in answer_list])
333
+
334
+ def AC_compute(answer_list, prediction):
335
+ pred = normalize_answer(prediction)
336
+ for answer in answer_list:
337
+ if normalize_answer(answer) in pred:
338
+ return 1
339
+ return 0
340
+
341
+
342
+ def F1_compute(answers, pred):
343
+ def get_tokens(s):
344
+ if not s: return []
345
+ return normalize_answer(s).split()
346
+
347
+ def compute_f1(a_gold, a_pred):
348
+ gold_toks = get_tokens(a_gold)
349
+ pred_toks = get_tokens(a_pred)
350
+ common = collections.Counter(gold_toks) & collections.Counter(pred_toks)
351
+ num_same = sum(common.values())
352
+ if len(gold_toks) == 0 or len(pred_toks) == 0:
353
+ # If either is no-answer, then F1 is 1 if they agree, 0 otherwise
354
+ return int(gold_toks == pred_toks)
355
+ if num_same == 0:
356
+ return 0
357
+ precision = 1.0 * num_same / len(pred_toks)
358
+ recall = 1.0 * num_same / len(gold_toks)
359
+ f1 = (2 * precision * recall) / (precision + recall)
360
+ return f1
361
+ return max([compute_f1(x, pred) for x in answers])
362
+
363
+
364
+ def deal_judge(pred):
365
+ if pred is None:
366
+ return True
367
+ if has_answer(["unknown", "no specific answer", "not provide", "cannot answer", "no information provided", "no answer", "not contain", "no definitive answer"], pred):
368
+ return True
369
+ return False
370
+
371
+
372
+ def deal_answer(pred, answers):
373
+ if pred is None:
374
+ return 0, 0
375
+ if pred.lower().startswith("answer:"):
376
+ pred = pred[7:]
377
+ return EM_compute(answers, pred), F1_compute(answers, pred)
378
+
379
+
380
+ def deal_post(pred):
381
+ giveup, istrue = True, None
382
+ if pred is None:
383
+ return giveup, istrue
384
+ if has_answer(["unclear", "not clear", "unknown", "partially correct", "partially incorrect", "not correct", "cannot determine", "cannot answer", "not incorrect", "incomplete"], pred):
385
+ giveup = True
386
+ elif has_answer(["correct", "true"], pred):
387
+ giveup, istrue = False, True
388
+ elif has_answer(["incorrect", "false"], pred):
389
+ giveup, istrue = False, False
390
+ else:
391
+ giveup = True
392
+ return giveup, istrue
393
+
394
+
395
+ def str2paras(s):
396
+ if s is None:
397
+ return None
398
+ paras = []
399
+ for text in s.split('\n'):
400
+ if text.strip() != '':
401
+ paras.append(": " + text)
402
+ return paras
403
+
404
+
405
+ # if __name__ == "__main__":
406
+ # file_list = os.listdir('d:/pycharmfiles/chat')
407
+
408
+ # for file in file_list:
409
+ # if not file.endswith('post'):
410
+ # continue
411
+ # print(file)
412
+ # indir = os.path.join('d:/pycharmfiles/chat', file)
413
+ # outdir = os.path.join('d:/pycharmfiles/llm_re/nq/data', file)
414
+ # outstr = ""
415
+ # infile = open(indir, 'r', encoding='utf-8')
416
+ # for line in tqdm(infile.readlines()):
417
+ # d = json.loads(line)
418
+ # if 'Prediction' in d.keys():
419
+ # d['Giveup'], d['EM'], d['F1'] = deal_answer(d['Prediction'], d['reference'])
420
+ # if 'Post' in d.keys():
421
+ # d['Post_Giveup'], d['Post_True']= deal_post(d['Post'])
422
+ # outstr += json.dumps(d) + '\n'
423
+ # infile.close()
424
+ # outfile = open(outdir, 'w', encoding='utf-8')
425
+ # outfile.write(outstr)
426
+ # outfile.close()
427
+
428
+
429
+ def load_source(file):
430
+ data = []
431
+ f = open(file, 'r', encoding='utf-8')
432
+ for line in f.readlines():
433
+ data.append(json.loads(line))
434
+ f.close()
435
+ return data
436
+
437
+
438
+ def remove_punctuation(s):
439
+ punctuation_pattern = r"^[^\w\s]+|[^\w\s]+$"
440
+ return re.sub(punctuation_pattern, '', s)
441
+
442
+
443
+ def save_file(args, results, add='res'):
444
+ save_dir = os.path.dirname(args.data)
445
+ model_base_file = os.path.basename(args.model) + \
446
+ "." + os.path.basename(args.data)[:-len(".json")]
447
+ if args.splits:
448
+ model_base_file += f".{args.worker}-{args.splits}"
449
+ with open(os.path.join(save_dir, f"{model_base_file}.{add}.json"), 'w') as f:
450
+ json.dump(results, f, indent=4)
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/gen.4.9,15:24.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea9bb9b95b1a7813082eef8f31ef07d78869ecf769d08852fc77762b4789a509
3
+ size 58610597
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/gen.4.9,3:34.info_extract.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6b59bc3b800fca781eaa5b051e855d7ea98eef6513531ef1a4ac114f0b6ccde
3
+ size 48303197
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_12.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00016c066349ac779557dce2f811affb385966566039443567e1dba9cfa96e31
3
+ size 53524353
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_13.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f4df36885215f33982031e3ced147404b67acfa4c35187ccb5878393cc4c8bb
3
+ size 53535044
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_5.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03e3acbcd2768a6a917cc41453135c3371f73cc5e82e1d13f50357275df2fad0
3
+ size 51836135
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_8.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:702a316a95c1110d6751304084ae60d7daa85685f21f41e1d8d9385476836d68
3
+ size 53030296
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_9.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9789860766b42d7df26668ad591509ec0c87693dd1e19218ba0b57e5849db69a
3
+ size 53349940
deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/combined_output_length_distribution.png ADDED

Git LFS Details

  • SHA256: 39f9b57cbc763c295a5ee9e0d74329f201b9454f70acc061eacdf874a519fcab
  • Pointer size: 130 Bytes
  • Size of remote file: 92.1 kB