SII-ChengqiLi commited on
Commit
7a911be
·
verified ·
1 Parent(s): 53012e1

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. EasyR1/.gitignore +184 -0
  2. EasyR1/.pre-commit-config.yaml +22 -0
  3. EasyR1/Dockerfile +68 -0
  4. EasyR1/Dockerfile.legacy +68 -0
  5. EasyR1/LICENSE +201 -0
  6. EasyR1/Makefile +30 -0
  7. EasyR1/README.md +249 -0
  8. EasyR1/assets/baselines.md +78 -0
  9. EasyR1/examples/android_gui_cookbook/COLLECT_DATA_README.md +18 -0
  10. EasyR1/examples/android_gui_cookbook/PLAY_GAME_README.md +38 -0
  11. EasyR1/examples/android_gui_cookbook/README.md +224 -0
  12. EasyR1/examples/android_gui_cookbook/adb_controller.py +143 -0
  13. EasyR1/examples/android_gui_cookbook/collect_data.py +489 -0
  14. EasyR1/examples/android_gui_cookbook/game_docker/.dockerignore +9 -0
  15. EasyR1/examples/android_gui_cookbook/game_docker/DOCKER_README.md +170 -0
  16. EasyR1/examples/android_gui_cookbook/game_docker/Dockerfile +15 -0
  17. EasyR1/examples/android_gui_cookbook/game_docker/game-deployment.yaml +33 -0
  18. EasyR1/examples/android_gui_cookbook/game_docker/game-service.yaml +24 -0
  19. EasyR1/examples/android_gui_cookbook/game_docker/number_game.html +603 -0
  20. EasyR1/examples/android_gui_cookbook/vlm_client.py +107 -0
  21. EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh +18 -0
  22. EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh +18 -0
  23. EasyR1/examples/format_prompt/dapo.jinja +1 -0
  24. EasyR1/examples/format_prompt/math.jinja +1 -0
  25. EasyR1/examples/format_prompt/r1v.jinja +1 -0
  26. EasyR1/examples/reward_function/android_gui.py +117 -0
  27. EasyR1/examples/reward_function/dapo.py +165 -0
  28. EasyR1/examples/reward_function/file_queue_judge_worker.py +227 -0
  29. EasyR1/examples/reward_function/math.py +51 -0
  30. EasyR1/examples/reward_function/paper_conclusion_file_queue_judge.py +201 -0
  31. EasyR1/examples/reward_function/paper_conclusion_judge_common.py +482 -0
  32. EasyR1/examples/reward_function/paper_conclusion_list_judge.py +44 -0
  33. EasyR1/examples/reward_function/r1v.py +52 -0
  34. EasyR1/pyproject.toml +39 -0
  35. EasyR1/requirements.txt +20 -0
  36. EasyR1/setup.py +61 -0
  37. EasyR1/tests/check_license.py +39 -0
  38. EasyR1/tests/test_checkpoint.py +50 -0
  39. EasyR1/tests/test_dataproto.py +183 -0
  40. EasyR1/tests/test_dynamic_batch.py +78 -0
  41. EasyR1/verl/models/transformers/__init__.py +13 -0
  42. EasyR1/verl/models/transformers/qwen2_vl.py +230 -0
  43. EasyR1/verl/models/transformers/qwen3_vl.py +261 -0
  44. EasyR1/verl/single_controller/base/register_center/__init__.py +13 -0
  45. EasyR1/verl/single_controller/base/worker_group.py +194 -0
  46. EasyR1/verl/single_controller/ray/__init__.py +18 -0
  47. EasyR1/verl/single_controller/ray/base.py +493 -0
  48. EasyR1/verl/utils/checkpoint/checkpoint_manager.py +169 -0
  49. EasyR1/verl/utils/checkpoint/fsdp_checkpoint_manager.py +158 -0
  50. EasyR1/verl/workers/sharding_manager/fsdp_vllm.py +227 -0
