Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +4 -0
- verl/verl.egg-info/PKG-INFO +327 -0
- verl/verl.egg-info/SOURCES.txt +747 -0
- verl/verl.egg-info/dependency_links.txt +1 -0
- verl/verl.egg-info/requires.txt +54 -0
- verl/verl.egg-info/top_level.txt +3 -0
- verl/verl/utils/checkpoint/__init__.py +17 -0
- verl/verl/utils/checkpoint/checkpoint_handler.py +204 -0
- verl/verl/utils/checkpoint/checkpoint_manager.py +237 -0
- verl/verl/utils/checkpoint/fsdp_checkpoint_manager.py +367 -0
- verl/verl/utils/checkpoint/megatron_checkpoint_manager.py +557 -0
- verl/verl/utils/dataset/README.md +16 -0
- verl/verl/utils/dataset/__init__.py +19 -0
- verl/verl/utils/dataset/dataset_utils.py +70 -0
- verl/verl/utils/dataset/multiturn_sft_dataset.py +442 -0
- verl/verl/utils/dataset/rl_dataset.py +383 -0
- verl/verl/utils/dataset/rm_dataset.py +144 -0
- verl/verl/utils/dataset/sft_dataset.py +186 -0
- verl/verl/utils/dataset/vision_utils.py +117 -0
- verl/verl/utils/debug/__init__.py +17 -0
- verl/verl/utils/debug/metrics.py +109 -0
- verl/verl/utils/debug/performance.py +17 -0
- verl/verl/utils/debug/trajectory_tracker.py +109 -0
- verl/verl/utils/experimental/__init__.py +13 -0
- verl/verl/utils/experimental/torch_functional.py +216 -0
- verl/verl/utils/kernel/__init__.py +31 -0
- verl/verl/utils/kernel/kernels.py +1586 -0
- verl/verl/utils/kernel/linear_cross_entropy.py +119 -0
- verl/verl/utils/logger/__init__.py +32 -0
- verl/verl/utils/logger/aggregate_logger.py +140 -0
- verl/verl/utils/megatron/__init__.py +13 -0
- verl/verl/utils/megatron/dist_checkpointing.py +56 -0
- verl/verl/utils/megatron/memory.py +38 -0
- verl/verl/utils/megatron/optimizer.py +108 -0
- verl/verl/utils/megatron/pipeline_parallel.py +71 -0
- verl/verl/utils/megatron/sequence_parallel.py +52 -0
- verl/verl/utils/megatron/tensor_parallel.py +186 -0
- verl/verl/utils/metric/__init__.py +17 -0
- verl/verl/utils/metric/utils.py +54 -0
- verl/verl/utils/profiler/__init__.py +40 -0
- verl/verl/utils/profiler/config.py +156 -0
- verl/verl/utils/profiler/empty_annotations.py +40 -0
- verl/verl/utils/profiler/mstx_profile.py +271 -0
- verl/verl/utils/profiler/nvtx_profile.py +200 -0
- verl/verl/utils/profiler/performance.py +240 -0
- verl/verl/utils/profiler/profile.py +371 -0
- verl/verl/utils/rendezvous/__init__.py +13 -0
- verl/verl/utils/rendezvous/ray_backend.py +73 -0
- verl/verl/utils/reward_score/__init__.py +134 -0
- verl/verl/utils/reward_score/geo3k.py +36 -0
.gitattributes
CHANGED
|
@@ -397,3 +397,7 @@ saves/qwen7B_it_fromit_326_think_sudoku_sequence_multitask/global_step_200/qwen2
|
|
| 397 |
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
|
| 398 |
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
|
| 399 |
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
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
|
| 398 |
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
|
| 399 |
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
|
| 400 |
+
wandb/latest-run/run-1fkf5bo1.wandb filter=lfs diff=lfs merge=lfs -text
|
| 401 |
+
wandb/offline-run-20251216_100052-vp4li00f/run-vp4li00f.wandb filter=lfs diff=lfs merge=lfs -text
|
| 402 |
+
wandb/offline-run-20251216_142423-iypt06ne/run-iypt06ne.wandb filter=lfs diff=lfs merge=lfs -text
|
| 403 |
+
wandb/offline-run-20251216_185932-u0k07wxi/run-u0k07wxi.wandb filter=lfs diff=lfs merge=lfs -text
|
verl/verl.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: verl
|
| 3 |
+
Version: 0.5.0.dev0
|
| 4 |
+
Summary: verl: Volcano Engine Reinforcement Learning for LLM
|
| 5 |
+
Home-page: https://github.com/volcengine/verl
|
| 6 |
+
Author: Bytedance - Seed - MLSys
|
| 7 |
+
Author-email: zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk
|
| 8 |
+
License: Apache-2.0
|
| 9 |
+
Requires-Python: >=3.10
|
| 10 |
+
Description-Content-Type: text/markdown
|
| 11 |
+
License-File: LICENSE
|
| 12 |
+
Requires-Dist: accelerate
|
| 13 |
+
Requires-Dist: codetiming
|
| 14 |
+
Requires-Dist: datasets
|
| 15 |
+
Requires-Dist: dill
|
| 16 |
+
Requires-Dist: hydra-core
|
| 17 |
+
Requires-Dist: numpy<2.0.0
|
| 18 |
+
Requires-Dist: pandas
|
| 19 |
+
Requires-Dist: peft
|
| 20 |
+
Requires-Dist: pyarrow>=19.0.0
|
| 21 |
+
Requires-Dist: pybind11
|
| 22 |
+
Requires-Dist: pylatexenc
|
| 23 |
+
Requires-Dist: ray[default]>=2.41.0
|
| 24 |
+
Requires-Dist: torchdata
|
| 25 |
+
Requires-Dist: tensordict!=0.9.0,<=0.10.0,>=0.8.0
|
| 26 |
+
Requires-Dist: transformers
|
| 27 |
+
Requires-Dist: wandb
|
| 28 |
+
Requires-Dist: packaging>=20.0
|
| 29 |
+
Requires-Dist: tensorboard
|
| 30 |
+
Provides-Extra: test
|
| 31 |
+
Requires-Dist: pytest; extra == "test"
|
| 32 |
+
Requires-Dist: pre-commit; extra == "test"
|
| 33 |
+
Requires-Dist: py-spy; extra == "test"
|
| 34 |
+
Requires-Dist: pytest-asyncio; extra == "test"
|
| 35 |
+
Provides-Extra: prime
|
| 36 |
+
Requires-Dist: pyext; extra == "prime"
|
| 37 |
+
Provides-Extra: geo
|
| 38 |
+
Requires-Dist: mathruler; extra == "geo"
|
| 39 |
+
Requires-Dist: torchvision; extra == "geo"
|
| 40 |
+
Requires-Dist: qwen_vl_utils; extra == "geo"
|
| 41 |
+
Provides-Extra: gpu
|
| 42 |
+
Requires-Dist: liger-kernel; extra == "gpu"
|
| 43 |
+
Requires-Dist: flash-attn; extra == "gpu"
|
| 44 |
+
Provides-Extra: math
|
| 45 |
+
Requires-Dist: math-verify; extra == "math"
|
| 46 |
+
Provides-Extra: vllm
|
| 47 |
+
Requires-Dist: tensordict!=0.9.0,<=0.10.0,>=0.8.0; extra == "vllm"
|
| 48 |
+
Requires-Dist: vllm<=0.9.1,>=0.7.3; extra == "vllm"
|
| 49 |
+
Provides-Extra: sglang
|
| 50 |
+
Requires-Dist: tensordict!=0.9.0,<=0.10.0,>=0.8.0; extra == "sglang"
|
| 51 |
+
Requires-Dist: sglang[openai,srt]==0.5.2; extra == "sglang"
|
| 52 |
+
Requires-Dist: torch==2.8.0; extra == "sglang"
|
| 53 |
+
Provides-Extra: trl
|
| 54 |
+
Requires-Dist: trl<=0.9.6; extra == "trl"
|
| 55 |
+
Provides-Extra: mcore
|
| 56 |
+
Requires-Dist: mbridge; extra == "mcore"
|
| 57 |
+
Dynamic: author
|
| 58 |
+
Dynamic: author-email
|
| 59 |
+
Dynamic: home-page
|
| 60 |
+
Dynamic: license-file
|
| 61 |
+
Dynamic: provides-extra
|
| 62 |
+
Dynamic: requires-dist
|
| 63 |
+
|
| 64 |
+
<div align="center">
|
| 65 |
+
👋 Hi, everyone!
|
| 66 |
+
verl is a RL training library initiated by <b>ByteDance Seed team</b> and maintained by the verl community.
|
| 67 |
+
<br>
|
| 68 |
+
<br>
|
| 69 |
+
</div>
|
| 70 |
+
|
| 71 |
+
<div align="center">
|
| 72 |
+
|
| 73 |
+
<a href="https://deepwiki.com/volcengine/verl"><img src="https://devin.ai/assets/deepwiki-badge.png" alt="Ask DeepWiki.com" style="height:20px;"></a>
|
| 74 |
+
[](https://github.com/volcengine/verl/stargazers)
|
| 75 |
+
[](https://twitter.com/verl_project)
|
| 76 |
+
<a href="https://join.slack.com/t/verl-project/shared_invite/zt-3c6mc2khw-v0lo6NfDPuFP6OnkrZwfqw"><img src="https://img.shields.io/badge/Slack-verl-blueviolet?logo=slack&"></a>
|
| 77 |
+
<a href="https://arxiv.org/pdf/2409.19256"><img src="https://img.shields.io/static/v1?label=EuroSys&message=Paper&color=red"></a>
|
| 78 |
+
[](https://verl.readthedocs.io/en/latest/)
|
| 79 |
+
<a href="https://raw.githubusercontent.com/eric-haibin-lin/verl-community/refs/heads/main/WeChat.JPG"><img src="https://img.shields.io/badge/微信-green?logo=wechat&"></a>
|
| 80 |
+
|
| 81 |
+
</div>
|
| 82 |
+
|
| 83 |
+

|
| 84 |
+
|
| 85 |
+
<h1 style="text-align: center;">verl: Volcano Engine Reinforcement Learning for LLMs</h1>
|
| 86 |
+
|
| 87 |
+
verl is a flexible, efficient and production-ready RL training library for large language models (LLMs).
|
| 88 |
+
|
| 89 |
+
verl is the open-source version of **[HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2)** paper.
|
| 90 |
+
|
| 91 |
+
verl is flexible and easy to use with:
|
| 92 |
+
|
| 93 |
+
- **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.
|
| 94 |
+
|
| 95 |
+
- **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
|
| 96 |
+
|
| 97 |
+
- **Flexible device mapping**: Supports various placement of models onto different sets of GPUs for efficient resource utilization and scalability across different cluster sizes.
|
| 98 |
+
|
| 99 |
+
- Ready integration with popular HuggingFace models
|
| 100 |
+
|
| 101 |
+
verl is fast with:
|
| 102 |
+
|
| 103 |
+
- **State-of-the-art throughput**: SOTA LLM training and inference engine integrations and SOTA RL throughput.
|
| 104 |
+
|
| 105 |
+
- **Efficient actor model resharding with 3D-HybridEngine**: Eliminates memory redundancy and significantly reduces communication overhead during transitions between training and generation phases.
|
| 106 |
+
|
| 107 |
+
</p>
|
| 108 |
+
|
| 109 |
+
## News
|
| 110 |
+
- [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.
|
| 111 |
+
- [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)
|
| 112 |
+
- [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)
|
| 113 |
+
- [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).
|
| 114 |
+
- [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.
|
| 115 |
+
<details><summary> more... </summary>
|
| 116 |
+
<ul>
|
| 117 |
+
<li>[2025/04] [Seed-Thinking-v1.5](https://github.com/ByteDance-Seed/Seed-Thinking-v1.5/blob/main/seed-thinking-v1.5.pdf) tech report is released! Trained with verl, Seed-Thinking-v1.5 achieves 86.7 on AIME 2024, 55.0 on Codeforces and 77.3 on GPQA, demonstrating excellent reasoning abilities in STEM and coding. Beyond reasoning tasks, the method demonstrates notable generalization across diverse domains.</li>
|
| 118 |
+
<li>[2025/07] verl keynote at [AWS AI Hours Singapore](https://pages.awscloud.com/aws-ai-hours-sg.html#agenda) on 7/8, verl & verl-agent project updates at [Agent for SWE meetup](https://lu.ma/e498qhsi) by LF AI & Data Singapore on 7/11.</li>
|
| 119 |
+
<li>[2025/06] verl team will provide latest project updates at [PyTorch Day China](https://www.lfasiallc.com/pytorch-day-china/) on June 7th. Meet our dev team in Beijing!</li>
|
| 120 |
+
<li> [2025/04] [VAPO](https://arxiv.org/pdf/2504.05118) (value-based augmented PPO) paper covers our latest RL method for reasoning models. Trained from Qwen-32B-base model, VAPO achieves 60.4 on AIME 2024, outperforming DAPO-32B.</li>
|
| 121 |
+
<li>[2025/05] [PF-PPO](https://arxiv.org/abs/2409.06957), accepted to ICML 2025, is now supported in verl! PF-PPO enhances policy learning efficiency and robustness by filtering potentially noisy reward signals and reusing high-quality experiences via a replay buffer.</li>
|
| 122 |
+
<li>[2025/04] We will give a tutorial about latest post-training techniques and programming guide for verl at [ICLR 2025 Expo](https://iclr.cc/virtual/2025/calendar?filter_events=Expo+Talk+Panel&filter_rooms=), [SCI-FM workshop](https://open-foundation-model.github.io/) and [LMSys afterparty](https://lu.ma/d23nyynm). Talk materials available [here](https://github.com/eric-haibin-lin/verl-community/tree/main/iclr25). </li>
|
| 123 |
+
<li>[2025/03] verl v0.3.0.post1 is released! See [release note](https://github.com/volcengine/verl/releases/) for details. It achieves [~1.4x speedup](https://tongyx361.github.io/blogs/posts/verl-intro/#/verl-flexible-and-efficient-rl-for-llms) compared to prev versions.</li>
|
| 124 |
+
<li>[2025/05] verl will be presented at [A2M Shanghai](https://a2m.msup.com.cn/home/?aid=4488&city=shanghai) on 5/16 - 5/17.</li>
|
| 125 |
+
<li>[2025/05] verl will be presented at [GOSIM x PyTorch Day 2025](https://paris2025.gosim.org/). See you in Paris! </li>
|
| 126 |
+
<li>[2025/03] We introduced the programming model of verl at the [vLLM Beijing Meetup](https://mp.weixin.qq.com/s/n77GibL2corAtQHtVEAzfg) and [verl intro and updates](https://github.com/eric-haibin-lin/verl-community/blob/main/slides/verl-lmsys-meetup.pdf) at the [SGLang-LMSYS Org Meetup](https://lu.ma/ntjrr7ig) in Sunnyvale mid-March.</li>
|
| 127 |
+
<li>[2025/03] We will present verl(HybridFlow) at EuroSys 2025. See you in Rotterdam!</li>
|
| 128 |
+
<li>[2025/02] verl v0.2.0.post2 is released!</li>
|
| 129 |
+
<li>[2025/02] We presented verl in the <a href="https://lu.ma/ji7atxux">Bytedance/NVIDIA/Anyscale Ray Meetup</a>. See you in San Jose!</li>
|
| 130 |
+
<li>[2025/01] [Doubao-1.5-pro](https://team.doubao.com/zh/special/doubao_1_5_pro) is released with SOTA-level performance on LLM & VLM. The RL scaling preview model is trained using verl, reaching OpenAI O1-level performance on math benchmarks (70.0 pass@1 on AIME).</li>
|
| 131 |
+
<li>[2024/12] verl is presented at Ray Forward 2024. Slides available <a href="https://github.com/eric-haibin-lin/verl-community/blob/main/slides/Ray_Forward_2024_%E5%B7%AB%E9%94%A1%E6%96%8C.pdf">here</a></li>
|
| 132 |
+
<li>[2024/12] The team presented <a href="https://neurips.cc/Expo/Conferences/2024/workshop/100677">Post-training LLMs: From Algorithms to Infrastructure</a> at NeurIPS 2024. <a href="https://github.com/eric-haibin-lin/verl-data/tree/neurips">Slides</a> and <a href="https://neurips.cc/Expo/Conferences/2024/workshop/100677">video</a> available.</li>
|
| 133 |
+
<li>[2024/10] verl is presented at Ray Summit. <a href="https://www.youtube.com/watch?v=MrhMcXkXvJU&list=PLzTswPQNepXntmT8jr9WaNfqQ60QwW7-U&index=37">Youtube video</a> available.</li>
|
| 134 |
+
<li>[2024/08] HybridFlow (verl) is accepted to EuroSys 2025.</li>
|
| 135 |
+
</ul>
|
| 136 |
+
</details>
|
| 137 |
+
|
| 138 |
+
## Key Features
|
| 139 |
+
|
| 140 |
+
- **FSDP**, **FSDP2** and **Megatron-LM** for training.
|
| 141 |
+
- **vLLM**, **SGLang** and **HF Transformers** for rollout generation.
|
| 142 |
+
- 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
|
| 143 |
+
- Supervised fine-tuning.
|
| 144 |
+
- 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.
|
| 145 |
+
- Support model-based reward and function-based reward (verifiable reward) for math, [coding](https://github.com/volcengine/verl/tree/main/recipe/dapo), etc
|
| 146 |
+
- Support vision-language models (VLMs) and [multi-modal RL](examples/grpo_trainer/run_qwen2_5_vl-7b.sh) with Qwen2.5-vl, Kimi-VL
|
| 147 |
+
- [Multi-turn with tool calling](https://github.com/volcengine/verl/tree/main/examples/sglang_multiturn)
|
| 148 |
+
- LLM alignment recipes such as [Self-play preference optimization (SPPO)](https://github.com/volcengine/verl/tree/main/recipe/sppo)
|
| 149 |
+
- 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).
|
| 150 |
+
- Scales up to 671B models and hundreds of GPUs with [expert parallelism](https://github.com/volcengine/verl/pull/1467)
|
| 151 |
+
- Multi-gpu [LoRA RL](https://verl.readthedocs.io/en/latest/advance/ppo_lora.html) support to save memory.
|
| 152 |
+
- Experiment tracking with wandb, swanlab, mlflow and tensorboard.
|
| 153 |
+
|
| 154 |
+
## Upcoming Features and Changes
|
| 155 |
+
|
| 156 |
+
- Q3 Roadmap https://github.com/volcengine/verl/issues/2388
|
| 157 |
+
- DeepSeek 671b optimizations with Megatron https://github.com/volcengine/verl/issues/1033
|
| 158 |
+
- Multi-turn rollout and tools using optimizations https://github.com/volcengine/verl/issues/1882
|
| 159 |
+
- [Agent integration](https://github.com/volcengine/verl/tree/main/verl/experimental/agent_loop)
|
| 160 |
+
- Async and off-policy architecture https://github.com/volcengine/verl/pull/2231
|
| 161 |
+
- List of breaking changes since v0.4 https://github.com/volcengine/verl/discussions/2270
|
| 162 |
+
|
| 163 |
+
## Getting Started
|
| 164 |
+
|
| 165 |
+
<a href="https://verl.readthedocs.io/en/latest/index.html"><b>Documentation</b></a>
|
| 166 |
+
|
| 167 |
+
**Quickstart:**
|
| 168 |
+
|
| 169 |
+
- [Installation](https://verl.readthedocs.io/en/latest/start/install.html)
|
| 170 |
+
- [Quickstart](https://verl.readthedocs.io/en/latest/start/quickstart.html)
|
| 171 |
+
- [Programming Guide](https://verl.readthedocs.io/en/latest/hybrid_flow.html) & [Tech Talk](https://hcqnc.xetlk.com/sl/3vACOK) (in Chinese)
|
| 172 |
+
- [PPO in verl](https://verl.readthedocs.io/en/latest/algo/ppo.html)
|
| 173 |
+
- [GRPO in verl](https://verl.readthedocs.io/en/latest/algo/grpo.html)
|
| 174 |
+
|
| 175 |
+
**Running a PPO example step-by-step:**
|
| 176 |
+
|
| 177 |
+
- [Prepare Data for Post-Training](https://verl.readthedocs.io/en/latest/preparation/prepare_data.html)
|
| 178 |
+
- [Implement Reward Function for Dataset](https://verl.readthedocs.io/en/latest/preparation/reward_function.html)
|
| 179 |
+
- [PPO Example Architecture](https://verl.readthedocs.io/en/latest/examples/ppo_code_architecture.html)
|
| 180 |
+
- [Config Explanation](https://verl.readthedocs.io/en/latest/examples/config.html)
|
| 181 |
+
|
| 182 |
+
**Reproducible algorithm baselines:**
|
| 183 |
+
|
| 184 |
+
- [RL performance on coding, math](https://verl.readthedocs.io/en/latest/algo/baseline.html)
|
| 185 |
+
|
| 186 |
+
**For code explanation and advance usage (extension):**
|
| 187 |
+
|
| 188 |
+
- PPO Trainer and Workers
|
| 189 |
+
- [PPO Ray Trainer](https://verl.readthedocs.io/en/latest/workers/ray_trainer.html)
|
| 190 |
+
- [PyTorch FSDP Backend](https://verl.readthedocs.io/en/latest/workers/fsdp_workers.html)
|
| 191 |
+
- [Megatron-LM Backend](https://verl.readthedocs.io/en/latest/index.html)
|
| 192 |
+
|
| 193 |
+
- Advanced Usage and Extension
|
| 194 |
+
- [Add Models with the FSDP Backend](https://verl.readthedocs.io/en/latest/advance/fsdp_extension.html)
|
| 195 |
+
- [Add Models with the Megatron-LM Backend](https://verl.readthedocs.io/en/latest/advance/megatron_extension.html)
|
| 196 |
+
- [Multi-turn Rollout Support](https://verl.readthedocs.io/en/latest/sglang_multiturn/multiturn.html)
|
| 197 |
+
- [Search Tool Integration](https://verl.readthedocs.io/en/latest/sglang_multiturn/search_tool_example.html)
|
| 198 |
+
- [Sandbox Fusion Integration](https://verl.readthedocs.io/en/latest/examples/sandbox_fusion_example.html)
|
| 199 |
+
- [Deployment using Separate GPU Resources](https://github.com/volcengine/verl/tree/main/examples/split_placement)
|
| 200 |
+
- [Extend to Other RL(HF) algorithms](https://verl.readthedocs.io/en/latest/advance/dpo_extension.html)
|
| 201 |
+
- [Ray API design tutorial](https://verl.readthedocs.io/en/latest/advance/placement.html)
|
| 202 |
+
|
| 203 |
+
**Blogs from the community**
|
| 204 |
+
|
| 205 |
+
- [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)
|
| 206 |
+
- [verl deployment on AWS SageMaker](https://medium.com/@kaige.yang0110/run-verl-on-sagemaker-using-4x8-l40s-gpus-8e6d5c3c61d3)
|
| 207 |
+
- [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)
|
| 208 |
+
- [Optimizing SGLang Memory Usage in verl](https://hebiao064.github.io/rl-memory-management)
|
| 209 |
+
- [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)
|
| 210 |
+
- [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)
|
| 211 |
+
- [veMLP x verl :玩转强化学习训练](https://mp.weixin.qq.com/s/7nbqxk4knMGd-hQE9ls2tA)
|
| 212 |
+
- [使用 verl 进行 GRPO 分布式强化学习训练最佳实践](https://www.volcengine.com/docs/6459/1463942)
|
| 213 |
+
- [HybridFlow verl 原文浅析](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/readme.md)
|
| 214 |
+
- [最高提升 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)
|
| 215 |
+
|
| 216 |
+
## Performance Tuning Guide
|
| 217 |
+
|
| 218 |
+
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.
|
| 219 |
+
|
| 220 |
+
## Upgrade to vLLM >= v0.8.2
|
| 221 |
+
|
| 222 |
+
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.
|
| 223 |
+
|
| 224 |
+
## Use Latest SGLang
|
| 225 |
+
|
| 226 |
+
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.
|
| 227 |
+
|
| 228 |
+
## Upgrade to FSDP2
|
| 229 |
+
|
| 230 |
+
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:
|
| 231 |
+
```
|
| 232 |
+
actor_rollout_ref.ref.strategy=fsdp2
|
| 233 |
+
actor_rollout_ref.actor.strategy=fsdp2
|
| 234 |
+
critic.strategy=fsdp2
|
| 235 |
+
reward_model.strategy=fsdp2
|
| 236 |
+
```
|
| 237 |
+
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
|
| 238 |
+
|
| 239 |
+
## AMD Support (ROCm Kernel)
|
| 240 |
+
|
| 241 |
+
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.
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
## Citation and acknowledgement
|
| 245 |
+
|
| 246 |
+
If you find the project helpful, please cite:
|
| 247 |
+
|
| 248 |
+
- [HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2)
|
| 249 |
+
- [A Framework for Training Large Language Models for Code Generation via Proximal Policy Optimization](https://i.cs.hku.hk/~cwu/papers/gmsheng-NL2Code24.pdf)
|
| 250 |
+
|
| 251 |
+
```bibtex
|
| 252 |
+
@article{sheng2024hybridflow,
|
| 253 |
+
title = {HybridFlow: A Flexible and Efficient RLHF Framework},
|
| 254 |
+
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},
|
| 255 |
+
year = {2024},
|
| 256 |
+
journal = {arXiv preprint arXiv: 2409.19256}
|
| 257 |
+
}
|
| 258 |
+
```
|
| 259 |
+
|
| 260 |
+
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.
|
| 261 |
+
|
| 262 |
+
## Awesome work using verl
|
| 263 |
+
|
| 264 |
+
- [TinyZero](https://github.com/Jiayi-Pan/TinyZero): a reproduction of **DeepSeek R1 Zero** recipe for reasoning tasks 
|
| 265 |
+
- [SkyThought](https://github.com/NovaSky-AI/SkyThought): RL training for Sky-T1-7B by NovaSky AI team. 
|
| 266 |
+
- [simpleRL-reason](https://github.com/hkust-nlp/simpleRL-reason): SimpleRL-Zoo: Investigating and Taming Zero Reinforcement Learning for Open Base Models in the Wild 
|
| 267 |
+
- [Easy-R1](https://github.com/hiyouga/EasyR1): **Multi-modal** RL training framework 
|
| 268 |
+
- [OpenManus-RL](https://github.com/OpenManus/OpenManus-RL): LLM Agents RL tunning framework for multiple agent environments. 
|
| 269 |
+
- [rllm](https://github.com/agentica-project/rllm): async RL training with [verl-pipeline](https://github.com/agentica-project/verl-pipeline) 
|
| 270 |
+
- [RAGEN](https://github.com/ZihanWang314/ragen): a general-purpose reasoning **agent** training framework 
|
| 271 |
+
- [Search-R1](https://github.com/PeterGriffinJin/Search-R1): RL with reasoning and **searching (tool-call)** interleaved LLMs 
|
| 272 |
+
- [ReSearch](https://github.com/Agent-RL/ReSearch): Learning to **Re**ason with **Search** for LLMs via Reinforcement Learning 
|
| 273 |
+
- [Skywork-OR1](https://github.com/SkyworkAI/Skywork-OR1): Skywork open reaonser series 
|
| 274 |
+
- [ToRL](https://github.com/GAIR-NLP/ToRL): Scaling tool-integrated RL 
|
| 275 |
+
- [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) 
|
| 276 |
+
- [verl-agent](https://github.com/langfengQ/verl-agent): A scalable training framework for **long-horizon LLM/VLM agents**, along with a new algorithm **GiGPO** 
|
| 277 |
+
- [RL-Factory](https://github.com/Simple-Efficient/RL-Factory): An easy and efficient RL post-training framework for Agentic Learning 
|
| 278 |
+
- [ReTool](https://retool-rl.github.io/): ReTool: reinforcement learning for strategic tool use in LLMs. Code release is in progress...
|
| 279 |
+
- [verl-tool](https://github.com/TIGER-AI-Lab/verl-tool): An unified and easy-to-extend tool-agent training framework based on verl
|
| 280 |
+
- [PRIME](https://github.com/PRIME-RL/PRIME): Process reinforcement through implicit rewards 
|
| 281 |
+
- [MemAgent](https://github.com/BytedTsinghua-SIA/MemAgent): MemAgent: Reshaping Long-Context LLM with Multi-Conv RL based Memory Agent 
|
| 282 |
+
- [POLARIS](https://github.com/ChenxinAn-fdu/POLARIS): A Post-training recipe for scaling RL on Advanced Reasoning models 
|
| 283 |
+
- [GUI-R1](https://github.com/ritzz-ai/GUI-R1): **GUI-R1**: A Generalist R1-style Vision-Language Action Model For **GUI Agents** 
|
| 284 |
+
- [DeepRetrieval](https://github.com/pat-jj/DeepRetrieval): RL Training of **Search Agent** with **Search/Retrieval Outcome** 
|
| 285 |
+
- [Code-R1](https://github.com/ganler/code-r1): Reproducing R1 for **Code** with Reliable Rewards 
|
| 286 |
+
- [DeepResearcher](https://github.com/GAIR-NLP/DeepResearcher): Scaling deep research via reinforcement learning in real-world environments 
|
| 287 |
+
- [VAGEN](https://github.com/RAGEN-AI/VAGEN): Training VLM agents with multi-turn reinforcement learning 
|
| 288 |
+
- [RM-R1](https://arxiv.org/abs/2505.02387): RL training of reasoning reward models 
|
| 289 |
+
- [LUFFY](https://arxiv.org/pdf/2504.14945): Learning to Reason under Off-Policy Guidance
|
| 290 |
+
- [DeepMath](https://github.com/zwhe99/DeepMath): DeepMath-103K data and series models for math reasoning
|
| 291 |
+
- [PACS](https://github.com/ritzz-ai/PACS): Implicit Actor Critic Coupling via a Supervised Learning Framework for RLVR 
|
| 292 |
+
- [Entropy Mechanism of RL](https://github.com/PRIME-RL/Entropy-Mechanism-of-RL): The Entropy Mechanism of Reinforcement Learning for Large Language Model Reasoning
|
| 293 |
+
- [LLaSA-TTS-GRPO](https://github.com/channel-io/ch-tts-llasa-rl-grpo): TTS fine-tuning with GRPO optimization based on LLASA models 
|
| 294 |
+
- [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.
|
| 295 |
+
- [RACRO](https://github.com/gyhdog99/RACRO2): Build multi-modal reasoning models via decoupling it into query-conditioned captioning and text-only reasoning 
|
| 296 |
+
- [Agent Lightning](https://github.com/microsoft/agent-lightning): A flexible and extensible framework that enables seamless agent optimization for any existing agent framework. 
|
| 297 |
+
- [VTool-R1](https://github.com/VTOOL-R1/vtool-r1): VLMs Learn to Think with Images via Reinforcement Learning on Multimodal Tool Use. 
|
| 298 |
+
- [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.
|
| 299 |
+
- [RL-PLUS](https://github.com/YihongDong/RL-PLUS): Countering Capability Boundary Collapse of LLMs in Reinforcement Learning with Hybrid-policy Optimization.
|
| 300 |
+
- [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 
|
| 301 |
+
- [Vision-SR1](https://github.com/zli12321/Vision-SR1): Self-Rewarding Vision-Language Model via Reasoning Decomposition 
|
| 302 |
+
- [SimpleVLA-RL](https://github.com/PRIME-RL/SimpleVLA-RL): SimpleVLA-RL: A Simple yet Effective Vision-Language Action Model for Reinforcement Learning 
|
| 303 |
+
- [Table-R1](https://github.com/Table-R1/Table-R1): Table-R1: Inference-Time Scaling for Table Reasoning 
|
| 304 |
+
|
| 305 |
+
and many more awesome work listed in [recipe](recipe/README.md).
|
| 306 |
+
|
| 307 |
+
## Contribution Guide
|
| 308 |
+
|
| 309 |
+
See [contributions guide](CONTRIBUTING.md)
|
| 310 |
+
|
| 311 |
+
## About [ByteDance Seed Team](https://team.doubao.com/)
|
| 312 |
+
|
| 313 |
+
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👇
|
| 314 |
+
<div>
|
| 315 |
+
<a href="https://team.doubao.com/">
|
| 316 |
+
<img src="https://img.shields.io/badge/Website-%231e37ff?style=for-the-badge&logo=bytedance&logoColor=white"></a>
|
| 317 |
+
<a href="https://github.com/user-attachments/assets/469535a8-42f2-4797-acdf-4f7a1d4a0c3e">
|
| 318 |
+
<img src="https://img.shields.io/badge/WeChat-07C160?style=for-the-badge&logo=wechat&logoColor=white"></a>
|
| 319 |
+
<a href="https://www.xiaohongshu.com/user/profile/668e7e15000000000303157d?xsec_token=ABl2-aqekpytY6A8TuxjrwnZskU-6BsMRE_ufQQaSAvjc%3D&xsec_source=pc_search">
|
| 320 |
+
<img src="https://img.shields.io/badge/Xiaohongshu-%23FF2442?style=for-the-badge&logo=xiaohongshu&logoColor=white"></a>
|
| 321 |
+
<a href="https://www.zhihu.com/org/dou-bao-da-mo-xing-tuan-dui/">
|
| 322 |
+
<img src="https://img.shields.io/badge/zhihu-%230084FF?style=for-the-badge&logo=zhihu&logoColor=white"></a>
|
| 323 |
+
|
| 324 |
+
</div>
|
| 325 |
+
---
|
| 326 |
+
|
| 327 |
+
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.
|
verl/verl.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,747 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 3 |
+
pyproject.toml
|
| 4 |
+
setup.py
|
| 5 |
+
./scripts/__init__.py
|
| 6 |
+
./scripts/converter_hf_to_mcore.py
|
| 7 |
+
./scripts/diagnose.py
|
| 8 |
+
./scripts/init_random_model.py
|
| 9 |
+
./scripts/legacy_model_merger.py
|
| 10 |
+
./scripts/print_cfg.py
|
| 11 |
+
./scripts/rollout_viewer.py
|
| 12 |
+
./tests/__init__.py
|
| 13 |
+
./tests/test_base_config_on_cpu.py
|
| 14 |
+
./tests/test_protocol_on_cpu.py
|
| 15 |
+
./tests/test_protocol_v2_on_cpu.py
|
| 16 |
+
./tests/interactions/__init__.py
|
| 17 |
+
./tests/interactions/test_gsm8k_interaction.py
|
| 18 |
+
./tests/interactions/test_interaction_registry.py
|
| 19 |
+
./tests/single_controller/__init__.py
|
| 20 |
+
./tests/single_controller/test_auto_padding_on_cpu.py
|
| 21 |
+
./tests/single_controller/test_colocated_workers.py
|
| 22 |
+
./tests/single_controller/test_colocated_workers_fused.py
|
| 23 |
+
./tests/single_controller/test_data_transfer.py
|
| 24 |
+
./tests/single_controller/test_decorator_on_cpu.py
|
| 25 |
+
./tests/single_controller/test_device_mesh_register.py
|
| 26 |
+
./tests/single_controller/test_driverfunc_to_worker.py
|
| 27 |
+
./tests/single_controller/test_fused_workers_on_cpu.py
|
| 28 |
+
./tests/single_controller/test_high_level_scheduling_api.py
|
| 29 |
+
./tests/single_controller/test_nested_worker.py
|
| 30 |
+
./tests/single_controller/test_ray_collectives.py
|
| 31 |
+
./tests/single_controller/test_ray_local_envs_on_cpu.py
|
| 32 |
+
./tests/single_controller/test_ray_utils_on_cpu.py
|
| 33 |
+
./tests/single_controller/test_rvdz.py
|
| 34 |
+
./tests/single_controller/test_worker_group_basics.py
|
| 35 |
+
./tests/single_controller/test_worker_group_torch.py
|
| 36 |
+
./tests/special_e2e/__init__.py
|
| 37 |
+
./tests/special_e2e/check_custom_rwd_fn.py
|
| 38 |
+
./tests/special_e2e/check_results.py
|
| 39 |
+
./tests/special_e2e/envs/__init__.py
|
| 40 |
+
./tests/special_e2e/envs/digit_completion/__init__.py
|
| 41 |
+
./tests/special_e2e/envs/digit_completion/task.py
|
| 42 |
+
./tests/special_e2e/envs/digit_completion/tokenizer.py
|
| 43 |
+
./tests/trainer/__init__.py
|
| 44 |
+
./tests/trainer/config/__init__.py
|
| 45 |
+
./tests/trainer/config/test_algo_config_on_cpu.py
|
| 46 |
+
./tests/trainer/config/test_legacy_config_on_cpu.py
|
| 47 |
+
./tests/trainer/ppo/__init__.py
|
| 48 |
+
./tests/trainer/ppo/test_core_algos_on_cpu.py
|
| 49 |
+
./tests/trainer/ppo/test_metric_utils_on_cpu.py
|
| 50 |
+
./verl/__init__.py
|
| 51 |
+
./verl/base_config.py
|
| 52 |
+
./verl/protocol.py
|
| 53 |
+
./verl/py.typed
|
| 54 |
+
./verl/experimental/__init__.py
|
| 55 |
+
./verl/experimental/agent_loop/__init__.py
|
| 56 |
+
./verl/experimental/agent_loop/agent_loop.py
|
| 57 |
+
./verl/experimental/agent_loop/single_turn_agent_loop.py
|
| 58 |
+
./verl/experimental/agent_loop/tool_agent_loop.py
|
| 59 |
+
./verl/experimental/agent_loop/tool_parser.py
|
| 60 |
+
./verl/experimental/dataset/__init__.py
|
| 61 |
+
./verl/experimental/dataset/sampler.py
|
| 62 |
+
./verl/experimental/dynamic_dataset/__init__.py
|
| 63 |
+
./verl/experimental/dynamic_dataset/dynamicgen_dataset.py
|
| 64 |
+
./verl/interactions/__init__.py
|
| 65 |
+
./verl/interactions/base.py
|
| 66 |
+
./verl/interactions/gsm8k_interaction.py
|
| 67 |
+
./verl/interactions/weather_interaction.py
|
| 68 |
+
./verl/interactions/utils/__init__.py
|
| 69 |
+
./verl/interactions/utils/interaction_registry.py
|
| 70 |
+
./verl/model_merger/__init__.py
|
| 71 |
+
./verl/model_merger/__main__.py
|
| 72 |
+
./verl/model_merger/base_model_merger.py
|
| 73 |
+
./verl/model_merger/fsdp_model_merger.py
|
| 74 |
+
./verl/model_merger/megatron_model_merger.py
|
| 75 |
+
./verl/models/__init__.py
|
| 76 |
+
./verl/models/registry.py
|
| 77 |
+
./verl/models/weight_loader_registry.py
|
| 78 |
+
./verl/models/llama/__init__.py
|
| 79 |
+
./verl/models/llama/megatron/__init__.py
|
| 80 |
+
./verl/models/llama/megatron/modeling_llama_megatron.py
|
| 81 |
+
./verl/models/llama/megatron/checkpoint_utils/__init__.py
|
| 82 |
+
./verl/models/llama/megatron/checkpoint_utils/llama_loader.py
|
| 83 |
+
./verl/models/llama/megatron/checkpoint_utils/llama_loader_depracated.py
|
| 84 |
+
./verl/models/llama/megatron/checkpoint_utils/llama_saver.py
|
| 85 |
+
./verl/models/llama/megatron/layers/__init__.py
|
| 86 |
+
./verl/models/llama/megatron/layers/parallel_attention.py
|
| 87 |
+
./verl/models/llama/megatron/layers/parallel_decoder.py
|
| 88 |
+
./verl/models/llama/megatron/layers/parallel_linear.py
|
| 89 |
+
./verl/models/llama/megatron/layers/parallel_mlp.py
|
| 90 |
+
./verl/models/llama/megatron/layers/parallel_rmsnorm.py
|
| 91 |
+
./verl/models/mcore/__init__.py
|
| 92 |
+
./verl/models/mcore/config_converter.py
|
| 93 |
+
./verl/models/mcore/loader.py
|
| 94 |
+
./verl/models/mcore/mbridge.py
|
| 95 |
+
./verl/models/mcore/model_forward.py
|
| 96 |
+
./verl/models/mcore/model_forward_fused.py
|
| 97 |
+
./verl/models/mcore/model_initializer.py
|
| 98 |
+
./verl/models/mcore/patch_v012.py
|
| 99 |
+
./verl/models/mcore/registry.py
|
| 100 |
+
./verl/models/mcore/saver.py
|
| 101 |
+
./verl/models/mcore/util.py
|
| 102 |
+
./verl/models/mcore/weight_converter.py
|
| 103 |
+
./verl/models/mcore/qwen2_5_vl/__init__.py
|
| 104 |
+
./verl/models/mcore/qwen2_5_vl/attention.py
|
| 105 |
+
./verl/models/mcore/qwen2_5_vl/model.py
|
| 106 |
+
./verl/models/mcore/qwen2_5_vl/rope_utils.py
|
| 107 |
+
./verl/models/mcore/qwen2_5_vl/vision_config.py
|
| 108 |
+
./verl/models/mcore/qwen2_5_vl/vision_model.py
|
| 109 |
+
./verl/models/mcore/qwen2_5_vl/vision_transformer_block.py
|
| 110 |
+
./verl/models/qwen2/__init__.py
|
| 111 |
+
./verl/models/qwen2/megatron/__init__.py
|
| 112 |
+
./verl/models/qwen2/megatron/modeling_qwen2_megatron.py
|
| 113 |
+
./verl/models/qwen2/megatron/checkpoint_utils/__init__.py
|
| 114 |
+
./verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader.py
|
| 115 |
+
./verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader_depracated.py
|
| 116 |
+
./verl/models/qwen2/megatron/checkpoint_utils/qwen2_saver.py
|
| 117 |
+
./verl/models/qwen2/megatron/layers/__init__.py
|
| 118 |
+
./verl/models/qwen2/megatron/layers/parallel_attention.py
|
| 119 |
+
./verl/models/qwen2/megatron/layers/parallel_decoder.py
|
| 120 |
+
./verl/models/qwen2/megatron/layers/parallel_linear.py
|
| 121 |
+
./verl/models/qwen2/megatron/layers/parallel_mlp.py
|
| 122 |
+
./verl/models/qwen2/megatron/layers/parallel_rmsnorm.py
|
| 123 |
+
./verl/models/transformers/__init__.py
|
| 124 |
+
./verl/models/transformers/apertus.py
|
| 125 |
+
./verl/models/transformers/dense_common.py
|
| 126 |
+
./verl/models/transformers/glm4v.py
|
| 127 |
+
./verl/models/transformers/kimi_vl.py
|
| 128 |
+
./verl/models/transformers/llama.py
|
| 129 |
+
./verl/models/transformers/monkey_patch.py
|
| 130 |
+
./verl/models/transformers/npu_patch.py
|
| 131 |
+
./verl/models/transformers/qwen2.py
|
| 132 |
+
./verl/models/transformers/qwen2_vl.py
|
| 133 |
+
./verl/models/transformers/qwen3_vl.py
|
| 134 |
+
./verl/single_controller/__init__.py
|
| 135 |
+
./verl/single_controller/base/__init__.py
|
| 136 |
+
./verl/single_controller/base/decorator.py
|
| 137 |
+
./verl/single_controller/base/worker.py
|
| 138 |
+
./verl/single_controller/base/worker_group.py
|
| 139 |
+
./verl/single_controller/ray/__init__.py
|
| 140 |
+
./verl/single_controller/ray/base.py
|
| 141 |
+
./verl/third_party/__init__.py
|
| 142 |
+
./verl/third_party/sglang/__init__.py
|
| 143 |
+
./verl/third_party/sglang/parallel_state.py
|
| 144 |
+
./verl/third_party/torch/__init__.py
|
| 145 |
+
./verl/third_party/torch/distributed/__init__.py
|
| 146 |
+
./verl/third_party/torch/distributed/_state_dict_utils.py
|
| 147 |
+
./verl/third_party/torch/distributed/checkpoint/__init__.py
|
| 148 |
+
./verl/third_party/torch/distributed/checkpoint/state_dict.py
|
| 149 |
+
./verl/third_party/vllm/__init__.py
|
| 150 |
+
./verl/tools/__init__.py
|
| 151 |
+
./verl/tools/base_tool.py
|
| 152 |
+
./verl/tools/geo3k_tool.py
|
| 153 |
+
./verl/tools/gsm8k_tool.py
|
| 154 |
+
./verl/tools/image_zoom_in_tool.py
|
| 155 |
+
./verl/tools/mcp_base_tool.py
|
| 156 |
+
./verl/tools/mcp_search_tool.py
|
| 157 |
+
./verl/tools/sandbox_fusion_tools.py
|
| 158 |
+
./verl/tools/schemas.py
|
| 159 |
+
./verl/tools/search_tool.py
|
| 160 |
+
./verl/tools/utils/__init__.py
|
| 161 |
+
./verl/tools/utils/search_r1_like_utils.py
|
| 162 |
+
./verl/tools/utils/tool_registry.py
|
| 163 |
+
./verl/trainer/__init__.py
|
| 164 |
+
./verl/trainer/constants_ppo.py
|
| 165 |
+
./verl/trainer/fsdp_sft_trainer.py
|
| 166 |
+
./verl/trainer/main_eval.py
|
| 167 |
+
./verl/trainer/main_generation.py
|
| 168 |
+
./verl/trainer/main_ppo.py
|
| 169 |
+
./verl/trainer/sft_trainer.py
|
| 170 |
+
./verl/trainer/config/__init__.py
|
| 171 |
+
./verl/trainer/config/_generated_ppo_megatron_trainer.yaml
|
| 172 |
+
./verl/trainer/config/_generated_ppo_trainer.yaml
|
| 173 |
+
./verl/trainer/config/algorithm.py
|
| 174 |
+
./verl/trainer/config/config.py
|
| 175 |
+
./verl/trainer/config/evaluation.yaml
|
| 176 |
+
./verl/trainer/config/generation.yaml
|
| 177 |
+
./verl/trainer/config/ppo_megatron_trainer.yaml
|
| 178 |
+
./verl/trainer/config/ppo_trainer.yaml
|
| 179 |
+
./verl/trainer/config/sft_trainer.yaml
|
| 180 |
+
./verl/trainer/config/sft_trainer_engine.yaml
|
| 181 |
+
./verl/trainer/config/actor/actor.yaml
|
| 182 |
+
./verl/trainer/config/actor/dp_actor.yaml
|
| 183 |
+
./verl/trainer/config/actor/megatron_actor.yaml
|
| 184 |
+
./verl/trainer/config/critic/critic.yaml
|
| 185 |
+
./verl/trainer/config/critic/dp_critic.yaml
|
| 186 |
+
./verl/trainer/config/critic/megatron_critic.yaml
|
| 187 |
+
./verl/trainer/config/data/legacy_data.yaml
|
| 188 |
+
./verl/trainer/config/engine/fsdp.yaml
|
| 189 |
+
./verl/trainer/config/engine/megatron.yaml
|
| 190 |
+
./verl/trainer/config/model/hf_model.yaml
|
| 191 |
+
./verl/trainer/config/npu_profile/npu_profile.yaml
|
| 192 |
+
./verl/trainer/config/optim/fsdp.yaml
|
| 193 |
+
./verl/trainer/config/optim/megatron.yaml
|
| 194 |
+
./verl/trainer/config/ref/dp_ref.yaml
|
| 195 |
+
./verl/trainer/config/ref/megatron_ref.yaml
|
| 196 |
+
./verl/trainer/config/ref/ref.yaml
|
| 197 |
+
./verl/trainer/config/reward_model/dp_reward_model.yaml
|
| 198 |
+
./verl/trainer/config/reward_model/megatron_reward_model.yaml
|
| 199 |
+
./verl/trainer/config/reward_model/reward_model.yaml
|
| 200 |
+
./verl/trainer/config/rollout/rollout.yaml
|
| 201 |
+
./verl/trainer/ppo/__init__.py
|
| 202 |
+
./verl/trainer/ppo/core_algos.py
|
| 203 |
+
./verl/trainer/ppo/metric_utils.py
|
| 204 |
+
./verl/trainer/ppo/ray_trainer.py
|
| 205 |
+
./verl/trainer/ppo/reward.py
|
| 206 |
+
./verl/trainer/ppo/utils.py
|
| 207 |
+
./verl/utils/__init__.py
|
| 208 |
+
./verl/utils/activation_offload.py
|
| 209 |
+
./verl/utils/attention_utils.py
|
| 210 |
+
./verl/utils/config.py
|
| 211 |
+
./verl/utils/device.py
|
| 212 |
+
./verl/utils/distributed.py
|
| 213 |
+
./verl/utils/flops_counter.py
|
| 214 |
+
./verl/utils/fs.py
|
| 215 |
+
./verl/utils/fsdp_utils.py
|
| 216 |
+
./verl/utils/groupwise.py
|
| 217 |
+
./verl/utils/hdfs_io.py
|
| 218 |
+
./verl/utils/import_utils.py
|
| 219 |
+
./verl/utils/logging_utils.py
|
| 220 |
+
./verl/utils/megatron_utils.py
|
| 221 |
+
./verl/utils/memory_buffer.py
|
| 222 |
+
./verl/utils/memory_utils.py
|
| 223 |
+
./verl/utils/model.py
|
| 224 |
+
./verl/utils/net_utils.py
|
| 225 |
+
./verl/utils/npu_utils.py
|
| 226 |
+
./verl/utils/py_functional.py
|
| 227 |
+
./verl/utils/ray_utils.py
|
| 228 |
+
./verl/utils/rollout_skip.py
|
| 229 |
+
./verl/utils/rollout_trace.py
|
| 230 |
+
./verl/utils/seqlen_balancing.py
|
| 231 |
+
./verl/utils/tensordict_utils.py
|
| 232 |
+
./verl/utils/tokenizer.py
|
| 233 |
+
./verl/utils/torch_dtypes.py
|
| 234 |
+
./verl/utils/torch_functional.py
|
| 235 |
+
./verl/utils/tracking.py
|
| 236 |
+
./verl/utils/transformers_compat.py
|
| 237 |
+
./verl/utils/ulysses.py
|
| 238 |
+
./verl/utils/checkpoint/__init__.py
|
| 239 |
+
./verl/utils/checkpoint/checkpoint_handler.py
|
| 240 |
+
./verl/utils/checkpoint/checkpoint_manager.py
|
| 241 |
+
./verl/utils/checkpoint/fsdp_checkpoint_manager.py
|
| 242 |
+
./verl/utils/checkpoint/megatron_checkpoint_manager.py
|
| 243 |
+
./verl/utils/dataset/__init__.py
|
| 244 |
+
./verl/utils/dataset/dataset_utils.py
|
| 245 |
+
./verl/utils/dataset/multiturn_sft_dataset.py
|
| 246 |
+
./verl/utils/dataset/rl_dataset.py
|
| 247 |
+
./verl/utils/dataset/rm_dataset.py
|
| 248 |
+
./verl/utils/dataset/sft_dataset.py
|
| 249 |
+
./verl/utils/dataset/vision_utils.py
|
| 250 |
+
./verl/utils/debug/__init__.py
|
| 251 |
+
./verl/utils/debug/metrics.py
|
| 252 |
+
./verl/utils/debug/performance.py
|
| 253 |
+
./verl/utils/debug/trajectory_tracker.py
|
| 254 |
+
./verl/utils/experimental/__init__.py
|
| 255 |
+
./verl/utils/experimental/torch_functional.py
|
| 256 |
+
./verl/utils/kernel/__init__.py
|
| 257 |
+
./verl/utils/kernel/kernels.py
|
| 258 |
+
./verl/utils/kernel/linear_cross_entropy.py
|
| 259 |
+
./verl/utils/logger/__init__.py
|
| 260 |
+
./verl/utils/logger/aggregate_logger.py
|
| 261 |
+
./verl/utils/megatron/__init__.py
|
| 262 |
+
./verl/utils/megatron/dist_checkpointing.py
|
| 263 |
+
./verl/utils/megatron/memory.py
|
| 264 |
+
./verl/utils/megatron/optimizer.py
|
| 265 |
+
./verl/utils/megatron/pipeline_parallel.py
|
| 266 |
+
./verl/utils/megatron/sequence_parallel.py
|
| 267 |
+
./verl/utils/megatron/tensor_parallel.py
|
| 268 |
+
./verl/utils/metric/__init__.py
|
| 269 |
+
./verl/utils/metric/utils.py
|
| 270 |
+
./verl/utils/profiler/__init__.py
|
| 271 |
+
./verl/utils/profiler/config.py
|
| 272 |
+
./verl/utils/profiler/empty_annotations.py
|
| 273 |
+
./verl/utils/profiler/mstx_profile.py
|
| 274 |
+
./verl/utils/profiler/nvtx_profile.py
|
| 275 |
+
./verl/utils/profiler/performance.py
|
| 276 |
+
./verl/utils/profiler/profile.py
|
| 277 |
+
./verl/utils/rendezvous/__init__.py
|
| 278 |
+
./verl/utils/rendezvous/ray_backend.py
|
| 279 |
+
./verl/utils/reward_score/__init__.py
|
| 280 |
+
./verl/utils/reward_score/geo3k.py
|
| 281 |
+
./verl/utils/reward_score/gsm8k.py
|
| 282 |
+
./verl/utils/reward_score/math_batch.py
|
| 283 |
+
./verl/utils/reward_score/math_dapo.py
|
| 284 |
+
./verl/utils/reward_score/math_reward.py
|
| 285 |
+
./verl/utils/reward_score/math_verify.py
|
| 286 |
+
./verl/utils/reward_score/search_r1_like_qa_em.py
|
| 287 |
+
./verl/utils/reward_score/prime_code/__init__.py
|
| 288 |
+
./verl/utils/reward_score/prime_code/testing_util.py
|
| 289 |
+
./verl/utils/reward_score/prime_code/utils.py
|
| 290 |
+
./verl/utils/reward_score/prime_math/__init__.py
|
| 291 |
+
./verl/utils/reward_score/prime_math/grader.py
|
| 292 |
+
./verl/utils/reward_score/prime_math/math_normalize.py
|
| 293 |
+
./verl/utils/reward_score/sandbox_fusion/__init__.py
|
| 294 |
+
./verl/utils/reward_score/sandbox_fusion/utils.py
|
| 295 |
+
./verl/utils/vllm/__init__.py
|
| 296 |
+
./verl/utils/vllm/patch.py
|
| 297 |
+
./verl/utils/vllm/utils.py
|
| 298 |
+
./verl/version/version
|
| 299 |
+
./verl/workers/__init__.py
|
| 300 |
+
./verl/workers/fsdp_workers.py
|
| 301 |
+
./verl/workers/megatron_workers.py
|
| 302 |
+
./verl/workers/actor/__init__.py
|
| 303 |
+
./verl/workers/actor/base.py
|
| 304 |
+
./verl/workers/actor/dp_actor.py
|
| 305 |
+
./verl/workers/actor/megatron_actor.py
|
| 306 |
+
./verl/workers/config/__init__.py
|
| 307 |
+
./verl/workers/config/actor.py
|
| 308 |
+
./verl/workers/config/critic.py
|
| 309 |
+
./verl/workers/config/engine.py
|
| 310 |
+
./verl/workers/config/model.py
|
| 311 |
+
./verl/workers/config/optimizer.py
|
| 312 |
+
./verl/workers/config/reward_model.py
|
| 313 |
+
./verl/workers/config/rollout.py
|
| 314 |
+
./verl/workers/critic/__init__.py
|
| 315 |
+
./verl/workers/critic/base.py
|
| 316 |
+
./verl/workers/critic/dp_critic.py
|
| 317 |
+
./verl/workers/critic/megatron_critic.py
|
| 318 |
+
./verl/workers/engine/__init__.py
|
| 319 |
+
./verl/workers/engine/base.py
|
| 320 |
+
./verl/workers/engine/utils.py
|
| 321 |
+
./verl/workers/engine/fsdp/__init__.py
|
| 322 |
+
./verl/workers/engine/fsdp/transformer_impl.py
|
| 323 |
+
./verl/workers/engine/fsdp/utils.py
|
| 324 |
+
./verl/workers/engine/megatron/__init__.py
|
| 325 |
+
./verl/workers/engine/megatron/transformer_impl.py
|
| 326 |
+
./verl/workers/engine/megatron/utils.py
|
| 327 |
+
./verl/workers/engine/mindspeed/__init__.py
|
| 328 |
+
./verl/workers/engine/mindspeed/transformer_impl.py
|
| 329 |
+
./verl/workers/reward_manager/__init__.py
|
| 330 |
+
./verl/workers/reward_manager/abstract.py
|
| 331 |
+
./verl/workers/reward_manager/batch.py
|
| 332 |
+
./verl/workers/reward_manager/dapo.py
|
| 333 |
+
./verl/workers/reward_manager/naive.py
|
| 334 |
+
./verl/workers/reward_manager/prime.py
|
| 335 |
+
./verl/workers/reward_manager/registry.py
|
| 336 |
+
./verl/workers/reward_model/__init__.py
|
| 337 |
+
./verl/workers/reward_model/base.py
|
| 338 |
+
./verl/workers/reward_model/megatron/__init__.py
|
| 339 |
+
./verl/workers/reward_model/megatron/reward_model.py
|
| 340 |
+
./verl/workers/roles/__init__.py
|
| 341 |
+
./verl/workers/roles/actor.py
|
| 342 |
+
./verl/workers/roles/critic.py
|
| 343 |
+
./verl/workers/roles/hybrid_engine.py
|
| 344 |
+
./verl/workers/roles/reward_model.py
|
| 345 |
+
./verl/workers/roles/reward_model_engine/__init__.py
|
| 346 |
+
./verl/workers/roles/reward_model_engine/base.py
|
| 347 |
+
./verl/workers/roles/reward_model_engine/sglang_reward_model.py
|
| 348 |
+
./verl/workers/roles/utils/__init__.py
|
| 349 |
+
./verl/workers/roles/utils/losses.py
|
| 350 |
+
./verl/workers/rollout/__init__.py
|
| 351 |
+
./verl/workers/rollout/base.py
|
| 352 |
+
./verl/workers/rollout/hf_rollout.py
|
| 353 |
+
./verl/workers/rollout/replica.py
|
| 354 |
+
./verl/workers/rollout/schemas.py
|
| 355 |
+
./verl/workers/rollout/tokenizer.py
|
| 356 |
+
./verl/workers/rollout/utils.py
|
| 357 |
+
./verl/workers/rollout/naive/__init__.py
|
| 358 |
+
./verl/workers/rollout/naive/naive_rollout.py
|
| 359 |
+
./verl/workers/rollout/sglang_rollout/__init__.py
|
| 360 |
+
./verl/workers/rollout/sglang_rollout/async_sglang_server.py
|
| 361 |
+
./verl/workers/rollout/sglang_rollout/http_server_engine.py
|
| 362 |
+
./verl/workers/rollout/sglang_rollout/sglang_rollout.py
|
| 363 |
+
./verl/workers/rollout/sglang_rollout/utils.py
|
| 364 |
+
./verl/workers/rollout/vllm_rollout/__init__.py
|
| 365 |
+
./verl/workers/rollout/vllm_rollout/vllm_async_server.py
|
| 366 |
+
./verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py
|
| 367 |
+
./verl/workers/sharding_manager/__init__.py
|
| 368 |
+
./verl/workers/sharding_manager/base.py
|
| 369 |
+
./verl/workers/sharding_manager/fsdp_sglang.py
|
| 370 |
+
./verl/workers/sharding_manager/fsdp_ulysses.py
|
| 371 |
+
./verl/workers/sharding_manager/fsdp_vllm.py
|
| 372 |
+
./verl/workers/sharding_manager/megatron_sglang.py
|
| 373 |
+
./verl/workers/sharding_manager/megatron_vllm.py
|
| 374 |
+
scripts/__init__.py
|
| 375 |
+
scripts/converter_hf_to_mcore.py
|
| 376 |
+
scripts/diagnose.py
|
| 377 |
+
scripts/init_random_model.py
|
| 378 |
+
scripts/legacy_model_merger.py
|
| 379 |
+
scripts/print_cfg.py
|
| 380 |
+
scripts/rollout_viewer.py
|
| 381 |
+
tests/__init__.py
|
| 382 |
+
tests/test_base_config_on_cpu.py
|
| 383 |
+
tests/test_protocol_on_cpu.py
|
| 384 |
+
tests/test_protocol_v2_on_cpu.py
|
| 385 |
+
tests/interactions/__init__.py
|
| 386 |
+
tests/interactions/test_gsm8k_interaction.py
|
| 387 |
+
tests/interactions/test_interaction_registry.py
|
| 388 |
+
tests/single_controller/__init__.py
|
| 389 |
+
tests/single_controller/test_auto_padding_on_cpu.py
|
| 390 |
+
tests/single_controller/test_colocated_workers.py
|
| 391 |
+
tests/single_controller/test_colocated_workers_fused.py
|
| 392 |
+
tests/single_controller/test_data_transfer.py
|
| 393 |
+
tests/single_controller/test_decorator_on_cpu.py
|
| 394 |
+
tests/single_controller/test_device_mesh_register.py
|
| 395 |
+
tests/single_controller/test_driverfunc_to_worker.py
|
| 396 |
+
tests/single_controller/test_fused_workers_on_cpu.py
|
| 397 |
+
tests/single_controller/test_high_level_scheduling_api.py
|
| 398 |
+
tests/single_controller/test_nested_worker.py
|
| 399 |
+
tests/single_controller/test_ray_collectives.py
|
| 400 |
+
tests/single_controller/test_ray_local_envs_on_cpu.py
|
| 401 |
+
tests/single_controller/test_ray_utils_on_cpu.py
|
| 402 |
+
tests/single_controller/test_rvdz.py
|
| 403 |
+
tests/single_controller/test_worker_group_basics.py
|
| 404 |
+
tests/single_controller/test_worker_group_torch.py
|
| 405 |
+
tests/special_e2e/__init__.py
|
| 406 |
+
tests/special_e2e/check_custom_rwd_fn.py
|
| 407 |
+
tests/special_e2e/check_results.py
|
| 408 |
+
tests/special_e2e/envs/__init__.py
|
| 409 |
+
tests/special_e2e/envs/digit_completion/__init__.py
|
| 410 |
+
tests/special_e2e/envs/digit_completion/task.py
|
| 411 |
+
tests/special_e2e/envs/digit_completion/tokenizer.py
|
| 412 |
+
tests/trainer/__init__.py
|
| 413 |
+
tests/trainer/config/__init__.py
|
| 414 |
+
tests/trainer/config/test_algo_config_on_cpu.py
|
| 415 |
+
tests/trainer/config/test_legacy_config_on_cpu.py
|
| 416 |
+
tests/trainer/ppo/__init__.py
|
| 417 |
+
tests/trainer/ppo/test_core_algos_on_cpu.py
|
| 418 |
+
tests/trainer/ppo/test_metric_utils_on_cpu.py
|
| 419 |
+
verl/__init__.py
|
| 420 |
+
verl/base_config.py
|
| 421 |
+
verl/protocol.py
|
| 422 |
+
verl/py.typed
|
| 423 |
+
verl.egg-info/PKG-INFO
|
| 424 |
+
verl.egg-info/SOURCES.txt
|
| 425 |
+
verl.egg-info/dependency_links.txt
|
| 426 |
+
verl.egg-info/requires.txt
|
| 427 |
+
verl.egg-info/top_level.txt
|
| 428 |
+
verl/experimental/__init__.py
|
| 429 |
+
verl/experimental/agent_loop/__init__.py
|
| 430 |
+
verl/experimental/agent_loop/agent_loop.py
|
| 431 |
+
verl/experimental/agent_loop/single_turn_agent_loop.py
|
| 432 |
+
verl/experimental/agent_loop/tool_agent_loop.py
|
| 433 |
+
verl/experimental/agent_loop/tool_parser.py
|
| 434 |
+
verl/experimental/dataset/__init__.py
|
| 435 |
+
verl/experimental/dataset/sampler.py
|
| 436 |
+
verl/experimental/dynamic_dataset/__init__.py
|
| 437 |
+
verl/experimental/dynamic_dataset/dynamicgen_dataset.py
|
| 438 |
+
verl/interactions/__init__.py
|
| 439 |
+
verl/interactions/base.py
|
| 440 |
+
verl/interactions/gsm8k_interaction.py
|
| 441 |
+
verl/interactions/weather_interaction.py
|
| 442 |
+
verl/interactions/utils/__init__.py
|
| 443 |
+
verl/interactions/utils/interaction_registry.py
|
| 444 |
+
verl/model_merger/__init__.py
|
| 445 |
+
verl/model_merger/__main__.py
|
| 446 |
+
verl/model_merger/base_model_merger.py
|
| 447 |
+
verl/model_merger/fsdp_model_merger.py
|
| 448 |
+
verl/model_merger/megatron_model_merger.py
|
| 449 |
+
verl/models/__init__.py
|
| 450 |
+
verl/models/registry.py
|
| 451 |
+
verl/models/weight_loader_registry.py
|
| 452 |
+
verl/models/llama/__init__.py
|
| 453 |
+
verl/models/llama/megatron/__init__.py
|
| 454 |
+
verl/models/llama/megatron/modeling_llama_megatron.py
|
| 455 |
+
verl/models/llama/megatron/checkpoint_utils/__init__.py
|
| 456 |
+
verl/models/llama/megatron/checkpoint_utils/llama_loader.py
|
| 457 |
+
verl/models/llama/megatron/checkpoint_utils/llama_loader_depracated.py
|
| 458 |
+
verl/models/llama/megatron/checkpoint_utils/llama_saver.py
|
| 459 |
+
verl/models/llama/megatron/layers/__init__.py
|
| 460 |
+
verl/models/llama/megatron/layers/parallel_attention.py
|
| 461 |
+
verl/models/llama/megatron/layers/parallel_decoder.py
|
| 462 |
+
verl/models/llama/megatron/layers/parallel_linear.py
|
| 463 |
+
verl/models/llama/megatron/layers/parallel_mlp.py
|
| 464 |
+
verl/models/llama/megatron/layers/parallel_rmsnorm.py
|
| 465 |
+
verl/models/mcore/__init__.py
|
| 466 |
+
verl/models/mcore/config_converter.py
|
| 467 |
+
verl/models/mcore/loader.py
|
| 468 |
+
verl/models/mcore/mbridge.py
|
| 469 |
+
verl/models/mcore/model_forward.py
|
| 470 |
+
verl/models/mcore/model_forward_fused.py
|
| 471 |
+
verl/models/mcore/model_initializer.py
|
| 472 |
+
verl/models/mcore/patch_v012.py
|
| 473 |
+
verl/models/mcore/registry.py
|
| 474 |
+
verl/models/mcore/saver.py
|
| 475 |
+
verl/models/mcore/util.py
|
| 476 |
+
verl/models/mcore/weight_converter.py
|
| 477 |
+
verl/models/mcore/qwen2_5_vl/__init__.py
|
| 478 |
+
verl/models/mcore/qwen2_5_vl/attention.py
|
| 479 |
+
verl/models/mcore/qwen2_5_vl/model.py
|
| 480 |
+
verl/models/mcore/qwen2_5_vl/rope_utils.py
|
| 481 |
+
verl/models/mcore/qwen2_5_vl/vision_config.py
|
| 482 |
+
verl/models/mcore/qwen2_5_vl/vision_model.py
|
| 483 |
+
verl/models/mcore/qwen2_5_vl/vision_transformer_block.py
|
| 484 |
+
verl/models/qwen2/__init__.py
|
| 485 |
+
verl/models/qwen2/megatron/__init__.py
|
| 486 |
+
verl/models/qwen2/megatron/modeling_qwen2_megatron.py
|
| 487 |
+
verl/models/qwen2/megatron/checkpoint_utils/__init__.py
|
| 488 |
+
verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader.py
|
| 489 |
+
verl/models/qwen2/megatron/checkpoint_utils/qwen2_loader_depracated.py
|
| 490 |
+
verl/models/qwen2/megatron/checkpoint_utils/qwen2_saver.py
|
| 491 |
+
verl/models/qwen2/megatron/layers/__init__.py
|
| 492 |
+
verl/models/qwen2/megatron/layers/parallel_attention.py
|
| 493 |
+
verl/models/qwen2/megatron/layers/parallel_decoder.py
|
| 494 |
+
verl/models/qwen2/megatron/layers/parallel_linear.py
|
| 495 |
+
verl/models/qwen2/megatron/layers/parallel_mlp.py
|
| 496 |
+
verl/models/qwen2/megatron/layers/parallel_rmsnorm.py
|
| 497 |
+
verl/models/transformers/__init__.py
|
| 498 |
+
verl/models/transformers/apertus.py
|
| 499 |
+
verl/models/transformers/dense_common.py
|
| 500 |
+
verl/models/transformers/glm4v.py
|
| 501 |
+
verl/models/transformers/kimi_vl.py
|
| 502 |
+
verl/models/transformers/llama.py
|
| 503 |
+
verl/models/transformers/monkey_patch.py
|
| 504 |
+
verl/models/transformers/npu_patch.py
|
| 505 |
+
verl/models/transformers/qwen2.py
|
| 506 |
+
verl/models/transformers/qwen2_vl.py
|
| 507 |
+
verl/models/transformers/qwen3_vl.py
|
| 508 |
+
verl/single_controller/__init__.py
|
| 509 |
+
verl/single_controller/base/__init__.py
|
| 510 |
+
verl/single_controller/base/decorator.py
|
| 511 |
+
verl/single_controller/base/worker.py
|
| 512 |
+
verl/single_controller/base/worker_group.py
|
| 513 |
+
verl/single_controller/ray/__init__.py
|
| 514 |
+
verl/single_controller/ray/base.py
|
| 515 |
+
verl/third_party/__init__.py
|
| 516 |
+
verl/third_party/sglang/__init__.py
|
| 517 |
+
verl/third_party/sglang/parallel_state.py
|
| 518 |
+
verl/third_party/torch/__init__.py
|
| 519 |
+
verl/third_party/torch/distributed/__init__.py
|
| 520 |
+
verl/third_party/torch/distributed/_state_dict_utils.py
|
| 521 |
+
verl/third_party/torch/distributed/checkpoint/__init__.py
|
| 522 |
+
verl/third_party/torch/distributed/checkpoint/state_dict.py
|
| 523 |
+
verl/third_party/vllm/__init__.py
|
| 524 |
+
verl/tools/__init__.py
|
| 525 |
+
verl/tools/base_tool.py
|
| 526 |
+
verl/tools/geo3k_tool.py
|
| 527 |
+
verl/tools/gsm8k_tool.py
|
| 528 |
+
verl/tools/image_zoom_in_tool.py
|
| 529 |
+
verl/tools/mcp_base_tool.py
|
| 530 |
+
verl/tools/mcp_search_tool.py
|
| 531 |
+
verl/tools/sandbox_fusion_tools.py
|
| 532 |
+
verl/tools/schemas.py
|
| 533 |
+
verl/tools/search_tool.py
|
| 534 |
+
verl/tools/utils/__init__.py
|
| 535 |
+
verl/tools/utils/search_r1_like_utils.py
|
| 536 |
+
verl/tools/utils/tool_registry.py
|
| 537 |
+
verl/trainer/__init__.py
|
| 538 |
+
verl/trainer/constants_ppo.py
|
| 539 |
+
verl/trainer/fsdp_sft_trainer.py
|
| 540 |
+
verl/trainer/main_eval.py
|
| 541 |
+
verl/trainer/main_generation.py
|
| 542 |
+
verl/trainer/main_ppo.py
|
| 543 |
+
verl/trainer/sft_trainer.py
|
| 544 |
+
verl/trainer/config/__init__.py
|
| 545 |
+
verl/trainer/config/_generated_ppo_megatron_trainer.yaml
|
| 546 |
+
verl/trainer/config/_generated_ppo_trainer.yaml
|
| 547 |
+
verl/trainer/config/algorithm.py
|
| 548 |
+
verl/trainer/config/config.py
|
| 549 |
+
verl/trainer/config/evaluation.yaml
|
| 550 |
+
verl/trainer/config/generation.yaml
|
| 551 |
+
verl/trainer/config/ppo_megatron_trainer.yaml
|
| 552 |
+
verl/trainer/config/ppo_trainer.yaml
|
| 553 |
+
verl/trainer/config/sft_trainer.yaml
|
| 554 |
+
verl/trainer/config/sft_trainer_engine.yaml
|
| 555 |
+
verl/trainer/config/actor/actor.yaml
|
| 556 |
+
verl/trainer/config/actor/dp_actor.yaml
|
| 557 |
+
verl/trainer/config/actor/megatron_actor.yaml
|
| 558 |
+
verl/trainer/config/critic/critic.yaml
|
| 559 |
+
verl/trainer/config/critic/dp_critic.yaml
|
| 560 |
+
verl/trainer/config/critic/megatron_critic.yaml
|
| 561 |
+
verl/trainer/config/data/legacy_data.yaml
|
| 562 |
+
verl/trainer/config/engine/fsdp.yaml
|
| 563 |
+
verl/trainer/config/engine/megatron.yaml
|
| 564 |
+
verl/trainer/config/model/hf_model.yaml
|
| 565 |
+
verl/trainer/config/npu_profile/npu_profile.yaml
|
| 566 |
+
verl/trainer/config/optim/fsdp.yaml
|
| 567 |
+
verl/trainer/config/optim/megatron.yaml
|
| 568 |
+
verl/trainer/config/ref/dp_ref.yaml
|
| 569 |
+
verl/trainer/config/ref/megatron_ref.yaml
|
| 570 |
+
verl/trainer/config/ref/ref.yaml
|
| 571 |
+
verl/trainer/config/reward_model/dp_reward_model.yaml
|
| 572 |
+
verl/trainer/config/reward_model/megatron_reward_model.yaml
|
| 573 |
+
verl/trainer/config/reward_model/reward_model.yaml
|
| 574 |
+
verl/trainer/config/rollout/rollout.yaml
|
| 575 |
+
verl/trainer/ppo/__init__.py
|
| 576 |
+
verl/trainer/ppo/core_algos.py
|
| 577 |
+
verl/trainer/ppo/metric_utils.py
|
| 578 |
+
verl/trainer/ppo/ray_trainer.py
|
| 579 |
+
verl/trainer/ppo/reward.py
|
| 580 |
+
verl/trainer/ppo/utils.py
|
| 581 |
+
verl/utils/__init__.py
|
| 582 |
+
verl/utils/activation_offload.py
|
| 583 |
+
verl/utils/attention_utils.py
|
| 584 |
+
verl/utils/config.py
|
| 585 |
+
verl/utils/device.py
|
| 586 |
+
verl/utils/distributed.py
|
| 587 |
+
verl/utils/flops_counter.py
|
| 588 |
+
verl/utils/fs.py
|
| 589 |
+
verl/utils/fsdp_utils.py
|
| 590 |
+
verl/utils/groupwise.py
|
| 591 |
+
verl/utils/hdfs_io.py
|
| 592 |
+
verl/utils/import_utils.py
|
| 593 |
+
verl/utils/logging_utils.py
|
| 594 |
+
verl/utils/megatron_utils.py
|
| 595 |
+
verl/utils/memory_buffer.py
|
| 596 |
+
verl/utils/memory_utils.py
|
| 597 |
+
verl/utils/model.py
|
| 598 |
+
verl/utils/net_utils.py
|
| 599 |
+
verl/utils/npu_utils.py
|
| 600 |
+
verl/utils/py_functional.py
|
| 601 |
+
verl/utils/ray_utils.py
|
| 602 |
+
verl/utils/rollout_skip.py
|
| 603 |
+
verl/utils/rollout_trace.py
|
| 604 |
+
verl/utils/seqlen_balancing.py
|
| 605 |
+
verl/utils/tensordict_utils.py
|
| 606 |
+
verl/utils/tokenizer.py
|
| 607 |
+
verl/utils/torch_dtypes.py
|
| 608 |
+
verl/utils/torch_functional.py
|
| 609 |
+
verl/utils/tracking.py
|
| 610 |
+
verl/utils/transformers_compat.py
|
| 611 |
+
verl/utils/ulysses.py
|
| 612 |
+
verl/utils/checkpoint/__init__.py
|
| 613 |
+
verl/utils/checkpoint/checkpoint_handler.py
|
| 614 |
+
verl/utils/checkpoint/checkpoint_manager.py
|
| 615 |
+
verl/utils/checkpoint/fsdp_checkpoint_manager.py
|
| 616 |
+
verl/utils/checkpoint/megatron_checkpoint_manager.py
|
| 617 |
+
verl/utils/dataset/__init__.py
|
| 618 |
+
verl/utils/dataset/dataset_utils.py
|
| 619 |
+
verl/utils/dataset/multiturn_sft_dataset.py
|
| 620 |
+
verl/utils/dataset/rl_dataset.py
|
| 621 |
+
verl/utils/dataset/rm_dataset.py
|
| 622 |
+
verl/utils/dataset/sft_dataset.py
|
| 623 |
+
verl/utils/dataset/vision_utils.py
|
| 624 |
+
verl/utils/debug/__init__.py
|
| 625 |
+
verl/utils/debug/metrics.py
|
| 626 |
+
verl/utils/debug/performance.py
|
| 627 |
+
verl/utils/debug/trajectory_tracker.py
|
| 628 |
+
verl/utils/experimental/__init__.py
|
| 629 |
+
verl/utils/experimental/torch_functional.py
|
| 630 |
+
verl/utils/kernel/__init__.py
|
| 631 |
+
verl/utils/kernel/kernels.py
|
| 632 |
+
verl/utils/kernel/linear_cross_entropy.py
|
| 633 |
+
verl/utils/logger/__init__.py
|
| 634 |
+
verl/utils/logger/aggregate_logger.py
|
| 635 |
+
verl/utils/megatron/__init__.py
|
| 636 |
+
verl/utils/megatron/dist_checkpointing.py
|
| 637 |
+
verl/utils/megatron/memory.py
|
| 638 |
+
verl/utils/megatron/optimizer.py
|
| 639 |
+
verl/utils/megatron/pipeline_parallel.py
|
| 640 |
+
verl/utils/megatron/sequence_parallel.py
|
| 641 |
+
verl/utils/megatron/tensor_parallel.py
|
| 642 |
+
verl/utils/metric/__init__.py
|
| 643 |
+
verl/utils/metric/utils.py
|
| 644 |
+
verl/utils/profiler/__init__.py
|
| 645 |
+
verl/utils/profiler/config.py
|
| 646 |
+
verl/utils/profiler/empty_annotations.py
|
| 647 |
+
verl/utils/profiler/mstx_profile.py
|
| 648 |
+
verl/utils/profiler/nvtx_profile.py
|
| 649 |
+
verl/utils/profiler/performance.py
|
| 650 |
+
verl/utils/profiler/profile.py
|
| 651 |
+
verl/utils/rendezvous/__init__.py
|
| 652 |
+
verl/utils/rendezvous/ray_backend.py
|
| 653 |
+
verl/utils/reward_score/__init__.py
|
| 654 |
+
verl/utils/reward_score/geo3k.py
|
| 655 |
+
verl/utils/reward_score/gsm8k.py
|
| 656 |
+
verl/utils/reward_score/math_batch.py
|
| 657 |
+
verl/utils/reward_score/math_dapo.py
|
| 658 |
+
verl/utils/reward_score/math_reward.py
|
| 659 |
+
verl/utils/reward_score/math_verify.py
|
| 660 |
+
verl/utils/reward_score/search_r1_like_qa_em.py
|
| 661 |
+
verl/utils/reward_score/prime_code/__init__.py
|
| 662 |
+
verl/utils/reward_score/prime_code/testing_util.py
|
| 663 |
+
verl/utils/reward_score/prime_code/utils.py
|
| 664 |
+
verl/utils/reward_score/prime_math/__init__.py
|
| 665 |
+
verl/utils/reward_score/prime_math/grader.py
|
| 666 |
+
verl/utils/reward_score/prime_math/math_normalize.py
|
| 667 |
+
verl/utils/reward_score/sandbox_fusion/__init__.py
|
| 668 |
+
verl/utils/reward_score/sandbox_fusion/utils.py
|
| 669 |
+
verl/utils/vllm/__init__.py
|
| 670 |
+
verl/utils/vllm/patch.py
|
| 671 |
+
verl/utils/vllm/utils.py
|
| 672 |
+
verl/version/version
|
| 673 |
+
verl/workers/__init__.py
|
| 674 |
+
verl/workers/fsdp_workers.py
|
| 675 |
+
verl/workers/megatron_workers.py
|
| 676 |
+
verl/workers/actor/__init__.py
|
| 677 |
+
verl/workers/actor/base.py
|
| 678 |
+
verl/workers/actor/dp_actor.py
|
| 679 |
+
verl/workers/actor/megatron_actor.py
|
| 680 |
+
verl/workers/config/__init__.py
|
| 681 |
+
verl/workers/config/actor.py
|
| 682 |
+
verl/workers/config/critic.py
|
| 683 |
+
verl/workers/config/engine.py
|
| 684 |
+
verl/workers/config/model.py
|
| 685 |
+
verl/workers/config/optimizer.py
|
| 686 |
+
verl/workers/config/reward_model.py
|
| 687 |
+
verl/workers/config/rollout.py
|
| 688 |
+
verl/workers/critic/__init__.py
|
| 689 |
+
verl/workers/critic/base.py
|
| 690 |
+
verl/workers/critic/dp_critic.py
|
| 691 |
+
verl/workers/critic/megatron_critic.py
|
| 692 |
+
verl/workers/engine/__init__.py
|
| 693 |
+
verl/workers/engine/base.py
|
| 694 |
+
verl/workers/engine/utils.py
|
| 695 |
+
verl/workers/engine/fsdp/__init__.py
|
| 696 |
+
verl/workers/engine/fsdp/transformer_impl.py
|
| 697 |
+
verl/workers/engine/fsdp/utils.py
|
| 698 |
+
verl/workers/engine/megatron/__init__.py
|
| 699 |
+
verl/workers/engine/megatron/transformer_impl.py
|
| 700 |
+
verl/workers/engine/megatron/utils.py
|
| 701 |
+
verl/workers/engine/mindspeed/__init__.py
|
| 702 |
+
verl/workers/engine/mindspeed/transformer_impl.py
|
| 703 |
+
verl/workers/reward_manager/__init__.py
|
| 704 |
+
verl/workers/reward_manager/abstract.py
|
| 705 |
+
verl/workers/reward_manager/batch.py
|
| 706 |
+
verl/workers/reward_manager/dapo.py
|
| 707 |
+
verl/workers/reward_manager/naive.py
|
| 708 |
+
verl/workers/reward_manager/prime.py
|
| 709 |
+
verl/workers/reward_manager/registry.py
|
| 710 |
+
verl/workers/reward_model/__init__.py
|
| 711 |
+
verl/workers/reward_model/base.py
|
| 712 |
+
verl/workers/reward_model/megatron/__init__.py
|
| 713 |
+
verl/workers/reward_model/megatron/reward_model.py
|
| 714 |
+
verl/workers/roles/__init__.py
|
| 715 |
+
verl/workers/roles/actor.py
|
| 716 |
+
verl/workers/roles/critic.py
|
| 717 |
+
verl/workers/roles/hybrid_engine.py
|
| 718 |
+
verl/workers/roles/reward_model.py
|
| 719 |
+
verl/workers/roles/reward_model_engine/__init__.py
|
| 720 |
+
verl/workers/roles/reward_model_engine/base.py
|
| 721 |
+
verl/workers/roles/reward_model_engine/sglang_reward_model.py
|
| 722 |
+
verl/workers/roles/utils/__init__.py
|
| 723 |
+
verl/workers/roles/utils/losses.py
|
| 724 |
+
verl/workers/rollout/__init__.py
|
| 725 |
+
verl/workers/rollout/base.py
|
| 726 |
+
verl/workers/rollout/hf_rollout.py
|
| 727 |
+
verl/workers/rollout/replica.py
|
| 728 |
+
verl/workers/rollout/schemas.py
|
| 729 |
+
verl/workers/rollout/tokenizer.py
|
| 730 |
+
verl/workers/rollout/utils.py
|
| 731 |
+
verl/workers/rollout/naive/__init__.py
|
| 732 |
+
verl/workers/rollout/naive/naive_rollout.py
|
| 733 |
+
verl/workers/rollout/sglang_rollout/__init__.py
|
| 734 |
+
verl/workers/rollout/sglang_rollout/async_sglang_server.py
|
| 735 |
+
verl/workers/rollout/sglang_rollout/http_server_engine.py
|
| 736 |
+
verl/workers/rollout/sglang_rollout/sglang_rollout.py
|
| 737 |
+
verl/workers/rollout/sglang_rollout/utils.py
|
| 738 |
+
verl/workers/rollout/vllm_rollout/__init__.py
|
| 739 |
+
verl/workers/rollout/vllm_rollout/vllm_async_server.py
|
| 740 |
+
verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py
|
| 741 |
+
verl/workers/sharding_manager/__init__.py
|
| 742 |
+
verl/workers/sharding_manager/base.py
|
| 743 |
+
verl/workers/sharding_manager/fsdp_sglang.py
|
| 744 |
+
verl/workers/sharding_manager/fsdp_ulysses.py
|
| 745 |
+
verl/workers/sharding_manager/fsdp_vllm.py
|
| 746 |
+
verl/workers/sharding_manager/megatron_sglang.py
|
| 747 |
+
verl/workers/sharding_manager/megatron_vllm.py
|
verl/verl.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
verl/verl.egg-info/requires.txt
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
accelerate
|
| 2 |
+
codetiming
|
| 3 |
+
datasets
|
| 4 |
+
dill
|
| 5 |
+
hydra-core
|
| 6 |
+
numpy<2.0.0
|
| 7 |
+
pandas
|
| 8 |
+
peft
|
| 9 |
+
pyarrow>=19.0.0
|
| 10 |
+
pybind11
|
| 11 |
+
pylatexenc
|
| 12 |
+
ray[default]>=2.41.0
|
| 13 |
+
torchdata
|
| 14 |
+
tensordict!=0.9.0,<=0.10.0,>=0.8.0
|
| 15 |
+
transformers
|
| 16 |
+
wandb
|
| 17 |
+
packaging>=20.0
|
| 18 |
+
tensorboard
|
| 19 |
+
|
| 20 |
+
[geo]
|
| 21 |
+
mathruler
|
| 22 |
+
torchvision
|
| 23 |
+
qwen_vl_utils
|
| 24 |
+
|
| 25 |
+
[gpu]
|
| 26 |
+
liger-kernel
|
| 27 |
+
flash-attn
|
| 28 |
+
|
| 29 |
+
[math]
|
| 30 |
+
math-verify
|
| 31 |
+
|
| 32 |
+
[mcore]
|
| 33 |
+
mbridge
|
| 34 |
+
|
| 35 |
+
[prime]
|
| 36 |
+
pyext
|
| 37 |
+
|
| 38 |
+
[sglang]
|
| 39 |
+
tensordict!=0.9.0,<=0.10.0,>=0.8.0
|
| 40 |
+
sglang[openai,srt]==0.5.2
|
| 41 |
+
torch==2.8.0
|
| 42 |
+
|
| 43 |
+
[test]
|
| 44 |
+
pytest
|
| 45 |
+
pre-commit
|
| 46 |
+
py-spy
|
| 47 |
+
pytest-asyncio
|
| 48 |
+
|
| 49 |
+
[trl]
|
| 50 |
+
trl<=0.9.6
|
| 51 |
+
|
| 52 |
+
[vllm]
|
| 53 |
+
tensordict!=0.9.0,<=0.10.0,>=0.8.0
|
| 54 |
+
vllm<=0.9.1,>=0.7.3
|
verl/verl.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
scripts
|
| 2 |
+
tests
|
| 3 |
+
verl
|
verl/verl/utils/checkpoint/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .checkpoint_handler import CheckpointHandler
|
| 16 |
+
|
| 17 |
+
__all__ = ["CheckpointHandler"]
|
verl/verl/utils/checkpoint/checkpoint_handler.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# TODO: add unit tests
|
| 17 |
+
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
|
| 24 |
+
import verl.utils.hdfs_io as hdfs_io
|
| 25 |
+
from verl.utils.checkpoint.checkpoint_manager import find_latest_ckpt_path, get_checkpoint_tracker_filename
|
| 26 |
+
from verl.utils.logger import log_with_rank
|
| 27 |
+
from verl.workers.engine import BaseEngine
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def extract_step(path):
|
| 31 |
+
match = re.search(r"global_step_(\d+)", path)
|
| 32 |
+
if match:
|
| 33 |
+
return int(match.group(1))
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
logger = logging.getLogger(__file__)
|
| 38 |
+
logger.setLevel(os.getenv("VERL_SFT_LOGGING_LEVEL", "WARN"))
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CheckpointHandler:
|
| 42 |
+
"""
|
| 43 |
+
Checkpoint handler handles the path, global_step of a checkpoint folder.
|
| 44 |
+
Currently, it only works with a single model.
|
| 45 |
+
We can expand it to support multiple models. It is expected to be used with SPMD style (e.g., torchrun)
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
engine: BaseEngine,
|
| 51 |
+
train_dataloader,
|
| 52 |
+
*,
|
| 53 |
+
default_local_dir,
|
| 54 |
+
max_ckpt_to_keep=None,
|
| 55 |
+
default_hdfs_dir=None,
|
| 56 |
+
resume_mode="auto",
|
| 57 |
+
resume_from_path=None,
|
| 58 |
+
):
|
| 59 |
+
self.default_local_dir = default_local_dir
|
| 60 |
+
self.max_ckpt_to_keep = max_ckpt_to_keep
|
| 61 |
+
self.default_hdfs_dir = default_hdfs_dir
|
| 62 |
+
self.resume_mode = resume_mode
|
| 63 |
+
self.resume_from_path = resume_from_path
|
| 64 |
+
self.engine = engine
|
| 65 |
+
self.train_dataloader = train_dataloader
|
| 66 |
+
self.rank = torch.distributed.get_rank()
|
| 67 |
+
|
| 68 |
+
def save_checkpoint(self, step):
|
| 69 |
+
"""Save checkpoint using FSDPCheckpointManager with improved tracking"""
|
| 70 |
+
from verl.utils.fs import local_mkdir_safe
|
| 71 |
+
|
| 72 |
+
# Determine checkpoint path
|
| 73 |
+
local_global_step_folder = os.path.join(self.default_local_dir, f"global_step_{step}")
|
| 74 |
+
if self.rank == 0:
|
| 75 |
+
print(f"Saving checkpoint to: {local_global_step_folder}")
|
| 76 |
+
|
| 77 |
+
# Get max checkpoints to keep
|
| 78 |
+
max_ckpt_to_keep = self.max_ckpt_to_keep
|
| 79 |
+
|
| 80 |
+
# Use checkpoint manager to save
|
| 81 |
+
self.engine.save_checkpoint(
|
| 82 |
+
local_path=local_global_step_folder, global_step=step, max_ckpt_to_keep=max_ckpt_to_keep
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Save dataloader state. Note that we only save the iterator in the train_dataloader.
|
| 86 |
+
# So it's identical in each dp rank.
|
| 87 |
+
if self.engine.is_mp_src_rank_with_outputs():
|
| 88 |
+
dp_rank = self.engine.get_data_parallel_rank()
|
| 89 |
+
local_mkdir_safe(local_global_step_folder)
|
| 90 |
+
dataloader_local_path = os.path.join(local_global_step_folder, f"data_{dp_rank}.pt")
|
| 91 |
+
|
| 92 |
+
# Use StatefulDataLoader's built-in state dict functionality
|
| 93 |
+
dataloader_state_dict = self.train_dataloader.state_dict()
|
| 94 |
+
torch.save(dataloader_state_dict, dataloader_local_path)
|
| 95 |
+
print(f"Saved dataloader state to: {dataloader_local_path}")
|
| 96 |
+
|
| 97 |
+
if self.rank == 0:
|
| 98 |
+
# Update latest checkpoint tracker (atomic write)
|
| 99 |
+
tracker_file = get_checkpoint_tracker_filename(self.default_local_dir)
|
| 100 |
+
temp_tracker_file = tracker_file + ".tmp"
|
| 101 |
+
with open(temp_tracker_file, "w") as f:
|
| 102 |
+
f.write(str(step))
|
| 103 |
+
os.rename(temp_tracker_file, tracker_file)
|
| 104 |
+
print(f"Updated checkpoint tracker: {tracker_file}")
|
| 105 |
+
|
| 106 |
+
# Copy to HDFS if configured
|
| 107 |
+
if self.rank == 0 and self.default_hdfs_dir:
|
| 108 |
+
hdfs_io.makedirs(self.default_hdfs_dir, exist_ok=True)
|
| 109 |
+
hdfs_io.copy(src=local_global_step_folder, dst=self.default_hdfs_dir, dirs_exist_ok=True)
|
| 110 |
+
|
| 111 |
+
torch.distributed.barrier()
|
| 112 |
+
|
| 113 |
+
def load_checkpoint(self):
|
| 114 |
+
# Determine resume path based on configuration
|
| 115 |
+
checkpoint_path = self._determine_resume_path()
|
| 116 |
+
|
| 117 |
+
if checkpoint_path is None:
|
| 118 |
+
return 0
|
| 119 |
+
|
| 120 |
+
# extract resume step from checkpoint path
|
| 121 |
+
resume_step = extract_step(checkpoint_path)
|
| 122 |
+
if resume_step is None:
|
| 123 |
+
log_with_rank(
|
| 124 |
+
f"Warning: Could not extract step number from {checkpoint_path}, starting from step 0",
|
| 125 |
+
logger=logger,
|
| 126 |
+
rank=self.rank,
|
| 127 |
+
level=logging.WARNING,
|
| 128 |
+
log_only_rank_0=True,
|
| 129 |
+
)
|
| 130 |
+
return 0
|
| 131 |
+
self.resume_global_step = resume_step
|
| 132 |
+
|
| 133 |
+
# Use checkpoint manager to load model state
|
| 134 |
+
self.engine.load_checkpoint(checkpoint_path)
|
| 135 |
+
# Always load dataloader state for StatefulDataLoader
|
| 136 |
+
self._load_dataloader_state(checkpoint_path)
|
| 137 |
+
|
| 138 |
+
return resume_step
|
| 139 |
+
|
| 140 |
+
def _load_dataloader_state(self, checkpoint_path: str):
|
| 141 |
+
"""Load dataloader state from checkpoint"""
|
| 142 |
+
dp_rank = self.engine.get_data_parallel_rank()
|
| 143 |
+
dataloader_path = os.path.join(checkpoint_path, f"data_{dp_rank}.pt")
|
| 144 |
+
|
| 145 |
+
if os.path.exists(dataloader_path):
|
| 146 |
+
# Use StatefulDataLoader's built-in state dict functionality
|
| 147 |
+
dataloader_state_dict = torch.load(dataloader_path, map_location="cpu", weights_only=False)
|
| 148 |
+
self.train_dataloader.load_state_dict(dataloader_state_dict)
|
| 149 |
+
|
| 150 |
+
log_with_rank(
|
| 151 |
+
f"Successfully loaded dataloader state from {dataloader_path}",
|
| 152 |
+
logger=logger,
|
| 153 |
+
rank=self.rank,
|
| 154 |
+
log_only_rank_0=True,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
else:
|
| 158 |
+
log_with_rank(
|
| 159 |
+
f"Warning: No dataloader state found at {dataloader_path}, will start from scratch",
|
| 160 |
+
logger=logger,
|
| 161 |
+
rank=self.rank,
|
| 162 |
+
level=logging.WARNING,
|
| 163 |
+
log_only_rank_0=True,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
def _determine_resume_path(self):
|
| 167 |
+
"""Determine the path to resume from based on resume_mode configuration"""
|
| 168 |
+
resume_mode = self.resume_mode
|
| 169 |
+
resume_from_path = self.resume_from_path
|
| 170 |
+
|
| 171 |
+
if resume_mode == "disable":
|
| 172 |
+
return None
|
| 173 |
+
elif resume_mode == "auto":
|
| 174 |
+
if resume_from_path is not None:
|
| 175 |
+
assert os.path.exists(resume_from_path), (
|
| 176 |
+
"resume_from_path must be null or an existing path when resume_mode is 'auto'"
|
| 177 |
+
)
|
| 178 |
+
assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps"
|
| 179 |
+
return resume_from_path
|
| 180 |
+
# Try to find the latest checkpoint in the default directory
|
| 181 |
+
return self._find_latest_checkpoint()
|
| 182 |
+
elif resume_mode == "resume_path":
|
| 183 |
+
assert os.path.exists(resume_from_path), (
|
| 184 |
+
"resume_from_path must be an existing path when resume_mode is 'resume_path'"
|
| 185 |
+
)
|
| 186 |
+
assert "global_step_" in resume_from_path, "resume_from_path must specify the global_steps"
|
| 187 |
+
return resume_from_path
|
| 188 |
+
else:
|
| 189 |
+
raise ValueError(f"Invalid resume_mode: {resume_mode}. Must be 'auto', 'disable', or 'resume_path'")
|
| 190 |
+
|
| 191 |
+
def _find_latest_checkpoint(self):
|
| 192 |
+
"""Find the latest checkpoint in the default local directory"""
|
| 193 |
+
checkpoint_dir = self.default_local_dir
|
| 194 |
+
|
| 195 |
+
if not os.path.exists(checkpoint_dir):
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
latest_checkpoint = find_latest_ckpt_path(checkpoint_dir)
|
| 199 |
+
|
| 200 |
+
if latest_checkpoint and self.rank == 0:
|
| 201 |
+
step_num = ext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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import random
|
| 17 |
+
import shutil
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import torch.distributed
|
| 22 |
+
from omegaconf import DictConfig
|
| 23 |
+
from transformers import PreTrainedTokenizer, ProcessorMixin
|
| 24 |
+
|
| 25 |
+
from verl.trainer.config import CheckpointConfig
|
| 26 |
+
from verl.utils.device import get_device_name, get_torch_device
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class BaseCheckpointManager:
|
| 30 |
+
"""
|
| 31 |
+
A checkpoint manager that saves and loads the following states in a SPMD way:
|
| 32 |
+
- model
|
| 33 |
+
- optimizer
|
| 34 |
+
- lr_scheduler
|
| 35 |
+
- extra_states
|
| 36 |
+
|
| 37 |
+
We save
|
| 38 |
+
- sharded model states and optimizer states
|
| 39 |
+
- full lr_scheduler states
|
| 40 |
+
- huggingface tokenizer and config for ckpt merge
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
model,
|
| 46 |
+
optimizer: torch.optim.Optimizer,
|
| 47 |
+
lr_scheduler: torch.optim.lr_scheduler.LRScheduler = None,
|
| 48 |
+
processing_class: PreTrainedTokenizer | ProcessorMixin = None,
|
| 49 |
+
checkpoint_config: DictConfig | CheckpointConfig = None,
|
| 50 |
+
):
|
| 51 |
+
self.checkpoint_config = checkpoint_config
|
| 52 |
+
checkpoint_load_contents = checkpoint_config.get("load_contents", None) if checkpoint_config else None
|
| 53 |
+
checkpoint_save_contents = checkpoint_config.get("save_contents", None) if checkpoint_config else None
|
| 54 |
+
if checkpoint_load_contents is None:
|
| 55 |
+
checkpoint_load_contents = ["model", "optimizer", "extra"]
|
| 56 |
+
if checkpoint_save_contents is None:
|
| 57 |
+
checkpoint_save_contents = ["model", "optimizer", "extra"]
|
| 58 |
+
self.previous_global_step = None
|
| 59 |
+
self.previous_saved_paths = []
|
| 60 |
+
|
| 61 |
+
self.model = model
|
| 62 |
+
self.optimizer = optimizer
|
| 63 |
+
self.lr_scheduler = lr_scheduler
|
| 64 |
+
self.processing_class = processing_class
|
| 65 |
+
self.checkpoint_load_contents = checkpoint_load_contents
|
| 66 |
+
self.checkpoint_save_contents = checkpoint_save_contents
|
| 67 |
+
|
| 68 |
+
self.rank = torch.distributed.get_rank()
|
| 69 |
+
self.world_size = torch.distributed.get_world_size()
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def should_save_model(self) -> bool:
|
| 73 |
+
"""
|
| 74 |
+
Returns True if 'model' is in checkpoint_save_contents, indicating the model state should be saved.
|
| 75 |
+
"""
|
| 76 |
+
return "model" in self.checkpoint_save_contents
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def should_save_optimizer(self) -> bool:
|
| 80 |
+
"""
|
| 81 |
+
Returns True if 'optimizer' is in checkpoint_save_contents, indicating the optimizer state should be saved.
|
| 82 |
+
"""
|
| 83 |
+
return "optimizer" in self.checkpoint_save_contents
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def should_save_extra(self) -> bool:
|
| 87 |
+
"""
|
| 88 |
+
Returns True if 'extra' is in checkpoint_save_contents, indicating the extra state should be saved.
|
| 89 |
+
"""
|
| 90 |
+
return "extra" in self.checkpoint_save_contents
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def should_save_hf_model(self) -> bool:
|
| 94 |
+
"""
|
| 95 |
+
Returns True if 'hf_model' is in checkpoint_save_contents, indicating the model should be converted to hf
|
| 96 |
+
model and saved.
|
| 97 |
+
"""
|
| 98 |
+
return "hf_model" in self.checkpoint_save_contents
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def should_load_model(self) -> bool:
|
| 102 |
+
"""
|
| 103 |
+
Returns True if 'model' is in checkpoint_load_contents, indicating the model state should be loaded.
|
| 104 |
+
"""
|
| 105 |
+
return "model" in self.checkpoint_load_contents
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def should_load_optimizer(self) -> bool:
|
| 109 |
+
"""
|
| 110 |
+
Returns True if 'optimizer' is in checkpoint_load_contents, indicating the optimizer state should be loaded.
|
| 111 |
+
"""
|
| 112 |
+
return "optimizer" in self.checkpoint_load_contents
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def should_load_extra(self) -> bool:
|
| 116 |
+
"""
|
| 117 |
+
Returns True if 'extra' is in checkpoint_load_contents, indicating the extra state should be loaded.
|
| 118 |
+
"""
|
| 119 |
+
return "extra" in self.checkpoint_load_contents
|
| 120 |
+
|
| 121 |
+
def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load: bool = False):
|
| 122 |
+
raise NotImplementedError
|
| 123 |
+
|
| 124 |
+
def save_checkpoint(
|
| 125 |
+
self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep: int = None
|
| 126 |
+
):
|
| 127 |
+
raise NotImplementedError
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def checkpath(local_path: str, hdfs_path: str):
|
| 131 |
+
assert local_path is not None or hdfs_path is not None, "local_path and hdfs_path cannot be both None"
|
| 132 |
+
return local_path is not None, local_path if local_path is not None else hdfs_path
|
| 133 |
+
|
| 134 |
+
def remove_previous_save_local_path(self, path):
|
| 135 |
+
if isinstance(path, str):
|
| 136 |
+
path = [path]
|
| 137 |
+
for p in path:
|
| 138 |
+
abs_path = os.path.abspath(p)
|
| 139 |
+
print(f"Checkpoint manager remove previous save local path: {abs_path}")
|
| 140 |
+
if not os.path.exists(abs_path):
|
| 141 |
+
continue
|
| 142 |
+
shutil.rmtree(abs_path, ignore_errors=True)
|
| 143 |
+
|
| 144 |
+
@staticmethod
|
| 145 |
+
def get_rng_state():
|
| 146 |
+
rng_state = {
|
| 147 |
+
"cpu": torch.get_rng_state(),
|
| 148 |
+
"numpy": np.random.get_state(),
|
| 149 |
+
"random": random.getstate(),
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
if get_device_name() != "cpu":
|
| 153 |
+
rng_state[get_device_name()] = get_torch_device().get_rng_state()
|
| 154 |
+
|
| 155 |
+
return rng_state
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def load_rng_state(rng_state):
|
| 159 |
+
torch.set_rng_state(rng_state["cpu"])
|
| 160 |
+
np.random.set_state(rng_state["numpy"])
|
| 161 |
+
random.setstate(rng_state["random"])
|
| 162 |
+
|
| 163 |
+
if get_device_name() != "cpu":
|
| 164 |
+
get_torch_device().set_rng_state(rng_state[get_device_name()])
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def find_latest_ckpt_path(path, directory_format="global_step_{}"):
|
| 168 |
+
"""
|
| 169 |
+
Return the most recent checkpoint directory based on a tracker file.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
path (str): Base directory containing the checkpoint tracker.
|
| 173 |
+
directory_format (str): Template for checkpoint subfolders with one
|
| 174 |
+
placeholder for the iteration number (default "global_step_{}").
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
str or None: Full path to the latest checkpoint directory, or
|
| 178 |
+
None if the tracker or checkpoint folder is missing.
|
| 179 |
+
"""
|
| 180 |
+
if path is None:
|
| 181 |
+
return None
|
| 182 |
+
|
| 183 |
+
tracker_file = get_checkpoint_tracker_filename(path)
|
| 184 |
+
if not os.path.exists(tracker_file):
|
| 185 |
+
print(f"Checkpoint tracker file does not exist: {tracker_file}")
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
with open(tracker_file, "rb") as f:
|
| 189 |
+
iteration = int(f.read().decode())
|
| 190 |
+
ckpt_path = os.path.join(path, directory_format.format(iteration))
|
| 191 |
+
if not os.path.exists(ckpt_path):
|
| 192 |
+
print("Checkpoint does not exist: %s", ckpt_path)
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
print("Found checkpoint: %s", ckpt_path)
|
| 196 |
+
return ckpt_path
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def get_checkpoint_tracker_filename(root_path: str):
|
| 200 |
+
"""
|
| 201 |
+
Tracker file rescords the latest chckpoint during training to restart from.
|
| 202 |
+
"""
|
| 203 |
+
return os.path.join(root_path, "latest_checkpointed_iteration.txt")
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def should_save_ckpt_esi(max_steps_duration: float, save_ckpt_duration: float = 60, redundant_time: float = 0) -> bool:
|
| 207 |
+
"""
|
| 208 |
+
Determine if checkpoint should be saved based on capacity esi expiration.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
max_steps_duration: Max estimated time (seconds) required to complete one training step
|
| 212 |
+
save_ckpt_duration: Estimated time (seconds) required to save checkpoint (default: 60)
|
| 213 |
+
redundant_time: Additional buffer time (seconds) for unexpected delays (default: 0)
|
| 214 |
+
"""
|
| 215 |
+
exp_ts_mlp = os.getenv("MLP_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP") # vemlp
|
| 216 |
+
exp_ts_aws = os.getenv("SAGEMAKER_CURRENT_CAPACITY_BLOCK_EXPIRATION_TIMESTAMP") # aws
|
| 217 |
+
if exp_ts_mlp:
|
| 218 |
+
try:
|
| 219 |
+
import time
|
| 220 |
+
|
| 221 |
+
remaining = float(exp_ts_mlp) - time.time()
|
| 222 |
+
except ValueError:
|
| 223 |
+
return False
|
| 224 |
+
return (
|
| 225 |
+
remaining > 0
|
| 226 |
+
and max_steps_duration > 0
|
| 227 |
+
and remaining <= save_ckpt_duration + max_steps_duration + redundant_time
|
| 228 |
+
)
|
| 229 |
+
elif exp_ts_aws:
|
| 230 |
+
from datetime import datetime, timedelta
|
| 231 |
+
|
| 232 |
+
expiration_time = datetime.fromtimestamp(int(exp_ts_aws))
|
| 233 |
+
time_difference = expiration_time - datetime.now()
|
| 234 |
+
threshold_minutes = (save_ckpt_duration + max_steps_duration + redundant_time) / 60
|
| 235 |
+
return time_difference < timedelta(minutes=threshold_minutes)
|
| 236 |
+
else:
|
| 237 |
+
return False
|
verl/verl/utils/checkpoint/fsdp_checkpoint_manager.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import logging
|
| 17 |
+
import os
|
| 18 |
+
import warnings
|
| 19 |
+
from dataclasses import asdict, dataclass
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.distributed
|
| 24 |
+
from accelerate import init_empty_weights
|
| 25 |
+
from omegaconf import DictConfig
|
| 26 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 27 |
+
from torch.distributed.fsdp import ShardedOptimStateDictConfig, ShardedStateDictConfig, StateDictType
|
| 28 |
+
from transformers import GenerationConfig, PreTrainedTokenizer, ProcessorMixin
|
| 29 |
+
from transformers.dynamic_module_utils import custom_object_save
|
| 30 |
+
|
| 31 |
+
from verl.utils.device import is_cuda_available
|
| 32 |
+
from verl.utils.fs import copy_to_local, is_non_local, local_mkdir_safe
|
| 33 |
+
from verl.utils.fsdp_utils import fsdp_version, get_fsdp_full_state_dict, get_fsdp_state_ctx
|
| 34 |
+
from verl.utils.logger import log_with_rank
|
| 35 |
+
|
| 36 |
+
from .checkpoint_manager import BaseCheckpointManager
|
| 37 |
+
|
| 38 |
+
# Setup logging
|
| 39 |
+
logger = logging.getLogger(__file__)
|
| 40 |
+
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO"))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class FSDPConfig:
|
| 45 |
+
"""Configuration for FSDP checkpointing.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
FSDP_version (int): Version of FSDP being used.
|
| 49 |
+
world_size (int): Number of processes in the distributed training setup.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
FSDP_version: int
|
| 53 |
+
world_size: int
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class FSDPCheckpointManager(BaseCheckpointManager):
|
| 57 |
+
"""
|
| 58 |
+
Manage FSDP checkpointing in SPMD training.
|
| 59 |
+
|
| 60 |
+
- Saves/loads per-rank sharded model & optimizer states
|
| 61 |
+
- Persists full lr_scheduler and RNG state
|
| 62 |
+
- Stores HF tokenizer/processor and model/config for unified restore
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
model (FSDP): Wrapped model instance.
|
| 66 |
+
optimizer (Optimizer): Training optimizer.
|
| 67 |
+
lr_scheduler (LRScheduler): Learning-rate scheduler.
|
| 68 |
+
processing_class (PreTrainedTokenizer or ProcessorMixin, optional):
|
| 69 |
+
Pre-/post-processing artifact handler.
|
| 70 |
+
checkpoint_contents DictConfig: Configuration for checkpoint contents.
|
| 71 |
+
- 'load': Components to load; must contain 'model'. Defaults to ['model', 'optimizer', 'extra'].
|
| 72 |
+
- 'save': Components to save; must contain 'model'. Defaults to ['model', 'optimizer', 'extra'].
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
model: FSDP,
|
| 78 |
+
optimizer: Optional[torch.optim.Optimizer] = None,
|
| 79 |
+
lr_scheduler: Optional[torch.optim.lr_scheduler.LRScheduler] = None,
|
| 80 |
+
processing_class: PreTrainedTokenizer | ProcessorMixin = None,
|
| 81 |
+
checkpoint_config: DictConfig = None,
|
| 82 |
+
**kwargs,
|
| 83 |
+
):
|
| 84 |
+
if processing_class is None and "tokenizer" in kwargs:
|
| 85 |
+
warnings.warn(
|
| 86 |
+
"`tokenizer` is deprecated. use `processing_class` instead.", DeprecationWarning, stacklevel=2
|
| 87 |
+
)
|
| 88 |
+
processing_class = kwargs.pop("tokenizer")
|
| 89 |
+
|
| 90 |
+
super().__init__(
|
| 91 |
+
model,
|
| 92 |
+
optimizer,
|
| 93 |
+
lr_scheduler=lr_scheduler,
|
| 94 |
+
processing_class=processing_class,
|
| 95 |
+
checkpoint_config=checkpoint_config,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load=False):
|
| 99 |
+
"""
|
| 100 |
+
Load an FSDP checkpoint for this rank.
|
| 101 |
+
|
| 102 |
+
Downloads and loads:
|
| 103 |
+
- model and optimizer shards
|
| 104 |
+
- extra state dict (scheduler + RNG)
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
local_path: Directory with per-rank checkpoint files.
|
| 108 |
+
hdfs_path: Unused (for API compatibility).
|
| 109 |
+
del_local_after_load: Remove local files after loading.
|
| 110 |
+
"""
|
| 111 |
+
if local_path is None:
|
| 112 |
+
return
|
| 113 |
+
|
| 114 |
+
# check if the checkpoint_load_contents is valid
|
| 115 |
+
if self.should_load_model:
|
| 116 |
+
assert self.model is not None, "model must be provided when checkpoint_contents.load includes ['model']"
|
| 117 |
+
if self.should_load_optimizer:
|
| 118 |
+
assert self.optimizer is not None, (
|
| 119 |
+
"optimizer must be provided when checkpoint_contents.load includes ['optimizer']"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# every rank download its own checkpoint
|
| 123 |
+
state_dict_cfg = (
|
| 124 |
+
ShardedStateDictConfig(offload_to_cpu=True if is_cuda_available else False)
|
| 125 |
+
if self.should_load_model
|
| 126 |
+
else None
|
| 127 |
+
)
|
| 128 |
+
optim_cfg = (
|
| 129 |
+
ShardedOptimStateDictConfig(offload_to_cpu=True if is_cuda_available else False)
|
| 130 |
+
if self.should_load_optimizer
|
| 131 |
+
else None
|
| 132 |
+
)
|
| 133 |
+
with get_fsdp_state_ctx(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg):
|
| 134 |
+
if self.should_load_model:
|
| 135 |
+
remote_model_path = os.path.join(local_path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt")
|
| 136 |
+
local_model_path = copy_to_local(remote_model_path)
|
| 137 |
+
model_state_dict = torch.load(local_model_path, weights_only=False)
|
| 138 |
+
self.model.load_state_dict(model_state_dict)
|
| 139 |
+
log_with_rank(f"Loaded model from {remote_model_path}", rank=self.rank, logger=logger)
|
| 140 |
+
|
| 141 |
+
if self.should_load_optimizer:
|
| 142 |
+
remote_optim_path = os.path.join(local_path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt")
|
| 143 |
+
local_optim_path = copy_to_local(remote_optim_path)
|
| 144 |
+
optimizer_state_dict = torch.load(local_optim_path, weights_only=False)
|
| 145 |
+
self.optimizer.load_state_dict(optimizer_state_dict)
|
| 146 |
+
log_with_rank(f"Loaded optimizer from {remote_optim_path}", rank=self.rank, logger=logger)
|
| 147 |
+
|
| 148 |
+
if self.should_load_extra:
|
| 149 |
+
remote_extra_state_path = os.path.join(
|
| 150 |
+
local_path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt"
|
| 151 |
+
)
|
| 152 |
+
local_extra_state_path = copy_to_local(remote_extra_state_path)
|
| 153 |
+
extra_state_dict = torch.load(local_extra_state_path, weights_only=False)
|
| 154 |
+
# recover random state
|
| 155 |
+
if "rng" in extra_state_dict:
|
| 156 |
+
# 'rng' may not exist for backward compatibility
|
| 157 |
+
self.load_rng_state(extra_state_dict["rng"])
|
| 158 |
+
log_with_rank(f"Loaded rng from {remote_extra_state_path}", rank=self.rank, logger=logger)
|
| 159 |
+
|
| 160 |
+
lr_scheduler_state_dict = extra_state_dict["lr_scheduler"]
|
| 161 |
+
if lr_scheduler_state_dict is not None and self.lr_scheduler is not None:
|
| 162 |
+
self.lr_scheduler.load_state_dict(lr_scheduler_state_dict)
|
| 163 |
+
log_with_rank(f"Loaded lr_scheduler from {remote_extra_state_path}", rank=self.rank, logger=logger)
|
| 164 |
+
|
| 165 |
+
if self.rank == 0 and del_local_after_load:
|
| 166 |
+
try:
|
| 167 |
+
os.remove(local_model_path) if is_non_local(local_model_path) else None
|
| 168 |
+
os.remove(local_optim_path) if is_non_local(local_optim_path) else None
|
| 169 |
+
os.remove(local_extra_state_path) if is_non_local(local_extra_state_path) else None
|
| 170 |
+
except Exception as e:
|
| 171 |
+
log_with_rank(
|
| 172 |
+
f"remove local resume ckpt file after loading failed, exception {e} will be ignored",
|
| 173 |
+
rank=self.rank,
|
| 174 |
+
logger=logger,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# wait for everyone to load checkpoints
|
| 178 |
+
torch.distributed.barrier()
|
| 179 |
+
|
| 180 |
+
def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep=None):
|
| 181 |
+
"""
|
| 182 |
+
Save an FSDP checkpoint for this rank.
|
| 183 |
+
|
| 184 |
+
Writes:
|
| 185 |
+
- model & optimizer shard files
|
| 186 |
+
- extra state dict (scheduler + RNG)
|
| 187 |
+
- HF tokenizer/processor and model/config on rank 0
|
| 188 |
+
- optional full HF model under 'huggingface/' if requested
|
| 189 |
+
|
| 190 |
+
Rotates old checkpoints, keeping at most `max_ckpt_to_keep`.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
local_path: Target directory for checkpoint files.
|
| 194 |
+
hdfs_path: Unused (for API compatibility).
|
| 195 |
+
global_step: Current training step (used for bookkeeping).
|
| 196 |
+
max_ckpt_to_keep: Number of recent checkpoints to retain.
|
| 197 |
+
"""
|
| 198 |
+
if local_path is None:
|
| 199 |
+
return
|
| 200 |
+
|
| 201 |
+
# record the previous global step
|
| 202 |
+
self.previous_global_step = global_step
|
| 203 |
+
|
| 204 |
+
# remove previous local_path, only rank 0 should do this
|
| 205 |
+
if (
|
| 206 |
+
self.rank == 0
|
| 207 |
+
and max_ckpt_to_keep
|
| 208 |
+
and isinstance(max_ckpt_to_keep, int)
|
| 209 |
+
and max_ckpt_to_keep > 0
|
| 210 |
+
and len(self.previous_saved_paths) >= max_ckpt_to_keep
|
| 211 |
+
):
|
| 212 |
+
keep_start = len(self.previous_saved_paths) - max_ckpt_to_keep + 1
|
| 213 |
+
self.remove_previous_save_local_path(self.previous_saved_paths[:keep_start])
|
| 214 |
+
self.previous_saved_paths = self.previous_saved_paths[keep_start:]
|
| 215 |
+
|
| 216 |
+
local_path = local_mkdir_safe(local_path)
|
| 217 |
+
torch.distributed.barrier()
|
| 218 |
+
|
| 219 |
+
# check if the checkpoint_save_contents is valid
|
| 220 |
+
if self.should_save_model:
|
| 221 |
+
assert self.model is not None, "model must be provided when checkpoint_contents.save includes ['model']"
|
| 222 |
+
if self.should_save_optimizer:
|
| 223 |
+
assert self.optimizer is not None, (
|
| 224 |
+
"optimizer must be provided when checkpoint_contents.save includes ['optimizer']"
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# every rank will save its own model and optim shard
|
| 228 |
+
state_dict_cfg = ShardedStateDictConfig(offload_to_cpu=True if is_cuda_available else False)
|
| 229 |
+
optim_cfg = ShardedOptimStateDictConfig(offload_to_cpu=True if is_cuda_available else False)
|
| 230 |
+
with warnings.catch_warnings():
|
| 231 |
+
warnings.simplefilter("ignore")
|
| 232 |
+
with get_fsdp_state_ctx(self.model, StateDictType.SHARDED_STATE_DICT, state_dict_cfg, optim_cfg):
|
| 233 |
+
model_path = os.path.join(local_path, f"model_world_size_{self.world_size}_rank_{self.rank}.pt")
|
| 234 |
+
optim_path = os.path.join(local_path, f"optim_world_size_{self.world_size}_rank_{self.rank}.pt")
|
| 235 |
+
extra_path = os.path.join(local_path, f"extra_state_world_size_{self.world_size}_rank_{self.rank}.pt")
|
| 236 |
+
|
| 237 |
+
if self.should_save_model:
|
| 238 |
+
model_state_dict = self.model.state_dict()
|
| 239 |
+
torch.save(model_state_dict, model_path)
|
| 240 |
+
log_with_rank(f"Saved model to {os.path.abspath(model_path)}", rank=self.rank, logger=logger)
|
| 241 |
+
|
| 242 |
+
if self.should_save_optimizer:
|
| 243 |
+
optimizer_state_dict = self.optimizer.state_dict()
|
| 244 |
+
torch.save(optimizer_state_dict, optim_path)
|
| 245 |
+
log_with_rank(f"Saved optim to {os.path.abspath(optim_path)}", rank=self.rank, logger=logger)
|
| 246 |
+
|
| 247 |
+
if self.should_save_extra:
|
| 248 |
+
lr_scheduler_state_dict = self.lr_scheduler.state_dict() if self.lr_scheduler is not None else None
|
| 249 |
+
extra_state_dict = {
|
| 250 |
+
"lr_scheduler": lr_scheduler_state_dict,
|
| 251 |
+
"rng": self.get_rng_state(),
|
| 252 |
+
}
|
| 253 |
+
torch.save(extra_state_dict, extra_path)
|
| 254 |
+
log_with_rank(f"Saved extra_state to {os.path.abspath(extra_path)}", rank=self.rank, logger=logger)
|
| 255 |
+
|
| 256 |
+
if self.rank == 0:
|
| 257 |
+
# Save HF tokenizer/processor and model config on rank 0 to huggingface/ directory, no matter whether
|
| 258 |
+
# huggingface model is requested to be saved or not.
|
| 259 |
+
|
| 260 |
+
if fsdp_version(self.model) == 1:
|
| 261 |
+
unwrap_model = self.model._fsdp_wrapped_module
|
| 262 |
+
else:
|
| 263 |
+
unwrap_model = self.model
|
| 264 |
+
|
| 265 |
+
hf_config_tokenizer_path = os.path.join(local_path, "huggingface")
|
| 266 |
+
local_mkdir_safe(hf_config_tokenizer_path)
|
| 267 |
+
model_config = unwrap_model.config
|
| 268 |
+
generation_config = None
|
| 269 |
+
if unwrap_model.can_generate() and hasattr(model_config, "name_or_path") and model_config.name_or_path:
|
| 270 |
+
try:
|
| 271 |
+
# Some model's name_or_path is empty if not initialized from pretrained,
|
| 272 |
+
# in this cases, we don't save generation config.
|
| 273 |
+
generation_config = GenerationConfig.from_pretrained(model_config.name_or_path)
|
| 274 |
+
generation_config.save_pretrained(hf_config_tokenizer_path)
|
| 275 |
+
except Exception:
|
| 276 |
+
# if the generation config isn't available, we don't save it
|
| 277 |
+
pass
|
| 278 |
+
|
| 279 |
+
model_config.save_pretrained(hf_config_tokenizer_path)
|
| 280 |
+
if self.processing_class is not None:
|
| 281 |
+
self.processing_class.save_pretrained(hf_config_tokenizer_path)
|
| 282 |
+
log_with_rank(
|
| 283 |
+
f"Saved model config and tokenizer class to {os.path.abspath(hf_config_tokenizer_path)}",
|
| 284 |
+
rank=self.rank,
|
| 285 |
+
logger=logger,
|
| 286 |
+
log_only_rank_0=True,
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# If we have a custom model, we copy the file defining it in the folder and set the attributes so it can be
|
| 290 |
+
# loaded from the Hub.
|
| 291 |
+
if hasattr(model_config, "auto_map"):
|
| 292 |
+
custom_object_save(unwrap_model, hf_config_tokenizer_path, config=model_config)
|
| 293 |
+
|
| 294 |
+
# Also save runtime FSDP config
|
| 295 |
+
fsdp_config_path = os.path.join(local_path, "fsdp_config.json")
|
| 296 |
+
fsdp_config = FSDPConfig(
|
| 297 |
+
FSDP_version=fsdp_version(self.model),
|
| 298 |
+
world_size=self.world_size,
|
| 299 |
+
)
|
| 300 |
+
with open(fsdp_config_path, "w") as f:
|
| 301 |
+
json.dump(asdict(fsdp_config), f, indent=4)
|
| 302 |
+
|
| 303 |
+
# wait for everyone to dump to local
|
| 304 |
+
torch.distributed.barrier()
|
| 305 |
+
|
| 306 |
+
if self.should_save_hf_model:
|
| 307 |
+
# Only rank 0 will save hf model and,
|
| 308 |
+
# offload to cpu to save LLMs which may be too large to fit in one GPU
|
| 309 |
+
state_dict = get_fsdp_full_state_dict(self.model, offload_to_cpu=True, rank0_only=True)
|
| 310 |
+
|
| 311 |
+
if self.rank == 0:
|
| 312 |
+
hf_local_path = os.path.join(local_path, "huggingface")
|
| 313 |
+
os.makedirs(hf_local_path, exist_ok=True)
|
| 314 |
+
|
| 315 |
+
if "ForTokenClassification" in model_config.architectures[0]:
|
| 316 |
+
from transformers import AutoModelForTokenClassification
|
| 317 |
+
|
| 318 |
+
auto_model_cls = AutoModelForTokenClassification
|
| 319 |
+
elif "ForCausalLM" in model_config.architectures[0]:
|
| 320 |
+
from transformers import AutoModelForCausalLM
|
| 321 |
+
|
| 322 |
+
auto_model_cls = AutoModelForCausalLM
|
| 323 |
+
elif "ForConditionalGeneration" in model_config.architectures[0]:
|
| 324 |
+
# Handle different transformers versions for Vision2Seq models
|
| 325 |
+
import transformers
|
| 326 |
+
from packaging import version
|
| 327 |
+
|
| 328 |
+
if version.parse(transformers.__version__) >= version.parse("4.54.0"):
|
| 329 |
+
# transformers >= 4.54.0 uses AutoModelForImageTextToText
|
| 330 |
+
from transformers import AutoModelForImageTextToText
|
| 331 |
+
|
| 332 |
+
auto_model_cls = AutoModelForImageTextToText
|
| 333 |
+
else:
|
| 334 |
+
# transformers < 4.54.0 uses AutoModelForVision2Seq
|
| 335 |
+
from transformers import AutoModelForVision2Seq
|
| 336 |
+
|
| 337 |
+
auto_model_cls = AutoModelForVision2Seq
|
| 338 |
+
else:
|
| 339 |
+
raise NotImplementedError(f"Unknown architecture {model_config['architectures']}")
|
| 340 |
+
|
| 341 |
+
with init_empty_weights():
|
| 342 |
+
save_model = auto_model_cls.from_config(model_config, torch_dtype=torch.bfloat16)
|
| 343 |
+
save_model.to_empty(device="cpu")
|
| 344 |
+
|
| 345 |
+
if save_model.can_generate():
|
| 346 |
+
if generation_config is not None:
|
| 347 |
+
save_model.generation_config = generation_config
|
| 348 |
+
else:
|
| 349 |
+
print(
|
| 350 |
+
f"Warning: {self.__class__.__name__}.save_checkpoint: Generation config file not found "
|
| 351 |
+
f"in, using a generation config created from the model config when saving hf_model."
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
save_model.save_pretrained(hf_local_path, state_dict=state_dict)
|
| 355 |
+
log_with_rank(
|
| 356 |
+
f"Saved hf_model to {os.path.abspath(hf_local_path)}",
|
| 357 |
+
rank=self.rank,
|
| 358 |
+
logger=logger,
|
| 359 |
+
log_only_rank_0=True,
|
| 360 |
+
)
|
| 361 |
+
del state_dict
|
| 362 |
+
del save_model
|
| 363 |
+
|
| 364 |
+
# wait for rank0 to dump hf_model to local
|
| 365 |
+
torch.distributed.barrier()
|
| 366 |
+
|
| 367 |
+
self.previous_saved_paths.append(local_path)
|
verl/verl/utils/checkpoint/megatron_checkpoint_manager.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import logging
|
| 17 |
+
import os
|
| 18 |
+
import random
|
| 19 |
+
from collections.abc import Callable
|
| 20 |
+
from dataclasses import asdict
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
import torch.distributed
|
| 25 |
+
from megatron.core import mpu, tensor_parallel
|
| 26 |
+
from megatron.core.dist_checkpointing.mapping import ShardedObject
|
| 27 |
+
from megatron.core.transformer.enums import AttnBackend
|
| 28 |
+
from transformers import GenerationConfig
|
| 29 |
+
|
| 30 |
+
from verl.models.weight_loader_registry import get_weight_saver
|
| 31 |
+
from verl.utils.device import get_device_name, get_torch_device
|
| 32 |
+
from verl.utils.fs import is_non_local, local_mkdir_safe
|
| 33 |
+
from verl.utils.logger import log_with_rank
|
| 34 |
+
from verl.utils.megatron.dist_checkpointing import load_dist_checkpointing, save_dist_checkpointing
|
| 35 |
+
from verl.utils.megatron_utils import (
|
| 36 |
+
get_dist_checkpoint_path,
|
| 37 |
+
get_hf_model_checkpoint_path,
|
| 38 |
+
get_transformer_config_checkpoint_path,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from .checkpoint_manager import BaseCheckpointManager
|
| 42 |
+
|
| 43 |
+
# Setup logging
|
| 44 |
+
logger = logging.getLogger(__file__)
|
| 45 |
+
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO"))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class MegatronCheckpointManager(BaseCheckpointManager):
|
| 49 |
+
"""
|
| 50 |
+
Checkpoint manager for Megatron-LM distributed training.
|
| 51 |
+
|
| 52 |
+
This class manages the saving and loading of model checkpoints in a Megatron-LM
|
| 53 |
+
distributed training environment. It handles various aspects of checkpointing
|
| 54 |
+
including model states, optimizer states, learning rate schedulers, and random
|
| 55 |
+
number generator states, ensuring compatibility with HuggingFace formats.
|
| 56 |
+
|
| 57 |
+
Key features:
|
| 58 |
+
- Distributed checkpoint saving and loading using Megatron's dist_checkpointing
|
| 59 |
+
- Support for tensor parallel, pipeline parallel, and data parallel configurations
|
| 60 |
+
- Automatic handling of model state dictionaries across multiple pipeline stages
|
| 61 |
+
- Integration with HuggingFace model configurations and tokenizers
|
| 62 |
+
- Random number generator state management for reproducibility
|
| 63 |
+
- Support for both synchronous and asynchronous checkpoint operations
|
| 64 |
+
|
| 65 |
+
The manager automatically handles:
|
| 66 |
+
- Directory structure creation based on global steps and process ranks
|
| 67 |
+
- Model configuration and tokenizer saving in HuggingFace format
|
| 68 |
+
- Optimizer and scheduler state persistence
|
| 69 |
+
- CUDA RNG state management for deterministic training
|
| 70 |
+
- Checkpoint cleanup and retention policies
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
model: The Megatron model instance to checkpoint
|
| 74 |
+
optimizer: The optimizer instance (optional)
|
| 75 |
+
lr_scheduler: The learning rate scheduler instance (optional)
|
| 76 |
+
|
| 77 |
+
Attributes:
|
| 78 |
+
model: Reference to the Megatron model being checkpointed
|
| 79 |
+
optimizer: Reference to the optimizer (if provided)
|
| 80 |
+
lr_scheduler: Reference to the learning rate scheduler (if provided)
|
| 81 |
+
rank: Current process rank in the distributed setup
|
| 82 |
+
|
| 83 |
+
Example:
|
| 84 |
+
```python
|
| 85 |
+
checkpoint_manager = MegatronCheckpointManager(
|
| 86 |
+
model=megatron_model,
|
| 87 |
+
optimizer=optimizer,
|
| 88 |
+
lr_scheduler=scheduler
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
checkpoint_manager.save_checkpoint(
|
| 92 |
+
local_path="checkpoints/step_1000",
|
| 93 |
+
global_step=1000
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
checkpoint_manager.load_checkpoint(
|
| 97 |
+
local_path="checkpoints/step_1000"
|
| 98 |
+
)
|
| 99 |
+
```
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def __init__(
|
| 103 |
+
self,
|
| 104 |
+
config,
|
| 105 |
+
checkpoint_config,
|
| 106 |
+
model_config,
|
| 107 |
+
transformer_config,
|
| 108 |
+
role,
|
| 109 |
+
model: torch.nn.ModuleList,
|
| 110 |
+
arch: str,
|
| 111 |
+
hf_config,
|
| 112 |
+
param_dtype: torch.dtype,
|
| 113 |
+
share_embeddings_and_output_weights: bool,
|
| 114 |
+
processing_class,
|
| 115 |
+
optimizer,
|
| 116 |
+
optimizer_scheduler,
|
| 117 |
+
use_distributed_optimizer: bool,
|
| 118 |
+
use_checkpoint_opt_param_scheduler: bool = False,
|
| 119 |
+
use_dist_checkpointing: bool = True,
|
| 120 |
+
bridge=None,
|
| 121 |
+
**kwargs,
|
| 122 |
+
):
|
| 123 |
+
super().__init__(
|
| 124 |
+
model,
|
| 125 |
+
optimizer=optimizer,
|
| 126 |
+
lr_scheduler=optimizer_scheduler,
|
| 127 |
+
processing_class=processing_class,
|
| 128 |
+
checkpoint_config=checkpoint_config,
|
| 129 |
+
)
|
| 130 |
+
self.arch = arch
|
| 131 |
+
self.config = config
|
| 132 |
+
self.transformer_config = transformer_config
|
| 133 |
+
self.role = role
|
| 134 |
+
self.is_value_model = False
|
| 135 |
+
if self.role in ["reward", "critic"]:
|
| 136 |
+
self.is_value_model = True
|
| 137 |
+
self.model_config = model_config
|
| 138 |
+
self.hf_config = hf_config
|
| 139 |
+
self.param_dtype = param_dtype
|
| 140 |
+
self.share_embeddings_and_output_weights = share_embeddings_and_output_weights
|
| 141 |
+
self.model_path = self.config.model.path
|
| 142 |
+
self.use_distributed_optimizer = use_distributed_optimizer
|
| 143 |
+
self.use_checkpoint_opt_param_scheduler = use_checkpoint_opt_param_scheduler
|
| 144 |
+
self.bridge = bridge
|
| 145 |
+
self.rank = torch.distributed.get_rank()
|
| 146 |
+
self.use_dist_checkpointing = use_dist_checkpointing or not self.bridge or self.is_value_model
|
| 147 |
+
self.use_hf_checkpoint = not self.use_dist_checkpointing
|
| 148 |
+
|
| 149 |
+
self.weight_saver = None
|
| 150 |
+
if self.bridge is None:
|
| 151 |
+
self.weight_saver = get_weight_saver(self.arch)
|
| 152 |
+
|
| 153 |
+
def get_rng_state(self, use_dist_ckpt: bool = True, data_parallel_random_init: bool = False):
|
| 154 |
+
"""collect rng state across data parallel ranks"""
|
| 155 |
+
rng_state = {
|
| 156 |
+
"random_rng_state": random.getstate(),
|
| 157 |
+
"np_rng_state": np.random.get_state(),
|
| 158 |
+
"torch_rng_state": torch.get_rng_state(),
|
| 159 |
+
"rng_tracker_states": tensor_parallel.get_cuda_rng_tracker().get_states(),
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
if get_device_name() != "cpu":
|
| 163 |
+
rng_state[f"{get_device_name()}_rng_state"] = get_torch_device().get_rng_state()
|
| 164 |
+
|
| 165 |
+
rng_state_list = None
|
| 166 |
+
if torch.distributed.is_initialized() and mpu.get_data_parallel_world_size() > 1 and data_parallel_random_init:
|
| 167 |
+
rng_state_list = [None for i in range(mpu.get_data_parallel_world_size())]
|
| 168 |
+
torch.distributed.all_gather_object(rng_state_list, rng_state, group=mpu.get_data_parallel_group())
|
| 169 |
+
else:
|
| 170 |
+
rng_state_list = [rng_state]
|
| 171 |
+
|
| 172 |
+
if use_dist_ckpt:
|
| 173 |
+
pp_rank = mpu.get_pipeline_model_parallel_rank()
|
| 174 |
+
pp_size = mpu.get_pipeline_model_parallel_world_size()
|
| 175 |
+
tp_rank = mpu.get_tensor_model_parallel_rank()
|
| 176 |
+
tp_size = mpu.get_tensor_model_parallel_world_size()
|
| 177 |
+
rng_state_list = ShardedObject(
|
| 178 |
+
"rng_state",
|
| 179 |
+
rng_state_list,
|
| 180 |
+
(pp_size, tp_size),
|
| 181 |
+
(pp_rank, tp_rank),
|
| 182 |
+
replica_id=mpu.get_data_parallel_rank(with_context_parallel=True),
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
return rng_state_list
|
| 186 |
+
|
| 187 |
+
def get_checkpoint_name(
|
| 188 |
+
self,
|
| 189 |
+
checkpoints_path,
|
| 190 |
+
pipeline_parallel=None,
|
| 191 |
+
tensor_rank=None,
|
| 192 |
+
pipeline_rank=None,
|
| 193 |
+
cp_rank=None,
|
| 194 |
+
expert_parallel=None,
|
| 195 |
+
expert_rank=None,
|
| 196 |
+
return_base_dir=True,
|
| 197 |
+
basename="model.pt",
|
| 198 |
+
):
|
| 199 |
+
"""Determine the directory name for this rank's checkpoint."""
|
| 200 |
+
# Use both the tensor and pipeline MP rank.
|
| 201 |
+
if pipeline_parallel is None:
|
| 202 |
+
pipeline_parallel = mpu.get_pipeline_model_parallel_world_size() > 1
|
| 203 |
+
if tensor_rank is None:
|
| 204 |
+
tensor_rank = mpu.get_tensor_model_parallel_rank()
|
| 205 |
+
if pipeline_rank is None:
|
| 206 |
+
pipeline_rank = mpu.get_pipeline_model_parallel_rank()
|
| 207 |
+
if cp_rank is None:
|
| 208 |
+
cp_rank = mpu.get_context_parallel_rank()
|
| 209 |
+
if expert_parallel is None:
|
| 210 |
+
expert_parallel = mpu.get_expert_model_parallel_world_size() > 1
|
| 211 |
+
if expert_rank is None:
|
| 212 |
+
expert_rank = mpu.get_expert_model_parallel_rank()
|
| 213 |
+
|
| 214 |
+
# Use both the tensor and pipeline MP rank. If using the distributed
|
| 215 |
+
# optimizer, then the optimizer's path must additionally include the
|
| 216 |
+
# data parallel rank.
|
| 217 |
+
|
| 218 |
+
# due to the fact that models are identical across cp ranks, cp rank is not used in the checkpoint path
|
| 219 |
+
if not pipeline_parallel:
|
| 220 |
+
common_path = os.path.join(checkpoints_path, f"mp_rank_{tensor_rank:02d}")
|
| 221 |
+
else:
|
| 222 |
+
common_path = os.path.join(checkpoints_path, f"mp_rank_{tensor_rank:02d}_{pipeline_rank:03d}")
|
| 223 |
+
|
| 224 |
+
if expert_parallel:
|
| 225 |
+
common_path = common_path + f"_{expert_rank:03d}"
|
| 226 |
+
|
| 227 |
+
os.makedirs(common_path, exist_ok=True)
|
| 228 |
+
|
| 229 |
+
if return_base_dir:
|
| 230 |
+
return common_path
|
| 231 |
+
return os.path.join(common_path, basename)
|
| 232 |
+
|
| 233 |
+
def generate_state_dict(
|
| 234 |
+
self, generate_model: bool = True, generate_optimizer: bool = True, generate_extra: bool = True
|
| 235 |
+
):
|
| 236 |
+
# For save dist checkpointing
|
| 237 |
+
state_dict = {}
|
| 238 |
+
|
| 239 |
+
# Should always generate model state dict
|
| 240 |
+
# All ranks Save Model to reduce memory pressure
|
| 241 |
+
# Get sharded state dict, notice that state_dict will collect among dp groups, causing memory pressure
|
| 242 |
+
for vpp_rank, model in enumerate(self.model):
|
| 243 |
+
if len(self.model) > 1:
|
| 244 |
+
mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank)
|
| 245 |
+
key = f"model{vpp_rank}" if len(self.model) > 1 else "model"
|
| 246 |
+
else:
|
| 247 |
+
key = "model"
|
| 248 |
+
if hasattr(model, "module"):
|
| 249 |
+
model = model.module
|
| 250 |
+
state_dict[key] = model.sharded_state_dict()
|
| 251 |
+
|
| 252 |
+
# Optimizer State Dict
|
| 253 |
+
if generate_optimizer:
|
| 254 |
+
torch.distributed.barrier()
|
| 255 |
+
optimizer_sharded_states = self.optimizer.sharded_state_dict(state_dict)
|
| 256 |
+
state_dict["optimizer"] = optimizer_sharded_states
|
| 257 |
+
|
| 258 |
+
if self.lr_scheduler is not None:
|
| 259 |
+
lr_state_dict = self.lr_scheduler.state_dict()
|
| 260 |
+
state_dict["lr_scheduler"] = lr_state_dict
|
| 261 |
+
|
| 262 |
+
if not generate_model:
|
| 263 |
+
state_dict.pop("model", None)
|
| 264 |
+
|
| 265 |
+
# RNG States State Dict
|
| 266 |
+
if generate_extra:
|
| 267 |
+
torch.distributed.barrier()
|
| 268 |
+
rng_state = self.get_rng_state()
|
| 269 |
+
state_dict["rng_state"] = rng_state
|
| 270 |
+
|
| 271 |
+
return state_dict
|
| 272 |
+
|
| 273 |
+
def load_rng_states(self, rng_states, data_parallel_random_init=False, use_dist_ckpt=True):
|
| 274 |
+
# access rng_state for data parallel rank
|
| 275 |
+
if data_parallel_random_init:
|
| 276 |
+
rng_states = rng_states[mpu.get_data_parallel_rank()]
|
| 277 |
+
else:
|
| 278 |
+
rng_states = rng_states[0]
|
| 279 |
+
random.setstate(rng_states["random_rng_state"])
|
| 280 |
+
np.random.set_state(rng_states["np_rng_state"])
|
| 281 |
+
torch.set_rng_state(rng_states["torch_rng_state"])
|
| 282 |
+
|
| 283 |
+
if get_device_name() != "cpu":
|
| 284 |
+
get_torch_device().set_rng_state(rng_states[f"{get_device_name()}_rng_state"])
|
| 285 |
+
|
| 286 |
+
# Check for empty states array
|
| 287 |
+
if not rng_states["rng_tracker_states"]:
|
| 288 |
+
raise KeyError
|
| 289 |
+
tensor_parallel.get_cuda_rng_tracker().set_states(rng_states["rng_tracker_states"])
|
| 290 |
+
|
| 291 |
+
def load_checkpoint(self, local_path: str, hdfs_path: str = None, del_local_after_load=False):
|
| 292 |
+
if local_path is not None:
|
| 293 |
+
assert os.path.exists(local_path), f"Checkpoint path {local_path} does not exist."
|
| 294 |
+
|
| 295 |
+
dist_checkpoint_path = get_dist_checkpoint_path(local_path)
|
| 296 |
+
|
| 297 |
+
# Get State Dict for loading
|
| 298 |
+
sharded_state_dict = self.generate_state_dict(
|
| 299 |
+
self.should_load_model and self.use_dist_checkpointing, self.should_load_optimizer, self.should_load_extra
|
| 300 |
+
)
|
| 301 |
+
log_with_rank(f"Generated state dict for loading: {sharded_state_dict.keys()}", rank=self.rank, logger=logger)
|
| 302 |
+
|
| 303 |
+
# Load Dist Checkpointing
|
| 304 |
+
state_dict = load_dist_checkpointing(
|
| 305 |
+
sharded_state_dict=sharded_state_dict,
|
| 306 |
+
ckpt_dir=dist_checkpoint_path,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
if self.should_load_model and self.use_dist_checkpointing:
|
| 310 |
+
assert "model" in state_dict or any(
|
| 311 |
+
f"model{vpp_rank}" in state_dict for vpp_rank in range(len(self.model))
|
| 312 |
+
), f"Model state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}."
|
| 313 |
+
for vpp_rank, model in enumerate(self.model):
|
| 314 |
+
if len(self.model) == 1:
|
| 315 |
+
model_state_dict = state_dict["model"]
|
| 316 |
+
else:
|
| 317 |
+
assert f"model{vpp_rank}" in state_dict, f"model{vpp_rank} not found in state_dict"
|
| 318 |
+
model_state_dict = state_dict[f"model{vpp_rank}"]
|
| 319 |
+
mpu.set_virtual_pipeline_model_parallel_rank(vpp_rank)
|
| 320 |
+
self.model[vpp_rank].load_state_dict(model_state_dict)
|
| 321 |
+
log_with_rank(f"Loaded sharded model checkpoint from {local_path}", rank=self.rank, logger=logger)
|
| 322 |
+
elif self.should_load_model and self.use_hf_checkpoint:
|
| 323 |
+
hf_model_path = get_hf_model_checkpoint_path(local_path)
|
| 324 |
+
self.bridge.load_weights(self.model, hf_model_path)
|
| 325 |
+
log_with_rank(f"Loaded HF model checkpoint from {hf_model_path} with bridge", rank=self.rank, logger=logger)
|
| 326 |
+
|
| 327 |
+
if self.should_load_optimizer:
|
| 328 |
+
assert "optimizer" in state_dict, (
|
| 329 |
+
f"Optimizer state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}."
|
| 330 |
+
)
|
| 331 |
+
optimizer_state_dict = state_dict["optimizer"]
|
| 332 |
+
self.optimizer.load_state_dict(optimizer_state_dict)
|
| 333 |
+
log_with_rank(f"Loaded optimizer checkpoint from {local_path}", rank=self.rank, logger=logger)
|
| 334 |
+
if self.use_checkpoint_opt_param_scheduler:
|
| 335 |
+
assert "lr_scheduler" in state_dict, (
|
| 336 |
+
f"LR scheduler state dict not found in {state_dict.keys()}. Please check the checkpoint file "
|
| 337 |
+
f"{local_path}."
|
| 338 |
+
)
|
| 339 |
+
lr_scheduler_state_dict = state_dict["lr_scheduler"]
|
| 340 |
+
if self.lr_scheduler is not None:
|
| 341 |
+
self.lr_scheduler.load_state_dict(lr_scheduler_state_dict)
|
| 342 |
+
log_with_rank(f"Loaded LR scheduler checkpoint from {local_path}", rank=self.rank, logger=logger)
|
| 343 |
+
|
| 344 |
+
if self.should_load_extra:
|
| 345 |
+
assert "rng_state" in state_dict, (
|
| 346 |
+
f"RNG state dict not found in {state_dict.keys()}. Please check the checkpoint file {local_path}."
|
| 347 |
+
)
|
| 348 |
+
rng_state = state_dict["rng_state"]
|
| 349 |
+
self.load_rng_states(rng_state)
|
| 350 |
+
log_with_rank(f"Loaded RNG states from {local_path}", rank=self.rank, logger=logger)
|
| 351 |
+
|
| 352 |
+
if del_local_after_load:
|
| 353 |
+
try:
|
| 354 |
+
os.remove(local_path) if is_non_local(local_path) else None
|
| 355 |
+
except Exception as e:
|
| 356 |
+
log_with_rank(
|
| 357 |
+
f"remove local resume ckpt file after loading failed, exception {e} will be ignored",
|
| 358 |
+
rank=self.rank,
|
| 359 |
+
logger=logger,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
def save_checkpoint(self, local_path: str, hdfs_path: str = None, global_step: int = 0, max_ckpt_to_keep=None):
|
| 363 |
+
# record the previous global step
|
| 364 |
+
self.previous_global_step = global_step
|
| 365 |
+
|
| 366 |
+
# remove previous local_path
|
| 367 |
+
if (
|
| 368 |
+
max_ckpt_to_keep
|
| 369 |
+
and isinstance(max_ckpt_to_keep, int)
|
| 370 |
+
and max_ckpt_to_keep > 0
|
| 371 |
+
and len(self.previous_saved_paths) >= max_ckpt_to_keep
|
| 372 |
+
):
|
| 373 |
+
keep_start = len(self.previous_saved_paths) - max_ckpt_to_keep + 1
|
| 374 |
+
self.remove_previous_save_local_path(self.previous_saved_paths[:keep_start])
|
| 375 |
+
self.previous_saved_paths = self.previous_saved_paths[keep_start:]
|
| 376 |
+
|
| 377 |
+
local_path = local_mkdir_safe(local_path)
|
| 378 |
+
dist_checkpoint_path = get_dist_checkpoint_path(local_path)
|
| 379 |
+
|
| 380 |
+
# Note that model weights, optimizer states, and extra states are generated
|
| 381 |
+
# together in a state dict, we save them in one time
|
| 382 |
+
if self.use_dist_checkpointing:
|
| 383 |
+
# Generate state dict for saving
|
| 384 |
+
state_dict = self.generate_state_dict(
|
| 385 |
+
self.should_save_model, self.should_save_optimizer, self.should_save_extra
|
| 386 |
+
)
|
| 387 |
+
log_with_rank(f"Generated state dict for saving: {state_dict.keys()}", rank=self.rank, logger=logger)
|
| 388 |
+
for vpp_rank, model in enumerate(self.model):
|
| 389 |
+
if len(self.model) > 1:
|
| 390 |
+
model_i_keys = state_dict[f"model{vpp_rank}"].keys()
|
| 391 |
+
log_with_rank(f"Generated state dict for saving: {model_i_keys}", rank=self.rank, logger=logger)
|
| 392 |
+
else:
|
| 393 |
+
log_with_rank(
|
| 394 |
+
f"Generated state dict for saving: {state_dict['model'].keys()}", rank=self.rank, logger=logger
|
| 395 |
+
)
|
| 396 |
+
# Start Async save if enabled
|
| 397 |
+
async_save_request = save_dist_checkpointing(
|
| 398 |
+
sharded_state_dict=state_dict,
|
| 399 |
+
ckpt_path=dist_checkpoint_path,
|
| 400 |
+
async_save=self.checkpoint_config.async_save,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# Synchronize all async save requests
|
| 404 |
+
if not self.checkpoint_config.async_save:
|
| 405 |
+
assert async_save_request is None, "Async save request should be None when not using async save."
|
| 406 |
+
torch.distributed.barrier()
|
| 407 |
+
else:
|
| 408 |
+
assert self.use_hf_checkpoint, "When not using distributed checkpointing, use_hf_checkpoint should be True."
|
| 409 |
+
# Generate optimizer and exra state dicts
|
| 410 |
+
state_dict = self.generate_state_dict(
|
| 411 |
+
generate_model=False,
|
| 412 |
+
generate_optimizer=self.should_save_optimizer,
|
| 413 |
+
generate_extra=self.should_save_extra,
|
| 414 |
+
)
|
| 415 |
+
# Save optimizer and extra states to local path
|
| 416 |
+
# Start Async save if enabled
|
| 417 |
+
async_save_request = save_dist_checkpointing(
|
| 418 |
+
sharded_state_dict=state_dict,
|
| 419 |
+
ckpt_path=dist_checkpoint_path,
|
| 420 |
+
async_save=self.checkpoint_config.async_save,
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
# Synchronize all async save requests
|
| 424 |
+
if not self.checkpoint_config.async_save:
|
| 425 |
+
assert async_save_request is None, "Async save request should be None when not using async save."
|
| 426 |
+
torch.distributed.barrier()
|
| 427 |
+
|
| 428 |
+
if self.should_save_model:
|
| 429 |
+
if self.use_hf_checkpoint:
|
| 430 |
+
# Use mbridge to save HF model checkpoint
|
| 431 |
+
log_with_rank(f"Saving HF model checkpoint to {local_path} with bridge", rank=self.rank, logger=logger)
|
| 432 |
+
hf_ckpt_path = get_hf_model_checkpoint_path(local_path)
|
| 433 |
+
self.bridge.save_weights(self.model, hf_ckpt_path)
|
| 434 |
+
log_with_rank(f"Saved bridge checkpoint to {hf_ckpt_path}", rank=self.rank, logger=logger)
|
| 435 |
+
|
| 436 |
+
# Only rank 0 saves the hf config and tokenizer to huggingface path
|
| 437 |
+
# No matter whether we save hf model or not
|
| 438 |
+
if self.rank == 0:
|
| 439 |
+
# Save tokenizer
|
| 440 |
+
hf_config_tokenizer_path = get_hf_model_checkpoint_path(local_path)
|
| 441 |
+
if self.processing_class is not None:
|
| 442 |
+
self.processing_class.save_pretrained(hf_config_tokenizer_path)
|
| 443 |
+
# Save huggingface config
|
| 444 |
+
self.hf_config.save_pretrained(hf_config_tokenizer_path)
|
| 445 |
+
if hasattr(self.hf_config, "name_or_path") and self.hf_config.name_or_path:
|
| 446 |
+
try:
|
| 447 |
+
generation_config = GenerationConfig.from_pretrained(self.hf_config.name_or_path)
|
| 448 |
+
generation_config.save_pretrained(hf_config_tokenizer_path)
|
| 449 |
+
except Exception:
|
| 450 |
+
# if the generation config isn't available, we don't save it
|
| 451 |
+
pass
|
| 452 |
+
log_with_rank(
|
| 453 |
+
f"Saved Huggingface config and tokenizer to {hf_config_tokenizer_path}",
|
| 454 |
+
rank=self.rank,
|
| 455 |
+
logger=logger,
|
| 456 |
+
log_only_rank_0=True,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
if self.should_save_extra:
|
| 460 |
+
if self.rank == 0:
|
| 461 |
+
# Save transformer config
|
| 462 |
+
print(self.transformer_config)
|
| 463 |
+
transformer_config_dict = asdict(self.transformer_config)
|
| 464 |
+
to_convert_types = {torch.dtype: str, AttnBackend: str}
|
| 465 |
+
ignore_types = [Callable]
|
| 466 |
+
pop_keys = []
|
| 467 |
+
for key, value in transformer_config_dict.items():
|
| 468 |
+
if type(value) in to_convert_types:
|
| 469 |
+
transformer_config_dict[key] = to_convert_types[type(value)](value)
|
| 470 |
+
if type(value) in ignore_types:
|
| 471 |
+
pop_keys.append(key)
|
| 472 |
+
if callable(value):
|
| 473 |
+
pop_keys.append(key)
|
| 474 |
+
for key in pop_keys:
|
| 475 |
+
transformer_config_dict.pop(key)
|
| 476 |
+
transformer_config_path = get_transformer_config_checkpoint_path(local_path)
|
| 477 |
+
with open(transformer_config_path, "w") as f:
|
| 478 |
+
json.dump(transformer_config_dict, f, indent=2)
|
| 479 |
+
|
| 480 |
+
if self.should_save_hf_model and not self.use_hf_checkpoint:
|
| 481 |
+
# wait for everyone to dump to local
|
| 482 |
+
if self.bridge is not None:
|
| 483 |
+
hf_model_ckpt_path = get_hf_model_checkpoint_path(local_path)
|
| 484 |
+
self.bridge.save_weights(self.model, hf_model_ckpt_path)
|
| 485 |
+
else:
|
| 486 |
+
state_dict = self.weight_saver(
|
| 487 |
+
self.model,
|
| 488 |
+
self.hf_config,
|
| 489 |
+
dtype=self.param_dtype,
|
| 490 |
+
is_value_model=self.is_value_model,
|
| 491 |
+
tie_word_embeddings=self.share_embeddings_and_output_weights,
|
| 492 |
+
)
|
| 493 |
+
|
| 494 |
+
torch.distributed.barrier()
|
| 495 |
+
if self.rank == 0:
|
| 496 |
+
hf_model_ckpt_path = get_hf_model_checkpoint_path(local_path)
|
| 497 |
+
import warnings
|
| 498 |
+
|
| 499 |
+
from accelerate import init_empty_weights
|
| 500 |
+
|
| 501 |
+
with init_empty_weights(), warnings.catch_warnings():
|
| 502 |
+
warnings.simplefilter("ignore")
|
| 503 |
+
if "mistral7b-rm" in self.config.model.path:
|
| 504 |
+
from transformers import MistralForSequenceClassification
|
| 505 |
+
|
| 506 |
+
model = MistralForSequenceClassification.from_pretrained(
|
| 507 |
+
self.config.model.path
|
| 508 |
+
) # use score head instead of lm_head
|
| 509 |
+
state_dict["score.weight"] = state_dict["score.weight"]
|
| 510 |
+
else:
|
| 511 |
+
from transformers import AutoModelForCausalLM
|
| 512 |
+
|
| 513 |
+
model = AutoModelForCausalLM.from_pretrained(self.config.model.path, torch_dtype="auto")
|
| 514 |
+
model.save_pretrained(hf_model_ckpt_path, state_dict=state_dict)
|
| 515 |
+
log_with_rank(
|
| 516 |
+
f"Saved Huggingface config and tokenizer to {hf_model_ckpt_path}",
|
| 517 |
+
rank=self.rank,
|
| 518 |
+
logger=logger,
|
| 519 |
+
log_only_rank_0=True,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
if hdfs_path is not None:
|
| 523 |
+
log_with_rank(
|
| 524 |
+
f"Uploading checkpoint to {hdfs_path}", rank=self.rank, logger=logger, log_only_rank_0=True
|
| 525 |
+
)
|
| 526 |
+
from verl.utils import hdfs_io
|
| 527 |
+
|
| 528 |
+
hdfs_io.makedirs(hdfs_path, exist_ok=True)
|
| 529 |
+
hdfs_io.copy(src=hf_model_ckpt_path, dst=hdfs_path, dirs_exist_ok=True)
|
| 530 |
+
log_with_rank(
|
| 531 |
+
f"HDFS checkpoint uploaded to {hdfs_path}",
|
| 532 |
+
rank=self.rank,
|
| 533 |
+
logger=logger,
|
| 534 |
+
log_only_rank_0=True,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
def finalize_save_fn():
|
| 538 |
+
# Rank 0 uploads checkpoint to HDFS if hdfs_path is provided
|
| 539 |
+
log_with_rank(
|
| 540 |
+
f"Dist checkpointing save completed for {dist_checkpoint_path}", rank=self.rank, logger=logger
|
| 541 |
+
)
|
| 542 |
+
if self.rank == 0:
|
| 543 |
+
if hdfs_path is not None:
|
| 544 |
+
log_with_rank(f"Uploading checkpoint to {hdfs_path}", rank=self.rank, logger=logger)
|
| 545 |
+
from verl.utils import hdfs_io
|
| 546 |
+
|
| 547 |
+
hdfs_io.makedirs(hdfs_path, exist_ok=True)
|
| 548 |
+
hdfs_io.copy(src=dist_checkpoint_path, dst=hdfs_path, dirs_exist_ok=True)
|
| 549 |
+
hdfs_io.copy(src=hf_config_tokenizer_path, dst=hdfs_path, dirs_exist_ok=True)
|
| 550 |
+
|
| 551 |
+
if self.checkpoint_config.async_save:
|
| 552 |
+
assert async_save_request is not None, "Async save request should not be None when using async save."
|
| 553 |
+
async_save_request.add_finalize_fn(finalize_save_fn)
|
| 554 |
+
else:
|
| 555 |
+
finalize_save_fn()
|
| 556 |
+
|
| 557 |
+
self.previous_saved_paths.append(local_path)
|
verl/verl/utils/dataset/README.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dataset Format
|
| 2 |
+
## RLHF dataset
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
Math problems
|
| 6 |
+
```json
|
| 7 |
+
{
|
| 8 |
+
"data_source": "openai/gsm8k",
|
| 9 |
+
"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 \"####\""}],
|
| 10 |
+
"ability": "math",
|
| 11 |
+
"reward_model": {
|
| 12 |
+
"style": "rule",
|
| 13 |
+
"ground_truth": ["72"]
|
| 14 |
+
},
|
| 15 |
+
}
|
| 16 |
+
```
|
verl/verl/utils/dataset/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .rl_dataset import RLHFDataset
|
| 16 |
+
from .rm_dataset import RMDataset
|
| 17 |
+
from .sft_dataset import SFTDataset
|
| 18 |
+
|
| 19 |
+
__all__ = ["RLHFDataset", "RMDataset", "SFTDataset"]
|
verl/verl/utils/dataset/dataset_utils.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from enum import Enum
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class DatasetPadMode(str, Enum):
|
| 22 |
+
"""Padding mode for dataset"""
|
| 23 |
+
|
| 24 |
+
RIGHT = "right"
|
| 25 |
+
LEFT_RIGHT = "left_right"
|
| 26 |
+
NO_PADDING = "no_padding"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SFTTensorCollator:
|
| 30 |
+
"""
|
| 31 |
+
A custom collate_fn that handles batching of sequences.
|
| 32 |
+
1. for variable-length sequences, convert them into NestedTensors.
|
| 33 |
+
2. for fixed-length sequences, use default_collate.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(self, pad_mode: DatasetPadMode = DatasetPadMode.LEFT_RIGHT):
|
| 37 |
+
self.pad_mode = pad_mode
|
| 38 |
+
|
| 39 |
+
def __call__(self, batch: list[dict[str, any]]) -> dict[str, any]:
|
| 40 |
+
if self.pad_mode == DatasetPadMode.NO_PADDING:
|
| 41 |
+
return self.collate_variable_batch(batch)
|
| 42 |
+
elif self.pad_mode in [DatasetPadMode.RIGHT, DatasetPadMode.LEFT_RIGHT]:
|
| 43 |
+
from torch.utils.data import default_collate
|
| 44 |
+
|
| 45 |
+
return default_collate(batch)
|
| 46 |
+
else:
|
| 47 |
+
raise NotImplementedError(f"pad_mode {self.pad_mode} not implemented")
|
| 48 |
+
|
| 49 |
+
def collate_variable_batch(self, batch: list[dict[str, any]]) -> dict[str, any]:
|
| 50 |
+
"""
|
| 51 |
+
Collates a list of samples into a single batch.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
batch: A list of dictionary samples from the dataset.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
A dictionary representing the batched data, with variable-length
|
| 58 |
+
sequences converted to NestedTensors.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
final_batch = {}
|
| 62 |
+
|
| 63 |
+
tensor_keys = [key for key in batch[0].keys() if isinstance(batch[0][key], torch.Tensor)]
|
| 64 |
+
|
| 65 |
+
# Handle tensor values by creating a NestedTensor.
|
| 66 |
+
for key in tensor_keys:
|
| 67 |
+
tensors = [item[key] for item in batch]
|
| 68 |
+
final_batch[key] = torch.nested.as_nested_tensor(tensors, layout=torch.jagged)
|
| 69 |
+
|
| 70 |
+
return final_batch
|
verl/verl/utils/dataset/multiturn_sft_dataset.py
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright 2025 ModelBest Inc. and/or its affiliates
|
| 3 |
+
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Multi-turn SFT dataset that supports training on conversation data with multiple turns
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import logging
|
| 20 |
+
from typing import Any, Optional
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
import torch
|
| 25 |
+
from omegaconf import ListConfig
|
| 26 |
+
from torch.utils.data import Dataset
|
| 27 |
+
from transformers import PreTrainedTokenizer
|
| 28 |
+
|
| 29 |
+
from verl.utils import hf_tokenizer
|
| 30 |
+
from verl.utils.dataset.dataset_utils import DatasetPadMode
|
| 31 |
+
from verl.utils.fs import copy_local_path_from_hdfs
|
| 32 |
+
from verl.utils.model import compute_position_id_with_mask
|
| 33 |
+
from verl.utils.torch_functional import pad_sequence_to_length, postprocess_data
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def convert_nested_value_to_list_recursive(data_item):
|
| 37 |
+
if isinstance(data_item, dict):
|
| 38 |
+
return {k: convert_nested_value_to_list_recursive(v) for k, v in data_item.items()}
|
| 39 |
+
elif isinstance(data_item, list):
|
| 40 |
+
return [convert_nested_value_to_list_recursive(elem) for elem in data_item]
|
| 41 |
+
elif isinstance(data_item, np.ndarray):
|
| 42 |
+
# Convert to list, then recursively process the elements of the new list
|
| 43 |
+
return convert_nested_value_to_list_recursive(data_item.tolist())
|
| 44 |
+
else:
|
| 45 |
+
# Base case: item is already a primitive type (int, str, float, bool, etc.)
|
| 46 |
+
return data_item
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MultiTurnSFTDataset(Dataset):
|
| 50 |
+
"""
|
| 51 |
+
Dataset for multi-turn conversations where each assistant response should be trained
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, parquet_files: str | list[str], tokenizer, config=None):
|
| 55 |
+
# Set defaults and extract parameters from config if provided
|
| 56 |
+
config = config or {}
|
| 57 |
+
self.pad_mode = config.get("pad_mode", "right")
|
| 58 |
+
assert self.pad_mode in ["right", "left_right", "no_padding"], (
|
| 59 |
+
f"Expect pad_mode to be 'right', 'left_right' or 'no_padding'. Got {self.pad_mode}"
|
| 60 |
+
)
|
| 61 |
+
self.truncation = config.get("truncation", "error")
|
| 62 |
+
# for right padding
|
| 63 |
+
self.max_length = config.get("max_length", 1024)
|
| 64 |
+
# for left right paddding to be consistent with RL
|
| 65 |
+
self.max_prompt_length = config.get("max_prompt_length", 512)
|
| 66 |
+
self.max_response_length = config.get("max_response_length", 512)
|
| 67 |
+
# Get messages_key from the new multiturn config structure
|
| 68 |
+
multiturn_config = config.get("multiturn", {})
|
| 69 |
+
self.messages_key = multiturn_config.get("messages_key", "messages")
|
| 70 |
+
self.tools_key = multiturn_config.get("tools_key", "tools")
|
| 71 |
+
self.enable_thinking_key = multiturn_config.get("enable_thinking_key", "enable_thinking")
|
| 72 |
+
self.apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", {})
|
| 73 |
+
assert self.truncation in ["error", "left", "right"]
|
| 74 |
+
|
| 75 |
+
if not isinstance(parquet_files, list | ListConfig):
|
| 76 |
+
parquet_files = [parquet_files]
|
| 77 |
+
|
| 78 |
+
self.parquet_files = parquet_files
|
| 79 |
+
if isinstance(tokenizer, str):
|
| 80 |
+
tokenizer = hf_tokenizer(tokenizer)
|
| 81 |
+
self.tokenizer: PreTrainedTokenizer = tokenizer
|
| 82 |
+
|
| 83 |
+
self._download()
|
| 84 |
+
self._read_files_and_process()
|
| 85 |
+
|
| 86 |
+
def _download(self):
|
| 87 |
+
for i, parquet_file in enumerate(self.parquet_files):
|
| 88 |
+
self.parquet_files[i] = copy_local_path_from_hdfs(parquet_file, verbose=True)
|
| 89 |
+
|
| 90 |
+
def _read_files_and_process(self):
|
| 91 |
+
def series_to_item(ls):
|
| 92 |
+
import numpy
|
| 93 |
+
import pandas
|
| 94 |
+
|
| 95 |
+
while isinstance(ls, pandas.core.series.Series | numpy.ndarray) and len(ls) == 1:
|
| 96 |
+
ls = ls[0]
|
| 97 |
+
return ls
|
| 98 |
+
|
| 99 |
+
dataframes = []
|
| 100 |
+
for parquet_file in self.parquet_files:
|
| 101 |
+
dataframe = pd.read_parquet(parquet_file)
|
| 102 |
+
dataframes.append(dataframe)
|
| 103 |
+
self.dataframe = pd.concat(dataframes)
|
| 104 |
+
|
| 105 |
+
# Extract messages list from dataframe
|
| 106 |
+
self.messages = self.dataframe[self.messages_key].apply(series_to_item).tolist()
|
| 107 |
+
|
| 108 |
+
# Extract tools list from dataframe
|
| 109 |
+
if self.tools_key in self.dataframe.columns:
|
| 110 |
+
self.tools = self.dataframe[self.tools_key].apply(convert_nested_value_to_list_recursive).tolist()
|
| 111 |
+
else:
|
| 112 |
+
self.tools = None
|
| 113 |
+
# Extract enable_thinking list from dataframe
|
| 114 |
+
if self.enable_thinking_key in self.dataframe.columns:
|
| 115 |
+
self.enable_thinking = self.dataframe[self.enable_thinking_key].tolist()
|
| 116 |
+
else:
|
| 117 |
+
self.enable_thinking = None
|
| 118 |
+
|
| 119 |
+
def __len__(self):
|
| 120 |
+
return len(self.messages)
|
| 121 |
+
|
| 122 |
+
def _process_message_tokens(
|
| 123 |
+
self,
|
| 124 |
+
messages: list[dict[str, Any]],
|
| 125 |
+
start_idx: int,
|
| 126 |
+
end_idx: int,
|
| 127 |
+
is_assistant: bool = False,
|
| 128 |
+
enable_thinking: Optional[bool] = None,
|
| 129 |
+
tools: Optional[list[dict[str, Any]]] = None,
|
| 130 |
+
) -> tuple[list[int], list[int], list[int]]:
|
| 131 |
+
"""
|
| 132 |
+
Process tokens for a single message or a group of messages.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
messages: List of message dictionaries
|
| 136 |
+
start_idx: Start index in messages list
|
| 137 |
+
end_idx: End index in messages list
|
| 138 |
+
is_assistant: Whether this is an assistant message
|
| 139 |
+
enable_thinking: Whether to enable thinking mode
|
| 140 |
+
|
| 141 |
+
Returns:
|
| 142 |
+
Tuple of (tokens, loss_mask, attention_mask)
|
| 143 |
+
"""
|
| 144 |
+
if start_idx > 0:
|
| 145 |
+
prev_applied_text = self.tokenizer.apply_chat_template(
|
| 146 |
+
messages[:start_idx],
|
| 147 |
+
tokenize=False,
|
| 148 |
+
add_generation_prompt=False,
|
| 149 |
+
enable_thinking=enable_thinking,
|
| 150 |
+
tools=tools,
|
| 151 |
+
**self.apply_chat_template_kwargs,
|
| 152 |
+
)
|
| 153 |
+
if is_assistant:
|
| 154 |
+
prev_applied_text_w_generation_prompt = self.tokenizer.apply_chat_template(
|
| 155 |
+
messages[:start_idx],
|
| 156 |
+
tokenize=False,
|
| 157 |
+
add_generation_prompt=True,
|
| 158 |
+
enable_thinking=enable_thinking,
|
| 159 |
+
tools=tools,
|
| 160 |
+
**self.apply_chat_template_kwargs,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
else:
|
| 164 |
+
prev_applied_text = ""
|
| 165 |
+
|
| 166 |
+
cur_applied_text = self.tokenizer.apply_chat_template(
|
| 167 |
+
messages[:end_idx],
|
| 168 |
+
tokenize=False,
|
| 169 |
+
add_generation_prompt=False,
|
| 170 |
+
enable_thinking=enable_thinking,
|
| 171 |
+
tools=tools,
|
| 172 |
+
**self.apply_chat_template_kwargs,
|
| 173 |
+
)
|
| 174 |
+
# Get tokens for the current message only
|
| 175 |
+
if is_assistant:
|
| 176 |
+
generation_prompt_text = prev_applied_text_w_generation_prompt[len(prev_applied_text) :]
|
| 177 |
+
generation_prompt_tokens = self.tokenizer.encode(
|
| 178 |
+
generation_prompt_text,
|
| 179 |
+
add_special_tokens=False,
|
| 180 |
+
)
|
| 181 |
+
_message_tokens = self.tokenizer.encode(
|
| 182 |
+
cur_applied_text[len(prev_applied_text_w_generation_prompt) :],
|
| 183 |
+
add_special_tokens=False,
|
| 184 |
+
)
|
| 185 |
+
message_tokens = generation_prompt_tokens + _message_tokens
|
| 186 |
+
loss_mask = [0] * (len(generation_prompt_tokens)) + [1] * (
|
| 187 |
+
len(message_tokens) - len(generation_prompt_tokens)
|
| 188 |
+
)
|
| 189 |
+
else:
|
| 190 |
+
message_tokens = self.tokenizer.encode(
|
| 191 |
+
cur_applied_text[len(prev_applied_text) :],
|
| 192 |
+
add_special_tokens=False,
|
| 193 |
+
)
|
| 194 |
+
loss_mask = [0] * len(message_tokens)
|
| 195 |
+
|
| 196 |
+
attention_mask = [1] * len(message_tokens)
|
| 197 |
+
|
| 198 |
+
return message_tokens, loss_mask, attention_mask
|
| 199 |
+
|
| 200 |
+
def _validate_and_convert_tokens(
|
| 201 |
+
self,
|
| 202 |
+
full_tokens: torch.Tensor,
|
| 203 |
+
concat_tokens: list[int],
|
| 204 |
+
concat_loss_mask: list[int],
|
| 205 |
+
concat_attention_mask: list[int],
|
| 206 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 207 |
+
"""
|
| 208 |
+
Validate tokenization and convert to tensors.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
full_tokens: Full conversation tokens
|
| 212 |
+
concat_tokens: Concatenated tokens
|
| 213 |
+
concat_loss_mask: Concatenated loss mask
|
| 214 |
+
concat_attention_mask: Concatenated attention mask
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
Tuple of (input_ids, loss_mask, attention_mask) as tensors
|
| 218 |
+
"""
|
| 219 |
+
full_tokens_list = full_tokens.tolist()
|
| 220 |
+
|
| 221 |
+
if len(concat_tokens) != len(full_tokens_list) or not all(
|
| 222 |
+
a == b for a, b in zip(concat_tokens, full_tokens_list, strict=True)
|
| 223 |
+
):
|
| 224 |
+
logging.warning(
|
| 225 |
+
f"Token mismatch detected! Full tokenization length: {len(full_tokens_list)}, Concatenated tokens "
|
| 226 |
+
f"length: {len(concat_tokens)}. Using concatenated version."
|
| 227 |
+
# f"full tokens text: {self.tokenizer.decode(full_tokens_list)}"
|
| 228 |
+
# f"concat tokens text: {self.tokenizer.decode(concat_tokens)}"
|
| 229 |
+
)
|
| 230 |
+
return (
|
| 231 |
+
torch.tensor(concat_tokens, dtype=torch.long),
|
| 232 |
+
torch.tensor(concat_loss_mask, dtype=torch.long),
|
| 233 |
+
torch.tensor(concat_attention_mask, dtype=torch.long),
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
return (
|
| 237 |
+
full_tokens,
|
| 238 |
+
torch.tensor(concat_loss_mask, dtype=torch.long),
|
| 239 |
+
torch.tensor(concat_attention_mask, dtype=torch.long),
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
def __getitem__(self, item):
|
| 243 |
+
tokenizer = self.tokenizer
|
| 244 |
+
messages = self.messages[item]
|
| 245 |
+
tools = self.tools[item] if self.tools is not None else None
|
| 246 |
+
enable_thinking = self.enable_thinking[item] if self.enable_thinking is not None else None
|
| 247 |
+
|
| 248 |
+
# First, get the full conversation tokens
|
| 249 |
+
try:
|
| 250 |
+
full_tokens = tokenizer.apply_chat_template(
|
| 251 |
+
messages,
|
| 252 |
+
tools=tools,
|
| 253 |
+
tokenize=True,
|
| 254 |
+
return_tensors="pt",
|
| 255 |
+
add_generation_prompt=False,
|
| 256 |
+
enable_thinking=enable_thinking,
|
| 257 |
+
**self.apply_chat_template_kwargs,
|
| 258 |
+
)
|
| 259 |
+
except Exception as e:
|
| 260 |
+
logging.error(
|
| 261 |
+
f"Error applying chat template: {e}\nMessages: {messages}\nTools: {tools}\nEnable thinking: "
|
| 262 |
+
f"{enable_thinking}"
|
| 263 |
+
)
|
| 264 |
+
raise
|
| 265 |
+
|
| 266 |
+
# Track concatenated tokens for validation
|
| 267 |
+
concat_tokens = []
|
| 268 |
+
concat_loss_mask = []
|
| 269 |
+
concat_attention_mask = []
|
| 270 |
+
|
| 271 |
+
i = 0
|
| 272 |
+
while i < len(messages):
|
| 273 |
+
cur_messages = messages[i]
|
| 274 |
+
if cur_messages["role"] == "assistant":
|
| 275 |
+
# Process assistant message
|
| 276 |
+
tokens, loss_mask, attention_mask = self._process_message_tokens(
|
| 277 |
+
messages, i, i + 1, is_assistant=True, enable_thinking=enable_thinking, tools=tools
|
| 278 |
+
)
|
| 279 |
+
i += 1
|
| 280 |
+
elif cur_messages["role"] == "tool":
|
| 281 |
+
# Process consecutive tool messages
|
| 282 |
+
st = i
|
| 283 |
+
ed = i + 1
|
| 284 |
+
while ed < len(messages) and messages[ed]["role"] == "tool":
|
| 285 |
+
ed += 1
|
| 286 |
+
tokens, loss_mask, attention_mask = self._process_message_tokens(
|
| 287 |
+
messages, st, ed, enable_thinking=enable_thinking, tools=tools
|
| 288 |
+
)
|
| 289 |
+
i = ed
|
| 290 |
+
elif cur_messages["role"] in ["user", "system"]:
|
| 291 |
+
# Process user or system message
|
| 292 |
+
if cur_messages["role"] == "system" and i != 0:
|
| 293 |
+
raise ValueError("System message should be the first message")
|
| 294 |
+
tokens, loss_mask, attention_mask = self._process_message_tokens(
|
| 295 |
+
messages, i, i + 1, enable_thinking=enable_thinking, tools=tools
|
| 296 |
+
)
|
| 297 |
+
i += 1
|
| 298 |
+
else:
|
| 299 |
+
raise ValueError(f"Unknown role: {cur_messages['role']}")
|
| 300 |
+
|
| 301 |
+
# override loss mask with mask in the dataset to handle multi-turn conversation
|
| 302 |
+
override_loss_mask = cur_messages.get("loss_mask", None)
|
| 303 |
+
if override_loss_mask is not None:
|
| 304 |
+
if isinstance(override_loss_mask, np.ndarray):
|
| 305 |
+
override_loss_mask = override_loss_mask.item()
|
| 306 |
+
assert isinstance(override_loss_mask, int), f"loss_mask should be int, got {type(override_loss_mask)}"
|
| 307 |
+
assert override_loss_mask in [0, 1], f"loss_mask should be 0 or 1, got {override_loss_mask}"
|
| 308 |
+
loss_mask = [override_loss_mask] * len(tokens)
|
| 309 |
+
|
| 310 |
+
concat_tokens.extend(tokens)
|
| 311 |
+
concat_loss_mask.extend(loss_mask)
|
| 312 |
+
concat_attention_mask.extend(attention_mask)
|
| 313 |
+
|
| 314 |
+
# Validate and convert tokens
|
| 315 |
+
input_ids, loss_mask, attention_mask = self._validate_and_convert_tokens(
|
| 316 |
+
full_tokens[0], concat_tokens, concat_loss_mask, concat_attention_mask
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
# encode prompt
|
| 320 |
+
if messages[0]["role"] == "system":
|
| 321 |
+
assert messages[1]["role"] == "user"
|
| 322 |
+
assert messages[2]["role"] == "assistant"
|
| 323 |
+
prompt_message_length = 2
|
| 324 |
+
elif messages[0]["role"] == "user":
|
| 325 |
+
assert messages[1]["role"] == "assistant"
|
| 326 |
+
prompt_message_length = 1
|
| 327 |
+
else:
|
| 328 |
+
raise ValueError(f"Unknown role: {messages[0]['role']}")
|
| 329 |
+
|
| 330 |
+
sequence_length = input_ids.shape[0]
|
| 331 |
+
# Handle sequence length
|
| 332 |
+
if self.pad_mode == DatasetPadMode.RIGHT:
|
| 333 |
+
if sequence_length < self.max_length:
|
| 334 |
+
# Pad sequences
|
| 335 |
+
pad_token_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else 0
|
| 336 |
+
padded_input_ids = torch.full((self.max_length - sequence_length,), pad_token_id, dtype=input_ids.dtype)
|
| 337 |
+
padded_attention_mask = torch.zeros((self.max_length - sequence_length,), dtype=attention_mask.dtype)
|
| 338 |
+
padded_loss_mask = torch.zeros((self.max_length - sequence_length,), dtype=loss_mask.dtype)
|
| 339 |
+
|
| 340 |
+
input_ids = torch.cat((input_ids, padded_input_ids))
|
| 341 |
+
attention_mask = torch.cat((attention_mask, padded_attention_mask))
|
| 342 |
+
loss_mask = torch.cat((loss_mask, padded_loss_mask))
|
| 343 |
+
elif sequence_length > self.max_length:
|
| 344 |
+
if self.truncation == "left":
|
| 345 |
+
input_ids = input_ids[-self.max_length :]
|
| 346 |
+
attention_mask = attention_mask[-self.max_length :]
|
| 347 |
+
loss_mask = loss_mask[-self.max_length :]
|
| 348 |
+
elif self.truncation == "right":
|
| 349 |
+
input_ids = input_ids[: self.max_length]
|
| 350 |
+
attention_mask = attention_mask[: self.max_length]
|
| 351 |
+
loss_mask = loss_mask[: self.max_length]
|
| 352 |
+
elif self.truncation == "error":
|
| 353 |
+
raise ValueError(f"{sequence_length=} is larger than {self.max_length=}")
|
| 354 |
+
else:
|
| 355 |
+
raise ValueError(f"Unknown truncation method {self.truncation}")
|
| 356 |
+
|
| 357 |
+
# Create position IDs
|
| 358 |
+
position_ids = torch.arange(len(input_ids), dtype=torch.long)
|
| 359 |
+
# Zero out position IDs for padding
|
| 360 |
+
position_ids = position_ids * attention_mask
|
| 361 |
+
|
| 362 |
+
return {
|
| 363 |
+
"input_ids": input_ids,
|
| 364 |
+
"attention_mask": attention_mask,
|
| 365 |
+
"position_ids": position_ids,
|
| 366 |
+
"loss_mask": loss_mask,
|
| 367 |
+
}
|
| 368 |
+
elif self.pad_mode == DatasetPadMode.LEFT_RIGHT:
|
| 369 |
+
assert self.truncation == "error", "Only support error truncation for left_right pad mode"
|
| 370 |
+
prompt_str = self.tokenizer.apply_chat_template(
|
| 371 |
+
messages[:prompt_message_length],
|
| 372 |
+
tools=tools,
|
| 373 |
+
tokenize=False,
|
| 374 |
+
add_generation_prompt=True,
|
| 375 |
+
enable_thinking=enable_thinking,
|
| 376 |
+
**self.apply_chat_template_kwargs,
|
| 377 |
+
)
|
| 378 |
+
prompt_ids = self.tokenizer.encode(prompt_str, add_special_tokens=False)
|
| 379 |
+
prompt_length = len(prompt_ids)
|
| 380 |
+
prompt_ids = input_ids[:prompt_length].unsqueeze(0)
|
| 381 |
+
prompt_attention_mask = attention_mask[:prompt_length].unsqueeze(0)
|
| 382 |
+
prompt_loss_mask = loss_mask[:prompt_length].unsqueeze(0)
|
| 383 |
+
response_ids = input_ids[prompt_length:].unsqueeze(0)
|
| 384 |
+
response_attention_mask = attention_mask[prompt_length:].unsqueeze(0)
|
| 385 |
+
response_loss_mask = loss_mask[prompt_length:].unsqueeze(0)
|
| 386 |
+
|
| 387 |
+
assert prompt_loss_mask.sum().item() == 0
|
| 388 |
+
|
| 389 |
+
prompt_ids, prompt_attention_mask = postprocess_data(
|
| 390 |
+
input_ids=prompt_ids,
|
| 391 |
+
attention_mask=prompt_attention_mask,
|
| 392 |
+
max_length=self.max_prompt_length,
|
| 393 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 394 |
+
left_pad=True,
|
| 395 |
+
truncation=self.truncation,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
response_ids, response_attention_mask = postprocess_data(
|
| 399 |
+
input_ids=response_ids,
|
| 400 |
+
attention_mask=response_attention_mask,
|
| 401 |
+
max_length=self.max_response_length,
|
| 402 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 403 |
+
left_pad=False,
|
| 404 |
+
truncation=self.truncation,
|
| 405 |
+
)
|
| 406 |
+
response_loss_mask = pad_sequence_to_length(
|
| 407 |
+
response_loss_mask, max_seq_len=self.max_response_length, pad_token_id=0, left_pad=False
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
prompt_ids = prompt_ids[0]
|
| 411 |
+
prompt_attention_mask = prompt_attention_mask[0]
|
| 412 |
+
response_ids = response_ids[0]
|
| 413 |
+
response_attention_mask = response_attention_mask[0]
|
| 414 |
+
response_loss_mask = response_loss_mask[0]
|
| 415 |
+
|
| 416 |
+
assert response_attention_mask[0].item() == 1
|
| 417 |
+
assert response_loss_mask[0].item() == 1
|
| 418 |
+
|
| 419 |
+
input_ids = torch.cat((prompt_ids, response_ids), dim=0)
|
| 420 |
+
attention_mask = torch.cat((prompt_attention_mask, response_attention_mask), dim=0)
|
| 421 |
+
position_ids = compute_position_id_with_mask(attention_mask)
|
| 422 |
+
|
| 423 |
+
return {
|
| 424 |
+
"input_ids": input_ids,
|
| 425 |
+
"attention_mask": attention_mask,
|
| 426 |
+
"position_ids": position_ids,
|
| 427 |
+
"responses": response_ids,
|
| 428 |
+
"response_mask": response_loss_mask,
|
| 429 |
+
}
|
| 430 |
+
elif self.pad_mode == DatasetPadMode.NO_PADDING:
|
| 431 |
+
# truncate input_ids if it is longer than max_length
|
| 432 |
+
if len(input_ids) > self.max_length:
|
| 433 |
+
input_ids = input_ids[: self.max_length]
|
| 434 |
+
loss_mask = loss_mask[: self.max_length]
|
| 435 |
+
# create position IDs
|
| 436 |
+
position_ids = torch.arange(len(input_ids), dtype=torch.long)
|
| 437 |
+
# return nested tensor with out padding
|
| 438 |
+
return {
|
| 439 |
+
"input_ids": input_ids,
|
| 440 |
+
"position_ids": position_ids,
|
| 441 |
+
"loss_mask": loss_mask,
|
| 442 |
+
}
|
verl/verl/utils/dataset/rl_dataset.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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copyright 2023-2024 SGLang Team
|
| 3 |
+
# Copyright 2025 ModelBest Inc. and/or its affiliates
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
import logging
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
from collections import defaultdict
|
| 22 |
+
from typing import Optional
|
| 23 |
+
|
| 24 |
+
import datasets
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
from omegaconf import DictConfig, ListConfig
|
| 28 |
+
from torch.utils.data import Dataset
|
| 29 |
+
from transformers import PreTrainedTokenizer, ProcessorMixin
|
| 30 |
+
|
| 31 |
+
import verl.utils.torch_functional as verl_F
|
| 32 |
+
from verl.utils.model import compute_position_id_with_mask
|
| 33 |
+
|
| 34 |
+
logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def collate_fn(data_list: list[dict]) -> dict:
|
| 38 |
+
"""
|
| 39 |
+
Collate a batch of sample dicts into batched tensors and arrays.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
data_list: List of dicts mapping feature names to torch.Tensor or other values.
|
| 43 |
+
|
| 44 |
+
Returns:
|
| 45 |
+
Dict where tensor entries are stacked into a torch.Tensor of shape
|
| 46 |
+
(batch_size, \*dims) and non-tensor entries are converted to
|
| 47 |
+
np.ndarray of dtype object with shape (batch_size,).
|
| 48 |
+
"""
|
| 49 |
+
tensors = defaultdict(list)
|
| 50 |
+
non_tensors = defaultdict(list)
|
| 51 |
+
|
| 52 |
+
for data in data_list:
|
| 53 |
+
for key, val in data.items():
|
| 54 |
+
if isinstance(val, torch.Tensor):
|
| 55 |
+
tensors[key].append(val)
|
| 56 |
+
else:
|
| 57 |
+
non_tensors[key].append(val)
|
| 58 |
+
|
| 59 |
+
for key, val in tensors.items():
|
| 60 |
+
tensors[key] = torch.stack(val, dim=0)
|
| 61 |
+
|
| 62 |
+
for key, val in non_tensors.items():
|
| 63 |
+
non_tensors[key] = np.fromiter(val, dtype=object, count=len(val))
|
| 64 |
+
|
| 65 |
+
return {**tensors, **non_tensors}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class RLHFDataset(Dataset):
|
| 69 |
+
"""
|
| 70 |
+
Load and preprocess RLHF data from Parquet files.
|
| 71 |
+
|
| 72 |
+
- Caches files locally.
|
| 73 |
+
- Reads into a HuggingFace Dataset and tokenizes prompts.
|
| 74 |
+
- Optionally handles images/videos via a ProcessorMixin.
|
| 75 |
+
- Filters prompts over a max length.
|
| 76 |
+
- Supports resuming from checkpoints.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
data_files (str or list): Path(s) to Parquet file(s).
|
| 80 |
+
tokenizer (PreTrainedTokenizer): For the tokenization of text to token IDs.
|
| 81 |
+
config (DictConfig): Options like cache_dir, prompt_key, max_prompt_length, truncation, etc.
|
| 82 |
+
processor (ProcessorMixin, optional): Multimodal preprocessor for images/videos.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(
|
| 86 |
+
self,
|
| 87 |
+
data_files: str | list[str],
|
| 88 |
+
tokenizer: PreTrainedTokenizer,
|
| 89 |
+
config: DictConfig,
|
| 90 |
+
processor: Optional[ProcessorMixin] = None,
|
| 91 |
+
):
|
| 92 |
+
if not isinstance(data_files, list | ListConfig):
|
| 93 |
+
data_files = [data_files]
|
| 94 |
+
|
| 95 |
+
self.data_files = copy.deepcopy(data_files)
|
| 96 |
+
self.original_data_files = copy.deepcopy(data_files) # use for resume
|
| 97 |
+
self.tokenizer = tokenizer
|
| 98 |
+
self.processor = processor
|
| 99 |
+
self.config = config
|
| 100 |
+
|
| 101 |
+
self.cache_dir = os.path.expanduser(config.get("cache_dir", "~/.cache/verl/rlhf"))
|
| 102 |
+
self.prompt_key = config.get("prompt_key", "prompt")
|
| 103 |
+
self.image_key = config.get("image_key", "images")
|
| 104 |
+
self.video_key = config.get("video_key", "videos")
|
| 105 |
+
self.max_prompt_length = config.get("max_prompt_length", 1024)
|
| 106 |
+
self.return_raw_chat = config.get("return_raw_chat", False)
|
| 107 |
+
self.return_full_prompt = config.get("return_full_prompt", False)
|
| 108 |
+
self.truncation = config.get("truncation", "error")
|
| 109 |
+
self.filter_overlong_prompts = config.get("filter_overlong_prompts", True)
|
| 110 |
+
self.apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", {})
|
| 111 |
+
|
| 112 |
+
self.num_workers = config.get("filter_overlong_prompts_workers", max(1, os.cpu_count() // 4))
|
| 113 |
+
self.num_workers = min(self.num_workers, os.cpu_count())
|
| 114 |
+
self.use_shm = config.get("use_shm", False)
|
| 115 |
+
self.chat_template_func = config.get("chat_template_func", None)
|
| 116 |
+
self.need_tools_kwargs = config.get("need_tools_kwargs", False)
|
| 117 |
+
self.filter_prompts = config.get("filter_prompts", True)
|
| 118 |
+
self.serialize_dataset = False
|
| 119 |
+
self.return_multi_modal_inputs = config.get("return_multi_modal_inputs", True)
|
| 120 |
+
|
| 121 |
+
self._download()
|
| 122 |
+
self._read_files_and_tokenize()
|
| 123 |
+
|
| 124 |
+
def _download(self, use_origin_parquet=False):
|
| 125 |
+
from verl.utils.fs import copy_to_local
|
| 126 |
+
|
| 127 |
+
data_files = self.data_files if not use_origin_parquet else self.original_data_files
|
| 128 |
+
for i, parquet_file in enumerate(data_files):
|
| 129 |
+
self.data_files[i] = copy_to_local(src=parquet_file, cache_dir=self.cache_dir, use_shm=self.use_shm)
|
| 130 |
+
|
| 131 |
+
def _read_files_and_tokenize(self):
|
| 132 |
+
dataframes = []
|
| 133 |
+
for parquet_file in self.data_files:
|
| 134 |
+
# read parquet files and cache
|
| 135 |
+
dataframe = datasets.load_dataset("parquet", data_files=parquet_file)["train"]
|
| 136 |
+
dataframes.append(dataframe)
|
| 137 |
+
self.dataframe: datasets.Dataset = datasets.concatenate_datasets(dataframes)
|
| 138 |
+
|
| 139 |
+
print(f"dataset len: {len(self.dataframe)}")
|
| 140 |
+
|
| 141 |
+
self.dataframe = self.maybe_filter_out_long_prompts(self.dataframe)
|
| 142 |
+
|
| 143 |
+
def maybe_filter_out_long_prompts(self, dataframe: datasets.Dataset = None):
|
| 144 |
+
# filter out too long prompts
|
| 145 |
+
if self.filter_overlong_prompts:
|
| 146 |
+
tokenizer = self.tokenizer
|
| 147 |
+
processor = self.processor
|
| 148 |
+
prompt_key = self.prompt_key
|
| 149 |
+
image_key = self.image_key
|
| 150 |
+
video_key = self.video_key
|
| 151 |
+
|
| 152 |
+
if processor is not None:
|
| 153 |
+
from verl.utils.dataset.vision_utils import process_image, process_video
|
| 154 |
+
|
| 155 |
+
def doc2len(doc) -> int:
|
| 156 |
+
messages = self._build_messages(doc)
|
| 157 |
+
raw_prompt = self.processor.apply_chat_template(
|
| 158 |
+
messages, add_generation_prompt=True, tokenize=False, **self.apply_chat_template_kwargs
|
| 159 |
+
)
|
| 160 |
+
images = (
|
| 161 |
+
[process_image(image) for image in doc[image_key]]
|
| 162 |
+
if image_key in doc and doc[image_key]
|
| 163 |
+
else None
|
| 164 |
+
)
|
| 165 |
+
videos = (
|
| 166 |
+
[process_video(video) for video in doc[video_key]]
|
| 167 |
+
if video_key in doc and doc[video_key]
|
| 168 |
+
else None
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
return len(processor(text=[raw_prompt], images=images, videos=videos)["input_ids"][0])
|
| 172 |
+
|
| 173 |
+
else:
|
| 174 |
+
|
| 175 |
+
def doc2len(doc) -> int:
|
| 176 |
+
return len(
|
| 177 |
+
tokenizer.apply_chat_template(
|
| 178 |
+
doc[prompt_key], add_generation_prompt=True, **self.apply_chat_template_kwargs
|
| 179 |
+
)
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
dataframe = dataframe.filter(
|
| 183 |
+
lambda doc: doc2len(doc) <= self.max_prompt_length,
|
| 184 |
+
num_proc=self.num_workers,
|
| 185 |
+
desc=f"Filtering prompts longer than {self.max_prompt_length} tokens",
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
print(f"filter dataset len: {len(dataframe)}")
|
| 189 |
+
return dataframe
|
| 190 |
+
|
| 191 |
+
def resume_dataset_state(self):
|
| 192 |
+
self.serialize_dataset = not hasattr(self, "original_data_files")
|
| 193 |
+
# resume dataframe if not it's serialized in data.pt
|
| 194 |
+
if not self.serialize_dataset:
|
| 195 |
+
self._download(use_origin_parquet=True) # download and resume from original parquet files
|
| 196 |
+
self._read_files_and_tokenize()
|
| 197 |
+
else:
|
| 198 |
+
print(r"old dataloader ckpt file is used, please train from scratch for better ckpt performance")
|
| 199 |
+
|
| 200 |
+
def __len__(self):
|
| 201 |
+
return len(self.dataframe)
|
| 202 |
+
|
| 203 |
+
def _build_messages(self, example: dict):
|
| 204 |
+
messages: list = example.pop(self.prompt_key)
|
| 205 |
+
|
| 206 |
+
if self.image_key in example or self.video_key in example:
|
| 207 |
+
for message in messages:
|
| 208 |
+
content = message["content"]
|
| 209 |
+
content_list = []
|
| 210 |
+
segments = re.split("(<image>|<video>)", content)
|
| 211 |
+
segments = [item for item in segments if item != ""]
|
| 212 |
+
for segment in segments:
|
| 213 |
+
if segment == "<image>":
|
| 214 |
+
content_list.append({"type": "image"})
|
| 215 |
+
elif segment == "<video>":
|
| 216 |
+
content_list.append({"type": "video"})
|
| 217 |
+
else:
|
| 218 |
+
content_list.append({"type": "text", "text": segment})
|
| 219 |
+
|
| 220 |
+
message["content"] = content_list
|
| 221 |
+
|
| 222 |
+
return messages
|
| 223 |
+
|
| 224 |
+
def __getitem__(self, item):
|
| 225 |
+
"""
|
| 226 |
+
Note that we also return the raw_input_ids so that it can be combined with other chat template
|
| 227 |
+
"""
|
| 228 |
+
row_dict: dict = self.dataframe[item]
|
| 229 |
+
messages = self._build_messages(row_dict)
|
| 230 |
+
model_inputs = {}
|
| 231 |
+
|
| 232 |
+
if self.processor is not None:
|
| 233 |
+
from verl.utils.dataset.vision_utils import process_image, process_video
|
| 234 |
+
|
| 235 |
+
raw_prompt = self.processor.apply_chat_template(
|
| 236 |
+
messages, add_generation_prompt=True, tokenize=False, **self.apply_chat_template_kwargs
|
| 237 |
+
)
|
| 238 |
+
multi_modal_data = {}
|
| 239 |
+
|
| 240 |
+
images = None
|
| 241 |
+
row_dict_images = row_dict.pop(self.image_key, None)
|
| 242 |
+
if row_dict_images:
|
| 243 |
+
images = [process_image(image) for image in row_dict_images]
|
| 244 |
+
|
| 245 |
+
# due to the image key is "image" instead of "images" in vllm, we need to use "image" here
|
| 246 |
+
# link: https://github.com/vllm-project/vllm/blob/3c545c0c3b98ee642373a308197d750d0e449403/vllm/multimodal/parse.py#L205
|
| 247 |
+
multi_modal_data["image"] = images
|
| 248 |
+
|
| 249 |
+
videos = None
|
| 250 |
+
row_dict_videos = row_dict.pop(self.video_key, None)
|
| 251 |
+
if row_dict_videos:
|
| 252 |
+
videos = [process_video(video) for video in row_dict_videos]
|
| 253 |
+
|
| 254 |
+
# due to the video key is "video" instead of "videos" in vllm, we need to use "video" here
|
| 255 |
+
# link: https://github.com/vllm-project/vllm/blob/3c545c0c3b98ee642373a308197d750d0e449403/vllm/multimodal/parse.py#L205
|
| 256 |
+
multi_modal_data["video"] = [video.numpy() for video in videos]
|
| 257 |
+
|
| 258 |
+
model_inputs = self.processor(text=[raw_prompt], images=images, videos=videos, return_tensors="pt")
|
| 259 |
+
|
| 260 |
+
input_ids = model_inputs.pop("input_ids")
|
| 261 |
+
attention_mask = model_inputs.pop("attention_mask")
|
| 262 |
+
|
| 263 |
+
if "second_per_grid_ts" in model_inputs:
|
| 264 |
+
model_inputs.pop("second_per_grid_ts")
|
| 265 |
+
|
| 266 |
+
# There's a trap here, multi_modal_inputs has to be a dict, not BatchFeature
|
| 267 |
+
row_dict["multi_modal_data"] = multi_modal_data
|
| 268 |
+
|
| 269 |
+
# We will do batch.union() in the trainer,
|
| 270 |
+
# so we cannot have "multi_modal_inputs" in row_dict if rollout generates new multi_modal_inputs
|
| 271 |
+
if self.return_multi_modal_inputs:
|
| 272 |
+
row_dict["multi_modal_inputs"] = dict(model_inputs)
|
| 273 |
+
|
| 274 |
+
# second_per_grid_ts isn't used for training, just for mrope
|
| 275 |
+
row_dict["multi_modal_inputs"].pop("second_per_grid_ts", None)
|
| 276 |
+
|
| 277 |
+
else:
|
| 278 |
+
if self.apply_chat_template_kwargs.get("chat_template") is None:
|
| 279 |
+
assert hasattr(self.tokenizer, "chat_template"), (
|
| 280 |
+
"chat_template should be provided in apply_chat_template_kwargs or tokenizer config, "
|
| 281 |
+
"models like GLM can copy chat_template.jinja from instruct models"
|
| 282 |
+
)
|
| 283 |
+
raw_prompt = self.tokenizer.apply_chat_template(
|
| 284 |
+
messages, add_generation_prompt=True, tokenize=False, **self.apply_chat_template_kwargs
|
| 285 |
+
)
|
| 286 |
+
model_inputs = self.tokenizer(raw_prompt, return_tensors="pt", add_special_tokens=False)
|
| 287 |
+
input_ids = model_inputs.pop("input_ids")
|
| 288 |
+
attention_mask = model_inputs.pop("attention_mask")
|
| 289 |
+
|
| 290 |
+
input_ids, attention_mask = verl_F.postprocess_data(
|
| 291 |
+
input_ids=input_ids,
|
| 292 |
+
attention_mask=attention_mask,
|
| 293 |
+
max_length=self.max_prompt_length,
|
| 294 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 295 |
+
left_pad=True,
|
| 296 |
+
truncation=self.truncation,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
if self.processor is not None and "Qwen2VLImageProcessor" in self.processor.image_processor.__class__.__name__:
|
| 300 |
+
# qwen-vl mrope
|
| 301 |
+
if "Qwen3VLProcessor" in self.processor.__class__.__name__:
|
| 302 |
+
from verl.models.transformers.qwen3_vl import get_rope_index
|
| 303 |
+
else:
|
| 304 |
+
from verl.models.transformers.qwen2_vl import get_rope_index
|
| 305 |
+
|
| 306 |
+
vision_position_ids = get_rope_index(
|
| 307 |
+
self.processor,
|
| 308 |
+
input_ids=input_ids[0],
|
| 309 |
+
image_grid_thw=model_inputs.get("image_grid_thw"),
|
| 310 |
+
video_grid_thw=model_inputs.get("video_grid_thw"),
|
| 311 |
+
second_per_grid_ts=model_inputs.get("second_per_grid_ts"),
|
| 312 |
+
attention_mask=attention_mask[0],
|
| 313 |
+
) # (3, seq_length)
|
| 314 |
+
valid_mask = attention_mask[0].bool()
|
| 315 |
+
text_position_ids = torch.ones((1, len(input_ids[0])), dtype=torch.long)
|
| 316 |
+
text_position_ids[0, valid_mask] = torch.arange(valid_mask.sum().item())
|
| 317 |
+
position_ids = [torch.cat((text_position_ids, vision_position_ids), dim=0)] # (1, 4, seq_length)
|
| 318 |
+
elif self.processor is not None and "Glm4vImageProcessor" in self.processor.image_processor.__class__.__name__:
|
| 319 |
+
from verl.models.transformers.glm4v import get_rope_index
|
| 320 |
+
|
| 321 |
+
vision_position_ids = get_rope_index(
|
| 322 |
+
self.processor,
|
| 323 |
+
input_ids=input_ids[0],
|
| 324 |
+
image_grid_thw=model_inputs.get("image_grid_thw"),
|
| 325 |
+
video_grid_thw=model_inputs.get("video_grid_thw"),
|
| 326 |
+
attention_mask=attention_mask[0],
|
| 327 |
+
) # (3, seq_length)
|
| 328 |
+
valid_mask = attention_mask[0].bool()
|
| 329 |
+
text_position_ids = torch.ones((1, len(input_ids[0])), dtype=torch.long)
|
| 330 |
+
text_position_ids[0, valid_mask] = torch.arange(valid_mask.sum().item())
|
| 331 |
+
position_ids = [torch.cat((text_position_ids, vision_position_ids), dim=0)] # (1, 4, seq_length)
|
| 332 |
+
else:
|
| 333 |
+
position_ids = compute_position_id_with_mask(attention_mask)
|
| 334 |
+
|
| 335 |
+
row_dict["input_ids"] = input_ids[0]
|
| 336 |
+
row_dict["attention_mask"] = attention_mask[0]
|
| 337 |
+
row_dict["position_ids"] = position_ids[0]
|
| 338 |
+
|
| 339 |
+
raw_prompt_ids = self.tokenizer.encode(raw_prompt, add_special_tokens=False)
|
| 340 |
+
if len(raw_prompt_ids) > self.max_prompt_length:
|
| 341 |
+
if self.truncation == "left":
|
| 342 |
+
raw_prompt_ids = raw_prompt_ids[-self.max_prompt_length :]
|
| 343 |
+
elif self.truncation == "right":
|
| 344 |
+
raw_prompt_ids = raw_prompt_ids[: self.max_prompt_length]
|
| 345 |
+
elif self.truncation == "middle":
|
| 346 |
+
left_half = self.max_prompt_length // 2
|
| 347 |
+
right_half = self.max_prompt_length - left_half
|
| 348 |
+
raw_prompt_ids = raw_prompt_ids[:left_half] + raw_prompt_ids[-right_half:]
|
| 349 |
+
elif self.truncation == "error":
|
| 350 |
+
raise RuntimeError(f"Prompt length {len(raw_prompt_ids)} is longer than {self.max_prompt_length}.")
|
| 351 |
+
|
| 352 |
+
row_dict["raw_prompt_ids"] = raw_prompt_ids
|
| 353 |
+
# encode prompts without chat template
|
| 354 |
+
if self.return_raw_chat:
|
| 355 |
+
row_dict["raw_prompt"] = messages
|
| 356 |
+
|
| 357 |
+
# get prompts with chat template
|
| 358 |
+
if self.return_full_prompt:
|
| 359 |
+
row_dict["full_prompts"] = raw_prompt # array of strings
|
| 360 |
+
|
| 361 |
+
# add index for each prompt
|
| 362 |
+
if "extra_info" not in row_dict or row_dict["extra_info"] is None:
|
| 363 |
+
row_dict["extra_info"] = dict()
|
| 364 |
+
index = row_dict.get("extra_info", {}).get("index", 0)
|
| 365 |
+
tools_kwargs = row_dict.get("extra_info", {}).get("tools_kwargs", {})
|
| 366 |
+
interaction_kwargs = row_dict.get("extra_info", {}).get("interaction_kwargs", {})
|
| 367 |
+
need_tools_kwargs = row_dict.get("extra_info", {}).get("need_tools_kwargs", self.need_tools_kwargs)
|
| 368 |
+
if need_tools_kwargs and not tools_kwargs:
|
| 369 |
+
logger.warning("tools_kwargs is empty for index {}, data source: {}", index, row_dict["data_source"])
|
| 370 |
+
row_dict["index"] = index
|
| 371 |
+
row_dict["tools_kwargs"] = tools_kwargs
|
| 372 |
+
row_dict["interaction_kwargs"] = interaction_kwargs
|
| 373 |
+
return row_dict
|
| 374 |
+
|
| 375 |
+
def __getstate__(self):
|
| 376 |
+
if not self.serialize_dataset:
|
| 377 |
+
state = self.__dict__.copy()
|
| 378 |
+
|
| 379 |
+
if "dataframe" in state:
|
| 380 |
+
del state["dataframe"]
|
| 381 |
+
return state
|
| 382 |
+
|
| 383 |
+
return self.__dict__.copy()
|
verl/verl/utils/dataset/rm_dataset.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
import torch
|
| 19 |
+
from torch.utils.data import Dataset
|
| 20 |
+
|
| 21 |
+
from verl.utils import hf_tokenizer
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def download_files_distributed(download_fn):
|
| 25 |
+
import torch.distributed
|
| 26 |
+
|
| 27 |
+
if torch.distributed.is_initialized():
|
| 28 |
+
if torch.distributed.get_rank() == 0:
|
| 29 |
+
# download files
|
| 30 |
+
download_fn()
|
| 31 |
+
|
| 32 |
+
torch.distributed.barrier()
|
| 33 |
+
else:
|
| 34 |
+
# download anyway
|
| 35 |
+
download_fn()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class RMDataset(Dataset):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
parquet_files: str | list[str],
|
| 42 |
+
tokenizer,
|
| 43 |
+
prompt_key="prompt",
|
| 44 |
+
chosen_key="chosen",
|
| 45 |
+
rejected_key="rejected",
|
| 46 |
+
max_length=1024,
|
| 47 |
+
add_eos=True,
|
| 48 |
+
cache_dir="~/.cache/verl/rm",
|
| 49 |
+
):
|
| 50 |
+
if not isinstance(parquet_files, list):
|
| 51 |
+
parquet_files = [parquet_files]
|
| 52 |
+
|
| 53 |
+
self.parquet_files = parquet_files
|
| 54 |
+
self.cache_dir = os.path.expanduser(cache_dir)
|
| 55 |
+
if isinstance(tokenizer, str):
|
| 56 |
+
tokenizer = hf_tokenizer(tokenizer)
|
| 57 |
+
self.tokenizer = tokenizer
|
| 58 |
+
|
| 59 |
+
self.prompt_key = prompt_key
|
| 60 |
+
self.chosen_key = chosen_key
|
| 61 |
+
self.rejected_key = rejected_key
|
| 62 |
+
|
| 63 |
+
self.add_eos = add_eos
|
| 64 |
+
self.max_length = max_length
|
| 65 |
+
|
| 66 |
+
self._download()
|
| 67 |
+
self._read_files_and_tokenize()
|
| 68 |
+
|
| 69 |
+
def _download(self):
|
| 70 |
+
def _download_files():
|
| 71 |
+
from verl.utils.fs import copy, is_non_local
|
| 72 |
+
|
| 73 |
+
os.makedirs(self.cache_dir, exist_ok=True)
|
| 74 |
+
assert os.path.exists(self.cache_dir)
|
| 75 |
+
for i, parquet_file in enumerate(self.parquet_files):
|
| 76 |
+
if is_non_local(parquet_file):
|
| 77 |
+
dst = os.path.join(self.cache_dir, os.path.basename(parquet_file))
|
| 78 |
+
if not os.path.exists(dst):
|
| 79 |
+
copy(src=parquet_file, dst=dst)
|
| 80 |
+
self.parquet_files[i] = dst
|
| 81 |
+
|
| 82 |
+
download_files_distributed(_download_files)
|
| 83 |
+
|
| 84 |
+
def _read_files_and_tokenize(self):
|
| 85 |
+
dataframes = []
|
| 86 |
+
for parquet_file in self.parquet_files:
|
| 87 |
+
# read parquet files and cache
|
| 88 |
+
dataframe = pd.read_parquet(parquet_file)
|
| 89 |
+
dataframes.append(dataframe)
|
| 90 |
+
self.dataframe = pd.concat(dataframes)
|
| 91 |
+
self.prompts = self.dataframe[self.prompt_key].tolist()
|
| 92 |
+
self.chosen_responses = self.dataframe[self.chosen_key].tolist()
|
| 93 |
+
self.rejected_responses = self.dataframe[self.rejected_key].tolist()
|
| 94 |
+
|
| 95 |
+
def __len__(self):
|
| 96 |
+
return len(self.prompts)
|
| 97 |
+
|
| 98 |
+
def _pad_to_length(self, input_ids, attention_mask):
|
| 99 |
+
curr_length = input_ids.shape[-1]
|
| 100 |
+
|
| 101 |
+
if curr_length < self.max_length:
|
| 102 |
+
input_ids = torch.cat(
|
| 103 |
+
(input_ids, torch.zeros(size=(self.max_length - curr_length,), dtype=input_ids.dtype)), dim=-1
|
| 104 |
+
)
|
| 105 |
+
attention_mask = torch.cat(
|
| 106 |
+
(attention_mask, torch.zeros(size=(self.max_length - curr_length,), dtype=attention_mask.dtype)), dim=-1
|
| 107 |
+
)
|
| 108 |
+
elif curr_length > self.max_length:
|
| 109 |
+
input_ids = input_ids[: self.max_length]
|
| 110 |
+
attention_mask = attention_mask[: self.max_length]
|
| 111 |
+
|
| 112 |
+
return input_ids, attention_mask
|
| 113 |
+
|
| 114 |
+
def __getitem__(self, item):
|
| 115 |
+
prompt = self.prompts[item]
|
| 116 |
+
chosen_response = self.chosen_responses[item]
|
| 117 |
+
rejected_response = self.rejected_responses[item]
|
| 118 |
+
|
| 119 |
+
prompt_ids = self.tokenizer(prompt, return_tensors="pt")["input_ids"][0]
|
| 120 |
+
chosen_response_ids = self.tokenizer(chosen_response, return_tensors="pt")["input_ids"][0]
|
| 121 |
+
rejected_response_ids = self.tokenizer(rejected_response, return_tensors="pt")["input_ids"][0]
|
| 122 |
+
|
| 123 |
+
if self.add_eos:
|
| 124 |
+
chosen_response_ids = torch.cat((chosen_response_ids, torch.tensor([self.tokenizer.eos_token_id])), dim=-1)
|
| 125 |
+
rejected_response_ids = torch.cat(
|
| 126 |
+
(rejected_response_ids, torch.tensor([self.tokenizer.eos_token_id])), dim=-1
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
chosen_input_ids = torch.cat((prompt_ids, chosen_response_ids), dim=-1)
|
| 130 |
+
chosen_attention_mask = torch.ones_like(chosen_input_ids)
|
| 131 |
+
|
| 132 |
+
rejected_input_ids = torch.cat((prompt_ids, rejected_response_ids), dim=-1)
|
| 133 |
+
rejected_attention_mask = torch.ones_like(rejected_input_ids)
|
| 134 |
+
|
| 135 |
+
chosen_input_ids, chosen_attention_mask = self._pad_to_length(chosen_input_ids, chosen_attention_mask)
|
| 136 |
+
rejected_input_ids, rejected_attention_mask = self._pad_to_length(rejected_input_ids, rejected_attention_mask)
|
| 137 |
+
|
| 138 |
+
input_ids = torch.stack((chosen_input_ids, rejected_input_ids), dim=0)
|
| 139 |
+
attention_mask = torch.stack((chosen_attention_mask, rejected_attention_mask), dim=0)
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"input_ids": input_ids,
|
| 143 |
+
"attention_mask": attention_mask,
|
| 144 |
+
}
|
verl/verl/utils/dataset/sft_dataset.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
SFT dataset
|
| 16 |
+
- We assume user pass a single parquet file.
|
| 17 |
+
- We load all the data into the memory.
|
| 18 |
+
Each parquet file contains
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import pandas as pd
|
| 22 |
+
import torch
|
| 23 |
+
from omegaconf.listconfig import ListConfig
|
| 24 |
+
from torch.utils.data import Dataset
|
| 25 |
+
from transformers import PreTrainedTokenizer
|
| 26 |
+
|
| 27 |
+
from verl.utils import hf_tokenizer
|
| 28 |
+
from verl.utils.fs import copy_to_local
|
| 29 |
+
from verl.utils.model import compute_position_id_with_mask
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class SFTDataset(Dataset):
|
| 33 |
+
"""
|
| 34 |
+
This is an in-memory SFTDataset
|
| 35 |
+
|
| 36 |
+
Arguments:
|
| 37 |
+
config (OmegaConf): the data config
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, parquet_files: str | ListConfig, tokenizer, config):
|
| 41 |
+
prompt_key = config.get("prompt_key", "prompt")
|
| 42 |
+
prompt_dict_keys = config.get("prompt_dict_keys", None)
|
| 43 |
+
response_key = config.get("response_key", "response")
|
| 44 |
+
response_dict_keys = config.get("response_dict_keys", None)
|
| 45 |
+
max_length = config.get("max_length", 1024)
|
| 46 |
+
truncation = config.get("truncation", "error")
|
| 47 |
+
use_shm = config.get("use_shm", False)
|
| 48 |
+
self.apply_chat_template_kwargs = config.get("apply_chat_template_kwargs", {})
|
| 49 |
+
|
| 50 |
+
assert truncation in ["error", "left", "right"]
|
| 51 |
+
self.truncation = truncation
|
| 52 |
+
self.use_shm = use_shm
|
| 53 |
+
|
| 54 |
+
if not isinstance(parquet_files, ListConfig):
|
| 55 |
+
parquet_files = [parquet_files]
|
| 56 |
+
|
| 57 |
+
self.parquet_files = parquet_files
|
| 58 |
+
if isinstance(tokenizer, str):
|
| 59 |
+
tokenizer = hf_tokenizer(tokenizer)
|
| 60 |
+
self.tokenizer: PreTrainedTokenizer = tokenizer
|
| 61 |
+
|
| 62 |
+
self.prompt_key = prompt_key if isinstance(prompt_key, tuple | list) else [prompt_key]
|
| 63 |
+
self.response_key = response_key if isinstance(response_key, tuple | list) else [response_key]
|
| 64 |
+
self.prompt_dict_keys = prompt_dict_keys if prompt_dict_keys else []
|
| 65 |
+
self.response_dict_keys = response_dict_keys if response_dict_keys else []
|
| 66 |
+
|
| 67 |
+
self.max_length = max_length
|
| 68 |
+
|
| 69 |
+
self._download()
|
| 70 |
+
self._read_files_and_tokenize()
|
| 71 |
+
|
| 72 |
+
def _download(self):
|
| 73 |
+
for i, parquet_file in enumerate(self.parquet_files):
|
| 74 |
+
self.parquet_files[i] = copy_to_local(parquet_file, verbose=True, use_shm=self.use_shm)
|
| 75 |
+
|
| 76 |
+
def _read_files_and_tokenize(self):
|
| 77 |
+
def series_to_item(ls):
|
| 78 |
+
import numpy
|
| 79 |
+
import pandas
|
| 80 |
+
|
| 81 |
+
while isinstance(ls, pandas.core.series.Series | numpy.ndarray) and len(ls) == 1:
|
| 82 |
+
ls = ls[0]
|
| 83 |
+
return ls
|
| 84 |
+
|
| 85 |
+
dataframes = []
|
| 86 |
+
for parquet_file in self.parquet_files:
|
| 87 |
+
# read parquet files and cache
|
| 88 |
+
dataframe = pd.read_parquet(parquet_file)
|
| 89 |
+
dataframes.append(dataframe)
|
| 90 |
+
self.dataframe = pd.concat(dataframes)
|
| 91 |
+
self.prompts = self.dataframe[self.prompt_key]
|
| 92 |
+
for key in self.prompt_dict_keys:
|
| 93 |
+
# type(x): pandas.core.series.Series
|
| 94 |
+
# type(x[0]): numpy.ndarray
|
| 95 |
+
# type(x[0][0]): dict
|
| 96 |
+
try:
|
| 97 |
+
self.prompts = self.prompts.apply(lambda x: series_to_item(x)[key], axis=1) # noqa: B023
|
| 98 |
+
except Exception:
|
| 99 |
+
print(f"self.prompts={self.prompts}")
|
| 100 |
+
raise
|
| 101 |
+
if isinstance(self.prompts, pd.DataFrame):
|
| 102 |
+
self.prompts = self.prompts.squeeze()
|
| 103 |
+
self.prompts = self.prompts.tolist()
|
| 104 |
+
self.responses = self.dataframe[self.response_key]
|
| 105 |
+
for key in self.response_dict_keys:
|
| 106 |
+
try:
|
| 107 |
+
self.responses = self.responses.apply(lambda x: series_to_item(x)[key], axis=1) # noqa: B023
|
| 108 |
+
except Exception:
|
| 109 |
+
print(f"self.responses={self.responses}")
|
| 110 |
+
raise
|
| 111 |
+
if isinstance(self.responses, pd.DataFrame):
|
| 112 |
+
self.responses = self.responses.squeeze()
|
| 113 |
+
self.responses = self.responses.tolist()
|
| 114 |
+
|
| 115 |
+
def __len__(self):
|
| 116 |
+
return len(self.prompts)
|
| 117 |
+
|
| 118 |
+
def __getitem__(self, item):
|
| 119 |
+
tokenizer = self.tokenizer
|
| 120 |
+
|
| 121 |
+
prompt = self.prompts[item]
|
| 122 |
+
response = self.responses[item]
|
| 123 |
+
|
| 124 |
+
# apply chat template
|
| 125 |
+
prompt_chat = [{"role": "user", "content": prompt}]
|
| 126 |
+
|
| 127 |
+
# string
|
| 128 |
+
prompt_chat_str = tokenizer.apply_chat_template(
|
| 129 |
+
prompt_chat, add_generation_prompt=True, tokenize=False, **self.apply_chat_template_kwargs
|
| 130 |
+
)
|
| 131 |
+
response_chat_str = response + tokenizer.eos_token
|
| 132 |
+
|
| 133 |
+
# tokenize
|
| 134 |
+
prompt_ids_output = tokenizer(prompt_chat_str, return_tensors="pt", add_special_tokens=False)
|
| 135 |
+
prompt_ids = prompt_ids_output["input_ids"][0]
|
| 136 |
+
prompt_attention_mask = prompt_ids_output["attention_mask"][0]
|
| 137 |
+
|
| 138 |
+
response_ids_output = tokenizer(response_chat_str, return_tensors="pt", add_special_tokens=False)
|
| 139 |
+
response_ids = response_ids_output["input_ids"][0]
|
| 140 |
+
response_attention_mask = response_ids_output["attention_mask"][0]
|
| 141 |
+
|
| 142 |
+
prompt_length = prompt_ids.shape[0]
|
| 143 |
+
response_length = response_ids.shape[0]
|
| 144 |
+
|
| 145 |
+
input_ids = torch.cat((prompt_ids, response_ids), dim=-1)
|
| 146 |
+
attention_mask = torch.cat((prompt_attention_mask, response_attention_mask), dim=-1)
|
| 147 |
+
|
| 148 |
+
# padding to max length
|
| 149 |
+
sequence_length = input_ids.shape[0]
|
| 150 |
+
if sequence_length < self.max_length:
|
| 151 |
+
padded_input_ids = (
|
| 152 |
+
torch.ones(size=(self.max_length - sequence_length,), dtype=input_ids.dtype)
|
| 153 |
+
* self.tokenizer.pad_token_id
|
| 154 |
+
)
|
| 155 |
+
padded_attention_mask = torch.zeros(size=(self.max_length - sequence_length,), dtype=attention_mask.dtype)
|
| 156 |
+
|
| 157 |
+
input_ids = torch.cat((input_ids, padded_input_ids))
|
| 158 |
+
attention_mask = torch.cat((attention_mask, padded_attention_mask))
|
| 159 |
+
elif sequence_length > self.max_length:
|
| 160 |
+
if self.truncation == "left":
|
| 161 |
+
# actually, left truncation may not be reasonable
|
| 162 |
+
input_ids = input_ids[-self.max_length :]
|
| 163 |
+
attention_mask = attention_mask[-self.max_length :]
|
| 164 |
+
elif self.truncation == "right":
|
| 165 |
+
input_ids = input_ids[: self.max_length]
|
| 166 |
+
attention_mask = attention_mask[: self.max_length]
|
| 167 |
+
elif self.truncation == "error":
|
| 168 |
+
raise NotImplementedError(f"{sequence_length=} is larger than {self.max_length=}")
|
| 169 |
+
else:
|
| 170 |
+
raise NotImplementedError(f"Unknown truncation method {self.truncation}")
|
| 171 |
+
|
| 172 |
+
position_ids = compute_position_id_with_mask(attention_mask)
|
| 173 |
+
|
| 174 |
+
loss_mask = attention_mask.clone()
|
| 175 |
+
if prompt_length > 1:
|
| 176 |
+
# mask out prompt for SFT.
|
| 177 |
+
loss_mask[: min(prompt_length, loss_mask.size(0)) - 1] = 0
|
| 178 |
+
# mask out the last token in response
|
| 179 |
+
loss_mask[min(prompt_length + response_length, loss_mask.size(0)) - 1] = 0
|
| 180 |
+
|
| 181 |
+
return {
|
| 182 |
+
"input_ids": input_ids,
|
| 183 |
+
"attention_mask": attention_mask,
|
| 184 |
+
"position_ids": position_ids,
|
| 185 |
+
"loss_mask": loss_mask,
|
| 186 |
+
}
|
verl/verl/utils/dataset/vision_utils.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from io import BytesIO
|
| 16 |
+
from typing import Optional
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from PIL import Image
|
| 20 |
+
from qwen_vl_utils import fetch_image, fetch_video
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def process_image(image: dict | Image.Image) -> Image.Image:
|
| 24 |
+
if isinstance(image, Image.Image):
|
| 25 |
+
return image.convert("RGB")
|
| 26 |
+
|
| 27 |
+
if "bytes" in image:
|
| 28 |
+
assert "image" not in image, "Cannot have both `bytes` and `image`"
|
| 29 |
+
image["image"] = Image.open(BytesIO(image["bytes"]))
|
| 30 |
+
|
| 31 |
+
return fetch_image(image)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
VIDEO_FORMAT_HELP = """Currently, we only support the video formats introduced in qwen2-vl.
|
| 35 |
+
Refer to https://github.com/QwenLM/Qwen2.5-VL?tab=readme-ov-file#using---transformers-to-chat.
|
| 36 |
+
|
| 37 |
+
eg.
|
| 38 |
+
{
|
| 39 |
+
"type": "video",
|
| 40 |
+
"video": [
|
| 41 |
+
"file:///path/to/frame1.jpg",
|
| 42 |
+
"file:///path/to/frame2.jpg"
|
| 43 |
+
]
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
{
|
| 47 |
+
"type": "video",
|
| 48 |
+
"video": "file:///path/to/video.mp4"
|
| 49 |
+
}
|
| 50 |
+
# Defaults to fps=2, min_frames=4, max_frames=768
|
| 51 |
+
|
| 52 |
+
{
|
| 53 |
+
"type": "video",
|
| 54 |
+
"video": "file:///path/to/video.mp4",
|
| 55 |
+
"fps": 2,
|
| 56 |
+
"min_frames": 1,
|
| 57 |
+
"max_frames": 32
|
| 58 |
+
}
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def process_video(
|
| 63 |
+
video: dict,
|
| 64 |
+
nframes: Optional[int] = None,
|
| 65 |
+
fps: Optional[float] = None,
|
| 66 |
+
fps_min_frames: Optional[int] = None,
|
| 67 |
+
fps_max_frames: Optional[int] = None,
|
| 68 |
+
) -> torch.Tensor:
|
| 69 |
+
"""Converts a video dict into a [n_frames, 3, H, W] tensor
|
| 70 |
+
|
| 71 |
+
Add video sample FPS in a future MR
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
if not isinstance(video, dict) or "video" not in video:
|
| 75 |
+
raise NotImplementedError(VIDEO_FORMAT_HELP)
|
| 76 |
+
assert nframes is None or fps is None, "Can't use both `nframes` or `fps`"
|
| 77 |
+
|
| 78 |
+
# Shallow copy... since we might want to add some keys
|
| 79 |
+
video = dict(video)
|
| 80 |
+
|
| 81 |
+
contains_sampling_rules = "nframes" in video or "fps" in video
|
| 82 |
+
if not contains_sampling_rules:
|
| 83 |
+
if nframes is not None:
|
| 84 |
+
video["nframes"] = nframes
|
| 85 |
+
elif fps is not None:
|
| 86 |
+
video["fps"] = fps
|
| 87 |
+
if fps_min_frames is not None:
|
| 88 |
+
video["min_frames"] = fps_min_frames
|
| 89 |
+
if fps_max_frames is not None:
|
| 90 |
+
video["max_frames"] = fps_max_frames
|
| 91 |
+
|
| 92 |
+
return fetch_video(video)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def process_multi_modal_inputs_for_minicpmo(input_ids, attention_mask, position_ids, cu_seqlens, multi_modal_inputs):
|
| 96 |
+
# Adjust image bounds based on left padding and cumulative sequence lengths
|
| 97 |
+
# This is necessary for MiniCPM-o's vision-language alignment
|
| 98 |
+
left_padding_length = torch.argmax(attention_mask, dim=1)
|
| 99 |
+
image_bounds = []
|
| 100 |
+
for i in range(len(multi_modal_inputs["image_bound"])):
|
| 101 |
+
image_bound = (
|
| 102 |
+
multi_modal_inputs["image_bound"][i].to(left_padding_length.device) - left_padding_length[i] + cu_seqlens[i]
|
| 103 |
+
)
|
| 104 |
+
image_bounds.append(image_bound)
|
| 105 |
+
|
| 106 |
+
# Flatten pixel values list for MiniCPM-o processing
|
| 107 |
+
pixel_values = []
|
| 108 |
+
for i in range(len(multi_modal_inputs["pixel_values"])):
|
| 109 |
+
pixel_values.extend([p for p in multi_modal_inputs["pixel_values"][i]])
|
| 110 |
+
|
| 111 |
+
multi_modal_inputs["pixel_values"] = [pixel_values]
|
| 112 |
+
multi_modal_inputs["image_bound"] = [torch.vstack(image_bounds)]
|
| 113 |
+
multi_modal_inputs["tgt_sizes"] = [torch.vstack(multi_modal_inputs["tgt_sizes"])]
|
| 114 |
+
multi_modal_inputs["input_ids"] = input_ids
|
| 115 |
+
multi_modal_inputs["attention_mask"] = attention_mask
|
| 116 |
+
multi_modal_inputs["position_ids"] = position_ids
|
| 117 |
+
return {"data": multi_modal_inputs}
|
verl/verl/utils/debug/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# APIs kept for backward compatibility purpose
|
| 16 |
+
# For new features please develop in verl/utils/profiler/
|
| 17 |
+
from ..profiler import * # noqa
|
verl/verl/utils/debug/metrics.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Individual Contributor: TomQunChaoA
|
| 2 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 3 |
+
# you may not use this file except in compliance with the License.
|
| 4 |
+
# You may obtain a copy of the License at
|
| 5 |
+
#
|
| 6 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
#
|
| 8 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 9 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 10 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 11 |
+
# See the License for the specific language governing permissions and
|
| 12 |
+
# limitations under the License.
|
| 13 |
+
|
| 14 |
+
import logging
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from verl.protocol import DataProto
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__file__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def calculate_token_list_diff(tensor1: torch.Tensor, tensor2: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
| 24 |
+
# verify inputs
|
| 25 |
+
if tensor1.numel() == 0 or tensor2.numel() == 0:
|
| 26 |
+
return torch.zeros(tensor1.shape[0], dtype=torch.long, device=tensor1.device)
|
| 27 |
+
if tensor1.shape != tensor2.shape or mask.shape != tensor1.shape or mask.shape != tensor2.shape:
|
| 28 |
+
print(
|
| 29 |
+
f"<WARN> dim of tensor1, tensor2, mask is not equal, {(tensor1.shape)=},{(tensor2.shape)=}, {(mask.shape)=}"
|
| 30 |
+
)
|
| 31 |
+
return torch.ones_like(tensor1)
|
| 32 |
+
# transfer to same device
|
| 33 |
+
if tensor2.device != tensor1.device:
|
| 34 |
+
tensor2 = tensor2.to(tensor1.device)
|
| 35 |
+
if mask.device != tensor1.device:
|
| 36 |
+
mask = mask.to(tensor1.device)
|
| 37 |
+
|
| 38 |
+
# calculate diff
|
| 39 |
+
diff_mask = tensor1 != tensor2
|
| 40 |
+
|
| 41 |
+
valid_diff_mask = diff_mask & (mask == 1)
|
| 42 |
+
|
| 43 |
+
diff_counts = valid_diff_mask.sum(dim=1)
|
| 44 |
+
|
| 45 |
+
return diff_counts
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def pearson_correlation_coefficient(tensor1: torch.Tensor, tensor2: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
| 49 |
+
# implemention of https://arxiv.org/pdf/2506.13585
|
| 50 |
+
if tensor1.shape != tensor2.shape or mask.shape != tensor1.shape or mask.shape != tensor2.shape:
|
| 51 |
+
return 0
|
| 52 |
+
mt1 = torch.masked_select(tensor1, mask)
|
| 53 |
+
mt2 = torch.masked_select(tensor2, mask)
|
| 54 |
+
result = torch.corrcoef(torch.stack([mt1, mt2], dim=0))
|
| 55 |
+
return result[0][1].detach().item()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def calculate_log_prob_diff(log_probs1: torch.Tensor, log_probs2: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
| 59 |
+
full_diff = torch.abs(log_probs1 - log_probs2)
|
| 60 |
+
return torch.masked_select(full_diff, mask)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def calculate_debug_metrics(data: DataProto) -> dict:
|
| 64 |
+
"""
|
| 65 |
+
calculate rollout vs actor logprobs diff, for debugging purpose
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
data: DataProto
|
| 69 |
+
the data batch to calculate
|
| 70 |
+
rollout_log_probs: log_probs record when rollout forward tokens
|
| 71 |
+
old_log_probs(actor log probs): log_probs record when actor forward tokens
|
| 72 |
+
loss_mask or attention_mask: to mask unrelated token
|
| 73 |
+
responses: the response tokens, for calculating size
|
| 74 |
+
Returns:
|
| 75 |
+
dict: metrics
|
| 76 |
+
"training/rollout_probs_diff_valid": 1->input is valid, 0->input is invalid
|
| 77 |
+
"training/rollout_probs_diff_max": max value of logprob diff of rollout vs. actor
|
| 78 |
+
"training/rollout_probs_diff_mean": mean value of logprob diff of rollout vs. actor
|
| 79 |
+
"training/rollout_probs_diff_std": std value of logprob diff of rollout vs. actor
|
| 80 |
+
"training/rollout_actor_probs_pearson_corr": logprob's pearson corrcoef of rollout vs. actor, reference to https://arxiv.org/pdf/2506.13585
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
rollout_old_log_probs = data.batch["rollout_log_probs"]
|
| 84 |
+
actor_old_log_probs = data.batch["old_log_probs"]
|
| 85 |
+
if "response_mask" in data.batch:
|
| 86 |
+
logger.debug("response mask found, use it to mask log probs")
|
| 87 |
+
log_prob_mask = data.batch["response_mask"]
|
| 88 |
+
elif "attention_mask" in data.batch:
|
| 89 |
+
log_prob_mask = data.batch["attention_mask"]
|
| 90 |
+
else:
|
| 91 |
+
logger.warning(f"no mask info found, use all log probs, {(data.batch.keys())=}")
|
| 92 |
+
log_prob_mask = torch.ones_like(rollout_old_log_probs)
|
| 93 |
+
responses = data.batch["responses"]
|
| 94 |
+
response_length = responses.size(1)
|
| 95 |
+
|
| 96 |
+
response_mask = log_prob_mask[:, -response_length:]
|
| 97 |
+
# calculate pearson corrcoef
|
| 98 |
+
actor_probs = torch.exp(actor_old_log_probs)
|
| 99 |
+
rollout_probs = torch.exp(rollout_old_log_probs)
|
| 100 |
+
response_mask_bool = response_mask.bool()
|
| 101 |
+
pearson_corrcoef = pearson_correlation_coefficient(actor_probs, rollout_probs, response_mask_bool)
|
| 102 |
+
rollout_probs_diff = calculate_log_prob_diff(actor_probs, rollout_probs, response_mask_bool)
|
| 103 |
+
return {
|
| 104 |
+
"training/rollout_probs_diff_valid": 1,
|
| 105 |
+
"training/rollout_probs_diff_max": torch.max(rollout_probs_diff).detach().item(),
|
| 106 |
+
"training/rollout_probs_diff_mean": torch.mean(rollout_probs_diff).detach().item(),
|
| 107 |
+
"training/rollout_probs_diff_std": torch.std(rollout_probs_diff).detach().item(),
|
| 108 |
+
"training/rollout_actor_probs_pearson_corr": pearson_corrcoef,
|
| 109 |
+
}
|
verl/verl/utils/debug/performance.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# APIs kept for backward compatibility purpose
|
| 16 |
+
# This file is deprecated, for new features please develop in profiler/performance.py
|
| 17 |
+
from verl.utils.profiler.performance import simple_timer, reduce_timing # noqa
|
verl/verl/utils/debug/trajectory_tracker.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
Trajectory tracker can be inserted into code to save the intermediate results.
|
| 16 |
+
The results will be dump to hdfs for offline comparison.
|
| 17 |
+
Each process will have a client that first move all the tensors to CPU
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import io
|
| 21 |
+
import os
|
| 22 |
+
import tempfile
|
| 23 |
+
from collections import deque
|
| 24 |
+
|
| 25 |
+
import ray
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
from verl.utils.hdfs_io import copy, makedirs
|
| 29 |
+
|
| 30 |
+
remote_copy = ray.remote(copy)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@ray.remote
|
| 34 |
+
def save_to_hdfs(data: io.BytesIO, name, hdfs_dir, verbose):
|
| 35 |
+
filename = name + ".pth"
|
| 36 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 37 |
+
local_filepath = os.path.join(tmpdirname, filename)
|
| 38 |
+
with open(local_filepath, "wb") as f:
|
| 39 |
+
f.write(data.getbuffer())
|
| 40 |
+
# upload to hdfs
|
| 41 |
+
|
| 42 |
+
if verbose:
|
| 43 |
+
print(f"Saving {local_filepath} to {hdfs_dir}")
|
| 44 |
+
try:
|
| 45 |
+
copy(local_filepath, hdfs_dir)
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(e)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@ray.remote
|
| 51 |
+
class TrajectoryTracker:
|
| 52 |
+
def __init__(self, hdfs_dir, verbose) -> None:
|
| 53 |
+
self.hdfs_dir = hdfs_dir
|
| 54 |
+
makedirs(hdfs_dir)
|
| 55 |
+
self.verbose = verbose
|
| 56 |
+
|
| 57 |
+
self.handle = deque()
|
| 58 |
+
|
| 59 |
+
def dump(self, data: io.BytesIO, name):
|
| 60 |
+
# get a temp file and write to it
|
| 61 |
+
self.handle.append(save_to_hdfs.remote(data, name, self.hdfs_dir, self.verbose))
|
| 62 |
+
|
| 63 |
+
def wait_for_hdfs(self):
|
| 64 |
+
while len(self.handle) != 0:
|
| 65 |
+
future = self.handle.popleft()
|
| 66 |
+
ray.get(future)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def dump_data(data, name):
|
| 70 |
+
enable = os.getenv("VERL_ENABLE_TRACKER", "0") == "1"
|
| 71 |
+
if not enable:
|
| 72 |
+
return
|
| 73 |
+
buffer = io.BytesIO()
|
| 74 |
+
torch.save(data, buffer)
|
| 75 |
+
tracker = get_trajectory_tracker()
|
| 76 |
+
ray.get(tracker.dump.remote(buffer, name))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def get_trajectory_tracker():
|
| 80 |
+
hdfs_dir = os.getenv("VERL_TRACKER_HDFS_DIR", default=None)
|
| 81 |
+
verbose = os.getenv("VERL_TRACKER_VERBOSE", default="0") == "1"
|
| 82 |
+
assert hdfs_dir is not None
|
| 83 |
+
tracker = TrajectoryTracker.options(name="global_tracker", get_if_exists=True, lifetime="detached").remote(
|
| 84 |
+
hdfs_dir, verbose
|
| 85 |
+
)
|
| 86 |
+
return tracker
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
# testing
|
| 91 |
+
os.environ["VERL_ENABLE_TRACKER"] = "1"
|
| 92 |
+
os.environ["VERL_TRACKER_HDFS_DIR"] = "~/debug/test"
|
| 93 |
+
|
| 94 |
+
@ray.remote
|
| 95 |
+
def process(iter):
|
| 96 |
+
data = {"obs": torch.randn(10, 20)}
|
| 97 |
+
dump_data(data, f"process_{iter}_obs")
|
| 98 |
+
|
| 99 |
+
ray.init()
|
| 100 |
+
|
| 101 |
+
output_lst = []
|
| 102 |
+
|
| 103 |
+
for i in range(10):
|
| 104 |
+
output_lst.append(process.remote(i))
|
| 105 |
+
|
| 106 |
+
out = ray.get(output_lst)
|
| 107 |
+
|
| 108 |
+
tracker = get_trajectory_tracker()
|
| 109 |
+
ray.get(tracker.wait_for_hdfs.remote())
|
verl/verl/utils/experimental/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
verl/verl/utils/experimental/torch_functional.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Optional
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _fused_linear_for_ppo_fwd(
|
| 21 |
+
hidden_states: torch.FloatTensor,
|
| 22 |
+
vocab_weights: torch.FloatTensor,
|
| 23 |
+
input_ids: torch.LongTensor,
|
| 24 |
+
temperature: float = 1.0,
|
| 25 |
+
) -> tuple[torch.FloatTensor, torch.FloatTensor]:
|
| 26 |
+
logits = (hidden_states @ vocab_weights.t()) / temperature
|
| 27 |
+
orig_dtype = logits.dtype
|
| 28 |
+
logits = logits.to(torch.float32)
|
| 29 |
+
|
| 30 |
+
# Slower but more numerically stable to do log_softmax than probs.log()
|
| 31 |
+
probs = logits.softmax(dim=-1)
|
| 32 |
+
log_probs = logits.log_softmax(dim=-1)
|
| 33 |
+
|
| 34 |
+
token_log_probs = log_probs.gather(-1, input_ids.unsqueeze(-1)).squeeze(-1)
|
| 35 |
+
entropy = torch.logsumexp(logits, dim=-1) - torch.sum(probs * logits, dim=-1)
|
| 36 |
+
|
| 37 |
+
return token_log_probs.to(orig_dtype), entropy.to(orig_dtype)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _fused_linear_for_ppo_bwd(
|
| 41 |
+
dlog_probs: Optional[torch.FloatTensor],
|
| 42 |
+
dentropy: Optional[torch.FloatTensor],
|
| 43 |
+
hidden_states: torch.FloatTensor,
|
| 44 |
+
vocab_weights: torch.FloatTensor,
|
| 45 |
+
input_ids: torch.LongTensor,
|
| 46 |
+
temperature: float = 1.0,
|
| 47 |
+
) -> tuple[torch.FloatTensor, torch.FloatTensor]:
|
| 48 |
+
logits = (hidden_states @ vocab_weights.t()) / temperature
|
| 49 |
+
orig_dtype = logits.dtype
|
| 50 |
+
logits = logits.to(torch.float32)
|
| 51 |
+
|
| 52 |
+
probs = logits.softmax(dim=-1)
|
| 53 |
+
|
| 54 |
+
dlogits = 0
|
| 55 |
+
|
| 56 |
+
# Gradient from log_probs
|
| 57 |
+
if dlog_probs is not None:
|
| 58 |
+
one_hot_input = torch.zeros_like(logits).scatter_(-1, input_ids.unsqueeze(-1), 1)
|
| 59 |
+
dlogits += dlog_probs.to(torch.float32).unsqueeze(-1) * (one_hot_input - probs)
|
| 60 |
+
|
| 61 |
+
# Gradient from entropy
|
| 62 |
+
if dentropy is not None:
|
| 63 |
+
log_probs = logits.log_softmax(dim=-1)
|
| 64 |
+
entropy = torch.logsumexp(logits, dim=-1) - torch.sum(probs * logits, dim=-1)
|
| 65 |
+
dlogits += probs * (log_probs + entropy.unsqueeze(-1)) * (-dentropy.unsqueeze(-1))
|
| 66 |
+
|
| 67 |
+
dlogits = dlogits.to(orig_dtype) / temperature
|
| 68 |
+
|
| 69 |
+
dhidden_states = dlogits @ vocab_weights
|
| 70 |
+
dvocab_weights = dlogits.t() @ hidden_states
|
| 71 |
+
|
| 72 |
+
return dhidden_states, dvocab_weights
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class FusedLinearForPPOFunction(torch.autograd.Function):
|
| 76 |
+
@staticmethod
|
| 77 |
+
def forward(
|
| 78 |
+
ctx,
|
| 79 |
+
hidden_states: torch.FloatTensor,
|
| 80 |
+
vocab_weights: torch.FloatTensor,
|
| 81 |
+
input_ids: torch.LongTensor,
|
| 82 |
+
temperature: float = 1.0,
|
| 83 |
+
chunk_size: int = 512,
|
| 84 |
+
) -> tuple[torch.FloatTensor, torch.FloatTensor]:
|
| 85 |
+
ctx.set_materialize_grads(False)
|
| 86 |
+
|
| 87 |
+
# Cast to a 2D tensor of the shape [T, D] for ease of working
|
| 88 |
+
orig_ndim = hidden_states.ndim
|
| 89 |
+
assert orig_ndim in (2, 3), f"Invalid hidden_states shape, received {hidden_states.shape}"
|
| 90 |
+
|
| 91 |
+
orig_batch_size = -1
|
| 92 |
+
if orig_ndim == 3:
|
| 93 |
+
assert input_ids.ndim == 2, f"input_ids shape doesn't match, {hidden_states.shape} {input_ids.shape}"
|
| 94 |
+
orig_batch_size = hidden_states.shape[0]
|
| 95 |
+
hidden_states = hidden_states.flatten(0, 1)
|
| 96 |
+
input_ids = input_ids.flatten(0, 1)
|
| 97 |
+
|
| 98 |
+
T = hidden_states.shape[0]
|
| 99 |
+
|
| 100 |
+
# Allocate memory for outputs
|
| 101 |
+
output_requires_grad = hidden_states.requires_grad or vocab_weights.requires_grad
|
| 102 |
+
log_probs = hidden_states.new_zeros(T, requires_grad=output_requires_grad)
|
| 103 |
+
entropy = hidden_states.new_zeros(T, requires_grad=output_requires_grad)
|
| 104 |
+
|
| 105 |
+
# Perform forward one chunk at a time
|
| 106 |
+
for chunk_start in range(0, T, chunk_size):
|
| 107 |
+
chunk_end = min(chunk_start + chunk_size, T)
|
| 108 |
+
|
| 109 |
+
chunk_log_probs, chunk_entropy = _fused_linear_for_ppo_fwd(
|
| 110 |
+
hidden_states=hidden_states[chunk_start:chunk_end],
|
| 111 |
+
vocab_weights=vocab_weights,
|
| 112 |
+
input_ids=input_ids[chunk_start:chunk_end],
|
| 113 |
+
temperature=temperature,
|
| 114 |
+
)
|
| 115 |
+
log_probs[chunk_start:chunk_end] = chunk_log_probs
|
| 116 |
+
entropy[chunk_start:chunk_end] = chunk_entropy
|
| 117 |
+
|
| 118 |
+
# Cast the output back to the original input dimension
|
| 119 |
+
if orig_ndim == 3:
|
| 120 |
+
log_probs = log_probs.view(orig_batch_size, -1)
|
| 121 |
+
entropy = entropy.view(orig_batch_size, -1)
|
| 122 |
+
|
| 123 |
+
ctx.save_for_backward(hidden_states, vocab_weights, input_ids)
|
| 124 |
+
ctx.orig_batch_size = orig_batch_size
|
| 125 |
+
ctx.orig_ndim = orig_ndim
|
| 126 |
+
ctx.temperature = temperature
|
| 127 |
+
ctx.chunk_size = chunk_size
|
| 128 |
+
|
| 129 |
+
return log_probs, entropy
|
| 130 |
+
|
| 131 |
+
@staticmethod
|
| 132 |
+
def backward(ctx, dlog_probs: Optional[torch.FloatTensor], dentropy: Optional[torch.FloatTensor]):
|
| 133 |
+
assert dlog_probs is not None or dentropy is not None
|
| 134 |
+
|
| 135 |
+
hidden_states, vocab_weights, input_ids = ctx.saved_tensors
|
| 136 |
+
orig_batch_size = ctx.orig_batch_size
|
| 137 |
+
orig_ndim = ctx.orig_ndim
|
| 138 |
+
temperature = ctx.temperature
|
| 139 |
+
chunk_size = ctx.chunk_size
|
| 140 |
+
|
| 141 |
+
# Here orig_ndim refers to the orig_ndim of hidden_states
|
| 142 |
+
if orig_ndim == 3:
|
| 143 |
+
if dlog_probs is not None:
|
| 144 |
+
dlog_probs = dlog_probs.flatten()
|
| 145 |
+
if dentropy is not None:
|
| 146 |
+
dentropy = dentropy.flatten()
|
| 147 |
+
|
| 148 |
+
T = hidden_states.shape[0]
|
| 149 |
+
|
| 150 |
+
# Allocate memory for outputs
|
| 151 |
+
dhidden_states = None
|
| 152 |
+
if hidden_states.requires_grad:
|
| 153 |
+
dhidden_states = torch.zeros_like(hidden_states)
|
| 154 |
+
dvocab_weights = None
|
| 155 |
+
if vocab_weights.requires_grad:
|
| 156 |
+
dvocab_weights = torch.zeros_like(vocab_weights)
|
| 157 |
+
|
| 158 |
+
# Perform backward one chunk at a time
|
| 159 |
+
for chunk_start in range(0, T, chunk_size):
|
| 160 |
+
chunk_end = min(chunk_start + chunk_size, T)
|
| 161 |
+
chunk_dlog_probs = None
|
| 162 |
+
if dlog_probs is not None:
|
| 163 |
+
chunk_dlog_probs = dlog_probs[chunk_start:chunk_end]
|
| 164 |
+
chunk_dentropy = None
|
| 165 |
+
if dentropy is not None:
|
| 166 |
+
chunk_dentropy = dentropy[chunk_start:chunk_end]
|
| 167 |
+
|
| 168 |
+
h, v = _fused_linear_for_ppo_bwd(
|
| 169 |
+
dlog_probs=chunk_dlog_probs,
|
| 170 |
+
dentropy=chunk_dentropy,
|
| 171 |
+
hidden_states=hidden_states[chunk_start:chunk_end],
|
| 172 |
+
vocab_weights=vocab_weights,
|
| 173 |
+
input_ids=input_ids[chunk_start:chunk_end],
|
| 174 |
+
temperature=temperature,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
if hidden_states.requires_grad:
|
| 178 |
+
dhidden_states[chunk_start:chunk_end] += h
|
| 179 |
+
if vocab_weights.requires_grad:
|
| 180 |
+
dvocab_weights += v
|
| 181 |
+
|
| 182 |
+
# Cast the output back to the original input dimension
|
| 183 |
+
if orig_ndim == 3 and hidden_states.requires_grad:
|
| 184 |
+
hidden_size = hidden_states.shape[-1]
|
| 185 |
+
dhidden_states = dhidden_states.view(orig_batch_size, -1, hidden_size)
|
| 186 |
+
|
| 187 |
+
return (
|
| 188 |
+
dhidden_states, # hidden_states
|
| 189 |
+
dvocab_weights, # vocab_weights
|
| 190 |
+
None, # input_ids
|
| 191 |
+
None, # temperature
|
| 192 |
+
None, # chunk_size
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class FusedLinearForPPO(torch.nn.Module):
|
| 197 |
+
def __init__(self, chunk_size: int = 512):
|
| 198 |
+
super().__init__()
|
| 199 |
+
|
| 200 |
+
self.chunk_size = chunk_size
|
| 201 |
+
|
| 202 |
+
def forward(
|
| 203 |
+
self,
|
| 204 |
+
hidden_states: torch.FloatTensor,
|
| 205 |
+
vocab_weights: torch.FloatTensor,
|
| 206 |
+
input_ids: torch.LongTensor,
|
| 207 |
+
temperature: float = 1.0,
|
| 208 |
+
) -> tuple[torch.FloatTensor, torch.FloatTensor]:
|
| 209 |
+
input_ids = input_ids.to(torch.int64)
|
| 210 |
+
return FusedLinearForPPOFunction.apply(
|
| 211 |
+
hidden_states,
|
| 212 |
+
vocab_weights,
|
| 213 |
+
input_ids,
|
| 214 |
+
temperature,
|
| 215 |
+
self.chunk_size,
|
| 216 |
+
)
|
verl/verl/utils/kernel/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 3 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 19 |
+
#
|
| 20 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 21 |
+
# you may not use this file except in compliance with the License.
|
| 22 |
+
# You may obtain a copy of the License at
|
| 23 |
+
#
|
| 24 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 25 |
+
#
|
| 26 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 27 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 28 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 29 |
+
# See the License for the specific language governing permissions and
|
| 30 |
+
# limitations under the License.
|
| 31 |
+
|
verl/verl/utils/kernel/kernels.py
ADDED
|
@@ -0,0 +1,1586 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 3 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 19 |
+
#
|
| 20 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 21 |
+
# you may not use this file except in compliance with the License.
|
| 22 |
+
# You may obtain a copy of the License at
|
| 23 |
+
#
|
| 24 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 25 |
+
#
|
| 26 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 27 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 28 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 29 |
+
# See the License for the specific language governing permissions and
|
| 30 |
+
# limitations under the License.
|
| 31 |
+
"""
|
| 32 |
+
Implementations of the linear cross entropy with token entropy kernel.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
import typing
|
| 36 |
+
from dataclasses import dataclass
|
| 37 |
+
|
| 38 |
+
import torch
|
| 39 |
+
import torch.distributed as dist
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
import triton
|
| 43 |
+
import triton.language as tl
|
| 44 |
+
|
| 45 |
+
HAVE_TRITON = True
|
| 46 |
+
except ImportError:
|
| 47 |
+
HAVE_TRITON = False
|
| 48 |
+
|
| 49 |
+
from verl.utils.device import get_torch_device
|
| 50 |
+
|
| 51 |
+
if not HAVE_TRITON:
|
| 52 |
+
from contextlib import contextmanager
|
| 53 |
+
from unittest.mock import MagicMock
|
| 54 |
+
|
| 55 |
+
@contextmanager
|
| 56 |
+
def null_decorator(*args, **kwargs):
|
| 57 |
+
if len(kwargs) == 0 and len(args) == 1 and callable(args[0]):
|
| 58 |
+
return args[0]
|
| 59 |
+
else:
|
| 60 |
+
|
| 61 |
+
def inner(func):
|
| 62 |
+
return func
|
| 63 |
+
|
| 64 |
+
return inner
|
| 65 |
+
|
| 66 |
+
triton = MagicMock()
|
| 67 |
+
triton.jit = null_decorator
|
| 68 |
+
triton.autotune = null_decorator
|
| 69 |
+
tl = MagicMock()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class EntropyReductionEnum:
|
| 74 |
+
"""
|
| 75 |
+
Enum for the reduction method of cross entropy.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
_None = 0
|
| 79 |
+
_Sum = 1
|
| 80 |
+
_Mean = 2
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_entropy_reduction_enum_number(reduction: str) -> int:
|
| 84 |
+
"""
|
| 85 |
+
Get the enum number for the reduction method of cross entropy.
|
| 86 |
+
"""
|
| 87 |
+
_enum = EntropyReductionEnum._None
|
| 88 |
+
if reduction == "none":
|
| 89 |
+
_enum = EntropyReductionEnum._None
|
| 90 |
+
elif reduction == "sum":
|
| 91 |
+
_enum = EntropyReductionEnum._Sum
|
| 92 |
+
elif reduction == "mean":
|
| 93 |
+
_enum = EntropyReductionEnum._Mean
|
| 94 |
+
else:
|
| 95 |
+
raise ValueError(f"Invalid reduction: {reduction}")
|
| 96 |
+
return _enum
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_entropy_reduction_enum(ce_reduction: int) -> EntropyReductionEnum:
|
| 100 |
+
"""
|
| 101 |
+
Get the enum for the reduction method of cross entropy.
|
| 102 |
+
"""
|
| 103 |
+
_enum = EntropyReductionEnum._None
|
| 104 |
+
if ce_reduction == 0:
|
| 105 |
+
_enum = EntropyReductionEnum._None
|
| 106 |
+
elif ce_reduction == 1:
|
| 107 |
+
_enum = EntropyReductionEnum._Sum
|
| 108 |
+
elif ce_reduction == 2:
|
| 109 |
+
_enum = EntropyReductionEnum._Mean
|
| 110 |
+
else:
|
| 111 |
+
raise ValueError(f"Invalid ce_reduction: {ce_reduction}")
|
| 112 |
+
return _enum
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@dataclass
|
| 116 |
+
class BackwardEnum:
|
| 117 |
+
"""
|
| 118 |
+
Enum for the backward method.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
_Total_Fuse_MN = (
|
| 122 |
+
0 # Fuse d_logits & d_hidden & d_weight, no intermediate storage, requires fp32 for d_hidden & d_weight
|
| 123 |
+
)
|
| 124 |
+
_Total_Separate = 1 # Store d_logits, no special requirements for d_hidden & d_weight
|
| 125 |
+
_Split_Dlogits_N = 2 # split d_logits along its N dimension, aka. vocab_size
|
| 126 |
+
_Split_Dlogits_M = 3 # split d_logits along its M dimension, aka. num_tokens
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
@dataclass
|
| 130 |
+
class Config:
|
| 131 |
+
"""Configuration for efficient entropy kernel operations.
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
_backward (BackwardEnum): Backward computation method. Defaults to BackwardEnum._Split_Dlogits_N.
|
| 135 |
+
_use_triton (bool): Whether to use Triton kernels for computation. Defaults to True.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
_backward: BackwardEnum = BackwardEnum._Split_Dlogits_N
|
| 139 |
+
_use_triton: bool = True
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
_config = Config()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def set_backward_method(backward_method: BackwardEnum):
|
| 146 |
+
"""
|
| 147 |
+
Set the backward method.
|
| 148 |
+
"""
|
| 149 |
+
global _config
|
| 150 |
+
_config._backward = backward_method
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@triton.autotune(
|
| 154 |
+
configs=[triton.Config({"BLOCK_SIZE_M": 128, "BLOCK_SIZE_N": 256, "BLOCK_SIZE_K": 32}, num_stages=3, num_warps=8)],
|
| 155 |
+
key=["num_tokens", "hidden_size", "vocab_size"],
|
| 156 |
+
)
|
| 157 |
+
@triton.jit
|
| 158 |
+
def efficient_entropy_kernel_general_mainloop(
|
| 159 |
+
rank,
|
| 160 |
+
hidden_ptr,
|
| 161 |
+
weight_ptr,
|
| 162 |
+
labels_ptr,
|
| 163 |
+
num_tokens,
|
| 164 |
+
hidden_size,
|
| 165 |
+
vocab_size,
|
| 166 |
+
vocab_per_split,
|
| 167 |
+
stride_hidden_m: tl.int64,
|
| 168 |
+
stride_hidden_k: tl.int64,
|
| 169 |
+
stride_weight_n: tl.int64,
|
| 170 |
+
stride_weight_k: tl.int64,
|
| 171 |
+
max_ptr,
|
| 172 |
+
stride_max_m: tl.int64,
|
| 173 |
+
stride_max_n: tl.int64,
|
| 174 |
+
accu_ptr,
|
| 175 |
+
stride_accu_m: tl.int64,
|
| 176 |
+
stride_accu_n: tl.int64,
|
| 177 |
+
entropy_b_ptr,
|
| 178 |
+
stride_entropy_b_m: tl.int64,
|
| 179 |
+
stride_entropy_b_n: tl.int64,
|
| 180 |
+
global_logprobs_ptr,
|
| 181 |
+
stride_global_logprobs: tl.int64,
|
| 182 |
+
global_logprobs_scalar_ptr,
|
| 183 |
+
rcp_temperature: tl.float32,
|
| 184 |
+
# Meta-parameters
|
| 185 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 186 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 187 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 188 |
+
):
|
| 189 |
+
"""
|
| 190 |
+
forward mainloop
|
| 191 |
+
"""
|
| 192 |
+
pid = tl.program_id(axis=0)
|
| 193 |
+
num_splits = (vocab_size + vocab_per_split - 1) // vocab_per_split
|
| 194 |
+
num_pid_m = tl.cdiv(num_tokens, BLOCK_SIZE_M)
|
| 195 |
+
num_pid_n = tl.cdiv(vocab_per_split, BLOCK_SIZE_N)
|
| 196 |
+
pid_m = pid % num_pid_m
|
| 197 |
+
pid_n = pid // num_pid_m
|
| 198 |
+
|
| 199 |
+
if pid_m == 0 and pid_n == 0:
|
| 200 |
+
tl.store(global_logprobs_scalar_ptr, 0.0)
|
| 201 |
+
|
| 202 |
+
# create pointers for the first blocks of hidden
|
| 203 |
+
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 204 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 205 |
+
hidden_ptrs = hidden_ptr + (offs_am[:, None] * stride_hidden_m + offs_k[None, :] * stride_hidden_k)
|
| 206 |
+
|
| 207 |
+
# load labels for this block
|
| 208 |
+
labels = tl.load(labels_ptr + offs_am, mask=offs_am < num_tokens)
|
| 209 |
+
|
| 210 |
+
# traverse over N dimension
|
| 211 |
+
# _max = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 212 |
+
_max = tl.full((BLOCK_SIZE_M,), -float("inf"), dtype=tl.float32)
|
| 213 |
+
_accu = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 214 |
+
_entropy_b = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 215 |
+
_logprobs = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 216 |
+
for n in range(0, num_pid_n):
|
| 217 |
+
offs_bn = pid_n * vocab_per_split + n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 218 |
+
# weight_ptrs = weight_ptr + (offs_k[:, None] * stride_weight_k + offs_bn[None, :] * stride_weight_n)
|
| 219 |
+
weight_ptrs = weight_ptr + (offs_bn[:, None] * stride_weight_n + offs_k[None, :] * stride_weight_k)
|
| 220 |
+
|
| 221 |
+
# iterate over K dimension
|
| 222 |
+
logits = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 223 |
+
for k in range(0, tl.cdiv(hidden_size, BLOCK_SIZE_K)):
|
| 224 |
+
# load the next block of hidden and weight
|
| 225 |
+
_hidden = tl.load(
|
| 226 |
+
hidden_ptrs,
|
| 227 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_am[:, None] < num_tokens),
|
| 228 |
+
other=0.0,
|
| 229 |
+
)
|
| 230 |
+
# _weight = tl.load(weight_ptrs,
|
| 231 |
+
# mask=(offs_k[:, None] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[None, :] < (min(
|
| 232 |
+
# (pid_n + 1) * vocab_per_split, vocab_size))),
|
| 233 |
+
# other=0.0)
|
| 234 |
+
|
| 235 |
+
_weight = tl.load(
|
| 236 |
+
weight_ptrs,
|
| 237 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K)
|
| 238 |
+
& (offs_bn[:, None] < (min((pid_n + 1) * vocab_per_split, vocab_size))),
|
| 239 |
+
other=0.0,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# GEMM
|
| 243 |
+
logits = tl.dot(_hidden, _weight.trans(), logits)
|
| 244 |
+
|
| 245 |
+
# advance the ptrs to the next K block
|
| 246 |
+
hidden_ptrs += BLOCK_SIZE_K * stride_hidden_k
|
| 247 |
+
weight_ptrs += BLOCK_SIZE_K * stride_weight_k
|
| 248 |
+
# reset hidden_ptrs for next iteration
|
| 249 |
+
hidden_ptrs -= hidden_size * stride_hidden_k
|
| 250 |
+
|
| 251 |
+
# scale logits by temperature
|
| 252 |
+
logits *= rcp_temperature
|
| 253 |
+
|
| 254 |
+
# update global maximum
|
| 255 |
+
_max_old = _max
|
| 256 |
+
m_pid_n = tl.max(logits, axis=1)
|
| 257 |
+
_max = tl.maximum(_max_old, m_pid_n)
|
| 258 |
+
|
| 259 |
+
exp_logits = tl.exp(logits - _max[:, None])
|
| 260 |
+
coeff = tl.exp(_max_old - _max)
|
| 261 |
+
_accu = coeff * _accu + tl.sum(exp_logits, axis=1)
|
| 262 |
+
|
| 263 |
+
_entropy_b = _entropy_b * coeff + tl.sum(logits * exp_logits, axis=1)
|
| 264 |
+
|
| 265 |
+
label_mask = (offs_bn + rank * vocab_size)[None, :] == labels[:, None]
|
| 266 |
+
_logprobs += tl.sum(logits * label_mask, axis=1)
|
| 267 |
+
|
| 268 |
+
# store maximum
|
| 269 |
+
offs_max_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 270 |
+
offs_max_n = pid_n
|
| 271 |
+
maximum_ptrs = max_ptr + offs_max_n * stride_max_n + offs_max_m * stride_max_m
|
| 272 |
+
tl.store(maximum_ptrs, _max, mask=(offs_max_m < num_tokens) & (offs_max_n < num_splits))
|
| 273 |
+
|
| 274 |
+
# store entropy
|
| 275 |
+
accu_ptrs = accu_ptr + offs_max_n * stride_accu_n + offs_max_m * stride_accu_m
|
| 276 |
+
tl.store(accu_ptrs, _accu, mask=(offs_max_m < num_tokens) & (offs_max_n[None] < num_splits))
|
| 277 |
+
entropy_b_ptrs = entropy_b_ptr + offs_max_n * stride_entropy_b_n + offs_max_m * stride_entropy_b_m
|
| 278 |
+
tl.store(entropy_b_ptrs, _entropy_b, mask=(offs_max_m < num_tokens) & (offs_max_n < num_splits))
|
| 279 |
+
|
| 280 |
+
# store logprobs
|
| 281 |
+
vocab_left_idx = pid_n * vocab_per_split + rank * vocab_size
|
| 282 |
+
vocab_right_idx = min((pid_n + 1) * vocab_per_split, vocab_size) + rank * vocab_size
|
| 283 |
+
mask = (labels >= vocab_left_idx) & (labels < vocab_right_idx)
|
| 284 |
+
mask &= offs_am < num_tokens
|
| 285 |
+
global_logprobs_ptrs = global_logprobs_ptr + offs_am * stride_global_logprobs
|
| 286 |
+
# tl.atomic_add(global_logprobs_ptrs, _logprobs, mask=mask)
|
| 287 |
+
tl.store(global_logprobs_ptrs, _logprobs, mask=mask)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
@triton.autotune(configs=[triton.Config({"BLOCK_SIZE_M": 16, "BLOCK_SIZE_N": 64})], key=["num_tokens", "num_splits"])
|
| 291 |
+
@triton.jit
|
| 292 |
+
def efficient_entropy_triton_kernel_epilogue(
|
| 293 |
+
max_ptr,
|
| 294 |
+
stride_max_m: tl.int64,
|
| 295 |
+
stride_max_n: tl.int64,
|
| 296 |
+
num_tokens,
|
| 297 |
+
num_splits,
|
| 298 |
+
global_max_ptr,
|
| 299 |
+
stride_global_max: tl.int64,
|
| 300 |
+
accu_ptr,
|
| 301 |
+
stride_accu_m: tl.int64,
|
| 302 |
+
stride_accu_n: tl.int64,
|
| 303 |
+
global_accu_ptr,
|
| 304 |
+
stride_global_accu: tl.int64,
|
| 305 |
+
entropy_b_ptr,
|
| 306 |
+
stride_entropy_b_m: tl.int64,
|
| 307 |
+
stride_entropy_b_n: tl.int64,
|
| 308 |
+
global_entropy_b_ptr,
|
| 309 |
+
stride_global_entropy_b: tl.int64,
|
| 310 |
+
global_entropy_ptr,
|
| 311 |
+
stride_global_entropy: tl.int64,
|
| 312 |
+
global_logprobs_ptr,
|
| 313 |
+
stride_global_logprobs: tl.int64,
|
| 314 |
+
global_logprobs_scalar_ptr,
|
| 315 |
+
reduction: int,
|
| 316 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 317 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 318 |
+
):
|
| 319 |
+
"""
|
| 320 |
+
foward epilogue
|
| 321 |
+
"""
|
| 322 |
+
pid_m = tl.program_id(axis=0)
|
| 323 |
+
|
| 324 |
+
offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 325 |
+
global_max = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 326 |
+
global_accu = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 327 |
+
global_entropy_b = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 328 |
+
for pid_n in range(0, tl.cdiv(num_splits, BLOCK_SIZE_N)):
|
| 329 |
+
offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 330 |
+
max_ptrs = max_ptr + offs_m[:, None] * stride_max_m + offs_n[None, :] * stride_max_n
|
| 331 |
+
|
| 332 |
+
_max = tl.load(max_ptrs, mask=(offs_m[:, None] < num_tokens) & (offs_n[None, :] < num_splits), other=0.0)
|
| 333 |
+
|
| 334 |
+
accu_ptrs = accu_ptr + offs_m[:, None] * stride_accu_m + offs_n[None, :] * stride_accu_n
|
| 335 |
+
_accu = tl.load(accu_ptrs, mask=(offs_m[:, None] < num_tokens) & (offs_n[None, :] < num_splits), other=0.0)
|
| 336 |
+
|
| 337 |
+
entropy_b_ptrs = entropy_b_ptr + offs_m[:, None] * stride_entropy_b_m + offs_n[None, :] * stride_entropy_b_n
|
| 338 |
+
_entropy_b = tl.load(
|
| 339 |
+
entropy_b_ptrs, mask=(offs_m[:, None] < num_tokens) & (offs_n[None, :] < num_splits), other=0.0
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
# local reduction
|
| 343 |
+
_max_old = global_max
|
| 344 |
+
_local_max = tl.max(_max, axis=1)
|
| 345 |
+
global_max = tl.maximum(global_max, _local_max)
|
| 346 |
+
|
| 347 |
+
_scale = tl.exp(_max - global_max[:, None])
|
| 348 |
+
_coeff = tl.exp(_max_old - global_max)
|
| 349 |
+
global_accu = _coeff * global_accu + tl.sum(_scale * _accu, axis=1)
|
| 350 |
+
global_entropy_b = _coeff * global_entropy_b + tl.sum(_scale * _entropy_b, axis=1)
|
| 351 |
+
|
| 352 |
+
# store
|
| 353 |
+
maximum_ptrs = global_max_ptr + offs_m * stride_global_max
|
| 354 |
+
tl.store(maximum_ptrs, global_max, mask=offs_m < num_tokens)
|
| 355 |
+
|
| 356 |
+
# store entropy_b
|
| 357 |
+
global_entropy_b = tl.fdiv(global_entropy_b, global_accu) # entropy_b
|
| 358 |
+
tl.store(global_entropy_b_ptr + offs_m * stride_global_entropy_b, global_entropy_b, mask=offs_m < num_tokens)
|
| 359 |
+
|
| 360 |
+
# store entropy
|
| 361 |
+
global_accu_ptrs = global_accu_ptr + offs_m * stride_global_accu
|
| 362 |
+
tl.store(global_accu_ptrs, global_accu, mask=offs_m < num_tokens)
|
| 363 |
+
global_entropy = tl.log(global_accu) + global_max - global_entropy_b # entropy_a
|
| 364 |
+
global_entropy_ptrs = global_entropy_ptr + offs_m * stride_global_entropy
|
| 365 |
+
tl.store(global_entropy_ptrs, global_entropy, mask=offs_m < num_tokens)
|
| 366 |
+
# update logprobs
|
| 367 |
+
global_logprobs_ptrs = global_logprobs_ptr + offs_m * stride_global_logprobs
|
| 368 |
+
global_logprobs = tl.load(global_logprobs_ptrs, mask=offs_m < num_tokens)
|
| 369 |
+
global_logprobs = global_max + tl.log(global_accu) - global_logprobs
|
| 370 |
+
|
| 371 |
+
global_logprobs = -1 * global_logprobs
|
| 372 |
+
if reduction == 0:
|
| 373 |
+
tl.store(global_logprobs_ptrs, global_logprobs, mask=offs_m < num_tokens)
|
| 374 |
+
elif reduction == 1:
|
| 375 |
+
global_logprobs_scalar = tl.sum(global_logprobs, axis=0)
|
| 376 |
+
tl.atomic_add(global_logprobs_scalar_ptr, global_logprobs_scalar)
|
| 377 |
+
elif reduction == 2:
|
| 378 |
+
global_logprobs_scalar = tl.sum(global_logprobs, axis=0) / num_tokens.to(tl.float32)
|
| 379 |
+
tl.atomic_add(global_logprobs_scalar_ptr, global_logprobs_scalar)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
@triton.autotune(configs=[triton.Config({"BLOCK_SIZE_M": 16, "BLOCK_SIZE_N": 64})], key=["num_tokens", "num_splits"])
|
| 383 |
+
@triton.jit
|
| 384 |
+
def efficient_entropy_triton_kernel_epilogue_tp(
|
| 385 |
+
num_tokens,
|
| 386 |
+
num_splits,
|
| 387 |
+
reduced_max_ptr,
|
| 388 |
+
stride_reduced_max_m: tl.int64,
|
| 389 |
+
stride_reduced_max_n: tl.int64,
|
| 390 |
+
original_max_ptr,
|
| 391 |
+
stride_original_max_m: tl.int64,
|
| 392 |
+
stride_original_max_n: tl.int64,
|
| 393 |
+
accu_ptr,
|
| 394 |
+
stride_accu_m: tl.int64,
|
| 395 |
+
stride_accu_n: tl.int64,
|
| 396 |
+
entropy_b_ptr,
|
| 397 |
+
stride_entropy_b_m: tl.int64,
|
| 398 |
+
stride_entropy_b_n: tl.int64,
|
| 399 |
+
global_max_ptr,
|
| 400 |
+
stride_global_max: tl.int64,
|
| 401 |
+
global_accu_ptr,
|
| 402 |
+
stride_global_accu: tl.int64,
|
| 403 |
+
global_entropy_b_ptr,
|
| 404 |
+
stride_global_entropy_b: tl.int64,
|
| 405 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 406 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 407 |
+
):
|
| 408 |
+
pid_m = tl.program_id(axis=0)
|
| 409 |
+
|
| 410 |
+
offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 411 |
+
|
| 412 |
+
global_max = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 413 |
+
global_accu = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 414 |
+
global_entropy_b = tl.zeros((BLOCK_SIZE_M,), dtype=tl.float32)
|
| 415 |
+
for pid_n in range(0, tl.cdiv(num_splits, BLOCK_SIZE_N)):
|
| 416 |
+
offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 417 |
+
|
| 418 |
+
_reduced_max = tl.load(
|
| 419 |
+
reduced_max_ptr + offs_m[:, None] * stride_reduced_max_m + offs_n[None, :] * stride_reduced_max_n,
|
| 420 |
+
mask=(offs_m[:, None] < num_tokens) & (offs_n[None, :] < num_splits),
|
| 421 |
+
other=0.0,
|
| 422 |
+
)
|
| 423 |
+
_original_max = tl.load(
|
| 424 |
+
original_max_ptr + offs_m[:, None] * stride_original_max_m + offs_n[None, :] * stride_original_max_n,
|
| 425 |
+
mask=(offs_m[:, None] < num_tokens) & (offs_n[None, :] < num_splits),
|
| 426 |
+
other=0.0,
|
| 427 |
+
)
|
| 428 |
+
_accu = tl.load(
|
| 429 |
+
accu_ptr + offs_m[:, None] * stride_accu_m + offs_n[None, :] * stride_accu_n,
|
| 430 |
+
mask=(offs_m[:, None] < num_tokens) & (offs_n[None, :] < num_splits),
|
| 431 |
+
other=0.0,
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
# local reduce-max
|
| 435 |
+
_max_old = global_max
|
| 436 |
+
_local_max = tl.max(_reduced_max, axis=1)
|
| 437 |
+
global_max = tl.maximum(global_max, _local_max)
|
| 438 |
+
|
| 439 |
+
# update accumulate
|
| 440 |
+
_coeff = tl.exp(_max_old - global_max)
|
| 441 |
+
_scale = tl.exp(_original_max - global_max[:, None])
|
| 442 |
+
global_accu = _coeff * global_accu + tl.sum(_scale * _accu, axis=1)
|
| 443 |
+
|
| 444 |
+
# update entropy_b
|
| 445 |
+
_entropy_b = tl.load(
|
| 446 |
+
entropy_b_ptr + offs_m[:, None] * stride_entropy_b_m + offs_n[None, :] * stride_entropy_b_n,
|
| 447 |
+
mask=(offs_m[:, None] < num_tokens) & (offs_n[None, :] < num_splits),
|
| 448 |
+
other=0.0,
|
| 449 |
+
)
|
| 450 |
+
global_entropy_b = _coeff * global_entropy_b + tl.sum(_scale * _entropy_b, axis=1)
|
| 451 |
+
|
| 452 |
+
# store
|
| 453 |
+
tl.store(global_max_ptr + offs_m * stride_global_max, global_max, mask=offs_m < num_tokens)
|
| 454 |
+
tl.store(global_accu_ptr + offs_m * stride_global_accu, global_accu, mask=offs_m < num_tokens)
|
| 455 |
+
tl.store(global_entropy_b_ptr + offs_m * stride_global_entropy_b, global_entropy_b, mask=offs_m < num_tokens)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
@triton.autotune(configs=[triton.Config({"BLOCK_SIZE_M": 16})], key=["num_tokens"])
|
| 459 |
+
@triton.jit
|
| 460 |
+
def efficient_entropy_triton_epilogue_tp_update(
|
| 461 |
+
num_tokens,
|
| 462 |
+
logprobs_ptr,
|
| 463 |
+
stride_logprobs: tl.int64,
|
| 464 |
+
maximum_ptr,
|
| 465 |
+
stride_maximum: tl.int64,
|
| 466 |
+
accumulate_ptr,
|
| 467 |
+
stride_accumulate: tl.int64,
|
| 468 |
+
entropy_b_ptr,
|
| 469 |
+
stride_entropy_b: tl.int64,
|
| 470 |
+
entropy_ptr,
|
| 471 |
+
stride_entropy: tl.int64,
|
| 472 |
+
logprobs_scalar_ptr,
|
| 473 |
+
reduction: int,
|
| 474 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 475 |
+
):
|
| 476 |
+
pid_m = tl.program_id(axis=0)
|
| 477 |
+
|
| 478 |
+
offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 479 |
+
|
| 480 |
+
maximum = tl.load(maximum_ptr + offs_m * stride_maximum, mask=offs_m < num_tokens)
|
| 481 |
+
accumulate = tl.load(accumulate_ptr + offs_m * stride_accumulate, mask=offs_m < num_tokens)
|
| 482 |
+
|
| 483 |
+
entropy_b = tl.load(entropy_b_ptr + offs_m * stride_entropy_b, mask=offs_m < num_tokens)
|
| 484 |
+
entropy_b = tl.fdiv(entropy_b, accumulate)
|
| 485 |
+
tl.store(entropy_b_ptr + offs_m * stride_entropy_b, entropy_b, mask=offs_m < num_tokens)
|
| 486 |
+
|
| 487 |
+
entropy = tl.log(accumulate) + maximum - entropy_b
|
| 488 |
+
tl.store(entropy_ptr + offs_m * stride_entropy, entropy, mask=offs_m < num_tokens)
|
| 489 |
+
|
| 490 |
+
logprobs = tl.load(logprobs_ptr + offs_m * stride_logprobs, mask=offs_m < num_tokens)
|
| 491 |
+
logprobs = maximum + tl.log(accumulate) - logprobs
|
| 492 |
+
|
| 493 |
+
logprobs = -1 * logprobs
|
| 494 |
+
if reduction == 0:
|
| 495 |
+
tl.store(logprobs_ptr + offs_m * stride_logprobs, logprobs, mask=offs_m < num_tokens)
|
| 496 |
+
elif reduction == 1:
|
| 497 |
+
logprobs_scalar = tl.sum(logprobs, axis=0)
|
| 498 |
+
tl.atomic_add(logprobs_scalar_ptr, logprobs_scalar)
|
| 499 |
+
elif reduction == 2:
|
| 500 |
+
logprobs_scalar = tl.sum(logprobs, axis=0) / num_tokens.to(tl.float32)
|
| 501 |
+
tl.atomic_add(logprobs_scalar_ptr, logprobs_scalar)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
_dedicated_stream, _dedicated_events = None, None
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def efficient_entropy_forward(
|
| 508 |
+
hidden: torch.Tensor,
|
| 509 |
+
weight: torch.Tensor,
|
| 510 |
+
labels: torch.Tensor,
|
| 511 |
+
reduction: typing.Optional[int] = 2,
|
| 512 |
+
temperature: typing.Optional[float] = 1.0,
|
| 513 |
+
dist_process_group: typing.Optional[dist.ProcessGroup] = None,
|
| 514 |
+
) -> list[torch.Tensor]:
|
| 515 |
+
"""
|
| 516 |
+
forward host function
|
| 517 |
+
"""
|
| 518 |
+
assert hidden.is_cuda and weight.is_cuda and labels.is_cuda
|
| 519 |
+
assert weight.device == hidden.device and labels.device == hidden.device
|
| 520 |
+
assert hidden.dim() == 2 and weight.dim() == 2 and labels.dim() == 1
|
| 521 |
+
assert hidden.is_contiguous() and weight.is_contiguous() and labels.is_contiguous()
|
| 522 |
+
|
| 523 |
+
assert hidden.shape[0] == labels.shape[0] and hidden.shape[1] == weight.shape[1]
|
| 524 |
+
|
| 525 |
+
_rank = 0 if dist_process_group is None else dist.get_rank(dist_process_group)
|
| 526 |
+
_world_size = 1 if dist_process_group is None else dist.get_world_size(dist_process_group)
|
| 527 |
+
|
| 528 |
+
if dist_process_group is not None and not hasattr(efficient_entropy_forward, "_initialized"):
|
| 529 |
+
global _dedicated_stream, _dedicated_events
|
| 530 |
+
_dedicated_stream = get_torch_device().Stream(hidden.device)
|
| 531 |
+
_dedicated_events = [get_torch_device().Event() for _ in range(2)]
|
| 532 |
+
efficient_entropy_forward._initialized = True
|
| 533 |
+
|
| 534 |
+
num_tokens, hidden_size = hidden.shape
|
| 535 |
+
num_tokens = labels.shape[0]
|
| 536 |
+
vocab_size, hidden_size = weight.shape
|
| 537 |
+
assert hidden_size % 128 == 0
|
| 538 |
+
|
| 539 |
+
REDUCTION = get_entropy_reduction_enum(reduction)
|
| 540 |
+
|
| 541 |
+
if REDUCTION == EntropyReductionEnum._None:
|
| 542 |
+
if dist_process_group is None:
|
| 543 |
+
logprobs = torch.empty((num_tokens,), device=hidden.device, dtype=torch.float32)
|
| 544 |
+
else:
|
| 545 |
+
logprobs = torch.zeros((num_tokens,), device=hidden.device, dtype=torch.float32)
|
| 546 |
+
elif REDUCTION in (EntropyReductionEnum._Sum, EntropyReductionEnum._Mean):
|
| 547 |
+
logprobs = torch.empty((), device=hidden.device, dtype=torch.float32)
|
| 548 |
+
else:
|
| 549 |
+
raise ValueError(f"Invalid reduction: {reduction}")
|
| 550 |
+
|
| 551 |
+
entropy = torch.empty((num_tokens,), device=hidden.device, dtype=torch.float32)
|
| 552 |
+
assert logprobs.is_contiguous() and entropy.is_contiguous()
|
| 553 |
+
|
| 554 |
+
maximum = torch.empty_like(entropy)
|
| 555 |
+
accumulate_and_entropy_b = torch.empty((num_tokens * 2,), device=hidden.device, dtype=torch.float32)
|
| 556 |
+
accumulate_and_entropy_b_view = accumulate_and_entropy_b.view(2, num_tokens)
|
| 557 |
+
accumulate = accumulate_and_entropy_b_view[0, :]
|
| 558 |
+
entropy_b = accumulate_and_entropy_b_view[1, :]
|
| 559 |
+
assert maximum.is_contiguous() and accumulate.is_contiguous() and entropy_b.is_contiguous()
|
| 560 |
+
|
| 561 |
+
vocab_per_split = 1024
|
| 562 |
+
assert vocab_per_split % 128 == 0
|
| 563 |
+
num_splits = (vocab_size + vocab_per_split - 1) // vocab_per_split
|
| 564 |
+
|
| 565 |
+
_max = torch.empty((num_tokens, num_splits), device=hidden.device, dtype=torch.float32)
|
| 566 |
+
_accu = torch.empty((num_tokens, num_splits), device=hidden.device, dtype=torch.float32)
|
| 567 |
+
_entropy_b = torch.empty((num_tokens, num_splits), device=hidden.device, dtype=torch.float32)
|
| 568 |
+
|
| 569 |
+
if REDUCTION == EntropyReductionEnum._None:
|
| 570 |
+
_logprobs = logprobs
|
| 571 |
+
else:
|
| 572 |
+
_logprobs = torch.empty((num_tokens,), device=hidden.device, dtype=torch.float32)
|
| 573 |
+
|
| 574 |
+
assert _accu.is_contiguous() and _entropy_b.is_contiguous() and _max.is_contiguous()
|
| 575 |
+
assert _accu.is_cuda and _entropy_b.is_cuda and _max.is_cuda
|
| 576 |
+
|
| 577 |
+
if _config._use_triton:
|
| 578 |
+
# 1D kernel launch, then split the tile
|
| 579 |
+
def mainloop_grid(meta):
|
| 580 |
+
return (triton.cdiv(num_tokens, meta["BLOCK_SIZE_M"]) * num_splits,)
|
| 581 |
+
|
| 582 |
+
efficient_entropy_kernel_general_mainloop[mainloop_grid](
|
| 583 |
+
_rank,
|
| 584 |
+
hidden,
|
| 585 |
+
weight,
|
| 586 |
+
labels,
|
| 587 |
+
num_tokens,
|
| 588 |
+
hidden_size,
|
| 589 |
+
vocab_size,
|
| 590 |
+
vocab_per_split,
|
| 591 |
+
hidden.stride(0),
|
| 592 |
+
hidden.stride(1),
|
| 593 |
+
weight.stride(0),
|
| 594 |
+
weight.stride(1),
|
| 595 |
+
_max,
|
| 596 |
+
_max.stride(0),
|
| 597 |
+
_max.stride(1),
|
| 598 |
+
_accu,
|
| 599 |
+
_accu.stride(0),
|
| 600 |
+
_accu.stride(1),
|
| 601 |
+
_entropy_b,
|
| 602 |
+
_entropy_b.stride(0),
|
| 603 |
+
_entropy_b.stride(1),
|
| 604 |
+
_logprobs,
|
| 605 |
+
_logprobs.stride(0),
|
| 606 |
+
logprobs,
|
| 607 |
+
1.0 / temperature,
|
| 608 |
+
)
|
| 609 |
+
else:
|
| 610 |
+
raise AssertionError("Triton is required for efficient entropy kernel")
|
| 611 |
+
|
| 612 |
+
# reduction on maximum and maximum_indices
|
| 613 |
+
def epilogue_grid(meta):
|
| 614 |
+
return (triton.cdiv(num_tokens, meta["BLOCK_SIZE_M"]),)
|
| 615 |
+
|
| 616 |
+
if dist_process_group is None:
|
| 617 |
+
efficient_entropy_triton_kernel_epilogue[epilogue_grid](
|
| 618 |
+
_max,
|
| 619 |
+
_max.stride(0),
|
| 620 |
+
_max.stride(1),
|
| 621 |
+
num_tokens,
|
| 622 |
+
num_splits,
|
| 623 |
+
maximum,
|
| 624 |
+
maximum.stride(0),
|
| 625 |
+
_accu,
|
| 626 |
+
_accu.stride(0),
|
| 627 |
+
_accu.stride(1),
|
| 628 |
+
accumulate,
|
| 629 |
+
accumulate.stride(0),
|
| 630 |
+
_entropy_b,
|
| 631 |
+
_entropy_b.stride(0),
|
| 632 |
+
_entropy_b.stride(1),
|
| 633 |
+
entropy_b,
|
| 634 |
+
entropy_b.stride(0),
|
| 635 |
+
entropy,
|
| 636 |
+
entropy.stride(0),
|
| 637 |
+
_logprobs,
|
| 638 |
+
_logprobs.stride(0),
|
| 639 |
+
logprobs,
|
| 640 |
+
REDUCTION,
|
| 641 |
+
)
|
| 642 |
+
else:
|
| 643 |
+
# tensor-parallel
|
| 644 |
+
_max_backup = _max.clone()
|
| 645 |
+
dist.all_reduce(_max, op=dist.ReduceOp.MAX, group=dist_process_group)
|
| 646 |
+
|
| 647 |
+
get_torch_device().current_stream().record_event(_dedicated_events[0])
|
| 648 |
+
with get_torch_device().stream(_dedicated_stream):
|
| 649 |
+
_dedicated_stream.wait_event(_dedicated_events[0])
|
| 650 |
+
dist.all_reduce(_logprobs, op=dist.ReduceOp.SUM, group=dist_process_group)
|
| 651 |
+
_dedicated_stream.record_event(_dedicated_events[1])
|
| 652 |
+
|
| 653 |
+
efficient_entropy_triton_kernel_epilogue_tp[epilogue_grid](
|
| 654 |
+
num_tokens,
|
| 655 |
+
num_splits,
|
| 656 |
+
_max,
|
| 657 |
+
_max.stride(0),
|
| 658 |
+
_max.stride(1),
|
| 659 |
+
_max_backup,
|
| 660 |
+
_max_backup.stride(0),
|
| 661 |
+
_max_backup.stride(1),
|
| 662 |
+
_accu,
|
| 663 |
+
_accu.stride(0),
|
| 664 |
+
_accu.stride(1),
|
| 665 |
+
_entropy_b,
|
| 666 |
+
_entropy_b.stride(0),
|
| 667 |
+
_entropy_b.stride(1),
|
| 668 |
+
maximum,
|
| 669 |
+
maximum.stride(0),
|
| 670 |
+
accumulate,
|
| 671 |
+
accumulate.stride(0),
|
| 672 |
+
entropy_b,
|
| 673 |
+
entropy_b.stride(0),
|
| 674 |
+
)
|
| 675 |
+
get_torch_device().current_stream().wait_event(_dedicated_events[1])
|
| 676 |
+
|
| 677 |
+
dist.all_reduce(accumulate_and_entropy_b, op=dist.ReduceOp.SUM, group=dist_process_group)
|
| 678 |
+
|
| 679 |
+
# update logprobs & entropy
|
| 680 |
+
efficient_entropy_triton_epilogue_tp_update[epilogue_grid](
|
| 681 |
+
num_tokens,
|
| 682 |
+
_logprobs,
|
| 683 |
+
_logprobs.stride(0),
|
| 684 |
+
maximum,
|
| 685 |
+
maximum.stride(0),
|
| 686 |
+
accumulate,
|
| 687 |
+
accumulate.stride(0),
|
| 688 |
+
entropy_b,
|
| 689 |
+
entropy_b.stride(0),
|
| 690 |
+
entropy,
|
| 691 |
+
entropy.stride(0),
|
| 692 |
+
logprobs,
|
| 693 |
+
REDUCTION,
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
return (logprobs, entropy, maximum, accumulate, entropy_b)
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
# NOTE: merge d_weight & d_hidden here, split along M & N
|
| 700 |
+
@triton.autotune(
|
| 701 |
+
configs=[
|
| 702 |
+
triton.Config(
|
| 703 |
+
{"BLOCK_SIZE_M": 128, "BLOCK_SIZE_N": 128, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 16},
|
| 704 |
+
num_stages=3,
|
| 705 |
+
num_warps=8,
|
| 706 |
+
)
|
| 707 |
+
],
|
| 708 |
+
key=["num_tokens", "hidden_size", "vocab_size"],
|
| 709 |
+
)
|
| 710 |
+
@triton.jit
|
| 711 |
+
def efficient_entropy_backward_kernel_general_mainloop_MN(
|
| 712 |
+
num_tokens: int,
|
| 713 |
+
hidden_size: int,
|
| 714 |
+
vocab_size: int,
|
| 715 |
+
rank: int,
|
| 716 |
+
hidden_ptr,
|
| 717 |
+
stride_hidden_m: tl.int64,
|
| 718 |
+
stride_hidden_k: tl.int64,
|
| 719 |
+
weight_ptr,
|
| 720 |
+
stride_weight_n: tl.int64,
|
| 721 |
+
stride_weight_k: tl.int64,
|
| 722 |
+
labels_ptr,
|
| 723 |
+
stride_labels: tl.int64,
|
| 724 |
+
maximum_ptr,
|
| 725 |
+
stride_maximum: tl.int64,
|
| 726 |
+
accu_ptr,
|
| 727 |
+
stride_accu: tl.int64,
|
| 728 |
+
d_entropy_ptr,
|
| 729 |
+
stride_d_entropy: tl.int64,
|
| 730 |
+
d_logprobs_ptr,
|
| 731 |
+
stride_d_logprobs: tl.int64,
|
| 732 |
+
reduction: int,
|
| 733 |
+
entropy_b_ptr,
|
| 734 |
+
stride_entropy_b: tl.int64,
|
| 735 |
+
d_hidden_ptr,
|
| 736 |
+
stride_d_hidden_m: tl.int64,
|
| 737 |
+
stride_d_hidden_k: tl.int64,
|
| 738 |
+
d_weight_ptr,
|
| 739 |
+
stride_d_weight_n: tl.int64,
|
| 740 |
+
stride_d_weight_k: tl.int64,
|
| 741 |
+
rcp_temperature: tl.float32,
|
| 742 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 743 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 744 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 745 |
+
GROUP_SIZE_M: tl.constexpr,
|
| 746 |
+
):
|
| 747 |
+
"""
|
| 748 |
+
backward mainloop, where d_logits & d_hidden & d_weight are fused
|
| 749 |
+
"""
|
| 750 |
+
# block swizzling
|
| 751 |
+
# pid = tl.program_id(axis=0)
|
| 752 |
+
# num_pid_m = tl.cdiv(num_tokens, BLOCK_SIZE_M)
|
| 753 |
+
# pid_m = pid % num_pid_m
|
| 754 |
+
# pid_n = pid // num_pid_m
|
| 755 |
+
|
| 756 |
+
pid = tl.program_id(axis=0)
|
| 757 |
+
num_pid_m = tl.cdiv(num_tokens, BLOCK_SIZE_M)
|
| 758 |
+
num_pid_n = tl.cdiv(vocab_size, BLOCK_SIZE_N)
|
| 759 |
+
num_pid_in_group = GROUP_SIZE_M * num_pid_n
|
| 760 |
+
group_id = pid // num_pid_in_group
|
| 761 |
+
first_pid_m = group_id * GROUP_SIZE_M
|
| 762 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
| 763 |
+
pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
|
| 764 |
+
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 765 |
+
|
| 766 |
+
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 767 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 768 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 769 |
+
|
| 770 |
+
maximum_ptrs = maximum_ptr + offs_am * stride_maximum
|
| 771 |
+
maximum = tl.load(maximum_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 772 |
+
accu_ptrs = accu_ptr + offs_am * stride_accu
|
| 773 |
+
accu = tl.load(accu_ptrs, mask=offs_am < num_tokens, other=1e-6) # epsilon to avoid division by zero
|
| 774 |
+
accu_rcp = tl.fdiv(1.0, accu)
|
| 775 |
+
|
| 776 |
+
d_entropy_ptrs = d_entropy_ptr + offs_am * stride_d_entropy
|
| 777 |
+
d_entropy = tl.load(d_entropy_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 778 |
+
if reduction == 0: # none
|
| 779 |
+
d_logprobs_ptrs = d_logprobs_ptr + offs_am * stride_d_logprobs
|
| 780 |
+
d_logprobs = tl.load(d_logprobs_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 781 |
+
elif reduction == 1: # sum
|
| 782 |
+
d_logprobs = tl.load(d_logprobs_ptr)
|
| 783 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 784 |
+
else: # mean
|
| 785 |
+
d_logprobs = tl.fdiv(tl.load(d_logprobs_ptr), num_tokens.to(tl.float32))
|
| 786 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 787 |
+
d_logprobs = -1 * d_logprobs
|
| 788 |
+
|
| 789 |
+
entropy_b_ptrs = entropy_b_ptr + offs_am * stride_entropy_b
|
| 790 |
+
entropy_b = tl.load(entropy_b_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 791 |
+
|
| 792 |
+
hidden_ptrs = hidden_ptr + (offs_am[:, None] * stride_hidden_m + offs_k[None, :] * stride_hidden_k)
|
| 793 |
+
# weight_ptrs = weight_ptr + (offs_k[:, None] * stride_weight_k + offs_bn[None, :] * stride_weight_n)
|
| 794 |
+
weight_ptrs = weight_ptr + (offs_bn[:, None] * stride_weight_n + offs_k[None, :] * stride_weight_k)
|
| 795 |
+
labels_ptrs = labels_ptr + offs_am * stride_labels
|
| 796 |
+
labels = tl.load(labels_ptrs, mask=offs_am < num_tokens, other=0)
|
| 797 |
+
|
| 798 |
+
d_hidden_ptrs = d_hidden_ptr + offs_am[:, None] * stride_d_hidden_m + offs_k[None, :] * stride_d_hidden_k
|
| 799 |
+
# d_weight_ptrs = d_weight_ptr + offs_k[:, None] * stride_d_weight_k + offs_bn[None, :] * stride_d_weight_n
|
| 800 |
+
d_weight_ptrs = d_weight_ptr + offs_bn[:, None] * stride_d_weight_n + offs_k[None, :] * stride_d_weight_k
|
| 801 |
+
|
| 802 |
+
logits = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 803 |
+
for k in range(0, tl.cdiv(hidden_size, BLOCK_SIZE_K)):
|
| 804 |
+
_hidden = tl.load(
|
| 805 |
+
hidden_ptrs,
|
| 806 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_am[:, None] < num_tokens),
|
| 807 |
+
other=0.0,
|
| 808 |
+
)
|
| 809 |
+
# _weight = tl.load(weight_ptrs,
|
| 810 |
+
# mask=(offs_k[:, None] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[None, :] < vocab_size),
|
| 811 |
+
# other=0.0)
|
| 812 |
+
_weight = tl.load(
|
| 813 |
+
weight_ptrs,
|
| 814 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[:, None] < vocab_size),
|
| 815 |
+
other=0.0,
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
logits = tl.dot(_hidden, _weight.trans(), logits)
|
| 819 |
+
|
| 820 |
+
hidden_ptrs += BLOCK_SIZE_K * stride_hidden_k
|
| 821 |
+
weight_ptrs += BLOCK_SIZE_K * stride_weight_k
|
| 822 |
+
hidden_ptrs -= hidden_size * stride_hidden_k
|
| 823 |
+
weight_ptrs -= hidden_size * stride_weight_k
|
| 824 |
+
|
| 825 |
+
# scale logits by temperature
|
| 826 |
+
logits *= rcp_temperature
|
| 827 |
+
|
| 828 |
+
exp_logits = tl.exp(logits - maximum[:, None])
|
| 829 |
+
|
| 830 |
+
mask = (offs_bn + rank * vocab_size)[None, :] == labels[:, None]
|
| 831 |
+
d_logits = d_logprobs[:, None] * (exp_logits * accu_rcp[:, None] - mask)
|
| 832 |
+
d_logits += d_entropy[:, None] * (-exp_logits * accu_rcp[:, None]) * (logits - entropy_b[:, None])
|
| 833 |
+
|
| 834 |
+
# scale d_logits by temperature
|
| 835 |
+
d_logits *= rcp_temperature
|
| 836 |
+
|
| 837 |
+
# loop for d_weight & d_hidden
|
| 838 |
+
for k in range(0, tl.cdiv(hidden_size, BLOCK_SIZE_K)):
|
| 839 |
+
_hidden = tl.load(
|
| 840 |
+
hidden_ptrs,
|
| 841 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_am[:, None] < num_tokens),
|
| 842 |
+
other=0.0,
|
| 843 |
+
)
|
| 844 |
+
# _d_weight = tl.dot(tl.trans(_hidden).to(tl.float32), d_logits)
|
| 845 |
+
# tl.atomic_add(d_weight_ptrs,
|
| 846 |
+
# _d_weight,
|
| 847 |
+
# mask=(offs_k[:, None] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[None, :] < vocab_size))
|
| 848 |
+
_d_weight = tl.dot(d_logits.trans(), _hidden.to(tl.float32))
|
| 849 |
+
tl.atomic_add(
|
| 850 |
+
d_weight_ptrs,
|
| 851 |
+
_d_weight,
|
| 852 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[:, None] < vocab_size),
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
# _weight = tl.load(weight_ptrs,
|
| 856 |
+
# mask=(offs_k[:, None] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[None, :] < vocab_size),
|
| 857 |
+
# other=0.0)
|
| 858 |
+
# _d_hidden = tl.dot(d_logits, tl.trans(_weight).to(tl.float32))
|
| 859 |
+
_weight = tl.load(
|
| 860 |
+
weight_ptrs,
|
| 861 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[:, None] < vocab_size),
|
| 862 |
+
other=0.0,
|
| 863 |
+
)
|
| 864 |
+
_d_hidden = tl.dot(d_logits, _weight.to(tl.float32))
|
| 865 |
+
tl.atomic_add(
|
| 866 |
+
d_hidden_ptrs,
|
| 867 |
+
_d_hidden,
|
| 868 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_am[:, None] < num_tokens),
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
hidden_ptrs += BLOCK_SIZE_K * stride_hidden_k
|
| 872 |
+
weight_ptrs += BLOCK_SIZE_K * stride_weight_k
|
| 873 |
+
d_hidden_ptrs += BLOCK_SIZE_K * stride_d_hidden_k
|
| 874 |
+
d_weight_ptrs += BLOCK_SIZE_K * stride_d_weight_k
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
@triton.autotune(
|
| 878 |
+
configs=[
|
| 879 |
+
triton.Config(
|
| 880 |
+
{"BLOCK_SIZE_M": 128, "BLOCK_SIZE_N": 128, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 16},
|
| 881 |
+
num_stages=3,
|
| 882 |
+
num_warps=8,
|
| 883 |
+
),
|
| 884 |
+
],
|
| 885 |
+
key=["num_tokens", "hidden_size", "vocab_size"],
|
| 886 |
+
)
|
| 887 |
+
@triton.jit
|
| 888 |
+
def efficient_entropy_backward_kernel_d_hidden(
|
| 889 |
+
num_tokens: int,
|
| 890 |
+
hidden_size: int,
|
| 891 |
+
vocab_size: int,
|
| 892 |
+
rank: int,
|
| 893 |
+
hidden_ptr,
|
| 894 |
+
stride_hidden_m: tl.int64,
|
| 895 |
+
stride_hidden_k: tl.int64,
|
| 896 |
+
weight_ptr,
|
| 897 |
+
stride_weight_n: tl.int64,
|
| 898 |
+
stride_weight_k: tl.int64,
|
| 899 |
+
labels_ptr,
|
| 900 |
+
stride_labels: tl.int64,
|
| 901 |
+
maximum_ptr,
|
| 902 |
+
stride_maximum: tl.int64,
|
| 903 |
+
accu_ptr,
|
| 904 |
+
stride_accu: tl.int64,
|
| 905 |
+
d_entropy_ptr,
|
| 906 |
+
stride_d_entropy: tl.int64,
|
| 907 |
+
d_logprobs_ptr,
|
| 908 |
+
stride_d_logprobs: tl.int64,
|
| 909 |
+
reduction: int,
|
| 910 |
+
entropy_b_ptr,
|
| 911 |
+
stride_entropy_b: tl.int64,
|
| 912 |
+
d_hidden_ptr,
|
| 913 |
+
stride_d_hidden_m: tl.int64,
|
| 914 |
+
stride_d_hidden_k: tl.int64,
|
| 915 |
+
rcp_temperature: tl.float32,
|
| 916 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 917 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 918 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 919 |
+
GROUP_SIZE_M: tl.constexpr,
|
| 920 |
+
):
|
| 921 |
+
"""
|
| 922 |
+
backward d_hidden
|
| 923 |
+
"""
|
| 924 |
+
pid = tl.program_id(axis=0)
|
| 925 |
+
num_pid_m = tl.cdiv(num_tokens, BLOCK_SIZE_M)
|
| 926 |
+
pid_m = pid % num_pid_m
|
| 927 |
+
pid_k = pid // num_pid_m
|
| 928 |
+
|
| 929 |
+
offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 930 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 931 |
+
result_offs_k = pid_k * BLOCK_SIZE_K + offs_k
|
| 932 |
+
|
| 933 |
+
maximum = tl.load(maximum_ptr + offs_m * stride_maximum, mask=offs_m < num_tokens, other=0.0)
|
| 934 |
+
accu = tl.load(accu_ptr + offs_m * stride_accu, mask=offs_m < num_tokens, other=1e-6)
|
| 935 |
+
accu_rcp = tl.fdiv(1.0, accu)
|
| 936 |
+
d_entropy = tl.load(d_entropy_ptr + offs_m * stride_d_entropy, mask=offs_m < num_tokens, other=0.0)
|
| 937 |
+
if reduction == 0:
|
| 938 |
+
d_logprobs = tl.load(d_logprobs_ptr + offs_m * stride_d_logprobs, mask=offs_m < num_tokens, other=0.0)
|
| 939 |
+
elif reduction == 1:
|
| 940 |
+
d_logprobs = tl.load(d_logprobs_ptr)
|
| 941 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 942 |
+
else:
|
| 943 |
+
d_logprobs = tl.fdiv(tl.load(d_logprobs_ptr), num_tokens.to(tl.float32))
|
| 944 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 945 |
+
d_logprobs = -1 * d_logprobs
|
| 946 |
+
|
| 947 |
+
entropy_b = tl.load(entropy_b_ptr + offs_m * stride_entropy_b, mask=offs_m < num_tokens, other=0.0)
|
| 948 |
+
labels = tl.load(labels_ptr + offs_m * stride_labels, mask=offs_m < num_tokens, other=0)
|
| 949 |
+
|
| 950 |
+
# iterate over vocab_size
|
| 951 |
+
d_hidden = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_K), dtype=tl.float32)
|
| 952 |
+
for n in range(0, tl.cdiv(vocab_size, BLOCK_SIZE_N)):
|
| 953 |
+
offs_n = n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 954 |
+
|
| 955 |
+
hidden_ptrs = hidden_ptr + (offs_m[:, None] * stride_hidden_m + offs_k[None, :] * stride_hidden_k)
|
| 956 |
+
weight_ptrs = weight_ptr + (offs_n[:, None] * stride_weight_n + offs_k[None, :] * stride_weight_k)
|
| 957 |
+
|
| 958 |
+
# iterate over hidden_size to get logits
|
| 959 |
+
logits = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 960 |
+
for k in range(0, tl.cdiv(hidden_size, BLOCK_SIZE_K)):
|
| 961 |
+
_hidden = tl.load(
|
| 962 |
+
hidden_ptrs,
|
| 963 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_m[:, None] < num_tokens),
|
| 964 |
+
other=0.0,
|
| 965 |
+
)
|
| 966 |
+
_weight = tl.load(
|
| 967 |
+
weight_ptrs,
|
| 968 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_n[:, None] < vocab_size),
|
| 969 |
+
other=0.0,
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
logits = tl.dot(_hidden, _weight.trans(), logits)
|
| 973 |
+
|
| 974 |
+
hidden_ptrs += BLOCK_SIZE_K * stride_hidden_k
|
| 975 |
+
weight_ptrs += BLOCK_SIZE_K * stride_weight_k
|
| 976 |
+
|
| 977 |
+
# scale logits by temperature
|
| 978 |
+
logits *= rcp_temperature
|
| 979 |
+
|
| 980 |
+
exp_logits = tl.exp(logits - maximum[:, None])
|
| 981 |
+
|
| 982 |
+
mask = (offs_n + rank * vocab_size)[None, :] == labels[:, None]
|
| 983 |
+
d_logits = d_logprobs[:, None] * (exp_logits * accu_rcp[:, None] - mask)
|
| 984 |
+
d_logits += d_entropy[:, None] * (-exp_logits * accu_rcp[:, None]) * (logits - entropy_b[:, None])
|
| 985 |
+
|
| 986 |
+
# scale d_logits
|
| 987 |
+
d_logits *= rcp_temperature
|
| 988 |
+
|
| 989 |
+
# calculate d_hidden
|
| 990 |
+
weight_ptrs = weight_ptr + (offs_n[:, None] * stride_weight_n + result_offs_k[None, :] * stride_weight_k)
|
| 991 |
+
_weight = tl.load(
|
| 992 |
+
weight_ptrs, mask=(result_offs_k[None, :] < hidden_size) & (offs_n[:, None] < vocab_size), other=0.0
|
| 993 |
+
)
|
| 994 |
+
d_hidden = tl.dot(d_logits.to(weight_ptr.dtype.element_ty), _weight, d_hidden)
|
| 995 |
+
|
| 996 |
+
# write back
|
| 997 |
+
tl.store(
|
| 998 |
+
d_hidden_ptr + offs_m[:, None] * stride_d_hidden_m + result_offs_k[None, :] * stride_d_hidden_k,
|
| 999 |
+
d_hidden,
|
| 1000 |
+
mask=(offs_m[:, None] < num_tokens) & (result_offs_k[None, :] < hidden_size),
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
@triton.autotune(
|
| 1005 |
+
configs=[
|
| 1006 |
+
triton.Config(
|
| 1007 |
+
{"BLOCK_SIZE_M": 128, "BLOCK_SIZE_N": 128, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 16},
|
| 1008 |
+
num_stages=3,
|
| 1009 |
+
num_warps=8,
|
| 1010 |
+
),
|
| 1011 |
+
],
|
| 1012 |
+
key=["num_tokens", "hidden_size", "vocab_size"],
|
| 1013 |
+
)
|
| 1014 |
+
@triton.jit
|
| 1015 |
+
def efficient_entropy_backward_kernel_d_weight(
|
| 1016 |
+
num_tokens: int,
|
| 1017 |
+
hidden_size: int,
|
| 1018 |
+
vocab_size: int,
|
| 1019 |
+
rank: int,
|
| 1020 |
+
hidden_ptr,
|
| 1021 |
+
stride_hidden_m: tl.int64,
|
| 1022 |
+
stride_hidden_k: tl.int64,
|
| 1023 |
+
weight_ptr,
|
| 1024 |
+
stride_weight_n: tl.int64,
|
| 1025 |
+
stride_weight_k: tl.int64,
|
| 1026 |
+
labels_ptr,
|
| 1027 |
+
stride_labels: tl.int64,
|
| 1028 |
+
maximum_ptr,
|
| 1029 |
+
stride_maximum: tl.int64,
|
| 1030 |
+
accu_ptr,
|
| 1031 |
+
stride_accu: tl.int64,
|
| 1032 |
+
d_entropy_ptr,
|
| 1033 |
+
stride_d_entropy: tl.int64,
|
| 1034 |
+
d_logprobs_ptr,
|
| 1035 |
+
stride_d_logprobs: tl.int64,
|
| 1036 |
+
reduction: int,
|
| 1037 |
+
entropy_b_ptr,
|
| 1038 |
+
stride_entropy_b: tl.int64,
|
| 1039 |
+
d_weight_ptr,
|
| 1040 |
+
stride_d_weight_n: tl.int64,
|
| 1041 |
+
stride_d_weight_k: tl.int64,
|
| 1042 |
+
rcp_temperature: tl.float32,
|
| 1043 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 1044 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 1045 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 1046 |
+
GROUP_SIZE_M: tl.constexpr,
|
| 1047 |
+
):
|
| 1048 |
+
pid = tl.program_id(axis=0)
|
| 1049 |
+
num_pid_n = tl.cdiv(vocab_size, BLOCK_SIZE_N)
|
| 1050 |
+
pid_n = pid % num_pid_n
|
| 1051 |
+
pid_k = pid // num_pid_n
|
| 1052 |
+
|
| 1053 |
+
offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 1054 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 1055 |
+
result_offs_k = pid_k * BLOCK_SIZE_K + offs_k
|
| 1056 |
+
|
| 1057 |
+
d_weight = tl.zeros((BLOCK_SIZE_N, BLOCK_SIZE_K), dtype=tl.float32)
|
| 1058 |
+
for m in range(0, tl.cdiv(num_tokens, BLOCK_SIZE_M)):
|
| 1059 |
+
offs_m = m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 1060 |
+
|
| 1061 |
+
maximum = tl.load(maximum_ptr + offs_m * stride_maximum, mask=offs_m < num_tokens, other=0.0)
|
| 1062 |
+
accu = tl.load(accu_ptr + offs_m * stride_accu, mask=offs_m < num_tokens, other=1e-6)
|
| 1063 |
+
accu_rcp = tl.fdiv(1.0, accu)
|
| 1064 |
+
d_entropy = tl.load(d_entropy_ptr + offs_m * stride_d_entropy, mask=offs_m < num_tokens, other=0.0)
|
| 1065 |
+
if reduction == 0:
|
| 1066 |
+
d_logprobs = tl.load(d_logprobs_ptr + offs_m * stride_d_logprobs, mask=offs_m < num_tokens, other=0.0)
|
| 1067 |
+
elif reduction == 1:
|
| 1068 |
+
d_logprobs = tl.load(d_logprobs_ptr)
|
| 1069 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 1070 |
+
else:
|
| 1071 |
+
d_logprobs = tl.fdiv(tl.load(d_logprobs_ptr), num_tokens.to(tl.float32))
|
| 1072 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 1073 |
+
d_logprobs = -1 * d_logprobs
|
| 1074 |
+
|
| 1075 |
+
entropy_b = tl.load(entropy_b_ptr + offs_m * stride_entropy_b, mask=offs_m < num_tokens, other=0.0)
|
| 1076 |
+
labels = tl.load(labels_ptr + offs_m * stride_labels, mask=offs_m < num_tokens, other=0)
|
| 1077 |
+
|
| 1078 |
+
hidden_ptrs = hidden_ptr + (offs_m[:, None] * stride_hidden_m + offs_k[None, :] * stride_hidden_k)
|
| 1079 |
+
weight_ptrs = weight_ptr + (offs_n[:, None] * stride_weight_n + offs_k[None, :] * stride_weight_k)
|
| 1080 |
+
|
| 1081 |
+
logits = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 1082 |
+
for k in range(0, tl.cdiv(hidden_size, BLOCK_SIZE_K)):
|
| 1083 |
+
_hidden = tl.load(
|
| 1084 |
+
hidden_ptrs,
|
| 1085 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_m[:, None] < num_tokens),
|
| 1086 |
+
other=0.0,
|
| 1087 |
+
)
|
| 1088 |
+
_weight = tl.load(
|
| 1089 |
+
weight_ptrs,
|
| 1090 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_n[:, None] < vocab_size),
|
| 1091 |
+
other=0.0,
|
| 1092 |
+
)
|
| 1093 |
+
|
| 1094 |
+
logits = tl.dot(_hidden, _weight.trans(), logits)
|
| 1095 |
+
|
| 1096 |
+
hidden_ptrs += BLOCK_SIZE_K * stride_hidden_k
|
| 1097 |
+
weight_ptrs += BLOCK_SIZE_K * stride_weight_k
|
| 1098 |
+
|
| 1099 |
+
logits *= rcp_temperature
|
| 1100 |
+
|
| 1101 |
+
exp_logits = tl.exp(logits - maximum[:, None])
|
| 1102 |
+
|
| 1103 |
+
mask = (offs_n + rank * vocab_size)[None, :] == labels[:, None]
|
| 1104 |
+
d_logits = d_logprobs[:, None] * (exp_logits * accu_rcp[:, None] - mask)
|
| 1105 |
+
d_logits += d_entropy[:, None] * (-exp_logits * accu_rcp[:, None]) * (logits - entropy_b[:, None])
|
| 1106 |
+
|
| 1107 |
+
d_logits *= rcp_temperature
|
| 1108 |
+
|
| 1109 |
+
hidden_ptrs = hidden_ptr + (offs_m[:, None] * stride_hidden_m + result_offs_k[None, :] * stride_hidden_k)
|
| 1110 |
+
_hidden = tl.load(
|
| 1111 |
+
hidden_ptrs, mask=(result_offs_k[None, :] < hidden_size) & (offs_m[:, None] < num_tokens), other=0.0
|
| 1112 |
+
)
|
| 1113 |
+
d_weight = tl.dot(d_logits.to(d_weight_ptr.dtype.element_ty).trans(), _hidden, d_weight)
|
| 1114 |
+
|
| 1115 |
+
# write back
|
| 1116 |
+
tl.store(
|
| 1117 |
+
d_weight_ptr + offs_n[:, None] * stride_d_weight_n + result_offs_k[None, :] * stride_d_weight_k,
|
| 1118 |
+
d_weight,
|
| 1119 |
+
mask=(offs_n[:, None] < vocab_size) & (result_offs_k[None, :] < hidden_size),
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
# NOTE: split tile from d_logits' perspective
|
| 1124 |
+
@triton.autotune(
|
| 1125 |
+
configs=[
|
| 1126 |
+
triton.Config(
|
| 1127 |
+
{"BLOCK_SIZE_M": 128, "BLOCK_SIZE_N": 256, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 16},
|
| 1128 |
+
num_stages=3,
|
| 1129 |
+
num_warps=8,
|
| 1130 |
+
),
|
| 1131 |
+
],
|
| 1132 |
+
key=["num_tokens", "hidden_size", "vocab_size"],
|
| 1133 |
+
)
|
| 1134 |
+
@triton.jit
|
| 1135 |
+
def efficient_entropy_backward_kernel_general_d_logits(
|
| 1136 |
+
num_tokens: int,
|
| 1137 |
+
hidden_size: int,
|
| 1138 |
+
vocab_size: int,
|
| 1139 |
+
rank: int,
|
| 1140 |
+
hidden_ptr,
|
| 1141 |
+
stride_hidden_m: tl.int64,
|
| 1142 |
+
stride_hidden_k: tl.int64,
|
| 1143 |
+
weight_ptr,
|
| 1144 |
+
stride_weight_n: tl.int64,
|
| 1145 |
+
stride_weight_k: tl.int64,
|
| 1146 |
+
labels_ptr,
|
| 1147 |
+
stride_labels: tl.int64,
|
| 1148 |
+
maximum_ptr,
|
| 1149 |
+
stride_maximum: tl.int64,
|
| 1150 |
+
accu_ptr,
|
| 1151 |
+
stride_accu: tl.int64,
|
| 1152 |
+
d_entropy_ptr,
|
| 1153 |
+
stride_d_entropy: tl.int64,
|
| 1154 |
+
d_logprobs_ptr,
|
| 1155 |
+
stride_d_logprobs: tl.int64,
|
| 1156 |
+
reduction: int,
|
| 1157 |
+
entropy_b_ptr,
|
| 1158 |
+
stride_entropy_b,
|
| 1159 |
+
d_logits_ptr,
|
| 1160 |
+
stride_d_logits_m: tl.int64,
|
| 1161 |
+
stride_d_logits_n: tl.int64,
|
| 1162 |
+
rcp_temperature: tl.float32,
|
| 1163 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 1164 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 1165 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 1166 |
+
GROUP_SIZE_M: tl.constexpr,
|
| 1167 |
+
):
|
| 1168 |
+
"""
|
| 1169 |
+
backward d_logits
|
| 1170 |
+
"""
|
| 1171 |
+
# block swizzling
|
| 1172 |
+
# pid = tl.program_id(axis=0)
|
| 1173 |
+
# num_pid_m = tl.cdiv(num_tokens, BLOCK_SIZE_M)
|
| 1174 |
+
# pid_m = pid % num_pid_m
|
| 1175 |
+
# pid_n = pid // num_pid_m
|
| 1176 |
+
|
| 1177 |
+
pid = tl.program_id(axis=0)
|
| 1178 |
+
num_pid_m = tl.cdiv(num_tokens, BLOCK_SIZE_M)
|
| 1179 |
+
num_pid_n = tl.cdiv(vocab_size, BLOCK_SIZE_N)
|
| 1180 |
+
num_pid_in_group = GROUP_SIZE_M * num_pid_n
|
| 1181 |
+
group_id = pid // num_pid_in_group
|
| 1182 |
+
first_pid_m = group_id * GROUP_SIZE_M
|
| 1183 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
| 1184 |
+
pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
|
| 1185 |
+
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 1186 |
+
|
| 1187 |
+
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 1188 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 1189 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 1190 |
+
|
| 1191 |
+
maximum_ptrs = maximum_ptr + offs_am * stride_maximum
|
| 1192 |
+
maximum = tl.load(maximum_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 1193 |
+
accu_ptrs = accu_ptr + offs_am * stride_accu
|
| 1194 |
+
accu = tl.load(accu_ptrs, mask=offs_am < num_tokens, other=1e-6) # epsilon to avoid division by zero
|
| 1195 |
+
accu_rcp = tl.fdiv(1.0, accu)
|
| 1196 |
+
|
| 1197 |
+
d_entropy_ptrs = d_entropy_ptr + offs_am * stride_d_entropy
|
| 1198 |
+
d_entropy = tl.load(d_entropy_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 1199 |
+
if reduction == 0: # none
|
| 1200 |
+
d_logprobs_ptrs = d_logprobs_ptr + offs_am * stride_d_logprobs
|
| 1201 |
+
d_logprobs = tl.load(d_logprobs_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 1202 |
+
elif reduction == 1: # sum
|
| 1203 |
+
d_logprobs = tl.load(d_logprobs_ptr)
|
| 1204 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 1205 |
+
else: # mean
|
| 1206 |
+
d_logprobs = tl.fdiv(tl.load(d_logprobs_ptr), num_tokens.to(tl.float32))
|
| 1207 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 1208 |
+
d_logprobs = -1 * d_logprobs
|
| 1209 |
+
|
| 1210 |
+
entropy_b_ptrs = entropy_b_ptr + offs_am * stride_entropy_b
|
| 1211 |
+
entropy_b = tl.load(entropy_b_ptrs, mask=offs_am < num_tokens, other=0.0)
|
| 1212 |
+
|
| 1213 |
+
hidden_ptrs = hidden_ptr + (offs_am[:, None] * stride_hidden_m + offs_k[None, :] * stride_hidden_k)
|
| 1214 |
+
# weight_ptrs = weight_ptr + (offs_k[:, None] * stride_weight_k + offs_bn[None, :] * stride_weight_n)
|
| 1215 |
+
weight_ptrs = weight_ptr + (offs_bn[:, None] * stride_weight_n + offs_k[None, :] * stride_weight_k)
|
| 1216 |
+
labels_ptrs = labels_ptr + offs_am * stride_labels
|
| 1217 |
+
labels = tl.load(labels_ptrs, mask=offs_am < num_tokens, other=0)
|
| 1218 |
+
|
| 1219 |
+
logits = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 1220 |
+
for k in range(0, tl.cdiv(hidden_size, BLOCK_SIZE_K)):
|
| 1221 |
+
_hidden = tl.load(
|
| 1222 |
+
hidden_ptrs,
|
| 1223 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_am[:, None] < num_tokens),
|
| 1224 |
+
other=0.0,
|
| 1225 |
+
)
|
| 1226 |
+
# _weight = tl.load(weight_ptrs,
|
| 1227 |
+
# mask=(offs_k[:, None] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[None, :] < vocab_size),
|
| 1228 |
+
# other=0.0)
|
| 1229 |
+
_weight = tl.load(
|
| 1230 |
+
weight_ptrs,
|
| 1231 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[:, None] < vocab_size),
|
| 1232 |
+
other=0.0,
|
| 1233 |
+
)
|
| 1234 |
+
|
| 1235 |
+
logits = tl.dot(_hidden, _weight.trans(), logits)
|
| 1236 |
+
|
| 1237 |
+
hidden_ptrs += BLOCK_SIZE_K * stride_hidden_k
|
| 1238 |
+
weight_ptrs += BLOCK_SIZE_K * stride_weight_k
|
| 1239 |
+
hidden_ptrs -= hidden_size * stride_hidden_k
|
| 1240 |
+
weight_ptrs -= hidden_size * stride_weight_k
|
| 1241 |
+
|
| 1242 |
+
# scale logits by temperature
|
| 1243 |
+
logits *= rcp_temperature
|
| 1244 |
+
|
| 1245 |
+
exp_logits = tl.exp(logits - maximum[:, None])
|
| 1246 |
+
|
| 1247 |
+
mask = (offs_bn + rank * vocab_size)[None, :] == labels[:, None]
|
| 1248 |
+
d_logits = d_logprobs[:, None] * (exp_logits * accu_rcp[:, None] - mask)
|
| 1249 |
+
d_logits += d_entropy[:, None] * (-exp_logits * accu_rcp[:, None]) * (logits - entropy_b[:, None])
|
| 1250 |
+
|
| 1251 |
+
# scale d_logits by temperature
|
| 1252 |
+
d_logits *= rcp_temperature
|
| 1253 |
+
|
| 1254 |
+
# store d_logits
|
| 1255 |
+
d_logits_ptrs = d_logits_ptr + offs_am[:, None] * stride_d_logits_m + offs_bn[None, :] * stride_d_logits_n
|
| 1256 |
+
tl.store(
|
| 1257 |
+
d_logits_ptrs,
|
| 1258 |
+
d_logits, # will be implicitly converted to d_logits_ptrs.dtype.element_ty
|
| 1259 |
+
mask=(offs_am[:, None] < num_tokens) & (offs_bn[None, :] < vocab_size),
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
@triton.autotune(
|
| 1264 |
+
configs=[
|
| 1265 |
+
triton.Config(
|
| 1266 |
+
{"BLOCK_SIZE_M": 128, "BLOCK_SIZE_N": 256, "BLOCK_SIZE_K": 32, "GROUP_SIZE_M": 16},
|
| 1267 |
+
num_stages=3,
|
| 1268 |
+
num_warps=8,
|
| 1269 |
+
),
|
| 1270 |
+
],
|
| 1271 |
+
key=["num_tokens", "hidden_size", "vocab_size"],
|
| 1272 |
+
)
|
| 1273 |
+
@triton.jit
|
| 1274 |
+
def efficient_entropy_backward_kernel_general_d_logits_split_N(
|
| 1275 |
+
split_idx: int,
|
| 1276 |
+
num_tokens: int,
|
| 1277 |
+
hidden_size: int,
|
| 1278 |
+
vocab_size: int,
|
| 1279 |
+
vocab_per_split: int,
|
| 1280 |
+
rank: int,
|
| 1281 |
+
hidden_ptr,
|
| 1282 |
+
stride_hidden_m: tl.int64,
|
| 1283 |
+
stride_hidden_k: tl.int64,
|
| 1284 |
+
weight_ptr,
|
| 1285 |
+
stride_weight_n: tl.int64,
|
| 1286 |
+
stride_weight_k: tl.int64,
|
| 1287 |
+
labels_ptr,
|
| 1288 |
+
stride_labels: tl.int64,
|
| 1289 |
+
maximum_ptr,
|
| 1290 |
+
stride_maximum: tl.int64,
|
| 1291 |
+
accu_ptr,
|
| 1292 |
+
stride_accu: tl.int64,
|
| 1293 |
+
d_entropy_ptr,
|
| 1294 |
+
stride_d_entropy: tl.int64,
|
| 1295 |
+
d_logprobs_ptr,
|
| 1296 |
+
stride_d_logprobs: tl.int64,
|
| 1297 |
+
reduction: int,
|
| 1298 |
+
entropy_b_ptr,
|
| 1299 |
+
stride_entropy_b,
|
| 1300 |
+
d_logits_ptr,
|
| 1301 |
+
stride_d_logits_m: tl.int64,
|
| 1302 |
+
stride_d_logits_n: tl.int64,
|
| 1303 |
+
rcp_temperature: tl.float32,
|
| 1304 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 1305 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 1306 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 1307 |
+
GROUP_SIZE_M: tl.constexpr,
|
| 1308 |
+
):
|
| 1309 |
+
pid = tl.program_id(axis=0)
|
| 1310 |
+
num_pid_m = tl.cdiv(num_tokens, BLOCK_SIZE_M)
|
| 1311 |
+
num_pid_n = tl.cdiv(vocab_per_split, BLOCK_SIZE_N)
|
| 1312 |
+
num_pid_in_group = GROUP_SIZE_M * num_pid_n
|
| 1313 |
+
group_id = pid // num_pid_in_group
|
| 1314 |
+
first_pid_m = group_id * GROUP_SIZE_M
|
| 1315 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
| 1316 |
+
pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
|
| 1317 |
+
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 1318 |
+
|
| 1319 |
+
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 1320 |
+
offs_bn = split_idx * vocab_per_split + pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 1321 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 1322 |
+
|
| 1323 |
+
maximum = tl.load(maximum_ptr + offs_am * stride_maximum, mask=offs_am < num_tokens, other=0.0)
|
| 1324 |
+
accu = tl.load(accu_ptr + offs_am * stride_accu, mask=offs_am < num_tokens, other=1e-6)
|
| 1325 |
+
accu_rcp = tl.fdiv(1.0, accu)
|
| 1326 |
+
d_entropy = tl.load(d_entropy_ptr + offs_am * stride_d_entropy, mask=offs_am < num_tokens, other=0.0)
|
| 1327 |
+
if reduction == 0:
|
| 1328 |
+
d_logprobs = tl.load(d_logprobs_ptr + offs_am * stride_d_logprobs, mask=offs_am < num_tokens, other=0.0)
|
| 1329 |
+
elif reduction == 1:
|
| 1330 |
+
d_logprobs = tl.load(d_logprobs_ptr)
|
| 1331 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 1332 |
+
else:
|
| 1333 |
+
d_logprobs = tl.fdiv(tl.load(d_logprobs_ptr), num_tokens.to(tl.float32))
|
| 1334 |
+
d_logprobs = tl.broadcast_to(d_logprobs, (BLOCK_SIZE_M,))
|
| 1335 |
+
d_logprobs = -1 * d_logprobs
|
| 1336 |
+
entropy_b = tl.load(entropy_b_ptr + offs_am * stride_entropy_b, mask=offs_am < num_tokens, other=0.0)
|
| 1337 |
+
labels = tl.load(labels_ptr + offs_am * stride_labels, mask=offs_am < num_tokens, other=0)
|
| 1338 |
+
|
| 1339 |
+
hidden_ptrs = hidden_ptr + (offs_am[:, None] * stride_hidden_m + offs_k[None, :] * stride_hidden_k)
|
| 1340 |
+
weight_ptrs = weight_ptr + (offs_bn[:, None] * stride_weight_n + offs_k[None, :] * stride_weight_k)
|
| 1341 |
+
|
| 1342 |
+
vocab_right_bound = min((split_idx + 1) * vocab_per_split, vocab_size)
|
| 1343 |
+
logits = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 1344 |
+
for k in range(0, tl.cdiv(hidden_size, BLOCK_SIZE_K)):
|
| 1345 |
+
_hidden = tl.load(
|
| 1346 |
+
hidden_ptrs,
|
| 1347 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_am[:, None] < num_tokens),
|
| 1348 |
+
other=0.0,
|
| 1349 |
+
)
|
| 1350 |
+
_weight = tl.load(
|
| 1351 |
+
weight_ptrs,
|
| 1352 |
+
mask=(offs_k[None, :] < hidden_size - k * BLOCK_SIZE_K) & (offs_bn[:, None] < vocab_right_bound),
|
| 1353 |
+
other=0.0,
|
| 1354 |
+
)
|
| 1355 |
+
logits = tl.dot(_hidden, _weight.trans(), logits)
|
| 1356 |
+
|
| 1357 |
+
hidden_ptrs += BLOCK_SIZE_K * stride_hidden_k
|
| 1358 |
+
weight_ptrs += BLOCK_SIZE_K * stride_weight_k
|
| 1359 |
+
|
| 1360 |
+
logits *= rcp_temperature
|
| 1361 |
+
exp_logits = tl.exp(logits - maximum[:, None])
|
| 1362 |
+
|
| 1363 |
+
mask = (offs_bn + rank * vocab_size)[None, :] == labels[:, None]
|
| 1364 |
+
d_logits = d_logprobs[:, None] * (exp_logits * accu_rcp[:, None] - mask)
|
| 1365 |
+
d_logits += d_entropy[:, None] * (-exp_logits * accu_rcp[:, None]) * (logits - entropy_b[:, None])
|
| 1366 |
+
|
| 1367 |
+
d_logits *= rcp_temperature
|
| 1368 |
+
|
| 1369 |
+
# filter d_logits with mask
|
| 1370 |
+
result_offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 1371 |
+
mask = (offs_am[:, None] < num_tokens) & (result_offs_n[None, :] < vocab_per_split)
|
| 1372 |
+
|
| 1373 |
+
tl.store(
|
| 1374 |
+
d_logits_ptr + offs_am[:, None] * stride_d_logits_m + result_offs_n[None, :] * stride_d_logits_n, d_logits, mask
|
| 1375 |
+
)
|
| 1376 |
+
|
| 1377 |
+
|
| 1378 |
+
def efficient_entropy_backward(
|
| 1379 |
+
dlogprobs: torch.Tensor,
|
| 1380 |
+
dentropy: torch.Tensor,
|
| 1381 |
+
hidden: torch.Tensor,
|
| 1382 |
+
weight: torch.Tensor,
|
| 1383 |
+
labels: torch.Tensor,
|
| 1384 |
+
maximum: torch.Tensor,
|
| 1385 |
+
acc: torch.Tensor,
|
| 1386 |
+
entropy_b: torch.Tensor,
|
| 1387 |
+
reduction: typing.Optional[int] = 2,
|
| 1388 |
+
should_return_fp32_grad: bool = False,
|
| 1389 |
+
temperature: typing.Optional[float] = 1.0,
|
| 1390 |
+
dist_process_group: typing.Optional[dist.ProcessGroup] = None,
|
| 1391 |
+
) -> list[torch.Tensor]:
|
| 1392 |
+
"""
|
| 1393 |
+
backward host function
|
| 1394 |
+
"""
|
| 1395 |
+
assert hidden.is_cuda and weight.is_cuda and labels.is_cuda
|
| 1396 |
+
assert weight.device == hidden.device and labels.device == hidden.device
|
| 1397 |
+
assert hidden.dim() == 2 and weight.dim() == 2 and labels.dim() == 1
|
| 1398 |
+
assert hidden.is_contiguous() and weight.is_contiguous() and labels.is_contiguous()
|
| 1399 |
+
assert hidden.shape[0] == labels.shape[0] and hidden.shape[1] == weight.shape[1]
|
| 1400 |
+
|
| 1401 |
+
_rank = 0 if dist_process_group is None else dist.get_rank(dist_process_group)
|
| 1402 |
+
_world_size = 1 if dist_process_group is None else dist.get_world_size(dist_process_group)
|
| 1403 |
+
|
| 1404 |
+
num_tokens, hidden_size = hidden.shape
|
| 1405 |
+
num_tokens = labels.shape[0]
|
| 1406 |
+
vocab_size, hidden_size = weight.shape
|
| 1407 |
+
assert hidden_size % 128 == 0
|
| 1408 |
+
|
| 1409 |
+
REDUCTION = get_entropy_reduction_enum(reduction)
|
| 1410 |
+
|
| 1411 |
+
if REDUCTION == EntropyReductionEnum._None:
|
| 1412 |
+
assert dlogprobs.shape == (num_tokens,)
|
| 1413 |
+
else:
|
| 1414 |
+
assert dlogprobs.dim() == 0
|
| 1415 |
+
|
| 1416 |
+
assert dlogprobs.is_contiguous() and dentropy.is_contiguous()
|
| 1417 |
+
assert dlogprobs.is_cuda and dentropy.is_cuda
|
| 1418 |
+
assert dlogprobs.device == hidden.device and dlogprobs.device == dentropy.device
|
| 1419 |
+
assert dentropy.shape == (num_tokens,)
|
| 1420 |
+
|
| 1421 |
+
d_hidden, d_weight = None, None
|
| 1422 |
+
if _config._backward == BackwardEnum._Total_Fuse_MN or should_return_fp32_grad:
|
| 1423 |
+
d_hidden = torch.zeros_like(hidden, dtype=torch.float32, device=hidden.device)
|
| 1424 |
+
d_weight = torch.zeros_like(weight, dtype=torch.float32, device=weight.device)
|
| 1425 |
+
else:
|
| 1426 |
+
d_hidden = torch.empty_like(hidden, dtype=hidden.dtype, device=hidden.device)
|
| 1427 |
+
d_weight = torch.empty_like(weight, dtype=hidden.dtype, device=weight.device)
|
| 1428 |
+
assert d_hidden.is_contiguous() and d_weight.is_contiguous()
|
| 1429 |
+
|
| 1430 |
+
assert maximum.is_contiguous() and acc.is_contiguous()
|
| 1431 |
+
assert maximum.device == hidden.device and acc.device == hidden.device
|
| 1432 |
+
assert maximum.shape == labels.shape == acc.shape
|
| 1433 |
+
assert maximum.is_cuda and acc.is_cuda
|
| 1434 |
+
|
| 1435 |
+
vocab_per_split = 1024
|
| 1436 |
+
assert vocab_per_split % 128 == 0
|
| 1437 |
+
num_splits = (vocab_size + vocab_per_split - 1) // vocab_per_split
|
| 1438 |
+
|
| 1439 |
+
assert entropy_b.is_contiguous() and entropy_b.is_cuda
|
| 1440 |
+
assert entropy_b.shape == (num_tokens,)
|
| 1441 |
+
|
| 1442 |
+
if _config._backward == BackwardEnum._Total_Fuse_MN:
|
| 1443 |
+
# --- Triton doesn't materialize d_logits at all. Split tiles at the perspective of d_logits.
|
| 1444 |
+
def mainloop_grid(meta):
|
| 1445 |
+
return (triton.cdiv(num_tokens, meta["BLOCK_SIZE_M"]) * triton.cdiv(vocab_size, meta["BLOCK_SIZE_N"]),)
|
| 1446 |
+
|
| 1447 |
+
efficient_entropy_backward_kernel_general_mainloop_MN[mainloop_grid](
|
| 1448 |
+
num_tokens,
|
| 1449 |
+
hidden_size,
|
| 1450 |
+
vocab_size,
|
| 1451 |
+
_rank,
|
| 1452 |
+
hidden,
|
| 1453 |
+
hidden.stride(0),
|
| 1454 |
+
hidden.stride(1),
|
| 1455 |
+
weight,
|
| 1456 |
+
weight.stride(0),
|
| 1457 |
+
weight.stride(1),
|
| 1458 |
+
labels,
|
| 1459 |
+
labels.stride(0),
|
| 1460 |
+
maximum,
|
| 1461 |
+
maximum.stride(0),
|
| 1462 |
+
acc,
|
| 1463 |
+
acc.stride(0),
|
| 1464 |
+
dentropy,
|
| 1465 |
+
dentropy.stride(0),
|
| 1466 |
+
dlogprobs,
|
| 1467 |
+
dlogprobs.stride(0) if REDUCTION == EntropyReductionEnum._None else 0,
|
| 1468 |
+
REDUCTION,
|
| 1469 |
+
entropy_b,
|
| 1470 |
+
entropy_b.stride(0),
|
| 1471 |
+
d_hidden,
|
| 1472 |
+
d_hidden.stride(0),
|
| 1473 |
+
d_hidden.stride(1),
|
| 1474 |
+
d_weight,
|
| 1475 |
+
d_weight.stride(0),
|
| 1476 |
+
d_weight.stride(1),
|
| 1477 |
+
1.0 / temperature,
|
| 1478 |
+
)
|
| 1479 |
+
|
| 1480 |
+
elif _config._backward == BackwardEnum._Total_Separate:
|
| 1481 |
+
_d_logits = torch.empty((num_tokens, vocab_size), device=hidden.device, dtype=hidden.dtype).contiguous()
|
| 1482 |
+
assert _d_logits.is_contiguous()
|
| 1483 |
+
|
| 1484 |
+
if _config._use_triton:
|
| 1485 |
+
|
| 1486 |
+
def d_logits_grid(meta):
|
| 1487 |
+
return (triton.cdiv(num_tokens, meta["BLOCK_SIZE_M"]) * triton.cdiv(vocab_size, meta["BLOCK_SIZE_N"]),)
|
| 1488 |
+
|
| 1489 |
+
efficient_entropy_backward_kernel_general_d_logits[d_logits_grid](
|
| 1490 |
+
num_tokens,
|
| 1491 |
+
hidden_size,
|
| 1492 |
+
vocab_size,
|
| 1493 |
+
_rank,
|
| 1494 |
+
hidden,
|
| 1495 |
+
hidden.stride(0),
|
| 1496 |
+
hidden.stride(1),
|
| 1497 |
+
weight,
|
| 1498 |
+
weight.stride(0),
|
| 1499 |
+
weight.stride(1),
|
| 1500 |
+
labels,
|
| 1501 |
+
labels.stride(0),
|
| 1502 |
+
maximum,
|
| 1503 |
+
maximum.stride(0),
|
| 1504 |
+
acc,
|
| 1505 |
+
acc.stride(0),
|
| 1506 |
+
dentropy,
|
| 1507 |
+
dentropy.stride(0),
|
| 1508 |
+
dlogprobs,
|
| 1509 |
+
dlogprobs.stride(0) if REDUCTION == EntropyReductionEnum._None else 0,
|
| 1510 |
+
REDUCTION,
|
| 1511 |
+
entropy_b,
|
| 1512 |
+
entropy_b.stride(0),
|
| 1513 |
+
_d_logits,
|
| 1514 |
+
_d_logits.stride(0),
|
| 1515 |
+
_d_logits.stride(1),
|
| 1516 |
+
1.0 / temperature,
|
| 1517 |
+
)
|
| 1518 |
+
|
| 1519 |
+
torch.matmul(_d_logits, weight, out=d_hidden)
|
| 1520 |
+
torch.matmul(_d_logits.T, hidden, out=d_weight)
|
| 1521 |
+
else:
|
| 1522 |
+
raise AssertionError("Triton is required for efficient entropy kernel")
|
| 1523 |
+
|
| 1524 |
+
elif _config._backward == BackwardEnum._Split_Dlogits_N:
|
| 1525 |
+
vocab_per_split = 9504
|
| 1526 |
+
num_splits = (vocab_size + vocab_per_split - 1) // vocab_per_split
|
| 1527 |
+
|
| 1528 |
+
_d_logits = torch.empty((num_tokens, vocab_per_split), device=hidden.device, dtype=hidden.dtype).contiguous()
|
| 1529 |
+
assert _d_logits.is_contiguous()
|
| 1530 |
+
|
| 1531 |
+
def d_logits_grid(meta):
|
| 1532 |
+
return (triton.cdiv(num_tokens, meta["BLOCK_SIZE_M"]) * triton.cdiv(vocab_per_split, meta["BLOCK_SIZE_N"]),)
|
| 1533 |
+
|
| 1534 |
+
for split_idx in range(num_splits):
|
| 1535 |
+
efficient_entropy_backward_kernel_general_d_logits_split_N[d_logits_grid](
|
| 1536 |
+
split_idx,
|
| 1537 |
+
num_tokens,
|
| 1538 |
+
hidden_size,
|
| 1539 |
+
vocab_size,
|
| 1540 |
+
vocab_per_split,
|
| 1541 |
+
_rank,
|
| 1542 |
+
hidden,
|
| 1543 |
+
hidden.stride(0),
|
| 1544 |
+
hidden.stride(1),
|
| 1545 |
+
weight,
|
| 1546 |
+
weight.stride(0),
|
| 1547 |
+
weight.stride(1),
|
| 1548 |
+
labels,
|
| 1549 |
+
labels.stride(0),
|
| 1550 |
+
maximum,
|
| 1551 |
+
maximum.stride(0),
|
| 1552 |
+
acc,
|
| 1553 |
+
acc.stride(0),
|
| 1554 |
+
dentropy,
|
| 1555 |
+
dentropy.stride(0),
|
| 1556 |
+
dlogprobs,
|
| 1557 |
+
dlogprobs.stride(0) if REDUCTION == EntropyReductionEnum._None else 0,
|
| 1558 |
+
REDUCTION,
|
| 1559 |
+
entropy_b,
|
| 1560 |
+
entropy_b.stride(0),
|
| 1561 |
+
_d_logits,
|
| 1562 |
+
_d_logits.stride(0),
|
| 1563 |
+
_d_logits.stride(1),
|
| 1564 |
+
1.0 / temperature,
|
| 1565 |
+
)
|
| 1566 |
+
|
| 1567 |
+
if split_idx == (num_splits - 1):
|
| 1568 |
+
vocab_right_bound = min((split_idx + 1) * vocab_per_split, vocab_size) - split_idx * vocab_per_split
|
| 1569 |
+
_d_logits = _d_logits[:, :vocab_right_bound].contiguous()
|
| 1570 |
+
|
| 1571 |
+
if split_idx == 0:
|
| 1572 |
+
torch.matmul(
|
| 1573 |
+
_d_logits, weight[split_idx * vocab_per_split : (split_idx + 1) * vocab_per_split, :], out=d_hidden
|
| 1574 |
+
)
|
| 1575 |
+
else:
|
| 1576 |
+
d_hidden += torch.matmul(
|
| 1577 |
+
_d_logits, weight[split_idx * vocab_per_split : (split_idx + 1) * vocab_per_split, :]
|
| 1578 |
+
)
|
| 1579 |
+
torch.matmul(
|
| 1580 |
+
_d_logits.T, hidden, out=d_weight[split_idx * vocab_per_split : (split_idx + 1) * vocab_per_split, :]
|
| 1581 |
+
)
|
| 1582 |
+
|
| 1583 |
+
elif _config._backward == BackwardEnum._Split_Dlogits_M:
|
| 1584 |
+
raise NotImplementedError("BackwardEnum._Split_Dlogits_M is not implemented yet")
|
| 1585 |
+
|
| 1586 |
+
return d_hidden, d_weight
|
verl/verl/utils/kernel/linear_cross_entropy.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 3 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
#
|
| 17 |
+
|
| 18 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 19 |
+
#
|
| 20 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 21 |
+
# you may not use this file except in compliance with the License.
|
| 22 |
+
# You may obtain a copy of the License at
|
| 23 |
+
#
|
| 24 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 25 |
+
#
|
| 26 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 27 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 28 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 29 |
+
# See the License for the specific language governing permissions and
|
| 30 |
+
# limitations under the License.
|
| 31 |
+
|
| 32 |
+
import typing
|
| 33 |
+
|
| 34 |
+
import torch
|
| 35 |
+
import torch.distributed as dist
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class LinearCrossEntropy(torch.autograd.Function):
|
| 39 |
+
@staticmethod
|
| 40 |
+
def forward(
|
| 41 |
+
ctx,
|
| 42 |
+
hidden: torch.Tensor,
|
| 43 |
+
weight: torch.Tensor,
|
| 44 |
+
labels: torch.Tensor,
|
| 45 |
+
temperature: typing.Optional[float] = 1.0,
|
| 46 |
+
reduction: typing.Optional[str] = "none",
|
| 47 |
+
dist_process_group: typing.Optional[dist.ProcessGroup] = None,
|
| 48 |
+
) -> list[torch.Tensor]:
|
| 49 |
+
"""_summary_
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
ctx (_type_): _description_
|
| 53 |
+
hidden (torch.Tensor): (batch_size, num_tokens, hidden_size) -> (batch_size * num_tokens, hidden_size)
|
| 54 |
+
weight (torch.Tensor): (vocab_size, hidden_size)
|
| 55 |
+
labels (torch.Tensor): (batch_size, num_tokens) -> (batch_size * num_tokens, )
|
| 56 |
+
temperature (typing.Optional[float], optional): _description_. Defaults to 1.0.
|
| 57 |
+
reduction (typing.Optional[str], optional): _description_. Defaults to "none".
|
| 58 |
+
dist_process_group (typing.Optional[dist.ProcessGroup], optional): _description_. Defaults to None.
|
| 59 |
+
|
| 60 |
+
Returns:
|
| 61 |
+
typing.List[torch.Tensor]: _description_
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
assert isinstance(temperature, float), f"temperature must be a float, but got {type(temperature)}"
|
| 65 |
+
assert isinstance(reduction, str), f"reduction must be a str, but got {type(reduction)}"
|
| 66 |
+
with torch.cuda.nvtx.range("LinearCrossEntropy-forward"):
|
| 67 |
+
from . import kernels
|
| 68 |
+
|
| 69 |
+
REDUCTION = kernels.get_entropy_reduction_enum_number(reduction.lower())
|
| 70 |
+
|
| 71 |
+
original_hidden_shape = hidden.shape
|
| 72 |
+
if len(hidden.shape) != 2:
|
| 73 |
+
hidden = hidden.view(-1, hidden.shape[-1]) # (batch_size * num_tokens, hidden_size)
|
| 74 |
+
if len(labels.shape) != 1:
|
| 75 |
+
labels = labels.view(-1)
|
| 76 |
+
|
| 77 |
+
logprobs, entropy, _maximum, _accumulate, _entropy_b = kernels.efficient_entropy_forward(
|
| 78 |
+
hidden, weight, labels, REDUCTION, temperature, dist_process_group
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
ctx.save_for_backward(hidden, weight, labels, _maximum, _accumulate, _entropy_b)
|
| 82 |
+
ctx.original_hidden_shape = original_hidden_shape
|
| 83 |
+
ctx.REDUCTION = REDUCTION
|
| 84 |
+
ctx.dist_process_group = dist_process_group
|
| 85 |
+
ctx.should_return_fp32_grad = False
|
| 86 |
+
ctx.temperature = temperature
|
| 87 |
+
return logprobs, entropy
|
| 88 |
+
|
| 89 |
+
@staticmethod
|
| 90 |
+
def backward(ctx, dlogprobs: torch.Tensor, dentropy: torch.Tensor) -> list[torch.Tensor]:
|
| 91 |
+
from . import kernels
|
| 92 |
+
|
| 93 |
+
with torch.cuda.nvtx.range("LinearCrossEntropy-backward"):
|
| 94 |
+
(hidden, weight, labels, _maximum, _accumulate, _entropy_b) = ctx.saved_tensors
|
| 95 |
+
REDUCTION = ctx.REDUCTION
|
| 96 |
+
dist_process_group = ctx.dist_process_group
|
| 97 |
+
should_return_fp32_grad = ctx.should_return_fp32_grad
|
| 98 |
+
temperature = ctx.temperature
|
| 99 |
+
|
| 100 |
+
d_hidden, d_weight = kernels.efficient_entropy_backward(
|
| 101 |
+
dlogprobs,
|
| 102 |
+
dentropy,
|
| 103 |
+
hidden,
|
| 104 |
+
weight,
|
| 105 |
+
labels,
|
| 106 |
+
_maximum,
|
| 107 |
+
_accumulate,
|
| 108 |
+
_entropy_b,
|
| 109 |
+
REDUCTION,
|
| 110 |
+
should_return_fp32_grad,
|
| 111 |
+
temperature,
|
| 112 |
+
dist_process_group,
|
| 113 |
+
)
|
| 114 |
+
d_hidden = d_hidden.view(ctx.original_hidden_shape)
|
| 115 |
+
|
| 116 |
+
return (d_hidden, d_weight, None, None, None, None)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
linear_cross_entropy = LinearCrossEntropy.apply
|
verl/verl/utils/logger/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from .aggregate_logger import (
|
| 17 |
+
DecoratorLoggerBase,
|
| 18 |
+
LocalLogger,
|
| 19 |
+
log_with_rank,
|
| 20 |
+
print_rank_0,
|
| 21 |
+
print_with_rank,
|
| 22 |
+
print_with_rank_and_timer,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"LocalLogger",
|
| 27 |
+
"DecoratorLoggerBase",
|
| 28 |
+
"print_rank_0",
|
| 29 |
+
"print_with_rank",
|
| 30 |
+
"print_with_rank_and_timer",
|
| 31 |
+
"log_with_rank",
|
| 32 |
+
]
|
verl/verl/utils/logger/aggregate_logger.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
A Ray logger will receive logging info from different processes.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import datetime
|
| 19 |
+
import logging
|
| 20 |
+
import numbers
|
| 21 |
+
import pprint
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def concat_dict_to_str(dict: dict, step):
|
| 27 |
+
output = [f"step:{step}"]
|
| 28 |
+
for k, v in dict.items():
|
| 29 |
+
if isinstance(v, numbers.Number):
|
| 30 |
+
output.append(f"{k}:{pprint.pformat(v)}")
|
| 31 |
+
output_str = " - ".join(output)
|
| 32 |
+
return output_str
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class LocalLogger:
|
| 36 |
+
"""
|
| 37 |
+
A local logger that logs messages to the console.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
print_to_console (bool): Whether to print to the console.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, print_to_console=True):
|
| 44 |
+
self.print_to_console = print_to_console
|
| 45 |
+
|
| 46 |
+
def flush(self):
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
def log(self, data, step):
|
| 50 |
+
if self.print_to_console:
|
| 51 |
+
print(concat_dict_to_str(data, step=step), flush=True)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class DecoratorLoggerBase:
|
| 55 |
+
"""
|
| 56 |
+
Base class for all decorators that log messages.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
role (str): The role (the name) of the logger.
|
| 60 |
+
logger (logging.Logger): The logger instance to use for logging.
|
| 61 |
+
level (int): The logging level.
|
| 62 |
+
rank (int): The rank of the process.
|
| 63 |
+
log_only_rank_0 (bool): If True, only log for rank 0.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self, role: str, logger: logging.Logger = None, level=logging.DEBUG, rank: int = 0, log_only_rank_0: bool = True
|
| 68 |
+
):
|
| 69 |
+
self.role = role
|
| 70 |
+
self.logger = logger
|
| 71 |
+
self.level = level
|
| 72 |
+
self.rank = rank
|
| 73 |
+
self.log_only_rank_0 = log_only_rank_0
|
| 74 |
+
self.logging_function = self.log_by_logging
|
| 75 |
+
if logger is None:
|
| 76 |
+
self.logging_function = self.log_by_print
|
| 77 |
+
|
| 78 |
+
def log_by_print(self, log_str):
|
| 79 |
+
if not self.log_only_rank_0 or self.rank == 0:
|
| 80 |
+
print(f"{self.role} {log_str}", flush=True)
|
| 81 |
+
|
| 82 |
+
def log_by_logging(self, log_str):
|
| 83 |
+
if self.logger is None:
|
| 84 |
+
raise ValueError("Logger is not initialized")
|
| 85 |
+
if not self.log_only_rank_0 or self.rank == 0:
|
| 86 |
+
self.logger.log(self.level, f"{self.role} {log_str}")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def print_rank_0(message):
|
| 90 |
+
"""If distributed is initialized, print only on rank 0."""
|
| 91 |
+
if torch.distributed.is_initialized():
|
| 92 |
+
if torch.distributed.get_rank() == 0:
|
| 93 |
+
print(message, flush=True)
|
| 94 |
+
else:
|
| 95 |
+
print(message, flush=True)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def print_with_rank(message: str, rank: int = 0, log_only_rank_0: bool = False):
|
| 99 |
+
"""_summary_
|
| 100 |
+
Print a message with rank information.
|
| 101 |
+
This function prints the message only if `log_only_rank_0` is False or if the rank is 0.
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
message (str): _description_
|
| 105 |
+
rank (int, optional): _description_. Defaults to 0.
|
| 106 |
+
log_only_rank_0 (bool, optional): _description_. Defaults to False.
|
| 107 |
+
"""
|
| 108 |
+
if not log_only_rank_0 or rank == 0:
|
| 109 |
+
print(f"[Rank {rank}] {message}", flush=True)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def print_with_rank_and_timer(message: str, rank: int = 0, log_only_rank_0: bool = False):
|
| 113 |
+
"""_summary_
|
| 114 |
+
Print a message with rank information and a timestamp.
|
| 115 |
+
This function prints the message only if `log_only_rank_0` is False or if the rank is 0.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
message (str): _description_
|
| 119 |
+
rank (int, optional): _description_. Defaults to 0.
|
| 120 |
+
log_only_rank_0 (bool, optional): _description_. Defaults to False.
|
| 121 |
+
"""
|
| 122 |
+
now = datetime.datetime.now()
|
| 123 |
+
message = f"[{now.strftime('%Y-%m-%d %H:%M:%S')}] [Rank {rank}] {message}"
|
| 124 |
+
if not log_only_rank_0 or rank == 0:
|
| 125 |
+
print(message, flush=True)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def log_with_rank(message: str, rank, logger: logging.Logger, level=logging.INFO, log_only_rank_0: bool = False):
|
| 129 |
+
"""_summary_
|
| 130 |
+
Log a message with rank information using a logger.
|
| 131 |
+
This function logs the message only if `log_only_rank_0` is False or if the rank is 0.
|
| 132 |
+
Args:
|
| 133 |
+
message (str): The message to log.
|
| 134 |
+
rank (int): The rank of the process.
|
| 135 |
+
logger (logging.Logger): The logger instance to use for logging.
|
| 136 |
+
level (int, optional): The logging level. Defaults to logging.INFO.
|
| 137 |
+
log_only_rank_0 (bool, optional): If True, only log for rank 0. Defaults to False.
|
| 138 |
+
"""
|
| 139 |
+
if not log_only_rank_0 or rank == 0:
|
| 140 |
+
logger.log(level, f"[Rank {rank}] {message}")
|
verl/verl/utils/megatron/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
verl/verl/utils/megatron/dist_checkpointing.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from megatron.core import dist_checkpointing, mpu
|
| 16 |
+
from megatron.core.dist_checkpointing.serialization import (
|
| 17 |
+
get_default_load_sharded_strategy,
|
| 18 |
+
get_default_save_sharded_strategy,
|
| 19 |
+
)
|
| 20 |
+
from megatron.core.dist_checkpointing.strategies.fully_parallel import (
|
| 21 |
+
FullyParallelLoadStrategyWrapper,
|
| 22 |
+
FullyParallelSaveStrategyWrapper,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def save_dist_checkpointing(sharded_state_dict, ckpt_path, async_save=False):
|
| 27 |
+
validate_sharding_integrity = True
|
| 28 |
+
# Get checkpointing strategies
|
| 29 |
+
save_strategy = get_default_save_sharded_strategy("torch_dist")
|
| 30 |
+
save_strategy = FullyParallelSaveStrategyWrapper(
|
| 31 |
+
save_strategy, mpu.get_data_parallel_group(with_context_parallel=True)
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Save model sharded state dicts
|
| 35 |
+
async_save_request = dist_checkpointing.save(
|
| 36 |
+
sharded_state_dict,
|
| 37 |
+
ckpt_path,
|
| 38 |
+
sharded_strategy=save_strategy,
|
| 39 |
+
async_sharded_save=async_save,
|
| 40 |
+
validate_access_integrity=validate_sharding_integrity,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
return async_save_request
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_dist_checkpointing(sharded_state_dict, ckpt_dir):
|
| 47 |
+
# Get checkpointing strategies
|
| 48 |
+
load_strategy = get_default_load_sharded_strategy(ckpt_dir)
|
| 49 |
+
load_strategy = FullyParallelLoadStrategyWrapper(
|
| 50 |
+
load_strategy, mpu.get_data_parallel_group(with_context_parallel=True)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Load model sharded state dicts
|
| 54 |
+
state_dict = dist_checkpointing.load(sharded_state_dict, ckpt_dir, sharded_strategy=load_strategy)
|
| 55 |
+
|
| 56 |
+
return state_dict
|
verl/verl/utils/megatron/memory.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
|
| 17 |
+
from verl.utils.device import get_device_id
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class MemoryBuffer:
|
| 21 |
+
def __init__(self, numel, numel_padded, dtype):
|
| 22 |
+
self.numel = numel
|
| 23 |
+
self.numel_padded = numel_padded
|
| 24 |
+
self.dtype = dtype
|
| 25 |
+
self.data = torch.zeros(self.numel_padded, dtype=self.dtype, device=get_device_id(), requires_grad=False)
|
| 26 |
+
|
| 27 |
+
def zero(self):
|
| 28 |
+
"""Reset the buffer to zero."""
|
| 29 |
+
self.data.zero_()
|
| 30 |
+
|
| 31 |
+
def get(self, shape, start_index):
|
| 32 |
+
"""Return a tensor with the input `shape` as a view into the
|
| 33 |
+
1-D data starting at `start_index`."""
|
| 34 |
+
end_index = start_index + shape.numel()
|
| 35 |
+
assert end_index <= self.numel, "requested tensor is out of the buffer range."
|
| 36 |
+
buffer_tensor = self.data[start_index:end_index]
|
| 37 |
+
buffer_tensor = buffer_tensor.view(shape)
|
| 38 |
+
return buffer_tensor
|
verl/verl/utils/megatron/optimizer.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from megatron.core.optimizer import OptimizerConfig
|
| 18 |
+
from megatron.core.optimizer import get_megatron_optimizer as get_megatron_optimizer_native
|
| 19 |
+
from megatron.core.optimizer_param_scheduler import OptimizerParamScheduler
|
| 20 |
+
|
| 21 |
+
from verl.utils.logger import print_rank_0
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def init_megatron_optim_config(optim_config: dict) -> OptimizerConfig:
|
| 25 |
+
optim_args = {
|
| 26 |
+
"optimizer": optim_config.optimizer,
|
| 27 |
+
"lr": optim_config.lr,
|
| 28 |
+
"min_lr": optim_config.min_lr,
|
| 29 |
+
"clip_grad": optim_config.clip_grad,
|
| 30 |
+
"weight_decay": optim_config.weight_decay,
|
| 31 |
+
"bf16": True,
|
| 32 |
+
"params_dtype": torch.bfloat16,
|
| 33 |
+
"use_distributed_optimizer": True,
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
override_config = optim_config.get("override_optimizer_config", {})
|
| 37 |
+
if override_config:
|
| 38 |
+
for k, v in override_config.items():
|
| 39 |
+
optim_args[k] = v
|
| 40 |
+
|
| 41 |
+
print_rank_0(f"optimizer config after override: {optim_args}")
|
| 42 |
+
|
| 43 |
+
config = OptimizerConfig(**optim_args)
|
| 44 |
+
return config
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_megatron_optimizer(
|
| 48 |
+
model,
|
| 49 |
+
config: OptimizerConfig,
|
| 50 |
+
no_weight_decay_cond=None,
|
| 51 |
+
scale_lr_cond=None,
|
| 52 |
+
lr_mult=1.0,
|
| 53 |
+
):
|
| 54 |
+
# Base optimizer.
|
| 55 |
+
return get_megatron_optimizer_native(
|
| 56 |
+
config=config,
|
| 57 |
+
model_chunks=model,
|
| 58 |
+
no_weight_decay_cond=no_weight_decay_cond,
|
| 59 |
+
scale_lr_cond=scale_lr_cond,
|
| 60 |
+
lr_mult=lr_mult,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_megatron_optimizer_param_scheduler(
|
| 65 |
+
optimizer,
|
| 66 |
+
config,
|
| 67 |
+
):
|
| 68 |
+
"""
|
| 69 |
+
Get the optimizer parameter scheduler for Megatron.
|
| 70 |
+
"""
|
| 71 |
+
lr_decay_steps = config.lr_decay_steps
|
| 72 |
+
lr_warmup_steps = config.lr_warmup_steps
|
| 73 |
+
if config.get("lr_decay_steps", None) is None:
|
| 74 |
+
lr_decay_steps = config.total_training_steps
|
| 75 |
+
wsd_decay_steps = None
|
| 76 |
+
if config.get("lr_wsd_decay_steps", None) is not None:
|
| 77 |
+
wsd_decay_steps = config.lr_wsd_decay_steps
|
| 78 |
+
if config.get("lr_warmup_steps_ratio", None) is not None and (
|
| 79 |
+
config.get("lr_warmup_steps", None) is None or config.lr_warmup_steps <= 0
|
| 80 |
+
):
|
| 81 |
+
lr_warmup_steps = int(config.lr_warmup_steps_ratio * lr_decay_steps)
|
| 82 |
+
|
| 83 |
+
opt_param_scheduler = OptimizerParamScheduler(
|
| 84 |
+
optimizer,
|
| 85 |
+
init_lr=config.lr_warmup_init,
|
| 86 |
+
max_lr=config.lr,
|
| 87 |
+
min_lr=config.min_lr,
|
| 88 |
+
lr_warmup_steps=lr_warmup_steps,
|
| 89 |
+
lr_decay_steps=lr_decay_steps,
|
| 90 |
+
lr_decay_style=config.lr_decay_style,
|
| 91 |
+
start_wd=config.weight_decay,
|
| 92 |
+
end_wd=config.weight_decay,
|
| 93 |
+
wd_incr_steps=config.total_training_steps,
|
| 94 |
+
wd_incr_style=config.weight_decay_incr_style,
|
| 95 |
+
use_checkpoint_opt_param_scheduler=config.use_checkpoint_opt_param_scheduler,
|
| 96 |
+
override_opt_param_scheduler=(not config.use_checkpoint_opt_param_scheduler),
|
| 97 |
+
wsd_decay_steps=wsd_decay_steps,
|
| 98 |
+
lr_wsd_decay_style=config.lr_wsd_decay_style,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
return opt_param_scheduler
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def get_megatron_last_lr(optimizer):
|
| 105 |
+
"""
|
| 106 |
+
Get the last learning rate from the optimizer parameter scheduler.
|
| 107 |
+
"""
|
| 108 |
+
return optimizer.param_groups[0]["lr"]
|
verl/verl/utils/megatron/pipeline_parallel.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from megatron.core import parallel_state as mpu
|
| 18 |
+
|
| 19 |
+
from .sequence_parallel import pad_to_sequence_parallel
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def compute_transformers_input_shapes(batches, meta_info):
|
| 23 |
+
from flash_attn.bert_padding import unpad_input # flash 2 is a must for Megatron
|
| 24 |
+
|
| 25 |
+
# pre-compute input shapes for each micro-batch at each pp stage
|
| 26 |
+
input_shapes = []
|
| 27 |
+
for model_inputs in batches:
|
| 28 |
+
input_ids = model_inputs["input_ids"]
|
| 29 |
+
attention_mask = model_inputs["attention_mask"]
|
| 30 |
+
input_ids_rmpad = unpad_input(input_ids.unsqueeze(dim=-1), attention_mask)[0] # (total_nnz, 1)
|
| 31 |
+
if meta_info["sequence_parallel"]:
|
| 32 |
+
input_ids_rmpad = pad_to_sequence_parallel(input_ids_rmpad)
|
| 33 |
+
# compute shapes for model_inputs
|
| 34 |
+
input_shapes.append(
|
| 35 |
+
torch.Size(
|
| 36 |
+
[
|
| 37 |
+
input_ids_rmpad.shape[0] // mpu.get_tensor_model_parallel_world_size(),
|
| 38 |
+
1,
|
| 39 |
+
meta_info["hidden_size"],
|
| 40 |
+
]
|
| 41 |
+
)
|
| 42 |
+
)
|
| 43 |
+
else:
|
| 44 |
+
# compute shapes for model_inputs
|
| 45 |
+
input_shapes.append(torch.Size([input_ids_rmpad.shape[0], 1, meta_info["hidden_size"]]))
|
| 46 |
+
return input_shapes
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def make_batch_generator(batches, vpp_size):
|
| 50 |
+
"""
|
| 51 |
+
Creates a batch generator suitable for Megatron pipeline parallelism,
|
| 52 |
+
handling virtual pipeline parallelism (VPP).
|
| 53 |
+
|
| 54 |
+
If VPP is used (vpp_size > 1), it duplicates the batch iterator for each
|
| 55 |
+
virtual pipeline stage. Otherwise, it returns a single iterator.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
batches: An iterable (e.g., list) of micro-batches.
|
| 59 |
+
vpp_size (int): The virtual pipeline model parallel size.
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
An iterator or a list of iterators over the micro-batches.
|
| 63 |
+
"""
|
| 64 |
+
if vpp_size > 1:
|
| 65 |
+
# has vpp
|
| 66 |
+
batch_generator = [batches] * vpp_size # number of vpp chunks
|
| 67 |
+
batch_generator = [iter(b) for b in batch_generator]
|
| 68 |
+
else:
|
| 69 |
+
# no vpp
|
| 70 |
+
batch_generator = iter(batches)
|
| 71 |
+
return batch_generator
|
verl/verl/utils/megatron/sequence_parallel.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from megatron.core import parallel_state as mpu
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def mark_parameter_as_sequence_parallel(parameter):
|
| 22 |
+
parameter.sequence_parallel = True
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def is_sequence_parallel_param(param):
|
| 26 |
+
return hasattr(param, "sequence_parallel") and param.sequence_parallel
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def pad_to_sequence_parallel(unpad_tokens: torch.Tensor):
|
| 30 |
+
"""pad the tokens such that the total length is a multiple of sp world size
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
unpad_tokens: (total_nnz, ...). Tokens after removing padding
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
the padded tokens: (total_nnz + pad_size,...)
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
total_nnz = unpad_tokens.shape[0]
|
| 40 |
+
sp_world_size = mpu.get_tensor_model_parallel_world_size()
|
| 41 |
+
|
| 42 |
+
pad_size = 0 if total_nnz % sp_world_size == 0 else sp_world_size - total_nnz % sp_world_size
|
| 43 |
+
|
| 44 |
+
if pad_size > 0:
|
| 45 |
+
if unpad_tokens.ndim == 1:
|
| 46 |
+
unpad_tokens = F.pad(unpad_tokens, (0, pad_size))
|
| 47 |
+
elif unpad_tokens.ndim == 2:
|
| 48 |
+
unpad_tokens = F.pad(unpad_tokens, (0, 0, 0, pad_size))
|
| 49 |
+
else:
|
| 50 |
+
raise NotImplementedError(f"Padding dim {unpad_tokens.ndim()} is not supported")
|
| 51 |
+
|
| 52 |
+
return unpad_tokens
|
verl/verl/utils/megatron/tensor_parallel.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""
|
| 16 |
+
Utilities for using tensor_parallel in megatron
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from typing import TYPE_CHECKING
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributed as dist
|
| 23 |
+
from megatron.core import parallel_state as mpu
|
| 24 |
+
from torch.nn import init
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from megatron.core import ModelParallelConfig
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def update_kwargs_with_config(dictionary: dict, config: "ModelParallelConfig"):
|
| 31 |
+
dictionary["config"] = config
|
| 32 |
+
return dictionary
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def get_default_kwargs_for_model_parallel_config():
|
| 36 |
+
model_parallel_config_kwargs = {
|
| 37 |
+
"params_dtype": torch.float32,
|
| 38 |
+
"use_cpu_initialization": False,
|
| 39 |
+
"perform_initialization": True,
|
| 40 |
+
"gradient_accumulation_fusion": False,
|
| 41 |
+
"sequence_parallel": False,
|
| 42 |
+
}
|
| 43 |
+
return model_parallel_config_kwargs
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_default_model_parallel_config():
|
| 47 |
+
from megatron.core import ModelParallelConfig
|
| 48 |
+
|
| 49 |
+
return ModelParallelConfig(**get_default_kwargs_for_model_parallel_config())
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_common_default_kwargs_for_parallel_linear():
|
| 53 |
+
default_model_parallel_config = get_default_model_parallel_config()
|
| 54 |
+
common_default_kwargs = {
|
| 55 |
+
"init_method": init.xavier_normal_,
|
| 56 |
+
"stride": 1,
|
| 57 |
+
"keep_master_weight_for_test": False,
|
| 58 |
+
"config": default_model_parallel_config,
|
| 59 |
+
}
|
| 60 |
+
return common_default_kwargs
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def get_default_kwargs_for_column_parallel_linear():
|
| 64 |
+
from megatron.core import ModelParallelConfig
|
| 65 |
+
|
| 66 |
+
model_parallel_config_kwargs = get_default_kwargs_for_model_parallel_config()
|
| 67 |
+
column_parallel_config_kwargs = {
|
| 68 |
+
"async_tensor_model_parallel_allreduce": False,
|
| 69 |
+
}
|
| 70 |
+
model_parallel_config_kwargs.update(column_parallel_config_kwargs)
|
| 71 |
+
column_default_kwargs = {
|
| 72 |
+
"config": ModelParallelConfig(**model_parallel_config_kwargs),
|
| 73 |
+
}
|
| 74 |
+
common_default_kwargs = get_common_default_kwargs_for_parallel_linear()
|
| 75 |
+
common_default_kwargs.update(column_default_kwargs)
|
| 76 |
+
return common_default_kwargs
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def get_default_kwargs_for_row_parallel_linear():
|
| 80 |
+
common_default_kwargs = get_common_default_kwargs_for_parallel_linear()
|
| 81 |
+
return common_default_kwargs
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def get_default_kwargs_for_parallel_embedding():
|
| 85 |
+
from megatron.core import ModelParallelConfig
|
| 86 |
+
|
| 87 |
+
model_parallel_config_kwargs = get_default_kwargs_for_model_parallel_config()
|
| 88 |
+
embedding_default_kwargs = {
|
| 89 |
+
"init_method": init.xavier_normal_,
|
| 90 |
+
"config": ModelParallelConfig(**model_parallel_config_kwargs),
|
| 91 |
+
}
|
| 92 |
+
return embedding_default_kwargs
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def is_tensor_parallel_param(param):
|
| 96 |
+
return hasattr(param, "tensor_model_parallel") and param.tensor_model_parallel
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_tensor_parallel_partition_dim(param):
|
| 100 |
+
assert is_tensor_parallel_param(param)
|
| 101 |
+
return param.partition_dim
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def get_tensor_parallel_partition_stride(param):
|
| 105 |
+
assert is_tensor_parallel_param(param)
|
| 106 |
+
return param.partition_stride
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class _VocabParallelEntropy(torch.autograd.Function):
|
| 110 |
+
@staticmethod
|
| 111 |
+
def forward(ctx, vocab_parallel_logits: torch.Tensor) -> torch.Tensor:
|
| 112 |
+
@torch.compile(dynamic=True)
|
| 113 |
+
def mul_reduce(a, b):
|
| 114 |
+
return (a * b).sum(dim=-1, keepdim=True)
|
| 115 |
+
|
| 116 |
+
logits_max = vocab_parallel_logits.max(dim=-1, keepdim=True).values
|
| 117 |
+
dist.all_reduce(logits_max, op=dist.ReduceOp.MAX, group=mpu.get_tensor_model_parallel_group())
|
| 118 |
+
normalized_vocab_parallel_logits = vocab_parallel_logits - logits_max
|
| 119 |
+
normalized_exp_logits = normalized_vocab_parallel_logits.exp_()
|
| 120 |
+
normalized_sum_exp_logits = normalized_exp_logits.sum(dim=-1, keepdim=True)
|
| 121 |
+
dist.all_reduce(normalized_sum_exp_logits, group=mpu.get_tensor_model_parallel_group())
|
| 122 |
+
softmax_logits = normalized_exp_logits.div_(normalized_sum_exp_logits)
|
| 123 |
+
sum_softmax_times_logits = mul_reduce(softmax_logits, vocab_parallel_logits)
|
| 124 |
+
dist.all_reduce(sum_softmax_times_logits, group=mpu.get_tensor_model_parallel_group())
|
| 125 |
+
entropy = logits_max + normalized_sum_exp_logits.log() - sum_softmax_times_logits
|
| 126 |
+
ctx.save_for_backward(vocab_parallel_logits, softmax_logits, sum_softmax_times_logits)
|
| 127 |
+
return entropy.squeeze(dim=-1)
|
| 128 |
+
|
| 129 |
+
@staticmethod
|
| 130 |
+
def backward(ctx, grad_output: torch.Tensor) -> torch.Tensor:
|
| 131 |
+
vocab_parallel_logits, softmax_logits, sum_softmax_times_logits = ctx.saved_tensors
|
| 132 |
+
# reuse softmax_logits as grad
|
| 133 |
+
vocab_parallel_logits.sub_(sum_softmax_times_logits)
|
| 134 |
+
softmax_logits.mul_(vocab_parallel_logits)
|
| 135 |
+
softmax_logits.mul_(grad_output.unsqueeze(dim=-1))
|
| 136 |
+
# recover vocab_parallel_logits
|
| 137 |
+
vocab_parallel_logits.add_(sum_softmax_times_logits)
|
| 138 |
+
softmax_logits.mul_(-1)
|
| 139 |
+
return softmax_logits
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def vocab_parallel_entropy(vocab_parallel_logits: torch.Tensor) -> torch.Tensor:
|
| 143 |
+
"""Compute entropy when the logits are sharded in tp ranks
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
vocab_parallel_logits: (total_nnz, vocab_size // tp_size)
|
| 147 |
+
|
| 148 |
+
Returns: (total_nnz,)
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
return _VocabParallelEntropy.apply(vocab_parallel_logits)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def vocab_parallel_log_probs_from_logits(logits, labels):
|
| 155 |
+
"""TODO(zhangchi.usc1992): We may change the implementation later"""
|
| 156 |
+
from megatron.core import tensor_parallel
|
| 157 |
+
|
| 158 |
+
return -tensor_parallel.vocab_parallel_cross_entropy(vocab_parallel_logits=logits, target=labels)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def vocab_parallel_log_probs_from_logits_response_rmpad(input_ids, attention_mask, logits_rmpad, response_length):
|
| 162 |
+
"""Similar to log_probs_from_logits_response_rmpad, but the logits_rmpad is now spliited across tensor parallel
|
| 163 |
+
region.
|
| 164 |
+
This will further reduce the peak memory usage during training
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
input_ids: [batch_size, seqlen]
|
| 168 |
+
attention_mask: [batch_size, seqlen]
|
| 169 |
+
logits_rmpad: [total_nnz, vocab_size // tp_size]
|
| 170 |
+
response_length: int
|
| 171 |
+
|
| 172 |
+
"""
|
| 173 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 174 |
+
|
| 175 |
+
batch_size, seqlen = input_ids.shape
|
| 176 |
+
input_ids_rmpad, indices, *_ = unpad_input(input_ids.unsqueeze(-1), attention_mask=attention_mask)
|
| 177 |
+
input_ids_rmpad = input_ids_rmpad.squeeze(-1)
|
| 178 |
+
input_ids_rmpad_rolled = torch.roll(input_ids_rmpad, shifts=-1, dims=0)
|
| 179 |
+
full_log_probs_rmpad = vocab_parallel_log_probs_from_logits(
|
| 180 |
+
logits=logits_rmpad, labels=input_ids_rmpad_rolled
|
| 181 |
+
) # (total_nnz,)
|
| 182 |
+
full_output = pad_input(
|
| 183 |
+
hidden_states=full_log_probs_rmpad.unsqueeze(-1), indices=indices, batch=batch_size, seqlen=seqlen
|
| 184 |
+
)
|
| 185 |
+
output = full_output.squeeze(-1)[:, -response_length - 1 : -1] # [batch_size, response_length]
|
| 186 |
+
return output
|
verl/verl/utils/metric/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from .utils import reduce_metrics
|
| 16 |
+
|
| 17 |
+
__all__ = ["reduce_metrics"]
|
verl/verl/utils/metric/utils.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""
|
| 15 |
+
Metrics utils.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def reduce_metrics(metrics: dict[str, list[Any]]) -> dict[str, Any]:
|
| 24 |
+
"""
|
| 25 |
+
Reduces a dictionary of metric lists by computing the mean, max, or min of each list.
|
| 26 |
+
The reduce operation is determined by the key name:
|
| 27 |
+
- If the key contains "max", np.max is used
|
| 28 |
+
- If the key contains "min", np.min is used
|
| 29 |
+
- Otherwise, np.mean is used
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
metrics: A dictionary mapping metric names to lists of metric values.
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
A dictionary with the same keys but with each list replaced by its reduced value.
|
| 36 |
+
|
| 37 |
+
Example:
|
| 38 |
+
>>> metrics = {
|
| 39 |
+
... "loss": [1.0, 2.0, 3.0],
|
| 40 |
+
... "accuracy": [0.8, 0.9, 0.7],
|
| 41 |
+
... "max_reward": [5.0, 8.0, 6.0],
|
| 42 |
+
... "min_error": [0.1, 0.05, 0.2]
|
| 43 |
+
... }
|
| 44 |
+
>>> reduce_metrics(metrics)
|
| 45 |
+
{"loss": 2.0, "accuracy": 0.8, "max_reward": 8.0, "min_error": 0.05}
|
| 46 |
+
"""
|
| 47 |
+
for key, val in metrics.items():
|
| 48 |
+
if "max" in key:
|
| 49 |
+
metrics[key] = np.max(val)
|
| 50 |
+
elif "min" in key:
|
| 51 |
+
metrics[key] = np.min(val)
|
| 52 |
+
else:
|
| 53 |
+
metrics[key] = np.mean(val)
|
| 54 |
+
return metrics
|
verl/verl/utils/profiler/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from ..device import is_npu_available
|
| 16 |
+
from ..import_utils import is_nvtx_available
|
| 17 |
+
from .performance import GPUMemoryLogger, log_gpu_memory_usage, simple_timer
|
| 18 |
+
from .profile import DistProfiler, DistProfilerExtension, ProfilerConfig
|
| 19 |
+
|
| 20 |
+
# Select marker implementations by availability, but keep DistProfiler as our dispatcher
|
| 21 |
+
if is_nvtx_available():
|
| 22 |
+
from .nvtx_profile import mark_annotate, mark_end_range, mark_start_range, marked_timer
|
| 23 |
+
elif is_npu_available:
|
| 24 |
+
from .mstx_profile import mark_annotate, mark_end_range, mark_start_range, marked_timer
|
| 25 |
+
else:
|
| 26 |
+
from .performance import marked_timer
|
| 27 |
+
from .profile import mark_annotate, mark_end_range, mark_start_range
|
| 28 |
+
|
| 29 |
+
__all__ = [
|
| 30 |
+
"GPUMemoryLogger",
|
| 31 |
+
"log_gpu_memory_usage",
|
| 32 |
+
"mark_start_range",
|
| 33 |
+
"mark_end_range",
|
| 34 |
+
"mark_annotate",
|
| 35 |
+
"DistProfiler",
|
| 36 |
+
"DistProfilerExtension",
|
| 37 |
+
"ProfilerConfig",
|
| 38 |
+
"simple_timer",
|
| 39 |
+
"marked_timer",
|
| 40 |
+
]
|
verl/verl/utils/profiler/config.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import warnings
|
| 16 |
+
from dataclasses import dataclass, field
|
| 17 |
+
from typing import Any, Optional
|
| 18 |
+
|
| 19 |
+
from omegaconf import MISSING
|
| 20 |
+
|
| 21 |
+
from verl.base_config import BaseConfig
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class NsightToolConfig(BaseConfig):
|
| 26 |
+
"""Nsight tool config."""
|
| 27 |
+
|
| 28 |
+
"True for each task has its own database, False for all tasks in one training step share one database."
|
| 29 |
+
discrete: bool = False
|
| 30 |
+
|
| 31 |
+
def __post_init__(self) -> None:
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class TorchProfilerToolConfig(BaseConfig):
|
| 37 |
+
"""Torch profiler tool config.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
step_start (int): Start step in update_policy.
|
| 41 |
+
step_end (int): End step.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
step_start: int = -1
|
| 45 |
+
step_end: int = -1
|
| 46 |
+
|
| 47 |
+
def __post_init__(self) -> None:
|
| 48 |
+
"""config validation logics go here"""
|
| 49 |
+
warnings.warn("Torch profiler tool config is not fully supported now.", stacklevel=1)
|
| 50 |
+
assert isinstance(self.step_start, int), f"Profiler step_start must be of type int, got {type(self.step_start)}"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class TorchMemoryToolConfig(BaseConfig):
|
| 55 |
+
"""Torch memory profiler tool config.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
trace_alloc_max_entries (int): Maximum number of memory allocation entries to track.
|
| 59 |
+
stack_depth (int): Stack trace depth for memory allocations.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
trace_alloc_max_entries: int = 100_000
|
| 63 |
+
stack_depth: int = 32
|
| 64 |
+
|
| 65 |
+
def __post_init__(self) -> None:
|
| 66 |
+
"""config validation logics go here"""
|
| 67 |
+
assert isinstance(self.trace_alloc_max_entries, int), (
|
| 68 |
+
f"trace_alloc_max_entries must be int, got {type(self.trace_alloc_max_entries)}"
|
| 69 |
+
)
|
| 70 |
+
assert isinstance(self.stack_depth, int), f"stack_depth must be int, got {type(self.stack_depth)}"
|
| 71 |
+
assert self.trace_alloc_max_entries > 0, (
|
| 72 |
+
f"trace_alloc_max_entries must be positive, got {self.trace_alloc_max_entries}"
|
| 73 |
+
)
|
| 74 |
+
assert self.stack_depth > 0, f"stack_depth must be positive, got {self.stack_depth}"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@dataclass
|
| 78 |
+
class NPUToolConfig(NsightToolConfig):
|
| 79 |
+
"""NPU profiler too; config."""
|
| 80 |
+
|
| 81 |
+
# options: npu, cpu, memory, shapes, module, stack
|
| 82 |
+
contents: list[str] = field(default_factory=list)
|
| 83 |
+
|
| 84 |
+
# Collection level, optional values: level_none, level0, level1, level2.
|
| 85 |
+
level: str = "level1"
|
| 86 |
+
|
| 87 |
+
# Whether to automatically parse the data.
|
| 88 |
+
analysis: bool = False
|
| 89 |
+
|
| 90 |
+
def __post_init__(self) -> None:
|
| 91 |
+
"""config validation logics go here"""
|
| 92 |
+
assert isinstance(self.contents, list), f"Profiler contents must be of type list, got {type(self.contents)}"
|
| 93 |
+
assert isinstance(self.level, str), f"Profiler level must be of type str, got {type(self.level)}"
|
| 94 |
+
assert isinstance(self.analysis, bool), f"Profiler analysis must be of type bool, got {type(self.analysis)}"
|
| 95 |
+
for content in self.contents:
|
| 96 |
+
assert content in ["npu", "cpu", "memory", "shapes", "module", "stack"], (
|
| 97 |
+
f"Profiler contents only supports npu, cpu, memory, shapes, module, stack, but gets {content}"
|
| 98 |
+
)
|
| 99 |
+
assert self.level in ["level_none", "level0", "level1", "level2"], (
|
| 100 |
+
f"Profiler level only supports level0, 1, 2, and level_none, but gets {self.level}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@dataclass
|
| 105 |
+
class ProfilerConfig(BaseConfig):
|
| 106 |
+
"""Worker profiler config.
|
| 107 |
+
|
| 108 |
+
The inheritance from BaseConfig provides omegaconf.DictConfig-like interface for a dataclass config.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
discrete (bool): True for each task has its own database, False for all tasks in one training step
|
| 112 |
+
share one database.
|
| 113 |
+
all_ranks (bool): Whether to profile all ranks.
|
| 114 |
+
ranks (list[int]): The ranks that will be profiled. Defaults to [].
|
| 115 |
+
global_tool_config (Any): Global tool configuration for all profiling tools.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
tool: Optional[str] = MISSING
|
| 119 |
+
enable: bool = False
|
| 120 |
+
all_ranks: bool = False
|
| 121 |
+
ranks: list[int] = field(default_factory=list)
|
| 122 |
+
save_path: Optional[str] = MISSING
|
| 123 |
+
tool_config: Any = MISSING # Just a placeholder, will use configs above directly
|
| 124 |
+
global_tool_config: Optional[Any] = None # Global tool configuration for all profiling tools
|
| 125 |
+
|
| 126 |
+
def union(self, other: "ProfilerConfig") -> "ProfilerConfig":
|
| 127 |
+
assert self.tool == other.tool, f"Cannot union ProfilerConfig with different tools: {self.tool} vs {other.tool}"
|
| 128 |
+
return ProfilerConfig(
|
| 129 |
+
tool=self.tool,
|
| 130 |
+
enable=self.enable or other.enable,
|
| 131 |
+
all_ranks=self.all_ranks or other.all_ranks,
|
| 132 |
+
ranks=list(set(self.ranks or []) | set(other.ranks or [])),
|
| 133 |
+
save_path=self.save_path,
|
| 134 |
+
tool_config=self.tool_config,
|
| 135 |
+
global_tool_config=self.global_tool_config or other.global_tool_config,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
def intersect(self, other: "ProfilerConfig") -> "ProfilerConfig":
|
| 139 |
+
assert self.tool == other.tool, (
|
| 140 |
+
f"Cannot intersect ProfilerConfig with different tools: {self.tool} vs {other.tool}"
|
| 141 |
+
)
|
| 142 |
+
return ProfilerConfig(
|
| 143 |
+
tool=self.tool,
|
| 144 |
+
enable=self.enable and other.enable,
|
| 145 |
+
all_ranks=self.all_ranks and other.all_ranks,
|
| 146 |
+
ranks=list(set(self.ranks or []) & set(other.ranks or [])),
|
| 147 |
+
save_path=self.save_path,
|
| 148 |
+
tool_config=self.tool_config,
|
| 149 |
+
global_tool_config=self.global_tool_config if self.global_tool_config else other.global_tool_config,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def __post_init__(self) -> None:
|
| 153 |
+
"""config validation logics go here"""
|
| 154 |
+
assert isinstance(self.ranks, set | list | tuple), (
|
| 155 |
+
f"Profiler ranks must be of type list, got {type(self.ranks)}"
|
| 156 |
+
)
|
verl/verl/utils/profiler/empty_annotations.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from typing import Callable, Optional
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def mark_start_range(
|
| 19 |
+
message: Optional[str] = None,
|
| 20 |
+
color: Optional[str] = None,
|
| 21 |
+
domain: Optional[str] = None,
|
| 22 |
+
category: Optional[str] = None,
|
| 23 |
+
) -> None:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def mark_end_range(range_id: str) -> None:
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def mark_annotate(
|
| 32 |
+
message: Optional[str] = None,
|
| 33 |
+
color: Optional[str] = None,
|
| 34 |
+
domain: Optional[str] = None,
|
| 35 |
+
category: Optional[str] = None,
|
| 36 |
+
) -> Callable:
|
| 37 |
+
def decorator(func):
|
| 38 |
+
return func
|
| 39 |
+
|
| 40 |
+
return decorator
|
verl/verl/utils/profiler/mstx_profile.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# Inspired from https://gitee.com/ascend/MindSpeed-RL/blob/master/mindspeed_rl/utils/utils.py
|
| 16 |
+
import functools
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
from contextlib import contextmanager
|
| 20 |
+
from typing import Any, Callable, Optional
|
| 21 |
+
|
| 22 |
+
import torch_npu
|
| 23 |
+
from torch_npu.npu import mstx
|
| 24 |
+
|
| 25 |
+
from .config import NPUToolConfig
|
| 26 |
+
from .profile import DistProfiler, ProfilerConfig
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def mark_start_range(message: Optional[str] = None) -> None:
|
| 30 |
+
"""Start a mark range in the profiler.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
message (str, optional):
|
| 34 |
+
The message to be displayed in the profiler. Defaults to None.
|
| 35 |
+
"""
|
| 36 |
+
return mstx.range_start(message=message)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def mark_end_range(range_id: str) -> None:
|
| 40 |
+
"""End a mark range in the profiler.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
range_id (str):
|
| 44 |
+
The id of the mark range to end.
|
| 45 |
+
"""
|
| 46 |
+
return mstx.range_end(range_id)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def mark_annotate(message: Optional[str] = None) -> Callable:
|
| 50 |
+
"""Decorate a function to annotate a mark range along with the function life cycle.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
message (str, optional):
|
| 54 |
+
The message to be displayed in the profiler. Defaults to None.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def decorator(func):
|
| 58 |
+
profile_message = message or func.__name__
|
| 59 |
+
return mstx.mstx_range(profile_message)(func)
|
| 60 |
+
|
| 61 |
+
return decorator
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@contextmanager
|
| 65 |
+
def marked_timer(name: str, timing_raw: dict[str, float], *args: Any, **kwargs: Any) -> None:
|
| 66 |
+
"""Context manager for timing with MSTX markers.
|
| 67 |
+
|
| 68 |
+
This utility function measures the execution time of code within its context,
|
| 69 |
+
accumulates the timing information, and adds MSTX markers for profiling.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
name (str): The name/identifier for this timing measurement.
|
| 73 |
+
timing_raw (Dict[str, float]): Dictionary to store timing information.
|
| 74 |
+
|
| 75 |
+
Yields:
|
| 76 |
+
None: This is a context manager that yields control back to the code block.
|
| 77 |
+
"""
|
| 78 |
+
if args:
|
| 79 |
+
logging.warning(f"Args are not supported in mstx_profile, but received: {args}")
|
| 80 |
+
if kwargs:
|
| 81 |
+
logging.warning(f"Kwargs are not supported in mstx_profile, but received: {kwargs}")
|
| 82 |
+
mark_range = mark_start_range(message=name)
|
| 83 |
+
from .performance import _timer
|
| 84 |
+
|
| 85 |
+
yield from _timer(name, timing_raw)
|
| 86 |
+
mark_end_range(mark_range)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def get_npu_profiler(
|
| 90 |
+
contents: list[str],
|
| 91 |
+
profile_level: str,
|
| 92 |
+
profile_save_path: str,
|
| 93 |
+
analysis: bool,
|
| 94 |
+
role: Optional[str] = None,
|
| 95 |
+
profile_step: Optional[str] = None,
|
| 96 |
+
):
|
| 97 |
+
"""Generate and return an NPU profiler object.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
contents (list[str]):
|
| 101 |
+
A list of options to control the collection content,
|
| 102 |
+
such as npu, cpu, memory, shapes, module, stack.
|
| 103 |
+
profile_level (str):
|
| 104 |
+
The collection level, which can be set to level_none,
|
| 105 |
+
level0, level1 and level2.
|
| 106 |
+
profile_save_path (str):
|
| 107 |
+
The path to save the collected data.
|
| 108 |
+
analysis (bool):
|
| 109 |
+
Whether to enables automatic data parsing.
|
| 110 |
+
role (str, optional):
|
| 111 |
+
The role of the current data collection. Defaults to None.
|
| 112 |
+
profile_step(str, optional):
|
| 113 |
+
The current training step. Defaults to None.
|
| 114 |
+
"""
|
| 115 |
+
if profile_level == "level_none":
|
| 116 |
+
level = torch_npu.profiler.ProfilerLevel.Level_none
|
| 117 |
+
elif profile_level == "level0":
|
| 118 |
+
level = torch_npu.profiler.ProfilerLevel.Level0
|
| 119 |
+
elif profile_level == "level1":
|
| 120 |
+
level = torch_npu.profiler.ProfilerLevel.Level1
|
| 121 |
+
elif profile_level == "level2":
|
| 122 |
+
level = torch_npu.profiler.ProfilerLevel.Level2
|
| 123 |
+
else:
|
| 124 |
+
raise ValueError(f"level only supports level0, 1, 2, and level_none, but gets {profile_level}")
|
| 125 |
+
|
| 126 |
+
if profile_step:
|
| 127 |
+
profile_save_path = os.path.join(profile_save_path, profile_step)
|
| 128 |
+
if role:
|
| 129 |
+
profile_save_path = os.path.join(profile_save_path, role)
|
| 130 |
+
|
| 131 |
+
experimental_config = torch_npu.profiler._ExperimentalConfig(
|
| 132 |
+
aic_metrics=torch_npu.profiler.AiCMetrics.PipeUtilization,
|
| 133 |
+
profiler_level=level,
|
| 134 |
+
export_type=torch_npu.profiler.ExportType.Text,
|
| 135 |
+
data_simplification=True,
|
| 136 |
+
msprof_tx=True,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
activites = []
|
| 140 |
+
if contents is None or "npu" in contents:
|
| 141 |
+
activites.append(torch_npu.profiler.ProfilerActivity.NPU)
|
| 142 |
+
if contents is None or "cpu" in contents:
|
| 143 |
+
activites.append(torch_npu.profiler.ProfilerActivity.CPU)
|
| 144 |
+
|
| 145 |
+
prof = torch_npu.profiler.profile(
|
| 146 |
+
with_modules=contents is None or "module" in contents,
|
| 147 |
+
with_stack=contents is None or "stack" in contents,
|
| 148 |
+
record_shapes=contents is None or "shapes" in contents,
|
| 149 |
+
profile_memory=contents is None or "memory" in contents,
|
| 150 |
+
activities=activites,
|
| 151 |
+
on_trace_ready=torch_npu.profiler.tensorboard_trace_handler(profile_save_path, analyse_flag=analysis),
|
| 152 |
+
experimental_config=experimental_config,
|
| 153 |
+
)
|
| 154 |
+
return prof
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class NPUProfiler(DistProfiler):
|
| 158 |
+
"""
|
| 159 |
+
NPU profiler. Initialized in a worker to control the NPU profiler.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
_define_count = 0
|
| 163 |
+
|
| 164 |
+
def __init__(self, rank: int, config: ProfilerConfig, tool_config: NPUToolConfig, **kwargs):
|
| 165 |
+
"""Initialize the NsightSystemsProfiler.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
rank (int): The rank of the current process.
|
| 169 |
+
config (Optional[ProfilerConfig]): Configuration for the profiler. If None, a default configuration is used.
|
| 170 |
+
tool_config (NPUToolConfig): The config to control npu profiler behavior.
|
| 171 |
+
"""
|
| 172 |
+
if not config:
|
| 173 |
+
config = ProfilerConfig(ranks=[], enable=False)
|
| 174 |
+
if not tool_config:
|
| 175 |
+
assert not config.enable, "tool_config must be set when profiler is enabled"
|
| 176 |
+
self.enable: bool = config.enable
|
| 177 |
+
if not config.enable:
|
| 178 |
+
return
|
| 179 |
+
self.this_step: bool = False
|
| 180 |
+
self.discrete: bool = tool_config.discrete
|
| 181 |
+
self.this_rank: bool = False
|
| 182 |
+
self.profile_npu = None
|
| 183 |
+
self.profile_contents = tool_config.contents
|
| 184 |
+
self.profile_level = tool_config.level
|
| 185 |
+
self.profile_save_path = config.save_path
|
| 186 |
+
self.analysis = tool_config.analysis
|
| 187 |
+
if config.all_ranks:
|
| 188 |
+
self.this_rank = True
|
| 189 |
+
elif config.ranks:
|
| 190 |
+
self.this_rank = rank in config.ranks
|
| 191 |
+
|
| 192 |
+
def start(self, **kwargs):
|
| 193 |
+
role, profile_step = kwargs.get("role", None), kwargs.get("profile_step", None)
|
| 194 |
+
profile_step = str(profile_step) if profile_step is not None else None
|
| 195 |
+
if self.enable and self.this_rank:
|
| 196 |
+
self.this_step = True
|
| 197 |
+
if not self.discrete and NPUProfiler._define_count == 0:
|
| 198 |
+
self.profile_npu = get_npu_profiler(
|
| 199 |
+
contents=self.profile_contents,
|
| 200 |
+
profile_level=self.profile_level,
|
| 201 |
+
profile_save_path=self.profile_save_path,
|
| 202 |
+
analysis=self.analysis,
|
| 203 |
+
role=role,
|
| 204 |
+
profile_step=profile_step,
|
| 205 |
+
)
|
| 206 |
+
self.profile_npu.start()
|
| 207 |
+
NPUProfiler._define_count += 1
|
| 208 |
+
|
| 209 |
+
def stop(self):
|
| 210 |
+
if self.enable and self.this_rank:
|
| 211 |
+
self.this_step = False
|
| 212 |
+
if not self.discrete and NPUProfiler._define_count == 1:
|
| 213 |
+
self.profile_npu.step()
|
| 214 |
+
self.profile_npu.stop()
|
| 215 |
+
NPUProfiler._define_count -= 1
|
| 216 |
+
|
| 217 |
+
def annotate(self, message: Optional[str] = None, role: Optional[str] = None, **kwargs_outer) -> Callable:
|
| 218 |
+
"""Decorate a Worker member function to profile the current rank in the current training step.
|
| 219 |
+
|
| 220 |
+
Requires the target function to be a member function of a Worker,
|
| 221 |
+
which has a member field `profiler` with NPUProfiler type.
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
message (str, optional):
|
| 225 |
+
The message to be displayed in the profiler. Defaults to None.
|
| 226 |
+
role (str, optional):
|
| 227 |
+
The role of the current data collection. Defaults to None.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
def decorator(func):
|
| 231 |
+
@functools.wraps(func)
|
| 232 |
+
def wrapper(*args, **kwargs_inner):
|
| 233 |
+
if not self.enable:
|
| 234 |
+
return func(*args, **kwargs_inner)
|
| 235 |
+
|
| 236 |
+
profile_name = message or func.__name__
|
| 237 |
+
discrete_mode = self.discrete
|
| 238 |
+
profile_enable = self.this_step and self.enable
|
| 239 |
+
|
| 240 |
+
if not profile_enable:
|
| 241 |
+
return func(*args, **kwargs_inner)
|
| 242 |
+
|
| 243 |
+
if profile_enable:
|
| 244 |
+
if not discrete_mode:
|
| 245 |
+
mark_range = mark_start_range(message=profile_name)
|
| 246 |
+
else:
|
| 247 |
+
profile_npu = get_npu_profiler(
|
| 248 |
+
contents=self.profile_contents,
|
| 249 |
+
profile_level=self.profile_level,
|
| 250 |
+
profile_save_path=self.profile_save_path,
|
| 251 |
+
analysis=self.analysis,
|
| 252 |
+
role=role,
|
| 253 |
+
)
|
| 254 |
+
profile_npu.start()
|
| 255 |
+
mark_range = mark_start_range(message=profile_name)
|
| 256 |
+
|
| 257 |
+
result = func(*args, **kwargs_inner)
|
| 258 |
+
|
| 259 |
+
if profile_enable:
|
| 260 |
+
if not discrete_mode:
|
| 261 |
+
mark_end_range(mark_range)
|
| 262 |
+
else:
|
| 263 |
+
mark_end_range(mark_range)
|
| 264 |
+
profile_npu.step()
|
| 265 |
+
profile_npu.stop()
|
| 266 |
+
|
| 267 |
+
return result
|
| 268 |
+
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import functools
|
| 17 |
+
from contextlib import contextmanager
|
| 18 |
+
from typing import Callable, Optional
|
| 19 |
+
|
| 20 |
+
import nvtx
|
| 21 |
+
import torch
|
| 22 |
+
|
| 23 |
+
from .config import NsightToolConfig
|
| 24 |
+
from .profile import DistProfiler, ProfilerConfig
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def mark_start_range(
|
| 28 |
+
message: Optional[str] = None,
|
| 29 |
+
color: Optional[str] = None,
|
| 30 |
+
domain: Optional[str] = None,
|
| 31 |
+
category: Optional[str] = None,
|
| 32 |
+
) -> None:
|
| 33 |
+
"""Start a mark range in the profiler.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
message (str, optional):
|
| 37 |
+
The message to be displayed in the profiler. Defaults to None.
|
| 38 |
+
color (str, optional):
|
| 39 |
+
The color of the range. Defaults to None.
|
| 40 |
+
domain (str, optional):
|
| 41 |
+
The domain of the range. Defaults to None.
|
| 42 |
+
category (str, optional):
|
| 43 |
+
The category of the range. Defaults to None.
|
| 44 |
+
"""
|
| 45 |
+
return nvtx.start_range(message=message, color=color, domain=domain, category=category)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def mark_end_range(range_id: str) -> None:
|
| 49 |
+
"""End a mark range in the profiler.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
range_id (str):
|
| 53 |
+
The id of the mark range to end.
|
| 54 |
+
"""
|
| 55 |
+
return nvtx.end_range(range_id)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def mark_annotate(
|
| 59 |
+
message: Optional[str] = None,
|
| 60 |
+
color: Optional[str] = None,
|
| 61 |
+
domain: Optional[str] = None,
|
| 62 |
+
category: Optional[str] = None,
|
| 63 |
+
) -> Callable:
|
| 64 |
+
"""Decorate a function to annotate a mark range along with the function life cycle.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
message (str, optional):
|
| 68 |
+
The message to be displayed in the profiler. Defaults to None.
|
| 69 |
+
color (str, optional):
|
| 70 |
+
The color of the range. Defaults to None.
|
| 71 |
+
domain (str, optional):
|
| 72 |
+
The domain of the range. Defaults to None.
|
| 73 |
+
category (str, optional):
|
| 74 |
+
The category of the range. Defaults to None.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def decorator(func):
|
| 78 |
+
profile_message = message or func.__name__
|
| 79 |
+
return nvtx.annotate(profile_message, color=color, domain=domain, category=category)(func)
|
| 80 |
+
|
| 81 |
+
return decorator
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@contextmanager
|
| 85 |
+
def marked_timer(
|
| 86 |
+
name: str,
|
| 87 |
+
timing_raw: dict[str, float],
|
| 88 |
+
color: str = None,
|
| 89 |
+
domain: Optional[str] = None,
|
| 90 |
+
category: Optional[str] = None,
|
| 91 |
+
):
|
| 92 |
+
"""Context manager for timing with NVTX markers.
|
| 93 |
+
|
| 94 |
+
This utility function measures the execution time of code within its context,
|
| 95 |
+
accumulates the timing information, and adds NVTX markers for profiling.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
name (str): The name/identifier for this timing measurement.
|
| 99 |
+
timing_raw (Dict[str, float]): Dictionary to store timing information.
|
| 100 |
+
color (Optional[str]): Color for the NVTX marker. Defaults to None.
|
| 101 |
+
domain (Optional[str]): Domain for the NVTX marker. Defaults to None.
|
| 102 |
+
category (Optional[str]): Category for the NVTX marker. Defaults to None.
|
| 103 |
+
|
| 104 |
+
Yields:
|
| 105 |
+
None: This is a context manager that yields control back to the code block.
|
| 106 |
+
"""
|
| 107 |
+
mark_range = mark_start_range(message=name, color=color, domain=domain, category=category)
|
| 108 |
+
from .performance import _timer
|
| 109 |
+
|
| 110 |
+
yield from _timer(name, timing_raw)
|
| 111 |
+
mark_end_range(mark_range)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class NsightSystemsProfiler(DistProfiler):
|
| 115 |
+
"""Nsight system profiler. Installed in a worker to control the Nsight system profiler."""
|
| 116 |
+
|
| 117 |
+
def __init__(self, rank: int, config: Optional[ProfilerConfig], tool_config: Optional[NsightToolConfig], **kwargs):
|
| 118 |
+
"""Initialize the NsightSystemsProfiler.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
rank (int): The rank of the current process.
|
| 122 |
+
config (Optional[ProfilerConfig]): Configuration for the profiler. If None, a default configuration is used.
|
| 123 |
+
"""
|
| 124 |
+
# If no configuration is provided, create a default ProfilerConfig with an empty list of ranks
|
| 125 |
+
if not config:
|
| 126 |
+
config = ProfilerConfig(ranks=[])
|
| 127 |
+
if not tool_config:
|
| 128 |
+
assert not config.enable, "tool_config must be provided when profiler is enabled"
|
| 129 |
+
self.enable = config.enable
|
| 130 |
+
if not config.enable:
|
| 131 |
+
return
|
| 132 |
+
self.this_step: bool = False
|
| 133 |
+
self.discrete: bool = tool_config.discrete
|
| 134 |
+
self.this_rank: bool = False
|
| 135 |
+
if config.all_ranks:
|
| 136 |
+
self.this_rank = True
|
| 137 |
+
elif config.ranks:
|
| 138 |
+
self.this_rank = rank in config.ranks
|
| 139 |
+
|
| 140 |
+
def start(self, **kwargs):
|
| 141 |
+
if self.enable and self.this_rank:
|
| 142 |
+
self.this_step = True
|
| 143 |
+
if not self.discrete:
|
| 144 |
+
torch.cuda.profiler.start()
|
| 145 |
+
|
| 146 |
+
def stop(self):
|
| 147 |
+
if self.enable and self.this_rank:
|
| 148 |
+
self.this_step = False
|
| 149 |
+
if not self.discrete:
|
| 150 |
+
torch.cuda.profiler.stop()
|
| 151 |
+
|
| 152 |
+
def annotate(
|
| 153 |
+
self,
|
| 154 |
+
message: Optional[str] = None,
|
| 155 |
+
color: Optional[str] = None,
|
| 156 |
+
domain: Optional[str] = None,
|
| 157 |
+
category: Optional[str] = None,
|
| 158 |
+
**kwargs_outer,
|
| 159 |
+
) -> Callable:
|
| 160 |
+
"""Decorate a Worker member function to profile the current rank in the current training step.
|
| 161 |
+
|
| 162 |
+
Requires the target function to be a member function of a Worker, which has a member field `profiler` with
|
| 163 |
+
NightSystemsProfiler type.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
message (str, optional):
|
| 167 |
+
The message to be displayed in the profiler. Defaults to None.
|
| 168 |
+
color (str, optional):
|
| 169 |
+
The color of the range. Defaults to None.
|
| 170 |
+
domain (str, optional):
|
| 171 |
+
The domain of the range. Defaults to None.
|
| 172 |
+
category (str, optional):
|
| 173 |
+
The category of the range. Defaults to None.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def decorator(func):
|
| 177 |
+
@functools.wraps(func)
|
| 178 |
+
def wrapper(*args, **kwargs_inner):
|
| 179 |
+
if not self.enable:
|
| 180 |
+
return func(*args, **kwargs_inner)
|
| 181 |
+
|
| 182 |
+
profile_name = message or func.__name__
|
| 183 |
+
|
| 184 |
+
if self.this_step:
|
| 185 |
+
if self.discrete:
|
| 186 |
+
torch.cuda.profiler.start()
|
| 187 |
+
mark_range = mark_start_range(message=profile_name, color=color, domain=domain, category=category)
|
| 188 |
+
|
| 189 |
+
result = func(*args, **kwargs_inner)
|
| 190 |
+
|
| 191 |
+
if self.this_step:
|
| 192 |
+
mark_end_range(mark_range)
|
| 193 |
+
if self.discrete:
|
| 194 |
+
torch.cuda.profiler.stop()
|
| 195 |
+
|
| 196 |
+
return result
|
| 197 |
+
|
| 198 |
+
return wrapper
|
| 199 |
+
|
| 200 |
+
return decorator
|
verl/verl/utils/profiler/performance.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import datetime
|
| 16 |
+
import inspect
|
| 17 |
+
import logging
|
| 18 |
+
from contextlib import contextmanager
|
| 19 |
+
from typing import Any, Optional
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.distributed as dist
|
| 23 |
+
from codetiming import Timer
|
| 24 |
+
|
| 25 |
+
from verl.utils.device import get_device_id, get_torch_device
|
| 26 |
+
from verl.utils.logger import DecoratorLoggerBase
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _get_current_mem_info(unit: str = "GB", precision: int = 2) -> tuple[str]:
|
| 30 |
+
"""Get current memory usage.
|
| 31 |
+
|
| 32 |
+
Note that CPU device memory info is always 0.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
unit (str, optional): The unit of memory measurement. Defaults to "GB".
|
| 36 |
+
precision (int, optional): The number of decimal places to round memory values. Defaults to 2.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
tuple[str]: A tuple containing memory allocated, memory reserved, memory used, and memory total
|
| 40 |
+
in the specified unit.
|
| 41 |
+
"""
|
| 42 |
+
assert unit in ["GB", "MB", "KB"]
|
| 43 |
+
device = get_torch_device()
|
| 44 |
+
# torch.cpu.memory_allocated() does not exist
|
| 45 |
+
if device == torch.cpu:
|
| 46 |
+
return "0.00", "0.00", "0.00", "0.00"
|
| 47 |
+
|
| 48 |
+
divisor = 1024**3 if unit == "GB" else 1024**2 if unit == "MB" else 1024
|
| 49 |
+
mem_allocated = get_torch_device().memory_allocated()
|
| 50 |
+
mem_reserved = get_torch_device().memory_reserved()
|
| 51 |
+
# use get_torch_device().mem_get_info to profile device memory
|
| 52 |
+
# since vllm's sleep mode works below pytorch
|
| 53 |
+
# see https://github.com/vllm-project/vllm/pull/11743#issuecomment-2754338119
|
| 54 |
+
mem_free, mem_total = get_torch_device().mem_get_info()
|
| 55 |
+
mem_used = mem_total - mem_free
|
| 56 |
+
mem_allocated = f"{mem_allocated / divisor:.{precision}f}"
|
| 57 |
+
mem_reserved = f"{mem_reserved / divisor:.{precision}f}"
|
| 58 |
+
mem_used = f"{mem_used / divisor:.{precision}f}"
|
| 59 |
+
mem_total = f"{mem_total / divisor:.{precision}f}"
|
| 60 |
+
return mem_allocated, mem_reserved, mem_used, mem_total
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def log_gpu_memory_usage(head: str, logger: logging.Logger = None, level=logging.DEBUG, rank: int = 0):
|
| 64 |
+
"""Log GPU memory usage information.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
head (str): A descriptive header for the memory usage log message.
|
| 68 |
+
logger (logging.Logger, optional): Logger instance to use for logging. If None, prints to stdout.
|
| 69 |
+
level: Logging level to use. Defaults to logging.DEBUG.
|
| 70 |
+
rank (int): The rank of the process to log memory for. Defaults to 0.
|
| 71 |
+
"""
|
| 72 |
+
if (not dist.is_initialized()) or (rank is None) or (dist.get_rank() == rank):
|
| 73 |
+
mem_allocated, mem_reserved, mem_used, mem_total = _get_current_mem_info()
|
| 74 |
+
message = (
|
| 75 |
+
f"{head}, memory allocated (GB): {mem_allocated}, memory reserved (GB): {mem_reserved}, "
|
| 76 |
+
f"device memory used/total (GB): {mem_used}/{mem_total}"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
if logger is None:
|
| 80 |
+
print(message)
|
| 81 |
+
else:
|
| 82 |
+
logger.log(msg=message, level=level)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class GPUMemoryLogger(DecoratorLoggerBase):
|
| 86 |
+
"""A decorator class to log GPU memory usage.
|
| 87 |
+
|
| 88 |
+
Example:
|
| 89 |
+
>>> from verl.utils.profiler.performance import GPUMemoryLogger
|
| 90 |
+
>>> @GPUMemoryLogger(role="actor")
|
| 91 |
+
>>> def update_actor(self, batch):
|
| 92 |
+
... # real actor update logics
|
| 93 |
+
... return
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def __init__(self, role: str, logger: logging.Logger = None, level=logging.DEBUG, log_only_rank_0: bool = True):
|
| 97 |
+
if dist.is_initialized() and dist.get_world_size() > 1:
|
| 98 |
+
rank = dist.get_rank()
|
| 99 |
+
else:
|
| 100 |
+
rank = 0
|
| 101 |
+
super().__init__(role, logger, level, rank, log_only_rank_0)
|
| 102 |
+
|
| 103 |
+
def __call__(self, decorated_function: callable):
|
| 104 |
+
def f(*args, **kwargs):
|
| 105 |
+
return self.log(decorated_function, *args, **kwargs)
|
| 106 |
+
|
| 107 |
+
return f
|
| 108 |
+
|
| 109 |
+
def log(self, func, *args, **kwargs):
|
| 110 |
+
name = func.__name__
|
| 111 |
+
mem_allocated, mem_reserved, mem_used, mem_total = _get_current_mem_info()
|
| 112 |
+
message = (
|
| 113 |
+
f"Before {name}, memory allocated (GB): {mem_allocated}, memory reserved (GB): {mem_reserved}, "
|
| 114 |
+
f"device memory used/total (GB): {mem_used}/{mem_total}"
|
| 115 |
+
)
|
| 116 |
+
self.logging_function(message)
|
| 117 |
+
|
| 118 |
+
output = func(*args, **kwargs)
|
| 119 |
+
|
| 120 |
+
mem_allocated, mem_reserved, mem_used, mem_total = _get_current_mem_info()
|
| 121 |
+
message = (
|
| 122 |
+
f"After {name}, memory allocated (GB): {mem_allocated}, memory reserved (GB): {mem_reserved}, "
|
| 123 |
+
f"device memory used/total (GB): {mem_used}/{mem_total}"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
self.logging_function(message)
|
| 127 |
+
return output
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def log_print(ctn: Any):
|
| 131 |
+
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 132 |
+
|
| 133 |
+
frame = inspect.currentframe().f_back
|
| 134 |
+
function_name = frame.f_code.co_name
|
| 135 |
+
line_number = frame.f_lineno
|
| 136 |
+
file_name = frame.f_code.co_filename.split("/")[-1]
|
| 137 |
+
print(f"[{current_time}-{file_name}:{line_number}:{function_name}]: {ctn}")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _timer(name: str, timing_raw: dict[str, float]):
|
| 141 |
+
"""Inner function that handles the core timing logic.
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
name (str): The name/identifier for this timing measurement.
|
| 145 |
+
timing_raw (Dict[str, float]): Dictionary to store timing information.
|
| 146 |
+
"""
|
| 147 |
+
with Timer(name=name, logger=None) as timer:
|
| 148 |
+
yield
|
| 149 |
+
if name not in timing_raw:
|
| 150 |
+
timing_raw[name] = 0
|
| 151 |
+
timing_raw[name] += timer.last
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@contextmanager
|
| 155 |
+
def simple_timer(name: str, timing_raw: dict[str, float]):
|
| 156 |
+
"""Context manager for basic timing without NVTX markers.
|
| 157 |
+
|
| 158 |
+
This utility function measures the execution time of code within its context
|
| 159 |
+
and accumulates the timing information in the provided dictionary.
|
| 160 |
+
|
| 161 |
+
Args:
|
| 162 |
+
name (str): The name/identifier for this timing measurement.
|
| 163 |
+
timing_raw (Dict[str, float]): Dictionary to store timing information.
|
| 164 |
+
|
| 165 |
+
Yields:
|
| 166 |
+
None: This is a context manager that yields control back to the code block.
|
| 167 |
+
"""
|
| 168 |
+
yield from _timer(name, timing_raw)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@contextmanager
|
| 172 |
+
def marked_timer(
|
| 173 |
+
name: str,
|
| 174 |
+
timing_raw: dict[str, float],
|
| 175 |
+
color: str = None,
|
| 176 |
+
domain: Optional[str] = None,
|
| 177 |
+
category: Optional[str] = None,
|
| 178 |
+
):
|
| 179 |
+
"""Context manager for timing with platform markers.
|
| 180 |
+
|
| 181 |
+
This utility function measures the execution time of code within its context,
|
| 182 |
+
accumulates the timing information, and adds platform markers for profiling.
|
| 183 |
+
This function is a default implementation when hardware profiler is not available.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
name (str): The name/identifier for this timing measurement.
|
| 187 |
+
timing_raw (Dict[str, float]): Dictionary to store timing information.
|
| 188 |
+
color (Optional[str]): Color for the marker. Defaults to None.
|
| 189 |
+
domain (Optional[str]): Domain for the marker. Defaults to None.
|
| 190 |
+
category (Optional[str]): Category for the marker. Defaults to None.
|
| 191 |
+
|
| 192 |
+
Yields:
|
| 193 |
+
None: This is a context manager that yields control back to the code block.
|
| 194 |
+
"""
|
| 195 |
+
yield from _timer(name, timing_raw)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def reduce_timing(
|
| 199 |
+
timing_raw: dict[str, float], reduce_op: torch.distributed.ReduceOp = torch.distributed.ReduceOp.AVG
|
| 200 |
+
) -> dict[str, float]:
|
| 201 |
+
"""Reduce timing information across all processes.
|
| 202 |
+
|
| 203 |
+
This function uses distributed communication to gather and sum the timing
|
| 204 |
+
information from all processes in a distributed environment.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
timing_raw (Dict[str, float]): Dictionary containing timing information.
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
Dict[str, float]: Reduced timing information.
|
| 211 |
+
"""
|
| 212 |
+
if not dist.is_initialized():
|
| 213 |
+
return timing_raw
|
| 214 |
+
|
| 215 |
+
key_list, timing_list = [], []
|
| 216 |
+
for key in sorted(timing_raw.keys()):
|
| 217 |
+
key_list.append(key)
|
| 218 |
+
timing_list.append(timing_raw[key])
|
| 219 |
+
timing_list = torch.tensor(timing_list, dtype=torch.float32, device=get_device_id())
|
| 220 |
+
torch.distributed.all_reduce(timing_list, op=reduce_op)
|
| 221 |
+
timing_list = [tensor.item() for tensor in timing_list.to("cpu")]
|
| 222 |
+
timing_generate = {key_list[i]: timing_list[i] for i in range(len(key_list))}
|
| 223 |
+
return timing_generate
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def topk_reduce_ratio_min_max(timing: float, k: int = 10) -> tuple[float, float, float]:
|
| 227 |
+
"""Calculate topk items take-up ratio, and min/max timing across all ranks."""
|
| 228 |
+
if not dist.is_initialized():
|
| 229 |
+
return -1.0, -1.0, -1.0
|
| 230 |
+
|
| 231 |
+
world_size = dist.get_world_size()
|
| 232 |
+
timing_tensor = torch.tensor(timing, dtype=torch.float32, device=get_device_id())
|
| 233 |
+
tensor_list = [torch.zeros(1, dtype=torch.float32, device=get_device_id()) for _ in range(world_size)]
|
| 234 |
+
torch.distributed.all_gather(tensor_list, timing_tensor)
|
| 235 |
+
tensor_stack = torch.stack(tensor_list)
|
| 236 |
+
timing_min = tensor_stack.min().cpu().item()
|
| 237 |
+
timing_max = tensor_stack.max().cpu().item()
|
| 238 |
+
top_k_percentile = torch.quantile(tensor_stack, 1 - k / 100)
|
| 239 |
+
tail_ratio = torch.mean((tensor_stack > top_k_percentile).float()).cpu().item()
|
| 240 |
+
return tail_ratio, timing_min, timing_max
|
verl/verl/utils/profiler/profile.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import functools
|
| 16 |
+
import os
|
| 17 |
+
from typing import Callable, Optional
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.distributed
|
| 21 |
+
|
| 22 |
+
from ..memory_utils import MemorySnapshotSampler, enable_memory_visualize
|
| 23 |
+
from .config import ProfilerConfig, TorchMemoryToolConfig, TorchProfilerToolConfig
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Profiler:
|
| 27 |
+
"""A PyTorch profiler wrapper class for collecting performance metrics.
|
| 28 |
+
|
| 29 |
+
TODO(haibin.lin): this should implement the DistProfiler interface, and the config should be unified.
|
| 30 |
+
|
| 31 |
+
This profiler provides a convenient interface for profiling PyTorch operations,
|
| 32 |
+
with support for:
|
| 33 |
+
|
| 34 |
+
- CPU and CUDA activity profiling
|
| 35 |
+
- Configurable profiling schedule (wait/warmup/active steps)
|
| 36 |
+
- Multi-rank profiling support
|
| 37 |
+
- Chrome trace export
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
config: Configuration object containing profiling parameters
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, config: ProfilerConfig, tool_config: Optional[TorchProfilerToolConfig] = None):
|
| 44 |
+
# note : if we do not set use_profile, it will be set as None, so that all function will be skip
|
| 45 |
+
if not config:
|
| 46 |
+
config = ProfilerConfig(ranks=[], enable=False)
|
| 47 |
+
if not tool_config:
|
| 48 |
+
assert not config.enable, "tool_config must be provided when profiler is enabled"
|
| 49 |
+
self.prof = None
|
| 50 |
+
self.saved = False
|
| 51 |
+
self.enable = config.enable
|
| 52 |
+
if not config.enable:
|
| 53 |
+
return
|
| 54 |
+
self.config = config
|
| 55 |
+
self.tool_config = tool_config
|
| 56 |
+
self.rank = torch.distributed.get_rank()
|
| 57 |
+
# we need to validate the config before using the profiler
|
| 58 |
+
self._validate()
|
| 59 |
+
if self.rank in self.config.profile_ranks:
|
| 60 |
+
print(f"[Profiler] Profiler init for rank {self.rank}")
|
| 61 |
+
|
| 62 |
+
self.prof = torch.profiler.profile(
|
| 63 |
+
activities=[
|
| 64 |
+
torch.profiler.ProfilerActivity.CPU,
|
| 65 |
+
torch.profiler.ProfilerActivity.CUDA,
|
| 66 |
+
],
|
| 67 |
+
schedule=torch.profiler.schedule(
|
| 68 |
+
wait=max(self.tool_config.step_start - 1, 0),
|
| 69 |
+
warmup=1 if self.tool_config.step_start > 0 else 0,
|
| 70 |
+
active=self.tool_config.step_end - self.tool_config.step_start,
|
| 71 |
+
repeat=1,
|
| 72 |
+
),
|
| 73 |
+
record_shapes=True,
|
| 74 |
+
with_stack=True,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
def _validate(self):
|
| 78 |
+
if self.enable:
|
| 79 |
+
if self.config.profile_ranks is None:
|
| 80 |
+
print("[WARNING] Profile ranks is not set, default to rank 0")
|
| 81 |
+
self.config.profile_ranks = [0]
|
| 82 |
+
assert self.tool_config.step_start >= 0, "[ERROR] Profile step start must be greater than 0"
|
| 83 |
+
assert self.tool_config.step_end >= 0, "[ERROR] Profile step end must be greater than 0"
|
| 84 |
+
assert self.tool_config.step_start < self.tool_config.step_end, (
|
| 85 |
+
"[ERROR] Profile step start must be less than step end"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def check(self):
|
| 89 |
+
return self.prof is not None and self.enable
|
| 90 |
+
|
| 91 |
+
def start(self):
|
| 92 |
+
if self.check():
|
| 93 |
+
print(f"[Profiler] started for rank {self.rank}")
|
| 94 |
+
self.prof.start()
|
| 95 |
+
|
| 96 |
+
def step(self):
|
| 97 |
+
if self.check():
|
| 98 |
+
self.prof.step()
|
| 99 |
+
|
| 100 |
+
def stop(self):
|
| 101 |
+
if self.check():
|
| 102 |
+
print(f"[Profiler] stopped for rank {self.rank}")
|
| 103 |
+
self.prof.stop()
|
| 104 |
+
|
| 105 |
+
def save(self):
|
| 106 |
+
if self.prof is not None and not self.saved:
|
| 107 |
+
if not os.path.exists(self.config.save_path):
|
| 108 |
+
os.makedirs(self.config.save_path)
|
| 109 |
+
save_file_name = f"/prof_start_{self.config.step_start}_end_{self.config.step_end}_rank_{self.rank}.json"
|
| 110 |
+
print(f"[Profiler] Saving trace to {self.config.save_path + save_file_name}")
|
| 111 |
+
self.prof.export_chrome_trace(self.config.save_path + save_file_name)
|
| 112 |
+
self.enable = False
|
| 113 |
+
self.saved = True
|
| 114 |
+
|
| 115 |
+
def stop_and_save(self):
|
| 116 |
+
if self.check():
|
| 117 |
+
self.stop()
|
| 118 |
+
self.save()
|
| 119 |
+
|
| 120 |
+
def stop_trace(self):
|
| 121 |
+
if self.check():
|
| 122 |
+
print(f"[Profiler] Trace stopped for rank {self.rank}")
|
| 123 |
+
self.enable = False
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def mark_start_range(
|
| 127 |
+
message: Optional[str] = None,
|
| 128 |
+
color: Optional[str] = None,
|
| 129 |
+
domain: Optional[str] = None,
|
| 130 |
+
category: Optional[str] = None,
|
| 131 |
+
) -> None:
|
| 132 |
+
"""Start a profiling range marker (no-op implementation).
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
message (Optional[str]): Message to associate with the range marker.
|
| 136 |
+
color (Optional[str]): Color for the marker visualization.
|
| 137 |
+
domain (Optional[str]): Domain for the marker.
|
| 138 |
+
category (Optional[str]): Category for the marker.
|
| 139 |
+
"""
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def mark_end_range(range_id: str) -> None:
|
| 144 |
+
"""End a profiling range marker (no-op implementation).
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
range_id (str): Identifier of the range to end.
|
| 148 |
+
"""
|
| 149 |
+
pass
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def mark_annotate(
|
| 153 |
+
message: Optional[str] = None,
|
| 154 |
+
color: Optional[str] = None,
|
| 155 |
+
domain: Optional[str] = None,
|
| 156 |
+
category: Optional[str] = None,
|
| 157 |
+
) -> Callable:
|
| 158 |
+
"""Decorator to annotate a function with profiling markers (no-op implementation).
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
message (Optional[str]): Message to associate with the annotation.
|
| 162 |
+
color (Optional[str]): Color for the marker visualization.
|
| 163 |
+
domain (Optional[str]): Domain for the marker.
|
| 164 |
+
category (Optional[str]): Category for the marker.
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
Callable: Decorator function that returns the original function unchanged.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
def decorator(func):
|
| 171 |
+
return func
|
| 172 |
+
|
| 173 |
+
return decorator
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class DistProfiler:
|
| 177 |
+
"""A dispatcher that delegates to specific profilers based on config.tool.
|
| 178 |
+
|
| 179 |
+
Supported tools:
|
| 180 |
+
- nsys: NsightSystemsProfiler
|
| 181 |
+
- npu: NPUProfiler (Ascend)
|
| 182 |
+
- torch: PyTorch torch.profiler wrapper
|
| 183 |
+
- torch_memory: Torch CUDA memory snapshot dump
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
def __init__(
|
| 187 |
+
self, rank: int, config: Optional[ProfilerConfig] = None, tool_config: Optional[object] = None, **kwargs
|
| 188 |
+
):
|
| 189 |
+
# Default config
|
| 190 |
+
if not config:
|
| 191 |
+
config = ProfilerConfig(ranks=[], enable=False)
|
| 192 |
+
|
| 193 |
+
self._impl = None
|
| 194 |
+
self._tool = getattr(config, "tool", None)
|
| 195 |
+
|
| 196 |
+
# Normalize rank selection
|
| 197 |
+
self._this_rank = False
|
| 198 |
+
if config.all_ranks:
|
| 199 |
+
self._this_rank = True
|
| 200 |
+
elif config.ranks:
|
| 201 |
+
self._this_rank = rank in config.ranks
|
| 202 |
+
else:
|
| 203 |
+
# default rank 0 if enabled but ranks unspecified
|
| 204 |
+
self._this_rank = (rank == 0) if config.enable else False
|
| 205 |
+
|
| 206 |
+
# Lazy import to avoid circular deps
|
| 207 |
+
if self._tool == "nsys":
|
| 208 |
+
from .nvtx_profile import NsightSystemsProfiler as _Nsight
|
| 209 |
+
|
| 210 |
+
self._impl = _Nsight(rank=rank, config=config, tool_config=tool_config, **kwargs)
|
| 211 |
+
elif self._tool == "npu":
|
| 212 |
+
from .mstx_profile import NPUProfiler as _Npu
|
| 213 |
+
|
| 214 |
+
self._impl = _Npu(rank=rank, config=config, tool_config=tool_config, **kwargs)
|
| 215 |
+
elif self._tool == "torch":
|
| 216 |
+
# Use the torch profiler wrapper defined above
|
| 217 |
+
self._impl = Profiler(config=config, tool_config=tool_config)
|
| 218 |
+
elif self._tool == "torch_memory":
|
| 219 |
+
self._impl = TorchMemoryProfiler(rank=rank, config=config, tool_config=tool_config)
|
| 220 |
+
else:
|
| 221 |
+
# Fallback to a no-op impl
|
| 222 |
+
self._impl = _NoOpProfiler()
|
| 223 |
+
|
| 224 |
+
def start(self, **kwargs):
|
| 225 |
+
return getattr(self._impl, "start", lambda **_: None)(**kwargs)
|
| 226 |
+
|
| 227 |
+
def stop(self):
|
| 228 |
+
return getattr(self._impl, "stop", lambda: None)()
|
| 229 |
+
|
| 230 |
+
@classmethod
|
| 231 |
+
def annotate(
|
| 232 |
+
cls,
|
| 233 |
+
message: Optional[str] = None,
|
| 234 |
+
color: Optional[str] = None,
|
| 235 |
+
domain: Optional[str] = None,
|
| 236 |
+
category: Optional[str] = None,
|
| 237 |
+
**kwargs_outer,
|
| 238 |
+
) -> Callable:
|
| 239 |
+
def decorator(func):
|
| 240 |
+
@functools.wraps(func)
|
| 241 |
+
def wrapper(self_instance, *args, **kwargs_inner):
|
| 242 |
+
profiler = getattr(self_instance, "profiler", None)
|
| 243 |
+
if not profiler:
|
| 244 |
+
return func(self_instance, *args, **kwargs_inner)
|
| 245 |
+
|
| 246 |
+
impl = profiler._impl
|
| 247 |
+
if hasattr(impl, "annotate"):
|
| 248 |
+
try:
|
| 249 |
+
actual_decorator = impl.annotate(
|
| 250 |
+
message=message, color=color, domain=domain, category=category, **kwargs_outer
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
return actual_decorator(func)(self_instance, *args, **kwargs_inner)
|
| 254 |
+
except Exception:
|
| 255 |
+
return func(self_instance, *args, **kwargs_inner)
|
| 256 |
+
return func(self_instance, *args, **kwargs_inner)
|
| 257 |
+
|
| 258 |
+
return wrapper
|
| 259 |
+
|
| 260 |
+
return decorator
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class _NoOpProfiler:
|
| 264 |
+
def start(self, **kwargs):
|
| 265 |
+
return
|
| 266 |
+
|
| 267 |
+
def stop(self):
|
| 268 |
+
return
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class TorchMemoryProfiler:
|
| 272 |
+
"""Profiler that dumps CUDA memory snapshots at step boundaries.
|
| 273 |
+
|
| 274 |
+
Behavior:
|
| 275 |
+
- On first construction (per process), enable memory history recording if CUDA is available
|
| 276 |
+
- On start(step=X), remember sub_dir for this step
|
| 277 |
+
- On stop(), dump a memory snapshot into config.save_path under the remembered sub_dir
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
_memory_history_enabled: bool = False
|
| 281 |
+
|
| 282 |
+
def __init__(
|
| 283 |
+
self, rank: int, config: Optional[ProfilerConfig], tool_config: Optional[TorchMemoryToolConfig] = None
|
| 284 |
+
):
|
| 285 |
+
# Always respond to explicit start/stop calls for torch_memory tool,
|
| 286 |
+
# regardless of per-role enable flag, to align with global step control.
|
| 287 |
+
self.enable = True
|
| 288 |
+
if not config:
|
| 289 |
+
config = ProfilerConfig(ranks=[])
|
| 290 |
+
self.config = config
|
| 291 |
+
self.rank = rank
|
| 292 |
+
self.this_step = False
|
| 293 |
+
self.sub_dir = None
|
| 294 |
+
self.sampler = MemorySnapshotSampler()
|
| 295 |
+
|
| 296 |
+
# Get parameters from tool_config, with fallback to defaults
|
| 297 |
+
if tool_config:
|
| 298 |
+
trace_alloc_max_entries = tool_config.trace_alloc_max_entries
|
| 299 |
+
stack_depth = tool_config.stack_depth
|
| 300 |
+
else:
|
| 301 |
+
trace_alloc_max_entries = 100_000
|
| 302 |
+
stack_depth = 32
|
| 303 |
+
|
| 304 |
+
# Best-effort enable memory history once
|
| 305 |
+
if not TorchMemoryProfiler._memory_history_enabled:
|
| 306 |
+
try:
|
| 307 |
+
enable_memory_visualize(trace_alloc_max_entries=trace_alloc_max_entries, stack_depth=stack_depth)
|
| 308 |
+
except Exception:
|
| 309 |
+
# silently ignore if not supported
|
| 310 |
+
pass
|
| 311 |
+
TorchMemoryProfiler._memory_history_enabled = True
|
| 312 |
+
|
| 313 |
+
def start(self, **kwargs):
|
| 314 |
+
if not self.enable:
|
| 315 |
+
return
|
| 316 |
+
if not self._should_profile_this_rank():
|
| 317 |
+
return
|
| 318 |
+
profile_step = kwargs.get("profile_step", None)
|
| 319 |
+
# Keep ranks aligned under same folder name
|
| 320 |
+
self.sub_dir = f"step{profile_step}" if profile_step is not None else None
|
| 321 |
+
self.this_step = True
|
| 322 |
+
|
| 323 |
+
def stop(self):
|
| 324 |
+
if not self.enable or not self.this_step:
|
| 325 |
+
return
|
| 326 |
+
self.this_step = False
|
| 327 |
+
if not self._should_profile_this_rank():
|
| 328 |
+
return
|
| 329 |
+
out_dir = self.config.save_path or "outputs/profile"
|
| 330 |
+
tag = "torch_memory"
|
| 331 |
+
# Dump snapshot; all ranks write into same sub_dir
|
| 332 |
+
try:
|
| 333 |
+
self.sampler.dump_memory_snapshot(out_dir=out_dir, tag=tag, sub_dir=self.sub_dir)
|
| 334 |
+
except Exception:
|
| 335 |
+
pass
|
| 336 |
+
|
| 337 |
+
def _should_profile_this_rank(self) -> bool:
|
| 338 |
+
if self.config.all_ranks:
|
| 339 |
+
return True
|
| 340 |
+
if self.config.ranks:
|
| 341 |
+
return self.rank in self.config.ranks
|
| 342 |
+
# default rank 0
|
| 343 |
+
return self.rank == 0
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class DistProfilerExtension:
|
| 347 |
+
"""An extension class for DistProfiler that provides distributed profiling capabilities.
|
| 348 |
+
|
| 349 |
+
It is intended for workers in verl that single controller invokes.
|
| 350 |
+
|
| 351 |
+
This class wraps a DistProfiler instance and provides methods to start/stop profiling
|
| 352 |
+
that can be dispatched across multiple ranks in a distributed training environment.
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
profiler (DistProfiler): The base distributed profiler instance to extend
|
| 356 |
+
"""
|
| 357 |
+
|
| 358 |
+
def __init__(self, profiler: DistProfiler):
|
| 359 |
+
self.profiler = profiler
|
| 360 |
+
|
| 361 |
+
from verl.single_controller.base.decorator import Dispatch, register
|
| 362 |
+
|
| 363 |
+
@register(dispatch_mode=Dispatch.ONE_TO_ALL)
|
| 364 |
+
def start_profile(self, **kwargs) -> None:
|
| 365 |
+
"""Start profiling for the current rank in the current training step."""
|
| 366 |
+
self.profiler.start(**kwargs)
|
| 367 |
+
|
| 368 |
+
@register(dispatch_mode=Dispatch.ONE_TO_ALL)
|
| 369 |
+
def stop_profile(self) -> None:
|
| 370 |
+
"""Stop profiling for the current rank in the current training step."""
|
| 371 |
+
self.profiler.stop()
|
verl/verl/utils/rendezvous/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
verl/verl/utils/rendezvous/ray_backend.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import ray
|
| 19 |
+
from cupy.cuda.nccl import NcclCommunicator, get_unique_id
|
| 20 |
+
from ray.util import list_named_actors
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@ray.remote
|
| 24 |
+
class NCCLIDStore:
|
| 25 |
+
def __init__(self, nccl_id):
|
| 26 |
+
self._nccl_id = nccl_id
|
| 27 |
+
|
| 28 |
+
def get(self):
|
| 29 |
+
return self._nccl_id
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_nccl_id_store_by_name(name):
|
| 33 |
+
all_actors = list_named_actors(all_namespaces=True)
|
| 34 |
+
matched_actors = [actor for actor in all_actors if actor.get("name", None) == name]
|
| 35 |
+
if len(matched_actors) == 1:
|
| 36 |
+
actor = matched_actors[0]
|
| 37 |
+
return ray.get_actor(**actor)
|
| 38 |
+
elif len(matched_actors) > 1:
|
| 39 |
+
logging.warning("multiple actors with same name found: %s", matched_actors)
|
| 40 |
+
elif len(matched_actors) == 0:
|
| 41 |
+
logging.info("failed to get any actor named %s", name)
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def create_nccl_communicator_in_ray(
|
| 46 |
+
rank: int, world_size: int, group_name: str, max_retries: int = 100, interval_s: int = 5
|
| 47 |
+
):
|
| 48 |
+
if rank == 0:
|
| 49 |
+
nccl_id = get_unique_id()
|
| 50 |
+
nccl_id_store = NCCLIDStore.options(name=group_name).remote(nccl_id)
|
| 51 |
+
|
| 52 |
+
assert ray.get(nccl_id_store.get.remote()) == nccl_id
|
| 53 |
+
communicator = NcclCommunicator(
|
| 54 |
+
ndev=world_size,
|
| 55 |
+
commId=nccl_id,
|
| 56 |
+
rank=0,
|
| 57 |
+
)
|
| 58 |
+
return communicator
|
| 59 |
+
else:
|
| 60 |
+
for i in range(max_retries):
|
| 61 |
+
nccl_id_store = get_nccl_id_store_by_name(group_name)
|
| 62 |
+
if nccl_id_store is not None:
|
| 63 |
+
logging.info("nccl_id_store %s got", group_name)
|
| 64 |
+
nccl_id = ray.get(nccl_id_store.get.remote())
|
| 65 |
+
logging.info("nccl id for %s got: %s", group_name, nccl_id)
|
| 66 |
+
communicator = NcclCommunicator(
|
| 67 |
+
ndev=world_size,
|
| 68 |
+
commId=nccl_id,
|
| 69 |
+
rank=rank,
|
| 70 |
+
)
|
| 71 |
+
return communicator
|
| 72 |
+
logging.info("failed to get nccl_id for %d time, sleep for %d seconds", i + 1, interval_s)
|
| 73 |
+
time.sleep(interval_s)
|
verl/verl/utils/reward_score/__init__.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
# from . import gsm8k, math, prime_math, prime_code
|
| 15 |
+
|
| 16 |
+
from verl.utils.import_utils import deprecated
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def default_compute_score(
|
| 20 |
+
data_source,
|
| 21 |
+
solution_str,
|
| 22 |
+
ground_truth,
|
| 23 |
+
extra_info=None,
|
| 24 |
+
sandbox_fusion_url=None,
|
| 25 |
+
concurrent_semaphore=None,
|
| 26 |
+
memory_limit_mb=None,
|
| 27 |
+
):
|
| 28 |
+
"""Compute the score for a given solution based on the data source.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
data_source (str): The source dataset identifier which determines the scoring method.
|
| 32 |
+
solution_str (str): The solution string to be evaluated.
|
| 33 |
+
ground_truth (str): The ground truth answer for comparison.
|
| 34 |
+
extra_info (dict, optional): Additional information that might be needed for scoring. Defaults to None.
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
float: The computed score as a floating point number. If the result is a dictionary,
|
| 38 |
+
it returns the dictionary instead.
|
| 39 |
+
|
| 40 |
+
Raises:
|
| 41 |
+
NotImplementedError: If the reward function is not implemented for the given data source.
|
| 42 |
+
"""
|
| 43 |
+
if data_source == "openai/gsm8k":
|
| 44 |
+
from . import gsm8k
|
| 45 |
+
|
| 46 |
+
res = gsm8k.compute_score(solution_str, ground_truth)
|
| 47 |
+
elif data_source in ["lighteval/MATH", "DigitalLearningGmbH/MATH-lighteval", "HuggingFaceH4/MATH-500"]:
|
| 48 |
+
from . import math_reward
|
| 49 |
+
|
| 50 |
+
res = math_reward.compute_score(solution_str, ground_truth)
|
| 51 |
+
# [Optional] Math-Verify Integration
|
| 52 |
+
# For enhanced accuracy, consider utilizing Math-Verify (https://github.com/huggingface/Math-Verify).
|
| 53 |
+
# Note: Math-Verify needs to be manually installed via pip: `pip install math-verify`.
|
| 54 |
+
# To use it, override the `compute_score` function with the following implementation:
|
| 55 |
+
|
| 56 |
+
# from . import math_verify
|
| 57 |
+
# res = math_verify.compute_score(solution_str, ground_truth)
|
| 58 |
+
elif data_source in ["math_dapo", "math", "math_dapo_reasoning"] or data_source.startswith("aime"):
|
| 59 |
+
from . import math_dapo
|
| 60 |
+
|
| 61 |
+
res = math_dapo.compute_score(solution_str, ground_truth)
|
| 62 |
+
elif data_source in [
|
| 63 |
+
"numina_aops_forum",
|
| 64 |
+
"numina_synthetic_math",
|
| 65 |
+
"numina_amc_aime",
|
| 66 |
+
"numina_synthetic_amc",
|
| 67 |
+
"numina_cn_k12",
|
| 68 |
+
"numina_olympiads",
|
| 69 |
+
]:
|
| 70 |
+
from . import prime_math
|
| 71 |
+
|
| 72 |
+
res = prime_math.compute_score(solution_str, ground_truth)
|
| 73 |
+
elif data_source in ["codecontests", "apps", "codeforces", "taco"]:
|
| 74 |
+
# Use the passed sandbox_fusion_url if available
|
| 75 |
+
if sandbox_fusion_url:
|
| 76 |
+
from . import sandbox_fusion
|
| 77 |
+
|
| 78 |
+
# Pass the URL directly, ground_truth likely contains test cases here
|
| 79 |
+
res = sandbox_fusion.compute_score(
|
| 80 |
+
sandbox_fusion_url, concurrent_semaphore, memory_limit_mb, solution_str, ground_truth, continuous=True
|
| 81 |
+
)
|
| 82 |
+
else:
|
| 83 |
+
# If no sandbox URL is provided, fall back to prime_code or raise error
|
| 84 |
+
from . import prime_code
|
| 85 |
+
|
| 86 |
+
# Assuming prime_code doesn't need the URL
|
| 87 |
+
res = prime_code.compute_score(solution_str, ground_truth, continuous=True)
|
| 88 |
+
elif data_source in ["hiyouga/geometry3k"]:
|
| 89 |
+
from . import geo3k
|
| 90 |
+
|
| 91 |
+
res = geo3k.compute_score(solution_str, ground_truth)
|
| 92 |
+
elif data_source in [
|
| 93 |
+
"searchR1_nq",
|
| 94 |
+
"searchR1_triviaqa",
|
| 95 |
+
"searchR1_popqa",
|
| 96 |
+
"searchR1_hotpotqa",
|
| 97 |
+
"searchR1_2wikimultihopqa",
|
| 98 |
+
"searchR1_musique",
|
| 99 |
+
"searchR1_bamboogle",
|
| 100 |
+
]:
|
| 101 |
+
from . import search_r1_like_qa_em
|
| 102 |
+
|
| 103 |
+
res = search_r1_like_qa_em.compute_score(solution_str, ground_truth)
|
| 104 |
+
|
| 105 |
+
else:
|
| 106 |
+
raise NotImplementedError(f"Reward function is not implemented for {data_source=}")
|
| 107 |
+
|
| 108 |
+
if isinstance(res, dict):
|
| 109 |
+
return res
|
| 110 |
+
elif isinstance(res, int | float | bool):
|
| 111 |
+
return float(res)
|
| 112 |
+
else:
|
| 113 |
+
return float(res[0])
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@deprecated("verl.utils.reward_score.default_compute_score")
|
| 117 |
+
def _default_compute_score(
|
| 118 |
+
data_source,
|
| 119 |
+
solution_str,
|
| 120 |
+
ground_truth,
|
| 121 |
+
extra_info=None,
|
| 122 |
+
sandbox_fusion_url=None,
|
| 123 |
+
concurrent_semaphore=None,
|
| 124 |
+
memory_limit_mb=None,
|
| 125 |
+
):
|
| 126 |
+
"""
|
| 127 |
+
Legacy function API to be deprecated. Please use `default_compute_score` instead.
|
| 128 |
+
"""
|
| 129 |
+
return default_compute_score(
|
| 130 |
+
data_source, solution_str, ground_truth, extra_info, sandbox_fusion_url, concurrent_semaphore, memory_limit_mb
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
__all__ = ["default_compute_score"]
|
verl/verl/utils/reward_score/geo3k.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import re
|
| 15 |
+
|
| 16 |
+
from mathruler.grader import extract_boxed_content, grade_answer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def format_reward(predict_str: str) -> float:
|
| 20 |
+
pattern = re.compile(r"<think>.*</think>.*\\boxed\{.*\}.*", re.DOTALL)
|
| 21 |
+
match_result = re.fullmatch(pattern, predict_str)
|
| 22 |
+
return 1.0 if match_result else 0.0
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def acc_reward(predict_str: str, ground_truth: str, use_boxed: bool = True) -> float:
|
| 26 |
+
if use_boxed:
|
| 27 |
+
answer = extract_boxed_content(predict_str)
|
| 28 |
+
else:
|
| 29 |
+
answer = predict_str
|
| 30 |
+
return 1.0 if grade_answer(answer, ground_truth) else 0.0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def compute_score(predict_str: str, ground_truth: str, use_boxed: bool = True, format_score: float = 0.1) -> float:
|
| 34 |
+
return (1.0 - format_score) * acc_reward(predict_str, ground_truth, use_boxed) + format_score * format_reward(
|
| 35 |
+
predict_str
|
| 36 |
+
)
|