diff --git a/.gitattributes b/.gitattributes index bed0738c7eeb449bca98b5d2f33c89a1ee56349a..129dcbb7664fe9020b3b1a01e9ee182e078b408c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text # Video files - compressed *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text +data/surgicalthinker_rl.json filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 7b95401dc46245ac339fc25059d4a56d90b4cde5..604b81b860a96f7e2103ba267a21288de3d28c17 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ ---- -license: apache-2.0 ---- +将data/下的文件放在之前data/Medical下 + +将model/下的EasyR1替换原来的project/OneThinker/EasyR1 + +bash env.sh 安装环境 \ No newline at end of file diff --git a/data/surgicalthinker_rl.json b/data/surgicalthinker_rl.json new file mode 100644 index 0000000000000000000000000000000000000000..890d4cdf5fa2d190589d08175ead55cd7ebd37ac --- /dev/null +++ b/data/surgicalthinker_rl.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d84c106ab9ae519a94d59ef4efdc5c8844f631a800ff3567245490f54671c9f3 +size 259793690 diff --git a/env.sh b/env.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed019e680843a708fdc30e9d0c45d3889a6270f3 --- /dev/null +++ b/env.sh @@ -0,0 +1,12 @@ +cd ../OneThinker/EasyR1 + +conda create -n easyr1 python=3.11 +conda activate easyr1 +cd EasyR1 +pip install torch==2.8.0 +pip install torchvision==0.23.0 +pip install transformers==4.57.6 +pip install vllm==0.11.0 +pip install qwen_vl_utils==0.0.14 +pip install flash-attn==2.8.3 --no-build-isolation --no-cache-dir +pip install -e . \ No newline at end of file diff --git a/model/EasyR1/.github/CODE_OF_CONDUCT.md b/model/EasyR1/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..c2035cea5425b8de8e88a563214d05dfd415352a --- /dev/null +++ b/model/EasyR1/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +`hoshihiyouga AT gmail DOT com`. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/model/EasyR1/.github/CONTRIBUTING.md b/model/EasyR1/.github/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..75dd70981d538ab46076e180fee68d4dc0cd0d13 --- /dev/null +++ b/model/EasyR1/.github/CONTRIBUTING.md @@ -0,0 +1,64 @@ +# Contributing to EasyR1 + +Everyone is welcome to contribute, and we value everybody's contribution. Code contributions are not the only way to help the community. Answering questions, helping others, and improving the documentation are also immensely valuable. + +It also helps us if you spread the word! Reference the library in blog posts about the awesome projects it made possible, shout out on Twitter every time it has helped you, or simply ⭐️ the repository to say thank you. + +However you choose to contribute, please be mindful and respect our [code of conduct](CODE_OF_CONDUCT.md). + +**This guide was heavily inspired by [transformers guide to contributing](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md).** + +## Ways to contribute + +There are several ways you can contribute to EasyR1: + +* Fix outstanding issues with the existing code. +* Submit issues related to bugs or desired new features. +* Contribute to the examples or to the documentation. + +### Style guide + +EasyR1 follows the [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html), check it for details. + +### Create a Pull Request + +1. Fork the [repository](https://github.com/hiyouga/EasyR1) by clicking on the [Fork](https://github.com/hiyouga/EasyR1/fork) button on the repository's page. This creates a copy of the code under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote: + +```bash +git clone git@github.com:[username]/EasyR1.git +cd EasyR1 +git remote add upstream https://github.com/hiyouga/EasyR1.git +``` + +3. Create a new branch to hold your development changes: + +```bash +git checkout -b dev_your_branch +``` + +4. Set up a development environment by running the following command in a virtual environment: + +```bash +pip install -e ".[dev]" +``` + +5. Check code before commit: + +```bash +make commit +make style && make quality +``` + +6. Submit changes: + +```bash +git add . +git commit -m "commit message" +git fetch upstream +git rebase upstream/main +git push -u origin dev_your_branch +``` + +7. Create a merge request from your branch `dev_your_branch` at [origin repo](https://github.com/hiyouga/EasyR1). diff --git a/model/EasyR1/.github/requirements-test.txt b/model/EasyR1/.github/requirements-test.txt new file mode 100644 index 0000000000000000000000000000000000000000..81c6ce493d4326b4bc705752876fd614a5f581f3 --- /dev/null +++ b/model/EasyR1/.github/requirements-test.txt @@ -0,0 +1,11 @@ +codetiming +datasets +pillow +pytest +qwen-vl-utils +ray[default] +ruff +tensordict +torch +torchvision +transformers>=4.54.0,<=4.57.0 diff --git a/model/EasyR1/.github/workflows/tests.yml b/model/EasyR1/.github/workflows/tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..2e69701a392842571df6d62a2dc36923d951b40b --- /dev/null +++ b/model/EasyR1/.github/workflows/tests.yml @@ -0,0 +1,64 @@ +name: tests + +on: + workflow_dispatch: + push: + branches: + - "main" + paths: + - "**/*.py" + - "**/requirements*.txt" + - ".github/workflows/*.yml" + pull_request: + branches: + - "main" + paths: + - "**/*.py" + - "**/requirements*.txt" + - ".github/workflows/*.yml" + +jobs: + tests: + strategy: + fail-fast: false + matrix: + python-version: + - "3.11" + os: + - "ubuntu-latest" + + runs-on: ${{ matrix.os }} + + concurrency: + group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.os }}-${{ matrix.python-version }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: "pip" + cache-dependency-path: "**/requirements*.txt" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu + python -m pip install -r .github/requirements-test.txt + python -m pip install --no-deps . + + - name: Check quality + run: | + make style && make quality + + - name: Check license + run: | + make license + + - name: Test with pytest + run: | + make test diff --git a/model/EasyR1/.pre-commit-config.yaml b/model/EasyR1/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d91faaf4d2ba7969d63ff9a40050b6c6fd34c23c --- /dev/null +++ b/model/EasyR1/.pre-commit-config.yaml @@ -0,0 +1,22 @@ +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: check-ast + - id: check-added-large-files + args: ['--maxkb=25000'] + - id: check-merge-conflict + - id: check-yaml + - id: debug-statements + - id: end-of-file-fixer + - id: requirements-txt-fixer + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + - id: no-commit-to-branch + args: ['--branch', 'main'] + +- repo: https://github.com/asottile/pyupgrade + rev: v3.17.0 + hooks: + - id: pyupgrade + args: [--py38-plus] diff --git a/model/EasyR1/Dockerfile b/model/EasyR1/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b01c4bd44302748c71b697dc497a122b948c032b --- /dev/null +++ b/model/EasyR1/Dockerfile @@ -0,0 +1,68 @@ +# Start from the NVIDIA official image (ubuntu-24.04 + cuda-12.9 + python-3.12) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-25-05.html +FROM nvcr.io/nvidia/pytorch:25.05-py3 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + transformer-engine flash-attn apex megatron-core \ + xgboost opencv grpcio + +# Remove nv file +RUN rm -rf /workspace + +# Fix cv2 +RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2 + +# Install torch-2.8.0+cu128 + vllm-0.11.0 +RUN pip install --no-cache-dir "vllm==0.11.0" "torch==2.8.0" "torchvision==0.23.0" "torchaudio==2.8.0" tensordict torchdata \ + "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=15.0.0" "grpcio>=1.62.1" "optree>=0.13.0" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb liger-kernel mathruler \ + pytest yapf py-spy pre-commit ruff + +# Install flash-attn-2.8.3 +RUN ABI_FLAG=$(python -c "import torch; print('TRUE' if torch._C._GLIBCXX_USE_CXX11_ABI else 'FALSE')") && \ + URL="https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.3/flash_attn-2.8.3+cu12torch2.8cxx11abi${ABI_FLAG}-cp312-cp312-linux_x86_64.whl" && \ + wget -nv -P /opt/tiger "${URL}" && \ + pip install --no-cache-dir "/opt/tiger/$(basename ${URL})" + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url diff --git a/model/EasyR1/Dockerfile.legacy b/model/EasyR1/Dockerfile.legacy new file mode 100644 index 0000000000000000000000000000000000000000..13ee6eee8a5065f7a374df8acdff23fd3db338ed --- /dev/null +++ b/model/EasyR1/Dockerfile.legacy @@ -0,0 +1,68 @@ +# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + transformer-engine flash-attn apex megatron-core \ + xgboost opencv grpcio + +# Remove nv file +RUN rm -rf /workspace + +# Fix cv2 +RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2 + +# Install torch-2.7.1+cu126 + vllm-0.10.0 +RUN pip install --no-cache-dir "vllm==0.10.0" "torch==2.7.1" "torchvision==0.22.1" "torchaudio==2.7.1" tensordict torchdata \ + "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=15.0.0" "grpcio>=1.62.1" "optree>=0.13.0" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb liger-kernel mathruler \ + pytest yapf py-spy pyext pre-commit ruff + +# Install flash-attn-2.8.2 +RUN ABI_FLAG=$(python -c "import torch; print('TRUE' if torch._C._GLIBCXX_USE_CXX11_ABI else 'FALSE')") && \ + URL="https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.2/flash_attn-2.8.2+cu12torch2.7cxx11abi${ABI_FLAG}-cp310-cp310-linux_x86_64.whl" && \ + wget -nv -P /opt/tiger "${URL}" && \ + pip install --no-cache-dir "/opt/tiger/$(basename ${URL})" + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url diff --git a/model/EasyR1/LICENSE b/model/EasyR1/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/model/EasyR1/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/model/EasyR1/Makefile b/model/EasyR1/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..ee0caff325f202b5509919f907bcc9bd4bfcd2b9 --- /dev/null +++ b/model/EasyR1/Makefile @@ -0,0 +1,24 @@ +.PHONY: build commit license quality style test + +check_dirs := examples scripts tests verl setup.py + +build: + python3 setup.py sdist bdist_wheel + +commit: + pre-commit install + pre-commit run --all-files + +license: + python3 tests/check_license.py $(check_dirs) + +quality: + ruff check $(check_dirs) + ruff format --check $(check_dirs) + +style: + ruff check $(check_dirs) --fix + ruff format $(check_dirs) + +test: + pytest -vv tests/ diff --git a/model/EasyR1/README.md b/model/EasyR1/README.md new file mode 100644 index 0000000000000000000000000000000000000000..00942726c2684f8b2f8d98f9c534e3161293169c --- /dev/null +++ b/model/EasyR1/README.md @@ -0,0 +1,236 @@ +# EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework + +[![GitHub Repo stars](https://img.shields.io/github/stars/hiyouga/EasyR1)](https://github.com/hiyouga/EasyR1/stargazers) +[![Twitter](https://img.shields.io/twitter/follow/llamafactory_ai)](https://twitter.com/llamafactory_ai) +[![Docker Pulls](https://img.shields.io/docker/pulls/hiyouga/verl)](https://hub.docker.com/r/hiyouga/verl/tags) + +### Used by [Amazon Web Services](https://aws.amazon.com/cn/blogs/china/building-llm-model-hub-based-on-llamafactory-and-easyr1/) + +This project is a clean fork of the original [veRL](https://github.com/volcengine/verl) project to support vision language models, we thank all the authors for providing such a high-performance RL training framework. + +EasyR1 is efficient and scalable due to the design of **[HybirdEngine](https://arxiv.org/abs/2409.19256)** and the latest release of **[vLLM](https://github.com/vllm-project/vllm)**'s SPMD mode. + +## Features + +- Supported models + - Llama3/Qwen2/Qwen2.5/Qwen3 language models + - Qwen2-VL/Qwen2.5-VL/Qwen3-VL vision language models + - DeepSeek-R1 distill models + +- Supported algorithms + - GRPO + - DAPO + - Reinforce++ + - ReMax + - RLOO + +- Supported datasets + - Any text, vision-text dataset in a [specific format](#custom-dataset) + +- Supported tricks + - Padding-free training + - Resuming from the latest/best checkpoint + - Wandb & SwanLab & Mlflow & Tensorboard tracking + +## Requirements + +### Software Requirements + +- Python 3.9+ +- transformers>=4.54.0 +- flash-attn>=2.4.3 +- vllm>=0.8.3 + +We provide a [Dockerfile](./Dockerfile) to easily build environments. + +We recommend using the [pre-built docker image](https://hub.docker.com/r/hiyouga/verl) in EasyR1. + +```bash +docker pull hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0 +docker run -it --ipc=host --gpus=all hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0 +``` + +If your environment does not support Docker, you can consider using **Apptainer**: + +```bash +apptainer pull easyr1.sif docker://hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0 +apptainer shell --nv --cleanenv --bind /mnt/your_dir:/mnt/your_dir easyr1.sif +``` + +Use `USE_MODELSCOPE_HUB=1` to download models from the ModelScope hub. + +### Hardware Requirements + +\* *estimated* + +| Method | Bits | 1.5B | 3B | 7B | 32B | 72B | +| ------------------------ | ---- | ------ | ------ | ------ | ------- | ------- | +| GRPO Full Fine-Tuning | AMP | 2*24GB | 4*40GB | 8*40GB | 16*80GB | 32*80GB | +| GRPO Full Fine-Tuning | BF16 | 1*24GB | 1*40GB | 4*40GB | 8*80GB | 16*80GB | + +> [!NOTE] +> Use `worker.actor.fsdp.torch_dtype=bf16` and `worker.actor.optim.strategy=adamw_bf16` to enable bf16 training. +> +> We are working hard to reduce the VRAM in RL training, LoRA support will be integrated in next updates. + +## Tutorial: Run Qwen2.5-VL GRPO on [Geometry3K](https://huggingface.co/datasets/hiyouga/geometry3k) Dataset in Just 3 Steps + +![image](assets/qwen2_5_vl_7b_geo.png) + +### Installation + +```bash +git clone https://github.com/hiyouga/EasyR1.git +cd EasyR1 +pip install -e . +``` + +### GRPO Training + +```bash +bash examples/qwen2_5_vl_7b_geo3k_grpo.sh +``` + +### Merge Checkpoint in Hugging Face Format + +```bash +python3 scripts/model_merger.py --local_dir checkpoints/easy_r1/exp_name/global_step_1/actor +``` + +> [!TIP] +> If you encounter issues with connecting to Hugging Face, consider using `export HF_ENDPOINT=https://hf-mirror.com`. +> +> If you want to use SwanLab logger, consider using `bash examples/qwen2_5_vl_7b_geo3k_swanlab.sh`. + +## Custom Dataset + +Please refer to the example datasets to prepare your own dataset. + +- Text dataset: https://huggingface.co/datasets/hiyouga/math12k +- Image-text dataset: https://huggingface.co/datasets/hiyouga/geometry3k +- Multi-image-text dataset: https://huggingface.co/datasets/hiyouga/journeybench-multi-image-vqa +- Text-image mixed dataset: https://huggingface.co/datasets/hiyouga/rl-mixed-dataset + +## How to Understand GRPO in EasyR1 + +![image](assets/easyr1_grpo.png) + +- To learn about the GRPO algorithm, you can refer to [Hugging Face's blog](https://huggingface.co/docs/trl/v0.16.1/en/grpo_trainer). + +## How to Run 70B+ Model in Multi-node Environment + +1. Start the Ray head node. + +```bash +ray start --head --port=6379 --dashboard-host=0.0.0.0 +``` + +2. Start the Ray worker node and connect to the head node. + +```bash +ray start --address=:6379 +``` + +3. Check the Ray resource pool. + +```bash +ray status +``` + +4. Run training script on the Ray head node only. + +```bash +bash examples/qwen2_5_vl_7b_geo3k_grpo.sh +``` + +See the **[veRL's official doc](https://verl.readthedocs.io/en/latest/start/multinode.html)** for more details about multi-node training and Ray debugger. + +## Other Baselines + +We also reproduced the following two baselines of the [R1-V](https://github.com/deep-agent/R1-V) project. +- [CLEVR-70k-Counting](examples/baselines/qwen2_5_vl_3b_clevr.sh): Train the Qwen2.5-VL-3B-Instruct model on counting problem. +- [GeoQA-8k](examples/baselines/qwen2_5_vl_3b_geoqa8k.sh): Train the Qwen2.5-VL-3B-Instruct model on GeoQA problem. + +## Performance Baselines + +See [baselines.md](assets/baselines.md). + +## Awesome Work using EasyR1 + +- **MMR1**: Enhancing Multimodal Reasoning with Variance-Aware Sampling and Open Resources. [![[code]](https://img.shields.io/github/stars/LengSicong/MMR1)](https://github.com/LengSicong/MMR1) [![[arxiv]](https://img.shields.io/badge/arxiv-2509.21268-blue)](https://arxiv.org/abs/2509.21268) +- **Vision-R1**: Incentivizing Reasoning Capability in Multimodal Large Language Models. [![[code]](https://img.shields.io/github/stars/Osilly/Vision-R1)](https://github.com/Osilly/Vision-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.06749-blue)](https://arxiv.org/abs/2503.06749) +- **Seg-Zero**: Reasoning-Chain Guided Segmentation via Cognitive Reinforcement. [![[code]](https://img.shields.io/github/stars/dvlab-research/Seg-Zero)](https://github.com/dvlab-research/Seg-Zero) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.06520-blue)](https://arxiv.org/abs/2503.06520) +- **MetaSpatial**: Reinforcing 3D Spatial Reasoning in VLMs for the Metaverse. [![[code]](https://img.shields.io/github/stars/PzySeere/MetaSpatial)](https://github.com/PzySeere/MetaSpatial) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.18470-blue)](https://arxiv.org/abs/2503.18470) +- **Temporal-R1**: Envolving Temporal Reasoning Capability into LMMs via Temporal Consistent Reward. [![[code]](https://img.shields.io/github/stars/appletea233/Temporal-R1)](https://github.com/appletea233/Temporal-R1) +- **NoisyRollout**: Reinforcing Visual Reasoning with Data Augmentation. [![[code]](https://img.shields.io/github/stars/John-AI-Lab/NoisyRollout)](https://github.com/John-AI-Lab/NoisyRollout) [![[arxiv]](https://img.shields.io/badge/arxiv-2504.13055-blue)](https://arxiv.org/pdf/2504.13055) +- **GUI-R1**: A Generalist R1-Style Vision-Language Action Model For GUI Agents. [![[code]](https://img.shields.io/github/stars/ritzz-ai/GUI-R1)](https://github.com/ritzz-ai/GUI-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2504.10458-blue)](https://arxiv.org/abs/2504.10458) +- **R1-Track**: Direct Application of MLLMs to Visual Object Tracking via Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/Wangbiao2/R1-Track)](https://github.com/Wangbiao2/R1-Track) +- **VisionReasoner**: Unified Visual Perception and Reasoning via Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/dvlab-research/VisionReasoner)](https://github.com/dvlab-research/VisionReasoner) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.12081-blue)](https://arxiv.org/abs/2505.12081) +- **MM-UPT**: Unsupervised Post-Training for Multi-Modal LLM Reasoning via GRPO. [![[code]](https://img.shields.io/github/stars/waltonfuture/MM-UPT)](https://github.com/waltonfuture/MM-UPT) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22453-blue)](https://arxiv.org/pdf/2505.22453) +- **RL-with-Cold-Start**: Advancing Multimodal Reasoning via Reinforcement Learning with Cold Start. [![[code]](https://img.shields.io/github/stars/waltonfuture/RL-with-Cold-Start)](https://github.com/waltonfuture/RL-with-Cold-Start) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22334-blue)](https://arxiv.org/pdf/2505.22334) +- **ViGoRL**: Grounded Reinforcement Learning for Visual Reasoning. [![[code]](https://img.shields.io/github/stars/Gabesarch/grounded-rl)](https://github.com/Gabesarch/grounded-rl) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22334-blue)](https://arxiv.org/abs/2505.23678) +- **Revisual-R1**: Advancing Multimodal Reasoning: From Optimized Cold Start to Staged Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/CSfufu/Revisual-R1)](https://github.com/CSfufu/Revisual-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2506.04207-blue)](https://arxiv.org/abs/2506.04207) +- **SophiaVL-R1**: Reinforcing MLLMs Reasoning with Thinking Reward. [![[code]](https://img.shields.io/github/stars/kxfan2002/SophiaVL-R1)](https://github.com/kxfan2002/SophiaVL-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.17018-blue)](https://arxiv.org/abs/2505.17018) +- **Vision-Matters**: Simple Visual Perturbations Can Boost Multimodal Math Reasoning. [![[code]](https://img.shields.io/github/stars/YutingLi0606/Vision-Matters)](https://github.com/YutingLi0606/Vision-Matters) [![[arxiv]](https://img.shields.io/badge/arxiv-2506.09736-blue)](https://arxiv.org/abs/2506.09736) +- **VTool-R1**: VLMs Learn to Think with Images via Reinforcement Learning on Multimodal Tool Use. [![[code]](https://img.shields.io/github/stars/VTOOL-R1/vtool-r1)](https://github.com/VTOOL-R1/vtool-r1) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.19255-blue)](https://arxiv.org/abs/2505.19255) +- **Long-RL**: Scaling RL to Long Sequences. [![[code]](https://img.shields.io/github/stars/NVlabs/Long-RL)](https://github.com/NVlabs/Long-RL) [![[arxiv]](https://img.shields.io/badge/arxiv-2507.07966-blue)](https://arxiv.org/abs/2507.07966) +- **EditGRPO**: Reinforcement Learning with Post-Rollout Edits for Clinically Accurate Chest X-Ray Report Generation. [![[code]](https://img.shields.io/github/stars/taokz/EditGRPO)](https://github.com/taokz/EditGRPO) + +## TODO + +- Support LoRA (high priority). +- Support ulysses parallelism for VLMs (middle priority). +- Support more VLM architectures. + +> [!NOTE] +> We will not provide scripts for supervised fine-tuning and inference in this project. If you have such requirements, we recommend using [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory). + +### Known bugs + +These features are temporarily disabled for now, we plan to fix them one-by-one in the future updates. + +- Vision language models are not compatible with ulysses parallelism yet. + +## Discussion Group + +👋 Join our [WeChat group](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/easyr1.jpg). + +## FAQs + +> ValueError: Image features and image tokens do not match: tokens: 8192, features 9800 + +Increase the `data.max_prompt_length` or reduce the `data.max_pixels`. + +> RuntimeError: CUDA Error: out of memory at /workspace/csrc/cumem_allocator.cpp:62 + +Reduce the `worker.rollout.gpu_memory_utilization` and enable `worker.actor.offload.offload_params`. + +> RuntimeError: 0 active drivers ([]). There should only be one. + +Uninstall `deepspeed` from the current python environment. + +## Citation + +Core contributors: [Yaowei Zheng](https://github.com/hiyouga), [Junting Lu](https://github.com/AL-377), [Shenzhi Wang](https://github.com/Shenzhi-Wang), [Zhangchi Feng](https://github.com/BUAADreamer), [Dongdong Kuang](https://github.com/Kuangdd01) and Yuwen Xiong + +We also thank Guangming Sheng and Chi Zhang for helpful discussions. + +```bibtex +@misc{zheng2025easyr1, + title = {EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework}, + author = {Yaowei Zheng, Junting Lu, Shenzhi Wang, Zhangchi Feng, Dongdong Kuang, Yuwen Xiong}, + howpublished = {\url{https://github.com/hiyouga/EasyR1}}, + year = {2025} +} +``` + +We recommend to also cite the original work. + +```bibtex +@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} +} +``` diff --git a/model/EasyR1/assets/baselines.md b/model/EasyR1/assets/baselines.md new file mode 100644 index 0000000000000000000000000000000000000000..d29cc6fa83085673f15325972b26df5c47f2f7a7 --- /dev/null +++ b/model/EasyR1/assets/baselines.md @@ -0,0 +1,51 @@ +# Baselines + +Environment: [hiyouga/verl:ngc-th2.7.1-cu12.6-vllm0.10.0](https://hub.docker.com/layers/hiyouga/verl/ngc-th2.7.1-cu12.6-vllm0.10.0/images/sha256-cfc8c1ce3ea52dee0444f3e58e900d0b1d3b6b315deaf5f58c44b5fbb52fa989) + +EasyR1 version: [v0.3.2](https://github.com/hiyouga/EasyR1/tree/v0.3.2) + +Welcome to contribute new data points! + +## Algorithm Baselines + +### [Qwen2.5-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct) on [Math12k](https://huggingface.co/datasets/hiyouga/math12k) + +| Size | Algorithm | Bits | LR | KL | Test Accuracy | +| ---- | ----------- | ---- | ---- | ---- | -------------------- | +| 7B | GRPO | AMP | 1e-6 | 1e-2 | 0.75 -> 0.77 (+0.02) | + +### [Qwen2.5-VL-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k) + +| Size | Algorithm | Bits | LR | KL | Test Accuracy | +| ---- | ----------- | ---- | ---- | ---- | -------------------- | +| 7B | GRPO | AMP | 1e-6 | 1e-2 | 0.37 -> 0.48 (+0.11) | +| 7B | GRPO | BF16 | 1e-6 | 1e-2 | 0.37 -> 0.48 (+0.11) | +| 7B | DAPO | AMP | 1e-6 | 1e-2 | 0.37 -> 0.50 (+0.13) | +| 3B | GRPO | AMP | 1e-6 | 1e-2 | 0.24 -> 0.38 (+0.14) | +| 32B | GRPO | BF16 | 1e-6 | 1e-2 | 0.50 -> 0.56 (+0.06) | + +> [!NOTE] +> The hyper-parameters not listed are all the same as the default values. + +## Performance Baselines + +### [Qwen2.5-VL-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k) + +| Size | GPU Type | Bits | Batch Size | vLLM TP | Peak Mem | Peak VRAM | Throughput | Sec per step | Actor MFU | +| ---- | ------------- | ---- | ---------- | ------- | -------- | --------- | ----------- | ------------ | --------- | +| 3B | 8 * H100 80GB | AMP | 1 / 2 | 2 | 120GB | 54GB | 1800 (+600) | 120s | 8.1% | +| 7B | 8 * H100 80GB | AMP | 1 / 2 | 2 | 120GB | 68GB | 1600 (+400) | 145s | 16.0% | +| 7B | 8 * H100 80GB | AMP | 4 / 8 | 2 | 200GB | 72GB | 2000 (+600) | 120s | 23.2% | +| 7B | 8 * L20 48GB | AMP | 1 / 2 | 2 | 120GB | 42GB | 410 (+0) | 580s | 26.5% | +| 7B | 8 * H100 80GB | BF16 | 1 / 2 | 2 | 120GB | 58GB | 1600 (+320) | 145s | 16.0% | +| 32B | 8 * H100 80GB | BF16 | 1 / 2 | 8 | 260GB | 72GB | 620 (+260) | 530s | 25.8% | + +- Batch Size: micro_batch_size_per_device_for_update / micro_batch_size_per_device_for_experience +- vLLM TP: rollout.tensor_parallel_size +- Peak Mem: Peak CPU memory usage +- Peak VRAM: Peak GPU memory usage +- Throughput: Number of tokens per second per GPU by one training step (including the improvement compared to the [previous version](https://github.com/hiyouga/EasyR1/blob/v0.3.1/assets/baselines.md)) +- Sec per step: Average time per step in seconds + +> [!NOTE] +> The hyper-parameters not listed are all the same as the default values. diff --git a/model/EasyR1/assets/easyr1_grpo.png b/model/EasyR1/assets/easyr1_grpo.png new file mode 100644 index 0000000000000000000000000000000000000000..cb943752cc91d5c8468d08f03837bd3a61290c77 --- /dev/null +++ b/model/EasyR1/assets/easyr1_grpo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abea6d96166d713ef03e1b0c4e6cbfcec65a83869dd31d9de41c3a887d04fa9a +size 865502 diff --git a/model/EasyR1/assets/qwen2_5_vl_7b_geo.png b/model/EasyR1/assets/qwen2_5_vl_7b_geo.png new file mode 100644 index 0000000000000000000000000000000000000000..2a72a5b7444ad64a9dc717e074839d60941b81d1 --- /dev/null +++ b/model/EasyR1/assets/qwen2_5_vl_7b_geo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f54564a9bbe374df9c94cf6d0ed6a0ec575f5983caa77372008f43b856a8c1f0 +size 106090 diff --git a/model/EasyR1/examples/README.md b/model/EasyR1/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1ae559c2eed0e74bdb9adcc555ea99ee896349b8 --- /dev/null +++ b/model/EasyR1/examples/README.md @@ -0,0 +1,190 @@ +--- +license: apache-2.0 +pipeline_tag: image-text-to-text +--- + + Chat + + + +# Qwen3-VL-4B-Instruct + + +Meet Qwen3-VL — the most powerful vision-language model in the Qwen series to date. + +This generation delivers comprehensive upgrades across the board: superior text understanding & generation, deeper visual perception & reasoning, extended context length, enhanced spatial and video dynamics comprehension, and stronger agent interaction capabilities. + +Available in Dense and MoE architectures that scale from edge to cloud, with Instruct and reasoning‑enhanced Thinking editions for flexible, on‑demand deployment. + + +#### Key Enhancements: + +* **Visual Agent**: Operates PC/mobile GUIs—recognizes elements, understands functions, invokes tools, completes tasks. + +* **Visual Coding Boost**: Generates Draw.io/HTML/CSS/JS from images/videos. + +* **Advanced Spatial Perception**: Judges object positions, viewpoints, and occlusions; provides stronger 2D grounding and enables 3D grounding for spatial reasoning and embodied AI. + +* **Long Context & Video Understanding**: Native 256K context, expandable to 1M; handles books and hours-long video with full recall and second-level indexing. + +* **Enhanced Multimodal Reasoning**: Excels in STEM/Math—causal analysis and logical, evidence-based answers. + +* **Upgraded Visual Recognition**: Broader, higher-quality pretraining is able to “recognize everything”—celebrities, anime, products, landmarks, flora/fauna, etc. + +* **Expanded OCR**: Supports 32 languages (up from 19); robust in low light, blur, and tilt; better with rare/ancient characters and jargon; improved long-document structure parsing. + +* **Text Understanding on par with pure LLMs**: Seamless text–vision fusion for lossless, unified comprehension. + + +#### Model Architecture Updates: + +

+ +

+ + +1. **Interleaved-MRoPE**: Full‑frequency allocation over time, width, and height via robust positional embeddings, enhancing long‑horizon video reasoning. + +2. **DeepStack**: Fuses multi‑level ViT features to capture fine‑grained details and sharpen image–text alignment. + +3. **Text–Timestamp Alignment:** Moves beyond T‑RoPE to precise, timestamp‑grounded event localization for stronger video temporal modeling. + +This is the weight repository for Qwen3-VL-4B-Instruct. + + +--- + +## Model Performance + +**Multimodal performance** + +![](https://qianwen-res.oss-accelerate.aliyuncs.com/Qwen3-VL/qwen3vl_4b_8b_vl_instruct.jpg) + +**Pure text performance** +![](https://qianwen-res.oss-accelerate.aliyuncs.com/Qwen3-VL/qwen3vl_4b_8b_text_instruct.jpg) + +## Quickstart + +Below, we provide simple examples to show how to use Qwen3-VL with 🤖 ModelScope and 🤗 Transformers. + +The code of Qwen3-VL has been in the latest Hugging Face transformers and we advise you to build from source with command: +``` +pip install git+https://github.com/huggingface/transformers +# pip install transformers==4.57.0 # currently, V4.57.0 is not released +``` + +### Using 🤗 Transformers to Chat + +Here we show a code snippet to show how to use the chat model with `transformers`: + +```python +from transformers import Qwen3VLForConditionalGeneration, AutoProcessor + +# default: Load the model on the available device(s) +model = Qwen3VLForConditionalGeneration.from_pretrained( + "Qwen/Qwen3-VL-4B-Instruct", dtype="auto", device_map="auto" +) + +# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios. +# model = Qwen3VLForConditionalGeneration.from_pretrained( +# "Qwen/Qwen3-VL-4B-Instruct", +# dtype=torch.bfloat16, +# attn_implementation="flash_attention_2", +# device_map="auto", +# ) + +processor = AutoProcessor.from_pretrained("Qwen/Qwen/Qwen3-VL-4B-Instruct") + +messages = [ + { + "role": "user", + "content": [ + { + "type": "image", + "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg", + }, + {"type": "text", "text": "Describe this image."}, + ], + } +] + +# Preparation for inference +inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + return_dict=True, + return_tensors="pt" +) + +# Inference: Generation of the output +generated_ids = model.generate(**inputs, max_new_tokens=128) +generated_ids_trimmed = [ + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) +] +output_text = processor.batch_decode( + generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False +) +print(output_text) +``` + +### Generation Hyperparameters +#### VL +```bash +export greedy='false' +export top_p=0.8 +export top_k=20 +export temperature=0.7 +export repetition_penalty=1.0 +export presence_penalty=1.5 +export out_seq_length=16384 +``` + +#### Text +```bash +export greedy='false' +export top_p=1.0 +export top_k=40 +export repetition_penalty=1.0 +export presence_penalty=2.0 +export temperature=1.0 +export out_seq_length=32768 +``` + + +## Citation + +If you find our work helpful, feel free to give us a cite. + +``` +@misc{qwen3technicalreport, + title={Qwen3 Technical Report}, + author={Qwen Team}, + year={2025}, + eprint={2505.09388}, + archivePrefix={arXiv}, + primaryClass={cs.CL}, + url={https://arxiv.org/abs/2505.09388}, +} + +@article{Qwen2.5-VL, + title={Qwen2.5-VL Technical Report}, + author={Bai, Shuai and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Song, Sibo and Dang, Kai and Wang, Peng and Wang, Shijie and Tang, Jun and Zhong, Humen and Zhu, Yuanzhi and Yang, Mingkun and Li, Zhaohai and Wan, Jianqiang and Wang, Pengfei and Ding, Wei and Fu, Zheren and Xu, Yiheng and Ye, Jiabo and Zhang, Xi and Xie, Tianbao and Cheng, Zesen and Zhang, Hang and Yang, Zhibo and Xu, Haiyang and Lin, Junyang}, + journal={arXiv preprint arXiv:2502.13923}, + year={2025} +} + +@article{Qwen2VL, + title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution}, + author={Wang, Peng and Bai, Shuai and Tan, Sinan and Wang, Shijie and Fan, Zhihao and Bai, Jinze and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Fan, Yang and Dang, Kai and Du, Mengfei and Ren, Xuancheng and Men, Rui and Liu, Dayiheng and Zhou, Chang and Zhou, Jingren and Lin, Junyang}, + journal={arXiv preprint arXiv:2409.12191}, + year={2024} +} + +@article{Qwen-VL, + title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond}, + author={Bai, Jinze and Bai, Shuai and Yang, Shusheng and Wang, Shijie and Tan, Sinan and Wang, Peng and Lin, Junyang and Zhou, Chang and Zhou, Jingren}, + journal={arXiv preprint arXiv:2308.12966}, + year={2023} +} +``` \ No newline at end of file diff --git a/model/EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh b/model/EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh new file mode 100644 index 0000000000000000000000000000000000000000..36d77b0c010d15254449c48601fad73bf58dce97 --- /dev/null +++ b/model/EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +set -x + +export PYTHONUNBUFFERED=1 + +MODEL_PATH=Qwen/Qwen2.5-VL-3B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=BUAADreamer/clevr_count_70k@train \ + data.val_files=BUAADreamer/clevr_count_70k@test \ + data.format_prompt=./examples/format_prompt/r1v.jinja \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.rollout.tensor_parallel_size=1 \ + worker.reward.reward_type=sequential \ + worker.reward.reward_function=./examples/reward_function/r1v.py:compute_score \ + trainer.experiment_name=qwen2_5_vl_3b_clevr \ + trainer.n_gpus_per_node=2 diff --git a/model/EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh b/model/EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..6f38ae2fd98ff6ac65b53c45c30596ce805ee4f2 --- /dev/null +++ b/model/EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +set -x + +export PYTHONUNBUFFERED=1 + +MODEL_PATH=Qwen/Qwen2.5-VL-3B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=leonardPKU/GEOQA_8K_R1V@train \ + data.val_files=leonardPKU/GEOQA_8K_R1V@test \ + data.format_prompt=./examples/format_prompt/r1v.jinja \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.rollout.tensor_parallel_size=1 \ + worker.reward.reward_type=sequential \ + worker.reward.reward_function=./examples/reward_function/r1v.py:compute_score \ + trainer.experiment_name=qwen2_5_vl_3b_geoqa8k \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/config_d_grpo.yaml b/model/EasyR1/examples/config_d_grpo.yaml new file mode 100644 index 0000000000000000000000000000000000000000..81b95933fa748b0e1189f884ea9ff9c430e7c517 --- /dev/null +++ b/model/EasyR1/examples/config_d_grpo.yaml @@ -0,0 +1,109 @@ +data: + train_files: "" + val_files: "" + prompt_key: problem + answer_key: answer + image_key: images + video_key: videos + image_dir: null + video_fps: 2.0 + max_prompt_length: 16384 + max_response_length: 4096 + rollout_batch_size: 512 # equivalent to verl's data.train_batch_size + mini_rollout_batch_size: null # equivalent to verl's data.gen_batch_size + val_batch_size: 1024 + format_prompt: “” + override_chat_template: null + shuffle: true + seed: 1 + min_pixels: 3136 + max_pixels: 1048576 + resize_size: 336 + filter_overlong_prompts: false + +algorithm: + adv_estimator: ema_grpo + disable_kl: true + use_kl_loss: true + kl_penalty: low_var_kl + kl_coef: 1.0e-2 + online_filtering: true # dapo filter groups + filter_key: accuracy + filter_low: 0.01 + filter_high: 0.99 + +worker: + actor: + global_batch_size: 128 # equivalent to verl's actor.ppo_mini_batch_size + micro_batch_size_per_device_for_update: 1 # equivalent to verl's actor.ppo_micro_batch_size_per_gpu + micro_batch_size_per_device_for_experience: 2 # equivalent to verl's rollout.log_prob_micro_batch_size_per_gpu + max_grad_norm: 1.0 + padding_free: true + dynamic_batching: true + ulysses_size: 1 + model: + model_path: Qwen/Qwen2.5-7B-Instruct + enable_gradient_checkpointing: true + trust_remote_code: false + freeze_vision_tower: true + optim: + lr: 5.0e-6 + weight_decay: 1.0e-2 + strategy: adamw # {adamw, adamw_bf16} + lr_warmup_ratio: 0.0 + fsdp: + enable_full_shard: true + enable_cpu_offload: false + enable_rank0_init: true + offload: + offload_params: false # true: more CPU memory; false: more GPU memory + offload_optimizer: false # true: more CPU memory; false: more GPU memory + + rollout: + n: 8 + temperature: 1.0 + top_p: 1.0 + limit_images: 0 + gpu_memory_utilization: 0.5 + enforce_eager: false + enable_chunked_prefill: false + tensor_parallel_size: 2 + disable_tqdm: true + max_num_batched_tokens: 20480 + val_override_config: + temperature: 0.7 + top_p: 0.95 + n: 1 + + ref: + fsdp: + enable_full_shard: true + enable_cpu_offload: false # true: more CPU memory; false: more GPU memory + enable_rank0_init: true + offload: + offload_params: false + + reward: + reward_type: batch + reward_function: EasyR1/verl/reward_function/onethinker_reward.py:compute_score + +trainer: + total_epochs: 1 + max_steps: null + project_name: easy_r1 + experiment_name: qwen2_5_7b_math_grpo + logger: ["file", "wandb"] + # logger: ["file"] + nnodes: 8 + n_gpus_per_node: 8 + max_try_make_batch: 20 # -1 means no limit + val_freq: -1 # -1 to disable + val_before_train: false + val_only: false + val_generations_to_log: 3 + save_freq: 200 # -1 to disable + save_limit: 100000 # -1 to disable + save_model_only: false + save_checkpoint_path: checkpoints/qwen3-8b-rl + load_checkpoint_path: null + find_last_checkpoint: true diff --git a/model/EasyR1/examples/config_ema_grpo.yaml b/model/EasyR1/examples/config_ema_grpo.yaml new file mode 100644 index 0000000000000000000000000000000000000000..70011817e0ac5e4e6bca79092246994583c1aa92 --- /dev/null +++ b/model/EasyR1/examples/config_ema_grpo.yaml @@ -0,0 +1,108 @@ +data: + train_files: "" + val_files: "" + prompt_key: problem + answer_key: answer + image_key: images + video_key: videos + image_dir: null + video_fps: 2.0 + max_prompt_length: 16384 + max_response_length: 4096 + rollout_batch_size: 128 + mini_rollout_batch_size: null + val_batch_size: 1024 + format_prompt: "" + override_chat_template: null + shuffle: true + seed: 1 + min_pixels: 3136 + max_pixels: 1048576 + resize_size: 336 + filter_overlong_prompts: false + +algorithm: + adv_estimator: ema_grpo + disable_kl: true + use_kl_loss: true + kl_penalty: low_var_kl + kl_coef: 1.0e-2 + online_filtering: false + filter_key: accuracy + filter_low: 0.0 + filter_high: 1.0 + +worker: + actor: + global_batch_size: 32 + micro_batch_size_per_device_for_update: 1 + micro_batch_size_per_device_for_experience: 1 + max_grad_norm: 1.0 + padding_free: true + dynamic_batching: true + ulysses_size: 1 + model: + model_path: "" + enable_gradient_checkpointing: true + trust_remote_code: false + freeze_vision_tower: true + optim: + lr: 5.0e-6 + weight_decay: 1.0e-2 + strategy: adamw + lr_warmup_ratio: 0.0 + fsdp: + enable_full_shard: true + enable_cpu_offload: false + enable_rank0_init: true + offload: + offload_params: false + offload_optimizer: false + + rollout: + n: 8 + temperature: 1.0 + top_p: 1.0 + limit_images: 0 + gpu_memory_utilization: 0.7 + enforce_eager: false + enable_chunked_prefill: false + tensor_parallel_size: 4 + disable_tqdm: true + max_num_batched_tokens: 20480 + val_override_config: + temperature: 0.7 + top_p: 0.95 + n: 1 + + ref: + fsdp: + enable_full_shard: true + enable_cpu_offload: false + enable_rank0_init: true + offload: + offload_params: false + + reward: + reward_type: batch + reward_function: EasyR1/verl/reward_function/onethinker_reward.py:compute_score + +trainer: + total_epochs: 1 + max_steps: null + project_name: easy_r1 + experiment_name: "" + logger: ["file", "wandb"] + nnodes: 1 + n_gpus_per_node: 2 + max_try_make_batch: 20 + val_freq: -1 + val_before_train: false + val_only: false + val_generations_to_log: 3 + save_freq: 200 + save_limit: 100000 + save_model_only: false + save_checkpoint_path: "" + load_checkpoint_path: null + find_last_checkpoint: false diff --git a/model/EasyR1/examples/config_ema_grpo_64.yaml b/model/EasyR1/examples/config_ema_grpo_64.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f3d1aa650f027f3fd223369c1069d6eb4f447ec3 --- /dev/null +++ b/model/EasyR1/examples/config_ema_grpo_64.yaml @@ -0,0 +1,109 @@ +data: + train_files: hiyouga/math12k@train + val_files: "" + prompt_key: problem + answer_key: answer + image_key: images + video_key: videos + image_dir: null + video_fps: 2.0 + max_prompt_length: 16384 + max_response_length: 4096 + rollout_batch_size: 512 # equivalent to verl's data.train_batch_size + mini_rollout_batch_size: null # equivalent to verl's data.gen_batch_size + val_batch_size: 1024 + format_prompt: “” + override_chat_template: null + shuffle: true + seed: 1 + min_pixels: 3136 + max_pixels: 1048576 + resize_size: 336 + filter_overlong_prompts: false + +algorithm: + adv_estimator: ema_grpo + disable_kl: true + use_kl_loss: true + kl_penalty: low_var_kl + kl_coef: 1.0e-2 + online_filtering: true # dapo filter groups + filter_key: accuracy + filter_low: 0.01 + filter_high: 0.99 + +worker: + actor: + global_batch_size: 128 # equivalent to verl's actor.ppo_mini_batch_size + micro_batch_size_per_device_for_update: 1 # equivalent to verl's actor.ppo_micro_batch_size_per_gpu + micro_batch_size_per_device_for_experience: 2 # equivalent to verl's rollout.log_prob_micro_batch_size_per_gpu + max_grad_norm: 1.0 + padding_free: true + dynamic_batching: true + ulysses_size: 1 + model: + model_path: Qwen/Qwen2.5-7B-Instruct + enable_gradient_checkpointing: true + trust_remote_code: false + freeze_vision_tower: true + optim: + lr: 5.0e-6 + weight_decay: 1.0e-2 + strategy: adamw # {adamw, adamw_bf16} + lr_warmup_ratio: 0.0 + fsdp: + enable_full_shard: true + enable_cpu_offload: false + enable_rank0_init: true + offload: + offload_params: false # true: more CPU memory; false: more GPU memory + offload_optimizer: false # true: more CPU memory; false: more GPU memory + + rollout: + n: 8 + temperature: 1.0 + top_p: 1.0 + limit_images: 0 + gpu_memory_utilization: 0.5 + enforce_eager: false + enable_chunked_prefill: false + tensor_parallel_size: 2 + disable_tqdm: true + max_num_batched_tokens: 20480 + val_override_config: + temperature: 0.7 + top_p: 0.95 + n: 1 + + ref: + fsdp: + enable_full_shard: true + enable_cpu_offload: false # true: more CPU memory; false: more GPU memory + enable_rank0_init: true + offload: + offload_params: false + + reward: + reward_type: batch + reward_function: EasyR1/verl/reward_function/onethinker_reward.py:compute_score + +trainer: + total_epochs: 1 + max_steps: null + project_name: easy_r1 + experiment_name: qwen2_5_7b_math_grpo + logger: ["file", "wandb"] + # logger: ["file"] + nnodes: 8 + n_gpus_per_node: 8 + max_try_make_batch: 20 # -1 means no limit + val_freq: -1 # -1 to disable + val_before_train: false + val_only: false + val_generations_to_log: 3 + save_freq: 200 # -1 to disable + save_limit: 100000 # -1 to disable + save_model_only: false + save_checkpoint_path: checkpoints/qwen3-8b-rl + load_checkpoint_path: null + find_last_checkpoint: true diff --git a/model/EasyR1/examples/config_grpo.yaml b/model/EasyR1/examples/config_grpo.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7b5d4a6729861f4d6ae0280650d69129f4b6a371 --- /dev/null +++ b/model/EasyR1/examples/config_grpo.yaml @@ -0,0 +1,108 @@ +data: + train_files: "" + val_files: "" + prompt_key: problem + answer_key: answer + image_key: images + video_key: videos + image_dir: null + video_fps: 2.0 + max_prompt_length: 16384 + max_response_length: 4096 + rollout_batch_size: 128 + mini_rollout_batch_size: null + val_batch_size: 1024 + format_prompt: "" + override_chat_template: null + shuffle: true + seed: 1 + min_pixels: 3136 + max_pixels: 1048576 + resize_size: 336 + filter_overlong_prompts: false + +algorithm: + adv_estimator: grpo + disable_kl: true + use_kl_loss: true + kl_penalty: low_var_kl + kl_coef: 1.0e-2 + online_filtering: false + filter_key: accuracy + filter_low: 0.0 + filter_high: 1.0 + +worker: + actor: + global_batch_size: 32 + micro_batch_size_per_device_for_update: 1 + micro_batch_size_per_device_for_experience: 1 + max_grad_norm: 1.0 + padding_free: true + dynamic_batching: true + ulysses_size: 1 + model: + model_path: "" + enable_gradient_checkpointing: true + trust_remote_code: false + freeze_vision_tower: true + optim: + lr: 5.0e-6 + weight_decay: 1.0e-2 + strategy: adamw + lr_warmup_ratio: 0.0 + fsdp: + enable_full_shard: true + enable_cpu_offload: false + enable_rank0_init: true + offload: + offload_params: false + offload_optimizer: false + + rollout: + n: 8 + temperature: 1.0 + top_p: 1.0 + limit_images: 0 + gpu_memory_utilization: 0.7 + enforce_eager: false + enable_chunked_prefill: false + tensor_parallel_size: 4 + disable_tqdm: true + max_num_batched_tokens: 20480 + val_override_config: + temperature: 0.7 + top_p: 0.95 + n: 1 + + ref: + fsdp: + enable_full_shard: true + enable_cpu_offload: false + enable_rank0_init: true + offload: + offload_params: false + + reward: + reward_type: batch + reward_function: EasyR1/verl/reward_function/onethinker_reward.py:compute_score + +trainer: + total_epochs: 1 + max_steps: null + project_name: easy_r1 + experiment_name: "" + logger: ["file", "wandb"] + nnodes: 1 + n_gpus_per_node: 2 + max_try_make_batch: 20 + val_freq: -1 + val_before_train: false + val_only: false + val_generations_to_log: 3 + save_freq: 1 + save_limit: 100000 + save_model_only: false + save_checkpoint_path: "" + load_checkpoint_path: null + find_last_checkpoint: false diff --git a/model/EasyR1/examples/format_prompt/dapo.jinja b/model/EasyR1/examples/format_prompt/dapo.jinja new file mode 100644 index 0000000000000000000000000000000000000000..ea56a6a64c1d8c6fac481abf6dbf9ebcfff37420 --- /dev/null +++ b/model/EasyR1/examples/format_prompt/dapo.jinja @@ -0,0 +1 @@ +Solve the following math problem step by step. The last line of your response should be of the form Answer: $Answer (without quotes) where $Answer is the answer to the problem.\n\n{{ content | trim }}\n\nRemember to put your answer on its own line after "Answer:". diff --git a/model/EasyR1/examples/format_prompt/math.jinja b/model/EasyR1/examples/format_prompt/math.jinja new file mode 100644 index 0000000000000000000000000000000000000000..8d6aa2344c57d654c87dbd26d90f7af473f82cc6 --- /dev/null +++ b/model/EasyR1/examples/format_prompt/math.jinja @@ -0,0 +1 @@ +{{ content | trim }} You FIRST think about the reasoning process as an internal monologue and then provide the final answer. The reasoning process MUST BE enclosed within tags. The final answer MUST BE put in \boxed{}. diff --git a/model/EasyR1/examples/format_prompt/r1v.jinja b/model/EasyR1/examples/format_prompt/r1v.jinja new file mode 100644 index 0000000000000000000000000000000000000000..0ecf6f471146202113d4e44c10777d60e65c8e8a --- /dev/null +++ b/model/EasyR1/examples/format_prompt/r1v.jinja @@ -0,0 +1 @@ +{{ content | trim }} A conversation between User and Assistant. The user asks a question, and the Assistant solves it. The assistant first thinks about the reasoning process in the mind and then provides the user with the answer. The reasoning process and answer are enclosed within and tags, respectively, i.e., reasoning process here answer here diff --git a/model/EasyR1/examples/qwen2_5_7b_math_grpo.sh b/model/EasyR1/examples/qwen2_5_7b_math_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6b364395f5309a1eb95dd6664a479b5938067ef --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_7b_math_grpo.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen2.5-7B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + worker.actor.model.model_path=${MODEL_PATH} diff --git a/model/EasyR1/examples/qwen2_5_vl_32b_geo3k_grpo.sh b/model/EasyR1/examples/qwen2_5_vl_32b_geo3k_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf23310cc0a6b50024032586c6fbf7fccd689de6 --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_vl_32b_geo3k_grpo.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen2.5-VL-32B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/geometry3k@train \ + data.val_files=hiyouga/geometry3k@test \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.actor.fsdp.torch_dtype=bf16 \ + worker.actor.optim.strategy=adamw_bf16 \ + worker.rollout.tensor_parallel_size=8 \ + trainer.experiment_name=qwen2_5_vl_32b_geo_grpo \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/qwen2_5_vl_3b_geo3k_grpo.sh b/model/EasyR1/examples/qwen2_5_vl_3b_geo3k_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ab288f99d018f1e44b6e79d89dc13bbfa55885b --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_vl_3b_geo3k_grpo.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen2.5-VL-3B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/geometry3k@train \ + data.val_files=hiyouga/geometry3k@test \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.rollout.tensor_parallel_size=1 \ + trainer.experiment_name=qwen2_5_vl_3b_geo_grpo \ + trainer.n_gpus_per_node=2 diff --git a/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_dapo.sh b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_dapo.sh new file mode 100644 index 0000000000000000000000000000000000000000..188977ad2e82e774a76e527659348cd6ff84ad9b --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_dapo.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen2.5-VL-7B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/geometry3k@train \ + data.val_files=hiyouga/geometry3k@test \ + data.mini_rollout_batch_size=128 \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.actor.clip_ratio_low=0.2 \ + worker.actor.clip_ratio_high=0.28 \ + algorithm.disable_kl=True \ + algorithm.online_filtering=True \ + trainer.experiment_name=qwen2_5_vl_7b_geo_dapo \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_grpo.sh b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b76f281ceb367aab4dc2ba5e2a028ca1aebcdfe --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_grpo.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen2.5-VL-7B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/geometry3k@train \ + data.val_files=hiyouga/geometry3k@test \ + worker.actor.model.model_path=${MODEL_PATH} \ + trainer.experiment_name=qwen2_5_vl_7b_geo_grpo \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_reinforce.sh b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_reinforce.sh new file mode 100644 index 0000000000000000000000000000000000000000..700afaf4e25efa5076b982861fd649e781b30175 --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_reinforce.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen2.5-VL-7B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/geometry3k@train \ + data.val_files=hiyouga/geometry3k@test \ + worker.actor.model.model_path=${MODEL_PATH} \ + algorithm.adv_estimator=reinforce_plus_plus \ + algorithm.use_kl_loss=false \ + algorithm.kl_penalty=kl \ + algorithm.kl_coef=1.0e-3 \ + trainer.experiment_name=qwen2_5_vl_7b_geo_reinforce_pp \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_swanlab.sh b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_swanlab.sh new file mode 100644 index 0000000000000000000000000000000000000000..e884d6341d166eb615c5ada2053a1a633b4a0ff8 --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_vl_7b_geo3k_swanlab.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen2.5-VL-7B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/geometry3k@train \ + data.val_files=hiyouga/geometry3k@test \ + worker.actor.model.model_path=${MODEL_PATH} \ + trainer.experiment_name=qwen2_5_vl_7b_geo_grpo \ + trainer.logger=['console','swanlab'] \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/qwen2_5_vl_7b_multi_image.sh b/model/EasyR1/examples/qwen2_5_vl_7b_multi_image.sh new file mode 100644 index 0000000000000000000000000000000000000000..020498fa1e1308cdfd7aedf52e3960ed565696e5 --- /dev/null +++ b/model/EasyR1/examples/qwen2_5_vl_7b_multi_image.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# REMINDER: this script uses test data split and should ONLY be used for debugging. DO NOT use for training. + +set -x + +MODEL_PATH=Qwen/Qwen2.5-VL-7B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/journeybench-multi-image-vqa@train \ + data.val_files=hiyouga/journeybench-multi-image-vqa@test \ + data.rollout_batch_size=256 \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.rollout.limit_images=2 \ + trainer.experiment_name=qwen2_5_vl_7b_multi_image \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/qwen3_14b_dapo17k_dapo.sh b/model/EasyR1/examples/qwen3_14b_dapo17k_dapo.sh new file mode 100644 index 0000000000000000000000000000000000000000..d111b2b056d95f138f8aa913dc13ef6ebffe9320 --- /dev/null +++ b/model/EasyR1/examples/qwen3_14b_dapo17k_dapo.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen3-14B-Base # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=Saigyouji-Yuyuko1000/dapo17k@train \ + data.val_files=Saigyouji-Yuyuko1000/dapo17k@test \ + data.format_prompt=./examples/format_prompt/dapo.jinja \ + data.max_prompt_length=2048 \ + data.max_response_length=20480 \ + data.rollout_batch_size=512 \ + data.mini_rollout_batch_size=256 \ + worker.actor.ulysses_size=8 \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.actor.fsdp.torch_dtype=bf16 \ + worker.actor.optim.strategy=adamw_bf16 \ + worker.actor.optim.weight_decay=0.1 \ + worker.actor.optim.lr_warmup_steps=10 \ + worker.actor.global_batch_size=32 \ + worker.actor.clip_ratio_low=0.2 \ + worker.actor.clip_ratio_high=0.28 \ + worker.actor.clip_ratio_dual=10.0 \ + worker.rollout.n=16 \ + worker.rollout.max_num_batched_tokens=22528 \ + worker.rollout.val_override_config='{"n":16,"temperature":1.0,"top_p":0.7}' \ + worker.rollout.gpu_memory_utilization=0.8 \ + worker.rollout.tensor_parallel_size=4 \ + worker.reward.reward_function=./examples/reward_function/dapo.py:compute_score \ + worker.reward.reward_function_kwargs='{"max_response_length":20480,"overlong_buffer_length":4096,"overlong_penalty_factor":1.0}' \ + algorithm.disable_kl=True \ + algorithm.online_filtering=True \ + algorithm.filter_key=accuracy_normalized \ + algorithm.filter_low=0.01 \ + algorithm.filter_high=0.99 \ + trainer.total_epochs=10 \ + trainer.max_try_make_batch=10 \ + trainer.experiment_name=qwen3_14b_dapo17k_dapo \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/qwen3_4b_math_grpo.sh b/model/EasyR1/examples/qwen3_4b_math_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac13be453d360cedea586adc7366495129e0fb14 --- /dev/null +++ b/model/EasyR1/examples/qwen3_4b_math_grpo.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen3-4B # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.max_response_length=4096 \ + worker.actor.model.model_path=${MODEL_PATH} \ + trainer.experiment_name=qwen3_4b_math_grpo diff --git a/model/EasyR1/examples/qwen3_vl_30b_geo3k_grpo.sh b/model/EasyR1/examples/qwen3_vl_30b_geo3k_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..bcbcacff77d779848a00d923c3c426ada52c2fb0 --- /dev/null +++ b/model/EasyR1/examples/qwen3_vl_30b_geo3k_grpo.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +set -x + +MODEL_PATH=Qwen/Qwen3-VL-30B-A3B-Instruct # replace it with your local file path + +python3 -m verl.trainer.main \ + config=examples/config.yaml \ + data.train_files=hiyouga/geometry3k@train \ + data.val_files=hiyouga/geometry3k@test \ + worker.actor.model.model_path=${MODEL_PATH} \ + worker.actor.fsdp.torch_dtype=bf16 \ + worker.actor.optim.strategy=adamw_bf16 \ + worker.rollout.tensor_parallel_size=8 \ + trainer.experiment_name=qwen3_vl_30b_geo_grpo \ + trainer.n_gpus_per_node=8 diff --git a/model/EasyR1/examples/runtime_env.yaml b/model/EasyR1/examples/runtime_env.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c2aba7aedb661c347b93d716ba840963ad799ba --- /dev/null +++ b/model/EasyR1/examples/runtime_env.yaml @@ -0,0 +1,10 @@ +working_dir: ./ +excludes: ["/.git/"] +env_vars: + TOKENIZERS_PARALLELISM: "true" + NCCL_DEBUG: "WARN" + VLLM_LOGGING_LEVEL: "WARN" + TORCH_NCCL_AVOID_RECORD_STREAMS: "1" + PYTORCH_CUDA_ALLOC_CONF: "expandable_segments:False" + CUDA_DEVICE_MAX_CONNECTIONS: "1" + VLLM_ALLREDUCE_USE_SYMM_MEM: "0" diff --git a/model/EasyR1/local_scripts/run_onethinker_rl.sh b/model/EasyR1/local_scripts/run_onethinker_rl.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a23a916eb237dbf380c1be52b2b35c2dbdbd245 --- /dev/null +++ b/model/EasyR1/local_scripts/run_onethinker_rl.sh @@ -0,0 +1,52 @@ + +#!/usr/bin/env bash +set -x + +export DECORD_EOF_RETRY_MAX=2048001 +export WANDB_API_KEY= + + +project_name='EasyR1-onethinker-rl' +exp_name='qwen3_vl_onethinker-rl' + +MODEL_PATH= +TRAIN_FILE="onethinker_rl_train.json" +TEST_FILE="onethinker_rl_train.json" +IMAGE_DIR= + +ROLLOUT_BS=128 +GLOBAL_BS=32 +MB_PER_UPDATE=1 +MB_PER_EXP=1 +TP_SIZE=4 +N_GPUS_PER_NODE=8 +NNODES=4 + + + +python3 -m verl.trainer.main \ + config=EasyR1/examples/config_ema_grpo_64.yaml \ + data.train_files="${TRAIN_FILE}" \ + data.val_files="${TEST_FILE}" \ + data.image_dir="${IMAGE_DIR}" \ + data.rollout_batch_size="${ROLLOUT_BS}" \ + worker.actor.global_batch_size="${GLOBAL_BS}" \ + worker.actor.micro_batch_size_per_device_for_update="${MB_PER_UPDATE}" \ + worker.actor.micro_batch_size_per_device_for_experience="${MB_PER_EXP}" \ + worker.actor.model.model_path="${MODEL_PATH}" \ + worker.actor.fsdp.torch_dtype=bf16 \ + worker.actor.optim.strategy=adamw_bf16 \ + worker.actor.optim.lr=2e-6 \ + worker.rollout.tensor_parallel_size="${TP_SIZE}" \ + algorithm.filter_low=0.01 \ + algorithm.filter_high=0.99 \ + algorithm.online_filtering=true \ + algorithm.filter_key=accuracy \ + trainer.project_name="${project_name}" \ + trainer.experiment_name="${exp_name}" \ + trainer.n_gpus_per_node="${N_GPUS_PER_NODE}" \ + trainer.nnodes="${NNODES}" \ + trainer.save_freq=100 \ + trainer.save_checkpoint_path=EasyR1/checkpoints + + diff --git a/model/EasyR1/local_scripts/run_surgicalthinker_rl_d-grpo.sh b/model/EasyR1/local_scripts/run_surgicalthinker_rl_d-grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..49018f2993f2032fa4f824eb8b4b5d11e96ed050 --- /dev/null +++ b/model/EasyR1/local_scripts/run_surgicalthinker_rl_d-grpo.sh @@ -0,0 +1,63 @@ + #!/usr/bin/env bash +set -x + +export DECORD_EOF_RETRY_MAX=2048001 +export WANDB_API_KEY=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 + +# NCCL settings to fix timeout +export NCCL_P2P_DISABLE=1 +export NCCL_TIMEOUT=1800 # 30 minutes timeout +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_DEBUG=WARN # Set to INFO for more debug output +export NCCL_BLOCKING_WAIT=0 + +# PyTorch distributed settings +export TORCH_DISTRIBUTED_DEBUG=OFF # Set to DETAIL for more debug info +export TORCH_NCCL_BLOCKING_WAIT=0 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 + + +project_name='EasyR1' +exp_name='surgicalthinker_onethinker_d-grpo' + +MODEL_PATH="/home/cgv/extend_data/wp/project/OneThinker/models/OneThinker/SurgicalThinker-SFT" +TRAIN_FILE="/home/cgv/extend_data/wp/data/Medical/surgicalthinker_rl_subset.json" +TEST_FILE="/home/cgv/extend_data/wp/data/Medical/surgicalthinker_rl_subset.json" +IMAGE_DIR="/home/cgv/extend_data/wp/data/Medical" + +ROLLOUT_BS=8 +GLOBAL_BS=8 +MB_PER_UPDATE=1 +MB_PER_EXP=1 +TP_SIZE=4 +N_GPUS_PER_NODE=8 +NNODES=1 + + + +python3 -m verl.trainer.main \ + config=EasyR1/examples/config_ema_grpo.yaml \ + data.train_files="${TRAIN_FILE}" \ + data.val_files="${TEST_FILE}" \ + data.image_dir="${IMAGE_DIR}" \ + data.rollout_batch_size="${ROLLOUT_BS}" \ + worker.actor.global_batch_size="${GLOBAL_BS}" \ + worker.actor.micro_batch_size_per_device_for_update="${MB_PER_UPDATE}" \ + worker.actor.micro_batch_size_per_device_for_experience="${MB_PER_EXP}" \ + worker.actor.model.model_path="${MODEL_PATH}" \ + worker.actor.fsdp.torch_dtype=bf16 \ + worker.actor.optim.strategy=adamw_bf16 \ + worker.actor.optim.lr=2e-6 \ + worker.rollout.tensor_parallel_size="${TP_SIZE}" \ + algorithm.filter_low=0.0 \ + algorithm.filter_high=1.0 \ + algorithm.online_filtering=false \ + algorithm.filter_key=accuracy \ + trainer.project_name="${project_name}" \ + trainer.experiment_name="${exp_name}" \ + trainer.n_gpus_per_node="${N_GPUS_PER_NODE}" \ + trainer.nnodes="${NNODES}" \ + trainer.save_freq=100 \ + trainer.save_checkpoint_path=EasyR1/checkpoints + + diff --git a/model/EasyR1/local_scripts/run_surgicalthinker_rl_ema-grpo.sh b/model/EasyR1/local_scripts/run_surgicalthinker_rl_ema-grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..886a417a11ebce5a2327307333cfe21fd328610a --- /dev/null +++ b/model/EasyR1/local_scripts/run_surgicalthinker_rl_ema-grpo.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -x + +export DECORD_EOF_RETRY_MAX=2048001 +export WANDB_API_KEY=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 + +# NCCL settings to fix timeout +export NCCL_P2P_DISABLE=1 +export NCCL_TIMEOUT=1800 # 30 minutes timeout +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_DEBUG=WARN # Set to INFO for more debug output +export NCCL_BLOCKING_WAIT=0 + +# PyTorch distributed settings +export TORCH_DISTRIBUTED_DEBUG=OFF # Set to DETAIL for more debug info +export TORCH_NCCL_BLOCKING_WAIT=0 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 + + +project_name='EasyR1' +exp_name='surgicalthinker_onethinker_rl_ema_grpo' + +MODEL_PATH="WangYe007/OneThinker_SurgicalThinker-SFT" +TRAIN_FILE="../../data/Medical/surgicalthinker_rl.json" +TEST_FILE="../../data/Medical/surgicalthinker_rl.json" +IMAGE_DIR="../../data/Medical" + +ROLLOUT_BS=128 +GLOBAL_BS=32 +MB_PER_UPDATE=1 +MB_PER_EXP=1 +TP_SIZE=4 +N_GPUS_PER_NODE=8 +NNODES=1 + + + +python3 -m verl.trainer.main \ + config=EasyR1/examples/config_ema_grpo.yaml \ + data.train_files="${TRAIN_FILE}" \ + data.val_files="${TEST_FILE}" \ + data.image_dir="${IMAGE_DIR}" \ + data.rollout_batch_size="${ROLLOUT_BS}" \ + worker.actor.global_batch_size="${GLOBAL_BS}" \ + worker.actor.micro_batch_size_per_device_for_update="${MB_PER_UPDATE}" \ + worker.actor.micro_batch_size_per_device_for_experience="${MB_PER_EXP}" \ + worker.actor.model.model_path="${MODEL_PATH}" \ + worker.actor.fsdp.torch_dtype=bf16 \ + worker.actor.optim.strategy=adamw_bf16 \ + worker.actor.optim.lr=2e-6 \ + worker.rollout.tensor_parallel_size="${TP_SIZE}" \ + algorithm.filter_low=0.0 \ + algorithm.filter_high=1.0 \ + algorithm.online_filtering=false \ + algorithm.filter_key=accuracy \ + trainer.project_name="${project_name}" \ + trainer.experiment_name="${exp_name}" \ + trainer.n_gpus_per_node="${N_GPUS_PER_NODE}" \ + trainer.nnodes="${NNODES}" \ + trainer.save_freq=50 \ + trainer.save_checkpoint_path=EasyR1/checkpoints/ema_grpo + + diff --git a/model/EasyR1/local_scripts/run_surgicalthinker_rl_grpo.sh b/model/EasyR1/local_scripts/run_surgicalthinker_rl_grpo.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a7c3f16b68b0f85dad721e64849c20e6b258e73 --- /dev/null +++ b/model/EasyR1/local_scripts/run_surgicalthinker_rl_grpo.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +set -x + +export DECORD_EOF_RETRY_MAX=2048001 +export WANDB_API_KEY=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 + +# NCCL settings to fix timeout +export NCCL_P2P_DISABLE=1 +export NCCL_TIMEOUT=1800 # 30 minutes timeout +export NCCL_ASYNC_ERROR_HANDLING=1 +export NCCL_DEBUG=WARN # Set to INFO for more debug output +export NCCL_BLOCKING_WAIT=0 + +# PyTorch distributed settings +export TORCH_DISTRIBUTED_DEBUG=OFF # Set to DETAIL for more debug info +export TORCH_NCCL_BLOCKING_WAIT=0 +export TORCH_NCCL_ASYNC_ERROR_HANDLING=1 + + +project_name='EasyR1' +exp_name='surgicalthinker_onethinker_grpo' + +MODEL_PATH="WangYe007/OneThinker_SurgicalThinker-SFT" +TRAIN_FILE="../../data/Medical/surgicalthinker_rl.json" +TEST_FILE="../../data/Medical/surgicalthinker_rl.json" +IMAGE_DIR="../../data/Medical" + +ROLLOUT_BS=128 +GLOBAL_BS=32 +MB_PER_UPDATE=1 +MB_PER_EXP=1 +TP_SIZE=4 +N_GPUS_PER_NODE=8 +NNODES=1 + + + +python3 -m verl.trainer.main \ + config=EasyR1/examples/config_grpo.yaml \ + data.train_files="${TRAIN_FILE}" \ + data.val_files="${TEST_FILE}" \ + data.image_dir="${IMAGE_DIR}" \ + data.rollout_batch_size="${ROLLOUT_BS}" \ + worker.actor.global_batch_size="${GLOBAL_BS}" \ + worker.actor.micro_batch_size_per_device_for_update="${MB_PER_UPDATE}" \ + worker.actor.micro_batch_size_per_device_for_experience="${MB_PER_EXP}" \ + worker.actor.model.model_path="${MODEL_PATH}" \ + worker.actor.fsdp.torch_dtype=bf16 \ + worker.actor.optim.strategy=adamw_bf16 \ + worker.actor.optim.lr=2e-6 \ + worker.rollout.tensor_parallel_size="${TP_SIZE}" \ + algorithm.filter_low=0.0 \ + algorithm.filter_high=1.0 \ + algorithm.online_filtering=false \ + algorithm.filter_key=accuracy \ + trainer.project_name="${project_name}" \ + trainer.experiment_name="${exp_name}" \ + trainer.n_gpus_per_node="${N_GPUS_PER_NODE}" \ + trainer.nnodes="${NNODES}" \ + trainer.save_freq=50 \ + trainer.save_checkpoint_path=EasyR1/checkpoints/grpo + + diff --git a/model/EasyR1/pyproject.toml b/model/EasyR1/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f579c19b4ec15bfb975ea1ad1d266d00a516dfe --- /dev/null +++ b/model/EasyR1/pyproject.toml @@ -0,0 +1,39 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "verl" +dynamic = [ + "version", + "dependencies", + "optional-dependencies", + "requires-python", + "authors", + "description", + "readme", + "license" +] + +[tool.ruff] +target-version = "py39" +line-length = 119 +indent-width = 4 + +[tool.ruff.lint] +ignore = ["C901", "E501", "E741", "W605", "C408"] +select = ["C", "E", "F", "I", "W", "RUF022"] + +[tool.ruff.lint.per-file-ignores] +"__init__.py" = ["E402", "F401", "F403", "F811"] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["verl"] +known-third-party = ["torch", "transformers", "wandb"] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" +skip-magic-trailing-comma = false +line-ending = "auto" diff --git a/model/EasyR1/requirements.txt b/model/EasyR1/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..5df5ea59cc916ef0f87b90f6ca0765f2c6c03c9f --- /dev/null +++ b/model/EasyR1/requirements.txt @@ -0,0 +1,20 @@ +accelerate +codetiming +datasets +# flash-attn>=2.4.3 +liger-kernel +mathruler +numpy +omegaconf +pandas +peft +pillow +pyarrow>=15.0.0 +pylatexenc +qwen-vl-utils +ray[default] +tensordict +torchdata +# transformers>=4.54.0,<=4.57.0 +# vllm>=0.8.0 +wandb diff --git a/model/EasyR1/scripts/model_merger.py b/model/EasyR1/scripts/model_merger.py new file mode 100644 index 0000000000000000000000000000000000000000..f922bb0dc8767e53265127b980dd1874766dcd90 --- /dev/null +++ b/model/EasyR1/scripts/model_merger.py @@ -0,0 +1,186 @@ +# 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. + +import argparse +import os +import re +from concurrent.futures import ThreadPoolExecutor + +import numpy as np +import torch +from torch.distributed._tensor import DTensor, Placement, Shard +from transformers import ( + AutoConfig, + AutoModelForCausalLM, + AutoModelForImageTextToText, + AutoModelForTokenClassification, + PretrainedConfig, + PreTrainedModel, +) + + +def merge_by_placement(tensors: list[torch.Tensor], placement: Placement): + if placement.is_replicate(): + return tensors[0] + elif placement.is_partial(): + raise NotImplementedError("Partial placement is not supported yet") + elif placement.is_shard(): + return torch.cat(tensors, dim=placement.dim).contiguous() + else: + raise ValueError(f"Unsupported placement: {placement}") + + +def upload_model_to_huggingface(local_path: str, remote_path: str): + # Push to hugging face + from huggingface_hub import HfApi + + api = HfApi() + api.create_repo(repo_id=remote_path, private=False, exist_ok=True) + api.upload_folder(repo_id=remote_path, folder_path=local_path, repo_type="model") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--local_dir", required=True, type=str, help="The path for your saved model") + parser.add_argument("--hf_upload_path", default=False, type=str, help="The path of the huggingface repo to upload") + args = parser.parse_args() + local_dir: str = args.local_dir + + assert not local_dir.endswith("huggingface"), "The local_dir should not end with huggingface." + + # copy rank zero to find the shape of (dp, fsdp) + rank = 0 + world_size = 0 + for filename in os.listdir(local_dir): + match = re.match(r"model_world_size_(\d+)_rank_0\.pt", filename) + if match: + world_size = match.group(1) + break + + assert world_size, "No model file with the proper format." + + rank0_weight_path = os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt") + state_dict = torch.load(rank0_weight_path, map_location="cpu", weights_only=False) + pivot_key = sorted(state_dict.keys())[0] + weight = state_dict[pivot_key] + if isinstance(weight, DTensor): + # get sharding info + device_mesh = weight.device_mesh + mesh = device_mesh.mesh + mesh_dim_names = device_mesh.mesh_dim_names + else: + # for non-DTensor + mesh = np.array([int(world_size)], dtype=np.int64) + mesh_dim_names = ("fsdp",) + + print(f"Got device mesh {mesh}, mesh_dim_names {mesh_dim_names}") + + assert mesh_dim_names in (("fsdp",), ("ddp", "fsdp")), f"Unsupported mesh_dim_names {mesh_dim_names}." + + if "tp" in mesh_dim_names: + # fsdp * tp + total_shards = mesh.shape[-1] * mesh.shape[-2] + mesh_shape = (mesh.shape[-2], mesh.shape[-1]) + else: + # fsdp + total_shards = mesh.shape[-1] + mesh_shape = (mesh.shape[-1],) + + print(f"Processing {total_shards} model shards in total.") + model_state_dict_lst = [] + model_state_dict_lst.append(state_dict) + model_state_dict_lst.extend([""] * (total_shards - 1)) + + def process_one_shard(rank, model_state_dict_lst): + model_path = os.path.join(local_dir, f"model_world_size_{world_size}_rank_{rank}.pt") + state_dict = torch.load(model_path, map_location="cpu", weights_only=False) + model_state_dict_lst[rank] = state_dict + return state_dict + + with ThreadPoolExecutor(max_workers=min(32, os.cpu_count())) as executor: + for rank in range(1, total_shards): + executor.submit(process_one_shard, rank, model_state_dict_lst) + + state_dict: dict[str, list[torch.Tensor]] = {} + param_placements: dict[str, list[Placement]] = {} + keys = set(model_state_dict_lst[0].keys()) + for key in keys: + state_dict[key] = [] + for model_state_dict in model_state_dict_lst: + try: + tensor = model_state_dict.pop(key) + except Exception: + print(f"Cannot find key {key} in rank {rank}.") + + if isinstance(tensor, DTensor): + state_dict[key].append(tensor._local_tensor.bfloat16()) + placements = tuple(tensor.placements) + # replicated placement at ddp dimension can be discarded + if mesh_dim_names[0] == "ddp": + placements = placements[1:] + + if key not in param_placements: + param_placements[key] = placements + else: + assert param_placements[key] == placements + else: + state_dict[key].append(tensor.bfloat16()) + + del model_state_dict_lst + + for key in sorted(state_dict): + if not isinstance(state_dict[key], list): + print(f"No need to merge key {key}") + continue + + if key in param_placements: + # merge shards + placements: tuple[Shard] = param_placements[key] + if len(mesh_shape) == 1: + # 1-D list, FSDP without TP + assert len(placements) == 1 + shards = state_dict[key] + state_dict[key] = merge_by_placement(shards, placements[0]) + else: + # 2-D list, FSDP + TP + raise NotImplementedError("FSDP + TP is not supported yet.") + else: + state_dict[key] = torch.cat(state_dict[key], dim=0) + + print("Merge completed.") + hf_path = os.path.join(local_dir, "huggingface") + config: PretrainedConfig = AutoConfig.from_pretrained(hf_path) + architectures: list[str] = getattr(config, "architectures", ["Unknown"]) + + if "ForTokenClassification" in architectures[0]: + AutoClass = AutoModelForTokenClassification + elif "ForConditionalGeneration" in architectures[0]: + AutoClass = AutoModelForImageTextToText + elif "ForCausalLM" in architectures[0]: + AutoClass = AutoModelForCausalLM + else: + raise NotImplementedError(f"Unknown architecture {architectures}.") + + with torch.device("meta"): + model: PreTrainedModel = AutoClass.from_config(config, torch_dtype=torch.bfloat16) + + assert isinstance(model, PreTrainedModel) + model.to_empty(device="cpu") + + print(f"Saving model to {hf_path}...") + model.save_pretrained(hf_path, state_dict=state_dict) + del state_dict, model + + if args.hf_upload_path: + upload_model_to_huggingface(hf_path, args.hf_upload_path) diff --git a/model/EasyR1/setup.py b/model/EasyR1/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..b836e58c98f8ec15ddcfcf9f4f96daa71de0bf59 --- /dev/null +++ b/model/EasyR1/setup.py @@ -0,0 +1,61 @@ +# 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. + +import os +import re + +from setuptools import find_packages, setup + + +def get_version() -> str: + with open(os.path.join("verl", "__init__.py"), encoding="utf-8") as f: + file_content = f.read() + pattern = r"__version__\W*=\W*\"([^\"]+)\"" + (version,) = re.findall(pattern, file_content) + return version + + +def get_requires() -> list[str]: + with open("requirements.txt", encoding="utf-8") as f: + file_content = f.read() + lines = [line.strip() for line in file_content.strip().split("\n") if not line.startswith("#")] + return lines + + +extra_require = { + "dev": ["pre-commit", "ruff"], +} + + +def main(): + setup( + name="verl", + version=get_version(), + description="An Efficient, Scalable, Multi-Modality RL Training Framework based on veRL", + long_description=open("README.md", encoding="utf-8").read(), + long_description_content_type="text/markdown", + author="verl", + author_email="zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk, hiyouga@buaa.edu.cn", + license="Apache 2.0 License", + url="https://github.com/volcengine/verl", + package_dir={"": "."}, + packages=find_packages(where="."), + python_requires=">=3.9.0", + install_requires=get_requires(), + extras_require=extra_require, + ) + + +if __name__ == "__main__": + main() diff --git a/model/EasyR1/tests/check_license.py b/model/EasyR1/tests/check_license.py new file mode 100644 index 0000000000000000000000000000000000000000..4196c7a6a64a6b662bbde8f8a2550fbc111772cf --- /dev/null +++ b/model/EasyR1/tests/check_license.py @@ -0,0 +1,39 @@ +# 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. + +import sys +from pathlib import Path + + +KEYWORDS = ("Copyright", "2024", "Bytedance") + + +def main(): + path_list: list[Path] = [] + for check_dir in sys.argv[1:]: + path_list.extend(Path(check_dir).glob("**/*.py")) + + for path in path_list: + with open(path.absolute(), encoding="utf-8") as f: + file_content = f.read().strip().split("\n") + license = "\n".join(file_content[:5]) + if not license: + continue + + print(f"Check license: {path}") + assert all(keyword in license for keyword in KEYWORDS), f"File {path} does not contain license." + + +if __name__ == "__main__": + main() diff --git a/model/EasyR1/tests/test_checkpoint.py b/model/EasyR1/tests/test_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..bc94a5d6270c42d9496901365c4799cc36977be6 --- /dev/null +++ b/model/EasyR1/tests/test_checkpoint.py @@ -0,0 +1,50 @@ +# 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. + + +import json +import os +import shutil +import uuid + +import pytest + +from verl.utils.checkpoint import CHECKPOINT_TRACKER, find_latest_ckpt, remove_obsolete_ckpt + + +@pytest.fixture +def save_checkpoint_path(): + ckpt_dir = os.path.join("checkpoints", str(uuid.uuid4())) + os.makedirs(ckpt_dir, exist_ok=True) + yield ckpt_dir + shutil.rmtree(ckpt_dir, ignore_errors=True) + + +def test_find_latest_ckpt(save_checkpoint_path): + with open(os.path.join(save_checkpoint_path, CHECKPOINT_TRACKER), "w") as f: + json.dump({"last_global_step": 10}, f, ensure_ascii=False, indent=2) + + assert find_latest_ckpt(save_checkpoint_path)[0] is None + os.makedirs(os.path.join(save_checkpoint_path, "global_step_10"), exist_ok=True) + assert find_latest_ckpt(save_checkpoint_path)[0] == os.path.join(save_checkpoint_path, "global_step_10") + + +def test_remove_obsolete_ckpt(save_checkpoint_path): + for step in range(5, 30, 5): + os.makedirs(os.path.join(save_checkpoint_path, f"global_step_{step}"), exist_ok=True) + + remove_obsolete_ckpt(save_checkpoint_path, global_step=30, best_global_step=10, save_limit=3) + for step in range(5, 30, 5): + is_exist = step in [10, 25] + assert os.path.exists(os.path.join(save_checkpoint_path, f"global_step_{step}")) == is_exist diff --git a/model/EasyR1/tests/test_dataproto.py b/model/EasyR1/tests/test_dataproto.py new file mode 100644 index 0000000000000000000000000000000000000000..b1984c9b72c18ac675eb665cba0d58cb7dd28694 --- /dev/null +++ b/model/EasyR1/tests/test_dataproto.py @@ -0,0 +1,183 @@ +# 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. + + +import os +from typing import Any, Optional + +import numpy as np +import pytest +import torch + +from verl.protocol import DataProto, pad_dataproto_to_divisor, unpad_dataproto + + +def _get_data_proto( + tensors: Optional[dict[str, list[Any]]] = None, + non_tensors: Optional[dict[str, list[Any]]] = None, + meta_info: Optional[dict[str, Any]] = None, +) -> DataProto: + if tensors is None and non_tensors is None: + tensors = {"obs": [1, 2, 3, 4, 5, 6]} + non_tensors = {"labels": ["a", "b", "c", "d", "e", "f"]} + + if tensors is not None: + tensors = {k: torch.tensor(v) if not isinstance(v, torch.Tensor) else v for k, v in tensors.items()} + + if non_tensors is not None: + non_tensors = { + k: np.array(v, dtype=object) if not isinstance(v, np.ndarray) else v for k, v in non_tensors.items() + } + + meta_info = meta_info or {"info": "test_info"} + return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info) + + +def _assert_equal(data1: DataProto, data2: Optional[DataProto] = None): + data2 = data2 or _get_data_proto() + if data1.batch is not None: + assert data1.batch.keys() == data2.batch.keys() + for key in data1.batch.keys(): + assert torch.all(data1.batch[key] == data2.batch[key]) + else: + assert data2.batch is None + + if data1.non_tensor_batch is not None: + assert data1.non_tensor_batch.keys() == data2.non_tensor_batch.keys() + for key in data1.non_tensor_batch.keys(): + assert np.all(data1.non_tensor_batch[key] == data2.non_tensor_batch[key]) + else: + assert data2.non_tensor_batch is None + + assert data1.meta_info == data2.meta_info + + +def test_tensor_dict_constructor(): + obs = torch.randn(100, 10) + act = torch.randn(100, 10, 3) + data = DataProto.from_dict(tensors={"obs": obs, "act": act}) + assert len(data) == 100 + + with pytest.raises(AssertionError): + data = DataProto.from_dict(tensors={"obs": obs, "act": act}, num_batch_dims=2) + + with pytest.raises(AssertionError): + data = DataProto.from_dict(tensors={"obs": obs, "act": act}, num_batch_dims=3) + + labels = np.array(["a", "b", "c"], dtype=object) + data = DataProto.from_dict(non_tensors={"labels": labels}) + assert len(data) == 3 + + +def test_getitem(): + data = _get_data_proto() + assert data[0].batch["obs"] == torch.tensor(1) + assert data[0].non_tensor_batch["labels"] == "a" + _assert_equal(data[1:3], _get_data_proto({"obs": [2, 3]}, {"labels": ["b", "c"]})) + _assert_equal(data[[0, 2]], _get_data_proto({"obs": [1, 3]}, {"labels": ["a", "c"]})) + _assert_equal(data[torch.tensor([1])], _get_data_proto({"obs": [2]}, {"labels": ["b"]})) + + +def test_select_pop(): + obs = torch.randn(100, 10) + act = torch.randn(100, 3) + dataset = _get_data_proto(tensors={"obs": obs, "act": act}, meta_info={"p": 1, "q": 2}) + selected_dataset = dataset.select(batch_keys=["obs"], meta_info_keys=["p"]) + + assert selected_dataset.batch.keys() == {"obs"} + assert selected_dataset.meta_info.keys() == {"p"} + assert dataset.batch.keys() == {"obs", "act"} + assert dataset.meta_info.keys() == {"p", "q"} + + popped_dataset = dataset.pop(batch_keys=["obs"], meta_info_keys=["p"]) + assert popped_dataset.batch.keys() == {"obs"} + assert popped_dataset.meta_info.keys() == {"p"} + assert dataset.batch.keys() == {"act"} + assert dataset.meta_info.keys() == {"q"} + + +def test_chunk_concat_split(): + data = _get_data_proto() + with pytest.raises(AssertionError): + data.chunk(5) + + chunked_data = data.chunk(2) + + assert len(chunked_data) == 2 + expected_data = _get_data_proto({"obs": [1, 2, 3]}, {"labels": ["a", "b", "c"]}) + _assert_equal(chunked_data[0], expected_data) + + concat_data = DataProto.concat(chunked_data) + _assert_equal(concat_data, data) + + splitted_data = data.split(2) + assert len(splitted_data) == 3 + expected_data = _get_data_proto({"obs": [1, 2]}, {"labels": ["a", "b"]}) + _assert_equal(splitted_data[0], expected_data) + + +def test_reorder(): + data = _get_data_proto() + data.reorder(torch.tensor([3, 4, 2, 0, 1, 5])) + expected_data = _get_data_proto({"obs": [4, 5, 3, 1, 2, 6]}, {"labels": ["d", "e", "c", "a", "b", "f"]}) + _assert_equal(data, expected_data) + + +@pytest.mark.parametrize("interleave", [True, False]) +def test_repeat(interleave: bool): + data = _get_data_proto({"obs": [1, 2]}, {"labels": ["a", "b"]}) + repeated_data = data.repeat(repeat_times=2, interleave=interleave) + expected_tensors = {"obs": [1, 1, 2, 2] if interleave else [1, 2, 1, 2]} + expected_non_tensors = {"labels": ["a", "a", "b", "b"] if interleave else ["a", "b", "a", "b"]} + _assert_equal(repeated_data, _get_data_proto(expected_tensors, expected_non_tensors)) + + +@pytest.mark.parametrize("size_divisor", [2, 3]) +def test_dataproto_pad_unpad(size_divisor: int): + data = _get_data_proto({"obs": [1, 2, 3]}, {"labels": ["a", "b", "c"]}) + # test size_divisor=2 + padded_data, pad_size = pad_dataproto_to_divisor(data, size_divisor=size_divisor) + unpadded_data = unpad_dataproto(padded_data, pad_size=pad_size) + + if size_divisor == 2: + assert pad_size == 1 + expected_tensors = {"obs": [1, 2, 3, 1]} + expected_non_tensors = {"labels": ["a", "b", "c", "a"]} + expected_data = _get_data_proto(expected_tensors, expected_non_tensors) + else: + assert pad_size == 0 + expected_data = data + + _assert_equal(padded_data, expected_data) + _assert_equal(unpadded_data, data) + + +def test_data_proto_save_load(): + data = _get_data_proto() + data.save_to_disk("test_data.pt") + loaded_data = DataProto.load_from_disk("test_data.pt") + os.remove("test_data.pt") + _assert_equal(data, loaded_data) + + +def test_union_tensor_dict(): + obs = torch.randn(100, 10) + data1 = _get_data_proto({"obs": obs, "act": torch.randn(100, 3)}) + data2 = _get_data_proto({"obs": obs, "rew": torch.randn(100)}) + data1.union(data2) + + data1 = _get_data_proto({"obs": obs, "act": torch.randn(100, 3)}) + data2 = _get_data_proto({"obs": obs + 1, "rew": torch.randn(100)}) + with pytest.raises(ValueError): + data1.union(data2) diff --git a/model/EasyR1/tests/test_dataset.py b/model/EasyR1/tests/test_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..a35232eaa053025000fec2d308a08474806d9ad6 --- /dev/null +++ b/model/EasyR1/tests/test_dataset.py @@ -0,0 +1,57 @@ +# 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. + +import pytest +import torch +from PIL.Image import Image + +from verl.utils.dataset import RLHFDataset +from verl.utils.tokenizer import get_processor, get_tokenizer + + +@pytest.mark.parametrize("use_fast", [True, False]) +def test_image_dataset(use_fast: bool): + tokenizer = get_tokenizer("Qwen/Qwen2.5-VL-7B-Instruct", use_fast=use_fast) + processor = get_processor("Qwen/Qwen2.5-VL-7B-Instruct", use_fast=use_fast) + dataset = RLHFDataset( + data_path="hiyouga/geometry3k@test", + tokenizer=tokenizer, + processor=processor, + prompt_key="problem", + answer_key="answer", + image_key="images", + max_prompt_length=16, + truncation="right", + filter_overlong_prompts=False, + ) + token_ids = [151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 151652, 151655] + assert set(dataset[0].keys()) == { + "input_ids", + "attention_mask", + "position_ids", + "raw_prompt_ids", + "ground_truth", + "multi_modal_data", + } + assert torch.all(dataset[0]["input_ids"] == torch.tensor(token_ids)) + assert torch.all(dataset[0]["attention_mask"] == torch.ones(16)) + assert torch.all(dataset[0]["position_ids"] == torch.arange(16).unsqueeze(0).expand(4, -1)) + assert list(dataset[0]["position_ids"].size()) == [4, 16] # avoid fake positive caused by broadcasting + assert dataset[0]["raw_prompt_ids"] == token_ids + assert dataset[0]["ground_truth"] == "48" + assert isinstance(dataset[0]["multi_modal_data"]["images"][0], Image) + + +if __name__ == "__main__": + test_image_dataset() diff --git a/model/EasyR1/tests/test_dynamic_batch.py b/model/EasyR1/tests/test_dynamic_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..3c94ee215ed3671841f980d8841b3d959bf2e145 --- /dev/null +++ b/model/EasyR1/tests/test_dynamic_batch.py @@ -0,0 +1,78 @@ +# 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. + +import numpy as np +import torch + +from verl.protocol import DataProto +from verl.utils.seqlen_balancing import prepare_dynamic_batch, restore_dynamic_batch + + +def _create_random_mask( + input_ids: torch.Tensor, + max_ratio_of_valid_token: float, + max_ratio_of_left_padding: float, + min_ratio_of_valid_token: float = 0, +) -> torch.Tensor: + """Create a random mask given input_ids. Support left padding and right padding. + + Process: + - Sample valid token length + - Sample left_padding length + - Generate padding + + Args: + input_ids: + shape (batch_size, seq_len) + + Returns: + mask: + shape (batch_size, seq_len) + """ + assert max_ratio_of_valid_token > 0 and max_ratio_of_valid_token <= 1.0 + assert max_ratio_of_left_padding >= 0 and max_ratio_of_left_padding < 1.0 + assert min_ratio_of_valid_token <= max_ratio_of_valid_token + + batch_size, sequence_length = input_ids.shape + max_num_valid_tokens = int(sequence_length * max_ratio_of_valid_token) + min_num_valid_tokens = max(1, int(sequence_length * min_ratio_of_valid_token)) + max_left_padding = int(sequence_length * max_ratio_of_left_padding) + assert max_num_valid_tokens + max_left_padding <= sequence_length + assert max_num_valid_tokens > 0 and max_ratio_of_valid_token <= sequence_length + mask = torch.ones_like(input_ids, dtype=torch.int64) + # TODO: we can make this faster + for i in range(batch_size): + num_left_padding = np.random.randint(low=0, high=max_left_padding + 1, dtype=np.int64) + num_valid = np.random.randint(low=min_num_valid_tokens, high=max_num_valid_tokens + 1, dtype=np.int64) + + for index in range(num_left_padding): + mask[i, index] = 0 + + for index in range(num_left_padding + num_valid, sequence_length): + mask[i, index] = 0 + + return mask + + +def test_dynamic_batch(): + input_ids = torch.randint(low=0, high=10, size=(20, 100)) + attention_mask = _create_random_mask( + input_ids=input_ids, max_ratio_of_left_padding=0.1, max_ratio_of_valid_token=0.9, min_ratio_of_valid_token=0.5 + ) + data = {"input_ids": input_ids, "attention_mask": attention_mask} + dataproto = DataProto.from_single_dict(data) + micro_batches, micro_bsz_idx_lst = prepare_dynamic_batch(dataproto, max_token_len=300) + input_ids = torch.cat([micro_batch.batch["input_ids"] for micro_batch in micro_batches], dim=0) + input_ids = restore_dynamic_batch(input_ids, micro_bsz_idx_lst) + torch.testing.assert_close(input_ids, dataproto.batch["input_ids"]) diff --git a/model/EasyR1/verl.egg-info/PKG-INFO b/model/EasyR1/verl.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..e66dfb0ad5a063eb34f998d17d55273201d736b0 --- /dev/null +++ b/model/EasyR1/verl.egg-info/PKG-INFO @@ -0,0 +1,279 @@ +Metadata-Version: 2.4 +Name: verl +Version: 0.3.3.dev0 +Summary: An Efficient, Scalable, Multi-Modality RL Training Framework based on veRL +Home-page: https://github.com/volcengine/verl +Author: verl +Author-email: zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk, hiyouga@buaa.edu.cn +License: Apache 2.0 License +Requires-Python: >=3.9.0 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: accelerate +Requires-Dist: codetiming +Requires-Dist: datasets +Requires-Dist: liger-kernel +Requires-Dist: mathruler +Requires-Dist: numpy +Requires-Dist: omegaconf +Requires-Dist: pandas +Requires-Dist: peft +Requires-Dist: pillow +Requires-Dist: pyarrow>=15.0.0 +Requires-Dist: pylatexenc +Requires-Dist: qwen-vl-utils +Requires-Dist: ray[default] +Requires-Dist: tensordict +Requires-Dist: torchdata +Requires-Dist: wandb +Provides-Extra: dev +Requires-Dist: pre-commit; extra == "dev" +Requires-Dist: ruff; extra == "dev" +Dynamic: author +Dynamic: author-email +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +# EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework + +[![GitHub Repo stars](https://img.shields.io/github/stars/hiyouga/EasyR1)](https://github.com/hiyouga/EasyR1/stargazers) +[![Twitter](https://img.shields.io/twitter/follow/llamafactory_ai)](https://twitter.com/llamafactory_ai) +[![Docker Pulls](https://img.shields.io/docker/pulls/hiyouga/verl)](https://hub.docker.com/r/hiyouga/verl/tags) + +### Used by [Amazon Web Services](https://aws.amazon.com/cn/blogs/china/building-llm-model-hub-based-on-llamafactory-and-easyr1/) + +This project is a clean fork of the original [veRL](https://github.com/volcengine/verl) project to support vision language models, we thank all the authors for providing such a high-performance RL training framework. + +EasyR1 is efficient and scalable due to the design of **[HybirdEngine](https://arxiv.org/abs/2409.19256)** and the latest release of **[vLLM](https://github.com/vllm-project/vllm)**'s SPMD mode. + +## Features + +- Supported models + - Llama3/Qwen2/Qwen2.5/Qwen3 language models + - Qwen2-VL/Qwen2.5-VL/Qwen3-VL vision language models + - DeepSeek-R1 distill models + +- Supported algorithms + - GRPO + - DAPO + - Reinforce++ + - ReMax + - RLOO + +- Supported datasets + - Any text, vision-text dataset in a [specific format](#custom-dataset) + +- Supported tricks + - Padding-free training + - Resuming from the latest/best checkpoint + - Wandb & SwanLab & Mlflow & Tensorboard tracking + +## Requirements + +### Software Requirements + +- Python 3.9+ +- transformers>=4.54.0 +- flash-attn>=2.4.3 +- vllm>=0.8.3 + +We provide a [Dockerfile](./Dockerfile) to easily build environments. + +We recommend using the [pre-built docker image](https://hub.docker.com/r/hiyouga/verl) in EasyR1. + +```bash +docker pull hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0 +docker run -it --ipc=host --gpus=all hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0 +``` + +If your environment does not support Docker, you can consider using **Apptainer**: + +```bash +apptainer pull easyr1.sif docker://hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0 +apptainer shell --nv --cleanenv --bind /mnt/your_dir:/mnt/your_dir easyr1.sif +``` + +Use `USE_MODELSCOPE_HUB=1` to download models from the ModelScope hub. + +### Hardware Requirements + +\* *estimated* + +| Method | Bits | 1.5B | 3B | 7B | 32B | 72B | +| ------------------------ | ---- | ------ | ------ | ------ | ------- | ------- | +| GRPO Full Fine-Tuning | AMP | 2*24GB | 4*40GB | 8*40GB | 16*80GB | 32*80GB | +| GRPO Full Fine-Tuning | BF16 | 1*24GB | 1*40GB | 4*40GB | 8*80GB | 16*80GB | + +> [!NOTE] +> Use `worker.actor.fsdp.torch_dtype=bf16` and `worker.actor.optim.strategy=adamw_bf16` to enable bf16 training. +> +> We are working hard to reduce the VRAM in RL training, LoRA support will be integrated in next updates. + +## Tutorial: Run Qwen2.5-VL GRPO on [Geometry3K](https://huggingface.co/datasets/hiyouga/geometry3k) Dataset in Just 3 Steps + +![image](assets/qwen2_5_vl_7b_geo.png) + +### Installation + +```bash +git clone https://github.com/hiyouga/EasyR1.git +cd EasyR1 +pip install -e . +``` + +### GRPO Training + +```bash +bash examples/qwen2_5_vl_7b_geo3k_grpo.sh +``` + +### Merge Checkpoint in Hugging Face Format + +```bash +python3 scripts/model_merger.py --local_dir checkpoints/easy_r1/exp_name/global_step_1/actor +``` + +> [!TIP] +> If you encounter issues with connecting to Hugging Face, consider using `export HF_ENDPOINT=https://hf-mirror.com`. +> +> If you want to use SwanLab logger, consider using `bash examples/qwen2_5_vl_7b_geo3k_swanlab.sh`. + +## Custom Dataset + +Please refer to the example datasets to prepare your own dataset. + +- Text dataset: https://huggingface.co/datasets/hiyouga/math12k +- Image-text dataset: https://huggingface.co/datasets/hiyouga/geometry3k +- Multi-image-text dataset: https://huggingface.co/datasets/hiyouga/journeybench-multi-image-vqa +- Text-image mixed dataset: https://huggingface.co/datasets/hiyouga/rl-mixed-dataset + +## How to Understand GRPO in EasyR1 + +![image](assets/easyr1_grpo.png) + +- To learn about the GRPO algorithm, you can refer to [Hugging Face's blog](https://huggingface.co/docs/trl/v0.16.1/en/grpo_trainer). + +## How to Run 70B+ Model in Multi-node Environment + +1. Start the Ray head node. + +```bash +ray start --head --port=6379 --dashboard-host=0.0.0.0 +``` + +2. Start the Ray worker node and connect to the head node. + +```bash +ray start --address=:6379 +``` + +3. Check the Ray resource pool. + +```bash +ray status +``` + +4. Run training script on the Ray head node only. + +```bash +bash examples/qwen2_5_vl_7b_geo3k_grpo.sh +``` + +See the **[veRL's official doc](https://verl.readthedocs.io/en/latest/start/multinode.html)** for more details about multi-node training and Ray debugger. + +## Other Baselines + +We also reproduced the following two baselines of the [R1-V](https://github.com/deep-agent/R1-V) project. +- [CLEVR-70k-Counting](examples/baselines/qwen2_5_vl_3b_clevr.sh): Train the Qwen2.5-VL-3B-Instruct model on counting problem. +- [GeoQA-8k](examples/baselines/qwen2_5_vl_3b_geoqa8k.sh): Train the Qwen2.5-VL-3B-Instruct model on GeoQA problem. + +## Performance Baselines + +See [baselines.md](assets/baselines.md). + +## Awesome Work using EasyR1 + +- **MMR1**: Enhancing Multimodal Reasoning with Variance-Aware Sampling and Open Resources. [![[code]](https://img.shields.io/github/stars/LengSicong/MMR1)](https://github.com/LengSicong/MMR1) [![[arxiv]](https://img.shields.io/badge/arxiv-2509.21268-blue)](https://arxiv.org/abs/2509.21268) +- **Vision-R1**: Incentivizing Reasoning Capability in Multimodal Large Language Models. [![[code]](https://img.shields.io/github/stars/Osilly/Vision-R1)](https://github.com/Osilly/Vision-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.06749-blue)](https://arxiv.org/abs/2503.06749) +- **Seg-Zero**: Reasoning-Chain Guided Segmentation via Cognitive Reinforcement. [![[code]](https://img.shields.io/github/stars/dvlab-research/Seg-Zero)](https://github.com/dvlab-research/Seg-Zero) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.06520-blue)](https://arxiv.org/abs/2503.06520) +- **MetaSpatial**: Reinforcing 3D Spatial Reasoning in VLMs for the Metaverse. [![[code]](https://img.shields.io/github/stars/PzySeere/MetaSpatial)](https://github.com/PzySeere/MetaSpatial) [![[arxiv]](https://img.shields.io/badge/arxiv-2503.18470-blue)](https://arxiv.org/abs/2503.18470) +- **Temporal-R1**: Envolving Temporal Reasoning Capability into LMMs via Temporal Consistent Reward. [![[code]](https://img.shields.io/github/stars/appletea233/Temporal-R1)](https://github.com/appletea233/Temporal-R1) +- **NoisyRollout**: Reinforcing Visual Reasoning with Data Augmentation. [![[code]](https://img.shields.io/github/stars/John-AI-Lab/NoisyRollout)](https://github.com/John-AI-Lab/NoisyRollout) [![[arxiv]](https://img.shields.io/badge/arxiv-2504.13055-blue)](https://arxiv.org/pdf/2504.13055) +- **GUI-R1**: A Generalist R1-Style Vision-Language Action Model For GUI Agents. [![[code]](https://img.shields.io/github/stars/ritzz-ai/GUI-R1)](https://github.com/ritzz-ai/GUI-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2504.10458-blue)](https://arxiv.org/abs/2504.10458) +- **R1-Track**: Direct Application of MLLMs to Visual Object Tracking via Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/Wangbiao2/R1-Track)](https://github.com/Wangbiao2/R1-Track) +- **VisionReasoner**: Unified Visual Perception and Reasoning via Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/dvlab-research/VisionReasoner)](https://github.com/dvlab-research/VisionReasoner) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.12081-blue)](https://arxiv.org/abs/2505.12081) +- **MM-UPT**: Unsupervised Post-Training for Multi-Modal LLM Reasoning via GRPO. [![[code]](https://img.shields.io/github/stars/waltonfuture/MM-UPT)](https://github.com/waltonfuture/MM-UPT) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22453-blue)](https://arxiv.org/pdf/2505.22453) +- **RL-with-Cold-Start**: Advancing Multimodal Reasoning via Reinforcement Learning with Cold Start. [![[code]](https://img.shields.io/github/stars/waltonfuture/RL-with-Cold-Start)](https://github.com/waltonfuture/RL-with-Cold-Start) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22334-blue)](https://arxiv.org/pdf/2505.22334) +- **ViGoRL**: Grounded Reinforcement Learning for Visual Reasoning. [![[code]](https://img.shields.io/github/stars/Gabesarch/grounded-rl)](https://github.com/Gabesarch/grounded-rl) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.22334-blue)](https://arxiv.org/abs/2505.23678) +- **Revisual-R1**: Advancing Multimodal Reasoning: From Optimized Cold Start to Staged Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/CSfufu/Revisual-R1)](https://github.com/CSfufu/Revisual-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2506.04207-blue)](https://arxiv.org/abs/2506.04207) +- **SophiaVL-R1**: Reinforcing MLLMs Reasoning with Thinking Reward. [![[code]](https://img.shields.io/github/stars/kxfan2002/SophiaVL-R1)](https://github.com/kxfan2002/SophiaVL-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.17018-blue)](https://arxiv.org/abs/2505.17018) +- **Vision-Matters**: Simple Visual Perturbations Can Boost Multimodal Math Reasoning. [![[code]](https://img.shields.io/github/stars/YutingLi0606/Vision-Matters)](https://github.com/YutingLi0606/Vision-Matters) [![[arxiv]](https://img.shields.io/badge/arxiv-2506.09736-blue)](https://arxiv.org/abs/2506.09736) +- **VTool-R1**: VLMs Learn to Think with Images via Reinforcement Learning on Multimodal Tool Use. [![[code]](https://img.shields.io/github/stars/VTOOL-R1/vtool-r1)](https://github.com/VTOOL-R1/vtool-r1) [![[arxiv]](https://img.shields.io/badge/arxiv-2505.19255-blue)](https://arxiv.org/abs/2505.19255) +- **Long-RL**: Scaling RL to Long Sequences. [![[code]](https://img.shields.io/github/stars/NVlabs/Long-RL)](https://github.com/NVlabs/Long-RL) [![[arxiv]](https://img.shields.io/badge/arxiv-2507.07966-blue)](https://arxiv.org/abs/2507.07966) +- **EditGRPO**: Reinforcement Learning with Post-Rollout Edits for Clinically Accurate Chest X-Ray Report Generation. [![[code]](https://img.shields.io/github/stars/taokz/EditGRPO)](https://github.com/taokz/EditGRPO) + +## TODO + +- Support LoRA (high priority). +- Support ulysses parallelism for VLMs (middle priority). +- Support more VLM architectures. + +> [!NOTE] +> We will not provide scripts for supervised fine-tuning and inference in this project. If you have such requirements, we recommend using [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory). + +### Known bugs + +These features are temporarily disabled for now, we plan to fix them one-by-one in the future updates. + +- Vision language models are not compatible with ulysses parallelism yet. + +## Discussion Group + +👋 Join our [WeChat group](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/easyr1.jpg). + +## FAQs + +> ValueError: Image features and image tokens do not match: tokens: 8192, features 9800 + +Increase the `data.max_prompt_length` or reduce the `data.max_pixels`. + +> RuntimeError: CUDA Error: out of memory at /workspace/csrc/cumem_allocator.cpp:62 + +Reduce the `worker.rollout.gpu_memory_utilization` and enable `worker.actor.offload.offload_params`. + +> RuntimeError: 0 active drivers ([]). There should only be one. + +Uninstall `deepspeed` from the current python environment. + +## Citation + +Core contributors: [Yaowei Zheng](https://github.com/hiyouga), [Junting Lu](https://github.com/AL-377), [Shenzhi Wang](https://github.com/Shenzhi-Wang), [Zhangchi Feng](https://github.com/BUAADreamer), [Dongdong Kuang](https://github.com/Kuangdd01) and Yuwen Xiong + +We also thank Guangming Sheng and Chi Zhang for helpful discussions. + +```bibtex +@misc{zheng2025easyr1, + title = {EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework}, + author = {Yaowei Zheng, Junting Lu, Shenzhi Wang, Zhangchi Feng, Dongdong Kuang, Yuwen Xiong}, + howpublished = {\url{https://github.com/hiyouga/EasyR1}}, + year = {2025} +} +``` + +We recommend to also cite the original work. + +```bibtex +@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} +} +``` diff --git a/model/EasyR1/verl.egg-info/SOURCES.txt b/model/EasyR1/verl.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..90fe1d40180051b7c1c5795888f6ec2656951ee8 --- /dev/null +++ b/model/EasyR1/verl.egg-info/SOURCES.txt @@ -0,0 +1,155 @@ +LICENSE +README.md +pyproject.toml +setup.py +./verl/__init__.py +./verl/protocol.py +./verl/models/__init__.py +./verl/models/monkey_patch.py +./verl/models/transformers/__init__.py +./verl/models/transformers/flash_attention_utils.py +./verl/models/transformers/qwen2_vl.py +./verl/models/transformers/qwen3_vl.py +./verl/reward_function/__init__.py +./verl/reward_function/dapo.py +./verl/reward_function/math.py +./verl/reward_function/onethinker_reward.py +./verl/reward_function/r1v.py +./verl/single_controller/__init__.py +./verl/single_controller/base/__init__.py +./verl/single_controller/base/decorator.py +./verl/single_controller/base/worker.py +./verl/single_controller/base/worker_group.py +./verl/single_controller/base/register_center/__init__.py +./verl/single_controller/base/register_center/ray.py +./verl/single_controller/ray/__init__.py +./verl/single_controller/ray/base.py +./verl/trainer/__init__.py +./verl/trainer/config.py +./verl/trainer/core_algos.py +./verl/trainer/data_loader.py +./verl/trainer/main.py +./verl/trainer/metrics.py +./verl/trainer/ray_trainer.py +./verl/utils/__init__.py +./verl/utils/dataset.py +./verl/utils/flops_counter.py +./verl/utils/fsdp_utils.py +./verl/utils/model_utils.py +./verl/utils/py_functional.py +./verl/utils/seqlen_balancing.py +./verl/utils/tokenizer.py +./verl/utils/torch_dtypes.py +./verl/utils/torch_functional.py +./verl/utils/ulysses.py +./verl/utils/checkpoint/__init__.py +./verl/utils/checkpoint/checkpoint_manager.py +./verl/utils/checkpoint/fsdp_checkpoint_manager.py +./verl/utils/logger/__init__.py +./verl/utils/logger/gen_logger.py +./verl/utils/logger/logger.py +./verl/workers/__init__.py +./verl/workers/config.py +./verl/workers/fsdp_workers.py +./verl/workers/protocol_original.py +./verl/workers/actor/__init__.py +./verl/workers/actor/base.py +./verl/workers/actor/config.py +./verl/workers/actor/dp_actor.py +./verl/workers/critic/__init__.py +./verl/workers/critic/base.py +./verl/workers/critic/config.py +./verl/workers/critic/dp_critic.py +./verl/workers/reward/__init__.py +./verl/workers/reward/config.py +./verl/workers/reward/function.py +./verl/workers/reward/model_reward.py +./verl/workers/rollout/__init__.py +./verl/workers/rollout/base.py +./verl/workers/rollout/config.py +./verl/workers/rollout/vllm_rollout_spmd.py +./verl/workers/rollout/vllm_rollout_spmd_new.py +./verl/workers/sharding_manager/__init__.py +./verl/workers/sharding_manager/base.py +./verl/workers/sharding_manager/fsdp_ulysses.py +./verl/workers/sharding_manager/fsdp_vllm.py +tests/test_checkpoint.py +tests/test_dataproto.py +tests/test_dataset.py +tests/test_dynamic_batch.py +verl/__init__.py +verl/protocol.py +verl.egg-info/PKG-INFO +verl.egg-info/SOURCES.txt +verl.egg-info/dependency_links.txt +verl.egg-info/requires.txt +verl.egg-info/top_level.txt +verl/models/__init__.py +verl/models/monkey_patch.py +verl/models/transformers/__init__.py +verl/models/transformers/flash_attention_utils.py +verl/models/transformers/qwen2_vl.py +verl/models/transformers/qwen3_vl.py +verl/reward_function/__init__.py +verl/reward_function/dapo.py +verl/reward_function/math.py +verl/reward_function/onethinker_reward.py +verl/reward_function/r1v.py +verl/single_controller/__init__.py +verl/single_controller/base/__init__.py +verl/single_controller/base/decorator.py +verl/single_controller/base/worker.py +verl/single_controller/base/worker_group.py +verl/single_controller/base/register_center/__init__.py +verl/single_controller/base/register_center/ray.py +verl/single_controller/ray/__init__.py +verl/single_controller/ray/base.py +verl/trainer/__init__.py +verl/trainer/config.py +verl/trainer/core_algos.py +verl/trainer/data_loader.py +verl/trainer/main.py +verl/trainer/metrics.py +verl/trainer/ray_trainer.py +verl/utils/__init__.py +verl/utils/dataset.py +verl/utils/flops_counter.py +verl/utils/fsdp_utils.py +verl/utils/model_utils.py +verl/utils/py_functional.py +verl/utils/seqlen_balancing.py +verl/utils/tokenizer.py +verl/utils/torch_dtypes.py +verl/utils/torch_functional.py +verl/utils/ulysses.py +verl/utils/checkpoint/__init__.py +verl/utils/checkpoint/checkpoint_manager.py +verl/utils/checkpoint/fsdp_checkpoint_manager.py +verl/utils/logger/__init__.py +verl/utils/logger/gen_logger.py +verl/utils/logger/logger.py +verl/workers/__init__.py +verl/workers/config.py +verl/workers/fsdp_workers.py +verl/workers/protocol_original.py +verl/workers/actor/__init__.py +verl/workers/actor/base.py +verl/workers/actor/config.py +verl/workers/actor/dp_actor.py +verl/workers/critic/__init__.py +verl/workers/critic/base.py +verl/workers/critic/config.py +verl/workers/critic/dp_critic.py +verl/workers/reward/__init__.py +verl/workers/reward/config.py +verl/workers/reward/function.py +verl/workers/reward/model_reward.py +verl/workers/rollout/__init__.py +verl/workers/rollout/base.py +verl/workers/rollout/config.py +verl/workers/rollout/vllm_rollout_spmd.py +verl/workers/rollout/vllm_rollout_spmd_new.py +verl/workers/sharding_manager/__init__.py +verl/workers/sharding_manager/base.py +verl/workers/sharding_manager/fsdp_ulysses.py +verl/workers/sharding_manager/fsdp_vllm.py \ No newline at end of file diff --git a/model/EasyR1/verl.egg-info/dependency_links.txt b/model/EasyR1/verl.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/model/EasyR1/verl.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/model/EasyR1/verl.egg-info/requires.txt b/model/EasyR1/verl.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..47b82b288eef5a8d3944a277cabce23026e2f4e5 --- /dev/null +++ b/model/EasyR1/verl.egg-info/requires.txt @@ -0,0 +1,21 @@ +accelerate +codetiming +datasets +liger-kernel +mathruler +numpy +omegaconf +pandas +peft +pillow +pyarrow>=15.0.0 +pylatexenc +qwen-vl-utils +ray[default] +tensordict +torchdata +wandb + +[dev] +pre-commit +ruff diff --git a/model/EasyR1/verl.egg-info/top_level.txt b/model/EasyR1/verl.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..7258c86b3665f4d69215308ad2d9e26e791da623 --- /dev/null +++ b/model/EasyR1/verl.egg-info/top_level.txt @@ -0,0 +1 @@ +verl diff --git a/model/EasyR1/verl/__init__.py b/model/EasyR1/verl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fb0cd6c4de9be1eae813dda982eae3c732b56156 --- /dev/null +++ b/model/EasyR1/verl/__init__.py @@ -0,0 +1,32 @@ +# 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. + +import os + +from .utils.py_functional import is_package_available + + +if is_package_available("modelscope"): + from modelscope.utils.hf_util import patch_hub # type: ignore + + +__version__ = "0.3.3.dev0" + + +if os.getenv("USE_MODELSCOPE_HUB", "0").lower() in ["true", "y", "1"]: + # Patch hub to download models from modelscope to speed up. + if not is_package_available("modelscope"): + raise ImportError("You are using the modelscope hub, please install modelscope by `pip install modelscope`.") + + patch_hub() diff --git a/model/EasyR1/verl/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..291397c7344bcff5a8daf964574df2dbc29c9303 Binary files /dev/null and b/model/EasyR1/verl/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/__pycache__/protocol.cpython-311.pyc b/model/EasyR1/verl/__pycache__/protocol.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20418b6f2673356c27769dea735808309b2345c5 Binary files /dev/null and b/model/EasyR1/verl/__pycache__/protocol.cpython-311.pyc differ diff --git a/model/EasyR1/verl/models/__init__.py b/model/EasyR1/verl/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce90c5eb352d85c59105c0dc85b5f1dd576f095 --- /dev/null +++ b/model/EasyR1/verl/models/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/model/EasyR1/verl/models/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/models/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb971f7324d436c27c7c055784e272e2a1e7a0b7 Binary files /dev/null and b/model/EasyR1/verl/models/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/models/__pycache__/monkey_patch.cpython-311.pyc b/model/EasyR1/verl/models/__pycache__/monkey_patch.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40a2927b5c34d20ab5293fb9f838b7b6d23c7b4d Binary files /dev/null and b/model/EasyR1/verl/models/__pycache__/monkey_patch.cpython-311.pyc differ diff --git a/model/EasyR1/verl/models/monkey_patch.py b/model/EasyR1/verl/models/monkey_patch.py new file mode 100644 index 0000000000000000000000000000000000000000..ccabc73b9046497fa7bf59ed57dd418981f42033 --- /dev/null +++ b/model/EasyR1/verl/models/monkey_patch.py @@ -0,0 +1,80 @@ +# 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. + +from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS + +from ..utils.py_functional import is_transformers_version_greater_than +from .transformers.flash_attention_utils import flash_attention_forward + + +SUPPORTED_MODEL_TYPE = ( + "llama", + "gemma", + "gemma2", + "mistral", + "qwen2", + "qwen2_moe", + "qwen3", + "qwen3_moe", + "qwen2_vl", + "qwen2_5_vl", + "qwen3_vl", + "qwen3_vl_moe", +) + +QWEN2_VL_MODELS = ("qwen2_vl", "qwen2_5_vl") +QWEN3_VL_MODELS = ("qwen3_vl", "qwen3_vl_moe") + + +def apply_ulysses_patch(model_type: str) -> None: + if not is_transformers_version_greater_than("4.54.0"): + raise RuntimeError("Only support transformers >= 4.54.0.") + + + if model_type in SUPPORTED_MODEL_TYPE: + ALL_ATTENTION_FUNCTIONS["flash_attention_2"] = flash_attention_forward + else: + #model_type = "qwen2_5_vl" + raise NotImplementedError(f"Model architecture {model_type} is not supported yet.") + + if model_type in QWEN2_VL_MODELS: + from transformers.models.qwen2_5_vl.modeling_qwen2_5_vl import ( + Qwen2_5_VLForConditionalGeneration, + Qwen2_5_VLModel, + ) + from transformers.models.qwen2_vl.modeling_qwen2_vl import Qwen2VLForConditionalGeneration, Qwen2VLModel + + from .transformers.qwen2_vl import qwen2_vl_base_forward, qwen2_vl_model_forward + + # fix text-image mixed data + Qwen2VLModel.forward = qwen2_vl_base_forward + Qwen2_5_VLModel.forward = qwen2_vl_base_forward + # TODO: add linear cross entropy kernels + Qwen2VLForConditionalGeneration.forward = qwen2_vl_model_forward + Qwen2_5_VLForConditionalGeneration.forward = qwen2_vl_model_forward + elif model_type in QWEN3_VL_MODELS: + from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLForConditionalGeneration, Qwen3VLModel + from transformers.models.qwen3_vl_moe.modeling_qwen3_vl_moe import ( + Qwen3VLMoeForConditionalGeneration, + Qwen3VLMoeModel, + ) + + from .transformers.qwen3_vl import qwen3_vl_base_forward, qwen3_vl_model_forward + + # fix text-image mixed data + Qwen3VLModel.forward = qwen3_vl_base_forward + Qwen3VLMoeModel.forward = qwen3_vl_base_forward + # TODO: add linear cross entropy kernels + Qwen3VLForConditionalGeneration.forward = qwen3_vl_model_forward + Qwen3VLMoeForConditionalGeneration.forward = qwen3_vl_model_forward diff --git a/model/EasyR1/verl/models/transformers/__init__.py b/model/EasyR1/verl/models/transformers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce90c5eb352d85c59105c0dc85b5f1dd576f095 --- /dev/null +++ b/model/EasyR1/verl/models/transformers/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/model/EasyR1/verl/models/transformers/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/models/transformers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c07eb7f0982f261a3a0af1542930bae28a66dd0 Binary files /dev/null and b/model/EasyR1/verl/models/transformers/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/models/transformers/__pycache__/flash_attention_utils.cpython-311.pyc b/model/EasyR1/verl/models/transformers/__pycache__/flash_attention_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efe07c81166042e03e3b9e5bab515c9ed1c78066 Binary files /dev/null and b/model/EasyR1/verl/models/transformers/__pycache__/flash_attention_utils.cpython-311.pyc differ diff --git a/model/EasyR1/verl/models/transformers/__pycache__/qwen3_vl.cpython-311.pyc b/model/EasyR1/verl/models/transformers/__pycache__/qwen3_vl.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85b84dc4eb8202431b826a1ae82704ed91f232d7 Binary files /dev/null and b/model/EasyR1/verl/models/transformers/__pycache__/qwen3_vl.cpython-311.pyc differ diff --git a/model/EasyR1/verl/models/transformers/flash_attention_utils.py b/model/EasyR1/verl/models/transformers/flash_attention_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6ca119a959717f4ae607d97312487bd9a0a0090f --- /dev/null +++ b/model/EasyR1/verl/models/transformers/flash_attention_utils.py @@ -0,0 +1,185 @@ +# Copyright 2024 The Fairseq Authors and the HuggingFace Inc. team +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# Based on https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/modeling_flash_attention_utils.py +# +# 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. + +import inspect +import os +from typing import Optional, Tuple + +import torch +import torch.distributed as dist +from transformers.modeling_flash_attention_utils import _flash_attention_forward, fa_peft_integration_check +from transformers.utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10 + +from ...utils.ulysses import ( + gather_heads_scatter_seq, + gather_seq_scatter_heads, + get_ulysses_sequence_parallel_group, + get_ulysses_sequence_parallel_world_size, +) + + +if is_flash_attn_2_available(): + from flash_attn import flash_attn_func, flash_attn_varlen_func + + _flash_supports_window_size = "window_size" in inspect.signature(flash_attn_func).parameters + _flash_supports_deterministic = "deterministic" in inspect.signature(flash_attn_func).parameters + _flash_deterministic_enabled = os.getenv("FLASH_ATTENTION_DETERMINISTIC", "0") == "1" + _flash_use_top_left_mask = not is_flash_attn_greater_or_equal_2_10() + + +def prepare_fa2_from_position_ids( + query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, position_ids: torch.Tensor +): + assert position_ids.ndim == 2 # (batch_size, seq_length) + query = query.contiguous().view(-1, query.size(-2), query.size(-1)) + key = key.contiguous().view(-1, key.size(-2), key.size(-1)) + value = value.contiguous().view(-1, value.size(-2), value.size(-1)) + tensor_kwargs = {"dtype": torch.int32, "device": position_ids.device} + position_ids = position_ids.view(-1) + cu_seqlens = torch.cat( + ( + (position_ids == 0).nonzero().view(-1).to(**tensor_kwargs), + torch.tensor(position_ids.size(), **tensor_kwargs), + ) + ) + max_length = cu_seqlens.diff().max() # use cu_seqlens to infer max_length for qwen2vl mrope + return (query, key, value, (cu_seqlens, cu_seqlens), (max_length, max_length)) + + +def _custom_flash_attention_forward( + query_states: torch.Tensor, + key_states: torch.Tensor, + value_states: torch.Tensor, + attention_mask: Optional[torch.Tensor], + query_length: int, + is_causal: bool = True, + position_ids: Optional[torch.Tensor] = None, + sliding_window: Optional[int] = None, + use_top_left_mask: bool = False, + deterministic: Optional[bool] = None, + **kwargs, +): + """ + Patches flash attention forward to handle 3D position ids in mrope. (3, batch_size, seq_length) + """ + # Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length). + use_sliding_windows = ( + _flash_supports_window_size and sliding_window is not None and key_states.shape[1] > sliding_window + ) + flash_kwargs = {"window_size": (sliding_window, sliding_window)} if use_sliding_windows else {} + + if _flash_supports_deterministic: + flash_kwargs["deterministic"] = deterministic if deterministic is not None else _flash_deterministic_enabled + + if kwargs.get("softcap") is not None: + flash_kwargs["softcap"] = kwargs.pop("softcap") + + query_states, key_states, value_states = fa_peft_integration_check( + query_states, key_states, value_states, target_dtype=torch.bfloat16 + ) + + sp_size = get_ulysses_sequence_parallel_world_size() + if sp_size > 1: + # qkv: (batch_size, seq_length / sp_size, num_head, head_size) + query_states = gather_seq_scatter_heads(query_states, seq_dim=1, head_dim=2) + key_states = gather_seq_scatter_heads(key_states, seq_dim=1, head_dim=2) + value_states = gather_seq_scatter_heads(value_states, seq_dim=1, head_dim=2) + position_ids_lst = [torch.empty_like(position_ids) for _ in range(sp_size)] + position_ids = dist.all_gather(position_ids_lst, position_ids, group=get_ulysses_sequence_parallel_group()) + position_ids = torch.cat(position_ids_lst, dim=-1) # (batch_size, seq_length) + + if position_ids is not None and query_length != 1 and not (torch.diff(position_ids, dim=-1) >= 0).all(): + batch_size = query_states.size(0) + q, k, v, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_q, max_seqlen_k) = prepare_fa2_from_position_ids( + query_states, key_states, value_states, position_ids + ) + attn_output = flash_attn_varlen_func( + q, + k, + v, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + dropout_p=kwargs.pop("dropout", 0.0), + softmax_scale=kwargs.pop("softmax_scale", None), + causal=is_causal, + **flash_kwargs, + ) + attn_output = attn_output.view(batch_size, -1, attn_output.size(-2), attn_output.size(-1)) + else: + attn_output = _flash_attention_forward( + query_states, + key_states, + value_states, + attention_mask, + query_length, + is_causal=is_causal, + position_ids=position_ids, + sliding_window=sliding_window, + use_top_left_mask=use_top_left_mask, + deterministic=deterministic, + **kwargs, + ) + + if sp_size > 1: + # output: (batch_size, seq_length / sp_size, num_head, head_size) + attn_output = gather_heads_scatter_seq(attn_output, head_dim=2, seq_dim=1) + + return attn_output + + +def flash_attention_forward( + module: torch.nn.Module, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attention_mask: Optional[torch.Tensor], + dropout: float = 0.0, + scaling: Optional[float] = None, + sliding_window: Optional[int] = None, + softcap: Optional[float] = None, + **kwargs, +) -> Tuple[torch.Tensor, None]: + # This is before the transpose + q_len = query.shape[2] + + # FA2 uses non-transposed inputs + query = query.transpose(1, 2) + key = key.transpose(1, 2) + value = value.transpose(1, 2) + + # FA2 uses the kwargs value if explicitly passed, otherwise it uses the module attribute + is_causal = kwargs.pop("is_causal", None) + if is_causal is None: + is_causal = getattr(module, "is_causal", True) + + attn_output = _custom_flash_attention_forward( + query, + key, + value, + attention_mask, + query_length=q_len, + is_causal=is_causal, + dropout=dropout, + softmax_scale=scaling, + sliding_window=sliding_window, + softcap=softcap, + use_top_left_mask=_flash_use_top_left_mask, + **kwargs, + ) + + return attn_output, None diff --git a/model/EasyR1/verl/models/transformers/qwen2_vl.py b/model/EasyR1/verl/models/transformers/qwen2_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..8830816118aa7c3f0c9ccc1ddd55ac33e5a61171 --- /dev/null +++ b/model/EasyR1/verl/models/transformers/qwen2_vl.py @@ -0,0 +1,292 @@ +# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# Based on: +# https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py +# +# 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. + +from typing import Optional + +import torch +from transformers.models.qwen2_vl.modeling_qwen2_vl import ( + Qwen2VLCausalLMOutputWithPast, + Qwen2VLForConditionalGeneration, + Qwen2VLModel, + Qwen2VLModelOutputWithPast, +) +from transformers.models.qwen2_vl.processing_qwen2_vl import Qwen2VLProcessor + + +def get_rope_index( + processor: "Qwen2VLProcessor", + input_ids: torch.Tensor, + image_grid_thw: Optional[torch.Tensor] = None, + video_grid_thw: Optional[torch.Tensor] = None, + second_per_grid_ts: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Gets the position ids for Qwen2-VL, it should be generated before sharding the sequence. + The batch dim has been removed and the input_ids should be a 1D tensor representing a single example. + https://github.com/huggingface/transformers/blob/v4.52.4/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py#L1405 + """ + spatial_merge_size = processor.image_processor.merge_size + tokens_per_second = 2 + image_token_id = processor.tokenizer.convert_tokens_to_ids("<|image_pad|>") + video_token_id = processor.tokenizer.convert_tokens_to_ids("<|video_pad|>") + vision_start_token_id = processor.tokenizer.convert_tokens_to_ids("<|vision_start|>") + if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): + if attention_mask is None: + attention_mask = torch.ones_like(input_ids) + + position_ids = torch.ones(3, input_ids.size(0), dtype=input_ids.dtype, device=input_ids.device) # (3, seqlen) + image_index, video_index = 0, 0 + input_ids = input_ids[attention_mask == 1] + image_nums, video_nums = 0, 0 + vision_start_indices = torch.argwhere(input_ids == vision_start_token_id) + vision_tokens = input_ids[vision_start_indices + 1] + image_nums = (vision_tokens == image_token_id).sum() + video_nums = (vision_tokens == video_token_id).sum() + input_tokens = input_ids.tolist() + llm_pos_ids_list: list = [] + st = 0 + remain_images, remain_videos = image_nums, video_nums + for _ in range(image_nums + video_nums): + if image_token_id in input_tokens and remain_images > 0: + ed_image = input_tokens.index(image_token_id, st) + else: + ed_image = len(input_tokens) + 1 + if video_token_id in input_tokens and remain_videos > 0: + ed_video = input_tokens.index(video_token_id, st) + else: + ed_video = len(input_tokens) + 1 + if ed_image < ed_video: + t, h, w = ( + image_grid_thw[image_index][0], + image_grid_thw[image_index][1], + image_grid_thw[image_index][2], + ) + second_per_grid_t = 0 + image_index += 1 + remain_images -= 1 + ed = ed_image + else: + t, h, w = ( + video_grid_thw[video_index][0], + video_grid_thw[video_index][1], + video_grid_thw[video_index][2], + ) + if second_per_grid_ts is not None: + second_per_grid_t = second_per_grid_ts[video_index] + else: + second_per_grid_t = 1.0 + + video_index += 1 + remain_videos -= 1 + ed = ed_video + + llm_grid_t, llm_grid_h, llm_grid_w = ( + t.item(), + h.item() // spatial_merge_size, + w.item() // spatial_merge_size, + ) + text_len = ed - st + + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w) + t_index = (t_index * second_per_grid_t * tokens_per_second).long().flatten() + h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() + w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() + llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) + st = ed + llm_grid_t * llm_grid_h * llm_grid_w + + if st < len(input_tokens): + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + text_len = len(input_tokens) - st + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) + position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device) + else: + if attention_mask is not None: + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + position_ids = position_ids.unsqueeze(0).expand(3, -1).to(input_ids.device) + else: + position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1) + + return position_ids + + +def _get_input_embeds( + model: "Qwen2VLModel", + input_ids: torch.LongTensor, + attention_mask: Optional[torch.Tensor] = None, + pixel_values: Optional[torch.FloatTensor] = None, + pixel_values_videos: Optional[torch.FloatTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, +): + inputs_embeds = model.get_input_embeddings()(input_ids) + # if pixel_values is not None: + # pixel_values = pixel_values.type(model.visual.dtype) + # image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) + # n_image_tokens = (input_ids == model.config.image_token_id).sum().item() + # n_image_features = image_embeds.shape[0] + # if n_image_tokens != n_image_features: + # raise ValueError( + # f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" + # ) + + # mask = input_ids == model.config.image_token_id + # mask_unsqueezed = mask.unsqueeze(-1) + # mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) + # image_mask = mask_expanded.to(inputs_embeds.device) + + # image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + # inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) + + # if pixel_values_videos is not None: + # pixel_values_videos = pixel_values_videos.type(model.visual.dtype) + # video_embeds = model.visual(pixel_values_videos, grid_thw=video_grid_thw) + # n_video_tokens = (input_ids == model.config.video_token_id).sum().item() + # n_video_features = video_embeds.shape[0] + # if n_video_tokens != n_video_features: + # raise ValueError( + # f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" + # ) + + # mask = input_ids == model.config.video_token_id + # mask_unsqueezed = mask.unsqueeze(-1) + # mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) + # video_mask = mask_expanded.to(inputs_embeds.device) + + # video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + # inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) + + # if pixel_values is None and pixel_values_videos is None: + # config = model.config.vision_config + # patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2 + # pixel_values = torch.zeros((16, patch_dim), dtype=inputs_embeds.dtype, device=inputs_embeds.device) + # image_grid_thw = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) + # image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) + # inputs_embeds += 0.0 * image_embeds.mean() + + # Image branch + if pixel_values is not None: + pixel_values = pixel_values.type(model.visual.dtype) + image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) + n_image_tokens = (input_ids == model.config.image_token_id).sum().item() + n_image_features = image_embeds.shape[0] + if n_image_tokens != n_image_features: + raise ValueError( + f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" + ) + + mask = input_ids == model.config.image_token_id + mask_unsqueezed = mask.unsqueeze(-1) + mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) + image_mask = mask_expanded.to(inputs_embeds.device) + + image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) + else: + # [NEW] When image is missing: use a tiny dummy input to "activate" the image branch (hook into the graph without changing values) + config = model.config.vision_config + patch_dim = config.in_channels * config.temporal_patch_size * (config.patch_size ** 2) + _dummy_pixels_img = torch.zeros( + (16, patch_dim), + dtype=inputs_embeds.dtype, + device=inputs_embeds.device + ).type(model.visual.dtype) + _dummy_grid_img = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) + _dummy_img_embeds = model.visual(_dummy_pixels_img, grid_thw=_dummy_grid_img) + inputs_embeds = inputs_embeds + 0.0 * _dummy_img_embeds.mean() # Values unchanged, but graph/gradients connected + + # Video branch + if pixel_values_videos is not None: + pixel_values_videos = pixel_values_videos.type(model.visual.dtype) + video_embeds = model.visual(pixel_values_videos, grid_thw=video_grid_thw) + n_video_tokens = (input_ids == model.config.video_token_id).sum().item() + n_video_features = video_embeds.shape[0] + if n_video_tokens != n_video_features: + raise ValueError( + f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" + ) + + mask = input_ids == model.config.video_token_id + mask_unsqueezed = mask.unsqueeze(-1) + mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) + video_mask = mask_expanded.to(inputs_embeds.device) + + video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) + else: + # [NEW] When video is missing: use a tiny dummy input to "activate" the video branch (hook into the graph without changing values) + config = model.config.vision_config + patch_dim = config.in_channels * config.temporal_patch_size * (config.patch_size ** 2) + _dummy_pixels_vid = torch.zeros( + (16, patch_dim), + dtype=inputs_embeds.dtype, + device=inputs_embeds.device + ).type(model.visual.dtype) + _dummy_grid_vid = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) + _dummy_vid_embeds = model.visual(_dummy_pixels_vid, grid_thw=_dummy_grid_vid) + inputs_embeds = inputs_embeds + 0.0 * _dummy_vid_embeds.mean() # Values unchanged, but graph/gradients connected + + if attention_mask is not None: + attention_mask = attention_mask.to(inputs_embeds.device) + + return { + "inputs_embeds": inputs_embeds, + "attention_mask": attention_mask, + } + + +def qwen2_vl_base_forward( + self: "Qwen2VLModel", + input_ids: torch.LongTensor, + attention_mask: Optional[torch.Tensor] = None, + pixel_values: Optional[torch.FloatTensor] = None, + pixel_values_videos: Optional[torch.FloatTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, + **kwargs, +): + position_ids = kwargs.get("position_ids") + if isinstance(position_ids, torch.Tensor) and (position_ids.ndim != 3 or position_ids.size(0) != 4): + # we concat the text position ids with the 3D vision position ids by default + # see https://github.com/huggingface/transformers/pull/39447 + raise ValueError("position_ids should be a 3D tensor of shape (4, batch_size, seq_length).") + + input_kwargs = _get_input_embeds( + self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw + ) + kwargs.update(input_kwargs) # avoid lora module to have multiple keyword arguments + outputs = self.language_model(input_ids=None, **kwargs) + return Qwen2VLModelOutputWithPast(last_hidden_state=outputs.last_hidden_state) + + +def qwen2_vl_model_forward( + self: "Qwen2VLForConditionalGeneration", + input_ids: torch.LongTensor, + labels: Optional[torch.LongTensor] = None, + **kwargs, +) -> "Qwen2VLCausalLMOutputWithPast": + outputs = self.model(input_ids=input_ids, **kwargs) + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + + return Qwen2VLCausalLMOutputWithPast(logits=logits) diff --git a/model/EasyR1/verl/models/transformers/qwen3_vl.py b/model/EasyR1/verl/models/transformers/qwen3_vl.py new file mode 100644 index 0000000000000000000000000000000000000000..cb8a629ffaba655440134b877be71ff98749baa2 --- /dev/null +++ b/model/EasyR1/verl/models/transformers/qwen3_vl.py @@ -0,0 +1,375 @@ +# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# Based on: +# https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py +# +# 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. + +from typing import Optional + +import torch +from transformers.models.qwen3_vl.modeling_qwen3_vl import ( + Qwen3VLCausalLMOutputWithPast, + Qwen3VLForConditionalGeneration, + Qwen3VLModel, + Qwen3VLModelOutputWithPast, +) +from transformers.models.qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor + + +def get_rope_index( + processor: "Qwen3VLProcessor", + input_ids: torch.Tensor, + image_grid_thw: Optional[torch.Tensor] = None, + video_grid_thw: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + **kwargs, +) -> torch.Tensor: + """ + Gets the position ids for Qwen3-VL, it should be generated before sharding the sequence. + The batch dim has been removed and the input_ids should be a 1D tensor representing a single example. + https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py#L916 + """ + spatial_merge_size = processor.image_processor.merge_size + image_token_id = processor.image_token_id + video_token_id = processor.video_token_id + vision_start_token_id = processor.vision_start_token_id + + # Since we use timestamps to seperate videos, + # like , + # the video_grid_thw should also be split + if video_grid_thw is not None: + video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0) + video_grid_thw[:, 0] = 1 + + if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None): + if attention_mask is None: + attention_mask = torch.ones_like(input_ids) + + position_ids = torch.ones(3, input_ids.shape[0], dtype=input_ids.dtype, device=input_ids.device) + image_index, video_index = 0, 0 + attention_mask = attention_mask.to(input_ids.device) + input_ids = input_ids[attention_mask == 1] + image_nums, video_nums = 0, 0 + vision_start_indices = torch.argwhere(input_ids == vision_start_token_id) + vision_tokens = input_ids[vision_start_indices + 1] + image_nums = (vision_tokens == image_token_id).sum() + video_nums = (vision_tokens == video_token_id).sum() + input_tokens = input_ids.tolist() + llm_pos_ids_list: list = [] + st = 0 + remain_images, remain_videos = image_nums, video_nums + for _ in range(image_nums + video_nums): + if image_token_id in input_tokens and remain_images > 0: + ed_image = input_tokens.index(image_token_id, st) + else: + ed_image = len(input_tokens) + 1 + if video_token_id in input_tokens and remain_videos > 0: + ed_video = input_tokens.index(video_token_id, st) + else: + ed_video = len(input_tokens) + 1 + if ed_image < ed_video: + t, h, w = ( + image_grid_thw[image_index][0], + image_grid_thw[image_index][1], + image_grid_thw[image_index][2], + ) + image_index += 1 + remain_images -= 1 + ed = ed_image + else: + t, h, w = ( + video_grid_thw[video_index][0], + video_grid_thw[video_index][1], + video_grid_thw[video_index][2], + ) + video_index += 1 + remain_videos -= 1 + ed = ed_video + + llm_grid_t, llm_grid_h, llm_grid_w = ( + t.item(), + h.item() // spatial_merge_size, + w.item() // spatial_merge_size, + ) + text_len = ed - st + + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + # t_index is always 0 because llm_grid_t is always 1 (we use timestamps to encode the temporal information for videos) + t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten() + h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten() + w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten() + llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx) + st = ed + llm_grid_t * llm_grid_h * llm_grid_w + + if st < len(input_tokens): + st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0 + text_len = len(input_tokens) - st + llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx) + + llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1) + position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device) + else: + if attention_mask is not None: + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + position_ids = position_ids.unsqueeze(0).expand(3, -1).to(attention_mask.device) + else: + position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1) + + return position_ids + + +def _get_input_embeds( + model: "Qwen3VLModel", + input_ids: torch.LongTensor, + attention_mask: Optional[torch.Tensor] = None, + pixel_values: Optional[torch.FloatTensor] = None, + pixel_values_videos: Optional[torch.FloatTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, +): + inputs_embeds = model.get_input_embeddings()(input_ids) + image_mask, video_mask = None, None + if pixel_values is not None: + pixel_values = pixel_values.type(model.visual.dtype) + image_embeds, deepstack_image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) + n_image_tokens = (input_ids == model.config.image_token_id).sum().item() + n_image_features = image_embeds.shape[0] + + # print('image',pixel_values.shape,image_grid_thw) + + # import pdb + # pdb.set_trace() + + # print('n_image_tokens', n_image_tokens) + # print('n_image_features', n_image_features) + + + if n_image_tokens != n_image_features: + # raise ValueError( + # f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" + # ) + + from datetime import datetime + import os, json + msg = f"[NOT ALIGN][image] tokens={int(n_image_tokens)} features={int(n_image_features)}" + print(msg) + _log_path = os.environ.get("BAD_SAMPLES_LOG", "./EasyR1/bad_samples.txt") + try: + with open(_log_path, "a", encoding="utf-8") as f: + f.write(json.dumps({"time": datetime.now().isoformat(timespec="seconds"), "error": msg}, ensure_ascii=False) + "\n") + except Exception as _e: + print("[warn] log write failed:", _e) + + need, have = int(n_image_tokens), int(n_image_features) + if have > need: + image_embeds = image_embeds[:need] + if deepstack_image_embeds is not None: + deepstack_image_embeds = [e[:need] for e in deepstack_image_embeds] + elif have < need: + pad = need - have + z = torch.zeros((pad, image_embeds.size(-1)), dtype=image_embeds.dtype, device=image_embeds.device) + image_embeds = torch.cat([image_embeds, z], dim=0) + if deepstack_image_embeds is not None: + deepstack_image_embeds = [torch.cat([e, torch.zeros((pad, e.size(-1)), dtype=e.dtype, device=e.device)], dim=0) + for e in deepstack_image_embeds] + + + mask = input_ids == model.config.image_token_id + mask_unsqueezed = mask.unsqueeze(-1) + mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) + image_mask = mask_expanded.to(inputs_embeds.device) + + image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) + + if pixel_values_videos is not None: + pixel_values_videos = pixel_values_videos.type(model.visual.dtype) + video_embeds, deepstack_video_embeds = model.visual(pixel_values_videos, grid_thw=video_grid_thw) + n_video_tokens = (input_ids == model.config.video_token_id).sum().item() + n_video_features = video_embeds.shape[0] + + # print('video',pixel_values_videos.shape,video_grid_thw) + + + #print('n_video_tokens', n_video_tokens) + #print('n_video_features', n_video_features) + # import pdb + # pdb.set_trace() + + if n_video_tokens != n_video_features: + # raise ValueError( + # f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" + # ) + + from datetime import datetime + import os, json + msg = f"[NOT ALIGN][video] tokens={int(n_video_tokens)} features={int(n_video_features)}" + print(msg) + _log_path = os.environ.get("BAD_SAMPLES_LOG", "./EasyR1/bad_samples.txt") + try: + with open(_log_path, "a", encoding="utf-8") as f: + f.write(json.dumps({"time": datetime.now().isoformat(timespec="seconds"), "error": msg}, ensure_ascii=False) + "\n") + except Exception as _e: + print("[warn] log write failed:", _e) + + need, have = int(n_video_tokens), int(n_video_features) + if have > need: + video_embeds = video_embeds[:need] + if deepstack_video_embeds is not None: + deepstack_video_embeds = [e[:need] for e in deepstack_video_embeds] + elif have < need: + pad = need - have + z = torch.zeros((pad, video_embeds.size(-1)), dtype=video_embeds.dtype, device=video_embeds.device) + video_embeds = torch.cat([video_embeds, z], dim=0) + if deepstack_video_embeds is not None: + deepstack_video_embeds = [torch.cat([e, torch.zeros((pad, e.size(-1)), dtype=e.dtype, device=e.device)], dim=0) + for e in deepstack_video_embeds] + + + mask = input_ids == model.config.video_token_id + mask_unsqueezed = mask.unsqueeze(-1) + mask_expanded = mask_unsqueezed.expand_as(inputs_embeds) + video_mask = mask_expanded.to(inputs_embeds.device) + + video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds) + + + + visual_pos_masks = None + deepstack_visual_embeds = None + if image_mask is not None and video_mask is not None: + # aggregate visual_pos_masks and deepstack_visual_embeds + image_mask = image_mask[..., 0] + video_mask = video_mask[..., 0] + visual_pos_masks = image_mask | video_mask + deepstack_visual_embeds = [] + image_mask_joint = image_mask[visual_pos_masks] + video_mask_joint = video_mask[visual_pos_masks] + for img_embed, vid_embed in zip(deepstack_image_embeds, deepstack_video_embeds): + embed_joint = img_embed.new_zeros(visual_pos_masks.sum(), img_embed.shape[-1]).to(img_embed.device) + embed_joint[image_mask_joint, :] = img_embed + embed_joint[video_mask_joint, :] = vid_embed + deepstack_visual_embeds.append(embed_joint) + elif image_mask is not None: + image_mask = image_mask[..., 0] + visual_pos_masks = image_mask + deepstack_visual_embeds = deepstack_image_embeds + elif video_mask is not None: + video_mask = video_mask[..., 0] + visual_pos_masks = video_mask + deepstack_visual_embeds = deepstack_video_embeds + + if pixel_values is None and pixel_values_videos is None: + config = model.config.vision_config + patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2 + pixel_values = torch.zeros((16, patch_dim), dtype=inputs_embeds.dtype, device=inputs_embeds.device) + image_grid_thw = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) + # image_embeds, _ = model.visual(pixel_values, grid_thw=image_grid_thw) + image_embeds, dummy_deepstack_image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw) + inputs_embeds += 0.0 * image_embeds.mean() + for emb in dummy_deepstack_image_embeds or []: + inputs_embeds += 0.0 * emb.mean() + + # for image-video mixed training + + if pixel_values is not None and pixel_values_videos is None: + config = model.config.vision_config + patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2 + + _video_grid_thw = video_grid_thw if ('video_grid_thw' in locals() and video_grid_thw is not None) \ + else torch.tensor([[2, 4, 4]], dtype=torch.long, device=inputs_embeds.device) + _T, _H, _W = _video_grid_thw[0].tolist() + _n_tokens = int(_T * _H * _W) + + _dummy_video_pixels = torch.zeros((_n_tokens, patch_dim), + dtype=inputs_embeds.dtype, + device=inputs_embeds.device) + + _video_embeds, _video_deepstack = model.visual(_dummy_video_pixels, grid_thw=_video_grid_thw) + inputs_embeds = inputs_embeds + 0.0 * _video_embeds.mean() + for _emb in _video_deepstack or []: + inputs_embeds = inputs_embeds + 0.0 * _emb.mean() + + + if pixel_values is None and pixel_values_videos is not None: + config = model.config.vision_config + patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2 + + _image_grid_thw = image_grid_thw if ('image_grid_thw' in locals() and image_grid_thw is not None) \ + else torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device) + _T, _H, _W = _image_grid_thw[0].tolist() + _n_tokens = int(_T * _H * _W) + + _dummy_image_pixels = torch.zeros((_n_tokens, patch_dim), + dtype=inputs_embeds.dtype, + device=inputs_embeds.device) + + _image_embeds, _image_deepstack = model.visual(_dummy_image_pixels, grid_thw=_image_grid_thw) + inputs_embeds = inputs_embeds + 0.0 * _image_embeds.mean() + for _emb in _image_deepstack or []: + inputs_embeds = inputs_embeds + 0.0 * _emb.mean() + + + + if attention_mask is not None: + attention_mask = attention_mask.to(inputs_embeds.device) + + return { + "inputs_embeds": inputs_embeds, + "attention_mask": attention_mask, + "visual_pos_masks": visual_pos_masks, + "deepstack_visual_embeds": deepstack_visual_embeds, + } + + + + +def qwen3_vl_base_forward( + self: "Qwen3VLModel", + input_ids: torch.LongTensor, + attention_mask: Optional[torch.Tensor] = None, + pixel_values: Optional[torch.FloatTensor] = None, + pixel_values_videos: Optional[torch.FloatTensor] = None, + image_grid_thw: Optional[torch.LongTensor] = None, + video_grid_thw: Optional[torch.LongTensor] = None, + **kwargs, +): + position_ids = kwargs.get("position_ids") + if isinstance(position_ids, torch.Tensor) and (position_ids.ndim != 3 or position_ids.size(0) != 4): + # we concat the text position ids with the 3D vision position ids by default + # see https://github.com/huggingface/transformers/pull/39447 + raise ValueError("position_ids should be a 3D tensor of shape (4, batch_size, seq_length).") + + input_kwargs = _get_input_embeds( + self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw + ) + kwargs.update(input_kwargs) # avoid lora module to have multiple keyword arguments + outputs = self.language_model(input_ids=None, **kwargs) + return Qwen3VLModelOutputWithPast(last_hidden_state=outputs.last_hidden_state) + +def qwen3_vl_model_forward( + self: "Qwen3VLForConditionalGeneration", + input_ids: torch.LongTensor, + labels: Optional[torch.LongTensor] = None, + **kwargs, +) -> "Qwen3VLCausalLMOutputWithPast": + outputs = self.model(input_ids=input_ids, **kwargs) + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + + return Qwen3VLCausalLMOutputWithPast(logits=logits) diff --git a/model/EasyR1/verl/protocol.py b/model/EasyR1/verl/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..dc3407230483f2beaa68843990954e9c17fd384e --- /dev/null +++ b/model/EasyR1/verl/protocol.py @@ -0,0 +1,1476 @@ +# # 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. +# """ +# Implement base data transfer protocol between any two functions, modules. +# We can subclass Protocol to define more detailed batch info with specific keys +# """ +# import copy +# import io +# import os +# import pickle +# from collections import defaultdict +# from dataclasses import dataclass, field +# from typing import Any, Callable, Optional, Union + +# import numpy as np +# import ray +# import torch +# from numpy.typing import NDArray +# from tensordict import TensorDict +# from torch.distributed import ProcessGroup +# from torch.utils.data import DataLoader + +# from .utils.py_functional import union_two_dict + + +# try: +# import tensordict +# tensordict.set_lazy_legacy(False).set() +# except Exception: +# pass + + +# __all__ = ["DataProto", "union_tensor_dict"] + +# # ====== Feature switches (default OFF to keep original behavior) ====== +# DP_SMART_UNION = 1 # per-sample smart union for non-tensors +# DP_AUTO_ALIGN = 1 # auto align non_tensors length to batch_size +# DP_RELAX_FROM_SINGLE = 1 # from_single_dict accepts non-ndarray by casting to object + + +# def pad_dataproto_to_divisor(data: "DataProto", size_divisor: int) -> tuple["DataProto", int]: +# """Pad a DataProto to size divisible by size_divisor""" +# assert isinstance(data, DataProto), "data must be a DataProto" +# if len(data) % size_divisor != 0: +# pad_size = size_divisor - len(data) % size_divisor +# padding_protos = [] +# remaining_pad = pad_size +# while remaining_pad > 0: +# take_size = min(remaining_pad, len(data)) +# padding_protos.append(data[:take_size]) +# remaining_pad -= take_size +# data_padded = DataProto.concat([data] + padding_protos) +# else: +# pad_size = 0 +# data_padded = data +# return data_padded, pad_size + + +# def unpad_dataproto(data: "DataProto", pad_size: int) -> "DataProto": +# if pad_size != 0: +# data = data[:-pad_size] +# return data + + +# def union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict: +# """Union two tensordicts.""" +# if tensor_dict1.batch_size != tensor_dict2.batch_size: +# raise ValueError( +# f"Two tensor dict must have identical batch size. Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}" +# ) +# for key in tensor_dict2.keys(): +# if key in tensor_dict1 and not torch.equal(tensor_dict1[key], tensor_dict2[key]): +# raise ValueError(f"Key already exists: {key}.") +# tensor_dict1[key] = tensor_dict2[key] +# return tensor_dict1 + + +# # ---------------------- non-tensor union (two modes) ---------------------- +# # Strict mode (original behavior) +# def _union_numpy_dict_strict(tensor_dict1: dict[str, NDArray], tensor_dict2: dict[str, NDArray]) -> dict[str, NDArray]: +# for key in tensor_dict2.keys(): +# if key in tensor_dict1: +# assert isinstance(tensor_dict2[key], np.ndarray) +# assert isinstance(tensor_dict1[key], np.ndarray) +# if not np.all(tensor_dict1[key] == tensor_dict2[key]): +# raise ValueError(f"Key already exists: {key}.") +# tensor_dict1[key] = tensor_dict2[key] +# return tensor_dict1 + + +# # Smart mode (opt-in): per-sample merge with None tolerance +# def _to_obj_1d(x) -> NDArray: +# if isinstance(x, np.ndarray) and x.dtype == np.dtype(object): +# return x +# return np.array(x, dtype=object) + + +# def _elem_equal(x: Any, y: Any) -> bool: +# if x is y: +# return True +# if isinstance(x, str) and isinstance(y, str): +# return x == y +# if isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor): +# try: +# return x.shape == y.shape and torch.equal(x.cpu(), y.cpu()) +# except Exception: +# return False +# if isinstance(x, np.ndarray) and isinstance(y, np.ndarray) and x.dtype != object and y.dtype != object: +# try: +# return x.shape == y.shape and np.array_equal(x, y) +# except Exception: +# return False +# try: +# return x == y +# except Exception: +# return False + + +# def _union_numpy_dict_smart(tensor_dict1: dict[str, NDArray], tensor_dict2: dict[str, NDArray]) -> dict[str, NDArray]: +# """ +# Per-sample merge: +# - missing side (None) -> take the other; +# - both non-None and equal -> keep left; +# - both non-None and not equal -> raise with conflict indices (first few). +# """ +# for key, v2 in tensor_dict2.items(): +# if key not in tensor_dict1: +# tensor_dict1[key] = v2 +# continue + +# v1 = tensor_dict1[key] +# a1 = _to_obj_1d(v1) +# a2 = _to_obj_1d(v2) + +# if a1.shape != a2.shape: +# raise ValueError(f"Key '{key}' has different shapes: {a1.shape} vs {a2.shape}") + +# merged = np.empty_like(a1, dtype=object) +# conflict_idx = [] + +# for i in range(a1.shape[0]): +# x, y = a1[i], a2[i] +# if x is None and y is None: +# merged[i] = None +# elif x is None: +# merged[i] = y +# elif y is None: +# merged[i] = x +# else: +# if _elem_equal(x, y): +# merged[i] = x +# else: +# conflict_idx.append(i) +# merged[i] = x # keep left, but we still error after loop + +# if conflict_idx: +# head = conflict_idx[:5] +# raise ValueError(f"Key already exists and conflicts on sample indices {head} (key='{key}').") + +# tensor_dict1[key] = merged + +# return tensor_dict1 + + +# # Public entry: choose by switch (default strict/original) +# def union_numpy_dict(tensor_dict1: dict[str, NDArray], tensor_dict2: dict[str, NDArray]) -> dict[str, NDArray]: +# if DP_SMART_UNION: +# return _union_numpy_dict_smart(tensor_dict1, tensor_dict2) +# else: +# return _union_numpy_dict_strict(tensor_dict1, tensor_dict2) + + +# # ---------------------- helpers ---------------------- +# def batch_collate(features: list[dict[str, Any]]) -> dict[str, list[Any]]: +# if len(features) == 0: +# return {} +# batch_features = defaultdict(list) +# for feature in features: +# for key, value in feature.items(): +# batch_features[key].append(value) +# return batch_features + + +# def fold_batch_dim(data: "DataProto", new_batch_size: int): +# """ +# Fold a batch dim from [bsz, xxx] into [new_bsz, bsz // new_bsz, xxx] +# """ +# batch_size = data.batch.batch_size[0] +# assert batch_size % new_batch_size == 0 + +# tensor: TensorDict = data.batch +# non_tensor = data.non_tensor_batch + +# tensor = tensor.view(new_batch_size, -1) +# tensor.auto_batch_size_(batch_dims=1) + +# for key, value in non_tensor.items(): +# non_tensor[key] = np.reshape(value, newshape=(new_batch_size, -1, *value.shape[1:])) + +# return DataProto(batch=tensor, non_tensor_batch=non_tensor, meta_info=data.meta_info) + + +# def collate_fn(data_items: list["DataProtoItem"]): +# batch = [] +# non_tensor_batch = [] +# for data in data_items: +# batch.append(data.batch) +# non_tensor_batch.append(data.non_tensor_batch) + +# batch = torch.stack(batch).contiguous() +# non_tensor_batch = batch_collate(non_tensor_batch) +# non_tensor_batch = {key: np.array(value, dtype=object) for key, value in non_tensor_batch.items()} +# return DataProto(batch=batch, non_tensor_batch=non_tensor_batch) + + +# @dataclass +# class DataProtoItem: +# batch: Optional[TensorDict] = None +# non_tensor_batch: dict[str, NDArray] = field(default_factory=dict) +# meta_info: dict[str, Any] = field(default_factory=dict) + + +# @dataclass +# class DataProto: +# """ +# A DataProto is a data structure that aims to provide a standard protocol for data exchange between functions. +# It contains a batch (TensorDict) and a meta_info (Dict). +# """ + +# batch: Optional[TensorDict] = None +# non_tensor_batch: dict[str, NDArray] = field(default_factory=dict) +# meta_info: dict[str, Any] = field(default_factory=dict) + +# @staticmethod +# def _ensure_obj_array(v) -> NDArray: +# if isinstance(v, np.ndarray) and v.dtype == np.dtype(object): +# return v +# return np.array(v, dtype=object) + +# @classmethod +# def _align_non_tensors_len(cls, non_tensors: dict[str, NDArray], batch_size: int) -> None: +# """Align non_tensors along dim0 to batch_size (pad with None or truncate).""" +# for k, v in list(non_tensors.items()): +# v = cls._ensure_obj_array(v) +# cur = v.shape[0] +# if cur < batch_size: +# pad_n = batch_size - cur +# pad = np.array([None] * pad_n, dtype=object) +# non_tensors[k] = np.concatenate([v, pad], axis=0) +# elif cur > batch_size: +# non_tensors[k] = v[:batch_size] +# else: +# non_tensors[k] = v + +# def __post_init__(self): +# # Only auto-align when explicitly enabled; otherwise keep original strictness. +# if DP_AUTO_ALIGN and self.batch is not None and len(self.non_tensor_batch) != 0: +# self._align_non_tensors_len(self.non_tensor_batch, self.batch.batch_size[0]) +# self.check_consistency() # perform necessary checking + +# def __len__(self) -> int: +# if self.batch is not None: +# return self.batch.batch_size[0] +# elif self.non_tensor_batch is not None and len(self.non_tensor_batch) > 0: +# pivot_key = list(self.non_tensor_batch.keys())[0] +# return self.non_tensor_batch[pivot_key].shape[0] +# else: +# return 0 + +# def __getitem__( +# self, item: Union[int, slice, list[int], np.ndarray, torch.Tensor] +# ) -> Union["DataProto", "DataProtoItem"]: +# if isinstance(item, slice): +# return self.slice_select(item.start, item.stop, item.step) + +# if isinstance(item, (list, np.ndarray, torch.Tensor)): +# return self.index_select(item) + +# if isinstance(item, (int, np.integer)): +# tensor_data = self.batch[item] if self.batch is not None else None +# non_tensor_data = {key: value[item] for key, value in self.non_tensor_batch.items()} +# return DataProtoItem(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info) + +# raise TypeError(f"Indexing with {type(item)} is not supported.") + +# def __getstate__(self) -> tuple[bytes, dict[str, NDArray], dict[str, Any]]: +# if self.batch is not None: +# batch_to_save: TensorDict = self.batch.contiguous() +# batch_to_save: TensorDict = batch_to_save.consolidate() +# else: +# batch_to_save = None + +# buffer = io.BytesIO() +# torch.save(batch_to_save, buffer) +# buffer_bytes = buffer.getvalue() +# return buffer_bytes, self.non_tensor_batch, self.meta_info + +# def __setstate__(self, data: tuple[bytes, dict[str, NDArray], dict[str, Any]]) -> None: +# batch_deserialized_bytes, non_tensor_batch, meta_info = data +# batch_deserialized = io.BytesIO(batch_deserialized_bytes) +# batch = torch.load(batch_deserialized, weights_only=False, map_location="cpu") +# self.batch = batch +# self.non_tensor_batch = non_tensor_batch +# self.meta_info = meta_info + +# def save_to_disk(self, filepath: str) -> None: +# with open(filepath, "wb") as f: +# pickle.dump(self, f) + +# @staticmethod +# def load_from_disk(filepath: str) -> "DataProto": +# with open(filepath, "rb") as f: +# data = pickle.load(f) +# return data + +# def print_size(self, prefix: str = "") -> None: +# size_of_tensordict = 0 +# if self.batch is not None: +# for tensor in self.batch.values(): +# if isinstance(tensor, torch.Tensor): +# size_of_tensordict += tensor.element_size() * tensor.numel() + +# size_of_numpy_array = 0 +# for value in self.non_tensor_batch.values(): +# size_of_numpy_array += value.nbytes + +# size_of_numpy_array /= 1024**3 +# size_of_tensordict /= 1024**3 + +# message = f"Size of tensordict: {size_of_tensordict} GB, size of non_tensor_batch: {size_of_numpy_array} GB." +# print({prefix}, {message}) + +# def check_consistency(self): +# """Check the consistency of the DataProto. Mainly for batch and non_tensor_batch""" +# if self.batch is not None: +# assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1" + +# if self.batch is not None and len(self.non_tensor_batch) != 0: +# assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1 when non_tensor_batch is not empty." +# batch_size = self.batch.batch_size[0] +# # Only auto-align when enabled; otherwise keep original assertion behavior +# if DP_AUTO_ALIGN: +# self._align_non_tensors_len(self.non_tensor_batch, batch_size) +# for key, value in self.non_tensor_batch.items(): +# assert len(value) == batch_size, f"key {key} length {len(value)} is not equal to bsz {batch_size}." + +# @classmethod +# def from_single_dict( +# cls, +# data: dict[str, Union[torch.Tensor, NDArray]], +# meta_info: Optional[dict[str, Any]] = None, +# ) -> "DataProto": +# tensors, non_tensors = {}, {} +# for key, value in data.items(): +# if isinstance(value, torch.Tensor): +# tensors[key] = value +# elif isinstance(value, np.ndarray): +# non_tensors[key] = value +# else: +# if DP_RELAX_FROM_SINGLE: +# non_tensors[key] = np.array(value, dtype=object) +# else: +# raise ValueError(f"Unsupported type in data {type(value)}") +# return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info) + +# @classmethod +# def from_dict( +# cls, +# tensors: Optional[dict[str, torch.Tensor]] = None, +# non_tensors: Optional[dict[str, NDArray]] = None, +# meta_info: Optional[dict[str, Any]] = None, +# num_batch_dims: int = 1, +# ) -> "DataProto": +# """Create a DataProto from a dict of tensors.""" +# assert num_batch_dims > 0, "num_batch_dims must be greater than zero" +# if non_tensors is not None: +# assert num_batch_dims == 1, "only support num_batch_dims=1 when non_tensors is not None." + +# tensors = tensors or {} +# non_tensors = non_tensors or {} +# meta_info = meta_info or {} +# assert isinstance(tensors, dict) and isinstance(non_tensors, dict) and isinstance(meta_info, dict) + +# # get and check batch size +# batch_size = None +# pivot_key = None +# for key, tensor in tensors.items(): +# if batch_size is None: +# batch_size = tensor.shape[:num_batch_dims] +# pivot_key = key +# else: +# current_batch = tensor.shape[:num_batch_dims] +# assert batch_size == current_batch, ( +# f"Not all the tensor in tensors have the same batch size with batch_dims={num_batch_dims}. " +# f"Got {pivot_key} has {batch_size}, {key} has {current_batch}." +# ) + +# # keep original: normalize non_tensors to object ndarray for consistency +# for key, value in non_tensors.items(): +# if not isinstance(value, np.ndarray) or value.dtype != np.dtype(object): +# non_tensors[key] = np.array(value, dtype=object) + +# tensor_dict = TensorDict(source=tensors, batch_size=batch_size) if tensors else None +# return cls(batch=tensor_dict, non_tensor_batch=non_tensors, meta_info=meta_info) + +# def to(self, device: torch.device, non_blocking: bool = False) -> "DataProto": +# """Move the batch to device""" +# if self.batch is not None: +# self.batch = self.batch.to(device, non_blocking=non_blocking) +# return self + +# def select( +# self, +# batch_keys: Optional[list[str]] = None, +# non_tensor_batch_keys: Optional[list[str]] = None, +# meta_info_keys: Optional[list[str]] = None, +# deepcopy: bool = False, +# ) -> "DataProto": +# """Select a subset of the DataProto via batch_keys and meta_info_keys""" +# if batch_keys is not None: +# batch_keys = tuple(filter(lambda k: k in self.batch, batch_keys)) +# sub_batch = self.batch.select(*batch_keys) +# else: +# sub_batch = self.batch + +# if non_tensor_batch_keys is not None: +# non_tensor_batch_keys = tuple(filter(lambda k: k in self.non_tensor_batch, non_tensor_batch_keys)) +# non_tensor_batch = {k: v for k, v in self.non_tensor_batch.items() if k in non_tensor_batch_keys} +# else: +# non_tensor_batch = self.non_tensor_batch + +# if deepcopy: +# non_tensor_batch = copy.deepcopy(non_tensor_batch) + +# if meta_info_keys is not None: +# meta_info_keys = tuple(filter(lambda k: k in self.meta_info, meta_info_keys)) +# sub_meta_info = {k: v for k, v in self.meta_info.items() if k in meta_info_keys} +# else: +# sub_meta_info = self.meta_info + +# if deepcopy: +# sub_meta_info = copy.deepcopy(sub_meta_info) + +# return DataProto(batch=sub_batch, non_tensor_batch=non_tensor_batch, meta_info=sub_meta_info) + +# def index_select(self, index: Union[list[int], NDArray, torch.Tensor]) -> "DataProto": +# """Select a subset via index.""" +# if isinstance(index, list): +# index = np.array(index, dtype=bool if isinstance(index[0], bool) else np.int32) +# elif isinstance(index, torch.Tensor): +# index = index.detach().cpu().numpy() + +# tensor_data = self.batch[index] if self.batch is not None else None +# non_tensor_data = {key: value[index] for key, value in self.non_tensor_batch.items()} +# return DataProto(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info) + +# def slice_select( +# self, start: Optional[int] = None, end: Optional[int] = None, step: Optional[int] = None +# ) -> "DataProto": +# """Select a subset via slice.""" +# index = slice(start, end, step) +# tensor_data = self.batch[index] if self.batch is not None else None +# non_tensor_data = {key: value[index] for key, value in self.non_tensor_batch.items()} +# return DataProto(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info) + +# def pop( +# self, +# batch_keys: Optional[list[str]] = None, +# non_tensor_batch_keys: Optional[list[str]] = None, +# meta_info_keys: Optional[list[str]] = None, +# ) -> "DataProto": +# """Pop a subset of the DataProto via keys""" +# assert batch_keys is not None +# non_tensor_batch_keys = non_tensor_batch_keys or [] +# meta_info_keys = meta_info_keys or [] + +# tensors = {} +# for key in filter(lambda k: k in self.batch, batch_keys): +# tensors[key] = self.batch.pop(key) + +# non_tensors = {} +# for key in filter(lambda k: k in self.non_tensor_batch, non_tensor_batch_keys): +# non_tensors[key] = self.non_tensor_batch.pop(key) + +# meta_info = {} +# for key in filter(lambda k: k in self.meta_info, meta_info_keys): +# meta_info[key] = self.meta_info.pop(key) + +# return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info) + +# def rename( +# self, old_keys: Optional[Union[str, list[str]]] = None, new_keys: Optional[Union[str, list[str]]] = None +# ) -> "DataProto": +# """Rename keys in the batch only.""" +# def validate_input(keys): +# if keys is not None: +# if isinstance(keys, str): +# keys = [keys] +# elif isinstance(keys, list): +# pass +# else: +# raise TypeError(f"keys must be a list or a string, but got {type(keys)}") +# return keys + +# old_keys = validate_input(old_keys) +# new_keys = validate_input(new_keys) + +# if len(new_keys) != len(old_keys): +# raise ValueError( +# f"new_keys and old_keys must have the same length, but got {len(new_keys)} and {len(old_keys)}" +# ) + +# self.batch.rename_key_(tuple(old_keys), tuple(new_keys)) +# return self + +# def union(self, other: "DataProto") -> "DataProto": +# """Union with another DataProto. Union batch and meta_info separately.""" +# self.batch = union_tensor_dict(self.batch, other.batch) +# self.non_tensor_batch = union_numpy_dict(self.non_tensor_batch, other.non_tensor_batch) +# self.meta_info = union_two_dict(self.meta_info, other.meta_info) +# return self + +# def make_iterator( +# self, mini_batch_size: int, epochs: int, seed: int = None, dataloader_kwargs: dict[str, Any] = None +# ): +# """Make an iterator from the DataProto.""" +# assert self.batch.batch_size[0] % mini_batch_size == 0, f"{self.batch.batch_size[0]} % {mini_batch_size} != 0" +# if seed is not None: +# generator = torch.Generator() +# generator.manual_seed(seed) +# else: +# generator = None + +# dataloader_kwargs = dataloader_kwargs or {} +# assert isinstance(dataloader_kwargs, dict) +# train_dataloader = DataLoader( +# dataset=self, +# batch_size=mini_batch_size, +# collate_fn=collate_fn, +# generator=generator, +# **dataloader_kwargs, +# ) + +# def get_data(): +# for _ in range(epochs): +# for data in train_dataloader: +# setattr(data, "meta_info", self.meta_info) +# yield data + +# return iter(get_data()) + +# def chunk(self, chunks: int) -> list["DataProto"]: +# """Split the batch among dim=0 into chunks.""" +# assert len(self) % chunks == 0, ( +# f"only support equal chunk. Got size of DataProto {len(self)} and chunk {chunks}." +# ) +# if self.batch is not None: +# batch_lst = self.batch.chunk(chunks=chunks, dim=0) +# else: +# batch_lst = [None for _ in range(chunks)] + +# non_tensor_batch_lst = [{} for _ in range(chunks)] +# for key, value in self.non_tensor_batch.items(): +# non_tensor_lst = np.array_split(value, chunks) +# for i in range(chunks): +# non_tensor_batch_lst[i][key] = non_tensor_lst[i] + +# return [ +# DataProto(batch=batch_lst[i], non_tensor_batch=non_tensor_batch_lst[i], meta_info=self.meta_info) +# for i in range(chunks) +# ] + +# def split(self, split_size: int) -> list["DataProto"]: +# """Split the batch among dim=0 into chunks.""" +# assert len(self) % split_size == 0, ( +# f"only support equal split. Got size of DataProto {len(self)} and split {split_size}." +# ) +# chunks = len(self) // split_size +# return self.chunk(chunks) + +# @staticmethod +# def concat(data: list["DataProto"]) -> "DataProto": +# """Concat a list of DataProto.""" +# batch_lst = [batch.batch for batch in data] +# new_batch = torch.cat(batch_lst, dim=0) if batch_lst[0] is not None else None +# non_tensor_batch = batch_collate([d.non_tensor_batch for d in data]) +# for key, value in non_tensor_batch.items(): +# non_tensor_batch[key] = np.concatenate(value, axis=0) + +# return DataProto(batch=new_batch, non_tensor_batch=non_tensor_batch, meta_info=data[0].meta_info) + +# def reorder(self, indices: torch.Tensor) -> None: +# """In-place reorder by indices.""" +# indices_np = indices.detach().numpy() +# self.batch = self.batch[indices] +# self.non_tensor_batch = {key: value[indices_np] for key, value in self.non_tensor_batch.items()} + +# def repeat(self, repeat_times: int, interleave: bool = True) -> "DataProto": +# """Repeat the batch data a specified number of times.""" +# if self.batch is not None: +# if interleave: +# repeated_tensors = { +# key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items() +# } +# else: +# repeated_tensors = { +# key: tensor.unsqueeze(0).expand(repeat_times, *tensor.shape).reshape(-1, *tensor.shape[1:]) +# for key, tensor in self.batch.items() +# } + +# repeated_batch = TensorDict( +# source=repeated_tensors, +# batch_size=(self.batch.batch_size[0] * repeat_times,), +# ) +# else: +# repeated_batch = None + +# repeated_non_tensor_batch = {} +# for key, value in self.non_tensor_batch.items(): +# if interleave: +# repeated_non_tensor_batch[key] = np.repeat(value, repeat_times, axis=0) +# else: +# repeated_non_tensor_batch[key] = np.tile(value, (repeat_times,) + (1,) * (value.ndim - 1)) + +# return DataProto( +# batch=repeated_batch, +# non_tensor_batch=repeated_non_tensor_batch, +# meta_info=self.meta_info, +# ) + + +# @dataclass +# class DataProtoFuture: +# """ +# DataProtoFuture aims to eliminate actual data fetching on driver. +# """ + +# collect_fn: Callable +# futures: list[ray.ObjectRef] +# dispatch_fn: Callable = None + +# @staticmethod +# def concat(data: list[ray.ObjectRef]) -> "DataProtoFuture": +# output = DataProtoFuture(collect_fn=DataProto.concat, futures=data) +# return output + +# def chunk(self, chunks: int) -> list["DataProtoFuture"]: +# from functools import partial + +# arg_future_lst = [] +# for i in range(chunks): +# # note that we can't directly pass i and chunks +# def dispatch_fn(x, i, chunks): +# return x.chunk(chunks=chunks)[i] + +# arg_future = DataProtoFuture( +# collect_fn=self.collect_fn, dispatch_fn=partial(dispatch_fn, i=i, chunks=chunks), futures=self.futures +# ) +# arg_future_lst.append(arg_future) +# return arg_future_lst + +# def get(self): +# outputs = ray.get(self.futures) # dp_size +# for output in outputs: +# assert isinstance(output, DataProto) + +# outputs = self.collect_fn(outputs) # select dp, concat +# if self.dispatch_fn is not None: +# outputs = self.dispatch_fn(outputs) # split in batch dim, select using dp + +# return outputs + + +# def allgather_dict_tensors( +# tensors: Union[dict[str, torch.Tensor], TensorDict], size: int, group: ProcessGroup, dim: int = 0 +# ) -> Union[dict[str, torch.Tensor], TensorDict]: +# """ +# TODO: optimize this. +# - We can use async ops +# - We can use only one allgather +# """ +# if isinstance(tensors, TensorDict): +# is_tensor_dict = True +# tensors_as_dict = tensors.to_dict() +# else: +# tensors_as_dict = tensors +# is_tensor_dict = False + +# output = {} +# sorted_keys = sorted(tensors_as_dict.keys()) +# for key in sorted_keys: +# value = tensors_as_dict[key] +# output[key] = [torch.empty_like(value) for _ in range(size)] +# torch.distributed.all_gather(output[key], value, group=group, async_op=False) +# output[key] = torch.cat(output[key], dim=dim) + +# if is_tensor_dict: +# output = TensorDict(source=output, batch_size=tensors.batch_size[0] * size) + +# return output + + +# def all_gather_data_proto(data: DataProto, size: int, group: ProcessGroup) -> None: +# # Note that this is an inplace operator just like torch.distributed.all_gather +# prev_device = data.batch.device +# data.batch = data.batch.cuda(device=torch.cuda.current_device()) +# data.batch = allgather_dict_tensors(data.batch.contiguous(), size=size, group=group, dim=0) +# data.batch = data.batch.to(prev_device) +# # all gather non_tensor_batch +# all_non_tensor_batch = [None for _ in range(size)] +# torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=group) +# data.non_tensor_batch = {k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch} + + + + + +# 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. +""" +Implement base data transfer protocol between any two functions, modules. +We can subclass Protocol to define more detailed batch info with specific keys +""" + +import copy +import io +import pickle +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Any, Callable, Optional, Union + +import numpy as np +import ray +import torch +from numpy.typing import NDArray +from tensordict import TensorDict +from torch.distributed import ProcessGroup +from torch.utils.data import DataLoader + +from .utils.py_functional import union_two_dict + + +try: + import tensordict + + tensordict.set_lazy_legacy(False).set() +except Exception: + pass + + +__all__ = ["DataProto", "union_tensor_dict"] + + +def pad_dataproto_to_divisor(data: "DataProto", size_divisor: int) -> tuple["DataProto", int]: + """Pad a DataProto to size divisible by size_divisor + + Args: + data (DataProto): the unpadded DataProto + size_divisor (int): size divisor + + Returns: + data (DataProto): the padded DataProto + pad_size (int) + """ + assert isinstance(data, DataProto), "data must be a DataProto" + if len(data) % size_divisor != 0: + pad_size = size_divisor - len(data) % size_divisor + padding_protos = [] + remaining_pad = pad_size + while remaining_pad > 0: + take_size = min(remaining_pad, len(data)) + padding_protos.append(data[:take_size]) + remaining_pad -= take_size + + data_padded = DataProto.concat([data] + padding_protos) + else: + pad_size = 0 + data_padded = data + + return data_padded, pad_size + + +def unpad_dataproto(data: "DataProto", pad_size: int) -> "DataProto": + if pad_size != 0: + data = data[:-pad_size] + + return data + + +def union_tensor_dict(tensor_dict1: TensorDict, tensor_dict2: TensorDict) -> TensorDict: + """Union two tensordicts.""" + if tensor_dict1.batch_size != tensor_dict2.batch_size: + raise ValueError( + f"Two tensor dict must have identical batch size. Got {tensor_dict1.batch_size} and {tensor_dict2.batch_size}" + ) + + for key in tensor_dict2.keys(): + if key in tensor_dict1 and not torch.equal(tensor_dict1[key], tensor_dict2[key]): + raise ValueError(f"Key already exists: {key}.") + + tensor_dict1[key] = tensor_dict2[key] + + return tensor_dict1 + + +def union_numpy_dict(tensor_dict1: dict[str, NDArray], tensor_dict2: dict[str, NDArray]) -> dict[str, NDArray]: + for key in tensor_dict2.keys(): + if key in tensor_dict1: + assert isinstance(tensor_dict2[key], np.ndarray) + assert isinstance(tensor_dict1[key], np.ndarray) + if not np.all(tensor_dict1[key] == tensor_dict2[key]): + raise ValueError(f"Key already exists: {key}.") + + tensor_dict1[key] = tensor_dict2[key] + + return tensor_dict1 + + +def batch_collate(features: list[dict[str, Any]]) -> dict[str, list[Any]]: + if len(features) == 0: + return {} + + batch_features = defaultdict(list) + for feature in features: + for key, value in feature.items(): + batch_features[key].append(value) + + return batch_features + + +def fold_batch_dim(data: "DataProto", new_batch_size: int): + """ + Fold a batch dim from [bsz, xxx] into [new_bsz, bsz // new_bsz, xxx] + """ + batch_size = data.batch.batch_size[0] + + assert batch_size % new_batch_size == 0 + + tensor: TensorDict = data.batch + non_tensor = data.non_tensor_batch + + tensor = tensor.view(new_batch_size, -1) + tensor.auto_batch_size_(batch_dims=1) + + for key, value in non_tensor.items(): + non_tensor[key] = np.reshape(value, newshape=(new_batch_size, -1, *value.shape[1:])) + + return DataProto(batch=tensor, non_tensor_batch=non_tensor, meta_info=data.meta_info) + + +def collate_fn(data_items: list["DataProtoItem"]): + batch = [] + non_tensor_batch = [] + for data in data_items: + batch.append(data.batch) + non_tensor_batch.append(data.non_tensor_batch) + + batch = torch.stack(batch).contiguous() + non_tensor_batch = batch_collate(non_tensor_batch) + non_tensor_batch = {key: np.array(value, dtype=object) for key, value in non_tensor_batch.items()} + return DataProto(batch=batch, non_tensor_batch=non_tensor_batch) + + +@dataclass +class DataProtoItem: + batch: Optional[TensorDict] = None + non_tensor_batch: dict[str, NDArray] = field(default_factory=dict) + meta_info: dict[str, Any] = field(default_factory=dict) + + +@dataclass +class DataProto: + """ + A DataProto is a data structure that aims to provide a standard protocol for data exchange between functions. + It contains a batch (TensorDict) and a meta_info (Dict). The batch is a TensorDict https://pytorch.org/tensordict/. + TensorDict allows you to manipulate a dictionary of Tensors like a single Tensor. Ideally, the tensors with the + same batch size should be put inside batch. + """ + + batch: Optional[TensorDict] = None + non_tensor_batch: dict[str, NDArray] = field(default_factory=dict) + meta_info: dict[str, Any] = field(default_factory=dict) + + def __post_init__(self): + self.check_consistency() # perform necessary checking + + def __len__(self) -> int: + if self.batch is not None: + return self.batch.batch_size[0] + elif self.non_tensor_batch is not None and len(self.non_tensor_batch) > 0: + pivot_key = list(self.non_tensor_batch.keys())[0] + return self.non_tensor_batch[pivot_key].shape[0] + else: + return 0 + + def __getitem__( + self, item: Union[int, slice, list[int], np.ndarray, torch.Tensor] + ) -> Union["DataProto", "DataProtoItem"]: + if isinstance(item, slice): + return self.slice_select(item.start, item.stop, item.step) + + if isinstance(item, (list, np.ndarray, torch.Tensor)): + return self.index_select(item) + + if isinstance(item, (int, np.integer)): + tensor_data = self.batch[item] if self.batch is not None else None + non_tensor_data = {key: value[item] for key, value in self.non_tensor_batch.items()} + return DataProtoItem(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info) + + raise TypeError(f"Indexing with {type(item)} is not supported.") + + def __getstate__(self) -> tuple[bytes, dict[str, NDArray], dict[str, Any]]: + if self.batch is not None: + batch_to_save: TensorDict = self.batch.contiguous() + batch_to_save: TensorDict = batch_to_save.consolidate() + else: + batch_to_save = None + + buffer = io.BytesIO() + torch.save(batch_to_save, buffer) + buffer_bytes = buffer.getvalue() + return buffer_bytes, self.non_tensor_batch, self.meta_info + + def __setstate__(self, data: tuple[bytes, dict[str, NDArray], dict[str, Any]]) -> None: + batch_deserialized_bytes, non_tensor_batch, meta_info = data + batch_deserialized = io.BytesIO(batch_deserialized_bytes) + batch = torch.load(batch_deserialized, weights_only=False, map_location="cpu") + self.batch = batch + self.non_tensor_batch = non_tensor_batch + self.meta_info = meta_info + + def save_to_disk(self, filepath: str) -> None: + with open(filepath, "wb") as f: + pickle.dump(self, f) + + @staticmethod + def load_from_disk(filepath: str) -> "DataProto": + with open(filepath, "rb") as f: + data = pickle.load(f) + return data + + def print_size(self, prefix: str = "") -> None: + size_of_tensordict = 0 + if self.batch is not None: + for tensor in self.batch.values(): + if isinstance(tensor, torch.Tensor): + size_of_tensordict += tensor.element_size() * tensor.numel() + + size_of_numpy_array = 0 + for value in self.non_tensor_batch.values(): + size_of_numpy_array += value.nbytes + + size_of_numpy_array /= 1024**3 + size_of_tensordict /= 1024**3 + + message = f"Size of tensordict: {size_of_tensordict} GB, size of non_tensor_batch: {size_of_numpy_array} GB." + print({prefix}, {message}) + + def check_consistency(self): + """Check the consistency of the DataProto. Mainly for batch and non_tensor_batch + We expose this function as a public one so that user can call themselves directly + """ + if self.batch is not None: + assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1" + + if self.batch is not None and len(self.non_tensor_batch) != 0: + # TODO: we can actually lift this restriction if needed + assert len(self.batch.batch_size) == 1, "only support num_batch_dims=1 when non_tensor_batch is not empty." + + batch_size = self.batch.batch_size[0] + #print(self.non_tensor_batch.items()) + for key, value in self.non_tensor_batch.items(): + assert len(value) == batch_size, f"key {key} length {len(value)} is not equal to bsz {batch_size}." + + @classmethod + def from_single_dict( + cls, + data: dict[str, Union[torch.Tensor, NDArray]], + meta_info: Optional[dict[str, Any]] = None, + ) -> "DataProto": + tensors, non_tensors = {}, {} + for key, value in data.items(): + if isinstance(value, torch.Tensor): + tensors[key] = value + elif isinstance(value, np.ndarray): + non_tensors[key] = value + else: + raise ValueError(f"Unsupported type in data {type(value)}") + + return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info) + + @classmethod + def from_dict( + cls, + tensors: Optional[dict[str, torch.Tensor]] = None, + non_tensors: Optional[dict[str, NDArray]] = None, + meta_info: Optional[dict[str, Any]] = None, + num_batch_dims: int = 1, + ) -> "DataProto": + """Create a DataProto from a dict of tensors. This assumes that + 1. All the tensor in tensors have the same dim0 + 2. Only dim0 is the batch dim + """ + assert num_batch_dims > 0, "num_batch_dims must be greater than zero" + if non_tensors is not None: + assert num_batch_dims == 1, "only support num_batch_dims=1 when non_tensors is not None." + + tensors = tensors or {} + non_tensors = non_tensors or {} + meta_info = meta_info or {} + assert isinstance(tensors, dict) and isinstance(non_tensors, dict) and isinstance(meta_info, dict) + + # get and check batch size + batch_size = None + pivot_key = None + for key, tensor in tensors.items(): + if batch_size is None: + batch_size = tensor.shape[:num_batch_dims] + pivot_key = key + else: + current_batch = tensor.shape[:num_batch_dims] + assert batch_size == current_batch, ( + f"Not all the tensor in tensors have the same batch size with batch_dims={num_batch_dims}. " + f"Got {pivot_key} has {batch_size}, {key} has {current_batch}." + ) + + for key, value in non_tensors.items(): + if not isinstance(value, np.ndarray) or value.dtype != np.dtype(object): + non_tensors[key] = np.array(value, dtype=object) + + tensor_dict = TensorDict(source=tensors, batch_size=batch_size) if tensors else None + return cls(batch=tensor_dict, non_tensor_batch=non_tensors, meta_info=meta_info) + + def to(self, device: torch.device, non_blocking: bool = False) -> "DataProto": + """Move the batch to device + + Args: + device (torch.device): the device to move to. + non_blocking (bool, optional): whether to use non-blocking mode. Defaults to False. + + Returns: + DataProto: the current DataProto. + + NOTE: remember to use torch.cuda.synchronize() after self.to("cpu") to avoid weird number + """ + if self.batch is not None: + self.batch = self.batch.to(device, non_blocking=non_blocking) + + return self + + def select( + self, + batch_keys: Optional[list[str]] = None, + non_tensor_batch_keys: Optional[list[str]] = None, + meta_info_keys: Optional[list[str]] = None, + deepcopy: bool = False, + ) -> "DataProto": + """Select a subset of the DataProto via batch_keys and meta_info_keys + + Args: + batch_keys (list, optional): a list of strings indicating the keys in batch to select + meta_info_keys (list, optional): a list of keys indicating the meta info to select + + Returns: + DataProto: the DataProto with the selected batch_keys and meta_info_keys + """ + # TODO (zhangchi.usc1992) whether to copy + if batch_keys is not None: + batch_keys = tuple(filter(lambda k: k in self.batch, batch_keys)) + sub_batch = self.batch.select(*batch_keys) + else: + sub_batch = self.batch + + if non_tensor_batch_keys is not None: + # we must convert it to tuple to avoid the missing elements + non_tensor_batch_keys = tuple(filter(lambda k: k in self.non_tensor_batch, non_tensor_batch_keys)) + non_tensor_batch = {k: v for k, v in self.non_tensor_batch.items() if k in non_tensor_batch_keys} + else: + non_tensor_batch = self.non_tensor_batch + + if deepcopy: + non_tensor_batch = copy.deepcopy(non_tensor_batch) + + if meta_info_keys is not None: + meta_info_keys = tuple(filter(lambda k: k in self.meta_info, meta_info_keys)) + sub_meta_info = {k: v for k, v in self.meta_info.items() if k in meta_info_keys} + else: + sub_meta_info = self.meta_info + + if deepcopy: + sub_meta_info = copy.deepcopy(sub_meta_info) + + return DataProto(batch=sub_batch, non_tensor_batch=non_tensor_batch, meta_info=sub_meta_info) + + def index_select(self, index: Union[list[int], NDArray, torch.Tensor]) -> "DataProto": + """Select a subset of the DataProto via index. + + Args: + index (list, ndarray, torch.Tensor): a list of indices to select. + + Returns: + DataProto: the DataProto containing the selected indices. + """ + if isinstance(index, list): + index = np.array(index, dtype=bool if isinstance(index[0], bool) else np.int32) + elif isinstance(index, torch.Tensor): + index = index.detach().cpu().numpy() + + tensor_data = self.batch[index] if self.batch is not None else None + non_tensor_data = {key: value[index] for key, value in self.non_tensor_batch.items()} + return DataProto(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info) + + def slice_select( + self, start: Optional[int] = None, end: Optional[int] = None, step: Optional[int] = None + ) -> "DataProto": + """Select a subset of the DataProto via slice. + + Args: + start (int, optional): the start index of the slice. + end (int, optional): the end index of the slice. + step (int, optional): the step of the slice. + + Returns: + DataProto: the DataProto containing the selected slice. + """ + index = slice(start, end, step) + tensor_data = self.batch[index] if self.batch is not None else None + non_tensor_data = {key: value[index] for key, value in self.non_tensor_batch.items()} + return DataProto(batch=tensor_data, non_tensor_batch=non_tensor_data, meta_info=self.meta_info) + + def pop( + self, + batch_keys: Optional[list[str]] = None, + non_tensor_batch_keys: Optional[list[str]] = None, + meta_info_keys: Optional[list[str]] = None, + ) -> "DataProto": + """Pop a subset of the DataProto via `batch_keys` and `meta_info_keys` + + Args: + batch_keys (list, optional): a list of strings indicating the keys in batch to pop + meta_info_keys (list, optional): a list of keys indicating the meta info to pop + + Returns: + DataProto: the DataProto with the poped batch_keys and meta_info_keys + """ + assert batch_keys is not None + non_tensor_batch_keys = non_tensor_batch_keys or [] + meta_info_keys = meta_info_keys or [] + + tensors = {} + for key in filter(lambda k: k in self.batch, batch_keys): + tensors[key] = self.batch.pop(key) + + non_tensors = {} + for key in filter(lambda k: k in self.non_tensor_batch, non_tensor_batch_keys): + non_tensors[key] = self.non_tensor_batch.pop(key) + + meta_info = {} + for key in filter(lambda k: k in self.meta_info, meta_info_keys): + meta_info[key] = self.meta_info.pop(key) + + return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info) + + def rename( + self, old_keys: Optional[Union[str, list[str]]] = None, new_keys: Optional[Union[str, list[str]]] = None + ) -> "DataProto": + """ + Note that this function only rename the key in the batch + """ + + def validate_input(keys): + if keys is not None: + if isinstance(keys, str): + keys = [keys] + elif isinstance(keys, list): + pass + else: + raise TypeError(f"keys must be a list or a string, but got {type(keys)}") + return keys + + old_keys = validate_input(old_keys) + new_keys = validate_input(new_keys) + + if len(new_keys) != len(old_keys): + raise ValueError( + f"new_keys and old_keys must have the same length, but got {len(new_keys)} and {len(old_keys)}" + ) + + self.batch.rename_key_(tuple(old_keys), tuple(new_keys)) + + return self + + def union(self, other: "DataProto") -> "DataProto": + """Union with another DataProto. Union batch and meta_info separately. + Throw an error if + - there are conflict keys in batch and they are not equal + - the batch size of two data batch is not the same + - there are conflict keys in meta_info and they are not the same. + + Args: + other (DataProto): another DataProto to union + + Returns: + DataProto: the DataProto after union + """ + self.batch = union_tensor_dict(self.batch, other.batch) + self.non_tensor_batch = union_numpy_dict(self.non_tensor_batch, other.non_tensor_batch) + self.meta_info = union_two_dict(self.meta_info, other.meta_info) + return self + + def make_iterator( + self, mini_batch_size: int, epochs: int, seed: int = None, dataloader_kwargs: dict[str, Any] = None + ): + """Make an iterator from the DataProto. This is built upon that TensorDict can be used as a normal Pytorch + dataset. See https://pytorch.org/tensordict/tutorials/data_fashion for more details. + + Args: + mini_batch_size (int): mini-batch size when iterating the dataset. We require that + ``batch.batch_size[0] % mini_batch_size == 0`` + epochs (int): number of epochs when iterating the dataset. + dataloader_kwargs: internally, it returns a DataLoader over the batch. + The dataloader_kwargs is the kwargs passed to the DataLoader + + Returns: + Iterator: an iterator that yields a mini-batch data at a time. The total number of iteration steps is + ``self.batch.batch_size * epochs // mini_batch_size`` + """ + assert self.batch.batch_size[0] % mini_batch_size == 0, f"{self.batch.batch_size[0]} % {mini_batch_size} != 0" + if seed is not None: + generator = torch.Generator() + generator.manual_seed(seed) + else: + generator = None + + dataloader_kwargs = dataloader_kwargs or {} + assert isinstance(dataloader_kwargs, dict) + train_dataloader = DataLoader( + dataset=self, + batch_size=mini_batch_size, + collate_fn=collate_fn, + generator=generator, + **dataloader_kwargs, + ) + + def get_data(): + for _ in range(epochs): + for data in train_dataloader: + setattr(data, "meta_info", self.meta_info) + yield data + + return iter(get_data()) + + def chunk(self, chunks: int) -> list["DataProto"]: + """Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split. + + Args: + chunks (int): the number of chunks to split on dim=0 + + Returns: + List[DataProto]: a list of DataProto after splitting + """ + assert len(self) % chunks == 0, ( + f"only support equal chunk. Got size of DataProto {len(self)} and chunk {chunks}." + ) + if self.batch is not None: + batch_lst = self.batch.chunk(chunks=chunks, dim=0) + else: + batch_lst = [None for _ in range(chunks)] + + non_tensor_batch_lst = [{} for _ in range(chunks)] + for key, value in self.non_tensor_batch.items(): + non_tensor_lst = np.array_split(value, chunks) + for i in range(chunks): + non_tensor_batch_lst[i][key] = non_tensor_lst[i] + + return [ + DataProto(batch=batch_lst[i], non_tensor_batch=non_tensor_batch_lst[i], meta_info=self.meta_info) + for i in range(chunks) + ] + + def split(self, split_size: int) -> list["DataProto"]: + """Split the batch among dim=0 into chunks. The meta_info is passed to each DataProto after split. + + Args: + split_size (int): the size of each split + + Returns: + List[DataProto]: a list of DataProto after splitting + """ + assert len(self) % split_size == 0, ( + f"only support equal split. Got size of DataProto {len(self)} and split {split_size}." + ) + chunks = len(self) // split_size + return self.chunk(chunks) + + @staticmethod + def concat(data: list["DataProto"]) -> "DataProto": + """Concat a list of DataProto. The batch is concatenated among dim=0. + The meta_info is assumed to be identical and will use the first one. + + Args: + data (List[DataProto]): list of DataProto + + Returns: + DataProto: concatenated DataProto + """ + batch_lst = [batch.batch for batch in data] + new_batch = torch.cat(batch_lst, dim=0) if batch_lst[0] is not None else None + non_tensor_batch = batch_collate([d.non_tensor_batch for d in data]) + for key, value in non_tensor_batch.items(): + non_tensor_batch[key] = np.concatenate(value, axis=0) + + return DataProto(batch=new_batch, non_tensor_batch=non_tensor_batch, meta_info=data[0].meta_info) + + def reorder(self, indices: torch.Tensor) -> None: + """ + Note that this operation is in-place + """ + indices_np = indices.detach().numpy() + self.batch = self.batch[indices] + self.non_tensor_batch = {key: value[indices_np] for key, value in self.non_tensor_batch.items()} + + def repeat(self, repeat_times: int, interleave: bool = True) -> "DataProto": + """ + Repeat the batch data a specified number of times. + + Args: + repeat_times (int): Number of times to repeat the data. + interleave (bool): Whether to interleave the repeated data. + + Returns: + DataProto: A new DataProto with repeated data. + """ + if self.batch is not None: + if interleave: # interleave the data + repeated_tensors = { + key: tensor.repeat_interleave(repeat_times, dim=0) for key, tensor in self.batch.items() + } + else: # stack the data + repeated_tensors = { + key: tensor.unsqueeze(0).expand(repeat_times, *tensor.shape).reshape(-1, *tensor.shape[1:]) + for key, tensor in self.batch.items() + } + + repeated_batch = TensorDict( + source=repeated_tensors, + batch_size=(self.batch.batch_size[0] * repeat_times,), + ) + else: + repeated_batch = None + + repeated_non_tensor_batch = {} + for key, value in self.non_tensor_batch.items(): + if interleave: + repeated_non_tensor_batch[key] = np.repeat(value, repeat_times, axis=0) + else: + repeated_non_tensor_batch[key] = np.tile(value, (repeat_times,) + (1,) * (value.ndim - 1)) + + return DataProto( + batch=repeated_batch, + non_tensor_batch=repeated_non_tensor_batch, + meta_info=self.meta_info, + ) + + +@dataclass +class DataProtoFuture: + """ + DataProtoFuture aims to eliminate actual data fetching on driver. By doing so, the driver doesn't have to wait + for data so that asynchronous execution becomes possible. + DataProtoFuture contains a list of futures from another WorkerGroup of size world_size. + - collect_fn is a Callable that reduces the list of futures to a DataProto + - dispatch_fn is a Callable that partitions the DataProto into a list of DataProto of size world_size and then select + + Potential issue: we can optimize dispatch_fn(collect_fn) such that only needed data is fetched on destination + - DataProtoFuture only supports directly passing from the output of a method to another input. You can't perform any + operation on the DataProtoFuture in driver. + """ + + collect_fn: Callable + futures: list[ray.ObjectRef] + dispatch_fn: Callable = None + + @staticmethod + def concat(data: list[ray.ObjectRef]) -> "DataProtoFuture": + output = DataProtoFuture(collect_fn=DataProto.concat, futures=data) + return output + + def chunk(self, chunks: int) -> list["DataProtoFuture"]: + from functools import partial + + arg_future_lst = [] + for i in range(chunks): + # note that we can't directly pass i and chunks + def dispatch_fn(x, i, chunks): + return x.chunk(chunks=chunks)[i] + + arg_future = DataProtoFuture( + collect_fn=self.collect_fn, dispatch_fn=partial(dispatch_fn, i=i, chunks=chunks), futures=self.futures + ) + arg_future_lst.append(arg_future) + return arg_future_lst + + def get(self): + outputs = ray.get(self.futures) # dp_size + for output in outputs: + assert isinstance(output, DataProto) + + outputs = self.collect_fn(outputs) # select dp, concat + if self.dispatch_fn is not None: + outputs = self.dispatch_fn(outputs) # split in batch dim, select using dp + + return outputs + + +def allgather_dict_tensors( + tensors: Union[dict[str, torch.Tensor], TensorDict], size: int, group: ProcessGroup, dim: int = 0 +) -> Union[dict[str, torch.Tensor], TensorDict]: + """ + TODO: optimize this. + - We can use async ops + - We can use only one allgather + """ + if isinstance(tensors, TensorDict): + is_tensor_dict = True + tensors_as_dict = tensors.to_dict() + else: + tensors_as_dict = tensors + is_tensor_dict = False + + output = {} + sorted_keys = sorted(tensors_as_dict.keys()) + for key in sorted_keys: + value = tensors_as_dict[key] + output[key] = [torch.empty_like(value) for _ in range(size)] + torch.distributed.all_gather(output[key], value, group=group, async_op=False) + output[key] = torch.cat(output[key], dim=dim) + + if is_tensor_dict: + output = TensorDict(source=output, batch_size=tensors.batch_size[0] * size) + + return output + + +def all_gather_data_proto(data: DataProto, size: int, group: ProcessGroup) -> None: + # Note that this is an inplace operator just like torch.distributed.all_gather + prev_device = data.batch.device + data.batch = data.batch.cuda(device=torch.cuda.current_device()) + data.batch = allgather_dict_tensors(data.batch.contiguous(), size=size, group=group, dim=0) + data.batch = data.batch.to(prev_device) + # all gather non_tensor_batch + all_non_tensor_batch = [None for _ in range(size)] + torch.distributed.all_gather_object(all_non_tensor_batch, data.non_tensor_batch, group=group) + data.non_tensor_batch = {k: np.concatenate([d[k] for d in all_non_tensor_batch]) for k in data.non_tensor_batch} diff --git a/model/EasyR1/verl/reward_function/__init__.py b/model/EasyR1/verl/reward_function/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/model/EasyR1/verl/reward_function/__pycache__/onethinker_reward.cpython-311.pyc b/model/EasyR1/verl/reward_function/__pycache__/onethinker_reward.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2b1b363c43e7d81917eb4a3b1deb49c2680477f Binary files /dev/null and b/model/EasyR1/verl/reward_function/__pycache__/onethinker_reward.cpython-311.pyc differ diff --git a/model/EasyR1/verl/reward_function/dapo.py b/model/EasyR1/verl/reward_function/dapo.py new file mode 100644 index 0000000000000000000000000000000000000000..9285cd1d0fddf892302f9b343ace79eb4ec8ca15 --- /dev/null +++ b/model/EasyR1/verl/reward_function/dapo.py @@ -0,0 +1,163 @@ +# 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. + +import re +from typing import Any + + +# Constants for normalization +SUBSTITUTIONS = [ + ("an ", ""), + ("a ", ""), + (".$", "$"), + ("\\$", ""), + (r"\ ", ""), + (" ", ""), + ("mbox", "text"), + (",\\text{and}", ","), + ("\\text{and}", ","), + ("\\text{m}", "\\text{}"), +] + +REMOVED_EXPRESSIONS = [ + "square", + "ways", + "integers", + "dollars", + "mph", + "inches", + "hours", + "km", + "units", + "\\ldots", + "sue", + "points", + "feet", + "minutes", + "digits", + "cents", + "degrees", + "cm", + "gm", + "pounds", + "meters", + "meals", + "edges", + "students", + "childrentickets", + "multiples", + "\\text{s}", + "\\text{.}", + "\\text{\ns}", + "\\text{}^2", + "\\text{}^3", + "\\text{\n}", + "\\text{}", + r"\mathrm{th}", + r"^\circ", + r"^{\circ}", + r"\;", + r",\!", + "{,}", + '"', + "\\dots", +] + + +def normalize_final_answer(final_answer: str) -> str: + """Normalize a final answer to a quantitative reasoning question. + + Args: + final_answer: The answer string to normalize + + Returns: + Normalized answer string + """ + final_answer = final_answer.split("=")[-1] + + # Apply substitutions and removals + for before, after in SUBSTITUTIONS: + final_answer = final_answer.replace(before, after) + for expr in REMOVED_EXPRESSIONS: + final_answer = final_answer.replace(expr, "") + + # Extract and normalize LaTeX math + final_answer = re.sub(r"(.*?)(\$)(.*?)(\$)(.*)", "$\\3$", final_answer) + final_answer = re.sub(r"(\\text\{)(.*?)(\})", "\\2", final_answer) + final_answer = re.sub(r"(\\textbf\{)(.*?)(\})", "\\2", final_answer) + final_answer = re.sub(r"(\\overline\{)(.*?)(\})", "\\2", final_answer) + final_answer = re.sub(r"(\\boxed\{)(.*)(\})", "\\2", final_answer) + + # Normalize shorthand TeX: + # \fracab -> \frac{a}{b} + # \frac{abc}{bef} -> \frac{abc}{bef} + # \fracabc -> \frac{a}{b}c + # \sqrta -> \sqrt{a} + # \sqrtab -> sqrt{a}b + final_answer = re.sub(r"(frac)([^{])(.)", "frac{\\2}{\\3}", final_answer) + final_answer = re.sub(r"(sqrt)([^{])", "sqrt{\\2}", final_answer) + final_answer = final_answer.replace("$", "") + + # Normalize numbers + if final_answer.replace(",", "").isdigit(): + final_answer = final_answer.replace(",", "") + + return final_answer.strip() + + +def accuracy_reward(response: str, ground_truth: str) -> float: + match = re.findall(r"(?i)Answer\s*:\s*([^\n]+)", response) + answer = match[-1] if match else "[INVALID]" + if normalize_final_answer(answer) == normalize_final_answer(ground_truth): + return 1.0 + else: + return -1.0 + + +def soft_overlong_punishment(response_length: int, max_response_length: int, overlong_buffer_length: int): + expected_len = max_response_length - overlong_buffer_length + if response_length <= expected_len: + return 0.0 + elif response_length <= max_response_length: + return (expected_len - response_length) / overlong_buffer_length + else: + return -1.0 + + +def compute_score( + reward_inputs: list[dict[str, Any]], + max_response_length: int, + overlong_buffer_length: int, + overlong_penalty_factor: float, +) -> list[dict[str, float]]: + if not isinstance(reward_inputs, list): + raise ValueError("Please use `reward_type=batch` for dapo reward function.") + + scores = [] + for reward_input in reward_inputs: + response = reward_input["response"][-300:] # The longest answer in MATH-500 has 159 characters + accuracy_score = accuracy_reward(response, reward_input["ground_truth"]) + overlong_score = soft_overlong_punishment( + reward_input["response_length"], max_response_length, overlong_buffer_length + ) + scores.append( + { + "overall": accuracy_score + overlong_score * overlong_penalty_factor, + "accuracy": accuracy_score, + "overlong": overlong_score, + "accuracy_normalized": 0.5 * (accuracy_score + 1.0), + } + ) + + return scores diff --git a/model/EasyR1/verl/reward_function/math.py b/model/EasyR1/verl/reward_function/math.py new file mode 100644 index 0000000000000000000000000000000000000000..ea75e3e91b5bdf2b7fe4825bd52630ebdcc60877 --- /dev/null +++ b/model/EasyR1/verl/reward_function/math.py @@ -0,0 +1,49 @@ +# 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. + +import re +from typing import Any + +from mathruler.grader import extract_boxed_content, grade_answer + + +def format_reward(response: str) -> float: + pattern = re.compile(r".*.*\\boxed\{.*\}.*", re.DOTALL) + format_match = re.fullmatch(pattern, response) + return 1.0 if format_match else 0.0 + + +def accuracy_reward(response: str, ground_truth: str) -> float: + answer = extract_boxed_content(response) + return 1.0 if grade_answer(answer, ground_truth) else 0.0 + + +def compute_score(reward_inputs: list[dict[str, Any]], format_weight: float = 0.1) -> list[dict[str, float]]: + if not isinstance(reward_inputs, list): + raise ValueError("Please use `reward_type=batch` for math reward function.") + + scores = [] + for reward_input in reward_inputs: + response = re.sub(r"\s*(<|>|/)\s*", r"\1", reward_input["response"]) # handle qwen2.5vl-32b format + format_score = format_reward(response) + accuracy_score = accuracy_reward(response, reward_input["ground_truth"]) + scores.append( + { + "overall": (1 - format_weight) * accuracy_score + format_weight * format_score, + "format": format_score, + "accuracy": accuracy_score, + } + ) + + return scores diff --git a/model/EasyR1/verl/reward_function/onethinker_reward.py b/model/EasyR1/verl/reward_function/onethinker_reward.py new file mode 100644 index 0000000000000000000000000000000000000000..e5501bfac73c8466743eaca55a72294a00e581c8 --- /dev/null +++ b/model/EasyR1/verl/reward_function/onethinker_reward.py @@ -0,0 +1,739 @@ +# -*- coding: utf-8 -*- +# Rewards for multimodal tasks with ...... outputs. +import re +import json +import math +import itertools +from typing import Any, Dict, List, Optional +import random + +import torch +from rouge_score import rouge_scorer +from math_verify import parse as math_parse, verify as math_verify +from mathruler.grader import grade_answer + +# ===================== Model-based reward configuration ===================== +# Whether to use external Reward Model to compute accuracy for open-ended type +USE_MODEL_FOR_OPEN_ENDED: bool = False + +# External RM model and service address (kept consistent with example) +RM_MODEL_PATH = "internlm/POLAR-7B" +RM_SERVER_ADDRESS = "xx.xx.xx.xx:xxxx" +# ========================================================== + +# ===================== External RM evaluation dependencies ===================== +from verl.workers.reward.model_reward import RewardModelClient +import numpy as np +# ========================================================= + + +# ------------------------- +# Patterns for format check +# ------------------------- +THINK_ANSWER_PATTERN = re.compile( + r"\A\s*.*?\s*.*?\s*\Z", + re.DOTALL +) + +ANSWER_CAPTURE_PATTERN = re.compile( + r"\s*(.*?)\s*", + re.DOTALL +) + + +# ------------------------- +# Utilities +# ------------------------- +def extract_answer(text: str) -> Optional[str]: + if not isinstance(text, str): + return None + m = ANSWER_CAPTURE_PATTERN.search(text) + return m.group(1).strip() if m else None + + +def normalize_number(num_str: str) -> Optional[float]: + try: + return float((num_str or "").replace(",", "")) + except Exception: + return None + + +def mean_relative_accuracy(pred, target, start=0.5, end=0.95, interval=0.05) -> float: + pred_t = torch.tensor(pred, dtype=torch.float32) + tgt_t = torch.tensor(target, dtype=torch.float32) + rel_error = torch.abs(pred_t - tgt_t) / (torch.abs(tgt_t) + 1e-8) + thresholds = torch.arange(start, end + interval/2, interval, dtype=torch.float32) + return (rel_error < (1 - thresholds)).float().mean().item() + + +def wer(reference: str, hypothesis: str) -> float: + ref_words, hyp_words = (reference or "").split(), (hypothesis or "").split() + m, n = len(ref_words), len(hyp_words) + d = [[0] * (n + 1) for _ in range(m + 1)] + for i in range(m + 1): d[i][0] = i + for j in range(n + 1): d[0][j] = j + for i in range(1, m + 1): + for j in range(1, n + 1): + d[i][j] = d[i - 1][j - 1] if ref_words[i - 1] == hyp_words[j - 1] else 1 + min( + d[i - 1][j], d[i][j - 1], d[i - 1][j - 1] + ) + return d[m][n] / max(1, m) + + +def compute_rouge_score(reference: str, hypothesis: str) -> float: + scorer = rouge_scorer.RougeScorer(['rouge1', 'rouge2', 'rougeL'], use_stemmer=True) + scores = scorer.score(reference or "", hypothesis or "") + return (scores['rouge1'].fmeasure + scores['rouge2'].fmeasure + scores['rougeL'].fmeasure) / 3.0 + + +# ---------- IoU helpers (strict format: must be numeric lists) ---------- +def _is_list_of_numbers(x, n=None): + if not isinstance(x, list): + return False + if n is not None and len(x) != n: + return False + try: + for v in x: + float(v) + return True + except Exception: + return False + + +def iou_1d(pred: List[float], gt: List[float]) -> float: + # Strict: must be numeric lists with length 2; otherwise return 0 + if not _is_list_of_numbers(pred, 2) or not _is_list_of_numbers(gt, 2): + return 0.0 + try: + s1, e1 = float(pred[0]), float(pred[1]) + s2, e2 = float(gt[0]), float(gt[1]) + except Exception: + return 0.0 + inter = max(0.0, min(e1, e2) - max(s1, s2)) + union = max(e1, e2) - min(s1, s2) + return inter / union if union > 1e-12 else 0.0 + + +def iou_2d(box1: List[float], box2: List[float]) -> float: + # Strict: must be numeric lists with length 4; otherwise return 0 + if not _is_list_of_numbers(box1, 4) or not _is_list_of_numbers(box2, 4): + return 0.0 + try: + x1, y1, x2, y2 = map(float, box1) + X1, Y1, X2, Y2 = map(float, box2) + except Exception: + return 0.0 + inter_x1, inter_y1 = max(x1, X1), max(y1, Y1) + inter_x2, inter_y2 = min(x2, X2), min(y2, Y2) + inter_area = max(0.0, inter_x2 - inter_x1) * max(0.0, inter_y2 - inter_y1) + area1 = max(0.0, x2 - x1) * max(0.0, y2 - y1) + area2 = max(0.0, X2 - X1) * max(0.0, Y2 - Y1) + union = area1 + area2 - inter_area + return inter_area / union if union > 1e-12 else 0.0 + + +def mean_iou_over_gt_frames(pred_boxes: Dict[str, List[float]], gt_boxes: Dict[str, List[float]]) -> float: + """ + For tracking: average over all GT frames (missing predicted frames are counted as 0). + pred_boxes, gt_boxes: {frame_str: [x1,y1,x2,y2]} + """ + if not isinstance(gt_boxes, dict) or not gt_boxes: + return 0.0 + total, n = 0.0, 0 + for k, gbox in gt_boxes.items(): + total += iou_2d(pred_boxes.get(k, []), gbox) + n += 1 + return total / n if n > 0 else 0.0 + + +def mean_iou_over_intersection(pred_boxes: Dict[str, List[float]], gt_boxes: Dict[str, List[float]]) -> float: + """ + For spatial-temporal tasks: IoU is averaged only over the intersection of frame keys + (missing frames are not penalized). + """ + if not isinstance(pred_boxes, dict) or not isinstance(gt_boxes, dict): + return 0.0 + common = [k for k in pred_boxes.keys() if k in gt_boxes] + if not common: + return 0.0 + vals = [iou_2d(pred_boxes[k], gt_boxes[k]) for k in common] + return sum(vals) / len(vals) if vals else 0.0 + + +# ------------------------- +# Segmentation point matching: strict 3↔3 optimal assignment +# ------------------------- +def _pairwise_l2(p, q) -> float: + try: + dx = float(p[0]) - float(q[0]) + dy = float(p[1]) - float(q[1]) + return math.hypot(dx, dy) + except Exception: + return float("inf") + + +def assignment_similarity_3(pred_pts: List[List[float]], + gt_pts: List[List[float]], + sigma: float = 50.0) -> float: + """ + 3↔3 optimal matching (minimal total distance), returns Gaussian kernel similarity: + sim = exp(- (avg_dist^2) / (2 * sigma^2)) ∈ [0,1] + + Explanation of parameters: + - sigma: controls sensitivity range (smaller → more sensitive, sharper) + - pred_pts, gt_pts: [[x,y], [x,y], [x,y]] exactly 3 points each + - If the number or format of points is invalid, return 0.0 + """ + # ----------- Check input validity ----------- + if not isinstance(pred_pts, list) or not isinstance(gt_pts, list) or len(pred_pts) != 3 or len(gt_pts) != 3: + return 0.0 + for p in pred_pts + gt_pts: + if not _is_list_of_numbers(p, 2): + return 0.0 + + # ----------- Compute optimal matching distance ----------- + best_sum = float('inf') + for perm in itertools.permutations(range(3)): + s = 0.0 + good = True + for i in range(3): + d = _pairwise_l2(pred_pts[perm[i]], gt_pts[i]) + if math.isinf(d): + good = False + break + s += d + if good: + best_sum = min(best_sum, s) + + if math.isinf(best_sum): + return 0.0 + + # ----------- Average distance & Gaussian similarity ----------- + avg_d = best_sum / 3.0 + sim = math.exp(- (avg_d ** 2) / (2 * sigma ** 2)) + return max(0.0, min(1.0, sim)) + + +# ------------------------- +# Format reward + structure reward +# ------------------------- +def tag_format_reward(response: str) -> float: + """ + Format requirement (format reward): + Must strictly be: ...... + Arbitrary newlines/whitespaces are allowed in the middle, but tag order and closures must be correct. + Returns 1.0 if satisfied; otherwise 0.0. + """ + return 1.0 if THINK_ANSWER_PATTERN.fullmatch(response or "") else 0.0 + + +def answer_structure_bonus(answer: str, ground_truth: str, data_type: str, problem_type: str) -> float: + """ + Structure requirements (structure reward): + - spatial-temporal grounding: + JSON structure must satisfy: + {"time": [s, e], "boxes": {"frame_id": [x1, y1, x2, y2], ...}} + +0.25 if the structure is valid; + plus bbox key overlap ratio * 0.25 (overlap ratio = |pred.keys ∩ gt.keys| / |gt.keys|). + - tracking: + JSON structure must satisfy: + {"boxes": {"frame_id": [x1, y1, x2, y2], ...}} + +0.25 if the structure is valid; + plus bbox key overlap ratio * 0.25. + - temporal grounding: + {"time": [s, e]} gets +0.5 if valid, otherwise 0. + - spatial grounding: + {"boxes": [x1, y1, x2, y2]} gets +0.5 if valid, otherwise 0. + - segmentation: + * image: + {"boxes": [..], "positive_points": [[x,y],[x,y],[x,y]], "negative_points": [[x,y],[x,y],[x,y]]} + * video: + {"time": t, "boxes": [..], "positive_points": [[x,y],[x,y],[x,y]], "negative_points": [[x,y],[x,y],[x,y]]} + +0.5 if the corresponding structure is satisfied, otherwise 0. + - Other non-structured tasks: default +0.5. + """ + ptype = (problem_type or "").lower() + dtype = (data_type or "").lower() + + def _json(s): + try: + return json.loads(s) + except Exception: + return None + + if ptype in {"spatial-temporal grounding", "tracking"}: + obj_pred = _json(answer) + obj_gt = _json(ground_truth) + part_json = 0.0 + part_overlap = 0.0 + + if ptype == "spatial-temporal grounding": + json_ok = ( + isinstance(obj_pred, dict) + and isinstance(obj_pred.get("time"), list) and len(obj_pred["time"]) == 2 + and isinstance(obj_pred.get("boxes"), dict) + and all(_is_list_of_numbers(v, 4) for v in obj_pred["boxes"].values()) + ) + else: # tracking + json_ok = ( + isinstance(obj_pred, dict) + and isinstance(obj_pred.get("boxes"), dict) + and all(_is_list_of_numbers(v, 4) for v in obj_pred["boxes"].values()) + ) + if json_ok: + part_json = 0.25 + + if isinstance(obj_pred, dict) and isinstance(obj_gt, dict): + pboxes = obj_pred.get("boxes", {}) + gboxes = obj_gt.get("boxes", {}) + if isinstance(pboxes, dict) and isinstance(gboxes, dict) and len(gboxes) > 0: + inter = set(pboxes.keys()) & set(gboxes.keys()) + overlap_ratio = len(inter) / float(len(gboxes)) + part_overlap = 0.25 * max(0.0, min(1.0, float(overlap_ratio))) + + return part_json + part_overlap + + needs_check = {"temporal grounding", "spatial grounding", "segmentation"} + # if ptype in needs_check: + if ptype in needs_check or "segmentation" in ptype: + obj = _json(answer) + if ptype == "temporal grounding": + ok = isinstance(obj, dict) and _is_list_of_numbers(obj.get("time"), 2) + return 0.5 if ok else 0.0 + + if ptype == "spatial grounding": + ok = isinstance(obj, dict) and _is_list_of_numbers(obj.get("boxes"), 4) + return 0.5 if ok else 0.0 + + # if ptype == "segmentation": + if ptype == "segmentation" or "segmentation" in ptype: + if dtype == "image": + ok = ( + isinstance(obj, dict) + and _is_list_of_numbers(obj.get("boxes"), 4) + and isinstance(obj.get("positive_points"), list) and len(obj["positive_points"]) == 3 + and isinstance(obj.get("negative_points"), list) and len(obj["negative_points"]) == 3 + and all(_is_list_of_numbers(p, 2) for p in obj["positive_points"]) + and all(_is_list_of_numbers(p, 2) for p in obj["negative_points"]) + ) + return 0.5 if ok else 0.0 + elif dtype == "video": + ok = ( + isinstance(obj, dict) + and isinstance(obj.get("time"), (int, float)) # time must be numeric + and _is_list_of_numbers(obj.get("boxes"), 4) + and isinstance(obj.get("positive_points"), list) and len(obj["positive_points"]) == 3 + and isinstance(obj.get("negative_points"), list) and len(obj["negative_points"]) == 3 + and all(_is_list_of_numbers(p, 2) for p in obj["positive_points"]) + and all(_is_list_of_numbers(p, 2) for p in obj["negative_points"]) + ) + return 0.5 if ok else 0.0 + else: + return 0.0 + + # Non-structured tasks: default +0.5 + return 0.5 + + +# ------------------------- +# Math equivalence helper +# ------------------------- +def _math_equivalent(gt: str, pred: str) -> bool: + """ + Use math_verify to perform symbolic equivalence checking; if it fails (exceptions, etc.), + fall back to grade_answer. + """ + try: + return bool(math_verify(math_parse(gt), math_parse(pred))) + except Exception: + return grade_answer(pred, gt) + + +# ------------------------- +# Accuracy reward (normalized to [0,1]) +# ------------------------- +def accuracy_reward(response: str, + ground_truth: str, + data_type: str, + problem_type: str) -> float: + """ + Normalized accuracy ∈ [0,1]. Strict format requirement: if the format is invalid, always return 0. + Wrapped with try/except: any exception → 0.0. + """ + try: + ans = extract_answer(response) or response.strip() + ptype = (problem_type or "").lower() + dtype = (data_type or "").lower() + gt = ground_truth or "" + + # ------ Pure QA type ------ + if ptype == "multiple choice": + return 1.0 if grade_answer(ans.strip(), gt.strip()) else 0.0 + + if ptype == "numerical": + gt_num, pr_num = normalize_number(gt), normalize_number(ans) + return 1.0 if (gt_num is not None and pr_num is not None and round(gt_num, 2) == round(pr_num, 2)) else 0.0 + + if ptype == "regression": + gt_num, pr_num = normalize_number(gt), normalize_number(ans) + if gt_num is None or pr_num is None: + return 0.0 + return mean_relative_accuracy(pr_num, gt_num) + + if ptype == "ocr": + return max(0.0, min(1.0, 1.0 - wer(gt, ans))) + + if ptype == "open-ended": + return max(0.0, min(1.0, compute_rouge_score(gt, ans))) + + if ptype == "math": + return 1.0 if _math_equivalent(gt, ans) else 0.0 + + # ------ JSON type (strict format)------ + def _load_json(s: str): + try: + return json.loads(s) + except Exception: + return None + + # temporal grounding: tIoU ∈ [0,1] + if ptype == "temporal grounding": + pred = _load_json(ans) + gtj = _load_json(gt) + if not isinstance(pred, dict) or not isinstance(gtj, dict): + return 0.0 + return iou_1d(pred.get("time"), gtj.get("time")) + + # spatial grounding: box IoU ∈ [0,1] + if ptype == "spatial grounding": + pred = _load_json(ans) + gtj = _load_json(gt) + if not isinstance(pred, dict) or not isinstance(gtj, dict): + return 0.0 + return iou_2d(pred.get("boxes"), gtj.get("boxes")) + + # spatial-temporal grounding: 0.5*tIoU + 0.5*mIoU(intersection) + if ptype == "spatial-temporal grounding": + pred = _load_json(ans) + gtj = _load_json(gt) + if not isinstance(pred, dict) or not isinstance(gtj, dict): + return 0.0 + tiou = iou_1d(pred.get("time"), gtj.get("time")) + pboxes = pred.get("boxes") + gboxes = gtj.get("boxes") + if not isinstance(pboxes, dict) or not isinstance(gboxes, dict): + miou_inter = 0.0 + else: + miou_inter = mean_iou_over_intersection(pboxes, gboxes) + return 0.5 * tiou + 0.5 * miou_inter + + # tracking: mean mIoU over GT frames (missing frames = 0) + if ptype == "tracking": + pred = _load_json(ans) + gtj = _load_json(gt) + if not isinstance(pred, dict) or not isinstance(gtj, dict): + return 0.0 + pboxes = pred.get("boxes") + gboxes = gtj.get("boxes") + if not isinstance(pboxes, dict) or not isinstance(gboxes, dict): + return 0.0 + return mean_iou_over_gt_frames(pboxes, gboxes) + + # segmentation(image/video) + # if ptype == "segmentation": + if "segmentation" in ptype: + pred = _load_json(ans) + gtj = _load_json(gt) + if not isinstance(pred, dict) or not isinstance(gtj, dict): + return 0.0 + + iou = iou_2d(pred.get("boxes"), gtj.get("boxes")) + + # pos_pred = pred.get("positive_points") + # pos_gt = gtj.get("positive_points") + # neg_pred = pred.get("negative_points") + # neg_gt = gtj.get("negative_points") + + # # Must be strict 3↔3 + # if not (isinstance(pos_pred, list) and len(pos_pred) == 3 and + # isinstance(pos_gt, list) and len(pos_gt) == 3 and + # all(_is_list_of_numbers(p, 2) for p in pos_pred) and + # all(_is_list_of_numbers(p, 2) for p in pos_gt)): + # return 0.0 + # if not (isinstance(neg_pred, list) and len(neg_pred) == 3 and + # isinstance(neg_gt, list) and len(neg_gt) == 3 and + # all(_is_list_of_numbers(p, 2) for p in neg_pred) and + # all(_is_list_of_numbers(p, 2) for p in neg_gt)): + # return 0.0 + + # pos_sim = assignment_similarity_3(pos_pred, pos_gt) + # neg_sim = assignment_similarity_3(neg_pred, neg_gt) + + if dtype == "image": + # return 0.5 * iou + 0.25 * pos_sim + 0.25 * neg_sim + return iou + + if dtype == "video": + # time must be numeric (strict) + t_pred = pred.get("time") + t_gt = gtj.get("time") + if not isinstance(t_pred, (int, float)) or not isinstance(t_gt, (int, float)): + return 0.0 + time_sim = math.exp(-abs(float(t_pred) - float(t_gt)) / 2.0) # τ=2s + return 0.3 * iou + 0.3 * time_sim + 0.2 * pos_sim + 0.2 * neg_sim + + return 0.0 + + if "localization" in ptype: + # Handle both dict format {"boxes": [...]} and direct list format [...] + pred = _load_json(ans) + gtj = _load_json(gt) + + # Direct list format: [x1, y1, x2, y2] + if isinstance(pred, list) and isinstance(gtj, list): + return iou_2d(pred, gtj) + + # Dict format: {"boxes": [x1, y1, x2, y2]} + if isinstance(pred, dict) and isinstance(gtj, dict): + return iou_2d(pred.get("boxes"), gtj.get("boxes")) + + return 0.0 + + if "recognition" in ptype: + # Handle multi-label case: compare as sets (order-independent) + gt_labels = set(label.strip().lower() for label in gt.split(",")) + ans_labels = set(label.strip().lower() for label in ans.split(",")) + return 1.0 if gt_labels == ans_labels else 0.0 + + if ptype == "surgical instrument count": + # Use numerical comparison for count task + try: + gt_num = int(gt.strip()) + ans_num = int(ans.strip()) + return 1.0 if gt_num == ans_num else 0.0 + except ValueError: + # Fallback to string comparison if not valid numbers + return 1.0 if gt.lower().strip() == ans.lower().strip() else 0.0 + + if ptype == "critical view safety": + # Parse list format: ['Yes', 'Yes', 'No'] + try: + import ast + gt_list = ast.literal_eval(gt.strip()) + ans_list = ast.literal_eval(ans.strip()) + if not isinstance(gt_list, list) or not isinstance(ans_list, list): + return 0.0 + if len(gt_list) != 3 or len(ans_list) != 3: + return 0.0 + # Calculate accuracy for 3 CVS criteria + correct = sum(1 for g, a in zip(gt_list, ans_list) if g.strip().lower() == a.strip().lower()) + return correct / 3.0 + except (ValueError, SyntaxError): + return 0.0 + + # Unknown type + return 0.0 + except Exception: + # Outer fallback: any exception will be scored as 0 + return 0.0 + + +# ===================== Wrapper: batch call external model for open-ended ===================== +def evaluate_open_ended_with_rm( + open_ended_queue: List[Dict[str, Any]], + results: List[Dict[str, float]], + format_weight: float, + rm_server_type: str, + rm_batch_size: int, + normalize_model_reward_by_problem_id: bool +) -> None: + """ + Take open-ended samples in open_ended_queue, and call external RM in batches to evaluate accuracy. + Failed batches fall back to ROUGE. Optionally apply mean-std → min-max normalization within + each problem_id group. + After evaluation, this function will fill results[idx]['accuracy'] in-place and recompute + results[idx]['overall']. + """ + if not USE_MODEL_FOR_OPEN_ENDED or not open_ended_queue: + return + + client = RewardModelClient( + RM_MODEL_PATH, + server_type=rm_server_type, + server_address=RM_SERVER_ADDRESS + ) + + def _chunks(lst, n): + for i in range(0, len(lst), n): + yield lst[i:i+n] + + model_scores: List[float] = [0.0] * len(open_ended_queue) + + for batch_id, batch in enumerate(_chunks(open_ended_queue, rm_batch_size)): + data = [{"prompt": b["prompt"], "reference": b["reference"], "output": b["output"]} for b in batch] + try: + rewards = client(data) # expected to return list[float] + for j, sc in enumerate(rewards): + model_scores[(batch_id * rm_batch_size) + j] = float(sc) + except Exception: + # Fallback: use ROUGE to compute scores for this batch + for j, b in enumerate(batch): + ref = b["reference"] + out = b["output"] + model_scores[(batch_id * rm_batch_size) + j] = float(max(0.0, min(1.0, compute_rouge_score(ref, out)))) + + if normalize_model_reward_by_problem_id: + groups: Dict[Any, List[int]] = {} + for k, b in enumerate(open_ended_queue): + gid = b.get("problem_id", None) + groups.setdefault(gid, []).append(k) + + for gid, indices in groups.items(): + vals = np.array([model_scores[k] for k in indices], dtype=np.float32) + mean, std = vals.mean(), vals.std() + if std == 0: + norm_vals = np.ones_like(vals) + else: + z = (vals - mean) / (std + 1e-6) + norm_vals = (z - z.min()) / (z.max() - z.min() + 1e-12) + for t, k in enumerate(indices): + model_scores[k] = float(norm_vals[t]) + + # Fill back accuracy, and recompute overall + for k, b in enumerate(open_ended_queue): + idx = b["idx"] + results[idx]["accuracy"] = float(max(0.0, min(1.0, model_scores[k]))) + results[idx]["overall"] = ( + (1.0 - format_weight) * results[idx]["accuracy"] + + format_weight * results[idx]["format"] + + results[idx]["structure_reward"] + ) +# ================================================================== + + +# ------------------------- +# Public API +# ------------------------- +def compute_score( + reward_inputs: List[Dict[str, Any]], + format_weight: float = 0.1, + # ===== Still kept as configurable parameters ===== + rm_server_type: str = "vllm", + rm_batch_size: int = 64, + normalize_model_reward_by_problem_id: bool = True, +) -> List[Dict[str, float]]: + """ + Batch interface. + Each item: + { + "response": str, + "response_length": int, + "ground_truth": str, # may also contain ..., here we extract it first + "data_type": str, # "image" | "video" | ... + "problem_type": str # see branches above + # Optional additional fields: + # "problem": str # used as prompt for external RM in open-ended tasks + # "problem_id": Any # grouping key for normalization + } + Returns: list of dict with keys {overall, format, accuracy, structure_reward} + overall = (1 - format_weight) * accuracy + format_weight * format + structure_reward + - format: 1.0 if ......, otherwise 0.0 + - structure_reward: + * spatial-temporal / tracking: 0.25 (JSON valid) + 0.25 (key overlap ratio) + * other structured tasks: +0.5 if valid + * non-structured tasks: default +0.5 + """ + if not isinstance(reward_inputs, list): + raise ValueError("Please use `reward_type=batch` for this reward function.") + + results: List[Dict[str, float]] = [] + # ===================== Collect open-ended samples to be evaluated ===================== + open_ended_queue = [] # Each item: {idx, prompt, reference, output, problem_id} + # ================================================================ + + for idx, item in enumerate(reward_inputs): + try: + # Normalize tag whitespaces, e.g. < / think > → + raw_response = item.get("response", "") or "" + response = re.sub(r"\s*(<|>|/)\s*", r"\1", raw_response) + # print(f"reponse: {response}") + + # print(response) + + data_type = item.get("data_type", "") or "" + problem_type = item.get("problem_type", "") or "" + + # ground_truth may also be wrapped in ...; extract it first here + raw_gt = item.get("ground_truth", "") or "" + gt_extracted = extract_answer(raw_gt) or raw_gt + # print(f"gt_extracted: {gt_extracted}") + + # 1) format reward —— requires strict tag structure: ...... + f_score = tag_format_reward(response) + + # 2) structure reward —— according to JSON structure requirements by task type (see function doc) + ans = extract_answer(response) or "" + s_reward = answer_structure_bonus(ans, gt_extracted, data_type, problem_type) + + # 3) accuracy (all normalized to [0,1]) + if USE_MODEL_FOR_OPEN_ENDED and (problem_type or "").lower() == "open-ended": + # First set to 0, and finally compute with external model and fill back + a_score = 0.0 + open_ended_queue.append({ + "idx": idx, + "prompt": item.get("problem", "") or "", + "reference": gt_extracted or "", + "output": ans or "", + "problem_id": item.get("problem_id", None), + }) + else: + a_score = accuracy_reward(response, gt_extracted, data_type, problem_type) + + if f_score == 0: + s_reward = 0 + + overall = (1.0 - format_weight) * a_score + format_weight * f_score + s_reward + + results.append({ + "overall": float(overall), + "format": float(f_score), + "accuracy": float(a_score), + "structure_reward": float(s_reward), + }) + except Exception: + # Fallback for the entire sample: any exception, all four fields are set to 0 + results.append({ + "overall": 0.0, + "format": 0.0, + "accuracy": 0.0, + "structure_reward": 0.0, + }) + + + + # ===================== Call wrapper for batch external evaluation and fill back ===================== + evaluate_open_ended_with_rm( + open_ended_queue=open_ended_queue, + results=results, + format_weight=format_weight, + rm_server_type=rm_server_type, + rm_batch_size=rm_batch_size, + normalize_model_reward_by_problem_id=normalize_model_reward_by_problem_id + ) + # ====================================================================== + + if random.random() < 0.01: + + for idx, item in enumerate(reward_inputs): + + print('type', item.get("problem_type", "")) + print('gt', extract_answer(item.get("ground_truth", ""))) + print('ans', extract_answer(item.get("response", ""))) + print({ + "overall": results[idx]["overall"], + "format": results[idx]["format"], + "accuracy": results[idx]["accuracy"], + "structure_reward": results[idx]["structure_reward"], + }) + + return results diff --git a/model/EasyR1/verl/reward_function/r1v.py b/model/EasyR1/verl/reward_function/r1v.py new file mode 100644 index 0000000000000000000000000000000000000000..6a28548b292cc2aae217fbf923751ac518a022ab --- /dev/null +++ b/model/EasyR1/verl/reward_function/r1v.py @@ -0,0 +1,50 @@ +# 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. + +import re +from typing import Any + +from mathruler.grader import grade_answer + + +def format_reward(response: str) -> float: + pattern = re.compile(r".*?\s*.*?", re.DOTALL) + format_match = re.fullmatch(pattern, response) + return 1.0 if format_match else 0.0 + + +def accuracy_reward(response: str, ground_truth: str) -> float: + try: + content_match = re.search(r"(.*?)", response) + given_answer = content_match.group(1).strip() if content_match else response.strip() + if grade_answer(given_answer, ground_truth.strip()): + return 1.0 + + except Exception: + pass + + return 0.0 + + +def compute_score(reward_input: dict[str, Any], format_weight: float = 0.5) -> dict[str, float]: + if not isinstance(reward_input, dict): + raise ValueError("Please use `reward_type=sequential` for r1v reward function.") + + format_score = format_reward(reward_input["response"]) + accuracy_score = accuracy_reward(reward_input["response"], reward_input["ground_truth"]) + return { + "overall": (1 - format_weight) * accuracy_score + format_weight * format_score, + "format": format_score, + "accuracy": accuracy_score, + } diff --git a/model/EasyR1/verl/single_controller/__init__.py b/model/EasyR1/verl/single_controller/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce90c5eb352d85c59105c0dc85b5f1dd576f095 --- /dev/null +++ b/model/EasyR1/verl/single_controller/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/model/EasyR1/verl/single_controller/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/single_controller/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a9b87004b35b4327a1bfe00a10849cb630ca512 Binary files /dev/null and b/model/EasyR1/verl/single_controller/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/base/__init__.py b/model/EasyR1/verl/single_controller/base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..46c9670eebda2595b2ea248c640f9d533506c226 --- /dev/null +++ b/model/EasyR1/verl/single_controller/base/__init__.py @@ -0,0 +1,19 @@ +# 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. + +from .worker import Worker +from .worker_group import ClassWithInitArgs, ResourcePool, WorkerGroup + + +__all__ = ["ClassWithInitArgs", "ResourcePool", "Worker", "WorkerGroup"] diff --git a/model/EasyR1/verl/single_controller/base/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/single_controller/base/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1d62e5db5363f8ed7fa286078ef59e0a519b2c6 Binary files /dev/null and b/model/EasyR1/verl/single_controller/base/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/base/__pycache__/decorator.cpython-311.pyc b/model/EasyR1/verl/single_controller/base/__pycache__/decorator.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0706ebf76a229432dd8e63b9db174bd664d950f Binary files /dev/null and b/model/EasyR1/verl/single_controller/base/__pycache__/decorator.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/base/__pycache__/worker.cpython-311.pyc b/model/EasyR1/verl/single_controller/base/__pycache__/worker.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f69a03653abfea27f7497c38f9dc0b8d03acf731 Binary files /dev/null and b/model/EasyR1/verl/single_controller/base/__pycache__/worker.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/base/__pycache__/worker_group.cpython-311.pyc b/model/EasyR1/verl/single_controller/base/__pycache__/worker_group.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..763ef5025c390e8e17f681ee353678ed5b87856a Binary files /dev/null and b/model/EasyR1/verl/single_controller/base/__pycache__/worker_group.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/base/decorator.py b/model/EasyR1/verl/single_controller/base/decorator.py new file mode 100644 index 0000000000000000000000000000000000000000..3967b1eee775557ec59c34031c1593b7f8252132 --- /dev/null +++ b/model/EasyR1/verl/single_controller/base/decorator.py @@ -0,0 +1,213 @@ +# 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. + +from enum import Enum, auto +from functools import wraps +from types import FunctionType +from typing import TYPE_CHECKING, Literal, Union + +import ray + +from ...protocol import DataProto, DataProtoFuture + + +if TYPE_CHECKING: + from .worker_group import WorkerGroup + + +# here we add a magic number of avoid user-defined function already have this attribute +MAGIC_ATTR = "attrs_3141562937" + + +class Dispatch(Enum): + RANK_ZERO = auto() + ONE_TO_ALL = auto() + ALL_TO_ALL = auto() + DP_COMPUTE = auto() + DP_COMPUTE_PROTO = auto() + DP_COMPUTE_PROTO_WITH_FUNC = auto() + DP_COMPUTE_METRIC = auto() + + +class Execute(Enum): + ALL = 0 + RANK_ZERO = 1 + + +def _split_args_kwargs_data_proto(chunks: int, *args, **kwargs): + splitted_args = [] + for arg in args: + assert isinstance(arg, (DataProto, DataProtoFuture)) + splitted_args.append(arg.chunk(chunks=chunks)) + + splitted_kwargs = {} + for key, value in kwargs.items(): + assert isinstance(value, (DataProto, DataProtoFuture)) + splitted_kwargs[key] = value.chunk(chunks=chunks) + + return splitted_args, splitted_kwargs + + +def dispatch_one_to_all(worker_group: "WorkerGroup", *args, **kwargs): + args = tuple([arg] * worker_group.world_size for arg in args) + kwargs = {k: [v] * worker_group.world_size for k, v in kwargs.items()} + return args, kwargs + + +def dispatch_all_to_all(worker_group: "WorkerGroup", *args, **kwargs): + return args, kwargs + + +def collect_all_to_all(worker_group: "WorkerGroup", output): + return output + + +def _concat_data_proto_or_future(outputs: list[DataProto]) -> DataProto: + # make sure all the elements in output has the same type + for output in outputs: + assert type(output) is type(outputs[0]) + + output = outputs[0] + + if isinstance(output, DataProto): + return DataProto.concat(outputs) + elif isinstance(output, ray.ObjectRef): + return DataProtoFuture.concat(outputs) + else: + raise NotImplementedError + + +def dispatch_dp_compute(worker_group: "WorkerGroup", *args, **kwargs): + for arg in args: + assert isinstance(arg, (tuple, list)) and len(arg) == worker_group.world_size + + for value in kwargs.values(): + assert isinstance(value, (tuple, list)) and len(value) == worker_group.world_size + + return args, kwargs + + +def collect_dp_compute(worker_group: "WorkerGroup", outputs: list[DataProto]) -> list[DataProto]: + assert len(outputs) == worker_group.world_size + return outputs + + +def dispatch_dp_compute_data_proto(worker_group: "WorkerGroup", *args, **kwargs): + splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.world_size, *args, **kwargs) + return splitted_args, splitted_kwargs + + +def dispatch_dp_compute_data_proto_with_func(worker_group: "WorkerGroup", *args, **kwargs): + assert type(args[0]) is FunctionType # NOTE: The first one args is a function! + splitted_args, splitted_kwargs = _split_args_kwargs_data_proto(worker_group.world_size, *args[1:], **kwargs) + splitted_args_with_func = [[args[0]] * worker_group.world_size] + splitted_args + return splitted_args_with_func, splitted_kwargs + + +def collect_dp_compute_data_proto(worker_group: "WorkerGroup", outputs: list[DataProto]) -> DataProto: + for output in outputs: + assert isinstance(output, (DataProto, ray.ObjectRef)), f"Expect a DataProto, but got {type(output)}" + + outputs = collect_dp_compute(worker_group, outputs) + return _concat_data_proto_or_future(outputs) + + +def get_predefined_dispatch_fn(dispatch_mode: Dispatch): + predefined_dispatch_mode_fn = { + Dispatch.ONE_TO_ALL: { + "dispatch_fn": dispatch_one_to_all, + "collect_fn": collect_all_to_all, + }, + Dispatch.ALL_TO_ALL: { + "dispatch_fn": dispatch_all_to_all, + "collect_fn": collect_all_to_all, + }, + Dispatch.DP_COMPUTE: { + "dispatch_fn": dispatch_dp_compute, + "collect_fn": collect_dp_compute, + }, + Dispatch.DP_COMPUTE_PROTO: { + "dispatch_fn": dispatch_dp_compute_data_proto, + "collect_fn": collect_dp_compute_data_proto, + }, + Dispatch.DP_COMPUTE_PROTO_WITH_FUNC: { + "dispatch_fn": dispatch_dp_compute_data_proto_with_func, + "collect_fn": collect_dp_compute_data_proto, + }, + Dispatch.DP_COMPUTE_METRIC: { + "dispatch_fn": dispatch_dp_compute_data_proto, + "collect_fn": collect_dp_compute, + }, + } + return predefined_dispatch_mode_fn[dispatch_mode] + + +def get_predefined_execute_fn(execute_mode: Execute): + """ + Note that here we only asks execute_all and execute_rank_zero to be implemented + Leave the choice of how these two functions handle argument 'blocking' to users + """ + predefined_execute_mode_fn = { + Execute.ALL: {"execute_fn_name": "execute_all"}, + Execute.RANK_ZERO: {"execute_fn_name": "execute_rank_zero"}, + } + return predefined_execute_mode_fn[execute_mode] + + +def _check_dispatch_mode(dispatch_mode: Union[Dispatch, dict[Literal["dispatch_fn", "collect_fn"], FunctionType]]): + assert isinstance(dispatch_mode, (Dispatch, dict)), ( + f"dispatch_mode must be a Dispatch or a Dict. Got {dispatch_mode}" + ) + if isinstance(dispatch_mode, dict): + necessary_keys = ["dispatch_fn", "collect_fn"] + for key in necessary_keys: + assert key in dispatch_mode, f"key {key} should be in dispatch_mode if it is a dictionary" + + +def _check_execute_mode(execute_mode: Execute): + assert isinstance(execute_mode, Execute), f"execute_mode must be a Execute. Got {execute_mode}" + + +def _materialize_futures(*args, **kwargs): + new_args = [] + for arg in args: + if isinstance(arg, DataProtoFuture): + arg = arg.get() + # add more type to materialize + new_args.append(arg) + + for key, value in kwargs.items(): + if isinstance(value, DataProtoFuture): + kwargs[key] = value.get() + + new_args = tuple(new_args) + return new_args, kwargs + + +def register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.ALL, blocking=True, materialize_futures=True): + _check_dispatch_mode(dispatch_mode=dispatch_mode) + _check_execute_mode(execute_mode=execute_mode) + + def decorator(func): + @wraps(func) + def inner(*args, **kwargs): + if materialize_futures: + args, kwargs = _materialize_futures(*args, **kwargs) + return func(*args, **kwargs) + + attrs = {"dispatch_mode": dispatch_mode, "execute_mode": execute_mode, "blocking": blocking} + setattr(inner, MAGIC_ATTR, attrs) + return inner + + return decorator diff --git a/model/EasyR1/verl/single_controller/base/register_center/__init__.py b/model/EasyR1/verl/single_controller/base/register_center/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce90c5eb352d85c59105c0dc85b5f1dd576f095 --- /dev/null +++ b/model/EasyR1/verl/single_controller/base/register_center/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/model/EasyR1/verl/single_controller/base/register_center/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/single_controller/base/register_center/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ce1d6e8b5581599b2c84f6594f7e3b02680e10f Binary files /dev/null and b/model/EasyR1/verl/single_controller/base/register_center/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/base/register_center/__pycache__/ray.cpython-311.pyc b/model/EasyR1/verl/single_controller/base/register_center/__pycache__/ray.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..690f2d8a21407fdc770cb63de22611b55e5a1cc0 Binary files /dev/null and b/model/EasyR1/verl/single_controller/base/register_center/__pycache__/ray.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/base/register_center/ray.py b/model/EasyR1/verl/single_controller/base/register_center/ray.py new file mode 100644 index 0000000000000000000000000000000000000000..de7f702a894ef5cd87fa90931e6bd260f8b68b13 --- /dev/null +++ b/model/EasyR1/verl/single_controller/base/register_center/ray.py @@ -0,0 +1,28 @@ +# 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. + +import ray + + +@ray.remote +class WorkerGroupRegisterCenter: + def __init__(self, rank_zero_info): + self.rank_zero_info = rank_zero_info + + def get_rank_zero_info(self): + return self.rank_zero_info + + +def create_worker_group_register_center(name, info): + return WorkerGroupRegisterCenter.options(name=name).remote(info) diff --git a/model/EasyR1/verl/single_controller/base/worker.py b/model/EasyR1/verl/single_controller/base/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..9ecffca6b8d7589b292fbb25b5cf74c004cc4fad --- /dev/null +++ b/model/EasyR1/verl/single_controller/base/worker.py @@ -0,0 +1,202 @@ +# 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. +""" +the class for Worker +""" + +import os +import socket +from dataclasses import dataclass +from typing import Tuple + +import ray +import torch + +from .decorator import Dispatch, Execute, register +from .register_center.ray import create_worker_group_register_center + + +@dataclass +class DistRankInfo: + tp_rank: int + dp_rank: int + pp_rank: int + + +@dataclass +class DistGlobalInfo: + tp_size: int + dp_size: int + pp_size: int + + +class WorkerHelper: + def _get_node_ip(self) -> str: + host_ipv4 = os.getenv("MY_HOST_IP", None) + host_ipv6 = os.getenv("MY_HOST_IPV6", None) + host_ip_by_env = host_ipv4 or host_ipv6 + host_ip_by_sdk = ray._private.services.get_node_ip_address() + + host_ip = host_ip_by_env or host_ip_by_sdk + return host_ip + + def _get_free_port(self) -> int: + with socket.socket() as sock: + sock.bind(("", 0)) + return sock.getsockname()[1] + + def get_availale_master_addr_port(self) -> Tuple[str, str]: + return self._get_node_ip(), str(self._get_free_port()) + + def _get_pid(self): + return + + +class WorkerMeta: + keys = [ + "WORLD_SIZE", + "RANK", + "LOCAL_WORLD_SIZE", + "LOCAL_RANK", + "MASTER_ADDR", + "MASTER_PORT", + "CUDA_VISIBLE_DEVICES", + ] + + def __init__(self, store) -> None: + self._store = store + + def to_dict(self): + return {f"_{key.lower()}": self._store.get(f"_{key.lower()}", None) for key in WorkerMeta.keys} + + +# we assume that in each WorkerGroup, there is a Master Worker +class Worker(WorkerHelper): + """A (distributed) worker.""" + + _world_size: int + _rank: int + _local_world_size: int + _local_rank: int + _master_addr: str + _master_port: str + _cuda_visible_devices: str + + def __new__(cls, *args, **kwargs): + instance = super().__new__(cls) + + # note that here we use int to distinguish + disable_worker_init = int(os.getenv("DISABLE_WORKER_INIT", 0)) + if disable_worker_init: + return instance + + rank = os.getenv("RANK", None) + worker_group_prefix = os.getenv("WG_PREFIX", None) + + # when decorator @ray.remote applies, __new__ will be called while we don't want to apply _configure_before_init + if None not in [rank, worker_group_prefix] and "ActorClass(" not in cls.__name__: + instance._configure_before_init(f"{worker_group_prefix}_register_center", int(rank)) + + return instance + + def _configure_before_init(self, register_center_name: str, rank: int): + assert isinstance(rank, int), f"rank must be int, instead of {type(rank)}" + + if rank == 0: + master_addr, master_port = self.get_availale_master_addr_port() + rank_zero_info = { + "MASTER_ADDR": master_addr, + "MASTER_PORT": master_port, + } + self.register_center = create_worker_group_register_center(name=register_center_name, info=rank_zero_info) + os.environ.update(rank_zero_info) + + def __init__(self, cuda_visible_devices=None) -> None: + # construct a meta from envrionment variable. Note that the import must be inside the class because it is executed remotely + world_size = int(os.getenv("WORLD_SIZE")) + rank = int(os.getenv("RANK")) + self._rank = rank + self._world_size = world_size + + if "AMD" in torch.cuda.get_device_name(): + os.environ["CUDA_VISIBLE_DEVICES"] = os.getenv("ROCR_VISIBLE_DEVICES") + os.environ["LOCAL_RANK"] = os.getenv("RAY_LOCAL_RANK") + cuda_visible_devices = os.getenv("LOCAL_RANK", "0") + torch.cuda.set_device(int(cuda_visible_devices)) + + master_addr = os.getenv("MASTER_ADDR") + master_port = os.getenv("MASTER_PORT") + + local_world_size = int(os.getenv("LOCAL_WORLD_SIZE", "1")) + local_rank = int(os.getenv("LOCAL_RANK", "0")) + + store = { + "_world_size": world_size, + "_rank": rank, + "_local_world_size": local_world_size, + "_local_rank": local_rank, + "_master_addr": master_addr, + "_master_port": master_port, + } + if cuda_visible_devices is not None: + store["_cuda_visible_devices"] = cuda_visible_devices + + meta = WorkerMeta(store=store) + self._configure_with_meta(meta=meta) + + def _configure_with_meta(self, meta: WorkerMeta): + """ + This function should only be called inside by WorkerGroup + """ + assert isinstance(meta, WorkerMeta) + self.__dict__.update(meta.to_dict()) # this is hacky + # print(f"__dict__: {self.__dict__}") + for key in WorkerMeta.keys: + val = self.__dict__.get(f"_{key.lower()}", None) + if val is not None: + # print(f"set {key} to {val}") + os.environ[key] = str(val) + + os.environ["REDIS_STORE_SERVER_HOST"] = ( + str(self._master_addr).replace("[", "").replace("]", "") if self._master_addr else "" + ) + + def get_master_addr_port(self): + return self._master_addr, self._master_port + + def get_cuda_visible_devices(self): + cuda_visible_devices = os.getenv("CUDA_VISIBLE_DEVICES", "not set") + return cuda_visible_devices + + def print_rank0(self, *args, **kwargs): + if self.rank == 0: + print(*args, **kwargs) + + @property + def world_size(self): + return self._world_size + + @property + def rank(self): + return self._rank + + @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO_WITH_FUNC) + def execute_with_func_generator(self, func, *args, **kwargs): + ret_proto = func(self, *args, **kwargs) + return ret_proto + + @register(dispatch_mode=Dispatch.ALL_TO_ALL, execute_mode=Execute.RANK_ZERO) + def execute_func_rank_zero(self, func, *args, **kwargs): + result = func(*args, **kwargs) + return result diff --git a/model/EasyR1/verl/single_controller/base/worker_group.py b/model/EasyR1/verl/single_controller/base/worker_group.py new file mode 100644 index 0000000000000000000000000000000000000000..092aca841ce8b1ddd8b00f58502c597859eda8ca --- /dev/null +++ b/model/EasyR1/verl/single_controller/base/worker_group.py @@ -0,0 +1,194 @@ +# 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. +""" +the class of WorkerGroup +""" + +import logging +import signal +import threading +import time +from typing import Any, Callable, Optional + +from .decorator import MAGIC_ATTR, Dispatch, get_predefined_dispatch_fn, get_predefined_execute_fn + + +class ResourcePool: + """The resource pool with meta info such as world size.""" + + def __init__( + self, process_on_nodes: Optional[Any] = None, max_colocate_count: int = 10, n_gpus_per_node: int = 8 + ) -> None: + if process_on_nodes is None: + process_on_nodes = [] + + self._store = process_on_nodes + self.max_colocate_count = max_colocate_count + self.n_gpus_per_node = n_gpus_per_node # this is left for future huawei GPU that contains 16 GPUs per node + + def add_node(self, process_count): + self._store.append(process_count) + + @property + def world_size(self): + return sum(self._store) + + def __call__(self) -> Any: + return self._store + + @property + def store(self): + return self._store + + def local_world_size_list(self) -> list[int]: + nested_local_world_size_list = [ + [local_world_size for _ in range(local_world_size)] for local_world_size in self._store + ] + return [item for row in nested_local_world_size_list for item in row] + + def local_rank_list(self) -> list[int]: + nested_local_rank_list = [[i for i in range(local_world_size)] for local_world_size in self._store] # noqa: C416 + return [item for row in nested_local_rank_list for item in row] + + +class ClassWithInitArgs: + """ + This class stores a class constructor and the args/kwargs to construct the class. + It is used to instantiate the remote class. + """ + + def __init__(self, cls, *args, **kwargs) -> None: + self.cls = cls + self.args = args + self.kwargs = kwargs + + def __call__(self) -> Any: + return self.cls(*self.args, **self.kwargs) + + +def check_workers_alive(workers: list, is_alive: Callable, gap_time: float = 1) -> None: + while True: + for worker in workers: + if not is_alive(worker): + logging.warning(f"Worker {worker} is not alive, sending signal to main thread") + signal.raise_signal(signal.SIGABRT) + + time.sleep(gap_time) + + +class WorkerGroup: + """A group of workers""" + + def __init__(self, resource_pool: ResourcePool, **kwargs) -> None: + self._is_init_with_detached_workers = True if resource_pool is None else False + + if resource_pool is not None: + # handle the case when WorkGroup is attached to an existing one + self._procecss_dispatch_config = resource_pool() + else: + self._procecss_dispatch_config = None + + self._workers = [] + self._worker_names = [] + + self._master_addr = None + self._master_port = None + + self._checker_thread: threading.Thread = None + + def _is_worker_alive(self, worker): + raise NotImplementedError("WorkerGroup._is_worker_alive called, should be implemented in derived class.") + + def _block_until_all_workers_alive(self) -> None: + while True: + all_state = [self._is_worker_alive(worker) for worker in self._workers] + if False in all_state: + time.sleep(1) + else: + break + + def start_worker_aliveness_check(self, every_n_seconds=1) -> None: + # before starting checking worker aliveness, make sure all workers are already alive + self._block_until_all_workers_alive() + + self._checker_thread = threading.Thread( + target=check_workers_alive, args=(self._workers, self._is_worker_alive, every_n_seconds) + ) + self._checker_thread.start() + + @property + def world_size(self): + return len(self._workers) + + def _bind_worker_method(self, user_defined_cls, func_generator): + """ + Bind the worker method to the WorkerGroup + """ + for method_name in dir(user_defined_cls): + try: + method = getattr(user_defined_cls, method_name) + assert callable(method), f"{method_name} in {user_defined_cls} is not callable" + except Exception: + # if it is a property, it will fail because Class doesn't have instance property + continue + + if hasattr(method, MAGIC_ATTR): + # this method is decorated by register + attribute = getattr(method, MAGIC_ATTR) + assert isinstance(attribute, dict), f"attribute must be a dictionary. Got {type(attribute)}" + assert "dispatch_mode" in attribute, "attribute must contain dispatch_mode in its key" + + dispatch_mode = attribute["dispatch_mode"] + execute_mode = attribute["execute_mode"] + blocking = attribute["blocking"] + + # get dispatch fn + if isinstance(dispatch_mode, Dispatch): + # get default dispatch fn + fn = get_predefined_dispatch_fn(dispatch_mode=dispatch_mode) + dispatch_fn = fn["dispatch_fn"] + collect_fn = fn["collect_fn"] + else: + assert isinstance(dispatch_mode, dict) + assert "dispatch_fn" in dispatch_mode + assert "collect_fn" in dispatch_mode + dispatch_fn = dispatch_mode["dispatch_fn"] + collect_fn = dispatch_mode["collect_fn"] + + # get execute_fn_name + execute_mode = get_predefined_execute_fn(execute_mode=execute_mode) + wg_execute_fn_name = execute_mode["execute_fn_name"] + + # get execute_fn from string + try: + execute_fn = getattr(self, wg_execute_fn_name) + assert callable(execute_fn), "execute_fn must be callable" + except Exception: + print(f"execute_fn {wg_execute_fn_name} is invalid") + raise + + # bind a new method to the RayWorkerGroup + func = func_generator( + self, + method_name, + dispatch_fn=dispatch_fn, + collect_fn=collect_fn, + execute_fn=execute_fn, + blocking=blocking, + ) + + try: + setattr(self, method_name, func) + except Exception: + raise ValueError(f"Fail to set method_name {method_name}") diff --git a/model/EasyR1/verl/single_controller/ray/__init__.py b/model/EasyR1/verl/single_controller/ray/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25b3141cee9f146d18c92b5625a327a1d9f2dbce --- /dev/null +++ b/model/EasyR1/verl/single_controller/ray/__init__.py @@ -0,0 +1,18 @@ +# 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. + +from .base import RayClassWithInitArgs, RayResourcePool, RayWorkerGroup, create_colocated_worker_cls + + +__all__ = ["RayClassWithInitArgs", "RayResourcePool", "RayWorkerGroup", "create_colocated_worker_cls"] diff --git a/model/EasyR1/verl/single_controller/ray/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/single_controller/ray/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07f63e8fe6d3f68203e8e14914cdc0240b290e5f Binary files /dev/null and b/model/EasyR1/verl/single_controller/ray/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/ray/__pycache__/base.cpython-311.pyc b/model/EasyR1/verl/single_controller/ray/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a92a402de3df2c1aabdbccc9a2809a170e903899 Binary files /dev/null and b/model/EasyR1/verl/single_controller/ray/__pycache__/base.cpython-311.pyc differ diff --git a/model/EasyR1/verl/single_controller/ray/base.py b/model/EasyR1/verl/single_controller/ray/base.py new file mode 100644 index 0000000000000000000000000000000000000000..048ee219ebe47f09433bf30a71183d7a0a3d8c39 --- /dev/null +++ b/model/EasyR1/verl/single_controller/ray/base.py @@ -0,0 +1,493 @@ +# 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. + +import os +import random +import re +import string +import time +from typing import Any, Optional +from unittest.mock import patch + +import ray +from ray.actor import ActorHandle +from ray.experimental.state.api import get_actor +from ray.util import list_named_actors +from ray.util.placement_group import PlacementGroup, placement_group +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy, PlacementGroupSchedulingStrategy + +from ..base import ClassWithInitArgs, ResourcePool, Worker, WorkerGroup +from ..base.decorator import MAGIC_ATTR + + +__all__ = ["Worker"] + + +def get_random_string(length: int) -> str: + letters_digits = string.ascii_letters + string.digits + return "".join(random.choice(letters_digits) for _ in range(length)) + + +def func_generator(self, method_name, dispatch_fn, collect_fn, execute_fn, blocking): + def func(*args, **kwargs): + args, kwargs = dispatch_fn(self, *args, **kwargs) + output = execute_fn(method_name, *args, **kwargs) + if blocking: + output = ray.get(output) + output = collect_fn(self, output) + return output + + return func + + +def sort_placement_group_by_node_ip(pgs: list[PlacementGroup]) -> list[PlacementGroup]: + """ + Sort the placement groups by node ip, all bundles in a single placement group should be on the same node. + + FSDPCheckpointManager saves sharded model states and optimizer states in local storage, which requires RANK + to be consistent across nodes when resume from checkpoint. + + With this function, if there's only one resource pool and there's no node change, RANK should be consistent + across nodes in multiple ray jobs, even if the whole ray cluster is restarted. + """ + node_ip = {node["NodeID"]: node["NodeManagerAddress"] for node in ray.nodes()} + pg_ip = {} + for pg in pgs: + specs = ray._private.state.state.placement_group_table(pg.id) + # all bunles should be on the same node + node_id = specs["bundles_to_node_id"][0] + pg_ip[pg.id] = node_ip[node_id] + + return sorted(pgs, key=lambda pg: pg_ip[pg.id]) + + +class RayResourcePool(ResourcePool): + def __init__( + self, + process_on_nodes: list[int] = None, + use_gpu: bool = True, + name_prefix: str = "", + max_colocate_count: int = 5, + detached: bool = False, + ) -> None: + super().__init__(process_on_nodes, max_colocate_count) + self.use_gpu = use_gpu + # print(f"in RayProcessDispatchConfiguration: name_prefix = {name_prefix}") + self.name_prefix = name_prefix + self.pgs = None + self.detached = detached + + def get_placement_groups(self, strategy: str = "STRICT_PACK", name: Optional[str] = None) -> list[PlacementGroup]: + if self.pgs is not None: + return self.pgs + + pg_name_prefix = ( + name if name else f"{self.name_prefix}verl_group_{'_'.join([str(count) for count in self._store])}:" + ) + # print(f"pg_name_prefix = {pg_name_prefix}") + pg_scheme = [ + [ + {"CPU": self.max_colocate_count, "GPU": 1} if self.use_gpu else {"CPU": self.max_colocate_count} + for _ in range(process_count) + ] + for process_count in self._store + ] + + lifetime = "detached" if self.detached else None + + pgs = [ + placement_group(bundles=bundles, strategy=strategy, name=pg_name_prefix + str(idx), lifetime=lifetime) + for idx, bundles in enumerate(pg_scheme) + ] + + ray.get([pg.ready() for pg in pgs]) + + self.pgs = pgs + return pgs + + +def extract_pg_from_exist( + resource_pools: dict[str, RayResourcePool], src_role_names: list[str], resource_pool: RayResourcePool +) -> list[PlacementGroup]: + src_pgs = [ + pg + for role_name, resource_pool in resource_pools.items() + for pg in resource_pool.get_placement_groups() + if role_name in src_role_names + ] + + sorted_src_pgs = sorted(src_pgs, key=lambda pg: pg.bundle_count, reverse=True) + sorted_process_on_nodes = sorted([(val, idx) for idx, val in enumerate(resource_pool.store)], reverse=True) + + unsorted_pgs: list[tuple[int, PlacementGroup]] = [] + searching_idx = 0 + for request_process, original_idx in sorted_process_on_nodes: + assert searching_idx < len(sorted_src_pgs), f"no enough nodes for request: searching {searching_idx} th node" + assert request_process <= sorted_src_pgs[searching_idx].bundle_count, ( + f"requesting {request_process} processes, bundle count cannot satisfy" + ) + unsorted_pgs.append((original_idx, sorted_src_pgs[searching_idx])) + searching_idx += 1 + + return [pg for _, pg in sorted(unsorted_pgs)] + + +def merge_resource_pool(rp1: RayResourcePool, rp2: RayResourcePool) -> RayResourcePool: + assert rp1.use_gpu == rp2.use_gpu, "Both RayResourcePool must either use_gpu or not" + assert rp1.max_colocate_count == rp2.max_colocate_count, ( + "Both RayResourcePool must has the same max_colocate_count" + ) + assert rp1.n_gpus_per_node == rp2.n_gpus_per_node, "Both RayResourcePool must has the same n_gpus_per_node" + assert rp1.detached == rp2.detached, "Detached ResourcePool cannot be merged with non-detached ResourcePool" + + new_store = rp1.store + rp2.store + + merged = RayResourcePool(new_store, rp1.use_gpu, f"{rp1.name_prefix}_{rp2.name_prefix}") + merged.pgs = rp1.get_placement_groups() + rp2.get_placement_groups() + + return merged + + +class RayClassWithInitArgs(ClassWithInitArgs): + def __init__(self, cls, *args, **kwargs) -> None: + # self._options = kwargs.pop('options', dict()) + super().__init__(cls, *args, **kwargs) + self._options = {} + self._additional_resource = {} + + def set_additional_resource(self, additional_resource): + self._additional_resource = additional_resource + + def update_options(self, options: dict): + self._options.update(options) + + def __call__( + self, + placement_group: PlacementGroup, + placement_group_bundle_idx: int, + use_gpu: bool = True, + num_gpus: int = 1, + sharing_with: Worker = None, + ) -> Any: + if sharing_with is not None: + target_node_id = ray.get(sharing_with.get_node_id.remote()) + cuda_visible_devices = ray.get(sharing_with.get_cuda_visible_devices.remote()) + options = {"scheduling_strategy": NodeAffinitySchedulingStrategy(node_id=target_node_id, soft=False)} + return self.cls.options(**options).remote( + *self.args, cuda_visible_devices=cuda_visible_devices, **self.kwargs + ) + + options = { + "scheduling_strategy": PlacementGroupSchedulingStrategy( + placement_group=placement_group, placement_group_bundle_index=placement_group_bundle_idx + ) + } + options.update(self._options) + + if use_gpu: + options["num_gpus"] = num_gpus + + if len(self._additional_resource) > 1: + for k, v in self._additional_resource.items(): + options[k] = v + + # print("cls:", self.cls) + # print("args: ", self.args) + # print("kwargs: ", self.kwargs) + return self.cls.options(**options).remote(*self.args, **self.kwargs) + + +class RayWorkerGroup(WorkerGroup): + def __init__( + self, + resource_pool: RayResourcePool = None, + ray_cls_with_init: RayClassWithInitArgs = None, + bin_pack: bool = True, + name_prefix: str = None, + detached: bool = False, + worker_names: list[str] = None, + **kwargs, + ) -> None: + super().__init__(resource_pool=resource_pool, **kwargs) + self.ray_cls_with_init = ray_cls_with_init + self.name_prefix = get_random_string(length=6) if name_prefix is None else name_prefix + + if worker_names is not None: + assert self._is_init_with_detached_workers + self._worker_names = worker_names + + if self._is_init_with_detached_workers: + self._init_with_detached_workers(worker_names=worker_names) + else: + self._init_with_resource_pool( + resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, bin_pack=bin_pack, detached=detached + ) + + if ray_cls_with_init is not None: + self._bind_worker_method(self.ray_cls_with_init.cls, func_generator) + + def _is_worker_alive(self, worker: ActorHandle) -> bool: + worker_state_dict = get_actor(worker._actor_id.hex()) + return worker_state_dict.get("state", "undefined") == "ALIVE" if worker_state_dict is not None else False + + def _init_with_detached_workers(self, worker_names: list[str]) -> None: + workers = [ray.get_actor(name=name) for name in worker_names] + self._workers = workers + self._world_size = len(worker_names) + + def _init_with_resource_pool( + self, resource_pool: RayResourcePool, ray_cls_with_init: RayClassWithInitArgs, bin_pack: bool, detached: bool + ): + use_gpu = resource_pool.use_gpu + + strategy = "PACK" + if bin_pack: + strategy = "STRICT_PACK" + + pgs = resource_pool.get_placement_groups(strategy=strategy) + world_size = resource_pool.world_size + self._world_size = world_size + # cia.add_kwarg("_world_size", world_size) + num_gpus = 1 / resource_pool.max_colocate_count + + rank = -1 + local_world_size = resource_pool.store[0] + for pg_idx, pg in enumerate(sort_placement_group_by_node_ip(pgs)): + assert local_world_size <= pg.bundle_count, f"when generating for {self.name_prefix}, for the " + for local_rank in range(local_world_size): + rank += 1 + + # we pass in environment variable at option so that Worker can use environment variable to set + env_vars = { + "WORLD_SIZE": str(world_size), + "RANK": str(rank), + "WG_PREFIX": self.name_prefix, + "WG_BACKEND": "ray", + "RAY_LOCAL_WORLD_SIZE": str(local_world_size), + "RAY_LOCAL_RANK": str(local_rank), + } + if rank != 0: + env_vars["MASTER_ADDR"] = self._master_addr + env_vars["MASTER_PORT"] = self._master_port + + cia_name = type(ray_cls_with_init.cls).__name__ + match = re.search(r"ActorClass\(([^)]+)\)", cia_name) # ray.remote(Obj) -> "ActorClass(Obj)" + cia_name = match.group(1) if match else cia_name # "ActorClass(Obj)" -> "Obj" + name = f"{self.name_prefix}{cia_name}_{pg_idx}:{local_rank}" # e.g. Worker_2:5 + + ray_cls_with_init.update_options({"runtime_env": {"env_vars": env_vars}, "name": name}) + + if detached: + ray_cls_with_init.update_options({"lifetime": "detached"}) + + # create a worker + worker = ray_cls_with_init( + placement_group=pg, placement_group_bundle_idx=local_rank, use_gpu=use_gpu, num_gpus=num_gpus + ) + self._workers.append(worker) + self._worker_names.append(name) + + if rank == 0: + register_center_actor = None + for _ in range(120): + if f"{self.name_prefix}_register_center" not in list_named_actors(): + time.sleep(1) + else: + register_center_actor = ray.get_actor(f"{self.name_prefix}_register_center") + break + assert register_center_actor is not None, ( + f"failed to get register_center_actor: {self.name_prefix}_register_center in {list_named_actors(all_namespaces=True)}" + ) + rank_zero_info = ray.get(register_center_actor.get_rank_zero_info.remote()) + self._master_addr, self._master_port = rank_zero_info["MASTER_ADDR"], rank_zero_info["MASTER_PORT"] + # print(f"rank_zero_info: {rank_zero_info}") + # print(f"master_addr: {self._master_addr}, master_port: {self._master_port}") + + @property + def worker_names(self): + return self._worker_names + + @classmethod + def from_detached(cls, worker_names=None, ray_cls_with_init=None): + worker_group = cls( + resource_pool=None, ray_cls_with_init=ray_cls_with_init, name_prefix=None, worker_names=worker_names + ) + return worker_group + + def spawn(self, prefix_set): + """ + spawn to a dictionary of worker groups, each with a subset of method with prefix. + + """ + + def _rebind_actor_methods(worker_group, actor_name): + """ + bind the method with actor_prefix to its original name + """ + prefix: str = actor_name + "_" + for method_name in dir(worker_group): + if method_name.startswith(prefix): + # only valid when Python >= 3.9 + original_method_name = method_name.removeprefix(prefix) + method = getattr(worker_group, method_name) + setattr(worker_group, original_method_name, method) + + new_worker_group_dict = {} + for prefix in prefix_set: + new_worker_group = self.from_detached( + worker_names=self._worker_names, ray_cls_with_init=self.ray_cls_with_init + ) + + _rebind_actor_methods(new_worker_group, prefix) + new_worker_group_dict[prefix] = new_worker_group + return new_worker_group_dict + + def execute_rank_zero_sync(self, method_name: str, *args, **kwargs): + return ray.get(self.execute_rank_zero_async(method_name, *args, **kwargs)) + + def execute_rank_zero_async(self, method_name: str, *args, **kwargs): + remote_call = getattr(self._workers[0], method_name) + return remote_call.remote(*args, **kwargs) + + def execute_rank_zero(self, method_name: str, *args, **kwargs): + return self.execute_rank_zero_async(method_name, *args, **kwargs) + + def execute_all(self, method_name: str, *args, **kwargs): + return self.execute_all_async(method_name, *args, **kwargs) + + def execute_all_sync(self, method_name: str, *args, **kwargs): + return ray.get(self.execute_all_async(method_name, *args, **kwargs)) + + def execute_all_async(self, method_name: str, *args, **kwargs): + # Here we assume that if all the parameters in args and kwargs are lists, + # and the lengths of all these lists are the same as len(self._workers), + # then we will send each element in the list to the corresponding worker. + # print(f"execute_all_async: method {method_name}({args}, {kwargs})") + length = len(self._workers) + if all(isinstance(arg, list) for arg in args) and all(isinstance(kwarg, list) for kwarg in kwargs.values()): + if all(len(arg) == length for arg in args) and all(len(kwarg) == length for kwarg in kwargs.values()): + # print(f"splitting args and kwargs into {length} shards") + result = [] + for i in range(length): + sliced_args = tuple(arg[i] for arg in args) + sliced_kwargs = {k: v[i] for k, v in kwargs.items()} + remote_call = getattr(self._workers[i], method_name) + result.append(remote_call.remote(*sliced_args, **sliced_kwargs)) + return result + + return [getattr(worker, method_name).remote(*args, **kwargs) for worker in self._workers] + + @property + def master_address(self): + return self._master_addr + + @property + def master_port(self): + return self._master_port + + @property + def workers(self): + return self._workers + + @property + def world_size(self): + return self._world_size + + +""" +Utilities that enables creating workers inside the same ray.Actor, +with code written in separate ray.Actors. +""" + + +def _bind_workers_method_to_parent(cls, key, user_defined_cls): + """ + Binds the methods of each worker to the WorkerDict. + Note that we only bind public methods that are decorated by register + """ + for method_name in dir(user_defined_cls): + try: + method = getattr(user_defined_cls, method_name) + assert callable(method), f"{method_name} in {user_defined_cls} is not callable" + except Exception: + # if it is a property, it will fail because Class doesn't have instance property + continue + + if hasattr(method, MAGIC_ATTR): + + def generate_function(name): + def func(self, *args, **kwargs): + # dispatch to the actual worker + return getattr(self.worker_dict[key], name)(*args, **kwargs) + + return func + + func = generate_function(method_name) + # pass MAGIC_ATTR for outer worker group + setattr(func, MAGIC_ATTR, getattr(method, MAGIC_ATTR)) + try: + method_name_with_prefix = key + "_" + method_name + setattr(cls, method_name_with_prefix, func) + # print(f'Binding {method_name_with_prefix}') + except Exception: + raise ValueError(f"Fail to set method_name {method_name}") + + +def _unwrap_ray_remote(cls): + if hasattr(cls, "__ray_actor_class__"): + cls = cls.__ray_actor_class__ + return cls + + +def create_colocated_worker_cls(class_dict: dict[str, RayClassWithInitArgs]): + """ + This function should return a class instance that delegates the calls to every + cls in cls_dict + """ + cls_dict = {} + init_args_dict = {} + worker_cls = None + for key, cls in class_dict.items(): + if worker_cls is None: + worker_cls = cls.cls.__ray_actor_class__.__base__ + else: + assert worker_cls == cls.cls.__ray_actor_class__.__base__, ( + "the worker class should be the same when share the same process" + ) + cls_dict[key] = cls.cls + init_args_dict[key] = {"args": cls.args, "kwargs": cls.kwargs} + + assert cls_dict.keys() == init_args_dict.keys() + + # TODO: create a class with customizable name + class WorkerDict(worker_cls): + def __init__(self): + super().__init__() + self.worker_dict = {} + for key, user_defined_cls in cls_dict.items(): + user_defined_cls = _unwrap_ray_remote(user_defined_cls) + # directly instantiate the class without remote + with patch.dict(os.environ, {"DISABLE_WORKER_INIT": "1"}): + self.worker_dict[key] = user_defined_cls( + *init_args_dict[key].get("args", ()), **init_args_dict[key].get("kwargs", {}) + ) + + # now monkey-patch the methods from inner class to WorkerDict + for key, user_defined_cls in cls_dict.items(): + user_defined_cls = _unwrap_ray_remote(user_defined_cls) + _bind_workers_method_to_parent(WorkerDict, key, user_defined_cls) + + remote_cls = ray.remote(WorkerDict) + remote_cls = RayClassWithInitArgs(cls=remote_cls) + return remote_cls diff --git a/model/EasyR1/verl/trainer/__init__.py b/model/EasyR1/verl/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce90c5eb352d85c59105c0dc85b5f1dd576f095 --- /dev/null +++ b/model/EasyR1/verl/trainer/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/model/EasyR1/verl/trainer/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/trainer/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d79faff6a58dddf9345315f7cdf4cd0bebbc94ee Binary files /dev/null and b/model/EasyR1/verl/trainer/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/trainer/__pycache__/config.cpython-311.pyc b/model/EasyR1/verl/trainer/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb6727bbadbaf2ba535e515b685d6c2320e45563 Binary files /dev/null and b/model/EasyR1/verl/trainer/__pycache__/config.cpython-311.pyc differ diff --git a/model/EasyR1/verl/trainer/__pycache__/core_algos.cpython-311.pyc b/model/EasyR1/verl/trainer/__pycache__/core_algos.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..099c241254bc6a9ef02ccb61a74ce157c3654294 Binary files /dev/null and b/model/EasyR1/verl/trainer/__pycache__/core_algos.cpython-311.pyc differ diff --git a/model/EasyR1/verl/trainer/__pycache__/data_loader.cpython-311.pyc b/model/EasyR1/verl/trainer/__pycache__/data_loader.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f304db15c42632da8d2ad9daaaa0bccf9d7a5084 Binary files /dev/null and b/model/EasyR1/verl/trainer/__pycache__/data_loader.cpython-311.pyc differ diff --git a/model/EasyR1/verl/trainer/__pycache__/main.cpython-311.pyc b/model/EasyR1/verl/trainer/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..469da84f5beef9ed77269ec55c36abfa957a15c3 Binary files /dev/null and b/model/EasyR1/verl/trainer/__pycache__/main.cpython-311.pyc differ diff --git a/model/EasyR1/verl/trainer/__pycache__/metrics.cpython-311.pyc b/model/EasyR1/verl/trainer/__pycache__/metrics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..351e013b5bf8ea96cf4eb09388a092bc07020e03 Binary files /dev/null and b/model/EasyR1/verl/trainer/__pycache__/metrics.cpython-311.pyc differ diff --git a/model/EasyR1/verl/trainer/__pycache__/ray_trainer.cpython-311.pyc b/model/EasyR1/verl/trainer/__pycache__/ray_trainer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11313c0967af1119d65b9769f2f99d7a02a44586 Binary files /dev/null and b/model/EasyR1/verl/trainer/__pycache__/ray_trainer.cpython-311.pyc differ diff --git a/model/EasyR1/verl/trainer/config.py b/model/EasyR1/verl/trainer/config.py new file mode 100644 index 0000000000000000000000000000000000000000..13e7b9f86cd29e7dda2b4a13d761027330b29af0 --- /dev/null +++ b/model/EasyR1/verl/trainer/config.py @@ -0,0 +1,184 @@ +# 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. +""" +PPO config +""" + +import os +from dataclasses import asdict, dataclass, field, fields, is_dataclass +from typing import Optional, Tuple + +from ..workers.config import WorkerConfig + + +def recursive_post_init(dataclass_obj): + if hasattr(dataclass_obj, "post_init"): + dataclass_obj.post_init() + + for attr in fields(dataclass_obj): + if is_dataclass(getattr(dataclass_obj, attr.name)): + recursive_post_init(getattr(dataclass_obj, attr.name)) + + +@dataclass +class DataConfig: + train_files: str = "" + val_files: str = "" + prompt_key: str = "prompt" + answer_key: str = "answer" + image_key: str = "images" + video_key: str = "videos" + image_dir: Optional[str] = None + video_fps: float = 2.0 + max_prompt_length: int = 512 + max_response_length: int = 512 + rollout_batch_size: int = 512 + mini_rollout_batch_size: Optional[int] = None + val_batch_size: int = -1 + format_prompt: Optional[str] = None + override_chat_template: Optional[str] = None + shuffle: bool = True + seed: int = 1 + min_pixels: Optional[int] = 262144 + max_pixels: Optional[int] = 4194304 + resize_size: int = 0 + """resize image shorter side to this size, 0 means disabled""" + filter_overlong_prompts: bool = True + filter_overlong_prompts_workers: int = 16 + + def post_init(self): + if self.image_dir is not None: + if os.path.exists(self.image_dir): # ray job uses absolute path + self.image_dir = os.path.abspath(self.image_dir) + else: + print(f"Image directory {self.image_dir} not found.") + self.image_dir = None + + if self.format_prompt is not None: + if os.path.exists(self.format_prompt): # ray job uses absolute path + self.format_prompt = os.path.abspath(self.format_prompt) + else: + print(f"Format prompt file {self.format_prompt} not found.") + self.format_prompt = None + + +@dataclass +class AlgorithmConfig: + gamma: float = 1.0 + """discount factor for ppo gae advantage estimator""" + lam: float = 1.0 + """lambda value for ppo gae advantage estimator""" + adv_estimator: str = "grpo" + """advantage estimator, support `gae`, `grpo`, `reinforce_plus_plus`, `remax`, `rloo`""" + disable_kl: bool = False + """disable reference model""" + use_kl_loss: bool = False + """use kl loss instead of kl in reward""" + kl_penalty: str = "kl" + """kl penalty type, support `kl`, `abs`, `mse`, `low_var_kl`, `full`""" + kl_coef: float = 1e-3 + """kl coefficient""" + kl_type: str = "fixed" + """kl controller type, support `fixed`, `adaptive`""" + kl_horizon: float = 10000.0 + """kl horizon for adaptive kl controller""" + kl_target: float = 0.1 + """target kl for adaptive kl controller""" + online_filtering: bool = False + """use online filtering""" + filter_key: str = "overall" + """reward key for filtering samples""" + filter_low: float = 0.01 + """filter out low reward samples if online filtering""" + filter_high: float = 0.99 + """filter out high reward samples if online filtering""" + + +@dataclass +class TrainerConfig: + total_epochs: int = 15 + """total epochs for training""" + max_steps: Optional[int] = None + """max steps for training, if specified, total_epochs is ignored""" + project_name: str = "easy_r1" + """project name for logger""" + experiment_name: str = "demo" + """experiment name for logger""" + logger: Tuple[str] = ("console", "wandb") + """logger type, support `console`, `mlflow`, `swanlab`, `tensorboard`, `wandb`""" + nnodes: int = 1 + """number of nodes for training""" + n_gpus_per_node: int = 8 + """number of gpus per node for training""" + max_try_make_batch: int = 20 + """max number of generations for online filtering, -1 means no limit""" + critic_warmup: int = 0 + """critic warmup steps""" + val_freq: int = -1 + """validation frequency, -1 means no validation""" + val_before_train: bool = True + """validate before training""" + val_only: bool = False + """validate only, skip training""" + val_generations_to_log: int = 0 + """number of generations to log for validation""" + save_freq: int = -1 + """save frequency, -1 means no saving""" + save_limit: int = -1 + """max number of checkpoints to save, -1 means no limit""" + save_model_only: bool = False + """save model only, no optimizer state dict""" + save_checkpoint_path: Optional[str] = None + """save checkpoint path, if not specified, use `checkpoints/project_name/experiment_name`""" + load_checkpoint_path: Optional[str] = None + """load checkpoint path""" + ray_timeline: Optional[str] = None + """file to save ray timeline""" + find_last_checkpoint: bool = True + """automatically find the last checkpoint in the save checkpoint path to resume training""" + + def post_init(self): + if self.save_checkpoint_path is None: + self.save_checkpoint_path = os.path.join("checkpoints", self.project_name, self.experiment_name) + + self.save_checkpoint_path = os.path.abspath(self.save_checkpoint_path) # ray job uses absolute path + if self.load_checkpoint_path is not None: + if os.path.exists(self.load_checkpoint_path): # ray job uses absolute path + self.load_checkpoint_path = os.path.abspath(self.load_checkpoint_path) + else: + print(f"Model checkpoint {self.load_checkpoint_path} not found.") + self.load_checkpoint_path = None + + +@dataclass +class PPOConfig: + data: DataConfig = field(default_factory=DataConfig) + worker: WorkerConfig = field(default_factory=WorkerConfig) + algorithm: AlgorithmConfig = field(default_factory=AlgorithmConfig) + trainer: TrainerConfig = field(default_factory=TrainerConfig) + + def post_init(self): + self.worker.rollout.prompt_length = self.data.max_prompt_length + self.worker.rollout.response_length = self.data.max_response_length + self.worker.rollout.trust_remote_code = self.worker.actor.model.trust_remote_code + self.worker.actor.disable_kl = self.algorithm.disable_kl + self.worker.actor.use_kl_loss = self.algorithm.use_kl_loss + self.worker.actor.kl_penalty = self.algorithm.kl_penalty + self.worker.actor.kl_coef = self.algorithm.kl_coef + + def deep_post_init(self): + recursive_post_init(self) + + def to_dict(self): + return asdict(self) diff --git a/model/EasyR1/verl/trainer/core_algos.py b/model/EasyR1/verl/trainer/core_algos.py new file mode 100644 index 0000000000000000000000000000000000000000..338356a0003bb3cf95e90e21e3b00fe59dafed84 --- /dev/null +++ b/model/EasyR1/verl/trainer/core_algos.py @@ -0,0 +1,825 @@ +# Copyright 2022 The HuggingFace Team +# 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. +""" +Core functions to implement PPO algorithms. +The function implemented in this file should be used by trainer with different distributed strategies to +implement PPO +""" + +from abc import ABC, abstractmethod +from collections import defaultdict +from enum import Enum +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np +import torch +import torch.nn.functional as F + +from ..utils import torch_functional as VF + + +if TYPE_CHECKING: + from .config import AlgorithmConfig + + +class KLController(ABC): + kl_coef: float + """KL coefficient.""" + + @abstractmethod + def update(self, current_kl: float, n_steps: int): + """Update kl_coef according to current KL.""" + ... + + +class AdaptiveKLController(KLController): + """Adaptive KL controller described in: https://arxiv.org/pdf/1909.08593.pdf + + Copied from https://github.com/huggingface/trl/blob/v0.11.0/trl/trainer/utils.py#L54""" + + def __init__(self, init_kl_coef: float, target_kl: float, horizon: float): + self.kl_coef = init_kl_coef + self.target = target_kl + self.horizon = horizon + + def update(self, current_kl: float, n_steps: int): + target = self.target + proportional_error = np.clip(current_kl / target - 1, -0.2, 0.2) + mult = 1 + proportional_error * n_steps / self.horizon + self.kl_coef *= mult + + +class FixedKLController(KLController): + """Fixed KL controller. + + Copeid from https://github.com/huggingface/trl/blob/v0.11.0/trl/trainer/utils.py#L72""" + + def __init__(self, init_kl_coef: float): + self.kl_coef = init_kl_coef + + def update(self, current_kl: float, n_steps: int): + pass + + +class AdvantageEstimator(str, Enum): + """ + Using an enumeration class to avoid spelling errors in adv_estimator + """ + + GAE = "gae" + GRPO = "grpo" + REINFORCE_PLUS_PLUS = "reinforce_plus_plus" + REMAX = "remax" + RLOO = "rloo" + EMA_GRPO = "ema_grpo" + + +ADV_ESTIMATOR_MAP: dict[str, Any] = {} + + +def get_kl_controller(algorithm_config: "AlgorithmConfig") -> KLController: + """Adapted from https://github.com/huggingface/trl/blob/v0.11.0/trl/trainer/ppo_trainer.py#L319""" + if algorithm_config.kl_type == "fixed": + kl_ctrl = FixedKLController(init_kl_coef=algorithm_config.kl_coef) + elif algorithm_config.kl_type == "adaptive": + assert algorithm_config.kl_horizon > 0, f"horizon must be larger than 0. Got {algorithm_config.kl_horizon}." + kl_ctrl = AdaptiveKLController( + init_kl_coef=algorithm_config.kl_coef, + target_kl=algorithm_config.kl_target, + horizon=algorithm_config.kl_horizon, + ) + else: + raise ValueError(f"Unknown kl type: {algorithm_config.kl_type}.") + + return kl_ctrl + + +def register_adv_estimator(name: AdvantageEstimator): + """Decorator to register a advantage estimator function with a given name.""" + + def decorator(fn): + wrapped_fn = torch.no_grad()(fn) + ADV_ESTIMATOR_MAP[getattr(name, "value", name)] = wrapped_fn + return wrapped_fn + + return decorator + + +def compute_advantage_return(name: AdvantageEstimator, **kwargs) -> tuple[torch.Tensor, torch.Tensor]: + """Compute advantage and return for a given advantage estimator.""" + return ADV_ESTIMATOR_MAP[getattr(name, "value", name)](**kwargs) + + +@register_adv_estimator(AdvantageEstimator.GAE) +def compute_gae_advantage_return( + token_level_rewards: torch.Tensor, + values: torch.Tensor, + response_mask: torch.Tensor, + gamma: torch.Tensor, + lam: torch.Tensor, + **kwargs, +) -> tuple[torch.Tensor, torch.Tensor]: + """Adapted from https://github.com/huggingface/trl/blob/v0.16.0/trl/trainer/ppo_trainer.py#L513 + + Args: + token_level_rewards: `(torch.Tensor)` + shape: (bs, response_length) + values: `(torch.Tensor)` + shape: (bs, response_length) + response_mask: `(torch.Tensor)` + shape: (bs, response_length). The token after eos tokens have mask zero. + gamma: `(float)` + discounted factor used in RL + lam: `(float)` + lambda value when computing Generalized Advantage Estimation (https://arxiv.org/abs/1506.02438) + + Returns: + advantages: `(torch.Tensor)` + shape: (bs, response_length) + returns: `(torch.Tensor)` + shape: (bs, response_length) + + """ + lastgaelam = 0 + advantages_reversed = [] + gen_len = token_level_rewards.shape[-1] + for t in reversed(range(gen_len)): + nextvalues = values[:, t + 1] if t < gen_len - 1 else 0.0 + delta = token_level_rewards[:, t] + gamma * nextvalues - values[:, t] + lastgaelam = delta + gamma * lam * lastgaelam + advantages_reversed.append(lastgaelam) + + advantages = torch.stack(advantages_reversed[::-1], dim=1) + returns = advantages + values + advantages = VF.masked_whiten(advantages, response_mask) + return advantages, returns + + +# NOTE(sgm): this implementation only consider outcome supervision, where the reward is a scalar. +@register_adv_estimator(AdvantageEstimator.GRPO) +def compute_grpo_outcome_advantage( + token_level_rewards: torch.Tensor, response_mask: torch.Tensor, index: torch.Tensor, eps: float = 1e-6, **kwargs +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Compute advantage for GRPO, operating only on Outcome reward (with only one scalar reward for each response). + + Args: + token_level_rewards: `(torch.Tensor)` + shape: (bs, response_length) + response_mask: `(torch.Tensor)` + shape: (bs, response_length) + index: `(torch.Tensor)` + shape: (bs,) + eps: `(float)` + epsilon value to avoid division by zero + + Returns: + advantages: `(torch.Tensor)` + shape: (bs, response_length) + returns: `(torch.Tensor)` + shape: (bs, response_length) + + """ + scores = token_level_rewards.sum(dim=-1) + id2score = defaultdict(list) + id2mean, id2std = {}, {} + + bsz = scores.shape[0] + for i in range(bsz): + id2score[index[i]].append(scores[i]) + + for idx in id2score: + assert len(id2score[idx]) > 1, "GRPO needs rollout.n > 1." + id2mean[idx] = torch.mean(torch.tensor(id2score[idx])) + id2std[idx] = torch.std(torch.tensor(id2score[idx])) + + for i in range(bsz): + scores[i] = (scores[i] - id2mean[index[i]]) / (id2std[index[i]] + eps) + + returns = scores.unsqueeze(-1) * response_mask + return returns, returns + + + + + + +class _EmaStdTracker: + """ + Maintain EMA first moment E[X] and second moment E[X^2] for each "task key", + and compute std = sqrt(E[X^2] - (E[X])^2). + - Here X refers to the "Outcome score" (a single scalar obtained by summing token-level rewards over time). + - The statistics are persistent only within a single process / rank; in multi-process settings, + each process maintains its own tracker (for global consistency, use all-reduce or save to trainer state externally). + - Benefit of EMA: adaptive to non-stationary distributions; meanwhile avoids over-reliance on early statistics + (the effective memory length is controlled by decay). + """ + def __init__(self, decay: float = 0.99, min_std: float = 1e-3): + self.decay = decay # EMA decay factor; larger means longer memory + self.min_std = min_std # Lower bound of std for numerical stability to avoid division by zero + # Mapping: task_key -> { "m1": E[X], "m2": E[X^2], "initialized": bool } + self.state: dict[str, dict[str, float]] = {} + + def get_std(self, key: str) -> float: + """ + Get the current EMA standard deviation of the given task. + If uninitialized, return min_std (a conservative value to avoid explosion / NaN at the beginning). + """ + s = self.state.get(key) + if not s or not s.get("initialized", False): + return self.min_std + # Numerical stability: E[X^2] - (E[X])^2 can be slightly negative due to floating-point errors; clamp it + var = max(s["m2"] - s["m1"] * s["m1"], 0.0) + # Also clamp std with a lower bound to prevent scaling explosion caused by extremely small variance + return float(max(var, self.min_std ** 2) ** 0.5) + + def update_with_batch_scores(self, key: str, scores: torch.Tensor): + """ + Update EMA first and second moments using the "current batch of outcome scores" for this task. + Convention: normalization uses the *old EMA values*, and EMA is updated *afterward* using this batch, + to avoid bias caused by "seeing itself". + """ + if scores.numel() == 0: + return + x = scores.float() + # Directly use mean and second moment for EMA (not unbiased variance; + # EMA itself is a biased estimator but is more robust for online / non-stationary settings) + m1_batch = x.mean().item() + m2_batch = (x * x).mean().item() + + s = self.state.get(key) + if s is None or not s.get("initialized", False): + # First time seeing this task: initialize with current batch statistics + self.state[key] = {"m1": m1_batch, "m2": m2_batch, "initialized": True} + else: + d = self.decay + s["m1"] = d * s["m1"] + (1.0 - d) * m1_batch + s["m2"] = d * s["m2"] + (1.0 - d) * m2_batch + s["initialized"] = True + + # ===== NEW: get the current EMA mean for this task (return 0.0 if uninitialized) ===== + def get_mean(self, key: str) -> float: + """ + Return the current EMA mean (E[X]) of the task. Return 0.0 if uninitialized. + (Used only for logging / monitoring; not involved in algorithmic scaling; no clipping applied.) + """ + s = self.state.get(key) + if not s or not s.get("initialized", False): + return 0.0 + return float(s["m1"]) + + # ===== NEW: print means and stds in two lines ===== + def log_means_and_stds( + self, + keys: list[str] | None = None, + print_fn=None, + tag_means: str = "EMA_MEAN", + tag_stds: str = "EMA_STD", + digits: int = 6, + sort_keys: bool = True, + ) -> None: + """ + Print in two lines: + [EMA_MEAN] task=mean:... + [EMA_STD] task=std:... + """ + if print_fn is None: + print_fn = print + if keys is None: + keys = list(self.state.keys()) + if sort_keys: + keys = sorted(keys) + if not keys: + try: + print_fn(f"[{tag_means}] (empty)") + print_fn(f"[{tag_stds}] (empty)") + except Exception: + pass + return + + mean_line = "[{tag}] ".format(tag=tag_means) + ", ".join( + f"{k}=mean:{self.get_mean(k):.{digits}f}" for k in keys + ) + std_line = "[{tag}] ".format(tag=tag_stds) + ", ".join( + f"{k}=std:{self.get_std(k):.{digits}f}" for k in keys + ) + try: + print_fn(mean_line) + print_fn(std_line) + except Exception: + # Defensive: avoid logger / print_fn failure affecting training + pass + + + + + +# Global (process-local) singleton; for cross-process sharing, synchronize outside +_EMA_STD_TRACKER = _EmaStdTracker() + + +# ===== NEW: task key generation function ===== +def _task_key_of(sample_problem_type: str, sample_data_type: str | None) -> str: + """ + Task partition rule: + - By default, aggregate by problem_type; + - If problem_type == "segmentation", further split by data_type into + "segmentation/image" and "segmentation/video". + """ + if sample_problem_type == "segmentation": + dt = (sample_data_type or "").lower() + if dt in ("video", "image"): + return f"segmentation/{dt}" + return sample_problem_type + + + +@register_adv_estimator(AdvantageEstimator.EMA_GRPO) +def compute_ema_grpo_outcome_advantage( + token_level_rewards: torch.Tensor, # (bs, response_length) + response_mask: torch.Tensor, # (bs, response_length) + index, # (bs,) group id: numpy array / list[str] / torch.Tensor (same prompt shares) + problem_type, # (bs,) numpy/list/torch.Tensor: strings + data_type=None, # (bs,) numpy/list/torch.Tensor/None: strings; only used to split segmentation image/video + # ===== Tunable hyperparameters (can be passed through AlgorithmConfig) ===== + ema_decay: float = 0.99, # EMA decay; can be smaller (e.g., 0.97) for non-stationary tasks + min_std: float = 1e-3, # Lower bound for numerical stability + use_group_mean_centering: bool = True, # Whether to keep GRPO-style group-wise mean-centering (recommended True) + eps: float = 1e-6, # Division-by-zero protection during scaling + # NEW: guard rail: fallback to group std if the threshold is exceeded (default ±5) + guard_abs_max: float = 5.0, + **kwargs, +) -> tuple[torch.Tensor, torch.Tensor]: + """ + EMA-GRPO (Outcome supervision): + 1) Keep GRPO-style group-wise mean-centering (samples with the same index are centered), + to reduce intra-group variance; + 2) No longer use "group std" for scaling; instead use "task-level EMA std"; + 3) **First update EMA using current batch scores (including initialization), + then scale using the "updated" std**, + i.e., statistics that have "seen themselves", improving responsiveness to non-stationary distributions; + 4) **Guard rail**: if after scaling with "task-level std", any value in a group + (same index) exceeds [-guard_abs_max, +guard_abs_max], + then that group falls back to "group std" scaling (only that group is affected). + Returns: + advantages: (bs, response_length) + returns: (bs, response_length) + """ + # —— Device / dtype alignment (consistent with original file conventions) —— + device = token_level_rewards.device + dtype = token_level_rewards.dtype + + # —— Set global tracker hyperparameters (if desired to set only once, one can add a flag; + # here we directly assign for clarity) —— + _EMA_STD_TRACKER.decay = float(ema_decay) + _EMA_STD_TRACKER.min_std = float(min_std) + + # —— Convert index / problem_type / data_type to Python lists uniformly + # (robustly handling numpy / torch / list) —— + def _to_list(x): + if x is None: + return None + if torch.is_tensor(x): + x = x.tolist() + else: + try: + import numpy as _np + if isinstance(x, _np.ndarray): + x = x.tolist() + except Exception: + pass + if not isinstance(x, (list, tuple)): + x = list(x) + return x + + index_list = _to_list(index) + problem_type_list = _to_list(problem_type) + data_type_list = _to_list(data_type) + + # Note: index may be UUID or any hashable object; convert to str uniformly as the grouping key + index_keys = [str(g) for g in index_list] + + # —— Aggregate token-level reward into a single "Outcome score": + # in most scenarios, only the last token is outcome and others are 0 —— + scores = token_level_rewards.sum(dim=-1) # (bs,) + + bsz = scores.shape[0] + + # —— Group sample positions by "task key" —— + # Task partition rule: default by problem_type; + # if problem_type == "segmentation", further split by data_type + def _task_key_of(sample_problem_type: str, sample_data_type: str | None) -> str: + if sample_problem_type == "segmentation": + dt = (sample_data_type or "").lower() + if dt in ("video", "image"): + return f"segmentation/{dt}" + return sample_problem_type + + task_to_pos: dict[str, list[int]] = {} + for i in range(bsz): + pt = str(problem_type_list[i]) if problem_type_list is not None else "" + dt = None + if pt == "segmentation" and data_type_list is not None: + dt = str(data_type_list[i]) if i < len(data_type_list) else None + key = _task_key_of(pt, dt) + task_to_pos.setdefault(key, []).append(i) + + # —— Group-wise mean-centering (multiple samples with the same index) —— + centered = scores.clone() + gid_to_pos: dict[str, list[int]] = {} + for i, gid in enumerate(index_keys): + gid_to_pos.setdefault(gid, []).append(i) + + if use_group_mean_centering: + for gid, pos_list in gid_to_pos.items(): + # GRPO / EMA-GRPO assumption: each group must have at least 2 samples + assert len(pos_list) > 1, "EMA-GRPO requires rollout.n > 1 per group (same index)." + g = scores[pos_list] + g_mean = g.mean() + centered[pos_list] = g - g_mean + else: + # If centering is disabled, this is a no-op; keep shape consistency + centered = centered - 0.0 + + # ========================= + # First use "current batch scores" to **update / initialize** + # the EMA statistics for each task, + # then read the "updated" task std for scaling. + # ========================= + + # First update / initialize EMA for each task using this batch's scores + for key, pos_list in task_to_pos.items(): + _EMA_STD_TRACKER.update_with_batch_scores(key, scores[pos_list]) + + # 【Logging】current task stds (statistics already include this batch) + _EMA_STD_TRACKER.log_means_and_stds( + keys=None, + tag_means="EMA_MEAN(after_update)", + tag_stds="EMA_STD(after_update)", + ) + + + # Then read the "updated" std for scaling (statistics that have "seen themselves") + scaled = centered.clone() + + # —— For each "task key", further split into "groups" (same index) for guard-rail checking —— + from collections import defaultdict as _dd + for key, task_pos in task_to_pos.items(): + task_std = _EMA_STD_TRACKER.get_std(key) # already includes contribution from this batch + + # Under this task, further group samples by "group id (index_keys)" + group_to_pos: dict[str, list[int]] = _dd(list) + for i in task_pos: + group_to_pos[index_keys[i]].append(i) + + # For each group, first try scaling with "task-level std"; + # if any value exceeds the guard, fall back to "group std" + for gid, gpos in group_to_pos.items(): + # 1) First scale this group with the task-level std + tmp = centered[gpos] / (task_std + eps) + + # 2) Guard check: if any value exceeds [-guard_abs_max, +guard_abs_max], fall back + if torch.any(torch.abs(tmp) > guard_abs_max): + # Group std: follow original GRPO logic, use the group-wise std of scores + g_scores = scores[gpos].float() + g_std = torch.std(g_scores, unbiased=False).item() + scaled[gpos] = centered[gpos] / (g_std + eps) + else: + # No violation: keep task-level std scaling + scaled[gpos] = tmp + + # —— Broadcast back to token dimension and multiply by mask + # (same return convention as the original implementation: for pure outcome, + # advantages == returns) —— + if response_mask.device != device: + response_mask = response_mask.to(device) + if not torch.is_floating_point(response_mask): + response_mask = response_mask.to(dtype) + + returns = scaled.to(dtype).unsqueeze(-1) * response_mask # (bs, T) + advantages = returns # Pure outcome supervision: A = R + + return advantages, returns + + + + + +@register_adv_estimator(AdvantageEstimator.RLOO) +def compute_rloo_outcome_advantage( + token_level_rewards: torch.Tensor, response_mask: torch.Tensor, index: torch.Tensor, **kwargs +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Compute advantage for RLOO based on https://arxiv.org/abs/2402.14740 + + Args: + token_level_rewards: `(torch.Tensor)` + shape: (bs, response_length) + response_mask: `(torch.Tensor)` + shape: (bs, response_length) + index: `(torch.Tensor)` + shape: (bs,) + + Returns: + advantages: `(torch.Tensor)` + shape: (bs, response_length) + returns: `(torch.Tensor)` + shape: (bs, response_length) + + """ + scores = token_level_rewards.sum(dim=-1) + + id2score = defaultdict(list) + id2sum = {} + bsz = scores.shape[0] + for i in range(bsz): + id2score[index[i]].append(scores[i]) + + for idx in id2score: + id2sum[idx] = torch.sum(torch.tensor(id2score[idx])) + + for i in range(bsz): + sample_num = len(id2score[index[i]]) + assert sample_num > 1, "RLOO needs rollout.n > 1." + baseline = (id2sum[index[i]] - scores[i]) / (sample_num - 1) + scores[i] = scores[i] - baseline + + returns = scores.unsqueeze(-1) * response_mask + return returns, returns + + +@register_adv_estimator(AdvantageEstimator.REINFORCE_PLUS_PLUS) +def compute_reinforce_plus_plus_outcome_advantage( + token_level_rewards: torch.Tensor, response_mask: torch.Tensor, gamma: torch.Tensor, **kwargs +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Compute advantage for REINFORCE++. + This implementation is based on the paper: https://arxiv.org/abs/2501.03262 + + Args: + token_level_rewards: `(torch.Tensor)` + shape: (bs, response_length) + response_mask: `(torch.Tensor)` + shape: (bs, response_length) + + Returns: + advantages: `(torch.Tensor)` + shape: (bs, response_length) + returns: `(torch.Tensor)` + shape: (bs, response_length) + + """ + returns = torch.zeros_like(token_level_rewards) + running_return = 0 + for t in reversed(range(token_level_rewards.shape[1])): + running_return = token_level_rewards[:, t] + gamma * running_return + returns[:, t] = running_return + # Reset after EOS + running_return = running_return * response_mask[:, t] + + advantages = VF.masked_whiten(returns, response_mask) + return advantages, returns + + +@register_adv_estimator(AdvantageEstimator.REMAX) +def compute_remax_outcome_advantage( + token_level_rewards: torch.Tensor, reward_baselines: torch.Tensor, response_mask: torch.Tensor, **kwargs +) -> tuple[torch.Tensor, torch.Tensor]: + """ + Compute advantage for ReMax, operating only on Outcome reward + This implementation is based on the paper: https://arxiv.org/abs/2310.10505 + + (with only one scalar reward for each response). + Args: + token_level_rewards: `(torch.Tensor)` + shape: (bs, response_length) + reward_baselines: `(torch.Tensor)` + shape: (bs,) + response_mask: `(torch.Tensor)` + shape: (bs, response_length) + + Returns: + advantages: `(torch.Tensor)` + shape: (bs, response_length) + returns: `(torch.Tensor)` + shape: (bs, response_length) + + """ + scores = token_level_rewards.sum(dim=-1) - reward_baselines + returns = scores.unsqueeze(-1) * response_mask + return returns, returns + + +def compute_rewards( + token_level_scores: torch.Tensor, + log_probs: torch.Tensor, + ref_log_probs: torch.Tensor, + kl_ratio: float, +) -> torch.Tensor: + kl = log_probs - ref_log_probs + return token_level_scores - kl * kl_ratio + + +def average_loss( + values: torch.Tensor, mask: torch.Tensor, mode: Literal["token", "seq"], eps: float = 1e-8 +) -> torch.Tensor: + """Average the policy loss. + + Args: + values: `(torch.Tensor)` + shape: (bs, response_length) + mask: `(torch.Tensor)` + shape: (bs, response_length) + mode: `(Literal["token", "seq"])` + "token": average the loss in the whole batch + "seq": average the loss in each sequence then average the mean of the means + eps: `(float)` + epsilon value + + Returns: + loss: `a scalar torch.Tensor` + """ + if mode == "token": + return VF.masked_mean(values, mask, eps=eps) + elif mode == "seq": + return ((values * mask).sum(-1) / (mask.sum(-1) + eps)).mean() + else: + raise NotImplementedError(f"Unknown mode: {mode}.") + + +def compute_policy_loss( + old_log_probs: torch.Tensor, + log_probs: torch.Tensor, + advantages: torch.Tensor, + response_mask: torch.Tensor, + clip_ratio_low: float, + clip_ratio_high: float, + clip_ratio_dual: float, + loss_avg_mode: Literal["token", "seq"], +) -> tuple[torch.Tensor, dict[str, float]]: + """Compute the clipped policy objective and related metrics for PPO. + + Adapted from https://github.com/huggingface/trl/blob/v0.15.0/trl/trainer/ppo_trainer.py#L568 + + Args: + old_log_prob: `(torch.Tensor)` + shape: (bs, response_length) + log_prob: `(torch.Tensor)` + shape: (bs, response_length) + advantages: `(torch.Tensor)` + shape: (bs, response_length) + response_mask: `(torch.Tensor)` + shape: (bs, response_length) + clip_ratio_low: (float) + The lower clip range used in PPO. See https://arxiv.org/abs/1707.06347 + clip_ratio_high: (float) + The higher clip range used in DAPO. See https://arxiv.org/pdf/2503.14476 + clip_ratio_dual: (float) + The dual clip range used in Dual-clip PPO. See https://arxiv.org/pdf/1912.09729 + loss_avg_mode: (Literal["token", "seq"]) + "token": average the loss in the whole batch + "seq": average the loss in each sequence then average the mean of the means + + Returns: + pg_loss: `a scalar torch.Tensor` + policy gradient loss computed via PPO + pg_clipfrac_higher: (float) + a float number indicating the fraction of policy gradient loss being clipped to a higher value + pg_clipfrac_lower: (float) + a float number indicating the fraction of policy gradient loss being clipped to a lower value + ppo_kl: (float) + a float number indicating the mean KL divergence between the old policy and the new policy + entropy_loss: (float) + a float number indicating the mean entropy loss + + """ + negative_approx_kl = log_probs - old_log_probs + # clamp negative_approx_kl to avoid nan kld + negative_approx_kl = torch.clamp(negative_approx_kl, -20.0, 20.0) + ratio = torch.exp(negative_approx_kl) + # clamp the ratio before exp to avoid nan grad + # see: https://github.com/pytorch/pytorch/issues/10729 + clipped_ratio = torch.exp( + torch.clamp(negative_approx_kl, np.log(1.0 - clip_ratio_low), np.log(1.0 + clip_ratio_high)) + ) + + # pg metrics + metrics = {"ppo_kl": -negative_approx_kl} + # use negative log probs as an estimator of entropy loss + metrics["entropy_loss"] = average_loss(-log_probs, response_mask, mode=loss_avg_mode) + + pg_loss = -advantages * ratio # -ratio * A + pg_loss2 = -advantages * clipped_ratio # -clip(ratio, 1-clip_low, 1+clip_high) * A + pg_loss3 = -advantages * clip_ratio_dual # -clip_dual * A + + clipped_pg_loss_higher = torch.max(pg_loss, pg_loss2) # clip if pg_loss < pg_loss2 + metrics["pg_clipfrac_higher"] = (pg_loss < pg_loss2).float() + clipped_pg_loss_lower = torch.min(clipped_pg_loss_higher, pg_loss3) # clip if pg_loss > pg_loss3 and adv < 0 + final_pg_loss = torch.where(advantages < 0, clipped_pg_loss_lower, clipped_pg_loss_higher) + metrics["pg_clipfrac_lower"] = (clipped_pg_loss_higher > pg_loss3).float() * (advantages < 0).float() + + final_pg_loss = average_loss(final_pg_loss, response_mask, mode=loss_avg_mode) + metrics = {k: VF.masked_mean(v, response_mask).detach().item() for k, v in metrics.items()} + return final_pg_loss, metrics + + +def compute_value_loss( + vpreds: torch.Tensor, + returns: torch.Tensor, + values: torch.Tensor, + response_mask: torch.Tensor, + cliprange_value: float, + loss_avg_mode: Literal["token", "seq"], +) -> tuple[torch.Tensor, dict[str, float]]: + """Compute the value loss. + + Adapted from https://github.com/huggingface/trl/blob/v0.15.0/trl/trainer/ppo_trainer.py#L556 + + Args: + vpreds (`torch.FloatTensor`): + Predicted values of the value head, shape (`batch_size`, `response_length`) + returns: (`torch.FloatTensor`): + Ground truth returns, shape (`batch_size`, `response_length`) + values (`torch.FloatTensor`): + Old values of value head, shape (`batch_size`, `response_length`) + response_mask: `(torch.Tensor)` + shape: (bs, response_length) + cliprange_value: (float) + The clip range for value net used in PPO. See https://arxiv.org/abs/1707.06347 + loss_avg_mode: (Literal["token", "seq"]) + "token": average the loss in the whole batch + "seq": average the loss in each sequence then average the mean of the means + + Returns: + vf_loss: a scalar (`torch.FloatTensor`): + value function loss + vf_clipfrac: a float + The ratio of vf being clipped + vpred_mean: a float + The mean of predicted values + + """ + vpredclipped = torch.clamp(vpreds, values - cliprange_value, values + cliprange_value) + vf_loss1 = torch.square(vpreds - returns) + vf_loss2 = torch.square(vpredclipped - returns) + clipped_vf_losses = torch.max(vf_loss1, vf_loss2) # clip if vf_loss1 < vf_loss2 + vf_loss = 0.5 * average_loss(clipped_vf_losses, response_mask, mode=loss_avg_mode) + metrics = { + "vf_clipfrac": VF.masked_mean((vf_loss1 < vf_loss2).float(), response_mask).detach().item(), + "vpred_mean": VF.masked_mean(vpreds, response_mask).detach().item(), + } + return vf_loss, metrics + + +def compute_kl( + log_probs: torch.FloatTensor, + ref_log_probs: torch.FloatTensor, + kl_penalty: Literal["kl", "abs", "mse", "low_var_kl", "full"], +) -> torch.Tensor: + """Compute KL divergence given log_probs and ref_log_probs. + + Adapted from https://github.com/huggingface/trl/blob/v0.11.0/trl/trainer/ppo_trainer.py#L1150 + + Args: + log_probs: torch.Tensor + ref_log_probs: torch.Tensor + kl_penalty: str ("kl", "abs", "mse", "low_var_kl", "full") + + Returns: + kl_div: torch.Tensor + + """ + log_probs, ref_log_probs = log_probs.float(), ref_log_probs.float() + if kl_penalty == "kl": + return log_probs - ref_log_probs + + if kl_penalty == "abs": + return (log_probs - ref_log_probs).abs() + + if kl_penalty == "mse": + return 0.5 * (log_probs - ref_log_probs).square() + + # J. Schulman. Approximating kl divergence, 2020. + # URL http://joschu.net/blog/kl-approx.html + if kl_penalty == "low_var_kl": + # For numerical stability + kl = (ref_log_probs - log_probs).clamp(-20.0, 20.0) + kld = (kl.exp() - kl - 1).contiguous() + return torch.clamp(kld, min=-10.0, max=10.0) + + if kl_penalty == "full": + return F.kl_div(ref_log_probs, log_probs, log_target=True, reduction="none").sum(-1) + + raise NotImplementedError(f"Unknown KL penalty: {kl_penalty}.") diff --git a/model/EasyR1/verl/trainer/data_loader.py b/model/EasyR1/verl/trainer/data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..99a135554544c830b0c0cfa6d07b651d389e1380 --- /dev/null +++ b/model/EasyR1/verl/trainer/data_loader.py @@ -0,0 +1,107 @@ +# 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. + +from typing import Optional + +import torch +from torch.utils.data import RandomSampler, SequentialSampler +from torchdata.stateful_dataloader import StatefulDataLoader +from transformers import PreTrainedTokenizer, ProcessorMixin + +from ..utils.dataset import RLHFDataset, collate_fn +from .config import DataConfig + + +def create_dataloader(config: DataConfig, tokenizer: PreTrainedTokenizer, processor: Optional[ProcessorMixin]) -> None: + train_dataset = RLHFDataset( + data_path=config.train_files, + tokenizer=tokenizer, + processor=processor, + prompt_key=config.prompt_key, + answer_key=config.answer_key, + image_key=config.image_key, + video_key=config.video_key, + image_dir=config.image_dir, + video_fps=config.video_fps, + max_prompt_length=config.max_prompt_length, + truncation="right", + format_prompt=config.format_prompt, + min_pixels=config.min_pixels, + max_pixels=config.max_pixels, + resize_size=config.resize_size, + filter_overlong_prompts=config.filter_overlong_prompts, + filter_overlong_prompts_workers=config.filter_overlong_prompts_workers, + ) + # use sampler for better ckpt resume + if config.shuffle: + train_dataloader_generator = torch.Generator() + train_dataloader_generator.manual_seed(config.seed) + sampler = RandomSampler(data_source=train_dataset, generator=train_dataloader_generator) + else: + sampler = SequentialSampler(data_source=train_dataset) + + if config.mini_rollout_batch_size is not None: + train_batch_size = config.mini_rollout_batch_size + else: + train_batch_size = config.rollout_batch_size + + train_dataloader = StatefulDataLoader( + dataset=train_dataset, + batch_size=train_batch_size, + sampler=sampler, + num_workers=8, + collate_fn=collate_fn, + pin_memory=False, + drop_last=True, + ) + + val_dataset = RLHFDataset( + data_path=config.val_files, + tokenizer=tokenizer, + processor=processor, + prompt_key=config.prompt_key, + answer_key=config.answer_key, + image_key=config.image_key, + video_key=config.video_key, + image_dir=config.image_dir, + video_fps=config.video_fps, + max_prompt_length=config.max_prompt_length, + truncation="right", + format_prompt=config.format_prompt, + min_pixels=config.min_pixels, + max_pixels=config.max_pixels, + resize_size=config.resize_size, + filter_overlong_prompts=config.filter_overlong_prompts, + ) + + if config.val_batch_size == -1: + val_batch_size = len(val_dataset) + else: + val_batch_size = config.val_batch_size + + val_dataloader = StatefulDataLoader( + dataset=val_dataset, + batch_size=val_batch_size, + shuffle=False, + num_workers=8, + collate_fn=collate_fn, + pin_memory=False, + drop_last=False, + ) + + assert len(train_dataloader) >= 1 + assert len(val_dataloader) >= 1 + print(f"Size of train dataloader: {len(train_dataloader)}") + print(f"Size of val dataloader: {len(val_dataloader)}") + return train_dataloader, val_dataloader diff --git a/model/EasyR1/verl/trainer/main.py b/model/EasyR1/verl/trainer/main.py new file mode 100644 index 0000000000000000000000000000000000000000..b448c20654be7cb4b388018c87ffce0de2e9d8e0 --- /dev/null +++ b/model/EasyR1/verl/trainer/main.py @@ -0,0 +1,135 @@ +# 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. + +import json + +import ray +from omegaconf import OmegaConf + +from ..single_controller.ray import RayWorkerGroup +from ..utils.tokenizer import get_processor, get_tokenizer +from ..workers.fsdp_workers import FSDPWorker +from ..workers.reward import BatchFunctionRewardManager, SequentialFunctionRewardManager +from .config import PPOConfig +from .data_loader import create_dataloader +from .ray_trainer import RayPPOTrainer, ResourcePoolManager, Role + + +# please make sure main_task is not scheduled on head +@ray.remote(num_cpus=1) +class Runner: + """A runner for RL training.""" + + def run(self, config: PPOConfig): + # print config + print(json.dumps(config.to_dict(), indent=2)) + + # instantiate tokenizer + tokenizer = get_tokenizer( + config.worker.actor.model.model_path, + override_chat_template=config.data.override_chat_template, + trust_remote_code=config.worker.actor.model.trust_remote_code, + use_fast=True, + ) + processor = get_processor( + config.worker.actor.model.model_path, + override_chat_template=config.data.override_chat_template, + trust_remote_code=config.worker.actor.model.trust_remote_code, + use_fast=True, + ) + + # define worker classes + ray_worker_group_cls = RayWorkerGroup + role_worker_mapping = { + Role.ActorRolloutRef: ray.remote(FSDPWorker), + Role.Critic: ray.remote(FSDPWorker), + } + global_pool_id = "global_pool" + resource_pool_spec = { + global_pool_id: [config.trainer.n_gpus_per_node] * config.trainer.nnodes, + } + mapping = { + Role.ActorRolloutRef: global_pool_id, + Role.Critic: global_pool_id, + } + resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=mapping) + + if config.worker.reward.reward_type == "sequential": + RewardManager = SequentialFunctionRewardManager + elif config.worker.reward.reward_type == "batch": + RewardManager = BatchFunctionRewardManager + else: + raise NotImplementedError(f"Unknown reward type {config.worker.reward.reward_type}.") + + RemoteRewardManager = ray.remote(RewardManager).options(num_cpus=config.worker.reward.num_cpus) + reward_fn = RemoteRewardManager.remote(config.worker.reward, tokenizer) + val_reward_fn = RemoteRewardManager.remote(config.worker.reward, tokenizer) + + train_dataloader, val_dataloader = create_dataloader(config.data, tokenizer, processor) + + trainer = RayPPOTrainer( + config=config, + tokenizer=tokenizer, + processor=processor, + train_dataloader=train_dataloader, + val_dataloader=val_dataloader, + 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() + + +def main(): + cli_args = OmegaConf.from_cli() + default_config = OmegaConf.structured(PPOConfig()) + + if hasattr(cli_args, "config"): + config_path = cli_args.pop("config", None) + file_config = OmegaConf.load(config_path) + default_config = OmegaConf.merge(default_config, file_config) + + ppo_config = OmegaConf.merge(default_config, cli_args) + ppo_config: PPOConfig = OmegaConf.to_object(ppo_config) + ppo_config.deep_post_init() + + if not ray.is_initialized(): + runtime_env = { + "env_vars": { + "TOKENIZERS_PARALLELISM": "true", + "NCCL_DEBUG": "WARN", + "VLLM_LOGGING_LEVEL": "WARN", + "TORCH_NCCL_AVOID_RECORD_STREAMS": "1", + "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:False", + "CUDA_DEVICE_MAX_CONNECTIONS": "1", + "VLLM_ALLREDUCE_USE_SYMM_MEM": "0", + } + } + # import os + # os.environ["TOKENIZERS_PARALLELISM"] = "true" + ray.init(runtime_env=runtime_env) + + runner = Runner.remote() + ray.get(runner.run.remote(ppo_config)) + + if ppo_config.trainer.ray_timeline is not None: + # use `export RAY_PROFILING=1` to record the ray timeline + ray.timeline(filename=ppo_config.trainer.ray_timeline) + + +if __name__ == "__main__": + main() diff --git a/model/EasyR1/verl/trainer/metrics.py b/model/EasyR1/verl/trainer/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..651a41efdc2bf5f80eb9308ca82b29aa639e769c --- /dev/null +++ b/model/EasyR1/verl/trainer/metrics.py @@ -0,0 +1,123 @@ +# 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. + +from typing import Any + +import numpy as np +import torch + +from ..protocol import DataProto + + +def reduce_metrics(metrics: dict[str, list[Any]]) -> dict[str, Any]: + return {key: np.mean(value) for key, value in metrics.items()} + + +def compute_length_metrics(batch: DataProto) -> dict[str, Any]: + max_response_length = batch.batch["responses"].size(-1) + max_prompt_length = batch.batch["attention_mask"].size(-1) - max_response_length + + prompt_length = batch.batch["attention_mask"][:, :-max_response_length].sum(-1).float() + response_length = batch.batch["attention_mask"][:, -max_response_length:].sum(-1).float() + + return { + # response length + "response_length/mean": torch.mean(response_length).detach().item(), + "response_length/max": torch.max(response_length).detach().item(), + "response_length/min": torch.min(response_length).detach().item(), + "response_length/clip_ratio": torch.eq(response_length, max_response_length).float().mean().detach().item(), + # prompt length + "prompt_length/mean": torch.mean(prompt_length).detach().item(), + "prompt_length/max": torch.max(prompt_length).detach().item(), + "prompt_length/min": torch.min(prompt_length).detach().item(), + "prompt_length/clip_ratio": torch.eq(prompt_length, max_prompt_length).float().mean().detach().item(), + } + + +def compute_data_metrics(batch: DataProto, use_critic: bool = False) -> dict[str, Any]: + sequence_score = batch.batch["token_level_scores"].sum(-1) + sequence_reward = batch.batch["token_level_rewards"].sum(-1) + + advantages = batch.batch["advantages"] + returns = batch.batch["returns"] + + max_response_length = batch.batch["responses"].size(-1) + response_mask = batch.batch["attention_mask"][:, -max_response_length:].bool() + + valid_adv = torch.masked_select(advantages, response_mask) + valid_returns = torch.masked_select(returns, response_mask) + + if use_critic: + values = batch.batch["values"] + valid_values = torch.masked_select(values, response_mask) + return_diff_var = torch.var(valid_returns - valid_values) + return_var = torch.var(valid_returns) + + return { + # score + "critic/score/mean": torch.mean(sequence_score).detach().item(), + "critic/score/max": torch.max(sequence_score).detach().item(), + "critic/score/min": torch.min(sequence_score).detach().item(), + # reward + "critic/rewards/mean": torch.mean(sequence_reward).detach().item(), + "critic/rewards/max": torch.max(sequence_reward).detach().item(), + "critic/rewards/min": torch.min(sequence_reward).detach().item(), + # adv + "critic/advantages/mean": torch.mean(valid_adv).detach().item(), + "critic/advantages/max": torch.max(valid_adv).detach().item(), + "critic/advantages/min": torch.min(valid_adv).detach().item(), + # returns + "critic/returns/mean": torch.mean(valid_returns).detach().item(), + "critic/returns/max": torch.max(valid_returns).detach().item(), + "critic/returns/min": torch.min(valid_returns).detach().item(), + **( + { + # values + "critic/values/mean": torch.mean(valid_values).detach().item(), + "critic/values/max": torch.max(valid_values).detach().item(), + "critic/values/min": torch.min(valid_values).detach().item(), + # vf explained var + "critic/vf_explained_var": (1.0 - return_diff_var / (return_var + 1e-5)).detach().item(), + } + if use_critic + else {} + ), + **compute_length_metrics(batch), + } + + +def compute_timing_metrics(batch: DataProto, timing_raw: dict[str, float]) -> dict[str, Any]: + num_response_tokens = torch.sum(batch.batch["response_mask"]).item() + num_overall_tokens = sum(batch.meta_info["global_token_num"]) + num_tokens_of_section = { + **dict.fromkeys(["gen", "reward"], num_response_tokens), + **dict.fromkeys(["ref", "old", "values", "adv", "update_critic", "update_actor"], num_overall_tokens), + } + return { + **{f"timing_s/{name}": value for name, value in timing_raw.items()}, + **{ + f"timing_per_token_ms/{name}": timing_raw[name] * 1000 / num_tokens_of_section[name] + for name in set(num_tokens_of_section.keys()) & set(timing_raw.keys()) + }, + } + + +def compute_throughout_metrics(batch: DataProto, timing_raw: dict[str, float], num_gpus: int) -> dict[str, Any]: + total_num_tokens = sum(batch.meta_info["global_token_num"]) + time = timing_raw["step"] + return { + "perf/total_num_tokens": total_num_tokens, + "perf/time_per_step": time, + "perf/throughput": total_num_tokens / (time * num_gpus), + } diff --git a/model/EasyR1/verl/trainer/ray_trainer.py b/model/EasyR1/verl/trainer/ray_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..6f41fdd9419d8479f3aaeaffd3e863e8f584ac1a --- /dev/null +++ b/model/EasyR1/verl/trainer/ray_trainer.py @@ -0,0 +1,710 @@ +# 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. +""" +PPO Trainer with Ray-based single controller. +This trainer supports model-agonistic model initialization with huggingface. +""" + +import json +import os +import uuid +from collections import defaultdict +from copy import deepcopy +from dataclasses import dataclass, field +from enum import IntEnum, auto +from typing import Any, Optional, Type + +import numpy as np +import ray +import torch +from ray.experimental.tqdm_ray import tqdm +from torchdata.stateful_dataloader import StatefulDataLoader +from transformers import PreTrainedTokenizer, ProcessorMixin + +from ..protocol import DataProto, pad_dataproto_to_divisor, unpad_dataproto +from ..single_controller.base import Worker +from ..single_controller.ray import RayClassWithInitArgs, RayResourcePool, RayWorkerGroup +from ..single_controller.ray.base import create_colocated_worker_cls +from ..utils import torch_functional as VF +from ..utils.checkpoint import CHECKPOINT_TRACKER, find_latest_ckpt, remove_obsolete_ckpt +from ..utils.logger import Tracker +from ..utils.py_functional import convert_dict_to_str, timer, unflatten_dict +from ..utils.seqlen_balancing import get_seqlen_balanced_partitions, log_seqlen_unbalance +from ..workers.fsdp_workers import FSDPWorker +from ..workers.reward import FunctionRewardManager +from .config import PPOConfig +from .core_algos import ( + AdvantageEstimator, + FixedKLController, + KLController, + compute_advantage_return, + compute_kl, + get_kl_controller, +) +from .metrics import ( + compute_data_metrics, + compute_length_metrics, + compute_throughout_metrics, + compute_timing_metrics, + reduce_metrics, +) + + +class Role(IntEnum): + """ + To create more roles dynamically, you can subclass Role and add new members + """ + + Actor = auto() + Rollout = auto() + ActorRollout = auto() + Critic = auto() + RefPolicy = auto() + RewardModel = auto() + ActorRolloutRef = auto() + + +@dataclass +class ResourcePoolManager: + """ + Define a resource pool specification. Resource pool will be initialized first. + """ + + resource_pool_spec: dict[str, list[int]] + mapping: dict[Role, str] + resource_pool_dict: dict[str, RayResourcePool] = field(default_factory=dict) + + def create_resource_pool(self): + """Create ray resource pools for distributed training.""" + for resource_pool_name, process_on_nodes in self.resource_pool_spec.items(): + # max_colocate_count means the number of WorkerGroups (i.e. processes) in each RayResourcePool + # For FSDP backend, we recommend using max_colocate_count=1 that merge all WorkerGroups into one. + # For Megatron backend, we recommend using max_colocate_count>1 that can utilize different WorkerGroup for different models + resource_pool = RayResourcePool( + process_on_nodes=process_on_nodes, use_gpu=True, max_colocate_count=1, name_prefix=resource_pool_name + ) + self.resource_pool_dict[resource_pool_name] = resource_pool + + self._check_resource_available() + + def get_resource_pool(self, role: Role) -> RayResourcePool: + """Get the resource pool of the worker.""" + return self.resource_pool_dict[self.mapping[role]] + + def get_num_gpus(self) -> int: + """Get the number of gpus in this cluster.""" + return sum([n_gpus for process_on_nodes in self.resource_pool_spec.values() for n_gpus in process_on_nodes]) + + def _check_resource_available(self): + """Check if the resource pool can be satisfied in this ray cluster.""" + gpus_available = ray.available_resources().get("GPU", 0) + gpus_required = self.get_num_gpus() + # if gpus_available < gpus_required: + # raise ValueError(f"Total available GPUs {gpus_available} is less than total desired GPUs {gpus_required}.") + + +def apply_kl_penalty(data: DataProto, kl_ctrl: KLController, kl_penalty="kl"): + """Apply KL penalty to the token-level rewards.""" + token_level_scores = data.batch["token_level_scores"] + batch_size = data.batch.batch_size[0] + response_mask = data.batch["response_mask"] + + # compute kl between ref_policy and current policy + kld = compute_kl(data.batch["old_log_probs"], data.batch["ref_log_probs"], kl_penalty=kl_penalty) + kld = kld * response_mask # (batch_size, response_length) + + data.batch["token_level_rewards"] = token_level_scores - kl_ctrl.kl_coef * kld + + current_kl = torch.mean(VF.masked_mean(kld, mask=response_mask, dim=-1)).item() + metrics = {"actor/kl_penalty": current_kl, "actor/kl_coef": kl_ctrl.kl_coef} + + # According to https://github.com/huggingface/trl/blob/v0.11.0/trl/trainer/ppo_trainer.py#L880 + kl_ctrl.update(current_kl=current_kl, n_steps=batch_size) + return data, metrics + + +def compute_advantage(data: DataProto, adv_estimator: AdvantageEstimator, gamma: float = 1.0, lam: float = 1.0): + """Compute advantage estimates for policy optimization.""" + adv_inputs = { + "token_level_rewards": data.batch["token_level_rewards"], + "response_mask": data.batch["response_mask"], + "index": data.non_tensor_batch["uid"], + "gamma": gamma, + "lam": lam, + "data_type": data.non_tensor_batch["data_type"], + "problem_type": data.non_tensor_batch["problem_type"], + } + + # print(adv_inputs) + + if "values" in data.batch: + adv_inputs["values"] = data.batch["values"] + + if "reward_baselines" in data.batch: + adv_inputs["reward_baselines"] = data.batch["reward_baselines"] + + advantages, returns = compute_advantage_return(adv_estimator, **adv_inputs) + data.batch["advantages"] = advantages + data.batch["returns"] = returns + return data + + +class RayPPOTrainer: + """ + Note that this trainer runs on the driver process on a single CPU/GPU node. + """ + + def __init__( + self, + config: PPOConfig, + tokenizer: PreTrainedTokenizer, + processor: Optional[ProcessorMixin], + train_dataloader: StatefulDataLoader, + val_dataloader: StatefulDataLoader, + role_worker_mapping: dict[Role, Type[Worker]], + resource_pool_manager: ResourcePoolManager, + ray_worker_group_cls: Type[RayWorkerGroup] = RayWorkerGroup, + reward_fn: Optional[FunctionRewardManager] = None, + val_reward_fn: Optional[FunctionRewardManager] = None, + ): + self.tokenizer = tokenizer + self.processor = processor + self.train_dataloader = train_dataloader + self.val_dataloader = val_dataloader + self.config = config + self.reward_fn = reward_fn + self.val_reward_fn = val_reward_fn + + self.val_reward_score = 0.0 + self.best_val_reward_score = -1.0 + self.best_global_step = None + + self.hybrid_engine = config.worker.hybrid_engine + self.role_worker_mapping = role_worker_mapping + self.resource_pool_manager = resource_pool_manager + self.use_reward_model = Role.RewardModel in role_worker_mapping + self.ray_worker_group_cls = ray_worker_group_cls + + # define KL control + if config.algorithm.disable_kl: + self.use_reference_policy = False + self.kl_ctrl = FixedKLController(init_kl_coef=0.0) + print("KL is disabled, no KL metrics will be logged. Please set `kl_coef=0` to log KL metrics.") + else: + self.use_reference_policy = True + self.kl_ctrl = get_kl_controller(config.algorithm) + + if config.algorithm.adv_estimator == AdvantageEstimator.GAE: + self.use_critic = True + else: + self.use_critic = False + + if config.algorithm.adv_estimator not in list(AdvantageEstimator): + raise NotImplementedError(f"Unknown advantage estimator: {config.algorithm.adv_estimator}.") + + if config.data.rollout_batch_size % config.worker.actor.global_batch_size != 0: + raise ValueError("Rollout batch size must be divisible by actor global batch size.") + + if ( + config.data.rollout_batch_size * config.worker.rollout.n + ) % config.worker.actor.micro_batch_size_per_device_for_experience != 0: + raise ValueError( + "Rollout batch size * rollout.n must be divisible by actor micro batch size for experience." + ) + + if self.use_critic: + if config.data.rollout_batch_size % config.worker.critic.global_batch_size != 0: + raise ValueError("Rollout batch size must be divisible by critic global batch size.") + + if ( + config.data.rollout_batch_size * config.worker.rollout.n + ) % config.worker.critic.micro_batch_size_per_device_for_experience != 0: + raise ValueError( + "Rollout batch size * rollout.n must be divisible by critic micro batch size for experience." + ) + + if ( + config.algorithm.adv_estimator in (AdvantageEstimator.GRPO, AdvantageEstimator.RLOO) + and config.worker.rollout.n == 1 + ): + raise ValueError("GRPO and RLOO algorithm need `config.worker.rollout.n > 1`.") + + if config.trainer.max_steps is not None: + self.training_steps = config.trainer.max_steps + elif config.data.mini_rollout_batch_size is not None: + num_examples = len(train_dataloader) * config.data.mini_rollout_batch_size + self.training_steps = num_examples // config.data.rollout_batch_size * config.trainer.total_epochs + else: + self.training_steps = len(train_dataloader) * config.trainer.total_epochs + + config.worker.actor.optim.training_steps = self.training_steps + config.worker.critic.optim.training_steps = self.training_steps + print(f"Total training steps: {self.training_steps}") + + def init_workers(self) -> None: + """Init resource pool and worker group""" + self.resource_pool_manager.create_resource_pool() + self.resource_pool_to_cls = {pool: {} for pool in self.resource_pool_manager.resource_pool_dict.values()} + + # create actor, rollout and ref + if self.hybrid_engine: + resource_pool = self.resource_pool_manager.get_resource_pool(Role.ActorRolloutRef) + actor_rollout_ref_cls = RayClassWithInitArgs( + cls=self.role_worker_mapping[Role.ActorRolloutRef], config=self.config.worker, role="actor_rollout_ref" + ) + self.resource_pool_to_cls[resource_pool]["actor_rollout_ref"] = actor_rollout_ref_cls + else: + raise NotImplementedError + + # create critic + if self.use_critic: + resource_pool = self.resource_pool_manager.get_resource_pool(Role.Critic) + critic_cls = RayClassWithInitArgs( + cls=self.role_worker_mapping[Role.Critic], config=self.config.worker, role="critic" + ) + self.resource_pool_to_cls[resource_pool]["critic"] = critic_cls + + # create a reward model if reward_fn is None + if self.use_reward_model: + # we create a RM here + resource_pool = self.resource_pool_manager.get_resource_pool(Role.RewardModel) + rm_cls = RayClassWithInitArgs( + cls=self.role_worker_mapping[Role.RewardModel], config=self.config.worker, role="reward" + ) + self.resource_pool_to_cls[resource_pool]["rm"] = rm_cls + + # initialize WorkerGroup + # NOTE: if you want to use a different resource pool for each role, which can support different parallel size, + # you should not use `create_colocated_worker_cls`. Instead, directly pass different resource pool to different worker groups. + # See https://github.com/volcengine/verl/blob/master/examples/ray/tutorial.ipynb for more information. + all_wg: dict[str, FSDPWorker] = {} + self.wg_dicts = [] + for resource_pool, class_dict in self.resource_pool_to_cls.items(): + worker_dict_cls = create_colocated_worker_cls(class_dict=class_dict) + wg_dict = self.ray_worker_group_cls(resource_pool=resource_pool, ray_cls_with_init=worker_dict_cls) + spawn_wg = wg_dict.spawn(prefix_set=class_dict.keys()) + all_wg.update(spawn_wg) + # keep the referece of WorkerDict to support ray >= 2.31. Ref: https://github.com/ray-project/ray/pull/45699 + self.wg_dicts.append(wg_dict) + + if self.use_critic: + self.critic_wg = all_wg["critic"] + self.critic_wg.init_model() + + if self.use_reward_model: + self.rm_wg = all_wg["rm"] + self.rm_wg.init_model() + + # we should create rollout at the end so that vllm can have a better estimation of kv cache memory + self.actor_rollout_ref_wg = all_wg["actor_rollout_ref"] + self.actor_rollout_ref_wg.init_model() + + def _save_checkpoint(self) -> None: + # path: {save_checkpoint_path}/global_step_{global_step}/{actor,critic} + if self.val_reward_score > self.best_val_reward_score: + self.best_val_reward_score = self.val_reward_score + self.best_global_step = self.global_step + + remove_obsolete_ckpt( + self.config.trainer.save_checkpoint_path, + self.global_step, + self.best_global_step, + self.config.trainer.save_limit, + ) + folder_path = os.path.join(self.config.trainer.save_checkpoint_path, f"global_step_{self.global_step}") + actor_path = os.path.join(folder_path, "actor") + self.actor_rollout_ref_wg.save_checkpoint(actor_path, save_model_only=self.config.trainer.save_model_only) + + if self.use_critic: + critic_path = os.path.join(folder_path, "critic") + self.critic_wg.save_checkpoint(critic_path, save_model_only=self.config.trainer.save_model_only) + + dataloader_path = os.path.join(folder_path, "dataloader.pt") + dataloader_state_dict = self.train_dataloader.state_dict() + torch.save(dataloader_state_dict, dataloader_path) + + checkpointer_tracker_info = { + "best_global_step": self.best_global_step, + "best_val_reward_score": round(self.best_val_reward_score, 4), + "last_global_step": self.global_step, + "last_actor_path": os.path.abspath(actor_path), + } + checkpointer_tracker_path = os.path.join(self.config.trainer.save_checkpoint_path, CHECKPOINT_TRACKER) + with open(checkpointer_tracker_path, "w") as f: + json.dump(checkpointer_tracker_info, f, ensure_ascii=False, indent=2) + + def _load_checkpoint(self) -> None: + if self.config.trainer.load_checkpoint_path is not None: + load_checkpoint_path = self.config.trainer.load_checkpoint_path + elif self.config.trainer.find_last_checkpoint: + load_checkpoint_path, tracker_info = find_latest_ckpt(self.config.trainer.save_checkpoint_path) + if tracker_info is not None: + self.best_val_reward_score = tracker_info.get("best_val_reward_score", 0.0) + self.best_global_step = tracker_info.get("best_global_step", 0) + else: + load_checkpoint_path = None + + if load_checkpoint_path is None: + return + + if "global_step_" not in load_checkpoint_path.strip(os.path.sep).split(os.path.sep)[-1]: + raise ValueError("`load_checkpoint_path` should end with `global_step_*`.") + + print(f"Load from checkpoint: {load_checkpoint_path}.") + self.global_step = int(load_checkpoint_path.strip(os.path.sep).split("global_step_")[-1]) + actor_path = os.path.join(load_checkpoint_path, "actor") + self.actor_rollout_ref_wg.load_checkpoint(actor_path) + if self.use_critic: + critic_path = os.path.join(load_checkpoint_path, "critic") + self.critic_wg.load_checkpoint(critic_path) + + dataloader_path = os.path.join(load_checkpoint_path, "dataloader.pt") + if os.path.exists(dataloader_path): + dataloader_state_dict = torch.load(dataloader_path, weights_only=False) + self.train_dataloader.load_state_dict(dataloader_state_dict) + else: + print(f"No dataloader state found at {dataloader_path}, will start from scratch.") + + def _maybe_log_val_generations( + self, inputs: list[str], outputs: list[str], labels: list[str], scores: list[float] + ) -> None: + """Log a table of validation samples""" + if self.config.trainer.val_generations_to_log <= 0: + return + + # Create tuples of (input, output, score) and sort by input text + samples = list(zip(inputs, outputs, labels, scores)) + samples.sort(key=lambda x: x[0]) # Sort by input text + + # Use fixed random seed for deterministic shuffling + rng = np.random.RandomState(42) + rng.shuffle(samples) + + samples = samples[: self.config.trainer.val_generations_to_log] + self.logger.log_generation(samples, self.global_step) + + def _validate(self) -> dict[str, Any]: + reward_tensor_lst = [] + # Lists to collect samples for the table + sample_inputs, sample_outputs, sample_labels, sample_scores = [], [], [], [] + reward_metrics_lst = defaultdict(list) + length_metrics_lst = defaultdict(list) + print("Start validation...") + self.actor_rollout_ref_wg.prepare_rollout_engine() + for batch_dict in self.val_dataloader: + test_batch = DataProto.from_single_dict(batch_dict) + test_gen_batch = test_batch.pop( + batch_keys=["input_ids", "attention_mask", "position_ids"], + non_tensor_batch_keys=["raw_prompt_ids", "multi_modal_data"], + ) + repeat_times = self.config.worker.rollout.val_override_config.get("n", 1) + test_gen_batch.meta_info = self.config.worker.rollout.val_override_config + test_gen_batch.meta_info["min_pixels"] = self.config.data.min_pixels + test_gen_batch.meta_info["max_pixels"] = self.config.data.max_pixels + test_gen_batch.meta_info["resize_size"] = self.config.data.resize_size + test_gen_batch.meta_info["video_fps"] = self.config.data.video_fps + + test_gen_batch, pad_size = pad_dataproto_to_divisor(test_gen_batch, self.actor_rollout_ref_wg.world_size) + test_output_gen_batch = self.actor_rollout_ref_wg.generate_sequences(test_gen_batch) + test_output_gen_batch = unpad_dataproto(test_output_gen_batch, pad_size=pad_size * repeat_times) + + # repeat to align with repeated responses in rollout + test_batch = test_batch.repeat(repeat_times=repeat_times, interleave=True) + test_batch = test_batch.union(test_output_gen_batch) + + # evaluate using reward_function + reward_tensor, reward_metrics = ray.get(self.val_reward_fn.compute_reward.remote(test_batch)) + + # store generations + input_ids = test_batch.batch["prompts"] + input_texts = [self.tokenizer.decode(ids, skip_special_tokens=True) for ids in input_ids] + output_ids = test_batch.batch["responses"] + output_texts = [self.tokenizer.decode(ids, skip_special_tokens=True) for ids in output_ids] + scores = reward_tensor.sum(-1).cpu().tolist() + sample_inputs.extend(input_texts) + sample_outputs.extend(output_texts) + sample_labels.extend(test_batch.non_tensor_batch["ground_truth"].tolist()) + sample_scores.extend(scores) + + reward_tensor_lst.append(reward_tensor) + for key, value in reward_metrics.items(): + reward_metrics_lst[key].extend(value) + + for key, value in compute_length_metrics(test_batch).items(): + length_metrics_lst[key].append(value) + + self.actor_rollout_ref_wg.release_rollout_engine() + self._maybe_log_val_generations(sample_inputs, sample_outputs, sample_labels, sample_scores) + self.val_reward_score = torch.cat(reward_tensor_lst, dim=0).sum(-1).mean().item() + val_reward_metrics = {f"val/{key}_reward": value for key, value in reduce_metrics(reward_metrics_lst).items()} + val_length_metrics = {f"val_{key}": value for key, value in reduce_metrics(length_metrics_lst).items()} + print("Finish validation.") + return {"val/reward_score": self.val_reward_score, **val_reward_metrics, **val_length_metrics} + + def _balance_batch(self, batch: DataProto, metrics: dict[str, Any], logging_prefix: str = "global_seqlen") -> None: + """Reorder the data on single controller such that each dp rank gets similar total tokens""" + attention_mask = batch.batch["attention_mask"] + batch_size = attention_mask.shape[0] + global_seqlen_lst = batch.batch["attention_mask"].view(batch_size, -1).sum(-1).tolist() # (train_batch_size,) + world_size = self.actor_rollout_ref_wg.world_size + global_partition_lst = get_seqlen_balanced_partitions( + global_seqlen_lst, k_partitions=world_size, equal_size=True + ) + # reorder based on index. The data will be automatically equally partitioned by dispatch function + global_idx = torch.tensor([j for partition in global_partition_lst for j in partition]) + batch.reorder(global_idx) + global_balance_stats = log_seqlen_unbalance( + seqlen_list=global_seqlen_lst, partitions=global_partition_lst, prefix=logging_prefix + ) + metrics.update(global_balance_stats) + + def _make_batch_data(self, metrics: dict[str, Any]) -> DataProto: + batch = None + all_metrics = defaultdict(list) + num_try_make_batch = 0 + print("Start generating batch...") + while True: + num_try_make_batch += 1 + try: + batch_dict = next(self.data_iterator) + except StopIteration: + self.data_iterator = iter(self.train_dataloader) + batch_dict = next(self.data_iterator) + + meta_info = { + "min_pixels": self.config.data.min_pixels, + "max_pixels": self.config.data.max_pixels, + "resize_size": self.config.data.resize_size, + "video_fps": self.config.data.video_fps, + } + new_batch: DataProto = DataProto.from_single_dict(batch_dict, meta_info=meta_info) + new_batch.non_tensor_batch["uid"] = np.array( + [str(uuid.uuid4()) for _ in range(len(new_batch.batch))], dtype=object + ) + + # pop those keys for generation + gen_batch = new_batch.pop( + batch_keys=["input_ids", "attention_mask", "position_ids"], + non_tensor_batch_keys=["raw_prompt_ids", "multi_modal_data"], + meta_info_keys=["min_pixels", "max_pixels", "resize_size", "video_fps"], + ) + + # generate a batch + gen_batch_output = self.actor_rollout_ref_wg.generate_sequences(gen_batch) + + if self.config.algorithm.adv_estimator == "remax": + gen_baseline_batch = deepcopy(gen_batch) + gen_baseline_batch.meta_info["temperature"] = 0 + gen_baseline_batch.meta_info["n"] = 1 + gen_baseline_output = self.actor_rollout_ref_wg.generate_sequences(gen_baseline_batch) + + new_batch = new_batch.union(gen_baseline_output) + reward_baseline_tensor, _ = ray.get(self.reward_fn.compute_reward.remote(new_batch)) + reward_baseline_tensor = reward_baseline_tensor.sum(dim=-1) + + new_batch.pop(batch_keys=list(gen_baseline_output.batch.keys())) + new_batch.batch["reward_baselines"] = reward_baseline_tensor + del gen_baseline_batch, gen_baseline_output + + # repeat to align with repeated responses in rollout + new_batch = new_batch.repeat(repeat_times=self.config.worker.rollout.n, interleave=True) + new_batch = new_batch.union(gen_batch_output) + + # filter group + if self.config.algorithm.online_filtering: + reward_tensor, reward_metrics = ray.get(self.reward_fn.compute_reward.remote(new_batch)) + new_batch.batch["token_level_scores"] = reward_tensor + for k, v in reward_metrics.items(): + all_metrics[k].extend(v) + + filter_scores = reward_metrics[self.config.algorithm.filter_key] + uids = new_batch.non_tensor_batch["uid"] + uid2scores = defaultdict(list) + for uid, score in zip(uids, filter_scores): + uid2scores[uid].append(score) + + uid2mean = {uid: np.mean(scores) for uid, scores in uid2scores.items()} + kept_uids = [ + uid + for uid, avg_score in uid2mean.items() + if avg_score > self.config.algorithm.filter_low and avg_score < self.config.algorithm.filter_high + ] + kept_sample_idxs = [idx for idx, uid in enumerate(uids) if uid in kept_uids] + if len(kept_sample_idxs) == 0: + raise RuntimeError("No sample is kept after filtering. Please check your data.") + + new_batch = new_batch[kept_sample_idxs] + + batch = DataProto.concat([batch, new_batch]) if batch is not None else new_batch + current_batch_size = len(batch) // self.config.worker.rollout.n + rollout_batch_size = self.config.data.rollout_batch_size + if current_batch_size < rollout_batch_size: + print(f"{current_batch_size=} < {rollout_batch_size=}") + max_try_make_batch = self.config.trainer.max_try_make_batch + if max_try_make_batch <= 0 or num_try_make_batch < max_try_make_batch: + print(f"{num_try_make_batch=}. Continue generating...") + else: + raise RuntimeError( + f"{num_try_make_batch=} >= {max_try_make_batch=}. Generated too many. Please check your data." + ) + else: + print(f"{current_batch_size=} >= {rollout_batch_size=}. Finish generating.") + if self.config.algorithm.online_filtering: + metrics.update({f"reward/{k}": v for k, v in reduce_metrics(all_metrics).items()}) + + return batch[: self.config.data.rollout_batch_size * self.config.worker.rollout.n] + + 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. + """ + self.logger = Tracker(loggers=self.config.trainer.logger, config=self.config.to_dict()) + self.global_step = 0 + main_tqdm = tqdm(range(self.training_steps), desc="Running step", position=0) + val_metrics: Optional[dict[str, Any]] = None + + # load checkpoint before doing anything + self._load_checkpoint() + main_tqdm.update(self.global_step) + + # 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.val_before_train: + val_metrics = self._validate() + self.logger.log(data=val_metrics, step=self.global_step) + if self.config.trainer.val_only: + return + + self.data_iterator = iter(self.train_dataloader) + while self.global_step < self.training_steps: + self.global_step += 1 + + metrics, timing_raw = {}, {} + with timer("step", timing_raw): + # make a batch of data + with timer("gen", timing_raw): + self.actor_rollout_ref_wg.prepare_rollout_engine() + batch = self._make_batch_data(metrics=metrics) + self.actor_rollout_ref_wg.release_rollout_engine() + + # balance the number of valid tokens on each dp rank. + # NOTE: 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() + + # compute reward + if "token_level_scores" not in batch.batch: + with timer("reward", timing_raw): + reward_ref = self.reward_fn.compute_reward.remote(batch) + + # recompute old_log_probs + with timer("old", timing_raw): + old_log_probs = self.actor_rollout_ref_wg.compute_log_probs(batch) + batch = batch.union(old_log_probs) + + # compute ref_log_probs + if self.use_reference_policy: + with timer("ref", timing_raw): + ref_log_probs = self.actor_rollout_ref_wg.compute_ref_log_probs(batch) + batch = batch.union(ref_log_probs) + + # 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): + if "token_level_scores" not in batch.batch: + # get token level scores asynchronously + reward_tensor, reward_metrics = ray.get(reward_ref) + batch.batch["token_level_scores"] = reward_tensor + reward_metrics = {f"reward/{k}": v for k, v in reduce_metrics(reward_metrics).items()} + metrics.update(reward_metrics) + + # apply kl penalty if available + if not self.config.algorithm.use_kl_loss and self.use_reference_policy: + # apply kl penalty to reward + batch, kl_metrics = apply_kl_penalty(batch, self.kl_ctrl, 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, + ) + + # update critic + if self.use_critic: + with timer("update_critic", timing_raw): + critic_output = self.critic_wg.update_critic(batch) + + critic_metrics = reduce_metrics(critic_output.non_tensor_batch) + metrics.update(critic_metrics) + + # update actor + if self.config.trainer.critic_warmup <= self.global_step: + with timer("update_actor", timing_raw): + actor_output = self.actor_rollout_ref_wg.update_actor(batch) + + actor_metrics = reduce_metrics(actor_output.non_tensor_batch) + metrics.update(actor_metrics) + + # validate + if ( + self.val_reward_fn is not None + and self.config.trainer.val_freq > 0 + and self.global_step % self.config.trainer.val_freq == 0 + ): + with timer("validation", timing_raw): + val_metrics = self._validate() + + metrics.update(val_metrics) + + if self.config.trainer.save_freq > 0 and self.global_step % self.config.trainer.save_freq == 0: + with timer("save_checkpoint", timing_raw): + self._save_checkpoint() + + # collect metrics + num_gpus = self.resource_pool_manager.get_num_gpus() + metrics.update(compute_data_metrics(batch=batch, use_critic=self.use_critic)) + metrics.update(compute_timing_metrics(batch=batch, timing_raw=timing_raw)) + metrics.update(compute_throughout_metrics(batch=batch, timing_raw=timing_raw, num_gpus=num_gpus)) + + self.logger.log(data=metrics, step=self.global_step) + main_tqdm.update() + + # perform validation after training + if self.val_reward_fn is not None: + if ( + val_metrics is None + or self.config.trainer.val_freq <= 0 + or self.global_step % self.config.trainer.val_freq != 0 + ): + val_metrics = self._validate() + self.logger.log(data=val_metrics, step=self.global_step) + + print(f"Final validation metrics:\n{convert_dict_to_str(unflatten_dict(val_metrics))}") + + if self.config.trainer.save_freq <= 0 or self.global_step % self.config.trainer.save_freq != 0: + self._save_checkpoint() diff --git a/model/EasyR1/verl/utils/__init__.py b/model/EasyR1/verl/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ce90c5eb352d85c59105c0dc85b5f1dd576f095 --- /dev/null +++ b/model/EasyR1/verl/utils/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/model/EasyR1/verl/utils/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5792a5b537152baac33feb530771711f50c18e5 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/dataset.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/dataset.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ffcc99b999e0d4b25a68ddb24378e8b0774ff48 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/dataset.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/flops_counter.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/flops_counter.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6457bd8b57459a8555ba536d4cc60abc42a8ae9f Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/flops_counter.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/fsdp_utils.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/fsdp_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65dbec485e41dabe4b3bbafafb046a73b40c225e Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/fsdp_utils.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/model_utils.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/model_utils.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e234357d37f5dbb214712c3b50d14aa5ce005475 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/model_utils.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/py_functional.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/py_functional.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e15b8df721899457612a0e6e66d297d49355fbb8 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/py_functional.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/seqlen_balancing.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/seqlen_balancing.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6da78396764c891f04d31c6dd7137bae7f331da Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/seqlen_balancing.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/tokenizer.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/tokenizer.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7816e8bf585ac47fbc91946e24083601885e321 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/tokenizer.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/torch_dtypes.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/torch_dtypes.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10e65af3b31d122280763041fb1f94ac19ff7bd7 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/torch_dtypes.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/torch_functional.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/torch_functional.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3672837f8119dc1c2b218c9c8cb76369f2ac745 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/torch_functional.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/__pycache__/ulysses.cpython-311.pyc b/model/EasyR1/verl/utils/__pycache__/ulysses.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dd51f25786a84a34f6333393d939bafc85f6566 Binary files /dev/null and b/model/EasyR1/verl/utils/__pycache__/ulysses.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/checkpoint/__init__.py b/model/EasyR1/verl/utils/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee26fbbcbfcc73fc78dad6d4cc647b6edf253714 --- /dev/null +++ b/model/EasyR1/verl/utils/checkpoint/__init__.py @@ -0,0 +1,18 @@ +# 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. + +from .checkpoint_manager import CHECKPOINT_TRACKER, find_latest_ckpt, remove_obsolete_ckpt + + +__all__ = ["CHECKPOINT_TRACKER", "find_latest_ckpt", "remove_obsolete_ckpt"] diff --git a/model/EasyR1/verl/utils/checkpoint/__pycache__/__init__.cpython-311.pyc b/model/EasyR1/verl/utils/checkpoint/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed747b579376cc54b69adfcd5c074f01438716d2 Binary files /dev/null and b/model/EasyR1/verl/utils/checkpoint/__pycache__/__init__.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/checkpoint/__pycache__/checkpoint_manager.cpython-311.pyc b/model/EasyR1/verl/utils/checkpoint/__pycache__/checkpoint_manager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82820a58ab3db8edfb926cd7fcabc41ae8146174 Binary files /dev/null and b/model/EasyR1/verl/utils/checkpoint/__pycache__/checkpoint_manager.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/checkpoint/__pycache__/fsdp_checkpoint_manager.cpython-311.pyc b/model/EasyR1/verl/utils/checkpoint/__pycache__/fsdp_checkpoint_manager.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43c1f7403e2fcb906449fbeb74b5c17647b6f4c2 Binary files /dev/null and b/model/EasyR1/verl/utils/checkpoint/__pycache__/fsdp_checkpoint_manager.cpython-311.pyc differ diff --git a/model/EasyR1/verl/utils/checkpoint/checkpoint_manager.py b/model/EasyR1/verl/utils/checkpoint/checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..32a4ac2c79daa8790248b1529820716c1ef05a99 --- /dev/null +++ b/model/EasyR1/verl/utils/checkpoint/checkpoint_manager.py @@ -0,0 +1,169 @@ +# 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. + +import json +import os +import random +import re +import shutil +import tempfile +from abc import ABC, abstractmethod +from typing import Any, Optional, Union + +import numpy as np +import torch +import torch.distributed as dist +from filelock import FileLock +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from transformers import PreTrainedTokenizer, ProcessorMixin + + +CHECKPOINT_TRACKER = "checkpoint_tracker.json" + + +class BaseCheckpointManager(ABC): + """ + A checkpoint manager that saves and loads + - model + - optimizer + - lr_scheduler + - extra_states + in a SPMD way. + + We save + - sharded model states and optimizer states + - full lr_scheduler states + - huggingface tokenizer and config for ckpt merge + """ + + def __init__( + self, + model: FSDP, + optimizer: torch.optim.Optimizer, + lr_scheduler: torch.optim.lr_scheduler.LRScheduler, + processing_class: Union[PreTrainedTokenizer, ProcessorMixin], + ): + self.model = model + self.optimizer = optimizer + self.lr_scheduler = lr_scheduler + self.processing_class = processing_class + + assert isinstance(self.model, FSDP) + self.rank = dist.get_rank() + self.world_size = dist.get_world_size() + + @abstractmethod + def load_checkpoint(self, *args, **kwargs): + raise NotImplementedError + + @abstractmethod + def save_checkpoint(self, *args, **kwargs): + raise NotImplementedError + + @staticmethod + def local_mkdir(path: str) -> str: + if not os.path.isabs(path): + working_dir = os.getcwd() + path = os.path.join(working_dir, path) + + # Using hash value of path as lock file name to avoid long file name + lock_filename = f"ckpt_{hash(path) & 0xFFFFFFFF:08x}.lock" + lock_path = os.path.join(tempfile.gettempdir(), lock_filename) + + try: + with FileLock(lock_path, timeout=60): + os.makedirs(path, exist_ok=True) + except Exception as e: + print(f"Warning: Failed to acquire lock for {path}: {e}") + os.makedirs(path, exist_ok=True) # even if the lock is not acquired, try to create the directory + + return path + + @staticmethod + def get_rng_state() -> dict[str, Any]: + rng_state = { + "cpu": torch.get_rng_state(), + "cuda": torch.cuda.get_rng_state(), + "numpy": np.random.get_state(), + "random": random.getstate(), + } + return rng_state + + @staticmethod + def load_rng_state(rng_state: dict[str, Any]): + torch.set_rng_state(rng_state["cpu"]) + torch.cuda.set_rng_state(rng_state["cuda"]) + np.random.set_state(rng_state["numpy"]) + random.setstate(rng_state["random"]) + + +def get_checkpoint_tracker_filename(root_path: str) -> str: + """ + Tracker file rescords the latest chckpoint during training to restart from. + """ + return os.path.join(root_path, CHECKPOINT_TRACKER) + + +def find_latest_ckpt( + path: str, directory_format: str = "global_step_{}" +) -> tuple[Optional[str], Optional[dict[str, Any]]]: + """ + Find the latest checkpoint in the save path. + """ + tracker_file = get_checkpoint_tracker_filename(path) + if not os.path.exists(tracker_file): + return None, None + + with open(tracker_file, "rb") as f: + checkpointer_tracker_info = json.load(f) + + ckpt_path = os.path.join(path, directory_format.format(checkpointer_tracker_info["last_global_step"])) + if not os.path.exists(ckpt_path): + print(f"Checkpoint does not exist: {ckpt_path}") + return None, None + + print(f"Found latest checkpoint: {ckpt_path}, will resume from it. Turn off `find_last_checkpoint` to disable it.") + return ckpt_path, checkpointer_tracker_info + + +def remove_obsolete_ckpt( + path: str, global_step: int, best_global_step: int, save_limit: int = -1, directory_format: str = "global_step_{}" +): + """ + Remove the obsolete checkpoints that exceed the save limit. + """ + if save_limit <= 0 or not os.path.exists(path): + return + + num_ckpt_to_keep = save_limit - 1 # exclude the current ckpt + pattern = re.escape(directory_format).replace(r"\{\}", r"(\d+)") + ckpt_global_steps = [] + for folder in os.listdir(path): + if match := re.match(pattern, folder): + step = int(match.group(1)) + if step < global_step: + ckpt_global_steps.append(step) + + ckpt_global_steps.sort(reverse=True) + if best_global_step in ckpt_global_steps: # do not remove the best ckpt + ckpt_global_steps.remove(best_global_step) + num_ckpt_to_keep = max(num_ckpt_to_keep - 1, 0) + + for step in ckpt_global_steps[num_ckpt_to_keep:]: + folder_path = os.path.join(path, directory_format.format(step)) + try: + shutil.rmtree(folder_path, ignore_errors=True) + print(f"Removed obsolete checkpoint: {folder_path}") + except Exception as e: + print(f"Failed to remove {folder_path}: {e}") diff --git a/model/EasyR1/verl/utils/checkpoint/fsdp_checkpoint_manager.py b/model/EasyR1/verl/utils/checkpoint/fsdp_checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..c3801dbd22475d797c2d0edacde4b48a4b035e69 --- /dev/null +++ b/model/EasyR1/verl/utils/checkpoint/fsdp_checkpoint_manager.py @@ -0,0 +1,123 @@ +# 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. + +import os +from typing import Optional, Union + +import torch +import torch.distributed as dist +from torch.distributed.checkpoint.state_dict import ( + StateDictOptions, + get_model_state_dict, + get_state_dict, + set_state_dict, +) +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from transformers import PreTrainedModel, PreTrainedTokenizer, ProcessorMixin + +from .checkpoint_manager import BaseCheckpointManager + + +class FSDPCheckpointManager(BaseCheckpointManager): + """ + A checkpoint manager that saves and loads + - model + - optimizer + - lr_scheduler + - extra_states + in a SPMD way. + + We save + - sharded model states and optimizer states + - full lr_scheduler states + - huggingface tokenizer and config for ckpt merge + """ + + def __init__( + self, + model: FSDP, + optimizer: torch.optim.Optimizer, + lr_scheduler: torch.optim.lr_scheduler.LRScheduler, + processing_class: Union[PreTrainedTokenizer, ProcessorMixin], + ): + super().__init__(model, optimizer, lr_scheduler, processing_class) + + def load_checkpoint(self, path: Optional[str] = None): + if path is None: + return + + # every rank download its own checkpoint + model_path = os.path.join(path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt") + optim_path = os.path.join(path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt") + extra_path = os.path.join(path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt") + print(f"[rank-{self.rank}]: Loading model from {os.path.abspath(model_path)}.") + print(f"[rank-{self.rank}]: Loading optimizer from {os.path.abspath(optim_path)}.") + print(f"[rank-{self.rank}]: Loading extra_state from {os.path.abspath(extra_path)}.") + model_state_dict = torch.load(model_path, weights_only=False) + optim_state_dict = torch.load(optim_path, weights_only=False) + extra_state_dict = torch.load(extra_path, weights_only=False) + + state_dict_options = StateDictOptions(cpu_offload=True) + set_state_dict( + model=self.model, + optimizers=self.optimizer, + model_state_dict=model_state_dict, + optim_state_dict=optim_state_dict, + options=state_dict_options, + ) + self.lr_scheduler.load_state_dict(extra_state_dict["lr_scheduler"]) + + # recover random state + if "rng" in extra_state_dict: + self.load_rng_state(extra_state_dict["rng"]) + + def save_checkpoint(self, path: str, save_model_only: bool = False): + path = self.local_mkdir(path) + dist.barrier() + + # every rank will save its own model and optim shard + model_path = os.path.join(path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt") + optim_path = os.path.join(path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt") + extra_path = os.path.join(path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt") + + state_dict_options = StateDictOptions(cpu_offload=True) + if save_model_only: + model_state_dict = get_model_state_dict(self.model, options=state_dict_options) + print(f"[rank-{self.rank}]: Saving model to {os.path.abspath(model_path)}.") + torch.save(model_state_dict, model_path) + else: + model_state_dict, optim_state_dict = get_state_dict(self.model, self.optimizer, options=state_dict_options) + extra_state_dict = { + "lr_scheduler": self.lr_scheduler.state_dict(), + "rng": self.get_rng_state(), + } + print(f"[rank-{self.rank}]: Saving model to {os.path.abspath(model_path)}.") + print(f"[rank-{self.rank}]: Saving optimizer to {os.path.abspath(optim_path)}.") + print(f"[rank-{self.rank}]: Saving extra_state to {os.path.abspath(extra_path)}.") + torch.save(model_state_dict, model_path) + torch.save(optim_state_dict, optim_path) + torch.save(extra_state_dict, extra_path) + + # wait for everyone to dump to local + dist.barrier() + + if self.rank == 0: + hf_path = os.path.join(path, "huggingface") + os.makedirs(hf_path, exist_ok=True) + assert isinstance(self.model._fsdp_wrapped_module, PreTrainedModel) + self.model._fsdp_wrapped_module.config.save_pretrained(hf_path) + self.model._fsdp_wrapped_module.generation_config.save_pretrained(hf_path) + self.processing_class.save_pretrained(hf_path) + + dist.barrier() diff --git a/model/EasyR1/verl/utils/dataset.py b/model/EasyR1/verl/utils/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..c6de1b8df8381857e6669b6fddd6ce3ff5af5310 --- /dev/null +++ b/model/EasyR1/verl/utils/dataset.py @@ -0,0 +1,561 @@ +# + +# 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. + +import math +import os +from collections import defaultdict +from io import BytesIO +from typing import Any, Optional, Union + +import numpy as np +import torch +from datasets import load_dataset +from jinja2 import Template +from PIL import Image +from PIL.Image import Image as ImageObject +from qwen_vl_utils.vision_process import fetch_video +from torch.utils.data import Dataset +from transformers import PreTrainedTokenizer, ProcessorMixin + +from . import torch_functional as VF + + + +QUESTION_TEMPLATE = ( + "{Question}\n" + "Please answer this question based on the visual content." + "Provide your thinking process between the and tags, and then give your final answer between the and tags." + "At the end, you must output the final answer in the format:\n" + "\n" +) + +TYPE_TEMPLATE = { + "surgical tissue segmentation": ( + "Please provide only segmentation result in JSON format " + "within the ... tags.\n" + "Example:\n{\"boxes\": [x1, y1, x2, y2], \"positive_points\": [[x,y],[x,y],[x,y]], \"negative_points\": [[x,y],[x,y],[x,y]]}" + ), + "surgical instrument segmentation": ( + "Please provide only segmentation result in JSON format " + "within the ... tags.\n" + "Example:\n{\"boxes\": [x1, y1, x2, y2], \"positive_points\": [[x,y],[x,y],[x,y]], \"negative_points\": [[x,y],[x,y],[x,y]]}" + ), + "surgical tissue localization": ( + "Please provide only localization result " + "within the ... tags.\n" + "Example:\n[0, 38, 299, 132]" + ), + "surgical instrument localization": ( + "Please provide only localization result " + "within the ... tags.\n" + "Example:\n[0, 38, 299, 132]" + ), + # "surgical instrument count": (), + "surgical instrument count": ( + "Please provide only the count of surgical instruments " + "within the ... tags.\n" + "Example:\n3" + ), + "surgical instrument recognition": ( + "Please provide only the instrument names " + "within the ... tags.\n" + "Example:\nGrasper, Hook, Scissors" + ), + "surgical tissue recognition": ( + "Please provide only the tissue names " + "within the ... tags.\n" + "Example:\nGallbladder" + ), + "surgical triplet recognition": ( + "Please provide only the instrument-action-tissue triplets " + "within the ... tags.\n" + "Example:\nGrasper, Grasp, Gallbladder" + ), + "surgical action recognition": ( + "Please provide only the action names " + "within the ... tags.\n" + "Example:\nGrasp" + ), + "surgical step recognition": ( + "Please provide only the step type " + "within the ... tags.\n" + "Example:\nSellotomy" + ), + "surgical phase recognition": ( + "Please provide only the phase type " + "within the ... tags.\n" + "Example:\nSuturing" + ), + # "surgical motion prediction": ( + # "Please provide only the motion type " + # "within the ... tags.\n" + # "Example:\nUp" + # ), + # "surgical instrument tracking": (), + # "critical view safety": (), + "critical view safety": ( + "Please provide only the Yes or No list " + "within the ... tags.\n" + "Example:\n['No', 'No', 'No']" + ), + # "surgical skill assessment": (), + # "image caption": (), + # "video summary": () +} + +# TYPE_TEMPLATE = { +# "multiple choice": ( +# "Please provide only the single option letter (e.g., A, B, C, D, etc.) " +# "within the ... tags.\n" +# "Example:\nA" +# ), +# "numerical": ( +# "Please provide only the numerical value within the ... tags.\n" +# "Example:\n3.14" +# ), +# "OCR": ( +# "Please provide only the transcribed text within the ... tags.\n" +# "Example:\nHello World" +# ), +# "open-ended": ( +# "Please provide only your text answer within the ... tags.\n" +# "Example:\nThe capital of France is Paris." +# ), +# "regression": ( +# "Please provide only the numerical value within the ... tags.\n" +# "Example:\n42.7" +# ), +# "math": ( +# "Please provide only the final result (a number or LaTeX formula) within the ... tags.\n" +# "Example:\n$$-\\dfrac{3}{2}$$" +# ), +# "temporal grounding": ( +# "Please provide only the time span in seconds as JSON within the ... tags.\n" +# "Example:\n{\"time\": [12.3, 25.7]}" +# ), +# "spatial grounding": ( +# "Please provide only the bounding box as JSON with key 'boxes' within the ... tags.\n" +# "Example:\n{\"boxes\": [35, 227, 437, 932]}" +# ), +# "spatial-temporal grounding": ( +# "Please provide only the time span in seconds and bounding boxes as JSON within the ... tags.\n" +# "You MUST output one bounding box for every integer second within the given time span (inclusive).\n" +# "Example:\n" +# "{\"time\": [8.125, 13.483], \"boxes\": {\"9\": [317, 422, 582, 997], " +# "\"10\": [332, 175, 442, 369], \"11\": [340, 180, 450, 370]}}\n" +# "Note: Each key in 'boxes' must be an integer second within the span, and its value must be a 4-number bounding box [x1, y1, x2, y2]." +# ), +# "tracking": ( +# "Please track the target object throughout the video and provide one bounding box per second, " +# "ONLY up to 32 seconds, within the ... tags.\n" +# "Example:\n" +# "{\"boxes\": {\"1\": [405, 230, 654, 463], \"2\": [435, 223, 678, 446], ..., " +# "\"32\": [415, 203, 691, 487]}}\n" +# "Note: Each key in 'boxes' must correspond to a second (1, 2, 3, ..., 32) and contain a 4-number bounding box [x1, y1, x2, y2]." +# ), +# "segmentation_image": ( +# "This task prepares inputs for image object segmentation with a specialized model (e.g., SAM2).\n" +# "Please provide ONE bounding box, 3 positive points (clearly INSIDE the object), and 3 negative points " +# "(clearly OUTSIDE the object) within the ... tags.\n" +# "Choose informative points that help distinguish object vs. background. Prefer negatives on clear non-object " +# "pixels INSIDE the box when safe; otherwise place them just outside on obvious background. " +# "Negatives must NEVER be on the object or on its boundary.\n" +# "Example:\n" +# "{\"boxes\": [x1, y1, x2, y2], \"positive_points\": [[x,y],[x,y],[x,y]], " +# "\"negative_points\": [[x,y],[x,y],[x,y]]}" +# ), +# "segmentation_video": ( +# "This task prepares inputs for video object segmentation with a specialized model (e.g., SAM2).\n" +# "Please select ONE representative time (in seconds), and provide ONE bounding box, " +# "3 positive points (clearly INSIDE the object), and 3 negative points (clearly OUTSIDE the object) " +# "within the ... tags.\n" +# "Choose informative points that help distinguish object vs. background. Prefer negatives on clear non-object " +# "pixels INSIDE the box when safe; otherwise place them just outside on obvious background. " +# "Negatives must NEVER be on the object or on its boundary.\n" +# "Example:\n" +# "{\"time\": , \"boxes\": [x1, y1, x2, y2], " +# "\"positive_points\": [[x,y],[x,y],[x,y]], \"negative_points\": [[x,y],[x,y],[x,y]]}" +# ) +# } + + +def collate_fn(features: list[dict[str, Any]]) -> dict[str, Any]: + tensors = defaultdict(list) + non_tensors = defaultdict(list) + for feature in features: + for key, value in feature.items(): + if isinstance(value, torch.Tensor): + tensors[key].append(value) + else: + non_tensors[key].append(value) + + for key, value in tensors.items(): + tensors[key] = torch.stack(value, dim=0) + + for key, value in non_tensors.items(): + non_tensors[key] = np.array(value, dtype=object) + + return {**tensors, **non_tensors} + + +def process_image( + image: Union[dict[str, Any], ImageObject, str], + min_pixels: Optional[int], + max_pixels: Optional[int], + resize_size: int = 0 +) -> ImageObject: + """ + Process image with optional resize by shorter side and pixel range constraints. + + Args: + image: Input image (path, dict with bytes, or PIL Image) + min_pixels: Minimum pixel count for image + max_pixels: Maximum pixel count for image + resize_size: Resize shorter side to this size. 0 means disabled. + + Returns: + Processed PIL Image in RGB mode + """ + if isinstance(image, str): + image = Image.open(image) + elif isinstance(image, dict): + image = Image.open(BytesIO(image["bytes"])) + elif isinstance(image, bytes): + image = Image.open(BytesIO(image)) + + image.load() + + if resize_size > 0: + w, h = image.width, image.height + if w < h: + new_w = resize_size + new_h = int(h * resize_size / w) + else: + new_h = resize_size + new_w = int(w * resize_size / h) + image = image.resize((new_w, new_h), Image.LANCZOS) + else: + if max_pixels is not None and (image.width * image.height) > max_pixels: + resize_factor = math.sqrt(max_pixels / (image.width * image.height)) + width, height = int(image.width * resize_factor), int(image.height * resize_factor) + image = image.resize((width, height)) + + if min_pixels is not None and (image.width * image.height) < min_pixels: + resize_factor = math.sqrt(min_pixels / (image.width * image.height)) + width, height = int(image.width * resize_factor), int(image.height * resize_factor) + image = image.resize((width, height)) + + if image.mode != "RGB": + image = image.convert("RGB") + + return image + + +def process_video( + video: str, min_pixels: int = 4*32*32, max_pixels: int = 64*32*32, max_frames: int = 128, video_fps: float = 2, return_fps: bool = False +): + vision_info = {"video": video, "min_pixels": min_pixels, "max_pixels": max_pixels, "max_frames": max_frames, "fps": video_fps} + return fetch_video(vision_info, image_patch_size=16, return_video_sample_fps=return_fps, return_video_metadata=return_fps) + + +class RLHFDataset(Dataset): + """ + We assume the dataset contains a column that contains prompts and other information + """ + + def __init__( + self, + data_path: str, + tokenizer: PreTrainedTokenizer, + processor: Optional[ProcessorMixin], + prompt_key: str = "prompt", + answer_key: str = "answer", + image_key: str = "images", + video_key: str = "videos", + image_dir: Optional[str] = None, + video_fps: float = 2.0, + max_prompt_length: int = 1024, + truncation: str = "error", + format_prompt: Optional[str] = None, + min_pixels: Optional[int] = None, + max_pixels: Optional[int] = None, + resize_size: int = 0, + filter_overlong_prompts: bool = True, + filter_overlong_prompts_workers: int = 16, + ): + self.tokenizer = tokenizer + self.processor = processor + self.prompt_key = prompt_key + self.answer_key = answer_key + self.image_key = image_key + self.video_key = video_key + self.image_dir = image_dir + self.video_fps = video_fps + self.max_prompt_length = max_prompt_length + self.truncation = truncation + self.min_pixels = min_pixels + self.max_pixels = max_pixels + self.resize_size = resize_size + + if "@" in data_path: + data_path, data_split = data_path.split("@") + else: + data_split = "train" + + if os.path.isdir(data_path): + # when we use dataset builder, we should always refer to the train split + file_type = os.path.splitext(os.listdir(data_path)[0])[-1][1:].replace("jsonl", "json") + self.dataset = load_dataset(file_type, data_dir=data_path, split=data_split) + elif os.path.isfile(data_path): + file_type = os.path.splitext(data_path)[-1][1:].replace("jsonl", "json") + self.dataset = load_dataset(file_type, data_files=data_path, split=data_split) + else: + # load remote dataset from huggingface hub + self.dataset = load_dataset(data_path, split=data_split) + + self.format_prompt = None + if format_prompt: + with open(format_prompt, encoding="utf-8") as f: + self.format_prompt = f.read() + + if filter_overlong_prompts: + self.dataset = self.dataset.filter( + self._filter_overlong_prompts, + desc="Filtering overlong prompts", + num_proc=filter_overlong_prompts_workers, + ) + + + def _build_messages(self, example: dict[str, Any]) -> list[dict[str, Any]]: + prompt_str: str = example[self.prompt_key] + # if self.format_prompt: + # format_prompt = Template(self.format_prompt.strip()) + # prompt_str = format_prompt.render(content=prompt_str) + + data_type = (example.get("data_type") or "").strip().lower() + pt = example.get("problem_type") or "" + question = prompt_str + + # if (pt == "multiple choice") and isinstance(example.get("options"), list) and example["options"]: + # opts = "\n".join(example["options"]) + # question = f"{question}\nOptions:\n{opts}" + + # if pt == "segmentation": + # type_key = "segmentation_video" if data_type == "video" else "segmentation_image" + # else: + type_key = pt + + tail = TYPE_TEMPLATE.get(type_key, "") + prompt_str = QUESTION_TEMPLATE.format(Question=question) + tail + + if self.image_key in example and isinstance(example.get(self.image_key), list) and len(example.get(self.image_key)) > 0: + # https://huggingface.co/docs/transformers/en/tasks/image_text_to_text + content_list = [] + for i, content in enumerate(prompt_str.split("")): + if i != 0: + content_list.append({"type": "image"}) + + if content: + content_list.append({"type": "text", "text": content}) + + # print(content_list) + + return [{"role": "user", "content": content_list}] + elif self.video_key in example and isinstance(example.get(self.video_key), list) and len(example.get(self.video_key)) > 0: + content_list = [] + for i, content in enumerate(prompt_str.split("