diff --git a/.gitattributes b/.gitattributes index b1875d6579e56307fbdbd99002635ebc208434a9..ce23a8ed6dd08105314b770e4dff749ad73e2b9b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2203,3 +2203,30 @@ deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_ 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 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 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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 diff --git a/deep_search/DeepResearcher/.gitignore b/deep_search/DeepResearcher/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0a197900e25d259ab4af2e31e78501787d7a6daa --- /dev/null +++ b/deep_search/DeepResearcher/.gitignore @@ -0,0 +1,174 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc diff --git a/deep_search/DeepResearcher/LICENSE b/deep_search/DeepResearcher/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/deep_search/DeepResearcher/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/deep_search/DeepResearcher/Notice.txt b/deep_search/DeepResearcher/Notice.txt new file mode 100644 index 0000000000000000000000000000000000000000..ade439da525ac3f82936e131a1ae386f43207fd8 --- /dev/null +++ b/deep_search/DeepResearcher/Notice.txt @@ -0,0 +1 @@ +Copyright 2023-2024 Bytedance Ltd. and/or its affiliates \ No newline at end of file diff --git a/deep_search/DeepResearcher/README.md b/deep_search/DeepResearcher/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d6523ddb9047cb189bb244ba91d633066542e851 --- /dev/null +++ b/deep_search/DeepResearcher/README.md @@ -0,0 +1,127 @@ +# DeepResearcher: Scaling Deep Research via Reinforcement Learning in Real-world Environments + +## 📝 Introduction + +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. + + + +

+    +    +

+ + +## 📋 Table of Contents + +- [Introduction](#-introduction) +- [Model](#-Model) +- [Performance](#-performance) +- [Get started](#-get-started) +- [Acknowledgement](#-Acknowledgement) +- [Citation](#✍️-citation) + + + + +## 🤖 Model +DeepResearcher is now available on huggingface-hub: +| Model Name | HF Checkpoint | Size | +| ---------- | ------------------------------------------------------------ | :------: | +| DeepResearcher-7b | [🤗 GAIR/DeepResearcher-7b](https://huggingface.co/GAIR/DeepResearcher-7b) | **7B** + + +## 🏆 Performance + +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. + +

+ +

+ + +## 🚀 Get Started + +### Package Installation + +To begin using this repo, you need to install the required dependencies. You can do this by running the following command: + +```bash +git clone https://github.com/GAIR-NLP/DeepResearcher.git +conda create -n deepresearcher python=3.10 +conda activate deepresearcher +cd DeepResearcher +pip3 install torch==2.4.0 --index-url https://download.pytorch.org/whl/cu124 +pip3 install flash-attn --no-build-isolation +cd verl +pip3 install -e . +cd ../ +pip3 install -r requirements.txt +``` + +### Start ray before training and inference +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**). +Here is the code of the head node: +```bash +export PET_NODE_RANK=0 +ray start --head +``` + +### Run backend handler + +Running the following command to launch the server handler: +1. Modify ```serper_api_key``` or ```azure_bing_search_subscription_key``` & ```search_engine``` in ```./scrl/handler/config.yaml``` +2. Add ```qwen-plus``` api key in ```./scrl/handler/server_handler.py``` +```python +client = OpenAI( + api_key="sk-xxx", + base_url="xxxx" +) +``` +3. Start server handler: +```bash + python ./scrl/handler/server_handler.py +``` + +After launching all server handlers, you can replace ```server_url_list``` in ```./scrl/handler/config.yaml``` in your training host node and then run: +```bash + python ./scrl/handler/handler.py +``` +### Training model + +Using the following command to train the model: +```bash + bash train_grpo.sh +``` + +### Evaluate +Using the following command to generate rollout: +```bash + bash evaluate.sh +``` +You can find the rollout file in: ```./outputs/{project_name}/{experiment_name}/rollout/rollout_step_0.json``` +You can rename and copy it into ```./evaluate/{experiment_name}_result.json``` + +Then, run the following command: +```bash + python ./evaluate/cacluate_metrics.py {experiment_name} +``` +You can check the score in ```./evaluate/{experiment_name}_score.json``` + +## 🙏 Acknowledgement + +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. + +## ✍️ Citation + +Please cite the repo if the model/code/conclusion in this repo are helpful to you. +``` +@misc{deepresearch, + author = {Zheng, Yuxiang and Fu, Dayuan and Hu, Xiangkun and Cai, Xiaojie and Ye, Lyumanshan and Lu, Pengrui and Liu, Pengfei}, + title = {DeepResearcher: Scaling Deep Research via Reinforcement Learning in Real-world Environments}, + year = {2025}, + publisher = {GitHub}, + journal = {GitHub repository}, + howpublished = {\url{https://github.com/GAIR-NLP/DeepResearcher}}, +} +``` diff --git a/deep_search/DeepResearcher/VERL_README.md b/deep_search/DeepResearcher/VERL_README.md new file mode 100644 index 0000000000000000000000000000000000000000..79326d9ad873f576a557887204628876c8d87bd6 --- /dev/null +++ b/deep_search/DeepResearcher/VERL_README.md @@ -0,0 +1,147 @@ +

verl: Volcano Engine Reinforcement Learning for LLM

+ +verl is a flexible, efficient and production-ready RL training library for large language models (LLMs). + +verl is the open-source version of **[HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2)** paper. + +verl is flexible and easy to use with: + +- **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. + +- **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. + +- **Flexible device mapping**: Supports various placement of models onto different sets of GPUs for efficient resource utilization and scalability across different cluster sizes. + +- Readily integration with popular HuggingFace models + + +verl is fast with: + +- **State-of-the-art throughput**: By seamlessly integrating existing SOTA LLM training and inference frameworks, verl achieves high generation and training throughput. + +- **Efficient actor model resharding with 3D-HybridEngine**: Eliminates memory redundancy and significantly reduces communication overhead during transitions between training and generation phases. + +

+| Documentation | Paper | Slack | Wechat | Twitter + + +

