Spaces:
Runtime error
Runtime error
rai-sant commited on
Commit ·
e35fa73
1
Parent(s): b3663f5
Add requirements.txt with dependencies
Browse filesFiles changed (20)
- .DS_StoreAdded
- DockerfileAdded+17
- LICENSEAdded+201
- MakefileAdded+20
- README.md+255-12
- assets/plan-of-attack.pngAdded
- configs/ddp.yamlAdded+16
- configs/zero2.yamlAdded+21
- configs/zero3.yamlAdded+22
- requirements.txtAdded+7
- setup.cfgAdded+41
- setup.pyAdded+135
- slurm/evaluate.slurmAdded+50
- slurm/generate.slurmAdded+201
- slurm/sft.slurmAdded+88
- src/open_r1/__init__.pyAdded+36
- src/open_r1/evaluate.pyAdded+103
- src/open_r1/generate.pyAdded+156
- src/open_r1/grpo.pyAdded+141
- src/open_r1/sft.pyAdded+101
1234567891011121314151617FROM python:3.11
RUN useradd -m -u 1000 userUSER userENV PATH="/home/user/.local/bin:$PATH"
WORKDIR /app
# Copy and install requirementsCOPY --chown=user ./requirements.txt requirements.txtRUN pip install --no-cache-dir --upgrade -r requirements.txt
# Copy application filesCOPY --chown=user . /app
# Set the application to run on port 7860CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314151617181920.PHONY: style quality
# make sure to test the local checkout in scripts and not the pre-installed one (don't use quotes!)export PYTHONPATH = src
check_dirs := src
style: black --line-length 119 --target-version py310 $(check_dirs) setup.py isort $(check_dirs) setup.py
quality: black --check --line-length 119 --target-version py310 $(check_dirs) setup.py isort --check-only $(check_dirs) setup.py flake8 --max-line-length 119 $(check_dirs) setup.py
# Evaluation
evaluate:123456789101112123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255---title: DeepSeek R1emoji: 🚀colorFrom: yellowcolorTo: purplesdk: dockerpinned: falselicense: apache-2.0short_description: deploy and run the open-source DeepSeek---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Open R1
*A fully open reproduction of DeepSeek-R1. This repo is work in progress, let's build it together!*
## Overview
The goal of this repo is to build the missing pieces of the R1 pipeline such that everybody can reproduce and build on top of it. The project is simple by design and mostly consists of:
- `src/open_r1` contains the scripts to train and evaluate models as well generate synthetic data: - `grpo.py`: trains a model with GRPO on a given dataset. - `sft.py`: simple SFT of a model on a dataset. - `evaluate.py`: evaluates a model on the R1 benchmarks. - `generate.py`: generate synthetic data from a model using [Distilabel](https://github.com/argilla-io/distilabel).- `Makefile` contains an easy to run command for each step in the R1 pipeline leveraging the scripts above.
### Plan of attack
We will use the DeepSeek-R1 [tech report](https://github.com/deepseek-ai/DeepSeek-R1) as a guide, which can roughly be broken down into three main steps:
* Step 1: replicate the R1-Distill models by distilling a high-quality corpus from DeepSeek-R1.* Step 2: replicate the pure RL pipeline that DeepSeek used to create R1-Zero. This will likely involve curating new, large-scale datasets for math, reasoning, and code.* Step 3: show we can go from base model to RL-tuned via multi-stage training.
<center> <img src="assets/plan-of-attack.png" width="500"></center>
## Installation
To run the code in this project, first, create a Python virtual environment using e.g. Conda:
```shellconda create -n openr1 python=3.11 && conda activate openr1```
Next, install vLLM:
```shellpip install vllm==0.6.6.post1
# For HF (cluster only has CUDA 12.1)pip install vllm==0.6.6.post1 --extra-index-url https://download.pytorch.org/whl/cu121```
This will also install PyTorch `v2.5.1` and it is **very important** to use this version since the vLLM binaries are compiled for it. You can then install the remaining dependencies for your specific use case via `pip install -e .[LIST OF MODES]`. For most contributors, we recommend:
```shellpip install -e ".[dev]"```
Next, log into your Hugging Face and Weights and Biases accounts as follows:
```shellhuggingface-cli loginwandb login```
Finally, check your system has Git LFS installed so that you can load and push models/datasets to the Hugging Face Hub:
```shellgit-lfs --version```
If it isn't installed, run:
```shellsudo apt-get install git-lfs```
## Training models
We support training models with either DDP or DeepSpeed ZeRO-2 and ZeRO-3. To switch between methods, simply change the path to the `accelerate` YAML config in `configs`.
> [!NOTE]> The training commands below are configured for a node of 8 x H100s (80GB). For different hardware and topologies, you may need to tune the batch size and number of gradient accumulation steps.
### SFT
To run SFT on a dataset distilled from DeepSeek-R1 with reasoning traces such as [Bespoke-Stratos-17k](https://huggingface.co/datasets/bespokelabs/Bespoke-Stratos-17k), run:
```accelerate launch --config_file=configs/zero3.yaml src/open_r1/sft.py \ --model_name_or_path Qwen/Qwen2.5-Math-1.5B-Instruct \ --dataset_name HuggingFaceH4/Bespoke-Stratos-17k \ --learning_rate 2.0e-5 \ --num_train_epochs 1 \ --packing \ --max_seq_length 4096 \ --per_device_train_batch_size 4 \ --per_device_eval_batch_size 4 \ --gradient_accumulation_steps 4 \ --gradient_checkpointing \ --bf16 \ --logging_steps 5 \ --eval_strategy steps \ --eval_steps 100 \ --output_dir data/Qwen2.5-1.5B-Open-R1-Distill```
To launch a Slurm job, run:
```shellsbatch --output=/path/to/logs/%x-%j.out --err=/path/to/logs/%x-%j.err slurm/sft.slurm {model} {dataset} {accelerator}```
Here `{model}` and `{dataset}` refer to the model and dataset IDs on the Hugging Face Hub, while `{accelerator}` refers to the choice of 🤗 Accelerate config in `configs`.
### GRPO
```accelerate launch --config_file configs/zero3.yaml src/open_r1/grpo.py \ --output_dir DeepSeek-R1-Distill-Qwen-7B-GRPO \ --model_name_or_path deepseek-ai/DeepSeek-R1-Distill-Qwen-7B \ --dataset_name AI-MO/NuminaMath-TIR \ --max_prompt_length 256 \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 16 \ --logging_steps 10 \ --bf16```
## Evaluating models
We use `lighteval` to evaluate models, with custom tasks defined in `src/open_r1/evaluate.py`. For models which fit on a single GPU, run:
```shellMODEL=deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5BMODEL_ARGS="pretrained=$MODEL,dtype=float16,max_model_length=32768,gpu_memory_utilisation=0.8"TASK=aime24OUTPUT_DIR=data/evals/$MODEL
lighteval vllm $MODEL_ARGS "custom|$TASK|0|0" \ --custom-tasks src/open_r1/evaluate.py \ --use-chat-template \ --system-prompt="Please reason step by step, and put your final answer within \boxed{}." \ --output-dir $OUTPUT_DIR ```
To increase throughput across multiple GPUs, use _data parallel_ as follows:
```shellNUM_GPUS=8MODEL=deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5BMODEL_ARGS="pretrained=$MODEL,dtype=float16,data_parallel_size=$NUM_GPUS,max_model_length=32768,gpu_memory_utilisation=0.8"TASK=aime24OUTPUT_DIR=data/evals/$MODEL
lighteval vllm $MODEL_ARGS "custom|$TASK|0|0" \ --custom-tasks src/open_r1/evaluate.py \ --use-chat-template \ --system-prompt="Please reason step by step, and put your final answer within \boxed{}." \ --output-dir $OUTPUT_DIR ```
For large models which require sharding across GPUs, use _tensor parallel_ and run:
```shellNUM_GPUS=8MODEL=deepseek-ai/DeepSeek-R1-Distill-Qwen-32BMODEL_ARGS="pretrained=$MODEL,dtype=float16,tensor_parallel_size=$NUM_GPUS,max_model_length=32768,gpu_memory_utilisation=0.8"TASK=aime24OUTPUT_DIR=data/evals/$MODEL
export VLLM_WORKER_MULTIPROC_METHOD=spawnlighteval vllm $MODEL_ARGS "custom|$TASK|0|0" \ --custom-tasks src/open_r1/evaluate.py \ --use-chat-template \ --system-prompt="Please reason step by step, and put your final answer within \boxed{}." \ --output-dir $OUTPUT_DIR ```
## Data generation
### Generate data from a smol distilled R1 model
The following example can be run in 1xH100. First install the following dependencies:
```shellpip install "distilabel[vllm]>=1.5.2"```
Now save the following snippet into a file named `pipeline.py` and run with `python pipeline.py`. It will generate for each of the 10 examples 4 generations (change the username for the repository to your org/user name):
```pythonfrom datasets import load_datasetfrom distilabel.models import vLLMfrom distilabel.pipeline import Pipelinefrom distilabel.steps.tasks import TextGeneration
prompt_template = """\You will be given a problem. Please reason step by step, and put your final answer within \boxed{}:{{ instruction }}"""
dataset = load_dataset("AI-MO/NuminaMath-TIR", split="train").select(range(10))
model_id = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B" # Exchange with another smol distilled r1
with Pipeline( name="distill-qwen-7b-r1", description="A pipeline to generate data from a distilled r1 model",) as pipeline:
llm = vLLM( model=model_id, tokenizer=model_id, extra_kwargs={ "tensor_parallel_size": 1, "max_model_len": 8192, }, generation_kwargs={ "temperature": 0.6, "max_new_tokens": 8192, }, ) prompt_column = "problem" text_generation = TextGeneration( llm=llm, template=prompt_template, num_generations=4, input_mappings={"instruction": prompt_column} if prompt_column is not None else {} )
if __name__ == "__main__": distiset = pipeline.run(dataset=dataset) distiset.push_to_hub(repo_id="username/numina-deepseek-r1-qwen-7b")```
Take a look at the sample dataset at [HuggingFaceH4/numina-deepseek-r1-qwen-7b](https://huggingface.co/datasets/HuggingFaceH4/numina-deepseek-r1-qwen-7b).
### Generate data from DeepSeek-R1
To run the bigger DeepSeek-R1, we used 2 nodes of 8xH100 each one, using the slurm file present in this repo at `slurm/generate.slurm`. First, install the dependencies:
(for now we need to install the vllm dev wheel that [fixes the R1 cuda graph capture](https://github.com/vllm-project/vllm/commits/221d388cc5a836fa189305785ed7e887cea8b510/csrc/moe/moe_align_sum_kernels.cu))```shellpip install https://wheels.vllm.ai/221d388cc5a836fa189305785ed7e887cea8b510/vllm-1.0.0.dev-cp38-abi3-manylinux1_x86_64.whl --extra-index-url https://download.pytorch.org/whl/cu121
pip install "distilabel[vllm,ray,openai]>=1.5.2"```
And then, place the `generate.slurm` file at the same level as `src/open_r1/generate.py` (it will try to run the file in the relative path), and run the following command:
```shellsbatch generate.slurm \ --hf-dataset AI-MO/NuminaMath-TIR \ --temperature 0.6 \ --prompt-column problem \ --model deepseek-ai/DeepSeek-R1 \ --hf-output-dataset username/r1-dataset```12345678910111213141516compute_environment: LOCAL_MACHINEdebug: falsedistributed_type: MULTI_GPUdowncast_bf16: 'no'gpu_ids: allmachine_rank: 0main_training_function: mainmixed_precision: bf16num_machines: 1num_processes: 8rdzv_backend: staticsame_network: truetpu_env: []tpu_use_cluster: falsetpu_use_sudo: falseuse_cpu: false123456789101112131415161718192021compute_environment: LOCAL_MACHINEdebug: falsedeepspeed_config: deepspeed_multinode_launcher: standard offload_optimizer_device: none offload_param_device: none zero3_init_flag: false zero_stage: 2distributed_type: DEEPSPEEDdowncast_bf16: 'no'machine_rank: 0main_training_function: mainmixed_precision: bf16num_machines: 1num_processes: 8rdzv_backend: staticsame_network: truetpu_env: []tpu_use_cluster: falsetpu_use_sudo: falseuse_cpu: false12345678910111213141516171819202122compute_environment: LOCAL_MACHINEdebug: falsedeepspeed_config: deepspeed_multinode_launcher: standard offload_optimizer_device: none offload_param_device: none zero3_init_flag: true zero3_save_16bit_model: true zero_stage: 3distributed_type: DEEPSPEEDdowncast_bf16: 'no'machine_rank: 0main_training_function: mainmixed_precision: bf16num_machines: 1num_processes: 8rdzv_backend: staticsame_network: truetpu_env: []tpu_use_cluster: falsetpu_use_sudo: falseuse_cpu: false1234567fastapiuvicorn[standard]torch>=2.0transformersvllm==0.6.6.post1distilabel[vllm]>=1.5.2datasets1234567891011121314151617181920212223242526272829303132333435363738394041[isort]default_section = FIRSTPARTYensure_newline_before_comments = Trueforce_grid_wrap = 0include_trailing_comma = Trueknown_first_party = open_r1known_third_party = transformers datasets fugashi git h5py matplotlib nltk numpy packaging pandas psutil pytest rouge_score sacrebleu seqeval sklearn streamlit torch tqdm
line_length = 119lines_after_imports = 2multi_line_output = 3use_parentheses = True
[flake8]ignore = E203, E501, E741, W503, W605max-line-length = 119per-file-ignores = # imported but unused __init__.py: F401
[tool:pytest]doctest_optionflags=NUMBER NORMALIZE_WHITESPACE ELLIPSIS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.## Adapted from huggingface/transformers: https://github.com/huggingface/transformers/blob/21a2d900eceeded7be9edc445b56877b95eda4ca/setup.py
import reimport shutilfrom pathlib import Path
from setuptools import find_packages, setup
# Remove stale open_r1.egg-info directory to avoid https://github.com/pypa/pip/issues/5466stale_egg_info = Path(__file__).parent / "open_r1.egg-info"if stale_egg_info.exists(): print( ( "Warning: {} exists.\n\n" "If you recently updated open_r1, this is expected,\n" "but it may prevent open_r1 from installing in editable mode.\n\n" "This directory is automatically generated by Python's packaging tools.\n" "I will remove it now.\n\n" "See https://github.com/pypa/pip/issues/5466 for details.\n" ).format(stale_egg_info) ) shutil.rmtree(stale_egg_info)
# IMPORTANT: all dependencies should be listed here with their version requirements, if any.# * If a dependency is fast-moving (e.g. transformers), pin to the exact version_deps = [ "accelerate>=1.2.1", "bitsandbytes>=0.43.0", "black>=24.4.2", "datasets>=3.2.0", "deepspeed==0.15.4", "distilabel[vllm,ray,openai]>=1.5.2", "einops>=0.8.0", "flake8>=6.0.0", "hf_transfer>=0.1.4", "huggingface-hub[cli]>=0.19.2,<1.0", "isort>=5.12.0", "liger_kernel==0.5.2", "lighteval @ git+https://github.com/huggingface/lighteval.git@4f381b352c0e467b5870a97d41cb66b487a2c503#egg=lighteval[math]", "math-verify>=0.3.2", # Used for math verification in grpo "packaging>=23.0", "parameterized>=0.9.0", "pytest", "safetensors>=0.3.3", "sentencepiece>=0.1.99", "torch>=2.5.1", "transformers @ git+https://github.com/huggingface/transformers.git@main", "trl @ git+https://github.com/huggingface/trl.git@main", "vllm==0.6.6.post1", "wandb>=0.19.1",]
# this is a lookup table with items like:## tokenizers: "tokenizers==0.9.4"# packaging: "packaging"## some of the values are versioned whereas others aren't.deps = {b: a for a, b in (re.findall(r"^(([^!=<>~ \[\]]+)(?:\[[^\]]+\])?(?:[!=<>~ ].*)?$)", x)[0] for x in _deps)}
def deps_list(*pkgs): return [deps[pkg] for pkg in pkgs]
extras = {}extras["tests"] = deps_list("pytest", "parameterized")extras["torch"] = deps_list("torch")extras["quality"] = deps_list("black", "isort", "flake8")extras["eval"] = deps_list("lighteval", "math-verify")extras["dev"] = extras["quality"] + extras["tests"] + extras["eval"]
# core dependencies shared across the whole project - keep this to a bare minimum :)install_requires = [ deps["accelerate"], deps["bitsandbytes"], deps["einops"], deps["datasets"], deps["deepspeed"], deps["hf_transfer"], deps["huggingface-hub"], deps["liger_kernel"], deps["packaging"], # utilities from PyPA to e.g., compare versions deps["safetensors"], deps["sentencepiece"], deps["transformers"], deps["trl"],]
setup( name="open-r1", version="0.1.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots) author="The Hugging Face team (past and future)", author_email="lewis@huggingface.co", description="Open R1", long_description=open("README.md", "r", encoding="utf-8").read(), long_description_content_type="text/markdown", keywords="llm inference-time compute reasoning", license="Apache", url="https://github.com/huggingface/open-r1", package_dir={"": "src"}, packages=find_packages("src"), zip_safe=False, extras_require=extras, python_requires=">=3.10.9", install_requires=install_requires, classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", "Intended Audience :: Education", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Topic :: Scientific/Engineering :: Artificial Intelligence", ],)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#!/bin/bash#SBATCH --job-name=open-r1-evaluate#SBATCH --nodes=1#SBATCH --ntasks-per-node=1#SBATCH --exclusive#SBATCH --gres=gpu:8#SBATCH --partition=hopper-prod #SBATCH --time=01:59:00#SBATCH --output=./logs/evaluate/%x-%j.out#SBATCH --err=./logs/evaluate/%x-%j.err
# Usage: sbatch slurm/evaluate.slurm deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B aime24
set -x -e
source ~/.bashrcconda activate openr1module load cuda/12.1echo "START TIME: $(date)"echo "PYTHON ENV: $(which python)"
NUM_GPUS=8MODEL=$1TASK=$2MODEL_ARGS="pretrained=$MODEL,dtype=float16,data_parallel_size=$NUM_GPUS,max_model_length=32768,gpu_memory_utilisation=0.8"OUTPUT_DIR=data/evals/$MODEL
# force crashing on nccl issues like hanging broadcastexport NCCL_ASYNC_ERROR_HANDLING=1# export NCCL_DEBUG=INFO# export NCCL_DEBUG_SUBSYS=COLL# export NCCL_SOCKET_NTHREADS=1# export NCCL_NSOCKS_PERTHREAD=1# export CUDA_LAUNCH_BLOCKING=1
# Specific configuration optimized for the Hugging Face Compute Cluster# Be ye warned this may not work on other clusters!module load cuda/12.1
lighteval vllm $MODEL_ARGS "custom|$TASK|0|0" \ --custom-tasks src/open_r1/evaluate.py \ --use-chat-template \ --system-prompt="Please reason step by step, and put your final answer within \boxed{}." \ --save-details --output-dir $OUTPUT_DIR
echo "END TIME: $(date)"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#!/bin/bash#SBATCH --job-name=deepseek-r1-generation#SBATCH --partition=hopper-prod#SBATCH --qos=normal#SBATCH --nodes=4#SBATCH --exclusive#SBATCH --gpus-per-node=8#SBATCH --output=./logs/%x-%j.out#SBATCH --err=./logs/%x-%j.err#SBATCH --time=08:00:00
# Parse command line argumentswhile [[ $# -gt 0 ]]; do case $1 in --hf-dataset) HF_DATASET="$2" shift 2 ;; --hf-dataset-config) HF_DATASET_CONFIG="$2" shift 2 ;; --hf-dataset-split) HF_DATASET_SPLIT="$2" shift 2 ;; --prompt-column) PROMPT_COLUMN="$2" shift 2 ;; --model) MODEL="$2" shift 2 ;; --temperature) TEMPERATURE="$2" shift 2 ;; --top-p) TOP_P="$2" shift 2 ;; --max-new-tokens) MAX_NEW_TOKENS="$2" shift 2 ;; --num-generations) NUM_GENERATIONS="$2" shift 2 ;; --hf-output-dataset) HF_OUTPUT_DATASET="$2" shift 2 ;; --private) PRIVATE="true" shift ;; *) echo "Unknown parameter: $1" exit 1 ;; esacdone
if [ -z "$MODEL" ] || [ -z "$HF_DATASET" ]; then echo "Error: --model and --hf-dataset are required parameters" exit 1fi
# Set default values for optional parametersHF_DATASET_SPLIT=${HF_DATASET_SPLIT:-"train"}PROMPT_COLUMN=${PROMPT_COLUMN:-"prompt"}MAX_NEW_TOKENS=${MAX_NEW_TOKENS:-8192}NUM_GENERATIONS=${NUM_GENERATIONS:-1}PRIVATE=${PRIVATE:-"false"}
# Print all input argumentsecho "Input arguments:"echo "MODEL: $MODEL"echo "HF_DATASET: $HF_DATASET"echo "HF_DATASET_CONFIG: $HF_DATASET_CONFIG"echo "HF_DATASET_SPLIT: $HF_DATASET_SPLIT"echo "PROMPT_COLUMN: $PROMPT_COLUMN"echo "TEMPERATURE: $TEMPERATURE"echo "TOP_P: $TOP_P"echo "MAX_NEW_TOKENS: $MAX_NEW_TOKENS"echo "NUM_GENERATIONS: $NUM_GENERATIONS"echo "HF_OUTPUT_DATASET: $HF_OUTPUT_DATASET"echo "PRIVATE: $PRIVATE"echo "-------------------"
set -ex
module load cuda/12.1
export LD_LIBRARY_PATH=.venv/lib/python3.11/site-packages/nvidia/nvjitlink/lib
echo "SLURM_JOB_ID: $SLURM_JOB_ID"echo "SLURM_JOB_NODELIST: $SLURM_JOB_NODELIST"
source .venv/bin/activate
# Getting the node namesnodes=$(scontrol show hostnames "$SLURM_JOB_NODELIST")nodes_array=($nodes)
# Get the IP address of the head nodehead_node=${nodes_array[0]}head_node_ip=$(srun --nodes=1 --ntasks=1 -w "$head_node" hostname --ip-address)
# Start Ray head nodeport=6379ip_head=$head_node_ip:$portexport ip_headecho "IP Head: $ip_head"
echo "Starting HEAD at $head_node"srun --nodes=1 --ntasks=1 -w "$head_node" \ ray start --head --node-ip-address="$head_node_ip" --port=$port \ --dashboard-host=0.0.0.0 \ --dashboard-port=8265 \ --block &
# Give some time to head node to start...sleep 10
# Start Ray worker nodesworker_num=$((SLURM_JOB_NUM_NODES - 1))
# Start from 1 (0 is head node)for ((i = 1; i <= worker_num; i++)); do node_i=${nodes_array[$i]} echo "Starting WORKER $i at $node_i" srun --nodes=1 --ntasks=1 -w "$node_i" \ ray start --address "$ip_head" \ --block & sleep 5done
# Give some time to the Ray cluster to gather infoecho "Waiting a bit for Ray cluster to gather node info..."sleep 60
# Run vllmRAY_ADDRESS="http://$head_node_ip:8265" ray job submit \ --working-dir src/open_r1 \ --no-wait \ -- vllm serve $MODEL \ --tensor-parallel-size 8 \ --pipeline-parallel-size 4 \ --gpu-memory-utilization=0.85 \ --max-model-len 16384 \ --enable-chunked-prefill \ --trust-remote-code \ --distributed-executor-backend ray
# wait for vllm to load the modelecho "Waiting for vLLM (http://$head_node_ip:8000) server to be up..."
# wait for vllm to load and serve the modelwhile true; do if curl -s -o /dev/null -w "%{http_code}" http://$head_node_ip:8000 >/dev/null 2>&1; then echo "Received response from http://$head_node_ip:8000" break else echo "Still waiting... (Press Ctrl+C to cancel)" sleep 60 fidone
echo "Checking available models..."curl http://$head_node_ip:8000/v1/models
echo "Executing sanity check..."curl http://$head_node_ip:8000/v1/completions \ -H "Content-Type: application/json" \ -d "{ \"model\": \"$MODEL\", \"prompt\": \"<|begin▁of▁sentence|><|User|>hi, how are you?<|Assistant|>\", \"max_tokens\": 2048, \"temperature\": 0.6 }"
# Finally submit the job to the clusterecho "Submitting job to ray cluster..."RAY_ADDRESS="http://$head_node_ip:8265" ray job submit \ --working-dir src/open_r1 \ -- python -u generate.py \ --model "$MODEL" \ --hf-dataset "$HF_DATASET" \ ${HF_DATASET_CONFIG:+--hf-dataset-config "$HF_DATASET_CONFIG"} \ --hf-dataset-split "$HF_DATASET_SPLIT" \ --prompt-column "$PROMPT_COLUMN" \ ${TEMPERATURE:+--temperature "$TEMPERATURE"} \ ${TOP_P:+--top-p "$TOP_P"} \ --max-new-tokens "$MAX_NEW_TOKENS" \ --num-generations "$NUM_GENERATIONS" \ ${HF_OUTPUT_DATASET:+--hf-output-dataset "$HF_OUTPUT_DATASET"} \ ${PRIVATE:+--private} \ --vllm-server-url "http://$head_node_ip:8000/v1"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788#!/bin/bash#SBATCH --job-name=open-r1-sft#SBATCH --nodes=1#SBATCH --ntasks-per-node=1#SBATCH --exclusive#SBATCH --gres=gpu:8#SBATCH --partition=hopper-prod #SBATCH --output=./logs/%x-%j.out#SBATCH --err=./logs/%x-%j.err
set -x -e
source ~/.bashrcconda activate openr1module load cuda/12.1echo "START TIME: $(date)"echo "PYTHON ENV: $(which python)"
MODEL_PATH=$1DATASET_PATH=$2ACCELERATOR=$3
# Training setupNUM_NODES=$SLURM_NNODESGPUS_PER_NODE=8WORLD_SIZE=$(($NUM_NODES*$GPUS_PER_NODE))
# so processes know who to talk toMASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)MASTER_PORT=6000
export CMD=" \ src/open_r1/sft.py \ --model_name_or_path $MODEL_PATH \ --dataset_name $DATASET_PATH \ --use_liger_kernel true \ --learning_rate 2.0e-5 \ --num_train_epochs 1 \ --packing \ --max_seq_length 4096 \ --per_device_train_batch_size 4 \ --per_device_eval_batch_size 4 \ --gradient_accumulation_steps 4 \ --gradient_checkpointing \ --bf16 \ --logging_steps 5 \ --eval_strategy steps \ --eval_steps 100 \ --output_dir data/Qwen2.5-1.5B-Open-R1-Distill "
export LAUNCHER="HF_HUB_ENABLE_HF_TRANSFER=1 ACCELERATE_LOG_LEVEL=info TRANSFORMERS_VERBOSITY=info accelerate launch \ --config_file configs/$ACCELERATOR.yaml \ --gradient_accumulation_steps 4 \ --num_machines $NUM_NODES \ --num_processes $WORLD_SIZE \ --main_process_ip $MASTER_ADDR \ --main_process_port $MASTER_PORT \ --machine_rank \$SLURM_PROCID \ --rdzv_conf "rdzv_backend=c10d,rdzv_endpoint=$MASTER_ADDR:$MASTER_PORT" \ --max_restarts 1 \ --role \$(hostname -s): \ --tee 3 \ "
# force crashing on nccl issues like hanging broadcastexport NCCL_ASYNC_ERROR_HANDLING=1# export NCCL_DEBUG=INFO# export NCCL_DEBUG_SUBSYS=COLL# export NCCL_SOCKET_NTHREADS=1# export NCCL_NSOCKS_PERTHREAD=1# export CUDA_LAUNCH_BLOCKING=1
# Specific configuration optimized for the Hugging Face Compute Cluster# Be ye warned this may not work on other clusters!module load cuda/12.1
# srun error handling:# --wait=60: wait 60 sec after the first task terminates before terminating all remaining tasks# --kill-on-bad-exit=1: terminate a step if any task exits with a non-zero exit codeSRUN_ARGS=" \ --wait=60 \ --kill-on-bad-exit=1 \ "
clear; srun $SRUN_ARGS --jobid $SLURM_JOB_ID bash -c "$LAUNCHER --role \$SLURMD_NODENAME: $CMD" 2>&1
echo "END TIME: $(date)"123456789101112131415161718192021222324252627282930313233343536# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
__version__ = "0.3.0.dev0"
from .configs import DataArguments, DPOConfig, H4ArgumentParser, ModelArguments, SFTConfigfrom .data import apply_chat_template, get_datasetsfrom .decontaminate import decontaminate_humanevalfrom .model_utils import get_checkpoint, get_kbit_device_map, get_quantization_config, get_tokenizer
__all__ = [ "DataArguments", "DPOConfig", "H4ArgumentParser", "ModelArguments", "SFTConfig", "apply_chat_template", "get_datasets", "decontaminate_humaneval", "get_checkpoint", "get_kbit_device_map", "get_quantization_config", "get_tokenizer",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Custom evaluation tasks for LightEval."""
from lighteval.metrics.dynamic_metrics import ( ExprExtractionConfig, LatexExtractionConfig, multilingual_extractive_match_metric,)from lighteval.tasks.lighteval_task import LightevalTaskConfigfrom lighteval.tasks.requests import Docfrom lighteval.utils.language import Language
latex_gold_metric = multilingual_extractive_match_metric( language=Language.ENGLISH, fallback_mode="first_match", precision=5, gold_extraction_target=(LatexExtractionConfig(),), pred_extraction_target=(ExprExtractionConfig(), LatexExtractionConfig()), aggregation_function=max,)
expr_gold_metric = multilingual_extractive_match_metric( language=Language.ENGLISH, fallback_mode="first_match", precision=5, gold_extraction_target=(ExprExtractionConfig(),), pred_extraction_target=(ExprExtractionConfig(), LatexExtractionConfig()), aggregation_function=max,)
def prompt_fn(line, task_name: str = None): """Assumes the model is either prompted to emit \\boxed{answer} or does so automatically""" return Doc( task_name=task_name, query=line["problem"], choices=[line["solution"]], gold_index=0, )
def aime_prompt_fn(line, task_name: str = None): return Doc( task_name=task_name, query=line["problem"], choices=[line["answer"]], gold_index=0, )
# Define tasksaime24 = LightevalTaskConfig( name="aime24", suite=["custom"], prompt_function=aime_prompt_fn, hf_repo="HuggingFaceH4/aime_2024", hf_subset="default", hf_avail_splits=["train"], evaluation_splits=["train"], few_shots_split=None, few_shots_select=None, generation_size=32768, metric=[expr_gold_metric], version=1,)math_500 = LightevalTaskConfig( name="math_500", suite=["custom"], prompt_function=prompt_fn, hf_repo="HuggingFaceH4/MATH-500", hf_subset="default", hf_avail_splits=["test"], evaluation_splits=["test"], few_shots_split=None, few_shots_select=None, generation_size=32768, metric=[latex_gold_metric], version=1,)
# Add tasks to the tableTASKS_TABLE = []TASKS_TABLE.append(aime24)TASKS_TABLE.append(math_500)
# MODULE LOGICif __name__ == "__main__": print([t["name"] for t in TASKS_TABLE]) print(len(TASKS_TABLE))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
from typing import Optional
from distilabel.llms import OpenAILLMfrom distilabel.pipeline import Pipelinefrom distilabel.steps.tasks import TextGeneration
def build_distilabel_pipeline( model: str, base_url: str = "http://localhost:8000/v1", prompt_column: Optional[str] = None, temperature: Optional[float] = None, top_p: Optional[float] = None, max_new_tokens: int = 8192, num_generations: int = 1,) -> Pipeline: generation_kwargs = {"max_new_tokens": max_new_tokens}
if temperature is not None: generation_kwargs["temperature"] = temperature
if top_p is not None: generation_kwargs["top_p"] = top_p
with Pipeline().ray() as pipeline: TextGeneration( llm=OpenAILLM( base_url=base_url, api_key="something", model=model, # thinking can take some time... timeout=10 * 60, generation_kwargs=generation_kwargs, ), input_mappings={"instruction": prompt_column} if prompt_column is not None else {}, input_batch_size=64, # on 4 nodes bs ~60+ leads to preemption due to KV cache exhaustion num_generations=num_generations, )
return pipeline
if __name__ == "__main__": import argparse
from datasets import load_dataset
parser = argparse.ArgumentParser(description="Run distilabel pipeline for generating responses with DeepSeek R1") parser.add_argument( "--hf-dataset", type=str, required=True, help="HuggingFace dataset to load", ) parser.add_argument( "--hf-dataset-config", type=str, required=False, help="Dataset config to use", ) parser.add_argument( "--hf-dataset-split", type=str, default="train", help="Dataset split to use", ) parser.add_argument("--prompt-column", type=str, default="prompt") parser.add_argument( "--model", type=str, required=True, help="Model name to use for generation", ) parser.add_argument( "--vllm-server-url", type=str, default="http://localhost:8000/v1", help="URL of the vLLM server", ) parser.add_argument( "--temperature", type=float, help="Temperature for generation", ) parser.add_argument( "--top-p", type=float, help="Top-p value for generation", ) parser.add_argument( "--max-new-tokens", type=int, default=8192, help="Maximum number of new tokens to generate", ) parser.add_argument( "--num-generations", type=int, default=1, help="Number of generations per problem", ) parser.add_argument( "--hf-output-dataset", type=str, required=False, help="HuggingFace repo to push results to", ) parser.add_argument( "--private", action="store_true", help="Whether to make the output dataset private when pushing to HF Hub", )
args = parser.parse_args()
print("\nRunning with arguments:") for arg, value in vars(args).items(): print(f" {arg}: {value}") print()
print(f"Loading '{args.hf_dataset}' (config: {args.hf_dataset_config}, split: {args.hf_dataset_split}) dataset...") dataset = load_dataset(args.hf_dataset, split=args.hf_dataset_split) print("Dataset loaded!")
pipeline = build_distilabel_pipeline( model=args.model, base_url=args.vllm_server_url, prompt_column=args.prompt_column, temperature=args.temperature, top_p=args.top_p, max_new_tokens=args.max_new_tokens, num_generations=args.num_generations, )
print("Running generation pipeline...") distiset = pipeline.run(dataset=dataset, use_cache=False) print("Generation pipeline finished!")
if args.hf_output_dataset: print(f"Pushing resulting dataset to '{args.hf_output_dataset}'...") distiset.push_to_hub(args.hf_output_dataset, private=args.private) print("Dataset pushed!")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
import refrom dataclasses import dataclass, field
from datasets import load_dataset
from latex2sympy2_extended import NormalizationConfigfrom math_verify import LatexExtractionConfig, parse, verifyfrom trl import GRPOConfig, GRPOTrainer, ModelConfig, ScriptArguments, TrlParser, get_peft_config
@dataclassclass GRPOScriptArguments(ScriptArguments): """ Script arguments for the GRPO training script.
Args: reward_funcs (`list[str]`): List of reward functions. Possible values: 'accuracy', 'format'. """
reward_funcs: list[str] = field( default_factory=lambda: ["accuracy", "format"], metadata={"help": "List of reward functions. Possible values: 'accuracy', 'format'"}, )
def accuracy_reward(completions, solution, **kwargs): """Reward function that checks if the completion is the same as the ground truth.""" contents = [completion[0]["content"] for completion in completions] rewards = [] for content, sol in zip(contents, solution): gold_parsed = parse(sol, extraction_mode="first_match", extraction_config=[LatexExtractionConfig()]) if len(gold_parsed) != 0: # We require the answer to be provided in correct latex (no malformed operators) answer_parsed = parse( content, extraction_config=[ LatexExtractionConfig( normalization_config=NormalizationConfig( nits=False, malformed_operators=False, basic_latex=True, equations=True, boxed=True, units=True, ), # Ensures that boxed is tried first boxed_match_priority=0, try_extract_without_anchor=False, ) ], extraction_mode="first_match", ) # Reward 1 if the content is the same as the ground truth, 0 otherwise reward = float(verify(answer_parsed, gold_parsed)) else: # If the gold solution is not parseable, we reward 1 to skip this example reward = 1.0 print("Failed to parse gold solution: ", sol) rewards.append(reward)
return rewards
def format_reward(completions, **kwargs): """Reward function that checks if the completion has a specific format.""" pattern = r"^<think>.*?</think><answer>.*?</answer>$" completion_contents = [completion[0]["content"] for completion in completions] matches = [re.match(pattern, content) for content in completion_contents] return [1.0 if match else 0.0 for match in matches]
reward_funcs_registry = { "accuracy": accuracy_reward, "format": format_reward,}
SYSTEM_PROMPT = ( "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>")
def main(script_args, training_args, model_args): # Get reward functions reward_funcs = [reward_funcs_registry[func] for func in script_args.reward_funcs]
# Load the dataset dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
# Format into conversation def make_conversation(example): return { "prompt": [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": example["problem"]}, ], }
dataset = dataset.map(make_conversation) dataset = dataset.remove_columns("messages")
# Initialize the GRPO trainer trainer = GRPOTrainer( model=model_args.model_name_or_path, reward_funcs=reward_funcs, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, peft_config=get_peft_config(model_args), )
# Train and push the model to the Hub trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)
if __name__ == "__main__": parser = TrlParser((GRPOScriptArguments, GRPOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() main(script_args, training_args, model_args)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Copyright 2025 The HuggingFace Team. All rights reserved.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Supervised fine-tuning script for decoder language models.
Usage:
# One 1 node of 8 x H100saccelerate launch --config_file=configs/zero3.yaml src/open_r1/sft.py \ --model_name_or_path Qwen/Qwen2.5-1.5B-Instruct \ --dataset_name HuggingFaceH4/Bespoke-Stratos-17k \ --learning_rate 2.0e-5 \ --num_train_epochs 1 \ --packing \ --max_seq_length 4096 \ --per_device_train_batch_size 4 \ --gradient_accumulation_steps 4 \ --gradient_checkpointing \ --bf16 \ --logging_steps 5 \ --eval_strategy steps \ --eval_steps 100 \ --output_dir data/Qwen2.5-1.5B-Open-R1-Distill"""
from datasets import load_datasetfrom transformers import AutoTokenizer
from trl import ( ModelConfig, ScriptArguments, SFTConfig, SFTTrainer, TrlParser, get_kbit_device_map, get_peft_config, get_quantization_config,)
def main(script_args, training_args, model_args): ################ # Model init kwargs & Tokenizer ################ quantization_config = get_quantization_config(model_args) model_kwargs = dict( revision=model_args.model_revision, trust_remote_code=model_args.trust_remote_code, attn_implementation=model_args.attn_implementation, torch_dtype=model_args.torch_dtype, use_cache=False if training_args.gradient_checkpointing else True, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, ) training_args.model_init_kwargs = model_kwargs tokenizer = AutoTokenizer.from_pretrained( model_args.model_name_or_path, trust_remote_code=model_args.trust_remote_code, use_fast=True ) tokenizer.pad_token = tokenizer.eos_token
################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config)
################ # Training ################ trainer = SFTTrainer( model=model_args.model_name_or_path, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None, processing_class=tokenizer, peft_config=get_peft_config(model_args), )
trainer.train()
# Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)
if __name__ == "__main__": parser = TrlParser((ScriptArguments, SFTConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_and_config() main(script_args, training_args, model_args).DS_StoreAdded
DockerfileAdded+17
LICENSEAdded+201
MakefileAdded+20
README.md+255-12
assets/plan-of-attack.pngAdded

configs/ddp.yamlAdded+16
configs/zero2.yamlAdded+21
configs/zero3.yamlAdded+22
requirements.txtAdded+7
setup.cfgAdded+41
setup.pyAdded+135
slurm/evaluate.slurmAdded+50
slurm/generate.slurmAdded+201
slurm/sft.slurmAdded+88
src/open_r1/__init__.pyAdded+36
src/open_r1/evaluate.pyAdded+103
src/open_r1/generate.pyAdded+156
src/open_r1/grpo.pyAdded+141
src/open_r1/sft.pyAdded+101