diff --git a/.gitattributes b/.gitattributes index 8453ec4f1a68c78e614639c8965fce4c8738d7f7..78837a1d17d7b7c1a9ef04497b073e0f6a727c64 100644 --- a/.gitattributes +++ b/.gitattributes @@ -397,3 +397,7 @@ saves/qwen7B_it_fromit_326_think_sudoku_sequence_multitask/global_step_200/qwen2 saves/qwen7B_it_fromit_think_cube3_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf/tokenizer.json filter=lfs diff=lfs merge=lfs -text saves/qwen7B_it_fromit_think_frozenlake_sequence_multitask/global_step_200/qwen2.5_7B_actor_hf/tokenizer.json filter=lfs diff=lfs merge=lfs -text saves/qwen7B_it_fromit_think_sokobanbox2_sequence_multitask/global_step_100/qwen2.5_7B_actor_hf/tokenizer.json filter=lfs diff=lfs merge=lfs -text +wandb/latest-run/run-1fkf5bo1.wandb filter=lfs diff=lfs merge=lfs -text +wandb/offline-run-20251216_100052-vp4li00f/run-vp4li00f.wandb filter=lfs diff=lfs merge=lfs -text +wandb/offline-run-20251216_142423-iypt06ne/run-iypt06ne.wandb filter=lfs diff=lfs merge=lfs -text +wandb/offline-run-20251216_185932-u0k07wxi/run-u0k07wxi.wandb filter=lfs diff=lfs merge=lfs -text diff --git a/verl/verl.egg-info/PKG-INFO b/verl/verl.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..a1d0ef472d9c3a2deb3fea4bfd3618b5ddd8ccbd --- /dev/null +++ b/verl/verl.egg-info/PKG-INFO @@ -0,0 +1,327 @@ +Metadata-Version: 2.4 +Name: verl +Version: 0.5.0.dev0 +Summary: verl: Volcano Engine Reinforcement Learning for LLM +Home-page: https://github.com/volcengine/verl +Author: Bytedance - Seed - MLSys +Author-email: zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk +License: Apache-2.0 +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: accelerate +Requires-Dist: codetiming +Requires-Dist: datasets +Requires-Dist: dill +Requires-Dist: hydra-core +Requires-Dist: numpy<2.0.0 +Requires-Dist: pandas +Requires-Dist: peft +Requires-Dist: pyarrow>=19.0.0 +Requires-Dist: pybind11 +Requires-Dist: pylatexenc +Requires-Dist: ray[default]>=2.41.0 +Requires-Dist: torchdata +Requires-Dist: tensordict!=0.9.0,<=0.10.0,>=0.8.0 +Requires-Dist: transformers +Requires-Dist: wandb +Requires-Dist: packaging>=20.0 +Requires-Dist: tensorboard +Provides-Extra: test +Requires-Dist: pytest; extra == "test" +Requires-Dist: pre-commit; extra == "test" +Requires-Dist: py-spy; extra == "test" +Requires-Dist: pytest-asyncio; extra == "test" +Provides-Extra: prime +Requires-Dist: pyext; extra == "prime" +Provides-Extra: geo +Requires-Dist: mathruler; extra == "geo" +Requires-Dist: torchvision; extra == "geo" +Requires-Dist: qwen_vl_utils; extra == "geo" +Provides-Extra: gpu +Requires-Dist: liger-kernel; extra == "gpu" +Requires-Dist: flash-attn; extra == "gpu" +Provides-Extra: math +Requires-Dist: math-verify; extra == "math" +Provides-Extra: vllm +Requires-Dist: tensordict!=0.9.0,<=0.10.0,>=0.8.0; extra == "vllm" +Requires-Dist: vllm<=0.9.1,>=0.7.3; extra == "vllm" +Provides-Extra: sglang +Requires-Dist: tensordict!=0.9.0,<=0.10.0,>=0.8.0; extra == "sglang" +Requires-Dist: sglang[openai,srt]==0.5.2; extra == "sglang" +Requires-Dist: torch==2.8.0; extra == "sglang" +Provides-Extra: trl +Requires-Dist: trl<=0.9.6; extra == "trl" +Provides-Extra: mcore +Requires-Dist: mbridge; extra == "mcore" +Dynamic: author +Dynamic: author-email +Dynamic: home-page +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist + +
+ 👋 Hi, everyone! + verl is a RL training library initiated by ByteDance Seed team and maintained by the verl community. +
+
+
+ +
+ +Ask DeepWiki.com +[![GitHub Repo stars](https://img.shields.io/github/stars/volcengine/verl)](https://github.com/volcengine/verl/stargazers) +[![Twitter](https://img.shields.io/twitter/follow/verl_project)](https://twitter.com/verl_project) + + +[![Documentation](https://img.shields.io/badge/documentation-blue)](https://verl.readthedocs.io/en/latest/) + + +
+ +![seed logo](https://github.com/user-attachments/assets/c42e675e-497c-4508-8bb9-093ad4d1f216) + +

verl: Volcano Engine Reinforcement Learning for LLMs

+ +verl is a flexible, efficient and production-ready RL training library for large language models (LLMs). + +verl is the open-source version of **[HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2)** paper. + +verl is flexible and easy to use with: + +- **Easy extension of diverse RL algorithms**: The hybrid-controller programming model enables flexible representation and efficient execution of complex post-training dataflows. Build RL dataflows such as GRPO, PPO in a few lines of code. + +- **Seamless integration of existing LLM infra with modular APIs**: Decouples computation and data dependencies, enabling seamless integration with existing LLM frameworks, such as FSDP, Megatron-LM, vLLM, SGLang, etc + +- **Flexible device mapping**: Supports various placement of models onto different sets of GPUs for efficient resource utilization and scalability across different cluster sizes. + +- Ready integration with popular HuggingFace models + +verl is fast with: + +- **State-of-the-art throughput**: SOTA LLM training and inference engine integrations and SOTA RL throughput. + +- **Efficient actor model resharding with 3D-HybridEngine**: Eliminates memory redundancy and significantly reduces communication overhead during transitions between training and generation phases. + +

+ +## News +- [2025/08] verl is presented in the [PyTorch Expert Exchange Webinar](https://www.youtube.com/watch?v=Vd79NmmqY3Q&t=2s). [Slides](https://github.com/eric-haibin-lin/verl-community/blob/main/slides/verl_talk_pytorch_2025_08.pdf) available. +- [2025/07] The [ReTool](https://arxiv.org/pdf/2504.11536) recipe is fully open sourced. [Blog](https://www.notion.so/verl-reTool-recipe-Using-multi-round-conversations-and-code-sandboxing-to-improve-the-math-of-large-23a8b5b7feba80b386b2e5b5e3c1cde0) +- [2025/07] The first verl meetup will be held at ICML Vancouver on July 16th! Please [join us](https://lu.ma/0ek2nyao) if you are at ICML! (onsite only) +- [2025/06] verl with Megatron backend enables large MoE models such as [DeepSeek-671B and Qwen3-235B](https://verl.readthedocs.io/en/latest/perf/dpsk.html). +- [2025/03] [DAPO](https://dapo-sia.github.io/) is the open-sourced SOTA RL algorithm that achieves 50 points on AIME 2024 based on the Qwen2.5-32B pre-trained model, surpassing the previous SOTA achieved by DeepSeek's GRPO (DeepSeek-R1-Zero-Qwen-32B). DAPO's training is fully powered by verl and the reproduction code is available in `recipe/dapo` now. +
more... + +
+ +## Key Features + +- **FSDP**, **FSDP2** and **Megatron-LM** for training. +- **vLLM**, **SGLang** and **HF Transformers** for rollout generation. +- Compatible with Hugging Face Transformers and Modelscope Hub: [Qwen-3](https://github.com/volcengine/verl/blob/main/examples/grpo_trainer/run_qwen3-8b.sh), Qwen-2.5, Llama3.1, Gemma2, DeepSeek-LLM, etc +- Supervised fine-tuning. +- Reinforcement learning with [PPO](examples/ppo_trainer/), [GRPO](examples/grpo_trainer/), [GSPO](recipe/gspo/), [ReMax](examples/remax_trainer/), [REINFORCE++](https://verl.readthedocs.io/en/latest/examples/config.html#algorithm), [RLOO](examples/rloo_trainer/), [PRIME](recipe/prime/), [DAPO](recipe/dapo/), [DrGRPO](recipe/drgrpo), [KL_Cov & Clip_Cov](recipe/entropy) etc. + - Support model-based reward and function-based reward (verifiable reward) for math, [coding](https://github.com/volcengine/verl/tree/main/recipe/dapo), etc + - Support vision-language models (VLMs) and [multi-modal RL](examples/grpo_trainer/run_qwen2_5_vl-7b.sh) with Qwen2.5-vl, Kimi-VL + - [Multi-turn with tool calling](https://github.com/volcengine/verl/tree/main/examples/sglang_multiturn) +- LLM alignment recipes such as [Self-play preference optimization (SPPO)](https://github.com/volcengine/verl/tree/main/recipe/sppo) +- Flash attention 2, [sequence packing](examples/ppo_trainer/run_qwen2-7b_seq_balance.sh), [sequence parallelism](examples/ppo_trainer/run_deepseek7b_llm_sp2.sh) support via DeepSpeed Ulysses, [LoRA](examples/sft/gsm8k/run_qwen_05_peft.sh), [Liger-kernel](examples/sft/gsm8k/run_qwen_05_sp2_liger.sh). +- Scales up to 671B models and hundreds of GPUs with [expert parallelism](https://github.com/volcengine/verl/pull/1467) +- Multi-gpu [LoRA RL](https://verl.readthedocs.io/en/latest/advance/ppo_lora.html) support to save memory. +- Experiment tracking with wandb, swanlab, mlflow and tensorboard. + +## Upcoming Features and Changes + +- Q3 Roadmap https://github.com/volcengine/verl/issues/2388 +- DeepSeek 671b optimizations with Megatron https://github.com/volcengine/verl/issues/1033 +- Multi-turn rollout and tools using optimizations https://github.com/volcengine/verl/issues/1882 +- [Agent integration](https://github.com/volcengine/verl/tree/main/verl/experimental/agent_loop) +- Async and off-policy architecture https://github.com/volcengine/verl/pull/2231 +- List of breaking changes since v0.4 https://github.com/volcengine/verl/discussions/2270 + +## Getting Started + +Documentation + +**Quickstart:** + +- [Installation](https://verl.readthedocs.io/en/latest/start/install.html) +- [Quickstart](https://verl.readthedocs.io/en/latest/start/quickstart.html) +- [Programming Guide](https://verl.readthedocs.io/en/latest/hybrid_flow.html) & [Tech Talk](https://hcqnc.xetlk.com/sl/3vACOK) (in Chinese) +- [PPO in verl](https://verl.readthedocs.io/en/latest/algo/ppo.html) +- [GRPO in verl](https://verl.readthedocs.io/en/latest/algo/grpo.html) + +**Running a PPO example step-by-step:** + +- [Prepare Data for Post-Training](https://verl.readthedocs.io/en/latest/preparation/prepare_data.html) +- [Implement Reward Function for Dataset](https://verl.readthedocs.io/en/latest/preparation/reward_function.html) +- [PPO Example Architecture](https://verl.readthedocs.io/en/latest/examples/ppo_code_architecture.html) +- [Config Explanation](https://verl.readthedocs.io/en/latest/examples/config.html) + +**Reproducible algorithm baselines:** + +- [RL performance on coding, math](https://verl.readthedocs.io/en/latest/algo/baseline.html) + +**For code explanation and advance usage (extension):** + +- PPO Trainer and Workers + - [PPO Ray Trainer](https://verl.readthedocs.io/en/latest/workers/ray_trainer.html) + - [PyTorch FSDP Backend](https://verl.readthedocs.io/en/latest/workers/fsdp_workers.html) + - [Megatron-LM Backend](https://verl.readthedocs.io/en/latest/index.html) + +- Advanced Usage and Extension + - [Add Models with the FSDP Backend](https://verl.readthedocs.io/en/latest/advance/fsdp_extension.html) + - [Add Models with the Megatron-LM Backend](https://verl.readthedocs.io/en/latest/advance/megatron_extension.html) + - [Multi-turn Rollout Support](https://verl.readthedocs.io/en/latest/sglang_multiturn/multiturn.html) + - [Search Tool Integration](https://verl.readthedocs.io/en/latest/sglang_multiturn/search_tool_example.html) + - [Sandbox Fusion Integration](https://verl.readthedocs.io/en/latest/examples/sandbox_fusion_example.html) + - [Deployment using Separate GPU Resources](https://github.com/volcengine/verl/tree/main/examples/split_placement) + - [Extend to Other RL(HF) algorithms](https://verl.readthedocs.io/en/latest/advance/dpo_extension.html) + - [Ray API design tutorial](https://verl.readthedocs.io/en/latest/advance/placement.html) + +**Blogs from the community** + +- [When Reasoning Models Break Tokenization: The Hidden Complexity of Multiturn Training](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/multi-turn/fast_tokenization/multiturn_tokenization_and_masking.md) +- [verl deployment on AWS SageMaker](https://medium.com/@kaige.yang0110/run-verl-on-sagemaker-using-4x8-l40s-gpus-8e6d5c3c61d3) +- [verl x SGLang Multi-turn Code Walkthrough](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/multi-turn/code-walk-through/readme_EN.md) +- [Optimizing SGLang Memory Usage in verl](https://hebiao064.github.io/rl-memory-management) +- [SGLang, verl, OpenBMB and Tsinghua University: Pioneering End-to-End Multi-Turn RLHF](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/multi-turn/verl-multiturn-rollout-Release.md) +- [Reinforcement Learning from Human Feedback on AMD GPUs with verl and ROCm Integration](https://rocm.blogs.amd.com/artificial-intelligence/verl-large-scale/README.html) +- [veMLP x verl :玩转强化学习训练](https://mp.weixin.qq.com/s/7nbqxk4knMGd-hQE9ls2tA) +- [使用 verl 进行 GRPO 分布式强化学习训练最佳实践](https://www.volcengine.com/docs/6459/1463942) +- [HybridFlow verl 原文浅析](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/readme.md) +- [最高提升 20 倍吞吐量!豆包大模型团队发布全新 RLHF 框架,现已开源!](https://team.doubao.com/en/blog/%E6%9C%80%E9%AB%98%E6%8F%90%E5%8D%8720%E5%80%8D%E5%90%9E%E5%90%90%E9%87%8F-%E8%B1%86%E5%8C%85%E5%A4%A7%E6%A8%A1%E5%9E%8B%E5%9B%A2%E9%98%9F%E5%8F%91%E5%B8%83%E5%85%A8%E6%96%B0-rlhf-%E6%A1%86%E6%9E%B6-%E7%8E%B0%E5%B7%B2%E5%BC%80%E6%BA%90) + +## Performance Tuning Guide + +The performance is essential for on-policy RL algorithm. We have written a detailed [performance tuning guide](https://verl.readthedocs.io/en/latest/perf/perf_tuning.html) to help you optimize performance. + +## Upgrade to vLLM >= v0.8.2 + +verl now supports vLLM>=0.8.2 when using FSDP as the training backend. Please refer to [this document](https://github.com/volcengine/verl/blob/main/docs/README_vllm0.8.md) for the installation guide and more information. Please avoid vllm 0.7.x, which contains bugs that may lead to OOMs and unexpected errors. + +## Use Latest SGLang + +SGLang is fully supported with verl, and SGLang RL Group is working extensively on building unique features, including multi-turn agentic RL, VLM RLHF, server-based RL, and partial rollout. Please refer to [this document](https://verl.readthedocs.io/en/latest/workers/sglang_worker.html) for the installation guide and more information. + +## Upgrade to FSDP2 + +verl is fully embracing FSDP2! FSDP2 is recommended by torch distributed team, providing better throughput and memory usage, and is composible with other features (e.g. torch.compile). To enable FSDP2, simply use verl main and set the following options: +``` +actor_rollout_ref.ref.strategy=fsdp2 +actor_rollout_ref.actor.strategy=fsdp2 +critic.strategy=fsdp2 +reward_model.strategy=fsdp2 +``` +Furthermore, FSDP2 cpu offloading is compatible with gradient accumulation. You can turn it on to save memory with `actor_rollout_ref.actor.fsdp_config.offload_policy=True`. For more details, see https://github.com/volcengine/verl/pull/1026 + +## AMD Support (ROCm Kernel) + +verl now supports FSDP as the training engine (Megatron support coming soon) and both integrates with vLLM and SGLang as inference engines. Please refer to [this document](https://github.com/volcengine/verl/blob/main/docs/amd_tutorial/amd_build_dockerfile_page.rst) for the installation guide and more information, and [this document](https://github.com/volcengine/verl/blob/main/docs/amd_tutorial/amd_vllm_page.rst) for the vLLM performance tuning for ROCm. + + +## Citation and acknowledgement + +If you find the project helpful, please cite: + +- [HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2) +- [A Framework for Training Large Language Models for Code Generation via Proximal Policy Optimization](https://i.cs.hku.hk/~cwu/papers/gmsheng-NL2Code24.pdf) + +```bibtex +@article{sheng2024hybridflow, + title = {HybridFlow: A Flexible and Efficient RLHF Framework}, + author = {Guangming Sheng and Chi Zhang and Zilingfeng Ye and Xibin Wu and Wang Zhang and Ru Zhang and Yanghua Peng and Haibin Lin and Chuan Wu}, + year = {2024}, + journal = {arXiv preprint arXiv: 2409.19256} +} +``` + +verl is inspired by the design of Nemo-Aligner, Deepspeed-chat and OpenRLHF. The project is adopted and contributed by Bytedance, Anyscale, LMSys.org, [Alibaba Qwen team](https://github.com/QwenLM/), Shanghai AI Lab, Tsinghua University, UC Berkeley, UCLA, UIUC, University of Hong Kong, ke.com, [All Hands AI](https://www.all-hands.dev/), [ModelBest](http://modelbest.cn/), JD AI Lab, Microsoft Research, [StepFun](https://www.stepfun.com/), Amazon, LinkedIn, Meituan, [Camel-AI](https://www.camel-ai.org/), [OpenManus](https://github.com/OpenManus), Xiaomi, NVIDIA research, [Baichuan](https://www.baichuan-ai.com/home), [RedNote](https://www.xiaohongshu.com/), [SwissAI](https://www.swiss-ai.org/), [Moonshot AI (Kimi)](https://www.moonshot-ai.com/), Baidu, Snowflake, Skywork.ai, JetBrains, [IceSword Lab](https://www.iceswordlab.com), and many more. + +## Awesome work using verl + +- [TinyZero](https://github.com/Jiayi-Pan/TinyZero): a reproduction of **DeepSeek R1 Zero** recipe for reasoning tasks ![GitHub Repo stars](https://img.shields.io/github/stars/Jiayi-Pan/TinyZero) +- [SkyThought](https://github.com/NovaSky-AI/SkyThought): RL training for Sky-T1-7B by NovaSky AI team. ![GitHub Repo stars](https://img.shields.io/github/stars/NovaSky-AI/SkyThought) +- [simpleRL-reason](https://github.com/hkust-nlp/simpleRL-reason): SimpleRL-Zoo: Investigating and Taming Zero Reinforcement Learning for Open Base Models in the Wild ![GitHub Repo stars](https://img.shields.io/github/stars/hkust-nlp/simpleRL-reason) +- [Easy-R1](https://github.com/hiyouga/EasyR1): **Multi-modal** RL training framework ![GitHub Repo stars](https://img.shields.io/github/stars/hiyouga/EasyR1) +- [OpenManus-RL](https://github.com/OpenManus/OpenManus-RL): LLM Agents RL tunning framework for multiple agent environments. ![GitHub Repo stars](https://img.shields.io/github/stars/OpenManus/OpenManus-RL) +- [rllm](https://github.com/agentica-project/rllm): async RL training with [verl-pipeline](https://github.com/agentica-project/verl-pipeline) ![GitHub Repo stars](https://img.shields.io/github/stars/agentica-project/rllm) +- [RAGEN](https://github.com/ZihanWang314/ragen): a general-purpose reasoning **agent** training framework ![GitHub Repo stars](https://img.shields.io/github/stars/ZihanWang314/ragen) +- [Search-R1](https://github.com/PeterGriffinJin/Search-R1): RL with reasoning and **searching (tool-call)** interleaved LLMs ![GitHub Repo stars](https://img.shields.io/github/stars/PeterGriffinJin/Search-R1) +- [ReSearch](https://github.com/Agent-RL/ReSearch): Learning to **Re**ason with **Search** for LLMs via Reinforcement Learning ![GitHub Repo stars](https://img.shields.io/github/stars/Agent-RL/ReSearch) +- [Skywork-OR1](https://github.com/SkyworkAI/Skywork-OR1): Skywork open reaonser series ![GitHub Repo stars](https://img.shields.io/github/stars/SkyworkAI/Skywork-OR1) +- [ToRL](https://github.com/GAIR-NLP/ToRL): Scaling tool-integrated RL ![GitHub Repo stars](https://img.shields.io/github/stars/GAIR-NLP/ToRL) +- [Absolute Zero Reasoner](https://github.com/LeapLabTHU/Absolute-Zero-Reasoner): [A no human curated data self-play framework for reasoning](https://arxiv.org/abs/2505.03335) ![GitHub Repo stars](https://img.shields.io/github/stars/LeapLabTHU/Absolute-Zero-Reasoner) +- [verl-agent](https://github.com/langfengQ/verl-agent): A scalable training framework for **long-horizon LLM/VLM agents**, along with a new algorithm **GiGPO** ![GitHub Repo stars](https://img.shields.io/github/stars/langfengQ/verl-agent) +- [RL-Factory](https://github.com/Simple-Efficient/RL-Factory): An easy and efficient RL post-training framework for Agentic Learning ![GitHub Repo stars](https://img.shields.io/github/stars/Simple-Efficient/RL-Factory) +- [ReTool](https://retool-rl.github.io/): ReTool: reinforcement learning for strategic tool use in LLMs. Code release is in progress... +- [verl-tool](https://github.com/TIGER-AI-Lab/verl-tool): An unified and easy-to-extend tool-agent training framework based on verl![GitHub Repo stars](https://img.shields.io/github/stars/TIGER-AI-Lab/verl-tool) +- [PRIME](https://github.com/PRIME-RL/PRIME): Process reinforcement through implicit rewards ![GitHub Repo stars](https://img.shields.io/github/stars/PRIME-RL/PRIME) +- [MemAgent](https://github.com/BytedTsinghua-SIA/MemAgent): MemAgent: Reshaping Long-Context LLM with Multi-Conv RL based Memory Agent ![GitHub Repo stars](https://img.shields.io/github/stars/BytedTsinghua-SIA/MemAgent) +- [POLARIS](https://github.com/ChenxinAn-fdu/POLARIS): A Post-training recipe for scaling RL on Advanced Reasoning models ![GitHub Repo stars](https://img.shields.io/github/stars/ChenxinAn-fdu/POLARIS) +- [GUI-R1](https://github.com/ritzz-ai/GUI-R1): **GUI-R1**: A Generalist R1-style Vision-Language Action Model For **GUI Agents** ![GitHub Repo stars](https://img.shields.io/github/stars/ritzz-ai/GUI-R1) +- [DeepRetrieval](https://github.com/pat-jj/DeepRetrieval): RL Training of **Search Agent** with **Search/Retrieval Outcome** ![GitHub Repo stars](https://img.shields.io/github/stars/pat-jj/DeepRetrieval) +- [Code-R1](https://github.com/ganler/code-r1): Reproducing R1 for **Code** with Reliable Rewards ![GitHub Repo stars](https://img.shields.io/github/stars/ganler/code-r1) +- [DeepResearcher](https://github.com/GAIR-NLP/DeepResearcher): Scaling deep research via reinforcement learning in real-world environments ![GitHub Repo stars](https://img.shields.io/github/stars/GAIR-NLP/DeepResearcher) +- [VAGEN](https://github.com/RAGEN-AI/VAGEN): Training VLM agents with multi-turn reinforcement learning ![GitHub Repo stars](https://img.shields.io/github/stars/RAGEN-AI/VAGEN) +- [RM-R1](https://arxiv.org/abs/2505.02387): RL training of reasoning reward models ![GitHub Repo stars](https://img.shields.io/github/stars/RM-R1-UIUC/RM-R1) +- [LUFFY](https://arxiv.org/pdf/2504.14945): Learning to Reason under Off-Policy Guidance![GitHub Repo stars](https://img.shields.io/github/stars/ElliottYan/LUFFY) +- [DeepMath](https://github.com/zwhe99/DeepMath): DeepMath-103K data and series models for math reasoning![GitHub Repo stars](https://img.shields.io/github/stars/zwhe99/DeepMath) +- [PACS](https://github.com/ritzz-ai/PACS): Implicit Actor Critic Coupling via a Supervised Learning Framework for RLVR ![GitHub Repo stars](https://img.shields.io/github/stars/ritzz-ai/PACS) +- [Entropy Mechanism of RL](https://github.com/PRIME-RL/Entropy-Mechanism-of-RL): The Entropy Mechanism of Reinforcement Learning for Large Language Model Reasoning![GitHub Repo stars](https://img.shields.io/github/stars/PRIME-RL/Entropy-Mechanism-of-RL) +- [LLaSA-TTS-GRPO](https://github.com/channel-io/ch-tts-llasa-rl-grpo): TTS fine-tuning with GRPO optimization based on LLASA models ![GitHub Repo stars](https://img.shields.io/github/stars/channel-io/ch-tts-llasa-rl-grpo) +- [PF-PPO](https://arxiv.org/abs/2409.06957): Policy Filtration for PPO based on the reliability of reward signals for more efficient and robust RLHF. +- [RACRO](https://github.com/gyhdog99/RACRO2): Build multi-modal reasoning models via decoupling it into query-conditioned captioning and text-only reasoning ![GitHub Repo stars](https://img.shields.io/github/stars/gyhdog99/RACRO2) +- [Agent Lightning](https://github.com/microsoft/agent-lightning): A flexible and extensible framework that enables seamless agent optimization for any existing agent framework. ![GitHub Repo stars](https://img.shields.io/github/stars/microsoft/agent-lightning) +- [VTool-R1](https://github.com/VTOOL-R1/vtool-r1): VLMs Learn to Think with Images via Reinforcement Learning on Multimodal Tool Use. ![GitHub Repo stars](https://img.shields.io/github/stars/VTOOL-R1/vtool-r1) +- [Kimina-Prover-RL](https://github.com/project-numina/kimina-prover-rl/tree/main/recipe/kimina_prover_rl): Training pipeline for formal theorem proving, based on a paradigm inspired by DeepSeek-R1. +- [RL-PLUS](https://github.com/YihongDong/RL-PLUS): Countering Capability Boundary Collapse of LLMs in Reinforcement Learning with Hybrid-policy Optimization. +- [rStar2-Agent](https://github.com/microsoft/rStar): Using reinforcement learning with multi-step tool-calling for math tasks, rStar2-Agent-14B reaches frontier-level math reasoning in just 510 RL training steps ![GitHub Repo stars](https://img.shields.io/github/stars/microsoft/rStar) +- [Vision-SR1](https://github.com/zli12321/Vision-SR1): Self-Rewarding Vision-Language Model via Reasoning Decomposition ![GitHub Repo stars](https://img.shields.io/github/stars/zli12321/Vision-SR1) +- [SimpleVLA-RL](https://github.com/PRIME-RL/SimpleVLA-RL): SimpleVLA-RL: A Simple yet Effective Vision-Language Action Model for Reinforcement Learning ![GitHub Repo stars](https://img.shields.io/github/stars/PRIME-RL/SimpleVLA-RL) +- [Table-R1](https://github.com/Table-R1/Table-R1): Table-R1: Inference-Time Scaling for Table Reasoning ![GitHub Repo stars](https://img.shields.io/github/stars/Table-R1/Table-R1) + +and many more awesome work listed in [recipe](recipe/README.md). + +## Contribution Guide + +See [contributions guide](CONTRIBUTING.md) + +## About [ByteDance Seed Team](https://team.doubao.com/) + +Founded in 2023, ByteDance Seed Team is dedicated to crafting the industry's most advanced AI foundation models. The team aspires to become a world-class research team and make significant contributions to the advancement of science and society. You can get to know Bytedance Seed better through the following channels👇 +
+ + + + + + + + + +
+--- + +We are HIRING! Send us an [email](mailto:the.verl.project@gmail.com) if you are interested in internship/FTE opportunities in RL for agents. diff --git a/verl/verl.egg-info/SOURCES.txt b/verl/verl.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..c5ee9162167af921ad4a4941651e8013278980fb --- /dev/null +++ b/verl/verl.egg-info/SOURCES.txt @@ -0,0 +1,747 @@ +LICENSE +README.md +pyproject.toml +setup.py +./scripts/__init__.py +./scripts/converter_hf_to_mcore.py +./scripts/diagnose.py +./scripts/init_random_model.py +./scripts/legacy_model_merger.py +./scripts/print_cfg.py +./scripts/rollout_viewer.py +./tests/__init__.py +./tests/test_base_config_on_cpu.py +./tests/test_protocol_on_cpu.py +./tests/test_protocol_v2_on_cpu.py +./tests/interactions/__init__.py +./tests/interactions/test_gsm8k_interaction.py +./tests/interactions/test_interaction_registry.py +./tests/single_controller/__init__.py +./tests/single_controller/test_auto_padding_on_cpu.py +./tests/single_controller/test_colocated_workers.py +./tests/single_controller/test_colocated_workers_fused.py +./tests/single_controller/test_data_transfer.py +./tests/single_controller/test_decorator_on_cpu.py +./tests/single_controller/test_device_mesh_register.py +./tests/single_controller/test_driverfunc_to_worker.py +./tests/single_controller/test_fused_workers_on_cpu.py +./tests/single_controller/test_high_level_scheduling_api.py +./tests/single_controller/test_nested_worker.py +./tests/single_controller/test_ray_collectives.py +./tests/single_controller/test_ray_local_envs_on_cpu.py +./tests/single_controller/test_ray_utils_on_cpu.py +./tests/single_controller/test_rvdz.py +./tests/single_controller/test_worker_group_basics.py +./tests/single_controller/test_worker_group_torch.py +./tests/special_e2e/__init__.py +./tests/special_e2e/check_custom_rwd_fn.py +./tests/special_e2e/check_results.py +./tests/special_e2e/envs/__init__.py +./tests/special_e2e/envs/digit_completion/__init__.py +./tests/special_e2e/envs/digit_completion/task.py +./tests/special_e2e/envs/digit_completion/tokenizer.py +./tests/trainer/__init__.py +./tests/trainer/config/__init__.py +./tests/trainer/config/test_algo_config_on_cpu.py +./tests/trainer/config/test_legacy_config_on_cpu.py +./tests/trainer/ppo/__init__.py +./tests/trainer/ppo/test_core_algos_on_cpu.py +./tests/trainer/ppo/test_metric_utils_on_cpu.py +./verl/__init__.py +./verl/base_config.py +./verl/protocol.py +./verl/py.typed +./verl/experimental/__init__.py +./verl/experimental/agent_loop/__init__.py +./verl/experimental/agent_loop/agent_loop.py +./verl/experimental/agent_loop/single_turn_agent_loop.py +./verl/experimental/agent_loop/tool_agent_loop.py +./verl/experimental/agent_loop/tool_parser.py +./verl/experimental/dataset/__init__.py +./verl/experimental/dataset/sampler.py +./verl/experimental/dynamic_dataset/__init__.py +./verl/experimental/dynamic_dataset/dynamicgen_dataset.py +./verl/interactions/__init__.py +./verl/interactions/base.py +./verl/interactions/gsm8k_interaction.py +./verl/interactions/weather_interaction.py +./verl/interactions/utils/__init__.py +./verl/interactions/utils/interaction_registry.py +./verl/model_merger/__init__.py +./verl/model_merger/__main__.py +./verl/model_merger/base_model_merger.py +./verl/model_merger/fsdp_model_merger.py +./verl/model_merger/megatron_model_merger.py +./verl/models/__init__.py +./verl/models/registry.py +./verl/models/weight_loader_registry.py +./verl/models/llama/__init__.py +./verl/models/llama/megatron/__init__.py +./verl/models/llama/megatron/modeling_llama_megatron.py +./verl/models/llama/megatron/checkpoint_utils/__init__.py +./verl/models/llama/megatron/checkpoint_utils/llama_loader.py +./verl/models/llama/megatron/checkpoint_utils/llama_loader_depracated.py +./verl/models/llama/megatron/checkpoint_utils/llama_saver.py +./verl/models/llama/megatron/layers/__init__.py +./verl/models/llama/megatron/layers/parallel_attention.py +./verl/models/llama/megatron/layers/parallel_decoder.py +./verl/models/llama/megatron/layers/parallel_linear.py +./verl/models/llama/megatron/layers/parallel_mlp.py +./verl/models/llama/megatron/layers/parallel_rmsnorm.py +./verl/models/mcore/__init__.py +./verl/models/mcore/config_converter.py +./verl/models/mcore/loader.py +./verl/models/mcore/mbridge.py +./verl/models/mcore/model_forward.py +./verl/models/mcore/model_forward_fused.py +./verl/models/mcore/model_initializer.py +./verl/models/mcore/patch_v012.py +./verl/models/mcore/registry.py +./verl/models/mcore/saver.py +./verl/models/mcore/util.py +./verl/models/mcore/weight_converter.py +./verl/models/mcore/qwen2_5_vl/__init__.py +./verl/models/mcore/qwen2_5_vl/attention.py +./verl/models/mcore/qwen2_5_vl/model.py +./verl/models/mcore/qwen2_5_vl/rope_utils.py +./verl/models/mcore/qwen2_5_vl/vision_config.py +./verl/models/mcore/qwen2_5_vl/vision_model.py +./verl/models/mcore/qwen2_5_vl/vision_transformer_block.py +./verl/models/qwen2/__init__.py +./verl/models/qwen2/megatron/__init__.py +./verl/models/qwen2/megatron/modeling_qwen2_megatron.py +./verl/models/qwen2/megatron/checkpoint_utils/__init__.py +./verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader.py +./verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader_depracated.py +./verl/models/qwen2/megatron/checkpoint_utils/qwen2_saver.py +./verl/models/qwen2/megatron/layers/__init__.py +./verl/models/qwen2/megatron/layers/parallel_attention.py +./verl/models/qwen2/megatron/layers/parallel_decoder.py +./verl/models/qwen2/megatron/layers/parallel_linear.py +./verl/models/qwen2/megatron/layers/parallel_mlp.py +./verl/models/qwen2/megatron/layers/parallel_rmsnorm.py +./verl/models/transformers/__init__.py +./verl/models/transformers/apertus.py +./verl/models/transformers/dense_common.py +./verl/models/transformers/glm4v.py +./verl/models/transformers/kimi_vl.py +./verl/models/transformers/llama.py +./verl/models/transformers/monkey_patch.py +./verl/models/transformers/npu_patch.py +./verl/models/transformers/qwen2.py +./verl/models/transformers/qwen2_vl.py +./verl/models/transformers/qwen3_vl.py +./verl/single_controller/__init__.py +./verl/single_controller/base/__init__.py +./verl/single_controller/base/decorator.py +./verl/single_controller/base/worker.py +./verl/single_controller/base/worker_group.py +./verl/single_controller/ray/__init__.py +./verl/single_controller/ray/base.py +./verl/third_party/__init__.py +./verl/third_party/sglang/__init__.py +./verl/third_party/sglang/parallel_state.py +./verl/third_party/torch/__init__.py +./verl/third_party/torch/distributed/__init__.py +./verl/third_party/torch/distributed/_state_dict_utils.py +./verl/third_party/torch/distributed/checkpoint/__init__.py +./verl/third_party/torch/distributed/checkpoint/state_dict.py +./verl/third_party/vllm/__init__.py +./verl/tools/__init__.py +./verl/tools/base_tool.py +./verl/tools/geo3k_tool.py +./verl/tools/gsm8k_tool.py +./verl/tools/image_zoom_in_tool.py +./verl/tools/mcp_base_tool.py +./verl/tools/mcp_search_tool.py +./verl/tools/sandbox_fusion_tools.py +./verl/tools/schemas.py +./verl/tools/search_tool.py +./verl/tools/utils/__init__.py +./verl/tools/utils/search_r1_like_utils.py +./verl/tools/utils/tool_registry.py +./verl/trainer/__init__.py +./verl/trainer/constants_ppo.py +./verl/trainer/fsdp_sft_trainer.py +./verl/trainer/main_eval.py +./verl/trainer/main_generation.py +./verl/trainer/main_ppo.py +./verl/trainer/sft_trainer.py +./verl/trainer/config/__init__.py +./verl/trainer/config/_generated_ppo_megatron_trainer.yaml +./verl/trainer/config/_generated_ppo_trainer.yaml +./verl/trainer/config/algorithm.py +./verl/trainer/config/config.py +./verl/trainer/config/evaluation.yaml +./verl/trainer/config/generation.yaml +./verl/trainer/config/ppo_megatron_trainer.yaml +./verl/trainer/config/ppo_trainer.yaml +./verl/trainer/config/sft_trainer.yaml +./verl/trainer/config/sft_trainer_engine.yaml +./verl/trainer/config/actor/actor.yaml +./verl/trainer/config/actor/dp_actor.yaml +./verl/trainer/config/actor/megatron_actor.yaml +./verl/trainer/config/critic/critic.yaml +./verl/trainer/config/critic/dp_critic.yaml +./verl/trainer/config/critic/megatron_critic.yaml +./verl/trainer/config/data/legacy_data.yaml +./verl/trainer/config/engine/fsdp.yaml +./verl/trainer/config/engine/megatron.yaml +./verl/trainer/config/model/hf_model.yaml +./verl/trainer/config/npu_profile/npu_profile.yaml +./verl/trainer/config/optim/fsdp.yaml +./verl/trainer/config/optim/megatron.yaml +./verl/trainer/config/ref/dp_ref.yaml +./verl/trainer/config/ref/megatron_ref.yaml +./verl/trainer/config/ref/ref.yaml +./verl/trainer/config/reward_model/dp_reward_model.yaml +./verl/trainer/config/reward_model/megatron_reward_model.yaml +./verl/trainer/config/reward_model/reward_model.yaml +./verl/trainer/config/rollout/rollout.yaml +./verl/trainer/ppo/__init__.py +./verl/trainer/ppo/core_algos.py +./verl/trainer/ppo/metric_utils.py +./verl/trainer/ppo/ray_trainer.py +./verl/trainer/ppo/reward.py +./verl/trainer/ppo/utils.py +./verl/utils/__init__.py +./verl/utils/activation_offload.py +./verl/utils/attention_utils.py +./verl/utils/config.py +./verl/utils/device.py +./verl/utils/distributed.py +./verl/utils/flops_counter.py +./verl/utils/fs.py +./verl/utils/fsdp_utils.py +./verl/utils/groupwise.py +./verl/utils/hdfs_io.py +./verl/utils/import_utils.py +./verl/utils/logging_utils.py +./verl/utils/megatron_utils.py +./verl/utils/memory_buffer.py +./verl/utils/memory_utils.py +./verl/utils/model.py +./verl/utils/net_utils.py +./verl/utils/npu_utils.py +./verl/utils/py_functional.py +./verl/utils/ray_utils.py +./verl/utils/rollout_skip.py +./verl/utils/rollout_trace.py +./verl/utils/seqlen_balancing.py +./verl/utils/tensordict_utils.py +./verl/utils/tokenizer.py +./verl/utils/torch_dtypes.py +./verl/utils/torch_functional.py +./verl/utils/tracking.py +./verl/utils/transformers_compat.py +./verl/utils/ulysses.py +./verl/utils/checkpoint/__init__.py +./verl/utils/checkpoint/checkpoint_handler.py +./verl/utils/checkpoint/checkpoint_manager.py +./verl/utils/checkpoint/fsdp_checkpoint_manager.py +./verl/utils/checkpoint/megatron_checkpoint_manager.py +./verl/utils/dataset/__init__.py +./verl/utils/dataset/dataset_utils.py +./verl/utils/dataset/multiturn_sft_dataset.py +./verl/utils/dataset/rl_dataset.py +./verl/utils/dataset/rm_dataset.py +./verl/utils/dataset/sft_dataset.py +./verl/utils/dataset/vision_utils.py +./verl/utils/debug/__init__.py +./verl/utils/debug/metrics.py +./verl/utils/debug/performance.py +./verl/utils/debug/trajectory_tracker.py +./verl/utils/experimental/__init__.py +./verl/utils/experimental/torch_functional.py +./verl/utils/kernel/__init__.py +./verl/utils/kernel/kernels.py +./verl/utils/kernel/linear_cross_entropy.py +./verl/utils/logger/__init__.py +./verl/utils/logger/aggregate_logger.py +./verl/utils/megatron/__init__.py +./verl/utils/megatron/dist_checkpointing.py +./verl/utils/megatron/memory.py +./verl/utils/megatron/optimizer.py +./verl/utils/megatron/pipeline_parallel.py +./verl/utils/megatron/sequence_parallel.py +./verl/utils/megatron/tensor_parallel.py +./verl/utils/metric/__init__.py +./verl/utils/metric/utils.py +./verl/utils/profiler/__init__.py +./verl/utils/profiler/config.py +./verl/utils/profiler/empty_annotations.py +./verl/utils/profiler/mstx_profile.py +./verl/utils/profiler/nvtx_profile.py +./verl/utils/profiler/performance.py +./verl/utils/profiler/profile.py +./verl/utils/rendezvous/__init__.py +./verl/utils/rendezvous/ray_backend.py +./verl/utils/reward_score/__init__.py +./verl/utils/reward_score/geo3k.py +./verl/utils/reward_score/gsm8k.py +./verl/utils/reward_score/math_batch.py +./verl/utils/reward_score/math_dapo.py +./verl/utils/reward_score/math_reward.py +./verl/utils/reward_score/math_verify.py +./verl/utils/reward_score/search_r1_like_qa_em.py +./verl/utils/reward_score/prime_code/__init__.py +./verl/utils/reward_score/prime_code/testing_util.py +./verl/utils/reward_score/prime_code/utils.py +./verl/utils/reward_score/prime_math/__init__.py +./verl/utils/reward_score/prime_math/grader.py +./verl/utils/reward_score/prime_math/math_normalize.py +./verl/utils/reward_score/sandbox_fusion/__init__.py +./verl/utils/reward_score/sandbox_fusion/utils.py +./verl/utils/vllm/__init__.py +./verl/utils/vllm/patch.py +./verl/utils/vllm/utils.py +./verl/version/version +./verl/workers/__init__.py +./verl/workers/fsdp_workers.py +./verl/workers/megatron_workers.py +./verl/workers/actor/__init__.py +./verl/workers/actor/base.py +./verl/workers/actor/dp_actor.py +./verl/workers/actor/megatron_actor.py +./verl/workers/config/__init__.py +./verl/workers/config/actor.py +./verl/workers/config/critic.py +./verl/workers/config/engine.py +./verl/workers/config/model.py +./verl/workers/config/optimizer.py +./verl/workers/config/reward_model.py +./verl/workers/config/rollout.py +./verl/workers/critic/__init__.py +./verl/workers/critic/base.py +./verl/workers/critic/dp_critic.py +./verl/workers/critic/megatron_critic.py +./verl/workers/engine/__init__.py +./verl/workers/engine/base.py +./verl/workers/engine/utils.py +./verl/workers/engine/fsdp/__init__.py +./verl/workers/engine/fsdp/transformer_impl.py +./verl/workers/engine/fsdp/utils.py +./verl/workers/engine/megatron/__init__.py +./verl/workers/engine/megatron/transformer_impl.py +./verl/workers/engine/megatron/utils.py +./verl/workers/engine/mindspeed/__init__.py +./verl/workers/engine/mindspeed/transformer_impl.py +./verl/workers/reward_manager/__init__.py +./verl/workers/reward_manager/abstract.py +./verl/workers/reward_manager/batch.py +./verl/workers/reward_manager/dapo.py +./verl/workers/reward_manager/naive.py +./verl/workers/reward_manager/prime.py +./verl/workers/reward_manager/registry.py +./verl/workers/reward_model/__init__.py +./verl/workers/reward_model/base.py +./verl/workers/reward_model/megatron/__init__.py +./verl/workers/reward_model/megatron/reward_model.py +./verl/workers/roles/__init__.py +./verl/workers/roles/actor.py +./verl/workers/roles/critic.py +./verl/workers/roles/hybrid_engine.py +./verl/workers/roles/reward_model.py +./verl/workers/roles/reward_model_engine/__init__.py +./verl/workers/roles/reward_model_engine/base.py +./verl/workers/roles/reward_model_engine/sglang_reward_model.py +./verl/workers/roles/utils/__init__.py +./verl/workers/roles/utils/losses.py +./verl/workers/rollout/__init__.py +./verl/workers/rollout/base.py +./verl/workers/rollout/hf_rollout.py +./verl/workers/rollout/replica.py +./verl/workers/rollout/schemas.py +./verl/workers/rollout/tokenizer.py +./verl/workers/rollout/utils.py +./verl/workers/rollout/naive/__init__.py +./verl/workers/rollout/naive/naive_rollout.py +./verl/workers/rollout/sglang_rollout/__init__.py +./verl/workers/rollout/sglang_rollout/async_sglang_server.py +./verl/workers/rollout/sglang_rollout/http_server_engine.py +./verl/workers/rollout/sglang_rollout/sglang_rollout.py +./verl/workers/rollout/sglang_rollout/utils.py +./verl/workers/rollout/vllm_rollout/__init__.py +./verl/workers/rollout/vllm_rollout/vllm_async_server.py +./verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py +./verl/workers/sharding_manager/__init__.py +./verl/workers/sharding_manager/base.py +./verl/workers/sharding_manager/fsdp_sglang.py +./verl/workers/sharding_manager/fsdp_ulysses.py +./verl/workers/sharding_manager/fsdp_vllm.py +./verl/workers/sharding_manager/megatron_sglang.py +./verl/workers/sharding_manager/megatron_vllm.py +scripts/__init__.py +scripts/converter_hf_to_mcore.py +scripts/diagnose.py +scripts/init_random_model.py +scripts/legacy_model_merger.py +scripts/print_cfg.py +scripts/rollout_viewer.py +tests/__init__.py +tests/test_base_config_on_cpu.py +tests/test_protocol_on_cpu.py +tests/test_protocol_v2_on_cpu.py +tests/interactions/__init__.py +tests/interactions/test_gsm8k_interaction.py +tests/interactions/test_interaction_registry.py +tests/single_controller/__init__.py +tests/single_controller/test_auto_padding_on_cpu.py +tests/single_controller/test_colocated_workers.py +tests/single_controller/test_colocated_workers_fused.py +tests/single_controller/test_data_transfer.py +tests/single_controller/test_decorator_on_cpu.py +tests/single_controller/test_device_mesh_register.py +tests/single_controller/test_driverfunc_to_worker.py +tests/single_controller/test_fused_workers_on_cpu.py +tests/single_controller/test_high_level_scheduling_api.py +tests/single_controller/test_nested_worker.py +tests/single_controller/test_ray_collectives.py +tests/single_controller/test_ray_local_envs_on_cpu.py +tests/single_controller/test_ray_utils_on_cpu.py +tests/single_controller/test_rvdz.py +tests/single_controller/test_worker_group_basics.py +tests/single_controller/test_worker_group_torch.py +tests/special_e2e/__init__.py +tests/special_e2e/check_custom_rwd_fn.py +tests/special_e2e/check_results.py +tests/special_e2e/envs/__init__.py +tests/special_e2e/envs/digit_completion/__init__.py +tests/special_e2e/envs/digit_completion/task.py +tests/special_e2e/envs/digit_completion/tokenizer.py +tests/trainer/__init__.py +tests/trainer/config/__init__.py +tests/trainer/config/test_algo_config_on_cpu.py +tests/trainer/config/test_legacy_config_on_cpu.py +tests/trainer/ppo/__init__.py +tests/trainer/ppo/test_core_algos_on_cpu.py +tests/trainer/ppo/test_metric_utils_on_cpu.py +verl/__init__.py +verl/base_config.py +verl/protocol.py +verl/py.typed +verl.egg-info/PKG-INFO +verl.egg-info/SOURCES.txt +verl.egg-info/dependency_links.txt +verl.egg-info/requires.txt +verl.egg-info/top_level.txt +verl/experimental/__init__.py +verl/experimental/agent_loop/__init__.py +verl/experimental/agent_loop/agent_loop.py +verl/experimental/agent_loop/single_turn_agent_loop.py +verl/experimental/agent_loop/tool_agent_loop.py +verl/experimental/agent_loop/tool_parser.py +verl/experimental/dataset/__init__.py +verl/experimental/dataset/sampler.py +verl/experimental/dynamic_dataset/__init__.py +verl/experimental/dynamic_dataset/dynamicgen_dataset.py +verl/interactions/__init__.py +verl/interactions/base.py +verl/interactions/gsm8k_interaction.py +verl/interactions/weather_interaction.py +verl/interactions/utils/__init__.py +verl/interactions/utils/interaction_registry.py +verl/model_merger/__init__.py +verl/model_merger/__main__.py +verl/model_merger/base_model_merger.py +verl/model_merger/fsdp_model_merger.py +verl/model_merger/megatron_model_merger.py +verl/models/__init__.py +verl/models/registry.py +verl/models/weight_loader_registry.py +verl/models/llama/__init__.py +verl/models/llama/megatron/__init__.py +verl/models/llama/megatron/modeling_llama_megatron.py +verl/models/llama/megatron/checkpoint_utils/__init__.py +verl/models/llama/megatron/checkpoint_utils/llama_loader.py +verl/models/llama/megatron/checkpoint_utils/llama_loader_depracated.py +verl/models/llama/megatron/checkpoint_utils/llama_saver.py +verl/models/llama/megatron/layers/__init__.py +verl/models/llama/megatron/layers/parallel_attention.py +verl/models/llama/megatron/layers/parallel_decoder.py +verl/models/llama/megatron/layers/parallel_linear.py +verl/models/llama/megatron/layers/parallel_mlp.py +verl/models/llama/megatron/layers/parallel_rmsnorm.py +verl/models/mcore/__init__.py +verl/models/mcore/config_converter.py +verl/models/mcore/loader.py +verl/models/mcore/mbridge.py +verl/models/mcore/model_forward.py +verl/models/mcore/model_forward_fused.py +verl/models/mcore/model_initializer.py +verl/models/mcore/patch_v012.py +verl/models/mcore/registry.py +verl/models/mcore/saver.py +verl/models/mcore/util.py +verl/models/mcore/weight_converter.py +verl/models/mcore/qwen2_5_vl/__init__.py +verl/models/mcore/qwen2_5_vl/attention.py +verl/models/mcore/qwen2_5_vl/model.py +verl/models/mcore/qwen2_5_vl/rope_utils.py +verl/models/mcore/qwen2_5_vl/vision_config.py +verl/models/mcore/qwen2_5_vl/vision_model.py +verl/models/mcore/qwen2_5_vl/vision_transformer_block.py +verl/models/qwen2/__init__.py +verl/models/qwen2/megatron/__init__.py +verl/models/qwen2/megatron/modeling_qwen2_megatron.py +verl/models/qwen2/megatron/checkpoint_utils/__init__.py +verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader.py +verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader_depracated.py +verl/models/qwen2/megatron/checkpoint_utils/qwen2_saver.py +verl/models/qwen2/megatron/layers/__init__.py +verl/models/qwen2/megatron/layers/parallel_attention.py +verl/models/qwen2/megatron/layers/parallel_decoder.py +verl/models/qwen2/megatron/layers/parallel_linear.py +verl/models/qwen2/megatron/layers/parallel_mlp.py +verl/models/qwen2/megatron/layers/parallel_rmsnorm.py +verl/models/transformers/__init__.py +verl/models/transformers/apertus.py +verl/models/transformers/dense_common.py +verl/models/transformers/glm4v.py +verl/models/transformers/kimi_vl.py +verl/models/transformers/llama.py +verl/models/transformers/monkey_patch.py +verl/models/transformers/npu_patch.py +verl/models/transformers/qwen2.py +verl/models/transformers/qwen2_vl.py +verl/models/transformers/qwen3_vl.py +verl/single_controller/__init__.py +verl/single_controller/base/__init__.py +verl/single_controller/base/decorator.py +verl/single_controller/base/worker.py +verl/single_controller/base/worker_group.py +verl/single_controller/ray/__init__.py +verl/single_controller/ray/base.py +verl/third_party/__init__.py +verl/third_party/sglang/__init__.py +verl/third_party/sglang/parallel_state.py +verl/third_party/torch/__init__.py +verl/third_party/torch/distributed/__init__.py +verl/third_party/torch/distributed/_state_dict_utils.py +verl/third_party/torch/distributed/checkpoint/__init__.py +verl/third_party/torch/distributed/checkpoint/state_dict.py +verl/third_party/vllm/__init__.py +verl/tools/__init__.py +verl/tools/base_tool.py +verl/tools/geo3k_tool.py +verl/tools/gsm8k_tool.py +verl/tools/image_zoom_in_tool.py +verl/tools/mcp_base_tool.py +verl/tools/mcp_search_tool.py +verl/tools/sandbox_fusion_tools.py +verl/tools/schemas.py +verl/tools/search_tool.py +verl/tools/utils/__init__.py +verl/tools/utils/search_r1_like_utils.py +verl/tools/utils/tool_registry.py +verl/trainer/__init__.py +verl/trainer/constants_ppo.py +verl/trainer/fsdp_sft_trainer.py +verl/trainer/main_eval.py +verl/trainer/main_generation.py +verl/trainer/main_ppo.py +verl/trainer/sft_trainer.py +verl/trainer/config/__init__.py +verl/trainer/config/_generated_ppo_megatron_trainer.yaml +verl/trainer/config/_generated_ppo_trainer.yaml +verl/trainer/config/algorithm.py +verl/trainer/config/config.py +verl/trainer/config/evaluation.yaml +verl/trainer/config/generation.yaml +verl/trainer/config/ppo_megatron_trainer.yaml +verl/trainer/config/ppo_trainer.yaml +verl/trainer/config/sft_trainer.yaml +verl/trainer/config/sft_trainer_engine.yaml +verl/trainer/config/actor/actor.yaml +verl/trainer/config/actor/dp_actor.yaml +verl/trainer/config/actor/megatron_actor.yaml +verl/trainer/config/critic/critic.yaml +verl/trainer/config/critic/dp_critic.yaml +verl/trainer/config/critic/megatron_critic.yaml +verl/trainer/config/data/legacy_data.yaml +verl/trainer/config/engine/fsdp.yaml +verl/trainer/config/engine/megatron.yaml +verl/trainer/config/model/hf_model.yaml +verl/trainer/config/npu_profile/npu_profile.yaml +verl/trainer/config/optim/fsdp.yaml +verl/trainer/config/optim/megatron.yaml +verl/trainer/config/ref/dp_ref.yaml +verl/trainer/config/ref/megatron_ref.yaml +verl/trainer/config/ref/ref.yaml +verl/trainer/config/reward_model/dp_reward_model.yaml +verl/trainer/config/reward_model/megatron_reward_model.yaml +verl/trainer/config/reward_model/reward_model.yaml +verl/trainer/config/rollout/rollout.yaml +verl/trainer/ppo/__init__.py +verl/trainer/ppo/core_algos.py +verl/trainer/ppo/metric_utils.py +verl/trainer/ppo/ray_trainer.py +verl/trainer/ppo/reward.py +verl/trainer/ppo/utils.py +verl/utils/__init__.py +verl/utils/activation_offload.py +verl/utils/attention_utils.py +verl/utils/config.py +verl/utils/device.py +verl/utils/distributed.py +verl/utils/flops_counter.py +verl/utils/fs.py +verl/utils/fsdp_utils.py +verl/utils/groupwise.py +verl/utils/hdfs_io.py +verl/utils/import_utils.py +verl/utils/logging_utils.py +verl/utils/megatron_utils.py +verl/utils/memory_buffer.py +verl/utils/memory_utils.py +verl/utils/model.py +verl/utils/net_utils.py +verl/utils/npu_utils.py +verl/utils/py_functional.py +verl/utils/ray_utils.py +verl/utils/rollout_skip.py +verl/utils/rollout_trace.py +verl/utils/seqlen_balancing.py +verl/utils/tensordict_utils.py +verl/utils/tokenizer.py +verl/utils/torch_dtypes.py +verl/utils/torch_functional.py +verl/utils/tracking.py +verl/utils/transformers_compat.py +verl/utils/ulysses.py +verl/utils/checkpoint/__init__.py +verl/utils/checkpoint/checkpoint_handler.py +verl/utils/checkpoint/checkpoint_manager.py +verl/utils/checkpoint/fsdp_checkpoint_manager.py +verl/utils/checkpoint/megatron_checkpoint_manager.py +verl/utils/dataset/__init__.py +verl/utils/dataset/dataset_utils.py +verl/utils/dataset/multiturn_sft_dataset.py +verl/utils/dataset/rl_dataset.py +verl/utils/dataset/rm_dataset.py +verl/utils/dataset/sft_dataset.py +verl/utils/dataset/vision_utils.py +verl/utils/debug/__init__.py +verl/utils/debug/metrics.py +verl/utils/debug/performance.py +verl/utils/debug/trajectory_tracker.py +verl/utils/experimental/__init__.py +verl/utils/experimental/torch_functional.py +verl/utils/kernel/__init__.py +verl/utils/kernel/kernels.py +verl/utils/kernel/linear_cross_entropy.py +verl/utils/logger/__init__.py +verl/utils/logger/aggregate_logger.py +verl/utils/megatron/__init__.py +verl/utils/megatron/dist_checkpointing.py +verl/utils/megatron/memory.py +verl/utils/megatron/optimizer.py +verl/utils/megatron/pipeline_parallel.py +verl/utils/megatron/sequence_parallel.py +verl/utils/megatron/tensor_parallel.py +verl/utils/metric/__init__.py +verl/utils/metric/utils.py +verl/utils/profiler/__init__.py +verl/utils/profiler/config.py +verl/utils/profiler/empty_annotations.py +verl/utils/profiler/mstx_profile.py +verl/utils/profiler/nvtx_profile.py +verl/utils/profiler/performance.py +verl/utils/profiler/profile.py +verl/utils/rendezvous/__init__.py +verl/utils/rendezvous/ray_backend.py +verl/utils/reward_score/__init__.py +verl/utils/reward_score/geo3k.py +verl/utils/reward_score/gsm8k.py +verl/utils/reward_score/math_batch.py +verl/utils/reward_score/math_dapo.py +verl/utils/reward_score/math_reward.py +verl/utils/reward_score/math_verify.py +verl/utils/reward_score/search_r1_like_qa_em.py +verl/utils/reward_score/prime_code/__init__.py +verl/utils/reward_score/prime_code/testing_util.py +verl/utils/reward_score/prime_code/utils.py +verl/utils/reward_score/prime_math/__init__.py +verl/utils/reward_score/prime_math/grader.py +verl/utils/reward_score/prime_math/math_normalize.py +verl/utils/reward_score/sandbox_fusion/__init__.py +verl/utils/reward_score/sandbox_fusion/utils.py +verl/utils/vllm/__init__.py +verl/utils/vllm/patch.py +verl/utils/vllm/utils.py +verl/version/version +verl/workers/__init__.py +verl/workers/fsdp_workers.py +verl/workers/megatron_workers.py +verl/workers/actor/__init__.py +verl/workers/actor/base.py +verl/workers/actor/dp_actor.py +verl/workers/actor/megatron_actor.py +verl/workers/config/__init__.py +verl/workers/config/actor.py +verl/workers/config/critic.py +verl/workers/config/engine.py +verl/workers/config/model.py +verl/workers/config/optimizer.py +verl/workers/config/reward_model.py +verl/workers/config/rollout.py +verl/workers/critic/__init__.py +verl/workers/critic/base.py +verl/workers/critic/dp_critic.py +verl/workers/critic/megatron_critic.py +verl/workers/engine/__init__.py +verl/workers/engine/base.py +verl/workers/engine/utils.py +verl/workers/engine/fsdp/__init__.py +verl/workers/engine/fsdp/transformer_impl.py +verl/workers/engine/fsdp/utils.py +verl/workers/engine/megatron/__init__.py +verl/workers/engine/megatron/transformer_impl.py +verl/workers/engine/megatron/utils.py +verl/workers/engine/mindspeed/__init__.py +verl/workers/engine/mindspeed/transformer_impl.py +verl/workers/reward_manager/__init__.py +verl/workers/reward_manager/abstract.py +verl/workers/reward_manager/batch.py +verl/workers/reward_manager/dapo.py +verl/workers/reward_manager/naive.py +verl/workers/reward_manager/prime.py +verl/workers/reward_manager/registry.py +verl/workers/reward_model/__init__.py +verl/workers/reward_model/base.py +verl/workers/reward_model/megatron/__init__.py +verl/workers/reward_model/megatron/reward_model.py +verl/workers/roles/__init__.py +verl/workers/roles/actor.py +verl/workers/roles/critic.py +verl/workers/roles/hybrid_engine.py +verl/workers/roles/reward_model.py +verl/workers/roles/reward_model_engine/__init__.py +verl/workers/roles/reward_model_engine/base.py +verl/workers/roles/reward_model_engine/sglang_reward_model.py +verl/workers/roles/utils/__init__.py +verl/workers/roles/utils/losses.py +verl/workers/rollout/__init__.py +verl/workers/rollout/base.py +verl/workers/rollout/hf_rollout.py +verl/workers/rollout/replica.py +verl/workers/rollout/schemas.py +verl/workers/rollout/tokenizer.py +verl/workers/rollout/utils.py +verl/workers/rollout/naive/__init__.py +verl/workers/rollout/naive/naive_rollout.py +verl/workers/rollout/sglang_rollout/__init__.py +verl/workers/rollout/sglang_rollout/async_sglang_server.py +verl/workers/rollout/sglang_rollout/http_server_engine.py +verl/workers/rollout/sglang_rollout/sglang_rollout.py +verl/workers/rollout/sglang_rollout/utils.py +verl/workers/rollout/vllm_rollout/__init__.py +verl/workers/rollout/vllm_rollout/vllm_async_server.py +verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py +verl/workers/sharding_manager/__init__.py +verl/workers/sharding_manager/base.py +verl/workers/sharding_manager/fsdp_sglang.py +verl/workers/sharding_manager/fsdp_ulysses.py +verl/workers/sharding_manager/fsdp_vllm.py +verl/workers/sharding_manager/megatron_sglang.py +verl/workers/sharding_manager/megatron_vllm.py \ No newline at end of file diff --git a/verl/verl.egg-info/dependency_links.txt b/verl/verl.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/verl/verl.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/verl/verl.egg-info/requires.txt b/verl/verl.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..3bfcef73cebee6ed7c3b1e91e458185d42c86346 --- /dev/null +++ b/verl/verl.egg-info/requires.txt @@ -0,0 +1,54 @@ +accelerate +codetiming +datasets +dill +hydra-core +numpy<2.0.0 +pandas +peft +pyarrow>=19.0.0 +pybind11 +pylatexenc +ray[default]>=2.41.0 +torchdata +tensordict!=0.9.0,<=0.10.0,>=0.8.0 +transformers +wandb +packaging>=20.0 +tensorboard + +[geo] +mathruler +torchvision +qwen_vl_utils + +[gpu] +liger-kernel +flash-attn + +[math] +math-verify + +[mcore] +mbridge + +[prime] +pyext + +[sglang] +tensordict!=0.9.0,<=0.10.0,>=0.8.0 +sglang[openai,srt]==0.5.2 +torch==2.8.0 + +[test] +pytest +pre-commit +py-spy +pytest-asyncio + +[trl] +trl<=0.9.6 + +[vllm] +tensordict!=0.9.0,<=0.10.0,>=0.8.0 +vllm<=0.9.1,>=0.7.3 diff --git a/verl/verl.egg-info/top_level.txt b/verl/verl.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..f655d798cdd5ad03c4cdd162d4a96bd8ac0d6057 --- /dev/null +++ b/verl/verl.egg-info/top_level.txt @@ -0,0 +1,3 @@ +scripts +tests +verl diff --git a/verl/verl/utils/checkpoint/__init__.py b/verl/verl/utils/checkpoint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f10b6c49eeb98ab50f8c37b5f2e72b56dbef4406 --- /dev/null +++ b/verl/verl/utils/checkpoint/__init__.py @@ -0,0 +1,17 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .checkpoint_handler import CheckpointHandler + +__all__ = ["CheckpointHandler"] diff --git a/verl/verl/utils/checkpoint/checkpoint_handler.py b/verl/verl/utils/checkpoint/checkpoint_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..43a9cfbb69418d9de56fd0c1cde2e089c4bd32af --- /dev/null +++ b/verl/verl/utils/checkpoint/checkpoint_handler.py @@ -0,0 +1,204 @@ +# Copyright 2025 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# TODO: add unit tests + +import logging +import os +import re + +import torch + +import verl.utils.hdfs_io as hdfs_io +from verl.utils.checkpoint.checkpoint_manager import find_latest_ckpt_path, get_checkpoint_tracker_filename +from verl.utils.logger import log_with_rank +from verl.workers.engine import BaseEngine + + +def extract_step(path): + match = re.search(r"global_step_(\d+)", path) + if match: + return int(match.group(1)) + return None + + +logger = logging.getLogger(__file__) +logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN")) + + +class CheckpointHandler: + """ + Checkpoint handler handles the path, global_step of a checkpoint folder. + Currently, it only works with a single model. + We can expand it to support multiple models. It is expected to be used with SPMD style (e.g., torchrun) + """ + + def __init__( + self, + engine: BaseEngine, + train_dataloader, + *, + default_local_dir, + max_ckpt_to_keep=None, + default_hdfs_dir=None, + resume_mode="auto", + resume_from_path=None, + ): + self.default_local_dir = default_local_dir + self.max_ckpt_to_keep = max_ckpt_to_keep + self.default_hdfs_dir = default_hdfs_dir + self.resume_mode = resume_mode + self.resume_from_path = resume_from_path + self.engine = engine + self.train_dataloader = train_dataloader + self.rank = torch.distributed.get_rank() + + def save_checkpoint(self, step): + """Save checkpoint using FSDPCheckpointManager with improved tracking""" + from verl.utils.fs import local_mkdir_safe + + # Determine checkpoint path + local_global_step_folder = os.path.join(self.default_local_dir, f"global_step_{step}") + if self.rank == 0: + print(f"Saving checkpoint to: {local_global_step_folder}") + + # Get max checkpoints to keep + max_ckpt_to_keep = self.max_ckpt_to_keep + + # Use checkpoint manager to save + self.engine.save_checkpoint( + local_path=local_global_step_folder, global_step=step, max_ckpt_to_keep=max_ckpt_to_keep + ) + + # Save dataloader state. Note that we only save the iterator in the train_dataloader. + # So it's identical in each dp rank. + if self.engine.is_mp_src_rank_with_outputs(): + dp_rank = self.engine.get_data_parallel_rank() + local_mkdir_safe(local_global_step_folder) + dataloader_local_path = os.path.join(local_global_step_folder, f"data_{dp_rank}.pt") + + # Use StatefulDataLoader's built-in state dict functionality + dataloader_state_dict = self.train_dataloader.state_dict() + torch.save(dataloader_state_dict, dataloader_local_path) + print(f"Saved dataloader state to: {dataloader_local_path}") + + if self.rank == 0: + # Update latest checkpoint tracker (atomic write) + tracker_file = get_checkpoint_tracker_filename(self.default_local_dir) + temp_tracker_file = tracker_file + ".tmp" + with open(temp_tracker_file, "w") as f: + f.write(str(step)) + os.rename(temp_tracker_file, tracker_file) + print(f"Updated checkpoint tracker: {tracker_file}") + + # Copy to HDFS if configured + if self.rank == 0 and self.default_hdfs_dir: + hdfs_io.makedirs(self.default_hdfs_dir, exist_ok=True) + hdfs_io.copy(src=local_global_step_folder, dst=self.default_hdfs_dir, dirs_exist_ok=True) + + torch.distributed.barrier() + + def load_checkpoint(self): + # Determine resume path based on configuration + checkpoint_path = self._determine_resume_path() + + if checkpoint_path is None: + return 0 + + # extract resume step from checkpoint path + resume_step = extract_step(checkpoint_path) + if resume_step is None: + log_with_rank( + f"Warning: Could not extract step number from {checkpoint_path}, starting from step 0", + logger=logger, + rank=self.rank, + level=logging.WARNING, + log_only_rank_0=True, + ) + return 0 + self.resume_global_step = resume_step + + # Use checkpoint manager to load model state + self.engine.load_checkpoint(checkpoint_path) + # Always load dataloader state for StatefulDataLoader + self._load_dataloader_state(checkpoint_path) + + return resume_step + + def _load_dataloader_state(self, checkpoint_path: str): + """Load dataloader state from checkpoint""" + dp_rank = self.engine.get_data_parallel_rank() + dataloader_path = os.path.join(checkpoint_path, f"data_{dp_rank}.pt") + + if os.path.exists(dataloader_path): + # Use StatefulDataLoader's built-in state dict functionality + dataloader_state_dict = torch.load(dataloader_path, map_location="cpu", weights_only=False) + self.train_dataloader.load_state_dict(dataloader_state_dict) + + log_with_rank( + f"Successfully loaded dataloader state from {dataloader_path}", + logger=logger, + rank=self.rank, + log_only_rank_0=True, + ) + + else: + log_with_rank( + f"Warning: No dataloader state found at {dataloader_path}, will start from scratch", + logger=logger, + rank=self.rank, + level=logging.WARNING, + log_only_rank_0=True, + ) + + def _determine_resume_path(self): + """Determine the path to resume from based on resume_mode configuration""" + resume_mode = self.resume_mode + resume_from_path = self.resume_from_path + + if resume_mode == "disable": + return None + elif resume_mode == "auto": + if resume_from_path is not None: + assert os.path.exists(resume_from_path), ( + "resume_from_path must be null or an existing path when resume_mode is 'auto'" + ) + assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps" + return resume_from_path + # Try to find the latest checkpoint in the default directory + return self._find_latest_checkpoint() + elif resume_mode == "resume_path": + assert os.path.exists(resume_from_path), ( + "resume_from_path must be an existing path when resume_mode is 'resume_path'" + ) + assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps" + return resume_from_path + else: + raise ValueError(f"Invalid resume_mode: {resume_mode}. Must be 'auto', 'disable', or 'resume_path'") + + def _find_latest_checkpoint(self): + """Find the latest checkpoint in the default local directory""" + checkpoint_dir = self.default_local_dir + + if not os.path.exists(checkpoint_dir): + return None + + latest_checkpoint = find_latest_ckpt_path(checkpoint_dir) + + if latest_checkpoint and self.rank == 0: + step_num = extract_step(latest_checkpoint) + print(f"Found latest checkpoint: {latest_checkpoint} (step {step_num})") + + return latest_checkpoint diff --git a/verl/verl/utils/checkpoint/checkpoint_manager.py b/verl/verl/utils/checkpoint/checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..74fc83ecc3c2e51c3c08a971f02a0d3273456885 --- /dev/null +++ b/verl/verl/utils/checkpoint/checkpoint_manager.py @@ -0,0 +1,237 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import random +import shutil + +import numpy as np +import torch +import torch.distributed +from omegaconf import DictConfig +from transformers import PreTrainedTokenizer, ProcessorMixin + +from verl.trainer.config import CheckpointConfig +from verl.utils.device import get_device_name, get_torch_device + + +class BaseCheckpointManager: + """ + A checkpoint manager that saves and loads the following states in a SPMD way: + - model + - optimizer + - lr_scheduler + - extra_states + + We save + - sharded model states and optimizer states + - full lr_scheduler states + - huggingface tokenizer and config for ckpt merge + """ + + def __init__( + self, + model, + optimizer: torch.optim.Optimizer, + lr_scheduler: torch.optim.lr_scheduler.LRScheduler = None, + processing_class: PreTrainedTokenizer | ProcessorMixin = None, + checkpoint_config: DictConfig | CheckpointConfig = None, + ): + self.checkpoint_config = checkpoint_config + checkpoint_load_contents = checkpoint_config.get("load_contents", None) if checkpoint_config else None + checkpoint_save_contents = checkpoint_config.get("save_contents", None) if checkpoint_config else None + if checkpoint_load_contents is None: + checkpoint_load_contents = ["model", "optimizer", "extra"] + if checkpoint_save_contents is None: + checkpoint_save_contents = ["model", "optimizer", "extra"] + self.previous_global_step = None + self.previous_saved_paths = [] + + self.model = model + self.optimizer = optimizer + self.lr_scheduler = lr_scheduler + self.processing_class = processing_class + self.checkpoint_load_contents = checkpoint_load_contents + self.checkpoint_save_contents = checkpoint_save_contents + + self.rank = torch.distributed.get_rank() + self.world_size = torch.distributed.get_world_size() + + @property + def should_save_model(self) -> bool: + """ + Returns True if 'model' is in checkpoint_save_contents, indicating the model state should be saved. + """ + return "model" in self.checkpoint_save_contents + + @property + def should_save_optimizer(self) -> bool: + """ + Returns True if 'optimizer' is in checkpoint_save_contents, indicating the optimizer state should be saved. + """ + return "optimizer" in self.checkpoint_save_contents + + @property + def should_save_extra(self) -> bool: + """ + Returns True if 'extra' is in checkpoint_save_contents, indicating the extra state should be saved. + """ + return "extra" in self.checkpoint_save_contents + + @property + def should_save_hf_model(self) -> bool: + """ + Returns True if 'hf_model' is in checkpoint_save_contents, indicating the model should be converted to hf + model and saved. + """ + return "hf_model" in self.checkpoint_save_contents + + @property + def should_load_model(self) -> bool: + """ + Returns True if 'model' is in checkpoint_load_contents, indicating the model state should be loaded. + """ + return "model" in self.checkpoint_load_contents + + @property + def should_load_optimizer(self) -> bool: + """ + Returns True if 'optimizer' is in checkpoint_load_contents, indicating the optimizer state should be loaded. + """ + return "optimizer" in self.checkpoint_load_contents + + @property + def should_load_extra(self) -> bool: + """ + Returns True if 'extra' is in checkpoint_load_contents, indicating the extra state should be loaded. + """ + return "extra" in self.checkpoint_load_contents + + def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load: bool = False): + raise NotImplementedError + + def save_checkpoint( + self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep: int = None + ): + raise NotImplementedError + + @staticmethod + def checkpath(local_path: str, hdfs_path: str): + assert local_path is not None or hdfs_path is not None, "local_path and hdfs_path cannot be both None" + return local_path is not None, local_path if local_path is not None else hdfs_path + + def remove_previous_save_local_path(self, path): + if isinstance(path, str): + path = [path] + for p in path: + abs_path = os.path.abspath(p) + print(f"Checkpoint manager remove previous save local path: {abs_path}") + if not os.path.exists(abs_path): + continue + shutil.rmtree(abs_path, ignore_errors=True) + + @staticmethod + def get_rng_state(): + rng_state = { + "cpu": torch.get_rng_state(), + "numpy": np.random.get_state(), + "random": random.getstate(), + } + + if get_device_name() != "cpu": + rng_state[get_device_name()] = get_torch_device().get_rng_state() + + return rng_state + + @staticmethod + def load_rng_state(rng_state): + torch.set_rng_state(rng_state["cpu"]) + np.random.set_state(rng_state["numpy"]) + random.setstate(rng_state["random"]) + + if get_device_name() != "cpu": + get_torch_device().set_rng_state(rng_state[get_device_name()]) + + +def find_latest_ckpt_path(path, directory_format="global_step_{}"): + """ + Return the most recent checkpoint directory based on a tracker file. + + Args: + path (str): Base directory containing the checkpoint tracker. + directory_format (str): Template for checkpoint subfolders with one + placeholder for the iteration number (default "global_step_{}"). + + Returns: + str or None: Full path to the latest checkpoint directory, or + None if the tracker or checkpoint folder is missing. + """ + if path is None: + return None + + tracker_file = get_checkpoint_tracker_filename(path) + if not os.path.exists(tracker_file): + print(f"Checkpoint tracker file does not exist: {tracker_file}") + return None + + with open(tracker_file, "rb") as f: + iteration = int(f.read().decode()) + ckpt_path = os.path.join(path, directory_format.format(iteration)) + if not os.path.exists(ckpt_path): + print("Checkpoint does not exist: %s", ckpt_path) + return None + + print("Found checkpoint: %s", ckpt_path) + return ckpt_path + + +def get_checkpoint_tracker_filename(root_path: str): + """ + Tracker file rescords the latest chckpoint during training to restart from. + """ + return os.path.join(root_path, "latest_checkpointed_iteration.txt") + + +def should_save_ckpt_esi(max_steps_duration: float, save_ckpt_duration: float = 60, redundant_time: float = 0) -> bool: + """ + Determine if checkpoint should be saved based on capacity esi expiration. + + Args: + max_steps_duration: Max estimated time (seconds) required to complete one training step + save_ckpt_duration: Estimated time (seconds) required to save checkpoint (default: 60) + redundant_time: Additional buffer time (seconds) for unexpected delays (default: 0) + """ + exp_ts_mlp = os.getenv("MLP_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP") # vemlp + exp_ts_aws = os.getenv("SAGEMAKER_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP") # aws + if exp_ts_mlp: + try: + import time + + remaining = float(exp_ts_mlp) - time.time() + except ValueError: + return False + return ( + remaining > 0 + and max_steps_duration > 0 + and remaining <= save_ckpt_duration + max_steps_duration + redundant_time + ) + elif exp_ts_aws: + from datetime import datetime, timedelta + + expiration_time = datetime.fromtimestamp(int(exp_ts_aws)) + time_difference = expiration_time - datetime.now() + threshold_minutes = (save_ckpt_duration + max_steps_duration + redundant_time) / 60 + return time_difference < timedelta(minutes=threshold_minutes) + else: + return False diff --git a/verl/verl/utils/checkpoint/fsdp_checkpoint_manager.py b/verl/verl/utils/checkpoint/fsdp_checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..4b3d7a8e7add0ee2330020aadba17a71c6e20b68 --- /dev/null +++ b/verl/verl/utils/checkpoint/fsdp_checkpoint_manager.py @@ -0,0 +1,367 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging +import os +import warnings +from dataclasses import asdict, dataclass +from typing import Optional + +import torch +import torch.distributed +from accelerate import init_empty_weights +from omegaconf import DictConfig +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp import ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictType +from transformers import GenerationConfig, PreTrainedTokenizer, ProcessorMixin +from transformers.dynamic_module_utils import custom_object_save + +from verl.utils.device import is_cuda_available +from verl.utils.fs import copy_to_local, is_non_local, local_mkdir_safe +from verl.utils.fsdp_utils import fsdp_version, get_fsdp_full_state_dict, get_fsdp_state_ctx +from verl.utils.logger import log_with_rank + +from .checkpoint_manager import BaseCheckpointManager + +# Setup logging +logger = logging.getLogger(__file__) +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO")) + + +@dataclass +class FSDPConfig: + """Configuration for FSDP checkpointing. + + Args: + FSDP_version (int): Version of FSDP being used. + world_size (int): Number of processes in the distributed training setup. + """ + + FSDP_version: int + world_size: int + + +class FSDPCheckpointManager(BaseCheckpointManager): + """ + Manage FSDP checkpointing in SPMD training. + + - Saves/loads per-rank sharded model & optimizer states + - Persists full lr_scheduler and RNG state + - Stores HF tokenizer/processor and model/config for unified restore + + Args: + model (FSDP): Wrapped model instance. + optimizer (Optimizer): Training optimizer. + lr_scheduler (LRScheduler): Learning-rate scheduler. + processing_class (PreTrainedTokenizer or ProcessorMixin, optional): + Pre-/post-processing artifact handler. + checkpoint_contents DictConfig: Configuration for checkpoint contents. + - 'load': Components to load; must contain 'model'. Defaults to ['model', 'optimizer', 'extra']. + - 'save': Components to save; must contain 'model'. Defaults to ['model', 'optimizer', 'extra']. + """ + + def __init__( + self, + model: FSDP, + optimizer: Optional[torch.optim.Optimizer] = None, + lr_scheduler: Optional[torch.optim.lr_scheduler.LRScheduler] = None, + processing_class: PreTrainedTokenizer | ProcessorMixin = None, + checkpoint_config: DictConfig = None, + **kwargs, + ): + if processing_class is None and "tokenizer" in kwargs: + warnings.warn( + "`tokenizer` is deprecated. use `processing_class` instead.", DeprecationWarning, stacklevel=2 + ) + processing_class = kwargs.pop("tokenizer") + + super().__init__( + model, + optimizer, + lr_scheduler=lr_scheduler, + processing_class=processing_class, + checkpoint_config=checkpoint_config, + ) + + def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load=False): + """ + Load an FSDP checkpoint for this rank. + + Downloads and loads: + - model and optimizer shards + - extra state dict (scheduler + RNG) + + Args: + local_path: Directory with per-rank checkpoint files. + hdfs_path: Unused (for API compatibility). + del_local_after_load: Remove local files after loading. + """ + if local_path is None: + return + + # check if the checkpoint_load_contents is valid + if self.should_load_model: + assert self.model is not None, "model must be provided when checkpoint_contents.load includes ['model']" + if self.should_load_optimizer: + assert self.optimizer is not None, ( + "optimizer must be provided when checkpoint_contents.load includes ['optimizer']" + ) + + # every rank download its own checkpoint + state_dict_cfg = ( + ShardedStateDictConfig(offload_to_cpu=True if is_cuda_available else False) + if self.should_load_model + else None + ) + optim_cfg = ( + ShardedOptimStateDictConfig(offload_to_cpu=True if is_cuda_available else False) + if self.should_load_optimizer + else None + ) + with get_fsdp_state_ctx(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg): + if self.should_load_model: + remote_model_path = os.path.join(local_path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt") + local_model_path = copy_to_local(remote_model_path) + model_state_dict = torch.load(local_model_path, weights_only=False) + self.model.load_state_dict(model_state_dict) + log_with_rank(f"Loaded model from {remote_model_path}", rank=self.rank, logger=logger) + + if self.should_load_optimizer: + remote_optim_path = os.path.join(local_path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt") + local_optim_path = copy_to_local(remote_optim_path) + optimizer_state_dict = torch.load(local_optim_path, weights_only=False) + self.optimizer.load_state_dict(optimizer_state_dict) + log_with_rank(f"Loaded optimizer from {remote_optim_path}", rank=self.rank, logger=logger) + + if self.should_load_extra: + remote_extra_state_path = os.path.join( + local_path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt" + ) + local_extra_state_path = copy_to_local(remote_extra_state_path) + extra_state_dict = torch.load(local_extra_state_path, weights_only=False) + # recover random state + if "rng" in extra_state_dict: + # 'rng' may not exist for backward compatibility + self.load_rng_state(extra_state_dict["rng"]) + log_with_rank(f"Loaded rng from {remote_extra_state_path}", rank=self.rank, logger=logger) + + lr_scheduler_state_dict = extra_state_dict["lr_scheduler"] + if lr_scheduler_state_dict is not None and self.lr_scheduler is not None: + self.lr_scheduler.load_state_dict(lr_scheduler_state_dict) + log_with_rank(f"Loaded lr_scheduler from {remote_extra_state_path}", rank=self.rank, logger=logger) + + if self.rank == 0 and del_local_after_load: + try: + os.remove(local_model_path) if is_non_local(local_model_path) else None + os.remove(local_optim_path) if is_non_local(local_optim_path) else None + os.remove(local_extra_state_path) if is_non_local(local_extra_state_path) else None + except Exception as e: + log_with_rank( + f"remove local resume ckpt file after loading failed, exception {e} will be ignored", + rank=self.rank, + logger=logger, + ) + + # wait for everyone to load checkpoints + torch.distributed.barrier() + + def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep=None): + """ + Save an FSDP checkpoint for this rank. + + Writes: + - model & optimizer shard files + - extra state dict (scheduler + RNG) + - HF tokenizer/processor and model/config on rank 0 + - optional full HF model under 'huggingface/' if requested + + Rotates old checkpoints, keeping at most `max_ckpt_to_keep`. + + Args: + local_path: Target directory for checkpoint files. + hdfs_path: Unused (for API compatibility). + global_step: Current training step (used for bookkeeping). + max_ckpt_to_keep: Number of recent checkpoints to retain. + """ + if local_path is None: + return + + # record the previous global step + self.previous_global_step = global_step + + # remove previous local_path, only rank 0 should do this + if ( + self.rank == 0 + and max_ckpt_to_keep + and isinstance(max_ckpt_to_keep, int) + and max_ckpt_to_keep > 0 + and len(self.previous_saved_paths) >= max_ckpt_to_keep + ): + keep_start = len(self.previous_saved_paths) - max_ckpt_to_keep + 1 + self.remove_previous_save_local_path(self.previous_saved_paths[:keep_start]) + self.previous_saved_paths = self.previous_saved_paths[keep_start:] + + local_path = local_mkdir_safe(local_path) + torch.distributed.barrier() + + # check if the checkpoint_save_contents is valid + if self.should_save_model: + assert self.model is not None, "model must be provided when checkpoint_contents.save includes ['model']" + if self.should_save_optimizer: + assert self.optimizer is not None, ( + "optimizer must be provided when checkpoint_contents.save includes ['optimizer']" + ) + + # every rank will save its own model and optim shard + state_dict_cfg = ShardedStateDictConfig(offload_to_cpu=True if is_cuda_available else False) + optim_cfg = ShardedOptimStateDictConfig(offload_to_cpu=True if is_cuda_available else False) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with get_fsdp_state_ctx(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg): + model_path = os.path.join(local_path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt") + optim_path = os.path.join(local_path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt") + extra_path = os.path.join(local_path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt") + + if self.should_save_model: + model_state_dict = self.model.state_dict() + torch.save(model_state_dict, model_path) + log_with_rank(f"Saved model to {os.path.abspath(model_path)}", rank=self.rank, logger=logger) + + if self.should_save_optimizer: + optimizer_state_dict = self.optimizer.state_dict() + torch.save(optimizer_state_dict, optim_path) + log_with_rank(f"Saved optim to {os.path.abspath(optim_path)}", rank=self.rank, logger=logger) + + if self.should_save_extra: + lr_scheduler_state_dict = self.lr_scheduler.state_dict() if self.lr_scheduler is not None else None + extra_state_dict = { + "lr_scheduler": lr_scheduler_state_dict, + "rng": self.get_rng_state(), + } + torch.save(extra_state_dict, extra_path) + log_with_rank(f"Saved extra_state to {os.path.abspath(extra_path)}", rank=self.rank, logger=logger) + + if self.rank == 0: + # Save HF tokenizer/processor and model config on rank 0 to huggingface/ directory, no matter whether + # huggingface model is requested to be saved or not. + + if fsdp_version(self.model) == 1: + unwrap_model = self.model._fsdp_wrapped_module + else: + unwrap_model = self.model + + hf_config_tokenizer_path = os.path.join(local_path, "huggingface") + local_mkdir_safe(hf_config_tokenizer_path) + model_config = unwrap_model.config + generation_config = None + if unwrap_model.can_generate() and hasattr(model_config, "name_or_path") and model_config.name_or_path: + try: + # Some model's name_or_path is empty if not initialized from pretrained, + # in this cases, we don't save generation config. + generation_config = GenerationConfig.from_pretrained(model_config.name_or_path) + generation_config.save_pretrained(hf_config_tokenizer_path) + except Exception: + # if the generation config isn't available, we don't save it + pass + + model_config.save_pretrained(hf_config_tokenizer_path) + if self.processing_class is not None: + self.processing_class.save_pretrained(hf_config_tokenizer_path) + log_with_rank( + f"Saved model config and tokenizer class to {os.path.abspath(hf_config_tokenizer_path)}", + rank=self.rank, + logger=logger, + log_only_rank_0=True, + ) + + # If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be + # loaded from the Hub. + if hasattr(model_config, "auto_map"): + custom_object_save(unwrap_model, hf_config_tokenizer_path, config=model_config) + + # Also save runtime FSDP config + fsdp_config_path = os.path.join(local_path, "fsdp_config.json") + fsdp_config = FSDPConfig( + FSDP_version=fsdp_version(self.model), + world_size=self.world_size, + ) + with open(fsdp_config_path, "w") as f: + json.dump(asdict(fsdp_config), f, indent=4) + + # wait for everyone to dump to local + torch.distributed.barrier() + + if self.should_save_hf_model: + # Only rank 0 will save hf model and, + # offload to cpu to save LLMs which may be too large to fit in one GPU + state_dict = get_fsdp_full_state_dict(self.model, offload_to_cpu=True, rank0_only=True) + + if self.rank == 0: + hf_local_path = os.path.join(local_path, "huggingface") + os.makedirs(hf_local_path, exist_ok=True) + + if "ForTokenClassification" in model_config.architectures[0]: + from transformers import AutoModelForTokenClassification + + auto_model_cls = AutoModelForTokenClassification + elif "ForCausalLM" in model_config.architectures[0]: + from transformers import AutoModelForCausalLM + + auto_model_cls = AutoModelForCausalLM + elif "ForConditionalGeneration" in model_config.architectures[0]: + # Handle different transformers versions for Vision2Seq models + import transformers + from packaging import version + + if version.parse(transformers.__version__) >= version.parse("4.54.0"): + # transformers >= 4.54.0 uses AutoModelForImageTextToText + from transformers import AutoModelForImageTextToText + + auto_model_cls = AutoModelForImageTextToText + else: + # transformers < 4.54.0 uses AutoModelForVision2Seq + from transformers import AutoModelForVision2Seq + + auto_model_cls = AutoModelForVision2Seq + else: + raise NotImplementedError(f"Unknown architecture {model_config['architectures']}") + + with init_empty_weights(): + save_model = auto_model_cls.from_config(model_config, torch_dtype=torch.bfloat16) + save_model.to_empty(device="cpu") + + if save_model.can_generate(): + if generation_config is not None: + save_model.generation_config = generation_config + else: + print( + f"Warning: {self.__class__.__name__}.save_checkpoint: Generation config file not found " + f"in, using a generation config created from the model config when saving hf_model." + ) + + save_model.save_pretrained(hf_local_path, state_dict=state_dict) + log_with_rank( + f"Saved hf_model to {os.path.abspath(hf_local_path)}", + rank=self.rank, + logger=logger, + log_only_rank_0=True, + ) + del state_dict + del save_model + + # wait for rank0 to dump hf_model to local + torch.distributed.barrier() + + self.previous_saved_paths.append(local_path) diff --git a/verl/verl/utils/checkpoint/megatron_checkpoint_manager.py b/verl/verl/utils/checkpoint/megatron_checkpoint_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..b91ef6070b99c4423c51bf3f9569ed7fb8149ae4 --- /dev/null +++ b/verl/verl/utils/checkpoint/megatron_checkpoint_manager.py @@ -0,0 +1,557 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import logging +import os +import random +from collections.abc import Callable +from dataclasses import asdict + +import numpy as np +import torch +import torch.distributed +from megatron.core import mpu, tensor_parallel +from megatron.core.dist_checkpointing.mapping import ShardedObject +from megatron.core.transformer.enums import AttnBackend +from transformers import GenerationConfig + +from verl.models.weight_loader_registry import get_weight_saver +from verl.utils.device import get_device_name, get_torch_device +from verl.utils.fs import is_non_local, local_mkdir_safe +from verl.utils.logger import log_with_rank +from verl.utils.megatron.dist_checkpointing import load_dist_checkpointing, save_dist_checkpointing +from verl.utils.megatron_utils import ( + get_dist_checkpoint_path, + get_hf_model_checkpoint_path, + get_transformer_config_checkpoint_path, +) + +from .checkpoint_manager import BaseCheckpointManager + +# Setup logging +logger = logging.getLogger(__file__) +logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO")) + + +class MegatronCheckpointManager(BaseCheckpointManager): + """ + Checkpoint manager for Megatron-LM distributed training. + + This class manages the saving and loading of model checkpoints in a Megatron-LM + distributed training environment. It handles various aspects of checkpointing + including model states, optimizer states, learning rate schedulers, and random + number generator states, ensuring compatibility with HuggingFace formats. + + Key features: + - Distributed checkpoint saving and loading using Megatron's dist_checkpointing + - Support for tensor parallel, pipeline parallel, and data parallel configurations + - Automatic handling of model state dictionaries across multiple pipeline stages + - Integration with HuggingFace model configurations and tokenizers + - Random number generator state management for reproducibility + - Support for both synchronous and asynchronous checkpoint operations + + The manager automatically handles: + - Directory structure creation based on global steps and process ranks + - Model configuration and tokenizer saving in HuggingFace format + - Optimizer and scheduler state persistence + - CUDA RNG state management for deterministic training + - Checkpoint cleanup and retention policies + + Args: + model: The Megatron model instance to checkpoint + optimizer: The optimizer instance (optional) + lr_scheduler: The learning rate scheduler instance (optional) + + Attributes: + model: Reference to the Megatron model being checkpointed + optimizer: Reference to the optimizer (if provided) + lr_scheduler: Reference to the learning rate scheduler (if provided) + rank: Current process rank in the distributed setup + + Example: + ```python + checkpoint_manager = MegatronCheckpointManager( + model=megatron_model, + optimizer=optimizer, + lr_scheduler=scheduler + ) + + checkpoint_manager.save_checkpoint( + local_path="checkpoints/step_1000", + global_step=1000 + ) + + checkpoint_manager.load_checkpoint( + local_path="checkpoints/step_1000" + ) + ``` + """ + + def __init__( + self, + config, + checkpoint_config, + model_config, + transformer_config, + role, + model: torch.nn.ModuleList, + arch: str, + hf_config, + param_dtype: torch.dtype, + share_embeddings_and_output_weights: bool, + processing_class, + optimizer, + optimizer_scheduler, + use_distributed_optimizer: bool, + use_checkpoint_opt_param_scheduler: bool = False, + use_dist_checkpointing: bool = True, + bridge=None, + **kwargs, + ): + super().__init__( + model, + optimizer=optimizer, + lr_scheduler=optimizer_scheduler, + processing_class=processing_class, + checkpoint_config=checkpoint_config, + ) + self.arch = arch + self.config = config + self.transformer_config = transformer_config + self.role = role + self.is_value_model = False + if self.role in ["reward", "critic"]: + self.is_value_model = True + self.model_config = model_config + self.hf_config = hf_config + self.param_dtype = param_dtype + self.share_embeddings_and_output_weights = share_embeddings_and_output_weights + self.model_path = self.config.model.path + self.use_distributed_optimizer = use_distributed_optimizer + self.use_checkpoint_opt_param_scheduler = use_checkpoint_opt_param_scheduler + self.bridge = bridge + self.rank = torch.distributed.get_rank() + self.use_dist_checkpointing = use_dist_checkpointing or not self.bridge or self.is_value_model + self.use_hf_checkpoint = not self.use_dist_checkpointing + + self.weight_saver = None + if self.bridge is None: + self.weight_saver = get_weight_saver(self.arch) + + def get_rng_state(self, use_dist_ckpt: bool = True, data_parallel_random_init: bool = False): + """collect rng state across data parallel ranks""" + rng_state = { + "random_rng_state": random.getstate(), + "np_rng_state": np.random.get_state(), + "torch_rng_state": torch.get_rng_state(), + "rng_tracker_states": tensor_parallel.get_cuda_rng_tracker().get_states(), + } + + if get_device_name() != "cpu": + rng_state[f"{get_device_name()}_rng_state"] = get_torch_device().get_rng_state() + + rng_state_list = None + if torch.distributed.is_initialized() and mpu.get_data_parallel_world_size() > 1 and data_parallel_random_init: + rng_state_list = [None for i in range(mpu.get_data_parallel_world_size())] + torch.distributed.all_gather_object(rng_state_list, rng_state, group=mpu.get_data_parallel_group()) + else: + rng_state_list = [rng_state] + + if use_dist_ckpt: + pp_rank = mpu.get_pipeline_model_parallel_rank() + pp_size = mpu.get_pipeline_model_parallel_world_size() + tp_rank = mpu.get_tensor_model_parallel_rank() + tp_size = mpu.get_tensor_model_parallel_world_size() + rng_state_list = ShardedObject( + "rng_state", + rng_state_list, + (pp_size, tp_size), + (pp_rank, tp_rank), + replica_id=mpu.get_data_parallel_rank(with_context_parallel=True), + ) + + return rng_state_list + + def get_checkpoint_name( + self, + checkpoints_path, + pipeline_parallel=None, + tensor_rank=None, + pipeline_rank=None, + cp_rank=None, + expert_parallel=None, + expert_rank=None, + return_base_dir=True, + basename="model.pt", + ): + """Determine the directory name for this rank's checkpoint.""" + # Use both the tensor and pipeline MP rank. + if pipeline_parallel is None: + pipeline_parallel = mpu.get_pipeline_model_parallel_world_size() > 1 + if tensor_rank is None: + tensor_rank = mpu.get_tensor_model_parallel_rank() + if pipeline_rank is None: + pipeline_rank = mpu.get_pipeline_model_parallel_rank() + if cp_rank is None: + cp_rank = mpu.get_context_parallel_rank() + if expert_parallel is None: + expert_parallel = mpu.get_expert_model_parallel_world_size() > 1 + if expert_rank is None: + expert_rank = mpu.get_expert_model_parallel_rank() + + # Use both the tensor and pipeline MP rank. If using the distributed + # optimizer, then the optimizer's path must additionally include the + # data parallel rank. + + # due to the fact that models are identical across cp ranks, cp rank is not used in the checkpoint path + if not pipeline_parallel: + common_path = os.path.join(checkpoints_path, f"mp_rank_{tensor_rank:02d}") + else: + common_path = os.path.join(checkpoints_path, f"mp_rank_{tensor_rank:02d}_{pipeline_rank:03d}") + + if expert_parallel: + common_path = common_path + f"_{expert_rank:03d}" + + os.makedirs(common_path, exist_ok=True) + + if return_base_dir: + return common_path + return os.path.join(common_path, basename) + + def generate_state_dict( + self, generate_model: bool = True, generate_optimizer: bool = True, generate_extra: bool = True + ): + # For save dist checkpointing + state_dict = {} + + # Should always generate model state dict + # All ranks Save Model to reduce memory pressure + # Get sharded state dict, notice that state_dict will collect among dp groups, causing memory pressure + for vpp_rank, model in enumerate(self.model): + if len(self.model) > 1: + mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank) + key = f"model{vpp_rank}" if len(self.model) > 1 else "model" + else: + key = "model" + if hasattr(model, "module"): + model = model.module + state_dict[key] = model.sharded_state_dict() + + # Optimizer State Dict + if generate_optimizer: + torch.distributed.barrier() + optimizer_sharded_states = self.optimizer.sharded_state_dict(state_dict) + state_dict["optimizer"] = optimizer_sharded_states + + if self.lr_scheduler is not None: + lr_state_dict = self.lr_scheduler.state_dict() + state_dict["lr_scheduler"] = lr_state_dict + + if not generate_model: + state_dict.pop("model", None) + + # RNG States State Dict + if generate_extra: + torch.distributed.barrier() + rng_state = self.get_rng_state() + state_dict["rng_state"] = rng_state + + return state_dict + + def load_rng_states(self, rng_states, data_parallel_random_init=False, use_dist_ckpt=True): + # access rng_state for data parallel rank + if data_parallel_random_init: + rng_states = rng_states[mpu.get_data_parallel_rank()] + else: + rng_states = rng_states[0] + random.setstate(rng_states["random_rng_state"]) + np.random.set_state(rng_states["np_rng_state"]) + torch.set_rng_state(rng_states["torch_rng_state"]) + + if get_device_name() != "cpu": + get_torch_device().set_rng_state(rng_states[f"{get_device_name()}_rng_state"]) + + # Check for empty states array + if not rng_states["rng_tracker_states"]: + raise KeyError + tensor_parallel.get_cuda_rng_tracker().set_states(rng_states["rng_tracker_states"]) + + def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load=False): + if local_path is not None: + assert os.path.exists(local_path), f"Checkpoint path {local_path} does not exist." + + dist_checkpoint_path = get_dist_checkpoint_path(local_path) + + # Get State Dict for loading + sharded_state_dict = self.generate_state_dict( + self.should_load_model and self.use_dist_checkpointing, self.should_load_optimizer, self.should_load_extra + ) + log_with_rank(f"Generated state dict for loading: {sharded_state_dict.keys()}", rank=self.rank, logger=logger) + + # Load Dist Checkpointing + state_dict = load_dist_checkpointing( + sharded_state_dict=sharded_state_dict, + ckpt_dir=dist_checkpoint_path, + ) + + if self.should_load_model and self.use_dist_checkpointing: + assert "model" in state_dict or any( + f"model{vpp_rank}" in state_dict for vpp_rank in range(len(self.model)) + ), f"Model state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}." + for vpp_rank, model in enumerate(self.model): + if len(self.model) == 1: + model_state_dict = state_dict["model"] + else: + assert f"model{vpp_rank}" in state_dict, f"model{vpp_rank} not found in state_dict" + model_state_dict = state_dict[f"model{vpp_rank}"] + mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank) + self.model[vpp_rank].load_state_dict(model_state_dict) + log_with_rank(f"Loaded sharded model checkpoint from {local_path}", rank=self.rank, logger=logger) + elif self.should_load_model and self.use_hf_checkpoint: + hf_model_path = get_hf_model_checkpoint_path(local_path) + self.bridge.load_weights(self.model, hf_model_path) + log_with_rank(f"Loaded HF model checkpoint from {hf_model_path} with bridge", rank=self.rank, logger=logger) + + if self.should_load_optimizer: + assert "optimizer" in state_dict, ( + f"Optimizer state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}." + ) + optimizer_state_dict = state_dict["optimizer"] + self.optimizer.load_state_dict(optimizer_state_dict) + log_with_rank(f"Loaded optimizer checkpoint from {local_path}", rank=self.rank, logger=logger) + if self.use_checkpoint_opt_param_scheduler: + assert "lr_scheduler" in state_dict, ( + f"LR scheduler state dict not found in {state_dict.keys()}. Please check the checkpoint file " + f"{local_path}." + ) + lr_scheduler_state_dict = state_dict["lr_scheduler"] + if self.lr_scheduler is not None: + self.lr_scheduler.load_state_dict(lr_scheduler_state_dict) + log_with_rank(f"Loaded LR scheduler checkpoint from {local_path}", rank=self.rank, logger=logger) + + if self.should_load_extra: + assert "rng_state" in state_dict, ( + f"RNG state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}." + ) + rng_state = state_dict["rng_state"] + self.load_rng_states(rng_state) + log_with_rank(f"Loaded RNG states from {local_path}", rank=self.rank, logger=logger) + + if del_local_after_load: + try: + os.remove(local_path) if is_non_local(local_path) else None + except Exception as e: + log_with_rank( + f"remove local resume ckpt file after loading failed, exception {e} will be ignored", + rank=self.rank, + logger=logger, + ) + + def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep=None): + # record the previous global step + self.previous_global_step = global_step + + # remove previous local_path + if ( + max_ckpt_to_keep + and isinstance(max_ckpt_to_keep, int) + and max_ckpt_to_keep > 0 + and len(self.previous_saved_paths) >= max_ckpt_to_keep + ): + keep_start = len(self.previous_saved_paths) - max_ckpt_to_keep + 1 + self.remove_previous_save_local_path(self.previous_saved_paths[:keep_start]) + self.previous_saved_paths = self.previous_saved_paths[keep_start:] + + local_path = local_mkdir_safe(local_path) + dist_checkpoint_path = get_dist_checkpoint_path(local_path) + + # Note that model weights, optimizer states, and extra states are generated + # together in a state dict, we save them in one time + if self.use_dist_checkpointing: + # Generate state dict for saving + state_dict = self.generate_state_dict( + self.should_save_model, self.should_save_optimizer, self.should_save_extra + ) + log_with_rank(f"Generated state dict for saving: {state_dict.keys()}", rank=self.rank, logger=logger) + for vpp_rank, model in enumerate(self.model): + if len(self.model) > 1: + model_i_keys = state_dict[f"model{vpp_rank}"].keys() + log_with_rank(f"Generated state dict for saving: {model_i_keys}", rank=self.rank, logger=logger) + else: + log_with_rank( + f"Generated state dict for saving: {state_dict['model'].keys()}", rank=self.rank, logger=logger + ) + # Start Async save if enabled + async_save_request = save_dist_checkpointing( + sharded_state_dict=state_dict, + ckpt_path=dist_checkpoint_path, + async_save=self.checkpoint_config.async_save, + ) + + # Synchronize all async save requests + if not self.checkpoint_config.async_save: + assert async_save_request is None, "Async save request should be None when not using async save." + torch.distributed.barrier() + else: + assert self.use_hf_checkpoint, "When not using distributed checkpointing, use_hf_checkpoint should be True." + # Generate optimizer and exra state dicts + state_dict = self.generate_state_dict( + generate_model=False, + generate_optimizer=self.should_save_optimizer, + generate_extra=self.should_save_extra, + ) + # Save optimizer and extra states to local path + # Start Async save if enabled + async_save_request = save_dist_checkpointing( + sharded_state_dict=state_dict, + ckpt_path=dist_checkpoint_path, + async_save=self.checkpoint_config.async_save, + ) + + # Synchronize all async save requests + if not self.checkpoint_config.async_save: + assert async_save_request is None, "Async save request should be None when not using async save." + torch.distributed.barrier() + + if self.should_save_model: + if self.use_hf_checkpoint: + # Use mbridge to save HF model checkpoint + log_with_rank(f"Saving HF model checkpoint to {local_path} with bridge", rank=self.rank, logger=logger) + hf_ckpt_path = get_hf_model_checkpoint_path(local_path) + self.bridge.save_weights(self.model, hf_ckpt_path) + log_with_rank(f"Saved bridge checkpoint to {hf_ckpt_path}", rank=self.rank, logger=logger) + + # Only rank 0 saves the hf config and tokenizer to huggingface path + # No matter whether we save hf model or not + if self.rank == 0: + # Save tokenizer + hf_config_tokenizer_path = get_hf_model_checkpoint_path(local_path) + if self.processing_class is not None: + self.processing_class.save_pretrained(hf_config_tokenizer_path) + # Save huggingface config + self.hf_config.save_pretrained(hf_config_tokenizer_path) + if hasattr(self.hf_config, "name_or_path") and self.hf_config.name_or_path: + try: + generation_config = GenerationConfig.from_pretrained(self.hf_config.name_or_path) + generation_config.save_pretrained(hf_config_tokenizer_path) + except Exception: + # if the generation config isn't available, we don't save it + pass + log_with_rank( + f"Saved Huggingface config and tokenizer to {hf_config_tokenizer_path}", + rank=self.rank, + logger=logger, + log_only_rank_0=True, + ) + + if self.should_save_extra: + if self.rank == 0: + # Save transformer config + print(self.transformer_config) + transformer_config_dict = asdict(self.transformer_config) + to_convert_types = {torch.dtype: str, AttnBackend: str} + ignore_types = [Callable] + pop_keys = [] + for key, value in transformer_config_dict.items(): + if type(value) in to_convert_types: + transformer_config_dict[key] = to_convert_types[type(value)](value) + if type(value) in ignore_types: + pop_keys.append(key) + if callable(value): + pop_keys.append(key) + for key in pop_keys: + transformer_config_dict.pop(key) + transformer_config_path = get_transformer_config_checkpoint_path(local_path) + with open(transformer_config_path, "w") as f: + json.dump(transformer_config_dict, f, indent=2) + + if self.should_save_hf_model and not self.use_hf_checkpoint: + # wait for everyone to dump to local + if self.bridge is not None: + hf_model_ckpt_path = get_hf_model_checkpoint_path(local_path) + self.bridge.save_weights(self.model, hf_model_ckpt_path) + else: + state_dict = self.weight_saver( + self.model, + self.hf_config, + dtype=self.param_dtype, + is_value_model=self.is_value_model, + tie_word_embeddings=self.share_embeddings_and_output_weights, + ) + + torch.distributed.barrier() + if self.rank == 0: + hf_model_ckpt_path = get_hf_model_checkpoint_path(local_path) + import warnings + + from accelerate import init_empty_weights + + with init_empty_weights(), warnings.catch_warnings(): + warnings.simplefilter("ignore") + if "mistral7b-rm" in self.config.model.path: + from transformers import MistralForSequenceClassification + + model = MistralForSequenceClassification.from_pretrained( + self.config.model.path + ) # use score head instead of lm_head + state_dict["score.weight"] = state_dict["score.weight"] + else: + from transformers import AutoModelForCausalLM + + model = AutoModelForCausalLM.from_pretrained(self.config.model.path, torch_dtype="auto") + model.save_pretrained(hf_model_ckpt_path, state_dict=state_dict) + log_with_rank( + f"Saved Huggingface config and tokenizer to {hf_model_ckpt_path}", + rank=self.rank, + logger=logger, + log_only_rank_0=True, + ) + + if hdfs_path is not None: + log_with_rank( + f"Uploading checkpoint to {hdfs_path}", rank=self.rank, logger=logger, log_only_rank_0=True + ) + from verl.utils import hdfs_io + + hdfs_io.makedirs(hdfs_path, exist_ok=True) + hdfs_io.copy(src=hf_model_ckpt_path, dst=hdfs_path, dirs_exist_ok=True) + log_with_rank( + f"HDFS checkpoint uploaded to {hdfs_path}", + rank=self.rank, + logger=logger, + log_only_rank_0=True, + ) + + def finalize_save_fn(): + # Rank 0 uploads checkpoint to HDFS if hdfs_path is provided + log_with_rank( + f"Dist checkpointing save completed for {dist_checkpoint_path}", rank=self.rank, logger=logger + ) + if self.rank == 0: + if hdfs_path is not None: + log_with_rank(f"Uploading checkpoint to {hdfs_path}", rank=self.rank, logger=logger) + from verl.utils import hdfs_io + + hdfs_io.makedirs(hdfs_path, exist_ok=True) + hdfs_io.copy(src=dist_checkpoint_path, dst=hdfs_path, dirs_exist_ok=True) + hdfs_io.copy(src=hf_config_tokenizer_path, dst=hdfs_path, dirs_exist_ok=True) + + if self.checkpoint_config.async_save: + assert async_save_request is not None, "Async save request should not be None when using async save." + async_save_request.add_finalize_fn(finalize_save_fn) + else: + finalize_save_fn() + + self.previous_saved_paths.append(local_path) diff --git a/verl/verl/utils/dataset/README.md b/verl/verl/utils/dataset/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f886a70aabf443fb167453d667529b62f3311765 --- /dev/null +++ b/verl/verl/utils/dataset/README.md @@ -0,0 +1,16 @@ +# Dataset Format +## RLHF dataset +We combine all the data sources into a single parquet files. We directly organize the prompt into the chat format so that multi-turn chats can be easily incorporated. In the prompt, we may add instruction following texts to guide the model output the answers in a particular format so that we can extract the answers. + +Math problems +```json +{ + "data_source": "openai/gsm8k", + "prompt": [{"role": "user", "content": "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May? Let's think step by step and output the final answer after \"####\""}], + "ability": "math", + "reward_model": { + "style": "rule", + "ground_truth": ["72"] + }, +} +``` diff --git a/verl/verl/utils/dataset/__init__.py b/verl/verl/utils/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6032d68c86423f0e6c57afba684dff5e1b8362c0 --- /dev/null +++ b/verl/verl/utils/dataset/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .rl_dataset import RLHFDataset +from .rm_dataset import RMDataset +from .sft_dataset import SFTDataset + +__all__ = ["RLHFDataset", "RMDataset", "SFTDataset"] diff --git a/verl/verl/utils/dataset/dataset_utils.py b/verl/verl/utils/dataset/dataset_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7354a0c896d3910d2539b1453a372a0ad1b0dad7 --- /dev/null +++ b/verl/verl/utils/dataset/dataset_utils.py @@ -0,0 +1,70 @@ +# Copyright 2025 Bytedance Ltd. and/or its affiliates + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from enum import Enum + +import torch + + +class DatasetPadMode(str, Enum): + """Padding mode for dataset""" + + RIGHT = "right" + LEFT_RIGHT = "left_right" + NO_PADDING = "no_padding" + + +class SFTTensorCollator: + """ + A custom collate_fn that handles batching of sequences. + 1. for variable-length sequences, convert them into NestedTensors. + 2. for fixed-length sequences, use default_collate. + """ + + def __init__(self, pad_mode: DatasetPadMode = DatasetPadMode.LEFT_RIGHT): + self.pad_mode = pad_mode + + def __call__(self, batch: list[dict[str, any]]) -> dict[str, any]: + if self.pad_mode == DatasetPadMode.NO_PADDING: + return self.collate_variable_batch(batch) + elif self.pad_mode in [DatasetPadMode.RIGHT, DatasetPadMode.LEFT_RIGHT]: + from torch.utils.data import default_collate + + return default_collate(batch) + else: + raise NotImplementedError(f"pad_mode {self.pad_mode} not implemented") + + def collate_variable_batch(self, batch: list[dict[str, any]]) -> dict[str, any]: + """ + Collates a list of samples into a single batch. + + Args: + batch: A list of dictionary samples from the dataset. + + Returns: + A dictionary representing the batched data, with variable-length + sequences converted to NestedTensors. + """ + + final_batch = {} + + tensor_keys = [key for key in batch[0].keys() if isinstance(batch[0][key], torch.Tensor)] + + # Handle tensor values by creating a NestedTensor. + for key in tensor_keys: + tensors = [item[key] for item in batch] + final_batch[key] = torch.nested.as_nested_tensor(tensors, layout=torch.jagged) + + return final_batch diff --git a/verl/verl/utils/dataset/multiturn_sft_dataset.py b/verl/verl/utils/dataset/multiturn_sft_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..e669e292bd247ed21a2918ffa42758cf0526a0f6 --- /dev/null +++ b/verl/verl/utils/dataset/multiturn_sft_dataset.py @@ -0,0 +1,442 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# Copyright 2025 ModelBest Inc. and/or its affiliates + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Multi-turn SFT dataset that supports training on conversation data with multiple turns +""" + +import logging +from typing import Any, Optional + +import numpy as np +import pandas as pd +import torch +from omegaconf import ListConfig +from torch.utils.data import Dataset +from transformers import PreTrainedTokenizer + +from verl.utils import hf_tokenizer +from verl.utils.dataset.dataset_utils import DatasetPadMode +from verl.utils.fs import copy_local_path_from_hdfs +from verl.utils.model import compute_position_id_with_mask +from verl.utils.torch_functional import pad_sequence_to_length, postprocess_data + + +def convert_nested_value_to_list_recursive(data_item): + if isinstance(data_item, dict): + return {k: convert_nested_value_to_list_recursive(v) for k, v in data_item.items()} + elif isinstance(data_item, list): + return [convert_nested_value_to_list_recursive(elem) for elem in data_item] + elif isinstance(data_item, np.ndarray): + # Convert to list, then recursively process the elements of the new list + return convert_nested_value_to_list_recursive(data_item.tolist()) + else: + # Base case: item is already a primitive type (int, str, float, bool, etc.) + return data_item + + +class MultiTurnSFTDataset(Dataset): + """ + Dataset for multi-turn conversations where each assistant response should be trained + """ + + def __init__(self, parquet_files: str | list[str], tokenizer, config=None): + # Set defaults and extract parameters from config if provided + config = config or {} + self.pad_mode = config.get("pad_mode", "right") + assert self.pad_mode in ["right", "left_right", "no_padding"], ( + f"Expect pad_mode to be 'right', 'left_right' or 'no_padding'. Got {self.pad_mode}" + ) + self.truncation = config.get("truncation", "error") + # for right padding + self.max_length = config.get("max_length", 1024) + # for left right paddding to be consistent with RL + self.max_prompt_length = config.get("max_prompt_length", 512) + self.max_response_length = config.get("max_response_length", 512) + # Get messages_key from the new multiturn config structure + multiturn_config = config.get("multiturn", {}) + self.messages_key = multiturn_config.get("messages_key", "messages") + self.tools_key = multiturn_config.get("tools_key", "tools") + self.enable_thinking_key = multiturn_config.get("enable_thinking_key", "enable_thinking") + self.apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", {}) + assert self.truncation in ["error", "left", "right"] + + if not isinstance(parquet_files, list | ListConfig): + parquet_files = [parquet_files] + + self.parquet_files = parquet_files + if isinstance(tokenizer, str): + tokenizer = hf_tokenizer(tokenizer) + self.tokenizer: PreTrainedTokenizer = tokenizer + + self._download() + self._read_files_and_process() + + def _download(self): + for i, parquet_file in enumerate(self.parquet_files): + self.parquet_files[i] = copy_local_path_from_hdfs(parquet_file, verbose=True) + + def _read_files_and_process(self): + def series_to_item(ls): + import numpy + import pandas + + while isinstance(ls, pandas.core.series.Series | numpy.ndarray) and len(ls) == 1: + ls = ls[0] + return ls + + dataframes = [] + for parquet_file in self.parquet_files: + dataframe = pd.read_parquet(parquet_file) + dataframes.append(dataframe) + self.dataframe = pd.concat(dataframes) + + # Extract messages list from dataframe + self.messages = self.dataframe[self.messages_key].apply(series_to_item).tolist() + + # Extract tools list from dataframe + if self.tools_key in self.dataframe.columns: + self.tools = self.dataframe[self.tools_key].apply(convert_nested_value_to_list_recursive).tolist() + else: + self.tools = None + # Extract enable_thinking list from dataframe + if self.enable_thinking_key in self.dataframe.columns: + self.enable_thinking = self.dataframe[self.enable_thinking_key].tolist() + else: + self.enable_thinking = None + + def __len__(self): + return len(self.messages) + + def _process_message_tokens( + self, + messages: list[dict[str, Any]], + start_idx: int, + end_idx: int, + is_assistant: bool = False, + enable_thinking: Optional[bool] = None, + tools: Optional[list[dict[str, Any]]] = None, + ) -> tuple[list[int], list[int], list[int]]: + """ + Process tokens for a single message or a group of messages. + + Args: + messages: List of message dictionaries + start_idx: Start index in messages list + end_idx: End index in messages list + is_assistant: Whether this is an assistant message + enable_thinking: Whether to enable thinking mode + + Returns: + Tuple of (tokens, loss_mask, attention_mask) + """ + if start_idx > 0: + prev_applied_text = self.tokenizer.apply_chat_template( + messages[:start_idx], + tokenize=False, + add_generation_prompt=False, + enable_thinking=enable_thinking, + tools=tools, + **self.apply_chat_template_kwargs, + ) + if is_assistant: + prev_applied_text_w_generation_prompt = self.tokenizer.apply_chat_template( + messages[:start_idx], + tokenize=False, + add_generation_prompt=True, + enable_thinking=enable_thinking, + tools=tools, + **self.apply_chat_template_kwargs, + ) + + else: + prev_applied_text = "" + + cur_applied_text = self.tokenizer.apply_chat_template( + messages[:end_idx], + tokenize=False, + add_generation_prompt=False, + enable_thinking=enable_thinking, + tools=tools, + **self.apply_chat_template_kwargs, + ) + # Get tokens for the current message only + if is_assistant: + generation_prompt_text = prev_applied_text_w_generation_prompt[len(prev_applied_text) :] + generation_prompt_tokens = self.tokenizer.encode( + generation_prompt_text, + add_special_tokens=False, + ) + _message_tokens = self.tokenizer.encode( + cur_applied_text[len(prev_applied_text_w_generation_prompt) :], + add_special_tokens=False, + ) + message_tokens = generation_prompt_tokens + _message_tokens + loss_mask = [0] * (len(generation_prompt_tokens)) + [1] * ( + len(message_tokens) - len(generation_prompt_tokens) + ) + else: + message_tokens = self.tokenizer.encode( + cur_applied_text[len(prev_applied_text) :], + add_special_tokens=False, + ) + loss_mask = [0] * len(message_tokens) + + attention_mask = [1] * len(message_tokens) + + return message_tokens, loss_mask, attention_mask + + def _validate_and_convert_tokens( + self, + full_tokens: torch.Tensor, + concat_tokens: list[int], + concat_loss_mask: list[int], + concat_attention_mask: list[int], + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Validate tokenization and convert to tensors. + + Args: + full_tokens: Full conversation tokens + concat_tokens: Concatenated tokens + concat_loss_mask: Concatenated loss mask + concat_attention_mask: Concatenated attention mask + + Returns: + Tuple of (input_ids, loss_mask, attention_mask) as tensors + """ + full_tokens_list = full_tokens.tolist() + + if len(concat_tokens) != len(full_tokens_list) or not all( + a == b for a, b in zip(concat_tokens, full_tokens_list, strict=True) + ): + logging.warning( + f"Token mismatch detected! Full tokenization length: {len(full_tokens_list)}, Concatenated tokens " + f"length: {len(concat_tokens)}. Using concatenated version." + # f"full tokens text: {self.tokenizer.decode(full_tokens_list)}" + # f"concat tokens text: {self.tokenizer.decode(concat_tokens)}" + ) + return ( + torch.tensor(concat_tokens, dtype=torch.long), + torch.tensor(concat_loss_mask, dtype=torch.long), + torch.tensor(concat_attention_mask, dtype=torch.long), + ) + + return ( + full_tokens, + torch.tensor(concat_loss_mask, dtype=torch.long), + torch.tensor(concat_attention_mask, dtype=torch.long), + ) + + def __getitem__(self, item): + tokenizer = self.tokenizer + messages = self.messages[item] + tools = self.tools[item] if self.tools is not None else None + enable_thinking = self.enable_thinking[item] if self.enable_thinking is not None else None + + # First, get the full conversation tokens + try: + full_tokens = tokenizer.apply_chat_template( + messages, + tools=tools, + tokenize=True, + return_tensors="pt", + add_generation_prompt=False, + enable_thinking=enable_thinking, + **self.apply_chat_template_kwargs, + ) + except Exception as e: + logging.error( + f"Error applying chat template: {e}\nMessages: {messages}\nTools: {tools}\nEnable thinking: " + f"{enable_thinking}" + ) + raise + + # Track concatenated tokens for validation + concat_tokens = [] + concat_loss_mask = [] + concat_attention_mask = [] + + i = 0 + while i < len(messages): + cur_messages = messages[i] + if cur_messages["role"] == "assistant": + # Process assistant message + tokens, loss_mask, attention_mask = self._process_message_tokens( + messages, i, i + 1, is_assistant=True, enable_thinking=enable_thinking, tools=tools + ) + i += 1 + elif cur_messages["role"] == "tool": + # Process consecutive tool messages + st = i + ed = i + 1 + while ed < len(messages) and messages[ed]["role"] == "tool": + ed += 1 + tokens, loss_mask, attention_mask = self._process_message_tokens( + messages, st, ed, enable_thinking=enable_thinking, tools=tools + ) + i = ed + elif cur_messages["role"] in ["user", "system"]: + # Process user or system message + if cur_messages["role"] == "system" and i != 0: + raise ValueError("System message should be the first message") + tokens, loss_mask, attention_mask = self._process_message_tokens( + messages, i, i + 1, enable_thinking=enable_thinking, tools=tools + ) + i += 1 + else: + raise ValueError(f"Unknown role: {cur_messages['role']}") + + # override loss mask with mask in the dataset to handle multi-turn conversation + override_loss_mask = cur_messages.get("loss_mask", None) + if override_loss_mask is not None: + if isinstance(override_loss_mask, np.ndarray): + override_loss_mask = override_loss_mask.item() + assert isinstance(override_loss_mask, int), f"loss_mask should be int, got {type(override_loss_mask)}" + assert override_loss_mask in [0, 1], f"loss_mask should be 0 or 1, got {override_loss_mask}" + loss_mask = [override_loss_mask] * len(tokens) + + concat_tokens.extend(tokens) + concat_loss_mask.extend(loss_mask) + concat_attention_mask.extend(attention_mask) + + # Validate and convert tokens + input_ids, loss_mask, attention_mask = self._validate_and_convert_tokens( + full_tokens[0], concat_tokens, concat_loss_mask, concat_attention_mask + ) + + # encode prompt + if messages[0]["role"] == "system": + assert messages[1]["role"] == "user" + assert messages[2]["role"] == "assistant" + prompt_message_length = 2 + elif messages[0]["role"] == "user": + assert messages[1]["role"] == "assistant" + prompt_message_length = 1 + else: + raise ValueError(f"Unknown role: {messages[0]['role']}") + + sequence_length = input_ids.shape[0] + # Handle sequence length + if self.pad_mode == DatasetPadMode.RIGHT: + if sequence_length < self.max_length: + # Pad sequences + pad_token_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else 0 + padded_input_ids = torch.full((self.max_length - sequence_length,), pad_token_id, dtype=input_ids.dtype) + padded_attention_mask = torch.zeros((self.max_length - sequence_length,), dtype=attention_mask.dtype) + padded_loss_mask = torch.zeros((self.max_length - sequence_length,), dtype=loss_mask.dtype) + + input_ids = torch.cat((input_ids, padded_input_ids)) + attention_mask = torch.cat((attention_mask, padded_attention_mask)) + loss_mask = torch.cat((loss_mask, padded_loss_mask)) + elif sequence_length > self.max_length: + if self.truncation == "left": + input_ids = input_ids[-self.max_length :] + attention_mask = attention_mask[-self.max_length :] + loss_mask = loss_mask[-self.max_length :] + elif self.truncation == "right": + input_ids = input_ids[: self.max_length] + attention_mask = attention_mask[: self.max_length] + loss_mask = loss_mask[: self.max_length] + elif self.truncation == "error": + raise ValueError(f"{sequence_length=} is larger than {self.max_length=}") + else: + raise ValueError(f"Unknown truncation method {self.truncation}") + + # Create position IDs + position_ids = torch.arange(len(input_ids), dtype=torch.long) + # Zero out position IDs for padding + position_ids = position_ids * attention_mask + + return { + "input_ids": input_ids, + "attention_mask": attention_mask, + "position_ids": position_ids, + "loss_mask": loss_mask, + } + elif self.pad_mode == DatasetPadMode.LEFT_RIGHT: + assert self.truncation == "error", "Only support error truncation for left_right pad mode" + prompt_str = self.tokenizer.apply_chat_template( + messages[:prompt_message_length], + tools=tools, + tokenize=False, + add_generation_prompt=True, + enable_thinking=enable_thinking, + **self.apply_chat_template_kwargs, + ) + prompt_ids = self.tokenizer.encode(prompt_str, add_special_tokens=False) + prompt_length = len(prompt_ids) + prompt_ids = input_ids[:prompt_length].unsqueeze(0) + prompt_attention_mask = attention_mask[:prompt_length].unsqueeze(0) + prompt_loss_mask = loss_mask[:prompt_length].unsqueeze(0) + response_ids = input_ids[prompt_length:].unsqueeze(0) + response_attention_mask = attention_mask[prompt_length:].unsqueeze(0) + response_loss_mask = loss_mask[prompt_length:].unsqueeze(0) + + assert prompt_loss_mask.sum().item() == 0 + + prompt_ids, prompt_attention_mask = postprocess_data( + input_ids=prompt_ids, + attention_mask=prompt_attention_mask, + max_length=self.max_prompt_length, + pad_token_id=self.tokenizer.pad_token_id, + left_pad=True, + truncation=self.truncation, + ) + + response_ids, response_attention_mask = postprocess_data( + input_ids=response_ids, + attention_mask=response_attention_mask, + max_length=self.max_response_length, + pad_token_id=self.tokenizer.pad_token_id, + left_pad=False, + truncation=self.truncation, + ) + response_loss_mask = pad_sequence_to_length( + response_loss_mask, max_seq_len=self.max_response_length, pad_token_id=0, left_pad=False + ) + + prompt_ids = prompt_ids[0] + prompt_attention_mask = prompt_attention_mask[0] + response_ids = response_ids[0] + response_attention_mask = response_attention_mask[0] + response_loss_mask = response_loss_mask[0] + + assert response_attention_mask[0].item() == 1 + assert response_loss_mask[0].item() == 1 + + input_ids = torch.cat((prompt_ids, response_ids), dim=0) + attention_mask = torch.cat((prompt_attention_mask, response_attention_mask), dim=0) + position_ids = compute_position_id_with_mask(attention_mask) + + return { + "input_ids": input_ids, + "attention_mask": attention_mask, + "position_ids": position_ids, + "responses": response_ids, + "response_mask": response_loss_mask, + } + elif self.pad_mode == DatasetPadMode.NO_PADDING: + # truncate input_ids if it is longer than max_length + if len(input_ids) > self.max_length: + input_ids = input_ids[: self.max_length] + loss_mask = loss_mask[: self.max_length] + # create position IDs + position_ids = torch.arange(len(input_ids), dtype=torch.long) + # return nested tensor with out padding + return { + "input_ids": input_ids, + "position_ids": position_ids, + "loss_mask": loss_mask, + } diff --git a/verl/verl/utils/dataset/rl_dataset.py b/verl/verl/utils/dataset/rl_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..63d1a3f2735485710548604d030c35d7df9e167e --- /dev/null +++ b/verl/verl/utils/dataset/rl_dataset.py @@ -0,0 +1,383 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# Copyright 2023-2024 SGLang Team +# Copyright 2025 ModelBest Inc. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import logging +import os +import re +from collections import defaultdict +from typing import Optional + +import datasets +import numpy as np +import torch +from omegaconf import DictConfig, ListConfig +from torch.utils.data import Dataset +from transformers import PreTrainedTokenizer, ProcessorMixin + +import verl.utils.torch_functional as verl_F +from verl.utils.model import compute_position_id_with_mask + +logger = logging.getLogger(__name__) + + +def collate_fn(data_list: list[dict]) -> dict: + """ + Collate a batch of sample dicts into batched tensors and arrays. + + Args: + data_list: List of dicts mapping feature names to torch.Tensor or other values. + + Returns: + Dict where tensor entries are stacked into a torch.Tensor of shape + (batch_size, \*dims) and non-tensor entries are converted to + np.ndarray of dtype object with shape (batch_size,). + """ + tensors = defaultdict(list) + non_tensors = defaultdict(list) + + for data in data_list: + for key, val in data.items(): + if isinstance(val, torch.Tensor): + tensors[key].append(val) + else: + non_tensors[key].append(val) + + for key, val in tensors.items(): + tensors[key] = torch.stack(val, dim=0) + + for key, val in non_tensors.items(): + non_tensors[key] = np.fromiter(val, dtype=object, count=len(val)) + + return {**tensors, **non_tensors} + + +class RLHFDataset(Dataset): + """ + Load and preprocess RLHF data from Parquet files. + + - Caches files locally. + - Reads into a HuggingFace Dataset and tokenizes prompts. + - Optionally handles images/videos via a ProcessorMixin. + - Filters prompts over a max length. + - Supports resuming from checkpoints. + + Args: + data_files (str or list): Path(s) to Parquet file(s). + tokenizer (PreTrainedTokenizer): For the tokenization of text to token IDs. + config (DictConfig): Options like cache_dir, prompt_key, max_prompt_length, truncation, etc. + processor (ProcessorMixin, optional): Multimodal preprocessor for images/videos. + """ + + def __init__( + self, + data_files: str | list[str], + tokenizer: PreTrainedTokenizer, + config: DictConfig, + processor: Optional[ProcessorMixin] = None, + ): + if not isinstance(data_files, list | ListConfig): + data_files = [data_files] + + self.data_files = copy.deepcopy(data_files) + self.original_data_files = copy.deepcopy(data_files) # use for resume + self.tokenizer = tokenizer + self.processor = processor + self.config = config + + self.cache_dir = os.path.expanduser(config.get("cache_dir", "~/.cache/verl/rlhf")) + self.prompt_key = config.get("prompt_key", "prompt") + self.image_key = config.get("image_key", "images") + self.video_key = config.get("video_key", "videos") + self.max_prompt_length = config.get("max_prompt_length", 1024) + self.return_raw_chat = config.get("return_raw_chat", False) + self.return_full_prompt = config.get("return_full_prompt", False) + self.truncation = config.get("truncation", "error") + self.filter_overlong_prompts = config.get("filter_overlong_prompts", True) + self.apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", {}) + + self.num_workers = config.get("filter_overlong_prompts_workers", max(1, os.cpu_count() // 4)) + self.num_workers = min(self.num_workers, os.cpu_count()) + self.use_shm = config.get("use_shm", False) + self.chat_template_func = config.get("chat_template_func", None) + self.need_tools_kwargs = config.get("need_tools_kwargs", False) + self.filter_prompts = config.get("filter_prompts", True) + self.serialize_dataset = False + self.return_multi_modal_inputs = config.get("return_multi_modal_inputs", True) + + self._download() + self._read_files_and_tokenize() + + def _download(self, use_origin_parquet=False): + from verl.utils.fs import copy_to_local + + data_files = self.data_files if not use_origin_parquet else self.original_data_files + for i, parquet_file in enumerate(data_files): + self.data_files[i] = copy_to_local(src=parquet_file, cache_dir=self.cache_dir, use_shm=self.use_shm) + + def _read_files_and_tokenize(self): + dataframes = [] + for parquet_file in self.data_files: + # read parquet files and cache + dataframe = datasets.load_dataset("parquet", data_files=parquet_file)["train"] + dataframes.append(dataframe) + self.dataframe: datasets.Dataset = datasets.concatenate_datasets(dataframes) + + print(f"dataset len: {len(self.dataframe)}") + + self.dataframe = self.maybe_filter_out_long_prompts(self.dataframe) + + def maybe_filter_out_long_prompts(self, dataframe: datasets.Dataset = None): + # filter out too long prompts + if self.filter_overlong_prompts: + tokenizer = self.tokenizer + processor = self.processor + prompt_key = self.prompt_key + image_key = self.image_key + video_key = self.video_key + + if processor is not None: + from verl.utils.dataset.vision_utils import process_image, process_video + + def doc2len(doc) -> int: + messages = self._build_messages(doc) + raw_prompt = self.processor.apply_chat_template( + messages, add_generation_prompt=True, tokenize=False, **self.apply_chat_template_kwargs + ) + images = ( + [process_image(image) for image in doc[image_key]] + if image_key in doc and doc[image_key] + else None + ) + videos = ( + [process_video(video) for video in doc[video_key]] + if video_key in doc and doc[video_key] + else None + ) + + return len(processor(text=[raw_prompt], images=images, videos=videos)["input_ids"][0]) + + else: + + def doc2len(doc) -> int: + return len( + tokenizer.apply_chat_template( + doc[prompt_key], add_generation_prompt=True, **self.apply_chat_template_kwargs + ) + ) + + dataframe = dataframe.filter( + lambda doc: doc2len(doc) <= self.max_prompt_length, + num_proc=self.num_workers, + desc=f"Filtering prompts longer than {self.max_prompt_length} tokens", + ) + + print(f"filter dataset len: {len(dataframe)}") + return dataframe + + def resume_dataset_state(self): + self.serialize_dataset = not hasattr(self, "original_data_files") + # resume dataframe if not it's serialized in data.pt + if not self.serialize_dataset: + self._download(use_origin_parquet=True) # download and resume from original parquet files + self._read_files_and_tokenize() + else: + print(r"old dataloader ckpt file is used, please train from scratch for better ckpt performance") + + def __len__(self): + return len(self.dataframe) + + def _build_messages(self, example: dict): + messages: list = example.pop(self.prompt_key) + + if self.image_key in example or self.video_key in example: + for message in messages: + content = message["content"] + content_list = [] + segments = re.split("(|