+ +## News +- [2025/3] We will present verl(HybridFlow) at [EuroSys 2025](https://2025.eurosys.org/). See you in in Rotterdam! +- [2025/2] verl v0.2.0.post1 is released! See [release note](https://github.com/volcengine/verl/releases/) for details. +- [2025/2] We presented verl in the [Bytedance/NVIDIA/Anyscale Ray Meetup](https://lu.ma/ji7atxux). See you in San Jose! +- [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). +- [2024/12] The team presented Post-training LLMs: From Algorithms to Infrastructure 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. +- [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). +- [2024/10] verl is presented at Ray Summit. [Youtube video](https://www.youtube.com/watch?v=MrhMcXkXvJU&list=PLzTswPQNepXntmT8jr9WaNfqQ60QwW7-U&index=37) available. +- [2024/08] HybridFlow (verl) is accepted to EuroSys 2025. + +## Key Features + +- **FSDP** and **Megatron-LM** for training. +- **vLLM** and **HF Transformers** for rollout generation, **SGLang** support coming soon. +- Compatible with Hugging Face Transformers. +- Supervised fine-tuning. +- 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. + - Support model-based reward and function-based reward (verifiable reward) + - Support vision-language models (VLMs) and [multi-modal RL](examples/grpo_trainer/run_qwen2_5_vl-7b.sh) +- 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). +- Scales up to 70B models and hundreds of GPUs. +- Experiment tracking with wandb, swanlab, mlflow and tensorboard. + +## Upcoming Features +- Reward model training +- DPO training +- DeepSeek integration with Megatron v0.11 +- SGLang integration + +## Getting Started + +**Quickstart:** +- [Installation](https://verl.readthedocs.io/en/latest/start/install.html) +- [Quickstart](https://verl.readthedocs.io/en/latest/start/quickstart.html) +- [Programming Guide](https://verl.readthedocs.io/en/latest/hybrid_flow.html) + +**Running a PPO example step-by-step:** +- Data and Reward Preparation + - [Prepare Data for Post-Training](https://verl.readthedocs.io/en/latest/preparation/prepare_data.html) + - [Implement Reward Function for Dataset](https://verl.readthedocs.io/en/latest/preparation/reward_function.html) +- Understanding the PPO Example + - [PPO Example Architecture](https://verl.readthedocs.io/en/latest/examples/ppo_code_architecture.html) + - [Config Explanation](https://verl.readthedocs.io/en/latest/examples/config.html) + - [Run GSM8K Example](https://verl.readthedocs.io/en/latest/examples/gsm8k_example.html) + +**Reproducible algorithm baselines:** +- [PPO, GRPO, ReMax](https://verl.readthedocs.io/en/latest/experiment/ppo.html) + +**For code explanation and advance usage (extension):** +- PPO Trainer and Workers + - [PPO Ray Trainer](https://verl.readthedocs.io/en/latest/workers/ray_trainer.html) + - [PyTorch FSDP Backend](https://verl.readthedocs.io/en/latest/workers/fsdp_workers.html) + - [Megatron-LM Backend](https://verl.readthedocs.io/en/latest/index.html) +- Advance Usage and Extension + - [Ray API design tutorial](https://verl.readthedocs.io/en/latest/advance/placement.html) + - [Extend to Other RL(HF) algorithms](https://verl.readthedocs.io/en/latest/advance/dpo_extension.html) + - [Add Models with the FSDP Backend](https://verl.readthedocs.io/en/latest/advance/fsdp_extension.html) + - [Add Models with the Megatron-LM Backend](https://verl.readthedocs.io/en/latest/advance/megatron_extension.html) + - [Deployment using Separate GPU Resources](https://github.com/volcengine/verl/tree/main/examples/split_placement) + +**Blogs from the community** +- [使用verl进行GRPO分布式强化学习训练最佳实践](https://www.volcengine.com/docs/6459/1463942) +- [HybridFlow veRL 原文浅析](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/readme.md) +- [最高提升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) + +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))! + +## Performance Tuning Guide +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. + +## vLLM v0.7 integration preview +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. + +## Citation and acknowledgement + +If you find the project helpful, please cite: +- [HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2) +- [A Framework for Training Large Language Models for Code Generation via Proximal Policy Optimization](https://i.cs.hku.hk/~cwu/papers/gmsheng-NL2Code24.pdf) + +```tex +@article{sheng2024hybridflow, + title = {HybridFlow: A Flexible and Efficient RLHF Framework}, + 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}, + year = {2024}, + journal = {arXiv preprint arXiv: 2409.19256} +} +``` + +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. + +## Awesome work using verl +- [TinyZero](https://github.com/Jiayi-Pan/TinyZero): a reproduction of **DeepSeek R1 Zero** recipe for reasoning tasks +- [PRIME](https://github.com/PRIME-RL/PRIME): Process reinforcement through implicit rewards +- [RAGEN](https://github.com/ZihanWang314/ragen): a general-purpose reasoning **agent** training framework +- [Logic-RL](https://github.com/Unakar/Logic-RL): a reproduction of DeepSeek R1 Zero on 2K Tiny Logic Puzzle Dataset. +- [deepscaler](https://github.com/agentica-project/deepscaler): iterative context scaling with GRPO +- [critic-rl](https://github.com/HKUNLP/critic-rl): LLM critics for code generation +- [Easy-R1](https://github.com/hiyouga/EasyR1): **Multi-modal** RL training framework +- [self-rewarding-reasoning-LLM](https://arxiv.org/pdf/2502.19613): self-rewarding and correction with **generative reward models** +- [Search-R1](https://github.com/PeterGriffinJin/Search-R1): RL with reasoning and **searching (tool-call)** interleaved LLMs +- [Code-R1](https://github.com/ganler/code-r1): Reproducing R1 for **Code** with Reliable Rewards +- [DQO](https://arxiv.org/abs/2410.09302): Enhancing multi-Step reasoning abilities of language models through direct Q-function optimization +- [FIRE](https://arxiv.org/abs/2410.21236): Flaming-hot initiation with regular execution sampling for large language models +- [ReSearch](https://github.com/Agent-RL/ReSearch): Learning to **Re**ason with **Search** for LLMs via Reinforcement Learning + +## Contribution Guide +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). + +### Code formatting +We use yapf (Google style) to enforce strict code formatting when reviewing PRs. To reformat you code locally, make sure you installed **latest** `yapf` +```bash +pip3 install yapf --upgrade +``` +Then, make sure you are at top level of verl repo and run +```bash +bash scripts/format.sh +``` +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. diff --git a/deep_search/DeepResearcher/evaluate.sh b/deep_search/DeepResearcher/evaluate.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ec4f2aa824f5bb439d59802e7c98e10a62b9575 --- /dev/null +++ b/deep_search/DeepResearcher/evaluate.sh @@ -0,0 +1,51 @@ + +export VLLM_ATTENTION_BACKEND=XFORMERS +export project_name="project_name" +export experiment_name="experiment_name" + + +PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \ + data.train_files=./data/train.parquet \ + data.val_files=./data/test.parquet \ + data.train_batch_size=256 \ + data.max_prompt_length=30767 \ + data.max_response_length=2000 \ + +data.max_model_len=32768 \ + data.data_writing_file=./signal/data.json \ + data.signal_writing_file=./signal/signal.json \ + actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \ + actor_rollout_ref.model.use_remove_padding=true \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.actor.ppo_mini_batch_size=4096 \ + actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=2 \ + actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=2 \ + actor_rollout_ref.rollout.tensor_model_parallel_size=1 \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \ + actor_rollout_ref.rollout.max_num_batched_tokens=32768 \ + actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=2 \ + actor_rollout_ref.actor.use_kl_loss=true \ + actor_rollout_ref.actor.use_dynamic_bsz=true \ + actor_rollout_ref.actor.fsdp_config.param_offload=true \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \ + actor_rollout_ref.ref.fsdp_config.param_offload=true \ + actor_rollout_ref.actor.ppo_max_token_len_per_gpu=12288 \ + actor_rollout_ref.actor.ulysses_sequence_parallel_size=4 \ + critic.optim.lr=1e-5 \ + critic.model.path=Qwen/Qwen2.5-7B-Instruct \ + critic.ppo_micro_batch_size_per_gpu=2 \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.logger=['console','wandb'] \ + trainer.project_name=${project_name} \ + trainer.experiment_name=${experiment_name} \ + +trainer.val_before_train=true \ + trainer.default_hdfs_dir=null \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=1 \ + trainer.test_freq=1 \ + trainer.remove_previous_ckpt_in_save=false \ + agent_grpo.n=16 \ + max_turns=10 \ + search_engine=online_search \ + trainer.total_epochs=1 2>&1 | tee ./${project_name}_${experiment_name}.log + diff --git a/deep_search/DeepResearcher/examples/data_preprocess/full_hh_rlhf.py b/deep_search/DeepResearcher/examples/data_preprocess/full_hh_rlhf.py new file mode 100644 index 0000000000000000000000000000000000000000..07e0884cb916cc5327d39955fcbbb76a596d60c3 --- /dev/null +++ b/deep_search/DeepResearcher/examples/data_preprocess/full_hh_rlhf.py @@ -0,0 +1,146 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +- Preprocess data and split the training set into 75% for training RM and 25% for validting RM. +- All the training data is used to train SFT and RL. +- Both chosen and rejected is used to train SFT +""" +import argparse +import os + +import pandas as pd +from datasets import load_dataset + +from tqdm.auto import tqdm + +from verl.utils.fs import copy, makedirs + + +def generate_sft_dataset(target_hdfs_path_dir, local_dir='~/data/full_hh_rlh/sft'): + dataset = load_dataset('Dahoas/full-hh-rlhf') + output = {'prompt': [], 'response': []} + for data in tqdm(dataset['train']): + # add chosen + output['prompt'].append(data['prompt']) + output['response'].append(data['chosen']) + + # add rejection + output['prompt'].append(data['prompt']) + output['response'].append(data['rejected']) + + df = pd.DataFrame(output) + + local_dir = os.path.expanduser(local_dir) + os.makedirs(local_dir, exist_ok=True) + + local_path = os.path.join(local_dir, 'train.parquet') + + df.to_parquet(path=local_path) + + if target_hdfs_path_dir is not None: + hdfs_dir = target_hdfs_path_dir + '/' + 'train.parquet' + makedirs(hdfs_dir) + + copy(local_path, hdfs_dir) + + +def generate_rm_dataset(target_hdfs_path_dir, local_dir='~/data/full_hh_rlh/rm'): + train_dataset = load_dataset('Dahoas/full-hh-rlhf', split='train[:75%]') + test_dataset = load_dataset('Dahoas/full-hh-rlhf', split='train[-25%:]') + + local_dir = os.path.expanduser(local_dir) + os.makedirs(local_dir, exist_ok=True) + + for dataset, name in zip([train_dataset, test_dataset], ['train', 'test']): + output = {'prompt': [], 'chosen': [], 'rejected': []} + for data in tqdm(dataset): + # add chosen + output['prompt'].append(data['prompt']) + output['chosen'].append(data['chosen']) + output['rejected'].append(data['rejected']) + + df = pd.DataFrame(output) + + local_path = os.path.join(local_dir, name + '.parquet') + + df.to_parquet(path=local_path) + + if target_hdfs_path_dir is not None: + hdfs_dir = target_hdfs_path_dir + '/' + name + '.parquet' + makedirs(hdfs_dir) + + copy(local_path, hdfs_dir) + + +def generate_rl_dataset(target_hdfs_path_dir, local_dir='~/data/full_hh_rlhf/rl'): + dataset = load_dataset('Dahoas/full-hh-rlhf') + train_dataset = dataset['train'] + + data_source = 'Dahoas/full-hh-rlhf' + + # add a row to each data item that represents a unique id + def make_map_fn(split): + + def process_fn(example, idx): + prompt = example.pop('prompt') + response = example.pop('response') + + data = { + "data_source": data_source, + "prompt": [{ + "role": "user", + "content": prompt + }], + "ability": "alignment", + "reward_model": { + "style": "model", + "ground_truth": response # should not be used + }, + "extra_info": { + 'split': split, + 'index': idx + } + } + return data + + return process_fn + + train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True) + local_dir = os.path.expanduser(local_dir) + local_path = os.path.join(local_dir, 'train.parquet') + train_dataset.to_parquet(local_path) + + if target_hdfs_path_dir is not None: + hdfs_dir = target_hdfs_path_dir + '/' + 'train.parquet' + makedirs(hdfs_dir) + + copy(local_path, hdfs_dir) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--split', type=str, choices=['sft', 'rm', 'rl'], required=True) + parser.add_argument('--local_dir', type=str, default='~/data/full_hh_rlhf') + parser.add_argument('--hdfs_dir', type=str, required=False, default=None) + + args = parser.parse_args() + + if args.split == 'sft': + generate_sft_dataset(args.hdfs_dir, os.path.join(args.local_dir, args.split)) + elif args.split == 'rm': + generate_rm_dataset(args.hdfs_dir, os.path.join(args.local_dir, args.split)) + elif args.split == 'rl': + generate_rl_dataset(args.hdfs_dir, os.path.join(args.local_dir, args.split)) + else: + raise NotImplementedError diff --git a/deep_search/DeepResearcher/examples/data_preprocess/geo3k.py b/deep_search/DeepResearcher/examples/data_preprocess/geo3k.py new file mode 100644 index 0000000000000000000000000000000000000000..3a0c776738fccd75bd824e9cd8fd77ce454e0e0d --- /dev/null +++ b/deep_search/DeepResearcher/examples/data_preprocess/geo3k.py @@ -0,0 +1,86 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Preprocess the Geometry3k dataset to parquet format +""" + +import os +import datasets + +from verl.utils.hdfs_io import copy, makedirs +import argparse + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--local_dir', default='~/data/geo3k') + parser.add_argument('--hdfs_dir', default=None) + + args = parser.parse_args() + + data_source = 'hiyouga/geometry3k' + + dataset = datasets.load_dataset(data_source) + + train_dataset = dataset['train'] + test_dataset = dataset['test'] + + instruction_following = ( + r'You FIRST think about the reasoning process as an internal monologue and then provide the final answer. ' + r'The reasoning process MUST BE enclosed within tags. The final answer MUST BE put in \boxed{}.' + ) + + # add a row to each data item that represents a unique id + def make_map_fn(split): + + def process_fn(example, idx): + problem = example.pop('problem') + prompt = problem + ' ' + instruction_following + answer = example.pop('answer') + images = example.pop('images') + + data = { + "data_source": data_source, + "prompt": [{ + "role": "user", + "content": prompt, + }], + "images": images, + "ability": "math", + "reward_model": { + "style": "rule", + "ground_truth": answer + }, + "extra_info": { + 'split': split, + 'index': idx, + 'answer': answer, + "question": problem, + } + } + return data + + return process_fn + + train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True, num_proc=8) + test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True, num_proc=8) + + local_dir = args.local_dir + hdfs_dir = args.hdfs_dir + + train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet')) + test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet')) + + if hdfs_dir is not None: + makedirs(hdfs_dir) + copy(src=local_dir, dst=hdfs_dir) diff --git a/deep_search/DeepResearcher/examples/data_preprocess/gsm8k.py b/deep_search/DeepResearcher/examples/data_preprocess/gsm8k.py new file mode 100644 index 0000000000000000000000000000000000000000..b82d7d71ad588d6b1f4ca01b6ea12fadcc2c3e3f --- /dev/null +++ b/deep_search/DeepResearcher/examples/data_preprocess/gsm8k.py @@ -0,0 +1,94 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Preprocess the GSM8k dataset to parquet format +""" + +import re +import os +import datasets + +from verl.utils.hdfs_io import copy, makedirs +import argparse + + +def extract_solution(solution_str): + solution = re.search("#### (\\-?[0-9\\.\\,]+)", solution_str) + assert solution is not None + final_solution = solution.group(0) + final_solution = final_solution.split('#### ')[1].replace(',', '') + return final_solution + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--local_dir', default='~/data/gsm8k') + parser.add_argument('--hdfs_dir', default=None) + + args = parser.parse_args() + + data_source = 'openai/gsm8k' + + dataset = datasets.load_dataset(data_source, 'main') + + train_dataset = dataset['train'] + test_dataset = dataset['test'] + + instruction_following = "Let's think step by step and output the final answer after \"####\"." + + # add a row to each data item that represents a unique id + def make_map_fn(split): + + def process_fn(example, idx): + question_raw = example.pop('question') + + question = question_raw + ' ' + instruction_following + + answer_raw = example.pop('answer') + solution = extract_solution(answer_raw) + data = { + "data_source": data_source, + "prompt": [{ + "role": "user", + "content": question, + }], + "ability": "math", + "reward_model": { + "style": "rule", + "ground_truth": solution + }, + "extra_info": { + 'split': split, + 'index': idx, + 'answer': answer_raw, + "question": question_raw, + } + } + return data + + return process_fn + + train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True) + test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True) + + local_dir = args.local_dir + hdfs_dir = args.hdfs_dir + + train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet')) + test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet')) + + if hdfs_dir is not None: + makedirs(hdfs_dir) + + copy(src=local_dir, dst=hdfs_dir) diff --git a/deep_search/DeepResearcher/examples/data_preprocess/hellaswag.py b/deep_search/DeepResearcher/examples/data_preprocess/hellaswag.py new file mode 100644 index 0000000000000000000000000000000000000000..39c8e8f55916ffcaa4c8fbedb98c3c710a504cb2 --- /dev/null +++ b/deep_search/DeepResearcher/examples/data_preprocess/hellaswag.py @@ -0,0 +1,102 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Preprocess Hellaswag dataset. + +""" + +import re +import os +import datasets + +from verl.utils.hdfs_io import copy, makedirs +import argparse + + +def preprocess(text): + text = text.strip() + # NOTE: Brackets are artifacts of the WikiHow dataset portion of HellaSwag. + text = text.replace(" [title]", ". ") + text = re.sub("\\[.*?\\]", "", text) + text = text.replace(" ", " ") + return text + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--local_dir', default='/opt/tiger/hellaswag') + parser.add_argument('--hdfs_dir', default=None) + + args = parser.parse_args() + + data_source = 'Rowan/hellaswag' + + dataset = datasets.load_dataset(data_source, trust_remote_code=True) + + train_dataset = dataset['train'] + val_dataset = dataset['validation'] + test_dataset = dataset['test'] + + instruction = 'Please complete the following sentence.\n' + + def make_map_fn(split): + + def process_fn(doc, idx): + ctx = doc["ctx_a"] + " " + doc["ctx_b"].capitalize() + query = preprocess(doc["activity_label"] + ": " + ctx) + choices = [preprocess(ending) for ending in doc["endings"]] + gold = int(doc["label"]) + + data = { + "data_source": data_source, + "prompt": [{ + "role": "user", + "content": query + }], + "ability": "nlp", + "reward_model": { + "style": "model", + "eval": "multiple_choice", # using loglikelihood + "ground_truth": gold, + "choices": choices + }, + "extra_info": { + 'split': split, + 'index': idx + } + } + return data + + return process_fn + + # filter data that doesn't have a label + train_dataset = train_dataset.filter(lambda x: len(x['label']) > 0) + val_dataset = val_dataset.filter(lambda x: len(x['label']) > 0) + test_dataset = test_dataset.filter(lambda x: len(x['label']) > 0) + + train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True) + val_dataset = val_dataset.map(function=make_map_fn('validation'), with_indices=True) + test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True) + + local_dir = args.local_dir + hdfs_dir = args.hdfs_dir + + train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet')) + val_dataset.to_parquet(os.path.join(local_dir, 'validation.parquet')) + test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet')) + + if hdfs_dir is not None: + makedirs(hdfs_dir) + + copy(src=local_dir, dst=hdfs_dir) diff --git a/deep_search/DeepResearcher/examples/data_preprocess/math_dataset.py b/deep_search/DeepResearcher/examples/data_preprocess/math_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..dc70d994ce60748af966217fc49058cf7a861b33 --- /dev/null +++ b/deep_search/DeepResearcher/examples/data_preprocess/math_dataset.py @@ -0,0 +1,91 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Preprocess the GSM8k dataset to parquet format +""" + +import os +import datasets + +from verl.utils.hdfs_io import copy, makedirs +import argparse + +from verl.utils.reward_score.math import remove_boxed, last_boxed_only_string + + +def extract_solution(solution_str): + return remove_boxed(last_boxed_only_string(solution_str)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--local_dir', default='~/data/math') + parser.add_argument('--hdfs_dir', default=None) + + args = parser.parse_args() + + # 'lighteval/MATH' is no longer available on huggingface. + # Use mirror repo: DigitalLearningGmbH/MATH-lighteval + data_source = 'DigitalLearningGmbH/MATH-lighteval' + print(f"Loading the {data_source} dataset from huggingface...", flush=True) + dataset = datasets.load_dataset(data_source, trust_remote_code=True) + + train_dataset = dataset['train'] + test_dataset = dataset['test'] + + instruction_following = "Let's think step by step and output the final answer within \\boxed{}." + + # add a row to each data item that represents a unique id + def make_map_fn(split): + + def process_fn(example, idx): + question = example.pop('problem') + + question = question + ' ' + instruction_following + + answer = example.pop('solution') + solution = extract_solution(answer) + data = { + "data_source": data_source, + "prompt": [{ + "role": "user", + "content": question + }], + "ability": "math", + "reward_model": { + "style": "rule", + "ground_truth": solution + }, + "extra_info": { + 'split': split, + 'index': idx + } + } + return data + + return process_fn + + train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True) + test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True) + + local_dir = args.local_dir + hdfs_dir = args.hdfs_dir + + train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet')) + test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet')) + + if hdfs_dir is not None: + makedirs(hdfs_dir) + + copy(src=local_dir, dst=hdfs_dir) diff --git a/deep_search/DeepResearcher/examples/grpo_trainer/run_deepseek7b_llm.sh b/deep_search/DeepResearcher/examples/grpo_trainer/run_deepseek7b_llm.sh new file mode 100644 index 0000000000000000000000000000000000000000..21562caa2f767715777ee2924ba054f44b67894e --- /dev/null +++ b/deep_search/DeepResearcher/examples/grpo_trainer/run_deepseek7b_llm.sh @@ -0,0 +1,37 @@ +set -x + +python3 -m verl.trainer.main_ppo \ + algorithm.adv_estimator=grpo \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.train_batch_size=1024 \ + data.max_prompt_length=512 \ + data.max_response_length=1024 \ + actor_rollout_ref.model.path=deepseek-ai/deepseek-llm-7b-chat \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.model.use_remove_padding=True \ + actor_rollout_ref.actor.ppo_mini_batch_size=256 \ + actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=80 \ + actor_rollout_ref.actor.use_kl_loss=True \ + actor_rollout_ref.actor.kl_loss_coef=0.001 \ + actor_rollout_ref.actor.kl_loss_type=low_var_kl \ + actor_rollout_ref.model.enable_gradient_checkpointing=True \ + actor_rollout_ref.actor.fsdp_config.param_offload=False \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \ + actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=160 \ + actor_rollout_ref.rollout.tensor_model_parallel_size=2 \ + actor_rollout_ref.rollout.name=vllm \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \ + actor_rollout_ref.rollout.n=5 \ + actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=160 \ + actor_rollout_ref.ref.fsdp_config.param_offload=True \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.critic_warmup=0 \ + trainer.logger=['console'] \ + trainer.project_name='verl_grpo_example_gsm8k' \ + trainer.experiment_name='deepseek_llm_7b_function_rm' \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=-1 \ + trainer.test_freq=5 \ + trainer.total_epochs=15 $@ \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2-7b_seq_balance.sh b/deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2-7b_seq_balance.sh new file mode 100644 index 0000000000000000000000000000000000000000..ae18603dd62bc072c91123712cddc9a280318a68 --- /dev/null +++ b/deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2-7b_seq_balance.sh @@ -0,0 +1,39 @@ +set -x + +export VLLM_ATTENTION_BACKEND=XFORMERS + +python3 -m verl.trainer.main_ppo \ + algorithm.adv_estimator=grpo \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.train_batch_size=1024 \ + data.max_prompt_length=512 \ + data.max_response_length=1024 \ + actor_rollout_ref.model.path=Qwen/Qwen2-7B-Instruct \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.model.use_remove_padding=True \ + actor_rollout_ref.actor.ppo_mini_batch_size=256 \ + actor_rollout_ref.actor.use_dynamic_bsz=True \ + actor_rollout_ref.actor.ppo_max_token_len_per_gpu=24000 \ + actor_rollout_ref.actor.use_kl_loss=True \ + actor_rollout_ref.actor.kl_loss_coef=0.001 \ + actor_rollout_ref.actor.kl_loss_type=low_var_kl \ + actor_rollout_ref.model.enable_gradient_checkpointing=True \ + actor_rollout_ref.actor.fsdp_config.param_offload=False \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \ + actor_rollout_ref.rollout.tensor_model_parallel_size=2 \ + actor_rollout_ref.rollout.name=vllm \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \ + actor_rollout_ref.rollout.n=5 \ + actor_rollout_ref.ref.fsdp_config.param_offload=True \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.critic_warmup=0 \ + trainer.logger=['console','wandb'] \ + trainer.project_name='verl_grpo_example_gsm8k' \ + trainer.experiment_name='qwen2_7b_function_rm_kl1e-3' \ + +trainer.val_before_train=False \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=-1 \ + trainer.test_freq=5 \ + trainer.total_epochs=15 $@ \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2_5_0_5b_seq_balance.sh b/deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2_5_0_5b_seq_balance.sh new file mode 100644 index 0000000000000000000000000000000000000000..db3d4c2c8832b2daafb868bb2c700bf9cb5df3eb --- /dev/null +++ b/deep_search/DeepResearcher/examples/grpo_trainer/run_qwen2_5_0_5b_seq_balance.sh @@ -0,0 +1,39 @@ +set -x + +export VLLM_ATTENTION_BACKEND=XFORMERS + +python3 -m verl.trainer.main_ppo \ + algorithm.adv_estimator=grpo \ + data.train_files=./data/gsm8k/train.parquet \ + data.val_files=./data/gsm8k/test.parquet \ + data.train_batch_size=1024 \ + data.max_prompt_length=512 \ + data.max_response_length=1024 \ + actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.model.use_remove_padding=True \ + actor_rollout_ref.actor.ppo_mini_batch_size=256 \ + actor_rollout_ref.actor.use_dynamic_bsz=True \ + actor_rollout_ref.actor.ppo_max_token_len_per_gpu=24000 \ + actor_rollout_ref.actor.use_kl_loss=True \ + actor_rollout_ref.actor.kl_loss_coef=0.001 \ + actor_rollout_ref.actor.kl_loss_type=low_var_kl \ + actor_rollout_ref.model.enable_gradient_checkpointing=True \ + actor_rollout_ref.actor.fsdp_config.param_offload=False \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \ + actor_rollout_ref.rollout.tensor_model_parallel_size=2 \ + actor_rollout_ref.rollout.name=vllm \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \ + actor_rollout_ref.rollout.n=5 \ + actor_rollout_ref.ref.fsdp_config.param_offload=True \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.critic_warmup=0 \ + trainer.logger=['console','wandb'] \ + trainer.project_name='verl_grpo_example_gsm8k' \ + trainer.experiment_name='qwen2.5_0.5b_function_rm_kl1e-3' \ + +trainer.val_before_train=False \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=1 \ + trainer.test_freq=1 \ + trainer.total_epochs=1 $@ \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/ray/tutorial.ipynb b/deep_search/DeepResearcher/examples/ray/tutorial.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..37784f6f9528be290cfbb9a685c78e4ea5a6d294 --- /dev/null +++ b/deep_search/DeepResearcher/examples/ray/tutorial.ipynb @@ -0,0 +1,958 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0ddc582b", + "metadata": {}, + "source": [ + "# VeRL Ray API Tutorial" + ] + }, + { + "cell_type": "markdown", + "id": "71fe3b94", + "metadata": {}, + "source": [ + "## Chapter 1: Ray Basics" + ] + }, + { + "cell_type": "code", + "execution_count": 144, + "id": "1347d381", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "import os" + ] + }, + { + "cell_type": "code", + "execution_count": 145, + "id": "e75b9d44", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "import ray\n", + "import torch\n", + "import warnings\n", + "warnings.filterwarnings('ignore')" + ] + }, + { + "cell_type": "code", + "execution_count": 146, + "id": "2e90ae00", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "2024-11-01 17:27:19,132\tINFO worker.py:1752 -- Started a local Ray instance.\n" + ] + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "9cc9d2ccbdfb48918c8fd6cd13a0807a", + "version_major": 2, + "version_minor": 0 + }, + "text/html": [ + "
\n", + "
\n", + "
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
Python version:3.9.2
Ray version:2.10.0
\n", + "\n", + "
\n", + "
\n" + ], + "text/plain": [ + "RayContext(dashboard_url='', python_version='3.9.2', ray_version='2.10.0', ray_commit='09abba26b5bf2707639bb637c208d062a47b46f6')" + ] + }, + "execution_count": 146, + "metadata": {}, + "output_type": "execute_result" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\u001b[36m(GPUAccumulator pid=224400)\u001b[0m rank 0, value: tensor([1.], device='cuda:0')\n", + "\u001b[36m(GPUAccumulator pid=225234)\u001b[0m rank 2, value: tensor([3.], device='cuda:0')\n", + "\u001b[36m(GPUAccumulator pid=225607)\u001b[0m rank 0, value: tensor([2.], device='cuda:0')\n", + "\u001b[36m(GPUAccumulator pid=226423)\u001b[0m rank 1, value: tensor([3.], device='cuda:0')\n", + "\u001b[36m(GPUAccumulator pid=226857)\u001b[0m rank 3, value: tensor([6.], device='cuda:0')\n", + "\u001b[36m(GPUAccumulatorDecorator pid=227475)\u001b[0m 10\n", + "\u001b[36m(GPUAccumulatorDecorator pid=227475)\u001b[0m rank 0, value: tensor([10.], device='cuda:0')\n", + "\u001b[36m(GPUAccumulatorDecorator pid=227655)\u001b[0m rank 1, value: tensor([11.], device='cuda:0')\n" + ] + } + ], + "source": [ + "# Build a local ray cluster. The head node and worker node are on this machine\n", + "ray.init()" + ] + }, + { + "cell_type": "markdown", + "id": "a127e4e4", + "metadata": {}, + "source": [ + "Implement an Accumulator class." + ] + }, + { + "cell_type": "code", + "execution_count": 147, + "id": "20e7b9a3", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "@ray.remote\n", + "class Accumulator:\n", + " def __init__(self):\n", + " self.value = 0\n", + " \n", + " def add(self, x):\n", + " self.value += x\n", + " \n", + " def get_value(self):\n", + " return self.value" + ] + }, + { + "cell_type": "code", + "execution_count": 148, + "id": "3b80098c", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Instantiate an accumulator. Accumulator can be viewed as a process, acting as an RPC service.\n", + "accumulator = Accumulator.remote()" + ] + }, + { + "cell_type": "code", + "execution_count": 149, + "id": "b14b1009", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n" + ] + } + ], + "source": [ + "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", + "# Get the value\n", + "value = ray.get(value_ref)\n", + "print(value)" + ] + }, + { + "cell_type": "code", + "execution_count": 150, + "id": "513a84b3", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n" + ] + } + ], + "source": [ + "# Accumulate, then check the result.\n", + "accumulator.add.remote(10) # Similarly, the 'add' here will return immediately.\n", + "new_value = ray.get(accumulator.get_value.remote())\n", + "print(new_value)" + ] + }, + { + "cell_type": "markdown", + "id": "3c332fe0", + "metadata": {}, + "source": [ + "## Chapter 2: Resource Pool and RayWorkerGroup\n", + "In the previous example, it was a simple single-process worker. \n", + "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." + ] + }, + { + "cell_type": "code", + "execution_count": 151, + "id": "04229afb", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from verl.single_controller.ray.base import RayResourcePool, RayClassWithInitArgs, RayWorkerGroup, merge_resource_pool\n", + "from verl.single_controller.base import Worker" + ] + }, + { + "cell_type": "code", + "execution_count": 152, + "id": "0d0dbd58", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "resource_pool = RayResourcePool([4], use_gpu=True)" + ] + }, + { + "cell_type": "code", + "execution_count": 153, + "id": "68f6838a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "@ray.remote\n", + "class GPUAccumulator(Worker):\n", + "\n", + " def __init__(self) -> None:\n", + " super().__init__()\n", + " # The initial value of each rank is the same as the rank\n", + " self.value = torch.zeros(size=(1,), device='cuda') + self.rank\n", + "\n", + " def add(self, x):\n", + " self.value += x\n", + " print(f'rank {self.rank}, value: {self.value}')\n", + " return self.value.cpu()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 154, + "id": "23aad8fe", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[tensor([1.]), tensor([2.]), tensor([3.]), tensor([4.])]\n" + ] + } + ], + "source": [ + "# 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", + "class_with_args = RayClassWithInitArgs(cls=GPUAccumulator)\n", + "worker_group = RayWorkerGroup(resource_pool, class_with_args)\n", + "print(worker_group.execute_all_sync('add', x=[1,1,1,1]))" + ] + }, + { + "cell_type": "markdown", + "id": "e6705284", + "metadata": {}, + "source": [ + "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", + "The return parameter is also a list, corresponding to the return value of each worker." + ] + }, + { + "cell_type": "markdown", + "id": "d25c2412", + "metadata": {}, + "source": [ + "### GPU Resource Sharing" + ] + }, + { + "cell_type": "markdown", + "id": "f74f6d24", + "metadata": {}, + "source": [ + "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." + ] + }, + { + "cell_type": "code", + "execution_count": 155, + "id": "49f9c06f", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Create a new resource pool and then merge the newly created resource pool with the previous one.\n", + "resource_pool_1 = RayResourcePool([4], use_gpu=True, name_prefix='a')\n", + "resource_pool_merge = merge_resource_pool(resource_pool, resource_pool_1)" + ] + }, + { + "cell_type": "code", + "execution_count": 156, + "id": "05c2e305", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Establish a RayWorkerGroup on the newly created resource pool.\n", + "worker_group_1 = RayWorkerGroup(resource_pool_1, class_with_args)\n", + "worker_group_merge = RayWorkerGroup(resource_pool_merge, class_with_args)" + ] + }, + { + "cell_type": "code", + "execution_count": 157, + "id": "6b9b13f4", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[tensor([2.]), tensor([3.]), tensor([4.]), tensor([5.])]\n" + ] + } + ], + "source": [ + "# Run 'add' on the second set of 4 GPUs; the result should be [2, 3, 4, 5].\n", + "output_1 = worker_group_1.execute_all_sync('add', x=[2,2,2,2])\n", + "print(output_1)" + ] + }, + { + "cell_type": "code", + "execution_count": 158, + "id": "d856d030", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[tensor([3.]), tensor([4.]), tensor([5.]), tensor([6.]), tensor([7.]), tensor([8.]), tensor([9.]), tensor([10.])]\n" + ] + } + ], + "source": [ + "# Run 'add' on the merged set of 8 GPUs; the result should be [3, 4, 5, 6, 7, 8, 9, 10].\n", + "output_merge = worker_group_merge.execute_all_sync('add', x=[3,3,3,3,3,3,3,3])\n", + "print(output_merge)" + ] + }, + { + "cell_type": "code", + "execution_count": 159, + "id": "33a4628c", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4 4 8\n" + ] + } + ], + "source": [ + "print(worker_group.world_size, worker_group_1.world_size, worker_group_merge.world_size)" + ] + }, + { + "cell_type": "markdown", + "id": "3df19d13", + "metadata": {}, + "source": [ + "## Chapter 3: Data Dispatch, Execution and Collection" + ] + }, + { + "cell_type": "markdown", + "id": "acb22d9d", + "metadata": {}, + "source": [ + "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", + "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." + ] + }, + { + "cell_type": "code", + "execution_count": 160, + "id": "35237432", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from verl.single_controller.base.decorator import register, Dispatch, Execute" + ] + }, + { + "cell_type": "code", + "execution_count": 161, + "id": "88b8ba3b", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "@ray.remote\n", + "class GPUAccumulatorDecorator(Worker):\n", + "\n", + " def __init__(self) -> None:\n", + " super().__init__()\n", + " # The initial value of each rank is the same as the rank\n", + " self.value = torch.zeros(size=(1,), device='cuda') + self.rank\n", + " \n", + " # map from a single input to all the worker\n", + " @register(Dispatch.ONE_TO_ALL)\n", + " def add(self, x):\n", + " print(x)\n", + " self.value = self.value + x\n", + " print(f'rank {self.rank}, value: {self.value}')\n", + " return self.value.cpu()" + ] + }, + { + "cell_type": "code", + "execution_count": 162, + "id": "eddaa043", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "class_with_args = RayClassWithInitArgs(cls=GPUAccumulatorDecorator)\n", + "gpu_accumulator_decorator = RayWorkerGroup(resource_pool_merge, class_with_args)" + ] + }, + { + "cell_type": "code", + "execution_count": 163, + "id": "10087c91", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[tensor([10.]), tensor([11.]), tensor([12.]), tensor([13.]), tensor([14.]), tensor([15.]), tensor([16.]), tensor([17.])]\n" + ] + } + ], + "source": [ + "# As we can see, 10 is automatically dispatched to each Worker in this RayWorkerGroup.\n", + "print(gpu_accumulator_decorator.add(x=10))" + ] + }, + { + "cell_type": "markdown", + "id": "540ee6ad", + "metadata": {}, + "source": [ + "### Custom Dispatch, Collection\n", + "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." + ] + }, + { + "cell_type": "code", + "execution_count": 164, + "id": "8e041270", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from verl.single_controller.base.decorator import register, Dispatch, collect_all_to_all, Execute" + ] + }, + { + "cell_type": "code", + "execution_count": 165, + "id": "43b5be31", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "def two_to_all_dispatch_fn(worker_group, *args, **kwargs):\n", + " \"\"\"\n", + " Assume the input is a list of 2. Duplicate the input interleaved and pass to each worker.\n", + " \"\"\"\n", + " for arg in args:\n", + " assert len(arg) == 2\n", + " for i in range(worker_group.world_size - 2):\n", + " arg.append(arg[i % 2])\n", + " for k, v in kwargs.items():\n", + " assert len(v) == 2\n", + " for i in range(worker_group.world_size - 2):\n", + " v.append(v[i % 2])\n", + " return args, kwargs\n", + "\n", + "\n", + "@ray.remote\n", + "class TestActor(Worker):\n", + " # TODO: pass *args and **kwargs is bug prone and not very convincing\n", + " def __init__(self, x) -> None:\n", + " super().__init__()\n", + " self._x = x\n", + "\n", + " def foo(self, y):\n", + " return self._x + y\n", + "\n", + " @register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.RANK_ZERO)\n", + " def foo_rank_zero(self, x, y):\n", + " return self._x + y + x\n", + "\n", + " @register(dispatch_mode={'dispatch_fn': two_to_all_dispatch_fn, 'collect_fn': collect_all_to_all})\n", + " def foo_custom(self, x, y):\n", + " return self._x + y + x" + ] + }, + { + "cell_type": "code", + "execution_count": 166, + "id": "83ec6609", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "class_with_args = RayClassWithInitArgs(cls=TestActor, x=2)\n", + "worker_group = RayWorkerGroup(resource_pool, class_with_args)" + ] + }, + { + "cell_type": "code", + "execution_count": 167, + "id": "62c58d8a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "output_ref = worker_group.foo_custom(x=[1, 2], y=[5, 6])\n", + "assert output_ref == [8, 10, 8, 10]\n", + "\n", + "output_ref = worker_group.foo_rank_zero(x=1, y=2)\n", + "assert output_ref == 5" + ] + }, + { + "cell_type": "code", + "execution_count": 168, + "id": "14689353", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "8\n" + ] + } + ], + "source": [ + "print(gpu_accumulator_decorator.world_size)" + ] + }, + { + "cell_type": "code", + "execution_count": 169, + "id": "2c80bbf4", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Shutdown ray cluster\n", + "ray.shutdown()" + ] + }, + { + "cell_type": "markdown", + "id": "a5c8151c", + "metadata": {}, + "source": [ + "## Chapter 4: NVMegatronRayWorkerGroup" + ] + }, + { + "cell_type": "markdown", + "id": "cd5680e9", + "metadata": {}, + "source": [ + "Due to the Ray issue, we can only support max_colocate_count=1 in RayResourcePool for now. \n", + "This means that each GPU can only have one process.\n", + "We can support max_colocate > 1 when applying this pull request: https://github.com/ray-project/ray/pull/44385" + ] + }, + { + "cell_type": "markdown", + "id": "92724419", + "metadata": {}, + "source": [ + "Therefore, we need to restart the ray and initialize a new resource_pool to demonstrate the **NVMegatronRayWorkerGroup**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9b038538", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Build a local ray cluster. The head node and worker node are on this machine\n", + "ray.init()" + ] + }, + { + "cell_type": "markdown", + "id": "ebfd8798", + "metadata": {}, + "source": [ + "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." + ] + }, + { + "cell_type": "code", + "execution_count": 171, + "id": "5a032154", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "/opt/tiger/Megatron-LM\n", + "/opt/tiger/Megatron-LM/megatron/__init__.py\n" + ] + } + ], + "source": [ + "import os\n", + "import sys\n", + "import site\n", + "\n", + "\n", + "current_pythonpath = os.environ.get('PYTHONPATH', '')\n", + "\n", + "new_path = '/opt/tiger/Megatron-LM'\n", + "\n", + "if current_pythonpath:\n", + " new_pythonpath = f'{new_path}:{current_pythonpath}'\n", + "else:\n", + " new_pythonpath = new_path\n", + "\n", + "os.environ['PYTHONPATH'] = new_pythonpath\n", + "\n", + "print(new_path)\n", + "sys.path.append(new_path)\n", + "\n", + "import megatron\n", + "print(megatron.__file__)" + ] + }, + { + "cell_type": "code", + "execution_count": 172, + "id": "8c84cd5a", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "from verl.single_controller.base.decorator import register, Dispatch, Execute\n", + "from verl.single_controller.ray.megatron import NVMegatronRayWorkerGroup\n", + "from verl.single_controller.base.megatron.worker import MegatronWorker\n", + "from verl.single_controller.ray.base import RayResourcePool, RayClassWithInitArgs, RayWorkerGroup\n", + "from omegaconf import OmegaConf\n", + "from megatron.core import parallel_state as mpu" + ] + }, + { + "cell_type": "code", + "execution_count": 173, + "id": "1b1debcc", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "resource_pool = RayResourcePool([4], use_gpu=True, max_colocate_count=1)" + ] + }, + { + "cell_type": "code", + "execution_count": 174, + "id": "bccbe081", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "@ray.remote\n", + "class MLPLayerWorker(MegatronWorker):\n", + " def __init__(self):\n", + " super().__init__()\n", + " rank = int(os.environ['LOCAL_RANK'])\n", + " torch.distributed.init_process_group(backend=\"nccl\")\n", + " torch.cuda.set_device(rank)\n", + "\n", + " mpu.initialize_model_parallel(\n", + " tensor_model_parallel_size=4,\n", + " pipeline_model_parallel_size=1,\n", + " virtual_pipeline_model_parallel_size=None,\n", + " pipeline_model_parallel_split_rank=None,\n", + " use_sharp=False,\n", + " context_parallel_size=1,\n", + " expert_model_parallel_size=1,\n", + " nccl_communicator_config_path=None,\n", + " )\n", + " from megatron.core import tensor_parallel\n", + " tensor_parallel.model_parallel_cuda_manual_seed(10)\n", + "\n", + "\n", + " @register(Dispatch.ONE_TO_ALL)\n", + " def init_model(self, config):\n", + " from omegaconf import OmegaConf\n", + " from verl.utils.megatron_utils import init_model_parallel_config\n", + " from verl.models.llama.megatron.layers import ParallelLlamaMLP\n", + " megatron_config = OmegaConf.create({\n", + " 'sequence_parallel': False,\n", + " 'param_dtype': 'fp32',\n", + " 'tensor_model_parallel_size': mpu.get_tensor_model_parallel_world_size(),\n", + " 'pipeline_model_parallel_rank': mpu.get_pipeline_model_parallel_rank(),\n", + " 'pipeline_model_parallel_size': mpu.get_pipeline_model_parallel_world_size(),\n", + " 'virtual_pipeline_model_parallel_rank': mpu.get_virtual_pipeline_model_parallel_rank(),\n", + " 'virtual_pipeline_model_parallel_size': mpu.get_virtual_pipeline_model_parallel_world_size()\n", + " })\n", + "\n", + " megatron_config = init_model_parallel_config(megatron_config)\n", + " self.parallel_layer = ParallelLlamaMLP(config=config, megatron_config=megatron_config)\n", + " \n", + " @register(Dispatch.ONE_TO_ALL)\n", + " def get_weights(self):\n", + " output = {}\n", + " for key, val in self.parallel_layer.named_parameters():\n", + " output[key] = val\n", + " return output\n", + " \n", + " @register(Dispatch.MEGATRON_COMPUTE)\n", + " def run_layer(self, x):\n", + " x = x.to('cuda')\n", + " y = self.parallel_layer(x)\n", + " return y" + ] + }, + { + "cell_type": "code", + "execution_count": 175, + "id": "a655271d", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "layer_cls = RayClassWithInitArgs(cls=MLPLayerWorker)\n", + "layer_worker_group = NVMegatronRayWorkerGroup(resource_pool=resource_pool,\n", + " ray_cls_with_init=layer_cls,\n", + " )\n" + ] + }, + { + "cell_type": "code", + "execution_count": 176, + "id": "f105ebee", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "4 4 1 1\n" + ] + } + ], + "source": [ + "print(layer_worker_group.world_size, layer_worker_group.tp_size, layer_worker_group.pp_size, layer_worker_group.dp_size)" + ] + }, + { + "cell_type": "code", + "execution_count": 177, + "id": "38655091", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "ffn_hidden_size = 11008\n", + "batch_size = 16\n", + "seq_len = 2048\n", + "hidden_size = 4096\n", + "\n", + "config = OmegaConf.create({\n", + " 'hidden_size': hidden_size,\n", + " 'intermediate_size': ffn_hidden_size,\n", + " 'hidden_act': 'silu',\n", + " 'pretraining_tp': 1,\n", + " 'tp': layer_worker_group.tp_size,\n", + "})" + ] + }, + { + "cell_type": "code", + "execution_count": 178, + "id": "a026efca", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "x = torch.rand(size=(seq_len, batch_size, hidden_size), dtype=torch.float32)" + ] + }, + { + "cell_type": "code", + "execution_count": 179, + "id": "f5fcaf13", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "[None, None, None, None]" + ] + }, + "execution_count": 179, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "layer_worker_group.init_model(config)" + ] + }, + { + "cell_type": "code", + "execution_count": 180, + "id": "3f5cc9b4", + "metadata": { + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "torch.Size([2048, 16, 4096])\n" + ] + } + ], + "source": [ + "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", + "print(output[0].shape)" + ] + }, + { + "cell_type": "code", + "execution_count": 181, + "id": "49792210", + "metadata": { + "tags": [] + }, + "outputs": [], + "source": [ + "# Shutdown ray cluster\n", + "ray.shutdown()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-3b_seq_balance.sh b/deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-3b_seq_balance.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc5b75b7750363c5ac893434d12a10358679f63d --- /dev/null +++ b/deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-3b_seq_balance.sh @@ -0,0 +1,42 @@ +set -x + +export HF_DATASETS_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +export VLLM_ATTENTION_BACKEND=XFORMERS + +python3 -m verl.trainer.main_ppo \ + algorithm.adv_estimator=remax \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.train_batch_size=512 \ + data.max_prompt_length=512 \ + data.max_response_length=1024 \ + actor_rollout_ref.model.path=Qwen/Qwen2.5-3B-Instruct \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.model.use_remove_padding=True \ + actor_rollout_ref.actor.ppo_mini_batch_size=128 \ + actor_rollout_ref.actor.use_dynamic_bsz=True \ + actor_rollout_ref.actor.ppo_max_token_len_per_gpu=30000 \ + actor_rollout_ref.actor.use_kl_loss=True \ + actor_rollout_ref.actor.kl_loss_coef=0.001 \ + actor_rollout_ref.actor.kl_loss_type=low_var_kl \ + actor_rollout_ref.model.enable_gradient_checkpointing=True \ + actor_rollout_ref.actor.fsdp_config.param_offload=False \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \ + actor_rollout_ref.rollout.tensor_model_parallel_size=2 \ + actor_rollout_ref.rollout.name=vllm \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.8 \ + actor_rollout_ref.rollout.n=4 \ + actor_rollout_ref.ref.fsdp_config.param_offload=True \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.critic_warmup=0 \ + trainer.logger=['console','wandb'] \ + trainer.project_name='verl_remax_example_gsm8k' \ + trainer.experiment_name='qwen2.5_3b_function_rm_kl1e-3' \ + +trainer.val_before_train=False \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=-1 \ + trainer.test_freq=5 \ + trainer.total_epochs=5 $@ diff --git a/deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-7b_seq_balance.sh b/deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-7b_seq_balance.sh new file mode 100644 index 0000000000000000000000000000000000000000..377a60c796c718c9cc45804724c7ed6cb8fa1d9a --- /dev/null +++ b/deep_search/DeepResearcher/examples/remax_trainer/run_qwen2.5-7b_seq_balance.sh @@ -0,0 +1,42 @@ +set -x + +export HF_DATASETS_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 + +export VLLM_ATTENTION_BACKEND=XFORMERS + +python3 -m verl.trainer.main_ppo \ + algorithm.adv_estimator=remax \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.train_batch_size=1024 \ + data.max_prompt_length=512 \ + data.max_response_length=1024 \ + actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.model.use_remove_padding=True \ + actor_rollout_ref.actor.ppo_mini_batch_size=256 \ + actor_rollout_ref.actor.use_dynamic_bsz=True \ + actor_rollout_ref.actor.ppo_max_token_len_per_gpu=24000 \ + actor_rollout_ref.actor.use_kl_loss=True \ + actor_rollout_ref.actor.kl_loss_coef=0.001 \ + actor_rollout_ref.actor.kl_loss_type=low_var_kl \ + actor_rollout_ref.model.enable_gradient_checkpointing=True \ + actor_rollout_ref.actor.fsdp_config.param_offload=False \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \ + actor_rollout_ref.rollout.tensor_model_parallel_size=2 \ + actor_rollout_ref.rollout.name=vllm \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.8 \ + actor_rollout_ref.rollout.n=4 \ + actor_rollout_ref.ref.fsdp_config.param_offload=True \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.critic_warmup=0 \ + trainer.logger=['console','wandb'] \ + trainer.project_name='verl_remax_example_gsm8k' \ + trainer.experiment_name='qwen2.5_7b_function_rm_kl1e-3' \ + +trainer.val_before_train=False \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=-1 \ + trainer.test_freq=5 \ + trainer.total_epochs=10 $@ diff --git a/deep_search/DeepResearcher/examples/rloo_trainer/run_qwen2-7b.sh b/deep_search/DeepResearcher/examples/rloo_trainer/run_qwen2-7b.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c0a4a6de1bea1a057d38067df13f474d29ecd9a --- /dev/null +++ b/deep_search/DeepResearcher/examples/rloo_trainer/run_qwen2-7b.sh @@ -0,0 +1,40 @@ +set -x + +export VLLM_ATTENTION_BACKEND=XFORMERS + +python3 -m verl.trainer.main_ppo \ + algorithm.adv_estimator=rloo \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.train_batch_size=1024 \ + data.max_prompt_length=512 \ + data.max_response_length=1024 \ + actor_rollout_ref.model.path=Qwen/Qwen2-7B-Instruct \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.model.use_remove_padding=True \ + actor_rollout_ref.actor.ppo_mini_batch_size=256 \ + actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=80 \ + actor_rollout_ref.actor.use_kl_loss=True \ + actor_rollout_ref.actor.kl_loss_coef=0.001 \ + actor_rollout_ref.actor.kl_loss_type=low_var_kl \ + actor_rollout_ref.model.enable_gradient_checkpointing=True \ + actor_rollout_ref.actor.fsdp_config.param_offload=False \ + actor_rollout_ref.actor.fsdp_config.grad_offload=False \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \ + actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=160 \ + actor_rollout_ref.rollout.tensor_model_parallel_size=2 \ + actor_rollout_ref.rollout.name=vllm \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \ + actor_rollout_ref.rollout.n=5 \ + actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=160 \ + actor_rollout_ref.ref.fsdp_config.param_offload=True \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.critic_warmup=0 \ + trainer.logger=['console','wandb'] \ + trainer.project_name='verl_rloo_example_gsm8k' \ + trainer.experiment_name='qwen2_7b_function_rm' \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=-1 \ + trainer.test_freq=5 \ + trainer.total_epochs=15 $@ \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/sft/gsm8k/run_deepseek_6b7.sh b/deep_search/DeepResearcher/examples/sft/gsm8k/run_deepseek_6b7.sh new file mode 100644 index 0000000000000000000000000000000000000000..f11965a69892ff89defe8feb2af100da4dfa4c71 --- /dev/null +++ b/deep_search/DeepResearcher/examples/sft/gsm8k/run_deepseek_6b7.sh @@ -0,0 +1,29 @@ +set -x + +if [ "$#" -lt 2 ]; then + echo "Usage: run_deepseek_6b7.sh [other_configs...]" + exit 1 +fi + +nproc_per_node=$1 +save_path=$2 + +# Shift the arguments so $@ refers to the rest +shift 2 + +torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \ + -m verl.trainer.fsdp_sft_trainer \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.prompt_key=extra_info \ + data.response_key=extra_info \ + +data.prompt_dict_keys=['question'] \ + +data.response_dict_keys=['answer'] \ + data.micro_batch_size_per_gpu=4 \ + model.partial_pretrain=deepseek-ai/deepseek-coder-6.7b-instruct \ + trainer.default_local_dir=$save_path \ + trainer.project_name=gsm8k-sft \ + trainer.experiment_name=gsm8k-sft-deepseek-coder-6.7b-instruct \ + trainer.total_epochs=4 \ + trainer.logger=['console','wandb'] \ + trainer.default_hdfs_dir=null $@ \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_2b.sh b/deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_2b.sh new file mode 100644 index 0000000000000000000000000000000000000000..6d7917d9e867fbb45379d49f4ba1bf01275fc8df --- /dev/null +++ b/deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_2b.sh @@ -0,0 +1,31 @@ +# Tested with 2 & 4 GPUs + +set -x + +if [ "$#" -lt 2 ]; then + echo "Usage: run_gemma_2b.sh [other_configs...]" + exit 1 +fi + +nproc_per_node=$1 +save_path=$2 + +# Shift the arguments so $@ refers to the rest +shift 2 + +torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \ + -m verl.trainer.fsdp_sft_trainer \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.prompt_key=extra_info \ + data.response_key=extra_info \ + +data.prompt_dict_keys=['question'] \ + +data.response_dict_keys=['answer'] \ + data.micro_batch_size_per_gpu=4 \ + model.partial_pretrain=google/gemma-2b-it \ + trainer.default_local_dir=$save_path \ + trainer.project_name=gsm8k-sft \ + trainer.experiment_name=gsm8k-sft-gemma-2b-it \ + trainer.total_epochs=2 \ + trainer.logger=['console','wandb'] \ + trainer.default_hdfs_dir=null $@ \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_7b.sh b/deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_7b.sh new file mode 100644 index 0000000000000000000000000000000000000000..fdf4435bb29e27715b0a8f3d9912ff513e927b99 --- /dev/null +++ b/deep_search/DeepResearcher/examples/sft/gsm8k/run_gemma_7b.sh @@ -0,0 +1,27 @@ +set -x + +if [ "$#" -lt 2 ]; then + echo "Usage: run_gemma_7b.sh [other_configs...]" + exit 1 +fi + +nproc_per_node=$1 +save_path=$2 + +# Shift the arguments so $@ refers to the rest +shift 2 + +torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \ + -m verl.trainer.fsdp_sft_trainer \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.prompt_key=prompt \ + data.response_key=answer \ + data.micro_batch_size_per_gpu=4 \ + model.partial_pretrain=google/gemma-1.1-7b-it \ + trainer.default_local_dir=$save_path \ + trainer.project_name=gsm8k-sft \ + trainer.experiment_name=gsm8k-sft-gemma-1.1-7b-it \ + trainer.total_epochs=4 \ + trainer.logger=['console','wandb'] \ + trainer.default_hdfs_dir=null $@ \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_peft.sh b/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_peft.sh new file mode 100644 index 0000000000000000000000000000000000000000..3ba61c3a6e0107e4bfc7144590c627d533a330a9 --- /dev/null +++ b/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_peft.sh @@ -0,0 +1,38 @@ +# Tested with 2 & 4 GPUs + +set -x + +if [ "$#" -lt 2 ]; then + echo "Usage: run_qwen_05_peft.sh [other_configs...]" + exit 1 +fi + +nproc_per_node=$1 +save_path=$2 + +# Shift the arguments so $@ refers to the rest +shift 2 + +torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \ + -m verl.trainer.fsdp_sft_trainer \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.prompt_key=extra_info \ + data.response_key=extra_info \ + optim.lr=1e-4 \ + +data.prompt_dict_keys=['question'] \ + +data.response_dict_keys=['answer'] \ + data.micro_batch_size_per_gpu=4 \ + model.partial_pretrain=Qwen/Qwen2.5-0.5B-Instruct \ + trainer.default_local_dir=$save_path \ + trainer.project_name=gsm8k-sft \ + trainer.experiment_name=gsm8k-sft-qwen-2.5-0.5b-instruct \ + trainer.logger=['console'] \ + trainer.total_epochs=1 \ + trainer.default_hdfs_dir=null $@ \ + model.lora_rank=32\ + model.lora_alpha=16 \ + model.target_modules=all-linear + + # Or you can do this: + # model.target_modules=[q_proj,v_proj] \ diff --git a/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2.sh b/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2.sh new file mode 100644 index 0000000000000000000000000000000000000000..a27cef1d48dd78f0a0baa1e74d2e0dadeee4fecb --- /dev/null +++ b/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2.sh @@ -0,0 +1,32 @@ +set -x + +if [ "$#" -lt 2 ]; then + echo "Usage: run_qwen_05_sp2.sh [other_configs...]" + exit 1 +fi + +nproc_per_node=$1 +save_path=$2 + +# Shift the arguments so $@ refers to the rest +shift 2 + +torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \ + -m verl.trainer.fsdp_sft_trainer \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.prompt_key=extra_info \ + data.response_key=extra_info \ + optim.lr=1e-4 \ + +data.prompt_dict_keys=['question'] \ + +data.response_dict_keys=['answer'] \ + data.micro_batch_size=4 \ + model.partial_pretrain=Qwen/Qwen2.5-0.5B-Instruct \ + trainer.default_local_dir=$save_path \ + trainer.project_name=gsm8k-sft \ + trainer.experiment_name=gsm8k-sft-qwen-2.5-0.5b-instruct-sp2 \ + trainer.logger=['console'] \ + trainer.total_training_steps=1 \ + trainer.default_hdfs_dir=null $@ \ + ulysses_sequence_parallel_size=2 \ + use_remove_padding=true diff --git a/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2_liger.sh b/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2_liger.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ef528fdcce7e638f20c8794c444897474e7e456 --- /dev/null +++ b/deep_search/DeepResearcher/examples/sft/gsm8k/run_qwen_05_sp2_liger.sh @@ -0,0 +1,32 @@ +set -x + +if [ "$#" -lt 2 ]; then + echo "Usage: run_qwen_05_sp2.sh [other_configs...]" + exit 1 +fi + +nproc_per_node=$1 +save_path=$2 + +# Shift the arguments so $@ refers to the rest +shift 2 + +torchrun --standalone --nnodes=1 --nproc_per_node=$nproc_per_node \ + -m verl.trainer.fsdp_sft_trainer \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.prompt_key=extra_info \ + data.response_key=extra_info \ + optim.lr=1e-4 \ + +data.prompt_dict_keys=['question'] \ + +data.response_dict_keys=['answer'] \ + data.micro_batch_size=4 \ + model.partial_pretrain=Qwen/Qwen2.5-0.5B-Instruct \ + model.use_liger=True \ + trainer.default_local_dir=$save_path \ + trainer.project_name=gsm8k-sft \ + trainer.experiment_name=gsm8k-sft-qwen-2.5-0.5b-instruct-sp2-liger \ + trainer.logger=['console'] \ + trainer.default_hdfs_dir=null $@ \ + ulysses_sequence_parallel_size=2 \ + use_remove_padding=true diff --git a/deep_search/DeepResearcher/examples/split_placement/README.md b/deep_search/DeepResearcher/examples/split_placement/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a552972594f9ddd142d6889cdee1a5def55c2939 --- /dev/null +++ b/deep_search/DeepResearcher/examples/split_placement/README.md @@ -0,0 +1,61 @@ +# Split Placement Example +Here we introduce how to run the naive implementation of the split placement of PPO algorithm. +We will release the complete version of flexible placement in the near future. + + For quickstart, you can only follow Step 2 to modify the code and then follow Step 4 to execute the split placement example. + +### Step 1: Placing the models to different GPUs +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. +```python +actor_rollout_ref_pool_id = 'actor_rollout_ref_pool' +critic_pool_id = 'critic_pool' +if config.trainer.nnodes // 2 == 0 and config.trainer.n_gpus_per_node // 2 > 0: + resource_pool_spec = { + actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes, + critic_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes, + } +else: + resource_pool_spec = { + actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2), + critic_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2), + } +print(f'resource_pool_spec: {resource_pool_spec}') +mapping = { + Role.ActorRollout: actor_rollout_ref_pool_id, + Role.Critic: critic_pool_id, + Role.RefPolicy: actor_rollout_ref_pool_id, +} +mapping[Role.RewardModel] = critic_pool_id +``` + +### Step 2: Make the models executed asynchronously +Based on the model placement, we need to make the models executed asynchronously. + +To do so, you need to turn off the `blocking` flag (i.e., `blocking=False`) in our decorator of some model operations. +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` + +``` +@register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO, blocking=False) +def update_actor(self, data: DataProto): + ... + +@register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO, blocking=False) +def update_critic(self, data: DataProto): + ... +``` + +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. + +### Step 3: Execute these operation in parallel in the single controller process +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. + +```python +critic_output = critic_output.get() +actor_output = actor_output.get() +``` + +### Step 4: Run the split placement example + +``` +bash run_deepseek7b_llm.sh +``` diff --git a/deep_search/DeepResearcher/examples/split_placement/config/ppo_trainer_split.yaml b/deep_search/DeepResearcher/examples/split_placement/config/ppo_trainer_split.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6fd08d3eb55143ab9d4854511f94f4060adef38 --- /dev/null +++ b/deep_search/DeepResearcher/examples/split_placement/config/ppo_trainer_split.yaml @@ -0,0 +1,171 @@ +data: + tokenizer: null + train_files: ~/data/rlhf/gsm8k/train.parquet + val_files: ~/data/rlhf/gsm8k/test.parquet + prompt_key: prompt + max_prompt_length: 512 + max_response_length: 512 + train_batch_size: 1024 + val_batch_size: null # DEPRECATED: Validation datasets are sent to inference engines as a whole batch, which will schedule the memory themselves + return_raw_input_ids: False # This should be set to true when the tokenizer between policy and rm differs + return_raw_chat: False + shuffle: True + +actor_rollout_ref: + hybrid_engine: True + model: + path: ~/models/deepseek-llm-7b-chat + external_lib: null + override_config: { } + enable_gradient_checkpointing: True + use_remove_padding: False + actor: + strategy: fsdp # This is for backward-compatibility + ppo_mini_batch_size: 256 + ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu + ppo_micro_batch_size_per_gpu: null + use_dynamic_bsz: False + ppo_max_token_len_per_gpu: 16384 # n * ${data.max_prompt_length} + ${data.max_response_length} + grad_clip: 1.0 + clip_ratio: 0.2 + entropy_coeff: 0.001 + use_kl_loss: False # True for GRPO + kl_loss_coef: 0.001 # for grpo + kl_loss_type: low_var_kl # for grpo + ppo_epochs: 1 + shuffle: False + ulysses_sequence_parallel_size: 1 # sp size + optim: + lr: 1e-6 + lr_warmup_steps_ratio: 0. # the total steps will be injected during runtime + min_lr_ratio: null # only useful for warmup with cosine + warmup_style: constant # select from constant/cosine + total_training_steps: -1 # must be override by program + fsdp_config: + wrap_policy: + # transformer_layer_cls_to_wrap: None + min_num_params: 0 + param_offload: False + optimizer_offload: False + fsdp_size: -1 + ref: + fsdp_config: + param_offload: False + wrap_policy: + # transformer_layer_cls_to_wrap: None + min_num_params: 0 + log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu + log_prob_micro_batch_size_per_gpu: null + log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz} + log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu} + ulysses_sequence_parallel_size: ${actor_rollout_ref.actor.ulysses_sequence_parallel_size} # sp size + rollout: + name: vllm + temperature: 1.0 + top_k: -1 # 0 for hf rollout, -1 for vllm rollout + top_p: 1 + prompt_length: ${data.max_prompt_length} # not use for opensource + response_length: ${data.max_response_length} + # for vllm rollout + dtype: bfloat16 # should align with FSDP + gpu_memory_utilization: 0.5 + ignore_eos: False + enforce_eager: True + free_cache_engine: True + load_format: dummy_dtensor + tensor_model_parallel_size: 2 + max_num_batched_tokens: 8192 + max_num_seqs: 1024 + log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu + log_prob_micro_batch_size_per_gpu: null + log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz} + log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu} + disable_log_stats: True + enable_chunked_prefill: True # could get higher throughput + # for hf rollout + do_sample: True + # number of responses (i.e. num sample times) + n: 1 # > 1 for grpo + +critic: + strategy: fsdp + optim: + lr: 1e-5 + lr_warmup_steps_ratio: 0. # the total steps will be injected during runtime + min_lr_ratio: null # only useful for warmup with cosine + warmup_style: constant # select from constant/cosine + total_training_steps: -1 # must be override by program + model: + path: ~/models/deepseek-llm-7b-chat + tokenizer_path: ${actor_rollout_ref.model.path} + override_config: { } + external_lib: ${actor_rollout_ref.model.external_lib} + enable_gradient_checkpointing: True + use_remove_padding: False + fsdp_config: + param_offload: False + optimizer_offload: False + wrap_policy: + # transformer_layer_cls_to_wrap: None + min_num_params: 0 + fsdp_size: -1 + ppo_mini_batch_size: ${actor_rollout_ref.actor.ppo_mini_batch_size} + ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu + ppo_micro_batch_size_per_gpu: null + forward_micro_batch_size: ${critic.ppo_micro_batch_size} + forward_micro_batch_size_per_gpu: ${critic.ppo_micro_batch_size_per_gpu} + use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz} + ppo_max_token_len_per_gpu: 32768 # (${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}) * 2 + forward_max_token_len_per_gpu: ${critic.ppo_max_token_len_per_gpu} + ulysses_sequence_parallel_size: 1 # sp size + ppo_epochs: ${actor_rollout_ref.actor.ppo_epochs} + shuffle: ${actor_rollout_ref.actor.shuffle} + grad_clip: 1.0 + cliprange_value: 0.5 + +reward_model: + enable: False + strategy: fsdp + model: + input_tokenizer: ${actor_rollout_ref.model.path} # set this to null if the chat template is identical + path: ~/models/FsfairX-LLaMA3-RM-v0.1 + external_lib: ${actor_rollout_ref.model.external_lib} + use_remove_padding: False + fsdp_config: + min_num_params: 0 + param_offload: False + fsdp_size: -1 + micro_batch_size: null # will be deprecated, use micro_batch_size_per_gpu + micro_batch_size_per_gpu: null # set a number + max_length: null + ulysses_sequence_parallel_size: 1 # sp size + use_dynamic_bsz: ${critic.use_dynamic_bsz} + forward_max_token_len_per_gpu: ${critic.forward_max_token_len_per_gpu} + reward_manager: naive + +algorithm: + gamma: 1.0 + lam: 1.0 + adv_estimator: gae + kl_penalty: kl # how to estimate kl divergence + kl_ctrl: + type: fixed + kl_coef: 0.001 + +trainer: + total_epochs: 30 + total_training_steps: null + project_name: verl_examples + experiment_name: gsm8k + logger: [ 'console', 'wandb' ] + val_generations_to_log_to_wandb: 0 + nnodes: 1 + n_gpus_per_node: 8 + save_freq: -1 + # auto: find the last ckpt to resume. If can't find, start from scratch + resume_mode: auto # or auto or resume_path if + resume_from_path: False + test_freq: -1 + critic_warmup: 0 + default_hdfs_dir: null + default_local_dir: checkpoints/${trainer.project_name}/${trainer.experiment_name} \ No newline at end of file diff --git a/deep_search/DeepResearcher/examples/split_placement/main_ppo_split.py b/deep_search/DeepResearcher/examples/split_placement/main_ppo_split.py new file mode 100644 index 0000000000000000000000000000000000000000..1727001b8ffe11f32e131bdbae6e16f481144ca3 --- /dev/null +++ b/deep_search/DeepResearcher/examples/split_placement/main_ppo_split.py @@ -0,0 +1,199 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Note that we don't combine the main with ray_trainer as ray_trainer is used by other main. +""" + +from verl import DataProto +import torch +from verl.utils.reward_score import gsm8k, math +from verl.trainer.ppo.ray_trainer import RayPPOTrainer + + +def _select_rm_score_fn(data_source): + if data_source == 'openai/gsm8k': + return gsm8k.compute_score + elif data_source == 'lighteval/MATH': + return math.compute_score + else: + raise NotImplementedError + + +class RewardManager(): + + def __init__(self, tokenizer, num_examine) -> None: + self.tokenizer = tokenizer + self.num_examine = num_examine # the number of batches of decoded responses to print to the console + + def __call__(self, data: DataProto): + """We will expand this function gradually based on the available datasets""" + + # If there is rm score, we directly return rm score. Otherwise, we compute via rm_score_fn + if 'rm_scores' in data.batch.keys(): + return data.batch['rm_scores'] + + reward_tensor = torch.zeros_like(data.batch['responses'], dtype=torch.float32) + + already_print_data_sources = {} + + for i in range(len(data)): + data_item = data[i] # DataProtoItem + + prompt_ids = data_item.batch['prompts'] + + prompt_length = prompt_ids.shape[-1] + + valid_prompt_length = data_item.batch['attention_mask'][:prompt_length].sum() + valid_prompt_ids = prompt_ids[-valid_prompt_length:] + + response_ids = data_item.batch['responses'] + valid_response_length = data_item.batch['attention_mask'][prompt_length:].sum() + valid_response_ids = response_ids[:valid_response_length] + + # decode + sequences = torch.cat((valid_prompt_ids, valid_response_ids)) + sequences_str = self.tokenizer.decode(sequences) + + ground_truth = data_item.non_tensor_batch['reward_model']['ground_truth'] + + # select rm_score + data_source = data_item.non_tensor_batch['data_source'] + compute_score_fn = _select_rm_score_fn(data_source) + + score = compute_score_fn(solution_str=sequences_str, ground_truth=ground_truth) + reward_tensor[i, valid_response_length - 1] = score + + if data_source not in already_print_data_sources: + already_print_data_sources[data_source] = 0 + + if already_print_data_sources[data_source] < self.num_examine: + already_print_data_sources[data_source] += 1 + print(sequences_str) + + return reward_tensor + + +import ray +import hydra +from split_monkey_patch import fit + + +@hydra.main(config_path='config', config_name='ppo_trainer_split', version_base=None) +def main(config): + if not ray.is_initialized(): + # this is for local ray cluster + ray.init(runtime_env={'env_vars': {'TOKENIZERS_PARALLELISM': 'true', 'NCCL_DEBUG': 'WARN'}}) + + ray.get(main_task.remote(config)) + + +@ray.remote +def main_task(config): + from verl.utils.fs import copy_to_local + from transformers import AutoTokenizer + + # print initial config + from pprint import pprint + from omegaconf import OmegaConf + pprint(OmegaConf.to_container(config, resolve=True)) # resolve=True will eval symbol values + OmegaConf.resolve(config) + + # download the checkpoint from hdfs + local_path = copy_to_local(config.actor_rollout_ref.model.path) + + # instantiate tokenizer + from verl.utils import hf_tokenizer + tokenizer = hf_tokenizer(local_path) + + # define worker classes + if config.actor_rollout_ref.actor.strategy == 'fsdp': + assert config.actor_rollout_ref.actor.strategy == config.critic.strategy + from verl.workers.fsdp_workers import ActorRolloutRefWorker, CriticWorker + from verl.single_controller.ray import RayWorkerGroup + ray_worker_group_cls = RayWorkerGroup + + elif config.actor_rollout_ref.actor.strategy == 'megatron': + assert config.actor_rollout_ref.actor.strategy == config.critic.strategy + from verl.workers.megatron_workers import ActorRolloutRefWorker, CriticWorker + from verl.single_controller.ray.megatron import NVMegatronRayWorkerGroup + ray_worker_group_cls = NVMegatronRayWorkerGroup + + else: + raise NotImplementedError + + from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role + + role_worker_mapping = { + Role.ActorRollout: ray.remote(ActorRolloutRefWorker), + Role.Critic: ray.remote(CriticWorker), + Role.RefPolicy: ray.remote(ActorRolloutRefWorker) + } + + # NOTE: initialze two resource pool + actor_rollout_ref_pool_id = 'actor_rollout_ref_pool' + critic_pool_id = 'critic_pool' + if config.trainer.nnodes // 2 == 0 and config.trainer.n_gpus_per_node // 2 > 0: + resource_pool_spec = { + actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes, + critic_pool_id: [config.trainer.n_gpus_per_node // 2] * config.trainer.nnodes, + } + else: + resource_pool_spec = { + actor_rollout_ref_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2), + critic_pool_id: [config.trainer.n_gpus_per_node] * (config.trainer.nnodes // 2), + } + print(f'resource_pool_spec: {resource_pool_spec}') + mapping = { + Role.ActorRollout: actor_rollout_ref_pool_id, + Role.Critic: critic_pool_id, + Role.RefPolicy: actor_rollout_ref_pool_id, + } + + # we should adopt a multi-source reward function here + # - for rule-based rm, we directly call a reward score + # - for model-based rm, we call a model + # - for code related prompt, we send to a sandbox if there are test cases + # - finally, we combine all the rewards together + # - The reward type depends on the tag of the data + if config.reward_model.enable: + if config.reward_model.strategy == 'fsdp': + from verl.workers.fsdp_workers import RewardModelWorker + elif config.reward_model.strategy == 'megatron': + from verl.workers.megatron_workers import RewardModelWorker + else: + raise NotImplementedError + role_worker_mapping[Role.RewardModel] = ray.remote(RewardModelWorker) + mapping[Role.RewardModel] = critic_pool_id + + reward_fn = RewardManager(tokenizer=tokenizer, num_examine=0) + + # Note that we always use function-based RM for validation + val_reward_fn = RewardManager(tokenizer=tokenizer, num_examine=1) + + resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=mapping) + + RayPPOTrainer.fit = fit + trainer = RayPPOTrainer(config=config, + tokenizer=tokenizer, + role_worker_mapping=role_worker_mapping, + resource_pool_manager=resource_pool_manager, + ray_worker_group_cls=ray_worker_group_cls, + reward_fn=reward_fn, + val_reward_fn=val_reward_fn) + trainer.init_workers() + trainer.fit() + + +if __name__ == '__main__': + main() diff --git a/deep_search/DeepResearcher/examples/split_placement/run_deepseek7b_llm.sh b/deep_search/DeepResearcher/examples/split_placement/run_deepseek7b_llm.sh new file mode 100644 index 0000000000000000000000000000000000000000..e0a47260f4a2799f8a0a5d8dda8f929d09558eaa --- /dev/null +++ b/deep_search/DeepResearcher/examples/split_placement/run_deepseek7b_llm.sh @@ -0,0 +1,35 @@ +set -x + +python3 main_ppo_split.py \ + data.train_files=$HOME/data/gsm8k/train.parquet \ + data.val_files=$HOME/data/gsm8k/test.parquet \ + data.train_batch_size=1024 \ + data.max_prompt_length=512 \ + data.max_response_length=512 \ + actor_rollout_ref.model.path=deepseek-ai/deepseek-llm-7b-chat \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.actor.ppo_mini_batch_size=256 \ + actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=8 \ + actor_rollout_ref.actor.fsdp_config.param_offload=False \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \ + actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=8 \ + actor_rollout_ref.rollout.tensor_model_parallel_size=4 \ + actor_rollout_ref.rollout.name=vllm \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.4 \ + actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=8 \ + actor_rollout_ref.ref.fsdp_config.param_offload=True \ + critic.optim.lr=1e-5 \ + critic.model.path=deepseek-ai/deepseek-llm-7b-chat \ + critic.model.enable_gradient_checkpointing=False \ + critic.ppo_micro_batch_size_per_gpu=8 \ + critic.model.fsdp_config.param_offload=False \ + critic.model.fsdp_config.optimizer_offload=False \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.critic_warmup=0 \ + trainer.logger=['console','wandb'] \ + trainer.project_name='verl_example_gsm8k' \ + trainer.experiment_name='deepseek_llm_7b_function_rm' \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=-1 \ + trainer.total_epochs=15 $@ diff --git a/deep_search/DeepResearcher/examples/split_placement/split_monkey_patch.py b/deep_search/DeepResearcher/examples/split_placement/split_monkey_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..dfcbc5c2e03f36ada623cb8597a0f653e3d2c4d4 --- /dev/null +++ b/deep_search/DeepResearcher/examples/split_placement/split_monkey_patch.py @@ -0,0 +1,197 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +An naive implementation of split placment example +""" +from pprint import pprint +from verl import DataProto +from verl.trainer.ppo.ray_trainer import compute_advantage, apply_kl_penalty, reduce_metrics, compute_data_metrics, _timer, compute_timing_metrics, AdvantageEstimator +from copy import deepcopy +import numpy as np +import torch +import uuid + + +def fit(self): + """ + The training loop of PPO. + The driver process only need to call the compute functions of the worker group through RPC to construct the PPO dataflow. + The light-weight advantage computation is done on the driver process. + """ + from verl.utils.tracking import Tracking + from omegaconf import OmegaConf + + logger = Tracking(project_name=self.config.trainer.project_name, + experiment_name=self.config.trainer.experiment_name, + default_backend=self.config.trainer.logger, + config=OmegaConf.to_container(self.config, resolve=True)) + + self.global_steps = 0 + + # load checkpoint before doing anything + self._load_checkpoint() + + # perform validation before training + # currently, we only support validation using the reward_function. + if self.val_reward_fn is not None and self.config.trainer.get('val_before_train', True): + val_metrics = self._validate() + pprint(f'Initial validation metrics: {val_metrics}') + logger.log(data=val_metrics, step=self.global_steps) + if self.config.trainer.get('val_only', False): + return + + # we start from step 1 + self.global_steps += 1 + + for epoch in range(self.config.trainer.total_epochs): + for batch_dict in self.train_dataloader: + metrics = {} + timing_raw = {} + + batch: DataProto = DataProto.from_single_dict(batch_dict) + + # pop those keys for generation + gen_batch = batch.pop(batch_keys=['input_ids', 'attention_mask', 'position_ids']) + + with _timer('step', timing_raw): + # generate a batch + with _timer('gen', timing_raw): + gen_batch_output = self.actor_rollout_wg.generate_sequences(gen_batch) + + if self.config.algorithm.adv_estimator == AdvantageEstimator.REMAX: + with _timer('gen_max', timing_raw): + gen_baseline_batch = deepcopy(gen_batch) + gen_baseline_batch.meta_info['do_sample'] = False + gen_baseline_output = self.actor_rollout_wg.generate_sequences(gen_baseline_batch) + + batch = batch.union(gen_baseline_output) + reward_baseline_tensor = self.reward_fn(batch) + reward_baseline_tensor = reward_baseline_tensor.sum(dim=-1) + + batch.pop(batch_keys=list(gen_baseline_output.batch.keys())) + + batch.batch['reward_baselines'] = reward_baseline_tensor + + del gen_baseline_batch, gen_baseline_output + + batch.non_tensor_batch['uid'] = np.array([str(uuid.uuid4()) for _ in range(len(batch.batch))], + dtype=object) + # repeat to align with repeated responses in rollout + batch = batch.repeat(repeat_times=self.config.actor_rollout_ref.rollout.n, interleave=True) + batch = batch.union(gen_batch_output) + + # balance the number of valid tokens on each dp rank. + # Note that this breaks the order of data inside the batch. + # Please take care when you implement group based adv computation such as GRPO and rloo + self._balance_batch(batch, metrics=metrics) + + # compute global_valid tokens + batch.meta_info['global_token_num'] = torch.sum(batch.batch['attention_mask'], dim=-1).tolist() + + # recompute old_log_probs + with _timer('old_log_prob', timing_raw): + old_log_prob = self.actor_rollout_wg.compute_log_prob(batch) + batch = batch.union(old_log_prob) + + if self.use_reference_policy: + # compute reference log_prob + with _timer('ref', timing_raw): + ref_log_prob = self.ref_policy_wg.compute_ref_log_prob(batch) + batch = batch.union(ref_log_prob) + + # compute values + if self.use_critic: + with _timer('values', timing_raw): + values = self.critic_wg.compute_values(batch) + batch = batch.union(values) + + with _timer('adv', timing_raw): + # compute scores. Support both model and function-based. + # We first compute the scores using reward model. Then, we call reward_fn to combine + # the results from reward model and rule-based results. + if self.use_rm: + # we first compute reward model score + reward_tensor = self.rm_wg.compute_rm_score(batch) + batch = batch.union(reward_tensor) + + # we combine with rule-based rm + reward_tensor = self.reward_fn(batch) + batch.batch['token_level_scores'] = reward_tensor + + # compute rewards. apply_kl_penalty if available + if not self.config.actor_rollout_ref.actor.get('use_kl_loss', False): + batch, kl_metrics = apply_kl_penalty(batch, + kl_ctrl=self.kl_ctrl, + kl_penalty=self.config.algorithm.kl_penalty) + metrics.update(kl_metrics) + else: + batch.batch['token_level_rewards'] = batch.batch['token_level_scores'] + + # compute advantages, executed on the driver process + batch = compute_advantage(batch, + adv_estimator=self.config.algorithm.adv_estimator, + gamma=self.config.algorithm.gamma, + lam=self.config.algorithm.lam, + num_repeat=self.config.actor_rollout_ref.rollout.n) + + # update critic + if self.use_critic: + with _timer('update_critic_call', timing_raw): + critic_output = self.critic_wg.update_critic(batch) + + # implement critic warmup + if self.config.trainer.critic_warmup <= self.global_steps: + # update actor + with _timer('update_actor_call', timing_raw): + actor_output = self.actor_rollout_wg.update_actor(batch) + + # NOTE: make sure you set blocking=False in update_actor and update_crtic in the worker class + with _timer('update_actor_critic', timing_raw): + critic_output = critic_output.get() + critic_output_metrics = reduce_metrics(critic_output.meta_info['metrics']) + metrics.update(critic_output_metrics) + + actor_output = actor_output.get() + actor_output_metrics = reduce_metrics(actor_output.meta_info['metrics']) + metrics.update(actor_output_metrics) + + # validate + if self.val_reward_fn is not None and self.config.trainer.test_freq > 0 and \ + self.global_steps % self.config.trainer.test_freq == 0: + with _timer('testing', timing_raw): + val_metrics: dict = self._validate() + metrics.update(val_metrics) + + if self.config.trainer.save_freq > 0 and \ + self.global_steps % self.config.trainer.save_freq == 0: + with _timer('save_checkpoint', timing_raw): + self._save_checkpoint() + + # collect metrics + metrics.update(compute_data_metrics(batch=batch, use_critic=self.use_critic)) + metrics.update(compute_timing_metrics(batch=batch, timing_raw=timing_raw)) + + # TODO: make a canonical logger that supports various backend + logger.log(data=metrics, step=self.global_steps) + + self.global_steps += 1 + + if self.global_steps >= self.total_training_steps: + + # perform validation after training + if self.val_reward_fn is not None: + val_metrics = self._validate() + pprint(f'Final validation metrics: {val_metrics}') + logger.log(data=val_metrics, step=self.global_steps) + return diff --git a/deep_search/DeepResearcher/pyproject.toml b/deep_search/DeepResearcher/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..a16fd814f556ba27f67b36f6b20e6f64043be38e --- /dev/null +++ b/deep_search/DeepResearcher/pyproject.toml @@ -0,0 +1,86 @@ +# ------------------------------- +# build-system +# ------------------------------- +[build-system] +requires = [ + "setuptools>=61.0", + "wheel" +] +build-backend = "setuptools.build_meta" + +# ------------------------------- +# project (PEP 621 metadata) +# ------------------------------- +[project] +name = "verl" +# We'll mark the version as "dynamic" because it's read from the file "verl/version/version" +# (PEP 621 calls this "dynamic version"). +# The actual version is specified in the [tool.setuptools.dynamic] section below. +dynamic = ["version"] + +description = "verl: Volcano Engine Reinforcement Learning for LLM" +license = {file = "LICENSE"} # or "Apache-2.0", if you prefer an SPDX identifier +readme = {file = "README.md", content-type = "text/markdown"} +requires-python = ">=3.8" + +authors = [ + { name = "Bytedance - Seed - MLSys", email = "zhangchi.usc1992@bytedance.com" }, + { name = "Bytedance - Seed - MLSys", email = "gmsheng@connect.hku.hk" }, +] + +# Dependencies corresponding to install_requires in setup.py +dependencies = [ + "accelerate", + "codetiming", + "datasets", + "dill", + "hydra-core", + "numpy", + "pandas", + "peft", + "pyarrow>=15.0.0", + "pybind11", + "pylatexenc", + "ray>=2.10", + "tensordict<0.6", + "torchdata", + "transformers", + "vllm<=0.6.3", + 'wandb', +] + +# Optional dependencies (extras_require in setup.py) +[project.optional-dependencies] +test = [ + "pytest", "yapf", "py-spy", +] +prime = ["pyext"] +gpu = ["liger-kernel", "flash-attn"] + +# URLs +[project.urls] +Homepage = "https://github.com/volcengine/verl" + +# ------------------------------- +# tool.setuptools - Additional config +# ------------------------------- +[tool.setuptools] +# True means `setuptools` will attempt to include all relevant files in package_data automatically. +# This corresponds to `include_package_data=True` in setup.py. +include-package-data = true + +# We read the version from a file in 'verl/version/version' +[tool.setuptools.dynamic] +version = {file = "verl/version/version"} + +# If you need to mimic `package_dir={'': '.'}`: +[tool.setuptools.package-dir] +"" = "." + +# If you need to include specific non-Python data (like YAML files or version file): +# This is the rough equivalent of package_data={'': ['version/*'], 'verl': ['trainer/config/*.yaml']} +[tool.setuptools.package-data] +verl = [ + "version/*", + "trainer/config/*.yaml" +] diff --git a/deep_search/DeepResearcher/requirements.txt b/deep_search/DeepResearcher/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c5058db3333a61fac13de7137d5d96b4e02d07a --- /dev/null +++ b/deep_search/DeepResearcher/requirements.txt @@ -0,0 +1,64 @@ +# requirements.txt records the full set of dependencies for development +accelerate +codetiming +datasets +dill +flash-attn +hydra-core +liger-kernel +numpy +pandas +peft +pyarrow>=15.0.0 +pybind11 +pylatexenc +ray[data,train,tune,serve] +tensordict<0.6 +torchdata +transformers +vllm<=0.6.3 +wandb +pathvalidate +smolagents +mammoth +pdfminer +python-pptx +puremagic +pydub +SpeechRecognition +PyPDF2 +youtube_transcript_api +serpapi +tqdm +pubchempy +Bio +scikit-learn +google_search_results +markdownify +numexpr +openai +openpyxl +python-dotenv +chess +sympy +xlrd +huggingface_hub +Requests +beautifulsoup4 +Pillow +modelscope +html2text +pathvalidate +smolagents +pdfminer +mammoth +pdfminer.six +python-pptx +pydub +puremagic +SpeechRecognition +youtube_transcript_api +html2text +flask +psutil +pymongo diff --git a/deep_search/DeepResearcher/setup.py b/deep_search/DeepResearcher/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..2abb13ecb57497e4257a998c828d0e830b8eb2db --- /dev/null +++ b/deep_search/DeepResearcher/setup.py @@ -0,0 +1,77 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# setup.py is the fallback installation script when pyproject.toml does not work +from setuptools import setup, find_packages +import os + +version_folder = os.path.dirname(os.path.join(os.path.abspath(__file__))) + +with open(os.path.join(version_folder, 'verl/version/version')) as f: + __version__ = f.read().strip() + +install_requires = [ + 'accelerate', + 'codetiming', + 'datasets', + 'dill', + 'hydra-core', + 'numpy', + 'pandas', + 'peft', + 'pyarrow>=15.0.0', + 'pybind11', + 'pylatexenc', + 'ray>=2.10', + 'tensordict<0.6', + 'torchdata', + 'transformers', + 'vllm<=0.6.3', + 'wandb', +] + +TEST_REQUIRES = ['pytest', 'yapf', 'py-spy'] +PRIME_REQUIRES = ['pyext'] +GEO_REQUIRES = ['mathruler'] +GPU_REQUIRES = ['liger-kernel', 'flash-attn'] + +extras_require = { + 'test': TEST_REQUIRES, + 'prime': PRIME_REQUIRES, + 'geo': GEO_REQUIRES, + 'gpu': GPU_REQUIRES, +} + +from pathlib import Path +this_directory = Path(__file__).parent +long_description = (this_directory / "README.md").read_text() + +setup( + name='verl', + version=__version__, + package_dir={'': '.'}, + packages=find_packages(where='.'), + url='https://github.com/volcengine/verl', + license='Apache 2.0', + author='Bytedance - Seed - MLSys', + author_email='zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk', + description='verl: Volcano Engine Reinforcement Learning for LLM', + install_requires=install_requires, + extras_require=extras_require, + package_data={'': ['version/*'], + 'verl': ['trainer/config/*.yaml'],}, + include_package_data=True, + long_description=long_description, + long_description_content_type='text/markdown' +) \ No newline at end of file diff --git a/deep_search/DeepResearcher/train_grpo.sh b/deep_search/DeepResearcher/train_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..dac16ed56e6e04c01b7c0aa2efce0a1addc117ab --- /dev/null +++ b/deep_search/DeepResearcher/train_grpo.sh @@ -0,0 +1,51 @@ + +export VLLM_ATTENTION_BACKEND=XFORMERS +export project_name="project_name" +export experiment_name="experiment_name" + + +PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \ + data.train_files=./data/train.parquet \ + data.val_files=./data/dev.parquet \ + data.train_batch_size=256 \ + data.max_prompt_length=30767 \ + data.max_response_length=2000 \ + +data.max_model_len=32768 \ + data.data_writing_file=./signal/data.json \ + data.signal_writing_file=./signal/signal.json \ + actor_rollout_ref.model.path=Qwen/Qwen2.5-7B-Instruct \ + actor_rollout_ref.model.use_remove_padding=true \ + actor_rollout_ref.actor.optim.lr=1e-6 \ + actor_rollout_ref.actor.ppo_mini_batch_size=4096 \ + actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=2 \ + actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=2 \ + actor_rollout_ref.rollout.tensor_model_parallel_size=1 \ + actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \ + actor_rollout_ref.rollout.max_num_batched_tokens=32768 \ + actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=2 \ + actor_rollout_ref.actor.use_kl_loss=true \ + actor_rollout_ref.actor.use_dynamic_bsz=true \ + actor_rollout_ref.actor.fsdp_config.param_offload=true \ + actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \ + actor_rollout_ref.ref.fsdp_config.param_offload=true \ + actor_rollout_ref.actor.ppo_max_token_len_per_gpu=12288 \ + actor_rollout_ref.actor.ulysses_sequence_parallel_size=4 \ + critic.optim.lr=1e-5 \ + critic.model.path=Qwen/Qwen2.5-7B-Instruct \ + critic.ppo_micro_batch_size_per_gpu=2 \ + algorithm.kl_ctrl.kl_coef=0.001 \ + trainer.logger=['console','wandb'] \ + trainer.project_name=${project_name} \ + trainer.experiment_name=${experiment_name} \ + +trainer.val_before_train=false \ + trainer.default_hdfs_dir=null \ + trainer.n_gpus_per_node=8 \ + trainer.nnodes=1 \ + trainer.save_freq=1 \ + trainer.test_freq=1 \ + trainer.remove_previous_ckpt_in_save=false \ + agent_grpo.n=16 \ + max_turns=10 \ + search_engine=online_search \ + trainer.total_epochs=1 2>&1 | tee ./${project_name}_${experiment_name}.log + diff --git a/deep_search/search_o1/eval/__pycache__/utils.cpython-310.pyc b/deep_search/search_o1/eval/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..970e037606f3b32e70b5a8b7ebcfbc6e366b00ca Binary files /dev/null and b/deep_search/search_o1/eval/__pycache__/utils.cpython-310.pyc differ diff --git a/deep_search/search_o1/eval/__pycache__/utils.cpython-39.pyc b/deep_search/search_o1/eval/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5b5d41a6f7f169c5d5ecf4623a5e3c794f3b366 Binary files /dev/null and b/deep_search/search_o1/eval/__pycache__/utils.cpython-39.pyc differ diff --git a/deep_search/search_o1/eval/add_eval.py b/deep_search/search_o1/eval/add_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..e62b62b2f46612bb43aedcf0b026cb1110e8be28 --- /dev/null +++ b/deep_search/search_o1/eval/add_eval.py @@ -0,0 +1,207 @@ +import json +import re +from utils import has_answer, EM_compute, F1_compute, AC_compute + +import os +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +import numpy as np +import matplotlib.pyplot as plt +import seaborn as sns + + + + + + +def calculate_statistics(data): + return { + 'mean': np.mean(data), + 'std': np.std(data), + 'median': np.median(data), + 'min': np.min(data), + 'max': np.max(data), + '25th_percentile': np.percentile(data, 25), + '75th_percentile': np.percentile(data, 75), + } + + +def analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len): + all_outputs_len_stats = calculate_statistics(all_outputs_len) + retrieval_outputs_len_stats = calculate_statistics(retrieval_outputs_len) + no_retrieval_outputs_len_stats = calculate_statistics(no_retrieval_outputs_len) + + # 打印统计数据 + print("All outputs length statistics:", all_outputs_len_stats) + print("Retrieval outputs length statistics:", retrieval_outputs_len_stats) + print("No retrieval outputs length statistics:", no_retrieval_outputs_len_stats) + + # 创建保存结果的目录 + output_dir = output_len_analyse_path + if not os.path.exists(output_dir): + os.makedirs(output_dir) + + # 绘制直方图并保存图像 + plt.figure(figsize=(12, 8)) + + # 绘制所有输出长度的直方图 + plt.subplot(2, 2, 1) + sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density') + plt.title('Distribution of All Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + # plt.savefig(os.path.join(output_dir, 'all_outputs_length_distribution.png')) + + # 绘制检索输出长度的直方图 + plt.subplot(2, 2, 2) + sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density') + plt.title('Distribution of Retrieval Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + # plt.savefig(os.path.join(output_dir, 'retrieval_outputs_length_distribution.png')) + + # 绘制没有检索输出长度的直方图 + plt.subplot(2, 2, 3) + sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density') + plt.title('Distribution of No Retrieval Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + # plt.savefig(os.path.join(output_dir, 'no_retrieval_outputs_length_distribution.png')) + + # 总体输出长度分布 + plt.subplot(2, 2, 4) + sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density', alpha=0.5) + sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density', alpha=0.5) + sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density', alpha=0.5) + plt.title('Overall Distribution of Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + plt.legend() + # plt.savefig(os.path.join(output_dir, 'overall_output_length_distribution.png')) + + # 保存所有图像 + plt.tight_layout() + plt.savefig(os.path.join(output_dir, 'combined_output_length_distribution.png')) + + plt.show() + +def has_run_retrieve(sample): + return bool (sample["search_count"]) + +def cal_has_answer(sample): + reason_has, search_has, analyses_has = 0, 0, 0 + for info in sample["all_info"]: + for k, v in info.items(): + if "reason" in k: + reason_has = max(reason_has, has_answer(sample['answer'], v)) + elif "search" in k: + search_has = max(search_has, has_answer(sample['answer'], v)) + elif "analyses" in k: + analyses_has = max(analyses_has, has_answer(sample['answer'], v)) + return {'reason': reason_has, 'search': search_has, 'analyse': analyses_has} + +def extract_answer(sample): + output = sample.get('output', '') + match = re.search(r'\\boxed\{(.*?)\}', output) + if match: + return match.group(1) + return output.rsplit('\n', 1)[-1] + +def cal_metrics(sample): + res = {} + pred = extract_answer(sample) + for m, func in { + 'em': EM_compute, + 'ac': AC_compute, + 'f1': F1_compute, + }.items(): + res[m] = func(sample['answer'], pred) + res.update(cal_has_answer(sample)) + res['search_count'] = sample['search_count'] + return res + +def add_eval(model_path, data_path): + + # model_path = "/opt/aps/workdir/sunshuang/search_o1/Qwen2.5-7B-Instruct" + # 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" + output_len_analyse_path = os.path.dirname(data_path) + + # model = AutoModelForCausalLM.from_pretrained(model_path).to(torch.bfloat16).to("cuda") + tokenizer = AutoTokenizer.from_pretrained(model_path) + + with open(data_path) as f: + results = json.load(f) + + # 初始化累加器 + total_metrics = {} + retrieval_true_metrics = {} + retrieval_false_metrics = {} + count_total = 0 + count_retrieval_true = 0 + count_retrieval_false = 0 + + # 计算平均长度 + all_outputs_len = [] + retrieval_outputs_len = [] + no_retrieval_outputs_len = [] + + # 遍历每个样本并计算指标 + for sample in results: + sample.update(sample["item"]) + metrics = cal_metrics(sample) + + output_ids = tokenizer(sample["output"], add_special_tokens=False)["input_ids"] + all_outputs_len.append(len(output_ids)) + + # 累加总的指标 + for key, value in metrics.items(): + total_metrics[key] = total_metrics.get(key, 0) + value + + # 根据是否跑了检索进行分类累加 + if has_run_retrieve(sample): + retrieval_outputs_len.append(len(output_ids)) + + for key, value in metrics.items(): + retrieval_true_metrics[key] = retrieval_true_metrics.get(key, 0) + value + count_retrieval_true += 1 + else: + no_retrieval_outputs_len.append(len(output_ids)) + for key, value in metrics.items(): + retrieval_false_metrics[key] = retrieval_false_metrics.get(key, 0) + value + count_retrieval_false += 1 + + count_total += 1 + + # 计算均值 + mean_metrics = {key: value / count_total for key, value in total_metrics.items()} + mean_retrieval_true_metrics = {key: value / count_retrieval_true for key, value in retrieval_true_metrics.items()} + mean_retrieval_false_metrics = {key: value / count_retrieval_false for key, value in retrieval_false_metrics.items()} + + mean_all_output_len = sum(all_outputs_len) / len(all_outputs_len) + mean_retrieval_outputs_len = sum(retrieval_outputs_len) / len(retrieval_outputs_len) + mean_no_retrieval_outputs_len = sum(no_retrieval_outputs_len) / len(no_retrieval_outputs_len) + + analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len) + + print(count_retrieval_false/count_total) + print(count_retrieval_true/count_total) + + # 打印结果 + print(f"model_path: {model_path}") + print(f"data_path: {data_path}") + print("Overall Mean Metrics:") + for key, value in mean_metrics.items(): + print(f"{key}: {value}") + print(f"output_len: {mean_all_output_len}") + + print("\nMean Metrics for Samples with Retrieval:") + for key, value in mean_retrieval_true_metrics.items(): + print(f"{key}: {value}") + print(f"output_len: {mean_retrieval_outputs_len}") + + print("\nMean Metrics for Samples without Retrieval:") + for key, value in mean_retrieval_false_metrics.items(): + print(f"{key}: {value}") + print(f"output_len: {mean_no_retrieval_outputs_len}") + +main() \ No newline at end of file diff --git a/deep_search/search_o1/eval/eval_seach_o1.py b/deep_search/search_o1/eval/eval_seach_o1.py new file mode 100644 index 0000000000000000000000000000000000000000..54e70c3b883c7522b73e124fe8f493a15ce55dfb --- /dev/null +++ b/deep_search/search_o1/eval/eval_seach_o1.py @@ -0,0 +1,93 @@ +import json +import re +from utils import has_answer, EM_compute, F1_compute, AC_compute + + +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: + results = json.load(f) + +def has_run_retrieve(sample): + return bool (sample["search_count"]) + +def cal_has_answer(sample): + reason_has, search_has, analyses_has = 0, 0, 0 + for info in sample["all_info"]: + for k, v in info.items(): + if "reason" in k: + reason_has = max(reason_has, has_answer(sample['answer'], v)) + elif "search" in k: + search_has = max(search_has, has_answer(sample['answer'], v)) + elif "analyses" in k: + analyses_has = max(analyses_has, has_answer(sample['answer'], v)) + return {'reason': reason_has, 'search': search_has, 'analyse': analyses_has} + +def extract_answer(sample): + output = sample.get('output', '') + match = re.search(r'\\boxed\{(.*?)\}', output) + if match: + return match.group(1) + return output.rsplit('\n', 1)[-1] + +def cal_metrics(sample): + res = {} + pred = extract_answer(sample) + for m, func in { + 'em': EM_compute, + 'ac': AC_compute, + 'f1': F1_compute, + }.items(): + res[m] = func(sample['answer'], pred) + res.update(cal_has_answer(sample)) + res['search_count'] = sample['search_count'] + return res + +def main(): + # 初始化累加器 + total_metrics = {} + retrieval_true_metrics = {} + retrieval_false_metrics = {} + count_total = 0 + count_retrieval_true = 0 + count_retrieval_false = 0 + + # 遍历每个样本并计算指标 + for sample in results: + sample.update(sample["item"]) + metrics = cal_metrics(sample) + + # 累加总的指标 + for key, value in metrics.items(): + total_metrics[key] = total_metrics.get(key, 0) + value + + # 根据是否跑了检索进行分类累加 + if has_run_retrieve(sample): + for key, value in metrics.items(): + retrieval_true_metrics[key] = retrieval_true_metrics.get(key, 0) + value + count_retrieval_true += 1 + else: + for key, value in metrics.items(): + retrieval_false_metrics[key] = retrieval_false_metrics.get(key, 0) + value + count_retrieval_false += 1 + + count_total += 1 + + # 计算均值 + mean_metrics = {key: value / count_total for key, value in total_metrics.items()} + mean_retrieval_true_metrics = {key: value / count_retrieval_true for key, value in retrieval_true_metrics.items()} + mean_retrieval_false_metrics = {key: value / count_retrieval_false for key, value in retrieval_false_metrics.items()} + print(count_retrieval_false/count_total) + print(count_retrieval_true/count_total) + # 打印结果 + print("Overall Mean Metrics:") + for key, value in mean_metrics.items(): + print(f"{key}: {value}") + + print("\nMean Metrics for Samples with Retrieval:") + for key, value in mean_retrieval_true_metrics.items(): + print(f"{key}: {value}") + + print("\nMean Metrics for Samples without Retrieval:") + for key, value in mean_retrieval_false_metrics.items(): + print(f"{key}: {value}") + +main() \ No newline at end of file diff --git a/deep_search/search_o1/eval/eval_seach_o1_with_output_len.py b/deep_search/search_o1/eval/eval_seach_o1_with_output_len.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5adff9cf005226a6f1f5e799fe6e4f6b6c1112 --- /dev/null +++ b/deep_search/search_o1/eval/eval_seach_o1_with_output_len.py @@ -0,0 +1,202 @@ +import json +import re +from utils import has_answer, EM_compute, F1_compute, AC_compute + +import os +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +import numpy as np +import matplotlib.pyplot as plt +import seaborn as sns + +model_path = "/opt/aps/workdir/sunshuang/search_o1/Qwen2.5-7B-Instruct" +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" +output_len_analyse_path = os.path.dirname(data_path) + +# model = AutoModelForCausalLM.from_pretrained(model_path).to(torch.bfloat16).to("cuda") +tokenizer = AutoTokenizer.from_pretrained(model_path) + +with open(data_path) as f: + results = json.load(f) + + +def calculate_statistics(data): + return { + 'mean': np.mean(data), + 'std': np.std(data), + 'median': np.median(data), + 'min': np.min(data), + 'max': np.max(data), + '25th_percentile': np.percentile(data, 25), + '75th_percentile': np.percentile(data, 75), + } + + +def analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len): + all_outputs_len_stats = calculate_statistics(all_outputs_len) + retrieval_outputs_len_stats = calculate_statistics(retrieval_outputs_len) + no_retrieval_outputs_len_stats = calculate_statistics(no_retrieval_outputs_len) + + # 打印统计数据 + print("All outputs length statistics:", all_outputs_len_stats) + print("Retrieval outputs length statistics:", retrieval_outputs_len_stats) + print("No retrieval outputs length statistics:", no_retrieval_outputs_len_stats) + + # 创建保存结果的目录 + output_dir = output_len_analyse_path + if not os.path.exists(output_dir): + os.makedirs(output_dir) + + # 绘制直方图并保存图像 + plt.figure(figsize=(12, 8)) + + # 绘制所有输出长度的直方图 + plt.subplot(2, 2, 1) + sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density') + plt.title('Distribution of All Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + # plt.savefig(os.path.join(output_dir, 'all_outputs_length_distribution.png')) + + # 绘制检索输出长度的直方图 + plt.subplot(2, 2, 2) + sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density') + plt.title('Distribution of Retrieval Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + # plt.savefig(os.path.join(output_dir, 'retrieval_outputs_length_distribution.png')) + + # 绘制没有检索输出长度的直方图 + plt.subplot(2, 2, 3) + sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density') + plt.title('Distribution of No Retrieval Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + # plt.savefig(os.path.join(output_dir, 'no_retrieval_outputs_length_distribution.png')) + + # 总体输出长度分布 + plt.subplot(2, 2, 4) + sns.histplot(all_outputs_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density', alpha=0.5) + sns.histplot(retrieval_outputs_len, kde=True, bins=30, color='green', label='Retrieval Outputs', stat='density', alpha=0.5) + sns.histplot(no_retrieval_outputs_len, kde=True, bins=30, color='red', label='No Retrieval Outputs', stat='density', alpha=0.5) + plt.title('Overall Distribution of Outputs Length') + plt.xlabel('Length') + plt.ylabel('Density') + plt.legend() + # plt.savefig(os.path.join(output_dir, 'overall_output_length_distribution.png')) + + # 保存所有图像 + plt.tight_layout() + plt.savefig(os.path.join(output_dir, 'combined_output_length_distribution.png')) + + plt.show() + +def has_run_retrieve(sample): + return bool (sample["search_count"]) + +def cal_has_answer(sample): + reason_has, search_has, analyses_has = 0, 0, 0 + for info in sample["all_info"]: + for k, v in info.items(): + if "reason" in k: + reason_has = max(reason_has, has_answer(sample['answer'], v)) + elif "search" in k: + search_has = max(search_has, has_answer(sample['answer'], v)) + elif "analyses" in k: + analyses_has = max(analyses_has, has_answer(sample['answer'], v)) + return {'reason': reason_has, 'search': search_has, 'analyse': analyses_has} + +def extract_answer(sample): + output = sample.get('output', '') + match = re.search(r'\\boxed\{(.*?)\}', output) + if match: + return match.group(1) + return output.rsplit('\n', 1)[-1] + +def cal_metrics(sample): + res = {} + pred = extract_answer(sample) + for m, func in { + 'em': EM_compute, + 'ac': AC_compute, + 'f1': F1_compute, + }.items(): + res[m] = func(sample['answer'], pred) + res.update(cal_has_answer(sample)) + res['search_count'] = sample['search_count'] + return res + +def main(): + # 初始化累加器 + total_metrics = {} + retrieval_true_metrics = {} + retrieval_false_metrics = {} + count_total = 0 + count_retrieval_true = 0 + count_retrieval_false = 0 + + # 计算平均长度 + all_outputs_len = [] + retrieval_outputs_len = [] + no_retrieval_outputs_len = [] + + # 遍历每个样本并计算指标 + for sample in results: + sample.update(sample["item"]) + metrics = cal_metrics(sample) + + output_ids = tokenizer(sample["output"], add_special_tokens=False)["input_ids"] + all_outputs_len.append(len(output_ids)) + + # 累加总的指标 + for key, value in metrics.items(): + total_metrics[key] = total_metrics.get(key, 0) + value + + # 根据是否跑了检索进行分类累加 + if has_run_retrieve(sample): + retrieval_outputs_len.append(len(output_ids)) + + for key, value in metrics.items(): + retrieval_true_metrics[key] = retrieval_true_metrics.get(key, 0) + value + count_retrieval_true += 1 + else: + no_retrieval_outputs_len.append(len(output_ids)) + for key, value in metrics.items(): + retrieval_false_metrics[key] = retrieval_false_metrics.get(key, 0) + value + count_retrieval_false += 1 + + count_total += 1 + + # 计算均值 + mean_metrics = {key: value / count_total for key, value in total_metrics.items()} + mean_retrieval_true_metrics = {key: value / count_retrieval_true for key, value in retrieval_true_metrics.items()} + mean_retrieval_false_metrics = {key: value / count_retrieval_false for key, value in retrieval_false_metrics.items()} + + mean_all_output_len = sum(all_outputs_len) / len(all_outputs_len) + mean_retrieval_outputs_len = sum(retrieval_outputs_len) / len(retrieval_outputs_len) + mean_no_retrieval_outputs_len = sum(no_retrieval_outputs_len) / len(no_retrieval_outputs_len) + + analyse_len(all_outputs_len, retrieval_outputs_len, no_retrieval_outputs_len) + + print(count_retrieval_false/count_total) + print(count_retrieval_true/count_total) + + # 打印结果 + print(f"model_path: {model_path}") + print(f"data_path: {data_path}") + print("Overall Mean Metrics:") + for key, value in mean_metrics.items(): + print(f"{key}: {value}") + print(f"output_len: {mean_all_output_len}") + + print("\nMean Metrics for Samples with Retrieval:") + for key, value in mean_retrieval_true_metrics.items(): + print(f"{key}: {value}") + print(f"output_len: {mean_retrieval_outputs_len}") + + print("\nMean Metrics for Samples without Retrieval:") + for key, value in mean_retrieval_false_metrics.items(): + print(f"{key}: {value}") + print(f"output_len: {mean_no_retrieval_outputs_len}") + +main() \ No newline at end of file diff --git a/deep_search/search_o1/eval/token_len.py b/deep_search/search_o1/eval/token_len.py new file mode 100644 index 0000000000000000000000000000000000000000..79903be6a7fe07055643e87b34593068b2e63f66 --- /dev/null +++ b/deep_search/search_o1/eval/token_len.py @@ -0,0 +1,76 @@ +import json +import re +from utils import has_answer, EM_compute, F1_compute, AC_compute + +import os +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +import numpy as np +import matplotlib.pyplot as plt +import seaborn as sns +from tqdm import tqdm + +def calculate_statistics(data): + return { + 'mean': np.mean(data), + 'std': np.std(data), + 'median': np.median(data), + 'min': np.min(data), + 'max': np.max(data), + '25th_percentile': np.percentile(data, 25), + '75th_percentile': np.percentile(data, 75), + } + + +def analyse_len(text_len): + text_len_stats = calculate_statistics(text_len) + + # 打印统计数据 + print("text length statistics:", text_len_stats) + + # 创建保存结果的目录 + output_dir = output_len_analyse_path + if not os.path.exists(output_dir): + os.makedirs(output_dir) + + # 绘制直方图并保存图像 + plt.figure(figsize=(12, 8)) + + # 绘制所有输出长度的直方图 + sns.histplot(text_len, kde=True, bins=30, color='blue', label='All Outputs', stat='density') + plt.title('Distribution of All texts Length') + plt.xlabel('Length') + plt.ylabel('Density') + plt.savefig(os.path.join(output_dir, 'text_len.png')) + + +def save_to_json(data, filename): + with open(filename, 'w', encoding='utf-8') as f: + json.dump(data, f, ensure_ascii=False, indent=4) + print(f"save to {filename}, data len: {len(data)}") +def load_json(file_path): + with open(file_path, "r", encoding="utf-8") as f: + data = json.load(f) + print(f"load from {file_path}, data len: {len(data)}") + return data + + + +if __name__=="__main__": + + 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" + model_path = "/capacity/userdata/models/Qwen2.5-32B-Instruct" + output_len_analyse_path = os.path.dirname(file_path) + # 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" + data = load_json(file_path) + + tokenizer = AutoTokenizer.from_pretrained(model_path) + + text_len = [] + for item in tqdm(data): + + text_ids = tokenizer(item["prompt"], add_special_tokens=False)["input_ids"] + text_len.append(len(text_ids)) + + analyse_len(text_len) + diff --git a/deep_search/search_o1/eval/topics_stats.py b/deep_search/search_o1/eval/topics_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..48ed54bbe610120e8ac7d5d037f9921df3e1edcf --- /dev/null +++ b/deep_search/search_o1/eval/topics_stats.py @@ -0,0 +1,140 @@ +import json +import os +from collections import defaultdict +import matplotlib.pyplot as plt +import numpy as np + +def read_json(file_path): + """从 JSON 文件中读取数据""" + with open(file_path, "r", encoding="utf-8") as f: + data = json.load(f) + print(f"load from {file_path}, total item: {len(data)}") + return data + +def read_jsonl(file_path): + """从 JSON Lines 文件中读取数据""" + data = [] + with open(file_path, "r", encoding="utf-8") as f: + for line in f: + data.append(json.loads(line.strip())) + print(f"load from {file_path}, total item: {len(data)}") + return data + + +# 统计并绘制图表的函数 +def topics_stats(file_original_path, file_turn_path, file_eval_path): + # 读取数据 + data_original_question = read_json(file_original_path) + data_turn = read_json(file_turn_path) + data_eval = read_json(file_eval_path) + + # 初始化统计字典 + stats = defaultdict(lambda: {"count": 0, "search_count": 0, "acc": 0, "em": 0, "f1": 0}) + + + + # 遍历数据,按 topic 进行统计 + for item_ori, item_turn, item_eval in zip(data_original_question, data_turn, data_eval): + assert item_ori["id"] == item_turn["item"]["id"] == item_eval["id"], "ID mismatch" + topic = item_ori["metadata"]["topic"] + search_count = item_turn["search_count"] + acc = item_eval["Metrics"]["acc"] + em = item_eval["Metrics"]["em"] + f1 = item_eval["Metrics"]["f1"] + + + stats[topic]["count"] += 1 + stats[topic]["search_count"] += search_count + stats[topic]["acc"] += acc + stats[topic]["em"] += em + stats[topic]["f1"] += f1 + + # 不分topic,统计所有的 + stats["all"]["count"] += 1 + stats["all"]["search_count"] += search_count + stats["all"]["acc"] += acc + stats["all"]["em"] += em + stats["all"]["f1"] += f1 + + output_stats_txt_file = os.path.join(os.path.dirname(file_turn_path), "topics_stats.txt") + + # 计算平均值 + avg_stats = {} + for topic, values in stats.items(): + count = values["count"] + avg_stats[topic] = { + "count": count, + "percentage": count / len(data_turn), + "search_count": values["search_count"] / count, + "acc": values["acc"] / count, + "em": values["em"] / count, + "f1": values["f1"] / count, + } + + avg_stats = dict(sorted(avg_stats.items())) + + # 输出统计数据 + # print("Topic Statistics:") + # for topic, metrics in avg_stats.items(): + # print(f"Topic: {topic}") + # print(f" Count: {metrics['count']}") + # print(f" Percentage: {metrics['percentage']:.2%}") + # print(f" Average Search Count: {metrics['search_count']:.2f}") + # print(f" Average Accuracy (acc): {metrics['acc']:.2f}") + # print(f" Average Exact Match (em): {metrics['em']:.2f}") + # print(f" Average F1 Score: {metrics['f1']:.2f}") + + with open(output_stats_txt_file, "w", encoding="utf-8") as f: + f.write("Topic Statistics:\n") + for topic, metrics in avg_stats.items(): + f.write(f"Topic: {topic}\n") + f.write(f" Count: {metrics['count']}\n") + f.write(f" Percentage: {metrics['percentage']:.2%}\n") + f.write(f" Average Search Count: {metrics['search_count']:.2f}\n") + f.write(f" Average Accuracy (acc): {metrics['acc']:.2f}\n") + f.write(f" Average Exact Match (em): {metrics['em']:.2f}\n") + f.write(f" Average F1 Score: {metrics['f1']:.2f}\n") + f.write("\n") + # 绘制图表 + topics = list(avg_stats.keys()) + search_counts = [metrics["search_count"] for metrics in avg_stats.values()] + accs = [metrics["acc"] for metrics in avg_stats.values()] + ems = [metrics["em"] for metrics in avg_stats.values()] + f1s = [metrics["f1"] for metrics in avg_stats.values()] + percentage = [metrics["percentage"] for metrics in avg_stats.values()] + + + x = np.arange(len(topics)) # 横坐标 + width = 0.15 # 柱状图宽度 + + fig, ax = plt.subplots(figsize=(20, 12)) + rects1 = ax.bar(x - 2.5 * width, search_counts, width, label="Search Count") + rects2 = ax.bar(x - 1.5 * width, accs, width, label="Accuracy (acc)") + rects3 = ax.bar(x - 0.5 * width, ems, width, label="Exact Match (em)") + rects4 = ax.bar(x + 0.5 * width, f1s, width, label="F1 Score") + rects5 = ax.bar(x + 1.5 * width, percentage, width, label="Percentage") # 新增的柱状图 + + + + # 添加标签和标题 + ax.set_xlabel("Topics") + ax.set_ylabel("Average Values") + ax.set_title("Average Metrics by Topic") + ax.set_xticks(x) + ax.set_xticklabels(topics, rotation=45, ha="right") + ax.legend() + + # 显示图表 + plt.tight_layout() + plt.show() + + figure_path = os.path.join(os.path.dirname(file_turn_path), "topics_stats.png") + plt.savefig(figure_path) + return avg_stats + + +file_original_path="/share/project/sunshuang/simpleqa_gen_data/data/simple_qa_test_set_format_with_metadata.json" +file_turn_path="/share/project/sunshuang/deep_research/search_o1/output/outputs_sum_all_webpage_simpleqa500_ckpt176/turn_12.json" +file_eval_path="/share/project/sunshuang/deep_research/search_o1/output/outputs_sum_all_webpage_simpleqa500_ckpt176/test.3.11,14:55.json" + +avg_stats = topics_stats(file_original_path, file_turn_path, file_eval_path) \ No newline at end of file diff --git a/deep_search/search_o1/eval/utils.py b/deep_search/search_o1/eval/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e6f34d9bb03ca770c6d1b708d1823d42bf5619fb --- /dev/null +++ b/deep_search/search_o1/eval/utils.py @@ -0,0 +1,450 @@ +num2alpha = { + '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', + '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', +} +import argparse +import collections +import json +import copy +import os +import re +import logging +import string +from typing import List +import regex +import unicodedata +from tqdm import tqdm + + +logger = logging.getLogger() + + +class Tokens(object): + """A class to represent a list of tokenized text.""" + TEXT = 0 + TEXT_WS = 1 + SPAN = 2 + POS = 3 + LEMMA = 4 + NER = 5 + + def __init__(self, data, annotators, opts=None): + self.data = data + self.annotators = annotators + self.opts = opts or {} + + def __len__(self): + """The number of tokens.""" + return len(self.data) + + def slice(self, i=None, j=None): + """Return a view of the list of tokens from [i, j).""" + new_tokens = copy.copy(self) + new_tokens.data = self.data[i: j] + return new_tokens + + def untokenize(self): + """Returns the original text (with whitespace reinserted).""" + return ''.join([t[self.TEXT_WS] for t in self.data]).strip() + + def words(self, uncased=False): + """Returns a list of the text of each token + Args: + uncased: lower cases text + """ + if uncased: + return [t[self.TEXT].lower() for t in self.data] + else: + return [t[self.TEXT] for t in self.data] + + def offsets(self): + """Returns a list of [start, end) character offsets of each token.""" + return [t[self.SPAN] for t in self.data] + + def pos(self): + """Returns a list of part-of-speech tags of each token. + Returns None if this annotation was not included. + """ + if 'pos' not in self.annotators: + return None + return [t[self.POS] for t in self.data] + + def lemmas(self): + """Returns a list of the lemmatized text of each token. + Returns None if this annotation was not included. + """ + if 'lemma' not in self.annotators: + return None + return [t[self.LEMMA] for t in self.data] + + def entities(self): + """Returns a list of named-entity-recognition tags of each token. + Returns None if this annotation was not included. + """ + if 'ner' not in self.annotators: + return None + return [t[self.NER] for t in self.data] + + def ngrams(self, n=1, uncased=False, filter_fn=None, as_strings=True): + """Returns a list of all ngrams from length 1 to n. + Args: + n: upper limit of ngram length + uncased: lower cases text + filter_fn: user function that takes in an ngram list and returns + True or False to keep or not keep the ngram + as_string: return the ngram as a string vs list + """ + + def _skip(gram): + if not filter_fn: + return False + return filter_fn(gram) + + words = self.words(uncased) + ngrams = [(s, e + 1) + for s in range(len(words)) + for e in range(s, min(s + n, len(words))) + if not _skip(words[s:e + 1])] + + # Concatenate into strings + if as_strings: + ngrams = ['{}'.format(' '.join(words[s:e])) for (s, e) in ngrams] + + return ngrams + + def entity_groups(self): + """Group consecutive entity tokens with the same NER tag.""" + entities = self.entities() + if not entities: + return None + non_ent = self.opts.get('non_ent', 'O') + groups = [] + idx = 0 + while idx < len(entities): + ner_tag = entities[idx] + # Check for entity tag + if ner_tag != non_ent: + # Chomp the sequence + start = idx + while (idx < len(entities) and entities[idx] == ner_tag): + idx += 1 + groups.append((self.slice(start, idx).untokenize(), ner_tag)) + else: + idx += 1 + return groups + + +class Tokenizer(object): + """Base tokenizer class. + Tokenizers implement tokenize, which should return a Tokens class. + """ + + def tokenize(self, text): + raise NotImplementedError + + def shutdown(self): + pass + + def __del__(self): + self.shutdown() + + +class SimpleTokenizer(Tokenizer): + ALPHA_NUM = r'[\p{L}\p{N}\p{M}]+' + NON_WS = r'[^\p{Z}\p{C}]' + + def __init__(self, **kwargs): + """ + Args: + annotators: None or empty set (only tokenizes). + """ + self._regexp = regex.compile( + '(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS), + flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE + ) + if len(kwargs.get('annotators', {})) > 0: + logger.warning('%s only tokenizes! Skipping annotators: %s' % + (type(self).__name__, kwargs.get('annotators'))) + self.annotators = set() + + def tokenize(self, text): + data = [] + matches = [m for m in self._regexp.finditer(text)] + for i in range(len(matches)): + # Get text + token = matches[i].group() + + # Get whitespace + span = matches[i].span() + start_ws = span[0] + if i + 1 < len(matches): + end_ws = matches[i + 1].span()[0] + else: + end_ws = span[1] + + # Format data + data.append(( + token, + text[start_ws: end_ws], + span, + )) + return Tokens(data, self.annotators) + +tokenizer = SimpleTokenizer() + +def normalize_span(text): + text = unicodedata.normalize('NFD', text) + text = tokenizer.tokenize(text).words(uncased=False) + return ' '.join(text), len(text) + +def has_answer(answers, text, match_type="string"): + # print(answers, text) + # input() + text = unicodedata.normalize('NFD', text) + if match_type == 'string': + text = tokenizer.tokenize(text).words(uncased=True) + for single_answer in answers: + single_answer = unicodedata.normalize('NFD', single_answer) + single_answer = tokenizer.tokenize(single_answer) + single_answer = single_answer.words(uncased=True) + for i in range(0, len(text) - len(single_answer) + 1): + if single_answer == text[i: i + len(single_answer)]: + return 1 + return 0 + +import unicodedata + +def fake_answer(answers, text, fake_ans, match_type="string"): + answers = might_right_answers(answers) + expand_answers(answers) + # Normalize the input text + text = unicodedata.normalize('NFD', text) + if match_type == 'string': + otext = tokenizer.tokenize(text).words(uncased=False) + oo = ' '.join(otext) + text = tokenizer.tokenize(text).words(uncased=True) + for single_answer in answers: + single_answer = unicodedata.normalize('NFD', single_answer) + single_answer = tokenizer.tokenize(single_answer) + single_answer = single_answer.words(uncased=True) + for i in range(0, len(text) - len(single_answer) + 1): + if single_answer == text[i: i + len(single_answer)]: + ss = ' '.join(otext[i: i + len(single_answer)]) + + oo = oo.replace(ss, fake_ans) + return clean_text(oo) + +def clean_text(text): + # 定义一个正则表达式模式,用于去除标点符号后面的多余空格 + # 这里定义了一些常见的英文标点符号 + pattern_remove_trailing_spaces = r'([,.!?;:\(\)\[\]\{\}—–—])\s+' + + # 定义一个正则表达式模式,用于去除标点符号前面的多余空格 + pattern_remove_leading_spaces = r'\s+([,.!?;:\(\)\[\]\{\}—–—])' + + # 定义一个正则表达式模式,确保标点符号前后至少保留一个空格 + pattern_preserve_single_space = r'(\s*)([,.!?;:\(\)\[\]\{\}—–—])(\s*)' + + # 去除标点符号后面的多余空格 + cleaned_text = re.sub(pattern_remove_trailing_spaces, r'\1 ', text) + + # 去除标点符号前面的多余空格 + cleaned_text = re.sub(pattern_remove_leading_spaces, r' \1', cleaned_text) + + # 确保标点符号前后至少保留一个空格 + cleaned_text = re.sub(pattern_preserve_single_space, r' \2 ', cleaned_text) + + # 去除首尾空白 + cleaned_text = cleaned_text.strip() + + # 最终去除连续的空格 + cleaned_text = re.sub(r'\s+', ' ', cleaned_text) + + return cleaned_text + + +def expand_answers(answers: List[str]): + copy_answers = answers.copy() + res = set(answers) + for single_answer in answers: + if normalize_answer(single_answer) != "": + res.add(normalize_answer(single_answer)) + original_answer = single_answer + single_answer = unicodedata.normalize('NFD', single_answer) + single_answer = tokenizer.tokenize(single_answer) + single_answer = single_answer.words(uncased=True) + for idx, word in enumerate(single_answer): + if word in num2alpha.keys(): + cnt = 0 + for word_before in single_answer[:idx]: + if word in word_before: + cnt += 1 + pos = 0 + while pos < len(original_answer) - len(word) + 1: + if original_answer[pos:].startswith(word): + if cnt == 0: + res.add(original_answer[:pos] + num2alpha[word] + original_answer[pos+len(word):]) + break + pos += len(word) + cnt -= 1 + else: + pos += 1 + for i in res: + if i.lower() not in [c.lower() for c in copy_answers] and i != "": + copy_answers.append(i) + return copy_answers + +def might_right_answers(answers): + ans = set(answers) + res = set() + for single_answer in answers: + original_answer = single_answer + single_answer = unicodedata.normalize('NFD', single_answer) + single_answer = tokenizer.tokenize(single_answer) + single_answer = single_answer.words(uncased=True) + for idx, word in enumerate(single_answer): + for spand_len in range(1, len(single_answer)): + cand_fake_ans = " ".join(single_answer[:idx] + single_answer[idx + spand_len:]) + if _remove_proj(normalize_answer(cand_fake_ans)).replace(" ","") != "": + res.add(cand_fake_ans) + return list(res - ans) + +def _remove_proj(text): + text = re.sub(r"\b(in|on|at|by|with|for|of|to)\b", " ", text) + return text + +def normalize_answer(s): + def remove_articles(text): + return re.sub(r"\b(a|an|the)\b", " ", text) + + def white_space_fix(text): + return " ".join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return "".join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + +def EM_compute(answer_list, prediction): + return max([int(normalize_answer(prediction) == normalize_answer(ground_truth)) for ground_truth in answer_list]) + +def AC_compute(answer_list, prediction): + pred = normalize_answer(prediction) + for answer in answer_list: + if normalize_answer(answer) in pred: + return 1 + return 0 + + +def F1_compute(answers, pred): + def get_tokens(s): + if not s: return [] + return normalize_answer(s).split() + + def compute_f1(a_gold, a_pred): + gold_toks = get_tokens(a_gold) + pred_toks = get_tokens(a_pred) + common = collections.Counter(gold_toks) & collections.Counter(pred_toks) + num_same = sum(common.values()) + if len(gold_toks) == 0 or len(pred_toks) == 0: + # If either is no-answer, then F1 is 1 if they agree, 0 otherwise + return int(gold_toks == pred_toks) + if num_same == 0: + return 0 + precision = 1.0 * num_same / len(pred_toks) + recall = 1.0 * num_same / len(gold_toks) + f1 = (2 * precision * recall) / (precision + recall) + return f1 + return max([compute_f1(x, pred) for x in answers]) + + +def deal_judge(pred): + if pred is None: + return True + if has_answer(["unknown", "no specific answer", "not provide", "cannot answer", "no information provided", "no answer", "not contain", "no definitive answer"], pred): + return True + return False + + +def deal_answer(pred, answers): + if pred is None: + return 0, 0 + if pred.lower().startswith("answer:"): + pred = pred[7:] + return EM_compute(answers, pred), F1_compute(answers, pred) + + +def deal_post(pred): + giveup, istrue = True, None + if pred is None: + return giveup, istrue + if has_answer(["unclear", "not clear", "unknown", "partially correct", "partially incorrect", "not correct", "cannot determine", "cannot answer", "not incorrect", "incomplete"], pred): + giveup = True + elif has_answer(["correct", "true"], pred): + giveup, istrue = False, True + elif has_answer(["incorrect", "false"], pred): + giveup, istrue = False, False + else: + giveup = True + return giveup, istrue + + +def str2paras(s): + if s is None: + return None + paras = [] + for text in s.split('\n'): + if text.strip() != '': + paras.append(": " + text) + return paras + + +# if __name__ == "__main__": +# file_list = os.listdir('d:/pycharmfiles/chat') + +# for file in file_list: +# if not file.endswith('post'): +# continue +# print(file) +# indir = os.path.join('d:/pycharmfiles/chat', file) +# outdir = os.path.join('d:/pycharmfiles/llm_re/nq/data', file) +# outstr = "" +# infile = open(indir, 'r', encoding='utf-8') +# for line in tqdm(infile.readlines()): +# d = json.loads(line) +# if 'Prediction' in d.keys(): +# d['Giveup'], d['EM'], d['F1'] = deal_answer(d['Prediction'], d['reference']) +# if 'Post' in d.keys(): +# d['Post_Giveup'], d['Post_True']= deal_post(d['Post']) +# outstr += json.dumps(d) + '\n' +# infile.close() +# outfile = open(outdir, 'w', encoding='utf-8') +# outfile.write(outstr) +# outfile.close() + + +def load_source(file): + data = [] + f = open(file, 'r', encoding='utf-8') + for line in f.readlines(): + data.append(json.loads(line)) + f.close() + return data + + +def remove_punctuation(s): + punctuation_pattern = r"^[^\w\s]+|[^\w\s]+$" + return re.sub(punctuation_pattern, '', s) + + +def save_file(args, results, add='res'): + save_dir = os.path.dirname(args.data) + model_base_file = os.path.basename(args.model) + \ + "." + os.path.basename(args.data)[:-len(".json")] + if args.splits: + model_base_file += f".{args.worker}-{args.splits}" + with open(os.path.join(save_dir, f"{model_base_file}.{add}.json"), 'w') as f: + json.dump(results, f, indent=4) diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..faa78f4297f4aad6e5c11df14c265f34a6f70530 --- /dev/null +++ b/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 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea9bb9b95b1a7813082eef8f31ef07d78869ecf769d08852fc77762b4789a509 +size 58610597 diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..e84e69f43e887d64c0fac60daa760c74adef7476 --- /dev/null +++ b/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 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6b59bc3b800fca781eaa5b051e855d7ea98eef6513531ef1a4ac114f0b6ccde +size 48303197 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_12.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_12.json new file mode 100644 index 0000000000000000000000000000000000000000..112b03365061bd46f4082517c63e7debc935afe1 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_12.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00016c066349ac779557dce2f811affb385966566039443567e1dba9cfa96e31 +size 53524353 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_13.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_13.json new file mode 100644 index 0000000000000000000000000000000000000000..90ce9219e46dccabec81462f741b5139237a94ca --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_13.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f4df36885215f33982031e3ced147404b67acfa4c35187ccb5878393cc4c8bb +size 53535044 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_5.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_5.json new file mode 100644 index 0000000000000000000000000000000000000000..b4d0aa6f23530e276035fbbbee4c6a5a25787961 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03e3acbcd2768a6a917cc41453135c3371f73cc5e82e1d13f50357275df2fad0 +size 51836135 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_8.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_8.json new file mode 100644 index 0000000000000000000000000000000000000000..ef4309a95c0128b63269b12599230699bcdabeea --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_8.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:702a316a95c1110d6751304084ae60d7daa85685f21f41e1d8d9385476836d68 +size 53030296 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_9.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_9.json new file mode 100644 index 0000000000000000000000000000000000000000..5247b522f8b13e55e39b684b4bf718a9db2687a7 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_1/turn_9.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9789860766b42d7df26668ad591509ec0c87693dd1e19218ba0b57e5849db69a +size 53349940 diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..6b131e9a0caa94ede62d92b7fd6aebe7fb3b3647 --- /dev/null +++ b/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 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39f9b57cbc763c295a5ee9e0d74329f201b9454f70acc061eacdf874a519fcab +size 92111 diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..8540258aadad5e279878a1e5d25d42ce36559212 --- /dev/null +++ b/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 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2bc8fa3fff50bbda859f92fb3549cbcdddf3a6f4fc3d1bdf6a54a5bb506da4a3 +size 46654148 diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..2d0724d179c3b1bd6d3980fb587093a3a536d104 --- /dev/null +++ b/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 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fe7643246940d81f96907275db2226d84110dc4404d64c2e377c1c82da73741 +size 57535171 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_1.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_1.json new file mode 100644 index 0000000000000000000000000000000000000000..94168d087f556468a93e3162db92e7ff0c8ddfac --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_1.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eea1242e6178bd065573bb79049698c325e2bfd3489c6a62ad6199724e3893fa +size 26189480 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_10.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_10.json new file mode 100644 index 0000000000000000000000000000000000000000..8dfef37450cd8bdb30c3cfe4e51c93e08fd21a6b --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_10.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a6f792220630bfa57ee09c29cd25ddd21c6e84e2ae8371267527ee7bbf15a2ab +size 52392429 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_11.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_11.json new file mode 100644 index 0000000000000000000000000000000000000000..c891937cff5affc34ce15af7cb2881896d7bd85a --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_11.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:092961b6bac1bc37c3ac9bc2e34d9dc37e0c8f33ddedd43ac026a06b2fc9bdc8 +size 52404861 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_12.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_12.json new file mode 100644 index 0000000000000000000000000000000000000000..807538fba4dd6b13966fb4b3b52a3620bacd226c --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_12.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:545fe30bafde365c428fd78bdabba4b3ef9954f1fcd45ebb8912065704e8012d +size 52408109 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_13.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_13.json new file mode 100644 index 0000000000000000000000000000000000000000..da9479535bd2db2fece4b3bfd27d1c925bd784f1 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_13.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12cc63c8631ec41d107fe0e917c51871dbd4042a422f60f7f20d30d56b546eb3 +size 52409856 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_2.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_2.json new file mode 100644 index 0000000000000000000000000000000000000000..e3b2cec4d749e7e8d68b03b3f7c9abb35afa39a8 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_2.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19ad5c54f4ebf19b29ba7652190bb0a6ea499c59cd26def11feec2c1e6721cf9 +size 41086905 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_3.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_3.json new file mode 100644 index 0000000000000000000000000000000000000000..5f007a2a47d51928d6334594f5919aa3fbfe3b28 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c33d8f878be14ab4f56cb00843fc375d1e90531201c01344f411dd8d44108eb2 +size 47724045 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_4.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_4.json new file mode 100644 index 0000000000000000000000000000000000000000..306636926da49f3376d143f561585e4aab170545 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_4.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad762888a9a91519a901b948a09568e2efbdf35c1e5edd06a254a4cdbd9f0953 +size 50242967 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_5.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_5.json new file mode 100644 index 0000000000000000000000000000000000000000..ade9b9db43961003f39b1c42afbde55603f90326 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05a52e4a8f235d94711c320a5393a5e67288f822e73107916af32c35825729c2 +size 51314948 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_6.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_6.json new file mode 100644 index 0000000000000000000000000000000000000000..66e9c594b14d563884d959406d0bb585ecae60cc --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_6.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:887781048d3d8ca08f8a5a014c82b59acfd9649fc0d380baf8ee13d7a40f719f +size 51702810 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_7.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_7.json new file mode 100644 index 0000000000000000000000000000000000000000..c9b8530bad97d3abff810987aee1592f77a3c4f9 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_7.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32e618f6b49d163b9ea79202b5d4dc2569e1674d0c82ca9e7b650e4a0b292f70 +size 52125220 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_8.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_8.json new file mode 100644 index 0000000000000000000000000000000000000000..653181ea5944c516ffd59f41f77d2171d7b711f8 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_8.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5ece68a455d0c162f42926c3ec2e3d4d8c45c7d760f6e31278ca3b71b93210b +size 52264671 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_9.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_9.json new file mode 100644 index 0000000000000000000000000000000000000000..1a8edacdf8542624c9da541e6af1ca0a6c649ec7 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_4/turn_9.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd1b7fc88965d47729ad306a3c21a89911e3209ab80c3ff09a0387841d7c24f7 +size 52355787 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/combined_output_length_distribution.png b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/combined_output_length_distribution.png new file mode 100644 index 0000000000000000000000000000000000000000..3018c9ededff371c4cb13e7c5074fe8cad061a64 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/combined_output_length_distribution.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f310e46eab183b37f9d35d72c3f92cccc873d386c6de2193ef39d6ac6fcf9311 +size 86751 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_11.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_11.json new file mode 100644 index 0000000000000000000000000000000000000000..ba6af45bdc84c4fa235855ea388d186892244b83 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_11.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9b1961942fdb9c136562cb359d325f4cb184fb865d18ddd41563258b97869cf +size 55283029 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_3.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_3.json new file mode 100644 index 0000000000000000000000000000000000000000..e34b4cdb8c9bc48fb4c96e682db204d0b324ca5c --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_3.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55e69859655b7dbcccfd436ed1f1f7fa74b3e9f2ab710c318f4e270c1e2951f1 +size 48757711 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_5.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_5.json new file mode 100644 index 0000000000000000000000000000000000000000..a094023486d44a970741cd61327d9c69c1019bda --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_5.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fdbe665a17c1688280d5248fb7a3815c3a6dfc1bc96d22ba2ea4117d5a4b7fb +size 53070076 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_6.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_6.json new file mode 100644 index 0000000000000000000000000000000000000000..70e5622a437b8b0ccb01fa5537ac6c6da9d0f081 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_6.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f385537caa15c8f488b072a8df0835d4a930ce285ac6533d4f8e13adbdf20e3 +size 53882991 diff --git a/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_7.json b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_7.json new file mode 100644 index 0000000000000000000000000000000000000000..231f6fd5e5216c8f61905f56497a562b66de0d99 --- /dev/null +++ b/deep_search/search_o1/output/output_sum_all_webpage_gen_data/outputs_17w_select_3k_for_dpo_split_4/rollout_8/turn_7.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b53d80013048fbfff805fbbb298e9f79b9f2dde53a69a37db55a13fa3877928a +size 54480583 diff --git a/deep_search/search_o1/sft_data/1.1k_cleaned_data_1097/error_count.json b/deep_search/search_o1/sft_data/1.1k_cleaned_data_1097/error_count.json new file mode 100644 index 0000000000000000000000000000000000000000..4be33d33543d8791711e36603b1619c3f0293c37 --- /dev/null +++ b/deep_search/search_o1/sft_data/1.1k_cleaned_data_1097/error_count.json @@ -0,0 +1,6 @@ +{ + "lang_error": 13, + "words_error": 123, + "boxed_error": 16, + "len_error": 5 +} \ No newline at end of file diff --git a/deep_search/search_o1/sft_data/__pycache__/math_equivalence.cpython-39.pyc b/deep_search/search_o1/sft_data/__pycache__/math_equivalence.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b94901f35abd2bc666dc30634e827cba63d691d7 Binary files /dev/null and b/deep_search/search_o1/sft_data/__pycache__/math_equivalence.cpython-39.pyc differ diff --git a/deep_search/search_o1/sft_data/__pycache__/prompts.cpython-39.pyc b/deep_search/search_o1/sft_data/__pycache__/prompts.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88059d720c18c3714c1970b3af11d557234f4e0c Binary files /dev/null and b/deep_search/search_o1/sft_data/__pycache__/prompts.cpython-39.pyc differ diff --git a/deep_search/search_o1/sft_data/no_error_data_871/error_count.json b/deep_search/search_o1/sft_data/no_error_data_871/error_count.json new file mode 100644 index 0000000000000000000000000000000000000000..9e26dfeeb6e641a33dae4961196235bdb965b21b --- /dev/null +++ b/deep_search/search_o1/sft_data/no_error_data_871/error_count.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/deep_search/search_o1/sft_data/nq_500/add_source.py b/deep_search/search_o1/sft_data/nq_500/add_source.py new file mode 100644 index 0000000000000000000000000000000000000000..c985948fed5bea5e738224c37e0a08fbfdd71895 --- /dev/null +++ b/deep_search/search_o1/sft_data/nq_500/add_source.py @@ -0,0 +1,28 @@ +import json + + +def read_json(file_path): + """从 JSON 文件中读取数据""" + with open(file_path, "r", encoding="utf-8") as f: + data = json.load(f) + print(f"load from {file_path}, total item: {len(data)}") + return data + +def write_json(data, file_path): + """将数据写入 JSON 文件""" + with open(file_path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=4) + print(f"save to {file_path}, total item: {len(data)}") + + + +input_file = "/share/project/sunshuang/deep_search/search_o1/sft_data/nq_500/new_instruction_237.json" +output_file = "/share/project/sunshuang/deep_search/search_o1/sft_data/nq_500/nq_237.json" + +data = read_json(input_file) + +for item in data: + item["source"] = "nq" + + +write_json(data, output_file) \ No newline at end of file