EasyR1/.gitignore ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ .idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
172
+
173
+ # pytorch
174
+ *.pt
175
+
176
+ # outputs
177
+ outputs/
178
+ checkpoints/
179
+ wandb/
180
+ tensorboard_log/
181
+
182
+ # data
183
+ images/
184
+ images*
EasyR1/.pre-commit-config.yaml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v5.0.0
4
+ hooks:
5
+ - id: check-ast
6
+ - id: check-added-large-files
7
+ args: ['--maxkb=25000']
8
+ - id: check-merge-conflict
9
+ - id: check-yaml
10
+ - id: debug-statements
11
+ - id: end-of-file-fixer
12
+ - id: requirements-txt-fixer
13
+ - id: trailing-whitespace
14
+ args: [--markdown-linebreak-ext=md]
15
+ - id: no-commit-to-branch
16
+ args: ['--branch', 'main']
17
+
18
+ - repo: https://github.com/asottile/pyupgrade
19
+ rev: v3.17.0
20
+ hooks:
21
+ - id: pyupgrade
22
+ args: [--py38-plus]
EasyR1/Dockerfile ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Start from the NVIDIA official image (ubuntu-24.04 + cuda-12.9 + python-3.12)
2
+ # https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-25-05.html
3
+ FROM nvcr.io/nvidia/pytorch:25.05-py3
4
+
5
+ # Define environments
6
+ ENV MAX_JOBS=32
7
+ ENV VLLM_WORKER_MULTIPROC_METHOD=spawn
8
+ ENV DEBIAN_FRONTEND=noninteractive
9
+ ENV NODE_OPTIONS=""
10
+ ENV PIP_ROOT_USER_ACTION=ignore
11
+ ENV HF_HUB_ENABLE_HF_TRANSFER="1"
12
+
13
+ # Define installation arguments
14
+ ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
15
+ ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
16
+
17
+ # Set apt source
18
+ RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
19
+ { \
20
+ echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \
21
+ echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \
22
+ echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \
23
+ echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \
24
+ } > /etc/apt/sources.list
25
+
26
+ # Install systemctl
27
+ RUN apt-get update && \
28
+ apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \
29
+ apt-get clean
30
+
31
+ # Install tini
32
+ RUN apt-get update && \
33
+ apt-get install -y tini && \
34
+ apt-get clean
35
+
36
+ # Change pip source
37
+ RUN pip config set global.index-url "${PIP_INDEX}" && \
38
+ pip config set global.extra-index-url "${PIP_INDEX}" && \
39
+ python -m pip install --upgrade pip
40
+
41
+ # Uninstall nv-pytorch fork
42
+ RUN pip uninstall -y torch torchvision torchaudio \
43
+ pytorch-quantization pytorch-triton torch-tensorrt \
44
+ transformer-engine flash-attn apex megatron-core \
45
+ xgboost opencv grpcio
46
+
47
+ # Remove nv file
48
+ RUN rm -rf /workspace
49
+
50
+ # Fix cv2
51
+ RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2
52
+
53
+ # Install torch-2.8.0+cu128 + vllm-0.11.0
54
+ RUN pip install --no-cache-dir "vllm==0.11.0" "torch==2.8.0" "torchvision==0.23.0" "torchaudio==2.8.0" tensordict torchdata \
55
+ "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \
56
+ "numpy<2.0.0" "pyarrow>=15.0.0" "grpcio>=1.62.1" "optree>=0.13.0" pandas \
57
+ ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb liger-kernel mathruler \
58
+ pytest yapf py-spy pre-commit ruff
59
+
60
+ # Install flash-attn-2.8.3
61
+ RUN ABI_FLAG=$(python -c "import torch; print('TRUE' if torch._C._GLIBCXX_USE_CXX11_ABI else 'FALSE')") && \
62
+ 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" && \
63
+ wget -nv -P /opt/tiger "${URL}" && \
64
+ pip install --no-cache-dir "/opt/tiger/$(basename ${URL})"
65
+
66
+ # Reset pip config
67
+ RUN pip config unset global.index-url && \
68
+ pip config unset global.extra-index-url
EasyR1/Dockerfile.legacy ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10)
2
+ # https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html
3
+ FROM nvcr.io/nvidia/pytorch:24.08-py3
4
+
5
+ # Define environments
6
+ ENV MAX_JOBS=32
7
+ ENV VLLM_WORKER_MULTIPROC_METHOD=spawn
8
+ ENV DEBIAN_FRONTEND=noninteractive
9
+ ENV NODE_OPTIONS=""
10
+ ENV PIP_ROOT_USER_ACTION=ignore
11
+ ENV HF_HUB_ENABLE_HF_TRANSFER="1"
12
+
13
+ # Define installation arguments
14
+ ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/
15
+ ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple
16
+
17
+ # Set apt source
18
+ RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \
19
+ { \
20
+ echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \
21
+ echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \
22
+ echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \
23
+ echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \
24
+ } > /etc/apt/sources.list
25
+
26
+ # Install systemctl
27
+ RUN apt-get update && \
28
+ apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \
29
+ apt-get clean
30
+
31
+ # Install tini
32
+ RUN apt-get update && \
33
+ apt-get install -y tini && \
34
+ apt-get clean
35
+
36
+ # Change pip source
37
+ RUN pip config set global.index-url "${PIP_INDEX}" && \
38
+ pip config set global.extra-index-url "${PIP_INDEX}" && \
39
+ python -m pip install --upgrade pip
40
+
41
+ # Uninstall nv-pytorch fork
42
+ RUN pip uninstall -y torch torchvision torchaudio \
43
+ pytorch-quantization pytorch-triton torch-tensorrt \
44
+ transformer-engine flash-attn apex megatron-core \
45
+ xgboost opencv grpcio
46
+
47
+ # Remove nv file
48
+ RUN rm -rf /workspace
49
+
50
+ # Fix cv2
51
+ RUN rm -rf /usr/local/lib/python3.10/dist-packages/cv2
52
+
53
+ # Install torch-2.7.1+cu126 + vllm-0.10.0
54
+ RUN pip install --no-cache-dir "vllm==0.10.0" "torch==2.7.1" "torchvision==0.22.1" "torchaudio==2.7.1" tensordict torchdata \
55
+ "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \
56
+ "numpy<2.0.0" "pyarrow>=15.0.0" "grpcio>=1.62.1" "optree>=0.13.0" pandas \
57
+ ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb liger-kernel mathruler \
58
+ pytest yapf py-spy pyext pre-commit ruff
59
+
60
+ # Install flash-attn-2.8.2
61
+ RUN ABI_FLAG=$(python -c "import torch; print('TRUE' if torch._C._GLIBCXX_USE_CXX11_ABI else 'FALSE')") && \
62
+ 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" && \
63
+ wget -nv -P /opt/tiger "${URL}" && \
64
+ pip install --no-cache-dir "/opt/tiger/$(basename ${URL})"
65
+
66
+ # Reset pip config
67
+ RUN pip config unset global.index-url && \
68
+ pip config unset global.extra-index-url
EasyR1/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
EasyR1/Makefile ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .PHONY: build commit license quality style test
2
+
3
+ check_dirs := examples scripts tests verl setup.py
4
+
5
+ code_dirs := scripts tests verl setup.py
6
+
7
+ RUN := $(shell command -v uv >/dev/null 2>&1 && echo "uv run" || echo "")
8
+ BUILD := $(shell command -v uv >/dev/null 2>&1 && echo "uv build" || echo "python -m build")
9
+ TOOL := $(shell command -v uv >/dev/null 2>&1 && echo "uvx" || echo "")
10
+
11
+ build:
12
+ $(RUN) python3 setup.py sdist bdist_wheel
13
+
14
+ commit:
15
+ $(TOOL) pre-commit install
16
+ $(TOOL) pre-commit run --all-files
17
+
18
+ license:
19
+ $(RUN) python3 tests/check_license.py $(code_dirs)
20
+
21
+ quality:
22
+ $(TOOL) ruff check $(check_dirs)
23
+ $(TOOL) ruff format --check $(check_dirs)
24
+
25
+ style:
26
+ $(TOOL) ruff check $(check_dirs) --fix
27
+ $(TOOL) ruff format $(check_dirs)
28
+
29
+ test:
30
+ $(RUN) pytest -vv tests/
EasyR1/README.md ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework
2
+
3
+ [![GitHub Repo stars](https://img.shields.io/github/stars/hiyouga/EasyR1)](https://github.com/hiyouga/EasyR1/stargazers)
4
+ [![Twitter](https://img.shields.io/twitter/follow/llamafactory_ai)](https://twitter.com/llamafactory_ai)
5
+ [![Docker Pulls](https://img.shields.io/docker/pulls/hiyouga/verl)](https://hub.docker.com/r/hiyouga/verl/tags)
6
+
7
+ ### Used by [Amazon Web Services](https://aws.amazon.com/cn/blogs/china/building-llm-model-hub-based-on-llamafactory-and-easyr1/)
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ ## Features
14
+
15
+ - Supported models
16
+ - Llama3/Qwen2/Qwen2.5/Qwen3 language models
17
+ - Qwen2-VL/Qwen2.5-VL/Qwen3-VL vision language models
18
+ - DeepSeek-R1 distill models
19
+
20
+ - Supported algorithms
21
+ - GRPO
22
+ - DAPO ![new](https://img.shields.io/badge/new-orange)
23
+ - Reinforce++
24
+ - ReMax
25
+ - RLOO
26
+ - GSPO ![new](https://img.shields.io/badge/new-orange)
27
+ - CISPO ![new](https://img.shields.io/badge/new-orange)
28
+
29
+ - Supported datasets
30
+ - Any text, vision-text dataset in a [specific format](#custom-dataset)
31
+
32
+ - Supported tricks
33
+ - Padding-free training
34
+ - LoRA training ![new](https://img.shields.io/badge/new-orange)
35
+ - Resuming from the latest/best checkpoint
36
+ - Wandb & SwanLab & Mlflow & Tensorboard tracking
37
+
38
+ ## Requirements
39
+
40
+ ### Software Requirements
41
+
42
+ - Python 3.9+
43
+ - transformers>=4.54.0
44
+ - flash-attn>=2.4.3
45
+ - vllm>=0.8.3
46
+
47
+ We provide a [Dockerfile](./Dockerfile) to easily build environments.
48
+
49
+ We recommend using the [pre-built docker image](https://hub.docker.com/r/hiyouga/verl) in EasyR1.
50
+
51
+ ```bash
52
+ docker pull hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0
53
+ docker run -it --ipc=host --gpus=all hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0
54
+ ```
55
+
56
+ If your environment does not support Docker, you can consider using **Apptainer**:
57
+
58
+ ```bash
59
+ apptainer pull easyr1.sif docker://hiyouga/verl:ngc-th2.8.0-cu12.9-vllm0.11.0
60
+ apptainer shell --nv --cleanenv --bind /mnt/your_dir:/mnt/your_dir easyr1.sif
61
+ ```
62
+
63
+ Use `USE_MODELSCOPE_HUB=1` to download models from the ModelScope hub.
64
+
65
+ ### Hardware Requirements
66
+
67
+ \* *estimated*
68
+
69
+ | Method | Bits | 1.5B | 3B | 7B | 32B | 72B |
70
+ | ------------------------ | ---- | ------ | ------ | ------ | ------- | ------- |
71
+ | GRPO Full Fine-Tuning | AMP | 2*24GB | 4*40GB | 8*40GB | 16*80GB | 32*80GB |
72
+ | GRPO Full Fine-Tuning | BF16 | 1*24GB | 1*40GB | 4*40GB | 8*80GB | 16*80GB |
73
+ | GRPO LoRA Fine-Tuning | AMP | 1*12GB | 1*24GB | 2*32GB | 2*80GB | 4*80GB |
74
+
75
+ > [!NOTE]
76
+ > Use `worker.actor.fsdp.torch_dtype=bf16` and `worker.actor.optim.strategy=adamw_bf16` to enable bf16 training.
77
+
78
+ ## Tutorial: Run Qwen2.5-VL GRPO on [Geometry3K](https://huggingface.co/datasets/hiyouga/geometry3k) Dataset in Just 3 Steps
79
+
80
+ ![image](assets/qwen2_5_vl_7b_geo.png)
81
+
82
+ ### Installation
83
+
84
+ ```bash
85
+ git clone https://github.com/hiyouga/EasyR1.git
86
+ cd EasyR1
87
+ pip install -e .
88
+ ```
89
+
90
+ ### GRPO Full Training
91
+
92
+ ```bash
93
+ bash examples/qwen2_5_vl_7b_geo3k_grpo.sh
94
+ ```
95
+
96
+ ### GRPO LoRA Training
97
+
98
+ ```bash
99
+ bash examples/qwen3_vl_4b_geo3k_grpo_lora.sh
100
+ ```
101
+
102
+ ### Merge Checkpoint in Hugging Face Format
103
+
104
+ ```bash
105
+ python3 scripts/model_merger.py --local_dir checkpoints/easy_r1/exp_name/global_step_1/actor
106
+ ```
107
+
108
+ > [!TIP]
109
+ > If you encounter issues with connecting to Hugging Face, consider using `export HF_ENDPOINT=https://hf-mirror.com`.
110
+ >
111
+ > If you want to use SwanLab logger, consider using `bash examples/qwen2_5_vl_7b_geo3k_swanlab.sh`.
112
+
113
+ ## Custom Dataset
114
+
115
+ Please refer to the example datasets to prepare your own dataset.
116
+
117
+ - Text dataset: https://huggingface.co/datasets/hiyouga/math12k
118
+ - Image-text dataset: https://huggingface.co/datasets/hiyouga/geometry3k
119
+ - Multi-image-text dataset: https://huggingface.co/datasets/hiyouga/journeybench-multi-image-vqa
120
+ - Text-image mixed dataset: https://huggingface.co/datasets/hiyouga/rl-mixed-dataset
121
+
122
+ ## How to Understand GRPO in EasyR1
123
+
124
+ ![image](assets/easyr1_grpo.png)
125
+
126
+ - 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).
127
+
128
+ ## How to Run 70B+ Model in Multi-node Environment
129
+
130
+ 1. Start the Ray head node.
131
+
132
+ ```bash
133
+ ray start --head --port=6379 --dashboard-host=0.0.0.0
134
+ ```
135
+
136
+ 2. Start the Ray worker node and connect to the head node.
137
+
138
+ ```bash
139
+ ray start --address=<head_node_ip>:6379
140
+ ```
141
+
142
+ 3. Check the Ray resource pool.
143
+
144
+ ```bash
145
+ ray status
146
+ ```
147
+
148
+ 4. Run training script on the Ray head node only.
149
+
150
+ ```bash
151
+ bash examples/qwen2_5_vl_7b_geo3k_grpo.sh
152
+ ```
153
+
154
+ 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.
155
+
156
+ ## Other Baselines
157
+
158
+ We also reproduced the following two baselines of the [R1-V](https://github.com/deep-agent/R1-V) project.
159
+ - [CLEVR-70k-Counting](examples/baselines/qwen2_5_vl_3b_clevr.sh): Train the Qwen2.5-VL-3B-Instruct model on counting problem.
160
+ - [GeoQA-8k](examples/baselines/qwen2_5_vl_3b_geoqa8k.sh): Train the Qwen2.5-VL-3B-Instruct model on GeoQA problem.
161
+
162
+ ## Performance Baselines
163
+
164
+ See [baselines.md](assets/baselines.md).
165
+
166
+ ## Awesome Work using EasyR1
167
+
168
+ - **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)
169
+ - **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)
170
+ - **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)
171
+ - **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)
172
+ - **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) [![[arxiv]](https://img.shields.io/badge/arxiv-2506.01908-blue)](https://arxiv.org/abs/2506.01908)
173
+ - **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)
174
+ - **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)
175
+ - **FAST-GRPO**: Fast-Slow Thinking framework that dynamically adapts reasoning depth based on question characteristics. [![[code]](https://img.shields.io/github/stars/Mr-Loevan/FAST)](https://github.com/Mr-Loevan/FAST) [![[arxiv]](https://img.shields.io/badge/arxiv-2504.18458-blue)](https://arxiv.org/abs/2504.18458)
176
+ - **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)
177
+ - **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)
178
+ - **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)
179
+ - **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)
180
+ - **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)
181
+ - **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)
182
+ - **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)
183
+ - **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)
184
+ - **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)
185
+ - **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)
186
+ - **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)
187
+ - **ARES**: Multimodal Adaptive Reasoning via Difficulty-Aware Token-Level Entropy Shaping. [![[code]](https://img.shields.io/github/stars/shawn0728/ARES)](https://github.com/shawn0728/ARES) [![[arxiv]](https://img.shields.io/badge/arxiv-2510.08457-blue)](https://arxiv.org/abs/2510.08457)
188
+ - **VPPO**: Spotlight on Token Perception for Multimodal Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/huaixuheqing/VPPO-RL)](https://github.com/huaixuheqing/VPPO-RL) [![[arxiv]](https://img.shields.io/badge/arxiv-2510.09285-blue)](https://arxiv.org/abs/2510.09285)
189
+ - **IE-Critic-R1**: Advancing the Explanatory Measurement of Text-Driven Image Editing for Human Perception Alignment. [![[code]](https://img.shields.io/github/stars/Coobiw/IE-Critic-R1)](https://github.com/Coobiw/IE-Critic-R1) [![[arxiv]](https://img.shields.io/badge/arxiv-2511.18055-blue)](https://arxiv.org/abs/2511.18055)
190
+ - **OneThinker**: All-in-one Reasoning Model for Image and Video. [![[code]](https://img.shields.io/github/stars/tulerfeng/OneThinker)](https://github.com/tulerfeng/OneThinker) [![[arxiv]](https://img.shields.io/badge/arxiv-2512.03043-blue)](https://arxiv.org/abs/2512.03043)
191
+ - **MetaphorStar**: Image Metaphor Understanding and Reasoning with End-to-End Visual Reinforcement Learning. [![[code]](https://img.shields.io/github/stars/MING-ZCH/MetaphorStar)](https://github.com/MING-ZCH/MetaphorStar) [![[arxiv]](https://img.shields.io/badge/arxiv-2602.10575-blue)](https://arxiv.org/abs/2602.10575)
192
+
193
+ ## TODO
194
+
195
+ - Support ulysses parallelism for VLMs (middle priority).
196
+ - Support more VLM architectures.
197
+
198
+ > [!NOTE]
199
+ > We will not provide scripts for supervised fine-tuning and inference in this project. If you have such requirements, we recommend using [LlamaFactory](https://github.com/hiyouga/LlamaFactory).
200
+
201
+ ### Known bugs
202
+
203
+ These features are temporarily disabled for now, we plan to fix them one-by-one in the future updates.
204
+
205
+ - Vision language models are not compatible with ulysses parallelism yet.
206
+
207
+ ## Discussion Group
208
+
209
+ 👋 Join our [WeChat group](https://github.com/hiyouga/llamafactory-community/blob/main/wechat/easyr1.jpg).
210
+
211
+ ## FAQs
212
+
213
+ > ValueError: Image features and image tokens do not match: tokens: 8192, features 9800
214
+
215
+ Increase the `data.max_prompt_length` or reduce the `data.max_pixels`.
216
+
217
+ > RuntimeError: CUDA Error: out of memory at /workspace/csrc/cumem_allocator.cpp:62
218
+
219
+ Reduce the `worker.rollout.gpu_memory_utilization` and enable `worker.actor.offload.offload_params`.
220
+
221
+ > RuntimeError: 0 active drivers ([]). There should only be one.
222
+
223
+ Uninstall `deepspeed` from the current python environment.
224
+
225
+ ## Citation
226
+
227
+ 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), Yuwen Xiong and Richong Zhang
228
+
229
+ We also thank Guangming Sheng and Chi Zhang for helpful discussions.
230
+
231
+ ```bibtex
232
+ @misc{zheng2025easyr1,
233
+ title = {EasyR1: An Efficient, Scalable, Multi-Modality RL Training Framework},
234
+ author = {Yaowei Zheng, Junting Lu, Shenzhi Wang, Zhangchi Feng, Dongdong Kuang, Yuwen Xiong, Richong Zhang},
235
+ howpublished = {\url{https://github.com/hiyouga/EasyR1}},
236
+ year = {2025}
237
+ }
238
+ ```
239
+
240
+ We recommend to also cite the original work.
241
+
242
+ ```bibtex
243
+ @article{sheng2024hybridflow,
244
+ title = {HybridFlow: A Flexible and Efficient RLHF Framework},
245
+ 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},
246
+ year = {2024},
247
+ journal = {arXiv preprint arXiv: 2409.19256}
248
+ }
249
+ ```
EasyR1/assets/baselines.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Baselines
2
+
3
+ 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)
4
+
5
+ EasyR1 version: [v0.3.2](https://github.com/hiyouga/EasyR1/tree/v0.3.2)
6
+
7
+ Welcome to contribute new data points!
8
+
9
+ ## Algorithm Baselines
10
+
11
+ ### [Qwen2.5-Instruct](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct) on [Math12k](https://huggingface.co/datasets/hiyouga/math12k)
12
+
13
+ | Size | Algorithm | Bits | LR | KL | Test Accuracy |
14
+ | ---- | ----------- | ---- | ---- | ---- | -------------------- |
15
+ | 7B | GRPO | AMP | 1e-6 | 1e-2 | 0.75 -> 0.77 (+0.02) |
16
+
17
+ ### [Qwen2.5-VL-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
18
+
19
+ | Size | Algorithm | Bits | LR | KL | Test Accuracy |
20
+ | ---- | ----------- | ---- | ---- | ---- | -------------------- |
21
+ | 7B | GRPO | AMP | 1e-6 | 1e-2 | 0.37 -> 0.48 (+0.11) |
22
+ | 7B | GRPO | BF16 | 1e-6 | 1e-2 | 0.37 -> 0.48 (+0.11) |
23
+ | 7B | DAPO | AMP | 1e-6 | 1e-2 | 0.37 -> 0.50 (+0.13) |
24
+ | 7B | GSPO | AMP | 1e-6 | 0 | 0.37 -> 0.48 (+0.11) |
25
+ | 7B | CISPO | AMP | 1e-6 | 1e-2 | 0.37 -> 0.50 (+0.13) |
26
+ | 7B | SAPO | AMP | 1e-6 | 0 | 0.37 -> 0.54 (+0.17) |
27
+ | 3B | GRPO | AMP | 1e-6 | 1e-2 | 0.24 -> 0.38 (+0.14) |
28
+ | 32B | GRPO | BF16 | 1e-6 | 1e-2 | 0.50 -> 0.56 (+0.06) |
29
+
30
+ ### [Qwen3-VL-Instruct](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
31
+
32
+ | Size | Algorithm | Bits | LR | KL | Test Accuracy |
33
+ | ------- | ----------- | ---- | ---- | ---- | -------------------- |
34
+ | 30B-A3B | GRPO | BF16 | 1e-6 | 1e-2 | 0.55 -> 0.78 (+0.23) |
35
+
36
+ ### [Qwen3-VL-Thinking](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Thinking) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
37
+
38
+ | Size | Algorithm | Bits | LR | KL | Test Accuracy |
39
+ | ------- | ----------- | ---- | ---- | ---- | -------------------- |
40
+ | 30B-A3B | GRPO | BF16 | 1e-6 | 1e-2 | 0.49 -> 0.77 (+0.28) |
41
+
42
+ > [!NOTE]
43
+ > The hyper-parameters not listed are all the same as the default values.
44
+
45
+ ## Performance Baselines
46
+
47
+ ### [Qwen2.5-VL-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
48
+
49
+ | Size | GPU Type | Bits | Batch Size | vLLM TP | Peak Mem | Peak VRAM | Throughput | Sec per step | Actor MFU |
50
+ | ---- | ------------- | ---- | ---------- | ------- | -------- | --------- | ----------- | ------------ | --------- |
51
+ | 3B | 8 * H100 80GB | AMP | 1 / 2 | 2 | 120GB | 54GB | 1800 (+600) | 120s | 8.1% |
52
+ | 7B | 8 * H100 80GB | AMP | 1 / 2 | 2 | 120GB | 68GB | 1600 (+400) | 145s | 16.0% |
53
+ | 7B | 8 * H100 80GB | AMP | 4 / 8 | 2 | 200GB | 72GB | 2000 (+600) | 120s | 23.2% |
54
+ | 7B | 8 * L20 48GB | AMP | 1 / 2 | 2 | 120GB | 42GB | 410 (+0) | 580s | 26.5% |
55
+ | 7B | 8 * H100 80GB | BF16 | 1 / 2 | 2 | 120GB | 58GB | 1600 (+320) | 145s | 16.0% |
56
+ | 32B | 8 * H100 80GB | BF16 | 1 / 2 | 8 | 260GB | 72GB | 620 (+260) | 530s | 25.8% |
57
+
58
+ ### [Qwen3-VL-Instruct](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
59
+
60
+ | Size | GPU Type | Bits | Batch Size | vLLM TP | Peak Mem | Peak VRAM | Throughput | Sec per step | Actor MFU |
61
+ | ------- | ------------- | ---- | ---------- | ------- | -------- | --------- | ----------- | ------------ | --------- |
62
+ | 30B-A3B | 8 * H800 80GB | BF16 | 1 / 2 | 8 | 170GB | 50GB | 80 | 4600s | 1.8% |
63
+
64
+ ### [Qwen3-VL-Thinking](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Thinking) on [Geometry3k](https://huggingface.co/datasets/hiyouga/geometry3k)
65
+
66
+ | Size | GPU Type | Bits | Batch Size | vLLM TP | Peak Mem | Peak VRAM | Throughput | Sec per step | Actor MFU |
67
+ | ------- | ------------- | ---- | ---------- | ------- | -------- | --------- | ----------- | ------------ | --------- |
68
+ | 30B-A3B | 8 * H800 80GB | BF16 | 1 / 2 | 8 | 210GB | 50GB | 65 | 8000s | 1.4% |
69
+
70
+ - Batch Size: micro_batch_size_per_device_for_update / micro_batch_size_per_device_for_experience
71
+ - vLLM TP: rollout.tensor_parallel_size
72
+ - Peak Mem: Peak CPU memory usage
73
+ - Peak VRAM: Peak GPU memory usage
74
+ - 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))
75
+ - Sec per step: Average time per step in seconds
76
+
77
+ > [!NOTE]
78
+ > The hyper-parameters not listed are all the same as the default values.
EasyR1/examples/android_gui_cookbook/COLLECT_DATA_README.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 连接 android 设备收集训练数据步骤
2
+
3
+ # 1. 在 Android 中打开游戏
4
+ ```shell
5
+ adb -s <android_ip>:5555 shell am start -a android.intent.action.VIEW -d "http://<game_ip>:8000/number_game.html"
6
+ ```
7
+
8
+ # 2. 收集训练数据
9
+ max-workers: number of devices
10
+
11
+ ```shell
12
+ python examples/android_gui_cookbook/collect_data.py \
13
+ --devices <android_ip1>:5555 <android_ip2>:5555 <android_ip3>:5555 \
14
+ --episodes 1 \
15
+ --parallel \
16
+ --max-workers 3 \
17
+ --output-dir game_data_raw
18
+ ```
EasyR1/examples/android_gui_cookbook/PLAY_GAME_README.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 连接 android 设备玩游戏步骤
2
+
3
+ android 云端 android 设备创建可参考: https://github.com/tkestack/tke-ai-playbook/pull/20
4
+
5
+ ## 1.在Android浏览器中打开游戏:
6
+ adb -s <android_ip>:5555 shell am start -a android.intent.action.VIEW -d "http://<game_ip>:8000/number_game.html"
7
+
8
+ ## 2. 确保设备已连接
9
+ adb connect <android_ip>:5555
10
+
11
+ ## 3. 执行游戏脚本
12
+ - ollama
13
+ ```shell
14
+ python examples/android_gui_cookbook/play_agent.py \
15
+ --model-type ollama \
16
+ --api-url http://localhost:11434 \
17
+ --model-name qwen2.5vl:3b \
18
+ --devices <android_ip>:5555 \
19
+ --debug
20
+ ```
21
+ - vllm
22
+ ```shell
23
+ python examples/android_gui_cookbook/play_agent.py \
24
+ --model-type vllm \
25
+ --api-url <vllm_ip> \
26
+ --model-name <model_id> \
27
+ --devices <android_ip>:5555 \
28
+ --debug
29
+ ```
30
+
31
+ # 参数说明
32
+
33
+ - --model-type: 模型类型(ollama 或 vllm),默认 ollama
34
+ - --api-url: API地址,默认 http://localhost:11434
35
+ - --model-name: 模型名称,默认 qwen2.5vl:3b
36
+ - --devices: 设备列表
37
+ - --episodes: 运行局数,默认 1
38
+ - --debug: 开启调试模式,显示VLM输出
EasyR1/examples/android_gui_cookbook/README.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Android GUI 数字游戏强化学习教程
2
+
3
+ 本教程涵盖:**云端环境部署** → **模型训练** → **模型测试** 三个完整流程。
4
+
5
+ ---
6
+
7
+ ## 1. 云端 Android 部署和游戏部署
8
+
9
+ ### 1.1 游戏部署
10
+
11
+ #### Docker 部署
12
+
13
+ ```bash
14
+ # 拉取并运行游戏容器
15
+ docker run -d \
16
+ --name number-game \
17
+ -p 8000:8000 \
18
+ ccr.ccs.tencentyun.com/yuehuazhang/number-game-rl:v1.4
19
+
20
+ # 访问游戏
21
+ # http://localhost:8000/number_game.html
22
+ ```
23
+
24
+ #### Kubernetes 部署
25
+
26
+ ```bash
27
+ # 使用提供的配置文件
28
+ kubectl apply -f examples/android_gui_cookbook/game_docker/game.yaml
29
+
30
+ # 获取外部访问地址
31
+ kubectl get svc number-game -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
32
+
33
+ # 访问: http://<EXTERNAL-IP>:8000/number_game.html
34
+ ```
35
+
36
+ ### 1.2 Android 设备连接
37
+
38
+ #### 创建云端 Android 设备
39
+ 参考文档:https://github.com/tkestack/tke-ai-playbook/pull/20
40
+
41
+ #### 连接设备并打开游戏
42
+
43
+ ```bash
44
+ # 连接设备
45
+ adb connect <android_ip>:5555
46
+
47
+ # 在设备浏览器打开游戏
48
+ adb -s <android_ip>:5555 shell am start -a android.intent.action.VIEW \
49
+ -d "http://<game_ip>:8000/number_game.html"
50
+
51
+ # 验证连接
52
+ adb devices
53
+ ```
54
+
55
+ ---
56
+
57
+ ## 2. 模型训练
58
+
59
+ ### 2.1 训练脚本说明
60
+
61
+ **核心文件**:
62
+ - `examples/qwen2_5_vl_3b_android_gui_grpo.sh` - 训练启动脚本
63
+ - `examples/format_prompt/android_gui.jinja` - 提示词模板
64
+ - `examples/reward_function/android_gui.py` - 奖励函数
65
+
66
+ **游戏规则**(由 `android_gui.jinja` 定义):
67
+ - 🟢 绿灯:选择**最大**数字 → 位置索引 (0/1/2)
68
+ - 🔴 红灯:选择**最小**数字 → 位置索引 (0/1/2)
69
+ - 🟡 黄灯:选择**中间**数字 → 位置索引 (0/1/2)
70
+
71
+ **评分规则**(由 `android_gui.py` 实现):
72
+ - 正确选择:`+1.0`
73
+ - 错误选择:`0.0`
74
+
75
+ ### 2.2 启动训练
76
+
77
+ ```bash
78
+ # 切换到 EasyR1 根目录
79
+ cd /path/to/EasyR1
80
+
81
+ # 运行训练脚本
82
+ bash examples/qwen2_5_vl_3b_android_gui_grpo.sh
83
+ ```
84
+
85
+ ### 2.3 关键训练参数
86
+
87
+ 脚本使用以下配置(基于 `config.yaml`,通过命令行覆盖):
88
+
89
+ | 参数 | 值 | 说明 |
90
+ |------|-----|------|
91
+ | `data.train_files` | `yuehua-s/numbergame@train` | 训练数据集 |
92
+ | `data.val_files` | `yuehua-s/numbergame@test` | 验证数据集 |
93
+ | `data.rollout_batch_size` | `32` | Rollout 批次大小 |
94
+ | `algorithm.kl_coef` | `0.04` | KL 散度系数 |
95
+ | `worker.actor.optim.lr` | `1e-5` | 学习率 |
96
+ | `worker.rollout.n` | `8` | 每步生成响应数 |
97
+ | `trainer.total_epochs` | `3` | 训练轮数 |
98
+ | `trainer.n_gpus_per_node` | `2` | 每节点 GPU 数 |
99
+
100
+ ### 2.4 导出模型
101
+
102
+ 训练完成后,检查点保存在 `checkpoints/<experiment_name>/global_step_<N>/actor`。
103
+
104
+ ```bash
105
+ # 合并模型(转换为 HuggingFace 格式)
106
+ python3 scripts/model_merger.py \
107
+ --local_dir /path/to/EasyR1/checkpoints/<experiment_name>/global_step_35/actor
108
+
109
+ # 导出目录:checkpoints/<experiment_name>/global_step_35/actor/huggingface/
110
+ ```
111
+
112
+ ---
113
+
114
+ ## 3. 使用 Agent 玩游戏测试模型效果
115
+
116
+ ### 3.1 启动推理服务
117
+
118
+ 使用 vLLM 部署训练好的模型:
119
+
120
+ ```bash
121
+ vllm serve /path/to/checkpoints/<experiment_name>/global_step_35/actor/huggingface/ \
122
+ --host 0.0.0.0 \
123
+ --port 8000
124
+ ```
125
+
126
+ ### 3.2 运行 Agent 测试
127
+
128
+ **核心文件**:
129
+ - `examples/android_gui_cookbook/play_agent.py` - Agent 主程序
130
+ - `examples/android_gui_cookbook/adb_controller.py` - ADB 控制
131
+ - `examples/android_gui_cookbook/vlm_client.py` - VLM 推理客户端
132
+
133
+ #### 使用 vLLM 模型
134
+
135
+ ```bash
136
+ python examples/android_gui_cookbook/play_agent.py \
137
+ --model-type vllm \
138
+ --api-url http://<vllm_server_ip>:8000 \
139
+ --model-name /path/to/checkpoints/xxx/global_step_35/actor/huggingface/ \
140
+ --devices <android_ip>:5555 \
141
+ --episodes 5 \
142
+ --debug
143
+ ```
144
+
145
+ #### 使用 Ollama 模型
146
+
147
+ ```bash
148
+ python examples/android_gui_cookbook/play_agent.py \
149
+ --model-type ollama \
150
+ --api-url http://localhost:11434 \
151
+ --model-name qwen2.5vl:3b \
152
+ --devices <android_ip1>:5555 <android_ip2>:5555 \
153
+ --episodes 3 \
154
+ --debug
155
+ ```
156
+
157
+ ### 3.3 参数说明
158
+
159
+ | 参数 | 默认值 | 说明 |
160
+ |------|--------|------|
161
+ | `--model-type` | `ollama` | 模型服务类型(`ollama` 或 `vllm`) |
162
+ | `--api-url` | `http://localhost:11434` | 模型 API 地址 |
163
+ | `--model-name` | `qwen2.5vl:3b` | 模型名称或路径 |
164
+ | `--devices` | `101.43.137.83:5555` | Android 设备列表(空格分隔) |
165
+ | `--episodes` | `1` | 每个设备运行局数 |
166
+ | `--debug` | `False` | 开启调试模式(显示 VLM 输出) |
167
+ | `--screenshot-dir` | `game_screenshots` | 截图保存目录 |
168
+
169
+ ### 3.4 测试流程
170
+
171
+ Agent 自动执行以下操作(每局 10 轮):
172
+
173
+ 1. **截图** - 捕获当前游戏画面
174
+ 2. **VLM 推理** - 识别指示灯颜色和数字,做出决策
175
+ 3. **点击卡片** - 点击选择的数字(位置 0/1/2)
176
+ 4. **验证点击** - 检查卡片颜色是否改变
177
+ 5. **点击下一轮** - 进入下一轮游戏
178
+
179
+ ### 3.5 查看结果
180
+
181
+ 测试完成后,结果保存在 `game_screenshots/<device_id>/`:
182
+
183
+ ```
184
+ game_screenshots/
185
+ └── <android_ip>_5555/
186
+ ├── round_01_<timestamp>.png # 每轮决策前截图
187
+ ├── round_01_after_click_<timestamp>.png # 点击后截图
188
+ ├── final_score_<timestamp>.png # 最终得分截图
189
+ └── result_<timestamp>.json # 游戏结果(JSON)
190
+ ```
191
+
192
+ **结果文件示例**:
193
+ ```json
194
+ {
195
+ "device_id": "101.43.137.83:5555",
196
+ "timestamp": "20251123_143025",
197
+ "total_rounds": 10,
198
+ "final_score": 80,
199
+ "model_type": "vllm",
200
+ "model_name": "/path/to/model"
201
+ }
202
+ ```
203
+
204
+ ---
205
+
206
+ ## 附录:文件结构
207
+
208
+ ```
209
+ examples/
210
+ ├── qwen2_5_vl_3b_android_gui_grpo.sh # 训练脚本
211
+ ├── config.yaml # 基础配置
212
+ ├── format_prompt/
213
+ │ └── android_gui.jinja # 提示词模板
214
+ ├── reward_function/
215
+ │ └── android_gui.py # 奖励函数
216
+ └── android_gui_cookbook/
217
+ ├── README.md # 本文档
218
+ ├── play_agent.py # Agent 主程序
219
+ ├── adb_controller.py # ADB 控制器
220
+ ├── vlm_client.py # VLM 客户端
221
+ └── game_docker/
222
+ ├── game.yaml # K8s 部署配置
223
+ └── DOCKER_README.md # Docker 详细说明
224
+ ```
EasyR1/examples/android_gui_cookbook/adb_controller.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ADB 设备控制器
3
+
4
+ 功能:
5
+ - 连接 Android 设备
6
+ - 执行点击、滑动、输入等操作
7
+ - 截图获取
8
+ - 设备状态检测
9
+ """
10
+
11
+ import io
12
+ import subprocess
13
+ import time
14
+ from typing import Optional, Tuple
15
+
16
+ from PIL import Image
17
+
18
+
19
+ class ADBController:
20
+ """Android Debug Bridge 控制器"""
21
+
22
+ def __init__(self, device_id: str = "emulator-5554"):
23
+ """
24
+ 初始化 ADB 控制器
25
+
26
+ Args:
27
+ device_id: 设备 ID (通过 `adb devices` 查看)
28
+ """
29
+ self.device_id = device_id
30
+ self._check_connection()
31
+
32
+ def _check_connection(self):
33
+ """检查设备连接"""
34
+ try:
35
+ result = subprocess.run(["adb", "devices"], capture_output=True, text=True, timeout=5)
36
+
37
+ if self.device_id not in result.stdout:
38
+ raise ConnectionError(f"设备 {self.device_id} 未连接。请运行 'adb devices' 查看可用设备。")
39
+
40
+ print(f"✓ 设备 {self.device_id} 已连接")
41
+
42
+ except FileNotFoundError:
43
+ raise RuntimeError("ADB 未安装或未添加到 PATH。请安装 Android SDK Platform-Tools。")
44
+ except subprocess.TimeoutExpired:
45
+ raise TimeoutError("ADB 连接超时,请检查设备状态。")
46
+
47
+ def execute_command(self, command: str, timeout: int = 10) -> str:
48
+ """
49
+ 执行 ADB 命令
50
+
51
+ Args:
52
+ command: ADB 命令 (不包含 'adb -s device_id' 前缀)
53
+ timeout: 超时时间 (秒)
54
+
55
+ Returns:
56
+ 命令输出结果
57
+ """
58
+ full_command = f"adb -s {self.device_id} {command}"
59
+
60
+ try:
61
+ result = subprocess.run(full_command.split(), capture_output=True, text=True, timeout=timeout)
62
+
63
+ if result.returncode != 0:
64
+ raise RuntimeError(f"命令执行失败: {result.stderr}")
65
+
66
+ return result.stdout
67
+
68
+ except subprocess.TimeoutExpired:
69
+ raise TimeoutError(f"命令执行超时: {command}")
70
+
71
+ def capture_screenshot(self, save_path: Optional[str] = None) -> Image.Image:
72
+ """
73
+ 截取屏幕截图
74
+
75
+ Args:
76
+ save_path: 保存路径 (可选)
77
+
78
+ Returns:
79
+ PIL Image 对象
80
+ """
81
+ try:
82
+ # 使用 screencap 命令
83
+ cmd = f"adb -s {self.device_id} exec-out screencap -p"
84
+ result = subprocess.run(
85
+ cmd.split(),
86
+ capture_output=True,
87
+ timeout=15, # 增加超时时间,特别是远程设备或并发时
88
+ )
89
+
90
+ if result.returncode != 0:
91
+ raise RuntimeError("截图失败")
92
+
93
+ # 将字节流转换为 PIL Image
94
+ image = Image.open(io.BytesIO(result.stdout))
95
+
96
+ if save_path:
97
+ image.save(save_path)
98
+ print(f"✓ 截图已保存: {save_path}")
99
+
100
+ return image
101
+
102
+ except Exception as e:
103
+ raise RuntimeError(f"截图失败: {e}")
104
+
105
+ def tap(self, x: int, y: int, delay: float = 0.5) -> bool:
106
+ """
107
+ 点击屏幕坐标
108
+
109
+ Args:
110
+ x: X 坐标
111
+ y: Y 坐标
112
+ delay: 点击后等待时间 (秒)
113
+
114
+ Returns:
115
+ 是否成功
116
+ """
117
+ try:
118
+ self.execute_command(f"shell input tap {x} {y}")
119
+ time.sleep(delay)
120
+ print(f"✓ 点击坐标: ({x}, {y})")
121
+ return True
122
+
123
+ except Exception as e:
124
+ print(f"✗ 点击失败: {e}")
125
+ return False
126
+
127
+ def get_screen_resolution(self) -> Tuple[int, int]:
128
+ """
129
+ 获取屏幕分辨率
130
+
131
+ Returns:
132
+ (width, height)
133
+ """
134
+ try:
135
+ output = self.execute_command("shell wm size")
136
+ # 输出格式: Physical size: 1080x2400
137
+ size_str = output.split(":")[-1].strip()
138
+ width, height = map(int, size_str.split("x"))
139
+ return width, height
140
+
141
+ except Exception as e:
142
+ print(f"⚠ 无法获取分辨率,使用默认值 (1080, 2400): {e}")
143
+ return 1080, 2400
EasyR1/examples/android_gui_cookbook/collect_data.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 数据收集脚本 - 用于离线训练数据集构建
3
+
4
+ 功能:
5
+ 1. 支持多设备并发收集游戏截图
6
+ 2. 截图命名格式规范,方便后续批量标注
7
+ 3. 只收集截图,不调用VLM(节省时间和资源)
8
+ 4. 自动重试失败的轮次
9
+ 5. 记录每局游戏的元数据
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import re
15
+ import time
16
+ from concurrent.futures import ThreadPoolExecutor, as_completed
17
+ from datetime import datetime
18
+ from pathlib import Path
19
+ from typing import Dict, List, Optional, Tuple
20
+
21
+ from adb_controller import ADBController
22
+
23
+
24
+ class DataCollector:
25
+ """游戏数据收集器"""
26
+
27
+ def __init__(self, device_id: str, output_dir: str = "game_data_raw", debug: bool = False):
28
+ self.device_id = device_id
29
+ self.debug = debug
30
+
31
+ # 创建输出目录(使用安全的文件名)
32
+ safe_device_id = device_id.replace(":", "_").replace(".", "_")
33
+ self.output_dir = Path(output_dir) / safe_device_id
34
+ self.output_dir.mkdir(parents=True, exist_ok=True)
35
+
36
+ # 检查已有的episode,自动续集
37
+ self.start_episode_id = self._find_next_episode_id()
38
+ if self.start_episode_id > 1:
39
+ print(f"[{device_id}] 检测到已有数据,从 Episode {self.start_episode_id} 继续收集")
40
+
41
+ # 初始化 ADB 控制器
42
+ print(f"[{device_id}] 连接 Android 设备...")
43
+ self.controller = ADBController(device_id=device_id)
44
+
45
+ # 获取屏幕分辨率
46
+ self.screen_width, self.screen_height = self.controller.get_screen_resolution()
47
+ print(f"[{device_id}] 屏幕分辨率: {self.screen_width}x{self.screen_height}")
48
+
49
+ # 游戏元数据
50
+ self.episodes = []
51
+
52
+ def _find_next_episode_id(self) -> int:
53
+ """
54
+ 查找下一个可用的episode_id(避免覆盖已有数据)
55
+
56
+ Returns:
57
+ 下一个episode_id(从1开始)
58
+ """
59
+ existing_episodes = list(self.output_dir.glob("episode_*_metadata.json"))
60
+
61
+ if not existing_episodes:
62
+ return 1
63
+
64
+ # 提取所有已有的episode_id
65
+ episode_ids = []
66
+ for metadata_file in existing_episodes:
67
+ # 文件名格式: episode_001_metadata.json
68
+ match = re.match(r"episode_(\d+)_metadata\.json", metadata_file.name)
69
+ if match:
70
+ episode_ids.append(int(match.group(1)))
71
+
72
+ if episode_ids:
73
+ return max(episode_ids) + 1
74
+ else:
75
+ return 1
76
+
77
+ def calculate_card_positions(self) -> List[Tuple[int, int]]:
78
+ """计算 3 个选项按钮的点击位置"""
79
+ # 根据截图分析,选项按钮在屏幕约65-68%高度处
80
+ y = 860 # 调整后的坐标(720x1280屏幕,避免触发键盘)
81
+ positions = [
82
+ (135, y), # 左边(选项a)
83
+ (360, y), # 中间(选项b)
84
+ (585, y), # 右边(选项c)
85
+ ]
86
+ return positions
87
+
88
+ def calculate_next_button_position(self) -> Tuple[int, int]:
89
+ """计算"下一轮"按钮的位置"""
90
+ # 下一轮按钮在屏幕约80-82%高度处
91
+ return (360, 1040)
92
+
93
+ def random_choice(self) -> int:
94
+ """随机选择一个索引(0, 1, 2)"""
95
+ import random
96
+
97
+ return random.choice([0, 1, 2])
98
+
99
+ def capture_and_save(self, episode_id: int, round_num: int, suffix: str = "") -> Optional[str]:
100
+ """
101
+ 截图并保存,使用标准化的文件名
102
+
103
+ 文件名格式: episode_{ep}_round_{rd}_{suffix}.png
104
+ 例如: episode_001_round_03_question.png, episode_001_round_03_result.png
105
+
106
+ Args:
107
+ episode_id: 局数
108
+ round_num: 轮数
109
+ suffix: 文件名后缀,如 "question" 或 "result"
110
+
111
+ Returns:
112
+ 保存的文件路径(相对路径),失败返回 None
113
+ """
114
+ try:
115
+ screenshot = self.controller.capture_screenshot()
116
+
117
+ # 标准化文件名
118
+ if suffix:
119
+ filename = f"episode_{episode_id:03d}_round_{round_num:02d}_{suffix}.png"
120
+ else:
121
+ filename = f"episode_{episode_id:03d}_round_{round_num:02d}.png"
122
+ filepath = self.output_dir / filename
123
+
124
+ screenshot.save(filepath)
125
+
126
+ if self.debug:
127
+ print(f"[{self.device_id}] 截图已保存: {filepath}")
128
+
129
+ return str(filepath.relative_to(self.output_dir.parent))
130
+
131
+ except Exception as e:
132
+ print(f"⚠ [{self.device_id}] 截图失败: {e}")
133
+ return None
134
+
135
+ def check_card_color_changed(self) -> bool:
136
+ """
137
+ 简单检查:等待一下后重新截图,看是否有颜色变化
138
+ 这里用简化的方法:如果点击后界面没报错,就认为成功
139
+ """
140
+ time.sleep(0.8)
141
+ return True # 简化处理,假设点击总是成功
142
+
143
+ def play_one_round(self, episode_id: int, round_num: int) -> Optional[Dict]:
144
+ """
145
+ 玩一轮游戏并收集数据
146
+
147
+ 收集两张截图:
148
+ 1. question.png - 操作前的状态(灯光+数字选项)
149
+ 2. result.png - 操作后的反馈(显示正确答案)
150
+
151
+ Returns:
152
+ 该轮的元数据字典,失败返回 None
153
+ """
154
+ print(f"[{self.device_id}] Round {round_num}/10")
155
+
156
+ # 短暂延迟,避免并发时ADB冲突
157
+ time.sleep(0.3)
158
+
159
+ # 1. 截图1:question(操作前状态)
160
+ question_screenshot = self.capture_and_save(episode_id, round_num, "question")
161
+ if question_screenshot is None:
162
+ return None
163
+
164
+ # 2. 随机选择一个卡片点击
165
+ selected_index = self.random_choice()
166
+
167
+ if self.debug:
168
+ print(f"[{self.device_id}] 随机选择索引: {selected_index}")
169
+
170
+ # 3. 点击卡片
171
+ positions = self.calculate_card_positions()
172
+ x, y = positions[selected_index]
173
+
174
+ max_retry = 3
175
+ click_success = False
176
+
177
+ for retry in range(max_retry):
178
+ success = self.controller.tap(x, y, delay=1.0)
179
+ if not success:
180
+ if retry < max_retry - 1:
181
+ print(f"⚠ [{self.device_id}] 点击失败,重试 {retry + 1}/{max_retry}")
182
+ time.sleep(0.5)
183
+ continue
184
+ else:
185
+ print(f"⚠ [{self.device_id}] 点击失败,跳过此轮")
186
+ return None
187
+
188
+ # 检查点击是否成功
189
+ if self.check_card_color_changed():
190
+ click_success = True
191
+ break
192
+ else:
193
+ if retry < max_retry - 1:
194
+ print(f"⚠ [{self.device_id}] 点击未生效,重试 {retry + 1}/{max_retry}")
195
+ time.sleep(0.5)
196
+
197
+ if not click_success:
198
+ print(f"⚠ [{self.device_id}] 多次点击均未成功")
199
+ return None
200
+
201
+ # 4. 等待反馈显示
202
+ time.sleep(1.5)
203
+
204
+ # 5. 截图2:result(操作后反馈,包含正确答案)
205
+ # 增加短暂延迟避免并发冲突
206
+ time.sleep(0.2)
207
+ result_screenshot = self.capture_and_save(episode_id, round_num, "result")
208
+ if result_screenshot is None:
209
+ print(f"⚠ [{self.device_id}] result截图失败")
210
+ return None
211
+
212
+ # 6. 点击"下一轮"按钮
213
+ next_x, next_y = self.calculate_next_button_position()
214
+ success = self.controller.tap(next_x, next_y, delay=1.0)
215
+
216
+ if not success:
217
+ print(f"⚠ [{self.device_id}] 点击下一轮失败")
218
+ return None
219
+
220
+ # 7. 返回该轮的元数据
221
+ metadata = {
222
+ "round": round_num,
223
+ "question_screenshot": question_screenshot,
224
+ "result_screenshot": result_screenshot,
225
+ "selected_index": selected_index,
226
+ "click_position": [x, y],
227
+ "timestamp": datetime.now().isoformat(),
228
+ }
229
+
230
+ return metadata
231
+
232
+ def collect_one_episode(self, episode_id: int) -> Dict:
233
+ """
234
+ 收集一局游戏的数据(10轮)
235
+
236
+ Returns:
237
+ 该局的元数据字典
238
+ """
239
+ print(f"\n{'=' * 60}")
240
+ print(f"[{self.device_id}] Episode {episode_id} 开始")
241
+ print(f"{'=' * 60}\n")
242
+
243
+ episode_metadata = {
244
+ "episode_id": episode_id,
245
+ "device_id": self.device_id,
246
+ "start_time": datetime.now().isoformat(),
247
+ "rounds": [],
248
+ "completed_rounds": 0,
249
+ "success": False,
250
+ }
251
+
252
+ # 收集10轮数据
253
+ completed_rounds = 0
254
+ attempt_count = 0
255
+ max_attempts = 20 # 最多尝试20次
256
+
257
+ while completed_rounds < 10 and attempt_count < max_attempts:
258
+ attempt_count += 1
259
+ round_num = completed_rounds + 1
260
+
261
+ round_metadata = self.play_one_round(episode_id, round_num)
262
+
263
+ if round_metadata is not None:
264
+ episode_metadata["rounds"].append(round_metadata)
265
+ completed_rounds += 1
266
+ print(f"✓ [{self.device_id}] Round {completed_rounds}/10 完成")
267
+
268
+ # 轮次间等待
269
+ if completed_rounds < 10:
270
+ time.sleep(1.0)
271
+ else:
272
+ print(f"⚠ [{self.device_id}] Round {round_num} 失败,重试...")
273
+ time.sleep(1.5)
274
+
275
+ episode_metadata["completed_rounds"] = completed_rounds
276
+ episode_metadata["success"] = completed_rounds == 10
277
+ episode_metadata["end_time"] = datetime.now().isoformat()
278
+
279
+ # 截取最终得分界面
280
+ time.sleep(2.0)
281
+ final_screenshot_path = self.capture_and_save(episode_id, 99, "final") # 用99表示final
282
+ if final_screenshot_path:
283
+ episode_metadata["final_screenshot"] = final_screenshot_path
284
+
285
+ # 保存该局的元数据
286
+ metadata_file = self.output_dir / f"episode_{episode_id:03d}_metadata.json"
287
+ with open(metadata_file, "w", encoding="utf-8") as f:
288
+ json.dump(episode_metadata, f, ensure_ascii=False, indent=2)
289
+
290
+ print(f"\n{'=' * 60}")
291
+ print(f"[{self.device_id}] Episode {episode_id} 完成")
292
+ print(f"[{self.device_id}] 成功轮数: {completed_rounds}/10")
293
+ print(f"[{self.device_id}] 元数据已保存: {metadata_file}")
294
+ print(f"{'=' * 60}\n")
295
+
296
+ self.episodes.append(episode_metadata)
297
+ return episode_metadata
298
+
299
+ def refresh_browser(self):
300
+ """刷新浏览器页面,准备下一局"""
301
+ print(f"[{self.device_id}] 刷新浏览器...")
302
+
303
+ # 点击刷新按钮
304
+ refresh_button_x = 380
305
+ refresh_button_y = 130
306
+ self.controller.tap(refresh_button_x, refresh_button_y, delay=1.0)
307
+
308
+ time.sleep(3.0) # 等待页面加载
309
+ print(f"[{self.device_id}] 浏览器已刷新")
310
+
311
+ def collect_data(self, num_episodes: int) -> List[Dict]:
312
+ """
313
+ 收集多局游戏数据
314
+
315
+ Args:
316
+ num_episodes: 要收集的局数
317
+
318
+ Returns:
319
+ 所有局的元数据列表
320
+ """
321
+ # 从续集ID开始
322
+ for i in range(num_episodes):
323
+ episode_id = self.start_episode_id + i
324
+ self.collect_one_episode(episode_id)
325
+
326
+ # 局间刷新浏览器(最后一局不需要)
327
+ if i < num_episodes - 1:
328
+ self.refresh_browser()
329
+ time.sleep(2.0)
330
+
331
+ # 保存汇总信息
332
+ summary = {
333
+ "device_id": self.device_id,
334
+ "total_episodes": num_episodes,
335
+ "successful_episodes": sum(1 for ep in self.episodes if ep["success"]),
336
+ "total_rounds_collected": sum(ep["completed_rounds"] for ep in self.episodes),
337
+ "collection_time": datetime.now().isoformat(),
338
+ "output_dir": str(self.output_dir),
339
+ "episodes": self.episodes,
340
+ }
341
+
342
+ summary_file = self.output_dir / "collection_summary.json"
343
+ with open(summary_file, "w", encoding="utf-8") as f:
344
+ json.dump(summary, f, ensure_ascii=False, indent=2)
345
+
346
+ print(f"\n{'=' * 60}")
347
+ print(f"[{self.device_id}] 数据收集完成!")
348
+ print(f"[{self.device_id}] 总局数: {num_episodes}")
349
+ print(f"[{self.device_id}] 成功局数: {summary['successful_episodes']}")
350
+ print(f"[{self.device_id}] 总轮数: {summary['total_rounds_collected']}")
351
+ print(f"[{self.device_id}] 汇总文件: {summary_file}")
352
+ print(f"{'=' * 60}\n")
353
+
354
+ return self.episodes
355
+
356
+
357
+ def collect_from_device(device_id: str, num_episodes: int, output_dir: str, debug: bool) -> Dict:
358
+ """
359
+ 从单个设备收集数据(用于并发执行)
360
+
361
+ Returns:
362
+ 收集汇总信息
363
+ """
364
+ try:
365
+ collector = DataCollector(device_id=device_id, output_dir=output_dir, debug=debug)
366
+
367
+ collector.collect_data(num_episodes)
368
+
369
+ # 读取汇总文件
370
+ summary_file = collector.output_dir / "collection_summary.json"
371
+ with open(summary_file, encoding="utf-8") as f:
372
+ return json.load(f)
373
+
374
+ except Exception as e:
375
+ print(f"⚠ 设备 {device_id} 收集失败: {e}")
376
+ import traceback
377
+
378
+ traceback.print_exc()
379
+ return {"device_id": device_id, "error": str(e), "success": False}
380
+
381
+
382
+ def main():
383
+ parser = argparse.ArgumentParser(description="游戏数据收集脚本(用于离线训练)")
384
+
385
+ # 设备配置
386
+ parser.add_argument(
387
+ "--devices",
388
+ type=str,
389
+ nargs="+",
390
+ required=True,
391
+ help="Android 设备地址列表,如: 101.43.137.83:5555 192.168.1.100:5555",
392
+ )
393
+
394
+ # 收集配置
395
+ parser.add_argument("--episodes", type=int, default=10, help="每个设备收集多少局游戏(默认10局)")
396
+
397
+ parser.add_argument("--output-dir", type=str, default="game_data_raw", help="输出目录(默认 game_data_raw)")
398
+
399
+ # 执行模式
400
+ parser.add_argument("--parallel", action="store_true", help="并发执行多个设备(默认顺序执行)")
401
+
402
+ parser.add_argument("--max-workers", type=int, default=4, help="并发执行时的最大线程数(默认4)")
403
+
404
+ parser.add_argument("--debug", action="store_true", help="开启调试模式")
405
+
406
+ args = parser.parse_args()
407
+
408
+ print("=" * 60)
409
+ print("游戏数据收集脚本")
410
+ print("=" * 60)
411
+ print(f"设备数量: {len(args.devices)}")
412
+ print(f"每设备局数: {args.episodes}")
413
+ print(f"预计总轮数: {len(args.devices) * args.episodes * 10}")
414
+ print(f"输出目录: {args.output_dir}")
415
+ print(f"执行模式: {'并发' if args.parallel else '顺序'}")
416
+ print("=" * 60)
417
+ print()
418
+
419
+ start_time = time.time()
420
+ all_summaries = []
421
+
422
+ if args.parallel and len(args.devices) > 1:
423
+ # 并发执行
424
+ print(f"使用 {min(args.max_workers, len(args.devices))} 个线程并发收集数据...\n")
425
+
426
+ with ThreadPoolExecutor(max_workers=min(args.max_workers, len(args.devices))) as executor:
427
+ # 提交所有任务
428
+ future_to_device = {
429
+ executor.submit(collect_from_device, device_id, args.episodes, args.output_dir, args.debug): device_id
430
+ for device_id in args.devices
431
+ }
432
+
433
+ # 等待完成
434
+ for future in as_completed(future_to_device):
435
+ device_id = future_to_device[future]
436
+ try:
437
+ summary = future.result()
438
+ all_summaries.append(summary)
439
+ print(f"✓ 设备 {device_id} 数据收集完成")
440
+ except Exception as e:
441
+ print(f"⚠ 设备 {device_id} 发生异常: {e}")
442
+ else:
443
+ # 顺序执行
444
+ for device_id in args.devices:
445
+ print(f"\n处理设备: {device_id}")
446
+ print("-" * 60)
447
+
448
+ summary = collect_from_device(device_id, args.episodes, args.output_dir, args.debug)
449
+ all_summaries.append(summary)
450
+
451
+ # 生成总汇总
452
+ elapsed_time = time.time() - start_time
453
+ total_summary = {
454
+ "total_devices": len(args.devices),
455
+ "episodes_per_device": args.episodes,
456
+ "total_episodes_collected": sum(s.get("total_episodes", 0) for s in all_summaries),
457
+ "successful_episodes": sum(s.get("successful_episodes", 0) for s in all_summaries),
458
+ "total_rounds_collected": sum(s.get("total_rounds_collected", 0) for s in all_summaries),
459
+ "collection_time_seconds": elapsed_time,
460
+ "output_dir": args.output_dir,
461
+ "timestamp": datetime.now().isoformat(),
462
+ "device_summaries": all_summaries,
463
+ }
464
+
465
+ # 保存总汇总
466
+ output_path = Path(args.output_dir)
467
+ output_path.mkdir(parents=True, exist_ok=True)
468
+
469
+ total_summary_file = output_path / "total_summary.json"
470
+ with open(total_summary_file, "w", encoding="utf-8") as f:
471
+ json.dump(total_summary, f, ensure_ascii=False, indent=2)
472
+
473
+ # 打印最终结果
474
+ print("\n" + "=" * 60)
475
+ print("所有数据收集完成!")
476
+ print("=" * 60)
477
+ print(f"总设备数: {total_summary['total_devices']}")
478
+ print(f"总局数: {total_summary['total_episodes_collected']}")
479
+ print(f"成功局数: {total_summary['successful_episodes']}")
480
+ print(f"总轮数: {total_summary['total_rounds_collected']}")
481
+ print(f"耗时: {elapsed_time:.1f} 秒 ({elapsed_time / 60:.1f} 分钟)")
482
+ print(f"输出目录: {args.output_dir}")
483
+ print(f"总汇总文件: {total_summary_file}")
484
+ print("=" * 60)
485
+ print("\n下一步: 使用标注脚本对收集的截图进行批量标注")
486
+
487
+
488
+ if __name__ == "__main__":
489
+ main()
EasyR1/examples/android_gui_cookbook/game_docker/.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Docker ignore file
2
+ *.pyc
3
+ __pycache__/
4
+ .git/
5
+ .gitignore
6
+ *.md
7
+ .DS_Store
8
+ DOCKER_README.md
9
+ game.yaml
EasyR1/examples/android_gui_cookbook/game_docker/DOCKER_README.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 数字选择游戏 - Docker 镜像
2
+
3
+ ## 📦 镜像信息
4
+
5
+ **镜像名称**: `number-game-rl`
6
+ **当前版本**: `v1.4`
7
+ **镜像仓库**: `ccr.ccs.tencentyun.com/yuehuazhang/number-game-rl`
8
+ **架构**: `linux/amd64`
9
+ **大小**: ~124MB
10
+ **基础镜像**: `python:3.11-slim`
11
+
12
+ ## 🚀 使用方法
13
+
14
+ ### 1. Docker 部署
15
+
16
+ ```bash
17
+ # 从腾讯云镜像仓库拉取并运行
18
+ docker run -d \
19
+ --name number-game \
20
+ -p 8000:8000 \
21
+ ccr.ccs.tencentyun.com/yuehuazhang/number-game-rl:v1.4
22
+
23
+ # 自定义端口(例如映射到9000)
24
+ docker run -d \
25
+ --name number-game \
26
+ -p 9000:8000 \
27
+ ccr.ccs.tencentyun.com/yuehuazhang/number-game-rl:v1.4
28
+ ```
29
+
30
+ ### 2. 访问游戏
31
+
32
+ 打开浏览器访问:
33
+ ```
34
+ http://localhost:8000/number_game.html
35
+ ```
36
+
37
+ ### 3. Kubernetes 部署(推荐)
38
+
39
+ 使用提供的 `game.yaml` 配置文件进行部署:
40
+
41
+ ```bash
42
+ # 部署到 Kubernetes 集群
43
+ kubectl apply -f game.yaml
44
+ ```
45
+
46
+ **game.yaml 配置说明:**
47
+
48
+ ```yaml
49
+ # Deployment 配置
50
+ apiVersion: apps/v1
51
+ kind: Deployment
52
+ metadata:
53
+ name: number-game
54
+ spec:
55
+ replicas: 1 # 副本数
56
+ template:
57
+ spec:
58
+ containers:
59
+ - name: number-game
60
+ image: ccr.ccs.tencentyun.com/yuehuazhang/number-game-rl:v1.4
61
+ imagePullPolicy: IfNotPresent # 镜像拉取策略
62
+ ports:
63
+ - containerPort: 8000
64
+ resources:
65
+ limits:
66
+ cpu: "2" # CPU限制:2核
67
+ memory: 4Gi # 内存限制:4GB
68
+ requests:
69
+ cpu: "2" # CPU请求:2核
70
+ memory: 4Gi # 内存请求:4GB
71
+
72
+ ---
73
+ # Service 配置(LoadBalancer类型)
74
+ apiVersion: v1
75
+ kind: Service
76
+ metadata:
77
+ name: number-game
78
+ annotations:
79
+ service.cloud.tencent.com/direct-access: "true" # 腾讯云直连
80
+ spec:
81
+ type: LoadBalancer # 使用负载均衡器
82
+ allocateLoadBalancerNodePorts: false # 不分配节点端口
83
+ ports:
84
+ - name: 8000-8000-tcp
85
+ port: 8000
86
+ targetPort: 8000
87
+ protocol: TCP
88
+ selector:
89
+ k8s-app: number-game
90
+ ```
91
+
92
+ **部署后访问:**
93
+
94
+ ```bash
95
+ # 查看服务状态
96
+ kubectl get svc number-game
97
+
98
+ # 获取 LoadBalancer 外部IP
99
+ kubectl get svc number-game -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
100
+
101
+ # 访问游戏(替换为实际的外部IP)
102
+ # http://<EXTERNAL-IP>:8000/number_game.html
103
+ ```
104
+
105
+ **扩缩容:**
106
+
107
+ ```bash
108
+ # 扩展副本数
109
+ kubectl scale deployment number-game --replicas=3
110
+
111
+ # 查看 Pod 状态
112
+ kubectl get pods -l k8s-app=number-game
113
+ ```
114
+
115
+ **删除部署:**
116
+
117
+ ```bash
118
+ kubectl delete -f game.yaml
119
+ ```
120
+
121
+ ## 🎮 游戏说明
122
+
123
+ 这是一个**条件反转数字选择游戏**,用于强化学习训练。
124
+
125
+ ### 游戏规则
126
+
127
+ 1. **观察指示灯**(屏幕上方3个圆形):
128
+ - 🟢 绿灯亮:选择**最大**的数字
129
+ - 🔴 红灯亮:选择**最小**的数字
130
+ - 🟡 黄灯亮:选择**中间**的数字
131
+
132
+ 2. **得分规则**:
133
+ - 选对:+10 分
134
+ - 选错:-10 分
135
+
136
+ 3. **游戏目标**:完成10轮,获得最高分
137
+
138
+ ### 适配分辨率
139
+
140
+ - 优化适配:720x1280(Android设备)
141
+ - 兼容:桌面浏览器、平板、手机
142
+
143
+ ## 🔧 镜像内容
144
+
145
+ ```
146
+ /app/
147
+ └── number_game.html # 游戏HTML文件(包含CSS和JavaScript)
148
+ ```
149
+
150
+ ## 📝 环境变量
151
+
152
+ 无需配置环境变量,开箱即用。
153
+
154
+ ## 🐛 故障排查
155
+
156
+ ### 容器无法启动
157
+ ```bash
158
+ docker logs number-game
159
+ ```
160
+
161
+ ### 端口冲突
162
+ ```bash
163
+ # 更换端口
164
+ docker run -d --name number-game -p 9000:8000 number-game-rl:v1.0
165
+ ```
166
+
167
+ ### 查看容器状态
168
+ ```bash
169
+ docker ps -a | grep number-game
170
+ ```
EasyR1/examples/android_gui_cookbook/game_docker/Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 数字选择游戏 - Docker镜像
2
+ # 平台: linux/amd64
3
+ FROM --platform=linux/amd64 python:3.11-slim
4
+
5
+ # 设置工作目录
6
+ WORKDIR /app
7
+
8
+ # 复制游戏文件
9
+ COPY number_game.html /app/
10
+
11
+ # 暴露端口
12
+ EXPOSE 8000
13
+
14
+ # 启动HTTP服务器
15
+ CMD ["python", "-m", "http.server", "8000"]
EasyR1/examples/android_gui_cookbook/game_docker/game-deployment.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ apiVersion: apps/v1
2
+ kind: Deployment
3
+ metadata:
4
+ labels:
5
+ k8s-app: number-game
6
+ qcloud-app: number-game
7
+ name: number-game
8
+ spec:
9
+ replicas: 1
10
+ selector:
11
+ matchLabels:
12
+ k8s-app: number-game
13
+ qcloud-app: number-game
14
+ template:
15
+ metadata:
16
+ labels:
17
+ k8s-app: number-game
18
+ qcloud-app: number-game
19
+ spec:
20
+ containers:
21
+ - image: ccr.ccs.tencentyun.com/yuehuazhang/number-game-rl:v1.4
22
+ imagePullPolicy: IfNotPresent
23
+ name: number-game
24
+ ports:
25
+ - containerPort: 8000
26
+ protocol: TCP
27
+ resources:
28
+ limits:
29
+ cpu: "2"
30
+ memory: 4Gi
31
+ requests:
32
+ cpu: "2"
33
+ memory: 4Gi
EasyR1/examples/android_gui_cookbook/game_docker/game-service.yaml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ apiVersion: v1
2
+ kind: Service
3
+ metadata:
4
+ annotations:
5
+ service.cloud.tencent.com/direct-access: "true"
6
+ labels:
7
+ k8s-app: number-game
8
+ qcloud-app: number-game
9
+ service.cloud.tencent.com/loadbalance-type: OPEN
10
+ name: number-game
11
+ spec:
12
+ allocateLoadBalancerNodePorts: false
13
+ ipFamilies:
14
+ - IPv4
15
+ ipFamilyPolicy: SingleStack
16
+ ports:
17
+ - name: 8000-8000-tcp
18
+ port: 8000
19
+ protocol: TCP
20
+ targetPort: 8000
21
+ selector:
22
+ k8s-app: number-game
23
+ qcloud-app: number-game
24
+ type: LoadBalancer
EasyR1/examples/android_gui_cookbook/game_docker/number_game.html ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
6
+ <title>数字选择游戏 - RL 训练</title>
7
+ <style>
8
+ * {
9
+ margin: 0;
10
+ padding: 0;
11
+ box-sizing: border-box;
12
+ -webkit-tap-highlight-color: transparent;
13
+ }
14
+
15
+ body {
16
+ font-family: 'Arial', sans-serif;
17
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
18
+ display: flex;
19
+ justify-content: center;
20
+ align-items: flex-start;
21
+ min-height: 100vh;
22
+ padding: 5px;
23
+ overflow-y: auto;
24
+ }
25
+
26
+ .game-container {
27
+ background: white;
28
+ border-radius: 12px;
29
+ box-shadow: 0 8px 20px rgba(0,0,0,0.3);
30
+ padding: 8px 10px;
31
+ max-width: 500px;
32
+ width: 100%;
33
+ margin-top: 5px;
34
+ }
35
+
36
+ .title {
37
+ text-align: center;
38
+ color: #333;
39
+ font-size: 16px;
40
+ font-weight: bold;
41
+ margin-bottom: 3px;
42
+ }
43
+
44
+ .subtitle {
45
+ text-align: center;
46
+ color: #666;
47
+ font-size: 10px;
48
+ margin-bottom: 6px;
49
+ }
50
+
51
+ .score-board {
52
+ background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
53
+ border-radius: 8px;
54
+ padding: 8px;
55
+ margin-bottom: 6px;
56
+ text-align: center;
57
+ color: white;
58
+ }
59
+
60
+ .score-label {
61
+ font-size: 11px;
62
+ margin-bottom: 3px;
63
+ opacity: 0.9;
64
+ }
65
+
66
+ .score-value {
67
+ font-size: 28px;
68
+ font-weight: bold;
69
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
70
+ }
71
+
72
+ .round-info {
73
+ display: flex;
74
+ justify-content: space-between;
75
+ margin-top: 5px;
76
+ font-size: 10px;
77
+ opacity: 0.9;
78
+ }
79
+
80
+ .instruction {
81
+ background: #f8f9fa;
82
+ border-radius: 6px;
83
+ padding: 6px;
84
+ margin-bottom: 6px;
85
+ text-align: center;
86
+ color: #333;
87
+ font-size: 11px;
88
+ font-weight: 500;
89
+ }
90
+
91
+ /* 指示灯容器 */
92
+ .indicator-container {
93
+ display: flex;
94
+ justify-content: center;
95
+ align-items: center;
96
+ gap: 10px;
97
+ margin-bottom: 6px;
98
+ padding: 8px;
99
+ background: #f8f9fa;
100
+ border-radius: 8px;
101
+ }
102
+
103
+ .indicator-light {
104
+ width: 45px;
105
+ height: 45px;
106
+ border-radius: 50%;
107
+ border: 2px solid #ddd;
108
+ display: flex;
109
+ align-items: center;
110
+ justify-content: center;
111
+ font-size: 9px;
112
+ font-weight: bold;
113
+ color: #999;
114
+ transition: all 0.3s ease;
115
+ position: relative;
116
+ }
117
+
118
+ .indicator-light.active {
119
+ border-color: #333;
120
+ box-shadow: 0 0 12px rgba(0,0,0,0.3), inset 0 0 12px rgba(255,255,255,0.3);
121
+ animation: glow 1.5s ease-in-out infinite;
122
+ }
123
+
124
+ .indicator-light.green {
125
+ background: radial-gradient(circle, #38ef7d, #11998e);
126
+ }
127
+
128
+ .indicator-light.red {
129
+ background: radial-gradient(circle, #f45c43, #eb3349);
130
+ }
131
+
132
+ .indicator-light.yellow {
133
+ background: radial-gradient(circle, #ffd200, #f7971e);
134
+ }
135
+
136
+ .indicator-light.inactive {
137
+ background: #ccc;
138
+ }
139
+
140
+ @keyframes glow {
141
+ 0%, 100% { box-shadow: 0 0 12px rgba(0,0,0,0.3), inset 0 0 12px rgba(255,255,255,0.3); }
142
+ 50% { box-shadow: 0 0 18px rgba(0,0,0,0.5), inset 0 0 18px rgba(255,255,255,0.5); }
143
+ }
144
+
145
+ .indicator-label {
146
+ text-align: center;
147
+ font-size: 9px;
148
+ color: #666;
149
+ margin-top: 3px;
150
+ }
151
+
152
+ .cards-container {
153
+ display: flex;
154
+ justify-content: space-around;
155
+ gap: 6px;
156
+ margin-bottom: 8px;
157
+ }
158
+
159
+ .card {
160
+ flex: 1;
161
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
162
+ border-radius: 10px;
163
+ padding: 20px 10px;
164
+ text-align: center;
165
+ cursor: pointer;
166
+ transition: all 0.3s ease;
167
+ box-shadow: 0 6px 15px rgba(0,0,0,0.2);
168
+ position: relative;
169
+ overflow: hidden;
170
+ }
171
+
172
+ .card:hover {
173
+ transform: translateY(-3px);
174
+ box-shadow: 0 8px 20px rgba(0,0,0,0.3);
175
+ }
176
+
177
+ .card:active {
178
+ transform: translateY(-1px);
179
+ }
180
+
181
+ .card.selected {
182
+ background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
183
+ animation: pulse 0.5s ease;
184
+ }
185
+
186
+ .card.correct {
187
+ background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
188
+ }
189
+
190
+ .card.wrong {
191
+ background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
192
+ }
193
+
194
+ .card.medium {
195
+ background: linear-gradient(135deg, #f7971e 0%, #ffd200 100%);
196
+ }
197
+
198
+ .card-number {
199
+ font-size: 42px;
200
+ font-weight: bold;
201
+ color: white;
202
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
203
+ }
204
+
205
+ .card-label {
206
+ font-size: 9px;
207
+ color: white;
208
+ margin-top: 5px;
209
+ opacity: 0.9;
210
+ }
211
+
212
+ @keyframes pulse {
213
+ 0%, 100% { transform: scale(1); }
214
+ 50% { transform: scale(1.05); }
215
+ }
216
+
217
+ .feedback {
218
+ text-align: center;
219
+ font-size: 13px;
220
+ font-weight: bold;
221
+ min-height: 20px;
222
+ margin-bottom: 8px;
223
+ transition: all 0.3s ease;
224
+ }
225
+
226
+ .feedback.correct {
227
+ color: #38ef7d;
228
+ }
229
+
230
+ .feedback.wrong {
231
+ color: #f45c43;
232
+ }
233
+
234
+ .feedback.medium {
235
+ color: #ffd200;
236
+ }
237
+
238
+ .next-button {
239
+ width: 100%;
240
+ padding: 10px;
241
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
242
+ color: white;
243
+ border: none;
244
+ border-radius: 6px;
245
+ font-size: 14px;
246
+ font-weight: bold;
247
+ cursor: pointer;
248
+ transition: all 0.3s ease;
249
+ box-shadow: 0 3px 10px rgba(0,0,0,0.2);
250
+ }
251
+
252
+ .next-button:hover {
253
+ transform: translateY(-2px);
254
+ box-shadow: 0 5px 12px rgba(0,0,0,0.3);
255
+ }
256
+
257
+ .next-button:active {
258
+ transform: translateY(0);
259
+ }
260
+
261
+ .next-button:disabled {
262
+ background: #ccc;
263
+ cursor: not-allowed;
264
+ transform: none;
265
+ }
266
+
267
+ .game-over {
268
+ text-align: center;
269
+ padding: 15px;
270
+ }
271
+
272
+ .game-over-title {
273
+ font-size: 20px;
274
+ color: #333;
275
+ margin-bottom: 10px;
276
+ font-weight: bold;
277
+ }
278
+
279
+ .final-score {
280
+ font-size: 40px;
281
+ font-weight: bold;
282
+ background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
283
+ -webkit-background-clip: text;
284
+ -webkit-text-fill-color: transparent;
285
+ margin-bottom: 15px;
286
+ }
287
+
288
+ .restart-button {
289
+ padding: 10px 25px;
290
+ background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
291
+ color: white;
292
+ border: none;
293
+ border-radius: 6px;
294
+ font-size: 14px;
295
+ font-weight: bold;
296
+ cursor: pointer;
297
+ box-shadow: 0 3px 10px rgba(0,0,0,0.2);
298
+ }
299
+
300
+ .stats {
301
+ margin-top: 15px;
302
+ background: #f8f9fa;
303
+ border-radius: 6px;
304
+ padding: 10px;
305
+ }
306
+
307
+ .stats-row {
308
+ display: flex;
309
+ justify-content: space-between;
310
+ margin: 5px 0;
311
+ font-size: 12px;
312
+ color: #333;
313
+ }
314
+ </style>
315
+ </head>
316
+ <body>
317
+ <div class="game-container">
318
+ <div id="gameView">
319
+ <h1 class="title">🎯 数字选择游戏</h1>
320
+ <p class="subtitle">观察指示灯,按规则选择数字</p>
321
+
322
+ <div class="score-board">
323
+ <div class="score-label">当前分数</div>
324
+ <div class="score-value" id="scoreDisplay">100</div>
325
+ <div class="round-info">
326
+ <span>回合: <span id="roundDisplay">1</span>/10</span>
327
+ <span>本轮: <span id="roundScoreDisplay">0</span></span>
328
+ </div>
329
+ </div>
330
+
331
+ <!-- 指示灯 -->
332
+ <div class="indicator-container">
333
+ <div>
334
+ <div class="indicator-light inactive" id="greenLight"></div>
335
+ <div class="indicator-label">选最大</div>
336
+ </div>
337
+ <div>
338
+ <div class="indicator-light inactive" id="redLight"></div>
339
+ <div class="indicator-label">选最小</div>
340
+ </div>
341
+ <div>
342
+ <div class="indicator-light inactive" id="yellowLight"></div>
343
+ <div class="indicator-label">选中间</div>
344
+ </div>
345
+ </div>
346
+
347
+ <div class="instruction" id="instructionText">
348
+ 📌 观察指示灯,按照规则选择数字
349
+ </div>
350
+
351
+ <div class="feedback" id="feedback"></div>
352
+
353
+ <div class="cards-container" id="cardsContainer">
354
+ <!-- 卡片将由 JavaScript 生成 -->
355
+ </div>
356
+
357
+ <button class="next-button" id="nextButton" onclick="nextRound()" disabled>
358
+ 下一轮 →
359
+ </button>
360
+ </div>
361
+
362
+ <div id="gameOverView" style="display: none;">
363
+ <div class="game-over">
364
+ <h1 class="game-over-title">🎉 游戏结束</h1>
365
+ <div class="final-score" id="finalScore">100</div>
366
+
367
+ <div class="stats">
368
+ <div class="stats-row">
369
+ <span>初始分数:</span>
370
+ <span>100</span>
371
+ </div>
372
+ <div class="stats-row">
373
+ <span>最终分数:</span>
374
+ <span id="finalScoreText">100</span>
375
+ </div>
376
+ <div class="stats-row">
377
+ <span>分数变化:</span>
378
+ <span id="scoreChange" style="font-weight: bold;">0</span>
379
+ </div>
380
+ <div class="stats-row">
381
+ <span>正确次数:</span>
382
+ <span id="correctCount">0</span>
383
+ </div>
384
+ <div class="stats-row">
385
+ <span>错误次数:</span>
386
+ <span id="wrongCount">0</span>
387
+ </div>
388
+ </div>
389
+
390
+ <button class="restart-button" onclick="restartGame()">
391
+ 🔄 重新开始
392
+ </button>
393
+ </div>
394
+ </div>
395
+ </div>
396
+
397
+ <script>
398
+ // 游戏状态
399
+ let score = 100;
400
+ let round = 1;
401
+ let maxRounds = 10;
402
+ let currentNumbers = [];
403
+ let selectedIndex = null;
404
+ let roundScore = 0;
405
+ let correctCount = 0;
406
+ let wrongCount = 0;
407
+ let currentRule = null; // 'max', 'min', 'mid'
408
+
409
+ // 初始化游戏
410
+ function initGame() {
411
+ score = 100;
412
+ round = 1;
413
+ selectedIndex = null;
414
+ roundScore = 0;
415
+ correctCount = 0;
416
+ wrongCount = 0;
417
+ generateNumbers();
418
+ updateDisplay();
419
+ document.getElementById('gameView').style.display = 'block';
420
+ document.getElementById('gameOverView').style.display = 'none';
421
+ }
422
+
423
+ // 生成随机数字和规则
424
+ function generateNumbers() {
425
+ currentNumbers = [];
426
+ const usedNumbers = new Set();
427
+
428
+ // 生成3个不重复的数字
429
+ while (currentNumbers.length < 3) {
430
+ const num = Math.floor(Math.random() * 9) + 1;
431
+ if (!usedNumbers.has(num)) {
432
+ currentNumbers.push(num);
433
+ usedNumbers.add(num);
434
+ }
435
+ }
436
+
437
+ // 随机选择规则
438
+ const rules = ['max', 'min', 'mid'];
439
+ currentRule = rules[Math.floor(Math.random() * rules.length)];
440
+
441
+ updateIndicators();
442
+ renderCards();
443
+ }
444
+
445
+ // 更新指示灯
446
+ function updateIndicators() {
447
+ const greenLight = document.getElementById('greenLight');
448
+ const redLight = document.getElementById('redLight');
449
+ const yellowLight = document.getElementById('yellowLight');
450
+
451
+ // 重置所有灯
452
+ greenLight.className = 'indicator-light inactive';
453
+ redLight.className = 'indicator-light inactive';
454
+ yellowLight.className = 'indicator-light inactive';
455
+
456
+ // 激活对应的灯
457
+ if (currentRule === 'max') {
458
+ greenLight.className = 'indicator-light green active';
459
+ } else if (currentRule === 'min') {
460
+ redLight.className = 'indicator-light red active';
461
+ } else if (currentRule === 'mid') {
462
+ yellowLight.className = 'indicator-light yellow active';
463
+ }
464
+ }
465
+
466
+ // 渲染卡片
467
+ function renderCards() {
468
+ const container = document.getElementById('cardsContainer');
469
+ container.innerHTML = '';
470
+
471
+ const labels = ['a', 'b', 'c'];
472
+ currentNumbers.forEach((num, index) => {
473
+ const card = document.createElement('div');
474
+ card.className = 'card';
475
+ card.innerHTML = `
476
+ <div class="card-number">${num}</div>
477
+ <div class="card-label">选项 ${labels[index]}</div>
478
+ `;
479
+ card.onclick = () => selectCard(index);
480
+ container.appendChild(card);
481
+ });
482
+
483
+ selectedIndex = null;
484
+ document.getElementById('nextButton').disabled = true;
485
+ document.getElementById('feedback').textContent = '';
486
+ document.getElementById('feedback').className = 'feedback';
487
+ }
488
+
489
+ // 选择卡片
490
+ function selectCard(index) {
491
+ if (selectedIndex !== null) return; // 已选择,不能重复选
492
+
493
+ selectedIndex = index;
494
+ const selected = currentNumbers[index];
495
+ const maxNum = Math.max(...currentNumbers);
496
+ const minNum = Math.min(...currentNumbers);
497
+
498
+ // 计算中间值:排序后取中间位置
499
+ const sortedNumbers = [...currentNumbers].sort((a, b) => a - b);
500
+ const midNum = sortedNumbers[1]; // 3个数字,中间位置是索引1
501
+
502
+ // 根据规则判断正确答案
503
+ let correctNum;
504
+ let ruleName;
505
+ if (currentRule === 'max') {
506
+ correctNum = maxNum;
507
+ ruleName = '最大';
508
+ } else if (currentRule === 'min') {
509
+ correctNum = minNum;
510
+ ruleName = '最小';
511
+ } else {
512
+ correctNum = midNum;
513
+ ruleName = '中间';
514
+ }
515
+
516
+ // 计算奖励
517
+ if (selected === correctNum) {
518
+ roundScore = 10;
519
+ showFeedback('correct', `✓ 正确!按规则选择了${ruleName}数字 ${selected},+10 分`);
520
+ correctCount++;
521
+ } else {
522
+ roundScore = -10;
523
+ showFeedback('wrong', `✗ 错误!应该选择${ruleName}数字 ${correctNum},-10 分`);
524
+ wrongCount++;
525
+ }
526
+
527
+ // 更新卡片样式
528
+ const cards = document.querySelectorAll('.card');
529
+ cards[index].classList.add('selected');
530
+
531
+ if (selected === correctNum) {
532
+ cards[index].classList.add('correct');
533
+ } else {
534
+ cards[index].classList.add('wrong');
535
+ }
536
+
537
+ // 显示正确答案
538
+ currentNumbers.forEach((num, i) => {
539
+ if (i !== index && num === correctNum) {
540
+ cards[i].classList.add('correct');
541
+ }
542
+ });
543
+
544
+ score += roundScore;
545
+ updateDisplay();
546
+ document.getElementById('nextButton').disabled = false;
547
+ }
548
+
549
+ // 显示反馈
550
+ function showFeedback(type, message) {
551
+ const feedback = document.getElementById('feedback');
552
+ feedback.textContent = message;
553
+ feedback.className = `feedback ${type}`;
554
+ }
555
+
556
+ // 更新显示
557
+ function updateDisplay() {
558
+ document.getElementById('scoreDisplay').textContent = score;
559
+ document.getElementById('roundDisplay').textContent = round;
560
+ document.getElementById('roundScoreDisplay').textContent =
561
+ roundScore > 0 ? `+${roundScore}` : roundScore;
562
+ }
563
+
564
+ // 下一轮
565
+ function nextRound() {
566
+ round++;
567
+ roundScore = 0;
568
+
569
+ if (round > maxRounds) {
570
+ gameOver();
571
+ } else {
572
+ generateNumbers();
573
+ updateDisplay();
574
+ }
575
+ }
576
+
577
+ // 游戏结束
578
+ function gameOver() {
579
+ document.getElementById('gameView').style.display = 'none';
580
+ document.getElementById('gameOverView').style.display = 'block';
581
+
582
+ document.getElementById('finalScore').textContent = score;
583
+ document.getElementById('finalScoreText').textContent = score;
584
+
585
+ const change = score - 100;
586
+ const changeElement = document.getElementById('scoreChange');
587
+ changeElement.textContent = change > 0 ? `+${change}` : change;
588
+ changeElement.style.color = change > 0 ? '#38ef7d' : '#f45c43';
589
+
590
+ document.getElementById('correctCount').textContent = correctCount;
591
+ document.getElementById('wrongCount').textContent = wrongCount;
592
+ }
593
+
594
+ // 重新开始
595
+ function restartGame() {
596
+ initGame();
597
+ }
598
+
599
+ // 页面加载时初始化
600
+ window.onload = initGame;
601
+ </script>
602
+ </body>
603
+ </html>
EasyR1/examples/android_gui_cookbook/vlm_client.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ VLM 模型客户端
3
+
4
+ 支持 Ollama 和 vLLM 两种模型服务
5
+ """
6
+
7
+ import base64
8
+ from io import BytesIO
9
+
10
+ import requests
11
+ from PIL import Image
12
+
13
+
14
+ class VLMClient:
15
+ """VLM 模型客户端(支持 Ollama 和 vLLM)"""
16
+
17
+ def __init__(self, model_type: str, api_url: str, model_name: str):
18
+ """
19
+ Args:
20
+ model_type: "ollama" 或 "vllm"
21
+ api_url: API 地址,如 "http://localhost:11434" 或 "http://localhost:8000"
22
+ model_name: 模型名称
23
+ """
24
+ self.model_type = model_type.lower()
25
+ self.api_url = api_url.rstrip("/")
26
+ self.model_name = model_name
27
+
28
+ if self.model_type not in ["ollama", "vllm"]:
29
+ raise ValueError(f"不支持的模型类型: {model_type}, 仅支持 'ollama' 或 'vllm'")
30
+
31
+ def _image_to_base64(self, image: Image.Image) -> str:
32
+ """将 PIL Image 转换为 base64 字符串"""
33
+ buffered = BytesIO()
34
+ image.save(buffered, format="PNG")
35
+ img_bytes = buffered.getvalue()
36
+ img_base64 = base64.b64encode(img_bytes).decode("utf-8")
37
+ return img_base64
38
+
39
+ def query(self, image: Image.Image, prompt: str) -> str:
40
+ """
41
+ 查询 VLM 模型
42
+
43
+ Args:
44
+ image: PIL Image 对象
45
+ prompt: 文本提示
46
+
47
+ Returns:
48
+ 模型响应文本
49
+ """
50
+ img_base64 = self._image_to_base64(image)
51
+
52
+ if self.model_type == "ollama":
53
+ return self._query_ollama(img_base64, prompt)
54
+ elif self.model_type == "vllm":
55
+ return self._query_vllm(img_base64, prompt)
56
+
57
+ def _query_ollama(self, img_base64: str, prompt: str) -> str:
58
+ """查询 Ollama API"""
59
+ try:
60
+ payload = {"model": self.model_name, "prompt": prompt, "images": [img_base64], "stream": False}
61
+
62
+ response = requests.post(f"{self.api_url}/api/generate", json=payload, timeout=60)
63
+
64
+ if response.status_code == 200:
65
+ result = response.json()
66
+ return result.get("response", "")
67
+ else:
68
+ print(f"⚠ Ollama API 错误: {response.status_code}")
69
+ return ""
70
+ except Exception as e:
71
+ print(f"⚠ Ollama 查询失败: {e}")
72
+ return ""
73
+
74
+ def _query_vllm(self, img_base64: str, prompt: str) -> str:
75
+ """查询 vLLM API (OpenAI compatible)"""
76
+ try:
77
+ payload = {
78
+ "model": self.model_name,
79
+ "messages": [
80
+ {
81
+ "role": "user",
82
+ "content": [
83
+ {"type": "text", "text": prompt},
84
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_base64}"}},
85
+ ],
86
+ }
87
+ ],
88
+ "max_tokens": 512,
89
+ "temperature": 0.7,
90
+ }
91
+
92
+ response = requests.post(
93
+ f"{self.api_url}/v1/chat/completions",
94
+ json=payload,
95
+ headers={"Content-Type": "application/json"},
96
+ timeout=60,
97
+ )
98
+
99
+ if response.status_code == 200:
100
+ result = response.json()
101
+ return result["choices"][0]["message"]["content"]
102
+ else:
103
+ print(f"⚠ vLLM API 错误: {response.status_code}")
104
+ return ""
105
+ except Exception as e:
106
+ print(f"⚠ vLLM 查询失败: {e}")
107
+ return ""
EasyR1/examples/baselines/qwen2_5_vl_3b_clevr.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ set -x
4
+
5
+ export PYTHONUNBUFFERED=1
6
+
7
+ MODEL_PATH=Qwen/Qwen2.5-VL-3B-Instruct # replace it with your local file path
8
+
9
+ python3 -m verl.trainer.main \
10
+ config=examples/config.yaml \
11
+ data.train_files=BUAADreamer/clevr_count_70k@train \
12
+ data.val_files=BUAADreamer/clevr_count_70k@test \
13
+ data.format_prompt=./examples/format_prompt/r1v.jinja \
14
+ worker.actor.model.model_path=${MODEL_PATH} \
15
+ worker.rollout.tensor_parallel_size=1 \
16
+ worker.reward.reward_function=./examples/reward_function/r1v.py:compute_score \
17
+ trainer.experiment_name=qwen2_5_vl_3b_clevr \
18
+ trainer.n_gpus_per_node=2
EasyR1/examples/baselines/qwen2_5_vl_3b_geoqa8k.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ set -x
4
+
5
+ export PYTHONUNBUFFERED=1
6
+
7
+ MODEL_PATH=Qwen/Qwen2.5-VL-3B-Instruct # replace it with your local file path
8
+
9
+ python3 -m verl.trainer.main \
10
+ config=examples/config.yaml \
11
+ data.train_files=leonardPKU/GEOQA_8K_R1V@train \
12
+ data.val_files=leonardPKU/GEOQA_8K_R1V@test \
13
+ data.format_prompt=./examples/format_prompt/r1v.jinja \
14
+ worker.actor.model.model_path=${MODEL_PATH} \
15
+ worker.rollout.tensor_parallel_size=1 \
16
+ worker.reward.reward_function=./examples/reward_function/r1v.py:compute_score \
17
+ trainer.experiment_name=qwen2_5_vl_3b_geoqa8k \
18
+ trainer.n_gpus_per_node=8
EasyR1/examples/format_prompt/dapo.jinja ADDED
@@ -0,0 +1 @@
 
 
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:".
EasyR1/examples/format_prompt/math.jinja ADDED
@@ -0,0 +1 @@
 
 
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 <think> </think> tags. The final answer MUST BE put in \boxed{}.
EasyR1/examples/format_prompt/r1v.jinja ADDED
@@ -0,0 +1 @@
 
 
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 <think> </think> and <answer> </answer> tags, respectively, i.e., <think> reasoning process here </think><answer> answer here </answer>
EasyR1/examples/reward_function/android_gui.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Number Game Reward Function
3
+
4
+ 评分规则:
5
+ - 选择正确的数字: +1.0
6
+ - 选择错误的数字: 0.0
7
+
8
+ 输入格式:
9
+ reward_input = {
10
+ "response": "1", # 模型输出的答案 (0/1/2)
11
+ "response_length": 10, # 响应长度(token数)
12
+ "ground_truth": "1" # 正确答案 (0/1/2)
13
+ }
14
+
15
+ 输出格式:
16
+ {
17
+ "overall": 1.0, # 总分(必需字段)
18
+ "accuracy": 1.0 # 准确率(可选,用于监控)
19
+ }
20
+ """
21
+
22
+ import re
23
+ from typing import Any
24
+
25
+
26
+ # Metadata - EasyR1框架要求
27
+ REWARD_NAME = "number_game"
28
+ REWARD_TYPE = "batch" # 批量处理模式
29
+
30
+
31
+ def extract_answer(response: str) -> str:
32
+ """
33
+ 从模型响应中提取答案索引
34
+
35
+ Args:
36
+ response: 模型的原始响应
37
+
38
+ Returns:
39
+ "0", "1", "2" 或 ""(提取失败)
40
+ """
41
+ # 情况1: 响应本身就是单个数字
42
+ response = response.strip()
43
+ if response in ["0", "1", "2"]:
44
+ return response
45
+
46
+ # 情况2: 响应包含多余文字,提取第一个出现的0/1/2
47
+ match = re.search(r"[012]", response)
48
+ if match:
49
+ return match.group(0)
50
+
51
+ # 提取失败
52
+ return ""
53
+
54
+
55
+ def compute_score(reward_inputs: list[dict[str, Any]]) -> list[dict[str, float]]:
56
+ """
57
+ 计算一批样本的得分
58
+
59
+ Args:
60
+ reward_inputs: 包含多个样本的列表,每个样本包含:
61
+ - response: 模型的响应
62
+ - response_length: 响应长度
63
+ - ground_truth: 正确答案
64
+
65
+ Returns:
66
+ 每个样本的得分字典列表,包含:
67
+ - overall: 总分(1.0表示正确,0.0表示错误)
68
+ - accuracy: 准确率(同overall,用于监控)
69
+ """
70
+ scores = []
71
+
72
+ for reward_input in reward_inputs:
73
+ response = reward_input.get("response", "")
74
+ ground_truth = reward_input.get("ground_truth", "")
75
+
76
+ # 提取答案
77
+ predicted = extract_answer(response)
78
+
79
+ # 计算得分
80
+ if predicted == ground_truth:
81
+ score = 1.0
82
+ else:
83
+ score = 0.0
84
+
85
+ # 返回格式:必须包含overall字段
86
+ scores.append({"overall": score, "accuracy": score})
87
+
88
+ return scores
89
+
90
+
91
+ # 测试用例
92
+ if __name__ == "__main__":
93
+ test_cases = [
94
+ # 完美匹配
95
+ {"response": "0", "response_length": 1, "ground_truth": "0"},
96
+ {"response": "1", "response_length": 1, "ground_truth": "1"},
97
+ {"response": "2", "response_length": 1, "ground_truth": "2"},
98
+ # 响应包含额外文字
99
+ {"response": "The answer is 1", "response_length": 15, "ground_truth": "1"},
100
+ {"response": "I choose option 2", "response_length": 18, "ground_truth": "2"},
101
+ # 错误答案
102
+ {"response": "0", "response_length": 1, "ground_truth": "1"},
103
+ {"response": "2", "response_length": 1, "ground_truth": "0"},
104
+ # 提取失败
105
+ {"response": "I don't know", "response_length": 12, "ground_truth": "1"},
106
+ {"response": "", "response_length": 0, "ground_truth": "2"},
107
+ ]
108
+
109
+ scores = compute_score(test_cases)
110
+
111
+ print("Reward Function Test Results:")
112
+ print("=" * 60)
113
+ for i, (test, score) in enumerate(zip(test_cases, scores), 1):
114
+ print(f"{i}. Response: {test['response']!r}")
115
+ print(f" Ground Truth: {test['ground_truth']!r}")
116
+ print(f" Score: {score}")
117
+ print()
EasyR1/examples/reward_function/dapo.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ from typing import Any
17
+
18
+
19
+ # Metadata
20
+ REWARD_NAME = "dapo"
21
+ REWARD_TYPE = "batch"
22
+
23
+
24
+ # Constants for normalization
25
+ SUBSTITUTIONS = [
26
+ ("an ", ""),
27
+ ("a ", ""),
28
+ (".$", "$"),
29
+ ("\\$", ""),
30
+ (r"\ ", ""),
31
+ (" ", ""),
32
+ ("mbox", "text"),
33
+ (",\\text{and}", ","),
34
+ ("\\text{and}", ","),
35
+ ("\\text{m}", "\\text{}"),
36
+ ]
37
+
38
+ REMOVED_EXPRESSIONS = [
39
+ "square",
40
+ "ways",
41
+ "integers",
42
+ "dollars",
43
+ "mph",
44
+ "inches",
45
+ "hours",
46
+ "km",
47
+ "units",
48
+ "\\ldots",
49
+ "sue",
50
+ "points",
51
+ "feet",
52
+ "minutes",
53
+ "digits",
54
+ "cents",
55
+ "degrees",
56
+ "cm",
57
+ "gm",
58
+ "pounds",
59
+ "meters",
60
+ "meals",
61
+ "edges",
62
+ "students",
63
+ "childrentickets",
64
+ "multiples",
65
+ "\\text{s}",
66
+ "\\text{.}",
67
+ "\\text{\ns}",
68
+ "\\text{}^2",
69
+ "\\text{}^3",
70
+ "\\text{\n}",
71
+ "\\text{}",
72
+ r"\mathrm{th}",
73
+ r"^\circ",
74
+ r"^{\circ}",
75
+ r"\;",
76
+ r",\!",
77
+ "{,}",
78
+ '"',
79
+ "\\dots",
80
+ ]
81
+
82
+
83
+ def normalize_final_answer(final_answer: str) -> str:
84
+ """Normalize a final answer to a quantitative reasoning question.
85
+
86
+ Args:
87
+ final_answer: The answer string to normalize
88
+
89
+ Returns:
90
+ Normalized answer string
91
+ """
92
+ final_answer = final_answer.split("=")[-1]
93
+
94
+ # Apply substitutions and removals
95
+ for before, after in SUBSTITUTIONS:
96
+ final_answer = final_answer.replace(before, after)
97
+ for expr in REMOVED_EXPRESSIONS:
98
+ final_answer = final_answer.replace(expr, "")
99
+
100
+ # Extract and normalize LaTeX math
101
+ final_answer = re.sub(r"(.*?)(\$)(.*?)(\$)(.*)", "$\\3$", final_answer)
102
+ final_answer = re.sub(r"(\\text\{)(.*?)(\})", "\\2", final_answer)
103
+ final_answer = re.sub(r"(\\textbf\{)(.*?)(\})", "\\2", final_answer)
104
+ final_answer = re.sub(r"(\\overline\{)(.*?)(\})", "\\2", final_answer)
105
+ final_answer = re.sub(r"(\\boxed\{)(.*)(\})", "\\2", final_answer)
106
+
107
+ # Normalize shorthand TeX:
108
+ # \fracab -> \frac{a}{b}
109
+ # \frac{abc}{bef} -> \frac{abc}{bef}
110
+ # \fracabc -> \frac{a}{b}c
111
+ # \sqrta -> \sqrt{a}
112
+ # \sqrtab -> sqrt{a}b
113
+ final_answer = re.sub(r"(frac)([^{])(.)", "frac{\\2}{\\3}", final_answer)
114
+ final_answer = re.sub(r"(sqrt)([^{])", "sqrt{\\2}", final_answer)
115
+ final_answer = final_answer.replace("$", "")
116
+
117
+ # Normalize numbers
118
+ if final_answer.replace(",", "").isdigit():
119
+ final_answer = final_answer.replace(",", "")
120
+
121
+ return final_answer.strip()
122
+
123
+
124
+ def accuracy_reward(response: str, ground_truth: str) -> float:
125
+ match = re.findall(r"(?i)Answer\s*:\s*([^\n]+)", response)
126
+ answer = match[-1] if match else "[INVALID]"
127
+ if normalize_final_answer(answer) == normalize_final_answer(ground_truth):
128
+ return 1.0
129
+ else:
130
+ return -1.0
131
+
132
+
133
+ def soft_overlong_punishment(response_length: int, max_response_length: int, overlong_buffer_length: int):
134
+ expected_len = max_response_length - overlong_buffer_length
135
+ if response_length <= expected_len:
136
+ return 0.0
137
+ elif response_length <= max_response_length:
138
+ return (expected_len - response_length) / overlong_buffer_length
139
+ else:
140
+ return -1.0
141
+
142
+
143
+ def compute_score(
144
+ reward_inputs: list[dict[str, Any]],
145
+ max_response_length: int,
146
+ overlong_buffer_length: int,
147
+ overlong_penalty_factor: float,
148
+ ) -> list[dict[str, float]]:
149
+ scores = []
150
+ for reward_input in reward_inputs:
151
+ response = reward_input["response"][-300:] # The longest answer in MATH-500 has 159 characters
152
+ accuracy_score = accuracy_reward(response, reward_input["ground_truth"])
153
+ overlong_score = soft_overlong_punishment(
154
+ reward_input["response_length"], max_response_length, overlong_buffer_length
155
+ )
156
+ scores.append(
157
+ {
158
+ "overall": accuracy_score + overlong_score * overlong_penalty_factor,
159
+ "accuracy": accuracy_score,
160
+ "overlong": overlong_score,
161
+ "accuracy_normalized": 0.5 * (accuracy_score + 1.0),
162
+ }
163
+ )
164
+
165
+ return scores
EasyR1/examples/reward_function/file_queue_judge_worker.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import socket
7
+ import sys
8
+ import time
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+
14
+ CURRENT_DIR = Path(__file__).resolve().parent
15
+ if str(CURRENT_DIR) not in sys.path:
16
+ sys.path.insert(0, str(CURRENT_DIR))
17
+
18
+ from paper_conclusion_judge_common import score_prepared_item_via_http
19
+
20
+
21
+ DEFAULT_QUEUE_ROOT = CURRENT_DIR.parent.parent / "shared_judge_queue"
22
+
23
+
24
+ def queue_dirs(queue_root: Path) -> dict[str, Path]:
25
+ requests_dir = queue_root / "requests"
26
+ results_dir = queue_root / "results"
27
+ return {
28
+ "pending": requests_dir / "pending",
29
+ "processing": requests_dir / "processing",
30
+ "ok": results_dir / "ok",
31
+ "error": results_dir / "error",
32
+ }
33
+
34
+
35
+ def ensure_queue_dirs(queue_root: Path) -> dict[str, Path]:
36
+ dirs = queue_dirs(queue_root)
37
+ for directory in dirs.values():
38
+ directory.mkdir(parents=True, exist_ok=True)
39
+ return dirs
40
+
41
+
42
+ def atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ tmp_path = path.with_name(path.name + ".tmp")
45
+ with tmp_path.open("w", encoding="utf-8") as f:
46
+ json.dump(payload, f, ensure_ascii=False)
47
+ os.replace(tmp_path, path)
48
+
49
+
50
+ def read_json(path: Path) -> dict[str, Any]:
51
+ with path.open("r", encoding="utf-8") as f:
52
+ return json.load(f)
53
+
54
+
55
+ def claim_pending_request(dirs: dict[str, Path]) -> Path | None:
56
+ for pending_path in sorted(dirs["pending"].glob("*.json")):
57
+ claimed_path = dirs["processing"] / pending_path.name
58
+ try:
59
+ os.replace(pending_path, claimed_path)
60
+ return claimed_path
61
+ except FileNotFoundError:
62
+ continue
63
+ return None
64
+
65
+
66
+ def recover_stale_requests(dirs: dict[str, Path], stale_processing_timeout: float) -> None:
67
+ if stale_processing_timeout <= 0:
68
+ return
69
+
70
+ now = time.time()
71
+ for processing_path in dirs["processing"].glob("*.json"):
72
+ result_ok_path = dirs["ok"] / processing_path.name
73
+ result_error_path = dirs["error"] / processing_path.name
74
+ if result_ok_path.exists() or result_error_path.exists():
75
+ continue
76
+
77
+ age_seconds = now - processing_path.stat().st_mtime
78
+ if age_seconds <= stale_processing_timeout:
79
+ continue
80
+
81
+ recovered_path = dirs["pending"] / processing_path.name
82
+ try:
83
+ os.replace(processing_path, recovered_path)
84
+ print(f"Recovered stale request {processing_path.name} back to pending.")
85
+ except FileNotFoundError:
86
+ continue
87
+
88
+
89
+ def process_request(
90
+ request_path: Path,
91
+ dirs: dict[str, Path],
92
+ *,
93
+ base_url: str,
94
+ model: str,
95
+ api_key: str,
96
+ timeout: float,
97
+ max_retries: int,
98
+ max_workers: int,
99
+ format_weight: float,
100
+ fallback_judge_score: float,
101
+ suppress_judge_errors: bool,
102
+ worker_name: str,
103
+ ) -> None:
104
+ request_payload = read_json(request_path)
105
+ request_id = str(request_payload["request_id"])
106
+ items = request_payload.get("items", [])
107
+ judge_config = request_payload.get("judge_config", {})
108
+ if not isinstance(items, list) or not items:
109
+ raise RuntimeError(f"Request {request_id} does not contain any items.")
110
+
111
+ worker_count = max(1, min(max_workers, len(items)))
112
+ request_model = str(judge_config.get("model") or model)
113
+ request_format_weight = float(judge_config.get("format_weight", format_weight))
114
+
115
+ def score_item(item: dict[str, Any]) -> dict[str, Any]:
116
+ score = score_prepared_item_via_http(
117
+ item,
118
+ base_url=base_url,
119
+ model=request_model,
120
+ api_key=api_key,
121
+ timeout=timeout,
122
+ max_retries=max_retries,
123
+ format_weight=request_format_weight,
124
+ fallback_judge_score=fallback_judge_score,
125
+ suppress_judge_errors=suppress_judge_errors,
126
+ )
127
+ return {"item_id": int(item["item_id"]), "score": score}
128
+
129
+ if worker_count == 1:
130
+ scores = [score_item(item) for item in items]
131
+ else:
132
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
133
+ futures = [executor.submit(score_item, item) for item in items]
134
+ scores = [future.result() for future in futures]
135
+
136
+ scores.sort(key=lambda item: item["item_id"])
137
+ result_payload = {
138
+ "request_id": request_id,
139
+ "status": "ok",
140
+ "processed_at": time.time(),
141
+ "worker": {
142
+ "host": socket.gethostname(),
143
+ "pid": os.getpid(),
144
+ "name": worker_name,
145
+ },
146
+ "scores": scores,
147
+ }
148
+ atomic_write_json(dirs["ok"] / f"{request_id}.json", result_payload)
149
+
150
+
151
+ def parse_args() -> argparse.Namespace:
152
+ parser = argparse.ArgumentParser(description="Process shared-directory judge requests for EasyR1 reward scoring.")
153
+ parser.add_argument("--queue-root", default=str(DEFAULT_QUEUE_ROOT))
154
+ parser.add_argument("--base-url", default="http://127.0.0.1:8000/v1")
155
+ parser.add_argument("--model", default="qwen3-4b-judge")
156
+ parser.add_argument("--api-key", default=None)
157
+ parser.add_argument("--api-key-env", default="OPENAI_API_KEY")
158
+ parser.add_argument("--timeout", type=float, default=120.0)
159
+ parser.add_argument("--max-retries", type=int, default=2)
160
+ parser.add_argument("--max-workers", type=int, default=8)
161
+ parser.add_argument("--format-weight", type=float, default=0.05)
162
+ parser.add_argument("--fallback-judge-score", type=float, default=0.0)
163
+ parser.add_argument("--poll-interval", type=float, default=0.25)
164
+ parser.add_argument("--poll-interval-max", type=float, default=1.0)
165
+ parser.add_argument("--stale-processing-timeout", type=float, default=1800.0)
166
+ parser.add_argument("--worker-name", default=socket.gethostname())
167
+ return parser.parse_args()
168
+
169
+
170
+ def main() -> int:
171
+ args = parse_args()
172
+ queue_root = Path(args.queue_root).expanduser().resolve()
173
+ dirs = ensure_queue_dirs(queue_root)
174
+ api_key = args.api_key if args.api_key is not None else os.environ.get(args.api_key_env, "EMPTY")
175
+
176
+ idle_sleep = args.poll_interval
177
+ print(f"Watching queue at {queue_root}")
178
+
179
+ while True:
180
+ recover_stale_requests(dirs, args.stale_processing_timeout)
181
+ request_path = claim_pending_request(dirs)
182
+ if request_path is None:
183
+ time.sleep(idle_sleep)
184
+ idle_sleep = min(args.poll_interval_max, max(args.poll_interval, idle_sleep * 2))
185
+ continue
186
+
187
+ idle_sleep = args.poll_interval
188
+ try:
189
+ process_request(
190
+ request_path,
191
+ dirs,
192
+ base_url=args.base_url,
193
+ model=args.model,
194
+ api_key=api_key,
195
+ timeout=args.timeout,
196
+ max_retries=args.max_retries,
197
+ max_workers=args.max_workers,
198
+ format_weight=args.format_weight,
199
+ fallback_judge_score=args.fallback_judge_score,
200
+ suppress_judge_errors=True,
201
+ worker_name=args.worker_name,
202
+ )
203
+ print(f"Processed request {request_path.stem}")
204
+ except Exception as exc:
205
+ request_id = request_path.stem
206
+ error_payload = {
207
+ "request_id": request_id,
208
+ "status": "error",
209
+ "processed_at": time.time(),
210
+ "worker": {
211
+ "host": socket.gethostname(),
212
+ "pid": os.getpid(),
213
+ "name": args.worker_name,
214
+ },
215
+ "error": repr(exc),
216
+ }
217
+ atomic_write_json(dirs["error"] / f"{request_id}.json", error_payload)
218
+ print(f"Failed request {request_id}: {exc}")
219
+ finally:
220
+ try:
221
+ request_path.unlink()
222
+ except FileNotFoundError:
223
+ pass
224
+
225
+
226
+ if __name__ == "__main__":
227
+ raise SystemExit(main())
EasyR1/examples/reward_function/math.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ from typing import Any
17
+
18
+ from mathruler.grader import extract_boxed_content, grade_answer
19
+
20
+
21
+ # Metadata
22
+ REWARD_NAME = "math"
23
+ REWARD_TYPE = "batch"
24
+
25
+
26
+ def format_reward(response: str) -> float:
27
+ pattern = re.compile(r"<think>.*</think>.*\\boxed\{.*\}.*", re.DOTALL)
28
+ format_match = re.fullmatch(pattern, response)
29
+ return 1.0 if format_match else 0.0
30
+
31
+
32
+ def accuracy_reward(response: str, ground_truth: str) -> float:
33
+ answer = extract_boxed_content(response)
34
+ return 1.0 if grade_answer(answer, ground_truth) else 0.0
35
+
36
+
37
+ def compute_score(reward_inputs: list[dict[str, Any]], format_weight: float = 0.1) -> list[dict[str, float]]:
38
+ scores = []
39
+ for reward_input in reward_inputs:
40
+ response = re.sub(r"\s*(<|>|/)\s*", r"\1", reward_input["response"]) # handle qwen2.5vl-32b format
41
+ format_score = format_reward(response)
42
+ accuracy_score = accuracy_reward(response, reward_input["ground_truth"])
43
+ scores.append(
44
+ {
45
+ "overall": (1 - format_weight) * accuracy_score + format_weight * format_score,
46
+ "format": format_score,
47
+ "accuracy": accuracy_score,
48
+ }
49
+ )
50
+
51
+ return scores
EasyR1/examples/reward_function/paper_conclusion_file_queue_judge.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import socket
4
+ import sys
5
+ import time
6
+ import uuid
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ CURRENT_DIR = Path(__file__).resolve().parent
12
+ if str(CURRENT_DIR) not in sys.path:
13
+ sys.path.insert(0, str(CURRENT_DIR))
14
+
15
+ from paper_conclusion_judge_common import get_cached_score, prepare_reward_item, store_cached_score
16
+
17
+
18
+ REWARD_NAME = "paper_conclusion_file_queue_judge"
19
+ REWARD_TYPE = "batch"
20
+
21
+ DEFAULT_QUEUE_ROOT = CURRENT_DIR.parent.parent / "shared_judge_queue"
22
+
23
+
24
+ def _queue_dirs(queue_root: Path) -> dict[str, Path]:
25
+ requests_dir = queue_root / "requests"
26
+ results_dir = queue_root / "results"
27
+ return {
28
+ "pending": requests_dir / "pending",
29
+ "processing": requests_dir / "processing",
30
+ "ok": results_dir / "ok",
31
+ "error": results_dir / "error",
32
+ }
33
+
34
+
35
+ def _ensure_queue_dirs(queue_root: Path) -> dict[str, Path]:
36
+ dirs = _queue_dirs(queue_root)
37
+ for directory in dirs.values():
38
+ directory.mkdir(parents=True, exist_ok=True)
39
+ return dirs
40
+
41
+
42
+ def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ tmp_path = path.with_name(path.name + ".tmp")
45
+ with tmp_path.open("w", encoding="utf-8") as f:
46
+ json.dump(payload, f, ensure_ascii=False)
47
+ os.replace(tmp_path, path)
48
+
49
+
50
+ def _read_json(path: Path) -> dict[str, Any]:
51
+ with path.open("r", encoding="utf-8") as f:
52
+ return json.load(f)
53
+
54
+
55
+ def _compute_wait_interval(
56
+ elapsed: float,
57
+ *,
58
+ poll_interval: float,
59
+ poll_interval_medium: float,
60
+ poll_interval_max: float,
61
+ poll_fast_seconds: float,
62
+ poll_medium_seconds: float,
63
+ ) -> float:
64
+ if elapsed < poll_fast_seconds:
65
+ return poll_interval
66
+ if elapsed < poll_medium_seconds:
67
+ return max(poll_interval, poll_interval_medium)
68
+ return max(poll_interval_medium, poll_interval_max)
69
+
70
+
71
+ def _normalize_score(score: dict[str, Any]) -> dict[str, float]:
72
+ return {
73
+ "overall": float(score["overall"]),
74
+ "format": float(score["format"]),
75
+ "judge": float(score["judge"]),
76
+ "matched": float(score["matched"]),
77
+ }
78
+
79
+
80
+ def compute_score(
81
+ reward_inputs: list[dict[str, Any]],
82
+ *,
83
+ queue_root: str = str(DEFAULT_QUEUE_ROOT),
84
+ model: str = "qwen3-4b-judge",
85
+ result_timeout: float = 1800.0,
86
+ poll_interval: float = 0.25,
87
+ poll_interval_medium: float = 0.5,
88
+ poll_interval_max: float = 1.0,
89
+ poll_fast_seconds: float = 10.0,
90
+ poll_medium_seconds: float = 60.0,
91
+ format_weight: float = 0.05,
92
+ experiment_name: str | None = None,
93
+ cleanup_results: bool = True,
94
+ **_: Any,
95
+ ) -> list[dict[str, float]]:
96
+ queue_root_path = Path(queue_root).expanduser().resolve()
97
+ dirs = _ensure_queue_dirs(queue_root_path)
98
+
99
+ final_scores: list[dict[str, float] | None] = [None] * len(reward_inputs)
100
+ pending_items: list[dict[str, Any]] = []
101
+ pending_cache_keys: dict[int, str | None] = {}
102
+
103
+ for item_id, reward_input in enumerate(reward_inputs):
104
+ prepared_item = prepare_reward_item(reward_input, model=model, format_weight=format_weight)
105
+ direct_score = prepared_item.get("direct_score")
106
+ if isinstance(direct_score, dict):
107
+ final_scores[item_id] = _normalize_score(direct_score)
108
+ continue
109
+
110
+ cache_key = prepared_item.get("cache_key")
111
+ cached_score = get_cached_score(cache_key)
112
+ if cached_score is not None:
113
+ final_scores[item_id] = _normalize_score(cached_score)
114
+ continue
115
+
116
+ pending_cache_keys[item_id] = cache_key
117
+ pending_items.append(
118
+ {
119
+ "item_id": item_id,
120
+ "paper_id": prepared_item["paper_id"],
121
+ "reference_conclusions": prepared_item["reference_conclusions"],
122
+ "predicted_conclusions": prepared_item["predicted_conclusions"],
123
+ "rubrics": prepared_item["rubrics"],
124
+ "format_score": float(prepared_item["format_score"]),
125
+ "cache_key": cache_key,
126
+ }
127
+ )
128
+
129
+ if not pending_items:
130
+ return [_normalize_score(score) for score in final_scores if score is not None]
131
+
132
+ request_id = str(uuid.uuid4())
133
+ request_path = dirs["pending"] / f"{request_id}.json"
134
+ ok_path = dirs["ok"] / f"{request_id}.json"
135
+ error_path = dirs["error"] / f"{request_id}.json"
136
+
137
+ request_payload = {
138
+ "request_id": request_id,
139
+ "version": 1,
140
+ "created_at": time.time(),
141
+ "source": {
142
+ "host": socket.gethostname(),
143
+ "pid": os.getpid(),
144
+ "experiment": experiment_name or os.environ.get("EXPERIMENT_NAME", ""),
145
+ },
146
+ "judge_config": {
147
+ "model": model,
148
+ "format_weight": format_weight,
149
+ },
150
+ "items": pending_items,
151
+ }
152
+ _atomic_write_json(request_path, request_payload)
153
+
154
+ start_time = time.time()
155
+ try:
156
+ while True:
157
+ if ok_path.exists():
158
+ result_payload = _read_json(ok_path)
159
+ if result_payload.get("request_id") != request_id:
160
+ raise RuntimeError(f"Mismatched result file for request {request_id}")
161
+ for item in result_payload.get("scores", []):
162
+ item_id = int(item["item_id"])
163
+ score = _normalize_score(item["score"])
164
+ final_scores[item_id] = score
165
+ store_cached_score(pending_cache_keys.get(item_id), score)
166
+
167
+ missing_ids = [idx for idx, score in enumerate(final_scores) if score is None]
168
+ if missing_ids:
169
+ raise RuntimeError(f"Missing scores for request {request_id}: {missing_ids}")
170
+
171
+ return [_normalize_score(score) for score in final_scores if score is not None]
172
+
173
+ if error_path.exists():
174
+ error_payload = _read_json(error_path)
175
+ raise RuntimeError(
176
+ f"Judge worker failed for request {request_id}: {error_payload.get('error', 'unknown error')}"
177
+ )
178
+
179
+ elapsed = time.time() - start_time
180
+ if elapsed > result_timeout:
181
+ raise TimeoutError(
182
+ f"Timed out waiting for judge result after {result_timeout:.1f}s for request {request_id}"
183
+ )
184
+
185
+ time.sleep(
186
+ _compute_wait_interval(
187
+ elapsed,
188
+ poll_interval=poll_interval,
189
+ poll_interval_medium=poll_interval_medium,
190
+ poll_interval_max=poll_interval_max,
191
+ poll_fast_seconds=poll_fast_seconds,
192
+ poll_medium_seconds=poll_medium_seconds,
193
+ )
194
+ )
195
+ finally:
196
+ if cleanup_results:
197
+ for result_path in (ok_path, error_path):
198
+ try:
199
+ result_path.unlink()
200
+ except FileNotFoundError:
201
+ pass
EasyR1/examples/reward_function/paper_conclusion_judge_common.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ import re
4
+ import threading
5
+ import time
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from typing import Any
8
+ from urllib import error, request
9
+
10
+
11
+ DEFAULT_RUBRIC = """You are evaluating whether the predicted conclusions for a single machine learning research paper match the reference conclusions.
12
+
13
+ You will be given all reference conclusions and all predicted conclusions for one paper.
14
+
15
+ Your task is to compare them and score the predictions strictly based on whether they express the same core scientific findings.
16
+
17
+ Matching rules:
18
+ - A predicted conclusion matches a reference conclusion only if they express the same core scientific finding.
19
+ - Ignore wording differences.
20
+ - Be strict: partial overlap, vagueness, or missing important qualifiers should NOT count as a match.
21
+ - Use one-to-one matching: each reference conclusion can match at most one predicted conclusion, and each predicted conclusion can match at most one reference conclusion.
22
+
23
+ Scoring rule:
24
+ - Let x be the number of reference conclusions.
25
+ - Let y be the number of predicted conclusions.
26
+ - Let a be the number of matched predicted conclusions.
27
+ - Let b = y - a.
28
+ - The final score is: max(0, a - b) / x.
29
+
30
+ Return the final score for this paper only."""
31
+
32
+ JSON_RESPONSE_SCHEMA = {
33
+ "matched_prediction_indices": [0],
34
+ "matched_reference_indices": [0],
35
+ "matched_count": 1,
36
+ "score": 0.5,
37
+ "reason": "brief explanation",
38
+ }
39
+
40
+ _CACHE_LOCK = threading.Lock()
41
+ _SCORE_CACHE: dict[str, dict[str, float]] = {}
42
+
43
+
44
+ def normalize_whitespace(text: str) -> str:
45
+ return re.sub(r"\s+", " ", text or "").strip()
46
+
47
+
48
+ def extract_answer_block(response: str) -> str:
49
+ match = re.search(r"<answer>(.*?)</answer>", response, re.DOTALL | re.IGNORECASE)
50
+ return match.group(1).strip() if match else response.strip()
51
+
52
+
53
+ def extract_json_object(text: str) -> dict[str, Any] | None:
54
+ text = text.strip()
55
+ if not text:
56
+ return None
57
+
58
+ candidates = [text]
59
+
60
+ fenced = re.findall(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL | re.IGNORECASE)
61
+ candidates.extend(fenced)
62
+
63
+ first = text.find("{")
64
+ last = text.rfind("}")
65
+ if first != -1 and last != -1 and last > first:
66
+ candidates.append(text[first : last + 1])
67
+
68
+ for candidate in candidates:
69
+ try:
70
+ loaded = json.loads(candidate)
71
+ except json.JSONDecodeError:
72
+ continue
73
+ if isinstance(loaded, dict):
74
+ return loaded
75
+
76
+ return None
77
+
78
+
79
+ def normalize_conclusions(items: Any) -> list[str]:
80
+ if not isinstance(items, list):
81
+ return []
82
+
83
+ normalized: list[str] = []
84
+ for item in items:
85
+ if not isinstance(item, str):
86
+ continue
87
+ text = normalize_whitespace(item)
88
+ if text:
89
+ normalized.append(text)
90
+ return normalized
91
+
92
+
93
+ def parse_numbered_conclusions(text: str) -> list[str]:
94
+ conclusions: list[str] = []
95
+ in_section = False
96
+ for line in text.splitlines():
97
+ stripped = line.strip()
98
+
99
+ if re.match(r"^conclusions?\s*[::]?\s*$", stripped, re.IGNORECASE):
100
+ in_section = True
101
+ continue
102
+
103
+ match = re.match(r"^(\d+)[..))、-]\s*(.+)$", stripped)
104
+ if match:
105
+ conclusions.append(normalize_whitespace(match.group(2)))
106
+ in_section = True
107
+ continue
108
+
109
+ if in_section and stripped and re.match(r"^[A-Z][A-Za-z0-9 _-]*[::]$", stripped):
110
+ break
111
+
112
+ return [item for item in conclusions if item]
113
+
114
+
115
+ def extract_predicted_conclusions(response: str) -> list[str]:
116
+ answer_block = extract_answer_block(response)
117
+ json_obj = extract_json_object(answer_block)
118
+
119
+ if json_obj is not None:
120
+ for key in ("conclusions", "predicted_conclusions", "answers"):
121
+ conclusions = normalize_conclusions(json_obj.get(key))
122
+ if conclusions:
123
+ return conclusions
124
+
125
+ return parse_numbered_conclusions(answer_block)
126
+
127
+
128
+ def format_reward(response: str) -> float:
129
+ return 1.0 if extract_predicted_conclusions(response) else 0.0
130
+
131
+
132
+ def make_score(*, format_score: float, judge_score: float, matched_count: float, format_weight: float) -> dict[str, float]:
133
+ overall = (1.0 - format_weight) * judge_score + format_weight * format_score
134
+ return {
135
+ "overall": overall,
136
+ "format": format_score,
137
+ "judge": judge_score,
138
+ "matched": matched_count,
139
+ }
140
+
141
+
142
+ def make_zero_score(format_score: float, format_weight: float) -> dict[str, float]:
143
+ return make_score(format_score=format_score, judge_score=0.0, matched_count=0.0, format_weight=format_weight)
144
+
145
+
146
+ def safe_float(value: Any, default: float = 0.0) -> float:
147
+ try:
148
+ result = float(value)
149
+ except (TypeError, ValueError):
150
+ return default
151
+ if math.isnan(result) or math.isinf(result):
152
+ return default
153
+ return result
154
+
155
+
156
+ def safe_int(value: Any, default: int = 0) -> int:
157
+ try:
158
+ return int(value)
159
+ except (TypeError, ValueError):
160
+ return default
161
+
162
+
163
+ def build_cache_key(model: str, paper_id: str, reference_conclusions: list[str], predicted_conclusions: list[str]) -> str:
164
+ payload = {
165
+ "model": model,
166
+ "paper_id": paper_id,
167
+ "reference_conclusions": reference_conclusions,
168
+ "predicted_conclusions": predicted_conclusions,
169
+ }
170
+ return json.dumps(payload, ensure_ascii=False, sort_keys=True)
171
+
172
+
173
+ def get_cached_score(cache_key: str | None) -> dict[str, float] | None:
174
+ if not cache_key:
175
+ return None
176
+ with _CACHE_LOCK:
177
+ cached = _SCORE_CACHE.get(cache_key)
178
+ if cached is None:
179
+ return None
180
+ return {
181
+ "overall": cached["overall"],
182
+ "format": cached["format"],
183
+ "judge": cached["judge"],
184
+ "matched": cached["matched"],
185
+ }
186
+
187
+
188
+ def store_cached_score(cache_key: str | None, score: dict[str, float]) -> None:
189
+ if not cache_key:
190
+ return
191
+ with _CACHE_LOCK:
192
+ _SCORE_CACHE[cache_key] = {
193
+ "overall": float(score["overall"]),
194
+ "format": float(score["format"]),
195
+ "judge": float(score["judge"]),
196
+ "matched": float(score["matched"]),
197
+ }
198
+
199
+
200
+ def format_indexed_list(items: list[str]) -> str:
201
+ if not items:
202
+ return "(empty)"
203
+ return "\n".join(f"{idx}. {item}" for idx, item in enumerate(items))
204
+
205
+
206
+ def build_messages(
207
+ reference_conclusions: list[str],
208
+ predicted_conclusions: list[str],
209
+ rubrics: str,
210
+ ) -> list[dict[str, str]]:
211
+ user_prompt = f"""Evaluate the predicted conclusion list against the reference conclusion list for exactly one paper.
212
+
213
+ Use strict one-to-one semantic matching between the two lists.
214
+
215
+ Rubric:
216
+ {rubrics}
217
+
218
+ Reference conclusions:
219
+ {format_indexed_list(reference_conclusions)}
220
+
221
+ Predicted conclusions:
222
+ {format_indexed_list(predicted_conclusions)}
223
+
224
+ Return a JSON object only, with this schema:
225
+ {json.dumps(JSON_RESPONSE_SCHEMA, ensure_ascii=False)}
226
+
227
+ Rules:
228
+ - `matched_prediction_indices` and `matched_reference_indices` must describe the one-to-one matches you used.
229
+ - `matched_count` must equal the number of matched pairs.
230
+ - `score` must follow the rubric exactly.
231
+ - If there are no valid matches, return empty index lists and score 0.
232
+ """
233
+
234
+ return [
235
+ {
236
+ "role": "system",
237
+ "content": "You are a strict evaluator for research-paper conclusion matching. Return JSON only.",
238
+ },
239
+ {"role": "user", "content": user_prompt},
240
+ ]
241
+
242
+
243
+ def post_json(
244
+ url: str,
245
+ payload: dict[str, Any],
246
+ timeout: float,
247
+ api_key: str,
248
+ ) -> dict[str, Any]:
249
+ body = json.dumps(payload).encode("utf-8")
250
+ headers = {"Content-Type": "application/json"}
251
+ if api_key:
252
+ headers["Authorization"] = f"Bearer {api_key}"
253
+ req = request.Request(
254
+ url,
255
+ data=body,
256
+ headers=headers,
257
+ method="POST",
258
+ )
259
+ with request.urlopen(req, timeout=timeout) as resp:
260
+ return json.loads(resp.read().decode("utf-8"))
261
+
262
+
263
+ def judge_once(
264
+ *,
265
+ base_url: str,
266
+ model: str,
267
+ api_key: str,
268
+ timeout: float,
269
+ reference_conclusions: list[str],
270
+ predicted_conclusions: list[str],
271
+ rubrics: str,
272
+ ) -> dict[str, Any]:
273
+ messages = build_messages(reference_conclusions, predicted_conclusions, rubrics)
274
+ payload = {
275
+ "model": model,
276
+ "messages": messages,
277
+ "temperature": 0.0,
278
+ "max_tokens": 512,
279
+ }
280
+ url = base_url.rstrip("/") + "/chat/completions"
281
+
282
+ response_data = post_json(url, payload, timeout=timeout, api_key=api_key)
283
+ choices = response_data.get("choices") or []
284
+ if not choices:
285
+ raise RuntimeError("Judge response does not contain choices.")
286
+
287
+ content = choices[0].get("message", {}).get("content", "")
288
+ json_obj = extract_json_object(content)
289
+ if json_obj is None:
290
+ raise RuntimeError(f"Judge output is not valid JSON: {content[:200]}")
291
+
292
+ matched_count = safe_int(json_obj.get("matched_count"), default=-1)
293
+ if matched_count < 0:
294
+ matched_preds = json_obj.get("matched_prediction_indices")
295
+ matched_refs = json_obj.get("matched_reference_indices")
296
+ matched_count = min(
297
+ len(matched_preds) if isinstance(matched_preds, list) else 0,
298
+ len(matched_refs) if isinstance(matched_refs, list) else 0,
299
+ )
300
+
301
+ ref_count = len(reference_conclusions)
302
+ pred_count = len(predicted_conclusions)
303
+ wrong_count = max(0, pred_count - matched_count)
304
+ computed_score = max(0.0, matched_count - wrong_count) / ref_count if ref_count > 0 else 0.0
305
+ reported_score = safe_float(json_obj.get("score"), default=computed_score)
306
+
307
+ return {
308
+ "judge_score": max(0.0, min(1.0, reported_score)),
309
+ "computed_score": max(0.0, min(1.0, computed_score)),
310
+ "matched_count": float(matched_count),
311
+ }
312
+
313
+
314
+ def judge_with_retries(
315
+ *,
316
+ base_url: str,
317
+ model: str,
318
+ api_key: str,
319
+ timeout: float,
320
+ max_retries: int,
321
+ reference_conclusions: list[str],
322
+ predicted_conclusions: list[str],
323
+ rubrics: str,
324
+ ) -> dict[str, float]:
325
+ last_error: Exception | None = None
326
+
327
+ for attempt in range(max_retries + 1):
328
+ try:
329
+ return judge_once(
330
+ base_url=base_url,
331
+ model=model,
332
+ api_key=api_key,
333
+ timeout=timeout,
334
+ reference_conclusions=reference_conclusions,
335
+ predicted_conclusions=predicted_conclusions,
336
+ rubrics=rubrics,
337
+ )
338
+ except (RuntimeError, error.URLError, error.HTTPError, TimeoutError, OSError, ValueError) as exc:
339
+ last_error = exc
340
+ if attempt < max_retries:
341
+ time.sleep(min(2**attempt, 8))
342
+
343
+ raise RuntimeError(f"Judge request failed after retries: {last_error}")
344
+
345
+
346
+ def prepare_reward_item(
347
+ reward_input: dict[str, Any],
348
+ *,
349
+ model: str,
350
+ format_weight: float,
351
+ ) -> dict[str, Any]:
352
+ response = reward_input.get("response", "") or ""
353
+ ground_truth = reward_input.get("ground_truth", {}) or {}
354
+
355
+ if not isinstance(ground_truth, dict):
356
+ return {"direct_score": make_zero_score(format_score=0.0, format_weight=format_weight)}
357
+
358
+ reference_conclusions = normalize_conclusions(ground_truth.get("reference_conclusions"))
359
+ predicted_conclusions = extract_predicted_conclusions(response)
360
+ paper_id = str(ground_truth.get("paper_id") or ground_truth.get("md5") or "unknown")
361
+ rubrics = ground_truth.get("rubrics") or DEFAULT_RUBRIC
362
+
363
+ format_score = 1.0 if predicted_conclusions else 0.0
364
+ if not reference_conclusions or not predicted_conclusions:
365
+ return {
366
+ "direct_score": make_zero_score(format_score=format_score, format_weight=format_weight),
367
+ "paper_id": paper_id,
368
+ "format_score": format_score,
369
+ }
370
+
371
+ cache_key = build_cache_key(model, paper_id, reference_conclusions, predicted_conclusions)
372
+ return {
373
+ "paper_id": paper_id,
374
+ "reference_conclusions": reference_conclusions,
375
+ "predicted_conclusions": predicted_conclusions,
376
+ "rubrics": rubrics,
377
+ "format_score": format_score,
378
+ "cache_key": cache_key,
379
+ }
380
+
381
+
382
+ def score_prepared_item_via_http(
383
+ prepared_item: dict[str, Any],
384
+ *,
385
+ base_url: str,
386
+ model: str,
387
+ api_key: str,
388
+ timeout: float,
389
+ max_retries: int,
390
+ format_weight: float,
391
+ fallback_judge_score: float,
392
+ suppress_judge_errors: bool,
393
+ ) -> dict[str, float]:
394
+ direct_score = prepared_item.get("direct_score")
395
+ if isinstance(direct_score, dict):
396
+ return direct_score
397
+
398
+ cache_key = prepared_item.get("cache_key")
399
+ cached = get_cached_score(cache_key)
400
+ if cached is not None:
401
+ return cached
402
+
403
+ try:
404
+ judge_result = judge_with_retries(
405
+ base_url=base_url,
406
+ model=model,
407
+ api_key=api_key,
408
+ timeout=timeout,
409
+ max_retries=max_retries,
410
+ reference_conclusions=prepared_item["reference_conclusions"],
411
+ predicted_conclusions=prepared_item["predicted_conclusions"],
412
+ rubrics=prepared_item["rubrics"],
413
+ )
414
+ judge_score = judge_result["computed_score"]
415
+ matched_count = judge_result["matched_count"]
416
+ except Exception:
417
+ if not suppress_judge_errors:
418
+ raise
419
+ judge_score = max(0.0, min(1.0, fallback_judge_score))
420
+ matched_count = 0.0
421
+
422
+ score = make_score(
423
+ format_score=float(prepared_item["format_score"]),
424
+ judge_score=judge_score,
425
+ matched_count=matched_count,
426
+ format_weight=format_weight,
427
+ )
428
+ store_cached_score(cache_key, score)
429
+ return score
430
+
431
+
432
+ def compute_scores_http(
433
+ reward_inputs: list[dict[str, Any]],
434
+ *,
435
+ base_url: str,
436
+ model: str,
437
+ api_key: str,
438
+ timeout: float,
439
+ max_retries: int,
440
+ max_workers: int,
441
+ format_weight: float,
442
+ fallback_judge_score: float,
443
+ suppress_judge_errors: bool,
444
+ ) -> list[dict[str, float]]:
445
+ prepared_items = [
446
+ prepare_reward_item(reward_input, model=model, format_weight=format_weight) for reward_input in reward_inputs
447
+ ]
448
+
449
+ worker_count = max(1, min(max_workers, len(prepared_items)))
450
+ if worker_count == 1:
451
+ return [
452
+ score_prepared_item_via_http(
453
+ prepared_item,
454
+ base_url=base_url,
455
+ model=model,
456
+ api_key=api_key,
457
+ timeout=timeout,
458
+ max_retries=max_retries,
459
+ format_weight=format_weight,
460
+ fallback_judge_score=fallback_judge_score,
461
+ suppress_judge_errors=suppress_judge_errors,
462
+ )
463
+ for prepared_item in prepared_items
464
+ ]
465
+
466
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
467
+ futures = [
468
+ executor.submit(
469
+ score_prepared_item_via_http,
470
+ prepared_item,
471
+ base_url=base_url,
472
+ model=model,
473
+ api_key=api_key,
474
+ timeout=timeout,
475
+ max_retries=max_retries,
476
+ format_weight=format_weight,
477
+ fallback_judge_score=fallback_judge_score,
478
+ suppress_judge_errors=suppress_judge_errors,
479
+ )
480
+ for prepared_item in prepared_items
481
+ ]
482
+ return [future.result() for future in futures]
EasyR1/examples/reward_function/paper_conclusion_list_judge.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+
7
+ CURRENT_DIR = Path(__file__).resolve().parent
8
+ if str(CURRENT_DIR) not in sys.path:
9
+ sys.path.insert(0, str(CURRENT_DIR))
10
+
11
+ from paper_conclusion_judge_common import compute_scores_http, extract_predicted_conclusions, format_reward
12
+
13
+
14
+ REWARD_NAME = "paper_conclusion_list_judge"
15
+ REWARD_TYPE = "batch"
16
+
17
+
18
+ def compute_score(
19
+ reward_inputs: list[dict[str, Any]],
20
+ *,
21
+ base_url: str = "http://127.0.0.1:8000/v1",
22
+ model: str = "qwen3-4b-judge",
23
+ api_key: str | None = None,
24
+ api_key_env: str = "OPENAI_API_KEY",
25
+ timeout: float = 120.0,
26
+ max_retries: int = 2,
27
+ max_workers: int = 8,
28
+ format_weight: float = 0.05,
29
+ fallback_judge_score: float = 0.0,
30
+ suppress_judge_errors: bool = True,
31
+ ) -> list[dict[str, float]]:
32
+ api_key = api_key if api_key is not None else os.environ.get(api_key_env, "EMPTY")
33
+ return compute_scores_http(
34
+ reward_inputs,
35
+ base_url=base_url,
36
+ model=model,
37
+ api_key=api_key,
38
+ timeout=timeout,
39
+ max_retries=max_retries,
40
+ max_workers=max_workers,
41
+ format_weight=format_weight,
42
+ fallback_judge_score=fallback_judge_score,
43
+ suppress_judge_errors=suppress_judge_errors,
44
+ )
EasyR1/examples/reward_function/r1v.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ from typing import Any
17
+
18
+ from mathruler.grader import grade_answer
19
+
20
+
21
+ # Metadata
22
+ REWARD_NAME = "r1v"
23
+ REWARD_TYPE = "sequential"
24
+
25
+
26
+ def format_reward(response: str) -> float:
27
+ pattern = re.compile(r"<think>.*?</think>\s*<answer>.*?</answer>", re.DOTALL)
28
+ format_match = re.fullmatch(pattern, response)
29
+ return 1.0 if format_match else 0.0
30
+
31
+
32
+ def accuracy_reward(response: str, ground_truth: str) -> float:
33
+ try:
34
+ content_match = re.search(r"<answer>(.*?)</answer>", response)
35
+ given_answer = content_match.group(1).strip() if content_match else response.strip()
36
+ if grade_answer(given_answer, ground_truth.strip()):
37
+ return 1.0
38
+
39
+ except Exception:
40
+ pass
41
+
42
+ return 0.0
43
+
44
+
45
+ def compute_score(reward_input: dict[str, Any], format_weight: float = 0.5) -> dict[str, float]:
46
+ format_score = format_reward(reward_input["response"])
47
+ accuracy_score = accuracy_reward(reward_input["response"], reward_input["ground_truth"])
48
+ return {
49
+ "overall": (1 - format_weight) * accuracy_score + format_weight * format_score,
50
+ "format": format_score,
51
+ "accuracy": accuracy_score,
52
+ }
EasyR1/pyproject.toml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "verl"
7
+ dynamic = [
8
+ "version",
9
+ "dependencies",
10
+ "optional-dependencies",
11
+ "requires-python",
12
+ "authors",
13
+ "description",
14
+ "readme",
15
+ "license"
16
+ ]
17
+
18
+ [tool.ruff]
19
+ target-version = "py39"
20
+ line-length = 119
21
+ indent-width = 4
22
+
23
+ [tool.ruff.lint]
24
+ ignore = ["C901", "E501", "E741", "W605", "C408"]
25
+ select = ["C", "E", "F", "I", "W", "RUF022"]
26
+
27
+ [tool.ruff.lint.per-file-ignores]
28
+ "__init__.py" = ["E402", "F401", "F403", "F811"]
29
+
30
+ [tool.ruff.lint.isort]
31
+ lines-after-imports = 2
32
+ known-first-party = ["verl"]
33
+ known-third-party = ["torch", "transformers", "wandb"]
34
+
35
+ [tool.ruff.format]
36
+ quote-style = "double"
37
+ indent-style = "space"
38
+ skip-magic-trailing-comma = false
39
+ line-ending = "auto"
EasyR1/requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ codetiming
3
+ datasets
4
+ flash-attn>=2.4.3
5
+ liger-kernel
6
+ mathruler
7
+ numpy
8
+ omegaconf
9
+ pandas
10
+ peft
11
+ pillow
12
+ pyarrow>=15.0.0
13
+ pylatexenc
14
+ qwen-vl-utils
15
+ ray[default]
16
+ tensordict
17
+ torchdata
18
+ transformers>=4.54.0,<5.0.0
19
+ vllm>=0.8.0
20
+ wandb
EasyR1/setup.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+
18
+ from setuptools import find_packages, setup
19
+
20
+
21
+ def get_version() -> str:
22
+ with open(os.path.join("verl", "__init__.py"), encoding="utf-8") as f:
23
+ file_content = f.read()
24
+ pattern = r"__version__\W*=\W*\"([^\"]+)\""
25
+ (version,) = re.findall(pattern, file_content)
26
+ return version
27
+
28
+
29
+ def get_requires() -> list[str]:
30
+ with open("requirements.txt", encoding="utf-8") as f:
31
+ file_content = f.read()
32
+ lines = [line.strip() for line in file_content.strip().split("\n") if not line.startswith("#")]
33
+ return lines
34
+
35
+
36
+ extra_require = {
37
+ "dev": ["pre-commit", "ruff"],
38
+ }
39
+
40
+
41
+ def main():
42
+ setup(
43
+ name="verl",
44
+ version=get_version(),
45
+ description="An Efficient, Scalable, Multi-Modality RL Training Framework based on veRL",
46
+ long_description=open("README.md", encoding="utf-8").read(),
47
+ long_description_content_type="text/markdown",
48
+ author="verl",
49
+ author_email="zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk, hiyouga@buaa.edu.cn",
50
+ license="Apache 2.0 License",
51
+ url="https://github.com/volcengine/verl",
52
+ package_dir={"": "."},
53
+ packages=find_packages(where="."),
54
+ python_requires=">=3.9.0",
55
+ install_requires=get_requires(),
56
+ extras_require=extra_require,
57
+ )
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
EasyR1/tests/check_license.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import sys
16
+ from pathlib import Path
17
+
18
+
19
+ KEYWORDS = ("Copyright", "2024", "Bytedance")
20
+
21
+
22
+ def main():
23
+ path_list: list[Path] = []
24
+ for check_dir in sys.argv[1:]:
25
+ path_list.extend(Path(check_dir).glob("**/*.py"))
26
+
27
+ for path in path_list:
28
+ with open(path.absolute(), encoding="utf-8") as f:
29
+ file_content = f.read().strip().split("\n")
30
+ license = "\n".join(file_content[:5])
31
+ if not license:
32
+ continue
33
+
34
+ print(f"Check license: {path}")
35
+ assert all(keyword in license for keyword in KEYWORDS), f"File {path} does not contain license."
36
+
37
+
38
+ if __name__ == "__main__":
39
+ main()
EasyR1/tests/test_checkpoint.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import json
17
+ import os
18
+ import shutil
19
+ import uuid
20
+
21
+ import pytest
22
+
23
+ from verl.utils.checkpoint import CHECKPOINT_TRACKER, find_latest_ckpt, remove_obsolete_ckpt
24
+
25
+
26
+ @pytest.fixture
27
+ def save_checkpoint_path():
28
+ ckpt_dir = os.path.join("checkpoints", str(uuid.uuid4()))
29
+ os.makedirs(ckpt_dir, exist_ok=True)
30
+ yield ckpt_dir
31
+ shutil.rmtree(ckpt_dir, ignore_errors=True)
32
+
33
+
34
+ def test_find_latest_ckpt(save_checkpoint_path):
35
+ with open(os.path.join(save_checkpoint_path, CHECKPOINT_TRACKER), "w") as f:
36
+ json.dump({"last_global_step": 10}, f, ensure_ascii=False, indent=2)
37
+
38
+ assert find_latest_ckpt(save_checkpoint_path)[0] is None
39
+ os.makedirs(os.path.join(save_checkpoint_path, "global_step_10"), exist_ok=True)
40
+ assert find_latest_ckpt(save_checkpoint_path)[0] == os.path.join(save_checkpoint_path, "global_step_10")
41
+
42
+
43
+ def test_remove_obsolete_ckpt(save_checkpoint_path):
44
+ for step in range(5, 30, 5):
45
+ os.makedirs(os.path.join(save_checkpoint_path, f"global_step_{step}"), exist_ok=True)
46
+
47
+ remove_obsolete_ckpt(save_checkpoint_path, global_step=30, best_global_step=10, save_limit=3)
48
+ for step in range(5, 30, 5):
49
+ is_exist = step in [10, 25]
50
+ assert os.path.exists(os.path.join(save_checkpoint_path, f"global_step_{step}")) == is_exist
EasyR1/tests/test_dataproto.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ import os
17
+ from typing import Any, Optional
18
+
19
+ import numpy as np
20
+ import pytest
21
+ import torch
22
+
23
+ from verl.protocol import DataProto, pad_dataproto_to_divisor, unpad_dataproto
24
+
25
+
26
+ def _get_data_proto(
27
+ tensors: Optional[dict[str, list[Any]]] = None,
28
+ non_tensors: Optional[dict[str, list[Any]]] = None,
29
+ meta_info: Optional[dict[str, Any]] = None,
30
+ ) -> DataProto:
31
+ if tensors is None and non_tensors is None:
32
+ tensors = {"obs": [1, 2, 3, 4, 5, 6]}
33
+ non_tensors = {"labels": ["a", "b", "c", "d", "e", "f"]}
34
+
35
+ if tensors is not None:
36
+ tensors = {k: torch.tensor(v) if not isinstance(v, torch.Tensor) else v for k, v in tensors.items()}
37
+
38
+ if non_tensors is not None:
39
+ non_tensors = {
40
+ k: np.array(v, dtype=object) if not isinstance(v, np.ndarray) else v for k, v in non_tensors.items()
41
+ }
42
+
43
+ meta_info = meta_info or {"info": "test_info"}
44
+ return DataProto.from_dict(tensors=tensors, non_tensors=non_tensors, meta_info=meta_info)
45
+
46
+
47
+ def _assert_equal(data1: DataProto, data2: Optional[DataProto] = None):
48
+ data2 = data2 or _get_data_proto()
49
+ if data1.batch is not None:
50
+ assert data1.batch.keys() == data2.batch.keys()
51
+ for key in data1.batch.keys():
52
+ assert torch.all(data1.batch[key] == data2.batch[key])
53
+ else:
54
+ assert data2.batch is None
55
+
56
+ if data1.non_tensor_batch is not None:
57
+ assert data1.non_tensor_batch.keys() == data2.non_tensor_batch.keys()
58
+ for key in data1.non_tensor_batch.keys():
59
+ assert np.all(data1.non_tensor_batch[key] == data2.non_tensor_batch[key])
60
+ else:
61
+ assert data2.non_tensor_batch is None
62
+
63
+ assert data1.meta_info == data2.meta_info
64
+
65
+
66
+ def test_tensor_dict_constructor():
67
+ obs = torch.randn(100, 10)
68
+ act = torch.randn(100, 10, 3)
69
+ data = DataProto.from_dict(tensors={"obs": obs, "act": act})
70
+ assert len(data) == 100
71
+
72
+ with pytest.raises(AssertionError):
73
+ data = DataProto.from_dict(tensors={"obs": obs, "act": act}, num_batch_dims=2)
74
+
75
+ with pytest.raises(AssertionError):
76
+ data = DataProto.from_dict(tensors={"obs": obs, "act": act}, num_batch_dims=3)
77
+
78
+ labels = np.array(["a", "b", "c"], dtype=object)
79
+ data = DataProto.from_dict(non_tensors={"labels": labels})
80
+ assert len(data) == 3
81
+
82
+
83
+ def test_getitem():
84
+ data = _get_data_proto()
85
+ assert data[0].batch["obs"] == torch.tensor(1)
86
+ assert data[0].non_tensor_batch["labels"] == "a"
87
+ _assert_equal(data[1:3], _get_data_proto({"obs": [2, 3]}, {"labels": ["b", "c"]}))
88
+ _assert_equal(data[[0, 2]], _get_data_proto({"obs": [1, 3]}, {"labels": ["a", "c"]}))
89
+ _assert_equal(data[torch.tensor([1])], _get_data_proto({"obs": [2]}, {"labels": ["b"]}))
90
+
91
+
92
+ def test_select_pop():
93
+ obs = torch.randn(100, 10)
94
+ act = torch.randn(100, 3)
95
+ dataset = _get_data_proto(tensors={"obs": obs, "act": act}, meta_info={"p": 1, "q": 2})
96
+ selected_dataset = dataset.select(batch_keys=["obs"], meta_info_keys=["p"])
97
+
98
+ assert selected_dataset.batch.keys() == {"obs"}
99
+ assert selected_dataset.meta_info.keys() == {"p"}
100
+ assert dataset.batch.keys() == {"obs", "act"}
101
+ assert dataset.meta_info.keys() == {"p", "q"}
102
+
103
+ popped_dataset = dataset.pop(batch_keys=["obs"], meta_info_keys=["p"])
104
+ assert popped_dataset.batch.keys() == {"obs"}
105
+ assert popped_dataset.meta_info.keys() == {"p"}
106
+ assert dataset.batch.keys() == {"act"}
107
+ assert dataset.meta_info.keys() == {"q"}
108
+
109
+
110
+ def test_chunk_concat_split():
111
+ data = _get_data_proto()
112
+ with pytest.raises(AssertionError):
113
+ data.chunk(5)
114
+
115
+ chunked_data = data.chunk(2)
116
+
117
+ assert len(chunked_data) == 2
118
+ expected_data = _get_data_proto({"obs": [1, 2, 3]}, {"labels": ["a", "b", "c"]})
119
+ _assert_equal(chunked_data[0], expected_data)
120
+
121
+ concat_data = DataProto.concat(chunked_data)
122
+ _assert_equal(concat_data, data)
123
+
124
+ splitted_data = data.split(2)
125
+ assert len(splitted_data) == 3
126
+ expected_data = _get_data_proto({"obs": [1, 2]}, {"labels": ["a", "b"]})
127
+ _assert_equal(splitted_data[0], expected_data)
128
+
129
+
130
+ def test_reorder():
131
+ data = _get_data_proto()
132
+ data.reorder(torch.tensor([3, 4, 2, 0, 1, 5]))
133
+ expected_data = _get_data_proto({"obs": [4, 5, 3, 1, 2, 6]}, {"labels": ["d", "e", "c", "a", "b", "f"]})
134
+ _assert_equal(data, expected_data)
135
+
136
+
137
+ @pytest.mark.parametrize("interleave", [True, False])
138
+ def test_repeat(interleave: bool):
139
+ data = _get_data_proto({"obs": [1, 2]}, {"labels": ["a", "b"]})
140
+ repeated_data = data.repeat(repeat_times=2, interleave=interleave)
141
+ expected_tensors = {"obs": [1, 1, 2, 2] if interleave else [1, 2, 1, 2]}
142
+ expected_non_tensors = {"labels": ["a", "a", "b", "b"] if interleave else ["a", "b", "a", "b"]}
143
+ _assert_equal(repeated_data, _get_data_proto(expected_tensors, expected_non_tensors))
144
+
145
+
146
+ @pytest.mark.parametrize("size_divisor", [2, 3])
147
+ def test_dataproto_pad_unpad(size_divisor: int):
148
+ data = _get_data_proto({"obs": [1, 2, 3]}, {"labels": ["a", "b", "c"]})
149
+ # test size_divisor=2
150
+ padded_data, pad_size = pad_dataproto_to_divisor(data, size_divisor=size_divisor)
151
+ unpadded_data = unpad_dataproto(padded_data, pad_size=pad_size)
152
+
153
+ if size_divisor == 2:
154
+ assert pad_size == 1
155
+ expected_tensors = {"obs": [1, 2, 3, 1]}
156
+ expected_non_tensors = {"labels": ["a", "b", "c", "a"]}
157
+ expected_data = _get_data_proto(expected_tensors, expected_non_tensors)
158
+ else:
159
+ assert pad_size == 0
160
+ expected_data = data
161
+
162
+ _assert_equal(padded_data, expected_data)
163
+ _assert_equal(unpadded_data, data)
164
+
165
+
166
+ def test_data_proto_save_load():
167
+ data = _get_data_proto()
168
+ data.save_to_disk("test_data.pt")
169
+ loaded_data = DataProto.load_from_disk("test_data.pt")
170
+ os.remove("test_data.pt")
171
+ _assert_equal(data, loaded_data)
172
+
173
+
174
+ def test_union_tensor_dict():
175
+ obs = torch.randn(100, 10)
176
+ data1 = _get_data_proto({"obs": obs, "act": torch.randn(100, 3)})
177
+ data2 = _get_data_proto({"obs": obs, "rew": torch.randn(100)})
178
+ data1.union(data2)
179
+
180
+ data1 = _get_data_proto({"obs": obs, "act": torch.randn(100, 3)})
181
+ data2 = _get_data_proto({"obs": obs + 1, "rew": torch.randn(100)})
182
+ with pytest.raises(ValueError):
183
+ data1.union(data2)
EasyR1/tests/test_dynamic_batch.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import numpy as np
16
+ import torch
17
+
18
+ from verl.protocol import DataProto
19
+ from verl.utils.seqlen_balancing import prepare_dynamic_batch, restore_dynamic_batch
20
+
21
+
22
+ def _create_random_mask(
23
+ input_ids: torch.Tensor,
24
+ max_ratio_of_valid_token: float,
25
+ max_ratio_of_left_padding: float,
26
+ min_ratio_of_valid_token: float = 0,
27
+ ) -> torch.Tensor:
28
+ """Create a random mask given input_ids. Support left padding and right padding.
29
+
30
+ Process:
31
+ - Sample valid token length
32
+ - Sample left_padding length
33
+ - Generate padding
34
+
35
+ Args:
36
+ input_ids:
37
+ shape (batch_size, seq_len)
38
+
39
+ Returns:
40
+ mask:
41
+ shape (batch_size, seq_len)
42
+ """
43
+ assert max_ratio_of_valid_token > 0 and max_ratio_of_valid_token <= 1.0
44
+ assert max_ratio_of_left_padding >= 0 and max_ratio_of_left_padding < 1.0
45
+ assert min_ratio_of_valid_token <= max_ratio_of_valid_token
46
+
47
+ batch_size, sequence_length = input_ids.shape
48
+ max_num_valid_tokens = int(sequence_length * max_ratio_of_valid_token)
49
+ min_num_valid_tokens = max(1, int(sequence_length * min_ratio_of_valid_token))
50
+ max_left_padding = int(sequence_length * max_ratio_of_left_padding)
51
+ assert max_num_valid_tokens + max_left_padding <= sequence_length
52
+ assert max_num_valid_tokens > 0 and max_ratio_of_valid_token <= sequence_length
53
+ mask = torch.ones_like(input_ids, dtype=torch.int64)
54
+ # TODO: we can make this faster
55
+ for i in range(batch_size):
56
+ num_left_padding = np.random.randint(low=0, high=max_left_padding + 1, dtype=np.int64)
57
+ num_valid = np.random.randint(low=min_num_valid_tokens, high=max_num_valid_tokens + 1, dtype=np.int64)
58
+
59
+ for index in range(num_left_padding):
60
+ mask[i, index] = 0
61
+
62
+ for index in range(num_left_padding + num_valid, sequence_length):
63
+ mask[i, index] = 0
64
+
65
+ return mask
66
+
67
+
68
+ def test_dynamic_batch():
69
+ input_ids = torch.randint(low=0, high=10, size=(20, 100))
70
+ attention_mask = _create_random_mask(
71
+ 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
72
+ )
73
+ data = {"input_ids": input_ids, "attention_mask": attention_mask}
74
+ dataproto = DataProto.from_single_dict(data)
75
+ micro_batches, micro_bsz_idx_lst = prepare_dynamic_batch(dataproto, max_token_len=300)
76
+ input_ids = torch.cat([micro_batch.batch["input_ids"] for micro_batch in micro_batches], dim=0)
77
+ input_ids = restore_dynamic_batch(input_ids, micro_bsz_idx_lst)
78
+ torch.testing.assert_close(input_ids, dataproto.batch["input_ids"])
EasyR1/verl/models/transformers/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
EasyR1/verl/models/transformers/qwen2_vl.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team
2
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
3
+ # Based on:
4
+ # https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+ from transformers.models.qwen2_vl.modeling_qwen2_vl import (
22
+ Qwen2VLCausalLMOutputWithPast,
23
+ Qwen2VLForConditionalGeneration,
24
+ Qwen2VLModel,
25
+ Qwen2VLModelOutputWithPast,
26
+ )
27
+ from transformers.models.qwen2_vl.processing_qwen2_vl import Qwen2VLProcessor
28
+
29
+
30
+ def get_rope_index(
31
+ processor: "Qwen2VLProcessor",
32
+ input_ids: torch.Tensor,
33
+ image_grid_thw: Optional[torch.Tensor] = None,
34
+ video_grid_thw: Optional[torch.Tensor] = None,
35
+ second_per_grid_ts: Optional[torch.Tensor] = None,
36
+ attention_mask: Optional[torch.Tensor] = None,
37
+ ) -> torch.Tensor:
38
+ """
39
+ Gets the position ids for Qwen2-VL, it should be generated before sharding the sequence.
40
+ The batch dim has been removed and the input_ids should be a 1D tensor representing a single example.
41
+ https://github.com/huggingface/transformers/blob/v4.52.4/src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py#L1405
42
+ """
43
+ spatial_merge_size = processor.image_processor.merge_size
44
+ tokens_per_second = 2
45
+ image_token_id = processor.tokenizer.convert_tokens_to_ids("<|image_pad|>")
46
+ video_token_id = processor.tokenizer.convert_tokens_to_ids("<|video_pad|>")
47
+ vision_start_token_id = processor.tokenizer.convert_tokens_to_ids("<|vision_start|>")
48
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
49
+ if attention_mask is None:
50
+ attention_mask = torch.ones_like(input_ids)
51
+
52
+ position_ids = torch.ones(3, input_ids.size(0), dtype=input_ids.dtype, device=input_ids.device) # (3, seqlen)
53
+ image_index, video_index = 0, 0
54
+ input_ids = input_ids[attention_mask == 1]
55
+ image_nums, video_nums = 0, 0
56
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id)
57
+ vision_tokens = input_ids[vision_start_indices + 1]
58
+ image_nums = (vision_tokens == image_token_id).sum()
59
+ video_nums = (vision_tokens == video_token_id).sum()
60
+ input_tokens = input_ids.tolist()
61
+ llm_pos_ids_list: list = []
62
+ st = 0
63
+ remain_images, remain_videos = image_nums, video_nums
64
+ for _ in range(image_nums + video_nums):
65
+ if image_token_id in input_tokens and remain_images > 0:
66
+ ed_image = input_tokens.index(image_token_id, st)
67
+ else:
68
+ ed_image = len(input_tokens) + 1
69
+ if video_token_id in input_tokens and remain_videos > 0:
70
+ ed_video = input_tokens.index(video_token_id, st)
71
+ else:
72
+ ed_video = len(input_tokens) + 1
73
+ if ed_image < ed_video:
74
+ t, h, w = (
75
+ image_grid_thw[image_index][0],
76
+ image_grid_thw[image_index][1],
77
+ image_grid_thw[image_index][2],
78
+ )
79
+ second_per_grid_t = 0
80
+ image_index += 1
81
+ remain_images -= 1
82
+ ed = ed_image
83
+ else:
84
+ t, h, w = (
85
+ video_grid_thw[video_index][0],
86
+ video_grid_thw[video_index][1],
87
+ video_grid_thw[video_index][2],
88
+ )
89
+ if second_per_grid_ts is not None:
90
+ second_per_grid_t = second_per_grid_ts[video_index]
91
+ else:
92
+ second_per_grid_t = 1.0
93
+
94
+ video_index += 1
95
+ remain_videos -= 1
96
+ ed = ed_video
97
+
98
+ llm_grid_t, llm_grid_h, llm_grid_w = (
99
+ t.item(),
100
+ h.item() // spatial_merge_size,
101
+ w.item() // spatial_merge_size,
102
+ )
103
+ text_len = ed - st
104
+
105
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
106
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
107
+
108
+ t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w)
109
+ t_index = (t_index * second_per_grid_t * tokens_per_second).long().flatten()
110
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
111
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
112
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
113
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
114
+
115
+ if st < len(input_tokens):
116
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
117
+ text_len = len(input_tokens) - st
118
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
119
+
120
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
121
+ position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device)
122
+ else:
123
+ if attention_mask is not None:
124
+ position_ids = attention_mask.long().cumsum(-1) - 1
125
+ position_ids.masked_fill_(attention_mask == 0, 1)
126
+ position_ids = position_ids.unsqueeze(0).expand(3, -1).to(input_ids.device)
127
+ else:
128
+ position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1)
129
+
130
+ return position_ids
131
+
132
+
133
+ def _get_input_embeds(
134
+ model: "Qwen2VLModel",
135
+ input_ids: torch.LongTensor,
136
+ attention_mask: Optional[torch.Tensor] = None,
137
+ pixel_values: Optional[torch.FloatTensor] = None,
138
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
139
+ image_grid_thw: Optional[torch.LongTensor] = None,
140
+ video_grid_thw: Optional[torch.LongTensor] = None,
141
+ ):
142
+ inputs_embeds = model.get_input_embeddings()(input_ids)
143
+ if pixel_values is not None:
144
+ pixel_values = pixel_values.type(model.visual.dtype)
145
+ image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw)
146
+ n_image_tokens = (input_ids == model.config.image_token_id).sum().item()
147
+ n_image_features = image_embeds.shape[0]
148
+ if n_image_tokens != n_image_features:
149
+ raise ValueError(
150
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
151
+ )
152
+
153
+ mask = input_ids == model.config.image_token_id
154
+ mask_unsqueezed = mask.unsqueeze(-1)
155
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
156
+ image_mask = mask_expanded.to(inputs_embeds.device)
157
+
158
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
159
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
160
+
161
+ if pixel_values_videos is not None:
162
+ pixel_values_videos = pixel_values_videos.type(model.visual.dtype)
163
+ video_embeds = model.visual(pixel_values_videos, grid_thw=video_grid_thw)
164
+ n_video_tokens = (input_ids == model.config.video_token_id).sum().item()
165
+ n_video_features = video_embeds.shape[0]
166
+ if n_video_tokens != n_video_features:
167
+ raise ValueError(
168
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
169
+ )
170
+
171
+ mask = input_ids == model.config.video_token_id
172
+ mask_unsqueezed = mask.unsqueeze(-1)
173
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
174
+ video_mask = mask_expanded.to(inputs_embeds.device)
175
+
176
+ video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
177
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
178
+
179
+ if pixel_values is None and pixel_values_videos is None:
180
+ config = model.config.vision_config
181
+ patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2
182
+ pixel_values = torch.zeros((16, patch_dim), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
183
+ image_grid_thw = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device)
184
+ image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw)
185
+ inputs_embeds += 0.0 * image_embeds.mean()
186
+
187
+ if attention_mask is not None:
188
+ attention_mask = attention_mask.to(inputs_embeds.device)
189
+
190
+ return {
191
+ "inputs_embeds": inputs_embeds,
192
+ "attention_mask": attention_mask,
193
+ }
194
+
195
+
196
+ def qwen2_vl_base_forward(
197
+ self: "Qwen2VLModel",
198
+ input_ids: torch.LongTensor,
199
+ attention_mask: Optional[torch.Tensor] = None,
200
+ pixel_values: Optional[torch.FloatTensor] = None,
201
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
202
+ image_grid_thw: Optional[torch.LongTensor] = None,
203
+ video_grid_thw: Optional[torch.LongTensor] = None,
204
+ **kwargs,
205
+ ):
206
+ position_ids = kwargs.get("position_ids")
207
+ if isinstance(position_ids, torch.Tensor) and (position_ids.ndim != 3 or position_ids.size(0) != 4):
208
+ # we concat the text position ids with the 3D vision position ids by default
209
+ # see https://github.com/huggingface/transformers/pull/39447
210
+ raise ValueError("position_ids should be a 3D tensor of shape (4, batch_size, seq_length).")
211
+
212
+ input_kwargs = _get_input_embeds(
213
+ self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw
214
+ )
215
+ kwargs.update(input_kwargs) # avoid lora module to have multiple keyword arguments
216
+ outputs = self.language_model(input_ids=None, **kwargs)
217
+ return Qwen2VLModelOutputWithPast(last_hidden_state=outputs.last_hidden_state)
218
+
219
+
220
+ def qwen2_vl_model_forward(
221
+ self: "Qwen2VLForConditionalGeneration",
222
+ input_ids: torch.LongTensor,
223
+ labels: Optional[torch.LongTensor] = None,
224
+ **kwargs,
225
+ ) -> "Qwen2VLCausalLMOutputWithPast":
226
+ outputs = self.model(input_ids=input_ids, **kwargs)
227
+ hidden_states = outputs[0]
228
+ logits = self.lm_head(hidden_states)
229
+
230
+ return Qwen2VLCausalLMOutputWithPast(logits=logits)
EasyR1/verl/models/transformers/qwen3_vl.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team
2
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
3
+ # Based on:
4
+ # https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/models/qwen2_vl/modeling_qwen2_vl.py
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ from typing import Optional
19
+
20
+ import torch
21
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import (
22
+ Qwen3VLCausalLMOutputWithPast,
23
+ Qwen3VLForConditionalGeneration,
24
+ Qwen3VLModel,
25
+ Qwen3VLModelOutputWithPast,
26
+ )
27
+ from transformers.models.qwen3_vl.processing_qwen3_vl import Qwen3VLProcessor
28
+
29
+
30
+ def get_rope_index(
31
+ processor: "Qwen3VLProcessor",
32
+ input_ids: torch.Tensor,
33
+ image_grid_thw: Optional[torch.Tensor] = None,
34
+ video_grid_thw: Optional[torch.Tensor] = None,
35
+ attention_mask: Optional[torch.Tensor] = None,
36
+ **kwargs,
37
+ ) -> torch.Tensor:
38
+ """
39
+ Gets the position ids for Qwen3-VL, it should be generated before sharding the sequence.
40
+ The batch dim has been removed and the input_ids should be a 1D tensor representing a single example.
41
+ https://github.com/huggingface/transformers/blob/v4.57.0/src/transformers/models/qwen3_vl/modeling_qwen3_vl.py#L916
42
+ """
43
+ spatial_merge_size = processor.image_processor.merge_size
44
+ image_token_id = processor.image_token_id
45
+ video_token_id = processor.video_token_id
46
+ vision_start_token_id = processor.vision_start_token_id
47
+
48
+ # Since we use timestamps to seperate videos,
49
+ # like <t1> <vision_start> <frame1> <vision_end> <t2> <vision_start> <frame2> <vision_end>,
50
+ # the video_grid_thw should also be split
51
+ if video_grid_thw is not None:
52
+ video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0)
53
+ video_grid_thw[:, 0] = 1
54
+
55
+ if input_ids is not None and (image_grid_thw is not None or video_grid_thw is not None):
56
+ if attention_mask is None:
57
+ attention_mask = torch.ones_like(input_ids)
58
+
59
+ position_ids = torch.ones(3, input_ids.shape[0], dtype=input_ids.dtype, device=input_ids.device)
60
+ image_index, video_index = 0, 0
61
+ attention_mask = attention_mask.to(input_ids.device)
62
+ input_ids = input_ids[attention_mask == 1]
63
+ image_nums, video_nums = 0, 0
64
+ vision_start_indices = torch.argwhere(input_ids == vision_start_token_id)
65
+ vision_tokens = input_ids[vision_start_indices + 1]
66
+ image_nums = (vision_tokens == image_token_id).sum()
67
+ video_nums = (vision_tokens == video_token_id).sum()
68
+ input_tokens = input_ids.tolist()
69
+ llm_pos_ids_list: list = []
70
+ st = 0
71
+ remain_images, remain_videos = image_nums, video_nums
72
+ for _ in range(image_nums + video_nums):
73
+ if image_token_id in input_tokens and remain_images > 0:
74
+ ed_image = input_tokens.index(image_token_id, st)
75
+ else:
76
+ ed_image = len(input_tokens) + 1
77
+ if video_token_id in input_tokens and remain_videos > 0:
78
+ ed_video = input_tokens.index(video_token_id, st)
79
+ else:
80
+ ed_video = len(input_tokens) + 1
81
+ if ed_image < ed_video:
82
+ t, h, w = (
83
+ image_grid_thw[image_index][0],
84
+ image_grid_thw[image_index][1],
85
+ image_grid_thw[image_index][2],
86
+ )
87
+ image_index += 1
88
+ remain_images -= 1
89
+ ed = ed_image
90
+ else:
91
+ t, h, w = (
92
+ video_grid_thw[video_index][0],
93
+ video_grid_thw[video_index][1],
94
+ video_grid_thw[video_index][2],
95
+ )
96
+ video_index += 1
97
+ remain_videos -= 1
98
+ ed = ed_video
99
+
100
+ llm_grid_t, llm_grid_h, llm_grid_w = (
101
+ t.item(),
102
+ h.item() // spatial_merge_size,
103
+ w.item() // spatial_merge_size,
104
+ )
105
+ text_len = ed - st
106
+
107
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
108
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
109
+
110
+ # t_index is always 0 because llm_grid_t is always 1 (we use timestamps to encode the temporal information for videos)
111
+ t_index = torch.arange(llm_grid_t).view(-1, 1).expand(-1, llm_grid_h * llm_grid_w).flatten()
112
+ h_index = torch.arange(llm_grid_h).view(1, -1, 1).expand(llm_grid_t, -1, llm_grid_w).flatten()
113
+ w_index = torch.arange(llm_grid_w).view(1, 1, -1).expand(llm_grid_t, llm_grid_h, -1).flatten()
114
+ llm_pos_ids_list.append(torch.stack([t_index, h_index, w_index]) + text_len + st_idx)
115
+ st = ed + llm_grid_t * llm_grid_h * llm_grid_w
116
+
117
+ if st < len(input_tokens):
118
+ st_idx = llm_pos_ids_list[-1].max() + 1 if len(llm_pos_ids_list) > 0 else 0
119
+ text_len = len(input_tokens) - st
120
+ llm_pos_ids_list.append(torch.arange(text_len).view(1, -1).expand(3, -1) + st_idx)
121
+
122
+ llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(3, -1)
123
+ position_ids[..., attention_mask == 1] = llm_positions.to(position_ids.device)
124
+ else:
125
+ if attention_mask is not None:
126
+ position_ids = attention_mask.long().cumsum(-1) - 1
127
+ position_ids.masked_fill_(attention_mask == 0, 1)
128
+ position_ids = position_ids.unsqueeze(0).expand(3, -1).to(attention_mask.device)
129
+ else:
130
+ position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).view(1, -1).expand(3, -1)
131
+
132
+ return position_ids
133
+
134
+
135
+ def _get_input_embeds(
136
+ model: "Qwen3VLModel",
137
+ input_ids: torch.LongTensor,
138
+ attention_mask: Optional[torch.Tensor] = None,
139
+ pixel_values: Optional[torch.FloatTensor] = None,
140
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
141
+ image_grid_thw: Optional[torch.LongTensor] = None,
142
+ video_grid_thw: Optional[torch.LongTensor] = None,
143
+ ):
144
+ inputs_embeds = model.get_input_embeddings()(input_ids)
145
+ image_mask, video_mask = None, None
146
+ if pixel_values is not None:
147
+ pixel_values = pixel_values.type(model.visual.dtype)
148
+ image_embeds, deepstack_image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw)
149
+ n_image_tokens = (input_ids == model.config.image_token_id).sum().item()
150
+ n_image_features = image_embeds.shape[0]
151
+ if n_image_tokens != n_image_features:
152
+ raise ValueError(
153
+ f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
154
+ )
155
+
156
+ mask = input_ids == model.config.image_token_id
157
+ mask_unsqueezed = mask.unsqueeze(-1)
158
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
159
+ image_mask = mask_expanded.to(inputs_embeds.device)
160
+
161
+ image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
162
+ inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
163
+
164
+ if pixel_values_videos is not None:
165
+ pixel_values_videos = pixel_values_videos.type(model.visual.dtype)
166
+ video_embeds, deepstack_video_embeds = model.visual(pixel_values_videos, grid_thw=video_grid_thw)
167
+ n_video_tokens = (input_ids == model.config.video_token_id).sum().item()
168
+ n_video_features = video_embeds.shape[0]
169
+ if n_video_tokens != n_video_features:
170
+ raise ValueError(
171
+ f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}"
172
+ )
173
+
174
+ mask = input_ids == model.config.video_token_id
175
+ mask_unsqueezed = mask.unsqueeze(-1)
176
+ mask_expanded = mask_unsqueezed.expand_as(inputs_embeds)
177
+ video_mask = mask_expanded.to(inputs_embeds.device)
178
+
179
+ video_embeds = video_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
180
+ inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
181
+
182
+ visual_pos_masks = None
183
+ deepstack_visual_embeds = None
184
+ if image_mask is not None and video_mask is not None:
185
+ # aggregate visual_pos_masks and deepstack_visual_embeds
186
+ image_mask = image_mask[..., 0]
187
+ video_mask = video_mask[..., 0]
188
+ visual_pos_masks = image_mask | video_mask
189
+ deepstack_visual_embeds = []
190
+ image_mask_joint = image_mask[visual_pos_masks]
191
+ video_mask_joint = video_mask[visual_pos_masks]
192
+ for img_embed, vid_embed in zip(deepstack_image_embeds, deepstack_video_embeds):
193
+ embed_joint = img_embed.new_zeros(visual_pos_masks.sum(), img_embed.shape[-1]).to(img_embed.device)
194
+ embed_joint[image_mask_joint, :] = img_embed
195
+ embed_joint[video_mask_joint, :] = vid_embed
196
+ deepstack_visual_embeds.append(embed_joint)
197
+ elif image_mask is not None:
198
+ image_mask = image_mask[..., 0]
199
+ visual_pos_masks = image_mask
200
+ deepstack_visual_embeds = deepstack_image_embeds
201
+ elif video_mask is not None:
202
+ video_mask = video_mask[..., 0]
203
+ visual_pos_masks = video_mask
204
+ deepstack_visual_embeds = deepstack_video_embeds
205
+
206
+ if pixel_values is None and pixel_values_videos is None:
207
+ config = model.config.vision_config
208
+ patch_dim = config.in_channels * config.temporal_patch_size * config.patch_size**2
209
+ pixel_values = torch.zeros((16, patch_dim), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
210
+ image_grid_thw = torch.tensor([[1, 4, 4]], dtype=torch.long, device=inputs_embeds.device)
211
+ image_embeds, dummy_deepstack_image_embeds = model.visual(pixel_values, grid_thw=image_grid_thw)
212
+ inputs_embeds += 0.0 * image_embeds.mean()
213
+ for emb in dummy_deepstack_image_embeds or []:
214
+ inputs_embeds += 0.0 * emb.mean()
215
+
216
+ if attention_mask is not None:
217
+ attention_mask = attention_mask.to(inputs_embeds.device)
218
+
219
+ return {
220
+ "inputs_embeds": inputs_embeds,
221
+ "attention_mask": attention_mask,
222
+ "visual_pos_masks": visual_pos_masks,
223
+ "deepstack_visual_embeds": deepstack_visual_embeds,
224
+ }
225
+
226
+
227
+ def qwen3_vl_base_forward(
228
+ self: "Qwen3VLModel",
229
+ input_ids: torch.LongTensor,
230
+ attention_mask: Optional[torch.Tensor] = None,
231
+ pixel_values: Optional[torch.FloatTensor] = None,
232
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
233
+ image_grid_thw: Optional[torch.LongTensor] = None,
234
+ video_grid_thw: Optional[torch.LongTensor] = None,
235
+ **kwargs,
236
+ ):
237
+ position_ids = kwargs.get("position_ids")
238
+ if isinstance(position_ids, torch.Tensor) and (position_ids.ndim != 3 or position_ids.size(0) != 4):
239
+ # we concat the text position ids with the 3D vision position ids by default
240
+ # see https://github.com/huggingface/transformers/pull/39447
241
+ raise ValueError("position_ids should be a 3D tensor of shape (4, batch_size, seq_length).")
242
+
243
+ input_kwargs = _get_input_embeds(
244
+ self, input_ids, attention_mask, pixel_values, pixel_values_videos, image_grid_thw, video_grid_thw
245
+ )
246
+ kwargs.update(input_kwargs) # avoid lora module to have multiple keyword arguments
247
+ outputs = self.language_model(input_ids=None, **kwargs)
248
+ return Qwen3VLModelOutputWithPast(last_hidden_state=outputs.last_hidden_state)
249
+
250
+
251
+ def qwen3_vl_model_forward(
252
+ self: "Qwen3VLForConditionalGeneration",
253
+ input_ids: torch.LongTensor,
254
+ labels: Optional[torch.LongTensor] = None,
255
+ **kwargs,
256
+ ) -> "Qwen3VLCausalLMOutputWithPast":
257
+ outputs = self.model(input_ids=input_ids, **kwargs)
258
+ hidden_states = outputs[0]
259
+ logits = self.lm_head(hidden_states)
260
+
261
+ return Qwen3VLCausalLMOutputWithPast(logits=logits)
EasyR1/verl/single_controller/base/register_center/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
EasyR1/verl/single_controller/base/worker_group.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ the class of WorkerGroup
16
+ """
17
+
18
+ import logging
19
+ import signal
20
+ import threading
21
+ import time
22
+ from typing import Any, Callable, Optional
23
+
24
+ from .decorator import MAGIC_ATTR, Dispatch, get_predefined_dispatch_fn, get_predefined_execute_fn
25
+
26
+
27
+ class ResourcePool:
28
+ """The resource pool with meta info such as world size."""
29
+
30
+ def __init__(
31
+ self, process_on_nodes: Optional[Any] = None, max_colocate_count: int = 10, n_gpus_per_node: int = 8
32
+ ) -> None:
33
+ if process_on_nodes is None:
34
+ process_on_nodes = []
35
+
36
+ self._store = process_on_nodes
37
+ self.max_colocate_count = max_colocate_count
38
+ self.n_gpus_per_node = n_gpus_per_node # this is left for future huawei GPU that contains 16 GPUs per node
39
+
40
+ def add_node(self, process_count):
41
+ self._store.append(process_count)
42
+
43
+ @property
44
+ def world_size(self):
45
+ return sum(self._store)
46
+
47
+ def __call__(self) -> Any:
48
+ return self._store
49
+
50
+ @property
51
+ def store(self):
52
+ return self._store
53
+
54
+ def local_world_size_list(self) -> list[int]:
55
+ nested_local_world_size_list = [
56
+ [local_world_size for _ in range(local_world_size)] for local_world_size in self._store
57
+ ]
58
+ return [item for row in nested_local_world_size_list for item in row]
59
+
60
+ def local_rank_list(self) -> list[int]:
61
+ nested_local_rank_list = [[i for i in range(local_world_size)] for local_world_size in self._store] # noqa: C416
62
+ return [item for row in nested_local_rank_list for item in row]
63
+
64
+
65
+ class ClassWithInitArgs:
66
+ """
67
+ This class stores a class constructor and the args/kwargs to construct the class.
68
+ It is used to instantiate the remote class.
69
+ """
70
+
71
+ def __init__(self, cls, *args, **kwargs) -> None:
72
+ self.cls = cls
73
+ self.args = args
74
+ self.kwargs = kwargs
75
+
76
+ def __call__(self) -> Any:
77
+ return self.cls(*self.args, **self.kwargs)
78
+
79
+
80
+ def check_workers_alive(workers: list, is_alive: Callable, gap_time: float = 1) -> None:
81
+ while True:
82
+ for worker in workers:
83
+ if not is_alive(worker):
84
+ logging.warning(f"Worker {worker} is not alive, sending signal to main thread")
85
+ signal.raise_signal(signal.SIGABRT)
86
+
87
+ time.sleep(gap_time)
88
+
89
+
90
+ class WorkerGroup:
91
+ """A group of workers"""
92
+
93
+ def __init__(self, resource_pool: ResourcePool, **kwargs) -> None:
94
+ self._is_init_with_detached_workers = True if resource_pool is None else False
95
+
96
+ if resource_pool is not None:
97
+ # handle the case when WorkGroup is attached to an existing one
98
+ self._procecss_dispatch_config = resource_pool()
99
+ else:
100
+ self._procecss_dispatch_config = None
101
+
102
+ self._workers = []
103
+ self._worker_names = []
104
+
105
+ self._master_addr = None
106
+ self._master_port = None
107
+
108
+ self._checker_thread: threading.Thread = None
109
+
110
+ def _is_worker_alive(self, worker):
111
+ raise NotImplementedError("WorkerGroup._is_worker_alive called, should be implemented in derived class.")
112
+
113
+ def _block_until_all_workers_alive(self) -> None:
114
+ while True:
115
+ all_state = [self._is_worker_alive(worker) for worker in self._workers]
116
+ if False in all_state:
117
+ time.sleep(1)
118
+ else:
119
+ break
120
+
121
+ def start_worker_aliveness_check(self, every_n_seconds=1) -> None:
122
+ # before starting checking worker aliveness, make sure all workers are already alive
123
+ self._block_until_all_workers_alive()
124
+
125
+ self._checker_thread = threading.Thread(
126
+ target=check_workers_alive, args=(self._workers, self._is_worker_alive, every_n_seconds)
127
+ )
128
+ self._checker_thread.start()
129
+
130
+ @property
131
+ def world_size(self):
132
+ return len(self._workers)
133
+
134
+ def _bind_worker_method(self, user_defined_cls, func_generator):
135
+ """
136
+ Bind the worker method to the WorkerGroup
137
+ """
138
+ for method_name in dir(user_defined_cls):
139
+ try:
140
+ method = getattr(user_defined_cls, method_name)
141
+ assert callable(method), f"{method_name} in {user_defined_cls} is not callable"
142
+ except Exception:
143
+ # if it is a property, it will fail because Class doesn't have instance property
144
+ continue
145
+
146
+ if hasattr(method, MAGIC_ATTR):
147
+ # this method is decorated by register
148
+ attribute = getattr(method, MAGIC_ATTR)
149
+ assert isinstance(attribute, dict), f"attribute must be a dictionary. Got {type(attribute)}"
150
+ assert "dispatch_mode" in attribute, "attribute must contain dispatch_mode in its key"
151
+
152
+ dispatch_mode = attribute["dispatch_mode"]
153
+ execute_mode = attribute["execute_mode"]
154
+ blocking = attribute["blocking"]
155
+
156
+ # get dispatch fn
157
+ if isinstance(dispatch_mode, Dispatch):
158
+ # get default dispatch fn
159
+ fn = get_predefined_dispatch_fn(dispatch_mode=dispatch_mode)
160
+ dispatch_fn = fn["dispatch_fn"]
161
+ collect_fn = fn["collect_fn"]
162
+ else:
163
+ assert isinstance(dispatch_mode, dict)
164
+ assert "dispatch_fn" in dispatch_mode
165
+ assert "collect_fn" in dispatch_mode
166
+ dispatch_fn = dispatch_mode["dispatch_fn"]
167
+ collect_fn = dispatch_mode["collect_fn"]
168
+
169
+ # get execute_fn_name
170
+ execute_mode = get_predefined_execute_fn(execute_mode=execute_mode)
171
+ wg_execute_fn_name = execute_mode["execute_fn_name"]
172
+
173
+ # get execute_fn from string
174
+ try:
175
+ execute_fn = getattr(self, wg_execute_fn_name)
176
+ assert callable(execute_fn), "execute_fn must be callable"
177
+ except Exception:
178
+ print(f"execute_fn {wg_execute_fn_name} is invalid")
179
+ raise
180
+
181
+ # bind a new method to the RayWorkerGroup
182
+ func = func_generator(
183
+ self,
184
+ method_name,
185
+ dispatch_fn=dispatch_fn,
186
+ collect_fn=collect_fn,
187
+ execute_fn=execute_fn,
188
+ blocking=blocking,
189
+ )
190
+
191
+ try:
192
+ setattr(self, method_name, func)
193
+ except Exception:
194
+ raise ValueError(f"Fail to set method_name {method_name}")
EasyR1/verl/single_controller/ray/__init__.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .base import RayClassWithInitArgs, RayResourcePool, RayWorkerGroup, create_colocated_worker_cls
16
+
17
+
18
+ __all__ = ["RayClassWithInitArgs", "RayResourcePool", "RayWorkerGroup", "create_colocated_worker_cls"]
EasyR1/verl/single_controller/ray/base.py ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import random
17
+ import re
18
+ import string
19
+ import time
20
+ from typing import Any, Optional
21
+ from unittest.mock import patch
22
+
23
+ import ray
24
+ from ray.actor import ActorHandle
25
+ from ray.experimental.state.api import get_actor
26
+ from ray.util import list_named_actors
27
+ from ray.util.placement_group import PlacementGroup, placement_group
28
+ from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy, PlacementGroupSchedulingStrategy
29
+
30
+ from ..base import ClassWithInitArgs, ResourcePool, Worker, WorkerGroup
31
+ from ..base.decorator import MAGIC_ATTR
32
+
33
+
34
+ __all__ = ["Worker"]
35
+
36
+
37
+ def get_random_string(length: int) -> str:
38
+ letters_digits = string.ascii_letters + string.digits
39
+ return "".join(random.choice(letters_digits) for _ in range(length))
40
+
41
+
42
+ def func_generator(self, method_name, dispatch_fn, collect_fn, execute_fn, blocking):
43
+ def func(*args, **kwargs):
44
+ args, kwargs = dispatch_fn(self, *args, **kwargs)
45
+ output = execute_fn(method_name, *args, **kwargs)
46
+ if blocking:
47
+ output = ray.get(output)
48
+ output = collect_fn(self, output)
49
+ return output
50
+
51
+ return func
52
+
53
+
54
+ def sort_placement_group_by_node_ip(pgs: list[PlacementGroup]) -> list[PlacementGroup]:
55
+ """
56
+ Sort the placement groups by node ip, all bundles in a single placement group should be on the same node.
57
+
58
+ FSDPCheckpointManager saves sharded model states and optimizer states in local storage, which requires RANK
59
+ to be consistent across nodes when resume from checkpoint.
60
+
61
+ With this function, if there's only one resource pool and there's no node change, RANK should be consistent
62
+ across nodes in multiple ray jobs, even if the whole ray cluster is restarted.
63
+ """
64
+ node_ip = {node["NodeID"]: node["NodeManagerAddress"] for node in ray.nodes()}
65
+ pg_ip = {}
66
+ for pg in pgs:
67
+ specs = ray._private.state.state.placement_group_table(pg.id)
68
+ # all bunles should be on the same node
69
+ node_id = specs["bundles_to_node_id"][0]
70
+ pg_ip[pg.id] = node_ip[node_id]
71
+
72
+ return sorted(pgs, key=lambda pg: pg_ip[pg.id])
73
+
74
+
75
+ class RayResourcePool(ResourcePool):
76
+ def __init__(
77
+ self,
78
+ process_on_nodes: list[int] = None,
79
+ use_gpu: bool = True,
80
+ name_prefix: str = "",
81
+ max_colocate_count: int = 5,
82
+ detached: bool = False,
83
+ ) -> None:
84
+ super().__init__(process_on_nodes, max_colocate_count)
85
+ self.use_gpu = use_gpu
86
+ # print(f"in RayProcessDispatchConfiguration: name_prefix = {name_prefix}")
87
+ self.name_prefix = name_prefix
88
+ self.pgs = None
89
+ self.detached = detached
90
+
91
+ def get_placement_groups(self, strategy: str = "STRICT_PACK", name: Optional[str] = None) -> list[PlacementGroup]:
92
+ if self.pgs is not None:
93
+ return self.pgs
94
+
95
+ pg_name_prefix = (
96
+ name if name else f"{self.name_prefix}verl_group_{'_'.join([str(count) for count in self._store])}:"
97
+ )
98
+ # print(f"pg_name_prefix = {pg_name_prefix}")
99
+ pg_scheme = [
100
+ [
101
+ {"CPU": self.max_colocate_count, "GPU": 1} if self.use_gpu else {"CPU": self.max_colocate_count}
102
+ for _ in range(process_count)
103
+ ]
104
+ for process_count in self._store
105
+ ]
106
+
107
+ lifetime = "detached" if self.detached else None
108
+
109
+ pgs = [
110
+ placement_group(bundles=bundles, strategy=strategy, name=pg_name_prefix + str(idx), lifetime=lifetime)
111
+ for idx, bundles in enumerate(pg_scheme)
112
+ ]
113
+
114
+ ray.get([pg.ready() for pg in pgs])
115
+
116
+ self.pgs = pgs
117
+ return pgs
118
+
119
+
120
+ def extract_pg_from_exist(
121
+ resource_pools: dict[str, RayResourcePool], src_role_names: list[str], resource_pool: RayResourcePool
122
+ ) -> list[PlacementGroup]:
123
+ src_pgs = [
124
+ pg
125
+ for role_name, resource_pool in resource_pools.items()
126
+ for pg in resource_pool.get_placement_groups()
127
+ if role_name in src_role_names
128
+ ]
129
+
130
+ sorted_src_pgs = sorted(src_pgs, key=lambda pg: pg.bundle_count, reverse=True)
131
+ sorted_process_on_nodes = sorted([(val, idx) for idx, val in enumerate(resource_pool.store)], reverse=True)
132
+
133
+ unsorted_pgs: list[tuple[int, PlacementGroup]] = []
134
+ searching_idx = 0
135
+ for request_process, original_idx in sorted_process_on_nodes:
136
+ assert searching_idx < len(sorted_src_pgs), f"no enough nodes for request: searching {searching_idx} th node"
137
+ assert request_process <= sorted_src_pgs[searching_idx].bundle_count, (
138
+ f"requesting {request_process} processes, bundle count cannot satisfy"
139
+ )
140
+ unsorted_pgs.append((original_idx, sorted_src_pgs[searching_idx]))
141
+ searching_idx += 1
142
+
143
+ return [pg for _, pg in sorted(unsorted_pgs)]
144
+
145
+
146
+ def merge_resource_pool(rp1: RayResourcePool, rp2: RayResourcePool) -> RayResourcePool:
147
+ assert rp1.use_gpu == rp2.use_gpu, "Both RayResourcePool must either use_gpu or not"
148
+ assert rp1.max_colocate_count == rp2.max_colocate_count, (
149
+ "Both RayResourcePool must has the same max_colocate_count"
150
+ )
151
+ assert rp1.n_gpus_per_node == rp2.n_gpus_per_node, "Both RayResourcePool must has the same n_gpus_per_node"
152
+ assert rp1.detached == rp2.detached, "Detached ResourcePool cannot be merged with non-detached ResourcePool"
153
+
154
+ new_store = rp1.store + rp2.store
155
+
156
+ merged = RayResourcePool(new_store, rp1.use_gpu, f"{rp1.name_prefix}_{rp2.name_prefix}")
157
+ merged.pgs = rp1.get_placement_groups() + rp2.get_placement_groups()
158
+
159
+ return merged
160
+
161
+
162
+ class RayClassWithInitArgs(ClassWithInitArgs):
163
+ def __init__(self, cls, *args, **kwargs) -> None:
164
+ # self._options = kwargs.pop('options', dict())
165
+ super().__init__(cls, *args, **kwargs)
166
+ self._options = {}
167
+ self._additional_resource = {}
168
+
169
+ def set_additional_resource(self, additional_resource):
170
+ self._additional_resource = additional_resource
171
+
172
+ def update_options(self, options: dict):
173
+ self._options.update(options)
174
+
175
+ def __call__(
176
+ self,
177
+ placement_group: PlacementGroup,
178
+ placement_group_bundle_idx: int,
179
+ use_gpu: bool = True,
180
+ num_gpus: int = 1,
181
+ sharing_with: Worker = None,
182
+ ) -> Any:
183
+ if sharing_with is not None:
184
+ target_node_id = ray.get(sharing_with.get_node_id.remote())
185
+ cuda_visible_devices = ray.get(sharing_with.get_cuda_visible_devices.remote())
186
+ options = {"scheduling_strategy": NodeAffinitySchedulingStrategy(node_id=target_node_id, soft=False)}
187
+ return self.cls.options(**options).remote(
188
+ *self.args, cuda_visible_devices=cuda_visible_devices, **self.kwargs
189
+ )
190
+
191
+ options = {
192
+ "scheduling_strategy": PlacementGroupSchedulingStrategy(
193
+ placement_group=placement_group, placement_group_bundle_index=placement_group_bundle_idx
194
+ )
195
+ }
196
+ options.update(self._options)
197
+
198
+ if use_gpu:
199
+ options["num_gpus"] = num_gpus
200
+
201
+ if len(self._additional_resource) > 1:
202
+ for k, v in self._additional_resource.items():
203
+ options[k] = v
204
+
205
+ # print("cls:", self.cls)
206
+ # print("args: ", self.args)
207
+ # print("kwargs: ", self.kwargs)
208
+ return self.cls.options(**options).remote(*self.args, **self.kwargs)
209
+
210
+
211
+ class RayWorkerGroup(WorkerGroup):
212
+ def __init__(
213
+ self,
214
+ resource_pool: RayResourcePool = None,
215
+ ray_cls_with_init: RayClassWithInitArgs = None,
216
+ bin_pack: bool = True,
217
+ name_prefix: str = None,
218
+ detached: bool = False,
219
+ worker_names: list[str] = None,
220
+ **kwargs,
221
+ ) -> None:
222
+ super().__init__(resource_pool=resource_pool, **kwargs)
223
+ self.ray_cls_with_init = ray_cls_with_init
224
+ self.name_prefix = get_random_string(length=6) if name_prefix is None else name_prefix
225
+
226
+ if worker_names is not None:
227
+ assert self._is_init_with_detached_workers
228
+ self._worker_names = worker_names
229
+
230
+ if self._is_init_with_detached_workers:
231
+ self._init_with_detached_workers(worker_names=worker_names)
232
+ else:
233
+ self._init_with_resource_pool(
234
+ resource_pool=resource_pool, ray_cls_with_init=ray_cls_with_init, bin_pack=bin_pack, detached=detached
235
+ )
236
+
237
+ if ray_cls_with_init is not None:
238
+ self._bind_worker_method(self.ray_cls_with_init.cls, func_generator)
239
+
240
+ def _is_worker_alive(self, worker: ActorHandle) -> bool:
241
+ worker_state_dict = get_actor(worker._actor_id.hex())
242
+ return worker_state_dict.get("state", "undefined") == "ALIVE" if worker_state_dict is not None else False
243
+
244
+ def _init_with_detached_workers(self, worker_names: list[str]) -> None:
245
+ workers = [ray.get_actor(name=name) for name in worker_names]
246
+ self._workers = workers
247
+ self._world_size = len(worker_names)
248
+
249
+ def _init_with_resource_pool(
250
+ self, resource_pool: RayResourcePool, ray_cls_with_init: RayClassWithInitArgs, bin_pack: bool, detached: bool
251
+ ):
252
+ use_gpu = resource_pool.use_gpu
253
+
254
+ strategy = "PACK"
255
+ if bin_pack:
256
+ strategy = "STRICT_PACK"
257
+
258
+ pgs = resource_pool.get_placement_groups(strategy=strategy)
259
+ world_size = resource_pool.world_size
260
+ self._world_size = world_size
261
+ # cia.add_kwarg("_world_size", world_size)
262
+ num_gpus = 1 / resource_pool.max_colocate_count
263
+
264
+ rank = -1
265
+ local_world_size = resource_pool.store[0]
266
+ for pg_idx, pg in enumerate(sort_placement_group_by_node_ip(pgs)):
267
+ assert local_world_size <= pg.bundle_count, f"when generating for {self.name_prefix}, for the "
268
+ for local_rank in range(local_world_size):
269
+ rank += 1
270
+
271
+ # we pass in environment variable at option so that Worker can use environment variable to set
272
+ env_vars = {
273
+ "WORLD_SIZE": str(world_size),
274
+ "RANK": str(rank),
275
+ "WG_PREFIX": self.name_prefix,
276
+ "WG_BACKEND": "ray",
277
+ "RAY_LOCAL_WORLD_SIZE": str(local_world_size),
278
+ "RAY_LOCAL_RANK": str(local_rank),
279
+ }
280
+ if rank != 0:
281
+ env_vars["MASTER_ADDR"] = self._master_addr
282
+ env_vars["MASTER_PORT"] = self._master_port
283
+
284
+ cia_name = type(ray_cls_with_init.cls).__name__
285
+ match = re.search(r"ActorClass\(([^)]+)\)", cia_name) # ray.remote(Obj) -> "ActorClass(Obj)"
286
+ cia_name = match.group(1) if match else cia_name # "ActorClass(Obj)" -> "Obj"
287
+ name = f"{self.name_prefix}{cia_name}_{pg_idx}:{local_rank}" # e.g. Worker_2:5
288
+
289
+ ray_cls_with_init.update_options({"runtime_env": {"env_vars": env_vars}, "name": name})
290
+
291
+ if detached:
292
+ ray_cls_with_init.update_options({"lifetime": "detached"})
293
+
294
+ # create a worker
295
+ worker = ray_cls_with_init(
296
+ placement_group=pg, placement_group_bundle_idx=local_rank, use_gpu=use_gpu, num_gpus=num_gpus
297
+ )
298
+ self._workers.append(worker)
299
+ self._worker_names.append(name)
300
+
301
+ if rank == 0:
302
+ register_center_actor = None
303
+ for _ in range(120):
304
+ if f"{self.name_prefix}_register_center" not in list_named_actors():
305
+ time.sleep(1)
306
+ else:
307
+ register_center_actor = ray.get_actor(f"{self.name_prefix}_register_center")
308
+ break
309
+ assert register_center_actor is not None, (
310
+ f"failed to get register_center_actor: {self.name_prefix}_register_center in {list_named_actors(all_namespaces=True)}"
311
+ )
312
+ rank_zero_info = ray.get(register_center_actor.get_rank_zero_info.remote())
313
+ self._master_addr, self._master_port = rank_zero_info["MASTER_ADDR"], rank_zero_info["MASTER_PORT"]
314
+ # print(f"rank_zero_info: {rank_zero_info}")
315
+ # print(f"master_addr: {self._master_addr}, master_port: {self._master_port}")
316
+
317
+ @property
318
+ def worker_names(self):
319
+ return self._worker_names
320
+
321
+ @classmethod
322
+ def from_detached(cls, worker_names=None, ray_cls_with_init=None):
323
+ worker_group = cls(
324
+ resource_pool=None, ray_cls_with_init=ray_cls_with_init, name_prefix=None, worker_names=worker_names
325
+ )
326
+ return worker_group
327
+
328
+ def spawn(self, prefix_set):
329
+ """
330
+ spawn to a dictionary of worker groups, each with a subset of method with prefix.
331
+
332
+ """
333
+
334
+ def _rebind_actor_methods(worker_group, actor_name):
335
+ """
336
+ bind the method with actor_prefix to its original name
337
+ """
338
+ prefix: str = actor_name + "_"
339
+ for method_name in dir(worker_group):
340
+ if method_name.startswith(prefix):
341
+ # only valid when Python >= 3.9
342
+ original_method_name = method_name.removeprefix(prefix)
343
+ method = getattr(worker_group, method_name)
344
+ setattr(worker_group, original_method_name, method)
345
+
346
+ new_worker_group_dict = {}
347
+ for prefix in prefix_set:
348
+ new_worker_group = self.from_detached(
349
+ worker_names=self._worker_names, ray_cls_with_init=self.ray_cls_with_init
350
+ )
351
+
352
+ _rebind_actor_methods(new_worker_group, prefix)
353
+ new_worker_group_dict[prefix] = new_worker_group
354
+ return new_worker_group_dict
355
+
356
+ def execute_rank_zero_sync(self, method_name: str, *args, **kwargs):
357
+ return ray.get(self.execute_rank_zero_async(method_name, *args, **kwargs))
358
+
359
+ def execute_rank_zero_async(self, method_name: str, *args, **kwargs):
360
+ remote_call = getattr(self._workers[0], method_name)
361
+ return remote_call.remote(*args, **kwargs)
362
+
363
+ def execute_rank_zero(self, method_name: str, *args, **kwargs):
364
+ return self.execute_rank_zero_async(method_name, *args, **kwargs)
365
+
366
+ def execute_all(self, method_name: str, *args, **kwargs):
367
+ return self.execute_all_async(method_name, *args, **kwargs)
368
+
369
+ def execute_all_sync(self, method_name: str, *args, **kwargs):
370
+ return ray.get(self.execute_all_async(method_name, *args, **kwargs))
371
+
372
+ def execute_all_async(self, method_name: str, *args, **kwargs):
373
+ # Here we assume that if all the parameters in args and kwargs are lists,
374
+ # and the lengths of all these lists are the same as len(self._workers),
375
+ # then we will send each element in the list to the corresponding worker.
376
+ # print(f"execute_all_async: method {method_name}({args}, {kwargs})")
377
+ length = len(self._workers)
378
+ if all(isinstance(arg, list) for arg in args) and all(isinstance(kwarg, list) for kwarg in kwargs.values()):
379
+ if all(len(arg) == length for arg in args) and all(len(kwarg) == length for kwarg in kwargs.values()):
380
+ # print(f"splitting args and kwargs into {length} shards")
381
+ result = []
382
+ for i in range(length):
383
+ sliced_args = tuple(arg[i] for arg in args)
384
+ sliced_kwargs = {k: v[i] for k, v in kwargs.items()}
385
+ remote_call = getattr(self._workers[i], method_name)
386
+ result.append(remote_call.remote(*sliced_args, **sliced_kwargs))
387
+ return result
388
+
389
+ return [getattr(worker, method_name).remote(*args, **kwargs) for worker in self._workers]
390
+
391
+ @property
392
+ def master_address(self):
393
+ return self._master_addr
394
+
395
+ @property
396
+ def master_port(self):
397
+ return self._master_port
398
+
399
+ @property
400
+ def workers(self):
401
+ return self._workers
402
+
403
+ @property
404
+ def world_size(self):
405
+ return self._world_size
406
+
407
+
408
+ """
409
+ Utilities that enables creating workers inside the same ray.Actor,
410
+ with code written in separate ray.Actors.
411
+ """
412
+
413
+
414
+ def _bind_workers_method_to_parent(cls, key, user_defined_cls):
415
+ """
416
+ Binds the methods of each worker to the WorkerDict.
417
+ Note that we only bind public methods that are decorated by register
418
+ """
419
+ for method_name in dir(user_defined_cls):
420
+ try:
421
+ method = getattr(user_defined_cls, method_name)
422
+ assert callable(method), f"{method_name} in {user_defined_cls} is not callable"
423
+ except Exception:
424
+ # if it is a property, it will fail because Class doesn't have instance property
425
+ continue
426
+
427
+ if hasattr(method, MAGIC_ATTR):
428
+
429
+ def generate_function(name):
430
+ def func(self, *args, **kwargs):
431
+ # dispatch to the actual worker
432
+ return getattr(self.worker_dict[key], name)(*args, **kwargs)
433
+
434
+ return func
435
+
436
+ func = generate_function(method_name)
437
+ # pass MAGIC_ATTR for outer worker group
438
+ setattr(func, MAGIC_ATTR, getattr(method, MAGIC_ATTR))
439
+ try:
440
+ method_name_with_prefix = key + "_" + method_name
441
+ setattr(cls, method_name_with_prefix, func)
442
+ # print(f'Binding {method_name_with_prefix}')
443
+ except Exception:
444
+ raise ValueError(f"Fail to set method_name {method_name}")
445
+
446
+
447
+ def _unwrap_ray_remote(cls):
448
+ if hasattr(cls, "__ray_actor_class__"):
449
+ cls = cls.__ray_actor_class__
450
+ return cls
451
+
452
+
453
+ def create_colocated_worker_cls(class_dict: dict[str, RayClassWithInitArgs]):
454
+ """
455
+ This function should return a class instance that delegates the calls to every
456
+ cls in cls_dict
457
+ """
458
+ cls_dict = {}
459
+ init_args_dict = {}
460
+ worker_cls = None
461
+ for key, cls in class_dict.items():
462
+ if worker_cls is None:
463
+ worker_cls = cls.cls.__ray_actor_class__.__base__
464
+ else:
465
+ assert worker_cls == cls.cls.__ray_actor_class__.__base__, (
466
+ "the worker class should be the same when share the same process"
467
+ )
468
+ cls_dict[key] = cls.cls
469
+ init_args_dict[key] = {"args": cls.args, "kwargs": cls.kwargs}
470
+
471
+ assert cls_dict.keys() == init_args_dict.keys()
472
+
473
+ # TODO: create a class with customizable name
474
+ class WorkerDict(worker_cls):
475
+ def __init__(self):
476
+ super().__init__()
477
+ self.worker_dict = {}
478
+ for key, user_defined_cls in cls_dict.items():
479
+ user_defined_cls = _unwrap_ray_remote(user_defined_cls)
480
+ # directly instantiate the class without remote
481
+ with patch.dict(os.environ, {"DISABLE_WORKER_INIT": "1"}):
482
+ self.worker_dict[key] = user_defined_cls(
483
+ *init_args_dict[key].get("args", ()), **init_args_dict[key].get("kwargs", {})
484
+ )
485
+
486
+ # now monkey-patch the methods from inner class to WorkerDict
487
+ for key, user_defined_cls in cls_dict.items():
488
+ user_defined_cls = _unwrap_ray_remote(user_defined_cls)
489
+ _bind_workers_method_to_parent(WorkerDict, key, user_defined_cls)
490
+
491
+ remote_cls = ray.remote(WorkerDict)
492
+ remote_cls = RayClassWithInitArgs(cls=remote_cls)
493
+ return remote_cls
EasyR1/verl/utils/checkpoint/checkpoint_manager.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import os
17
+ import random
18
+ import re
19
+ import shutil
20
+ import tempfile
21
+ from abc import ABC, abstractmethod
22
+ from typing import Any, Optional, Union
23
+
24
+ import numpy as np
25
+ import torch
26
+ import torch.distributed as dist
27
+ from filelock import FileLock
28
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
29
+ from transformers import PreTrainedTokenizer, ProcessorMixin
30
+
31
+
32
+ CHECKPOINT_TRACKER = "checkpoint_tracker.json"
33
+
34
+
35
+ class BaseCheckpointManager(ABC):
36
+ """
37
+ A checkpoint manager that saves and loads
38
+ - model
39
+ - optimizer
40
+ - lr_scheduler
41
+ - extra_states
42
+ in a SPMD way.
43
+
44
+ We save
45
+ - sharded model states and optimizer states
46
+ - full lr_scheduler states
47
+ - huggingface tokenizer and config for ckpt merge
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ model: FSDP,
53
+ optimizer: torch.optim.Optimizer,
54
+ lr_scheduler: torch.optim.lr_scheduler.LRScheduler,
55
+ processing_class: Union[PreTrainedTokenizer, ProcessorMixin],
56
+ ):
57
+ self.model = model
58
+ self.optimizer = optimizer
59
+ self.lr_scheduler = lr_scheduler
60
+ self.processing_class = processing_class
61
+
62
+ assert isinstance(self.model, FSDP)
63
+ self.rank = dist.get_rank()
64
+ self.world_size = dist.get_world_size()
65
+
66
+ @abstractmethod
67
+ def load_checkpoint(self, *args, **kwargs):
68
+ raise NotImplementedError
69
+
70
+ @abstractmethod
71
+ def save_checkpoint(self, *args, **kwargs):
72
+ raise NotImplementedError
73
+
74
+ @staticmethod
75
+ def local_mkdir(path: str) -> str:
76
+ if not os.path.isabs(path):
77
+ working_dir = os.getcwd()
78
+ path = os.path.join(working_dir, path)
79
+
80
+ # Using hash value of path as lock file name to avoid long file name
81
+ lock_filename = f"ckpt_{hash(path) & 0xFFFFFFFF:08x}.lock"
82
+ lock_path = os.path.join(tempfile.gettempdir(), lock_filename)
83
+
84
+ try:
85
+ with FileLock(lock_path, timeout=60):
86
+ os.makedirs(path, exist_ok=True)
87
+ except Exception as e:
88
+ print(f"Warning: Failed to acquire lock for {path}: {e}")
89
+ os.makedirs(path, exist_ok=True) # even if the lock is not acquired, try to create the directory
90
+
91
+ return path
92
+
93
+ @staticmethod
94
+ def get_rng_state() -> dict[str, Any]:
95
+ rng_state = {
96
+ "cpu": torch.get_rng_state(),
97
+ "cuda": torch.cuda.get_rng_state(),
98
+ "numpy": np.random.get_state(),
99
+ "random": random.getstate(),
100
+ }
101
+ return rng_state
102
+
103
+ @staticmethod
104
+ def load_rng_state(rng_state: dict[str, Any]):
105
+ torch.set_rng_state(rng_state["cpu"])
106
+ torch.cuda.set_rng_state(rng_state["cuda"])
107
+ np.random.set_state(rng_state["numpy"])
108
+ random.setstate(rng_state["random"])
109
+
110
+
111
+ def get_checkpoint_tracker_filename(root_path: str) -> str:
112
+ """
113
+ Tracker file rescords the latest chckpoint during training to restart from.
114
+ """
115
+ return os.path.join(root_path, CHECKPOINT_TRACKER)
116
+
117
+
118
+ def find_latest_ckpt(
119
+ path: str, directory_format: str = "global_step_{}"
120
+ ) -> tuple[Optional[str], Optional[dict[str, Any]]]:
121
+ """
122
+ Find the latest checkpoint in the save path.
123
+ """
124
+ tracker_file = get_checkpoint_tracker_filename(path)
125
+ if not os.path.exists(tracker_file):
126
+ return None, None
127
+
128
+ with open(tracker_file, "rb") as f:
129
+ checkpointer_tracker_info = json.load(f)
130
+
131
+ ckpt_path = os.path.join(path, directory_format.format(checkpointer_tracker_info["last_global_step"]))
132
+ if not os.path.exists(ckpt_path):
133
+ print(f"Checkpoint does not exist: {ckpt_path}")
134
+ return None, None
135
+
136
+ print(f"Found latest checkpoint: {ckpt_path}, will resume from it. Turn off `find_last_checkpoint` to disable it.")
137
+ return ckpt_path, checkpointer_tracker_info
138
+
139
+
140
+ def remove_obsolete_ckpt(
141
+ path: str, global_step: int, best_global_step: int, save_limit: int = -1, directory_format: str = "global_step_{}"
142
+ ):
143
+ """
144
+ Remove the obsolete checkpoints that exceed the save limit.
145
+ """
146
+ if save_limit <= 0 or not os.path.exists(path):
147
+ return
148
+
149
+ num_ckpt_to_keep = save_limit - 1 # exclude the current ckpt
150
+ pattern = re.escape(directory_format).replace(r"\{\}", r"(\d+)")
151
+ ckpt_global_steps = []
152
+ for folder in os.listdir(path):
153
+ if match := re.match(pattern, folder):
154
+ step = int(match.group(1))
155
+ if step < global_step:
156
+ ckpt_global_steps.append(step)
157
+
158
+ ckpt_global_steps.sort(reverse=True)
159
+ if best_global_step in ckpt_global_steps: # do not remove the best ckpt
160
+ ckpt_global_steps.remove(best_global_step)
161
+ num_ckpt_to_keep = max(num_ckpt_to_keep - 1, 0)
162
+
163
+ for step in ckpt_global_steps[num_ckpt_to_keep:]:
164
+ folder_path = os.path.join(path, directory_format.format(step))
165
+ try:
166
+ shutil.rmtree(folder_path, ignore_errors=True)
167
+ print(f"Removed obsolete checkpoint: {folder_path}")
168
+ except Exception as e:
169
+ print(f"Failed to remove {folder_path}: {e}")
EasyR1/verl/utils/checkpoint/fsdp_checkpoint_manager.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ import os
17
+ from dataclasses import asdict
18
+ from typing import Optional, Union
19
+
20
+ import torch
21
+ import torch.distributed as dist
22
+ from peft import PeftModel, get_peft_model_state_dict
23
+ from safetensors.torch import save_file
24
+ from torch.distributed._tensor import DTensor
25
+ from torch.distributed.checkpoint.state_dict import (
26
+ StateDictOptions,
27
+ get_model_state_dict,
28
+ get_state_dict,
29
+ set_state_dict,
30
+ )
31
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
32
+ from transformers import PreTrainedModel, PreTrainedTokenizer, ProcessorMixin
33
+
34
+ from .checkpoint_manager import BaseCheckpointManager
35
+
36
+
37
+ class FSDPCheckpointManager(BaseCheckpointManager):
38
+ """
39
+ A checkpoint manager that saves and loads
40
+ - model
41
+ - optimizer
42
+ - lr_scheduler
43
+ - extra_states
44
+ in a SPMD way.
45
+
46
+ We save
47
+ - sharded model states and optimizer states
48
+ - full lr_scheduler states
49
+ - huggingface tokenizer and config for ckpt merge
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ model: FSDP,
55
+ optimizer: torch.optim.Optimizer,
56
+ lr_scheduler: torch.optim.lr_scheduler.LRScheduler,
57
+ processing_class: Union[PreTrainedTokenizer, ProcessorMixin],
58
+ ):
59
+ super().__init__(model, optimizer, lr_scheduler, processing_class)
60
+
61
+ def load_checkpoint(self, path: Optional[str] = None):
62
+ if path is None:
63
+ return
64
+
65
+ # every rank download its own checkpoint
66
+ model_path = os.path.join(path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt")
67
+ optim_path = os.path.join(path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt")
68
+ extra_path = os.path.join(path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt")
69
+ print(f"[rank-{self.rank}]: Loading model from {os.path.abspath(model_path)}.")
70
+ print(f"[rank-{self.rank}]: Loading optimizer from {os.path.abspath(optim_path)}.")
71
+ print(f"[rank-{self.rank}]: Loading extra_state from {os.path.abspath(extra_path)}.")
72
+ model_state_dict = torch.load(model_path, weights_only=False)
73
+ optim_state_dict = torch.load(optim_path, weights_only=False)
74
+ extra_state_dict = torch.load(extra_path, weights_only=False)
75
+
76
+ state_dict_options = StateDictOptions(cpu_offload=True)
77
+ set_state_dict(
78
+ model=self.model,
79
+ optimizers=self.optimizer,
80
+ model_state_dict=model_state_dict,
81
+ optim_state_dict=optim_state_dict,
82
+ options=state_dict_options,
83
+ )
84
+ self.lr_scheduler.load_state_dict(extra_state_dict["lr_scheduler"])
85
+
86
+ # recover random state
87
+ if "rng" in extra_state_dict:
88
+ self.load_rng_state(extra_state_dict["rng"])
89
+
90
+ def save_checkpoint(self, path: str, save_model_only: bool = False):
91
+ path = self.local_mkdir(path)
92
+ dist.barrier()
93
+
94
+ # every rank will save its own model and optim shard
95
+ model_path = os.path.join(path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt")
96
+ optim_path = os.path.join(path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt")
97
+ extra_path = os.path.join(path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt")
98
+
99
+ state_dict_options = StateDictOptions(cpu_offload=True)
100
+ if save_model_only:
101
+ model_state_dict = get_model_state_dict(self.model, options=state_dict_options)
102
+ print(f"[rank-{self.rank}]: Saving model to {os.path.abspath(model_path)}.")
103
+ torch.save(model_state_dict, model_path)
104
+ else:
105
+ model_state_dict, optim_state_dict = get_state_dict(self.model, self.optimizer, options=state_dict_options)
106
+ extra_state_dict = {
107
+ "lr_scheduler": self.lr_scheduler.state_dict(),
108
+ "rng": self.get_rng_state(),
109
+ }
110
+ print(f"[rank-{self.rank}]: Saving model to {os.path.abspath(model_path)}.")
111
+ print(f"[rank-{self.rank}]: Saving optimizer to {os.path.abspath(optim_path)}.")
112
+ print(f"[rank-{self.rank}]: Saving extra_state to {os.path.abspath(extra_path)}.")
113
+ torch.save(model_state_dict, model_path)
114
+ torch.save(optim_state_dict, optim_path)
115
+ torch.save(extra_state_dict, extra_path)
116
+
117
+ # wait for everyone to dump to local
118
+ dist.barrier()
119
+
120
+ if self.rank == 0:
121
+ hf_path = os.path.join(path, "huggingface")
122
+ os.makedirs(hf_path, exist_ok=True)
123
+ assert isinstance(self.model._fsdp_wrapped_module, (PreTrainedModel, PeftModel))
124
+ self.model._fsdp_wrapped_module.config.save_pretrained(hf_path)
125
+ self.model._fsdp_wrapped_module.generation_config.save_pretrained(hf_path)
126
+ self.processing_class.save_pretrained(hf_path)
127
+
128
+ if isinstance(self.model._fsdp_wrapped_module, PeftModel):
129
+ lora_path = os.path.join(path, "lora_adapter")
130
+ peft_config = {}
131
+ if self.rank == 0:
132
+ os.makedirs(lora_path, exist_ok=True)
133
+ peft_config = asdict(self.model._fsdp_wrapped_module.peft_config.get("default", {}))
134
+ peft_config["task_type"] = peft_config["task_type"].value
135
+ peft_config["peft_type"] = peft_config["peft_type"].value
136
+ peft_config["target_modules"] = list(peft_config["target_modules"])
137
+
138
+ sharded_lora_weights = get_peft_model_state_dict(
139
+ self.model._fsdp_wrapped_module, state_dict=model_state_dict
140
+ )
141
+ cuda_device = torch.device("cuda")
142
+ lora_weights = {
143
+ name: sharded_weight.to(cuda_device).full_tensor().detach().cpu()
144
+ if isinstance(sharded_weight, DTensor)
145
+ else sharded_weight.detach().cpu()
146
+ for name, sharded_weight in sharded_lora_weights.items()
147
+ }
148
+ torch.cuda.empty_cache()
149
+ if self.rank == 0:
150
+ save_file(lora_weights, os.path.join(lora_path, "adapter_model.safetensors"))
151
+ with open(os.path.join(lora_path, "adapter_config.json"), "w", encoding="utf-8") as f:
152
+ json.dump(peft_config, f, ensure_ascii=False, indent=4)
153
+
154
+ dist.barrier()
155
+ if self.rank == 0:
156
+ print(f"[rank-{self.rank}]: Saved LoRA adapter to: {lora_path}")
157
+
158
+ dist.barrier()
EasyR1/verl/workers/sharding_manager/fsdp_vllm.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bytedance Ltd. and/or its affiliates
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import re
17
+ import time
18
+ from dataclasses import asdict
19
+ from typing import Iterable, Union
20
+
21
+ import torch
22
+ import torch.distributed as dist
23
+ from peft import PeftModel, get_peft_model_state_dict
24
+ from torch.distributed._tensor import DTensor
25
+ from torch.distributed.checkpoint.state_dict import get_model_state_dict
26
+ from torch.distributed.device_mesh import DeviceMesh
27
+ from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
28
+ from transformers import PreTrainedModel
29
+ from vllm import LLM
30
+ from vllm.distributed import parallel_state as vllm_ps
31
+
32
+ from ...protocol import DataProto, all_gather_data_proto
33
+ from ...utils.fsdp_utils import (
34
+ load_fsdp_model,
35
+ load_fsdp_submodule,
36
+ offload_fsdp_model,
37
+ offload_fsdp_submodule,
38
+ )
39
+ from ...utils.model_utils import print_gpu_memory_usage
40
+ from ...utils.vllm_utils import TensorLoRARequest
41
+ from .base import BaseShardingManager
42
+
43
+
44
+ class FSDPVLLMShardingManager(BaseShardingManager):
45
+ def __init__(
46
+ self,
47
+ module: FSDP,
48
+ inference_engine: LLM,
49
+ device_mesh: DeviceMesh,
50
+ use_param_offload: bool,
51
+ ):
52
+ self.module = module
53
+ self.inference_engine = inference_engine
54
+ self.device_mesh = device_mesh
55
+ self.use_param_offload = use_param_offload
56
+ self.loaded = False
57
+ self.is_lora = isinstance(self.module._fsdp_wrapped_module, PeftModel)
58
+
59
+ self.world_size = dist.get_world_size()
60
+ self.tp_size = vllm_ps.get_tensor_model_parallel_world_size()
61
+ self.tp_rank = vllm_ps.get_tensor_model_parallel_rank()
62
+ self.tp_group = vllm_ps.get_tensor_model_parallel_group().device_group
63
+
64
+ # Record freed bytes to estimate memory usage correctly
65
+ # https://github.com/vllm-project/vllm/pull/11743#issuecomment-2754338119
66
+ self.freed_bytes = 0
67
+
68
+ # Note that torch_random_states may be different on each dp rank
69
+ self.torch_random_states = torch.cuda.get_rng_state()
70
+ # get a random rng states
71
+ gen_dp_rank = self.device_mesh["dp"].get_local_rank()
72
+ torch.cuda.manual_seed(gen_dp_rank + 1000) # make sure all tp ranks have the same random states
73
+ self.gen_random_states = torch.cuda.get_rng_state()
74
+ torch.cuda.set_rng_state(self.torch_random_states)
75
+
76
+ def _rename_weight_keys(self, actor_weights: dict[str, Union[torch.Tensor, DTensor]], model: PreTrainedModel):
77
+ # convert state dict keys: https://github.com/huggingface/transformers/pull/38385
78
+ if not hasattr(model, "_checkpoint_conversion_mapping"):
79
+ return actor_weights
80
+
81
+ reverse_key_mapping = {v: k for k, v in model._checkpoint_conversion_mapping.items()}
82
+ original_weights = {}
83
+ for key, value in actor_weights.items():
84
+ for pattern, replacement in reverse_key_mapping.items():
85
+ replacement = replacement.lstrip("^") # strip off un-needed chars and patterns
86
+ replacement = re.sub(r"\(.*\)", "", replacement)
87
+ key, n_replace = re.subn(pattern, replacement, key)
88
+ # Early exit of the loop
89
+ if n_replace > 0:
90
+ break
91
+
92
+ original_weights[key] = value
93
+
94
+ return original_weights
95
+
96
+ def _make_weight_iterator(
97
+ self, actor_weights: dict[str, Union[torch.Tensor, DTensor]]
98
+ ) -> Iterable[tuple[str, torch.Tensor]]:
99
+ for name, tensor in actor_weights.items():
100
+ yield name, tensor.full_tensor() if isinstance(tensor, DTensor) else tensor
101
+
102
+ def _collect_lora_weights(self) -> dict:
103
+ """Collect LoRA weights from each transformer layer."""
104
+ lora_weights = {}
105
+ peft_model = getattr(self.module, "_fsdp_wrapped_module", self.module)
106
+ for name, submodule in self.module.named_modules():
107
+ # Transformer layers are typically named ...layers.N (numeric suffix).
108
+ if not name.rsplit("layers.", 1)[-1].isdigit():
109
+ continue
110
+
111
+ if self.use_param_offload:
112
+ load_fsdp_submodule(submodule)
113
+
114
+ peft_prefix = name.replace("_fsdp_wrapped_module.base_model.model.", "base_model.model.")
115
+ layer_weights = get_model_state_dict(submodule)
116
+ layer_lora_weights = get_peft_model_state_dict(peft_model, state_dict=layer_weights)
117
+ for lora_module_name, lora_weight in layer_lora_weights.items():
118
+ key = f"{peft_prefix}.{lora_module_name}"
119
+ if isinstance(lora_weight, DTensor):
120
+ lora_weights[key] = lora_weight.full_tensor().detach().cpu()
121
+ else:
122
+ lora_weights[key] = lora_weight.detach().cpu()
123
+
124
+ submodule._is_root = False
125
+ if self.use_param_offload:
126
+ offload_fsdp_submodule(submodule)
127
+
128
+ torch.cuda.empty_cache()
129
+
130
+ return lora_weights
131
+
132
+ def _sync_weight_to_vllm(self):
133
+ if self.use_param_offload and not self.is_lora:
134
+ load_fsdp_model(self.module)
135
+
136
+ if self.is_lora:
137
+ peft_config = self.module._fsdp_wrapped_module.peft_config.get("default", None)
138
+ actor_weights = self._collect_lora_weights()
139
+ else:
140
+ actor_weights = get_model_state_dict(self.module)
141
+ actor_weights = self._rename_weight_keys(actor_weights, self.module._fsdp_wrapped_module)
142
+
143
+ print_gpu_memory_usage("After gather model weights in sharding manager")
144
+
145
+ model = self.inference_engine.llm_engine.model_executor.driver_worker.worker.model_runner.model
146
+ if not self.is_lora:
147
+ model.load_weights(self._make_weight_iterator(actor_weights))
148
+ else:
149
+ lora_int_id = int(time.time_ns() % 0x7FFFFFFF)
150
+ lora_reqest = TensorLoRARequest(
151
+ lora_name=f"{lora_int_id}",
152
+ lora_int_id=lora_int_id,
153
+ lora_path="simon_lora_path",
154
+ peft_config=asdict(peft_config),
155
+ lora_tensors=actor_weights,
156
+ )
157
+ self.inference_engine.llm_engine.add_lora(lora_reqest)
158
+ print_gpu_memory_usage("After load LoRA weights in sharding manager")
159
+
160
+ del actor_weights
161
+ if self.use_param_offload and not self.is_lora:
162
+ offload_fsdp_model(self.module)
163
+
164
+ torch.cuda.empty_cache()
165
+ print_gpu_memory_usage("After sync model weights in sharding manager")
166
+
167
+ def load_vllm_and_sync_weights(self):
168
+ """Load vllm engine and sync model weights to vllm model."""
169
+ # NOTE: Basically, we only need `torch.cuda.empty_cache()` before vllm wake_up and
170
+ # after vllm sleep, since vllm has its own caching memory allocator CuMemAllocator.
171
+ # Out of vllm scope, we should avoid empty cache to let pytorch using caching memory
172
+ # to speed up memory allocations.
173
+ #
174
+ # pytorch: https://pytorch.org/docs/stable/notes/cuda.html#memory-management
175
+ # vllm: https://github.com/vllm-project/vllm/blob/v0.7.3/vllm/device_allocator/cumem.py#L103
176
+ torch.cuda.empty_cache()
177
+ assert self.loaded is False, "vllm engine has already been loaded"
178
+ self.loaded = True
179
+
180
+ print_gpu_memory_usage("Before vllm wake up in sharding manager")
181
+ if "tags" in inspect.signature(self.inference_engine.wake_up).parameters:
182
+ self.inference_engine.wake_up(tags=["weights"])
183
+ else:
184
+ self.inference_engine.wake_up()
185
+
186
+ self._sync_weight_to_vllm()
187
+
188
+ if "tags" in inspect.signature(self.inference_engine.wake_up).parameters:
189
+ self.inference_engine.wake_up(tags=["kv_cache"])
190
+
191
+ print_gpu_memory_usage("After vllm wake up in sharding manager")
192
+ # important: need to manually set the random states of each tp to be identical.
193
+ if self.device_mesh is not None:
194
+ self.torch_random_states = torch.cuda.get_rng_state()
195
+ torch.cuda.set_rng_state(self.gen_random_states)
196
+
197
+ def offload_vllm(self):
198
+ """Offload vllm engine."""
199
+ assert self.loaded is True, "vllm engine has not been loaded"
200
+ self.loaded = False
201
+
202
+ print_gpu_memory_usage("Before vllm offload in sharding manager")
203
+ free_bytes_before_sleep = torch.cuda.mem_get_info()[0]
204
+ self.inference_engine.sleep(level=1)
205
+ free_bytes_after_sleep = torch.cuda.mem_get_info()[0]
206
+ self.freed_bytes = free_bytes_after_sleep - free_bytes_before_sleep
207
+ print_gpu_memory_usage("After vllm offload in sharding manager")
208
+
209
+ self.module.train()
210
+ torch.cuda.empty_cache() # add empty cache after each compute
211
+
212
+ # restore random states
213
+ if self.device_mesh is not None:
214
+ self.gen_random_states = torch.cuda.get_rng_state()
215
+ torch.cuda.set_rng_state(self.torch_random_states)
216
+
217
+ def preprocess_data(self, data: DataProto) -> DataProto:
218
+ """All gather across tp group to make each rank has identical input."""
219
+ all_gather_data_proto(data, size=self.tp_size, group=self.tp_group)
220
+ return data
221
+
222
+ def postprocess_data(self, data: DataProto) -> DataProto:
223
+ """Get chunk data of this tp rank since we do all gather in preprocess."""
224
+ if self.tp_size > 1:
225
+ data = data.chunk(chunks=self.tp_size)[self.tp_rank]
226
+
227
+ return data