Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- verl/docs/_static/custom.css +217 -0
- verl/docs/_static/js/resizable-sidebar.js +251 -0
- verl/docs/_static/js/runllm-widget.js +14 -0
- verl/docs/_static/logo.png +3 -0
- verl/docs/advance/agent_loop.rst +238 -0
- verl/docs/advance/checkpoint.rst +183 -0
- verl/docs/advance/dpo_extension.rst +273 -0
- verl/docs/advance/fsdp_extension.rst +97 -0
- verl/docs/advance/megatron_extension.rst +20 -0
- verl/docs/advance/one_step_off.md +308 -0
- verl/docs/advance/placement.rst +13 -0
- verl/docs/advance/ppo_lora.rst +87 -0
- verl/docs/advance/rollout_skip.rst +61 -0
- verl/docs/advance/rollout_trace.rst +125 -0
- verl/docs/advance/rope.rst +39 -0
- verl/docs/algo/baseline.md +77 -0
- verl/docs/algo/collabllm.md +105 -0
- verl/docs/algo/dapo.md +187 -0
- verl/docs/algo/entropy.md +115 -0
- verl/docs/algo/gpg.md +36 -0
- verl/docs/algo/grpo.md +71 -0
- verl/docs/algo/opo.md +33 -0
- verl/docs/algo/ppo.md +105 -0
- verl/docs/algo/spin.md +179 -0
- verl/docs/algo/sppo.md +52 -0
- verl/docs/amd_tutorial/amd_build_dockerfile_page.rst +796 -0
- verl/docs/amd_tutorial/amd_vllm_page.rst +105 -0
- verl/docs/api/data.rst +61 -0
- verl/docs/api/single_controller.rst +30 -0
- verl/docs/api/trainer.rst +31 -0
- verl/docs/api/utils.rst +76 -0
- verl/docs/ascend_tutorial/ascend_profiling_en.rst +132 -0
- verl/docs/ascend_tutorial/ascend_profiling_zh.rst +119 -0
- verl/docs/ascend_tutorial/ascend_quick_start.rst +224 -0
- verl/docs/ascend_tutorial/ascend_sglang_quick_start.rst +113 -0
- verl/docs/examples/config.rst +673 -0
- verl/docs/examples/gsm8k_example.rst +190 -0
- verl/docs/examples/multi_modal_example.rst +45 -0
- verl/docs/examples/ppo_code_architecture.rst +209 -0
- verl/docs/examples/sandbox_fusion_example.rst +54 -0
- verl/docs/examples/skypilot_examples.rst +146 -0
- verl/docs/faq/faq.rst +209 -0
- verl/docs/perf/device_tuning.rst +281 -0
- verl/docs/perf/dpsk.md +88 -0
- verl/docs/perf/nsight_profiling.md +94 -0
- verl/docs/perf/perf_tuning.rst +224 -0
- verl/docs/perf/verl_profiler_system.md +36 -0
- verl/docs/preparation/prepare_data.rst +128 -0
- verl/docs/preparation/reward_function.rst +71 -0
- verl/docs/sglang_multiturn/interaction_system.rst +417 -0
verl/docs/_static/custom.css
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Make the documentation use full screen width */
|
| 2 |
+
.wy-nav-content {
|
| 3 |
+
max-width: none !important;
|
| 4 |
+
width: 100% !important;
|
| 5 |
+
padding: 1.618em 3.236em !important;
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
/* Adjust the content wrapper - will be set by JavaScript */
|
| 9 |
+
.wy-nav-content-wrap {
|
| 10 |
+
margin-left: 300px;
|
| 11 |
+
transition: margin-left 0.2s ease;
|
| 12 |
+
width: auto !important;
|
| 13 |
+
position: relative !important;
|
| 14 |
+
background: white !important;
|
| 15 |
+
min-height: 100vh !important;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
/* Make the main content area responsive */
|
| 19 |
+
.rst-content {
|
| 20 |
+
max-width: none !important;
|
| 21 |
+
width: 100% !important;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
/* Optional: Adjust table widths to prevent overflow */
|
| 25 |
+
.rst-content table.docutils {
|
| 26 |
+
width: 100% !important;
|
| 27 |
+
table-layout: auto !important;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
/* Optional: Better code block width handling */
|
| 31 |
+
.rst-content .highlight {
|
| 32 |
+
width: 100% !important;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
/* Content area positioning already handled above */
|
| 36 |
+
|
| 37 |
+
/* Optional: Improve readability with some margin on very wide screens */
|
| 38 |
+
@media (min-width: 1400px) {
|
| 39 |
+
.wy-nav-content {
|
| 40 |
+
max-width: none !important;
|
| 41 |
+
margin: 0 auto !important;
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
/* Resizable sidebar styles */
|
| 46 |
+
.wy-nav-side {
|
| 47 |
+
position: fixed !important;
|
| 48 |
+
top: 0 !important;
|
| 49 |
+
bottom: 0 !important;
|
| 50 |
+
left: 0 !important;
|
| 51 |
+
width: 300px;
|
| 52 |
+
min-width: 200px;
|
| 53 |
+
max-width: 600px;
|
| 54 |
+
display: flex;
|
| 55 |
+
flex-direction: column;
|
| 56 |
+
z-index: 200 !important;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
/* Ensure sidebar header (logo, search) adapts to width */
|
| 60 |
+
.wy-side-nav-search {
|
| 61 |
+
width: 100% !important;
|
| 62 |
+
box-sizing: border-box !important;
|
| 63 |
+
padding: 0.809em 0.809em !important;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
.wy-side-nav-search input[type="text"] {
|
| 67 |
+
width: 100% !important;
|
| 68 |
+
box-sizing: border-box !important;
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
/* Make logo/title area responsive */
|
| 72 |
+
.wy-side-nav-search > div.version {
|
| 73 |
+
width: 100% !important;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
.wy-side-nav-search > a {
|
| 77 |
+
width: 100% !important;
|
| 78 |
+
display: block !important;
|
| 79 |
+
white-space: nowrap !important;
|
| 80 |
+
overflow: hidden !important;
|
| 81 |
+
text-overflow: ellipsis !important;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/* Responsive adjustments for narrow sidebar */
|
| 85 |
+
@media (max-width: 300px) {
|
| 86 |
+
.wy-side-nav-search > a {
|
| 87 |
+
font-size: 0.9em !important;
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
.wy-side-nav-search input[type="text"] {
|
| 91 |
+
font-size: 0.8em !important;
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
/* Ensure search input doesn't overflow */
|
| 96 |
+
.wy-side-nav-search form {
|
| 97 |
+
width: 100% !important;
|
| 98 |
+
margin: 0 !important;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
/* Make search icon responsive */
|
| 102 |
+
.wy-side-nav-search .wy-dropdown {
|
| 103 |
+
width: 100% !important;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
/* Adjust search results dropdown width */
|
| 107 |
+
.wy-side-nav-search .wy-dropdown-menu {
|
| 108 |
+
width: 100% !important;
|
| 109 |
+
max-width: none !important;
|
| 110 |
+
left: 0 !important;
|
| 111 |
+
right: 0 !important;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
/* Resize handle is created by JavaScript */
|
| 115 |
+
|
| 116 |
+
/* Make sure the sidebar content doesn't overflow */
|
| 117 |
+
.wy-side-scroll {
|
| 118 |
+
width: 100% !important;
|
| 119 |
+
flex: 1 !important;
|
| 120 |
+
overflow-y: auto !important;
|
| 121 |
+
overflow-x: hidden !important;
|
| 122 |
+
padding-right: 10px !important;
|
| 123 |
+
box-sizing: border-box !important;
|
| 124 |
+
scroll-behavior: auto !important; /* Prevent smooth scrolling on sidebar itself */
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
/* Ensure proper scroll behavior for main content area */
|
| 128 |
+
html {
|
| 129 |
+
scroll-behavior: smooth !important;
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
/* Ensure anchor links work properly in main content */
|
| 133 |
+
.wy-nav-content-wrap {
|
| 134 |
+
scroll-behavior: smooth !important;
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
/* Fix scroll to target for anchor links */
|
| 138 |
+
.rst-content {
|
| 139 |
+
scroll-behavior: smooth !important;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
/* Fix anchor scroll offset to account for fixed header */
|
| 143 |
+
.rst-content .section {
|
| 144 |
+
scroll-margin-top: 60px;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
/* Fix anchor scroll offset for headers */
|
| 148 |
+
.rst-content h1, .rst-content h2, .rst-content h3, .rst-content h4, .rst-content h5, .rst-content h6 {
|
| 149 |
+
scroll-margin-top: 60px;
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
/* Fix anchor scroll offset for specific scroll targets */
|
| 153 |
+
.rst-content .headerlink {
|
| 154 |
+
scroll-margin-top: 60px;
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
/* Fix sidebar navigation styling */
|
| 158 |
+
.wy-menu-vertical {
|
| 159 |
+
width: 100% !important;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
.wy-menu-vertical li {
|
| 163 |
+
width: 100% !important;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
.wy-menu-vertical a {
|
| 167 |
+
width: 100% !important;
|
| 168 |
+
word-wrap: break-word !important;
|
| 169 |
+
white-space: normal !important;
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
/* Content area margin is handled by JavaScript */
|
| 173 |
+
|
| 174 |
+
/* Custom drag handle (more visible) */
|
| 175 |
+
.resize-handle {
|
| 176 |
+
position: absolute;
|
| 177 |
+
top: 0;
|
| 178 |
+
right: 0;
|
| 179 |
+
width: 8px;
|
| 180 |
+
height: 100%;
|
| 181 |
+
background: #ccc;
|
| 182 |
+
cursor: col-resize;
|
| 183 |
+
z-index: 1001;
|
| 184 |
+
opacity: 0.3;
|
| 185 |
+
transition: opacity 0.2s ease;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
.resize-handle:hover {
|
| 189 |
+
opacity: 0.8;
|
| 190 |
+
background: #999;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
.resize-handle::before {
|
| 194 |
+
content: '';
|
| 195 |
+
position: absolute;
|
| 196 |
+
top: 50%;
|
| 197 |
+
left: 50%;
|
| 198 |
+
width: 2px;
|
| 199 |
+
height: 20px;
|
| 200 |
+
background: #666;
|
| 201 |
+
transform: translate(-50%, -50%);
|
| 202 |
+
border-radius: 1px;
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
.resize-handle:hover::before {
|
| 206 |
+
background: #333;
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
/* Ensure smooth resizing */
|
| 210 |
+
.wy-nav-side.resizing {
|
| 211 |
+
user-select: none;
|
| 212 |
+
pointer-events: none;
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
.wy-nav-side.resizing .wy-side-scroll {
|
| 216 |
+
overflow: hidden;
|
| 217 |
+
}
|
verl/docs/_static/js/resizable-sidebar.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Resizable sidebar functionality
|
| 2 |
+
document.addEventListener('DOMContentLoaded', function() {
|
| 3 |
+
const sidebar = document.querySelector('.wy-nav-side');
|
| 4 |
+
const content = document.querySelector('.wy-nav-content-wrap');
|
| 5 |
+
|
| 6 |
+
if (!sidebar || !content) return;
|
| 7 |
+
|
| 8 |
+
// Create resize handle
|
| 9 |
+
const resizeHandle = document.createElement('div');
|
| 10 |
+
resizeHandle.className = 'resize-handle';
|
| 11 |
+
sidebar.appendChild(resizeHandle);
|
| 12 |
+
|
| 13 |
+
let isResizing = false;
|
| 14 |
+
let startX = 0;
|
| 15 |
+
let startWidth = 0;
|
| 16 |
+
|
| 17 |
+
// Get initial width
|
| 18 |
+
const getInitialWidth = () => {
|
| 19 |
+
return 300; // Default width
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
// Save width to localStorage
|
| 23 |
+
const saveWidth = (width) => {
|
| 24 |
+
localStorage.setItem('sidebar-width', width);
|
| 25 |
+
};
|
| 26 |
+
|
| 27 |
+
// Load width from localStorage
|
| 28 |
+
const loadWidth = () => {
|
| 29 |
+
const savedWidth = localStorage.getItem('sidebar-width');
|
| 30 |
+
if (savedWidth) {
|
| 31 |
+
const width = parseInt(savedWidth, 10);
|
| 32 |
+
if (width >= 200 && width <= 600) {
|
| 33 |
+
return width;
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
return getInitialWidth();
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
// Apply width to sidebar and content
|
| 40 |
+
const applyWidth = (width) => {
|
| 41 |
+
// Update sidebar width
|
| 42 |
+
sidebar.style.width = width + 'px';
|
| 43 |
+
|
| 44 |
+
// Update content margin with !important to override any CSS
|
| 45 |
+
content.style.setProperty('margin-left', width + 'px', 'important');
|
| 46 |
+
|
| 47 |
+
// Also update any other content wrapper that might exist
|
| 48 |
+
const contentInner = document.querySelector('.wy-nav-content');
|
| 49 |
+
if (contentInner) {
|
| 50 |
+
contentInner.style.setProperty('margin-left', '0px', 'important');
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
// Force reflow and repaint
|
| 54 |
+
sidebar.offsetHeight;
|
| 55 |
+
content.offsetHeight;
|
| 56 |
+
|
| 57 |
+
// Trigger window resize event to notify other components
|
| 58 |
+
window.dispatchEvent(new Event('resize'));
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
// Initialize with saved width
|
| 62 |
+
const initialWidth = loadWidth();
|
| 63 |
+
applyWidth(initialWidth);
|
| 64 |
+
|
| 65 |
+
// Mouse down on resize handle
|
| 66 |
+
resizeHandle.addEventListener('mousedown', (e) => {
|
| 67 |
+
isResizing = true;
|
| 68 |
+
startX = e.clientX;
|
| 69 |
+
startWidth = parseInt(window.getComputedStyle(sidebar).width, 10);
|
| 70 |
+
|
| 71 |
+
sidebar.classList.add('resizing');
|
| 72 |
+
document.body.style.cursor = 'col-resize';
|
| 73 |
+
document.body.style.userSelect = 'none';
|
| 74 |
+
|
| 75 |
+
// Add overlay to prevent iframe issues
|
| 76 |
+
const overlay = document.createElement('div');
|
| 77 |
+
overlay.style.cssText = `
|
| 78 |
+
position: fixed;
|
| 79 |
+
top: 0;
|
| 80 |
+
left: 0;
|
| 81 |
+
width: 100%;
|
| 82 |
+
height: 100%;
|
| 83 |
+
z-index: 9999;
|
| 84 |
+
cursor: col-resize;
|
| 85 |
+
`;
|
| 86 |
+
overlay.id = 'resize-overlay';
|
| 87 |
+
document.body.appendChild(overlay);
|
| 88 |
+
|
| 89 |
+
e.preventDefault();
|
| 90 |
+
});
|
| 91 |
+
|
| 92 |
+
// Mouse move
|
| 93 |
+
document.addEventListener('mousemove', (e) => {
|
| 94 |
+
if (!isResizing) return;
|
| 95 |
+
|
| 96 |
+
const width = startWidth + e.clientX - startX;
|
| 97 |
+
const clampedWidth = Math.max(200, Math.min(600, width));
|
| 98 |
+
applyWidth(clampedWidth);
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
// Mouse up
|
| 102 |
+
document.addEventListener('mouseup', () => {
|
| 103 |
+
if (!isResizing) return;
|
| 104 |
+
|
| 105 |
+
isResizing = false;
|
| 106 |
+
sidebar.classList.remove('resizing');
|
| 107 |
+
document.body.style.cursor = '';
|
| 108 |
+
document.body.style.userSelect = '';
|
| 109 |
+
|
| 110 |
+
// Remove overlay
|
| 111 |
+
const overlay = document.getElementById('resize-overlay');
|
| 112 |
+
if (overlay) {
|
| 113 |
+
overlay.remove();
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// Save the current width
|
| 117 |
+
const currentWidth = parseInt(window.getComputedStyle(sidebar).width, 10);
|
| 118 |
+
saveWidth(currentWidth);
|
| 119 |
+
});
|
| 120 |
+
|
| 121 |
+
// Handle window resize - removed to prevent infinite loop
|
| 122 |
+
// The sidebar width is fixed and managed by drag functionality, no need to recalculate on window resize
|
| 123 |
+
|
| 124 |
+
// Double-click to reset to default width
|
| 125 |
+
resizeHandle.addEventListener('dblclick', () => {
|
| 126 |
+
const defaultWidth = 300;
|
| 127 |
+
applyWidth(defaultWidth);
|
| 128 |
+
saveWidth(defaultWidth);
|
| 129 |
+
});
|
| 130 |
+
});
|
| 131 |
+
|
| 132 |
+
// Fix navigation issues - Using MutationObserver for reliable initialization
|
| 133 |
+
document.addEventListener('DOMContentLoaded', function() {
|
| 134 |
+
let navigationFixed = false;
|
| 135 |
+
|
| 136 |
+
function setupNavigationFix() {
|
| 137 |
+
if (navigationFixed) return;
|
| 138 |
+
|
| 139 |
+
// Find all links in the sidebar
|
| 140 |
+
const sidebarLinks = document.querySelectorAll('.wy-menu-vertical a');
|
| 141 |
+
|
| 142 |
+
// Only proceed if we have sidebar links
|
| 143 |
+
if (sidebarLinks.length === 0) return;
|
| 144 |
+
|
| 145 |
+
console.log('Setting up navigation fix...');
|
| 146 |
+
|
| 147 |
+
sidebarLinks.forEach(function(link) {
|
| 148 |
+
const href = link.getAttribute('href');
|
| 149 |
+
|
| 150 |
+
// Clone the link to remove all existing event listeners
|
| 151 |
+
const newLink = link.cloneNode(true);
|
| 152 |
+
|
| 153 |
+
// Add our own click handler
|
| 154 |
+
newLink.addEventListener('click', function(e) {
|
| 155 |
+
console.log('Link clicked:', href);
|
| 156 |
+
|
| 157 |
+
// If it's an anchor link within the same page
|
| 158 |
+
if (href && href.startsWith('#') && href !== '#') {
|
| 159 |
+
e.preventDefault();
|
| 160 |
+
e.stopPropagation();
|
| 161 |
+
|
| 162 |
+
const targetId = href.substring(1);
|
| 163 |
+
const targetElement = document.getElementById(targetId);
|
| 164 |
+
|
| 165 |
+
if (targetElement) {
|
| 166 |
+
// Calculate offset for fixed header
|
| 167 |
+
const headerHeight = 60;
|
| 168 |
+
const elementPosition = targetElement.getBoundingClientRect().top;
|
| 169 |
+
const offsetPosition = elementPosition + window.pageYOffset - headerHeight;
|
| 170 |
+
|
| 171 |
+
window.scrollTo({
|
| 172 |
+
top: offsetPosition,
|
| 173 |
+
behavior: 'smooth'
|
| 174 |
+
});
|
| 175 |
+
|
| 176 |
+
// Update URL hash
|
| 177 |
+
if (history.pushState) {
|
| 178 |
+
history.pushState(null, null, '#' + targetId);
|
| 179 |
+
} else {
|
| 180 |
+
location.hash = '#' + targetId;
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
// For external links, navigate normally
|
| 185 |
+
else if (href && !href.startsWith('#') && !href.startsWith('javascript:')) {
|
| 186 |
+
console.log('Navigating to external link:', href);
|
| 187 |
+
window.location.href = href;
|
| 188 |
+
}
|
| 189 |
+
});
|
| 190 |
+
|
| 191 |
+
// Replace the old link with the new one
|
| 192 |
+
link.parentNode.replaceChild(newLink, link);
|
| 193 |
+
});
|
| 194 |
+
|
| 195 |
+
navigationFixed = true;
|
| 196 |
+
|
| 197 |
+
// Handle initial page load with hash
|
| 198 |
+
if (window.location.hash) {
|
| 199 |
+
// Use requestAnimationFrame for better timing
|
| 200 |
+
requestAnimationFrame(() => {
|
| 201 |
+
const targetId = window.location.hash.substring(1);
|
| 202 |
+
const targetElement = document.getElementById(targetId);
|
| 203 |
+
if (targetElement) {
|
| 204 |
+
const headerHeight = 60;
|
| 205 |
+
const elementPosition = targetElement.getBoundingClientRect().top;
|
| 206 |
+
const offsetPosition = elementPosition + window.pageYOffset - headerHeight;
|
| 207 |
+
|
| 208 |
+
window.scrollTo({
|
| 209 |
+
top: offsetPosition,
|
| 210 |
+
behavior: 'smooth'
|
| 211 |
+
});
|
| 212 |
+
}
|
| 213 |
+
});
|
| 214 |
+
}
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
// Try to set up navigation fix immediately
|
| 218 |
+
setupNavigationFix();
|
| 219 |
+
|
| 220 |
+
// If it didn't work, use MutationObserver to watch for when sidebar links are added
|
| 221 |
+
if (!navigationFixed) {
|
| 222 |
+
const observer = new MutationObserver(function(mutations) {
|
| 223 |
+
mutations.forEach(function(mutation) {
|
| 224 |
+
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
|
| 225 |
+
// Check if sidebar links were added
|
| 226 |
+
const sidebarLinks = document.querySelectorAll('.wy-menu-vertical a');
|
| 227 |
+
if (sidebarLinks.length > 0) {
|
| 228 |
+
setupNavigationFix();
|
| 229 |
+
if (navigationFixed) {
|
| 230 |
+
observer.disconnect();
|
| 231 |
+
}
|
| 232 |
+
}
|
| 233 |
+
}
|
| 234 |
+
});
|
| 235 |
+
});
|
| 236 |
+
|
| 237 |
+
// Start observing the document for changes
|
| 238 |
+
observer.observe(document.body, {
|
| 239 |
+
childList: true,
|
| 240 |
+
subtree: true
|
| 241 |
+
});
|
| 242 |
+
|
| 243 |
+
// Fallback timeout in case MutationObserver doesn't work
|
| 244 |
+
setTimeout(function() {
|
| 245 |
+
if (!navigationFixed) {
|
| 246 |
+
setupNavigationFix();
|
| 247 |
+
}
|
| 248 |
+
observer.disconnect();
|
| 249 |
+
}, 5000);
|
| 250 |
+
}
|
| 251 |
+
});
|
verl/docs/_static/js/runllm-widget.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
document.addEventListener("DOMContentLoaded", function () {
|
| 2 |
+
var script = document.createElement("script");
|
| 3 |
+
script.type = "module";
|
| 4 |
+
script.id = "runllm-widget-script";
|
| 5 |
+
script.src = "https://widget.runllm.com";
|
| 6 |
+
script.setAttribute("version", "stable");
|
| 7 |
+
script.setAttribute("crossorigin", "true");
|
| 8 |
+
script.setAttribute("runllm-keyboard-shortcut", "Mod+j");
|
| 9 |
+
script.setAttribute("runllm-name", "verl Chatbot");
|
| 10 |
+
script.setAttribute("runllm-position", "TOP_RIGHT");
|
| 11 |
+
script.setAttribute("runllm-assistant-id", "679");
|
| 12 |
+
script.async = true;
|
| 13 |
+
document.head.appendChild(script);
|
| 14 |
+
});
|
verl/docs/_static/logo.png
ADDED
|
Git LFS Details
|
verl/docs/advance/agent_loop.rst
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Agent Loop
|
| 2 |
+
==========
|
| 3 |
+
|
| 4 |
+
Last updated: 07/17/2025.
|
| 5 |
+
|
| 6 |
+
.. versionadded:: 0.4.2
|
| 7 |
+
[status: alpha]
|
| 8 |
+
|
| 9 |
+
.. warning::
|
| 10 |
+
Agent Loop is ready for use, but the API may change in future releaes.
|
| 11 |
+
|
| 12 |
+
Agent Loop is designed as general interface for multi-turn rollout and agentic reinforcement learning.
|
| 13 |
+
|
| 14 |
+
**Design goal**:
|
| 15 |
+
|
| 16 |
+
- Plugable user defined agent loop
|
| 17 |
+
- Provide standard request generate api with different inference frameworks
|
| 18 |
+
- Provide request level load balance between multiple inference servers
|
| 19 |
+
|
| 20 |
+
**Non-goal**:
|
| 21 |
+
|
| 22 |
+
- How tool is defined and how to call tool
|
| 23 |
+
|
| 24 |
+
In high level overview, agent loop is given a prompt, run user defined loop: call LLM generate api, call tools, ...
|
| 25 |
+
and return the final output. The final output is then calculated reward and used as trajectory for RL training.
|
| 26 |
+
|
| 27 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/agent_loop_overview.svg?raw=true
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
API Design
|
| 31 |
+
----------
|
| 32 |
+
|
| 33 |
+
``AgentLoopBase`` class is the abstraction of agent loop, and ``run`` method is the only interface that user need to implement.
|
| 34 |
+
The run method, given prompt messages in format: [{"role": "user"}, {"content": "..."}], and additional sampling params,
|
| 35 |
+
could do whatever user wants, such as
|
| 36 |
+
|
| 37 |
+
- call LLM generate api
|
| 38 |
+
- call tools: web search, database query, code sandbox, ...
|
| 39 |
+
- environment interaction
|
| 40 |
+
- reflection
|
| 41 |
+
- ...
|
| 42 |
+
|
| 43 |
+
.. code:: python
|
| 44 |
+
|
| 45 |
+
class AgentLoopBase(ABC):
|
| 46 |
+
@abstractmethod
|
| 47 |
+
async def run(self, sampling_params: dict[str, Any], **kwargs) -> AgentLoopOutput:
|
| 48 |
+
"""Run agent loop to interact with LLM server and environment.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
sampling_params (Dict[str, Any]): LLM sampling params.
|
| 52 |
+
**kwargs: dataset fields from `verl.utils.dataset.RLHFDataset`.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
AgentLoopOutput: Agent loop output.
|
| 56 |
+
"""
|
| 57 |
+
raise NotImplementedError
|
| 58 |
+
|
| 59 |
+
After running user defined loop, run method should return ``AgentLoopOutput``, including prompt token ids,
|
| 60 |
+
response token ids, and response mask.
|
| 61 |
+
|
| 62 |
+
.. code:: python
|
| 63 |
+
|
| 64 |
+
class AgentLoopOutput(BaseModel):
|
| 65 |
+
"""Agent loop output."""
|
| 66 |
+
|
| 67 |
+
prompt_ids: list[int]
|
| 68 |
+
"""Prompt token ids."""
|
| 69 |
+
response_ids: list[int]
|
| 70 |
+
"""Response token ids including LLM generated token, tool response token."""
|
| 71 |
+
response_mask: list[int]
|
| 72 |
+
"""Response mask, 1 for LLM generated token, 0 for tool response token."""
|
| 73 |
+
|
| 74 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/agent_loop_output.svg?raw=true
|
| 75 |
+
|
| 76 |
+
.. note:: AgentLoopOutput only output one trajectory for a given prompt, multiple trajectories output is still under discussion.
|
| 77 |
+
|
| 78 |
+
Architecture Design
|
| 79 |
+
-------------------
|
| 80 |
+
|
| 81 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/agent_loop_architecture.png?raw=true
|
| 82 |
+
|
| 83 |
+
A single PPO step contain two phase: rollout and train. In rollout phase:
|
| 84 |
+
|
| 85 |
+
1. PPOTrainer sample a batch from dataset and call ``AgentLoopManager.generate_sequences``.
|
| 86 |
+
2. AgentLoopManager ``wake_up`` all async LLM server instances, which will sync weights between inference engine(vLLM/SGLang) and training engine(FSDP/Megatron-LM).
|
| 87 |
+
3. AgentLoopManager split batch into chunks and send each chunk to ``AgentLoopWorker``.
|
| 88 |
+
4. AgentLoopWorker receive chunk and for each prompt, spawn a user defined ``AgentLoopBase`` instance, run ``run`` coroutine until end and get ``AgentLoopOutput``.
|
| 89 |
+
|
| 90 |
+
.. tip::
|
| 91 |
+
AgentLoopWorker schedules multiple coroutines concurrently. If number of AgentLoopWorker equals batch_size, then each worker is response for one prompt.
|
| 92 |
+
|
| 93 |
+
In agent loop, when user need LLM generate response:
|
| 94 |
+
|
| 95 |
+
5. Call ``AsyncLLMServerManager.generate`` with prompt_ids.
|
| 96 |
+
6. AsyncLLMServerManager select a server instance with least request in first turn and send request to it. (In following turns, the request will be sent to the same server instance).
|
| 97 |
+
7. AsyncLLMServer receive a request, issue ipc/rpc with model_runner, and generate response. (There's slight differences between vLLM and SGLang, see below).
|
| 98 |
+
|
| 99 |
+
When all prompts in all AgentLoopWorker finish, AgentLoopManager gather results and return to PPOTrainer.
|
| 100 |
+
|
| 101 |
+
8. AgentLoopManager ``sleep`` all server instances, which will free kv cache and offload weights to CPU memory.
|
| 102 |
+
|
| 103 |
+
AsyncLLMServer
|
| 104 |
+
~~~~~~~~~~~~~~
|
| 105 |
+
|
| 106 |
+
AsyncLLMServer is the abstraction of LLM server with two types of generation api:
|
| 107 |
+
|
| 108 |
+
- `OpenAI chat completion <https://platform.openai.com/docs/api-reference/chat>`_: generate response for the given chat conversation.
|
| 109 |
+
- Token in token out: generate response ids for the given token ids.
|
| 110 |
+
|
| 111 |
+
We have officially supported vLLM and SGLang AsyncLLMServer, both of them implement the two api and are well tested.
|
| 112 |
+
Other inference engine should be easy to plug-in by implement the ``AsyncServerBase`` class.
|
| 113 |
+
|
| 114 |
+
.. code:: python
|
| 115 |
+
|
| 116 |
+
class AsyncServerBase(ABC):
|
| 117 |
+
@abstractmethod
|
| 118 |
+
async def chat_completion(self, raw_request: Request) -> JSONResponse:
|
| 119 |
+
"""OpenAI chat completion API.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
raw_request (Request): raw json request
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
JSONResponse: json response
|
| 126 |
+
|
| 127 |
+
API reference: https://platform.openai.com/docs/api-reference/chat/create
|
| 128 |
+
"""
|
| 129 |
+
raise NotImplementedError
|
| 130 |
+
|
| 131 |
+
@abstractmethod
|
| 132 |
+
async def generate(self, prompt_ids: list[int], sampling_params: dict[str, Any], request_id: str) -> list[int]:
|
| 133 |
+
"""Generate response ids given prompt ids.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
prompt_ids (List[int]): prompt ids
|
| 137 |
+
sampling_params (Dict[str, Any]): sampling params
|
| 138 |
+
request_id (str): request id
|
| 139 |
+
|
| 140 |
+
Returns:
|
| 141 |
+
List[int]: response ids
|
| 142 |
+
"""
|
| 143 |
+
raise NotImplementedError
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
Chat completion vs Token in token out
|
| 147 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 148 |
+
|
| 149 |
+
.. warning::
|
| 150 |
+
The following conclusion is based on our recent experience and is still open to investigation and discussion.
|
| 151 |
+
|
| 152 |
+
Almost all agent frameworks (LangGraph, CrewAI, LlamaIndex, etc) call LLM with OpenAI chat completion api, and
|
| 153 |
+
keep chat history as messages. So user may expect that we should use the chat completion api in multi-turn rollout.
|
| 154 |
+
|
| 155 |
+
But based on our recent experience on single-turn training on DAPO and multi-turn training on `retool <https://github.com/volcengine/verl/tree/main/recipe/retool>`_,
|
| 156 |
+
we found the token_ids from apply the final messages may not equal to the token_ids by concat prompt_ids and response_ids in each turn.
|
| 157 |
+
|
| 158 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/multi_turn.png?raw=true
|
| 159 |
+
|
| 160 |
+
**Where does this inconsistency happened?**
|
| 161 |
+
|
| 162 |
+
First, the tool parser may alter the content. For example
|
| 163 |
+
|
| 164 |
+
.. code:: json
|
| 165 |
+
|
| 166 |
+
{"role": "assistant", "content": "Let me call a <tool_call>...</tool_call> and get the result"}
|
| 167 |
+
|
| 168 |
+
After tool_calls extraction, the messages is like this:
|
| 169 |
+
|
| 170 |
+
.. code:: json
|
| 171 |
+
|
| 172 |
+
{"role": "assistant", "content": "Let me call a and get the result", "tool_calls": [{"name": "foo", "arguments": "{}"}]}
|
| 173 |
+
|
| 174 |
+
Encode the extracted message back is not equal to the original LLM generated response_ids.
|
| 175 |
+
|
| 176 |
+
Second, the `decode-encode` may also lead to inconsistency: `Agent-R1 issue#30 <https://github.com/0russwest0/Agent-R1/issues/30#issuecomment-2826155367>`_.
|
| 177 |
+
|
| 178 |
+
**What is the impact of this inconsistency?**
|
| 179 |
+
|
| 180 |
+
This inconsistency is not a big problem for serving/agent system, but is critical to RL training.
|
| 181 |
+
It causes the trajectory deviate from the policy model distribution. We have observed that apply_chat_template
|
| 182 |
+
to the final chat history messages make PPO training not even converged in single-turn.
|
| 183 |
+
|
| 184 |
+
vLLM
|
| 185 |
+
^^^^
|
| 186 |
+
|
| 187 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/async_vllm.png?raw=true
|
| 188 |
+
|
| 189 |
+
For vLLM, the Async LLM Engine is running in same process as the server, and ModelRunner is running in same process as FSDP/Megatron-LM workers.
|
| 190 |
+
Async LLM Engine communicate with ModelRunner through ZeroMQ. When server receive a request, it directly call engine to generate response_ids.
|
| 191 |
+
|
| 192 |
+
SGLang
|
| 193 |
+
^^^^^^
|
| 194 |
+
|
| 195 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/async_sglang.png?raw=true
|
| 196 |
+
|
| 197 |
+
For SGLang, the Async LLM Engine is running in same process as FSDP/Megatron-LM worker-0, and it spawn multiple subprocesses as ModelRunner.
|
| 198 |
+
Also, Async LLM Engine communicate with ModelRunner through ZeroMQ. When server receive a request, it remote call the worker-0 and get response_ids.
|
| 199 |
+
|
| 200 |
+
AsyncLLMServerManager
|
| 201 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 202 |
+
|
| 203 |
+
AsyncLLMServerManager serve as proxy to multiple AsyncLLMServer instances, provides:
|
| 204 |
+
|
| 205 |
+
- load balance: select a server instance with least request in first turn and send request to it.
|
| 206 |
+
- sticky session: bind request_id to server instance, so that the same request_id will be sent to the same server instance in following turns.
|
| 207 |
+
|
| 208 |
+
AsyncLLMServerManager is passed to ``AgentLoopBase.__init__``, whenever user want to interact with LLM in agent loop,
|
| 209 |
+
they can call ``AsyncLLMServerManager.generate`` to generate response_ids.
|
| 210 |
+
|
| 211 |
+
.. code:: python
|
| 212 |
+
|
| 213 |
+
class AsyncLLMServerManager:
|
| 214 |
+
async def generate(
|
| 215 |
+
self,
|
| 216 |
+
request_id,
|
| 217 |
+
*,
|
| 218 |
+
prompt_ids: list[int],
|
| 219 |
+
sampling_params: dict[str, Any],
|
| 220 |
+
) -> list[int]:
|
| 221 |
+
"""Generate tokens from prompt ids.
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
request_id (str): request id for sticky session.
|
| 225 |
+
prompt_ids (List[int]): List of prompt token ids.
|
| 226 |
+
sampling_params (Dict[str, Any]): Sampling parameters for the chat completion.
|
| 227 |
+
|
| 228 |
+
Returns:
|
| 229 |
+
List[int]: List of generated token ids.
|
| 230 |
+
"""
|
| 231 |
+
...
|
| 232 |
+
|
| 233 |
+
Next
|
| 234 |
+
----
|
| 235 |
+
|
| 236 |
+
- :doc:`Agentic RL Training<../start/agentic_rl>`: Quick start agentic RL training with gsm8k dataset.
|
| 237 |
+
- `LangGraph MathExpression <https://github.com/volcengine/verl/tree/main/recipe/langgraph_agent/example>`_: Demonstrate how to use LangGraph to build agent loop.
|
| 238 |
+
- `Retool <https://github.com/volcengine/verl/tree/main/recipe/retool>`_: End-to-end retool paper reproduction using tool agent.
|
verl/docs/advance/checkpoint.rst
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _checkpoint-page:
|
| 2 |
+
|
| 3 |
+
Using Checkpoints to Support Fault Tolerance Training
|
| 4 |
+
=====================================================
|
| 5 |
+
|
| 6 |
+
Last updated: 06/25/2025.
|
| 7 |
+
|
| 8 |
+
There could be training errors or machine failure during the whole RLHF training process,
|
| 9 |
+
so it is recommended to enable checkpoints to minimize your loss.
|
| 10 |
+
|
| 11 |
+
The API Interface has already been listed in :ref:`config-explain-page`,
|
| 12 |
+
and we will not repeat them. But there are still some technique details
|
| 13 |
+
we hope to clarify.
|
| 14 |
+
|
| 15 |
+
.. note::
|
| 16 |
+
|
| 17 |
+
Notice that the ``checkpoint.contents`` field has no effect to FSDP checkpoint except ``hf_model``,
|
| 18 |
+
the other 3 fields are binded together to save and load. We recommend to include ``model``, ``optimizer`` and ``extra`` all.
|
| 19 |
+
|
| 20 |
+
Checkpoint Saving Directory Structure
|
| 21 |
+
-------------------------------------
|
| 22 |
+
|
| 23 |
+
Commonly, we use the ``default_local_dir`` declared in ``ppo_trainer.yaml`` or ``ppo_megatron_trainer.yml``
|
| 24 |
+
to work as preffix when saving checkpoints, which is ``checkpoints/${trainer.project_name}/${trainer.experiment_name}``.
|
| 25 |
+
|
| 26 |
+
So the inner checkpoint structure of **FSDP** is like:
|
| 27 |
+
|
| 28 |
+
.. code::
|
| 29 |
+
|
| 30 |
+
checkpoints/${trainer.project_name}/${trainer.experiment_name}
|
| 31 |
+
├── global_steps_${i}
|
| 32 |
+
│ ├── actor
|
| 33 |
+
│ │ ├── huggingface # default save config and tokenizer, save huggingface model if include ``hf_model`` in checkpoint.contents
|
| 34 |
+
│ │ └── fsdp_config.json # FSDP config file, including world_size and fsdp version
|
| 35 |
+
│ │ ├── model_world_size_{self.world_size}_rank_{self.rank}.pt
|
| 36 |
+
│ │ ├── optim_world_size_{self.world_size}_rank_{self.rank}.pt
|
| 37 |
+
│ │ └── extra_state_world_size_{self.world_size}_rank_{self.rank}.pt
|
| 38 |
+
│ ├── critic
|
| 39 |
+
│ │ ├── huggingface
|
| 40 |
+
│ │ └── fsdp_config.json
|
| 41 |
+
│ │ ├── model_world_size_{self.world_size}_rank_{self.rank}.pt
|
| 42 |
+
│ │ ├── optim_world_size_{self.world_size}_rank_{self.rank}.pt
|
| 43 |
+
│ │ └── extra_state_world_size_{self.world_size}_rank_{self.rank}.pt
|
| 44 |
+
└── latest_checkpointed_iteration.txt
|
| 45 |
+
|
| 46 |
+
All model shards, optimizers and extra states are stored together, in a sharded and distributed way.
|
| 47 |
+
|
| 48 |
+
While **Megatron** current checkpoint structure is:
|
| 49 |
+
|
| 50 |
+
.. code::
|
| 51 |
+
|
| 52 |
+
checkpoints/${trainer.project_name}/${trainer.experiment_name}
|
| 53 |
+
├── global_steps_${i}
|
| 54 |
+
│ ├── actor
|
| 55 |
+
│ │ ├── huggingface # default save config and tokenizer, save huggingface model if include ``hf_mode`` in checkpoint.contents
|
| 56 |
+
│ │ └── dist_ckpt # save sharded model/optimizer/rng_states, naming the same as Megatron
|
| 57 |
+
│ └── critic
|
| 58 |
+
│ │ ├── huggingface
|
| 59 |
+
│ │ └── dist_ckpt
|
| 60 |
+
└── latest_checkpointed_iteration.txt
|
| 61 |
+
|
| 62 |
+
Convert FSDP and Megatron Checkpoints to HuggingFace Format Model
|
| 63 |
+
-----------------------------------------------------------------
|
| 64 |
+
|
| 65 |
+
We provide a tool to convert the FSDP and Megatron checkpoints to HuggingFace format model.
|
| 66 |
+
The tool is located in ``verl/model_merger``. For older versions of verl that don't include fsdp_config.json in checkpoints, you can use the legacy model merger located at ``verl/scripts/legacy_model_merger.py``.
|
| 67 |
+
|
| 68 |
+
The script supports two main sub-commands: `merge` (to convert and save checkpoints) and `test` (to validate merged checkpoints against a reference model).
|
| 69 |
+
The arguments for the `merge` sub-command are as follows:
|
| 70 |
+
|
| 71 |
+
.. code:: bash
|
| 72 |
+
|
| 73 |
+
usage: python -m verl.model_merger merge [-h] --backend {fsdp,megatron} [--local_dir LOCAL_DIR] [--tie-word-embedding] [--is-value-model] [--use_cpu_initialization] [--target_dir TARGET_DIR]
|
| 74 |
+
[--hf_upload_path HF_UPLOAD_PATH] [--private]
|
| 75 |
+
|
| 76 |
+
options:
|
| 77 |
+
-h, --help show this help message and exit
|
| 78 |
+
--backend {fsdp,megatron}
|
| 79 |
+
The backend of the model
|
| 80 |
+
--local_dir LOCAL_DIR
|
| 81 |
+
Path to the saved model checkpoints
|
| 82 |
+
--tie-word-embedding Whether to tie word embedding weights (currently only Megatron supported)
|
| 83 |
+
--is-value-model Whether the model is a value model (currently only Megatron supported)
|
| 84 |
+
--use_cpu_initialization
|
| 85 |
+
Whether to use CPU initialization for the model. This is useful for large models that cannot fit into GPU memory during initialization.
|
| 86 |
+
--target_dir TARGET_DIR
|
| 87 |
+
Directory to save the merged huggingface model
|
| 88 |
+
--hf_upload_path HF_UPLOAD_PATH
|
| 89 |
+
Hugging Face repository ID to upload the model
|
| 90 |
+
--private Whether to upload the model to a private Hugging Face repository
|
| 91 |
+
|
| 92 |
+
Example usage for merging Megatron checkpoints:
|
| 93 |
+
|
| 94 |
+
.. code:: bash
|
| 95 |
+
|
| 96 |
+
python -m verl.model_merger merge \
|
| 97 |
+
--backend megatron \
|
| 98 |
+
--tie-word-embedding \
|
| 99 |
+
--local_dir checkpoints/verl_megatron_gsm8k_examples/qwen2_5_0b5_megatron_saveload/global_step_1/actor \
|
| 100 |
+
--target_dir /path/to/merged_hf_model
|
| 101 |
+
|
| 102 |
+
Example usage for distributed merging Megatron checkpoints:
|
| 103 |
+
|
| 104 |
+
.. code:: bash
|
| 105 |
+
|
| 106 |
+
torchrun --nproc_per_node 1 --nnodes 8 --node_rank ${RANK} -m verl.model_merger merge \
|
| 107 |
+
--backend megatron \
|
| 108 |
+
--tie-word-embedding \
|
| 109 |
+
--local_dir checkpoints/verl_megatron_gsm8k_examples/qwen2_5_0b5_megatron_saveload/global_step_1/actor \
|
| 110 |
+
--target_dir /path/to/merged_hf_model
|
| 111 |
+
|
| 112 |
+
Example usage for merging FSDP checkpoints:
|
| 113 |
+
|
| 114 |
+
.. code:: bash
|
| 115 |
+
|
| 116 |
+
python -m verl.model_merger merge \
|
| 117 |
+
--backend fsdp \
|
| 118 |
+
--local_dir checkpoints/verl_fsdp_gsm8k_examples/qwen2_5_0b5_fsdp_saveload/global_step_1/actor \
|
| 119 |
+
--target_dir /path/to/merged_hf_model
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
Megatron Merger details
|
| 123 |
+
-----------------------
|
| 124 |
+
|
| 125 |
+
Current implement of decoder layers uses ``nn.ModuleList`` to store the layers,
|
| 126 |
+
and thus the model layers on every PP rank and VPP rank starts their index from 0.
|
| 127 |
+
|
| 128 |
+
There are 3 ways to correct this behavior:
|
| 129 |
+
|
| 130 |
+
1. Modify the decoder layer's state_dict, add ``offset`` to each layer's index, thus rewrite ``nn.ModuleList`` implementation.
|
| 131 |
+
2. Modify the layer index when saving checkpoint and recover them when loading checkpoint.
|
| 132 |
+
3. The Checkpoint merger do this work, calculate the actual ``offset`` from ``state_dict`` only, a little complex.
|
| 133 |
+
|
| 134 |
+
Current implementation use solution 2.
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
HuggingFace to Megatron DistCheckpoint details
|
| 138 |
+
----------------------------------------------
|
| 139 |
+
|
| 140 |
+
If your model is quite huge, we recommend you to use Megatron dist-checkpoint to load the model.
|
| 141 |
+
Megatron dist-checkpoint supports loading with different kinds of model parallelism,
|
| 142 |
+
and it is much faster than the original checkpoint loading.
|
| 143 |
+
|
| 144 |
+
To convert original HuggingFace model to Megatron dist-checkpoint,
|
| 145 |
+
you can use the ``scripts/converter_hf_to_mcore.py`` script. Large MoE models are temporarily supported with CPU initialization,
|
| 146 |
+
which is a little slower. While we are working on a better solution to support large models.
|
| 147 |
+
|
| 148 |
+
Example command to convert the model is as follows:
|
| 149 |
+
|
| 150 |
+
.. code:: bash
|
| 151 |
+
|
| 152 |
+
python scripts/converter_hf_to_mcore.py \
|
| 153 |
+
--hf_model_path Qwen/Qwen1.5-MoE-A2.7B-Chat \
|
| 154 |
+
--output_path /mnt/disk/Qwen/Qwen1.5-MoE-A2.7B-Chat \
|
| 155 |
+
--use_cpu_initialization # Only work for MoE models
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
Example command to distributed convert the huge model like deepseekv3 671B is as follows:
|
| 159 |
+
|
| 160 |
+
.. code:: bash
|
| 161 |
+
|
| 162 |
+
torchrun --nproc_per_node 1 --nnodes 8 --node_rank ${RANK} scripts/converter_hf_to_mcore.py \
|
| 163 |
+
--hf_model_path deepseek-ai/DeepSeek-V3 \
|
| 164 |
+
--output_path /mnt/disk/deepseek-ai/DeepSeek-V3 \
|
| 165 |
+
--use_cpu_initialization # Only work for MoE models
|
| 166 |
+
|
| 167 |
+
Original Checkpoint Utils
|
| 168 |
+
-------------------------
|
| 169 |
+
|
| 170 |
+
Original Checkpoint Utils refer to original checkpoint implementation in ``verl/models/[model]/megatron/checkpoint_utils``.
|
| 171 |
+
|
| 172 |
+
We only need ``[model]_loader.py`` in original checkpoint utils now, since we get rid of storing ``hf_model`` every time (which is not recommended for large model training, try only saving sharded models if you can).
|
| 173 |
+
|
| 174 |
+
.. note::
|
| 175 |
+
|
| 176 |
+
Note that ``[model]_loader`` only support environments where **storage clusters are able to connect with every calculation nodes**.
|
| 177 |
+
Because it utilizes **sharded load way to minimize the loading checkpoint overhead**.
|
| 178 |
+
Every rank loads its own data from ``state_dict`` which can be accessed by all of them.
|
| 179 |
+
While there is also no need to broadcast among DP ranks, since the saved state_dict is only produced by DP rank 0.
|
| 180 |
+
|
| 181 |
+
For users who can **only place the huggingface model on one device**, we keep the original costly implementation in ``[model]_loader_deprecated``. In this implementation, rank 0 broadcast all weights to each tp and pp rank, and then dp rank 0 broadcast to all dp ranks. There may be at risks of OOM.
|
| 182 |
+
|
| 183 |
+
To use deprecated loader, change the import package of ``load_state_dict_to_megatron_llama``.
|
verl/docs/advance/dpo_extension.rst
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Extend to other RL(HF) algorithms
|
| 2 |
+
=================================
|
| 3 |
+
|
| 4 |
+
Last updated: 02/25/2025.
|
| 5 |
+
|
| 6 |
+
We already implemented the complete training pipeline of the PPO
|
| 7 |
+
algorithms. To extend to other algorithms, we analyze the high-level
|
| 8 |
+
principle to use verl and provide a tutorial to implement the DPO
|
| 9 |
+
algorithm. Users can follow the similar paradigm to extend to other RL algorithms.
|
| 10 |
+
|
| 11 |
+
.. note:: **Key ideas**: Single process drives multi-process computation and data communication.
|
| 12 |
+
|
| 13 |
+
Overall Approach
|
| 14 |
+
----------------
|
| 15 |
+
|
| 16 |
+
Step 1: Consider what multi-machine multi-GPU computations are needed
|
| 17 |
+
for each model, such as ``generate_sequence`` , ``compute_log_prob`` and
|
| 18 |
+
``update_policy`` in the actor_rollout model. Implement distributed
|
| 19 |
+
single-process-multiple-data (SPMD) computation and encapsulate them
|
| 20 |
+
into APIs
|
| 21 |
+
|
| 22 |
+
Step 2: Based on different distributed scenarios, including FSDP and 3D
|
| 23 |
+
parallelism in Megatron-LM, implement single-process control of data
|
| 24 |
+
interaction among multi-process computations.
|
| 25 |
+
|
| 26 |
+
Step 3: Utilize the encapsulated APIs to implement the control flow
|
| 27 |
+
|
| 28 |
+
Example: Online DPO
|
| 29 |
+
-------------------
|
| 30 |
+
|
| 31 |
+
We use verl to implement a simple online DPO algorithm. The algorithm
|
| 32 |
+
flow of Online DPO is as follows:
|
| 33 |
+
|
| 34 |
+
1. There is a prompt (rollout) generator which has the same weight as
|
| 35 |
+
the actor model. After a batch of prompts are fed into the generator,
|
| 36 |
+
it generates N responses for each prompt.
|
| 37 |
+
2. Send all the prompts + responses to a verifier for scoring, which can
|
| 38 |
+
be reward model or a rule-based function. Then sort them in pairs to
|
| 39 |
+
form a training batch.
|
| 40 |
+
3. Use this training batch to train the actor model using DPO. During
|
| 41 |
+
the process, a reference policy is needed.
|
| 42 |
+
|
| 43 |
+
Step 1: What are the multi-machine multi-GPU computations
|
| 44 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 45 |
+
|
| 46 |
+
**Sample Generator**
|
| 47 |
+
|
| 48 |
+
Implementation details:
|
| 49 |
+
|
| 50 |
+
.. code:: python
|
| 51 |
+
|
| 52 |
+
from verl.single_controller.base import Worker
|
| 53 |
+
from verl.single_controller.ray import RayWorkerGroup, RayClassWithInitArgs, RayResourcePool
|
| 54 |
+
import ray
|
| 55 |
+
|
| 56 |
+
@ray.remote
|
| 57 |
+
class SampleGenerator(Worker):
|
| 58 |
+
def __init__(self, config):
|
| 59 |
+
super().__init__()
|
| 60 |
+
self.config = config
|
| 61 |
+
|
| 62 |
+
def generate_sequences(self, data):
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
Here, ``SampleGenerator`` can be viewed as a multi-process pulled up by
|
| 66 |
+
``torchrun``, with each process running the same code (SPMD).
|
| 67 |
+
``SampleGenerator`` needs to implement a ``generate_sequences`` API for
|
| 68 |
+
the control flow to call. The implementation details inside can use any
|
| 69 |
+
inference engine including vllm, sglang and huggingface. Users can
|
| 70 |
+
largely reuse the code in
|
| 71 |
+
verl/verl/workers/rollout/vllm_rollout/vllm_rollout.py and we won't
|
| 72 |
+
go into details here.
|
| 73 |
+
|
| 74 |
+
**ReferencePolicy inference**
|
| 75 |
+
|
| 76 |
+
API: compute reference log probability
|
| 77 |
+
|
| 78 |
+
.. code:: python
|
| 79 |
+
|
| 80 |
+
from verl.single_controller.base import Worker
|
| 81 |
+
import ray
|
| 82 |
+
|
| 83 |
+
@ray.remote
|
| 84 |
+
class ReferencePolicy(Worker):
|
| 85 |
+
def __init__(self):
|
| 86 |
+
super().__init__()
|
| 87 |
+
self.model = Model()
|
| 88 |
+
|
| 89 |
+
def infer(self, data):
|
| 90 |
+
return self.model(data)
|
| 91 |
+
|
| 92 |
+
**Actor update**
|
| 93 |
+
|
| 94 |
+
API: Update actor model parameters
|
| 95 |
+
|
| 96 |
+
.. code:: python
|
| 97 |
+
|
| 98 |
+
from verl.single_controller.base import Worker
|
| 99 |
+
import ray
|
| 100 |
+
|
| 101 |
+
@ray.remote
|
| 102 |
+
class DPOActor(Worker):
|
| 103 |
+
def __init__(self):
|
| 104 |
+
super().__init__()
|
| 105 |
+
self.model = Model()
|
| 106 |
+
self.model = FSDP(self.model) # or other distributed strategy
|
| 107 |
+
self.optimizer = optim.Adam(self.model.parameters(), lr=1e-3)
|
| 108 |
+
self.loss_fn = xxx
|
| 109 |
+
|
| 110 |
+
def update(self, data):
|
| 111 |
+
self.optimizer.zero_grad()
|
| 112 |
+
logits = self.model(data)
|
| 113 |
+
loss = self.loss_fn(logits)
|
| 114 |
+
loss.backward()
|
| 115 |
+
self.optimizer.step()
|
| 116 |
+
|
| 117 |
+
**Notes: How to distinguish between control processes and distributed computation processes**
|
| 118 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 119 |
+
|
| 120 |
+
- Control processes are generally functions directly decorated with
|
| 121 |
+
``@ray.remote``
|
| 122 |
+
- Computation processes are all wrapped into a ``RayWorkerGroup``.
|
| 123 |
+
|
| 124 |
+
Users can reuse most of the distribtued computation logics implemented
|
| 125 |
+
in PPO algorithm, including FSDP and Megatron-LM backend in
|
| 126 |
+
verl/verl/trainer/ppo.
|
| 127 |
+
|
| 128 |
+
Step 2: Based on different distributed scenarios, implement single-process control of multi-process data interaction
|
| 129 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 130 |
+
|
| 131 |
+
**The core problem to solve here is how a single process sends data to
|
| 132 |
+
multiple processes, drives multi-process computation, and how the
|
| 133 |
+
control process obtains the results of multi-process computation.**
|
| 134 |
+
First, we initialize the multi-process ``WorkerGroup`` in the control
|
| 135 |
+
process.
|
| 136 |
+
|
| 137 |
+
.. code:: python
|
| 138 |
+
|
| 139 |
+
@ray.remote(num_cpus=1)
|
| 140 |
+
def main_task(config):
|
| 141 |
+
# construct SampleGenerator
|
| 142 |
+
resource_pool = RayResourcePool(process_on_nodes=[8] * 2) # 16 GPUs
|
| 143 |
+
ray_cls = RayClassWithInitArgs(SampleGenerator, config=config)
|
| 144 |
+
# put SampleGenerator onto resource pool
|
| 145 |
+
worker_group = RayWorkerGroup(resource_pool, ray_cls)
|
| 146 |
+
|
| 147 |
+
# construct reference policy
|
| 148 |
+
|
| 149 |
+
As we can see, in the control process, multiple processes are wrapped
|
| 150 |
+
into a ``RayWorkerGroup``. Inside this ``WorkerGroup``, there is a
|
| 151 |
+
``self._workers`` member, where each worker is a RayActor
|
| 152 |
+
(https://docs.ray.io/en/latest/ray-core/actors.html) of SampleGenerator.
|
| 153 |
+
ray_trainer.md also provide an implementation of
|
| 154 |
+
``MegatronRayWorkerGroup``.
|
| 155 |
+
|
| 156 |
+
Assuming the model is distributed using FSDP, and there is a batch of
|
| 157 |
+
data on the control process, for data parallelism, the underlying
|
| 158 |
+
calling process is:
|
| 159 |
+
|
| 160 |
+
.. code:: python
|
| 161 |
+
|
| 162 |
+
data = xxx
|
| 163 |
+
data_list = data.chunk(dp_size)
|
| 164 |
+
|
| 165 |
+
output = []
|
| 166 |
+
for d in data_list:
|
| 167 |
+
# worker_group._workers[i] is a SampleGenerator
|
| 168 |
+
output.append(worker_group._workers[i].generate_sequences.remote(d))
|
| 169 |
+
|
| 170 |
+
output = ray.get(output)
|
| 171 |
+
output = torch.cat(output)
|
| 172 |
+
|
| 173 |
+
Single process calling multiple processes involves the following 3
|
| 174 |
+
steps:
|
| 175 |
+
|
| 176 |
+
1. Split the data into DP parts on the control process.
|
| 177 |
+
2. Send the data to remote, call the remote computation through RPC, and
|
| 178 |
+
utilize multi-process computation.
|
| 179 |
+
3. Obtain the computation results of each worker on the control process
|
| 180 |
+
and merge them.
|
| 181 |
+
|
| 182 |
+
Frequently calling these 3 steps on the controller process greatly hurts
|
| 183 |
+
code readability. **In verl, we have abstracted and encapsulated these 3
|
| 184 |
+
steps, so that the worker's method + dispatch + collect can be
|
| 185 |
+
registered into the worker_group**
|
| 186 |
+
|
| 187 |
+
.. code:: python
|
| 188 |
+
|
| 189 |
+
from verl.single_controller.base.decorator import register
|
| 190 |
+
|
| 191 |
+
def dispatch_data(worker_group, data):
|
| 192 |
+
return data.chunk(worker_group.world_size)
|
| 193 |
+
|
| 194 |
+
def collect_data(worker_group, data):
|
| 195 |
+
return torch.cat(data)
|
| 196 |
+
|
| 197 |
+
dispatch_mode = {
|
| 198 |
+
'dispatch_fn': dispatch_data,
|
| 199 |
+
'collect_fn': collect_data
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
@register(dispatch_mode=dispatch_mode)
|
| 203 |
+
def generate_sequences(self, data):
|
| 204 |
+
pass
|
| 205 |
+
|
| 206 |
+
In this way, we can directly call the method inside the worker through
|
| 207 |
+
the ``worker_group`` on the control (driver) process (which is a single
|
| 208 |
+
process):
|
| 209 |
+
|
| 210 |
+
.. code:: python
|
| 211 |
+
|
| 212 |
+
output = worker_group.generate_sequences(data)
|
| 213 |
+
|
| 214 |
+
This single line includes data splitting, data distribution and
|
| 215 |
+
computation, and data collection.
|
| 216 |
+
|
| 217 |
+
Furthermore, the model parallelism size of each model is usually fixed,
|
| 218 |
+
including dp, tp, pp. So for these common distributed scenarios, we have
|
| 219 |
+
pre-implemented specific dispatch and collect methods,in `decorator.py <https://github.com/volcengine/verl/blob/main/verl/single_controller/base/decorator.py>`_, which can be directly used to wrap the computations.
|
| 220 |
+
|
| 221 |
+
.. code:: python
|
| 222 |
+
|
| 223 |
+
from verl.single_controller.base.decorator import register, Dispatch
|
| 224 |
+
|
| 225 |
+
@register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO)
|
| 226 |
+
def generate_sequences(self, data: DataProto) -> DataProto:
|
| 227 |
+
pass
|
| 228 |
+
|
| 229 |
+
Here it requires the data interface to be ``DataProto``. Definition of
|
| 230 |
+
``DataProto`` is in `protocol.py <https://github.com/volcengine/verl/blob/main/verl/protocol.py>`_.
|
| 231 |
+
|
| 232 |
+
Step 3: Main training loop
|
| 233 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 234 |
+
|
| 235 |
+
With the above training flows, we can implement the algorithm's control
|
| 236 |
+
flow. It is recommended that ``main_task`` is also a ray remote process.
|
| 237 |
+
|
| 238 |
+
.. code:: python
|
| 239 |
+
|
| 240 |
+
@ray.remote(num_cpus=1)
|
| 241 |
+
def main_task(config):
|
| 242 |
+
# construct SampleGenerator
|
| 243 |
+
resource_pool = RayResourcePool(process_on_nodes=[8] * 2) # 16 GPUs
|
| 244 |
+
ray_cls = RayClassWithInitArgs(SampleGenerator, config=config)
|
| 245 |
+
# put SampleGenerator onto resource pool
|
| 246 |
+
sample_gen = RayWorkerGroup(resource_pool, ray_cls)
|
| 247 |
+
|
| 248 |
+
# construct reference policy
|
| 249 |
+
ray_cls = RayClassWithInitArgs(ReferencePolicy)
|
| 250 |
+
ref_policy = RayWorkerGroup(resource_pool, ray_cls)
|
| 251 |
+
|
| 252 |
+
# construct actor
|
| 253 |
+
ray_cls = RayClassWithInitArgs(DPOActor)
|
| 254 |
+
dpo_policy = RayWorkerGroup(resource_pool, ray_cls)
|
| 255 |
+
|
| 256 |
+
dataloader = DataLoader()
|
| 257 |
+
|
| 258 |
+
for data in dataloader:
|
| 259 |
+
# generate data
|
| 260 |
+
data = sample_gen.generate_sequences(data)
|
| 261 |
+
# generate scores for each data
|
| 262 |
+
data = generate_scores(data)
|
| 263 |
+
# generate pairwise data using scores
|
| 264 |
+
data = generate_pairwise_data(data)
|
| 265 |
+
# generate ref_log_prob
|
| 266 |
+
data.batch['ref_log_prob'] = ref_policy.infer(data)
|
| 267 |
+
# update using dpo
|
| 268 |
+
dpo_policy.update(data)
|
| 269 |
+
# logging
|
| 270 |
+
|
| 271 |
+
Here, different ``WorkerGroups`` can be placed in the same resource pool or
|
| 272 |
+
in different resource pools using ``create_colocated_worker_cls``
|
| 273 |
+
similar as in `ray_trainer.py <https://github.com/volcengine/verl/blob/main/verl/trainer/ppo/ray_trainer.py>`_.
|
verl/docs/advance/fsdp_extension.rst
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Add models with the FSDP backend
|
| 3 |
+
==================================
|
| 4 |
+
|
| 5 |
+
Last updated: 02/09/2025.
|
| 6 |
+
|
| 7 |
+
Model
|
| 8 |
+
--------------------------
|
| 9 |
+
|
| 10 |
+
In principle, our FSDP backend can support any HF model and we can
|
| 11 |
+
sychronoize the actor model weight with vLLM using `hf_weight_loader.py` under `third_party/vllm`.
|
| 12 |
+
However, ``hf_weight_loader`` is will gather the full state_dict of a
|
| 13 |
+
model during synchronization, which may cause OOM. We suggest using
|
| 14 |
+
``dtensor_weight_loader`` which gather the full model parameter layer by
|
| 15 |
+
layer to reduce the peak memory usage. We already support dtensor weight
|
| 16 |
+
loader for the models below in `dtensor_weight_loader.py` under `third_party/vllm`:
|
| 17 |
+
|
| 18 |
+
- ``GPT2LMHeadModel``
|
| 19 |
+
- ``LlamaForCausalLM``
|
| 20 |
+
- ``LLaMAForCausalLM``
|
| 21 |
+
- ``MistralForCausalLM``
|
| 22 |
+
- ``InternLMForCausalLM``
|
| 23 |
+
- ``AquilaModel``
|
| 24 |
+
- ``AquilaForCausalLM``
|
| 25 |
+
- ``Phi3ForCausalLM``
|
| 26 |
+
- ``GemmaForCausalLM``
|
| 27 |
+
- ``Gemma2ForCausalLM``
|
| 28 |
+
- ``GPTBigCodeForCausalLM``
|
| 29 |
+
- ``Starcoder2ForCausalLM``
|
| 30 |
+
- ``Qwen2ForCausalLM``
|
| 31 |
+
- ``DeepseekV2ForCausalLM``
|
| 32 |
+
|
| 33 |
+
To implement ``dtensor_weight_loader`` of a model that's supported in
|
| 34 |
+
vLLM, follow the guide of gemma model below:
|
| 35 |
+
|
| 36 |
+
1. Copy the
|
| 37 |
+
``load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]])`` from the vllm model class
|
| 38 |
+
to ``dtensor_weight_loaders.py``
|
| 39 |
+
2. Modify the arguments to
|
| 40 |
+
``(actor_weights: Dict, vllm_model: nn.Module)``
|
| 41 |
+
3. Replace the ``self`` to ``vllm_model``
|
| 42 |
+
4. Add the
|
| 43 |
+
``local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)``
|
| 44 |
+
before each ``param = params_dict[name]`` and modify the following
|
| 45 |
+
weight loading using ``local_loaded_weight``.
|
| 46 |
+
5. Register the implemented dtensor weight loader to ``__MODEL_DTENSOR_WEIGHT_LOADER_REGISTRY__``.
|
| 47 |
+
|
| 48 |
+
.. code-block:: diff
|
| 49 |
+
|
| 50 |
+
- def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
|
| 51 |
+
+ def gemma_dtensor_weight_loader(actor_weights: Dict, vllm_model: nn.Module) -> nn.Module:
|
| 52 |
+
stacked_params_mapping = [
|
| 53 |
+
# (param_name, shard_name, shard_id)
|
| 54 |
+
("qkv_proj", "q_proj", "q"),
|
| 55 |
+
("qkv_proj", "k_proj", "k"),
|
| 56 |
+
("qkv_proj", "v_proj", "v"),
|
| 57 |
+
("gate_up_proj", "gate_proj", 0),
|
| 58 |
+
("gate_up_proj", "up_proj", 1),
|
| 59 |
+
]
|
| 60 |
+
- params_dict = dict(self.named_parameters())
|
| 61 |
+
+ params_dict = dict(vllm_model.named_parameters())
|
| 62 |
+
loaded_params = set()
|
| 63 |
+
- for name, loaded_weight in weights:
|
| 64 |
+
+ for name, loaded_weight in actor_weights.items():
|
| 65 |
+
for (param_name, shard_name, shard_id) in stacked_params_mapping:
|
| 66 |
+
if shard_name not in name:
|
| 67 |
+
continue
|
| 68 |
+
name = name.replace(shard_name, param_name)
|
| 69 |
+
# Skip loading extra bias for GPTQ models.
|
| 70 |
+
if name.endswith(".bias") and name not in params_dict:
|
| 71 |
+
continue
|
| 72 |
+
+ local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)
|
| 73 |
+
param = params_dict[name]
|
| 74 |
+
weight_loader = param.weight_loader
|
| 75 |
+
- weight_loader(param, loaded_weight, shard_id)
|
| 76 |
+
+ weight_loader(param, local_loaded_weight.to(dtype=param.dtype), shard_id)
|
| 77 |
+
break
|
| 78 |
+
else:
|
| 79 |
+
# lm_head is not used in vllm as it is tied with embed_token.
|
| 80 |
+
# To prevent errors, skip loading lm_head.weight.
|
| 81 |
+
if "lm_head.weight" in name:
|
| 82 |
+
continue
|
| 83 |
+
# Skip loading extra bias for GPTQ models.
|
| 84 |
+
if name.endswith(".bias") and name not in params_dict:
|
| 85 |
+
continue
|
| 86 |
+
+ local_loaded_weight = redistribute_dtensor(param_name=name, loaded_weights=loaded_weight)
|
| 87 |
+
param = params_dict[name]
|
| 88 |
+
weight_loader = getattr(param, "weight_loader",
|
| 89 |
+
default_weight_loader)
|
| 90 |
+
- weight_loader(param, loaded_weight)
|
| 91 |
+
+ weight_loader(param, local_loaded_weight.to(dtype=param.dtype))
|
| 92 |
+
loaded_params.add(name)
|
| 93 |
+
unloaded_params = params_dict.keys() - loaded_params
|
| 94 |
+
if unloaded_params:
|
| 95 |
+
raise RuntimeError(
|
| 96 |
+
"Some weights are not initialized from checkpoints: "
|
| 97 |
+
f"{unloaded_params}")
|
verl/docs/advance/megatron_extension.rst
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Add models with the Megatron-LM backend
|
| 2 |
+
=========================================
|
| 3 |
+
|
| 4 |
+
Last updated: 04/25/2025.
|
| 5 |
+
|
| 6 |
+
Model
|
| 7 |
+
-----------
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
If use latest verl, we have direct support of ``GPTModel`` for Megatron backend.
|
| 11 |
+
You can use the similar way of using Megatron to pretrain custom models.
|
| 12 |
+
We list the steps here:
|
| 13 |
+
|
| 14 |
+
1. Find `model_initializer.py <https://github.com/volcengine/verl/blob/main/verl/models/mcore/model_initializer.py>`_
|
| 15 |
+
2. If your model is configurable by ``TransformerLayerSpec`` , you can
|
| 16 |
+
directly use ``GPTModel``. Otherwise, Please implement a new
|
| 17 |
+
``ModelLayerSpec`` and ``ModelLayer`` here.
|
| 18 |
+
3. Use the right ``LayerSpec`` , ``TransformerConfig`` and ``HuggingfaceConfig``
|
| 19 |
+
as arguments to initialize the GPTModel.
|
| 20 |
+
4. Return the model at last.
|
verl/docs/advance/one_step_off.md
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Recipe: One Step Off Policy Async Trainer
|
| 2 |
+
|
| 3 |
+
**Author:** `https://github.com/meituan-search`
|
| 4 |
+
|
| 5 |
+
Last updated: 07/17/2025.
|
| 6 |
+
|
| 7 |
+
## Introduction
|
| 8 |
+
|
| 9 |
+
### Background
|
| 10 |
+
|
| 11 |
+
The current reinforcement learning training process implemented by verl is synchronous, adhering to the algorithmic
|
| 12 |
+
workflows of established methods like PPO, GRPO, and DAPO. In each step, training samples are generated by the latest
|
| 13 |
+
model, and the model is updated after training completes. While this approach aligns with off-policy reinforcement
|
| 14 |
+
learning and stabilizes RL training, but it suffers from severe efficiency issues.
|
| 15 |
+
Model updates must wait for the longest output in the generation phase to complete.
|
| 16 |
+
During the generation of long-tail samples, GPUs remain idle, resulting in significant underutilization.
|
| 17 |
+
The more severe the long-tail problem in sample generation, the lower the overall training efficiency.
|
| 18 |
+
For example, in DAPO 32B training, the Rollout phase accounts for approximately 70% of the total time,
|
| 19 |
+
and increasing resources does not reduce the Rollout duration.
|
| 20 |
+
|
| 21 |
+

|
| 23 |
+
> source data: https://wandb.ai/verl-org/DAPO%20Reproduction%20on%20verl/workspace?nw=nwusertongyuxuan361
|
| 24 |
+
|
| 25 |
+
### Solution
|
| 26 |
+
|
| 27 |
+
We have implemented the **One Step Off Async Trainer** to help alleviate this issue. This approach parallelizes the
|
| 28 |
+
generation and training processes, utilizing samples generated in the previous step for current training.
|
| 29 |
+
It also involves appropriately partitioning resources, allocating dedicated resources for generation while automatically
|
| 30 |
+
assigning the remainder to training. By reducing resources allocated to the generation phase, we mitigate GPU idle time
|
| 31 |
+
during long-tail sample generation. Throughout this process, generation and training parameters maintain a one-step off
|
| 32 |
+
policy.
|
| 33 |
+
|
| 34 |
+

|
| 36 |
+
> reference: [AReaL: A Large-Scale Asynchronous Reinforcement Learning System for Language Reasoning](
|
| 37 |
+
> https://arxiv.org/abs/2505.24298)
|
| 38 |
+
|
| 39 |
+
Our core contributions include:
|
| 40 |
+
|
| 41 |
+
1. **Parallel Generation and Training**:
|
| 42 |
+
Samples for the next batch are asynchronously generated while the current batch is being trained.
|
| 43 |
+
|
| 44 |
+
2. **Resource Isolation**:
|
| 45 |
+
Unlike `hybrid_engine`, this method requires explicit resource allocation for rollout, with remaining resources
|
| 46 |
+
automatically assigned to training.
|
| 47 |
+
|
| 48 |
+
3. **NCCL Parameter Synchronization**:
|
| 49 |
+
Employs NCCL communication primitives for seamless parameter transfer between generation and training modules.
|
| 50 |
+
|
| 51 |
+
### Experimental Results
|
| 52 |
+
|
| 53 |
+
- **Machine Configuration**: 2 nodes with 16 H20 GPUs each
|
| 54 |
+
- Generation: 4 GPUs
|
| 55 |
+
- Training: 12 GPUs
|
| 56 |
+
- **Model**: Qwen2.5-Math-7B
|
| 57 |
+
- **Rollout Configuration**:
|
| 58 |
+
- **Max Response Length**: FSDP2: 20,480 tokens; Megatron: 8,192 tokens
|
| 59 |
+
- **Algorithm**: DAPO
|
| 60 |
+
- **Rollout Engine**: vLLM
|
| 61 |
+
|
| 62 |
+
| training mode | engine | step | gen | wait_prev_gen | generate_sequences | old_log_prob | update_actor | total time | acc/best@32/mean | acc/maj@32/mean |
|
| 63 |
+
|------------------------|---------------|------|-----|---------------|--------------------|--------------|--------------|---------------|------------------|-----------------|
|
| 64 |
+
| colocate sync | VLLM+FSDP2 | 749 | 321 | - | 247 | 88 | 286 | 19h18m | 0.5948 | 0.417 |
|
| 65 |
+
| one-step-overlap async | VLLM+FSDP2 | 520 | - | 45 | 458 | 108 | 337 | 15h34m(+23%) | 0.6165 | 0.494 |
|
| 66 |
+
| colocate sync | VLLM+Megatron | 699 | 207 | - | 162 | 119 | 344 | 18h21m | 0.605 | 0.4217 |
|
| 67 |
+
| one-step-overlap async | VLLM+Megatron | 566 | - | 59 | 501 | 120 | 347 | 13h06m (+40%) | 0.6569 | 0.4038 |
|
| 68 |
+
|
| 69 |
+
* colocate sync: step ≈ gen + old_log_prob + update_actor
|
| 70 |
+
* one-step-overlap async: step ≈ wait_prev_gen + old_log_prob + update_actor
|
| 71 |
+
|
| 72 |
+

|
| 74 |
+
|
| 75 |
+
> source data: https://wandb.ai/hou-zg-meituan/one-step-off-policy?nw=nwuserhouzg
|
| 76 |
+
|
| 77 |
+
## Implementation
|
| 78 |
+
|
| 79 |
+
### One Step Off Policy Async Pipline
|
| 80 |
+
|
| 81 |
+
Our implemented **One Step Off Policy Async Pipeline** integrates seamlessly into existing training logic at minimal
|
| 82 |
+
cost,
|
| 83 |
+
eliminating the need for additional sample storage management. The core mechanism uses `async_gen_next_batch`
|
| 84 |
+
for asynchronous rollout generation while maintaining continuous operation during epoch transitions
|
| 85 |
+
via `create_continuous_iterator`.
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
# iterator generator, simplify one-step integration of the training process
|
| 89 |
+
def _create_continuous_iterator(self):
|
| 90 |
+
for epoch in range(self.config.trainer.total_epochs):
|
| 91 |
+
iterator = iter(self.train_dataloader)
|
| 92 |
+
for batch_dict in iterator:
|
| 93 |
+
yield epoch, batch_dict
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# read next batch samples, parameters sync and launch asyn gen_seq
|
| 97 |
+
def _async_gen_next_batch(self, continuous_iterator):
|
| 98 |
+
# read train_data
|
| 99 |
+
try:
|
| 100 |
+
epoch, batch_dict = next(continuous_iterator)
|
| 101 |
+
except StopIteration:
|
| 102 |
+
return None
|
| 103 |
+
batch = DataProto.from_single_dict(batch_dict)
|
| 104 |
+
gen_batch = batch_pocess(batch)
|
| 105 |
+
# sync weights from actor to rollout
|
| 106 |
+
self.sync_rollout_weights()
|
| 107 |
+
# async generation
|
| 108 |
+
gen_batch_output = self.rollout_wg.async_generate_sequences(gen_batch)
|
| 109 |
+
# future encapsulated
|
| 110 |
+
return GenerationBatchFuture(epoch, batch, gen_batch_output)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
continuous_iterator = self._create_continuous_iterator()
|
| 114 |
+
# run rollout first to achieve one-step-off
|
| 115 |
+
batch_data_future = self._async_gen_next_batch(continuous_iterator)
|
| 116 |
+
|
| 117 |
+
while batch_data_future is not None:
|
| 118 |
+
# wait for the gen_seq result from the previous step
|
| 119 |
+
batch = batch_data_future.get()
|
| 120 |
+
# launch the next async call to generate sequences
|
| 121 |
+
batch_data_future = self._async_gen_next_batch(continuous_iterator)
|
| 122 |
+
|
| 123 |
+
# compute advantages
|
| 124 |
+
batch = critic.compute_values(batch)
|
| 125 |
+
batch = reference.compute_log_prob(batch)
|
| 126 |
+
batch = reward.compute_reward(batch)
|
| 127 |
+
batch = compute_advantages(batch)
|
| 128 |
+
|
| 129 |
+
# model update
|
| 130 |
+
critic_metrics = critic.update_critic(batch)
|
| 131 |
+
actor_metrics = actor.update_actor(batch)
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
### Parameter Synchronization
|
| 135 |
+
|
| 136 |
+
The exciting point is that our nccl based weights updating for rollout model has great performance.
|
| 137 |
+
At most of time, the latency is under 300ms, which is negligible for RLHF.
|
| 138 |
+
|
| 139 |
+
> **sync_rollout_weights**:The time for synchronizing parameters from actor to rollout is extremely fast and can almost
|
| 140 |
+
> be ignored because it is implemented with nccl.
|
| 141 |
+
|
| 142 |
+
```python
|
| 143 |
+
class ActorRolloutRefWorker:
|
| 144 |
+
# actor acquires the meta-info of model parameters for parameter sync
|
| 145 |
+
@register(dispatch_mode=Dispatch.ONE_TO_ALL)
|
| 146 |
+
def get_actor_weights_info(self):
|
| 147 |
+
params = self._get_actor_params()
|
| 148 |
+
ret = []
|
| 149 |
+
for key, tensor in params.items():
|
| 150 |
+
ret.append((key, tensor.size(), tensor.dtype))
|
| 151 |
+
self._weights_info = ret
|
| 152 |
+
return ret
|
| 153 |
+
|
| 154 |
+
# rollout sets the meta-info of model parameters for parameter sync
|
| 155 |
+
@register(dispatch_mode=Dispatch.ONE_TO_ALL)
|
| 156 |
+
def set_actor_weights_info(self, weights_info):
|
| 157 |
+
self._weights_info = weights_info
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class AsyncRayPPOTrainer(RayPPOTrainer):
|
| 161 |
+
def init_workers(self):
|
| 162 |
+
...
|
| 163 |
+
# rollout obtains the meta-info of model parameters from the actor for parameter sync
|
| 164 |
+
weights_info = self.actor_wg.get_actor_weights_info()[0]
|
| 165 |
+
self.rollout_wg.set_actor_weights_info(weights_info)
|
| 166 |
+
|
| 167 |
+
# Create an actor-rollout communication group for parameter sync
|
| 168 |
+
self.create_weight_sync_group
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
```python
|
| 172 |
+
# The driving process invokes the actor and rollout respectively to create a weight synchronization group based on nccl/hccl.
|
| 173 |
+
def create_weight_sync_group(self):
|
| 174 |
+
master_address = ray.get(self.actor_wg.workers[0]._get_node_ip.remote())
|
| 175 |
+
master_port = ray.get(self.actor_wg.workers[0]._get_free_port.remote())
|
| 176 |
+
world_size = len(self.actor_wg.workers + self.rollout_wg.workers)
|
| 177 |
+
self.actor_wg.create_weight_sync_group(
|
| 178 |
+
master_address,
|
| 179 |
+
master_port,
|
| 180 |
+
0,
|
| 181 |
+
world_size,
|
| 182 |
+
)
|
| 183 |
+
ray.get(
|
| 184 |
+
self.rollout_wg.create_weight_sync_group(
|
| 185 |
+
master_address,
|
| 186 |
+
master_port,
|
| 187 |
+
len(self.actor_wg.workers),
|
| 188 |
+
world_size,
|
| 189 |
+
)
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
# drive process call the actor and rollout respectively to sync parameters by nccl
|
| 193 |
+
def sync_rollout_weights(self):
|
| 194 |
+
self.actor_wg.sync_rollout_weights()
|
| 195 |
+
ray.get(self.rollout_wg.sync_rollout_weights())
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
# fsdp model parameter sync
|
| 199 |
+
@register(dispatch_mode=Dispatch.ONE_TO_ALL, blocking=False)
|
| 200 |
+
def sync_rollout_weights(self):
|
| 201 |
+
params = self._get_actor_params() if self._is_actor else None
|
| 202 |
+
if self._is_rollout:
|
| 203 |
+
inference_model = (
|
| 204 |
+
self.rollout.inference_engine.llm_engine.model_executor.driver_worker.worker.model_runner.model
|
| 205 |
+
)
|
| 206 |
+
from verl.utils.vllm.patch import patch_vllm_moe_model_weight_loader
|
| 207 |
+
patch_vllm_moe_model_weight_loader(inference_model)
|
| 208 |
+
# Model parameters are broadcast tensor-by-tensor from actor to rollout
|
| 209 |
+
for key, shape, dtype in self._weights_info:
|
| 210 |
+
tensor = torch.empty(shape, dtype=dtype, device=get_torch_device().current_device())
|
| 211 |
+
if self._is_actor:
|
| 212 |
+
assert key in params
|
| 213 |
+
origin_data = params[key]
|
| 214 |
+
if hasattr(origin_data, "full_tensor"):
|
| 215 |
+
origin_data = origin_data.full_tensor()
|
| 216 |
+
if torch.distributed.get_rank() == 0:
|
| 217 |
+
tensor.copy_(origin_data)
|
| 218 |
+
from ray.util.collective import collective
|
| 219 |
+
|
| 220 |
+
collective.broadcast(tensor, src_rank=0, group_name="actor_rollout")
|
| 221 |
+
if self._is_rollout:
|
| 222 |
+
inference_model.load_weights([(key, tensor)])
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
## Usage
|
| 226 |
+
|
| 227 |
+
### FSDP2 Configuration Example
|
| 228 |
+
|
| 229 |
+
```shell
|
| 230 |
+
python3 -m recipe.one_step_off_policy.async_main_ppo \
|
| 231 |
+
--config-path=config \
|
| 232 |
+
--config-name='one_step_off_ppo_trainer.yaml' \
|
| 233 |
+
actor_rollout_ref.actor.strategy=fsdp2 \
|
| 234 |
+
# actor and rollout are placed separately
|
| 235 |
+
actor_rollout_ref.hybrid_engine=False \
|
| 236 |
+
# actor and rollout resource
|
| 237 |
+
trainer.nnodes=1 \
|
| 238 |
+
trainer.n_gpus_per_node=6 \
|
| 239 |
+
rollout.nnodes=1 \
|
| 240 |
+
rollout.n_gpus_per_node=2
|
| 241 |
+
```
|
| 242 |
+
|
| 243 |
+
### Megatron Configuration Example
|
| 244 |
+
|
| 245 |
+
```shell
|
| 246 |
+
python3 -m recipe.one_step_off_policy.async_main_ppo \
|
| 247 |
+
--config-path=config \
|
| 248 |
+
--config-name='one_step_off_ppo_megatron_trainer.yaml' \
|
| 249 |
+
actor_rollout_ref.actor.strategy=megatron \
|
| 250 |
+
# actor and rollout are placed separately
|
| 251 |
+
actor_rollout_ref.hybrid_engine=False \
|
| 252 |
+
# actor and rollout resource
|
| 253 |
+
trainer.nnodes=1 \
|
| 254 |
+
trainer.n_gpus_per_node=6 \
|
| 255 |
+
rollout.nnodes=1 \
|
| 256 |
+
rollout.n_gpus_per_node=2
|
| 257 |
+
```
|
| 258 |
+
|
| 259 |
+
### Configuration Guidelines
|
| 260 |
+
|
| 261 |
+
1. **Card Number Relationships**
|
| 262 |
+
Maintain either of these relationships for optimal batch distribution:
|
| 263 |
+
- `actor_rollout_ref.rollout.n` should be an integer divisor of:
|
| 264 |
+
`trainer.n_gpus_per_node * trainer.nnodes`
|
| 265 |
+
- `actor_rollout_ref.rollout.n * data.train_batch_size` should be evenly divisible by:
|
| 266 |
+
`trainer.n_gpus_per_node * trainer.nnodes`
|
| 267 |
+
|
| 268 |
+
> Rationale: Ensures training samples can be evenly distributed across training GPUs when using partial resources for
|
| 269 |
+
generation.
|
| 270 |
+
|
| 271 |
+
2. **Dynamic Resource Tuning**
|
| 272 |
+
Adjust `trainer.nnodes` `trainer.n_gpus_per_node` `rollout.nnodes` `rollout.n_gpus_per_node` based on phase
|
| 273 |
+
durations:
|
| 274 |
+
- **Ideal state**: Rollout and training phases have comparable durations
|
| 275 |
+
- **Diagnostic metrics**:
|
| 276 |
+
- Monitor `wait_prev_gen` duration
|
| 277 |
+
- Analyze `sequence_length` distribution
|
| 278 |
+
- **Adjustment strategy**:
|
| 279 |
+
- High `wait_prev_gen` + uniform sequence lengths → Increase rollout resources
|
| 280 |
+
- High `wait_prev_gen` + long-tail sequences → Optimize stopping criteria (resource increase won't help)
|
| 281 |
+
> **wait_prev_gen**:The time consumed waiting for the previous rollout to end (the part that is not fully
|
| 282 |
+
overlapped).
|
| 283 |
+
**Resource Configuration Strategies:**
|
| 284 |
+
- **Resource-constrained scenario**: Optimize resource utilization by adjusting GPU allocation ratios,
|
| 285 |
+
keeping the number of nodes equal to allow training and rollout to share nodes;
|
| 286 |
+
- Configure `trainer.nnodes = rollout.nnodes` with
|
| 287 |
+
`trainer.n_gpus_per_node + rollout.n_gpus_per_node = physical_gpus_per_node`. Control rollout resource
|
| 288 |
+
allocation by adjusting `n_gpus_per_node`.
|
| 289 |
+
- **Resource-abundant scenario**: Optimize performance by adjusting the number of nodes,
|
| 290 |
+
keeping the number of GPUs per node equal to enable independent scaling of training and rollout
|
| 291 |
+
parallelism.
|
| 292 |
+
- Configure `trainer.n_gpus_per_node = rollout.n_gpus_per_node` and control rollout resource allocation by
|
| 293 |
+
adjusting `trainer.nnodes` and `rollout.nnodes`to achieve optimal performance.
|
| 294 |
+
> **Note**: The total number of nodes required by the system is not simply `trainer.nnodes + rollout.nnodes`. The
|
| 295 |
+
> actual calculation depends on GPU capacity:
|
| 296 |
+
> - When `trainer.n_gpus_per_node + rollout.n_gpus_per_node <= physical_gpus_per_node`,
|
| 297 |
+
> the required node count is `max(trainer.nnodes, rollout.nnodes)`
|
| 298 |
+
> - When `trainer.n_gpus_per_node + rollout.n_gpus_per_node > physical_gpus_per_node`,
|
| 299 |
+
> the required node count is `trainer.nnodes + rollout.nnodes`
|
| 300 |
+
|
| 301 |
+
## Functional Support
|
| 302 |
+
|
| 303 |
+
| Category | Support Situation |
|
| 304 |
+
|--------------------|-----------------------------------------------------------------------------------------------------------------|
|
| 305 |
+
| train engine | FSDP2 <br/> Megatron |
|
| 306 |
+
| rollout engine | vLLM |
|
| 307 |
+
| AdvantageEstimator | GRPO <br/> GRPO_PASSK <br/> REINFORCE_PLUS_PLUS <br/> RLOO <br/> OPO <br/> REINFORCE_PLUS_PLUS_BASELINE<br/>GPG |
|
| 308 |
+
| Reward | all |
|
verl/docs/advance/placement.rst
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Ray API Design Tutorial
|
| 2 |
+
=======================================
|
| 3 |
+
|
| 4 |
+
Last updated: 10/30/2024.
|
| 5 |
+
|
| 6 |
+
We provide a tutorial for our Ray API design, including:
|
| 7 |
+
|
| 8 |
+
- Ray basic concepts
|
| 9 |
+
- Resource Pool and RayWorkerGroup
|
| 10 |
+
- Data Dispatch, Execution and Collection
|
| 11 |
+
- Initialize the RayWorkerGroup and execute the distributed computation in the given Resource Pool
|
| 12 |
+
|
| 13 |
+
See details in `tutorial.ipynb <https://github.com/volcengine/verl/blob/main/examples/ray/tutorial.ipynb>`_.
|
verl/docs/advance/ppo_lora.rst
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
RL(HF) algorithms with LoRA Support
|
| 2 |
+
===========================================
|
| 3 |
+
|
| 4 |
+
Last updated: 06/05/2025.
|
| 5 |
+
|
| 6 |
+
We support LoRA (Low-Rank Adaptation) for reinforcement learning algorithms such as PPO, GRPO, and others.
|
| 7 |
+
|
| 8 |
+
LoRA is a parameter-efficient fine-tuning technique that injects trainable low-rank matrices into pre-trained weights (typically linear layers). This reduces memory footprint and compute cost, making it possible to fine-tune large models with limited hardware.
|
| 9 |
+
|
| 10 |
+
The benefits this brings include:
|
| 11 |
+
|
| 12 |
+
- reinforcement learning with very large models (e.g. 70B+) with modest hardware (e.g. 8x80G GPUs),
|
| 13 |
+
- enable larger batch sizes due to reduced memory usage,
|
| 14 |
+
- simplify model transfer and deployment, as only LoRA adapters need to be saved,
|
| 15 |
+
- Combine with techniques like `SLoRA <https://arxiv.org/abs/2311.03285>`_ or `CCoE <https://arxiv.org/abs/2407.11686>`_ to serve multiple LoRA adapters efficiently
|
| 16 |
+
|
| 17 |
+
This guide explains how to enable LoRA in RL training and configure related parameters.
|
| 18 |
+
|
| 19 |
+
Usage Guide
|
| 20 |
+
------------------------
|
| 21 |
+
1. Lora is available in the `verl.trainer.ppo.ray_trainer.RayPPOTrainer`. Examples are provided via the `verl.trainer.main_ppo` entry point.
|
| 22 |
+
|
| 23 |
+
2. Currently, LoRA is supported via huggingface peft, only with fsdp/fsdp2 and vllm backend (sglang support coming soon).
|
| 24 |
+
|
| 25 |
+
- `strategy=fsdp` or `strategy=fsdp2`
|
| 26 |
+
- `rollout.name=vllm`
|
| 27 |
+
|
| 28 |
+
3. Required configurations for LoRA:
|
| 29 |
+
|
| 30 |
+
- `actor_rollout_ref.model.lora_rank`: int, set to a reasonable value greater than 0 (e.g., 8, 16, 32, 64)
|
| 31 |
+
- `actor_rollout_ref.model.lora_alpha`: float, the alpha term in LoRA
|
| 32 |
+
- `actor_rollout_ref.rollout.load_format="safetensors"`: required. This enables vLLM to load the base model.
|
| 33 |
+
- `actor_rollout_ref.model.target_modules`: the target modules for LoRA. Typically set to "all-linear".
|
| 34 |
+
|
| 35 |
+
4. Recommend options:
|
| 36 |
+
|
| 37 |
+
- `actor_rollout_ref.model.use_shm=True`: preload the model into `/dev/shm` to improve model loading speed.
|
| 38 |
+
- `actor_rollout_ref.rollout.layered_summon=True`: this enables the actor-model to gather the FSDP shards per layers when synchronizing the LoRA Adapter to vLLM, thereby reducing GPU peak memory. Recommended if the model is very large (70B+) or the GPU memory is limited (< 48GB)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
Best Practices and Notes
|
| 42 |
+
-------------------------
|
| 43 |
+
|
| 44 |
+
1. **Learning rate**: it is recommended to increase the value of learning rate by an order of magnitude.
|
| 45 |
+
|
| 46 |
+
2. **LoRA Rank**:
|
| 47 |
+
|
| 48 |
+
- Too small a rank can hurt convergence.
|
| 49 |
+
- LoRA rank recommendation from @thelongestusernameofall:
|
| 50 |
+
|
| 51 |
+
- A very small lora_rank can lead to slower convergence or worse training performance. It is recommended to set lora_rank to be>=32. Tests have shown that for a 0.5B model, with lora_rank=32,the training convergence speed and final performance are almost identical to non-LoRA training
|
| 52 |
+
- For a 32B model,with lora_rank=128,the training convergence speed and final performance are also almost identical to non-LoRA training.
|
| 53 |
+
- More comprehensive reference results are coming soon.
|
| 54 |
+
|
| 55 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/f2b80b8b26829124dd393b7a795a0640eff11644/docs/lora.jpg?raw=true
|
| 56 |
+
|
| 57 |
+
3. Reference configuration for RL training with the Qwen2.5-72B model using 8 x 80GB GPUs (increase lora_rank if needed):
|
| 58 |
+
|
| 59 |
+
.. code-block::
|
| 60 |
+
|
| 61 |
+
data.train_batch_size=64 \
|
| 62 |
+
actor_rollout_ref.model.use_shm=True \
|
| 63 |
+
actor_rollout_ref.model.lora_rank=32 \
|
| 64 |
+
actor_rollout_ref.model.lora_alpha=32 \
|
| 65 |
+
actor_rollout_ref.model.target_modules=all-linear \
|
| 66 |
+
actor_rollout_ref.actor.optim.lr=3e-5 \
|
| 67 |
+
actor_rollout_ref.actor.fsdp_config.fsdp_size=8 \
|
| 68 |
+
actor_rollout_ref.actor.fsdp_config.param_offload=True \
|
| 69 |
+
actor_rollout_ref.actor.fsdp_config.optimizer_offload=True \
|
| 70 |
+
actor_rollout_ref.rollout.tensor_model_parallel_size=8 \
|
| 71 |
+
actor_rollout_ref.rollout.name=vllm \
|
| 72 |
+
actor_rollout_ref.rollout.gpu_memory_utilization=0.4 \
|
| 73 |
+
actor_rollout_ref.rollout.n=5 \
|
| 74 |
+
actor_rollout_ref.rollout.max_num_seqs=64 \
|
| 75 |
+
actor_rollout_ref.rollout.max_model_len=1536 \
|
| 76 |
+
actor_rollout_ref.rollout.max_num_batched_tokens=1536 \
|
| 77 |
+
actor_rollout_ref.rollout.load_format=safetensors \
|
| 78 |
+
actor_rollout_ref.rollout.layered_summon=True \
|
| 79 |
+
actor_rollout_ref.ref.fsdp_config.param_offload=True \
|
| 80 |
+
actor_rollout_ref.actor.ulysses_sequence_parallel_size=1 \
|
| 81 |
+
|
| 82 |
+
Example Script
|
| 83 |
+
-------------------
|
| 84 |
+
|
| 85 |
+
For an end-to-end example, refer to the script below:
|
| 86 |
+
|
| 87 |
+
examples/grpo_trainer/run_qwen2_5-3b_gsm8k_grpo_lora.sh
|
verl/docs/advance/rollout_skip.rst
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
RolloutSkip Function Usage Documentation
|
| 2 |
+
========================================
|
| 3 |
+
|
| 4 |
+
Last updated: 08/01/2025.
|
| 5 |
+
|
| 6 |
+
Applicable Scenarios
|
| 7 |
+
--------------------
|
| 8 |
+
|
| 9 |
+
The RolloutSkip functionality is designed to accelerate the rollout process in reinforcement learning training by caching and reusing previously generated sequences. This feature is particularly useful when:
|
| 10 |
+
|
| 11 |
+
1. You need to repeatedly run experiments with the same configuration
|
| 12 |
+
|
| 13 |
+
2. You want to save time by avoiding redundant sequence generation to come close to the optimal policy
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
API and Usage Example
|
| 17 |
+
----------------------
|
| 18 |
+
|
| 19 |
+
2.1 Trainer Adaptation
|
| 20 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 21 |
+
|
| 22 |
+
Both`RayDAPOTrainer()` (in `verl/recipe/dapo/dapo_ray_trainer.py`) and `RayPPOTrainer()`(in `verl/trainer/ppo/ray_trainer.py``) have already been adapted.
|
| 23 |
+
|
| 24 |
+
This is an example of how to patch rollout_skip in RayPPOTrainer.
|
| 25 |
+
|
| 26 |
+
.. code-block:: python
|
| 27 |
+
|
| 28 |
+
#* Import the RolloutSkip class
|
| 29 |
+
from verl.utils.rollout_skip import RolloutSkip
|
| 30 |
+
|
| 31 |
+
...
|
| 32 |
+
class RayPPOTrainer:
|
| 33 |
+
...
|
| 34 |
+
def fit(self):
|
| 35 |
+
...
|
| 36 |
+
|
| 37 |
+
#* Add code as follow:
|
| 38 |
+
rollout_skip = RolloutSkip(self.config, self.actor_rollout_wg)
|
| 39 |
+
rollout_skip.wrap_generate_sequences()
|
| 40 |
+
|
| 41 |
+
...
|
| 42 |
+
|
| 43 |
+
for epoch in range(self.config.trainer.total_epochs):
|
| 44 |
+
for batch_dict in self.train_dataloader:
|
| 45 |
+
...
|
| 46 |
+
|
| 47 |
+
2.2 Basic Configuration
|
| 48 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 49 |
+
|
| 50 |
+
Then, you should add the following parameters to your config to enable the RolloutSkip feature:
|
| 51 |
+
|
| 52 |
+
.. code-block:: bash
|
| 53 |
+
|
| 54 |
+
actor_rollout_ref.rollout.skip_rollout=True \
|
| 55 |
+
actor_rollout_ref.rollout.skip_dump_dir="/tmp/rollout_dump" \
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
Note:
|
| 59 |
+
|
| 60 |
+
1. The `skip_dump_dir` is the directory where the cached sequences will be stored. Ensure that this directory is writable and accessible by your training process. And make sure that `skip_dump_dir` is not relative path because ray will store the data in `/tmp/ray/session_<session_id>/` and the relative path will not be found in the worker.
|
| 61 |
+
2. The dumped data path follows this naming pattern `{experiment_name}_{project_name}_TrainGBS{train_gbs}__InferGBS{gen_gbs}__N{n}`, once you change the `experiment_name`, `project_name`, `train_gbs`, `gen_gbs`, or `n`, the cached data will be stored in a new directory.
|
verl/docs/advance/rollout_trace.rst
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Trace Function Usage Instructions
|
| 2 |
+
========================================
|
| 3 |
+
|
| 4 |
+
Last updated: 07/10/2025.
|
| 5 |
+
|
| 6 |
+
Applicable Scenarios
|
| 7 |
+
--------------------
|
| 8 |
+
|
| 9 |
+
Agentic RL involves multiple turns of conversations, tool invocations, and user interactions during the rollout process. During the Model Training process, it is necessary to track function calls, inputs, and outputs to understand the flow path of data within the application. The Trace feature helps, in complex multi-round conversations, to view the transformation of data during each interaction and the entire process leading to the final output by recording the inputs, outputs, and corresponding timestamps of functions, which is conducive to understanding the details of how the model processes data and optimizing the training results.
|
| 10 |
+
|
| 11 |
+
The Trace feature integrates commonly used Agent trace tools, including wandb weave and mlflow, which are already supported. Users can choose the appropriate trace tool according to their own needs and preferences. Here, we introduce the usage of each tool.
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
Trace Parameter Configuration
|
| 15 |
+
-----------------------------
|
| 16 |
+
|
| 17 |
+
- ``actor_rollout_ref.rollout.trace.backend=mlflow|weave`` # the trace backend type
|
| 18 |
+
- ``actor_rollout_ref.rollout.trace.token2text=True`` # To show decoded text in trace view
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
Glossary
|
| 22 |
+
--------
|
| 23 |
+
|
| 24 |
+
+----------------+------------------------------------------------------------------------------------------------------+
|
| 25 |
+
| Object | Explaination |
|
| 26 |
+
+================+======================================================================================================+
|
| 27 |
+
| trajectory | A complete multi-turn conversation includes: |
|
| 28 |
+
| | 1. LLM output at least once |
|
| 29 |
+
| | 2. Tool Call |
|
| 30 |
+
+----------------+------------------------------------------------------------------------------------------------------+
|
| 31 |
+
| step | The training step corresponds to the global_steps variable in the trainer |
|
| 32 |
+
+----------------+------------------------------------------------------------------------------------------------------+
|
| 33 |
+
| sample_index | The identifier of the sample, defined in the extra_info.index of the dataset. It is usually a number,|
|
| 34 |
+
| | but may also be a uuid in some cases. |
|
| 35 |
+
+----------------+------------------------------------------------------------------------------------------------------+
|
| 36 |
+
| rollout_n | In the GROP algorithm, each sample is rolled out n times. rollout_n represents the serial number of |
|
| 37 |
+
| | the rollout. |
|
| 38 |
+
+----------------+------------------------------------------------------------------------------------------------------+
|
| 39 |
+
| validate | Whether the test dataset is used for evaluation? |
|
| 40 |
+
+----------------+------------------------------------------------------------------------------------------------------+
|
| 41 |
+
|
| 42 |
+
Rollout trace functions
|
| 43 |
+
-----------------------
|
| 44 |
+
|
| 45 |
+
There are 2 functions used for tracing:
|
| 46 |
+
|
| 47 |
+
1. ``rollout_trace_op``: This is a decorator function used to mark the functions to trace. In default, only few method has it, you can add it to more functions to trace more infor.
|
| 48 |
+
2. ``rollout_trace_attr``: This function is used to mark the entry of a trajectory and input some info to trace. If you add new type of agent, you may need to add it to enable trace.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
Usage of wandb weave
|
| 52 |
+
--------------------
|
| 53 |
+
|
| 54 |
+
1.1 Basic Configuration
|
| 55 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 56 |
+
|
| 57 |
+
1. Set the ``WANDB_API_KEY`` environment variable
|
| 58 |
+
2. Configuration Parameters
|
| 59 |
+
|
| 60 |
+
1. ``actor_rollout_ref.rollout.trace.backend=weave``
|
| 61 |
+
2. ``trainer.logger=['console', 'wandb']``: This item is optional. Trace and logger are independent functions. When using Weave, it is recommended to also enable the wandb logger to implement both functions in one system.
|
| 62 |
+
3. ``trainer.project_name=$project_name``
|
| 63 |
+
4. ``trainer.experiment_name=$experiment_name``
|
| 64 |
+
5. ``actor_rollout_ref.rollout.mode=async``: Since trace is mainly used for agentic RL, need to enable agent toop using async mode for either vllm or sglang.
|
| 65 |
+
|
| 66 |
+
Note:
|
| 67 |
+
The Weave Free Plan comes with a default monthly network traffic allowance of 1GB. During the training process, the amount of trace data generated is substantial, reaching dozens of gigabytes per day, so it is necessary to select an appropriate wandb plan.
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
1.2 View Trace Logs
|
| 71 |
+
~~~~~~~~~~~~~~~~~~~
|
| 72 |
+
|
| 73 |
+
After executing the training, on the project page, you can see the WEAVE sidebar. Click Traces to view it.
|
| 74 |
+
|
| 75 |
+
Each Trace project corresponds to a trajectory. You can filter and select the trajectories you need to view by step, sample_index, rollout_n, and experiment_name.
|
| 76 |
+
|
| 77 |
+
After enabling token2text, prompt_text and response_text will be automatically added to the output of ToolAgentLoop.run, making it convenient to view the input and output content.
|
| 78 |
+
|
| 79 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/weave_trace_list.png?raw=true
|
| 80 |
+
|
| 81 |
+
1.3 Compare Trace Logs
|
| 82 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 83 |
+
|
| 84 |
+
Weave can select multiple trace items and then compare the differences among them.
|
| 85 |
+
|
| 86 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/weave_trace_compare.png?raw=true
|
| 87 |
+
|
| 88 |
+
Usage of mlflow
|
| 89 |
+
---------------
|
| 90 |
+
|
| 91 |
+
1. Basic Configuration
|
| 92 |
+
~~~~~~~~~~~~~~~~~~~~~~
|
| 93 |
+
|
| 94 |
+
1. Set the ``MLFLOW_TRACKING_URI`` environment variable, which can be:
|
| 95 |
+
|
| 96 |
+
1. Http and https URLs corresponding to online services
|
| 97 |
+
2. Local files or directories, such as ``sqlite:////tmp/mlruns.db``, indicate that data is stored in ``/tmp/mlruns.db``. When using local files, it is necessary to initialize the file first (e.g., start the UI: ``mlflow ui --backend-store-uri sqlite:////tmp/mlruns.db``) to avoid conflicts when multiple workers create files simultaneously.
|
| 98 |
+
|
| 99 |
+
2. Configuration Parameters
|
| 100 |
+
|
| 101 |
+
1. ``actor_rollout_ref.rollout.trace.backend=mlflow``
|
| 102 |
+
2. ``trainer.logger=['console', 'mlflow']``. This item is optional. Trace and logger are independent functions. When using mlflow, it is recommended to also enable the mlflow logger to implement both functions in one system.
|
| 103 |
+
3. ``trainer.project_name=$project_name``
|
| 104 |
+
4. ``trainer.experiment_name=$experiment_name``
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
2. View Log
|
| 108 |
+
~~~~~~~~~~~
|
| 109 |
+
|
| 110 |
+
Since ``trainer.project_name`` corresponds to Experiments in mlflow, in the mlflow view, you need to select the corresponding project name, then click the "Traces" tab to view traces. Among them, ``trainer.experiment_name`` corresponds to the experiment_name of tags, and tags corresponding to step, sample_index, rollout_n, etc., are used for filtering and viewing.
|
| 111 |
+
|
| 112 |
+
For example, searching for ``"tags.step = '1'"`` can display all trajectories of step 1.
|
| 113 |
+
|
| 114 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/mlflow_trace_list.png?raw=true
|
| 115 |
+
|
| 116 |
+
Opening one of the trajectories allows you to view each function call process within it.
|
| 117 |
+
|
| 118 |
+
After enabling token2text, prompt_text and response_text will be automatically added to the output of ToolAgentLoop.run, making it convenient to view the content.
|
| 119 |
+
|
| 120 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/mlflow_trace_view.png?raw=true
|
| 121 |
+
|
| 122 |
+
Note:
|
| 123 |
+
|
| 124 |
+
1. mlflow does not support comparing multiple traces
|
| 125 |
+
2. rollout_trace can not associate the mlflow trace with the run, so the trace content cannot be seen in the mlflow run logs.
|
verl/docs/advance/rope.rst
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
RoPE Scaling override
|
| 2 |
+
=======================================
|
| 3 |
+
|
| 4 |
+
Last updated: 05/14/2025.
|
| 5 |
+
|
| 6 |
+
Some models such as `Qwen/Qwen2.5-7B-Instruct <https://huggingface.co/Qwen/Qwen2.5-7B-Instruct#processing-long-texts>`_ support RoPE Scaling but don't have it defined in their config.json file.
|
| 7 |
+
For example, this model supports this configuration:
|
| 8 |
+
|
| 9 |
+
.. code:: python
|
| 10 |
+
|
| 11 |
+
{
|
| 12 |
+
...,
|
| 13 |
+
"rope_scaling": {
|
| 14 |
+
"factor": 4.0,
|
| 15 |
+
"original_max_position_embeddings": 32768,
|
| 16 |
+
"type": "yarn"
|
| 17 |
+
}
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
In order to support a longer context for such models, you must override the model configs when starting the trainer.
|
| 23 |
+
|
| 24 |
+
PPO example:
|
| 25 |
+
|
| 26 |
+
.. code:: bash
|
| 27 |
+
|
| 28 |
+
+actor_rollout_ref.model.override_config.rope_scaling.type=yarn \
|
| 29 |
+
+actor_rollout_ref.model.override_config.rope_scaling.factor=4.0 \
|
| 30 |
+
+actor_rollout_ref.model.override_config.rope_scaling.original_max_position_embeddings=32768 \
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
And for the critic model
|
| 34 |
+
|
| 35 |
+
.. code:: bash
|
| 36 |
+
|
| 37 |
+
+critic.model.override_config.rope_scaling.type=yarn \
|
| 38 |
+
+critic.model.override_config.rope_scaling.factor=4.0 \
|
| 39 |
+
+critic.model.override_config.rope_scaling.original_max_position_embeddings=32768 \
|
verl/docs/algo/baseline.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Algorithm Baselines
|
| 2 |
+
|
| 3 |
+
Last updated: 06/18/2025.
|
| 4 |
+
|
| 5 |
+
## Math related datasets
|
| 6 |
+
|
| 7 |
+
### GSM8k
|
| 8 |
+
|
| 9 |
+
Assuming GSM8k/math dataset is preprocessed via:
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
python3 examples/data_preprocess/*.py
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
Refer to the table below to reproduce RL training from different pre-trained checkpoints. Below is the performance on the GSM8k dataset if not specified otherwise. More comprehensive benchmark results areavailable in the recipe folder.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
| Hardware | Model | Method | Test score | Details |
|
| 19 |
+
|-------------|----------------------------------|-------------------|--------------|---------|
|
| 20 |
+
| NVIDIA GPU | google/gemma-2-2b-it | hf checkpoint | 23.9 | [Huggingface](https://huggingface.co/google/gemma-2-2b-it#benchmark-results) |
|
| 21 |
+
| NVIDIA GPU | google/gemma-2-2b-it | SFT | 52.06 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/gemma-2-2b-it-sft-0.411.log) |
|
| 22 |
+
| NVIDIA GPU | google/gemma-2-2b-it | SFT + PPO | 64.02 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/gemma-2-2b-it-ppo-bsz512_4-prompt1024-resp-512-0.640.log), [wandb](https://api.wandb.ai/links/verl-team/h7ux8602) |
|
| 23 |
+
| NVIDIA GPU | Qwen/Qwen2.5-0.5B-Instruct | hf checkpoint | 36.4 | [Qwen blog](https://qwenlm.github.io/blog/qwen2.5-llm/) |
|
| 24 |
+
| NVIDIA GPU | Qwen/Qwen2.5-0.5B-Instruct | PPO | 56.7 | [command and log](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-0.5B-bsz256_2-prompt1024-resp512-0.567.log) |
|
| 25 |
+
| NVIDIA GPU | Qwen/Qwen2.5-0.5B-Instruct | PRIME | 58.7 | [script](https://github.com/volcengine/verl/blob/main/recipe/prime/run_prime_qwen.sh), [wandb](https://api.wandb.ai/links/zefan-wang-thu-tsinghua-university/rxd1btvb) |
|
| 26 |
+
| NVIDIA GPU | Qwen/Qwen2.5-0.5B-Instruct | GRPO-LoRA | 54.3 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-0.5B-bsz64_2-prompt512-resp1024-lorarank32-score0.543.log)|
|
| 27 |
+
| NVIDIA GPU | Qwen/Qwen2.5-1.5B-Instruct | GRPO-LoRA | 77.9 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-1.5B-bsz64_2-prompt512-resp1024-lorarank32-score0.779.log)|
|
| 28 |
+
| NVIDIA GPU | Qwen/Qwen2.5-3B-Instruct | GRPO-LoRA | 86.1 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-3B-bsz64_2-prompt512-resp1024-lorarank32-score0.861.log)|
|
| 29 |
+
| NVIDIA GPU | deepseek-ai/deepseek-llm-7b-chat | PPO (Megatron) | 69.5 [1] | [log](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/deepseek-llm-7b-chat-megatron-bsz256_4-prompt512-resp512-0.695.log), [wandb](https://wandb.ai/verl-team/verl_megatron_gsm8k_examples/runs/10fetyr3) |
|
| 30 |
+
| NVIDIA GPU | Qwen/Qwen2-7B-Instruct | GRPO | 89 | [script](https://github.com/volcengine/verl/blob/a65c9157bc0b85b64cd753de19f94e80a11bd871/examples/grpo_trainer/run_qwen2-7b_seq_balance.sh) |
|
| 31 |
+
| NVIDIA GPU | Qwen/Qwen2-7B-Instruct | GRPO (FSDP2) | 89.8 | [log](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/qwen2-7b-fsdp2.log) |
|
| 32 |
+
| NVIDIA GPU | Qwen/Qwen2-7B-Instruct | GRPO (Megatron) | 89.6 | [log](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/qwen2-7b_math_megatron.log) |
|
| 33 |
+
| NVIDIA GPU | Qwen/Qwen2.5-7B-Instruct | ReMax | 97 | [script](https://github.com/eric-haibin-lin/verl/blob/main/examples/remax_trainer/run_qwen2.5-3b_seq_balance.sh), [wandb](https://wandb.ai/liziniu1997/verl_remax_example_gsm8k/runs/vxl10pln) |
|
| 34 |
+
| NVIDIA GPU | Qwen/Qwen2.5-7B-Instruct | SPPO | 65.6 (MATH) | [SPPO script](https://github.com/volcengine/verl/tree/main/recipe/sppo/README.md) |
|
| 35 |
+
| NVIDIA GPU | Qwen/Qwen2.5-7B-Instruct | GRPO-LoRA | 93.4 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-7B-bsz64_8-prompt512-resp1024-lorarank32-score0.934.log)|
|
| 36 |
+
| NVIDIA GPU | Mixtral-8x22B-Instruct-v0.1 | Instruct model | 83.7 | [Qwen Blog](https://qwenlm.github.io/blog/qwen2.5-llm/) |
|
| 37 |
+
| NVIDIA GPU | Mixtral-8x22B-Instruct-v0.1 | RLOO (Megatron) | 92.3 | [wandb](https://api.wandb.ai/links/ppo_dev/sbuiuf2d) |
|
| 38 |
+
| NVIDIA GPU | Qwen/Qwen2.5-7B-Instruct | SPIN | 92 | [script](https://github.com/volcengine/verl/tree/main/recipe/spin/README.md) |
|
| 39 |
+
| NVIDIA GPU | Qwen/Qwen2-7B-Instruct | GPG | 88 | [log](https://github.com/diqiuzhuanzhuan/verldata/blob/main/run_logs/qwen2-7b_math.log), [wandb](https://wandb.ai/diqiuzhuanzhuan/verl_gpg_example_gsm8k_math/runs/ab86c4va) |
|
| 40 |
+
| NVIDIA GPU | Qwen/Qwen2-7B-Instruct | GPG (Megatron) | 88 | [log](https://github.com/diqiuzhuanzhuan/verldata/blob/main/run_logs/qwen2-7b_math_megatron.log), [wandb](https://wandb.ai/diqiuzhuanzhuan/verl_gpg_example_gsm8k_math/runs/yy8bheu8) |
|
| 41 |
+
| NVIDIA GPU | Qwen/Qwen2.5-VL-7B-Instruct | GRPO (Megatron) | 65.4 (GEO3k) | [script](https://github.com/volcengine/verl/blob/main/examples/grpo_trainer/run_qwen2_5_vl-7b-megatron.sh), [wandb](https://api.wandb.ai/links/megatron-core-moe-dev/1yngvkek) |
|
| 42 |
+
| AMD MI300 | deepseek-ai/deepseek-llm-7b-chat | PPO | 70.5 [1] | [log](https://github.com/yushengsu-thu/verl_training_log/blob/main/gsm8k/ppo_run_deepseek7b_llm.log) |
|
| 43 |
+
| AMD MI300 | deepseek-ai/deepseek-llm-7b-chat | GRPO | 71.4 [1] | [log](https://github.com/yushengsu-thu/verl_training_log/blob/main/gsm8k/grpo_run_deepseek7b_llm.log) |
|
| 44 |
+
| NVIDIA GPU | Qwen/Qwen2.5-14B-Instruct | GRPO-LoRA | 94.6 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-14B-bsz64_8-prompt512-resp1024-lorarank32-score0.946.log)|
|
| 45 |
+
| NVIDIA GPU | Qwen/Qwen2.5-32B-Instruct | GRPO-LoRA | 95.8 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-32B-bsz64_8-prompt512-resp1024-lorarank32-score0.958.log)|
|
| 46 |
+
| NVIDIA GPU | Qwen/Qwen2.5-72B-Instruct | GRPO-LoRA | 96.0 | [command and logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-72B-bs64_8-prompt512-resp1024-lorarank32-score0.960.log)|
|
| 47 |
+
|
| 48 |
+
### DAPO math-17k
|
| 49 |
+
|
| 50 |
+
- Training DAPO math-17k dataset: https://huggingface.co/datasets/BytedTsinghua-SIA/DAPO-Math-17k
|
| 51 |
+
- Testing: AIME'24: https://huggingface.co/datasets/BytedTsinghua-SIA/AIME-2024
|
| 52 |
+
|
| 53 |
+
Note:
|
| 54 |
+
- For Qwen/Qwen2.5-Math-7B, we directly modify the max_position_embeddings to 32768 without observing performance degradation in order to train longer response length.
|
| 55 |
+
|
| 56 |
+
| Hardware | Model | Method | Test score | Details |
|
| 57 |
+
|-------------|-----------------------------|-------------------------|------------|---------|
|
| 58 |
+
| NVIDIA GPU | Qwen/Qwen2.5-Math-7B (32k) | DAPO | 36.3 | [command](https://github.com/volcengine/verl/blob/main/recipe/dapo/test_dapo_7b_math.sh), [logs](https://wandb.ai/verl-org/DAPO%20Reproduction%20on%20verl/runs/ow47vvon?nw=nwusertongyuxuan361)|
|
| 59 |
+
| NVIDIA GPU | Qwen/Qwen2.5-7B-Instruct | DAPO + Code Interpreter | 40.0 | [command](https://github.com/volcengine/verl/blob/main/recipe/retool/run_qwen2_7b_dapo.sh)|
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
## Coding related datasets
|
| 65 |
+
|
| 66 |
+
Below is the result on leetcode if not specified otherwise.
|
| 67 |
+
|
| 68 |
+
| Hardware | Model | Method | Test score | Details |
|
| 69 |
+
|-------------|----------------------------------|-------------------|--------------|---------|
|
| 70 |
+
| NVIDIA GPU | PRIME-RL/Eurus-2-7B-SFT | RPIME | 36.1 | [script](https://github.com/volcengine/verl/blob/main/recipe/prime/run_prime_qwen_code.sh), [swanlab](https://swanlab.cn/@wangzefan/prime_example/runs/7f541qhspgmy8nmhdlx35/chart) |
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
### Notes
|
| 74 |
+
|
| 75 |
+
[1] During evaluation, we have only extracted answers following the format `"####"`. A more flexible answer extraction, longer response length, and better prompt engineering may lead to a higher score.
|
| 76 |
+
|
| 77 |
+
[2] The default value of `actor_rollout_ref.actor.entropy_coeff` is set to `0.0` since verl 0.3.x on 2025-05-30, which is different from previous versions.
|
verl/docs/algo/collabllm.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Recipe: CollabLLM
|
| 2 |
+
|
| 3 |
+
Last updated: 09/22/2025.
|
| 4 |
+
|
| 5 |
+
> Open-Source Algorithm Implementation & Expriement Running: [Haiquan Chen](https://github.com/chenhaiq), [Shirley Wu](https://github.com/Wuyxin)
|
| 6 |
+
|
| 7 |
+
🏠 [Homepage](https://aka.ms/CollabLLM) | 📝 [Paper](https://arxiv.org/pdf/2502.00640) | 🤗 [Datasets & Models](https://huggingface.co/collabllm) | ⭐️ [Original Implementation](https://github.com/Wuyxin/collabllm)
|
| 8 |
+
|
| 9 |
+
`verl` provides a recipe for the Outstanding Paper at ICML 2025, **"CollabLLM: From Passive Responders to Active Collaborators"**. [CollabLLM](https://aka.ms/CollabLLM) is a unified fine-tuning framework that optimizes LLMs for effective and efficient multiturn collaboration with users.
|
| 10 |
+
|
| 11 |
+
**Core Idea:** Models are rewarded based on how well their responses enable effective *future* collaboration with users.
|
| 12 |
+
|
| 13 |
+
Paper Authors: [Shirley Wu](https://cs.stanford.edu/~shirwu/), [Michel Galley](https://www.microsoft.com/en-us/research/people/mgalley/), Baolin Peng, Hao Cheng, Gavin Li, Yao Dou, Weixin Cai, [James Zou](https://www.james-zou.com/), [Jure Leskovec](https://cs.stanford.edu/people/jure/), [Jianfeng Gao](https://www.microsoft.com/en-us/research/people/jfgao/)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
---
|
| 17 |
+
## Quick Start
|
| 18 |
+
|
| 19 |
+
### 0. Environment
|
| 20 |
+
Make sure the required packages for `verl` are installed. Additionally, install `litellm` and export the required API keys. The API model will be used for user simulators and, optionally, LLM Judges (see the Configuration section below).
|
| 21 |
+
|
| 22 |
+
### 1. Prepare Your Dataset
|
| 23 |
+
|
| 24 |
+
First, process your dataset using the provided script (see example commands and usage in `process_dataset.py`):
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
python process_dataset.py --dataset <> ... --dataset_type <sft or rl>
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
**Requirements:**
|
| 32 |
+
- Input: A Hugging Face multiturn dataset. Existing datasets: `collabllm/collabllm-multiturn-$DATASET`, with `DATASET` in one of [`math-hard(-large)`, `medium(-large)`, `bigcodebench(-large)`] (*-large are the datasets used in the CollabLLM paper)
|
| 33 |
+
- Example format: See [collabllm-multiturn-math-hard](https://huggingface.co/datasets/collabllm/collabllm-multiturn-math-hard)
|
| 34 |
+
- To generate your own dataset: Use [build_dataset.py](https://github.com/Wuyxin/collabllm/blob/main/scripts/engine/build_dataset.py) from the original CollabLLM repository
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
### 2. Train Your Model
|
| 38 |
+
|
| 39 |
+
**(Optional) For Supervised Fine-Tuning (SFT):**
|
| 40 |
+
```bash
|
| 41 |
+
bash train_sft_collabllm.sh
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
**For Reinforcement Learning (RL):**
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
bash train_rl_collabllm.sh
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
The RL script shows an example to train CollabLLM on `math-hard-large`.
|
| 51 |
+
|
| 52 |
+
- The config to sample future conversations are in `recipe/collabllm/config/collabllm_interaction_config.yaml`.
|
| 53 |
+
- The Multiturn-aware Reward is aggregated from these three conversational-level rewards:
|
| 54 |
+
|
| 55 |
+
```
|
| 56 |
+
+reward_model.reward_kwargs.metric_weights.accuracy=1 \
|
| 57 |
+
+reward_model.reward_kwargs.metric_weights.interactivity=1 \
|
| 58 |
+
+reward_model.reward_kwargs.metric_weights.token_amount=-0.0001 \
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
You can remove, add, or modify the weights depending on your task. A list of implemented metrics you can already add are under `recipe/collabllm/metrics`. For example, on `medium-large`, you can replace `accuracy` with `bleu_score` via
|
| 62 |
+
```
|
| 63 |
+
+reward_model.reward_kwargs.metric_weights.bleu_score=1
|
| 64 |
+
```
|
| 65 |
+
which will instead apply bleu score on the sampled future conversations.
|
| 66 |
+
|
| 67 |
+
## Algorithm
|
| 68 |
+
|
| 69 |
+
| Step | Name | Description |
|
| 70 |
+
|------|-------------------------------|-----------------------------------------------------------------------------|
|
| 71 |
+
| 1 | Model response generation | The model generates multiple responses for each prompt in a batch. |
|
| 72 |
+
| 2 | Collaborative simulation | A user simulator (e.g., GPT or Claude) samples `num_repeat_rollouts` conversations for up to `max_user_turns` additional turns. |
|
| 73 |
+
| 3 | Compute Multiturn-aware Reward | Customized conversational reward functions are applied to the sampled conversations. Rewards are aggregated, then averaged across rollouts. |
|
| 74 |
+
| 4 | Update model | The model weights are updated using the computed multiturn-aware rewards. |
|
| 75 |
+
|
| 76 |
+
---
|
| 77 |
+
|
| 78 |
+
## Configuration
|
| 79 |
+
|
| 80 |
+
The primary configuration is managed through the launch script `train_rl_collabllm.sh` and the YAML file `recipe/collabllm/config/collabllm_interaction_config.yaml`. Key configuration sections:
|
| 81 |
+
|
| 82 |
+
| Section | Key Parameters / Notes |
|
| 83 |
+
|----------------------|-----------------------------------------------------------------------------------------|
|
| 84 |
+
| `data` | Paths to training/validation files, batch sizes, sequence lengths. |
|
| 85 |
+
| `actor_rollout_ref` (common) | Base model path (used for actor + initial reference), FSDP settings, optimization (LR, scheduler). |
|
| 86 |
+
| `actor_rollout_ref` (CollabLLM-specific) | Hyperparameters under `actor_rollout_ref.rollout.multi_turn`: `max_user_turns`, `max_assistant_turns`, `num_repeat_rollouts`. |
|
| 87 |
+
| `interaction` | Defined in `collabllm_interaction_config.yaml`. Specifies user simulator and hyperparameters. Requires exported API keys. |
|
| 88 |
+
| `reward_model` | Manager set to `collabllm` by default. Modify `reward_model.reward_kwargs.metric_weights` for conversational rewards and weights. LLM Judge hyperparameters (e.g., `model`, `temperature`) go under `reward_model.reward_kwargs.llm_judge_kwargs`. |
|
| 89 |
+
| `algorithm` | GRPO-specific hyperparameters such as `actor_rollout_ref.rollout.n`. |
|
| 90 |
+
| `trainer` | Distributed training (nodes, GPUs per node), logging (WandB), checkpointing frequency. |
|
| 91 |
+
|
| 92 |
+
---
|
| 93 |
+
|
| 94 |
+
## Key Files
|
| 95 |
+
|
| 96 |
+
| File Path | Purpose |
|
| 97 |
+
|-----------|---------|
|
| 98 |
+
| `recipe/collabllm/collabllm_agent_loop.py` | Main logic to sample future conversations, using `CollabLLMInteraction` from `verl/interactions/collabllm_interaction.py`. |
|
| 99 |
+
| `verl/workers/reward_manager/collabllm.py` | Computes rewards for future conversations, leveraging `recipe/collabllm/reward_function.py` to apply each metric. |
|
| 100 |
+
|
| 101 |
+
---
|
| 102 |
+
|
| 103 |
+
## Acknowledgement
|
| 104 |
+
|
| 105 |
+
We sincerely thank the `verl` community and advisors for their contributions and guidance!
|
verl/docs/algo/dapo.md
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Recipe: Decoupled Clip and Dynamic Sampling Policy Optimization (DAPO)
|
| 2 |
+
|
| 3 |
+
Last updated: 06/19/2025.
|
| 4 |
+
|
| 5 |
+
> Open-Source Algorithm Implementation & Expriement Running: [Yuxuan Tong](https://tongyx361.github.io/), [Guangming Sheng](https://hk.linkedin.com/in/guangming-sheng-b50640211)
|
| 6 |
+
|
| 7 |
+
🏠 [Homepage](https://dapo-sia.github.io/) | 📝 [Paper@arXiv](https://arxiv.org/abs/2503.14476) | 🤗 [Datasets&Models@HF](https://huggingface.co/collections/BytedTsinghua-SIA/dapo-67d7f1517ee33c8aed059da0) | 🐱 [Code@GitHub](https://github.com/volcengine/verl/tree/recipe/dapo/recipe/dapo) | 🐱 [Repo@GitHub](https://github.com/BytedTsinghua-SIA/DAPO)
|
| 8 |
+
|
| 9 |
+
> We propose the **D**ecoupled Clip and Dynamic s**A**mpling **P**olicy **O**ptimization (DAPO) algorithm. By making our work publicly available, we provide the broader research community and society with practical access to scalable reinforcement learning, enabling all to benefit from these advancements. Our system is based on the awesome [verl](https://github.com/volcengine/verl) framework. Thanks for their great work! Applying DAPO training to Qwen2.5-32B base model proves to outperform the previous state-of-the-art DeepSeek-R1-Zero-Qwen-32B on AIME 2024, achieving **50%** accuracy with **50%** less training steps.
|
| 10 |
+
>
|
| 11 |
+
> 
|
| 12 |
+
|
| 13 |
+
## Quickstart
|
| 14 |
+
|
| 15 |
+
1. Prepare the datasets **on the Ray cluster**:
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
bash prepare_dapo_data.sh # This downloads the datasets to ${HOME}/verl/data by default
|
| 19 |
+
```
|
| 20 |
+
|
| 21 |
+
2. Submit the job to the Ray cluster **from any machine**:
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
cd verl # Repo root
|
| 25 |
+
export RAY_ADDRESS="http://${RAY_IP:-localhost}:8265" # The Ray cluster address to connect to
|
| 26 |
+
export WORKING_DIR="${PWD}" # The local directory to package to the Ray cluster
|
| 27 |
+
# Set the runtime environment like env vars and pip packages for the Ray cluster in yaml
|
| 28 |
+
export RUNTIME_ENV="./recipe/dapo/runtime_env.yaml" # This sets environment variables for the Ray cluster
|
| 29 |
+
bash recipe/dapo/run_dapo_qwen2.5_32b.sh # or other scripts
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
## Reproduction Runs
|
| 33 |
+
|
| 34 |
+
| Setup | AIME 2024 Acc. | Hardware | Image | Commit | Environment Variables | Training Script | Training Record |
|
| 35 |
+
| -------------------------------------------- | -------------- | --------- | -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
|
| 36 |
+
| DAPO | 52% | 16x8xH800 | `hiyouga/verl:ngc-th2.6.0-cu126-vllm0.8.3-flashinfer0.2.2-cxx11abi0` | [`4f80e4`](https://github.com/volcengine/verl/tree/4f80e465c2ec79ab9c3c30ec74b9745de61d0490) | [runtime_env.yaml](https://github.com/volcengine/verl/blob/4f80e465c2ec79ab9c3c30ec74b9745de61d0490/recipe/dapo/runtime_env.yaml) | [run_dapo_qwen2.5_32b.sh](https://github.com/volcengine/verl/blob/4f80e465c2ec79ab9c3c30ec74b9745de61d0490/recipe/dapo/run_dapo_qwen2.5_32b.sh) | [W&B](https://wandb.ai/verl-org/DAPO%20Reproduction%20on%20verl/workspace?nw=wmb4qxfht0n) |
|
| 37 |
+
| DAPO w/o Dynamic Sampling | 50% | 16x8xH800 | `hiyouga/verl:ngc-th2.6.0-cu126-vllm0.8.3-flashinfer0.2.2-cxx11abi0` | [`4f80e4`](https://github.com/volcengine/verl/tree/4f80e465c2ec79ab9c3c30ec74b9745de61d0490) | [runtime_env.yaml](https://github.com/volcengine/verl/blob/4f80e465c2ec79ab9c3c30ec74b9745de61d0490/recipe/dapo/runtime_env.yaml) | [run_dapo_wo_ds_qwen2.5_32b.sh](https://github.com/volcengine/verl/blob/4f80e465c2ec79ab9c3c30ec74b9745de61d0490/recipe/dapo/run_dapo_wo_ds_qwen2.5_32b.sh) | [W&B](https://wandb.ai/verl-org/DAPO%20Reproduction%20on%20verl/workspace?nw=wmb4qxfht0n) |
|
| 38 |
+
| DAPO w/o Token-level Loss & Dynamic Sampling | 44% | 16x8xH20 | `hiyouga/verl:ngc-th2.5.1-cu120-vllm0.7.4-hotfix` | [`4f80e4`](https://github.com/volcengine/verl/tree/4f80e465c2ec79ab9c3c30ec74b9745de61d0490) | [runtime_env.yaml](https://github.com/volcengine/verl/blob/4f80e465c2ec79ab9c3c30ec74b9745de61d0490/recipe/dapo/runtime_env.yaml) | [run_dapo_early_qwen2.5_32b.sh](https://github.com/volcengine/verl/blob/4f80e465c2ec79ab9c3c30ec74b9745de61d0490/recipe/dapo/run_dapo_early_qwen2.5_32b.sh) | [W&B](https://wandb.ai/verl-org/DAPO%20Reproduction%20on%20verl/workspace?nw=wmb4qxfht0n) |
|
| 39 |
+
|
| 40 |
+
> [!IMPORTANT]
|
| 41 |
+
>
|
| 42 |
+
> **📢 Call for Contribution!**
|
| 43 |
+
>
|
| 44 |
+
> Welcome to submit your reproduction runs and setups!
|
| 45 |
+
|
| 46 |
+
## Configuration
|
| 47 |
+
|
| 48 |
+
### Separated Clip Epsilons (-> Clip-Higher)
|
| 49 |
+
|
| 50 |
+
An example configuration:
|
| 51 |
+
|
| 52 |
+
```yaml
|
| 53 |
+
actor_rollout_ref:
|
| 54 |
+
actor:
|
| 55 |
+
clip_ratio_low: 0.2
|
| 56 |
+
clip_ratio_high: 0.28
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
`clip_ratio_low` and `clip_ratio_high` specify the $\varepsilon_{\text {low }}$ and $\varepsilon_{\text {high }}$ in the DAPO objective.
|
| 60 |
+
|
| 61 |
+
Core relevant code:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
pg_losses1 = -advantages * ratio
|
| 65 |
+
pg_losses2 = -advantages * torch.clamp(ratio, 1 - cliprange_low, 1 + cliprange_high)
|
| 66 |
+
pg_losses = torch.maximum(pg_losses1, pg_losses2)
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
### Dynamic Sampling (with Group Filtering)
|
| 70 |
+
|
| 71 |
+
An example configuration:
|
| 72 |
+
|
| 73 |
+
```yaml
|
| 74 |
+
data:
|
| 75 |
+
gen_batch_size: 1536
|
| 76 |
+
train_batch_size: 512
|
| 77 |
+
algorithm:
|
| 78 |
+
filter_groups:
|
| 79 |
+
enable: True
|
| 80 |
+
metric: acc # score / seq_reward / seq_final_reward / ...
|
| 81 |
+
max_num_gen_batches: 10 # Non-positive values mean no upper limit
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
Setting `filter_groups.enable` to `True` will filter out groups whose outputs' `metric` are all the same, e.g., for `acc`, groups whose outputs' accuracies are all 1 or 0.
|
| 85 |
+
|
| 86 |
+
The trainer will repeat sampling with `gen_batch_size` until there are enough qualified groups for `train_batch_size` or reaching the upper limit specified by `max_num_gen_batches`.
|
| 87 |
+
|
| 88 |
+
Core relevant code:
|
| 89 |
+
|
| 90 |
+
```python
|
| 91 |
+
prompt_bsz = self.config.data.train_batch_size
|
| 92 |
+
if num_prompt_in_batch < prompt_bsz:
|
| 93 |
+
print(f'{num_prompt_in_batch=} < {prompt_bsz=}')
|
| 94 |
+
num_gen_batches += 1
|
| 95 |
+
max_num_gen_batches = self.config.algorithm.filter_groups.max_num_gen_batches
|
| 96 |
+
if max_num_gen_batches <= 0 or num_gen_batches < max_num_gen_batches:
|
| 97 |
+
print(f'{num_gen_batches=} < {max_num_gen_batches=}. Keep generating...')
|
| 98 |
+
continue
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError(
|
| 101 |
+
f'{num_gen_batches=} >= {max_num_gen_batches=}. Generated too many. Please check your data.'
|
| 102 |
+
)
|
| 103 |
+
else:
|
| 104 |
+
# Align the batch
|
| 105 |
+
traj_bsz = self.config.data.train_batch_size * self.config.actor_rollout_ref.rollout.n
|
| 106 |
+
batch = batch[:traj_bsz]
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
### Flexible Loss Aggregation Mode (-> Token-level Loss)
|
| 110 |
+
|
| 111 |
+
An example configuration:
|
| 112 |
+
|
| 113 |
+
```yaml
|
| 114 |
+
actor_rollout_ref:
|
| 115 |
+
actor:
|
| 116 |
+
loss_agg_mode: "token-mean" # / "seq-mean-token-sum" / "seq-mean-token-mean"
|
| 117 |
+
# NOTE: "token-mean" is the default behavior
|
| 118 |
+
```
|
| 119 |
+
|
| 120 |
+
Setting `loss_agg_mode` to `token-mean` will mean the (policy gradient) loss across all the tokens in all the sequences in a mini-batch.
|
| 121 |
+
|
| 122 |
+
Core relevant code:
|
| 123 |
+
|
| 124 |
+
```python
|
| 125 |
+
if loss_agg_mode == "token-mean":
|
| 126 |
+
loss = verl_F.masked_mean(loss_mat, loss_mask)
|
| 127 |
+
elif loss_agg_mode == "seq-mean-token-sum":
|
| 128 |
+
seq_losses = torch.sum(loss_mat * loss_mask, dim=-1) # token-sum
|
| 129 |
+
loss = torch.mean(seq_losses) # seq-mean
|
| 130 |
+
elif loss_agg_mode == "seq-mean-token-mean":
|
| 131 |
+
seq_losses = torch.sum(loss_mat * loss_mask, dim=-1) / torch.sum(loss_mask, dim=-1) # token-mean
|
| 132 |
+
loss = torch.mean(seq_losses) # seq-mean
|
| 133 |
+
else:
|
| 134 |
+
raise ValueError(f"Invalid loss_agg_mode: {loss_agg_mode}")
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
### Overlong Reward Shaping
|
| 138 |
+
|
| 139 |
+
An example configuration:
|
| 140 |
+
|
| 141 |
+
```yaml
|
| 142 |
+
data:
|
| 143 |
+
max_response_length: 20480 # 16384 + 4096
|
| 144 |
+
reward_model:
|
| 145 |
+
overlong_buffer:
|
| 146 |
+
enable: True
|
| 147 |
+
len: 4096
|
| 148 |
+
penalty_factor: 1.0
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Setting `overlong_buffer.enable` to `True` will penalize the outputs whose lengths are overlong but still within the hard context limit.
|
| 152 |
+
|
| 153 |
+
Specifically, the penalty increases linearly from `0` to `overlong_buffer.penalty_factor` when the length of the output exceeds the `max_response_length` by `0` to `overlong_buffer.len` tokens.
|
| 154 |
+
|
| 155 |
+
Core relevant code:
|
| 156 |
+
|
| 157 |
+
```python
|
| 158 |
+
if self.overlong_buffer_cfg.enable:
|
| 159 |
+
overlong_buffer_len = self.overlong_buffer_cfg.len
|
| 160 |
+
expected_len = self.max_resp_len - overlong_buffer_len
|
| 161 |
+
exceed_len = valid_response_length - expected_len
|
| 162 |
+
overlong_penalty_factor = self.overlong_buffer_cfg.penalty_factor
|
| 163 |
+
overlong_reward = min(-exceed_len / overlong_buffer_len * overlong_penalty_factor, 0)
|
| 164 |
+
reward += overlong_reward
|
| 165 |
+
```
|
| 166 |
+
|
| 167 |
+
## FAQ
|
| 168 |
+
|
| 169 |
+
### Where is the "Overlong Filtering" in the paper?
|
| 170 |
+
|
| 171 |
+
Most experiments in the paper, including the best-performant one, are run without Overlong Filtering because it's somehow overlapping with Overlong Reward Shaping in terms of properly learning from the longest outputs. So we don't implement it here.
|
| 172 |
+
|
| 173 |
+
### What's the difference between [the `recipe/dapo` directory in the `main` branch](https://github.com/volcengine/verl/tree/main/recipe/dapo) and the [`recipe/dapo` branch](https://github.com/volcengine/verl/tree/recipe/dapo/recipe/dapo)?
|
| 174 |
+
|
| 175 |
+
[The `recipe/dapo` branch](https://github.com/volcengine/verl/tree/recipe/dapo/recipe/dapo) is for **as-is reproduction** and thus won't be updated with new features.
|
| 176 |
+
|
| 177 |
+
[The `recipe/dapo` directory in the `main` branch](https://github.com/volcengine/verl/tree/main/recipe/dapo) works as an example of how to extend the latest `verl` to implement an algorithm recipe, which will be maintained with new features.
|
| 178 |
+
|
| 179 |
+
### Why can't I produce similar results after modifications?
|
| 180 |
+
|
| 181 |
+
RL infrastructures nowadays still have inherent unrobustness, on which we are still working hard to improve.
|
| 182 |
+
|
| 183 |
+
We strongly recommend to only modify one thing at a time.
|
| 184 |
+
|
| 185 |
+
We also list some known problems here:
|
| 186 |
+
|
| 187 |
+
1. Enabling CUDA graph (`enforce_eager=False`) might cause model performance degradation, whose cause is still under investigation.
|
verl/docs/algo/entropy.md
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Recipe: Entropy Mechanism
|
| 2 |
+
|
| 3 |
+
Last updated: 06/27/2025.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
<div align="center">
|
| 7 |
+
|
| 8 |
+
The Entropy Mechanism of Reinforcement Learning for Large Language Model Reasoning.
|
| 9 |
+
|
| 10 |
+
[](https://arxiv.org/pdf/2505.22617) [](https://github.com/PRIME-RL/Entropy-Mechanism-of-RL) [](https://www.alphaxiv.org/abs/2505.22617) [](https://x.com/stingning/status/1928088554166505667) [](https://x.com/charlesfornlp/status/1928089451080585283) [](https://x.com/_akhaliq/status/1928077929105268861)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
<div align="center" style="font-family: Arial, sans-serif;">
|
| 15 |
+
<p>
|
| 16 |
+
<a href="#🎉news" style="text-decoration: none; font-weight: bold;">🎉 News</a> •
|
| 17 |
+
<a href="#✨getting-started" style="text-decoration: none; font-weight: bold;">✨ Getting Started</a> •
|
| 18 |
+
<a href="#📖introduction" style="text-decoration: none; font-weight: bold;">📖 Introduction</a>
|
| 19 |
+
</p>
|
| 20 |
+
<p>
|
| 21 |
+
<a href="#🎈citation" style="text-decoration: none; font-weight: bold;">🎈 Citation</a> •
|
| 22 |
+
<a href="#🌻acknowledgement" style="text-decoration: none; font-weight: bold;">🌻 Acknowledgement</a> •
|
| 23 |
+
<a href="#📬Contact" style="text-decoration: none; font-weight: bold;">📬 Contact</a> •
|
| 24 |
+
<a href="#📈star-history" style="text-decoration: none; font-weight: bold;">📈 Star History</a>
|
| 25 |
+
</p>
|
| 26 |
+
</div>
|
| 27 |
+
|
| 28 |
+
</div>
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
## 🎉News
|
| 32 |
+
|
| 33 |
+
- **[2025/05/29]** 🎉 Ranked **#1** of the day on [Huggingface Daily Papers](https://huggingface.co/papers?date=2025-05-29).
|
| 34 |
+
- **[2025/05/29]** Released our Paper on arXiv. See [here](https://arxiv.org/pdf/2505.22617). We provide insights into the entropy mechanism of RL for LLMs and propose two simple yet effective strategies to alleviate the entropy collapse.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
## ✨Getting started
|
| 39 |
+
|
| 40 |
+
After preparing the training data, for training Qwen2.5-7B on a single node, taking the KL-Cov approach as an example, you can simply run:
|
| 41 |
+
|
| 42 |
+
```
|
| 43 |
+
cd verl
|
| 44 |
+
conda activate your_env
|
| 45 |
+
bash recipe/dapo/7b_kl_cov.sh
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
While for training Qwen2.5-32B on multi nodes, you can run the following commands:
|
| 49 |
+
|
| 50 |
+
```
|
| 51 |
+
cd verl
|
| 52 |
+
conda activate your_env
|
| 53 |
+
bash recipe/dapo/32b_kl_cov.sh
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## 📖Introduction
|
| 57 |
+
|
| 58 |
+
<div align="left">
|
| 59 |
+
<img src="https://github.com/PRIME-RL/Entropy-Mechanism-of-RL/blob/main/figures/e2a.jpg?raw=true" alt="issue" style="width: 96%; height: auto;">
|
| 60 |
+
</div>
|
| 61 |
+
|
| 62 |
+
This paper addresses the entropy collapse issue in scaling reinforcement learning (RL) for large language models (LLMs), where policy entropy drops sharply during training, leading to overconfidence and performance saturation. We empirically establish a relationship between entropy ($H$) and performance ($R$): $R=−aexp(H)+b$, showing performance is bottlenecked by entropy exhaustion.
|
| 63 |
+
|
| 64 |
+
<div align="left">
|
| 65 |
+
<img src="https://github.com/PRIME-RL/Entropy-Mechanism-of-RL/blob/main/figures/cov.jpg?raw=true" alt="issue" style="width: 96%; height: auto;">
|
| 66 |
+
</div>
|
| 67 |
+
|
| 68 |
+
Theoretically, we find entropy changes are driven by the covariance between action probability and logit updates, which correlates with advantage in Policy Gradient methods. High-probability, high-advantage actions reduce entropy, while rare, high-advantage actions increase it. Empirically, the covariance term remains positive, explaining entropy’s monotonic decline. To mitigate this, we propose Clip-Cov and KL-Cov, which restrict updates for high-covariance tokens. These methods effectively prevent entropy collapse, and improve performance.
|
| 69 |
+
|
| 70 |
+
## 📃Evaluation
|
| 71 |
+
|
| 72 |
+
<div align="left">
|
| 73 |
+
<img src="https://github.com/PRIME-RL/Entropy-Mechanism-of-RL/blob/main/figures/performance_fig.jpg?raw=true" alt="issue" style="width: 96%; height: auto;">
|
| 74 |
+
</div>
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
Our method is able to maintain a considerably higher level of entropy throughout training. For example, when the baseline's entropy reaches a plateau and can no longer be consumed, the KL-Cov method still sustains an entropy level over 10 times higher. Meanwhile, the response length of the policy model steadily increases, and its performance on the test set consistently surpasses that of the baseline. This indicates that our model is able to explore more freely during training, learning better policy through RL.
|
| 78 |
+
| **Method** | **AIME24** | **AIME25** | **AMC** | **MATH-500** | **OMNI-MATH** | **OlympiadBench** | **Minerva** | **Avg.** |
|
| 79 |
+
| ----------------- | ---------: | ---------: | -------: | -----------: | ------------: | ----------------: | ----------: | -------: |
|
| 80 |
+
| *Qwen2.5-7B* | | | | | | | | |
|
| 81 |
+
| GRPO | 21.2 | 9.6 | 58.7 | 78.8 | 27.9 | 40.7 | 36.7 | 38.6 |
|
| 82 |
+
| w. Clip-higher | 18.1 | 11.5 | 56.6 | 79.2 | 29.8 | 43.3 | 40.4 | 38.8 |
|
| 83 |
+
| w. **`CLIP-Cov`** | 22.1 | **15.8** | 58.2 | 80.4 | **30.5** | **44.1** | **41.1** | 40.4 |
|
| 84 |
+
| w. **`KL-Cov`** | **22.6** | 12.9 | **61.4** | **80.8** | 29.1 | 42.6 | 38.2 | **40.6** |
|
| 85 |
+
| *Qwen2.5-32B* | | | | | | | | |
|
| 86 |
+
| GRPO | 21.8 | 16.2 | 69.7 | 84.2 | 35.2 | 43.6 | 45.5 | 45.8 |
|
| 87 |
+
| w. Clip-higher | 35.6 | 22.3 | 69.5 | 77.2 | 35.1 | 42.5 | 43.0 | 47.2 |
|
| 88 |
+
| w. **`CLIP-Cov`** | 32.3 | 22.7 | 67.2 | **87.0** | **42.0** | **57.2** | 46.0 | 50.3 |
|
| 89 |
+
| w. **`KL-Cov`** | **36.8** | **30.8** | **74.5** | 84.6 | 39.1 | 49.0 | **46.3** | **52.2** |
|
| 90 |
+
|
| 91 |
+
Our two approaches both achieve non-trivial improvements across all benchmarks. Compared to GRPO, our method outperforms it by 2.0% on average for the 7B model and by 6.4% for the 32B model. Moreover, we observe that our method yields more substantial gains on the larger Qwen2.5-32B. Specifically, our method achieves improvements of 15.0% and 14.6% compared to GRPO on the most challenging benchmarks, AIME24 and AIME25, respectively.
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
## 🎈Citation
|
| 95 |
+
If you find this paper or repo helpful, please cite us.
|
| 96 |
+
|
| 97 |
+
```bibtex
|
| 98 |
+
@article{cui2025entropy,
|
| 99 |
+
title={The Entropy Mechanism of Reinforcement Learning for Reasoning Language Models},
|
| 100 |
+
author={Cui, Ganqu and Zhang, Yuchen and Chen, Jiacheng and Yuan, Lifan and Wang, Zhi and Zuo, Yuxin and Li, Haozhan and Fan, Yuchen and Chen, Huayu and Chen, Weize and others},
|
| 101 |
+
journal={arXiv preprint arXiv:2505.22617},
|
| 102 |
+
year={2025}
|
| 103 |
+
}
|
| 104 |
+
```
|
| 105 |
+
## 🌻Acknowledgement
|
| 106 |
+
We implement our reinforcement learning algorithm extending from [verl](https://github.com/volcengine/verl). We utilize [vLLM](https://github.com/vllm-project/vllm) for inference. Our models are trained primarily on [Qwen2.5 family](https://github.com/QwenLM/Qwen2.5). Our training data is built from [DAPO-MATH](https://huggingface.co/datasets/BytedTsinghua-SIA/DAPO-Math-17k). Thanks for their great contributions!
|
| 107 |
+
|
| 108 |
+
## 📬 Contact
|
| 109 |
+
|
| 110 |
+
For questions, discussion, or collaboration opportunities, feel free to contact:
|
| 111 |
+
- Ganqu Cui: cuiganqu@pjlab.org.cn
|
| 112 |
+
- Yuchen Zhang: yuchen.zhang2003@gmail.com
|
| 113 |
+
- Jiacheng Chen: jackchan9345@gmail.com
|
| 114 |
+
- Ning Ding: ningding.cs@gmail.com
|
| 115 |
+
|
verl/docs/algo/gpg.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GPG: Group Policy Gradient
|
| 2 |
+
|
| 3 |
+
Last updated: 07/03/2025.
|
| 4 |
+
|
| 5 |
+
Group Policy Gradient (GPG) is a minimalist reinforcement learning (RL) method that enhances the reasoning ability of large language models without relying on supervised fine-tuning or complex tricks. GPG revisits traditional policy gradients and directly optimizes the RL objective—no surrogate losses, no KL penalties, no critic, and no reference model. Compared to GRPO, GPG is simpler, more efficient, and achieves better results on many tasks. For more details, please refer to the original paper [GPG: A Simple and Strong Reinforcement Learning Baseline for Model Reasoning
|
| 6 |
+
](https://arxiv.org/abs/2504.02546).
|
| 7 |
+
|
| 8 |
+
## Key Components
|
| 9 |
+
- Use a corrected advantage function to improve policy gradient accuracy and training efficiency.
|
| 10 |
+
- By eliminating the critic and reference models, avoiding KL divergence constraints, significantly simplifies the training process compared to Group Relative Policy Optimization (GRPO)
|
| 11 |
+
|
| 12 |
+
## Configuration
|
| 13 |
+
To configure GPG within the framework, use the following YAML settings.
|
| 14 |
+
|
| 15 |
+
```yaml
|
| 16 |
+
algorithm:
|
| 17 |
+
adv_estimator: gpg
|
| 18 |
+
actor_rollout_ref:
|
| 19 |
+
actor:
|
| 20 |
+
policy_loss:
|
| 21 |
+
loss_mode: "gpg"
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
## Advanced Extensions
|
| 25 |
+
GPG is a simple and strong baseline for model reasoning. Although it avoids using KL loss in its original form, you can still use KL loss to further improve the performance.
|
| 26 |
+
|
| 27 |
+
```yaml
|
| 28 |
+
algorithm:
|
| 29 |
+
adv_estimator: gpg
|
| 30 |
+
actor_rollout_ref:
|
| 31 |
+
actor:
|
| 32 |
+
use_kl_loss: True # enable kl regularization
|
| 33 |
+
kl_loss_coef: 0.01
|
| 34 |
+
policy_loss:
|
| 35 |
+
loss_mode: "gpg"
|
| 36 |
+
```
|
verl/docs/algo/grpo.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Group Relative Policy Optimization (GRPO)
|
| 2 |
+
|
| 3 |
+
Last updated: 05/31/2025.
|
| 4 |
+
|
| 5 |
+
In reinforcement learning, classic algorithms like PPO rely on a "critic" model to estimate the value of actions, guiding the learning process. However, training this critic model can be resource-intensive.
|
| 6 |
+
|
| 7 |
+
GRPO simplifies this process by eliminating the need for a separate critic model. Instead, it operates as follows:
|
| 8 |
+
- Group Sampling: For a given problem, the model generates multiple possible solutions, forming a "group" of outputs.
|
| 9 |
+
- Reward Assignment: Each solution is evaluated and assigned a reward based on its correctness or quality.
|
| 10 |
+
- Baseline Calculation: The average reward of the group serves as a baseline.
|
| 11 |
+
- Policy Update: The model updates its parameters by comparing each solution's reward to the group baseline, reinforcing better-than-average solutions and discouraging worse-than-average ones.
|
| 12 |
+
|
| 13 |
+
This approach reduces computational overhead by avoiding the training of a separate value estimation model, making the learning process more efficient. For more details, refer to the original paper [DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models](https://arxiv.org/pdf/2402.03300)
|
| 14 |
+
|
| 15 |
+
## Key Components
|
| 16 |
+
|
| 17 |
+
- No Value Function (Critic-less): unlike PPO, GRPO does not train a separate value network (critic)
|
| 18 |
+
- Group Sampling (Grouped Rollouts): instead of evaluating one rollout per input, GRPO generates multiple completions (responses) from the current policy for each prompt. This set of completions is referred to as a group.
|
| 19 |
+
- Relative Rewards: within each group, completions are scored (e.g., based on correctness), and rewards are normalized relative to the group.
|
| 20 |
+
|
| 21 |
+
## Configuration
|
| 22 |
+
|
| 23 |
+
Note that all configs containing `micro_batch_size` are used to configure the maximum sample or token count per forward or backward pass to avoid GPU OOMs, whose value should not change algorithmic/convergence behavior.
|
| 24 |
+
|
| 25 |
+
Despite that many configurations start with the `ppo_` prefix, they work across different RL algorithms in verl, as the GRPO training loop is similar to that of PPO (without critic).
|
| 26 |
+
|
| 27 |
+

|
| 28 |
+
|
| 29 |
+
- `actor_rollout.ref.rollout.n`: For each prompt, sample n times. Default to 1. For GRPO, please set it to a value larger than 1 for group sampling.
|
| 30 |
+
|
| 31 |
+
- `data.train_batch_size`: The global batch size of prompts used to generate a set of sampled trajectories/rollouts. The number of responses/trajectories is `data.train_batch_size * actor_rollout.ref.rollout.n`
|
| 32 |
+
|
| 33 |
+
- `actor_rollout_ref.actor.ppo_mini_batch_size`: The set of sampled trajectories is split into multiple mini-batches with batch_size=ppo_mini_batch_size for PPO actor updates. The ppo_mini_batch_size is a global size across all workers.
|
| 34 |
+
|
| 35 |
+
- `actor_rollout_ref.actor.ppo_epochs`: Number of epochs for GRPO updates on one set of sampled trajectories for actor
|
| 36 |
+
|
| 37 |
+
- `actor_rollout_ref.actor.clip_ratio`: The GRPO clip range. Default to 0.2
|
| 38 |
+
|
| 39 |
+
- `algorithm.adv_estimator`: Default is gae. Please set it to grpo instead
|
| 40 |
+
|
| 41 |
+
- `actor_rollout_ref.actor.loss_agg_mode`: Default is "token-mean". Options include "token-mean", "seq-mean-token-sum", "seq-mean-token-mean". The original GRPO paper takes the sample-level loss (seq-mean-token-mean), which may be unstable in long-CoT scenarios. All GRPO example scripts provided in verl uses the default configuration "token-mean" for loss aggregation instead.
|
| 42 |
+
|
| 43 |
+
Instead of adding KL penalty in the reward, GRPO regularizes by directly adding the KL divergence between the trained policy and the reference policy to the loss:
|
| 44 |
+
|
| 45 |
+
- `actor_rollout_ref.actor.use_kl_loss`: To use kl loss in the actor. When used, we are not applying KL in the reward function. Default is False. Please set it to True for GRPO.
|
| 46 |
+
|
| 47 |
+
- `actor_rollout_ref.actor.kl_loss_coef`: The coefficient of kl loss. Default is 0.001.
|
| 48 |
+
|
| 49 |
+
- `actor_rollout_ref.actor.kl_loss_type`: Support kl(k1), abs, mse(k2), low_var_kl(k3) and full. Appending "+" in the end (e.g., 'k1+' and 'k3+') would apply straight through to employ k2 for unbiased gradient estimation, regardless of the kl value estimation (see https://github.com/volcengine/verl/pull/2953#issuecomment-3162113848 for more details). How to calculate the kl divergence between actor and reference policy. See this blog post for detailed analysis: http://joschu.net/blog/kl-approx.html
|
| 50 |
+
|
| 51 |
+
## Advanced Extensions
|
| 52 |
+
|
| 53 |
+
### DrGRPO
|
| 54 |
+
|
| 55 |
+
[Understanding R1-Zero-Like Training: A Critical Perspective](https://arxiv.org/pdf/2503.20783) claims there's optimization bias in GRPO, which leads to artificially longer responses, especially for incorrect outputs. This inefficiency stems from the way GRPO calculates advantages using group-based reward normalization. Instead, DrGRPO aggregates token-level losses by normalizing with a global constant to eliminate length bias.
|
| 56 |
+
|
| 57 |
+
Configure the following to enable DrGRPO, with all other parameters the same as GRPO's:
|
| 58 |
+
|
| 59 |
+
- `actor_rollout_ref.actor.loss_agg_mode`: "seq-mean-token-sum-norm", which turns off seq-dim averaging
|
| 60 |
+
- `actor_rollout_ref.actor.use_kl_loss`: Please set it to False for DrGRPO
|
| 61 |
+
- `algorithm.norm_adv_by_std_in_grpo`: False, which turns off standard deviation norm
|
| 62 |
+
|
| 63 |
+
## Reference Example
|
| 64 |
+
|
| 65 |
+
Qwen2.5 GRPO training log and commands: [link](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/qwen2-7b-fsdp2.log)
|
| 66 |
+
|
| 67 |
+
```bash
|
| 68 |
+
bash examples/grpo_trainer/run_qwen3-8b.sh
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
For more reference performance, please see https://verl.readthedocs.io/en/latest/algo/baseline.html
|
verl/docs/algo/opo.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# On-Policy RL with Optimal Reward Baseline (OPO)
|
| 2 |
+
|
| 3 |
+
Last updated: 06/02/2025.
|
| 4 |
+
|
| 5 |
+
Loose on-policy constraints and suboptimal baselines in reinforcement learning often lead to training instability such as large policy shifts and entropy collapse. OPO addresses these challenges by using exact on-policy training with the theretically optimal reward baseline for advantage estimation. It achieves lower policy shifts and higher output entropy, encouraging more diverse and less repetitive responses.
|
| 6 |
+
|
| 7 |
+
OPO uses group sampling to generate multiple outputs for each input like GRPO. Unlike group-based algorithms which typically use the mean reward of a group as its baseline, OPO employs a theoretically optimal baseline: the length-weighted reward of the group. It also omits the standard deviation normalization. By adopting these two key components, OPO enables the training of a single policy model with the objective of maximizing only the expected reward. For more detailes, refer to the original paper [On-Policy RL with Optimal Reward Baseline](https://arxiv.org/pdf/2505.23585).
|
| 8 |
+
|
| 9 |
+
## Key Components
|
| 10 |
+
|
| 11 |
+
- Exact On-Policy Training: always generates responses from the current policy, without using any pre-generated data or off-policy data.
|
| 12 |
+
- Optimal Reward Baseline: uses a length-weighted reward of the group as the baseline for normalizing the rewards.
|
| 13 |
+
|
| 14 |
+
## Configuration
|
| 15 |
+
|
| 16 |
+
To configure OPO within the framework, use the following YAML settings. These parameters are crucial for enabling exact on-policy training and activating the optimal reward baseline.
|
| 17 |
+
|
| 18 |
+
```yaml
|
| 19 |
+
algorithm:
|
| 20 |
+
adv_estimator: opo # Use OPO for optimal reward baseline
|
| 21 |
+
data:
|
| 22 |
+
train_batch_size: 1024
|
| 23 |
+
actor_rollout_ref:
|
| 24 |
+
actor:
|
| 25 |
+
ppo_mini_batch_size: 1024 # ppo_mini_batch_size should equal to train_batch_size to enable exact on-policy training
|
| 26 |
+
entropy_coeff: 0 # disable entropy regularization
|
| 27 |
+
use_kl_loss: False # disable kl regularization
|
| 28 |
+
kl_loss_coef: 0
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
## Advanced Extensions
|
| 32 |
+
|
| 33 |
+
OPO can also be extended to other algorithms like RLOO and Reinforce++. It just needs to adjust their configurations to enable exact on-policy training and incorporate the optimal length-weighted reward baseline with minimal modifications to their advantage estimation functions.
|
verl/docs/algo/ppo.md
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Proximal Policy Optimization (PPO)
|
| 2 |
+
|
| 3 |
+
Last updated: 06/19/2025.
|
| 4 |
+
|
| 5 |
+
Proximal Policy Optimization (PPO) is a family of policy gradient methods for reinforcement learning, proposed by OpenAI in 2017. PPO strikes a balance between simplicity, stability, and performance, making it one of the most widely used algorithms in modern RL applications, including large-scale language model fine-tuning.
|
| 6 |
+
|
| 7 |
+
Traditional policy gradient methods like REINFORCE or Vanilla Policy Gradient suffer from:
|
| 8 |
+
|
| 9 |
+
- High variance and sample inefficiency.
|
| 10 |
+
- Instability due to large policy updates.
|
| 11 |
+
|
| 12 |
+
PPO addresses this problem using a clipped surrogate objective that avoids overly large updates without requiring second-order derivatives.
|
| 13 |
+
|
| 14 |
+
For more technical details regarding PPO, we suggest reading the introduction in the [OpenAI spinning up tutorial](https://spinningup.openai.com/en/latest/algorithms/ppo.html), and the paper [Proximal Policy Optimization Algorithms](https://arxiv.org/abs/1707.06347).
|
| 15 |
+
|
| 16 |
+
## Key Components
|
| 17 |
+
|
| 18 |
+
- Actor-Critic Architecture: PPO requires both an actor model (policy) and a critic model (value function). This differs from other algorithms like GRPO and RLOO that don't require a critic model.
|
| 19 |
+
|
| 20 |
+
- Generalized Advantage Estimation (GAE): PPO uses GAE for computing advantage values, which helps reduce variance in policy gradient estimates while maintaining low bias.
|
| 21 |
+
|
| 22 |
+
- Clipped Surrogate Objective: The core of PPO is implemented through the clipped surrogate objective function that limits policy updates.
|
| 23 |
+
|
| 24 |
+
## Configuration
|
| 25 |
+
|
| 26 |
+
Note that all configs containing `micro_batch_size` are used to configure the maximum sample or token count per forward or backward pass to avoid GPU OOMs, whose value should not change algorithmic/convergence behavior.
|
| 27 |
+
|
| 28 |
+
Most critic configs are similar to those of actors. Note that the critic model is omitted from the figure below.
|
| 29 |
+
|
| 30 |
+

|
| 31 |
+
|
| 32 |
+
- `data.train_batch_size`: The global batch size of prompts used to generate a set of sampled trajectories/rollouts. The number of responses/trajectories is `data.train_batch_size * actor_rollout.ref.rollout.n`
|
| 33 |
+
|
| 34 |
+
- `actor_rollout_ref.actor.ppo_mini_batch_size`: The set of sampled trajectories is split into multiple mini-batches with batch_size=ppo_mini_batch_size for PPO actor updates. The ppo_mini_batch_size is a global size across all workers
|
| 35 |
+
|
| 36 |
+
- `actor_rollout_ref.critic.ppo_mini_batch_size`: The set of sampled trajectories is split into multiple mini-batches with batch_size=ppo_mini_batch_size for PPO critic updates. The ppo_mini_batch_size is a global size across all workers
|
| 37 |
+
|
| 38 |
+
- `actor_rollout_ref.actor.clip_ratio`: The PPO clip range. Default to 0.2
|
| 39 |
+
|
| 40 |
+
- `actor_rollout_ref.actor.ppo_epochs`: Number of epochs for PPO updates on one set of sampled trajectories for actor
|
| 41 |
+
|
| 42 |
+
- `critic.ppo_epochs`: Number of epochs for PPO updates on one set of sampled trajectories for critic. Defaults to `actor_rollout_ref.actor.ppo_epochs`
|
| 43 |
+
|
| 44 |
+
- `algorithm.gemma`: discount factor
|
| 45 |
+
|
| 46 |
+
- `algorithm.lam`: The lambda term that trades off between bias and variance in the GAE estimator
|
| 47 |
+
|
| 48 |
+
- `algorithm.adv_estimator`: Support gae, grpo, reinforce_plus_plus, reinforce_plus_plus_baseline, rloo
|
| 49 |
+
|
| 50 |
+
## Advanced Extensions
|
| 51 |
+
|
| 52 |
+
### KL Divergence Control
|
| 53 |
+
|
| 54 |
+
Options to prevent the policy from diverging too far from a reference policy. Two mechanisms are available: KL reward penalty and KL loss. For more technical details, see [Training language models to follow instructions with human feedback](https://arxiv.org/abs/2203.02155)
|
| 55 |
+
|
| 56 |
+
Options to use KL loss for KL divergence control:
|
| 57 |
+
|
| 58 |
+
- `actor_rollout_ref.actor.use_kl_loss`: to use kl loss in the actor. When used, we are not applying KL in the reward function. Default is False
|
| 59 |
+
|
| 60 |
+
- `actor_rollout_ref.actor.kl_loss_coef`: The coefficient of kl loss. Default is 0.001.
|
| 61 |
+
|
| 62 |
+
- `actor_rollout_ref.actor.kl_loss_type`: Support kl(k1), abs, mse(k2), low_var_kl(k3) and full. Appending "+" in the end (e.g., 'k1+' and 'k3+') would apply straight through to employ k2 for unbiased gradient estimation, regardless of the kl value estimation (see https://github.com/volcengine/verl/pull/2953#issuecomment-3162113848 for more details). How to calculate the kl divergence between actor and reference policy. See this blog post for detailed analysis: http://joschu.net/blog/kl-approx.html
|
| 63 |
+
|
| 64 |
+
Options to use KL penalty in the reward:
|
| 65 |
+
|
| 66 |
+
- `algorithm.use_kl_in_reward`: Whether to enable in-reward kl penalty. Default is False.
|
| 67 |
+
|
| 68 |
+
- `algorithm.kl_penalty`: Support kl(k1), abs, mse(k2), low_var_kl(k3) and full. This defines the way to calculate the kl divergence between actor and reference policy. For specific options, refer to `kl_penalty` in core_algos.py. See this blog post for detailed analysis: http://joschu.net/blog/kl-approx.html
|
| 69 |
+
|
| 70 |
+
- `algorithm.kl_ctrl.kl_coef`: The (initial) coefficient of in-reward kl_penalty. Default is 0.001.
|
| 71 |
+
- `algorithm.kl_ctrl.type`: 'fixed' for FixedKLController and 'adaptive' for AdaptiveKLController.
|
| 72 |
+
- `algorithm.kl_ctrl.horizon`: See source code of AdaptiveKLController for details.
|
| 73 |
+
- `algorithm.kl_ctrl.target_kl`: See source code of AdaptiveKLController for details.
|
| 74 |
+
|
| 75 |
+
### Dual-clip PPO
|
| 76 |
+
|
| 77 |
+
The Dual-Clip PPO introduces a approach by applying a lower bound to the policy ratio when the advantage is less than zero, when multiplied by a large raito, does not exceed a specified lower bound.
|
| 78 |
+
|
| 79 |
+

|
| 80 |
+
|
| 81 |
+
- `actor_rollout_ref.actor.clip_ratio_c`: lower bound of the value for Dual-clip PPO, defaults to 3.0
|
| 82 |
+
|
| 83 |
+
## Reference Example
|
| 84 |
+
|
| 85 |
+
Qwen2.5 training log and commands: [link](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-0.5B-bsz256_2-prompt1024-resp512-0.567.log)
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
bash run_gemma.sh
|
| 89 |
+
trainer.n_gpus_per_node=1 \
|
| 90 |
+
actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
|
| 91 |
+
trainer.logger=console \
|
| 92 |
+
critic.model.path=Qwen/Qwen2.5-0.5B-Instruct \
|
| 93 |
+
actor_rollout_ref.model.path=Qwen/Qwen2.5-0.5B-Instruct \
|
| 94 |
+
data.train_batch_size=256 \
|
| 95 |
+
actor_rollout_ref.actor.ppo_mini_batch_size=64 \
|
| 96 |
+
actor_rollout_ref.actor.ppo_micro_batch_size=2 \
|
| 97 |
+
critic.ppo_micro_batch_size=2
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
Reference performance with verl v0.2:
|
| 101 |
+
|
| 102 |
+
| Model | Method | Score | Link |
|
| 103 |
+
|-------------------------------|------------------|-------|------------------------------------------------------------------------------------------------|
|
| 104 |
+
| Qwen/Qwen2.5-0.5B-Instruct | pretrained model | 36.4 | [Qwen Blog](https://qwenlm.github.io/blog/qwen2.5-llm/) |
|
| 105 |
+
| Qwen/Qwen2.5-0.5B-Instruct | PPO | 56.7 | [PPO Command and Logs](https://github.com/eric-haibin-lin/verl-data/blob/experiments/gsm8k/Qwen2.5-0.5B-bsz256_2-prompt1024-resp512-0.567.log) |
|
verl/docs/algo/spin.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Recipe: Self-Play Fine-Tuning (SPIN)
|
| 2 |
+
|
| 3 |
+
Last updated: 05/31/2025.
|
| 4 |
+
|
| 5 |
+
`verl` provides a recipe inspired by the paper **"Self-Play Fine-Tuning Converts Weak Language Models to Strong Language Models"** (SPIN). SPIN is a language model finetuning algorithm that enables iterative self-improvement through a self-play mechanism inspired by game theory.
|
| 6 |
+
|
| 7 |
+
**Core Idea:** Models learn by playing against themselves, reducing reliance on external preference datasets or stronger teacher models:
|
| 8 |
+
|
| 9 |
+
1. **Synthetic Data Generation:** The current model generates responses, creating its own training data from previous iterations.
|
| 10 |
+
2. **Two-Player Game Setup:** A game involving two players acted by a single LLM.
|
| 11 |
+
3. **Iterative Training:** The model progressively improves by refining its policy, with each iteration's model becoming the opponent for the next iteration.
|
| 12 |
+
|
| 13 |
+
Paper Authors: [Zixiang Chen](https://github.com/uclaml/SPIN)\*, [Yihe Deng](https://github.com/uclaml/SPIN)\*, [Huizhuo Yuan](https://scholar.google.com/citations?user=8foZzX4AAAAJ)\*, [Kaixuan Ji](https://scholar.google.com/citations?user=FOoKDukAAAAJ), [Quanquan Gu](https://web.cs.ucla.edu/~qgu/)
|
| 14 |
+
|
| 15 |
+
[[Webpage](https://uclaml.github.io/SPIN/)] [[Huggingface](https://huggingface.co/papers/2401.01335)] [[Paper](https://arxiv.org/abs/2401.01335)] [[Original Implementation](https://github.com/uclaml/SPIN)]
|
| 16 |
+
|
| 17 |
+
verl Implementation Authors: [Chendong Wang](https://cdwang96.github.io/), [Chenyang Zhao](https://github.com/zhaochenyang20)
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## Key Function (compute_online_dpo_loss) and Related works
|
| 22 |
+
SPIN (Chen et al., 2024) proposes an iterative self-play mechanism to fine-tune language models. In each iteration, SPIN's training objective, when using a logistic loss function, is equivalent to Direct Preference Optimization (DPO) loss (Rafailov et al., 2023).
|
| 23 |
+
|
| 24 |
+
This `verl` recipe realizes SPIN's core concept by using DPO loss iteratively (Xu et al., 2023; Xiong et al., 2023; Snorkel AI, 2024). This means that in each iteration, we fine-tune the LLM using DPO loss for preference optimization. Notably, Xu et al. (2023) explored iterative preference optimization with pairwise cringe loss, while Xiong et al. (2023) discussed how to bridge theory and practice for RLHF under KL constraints using iterative training. The concept of iterative preference learning was also explored in online DPO (Guo et al., 2024), which focuses on direct alignment from online AI feedback. In online DPO, preference data is dynamically updated during training, allowing the model to learn from its own generated data.
|
| 25 |
+
|
| 26 |
+
Specifically, we developed the **`compute_online_dpo_loss`** function and built this SPIN recipe on top of it. By incorporating online preference generation, this approach enables continuously refining language models without relying on fixed external preference datasets.
|
| 27 |
+
|
| 28 |
+
**Reference Papers:**
|
| 29 |
+
* [Self-Play Fine-Tuning Converts Weak Language Models to Strong Language Models](https://arxiv.org/abs/2401.01335) (Chen et al., 2024)
|
| 30 |
+
* [Direct Preference Optimization: Your Language Model is Secretly a Reward Model](https://arxiv.org/abs/2305.18290) (Rafailov et al., 2023)
|
| 31 |
+
* [Somethings are more cringe than others: Preference optimization with the pairwise cringe loss](https://arxiv.org/abs/2312.16682) (Xu et al., 2023)
|
| 32 |
+
* [Iterative preference learning from human feedback: Bridging theory and practice for rlhf under kl-constraint](https://arxiv.org/abs/2312.11456) (Xiong et al., 2023)
|
| 33 |
+
* [Snorkel-Mistral-PairRM-DPO](https://huggingface.co/snorkelai/Snorkel-Mistral-PairRM-DPO) (Snorkel AI, 2024)
|
| 34 |
+
* [Direct language model alignment from online ai feedback](https://arxiv.org/abs/2402.04792) (Guo et al., 2024)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
## Our Online DPO Implementation
|
| 38 |
+
|
| 39 |
+
Our `compute_online_dpo_loss` function adapts `verl`'s existing PPO infrastructure (based on `verl` v0.3.0.post1) for this iterative online DPO. Key aspects of our implementation include:
|
| 40 |
+
|
| 41 |
+
* **No Critic:** Unlike PPO, we omit the value function critic.
|
| 42 |
+
* **Dynamic Reference Model:** An explicit reference policy (`ref_policy_wg`) is used for DPO loss. This reference model's weights can be periodically updated from the actor (`ref_update_freq`), providing a dynamic baseline.
|
| 43 |
+
* **Online Preference Generation:** The `compute_onlineDPO_pref` function (in `core_algos.py`) dynamically creates chosen/rejected pairs based on a reward source (e.g., rule-based ranking for math problems).
|
| 44 |
+
* **DPO Loss Integration:** We replace PPO's policy loss with our `compute_online_dpo_loss` (in `core_algos.py`) within the actor update (`dp_actor.py`), directly optimizing the policy using the generated preferences.
|
| 45 |
+
* **Iterative Training Orchestration:** The `SpinTrainer` (in `spin_trainer.py`) manages the entire self-play loop: generation, preference labeling, optional reference model updates, and policy updates, enabling continuous self-improvement aligned with SPIN's principles.
|
| 46 |
+
|
| 47 |
+
---
|
| 48 |
+
## Algorithm
|
| 49 |
+
|
| 50 |
+
This recipe implements an Online algorithm adapted to the `verl` Reinforcement Learning framework, which provides an alternative to PPO for fine-tuning language models.
|
| 51 |
+
|
| 52 |
+
**Online Loop:** Instead of maximizing a scalar reward signal in PPO, this approach directly optimizes the policy model to align with preference data generated *online* during training:
|
| 53 |
+
|
| 54 |
+
1. **Generation:** The current model generates multiple responses for each prompt in a batch.
|
| 55 |
+
2. **Preference Labeling:** A function evaluates these generated responses to determine which one is preferred (chosen) and which is dispreferred (rejected). This can be done using a reward function or implicit ranking based on specific rules. (In this recipe, we use rule-based ranking on the math problem).
|
| 56 |
+
3. **Update:** This preference tuple (`prompt`, `chosen_response`, `rejected_response`) is used to update the actor model using `compute_online_dpo_loss`, comparing against a reference model.
|
| 57 |
+
|
| 58 |
+
**Connection with SPIN:**
|
| 59 |
+
Instead of only using a fixed target data distribution, the online generation loop in step 2 will dynamically change the target data distribution by using a certain Preference Labeling method (rule-based ranking on the math problem by selecting the better one in this recipe). This explores the direction mentioned in SPIN's paper Section 7 about "dynamically changing target data distribution" to potentially elevate LLM performance beyond the fixed human-annotated data ceiling.
|
| 60 |
+
|
| 61 |
+
---
|
| 62 |
+
|
| 63 |
+
## Reproduce the Experiment (Example Setup)
|
| 64 |
+
|
| 65 |
+
The following steps outline how to set up the environment and run the SPIN recipe, based on the provided test log using GSM8K and Qwen2.5-3B-Instruct.
|
| 66 |
+
|
| 67 |
+
1. **Setup Environment (Example using Docker):**
|
| 68 |
+
```bash
|
| 69 |
+
# Start a container with GPU access and shared memory
|
| 70 |
+
docker run -it --name spin_test --gpus all \
|
| 71 |
+
--shm-size=32g \
|
| 72 |
+
--ipc=host \
|
| 73 |
+
-v /path/to/host/.cache:/root/.cache \
|
| 74 |
+
-e HF_TOKEN=<YOUR_HUGGINGFACE_TOKEN> \
|
| 75 |
+
lmsysorg/sglang:latest \
|
| 76 |
+
/bin/bash
|
| 77 |
+
|
| 78 |
+
# Inside the container or on your host machine:
|
| 79 |
+
# Ensure /tmp is writable
|
| 80 |
+
mkdir -p /tmp
|
| 81 |
+
chmod 1777 /tmp
|
| 82 |
+
|
| 83 |
+
# Install Python 3.10 (if not present) and venv
|
| 84 |
+
sudo apt update
|
| 85 |
+
sudo apt install -y python3.10 python3.10-venv tmux
|
| 86 |
+
python3 -m ensurepip --upgrade
|
| 87 |
+
|
| 88 |
+
# Create and activate a virtual environment
|
| 89 |
+
python3 -m venv ~/.python/spin_env
|
| 90 |
+
source ~/.python/spin_env/bin/activate
|
| 91 |
+
|
| 92 |
+
# Install uv (fast package installer)
|
| 93 |
+
python3 -m pip install uv
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
2. **Install verl and Dependencies:**
|
| 97 |
+
```bash
|
| 98 |
+
# Clone the verl repository and checkout the spin branch
|
| 99 |
+
cd ~
|
| 100 |
+
git clone git@github.com:volcengine/verl.git && cd verl
|
| 101 |
+
|
| 102 |
+
# Install flash-attn (handle potential build issues)
|
| 103 |
+
python3 -m uv pip install wheel packaging
|
| 104 |
+
python3 -m uv pip install flash-attn --no-build-isolation --no-deps
|
| 105 |
+
|
| 106 |
+
# Install verl with sglang extras
|
| 107 |
+
python3 -m uv pip install -e ".[sglang]"
|
| 108 |
+
```
|
| 109 |
+
*Note: If `flash-attn` installation fails, try the manual steps again or consult its documentation.*
|
| 110 |
+
|
| 111 |
+
3. **Login & Download Data/Model:**
|
| 112 |
+
```bash
|
| 113 |
+
# Login to Weights & Biases (optional, for logging)
|
| 114 |
+
export WANDB_API_KEY=<YOUR_WANDB_API_KEY>
|
| 115 |
+
# wandb login
|
| 116 |
+
|
| 117 |
+
# Download the GSM8K dataset
|
| 118 |
+
python3 examples/data_preprocess/gsm8k.py --local_save_dir ~/data/gsm8k # Adjusted path
|
| 119 |
+
|
| 120 |
+
# Download the base model (Example: Qwen2.5-3B-Instruct)
|
| 121 |
+
huggingface-cli download Qwen/Qwen2.5-3B-Instruct --local-dir $HOME/models/Qwen2.5-3B-Instruct
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
4. **Configure:**
|
| 125 |
+
* Modify the configuration file (e.g., `config/spin_trainer.yaml` or the one specified in the run script) with correct paths to your downloaded model, data, desired hyperparameters (`dpo_beta`, learning rate, etc.), and distributed training settings (nodes, GPUs per node).
|
| 126 |
+
* Pay attention to `actor_rollout_ref.model_path`, `data` paths, `reward_model` config (if using one), and `trainer.ref_update_freq`.
|
| 127 |
+
|
| 128 |
+
5. **Run Training:**
|
| 129 |
+
```bash
|
| 130 |
+
# Set CUDA visible devices (adjust based on your hardware and config)
|
| 131 |
+
export CUDA_VISIBLE_DEVICES=0,1,2,3
|
| 132 |
+
|
| 133 |
+
# Launch the training script (e.g., test.sh or a custom script)
|
| 134 |
+
# Ensure test.sh points to the correct config and main script
|
| 135 |
+
bash recipe/spin/run_spin.sh
|
| 136 |
+
```
|
| 137 |
+
|
| 138 |
+
---
|
| 139 |
+
|
| 140 |
+
## Configuration
|
| 141 |
+
|
| 142 |
+
* The primary configuration is typically managed through a YAML file specified in the launch script (e.g., `config/spin_trainer.yaml`).
|
| 143 |
+
* Key configuration sections:
|
| 144 |
+
* `data`: Paths to training/validation prompt files, batch sizes, sequence lengths.
|
| 145 |
+
* `actor_rollout_ref`: Paths to the base model (used for actor and initial reference), FSDP settings, optimization parameters (learning rate, scheduler).
|
| 146 |
+
* `reward_model`: Configuration for the reward model used for online preference labeling (path, batch size, etc.). Can be omitted if using a simpler reward function.
|
| 147 |
+
* `algorithm`: DPO-specific hyperparameters like `dpo_beta`, `dpo_loss_type`.
|
| 148 |
+
* `trainer`: Distributed training settings (nodes, GPUs per node), logging (WandB), checkpointing frequency, and `ref_update_freq` (set > 0 to enable periodic reference model updates from the actor).
|
| 149 |
+
|
| 150 |
+
---
|
| 151 |
+
|
| 152 |
+
## Key Files
|
| 153 |
+
|
| 154 |
+
* `main_spin.py`: Main entry point using Hydra to load the config and launch the `SpinTrainer`.
|
| 155 |
+
* `spin_trainer.py`: Defines the `SpinTrainer` class, orchestrating the Online DPO training loop.
|
| 156 |
+
* `fsdp_workers.py`: Implements Ray workers (Actor, Reference) potentially using FSDP.
|
| 157 |
+
* `dp_actor.py`: Contains the actor class, including the DPO policy update logic.
|
| 158 |
+
* `core_algos.py`: Includes helper functions for `compute_online_dpo_loss` and `compute_onlineDPO_pref`.
|
| 159 |
+
* `config/spin_trainer.yaml` (or similar): Main Hydra configuration file for the recipe.
|
| 160 |
+
* `run_spin.sh` (or similar): Example bash script for launching a training run.
|
| 161 |
+
* `README.md`: This file.
|
| 162 |
+
|
| 163 |
+
---
|
| 164 |
+
|
| 165 |
+
## Acknowledgement
|
| 166 |
+
|
| 167 |
+
We sincerely thank the contribution and guidance from the `verl` community and advisors, including (adapted from SPPO):
|
| 168 |
+
|
| 169 |
+
* [Zixiang Chen](https://sites.google.com/view/zxchen)
|
| 170 |
+
* [Yuhao Yang](https://github.com/yhyang201)
|
| 171 |
+
* [Yifan Zhang](https://github.com/yifanzhang-pro)
|
| 172 |
+
* [Yongan Xiang](https://github.com/BearBiscuit05)
|
| 173 |
+
* [Junrong Lin](https://github.com/ocss884)
|
| 174 |
+
* [Yuxuan Tong](https://github.com/tongyx361)
|
| 175 |
+
* [Guangming Shen](https://github.com/PeterSH6)
|
| 176 |
+
* [Biao He](https://www.linkedin.com/in/biao-he/)
|
| 177 |
+
* [Qingquan Song](https://qingquansong.github.io/)
|
| 178 |
+
* [Chenyang Zhao](https://zhaochenyang20.github.io/Chayenne/)
|
| 179 |
+
* [Quanquan Gu](https://web.cs.ucla.edu/~qgu/)
|
verl/docs/algo/sppo.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Recipe: Self-Play Preference Optimization (SPPO)
|
| 2 |
+
|
| 3 |
+
Last updated: 05/28/2025.
|
| 4 |
+
|
| 5 |
+
verl provides a community recipe implementation for the paper [Self-Play Preference Optimization for Language Model Alignment](https://arxiv.org/abs/2405.00675). SPPO can significantly enhance the performance of an LLM without strong external signals such as responses or preferences from GPT-4. It can outperform the model trained with iterative direct preference optimization (DPO), among other methods. SPPO is theoretically grounded, ensuring that the LLM can converge to the von Neumann winner (i.e., Nash equilibrium) under general, potentially intransitive preference, and empirically validated through extensive evaluations on multiple datasets.
|
| 6 |
+
|
| 7 |
+
Paper Authors: [Yue Wu](https://yuewu.us/)\*, [Zhiqing Sun](https://www.cs.cmu.edu/~zhiqings/)\*, [Huizhuo Yuan](https://scholar.google.com/citations?user=8foZzX4AAAAJ)\*, [Kaixuan Ji](https://scholar.google.com/citations?user=FOoKDukAAAAJ), [Yiming Yang](https://www.cs.cmu.edu/~yiming/), [Quanquan Gu](https://web.cs.ucla.edu/~qgu/)
|
| 8 |
+
|
| 9 |
+
verl Implementation Authors: [Yuhao Yang](https://github.com/yhyang201), [Chenyang Zhao](https://github.com/zhaochenyang20)
|
| 10 |
+
|
| 11 |
+
[[Webpage](https://uclaml.github.io/SPPO/)] [[Huggingface](https://huggingface.co/papers/2405.00675)] [[Paper](https://arxiv.org/abs/2405.00675)][[Original Implementation](https://github.com/uclaml/SPPO)]
|
| 12 |
+
|
| 13 |
+
## Reproduce the Experiment
|
| 14 |
+
|
| 15 |
+
We evaluate the performance of SPPO on the MATH dataset. Starting from an initial score of 46.6 with Qwen2.5-7B-Instruct, we achieve a score of 65.6 after 20 epochs of training, placing our model approximately in the top 20 on the [MATH leaderboard](https://paperswithcode.com/sota/math-word-problem-solving-on-math). It's important to note that verl's internal evaluation metrics may not perfectly align with the official evaluation methodology for Qwen2.5-7B-Instruct. Therefore, for consistency and fair comparison, we report only the results based on verl's evaluation framework.
|
| 16 |
+
|
| 17 |
+
```
|
| 18 |
+
git clone git@github.com:volcengine/verl.git
|
| 19 |
+
cd verl
|
| 20 |
+
python3 -m uv pip install -e ".[sglang]"
|
| 21 |
+
|
| 22 |
+
export WANDB_API_KEY=<YOUR_WANDB_API_KEY>
|
| 23 |
+
|
| 24 |
+
python3 examples/data_preprocess/math_dataset.py --local_dir ~/data/math
|
| 25 |
+
huggingface-cli download Qwen/Qwen2.5-7B-Instruct --local-dir $HOME/models/Qwen2.5-7B-Instruct
|
| 26 |
+
|
| 27 |
+
export CUDA_VISIBLE_DEVICES=0,1,2,3
|
| 28 |
+
bash recipe/sppo/run_qwen2.5-7b_rm.sh
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
Note that the installation would occasionally fail to install flash-attn. If this happens, you can install it manually by running:
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
python3 -m uv pip install wheel
|
| 35 |
+
python3 -m uv pip install packaging
|
| 36 |
+
python3 -m uv pip install flash-attn --no-build-isolation --no-deps
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
## Acknowledgement
|
| 40 |
+
|
| 41 |
+
We sincerely thank the contribution and guidance from:
|
| 42 |
+
|
| 43 |
+
- [Yue Wu](https://yuewu.us/)
|
| 44 |
+
- [Chendong Wang](https://cdwang96.github.io/)
|
| 45 |
+
- [Yifan Zhang](https://github.com/yifanzhang-pro)
|
| 46 |
+
- [Yongan Xiang](https://github.com/BearBiscuit05)
|
| 47 |
+
- [Junrong Lin](https://github.com/ocss884)
|
| 48 |
+
- [Yuxuan Tong](https://github.com/tongyx361)
|
| 49 |
+
- [Guangming Shen](https://github.com/PeterSH6)
|
| 50 |
+
- [Biao He](https://www.linkedin.com/in/biao-he/)
|
| 51 |
+
- [Qingquan Song](https://qingquansong.github.io/)
|
| 52 |
+
- [Quanquan Gu](https://web.cs.ucla.edu/~qgu/)
|
verl/docs/amd_tutorial/amd_build_dockerfile_page.rst
ADDED
|
@@ -0,0 +1,796 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Getting started with AMD (ROCM Kernel)
|
| 2 |
+
=====================================================
|
| 3 |
+
|
| 4 |
+
Last updated: 07/06/2025.
|
| 5 |
+
|
| 6 |
+
Author: `Yusheng Su <https://yushengsu-thu.github.io/>`_
|
| 7 |
+
|
| 8 |
+
Setup
|
| 9 |
+
-----
|
| 10 |
+
|
| 11 |
+
If you run on AMD GPUs (MI300) with ROCM platform, you cannot use the previous quickstart to run verl. You should follow the following steps to build a docker and set ``RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES`` or ``RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES`` when starting ray in verl's RLHF training.
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
docker/Dockerfile.rocm
|
| 15 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 16 |
+
|
| 17 |
+
.. code-block:: bash
|
| 18 |
+
|
| 19 |
+
FROM "rlsys/rocm-6.3.4-patch:rocm6.3.4-numa-patch_ubuntu-22.04"
|
| 20 |
+
|
| 21 |
+
SHELL ["/bin/bash", "-ceuxo", "pipefail"]
|
| 22 |
+
|
| 23 |
+
ENV MAX_JOBS=512
|
| 24 |
+
|
| 25 |
+
ENV PATH="/usr/local/python3.12/bin:$PATH"
|
| 26 |
+
RUN ln -sf /usr/bin/python3.12 /usr/bin/python && \
|
| 27 |
+
ln -sf /usr/bin/pip3.12 /usr/bin/pip
|
| 28 |
+
|
| 29 |
+
############################################
|
| 30 |
+
RUN apt-get update
|
| 31 |
+
RUN apt-get install -y pkg-config liblzma-dev
|
| 32 |
+
############################################
|
| 33 |
+
|
| 34 |
+
###########################################
|
| 35 |
+
##########Install TransformerEngine########
|
| 36 |
+
###########################################
|
| 37 |
+
WORKDIR /workspace/
|
| 38 |
+
# transformer-engine install
|
| 39 |
+
# https://github.com/ROCm/TransformerEngine
|
| 40 |
+
RUN rm -rf TransformerEngine
|
| 41 |
+
RUN git clone --recursive https://github.com/ROCm/TransformerEngine.git
|
| 42 |
+
WORKDIR /workspace/TransformerEngine
|
| 43 |
+
git checkout 236178e5
|
| 44 |
+
# git checkout bb061ade
|
| 45 |
+
# git checkout 864405c
|
| 46 |
+
ENV NVTE_FRAMEWORK=pytorch
|
| 47 |
+
ENV NVTE_ROCM_ARCH=gfx942
|
| 48 |
+
ENV NVTE_USE_HIPBLASLT=1
|
| 49 |
+
ENV NVTE_USE_ROCM=1
|
| 50 |
+
# export CMAKE_PREFIX_PATH="/opt/rocm:/opt/rocm/hip:/usr/local:/usr:${CMAKE_PREFIX_PATH:-}"
|
| 51 |
+
ENV CMAKE_PREFIX_PATH="/opt/rocm:/opt/rocm/hip:/usr/local:/usr"
|
| 52 |
+
RUN MAX_JOBS=$(MAX_JOBS) pip install . -vvv
|
| 53 |
+
WORKDIR /workspace/
|
| 54 |
+
###########################################
|
| 55 |
+
###########################################
|
| 56 |
+
###########################################
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
####################################################################################
|
| 63 |
+
################Install vllm - sglang require vllm 0.6.7 dependency#################
|
| 64 |
+
####################################################################################
|
| 65 |
+
#### Require vllm 0.6.7 - checkout 113274a0
|
| 66 |
+
WORKDIR /workspace/
|
| 67 |
+
RUN rm -rf vllm
|
| 68 |
+
RUN pip uninstall -y vllm
|
| 69 |
+
# Refer to here (down-grade vllm to 0.6.3): https://docs.vllm.ai/en/v0.6.3/getting_started/amd-installation.html
|
| 70 |
+
RUN git clone https://github.com/ROCm/vllm.git
|
| 71 |
+
# git clone https://github.com/vllm-project/vllm.git
|
| 72 |
+
WORKDIR /workspace/vllm
|
| 73 |
+
RUN git checkout 113274a0
|
| 74 |
+
ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942"
|
| 75 |
+
#ENV MAX_JOBS=512
|
| 76 |
+
ENV MAX_JOBS=${MAX_JOBS}
|
| 77 |
+
RUN pip install "boto3>=1.26.0"
|
| 78 |
+
RUN pip install setuptools_scm
|
| 79 |
+
# will add src into py. You can delete the repo
|
| 80 |
+
RUN python3 setup.py install
|
| 81 |
+
WORKDIR /workspace/
|
| 82 |
+
####################################################################################
|
| 83 |
+
####################################################################################
|
| 84 |
+
####################################################################################
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
###########################################
|
| 89 |
+
############For hack docker################
|
| 90 |
+
###########################################
|
| 91 |
+
RUN pip install setuptools==75.8.0
|
| 92 |
+
###########################################
|
| 93 |
+
###########################################
|
| 94 |
+
###########################################
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
###########################################
|
| 99 |
+
############build sgalng###################
|
| 100 |
+
###########################################
|
| 101 |
+
# Set environment variables
|
| 102 |
+
ENV BASE_DIR=/sgl-workspace
|
| 103 |
+
ENV BUILD_TYPE=all
|
| 104 |
+
ENV SGL_REPO=https://github.com/sgl-project/sglang
|
| 105 |
+
ENV SGL_BRANCH=v0.4.6.post5
|
| 106 |
+
ENV TRITON_REPO=https://github.com/ROCm/triton.git
|
| 107 |
+
ENV TRITON_COMMIT=improve_fa_decode_3.0.0
|
| 108 |
+
ENV AITER_REPO=https://github.com/ROCm/aiter.git
|
| 109 |
+
ENV AITER_COMMIT=v0.1.2
|
| 110 |
+
# v0.1.2 version - commit id: 9d11f47
|
| 111 |
+
# ENV AITER_COMMIT=9d11f47
|
| 112 |
+
ENV HIP_FORCE_DEV_KERNARG=1
|
| 113 |
+
ENV HSA_NO_SCRATCH_RECLAIM=1
|
| 114 |
+
ENV SGLANG_SET_CPU_AFFINITY=1
|
| 115 |
+
ENV SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1
|
| 116 |
+
ENV NCCL_MIN_NCHANNELS=112
|
| 117 |
+
ENV MOE_PADDING=1
|
| 118 |
+
ENV VLLM_FP8_PADDING=1
|
| 119 |
+
ENV VLLM_FP8_ACT_PADDING=1
|
| 120 |
+
ENV VLLM_FP8_WEIGHT_PADDING=1
|
| 121 |
+
ENV VLLM_FP8_REDUCE_CONV=1
|
| 122 |
+
ENV TORCHINDUCTOR_MAX_AUTOTUNE=1
|
| 123 |
+
ENV TORCHINDUCTOR_MAX_AUTOTUNE_POINTWISE=1
|
| 124 |
+
ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942"
|
| 125 |
+
ENV AMDGPU_TARGETS=gfx942
|
| 126 |
+
ENV ROCM_ARCH=gfx942
|
| 127 |
+
ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942"
|
| 128 |
+
# Switch to working directory
|
| 129 |
+
WORKDIR /sgl-workspace
|
| 130 |
+
# Clean and create directory
|
| 131 |
+
RUN rm -rf /sgl-workspace && mkdir -p /sgl-workspace
|
| 132 |
+
|
| 133 |
+
# Clone and build sglang
|
| 134 |
+
RUN git clone ${SGL_REPO} \
|
| 135 |
+
&& cd sglang \
|
| 136 |
+
&& git checkout ${SGL_BRANCH} || echo "Using default branch" \
|
| 137 |
+
&& cd sgl-kernel \
|
| 138 |
+
&& rm -f pyproject.toml \
|
| 139 |
+
&& mv pyproject_rocm.toml pyproject.toml \
|
| 140 |
+
&& python setup_rocm.py install \
|
| 141 |
+
&& cd .. \
|
| 142 |
+
&& if [ "$BUILD_TYPE" = "srt" ]; then \
|
| 143 |
+
python -m pip --no-cache-dir install -e "python[srt_hip]"; \
|
| 144 |
+
else \
|
| 145 |
+
python -m pip --no-cache-dir install -e "python[all_hip]"; \
|
| 146 |
+
fi \
|
| 147 |
+
&& cd /sgl-workspace \
|
| 148 |
+
&& cp -r /sgl-workspace/sglang /sglang \
|
| 149 |
+
&& python -m pip cache purge
|
| 150 |
+
|
| 151 |
+
# Install common Python packages
|
| 152 |
+
RUN pip install IPython orjson python-multipart torchao pybind11
|
| 153 |
+
# Rebuild Triton
|
| 154 |
+
RUN pip uninstall -y triton || true \
|
| 155 |
+
&& git clone ${TRITON_REPO} \
|
| 156 |
+
&& cd triton \
|
| 157 |
+
&& git checkout ${TRITON_COMMIT} \
|
| 158 |
+
&& cd python \
|
| 159 |
+
&& python3 setup.py install \
|
| 160 |
+
&& cd /sgl-workspace
|
| 161 |
+
# ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942 --amdgpu-lower-module-lds-strategy=1"
|
| 162 |
+
# ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942"
|
| 163 |
+
|
| 164 |
+
# Build aiter
|
| 165 |
+
#version: Commit 9d11f47
|
| 166 |
+
# && git checkout ${AITER_COMMIT} \
|
| 167 |
+
RUN pip uninstall -y aiter || true
|
| 168 |
+
RUN git clone ${AITER_REPO} \
|
| 169 |
+
&& cd aiter \
|
| 170 |
+
&& git checkout ${AITER_COMMIT} \
|
| 171 |
+
&& git submodule sync \
|
| 172 |
+
&& git submodule update --init --recursive \
|
| 173 |
+
&& PREBUILD_KERNELS=1 GPU_ARCHS=gfx942 python3 setup.py install \
|
| 174 |
+
&& cd /sgl-workspace
|
| 175 |
+
|
| 176 |
+
# Copy MI300X config
|
| 177 |
+
RUN find /sgl-workspace/sglang/python/sglang/srt/layers/quantization/configs/ \
|
| 178 |
+
/sgl-workspace/sglang/python/sglang/srt/layers/moe/fused_moe_triton/configs/ \
|
| 179 |
+
-type f -name '*MI300X*' | \
|
| 180 |
+
xargs -I {} sh -c 'vf_config=$(echo "$1" | sed "s/MI300X/MI300X_VF/"); cp "$1" "$vf_config"' -- {}
|
| 181 |
+
|
| 182 |
+
# Environment setup complete.
|
| 183 |
+
RUN echo "Environment setup complete."
|
| 184 |
+
|
| 185 |
+
WORKDIR /workspace/
|
| 186 |
+
###########################################
|
| 187 |
+
###########################################
|
| 188 |
+
###########################################
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
###########################################
|
| 196 |
+
###############vllm v0.8.5#################
|
| 197 |
+
###########################################
|
| 198 |
+
WORKDIR /workspace/
|
| 199 |
+
|
| 200 |
+
ENV VLLM_TARGET_DEVICE=rocm
|
| 201 |
+
ENV ROCM_PATH=/opt/rocm
|
| 202 |
+
ENV SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev
|
| 203 |
+
# Find the repo path in: DockerFile/Dockerfile.rocm_yang
|
| 204 |
+
# RUN git clone https://github.com/RLFoundation/vllm-patch.git
|
| 205 |
+
RUN pip uninstall -y vllm || true
|
| 206 |
+
RUN rm -rf vllm-patch
|
| 207 |
+
RUN git clone https://github.com/RLFoundation/vllm-patch.git \
|
| 208 |
+
&& cd vllm-patch \
|
| 209 |
+
&& git checkout v0.8.5-sleep-numa \
|
| 210 |
+
&& rm -rf build/ dist/ *.egg-info \
|
| 211 |
+
&& ln -sf /opt/rocm/lib/libamdhip64.so /usr/lib/libamdhip64.so \
|
| 212 |
+
&& SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev PYTORCH_ROCM_ARCH="gfx90a;gfx942" MAX_JOBS=${MAX_JOBS} python3 setup.py install
|
| 213 |
+
# RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev PYTORCH_ROCM_ARCH="gfx90a;gfx942" MAX_JOBS=${MAX_JOBS} python3 setup.py develop
|
| 214 |
+
WORKDIR /workspace/
|
| 215 |
+
###########################################
|
| 216 |
+
###########################################
|
| 217 |
+
###########################################
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
#########################################
|
| 223 |
+
#### Install megatron-core###############
|
| 224 |
+
#########################################
|
| 225 |
+
RUN pip uninstall -y megatron-core && \
|
| 226 |
+
git clone https://github.com/yushengsu-thu/Megatron-LM-amd_version.git && \
|
| 227 |
+
cd Megatron-LM-amd_version && \
|
| 228 |
+
pip install -vvv -e . && \
|
| 229 |
+
cd /workspace/
|
| 230 |
+
#########################################
|
| 231 |
+
#########################################
|
| 232 |
+
#########################################
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
#######################################
|
| 238 |
+
################apex###################
|
| 239 |
+
#######################################
|
| 240 |
+
WORKDIR /workspace/
|
| 241 |
+
RUN pip uninstall -y apex && \
|
| 242 |
+
git clone git@github.com:ROCm/apex.git && \
|
| 243 |
+
cd apex && \
|
| 244 |
+
python setup.py install && \
|
| 245 |
+
cd /workspace/
|
| 246 |
+
#######################################
|
| 247 |
+
#######################################
|
| 248 |
+
#######################################
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
################################################################################
|
| 252 |
+
###########################Add torch_memory_saver###############################
|
| 253 |
+
################################################################################
|
| 254 |
+
# Set environment variables
|
| 255 |
+
ENV HIPCC_COMPILE_FLAGS_APPEND="--amdgpu-target=gfx90a;gfx942 -D__HIP_PLATFORM_AMD__"
|
| 256 |
+
ENV CFLAGS="-D__HIP_PLATFORM_AMD__"
|
| 257 |
+
ENV CXXFLAGS="-D__HIP_PLATFORM_AMD__"
|
| 258 |
+
RUN pip install "git+https://github.com/YangWang92/torch_memory_saver_numa.git@numa"
|
| 259 |
+
################################################################################
|
| 260 |
+
################################################################################
|
| 261 |
+
################################################################################
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
########################################
|
| 266 |
+
######Install ray#######################
|
| 267 |
+
########################################
|
| 268 |
+
# need to add this patch: https://github.com/ray-project/ray/pull/53531/files
|
| 269 |
+
RUN pip uninstall ray -y
|
| 270 |
+
RUN pip install "ray[data,train,tune,serve]>=2.47.0"
|
| 271 |
+
########################################
|
| 272 |
+
########################################
|
| 273 |
+
########################################
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
##########################################
|
| 277 |
+
#######Install other dependencies#########
|
| 278 |
+
##########################################
|
| 279 |
+
RUN pip install "tensordict==0.6.2" --no-deps && \
|
| 280 |
+
pip install accelerate \
|
| 281 |
+
codetiming \
|
| 282 |
+
datasets \
|
| 283 |
+
dill \
|
| 284 |
+
hydra-core \
|
| 285 |
+
liger-kernel \
|
| 286 |
+
numpy \
|
| 287 |
+
pandas \
|
| 288 |
+
peft \
|
| 289 |
+
"pyarrow>=15.0.0" \
|
| 290 |
+
pylatexenc \
|
| 291 |
+
torchdata \
|
| 292 |
+
wandb \
|
| 293 |
+
orjson \
|
| 294 |
+
pybind11
|
| 295 |
+
|
| 296 |
+
WORKDIR /workspace/
|
| 297 |
+
RUN git clone https://github.com/volcengine/verl.git && \
|
| 298 |
+
cd verl && \
|
| 299 |
+
pip install -e .
|
| 300 |
+
##########################################
|
| 301 |
+
##########################################
|
| 302 |
+
##########################################
|
| 303 |
+
|
| 304 |
+
WORKDIR /workspace/
|
| 305 |
+
CMD ["/usr/bin/bash"]
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
Build the image:
|
| 309 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 310 |
+
|
| 311 |
+
.. code-block:: bash
|
| 312 |
+
|
| 313 |
+
docker docker/build -t verl-rocm .
|
| 314 |
+
|
| 315 |
+
Run the container
|
| 316 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 317 |
+
|
| 318 |
+
Note: You can pull the docker from this DockerHub: [RLSys Foundation](https://hub.docker.com/u/yushengsuthu)
|
| 319 |
+
Pull the image:
|
| 320 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 321 |
+
|
| 322 |
+
.. code-block:: bash
|
| 323 |
+
|
| 324 |
+
docker pull rlsys/verl:verl-0.4.1_ubuntu-22.04_rocm6.3.4-numa-patch_vllm0.8.5_sglang0.4.6.post4
|
| 325 |
+
|
| 326 |
+
docker tag rlsys/verl:verl-0.4.1_ubuntu-22.04_rocm6.3.4-numa-patch_vllm0.8.5_sglang0.4.6.post4 verl-rocm:latest
|
| 327 |
+
|
| 328 |
+
Run the container
|
| 329 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
Optional: Running without root and with user permissions
|
| 333 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 334 |
+
|
| 335 |
+
.. code-block:: bash
|
| 336 |
+
|
| 337 |
+
docker run --rm -it \
|
| 338 |
+
--device /dev/dri \
|
| 339 |
+
--device /dev/kfd \
|
| 340 |
+
-p 8265:8265 \
|
| 341 |
+
--group-add video \
|
| 342 |
+
--cap-add SYS_PTRACE \
|
| 343 |
+
--security-opt seccomp=unconfined \
|
| 344 |
+
--privileged \
|
| 345 |
+
-v $HOME/.ssh:/root/.ssh \
|
| 346 |
+
-v $HOME:$HOME \
|
| 347 |
+
--shm-size 128G \
|
| 348 |
+
-w $PWD \
|
| 349 |
+
verl-rocm \
|
| 350 |
+
/bin/bash
|
| 351 |
+
|
| 352 |
+
(Optional): If you do not want to root mode and require assign yourself as the user
|
| 353 |
+
Please add ``-e HOST_UID=$(id -u)`` and ``-e HOST_GID=$(id -g)`` into the above docker launch script.
|
| 354 |
+
|
| 355 |
+
Example
|
| 356 |
+
-------
|
| 357 |
+
|
| 358 |
+
Due to to special setting in AMD (ROCM) torch,
|
| 359 |
+
1. If your ``ray>=2.45.0`` (default), you need to set ``RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES`` when starting ray in verl's RLHF training and add this [patch](https://github.com/ray-project/ray/pull/53531/files).
|
| 360 |
+
2. If your ``ray<2.45.0``, you need to set ``RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES`` when starting ray in verl's RLHF training.
|
| 361 |
+
Inference ``$ENGINE`` can be ``vllm`` or ``sglang``. We choose ``vllm`` as default in the following examples.
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
PPO
|
| 366 |
+
~~~
|
| 367 |
+
|
| 368 |
+
.. code-block:: bash
|
| 369 |
+
|
| 370 |
+
YOUR_PROJECT_NAME=r1-verl-ppo-upstream
|
| 371 |
+
YOUR_RUN_NAME=r1-training_ppo-upstream
|
| 372 |
+
# export HYDRA_FULL_ERROR=1
|
| 373 |
+
|
| 374 |
+
export HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
|
| 375 |
+
|
| 376 |
+
# [ray] < 2.45.0
|
| 377 |
+
#export RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES=1
|
| 378 |
+
|
| 379 |
+
# [ray] >= 2.45.0
|
| 380 |
+
export RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES=1 # Patch with https://github.com/ray-project/ray/pull/52794
|
| 381 |
+
|
| 382 |
+
GPUS_PER_NODE=8
|
| 383 |
+
MODEL_PATH=Qwen/Qwen2.5-0.5B-Instruct
|
| 384 |
+
python3 examples/data_preprocess/gsm8k.py --local_save_dir data/gsm8k
|
| 385 |
+
python3 -c "import transformers; transformers.pipeline('text-generation', model='$MODEL_PATH')"
|
| 386 |
+
ENGINE=vllm #sglang
|
| 387 |
+
|
| 388 |
+
PYTHONUNBUFFERED=1 python3 -m verl.trainer.main_ppo \
|
| 389 |
+
data.train_files=data/gsm8k/train.parquet \
|
| 390 |
+
data.val_files=data/gsm8k/test.parquet \
|
| 391 |
+
data.train_batch_size=256 \
|
| 392 |
+
data.val_batch_size=1312 \
|
| 393 |
+
data.max_prompt_length=512 \
|
| 394 |
+
data.max_response_length=256 \
|
| 395 |
+
actor_rollout_ref.model.path=$MODEL_PATH \
|
| 396 |
+
actor_rollout_ref.actor.optim.lr=1e-6 \
|
| 397 |
+
actor_rollout_ref.actor.ppo_mini_batch_size=64 \
|
| 398 |
+
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=4 \
|
| 399 |
+
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=8 \
|
| 400 |
+
actor_rollout_ref.rollout.tensor_model_parallel_size=1 \
|
| 401 |
+
actor_rollout_ref.rollout.name=$ENGINE \
|
| 402 |
+
actor_rollout_ref.rollout.gpu_memory_utilization=0.8 \
|
| 403 |
+
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=4 \
|
| 404 |
+
critic.optim.lr=1e-5 \
|
| 405 |
+
critic.model.path=$MODEL_PATH \
|
| 406 |
+
critic.ppo_micro_batch_size_per_gpu=4 \
|
| 407 |
+
algorithm.kl_ctrl.kl_coef=0.001 \
|
| 408 |
+
trainer.logger=console \
|
| 409 |
+
trainer.project_name=$YOUR_PROJECT_NAME \
|
| 410 |
+
trainer.experiment_name=$YOUR_RUN_NAME \
|
| 411 |
+
trainer.val_before_train=False \
|
| 412 |
+
trainer.n_gpus_per_node=$GPUS_PER_NODE \
|
| 413 |
+
trainer.nnodes=1 \
|
| 414 |
+
trainer.save_freq=10 \
|
| 415 |
+
trainer.test_freq=10 \
|
| 416 |
+
trainer.total_epochs=15 #2>&1 | tee verl_demo.log
|
| 417 |
+
|
| 418 |
+
GRPO
|
| 419 |
+
~~~~
|
| 420 |
+
|
| 421 |
+
.. code-block:: bash
|
| 422 |
+
|
| 423 |
+
YOUR_PROJECT_NAME=r1-verl-grpo-upstream
|
| 424 |
+
YOUR_RUN_NAME=r1-training_grpo-upstream
|
| 425 |
+
# export HYDRA_FULL_ERROR=1
|
| 426 |
+
# export FSDP_VERBOSE=1
|
| 427 |
+
|
| 428 |
+
#export HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
|
| 429 |
+
|
| 430 |
+
# [ray] < 2.45.0
|
| 431 |
+
#export RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES=1
|
| 432 |
+
|
| 433 |
+
# [ray] >= 2.45.0
|
| 434 |
+
export RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES=1 # Patch with https://github.com/ray-project/ray/pull/52794
|
| 435 |
+
|
| 436 |
+
GPUS_PER_NODE=8
|
| 437 |
+
MODEL_PATH=Qwen/Qwen2.5-0.5B-Instruct
|
| 438 |
+
# MODEL_PATH=Qwen/Qwen2-7B-Instruct
|
| 439 |
+
python3 examples/data_preprocess/gsm8k.py --local_save_dir data/gsm8k
|
| 440 |
+
python3 -c "import transformers; transformers.pipeline('text-generation', model='$MODEL_PATH')"
|
| 441 |
+
ENGINE=vllm #sglang
|
| 442 |
+
|
| 443 |
+
python3 -m verl.trainer.main_ppo \
|
| 444 |
+
algorithm.adv_estimator=grpo \
|
| 445 |
+
data.train_files=data/gsm8k/train.parquet \
|
| 446 |
+
data.val_files=data/gsm8k/test.parquet \
|
| 447 |
+
data.train_batch_size=1024 \
|
| 448 |
+
data.val_batch_size=1312 \
|
| 449 |
+
data.max_prompt_length=512 \
|
| 450 |
+
data.max_response_length=1024 \
|
| 451 |
+
actor_rollout_ref.model.path=$MODEL_PATH \
|
| 452 |
+
actor_rollout_ref.actor.optim.lr=1e-6 \
|
| 453 |
+
actor_rollout_ref.model.use_remove_padding=True \
|
| 454 |
+
actor_rollout_ref.actor.ppo_mini_batch_size=256 \
|
| 455 |
+
actor_rollout_ref.actor.use_dynamic_bsz=True \
|
| 456 |
+
actor_rollout_ref.actor.ppo_max_token_len_per_gpu=24000 \
|
| 457 |
+
actor_rollout_ref.actor.use_kl_loss=True \
|
| 458 |
+
actor_rollout_ref.actor.kl_loss_coef=0.001 \
|
| 459 |
+
actor_rollout_ref.actor.kl_loss_type=low_var_kl \
|
| 460 |
+
actor_rollout_ref.model.enable_gradient_checkpointing=Flase \
|
| 461 |
+
actor_rollout_ref.actor.fsdp_config.param_offload=False \
|
| 462 |
+
actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
|
| 463 |
+
actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
|
| 464 |
+
actor_rollout_ref.rollout.name=$ENGINE \
|
| 465 |
+
actor_rollout_ref.rollout.gpu_memory_utilization=0.8 \
|
| 466 |
+
actor_rollout_ref.rollout.n=5 \
|
| 467 |
+
actor_rollout_ref.ref.fsdp_config.param_offload=False \
|
| 468 |
+
algorithm.kl_ctrl.kl_coef=0.001 \
|
| 469 |
+
trainer.critic_warmup=0 \
|
| 470 |
+
trainer.logger=console \
|
| 471 |
+
trainer.project_name=$YOUR_PROJECT_NAME \
|
| 472 |
+
trainer.experiment_name=$YOUR_RUN_NAME \
|
| 473 |
+
trainer.n_gpus_per_node=$GPUS_PER_NODE \
|
| 474 |
+
trainer.val_before_train=False \
|
| 475 |
+
trainer.nnodes=1 \
|
| 476 |
+
trainer.save_freq=-1 \
|
| 477 |
+
trainer.test_freq=10 \
|
| 478 |
+
trainer.total_epochs=15
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
Multi-node training: slurm with Docker/Podman container
|
| 483 |
+
---------------------------------------------------------------------------------------
|
| 484 |
+
|
| 485 |
+
If you want to run multi-node training with slurm, you can use the following script.
|
| 486 |
+
|
| 487 |
+
.. note::
|
| 488 |
+
1. You need to use ``podman`` or ``docker`` in the following script. We will release the apptainer script later.
|
| 489 |
+
2. If you want to use ``podman``, you just replace ``docker`` with ``podman`` in the following script.
|
| 490 |
+
|
| 491 |
+
The script includes the following steps:
|
| 492 |
+
|
| 493 |
+
1. SLURM Configuration
|
| 494 |
+
2. Environment Setup
|
| 495 |
+
3. Docker/Podman Container Setup
|
| 496 |
+
4. Ray Cluster Initialization
|
| 497 |
+
5. Data Preprocessing
|
| 498 |
+
6. Model Setup
|
| 499 |
+
7. Training Launch
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
slurm_script.sh
|
| 503 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 504 |
+
|
| 505 |
+
.. code-block:: bash
|
| 506 |
+
|
| 507 |
+
#!/bin/bash
|
| 508 |
+
|
| 509 |
+
#SBATCH --job-name=verl-ray-on-slurm
|
| 510 |
+
#SBATCH --nodes=2
|
| 511 |
+
#SBATCH --ntasks-per-node=2
|
| 512 |
+
#SBATCH --mem=200G
|
| 513 |
+
#SBATCH --time=30-00:00:00
|
| 514 |
+
#SBATCH --gpus-per-node=8
|
| 515 |
+
#SBATCH --cpus-per-task=28
|
| 516 |
+
#SBATCH --output=../verl_log/slurm-%j.out
|
| 517 |
+
#SBATCH --error=../verl_log/slurm-%j.err
|
| 518 |
+
#SBATCH --nodelist=gpu-[0,1]
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
# load necessary modules
|
| 522 |
+
### Run this setup
|
| 523 |
+
# [Cluster]: Use docker
|
| 524 |
+
# docker pull docker.io/rocm/vllm:rocm6.2_mi300_ubuntu20.04_py3.9_vllm_0.6.4
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
##########################################################################
|
| 528 |
+
###The following setting should be set in different project and cluster###
|
| 529 |
+
##########################################################################
|
| 530 |
+
|
| 531 |
+
### Project
|
| 532 |
+
CONTAINER_NAME="multinode_verl_training"
|
| 533 |
+
IMG="verl.rocm"
|
| 534 |
+
DOCKERFILE="docker/Dockerfile.rocm"
|
| 535 |
+
# echo $PWD
|
| 536 |
+
verl_workdir="${HOME}/projects/verl_upstream"
|
| 537 |
+
export TRANSFORMERS_CACHE="${HOME}/.cache/huggingface"
|
| 538 |
+
export HF_HOME=$TRANSFORMERS_CACHE
|
| 539 |
+
|
| 540 |
+
### Cluster Network Setting
|
| 541 |
+
export NCCL_DEBUG=TRACE
|
| 542 |
+
export GPU_MAX_HW_QUEUES=2
|
| 543 |
+
export TORCH_NCCL_HIGH_PRIORITY=1
|
| 544 |
+
export NCCL_CHECKS_DISABLE=1
|
| 545 |
+
# export NCCL_IB_HCA=rdma0,rdma1,rdma2,rdma3,rdma4,rdma5,rdma6,rdma7
|
| 546 |
+
export NCCL_IB_HCA=mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_8,mlx5_9
|
| 547 |
+
export NCCL_IB_GID_INDEX=3
|
| 548 |
+
export NCCL_CROSS_NIC=0
|
| 549 |
+
export CUDA_DEVICE_MAX_CONNECTIONS=1
|
| 550 |
+
export NCCL_PROTO=Simple
|
| 551 |
+
export RCCL_MSCCL_ENABLE=0
|
| 552 |
+
export TOKENIZERS_PARALLELISM=false
|
| 553 |
+
export HSA_NO_SCRATCH_RECLAIM=1
|
| 554 |
+
##########################################################################
|
| 555 |
+
|
| 556 |
+
## Assign using GPUs
|
| 557 |
+
export HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
|
| 558 |
+
|
| 559 |
+
### For rocm and training script
|
| 560 |
+
# [ray] < 2.45.0
|
| 561 |
+
#export RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES=1
|
| 562 |
+
|
| 563 |
+
# [ray] >= 2.45.0
|
| 564 |
+
export RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES=1 # Patch with https://github.com/ray-project/ray/pull/52794
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
# Build and launch the Docker container
|
| 568 |
+
srun bash -c "
|
| 569 |
+
# Exit on any error
|
| 570 |
+
set -e
|
| 571 |
+
|
| 572 |
+
# Clean up dangling images (images with <none> tag)
|
| 573 |
+
docker image prune -f
|
| 574 |
+
|
| 575 |
+
# Need to pull the docker first
|
| 576 |
+
docker pull rlsys/verl:verl-0.4.1_ubuntu-22.04_rocm6.3.4-numa-patch_vllm0.8.5_sglang0.4.6.post4
|
| 577 |
+
|
| 578 |
+
if ! docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "${IMG}"; then
|
| 579 |
+
echo \"Building ${IMG} image...\"
|
| 580 |
+
docker build -f \"${DOCKERFILE}\" -t \"${IMG}\" .
|
| 581 |
+
else
|
| 582 |
+
echo \"${IMG} image already exists, skipping build\"
|
| 583 |
+
fi
|
| 584 |
+
|
| 585 |
+
# Removing old container if exists
|
| 586 |
+
docker rm \"${CONTAINER_NAME}\" 2>/dev/null || true
|
| 587 |
+
|
| 588 |
+
# Checking network devices
|
| 589 |
+
ibdev2netdev
|
| 590 |
+
|
| 591 |
+
# Launch the docker
|
| 592 |
+
docker run --rm -d \
|
| 593 |
+
-e HYDRA_FULL_ERROR=1 \
|
| 594 |
+
-e RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES=1 \
|
| 595 |
+
-e RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES=1 \
|
| 596 |
+
-e NCCL_DEBUG=${NCCL_DEBUG} \
|
| 597 |
+
-e GPU_MAX_HW_QUEUES=${GPU_MAX_HW_QUEUES} \
|
| 598 |
+
-e TORCH_NCCL_HIGH_PRIORITY=${TORCH_NCCL_HIGH_PRIORITY} \
|
| 599 |
+
-e NCCL_CHECKS_DISABLE=${NCCL_CHECKS_DISABLE} \
|
| 600 |
+
-e NCCL_IB_HCA=${NCCL_IB_HCA} \
|
| 601 |
+
-e NCCL_IB_GID_INDEX=${NCCL_IB_GID_INDEX} \
|
| 602 |
+
-e NCCL_CROSS_NIC=${NCCL_CROSS_NIC} \
|
| 603 |
+
-e CUDA_DEVICE_MAX_CONNECTIONS=${CUDA_DEVICE_MAX_CONNECTIONS} \
|
| 604 |
+
-e NCCL_PROTO=${NCCL_PROTO} \
|
| 605 |
+
-e RCCL_MSCCL_ENABLE=${RCCL_MSCCL_ENABLE} \
|
| 606 |
+
-e TOKENIZERS_PARALLELISM=${TOKENIZERS_PARALLELISM} \
|
| 607 |
+
-e HSA_NO_SCRATCH_RECLAIM=${HSA_NO_SCRATCH_RECLAIM} \
|
| 608 |
+
-e TRANSFORMERS_CACHE=${TRANSFORMERS_CACHE} \
|
| 609 |
+
-e HF_HOME=${HF_HOME} \
|
| 610 |
+
--network host \
|
| 611 |
+
--device /dev/dri \
|
| 612 |
+
--device /dev/kfd \
|
| 613 |
+
--device /dev/infiniband \
|
| 614 |
+
--group-add video \
|
| 615 |
+
--cap-add SYS_PTRACE \
|
| 616 |
+
--security-opt seccomp=unconfined \
|
| 617 |
+
--privileged \
|
| 618 |
+
-v \${HOME}:\${HOME} \
|
| 619 |
+
-v \${HOME}/.ssh:/root/.ssh \
|
| 620 |
+
-w "${verl_workdir}" \
|
| 621 |
+
--shm-size 128G \
|
| 622 |
+
--name \"${CONTAINER_NAME}\" \
|
| 623 |
+
\"${IMG}\" \
|
| 624 |
+
tail -f /dev/null
|
| 625 |
+
|
| 626 |
+
echo \"Container setup completed\"
|
| 627 |
+
"
|
| 628 |
+
# (Optional): If you do not want to root mode and require assign yuorself as the user
|
| 629 |
+
# Please add `-e HOST_UID=$(id -u)` and `-e HOST_GID=$(id -g)` into the above docker launch script.
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
### Ray launch the nodes before training
|
| 636 |
+
|
| 637 |
+
# Getting the node names
|
| 638 |
+
nodes_array=($(scontrol show hostnames "$SLURM_JOB_NODELIST" | tr '\n' ' '))
|
| 639 |
+
|
| 640 |
+
head_node=${nodes_array[0]}
|
| 641 |
+
head_node_ip=$(srun --nodes=1 --ntasks=1 -w "$head_node" hostname --ip-address)
|
| 642 |
+
|
| 643 |
+
# if we detect a space character in the head node IP, we'll
|
| 644 |
+
# convert it to an ipv4 address. This step is optional.
|
| 645 |
+
if [[ "$head_node_ip" == *" "* ]]; then
|
| 646 |
+
IFS=' ' read -ra ADDR <<<"$head_node_ip"
|
| 647 |
+
if [[ ${#ADDR[0]} -gt 16 ]]; then
|
| 648 |
+
head_node_ip=${ADDR[1]}
|
| 649 |
+
else
|
| 650 |
+
head_node_ip=${ADDR[0]}
|
| 651 |
+
fi
|
| 652 |
+
echo "IPV6 address detected. We split the IPV4 address as $head_node_ip"
|
| 653 |
+
fi
|
| 654 |
+
|
| 655 |
+
port=6379
|
| 656 |
+
ip_head=$head_node_ip:$port
|
| 657 |
+
export ip_head
|
| 658 |
+
echo "IP Head: $ip_head"
|
| 659 |
+
|
| 660 |
+
# make sure we set environment variables before Ray initialization
|
| 661 |
+
|
| 662 |
+
# Print out all env variables
|
| 663 |
+
printenv
|
| 664 |
+
|
| 665 |
+
echo "Starting HEAD at $head_node"
|
| 666 |
+
srun --nodes=1 --ntasks=1 -w "$head_node" \
|
| 667 |
+
docker exec "${CONTAINER_NAME}" \
|
| 668 |
+
ray start --head --node-ip-address="$head_node_ip" --port=$port \
|
| 669 |
+
--dashboard-port=8266 \
|
| 670 |
+
--num-cpus "${SLURM_CPUS_PER_TASK}" --num-gpus "${SLURM_GPUS_PER_NODE}" --block &
|
| 671 |
+
# optional, though may be useful in certain versions of Ray < 1.0.
|
| 672 |
+
sleep 10
|
| 673 |
+
|
| 674 |
+
# number of nodes other than the head node
|
| 675 |
+
worker_num=$((SLURM_JOB_NUM_NODES - 1))
|
| 676 |
+
|
| 677 |
+
for ((i = 1; i <= worker_num; i++)); do
|
| 678 |
+
node_i=${nodes_array[$i]}
|
| 679 |
+
echo "Debug: Starting worker on node_i = ${node_i}"
|
| 680 |
+
if [ -z "$node_i" ]; then
|
| 681 |
+
echo "Error: Empty node name for worker $i"
|
| 682 |
+
continue
|
| 683 |
+
fi
|
| 684 |
+
echo "Starting WORKER $i at $node_i"
|
| 685 |
+
srun --nodes=1 --ntasks=1 -w "$node_i" \
|
| 686 |
+
docker exec "${CONTAINER_NAME}" \
|
| 687 |
+
ray start --address "$ip_head" --num-cpus "${SLURM_CPUS_PER_TASK}" --num-gpus "${SLURM_GPUS_PER_NODE}" --block &
|
| 688 |
+
sleep 5
|
| 689 |
+
done
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
# Ray initlization test (See whether any error in the above execution)
|
| 695 |
+
echo "Testing Ray initialization in the slurm nodes..."
|
| 696 |
+
docker exec "${CONTAINER_NAME}" python3 -c '
|
| 697 |
+
import ray
|
| 698 |
+
try:
|
| 699 |
+
ray.init(address="auto")
|
| 700 |
+
print("\n=== Ray Cluster Status ===")
|
| 701 |
+
print(f"Number of nodes: {len(ray.nodes())}")
|
| 702 |
+
for node in ray.nodes():
|
| 703 |
+
print("Node: {}, Status: {}".format(node["NodeManagerHostname"], node["Alive"]))
|
| 704 |
+
# print(f"Node: {node}")
|
| 705 |
+
ray.shutdown()
|
| 706 |
+
print("Ray initialization successful!")
|
| 707 |
+
except Exception as e:
|
| 708 |
+
print(f"Ray initialization failed: {str(e)}")
|
| 709 |
+
'
|
| 710 |
+
echo "=== Ray test completed ==="
|
| 711 |
+
######
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
# Run data preprocessing
|
| 716 |
+
|
| 717 |
+
echo "Starting data preprocessing..."
|
| 718 |
+
docker exec "${CONTAINER_NAME}" \
|
| 719 |
+
python3 "examples/data_preprocess/gsm8k.py" "--local_save_dir" "../data/gsm8k"
|
| 720 |
+
|
| 721 |
+
echo "Starting data preprocessing..."
|
| 722 |
+
docker exec "${CONTAINER_NAME}" \
|
| 723 |
+
python3 "examples/data_preprocess/math_dataset.py" "--local_dir" "../data/math"
|
| 724 |
+
|
| 725 |
+
train_files="../data/gsm8k/train.parquet"
|
| 726 |
+
val_files="../data/gsm8k/test.parquet"
|
| 727 |
+
|
| 728 |
+
# Download and test model
|
| 729 |
+
echo "Loading model..."
|
| 730 |
+
docker exec "${CONTAINER_NAME}" \
|
| 731 |
+
python3 -c "import transformers; transformers.pipeline('text-generation', model='Qwen/Qwen2-7B-Instruct')"
|
| 732 |
+
MODEL_PATH="Qwen/Qwen2-7B-Instruct"
|
| 733 |
+
|
| 734 |
+
# Set model path after pipeline test
|
| 735 |
+
MODEL_PATH="Qwen/Qwen2.5-0.5B-Instruct"
|
| 736 |
+
|
| 737 |
+
echo "== Data and model loading Done =="
|
| 738 |
+
|
| 739 |
+
echo "Start to train..."
|
| 740 |
+
|
| 741 |
+
docker exec "${CONTAINER_NAME}" \
|
| 742 |
+
python3 -c "import transformers; transformers.pipeline('text-generation', model='Qwen/Qwen2-7B-Instruct')"
|
| 743 |
+
MODEL_PATH="Qwen/Qwen2-7B-Instruct"
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
PYTHONUNBUFFERED=1 srun --overlap --nodes=${SLURM_NNODES} --ntasks=1 -w "$head_node" \
|
| 747 |
+
docker exec "${CONTAINER_NAME}" \
|
| 748 |
+
python3 -m verl.trainer.main_ppo \
|
| 749 |
+
data.train_files=$train_files \
|
| 750 |
+
data.val_files=$val_files \
|
| 751 |
+
data.train_batch_size=1024 \
|
| 752 |
+
data.max_prompt_length=1024 \
|
| 753 |
+
data.max_response_length=1024 \
|
| 754 |
+
actor_rollout_ref.model.path=$MODEL_PATH \
|
| 755 |
+
actor_rollout_ref.model.enable_gradient_checkpointing=False \
|
| 756 |
+
actor_rollout_ref.actor.optim.lr=1e-6 \
|
| 757 |
+
actor_rollout_ref.model.use_remove_padding=True \
|
| 758 |
+
actor_rollout_ref.actor.ppo_mini_batch_size=256 \
|
| 759 |
+
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=8 \
|
| 760 |
+
actor_rollout_ref.model.enable_gradient_checkpointing=True \
|
| 761 |
+
actor_rollout_ref.actor.fsdp_config.param_offload=False \
|
| 762 |
+
actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
|
| 763 |
+
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=16 \
|
| 764 |
+
actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
|
| 765 |
+
actor_rollout_ref.rollout.name=vllm \
|
| 766 |
+
actor_rollout_ref.rollout.gpu_memory_utilization=0.9 \
|
| 767 |
+
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=16 \
|
| 768 |
+
actor_rollout_ref.ref.fsdp_config.param_offload=True \
|
| 769 |
+
critic.optim.lr=1e-5 \
|
| 770 |
+
critic.model.use_remove_padding=True \
|
| 771 |
+
critic.model.path=$MODEL_PATH \
|
| 772 |
+
critic.model.enable_gradient_checkpointing=False \
|
| 773 |
+
critic.ppo_micro_batch_size_per_gpu=8 \
|
| 774 |
+
critic.model.fsdp_config.param_offload=False \
|
| 775 |
+
critic.model.fsdp_config.optimizer_offload=False \
|
| 776 |
+
algorithm.kl_ctrl.kl_coef=0.0001 \
|
| 777 |
+
trainer.critic_warmup=0 \
|
| 778 |
+
trainer.logger='["console","wandb"]' \
|
| 779 |
+
trainer.project_name='verl_example' \
|
| 780 |
+
trainer.experiment_name='Qwen2.5-32B-Instruct_function_rm' \
|
| 781 |
+
trainer.n_gpus_per_node=${SLURM_GPUS_PER_NODE} \
|
| 782 |
+
trainer.val_before_train=False \
|
| 783 |
+
trainer.nnodes=${SLURM_NNODES} \
|
| 784 |
+
trainer.save_freq=-1 \
|
| 785 |
+
trainer.test_freq=10 \
|
| 786 |
+
trainer.total_epochs=15
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
Run slurm_script.sh
|
| 790 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 791 |
+
Just sbatch your slurm_script.sh
|
| 792 |
+
|
| 793 |
+
.. code-block:: bash
|
| 794 |
+
|
| 795 |
+
sbatch slurm_script.sh
|
| 796 |
+
|
verl/docs/amd_tutorial/amd_vllm_page.rst
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
verl performance tuning for AMD (ROCm Kernel)
|
| 2 |
+
=====================================================
|
| 3 |
+
|
| 4 |
+
Last updated: 04/25/2025.
|
| 5 |
+
|
| 6 |
+
Author: `Yang Wang <https://github.com/YangWang92/>`_
|
| 7 |
+
|
| 8 |
+
Patch vLLM to Enable Sleep Mode for AMD GPUs
|
| 9 |
+
--------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
By default, verl requires vLLM to enable sleep mode, which allows vLLM to offload GPU memory to CPU memory after rollout. However, this feature is still under review by the vLLM community.
|
| 12 |
+
|
| 13 |
+
To enable vLLM's sleep mode, you can first use community patched code (from `this pull request <https://github.com/vllm-project/vllm/pull/12695>`_) to build vLLM from the source code in the corresponding pull request. After the patch merged in vLLM main branch, you can directly install vLLM from the latest version.
|
| 14 |
+
|
| 15 |
+
1. Clone the vLLM repository and build it with the following commands:
|
| 16 |
+
|
| 17 |
+
.. code-block:: bash
|
| 18 |
+
|
| 19 |
+
git clone -b sleep_amd https://github.com/HollowMan6/vllm.git
|
| 20 |
+
cd vllm
|
| 21 |
+
sudo ln -sf /opt/rocm/lib/libamdhip64.so /usr/lib/libamdhip64.so
|
| 22 |
+
VLLM_TARGET_DEVICE=rocm ROCM_PATH=/opt/rocm/ VLLM_GPU_LANG=HIP SETUPTOOLS_SCM_PRETEND_VERSION=0.8.4.dev python3 setup.py develop
|
| 23 |
+
|
| 24 |
+
2. Additionally, make sure to use the ROCm version in your Docker image lager than or equal to ROCm 6.3.4, and we recommend to use ROCm 6.4.0 for better performance (see `this comment <https://github.com/vllm-project/vllm/pull/12695#issuecomment-2637839574>`_).
|
| 25 |
+
|
| 26 |
+
After the upgrade, you can verify whether sleep mode is enabled by running the following test code (from `this comment <https://github.com/vllm-project/vllm/pull/12695#issuecomment-2637839574>`_).
|
| 27 |
+
|
| 28 |
+
.. code-block:: python
|
| 29 |
+
|
| 30 |
+
import torch
|
| 31 |
+
from vllm import LLM
|
| 32 |
+
|
| 33 |
+
llm = LLM(model="meta-llama/Llama-3.1-8B-Instruct", enable_sleep_mode=True)
|
| 34 |
+
|
| 35 |
+
def run_inference(prompt):
|
| 36 |
+
outputs = llm.generate(prompt)
|
| 37 |
+
for output in outputs:
|
| 38 |
+
prompt = output.prompt
|
| 39 |
+
generated_text = output.outputs[0].text
|
| 40 |
+
print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
print("CUDA Memory Usage (after inference):")
|
| 44 |
+
torch.cuda.empty_cache()
|
| 45 |
+
print(f"{torch.cuda.memory_allocated()=}")
|
| 46 |
+
|
| 47 |
+
run_inference("San Francisco is")
|
| 48 |
+
llm.sleep()
|
| 49 |
+
|
| 50 |
+
print("CUDA Memory Usage (after sleep):")
|
| 51 |
+
torch.cuda.empty_cache()
|
| 52 |
+
print(f"{torch.cuda.memory_allocated()=}")
|
| 53 |
+
|
| 54 |
+
llm.wake_up()
|
| 55 |
+
|
| 56 |
+
print("CUDA Memory Usage (after wakeup):")
|
| 57 |
+
torch.cuda.empty_cache()
|
| 58 |
+
print(f"{torch.cuda.memory_allocated()=}")
|
| 59 |
+
|
| 60 |
+
run_inference("Paris is")
|
| 61 |
+
|
| 62 |
+
If sleep mode is enabled, you should see the memory usage reduce after sleep.
|
| 63 |
+
|
| 64 |
+
After applying the vLLM patch and completing the installation, you can enable sleep mode in verl to reduce memory overhead. This allows verl to offload unused GPU memory during rollout, significantly lowering the memory footprint during long-context training or multi-node reinforcement learning.
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
Enable CUDA Graph and Bypass ROCm-related issues
|
| 68 |
+
--------------------------------------------------------------
|
| 69 |
+
|
| 70 |
+
Due to potential issues with CUDA graph capture in ROCm, we’ve found that vLLM’s CUDA graph feature cannot be enabled on multiple nodes in verl on AMD platforms with vLLM V1 mode. This leads to significantly slower rollout performance.
|
| 71 |
+
|
| 72 |
+
Our investigation shows that ROCm may trigger an unexpected crash when attempting to capture large batches with CUDA graph. One workaround is to patch the LLM configuration (from `this commit <https://github.com/volcengine/verl/blob/v0.3.0.rc0/verl/workers/rollout/vllm_rollout/vllm_rollout_spmd.py#L100-L115>`_).
|
| 73 |
+
|
| 74 |
+
.. code-block:: python
|
| 75 |
+
|
| 76 |
+
self.inference_engine = LLM(
|
| 77 |
+
model=model_path,
|
| 78 |
+
enable_sleep_mode=True,
|
| 79 |
+
tensor_parallel_size=tensor_parallel_size,
|
| 80 |
+
distributed_executor_backend="external_launcher",
|
| 81 |
+
dtype=config.dtype,
|
| 82 |
+
enforce_eager=config.enforce_eager,
|
| 83 |
+
gpu_memory_utilization=config.gpu_memory_utilization,
|
| 84 |
+
disable_custom_all_reduce=True,
|
| 85 |
+
disable_mm_preprocessor_cache=True,
|
| 86 |
+
limit_mm_per_prompt=limit_mm_per_prompt,
|
| 87 |
+
skip_tokenizer_init=False,
|
| 88 |
+
max_model_len=max_model_len,
|
| 89 |
+
load_format=load_format,
|
| 90 |
+
disable_log_stats=config.disable_log_stats,
|
| 91 |
+
max_num_batched_tokens=max_num_batched_tokens,
|
| 92 |
+
enable_chunked_prefill=config.enable_chunked_prefill,
|
| 93 |
+
enable_prefix_caching=True,
|
| 94 |
+
trust_remote_code=trust_remote_code,
|
| 95 |
+
# enable compilation config to bypass oom on rocm
|
| 96 |
+
# change depends on your GPU memory size
|
| 97 |
+
compilation_config={"cudagraph_capture_sizes": [1, 2, 4, 8, 16, 32, 64]},
|
| 98 |
+
seed=config.get('seed', 0),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
Then, you can choose to enable CUDA graph by setting the following environment variables (see `this page <https://github.com/volcengine/verl/blob/v0.3.0.rc0/docs/README_vllm0.8.md>`_):
|
| 102 |
+
|
| 103 |
+
.. code-block:: bash
|
| 104 |
+
|
| 105 |
+
actor_rollout_ref.rollout.enforce_eager=False \
|
verl/docs/api/data.rst
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Data interface
|
| 2 |
+
=========================
|
| 3 |
+
|
| 4 |
+
Last updated: 05/19/2025 (API docstrings are auto-generated).
|
| 5 |
+
|
| 6 |
+
DataProto is the interface for data exchange.
|
| 7 |
+
|
| 8 |
+
The :class:`verl.DataProto` class contains two key members:
|
| 9 |
+
|
| 10 |
+
- batch: a :class:`tensordict.TensorDict` object for the actual data
|
| 11 |
+
- meta_info: a :class:`Dict` with additional meta information
|
| 12 |
+
|
| 13 |
+
TensorDict
|
| 14 |
+
~~~~~~~~~~~~
|
| 15 |
+
|
| 16 |
+
:attr:`DataProto.batch` is built on top of :class:`tensordict`, a project in the PyTorch ecosystem.
|
| 17 |
+
A TensorDict is a dict-like container for tensors. To instantiate a TensorDict, you must specify key-value pairs as well as the batch size.
|
| 18 |
+
|
| 19 |
+
.. code-block:: python
|
| 20 |
+
|
| 21 |
+
>>> import torch
|
| 22 |
+
>>> from tensordict import TensorDict
|
| 23 |
+
>>> tensordict = TensorDict({"zeros": torch.zeros(2, 3, 4), "ones": torch.ones(2, 3, 5)}, batch_size=[2,])
|
| 24 |
+
>>> tensordict["twos"] = 2 * torch.ones(2, 5, 6)
|
| 25 |
+
>>> zeros = tensordict["zeros"]
|
| 26 |
+
>>> tensordict
|
| 27 |
+
TensorDict(
|
| 28 |
+
fields={
|
| 29 |
+
ones: Tensor(shape=torch.Size([2, 3, 5]), device=cpu, dtype=torch.float32, is_shared=False),
|
| 30 |
+
twos: Tensor(shape=torch.Size([2, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False),
|
| 31 |
+
zeros: Tensor(shape=torch.Size([2, 3, 4]), device=cpu, dtype=torch.float32, is_shared=False)},
|
| 32 |
+
batch_size=torch.Size([2]),
|
| 33 |
+
device=None,
|
| 34 |
+
is_shared=False)
|
| 35 |
+
|
| 36 |
+
One can also index a tensordict along its batch_size. The contents of the TensorDict can be manipulated collectively as well.
|
| 37 |
+
|
| 38 |
+
.. code-block:: python
|
| 39 |
+
|
| 40 |
+
>>> tensordict[..., :1]
|
| 41 |
+
TensorDict(
|
| 42 |
+
fields={
|
| 43 |
+
ones: Tensor(shape=torch.Size([1, 3, 5]), device=cpu, dtype=torch.float32, is_shared=False),
|
| 44 |
+
twos: Tensor(shape=torch.Size([1, 5, 6]), device=cpu, dtype=torch.float32, is_shared=False),
|
| 45 |
+
zeros: Tensor(shape=torch.Size([1, 3, 4]), device=cpu, dtype=torch.float32, is_shared=False)},
|
| 46 |
+
batch_size=torch.Size([1]),
|
| 47 |
+
device=None,
|
| 48 |
+
is_shared=False)
|
| 49 |
+
>>> tensordict = tensordict.to("cuda:0")
|
| 50 |
+
>>> tensordict = tensordict.reshape(6)
|
| 51 |
+
|
| 52 |
+
For more about :class:`tensordict.TensorDict` usage, see the official tensordict_ documentation.
|
| 53 |
+
|
| 54 |
+
.. _tensordict: https://pytorch.org/tensordict/overview.html
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
Core APIs
|
| 58 |
+
~~~~~~~~~~~~~~~~~
|
| 59 |
+
|
| 60 |
+
.. autoclass:: verl.DataProto
|
| 61 |
+
:members: to, select, union, make_iterator, concat
|
verl/docs/api/single_controller.rst
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Single Controller interface
|
| 2 |
+
============================
|
| 3 |
+
|
| 4 |
+
Last updated: 05/27/2025 (API docstrings are auto-generated).
|
| 5 |
+
|
| 6 |
+
The Single Controller provides a unified interface for managing distributed workers
|
| 7 |
+
using Ray or other backends and executing functions across them.
|
| 8 |
+
It simplifies the process of dispatching tasks and collecting results, particularly
|
| 9 |
+
when dealing with data parallelism or model parallelism.
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
Core APIs
|
| 13 |
+
~~~~~~~~~~~~~~~~~
|
| 14 |
+
|
| 15 |
+
.. autoclass:: verl.single_controller.Worker
|
| 16 |
+
:members: __init__, __new__, get_master_addr_port, get_cuda_visible_devices, world_size, rank
|
| 17 |
+
|
| 18 |
+
.. autoclass:: verl.single_controller.WorkerGroup
|
| 19 |
+
:members: __init__, world_size
|
| 20 |
+
|
| 21 |
+
.. autoclass:: verl.single_controller.ClassWithInitArgs
|
| 22 |
+
:members: __init__, __call__
|
| 23 |
+
|
| 24 |
+
.. autoclass:: verl.single_controller.ResourcePool
|
| 25 |
+
:members: __init__, world_size, local_world_size_list, local_rank_list
|
| 26 |
+
|
| 27 |
+
.. autoclass:: verl.single_controller.ray.RayWorkerGroup
|
| 28 |
+
:members: __init__
|
| 29 |
+
|
| 30 |
+
.. autofunction:: verl.single_controller.ray.create_colocated_worker_cls
|
verl/docs/api/trainer.rst
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Trainer Interface
|
| 2 |
+
================================
|
| 3 |
+
|
| 4 |
+
Last updated: 06/08/2025 (API docstrings are auto-generated).
|
| 5 |
+
|
| 6 |
+
Trainers drive the training loop. Introducing new trainer classes in case of new training paradiam is encouraged.
|
| 7 |
+
|
| 8 |
+
.. autosummary::
|
| 9 |
+
:nosignatures:
|
| 10 |
+
|
| 11 |
+
verl.trainer.ppo.ray_trainer.RayPPOTrainer
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
Core APIs
|
| 15 |
+
~~~~~~~~~~~~~~~~~
|
| 16 |
+
|
| 17 |
+
.. autoclass:: verl.trainer.ppo.ray_trainer.RayPPOTrainer
|
| 18 |
+
:members: __init__, init_workers, fit
|
| 19 |
+
|
| 20 |
+
.. automodule:: verl.utils.tokenizer
|
| 21 |
+
:members: hf_tokenizer
|
| 22 |
+
|
| 23 |
+
.. automodule:: verl.trainer.ppo.core_algos
|
| 24 |
+
:members: agg_loss, kl_penalty, compute_policy_loss, kl_penalty
|
| 25 |
+
|
| 26 |
+
.. automodule:: verl.trainer.ppo.reward
|
| 27 |
+
:members: load_reward_manager, compute_reward, compute_reward_async
|
| 28 |
+
|
| 29 |
+
.. autoclass:: verl.workers.reward_manager.NaiveRewardManager
|
| 30 |
+
|
| 31 |
+
.. autoclass:: verl.workers.reward_manager.DAPORewardManager
|
verl/docs/api/utils.rst
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Utilities
|
| 2 |
+
============
|
| 3 |
+
|
| 4 |
+
Last updated: 05/19/2025 (API docstrings are auto-generated).
|
| 5 |
+
|
| 6 |
+
This section documents the utility functions and classes in the VERL library.
|
| 7 |
+
|
| 8 |
+
Python Functional Utilities
|
| 9 |
+
------------------------------
|
| 10 |
+
|
| 11 |
+
.. automodule:: verl.utils.py_functional
|
| 12 |
+
:members: append_to_dict
|
| 13 |
+
|
| 14 |
+
File System Utilities
|
| 15 |
+
------------------------
|
| 16 |
+
|
| 17 |
+
.. automodule:: verl.utils.fs
|
| 18 |
+
:members: copy_to_local
|
| 19 |
+
|
| 20 |
+
Tracking Utilities
|
| 21 |
+
---------------------
|
| 22 |
+
|
| 23 |
+
.. automodule:: verl.utils.tracking
|
| 24 |
+
:members: Tracking
|
| 25 |
+
|
| 26 |
+
Metrics Utilities
|
| 27 |
+
---------------------
|
| 28 |
+
|
| 29 |
+
.. automodule:: verl.utils.metric
|
| 30 |
+
:members: reduce_metrics
|
| 31 |
+
|
| 32 |
+
Checkpoint Management
|
| 33 |
+
------------------------
|
| 34 |
+
|
| 35 |
+
.. automodule:: verl.utils.checkpoint.checkpoint_manager
|
| 36 |
+
:members: find_latest_ckpt_path
|
| 37 |
+
|
| 38 |
+
.. automodule:: verl.utils.checkpoint.fsdp_checkpoint_manager
|
| 39 |
+
:members: FSDPCheckpointManager
|
| 40 |
+
|
| 41 |
+
Dataset Utilities
|
| 42 |
+
---------------------
|
| 43 |
+
|
| 44 |
+
.. automodule:: verl.utils.dataset.rl_dataset
|
| 45 |
+
:members: RLHFDataset, collate_fn
|
| 46 |
+
|
| 47 |
+
Torch Functional Utilities
|
| 48 |
+
-----------------------------
|
| 49 |
+
|
| 50 |
+
.. automodule:: verl.utils.torch_functional
|
| 51 |
+
:members: get_constant_schedule_with_warmup, masked_whiten, masked_mean, logprobs_from_logits
|
| 52 |
+
|
| 53 |
+
Sequence Length Balancing
|
| 54 |
+
----------------------------
|
| 55 |
+
|
| 56 |
+
.. automodule:: verl.utils.seqlen_balancing
|
| 57 |
+
:members: get_reverse_idx, rearrange_micro_batches
|
| 58 |
+
|
| 59 |
+
Ulysses Utilities
|
| 60 |
+
--------------------
|
| 61 |
+
|
| 62 |
+
.. automodule:: verl.utils.ulysses
|
| 63 |
+
:members: gather_outputs_and_unpad, ulysses_pad_and_slice_inputs
|
| 64 |
+
|
| 65 |
+
FSDP Utilities
|
| 66 |
+
------------------
|
| 67 |
+
|
| 68 |
+
.. automodule:: verl.utils.fsdp_utils
|
| 69 |
+
:members: get_fsdp_wrap_policy, get_init_weight_context_manager, init_fn, load_fsdp_model_to_gpu, load_fsdp_optimizer, offload_fsdp_model_to_cpu, offload_fsdp_optimizer,
|
| 70 |
+
|
| 71 |
+
Debug Utilities
|
| 72 |
+
-------------------
|
| 73 |
+
|
| 74 |
+
.. automodule:: verl.utils.profiler
|
| 75 |
+
:members: log_gpu_memory_usage, GPUMemoryLogger
|
| 76 |
+
|
verl/docs/ascend_tutorial/ascend_profiling_en.rst
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Data collection based on FSDP backend on Ascend devices(en)
|
| 2 |
+
==========================================================================================
|
| 3 |
+
|
| 4 |
+
Last updated: 08/14/2025.
|
| 5 |
+
|
| 6 |
+
This is a tutorial for data collection using the GRPO or DAPO algorithm
|
| 7 |
+
based on FSDP on Ascend devices.
|
| 8 |
+
|
| 9 |
+
Configuration
|
| 10 |
+
-------------
|
| 11 |
+
|
| 12 |
+
Leverage two levels of configuration to control data collection:
|
| 13 |
+
|
| 14 |
+
1. **Global profiler control**: Use parameters in ``ppo_trainer.yaml`` to control the collection mode and steps.
|
| 15 |
+
2. **Role profile control**: Use parameters in each role's ``profile`` field to control the collection mode for each role.
|
| 16 |
+
|
| 17 |
+
Global collection control
|
| 18 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 19 |
+
|
| 20 |
+
Use parameters in ppo_trainer.yaml to control the collection mode
|
| 21 |
+
and steps.
|
| 22 |
+
|
| 23 |
+
- global_profiler: Control the ranks and mode of profiling
|
| 24 |
+
|
| 25 |
+
- tool: The profiling tool to use, options are nsys, npu, torch,
|
| 26 |
+
torch_memory.
|
| 27 |
+
- steps: This parameter can be set as a list that has
|
| 28 |
+
collection steps, such as [2, 4], which means it will collect steps 2
|
| 29 |
+
and 4. If set to null, no collection occurs.
|
| 30 |
+
- save_path: The path to save the collected data. Default is
|
| 31 |
+
"outputs/profile".
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
Role collection control
|
| 35 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 36 |
+
|
| 37 |
+
In each role's ``profiler`` field, you can control the collection mode for that role.
|
| 38 |
+
|
| 39 |
+
- enable: Whether to enable profiling for this role.
|
| 40 |
+
- all_ranks: Whether to collect data from all ranks.
|
| 41 |
+
- ranks: A list of ranks to collect data from. If empty, no data is collected.
|
| 42 |
+
- tool_config: Configuration for the profiling tool used by this role.
|
| 43 |
+
|
| 44 |
+
Use parameters in each role's ``profiler.tool_config.npu`` to control npu profiler behavior:
|
| 45 |
+
|
| 46 |
+
- level: Collection level—options are level_none, level0, level1, and
|
| 47 |
+
level2
|
| 48 |
+
|
| 49 |
+
- level_none: Disables all level-based data collection (turns off
|
| 50 |
+
profiler_level).
|
| 51 |
+
- level0: Collect high-level application data, underlying NPU data,
|
| 52 |
+
and operator execution details on NPU.
|
| 53 |
+
- level1: Extends level0 by adding CANN-layer AscendCL data and AI
|
| 54 |
+
Core performance metrics on NPU.
|
| 55 |
+
- level2: Extends level1 by adding CANN-layer Runtime data and AI
|
| 56 |
+
CPU metrics.
|
| 57 |
+
|
| 58 |
+
- contents: A list of options to control the collection content, such as
|
| 59 |
+
npu, cpu, memory, shapes, module, stack.
|
| 60 |
+
|
| 61 |
+
- npu: Whether to collect device-side performance data.
|
| 62 |
+
- cpu: Whether to collect host-side performance data.
|
| 63 |
+
- memory: Whether to enable memory analysis.
|
| 64 |
+
- shapes: Whether to record tensor shapes.
|
| 65 |
+
- module: Whether to record framework-layer Python call stack
|
| 66 |
+
information.
|
| 67 |
+
- stack: Whether to record operator call stack information.
|
| 68 |
+
|
| 69 |
+
- analysis: Enables automatic data parsing.
|
| 70 |
+
- discrete: Whether to enable discrete mode.
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
Examples
|
| 74 |
+
--------
|
| 75 |
+
|
| 76 |
+
Disabling collection
|
| 77 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 78 |
+
|
| 79 |
+
.. code:: yaml
|
| 80 |
+
|
| 81 |
+
global_profiler:
|
| 82 |
+
steps: null # disable profile
|
| 83 |
+
|
| 84 |
+
End-to-End collection
|
| 85 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 86 |
+
|
| 87 |
+
.. code:: yaml
|
| 88 |
+
|
| 89 |
+
global_profiler:
|
| 90 |
+
steps: [1, 2, 5]
|
| 91 |
+
actor_rollout_ref:
|
| 92 |
+
actor:
|
| 93 |
+
profiler:
|
| 94 |
+
enable: True
|
| 95 |
+
all_ranks: True
|
| 96 |
+
tool_config:
|
| 97 |
+
npu:
|
| 98 |
+
discrete: False
|
| 99 |
+
# rollout & ref follow actor settings
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
Discrete Mode Collection
|
| 103 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 104 |
+
|
| 105 |
+
.. code:: yaml
|
| 106 |
+
|
| 107 |
+
global_profiler:
|
| 108 |
+
steps: [1, 2, 5]
|
| 109 |
+
actor_rollout_ref:
|
| 110 |
+
actor:
|
| 111 |
+
profiler:
|
| 112 |
+
enable: True
|
| 113 |
+
all_ranks: True
|
| 114 |
+
tool_config:
|
| 115 |
+
npu:
|
| 116 |
+
discrete: True
|
| 117 |
+
# rollout & ref follow actor settings
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
Visualization
|
| 121 |
+
-------------
|
| 122 |
+
|
| 123 |
+
Collected data is stored in the user-defined save_path and can be
|
| 124 |
+
visualized by using the `MindStudio Insight <https://www.hiascend.com/document/detail/zh/mindstudio/80RC1/GUI_baseddevelopmenttool/msascendinsightug/Insight_userguide_0002.html>`_ tool.
|
| 125 |
+
|
| 126 |
+
If the analysis parameter is set to False, offline parsing is required after data collection:
|
| 127 |
+
|
| 128 |
+
.. code:: python
|
| 129 |
+
|
| 130 |
+
import torch_npu
|
| 131 |
+
# Set profiler_path to the parent directory of the "localhost.localdomain_<PID>_<timestamp>_ascend_pt" folder
|
| 132 |
+
torch_npu.profiler.profiler.analyse(profiler_path=profiler_path)
|
verl/docs/ascend_tutorial/ascend_profiling_zh.rst
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Data collection based on FSDP backend on Ascend devices(zh)
|
| 2 |
+
====================================
|
| 3 |
+
|
| 4 |
+
在昇腾设备上基于FSDP后端进行数据采集
|
| 5 |
+
|
| 6 |
+
Last updated: 08/14/2025.
|
| 7 |
+
|
| 8 |
+
这是一份在昇腾设备上基于FSDP后端使用GRPO或DAPO算法进行数据采集的教程。
|
| 9 |
+
|
| 10 |
+
配置
|
| 11 |
+
----
|
| 12 |
+
|
| 13 |
+
使用两级profile设置来控制数据采集
|
| 14 |
+
|
| 15 |
+
- 全局采集控制:使用verl/trainer/config/ppo_trainer.yaml中的配置项控制采集的模式和步数,
|
| 16 |
+
- 角色profile控制:通过每个角色中的配置项控制等参数。
|
| 17 |
+
|
| 18 |
+
全局采集控制
|
| 19 |
+
~~~~~~~~~~~~
|
| 20 |
+
|
| 21 |
+
通过 ppo_trainer.yaml 中的参数控制采集步数和模式:
|
| 22 |
+
|
| 23 |
+
- global_profiler: 控制采集的rank和模式
|
| 24 |
+
|
| 25 |
+
- tool: 使用的采集工具,选项有 nsys、npu、torch、torch_memory。
|
| 26 |
+
- steps: 此参数可以设置为包含采集步数的列表,例如 [2, 4],表示将采集第2步和第4步。如果设置为 null,则不进行采集。
|
| 27 |
+
- save_path: 保存采集数据的路径。默认值为 "outputs/profile"。
|
| 28 |
+
|
| 29 |
+
角色profiler控制
|
| 30 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 31 |
+
|
| 32 |
+
在每个角色的 ``profiler`` 字段中,您可以控制该角色的采集模式。
|
| 33 |
+
|
| 34 |
+
- enable: 是否为此角色启用性能分析。
|
| 35 |
+
- all_ranks: 是否从所有rank收集数据。
|
| 36 |
+
- ranks: 要收集数据的rank列表。如果为空,则不收集数据。
|
| 37 |
+
- tool_config: 此角色使用的性能分析工具的配置。
|
| 38 |
+
|
| 39 |
+
通过每个角色的 ``profiler.tool_config.npu`` 中的参数控制具体采集行为:
|
| 40 |
+
|
| 41 |
+
- level: 采集级别—选项有 level_none、level0、level1 和 level2
|
| 42 |
+
|
| 43 |
+
- level_none: 禁用所有基于级别的数据采集(关闭 profiler_level)。
|
| 44 |
+
- level0: 采集高级应用数据、底层NPU数据和NPU上的算子执行详情。
|
| 45 |
+
- level1: 在level0基础上增加CANN层AscendCL数据和NPU上的AI Core性能指标。
|
| 46 |
+
- level2: 在level1基础上增加CANN层Runtime数据和AI CPU指标。
|
| 47 |
+
|
| 48 |
+
- contents: 控制采集内容的选项列表,例如
|
| 49 |
+
npu、cpu、memory、shapes、module、stack。
|
| 50 |
+
|
| 51 |
+
- npu: 是否采集设备端性能数据。
|
| 52 |
+
- cpu: 是否采集主机端性能数据。
|
| 53 |
+
- memory: 是否启用内存分析。
|
| 54 |
+
- shapes: 是否记录张量形状。
|
| 55 |
+
- module: 是否记录框架层Python调用栈信息。
|
| 56 |
+
- stack: 是否记录算子调用栈信息。
|
| 57 |
+
|
| 58 |
+
- analysis: 启用自动数据解析。
|
| 59 |
+
- discrete: 使用离散模式。
|
| 60 |
+
|
| 61 |
+
示例
|
| 62 |
+
----
|
| 63 |
+
|
| 64 |
+
禁用采集
|
| 65 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 66 |
+
|
| 67 |
+
.. code:: yaml
|
| 68 |
+
|
| 69 |
+
global_profiler:
|
| 70 |
+
steps: null # disable profile
|
| 71 |
+
|
| 72 |
+
端到端采集
|
| 73 |
+
~~~~~~~~~~~~~~~~~~~~~
|
| 74 |
+
|
| 75 |
+
.. code:: yaml
|
| 76 |
+
|
| 77 |
+
global_profiler:
|
| 78 |
+
steps: [1, 2, 5]
|
| 79 |
+
actor_rollout_ref:
|
| 80 |
+
actor:
|
| 81 |
+
profiler:
|
| 82 |
+
enable: True
|
| 83 |
+
all_ranks: True
|
| 84 |
+
tool_config:
|
| 85 |
+
npu:
|
| 86 |
+
discrete: False
|
| 87 |
+
# rollout & ref follow actor settings
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
离散模式采集
|
| 91 |
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
| 92 |
+
|
| 93 |
+
.. code:: yaml
|
| 94 |
+
|
| 95 |
+
global_profiler:
|
| 96 |
+
steps: [1, 2, 5]
|
| 97 |
+
actor_rollout_ref:
|
| 98 |
+
actor:
|
| 99 |
+
profiler:
|
| 100 |
+
enable: True
|
| 101 |
+
all_ranks: True
|
| 102 |
+
tool_config:
|
| 103 |
+
npu:
|
| 104 |
+
discrete: True
|
| 105 |
+
# rollout & ref follow actor settings
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
可视化
|
| 109 |
+
------
|
| 110 |
+
|
| 111 |
+
采集后的数据存放在用户设置的save_path下,可通过 `MindStudio Insight <https://www.hiascend.com/document/detail/zh/mindstudio/80RC1/GUI_baseddevelopmenttool/msascendinsightug/Insight_userguide_0002.html>`_ 工具进行可视化。
|
| 112 |
+
|
| 113 |
+
如果analysis参数设置为False,采集之后需要进行离线解析:
|
| 114 |
+
|
| 115 |
+
.. code:: python
|
| 116 |
+
|
| 117 |
+
import torch_npu
|
| 118 |
+
# profiler_path请设置为"localhost.localdomain_<PID>_<timestamp>_ascend_pt"目录的上一级目录
|
| 119 |
+
torch_npu.profiler.profiler.analyse(profiler_path=profiler_path)
|
verl/docs/ascend_tutorial/ascend_quick_start.rst
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
verl x Ascend
|
| 2 |
+
===================================
|
| 3 |
+
|
| 4 |
+
Last updated: 08/15/2025.
|
| 5 |
+
|
| 6 |
+
我们在 verl 上增加对华为昇腾设备的支持。
|
| 7 |
+
|
| 8 |
+
硬件支持
|
| 9 |
+
-----------------------------------
|
| 10 |
+
|
| 11 |
+
Atlas 200T A2 Box16
|
| 12 |
+
|
| 13 |
+
Atlas 900 A2 PODc
|
| 14 |
+
|
| 15 |
+
Atlas 800T A3
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
安装
|
| 19 |
+
-----------------------------------
|
| 20 |
+
|
| 21 |
+
基础环境准备
|
| 22 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 23 |
+
|
| 24 |
+
+-----------+-------------+
|
| 25 |
+
| software | version |
|
| 26 |
+
+-----------+-------------+
|
| 27 |
+
| Python | == 3.10 |
|
| 28 |
+
+-----------+-------------+
|
| 29 |
+
| CANN | == 8.1.RC1 |
|
| 30 |
+
+-----------+-------------+
|
| 31 |
+
| torch | == 2.5.1 |
|
| 32 |
+
+-----------+-------------+
|
| 33 |
+
| torch_npu | == 2.5.1 |
|
| 34 |
+
+-----------+-------------+
|
| 35 |
+
|
| 36 |
+
基础环境准备请参照这份 `文档 <https://gitee.com/ascend/pytorch>`_ 。
|
| 37 |
+
|
| 38 |
+
vllm & vllm-ascend
|
| 39 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 40 |
+
|
| 41 |
+
为了能够在 verl 中正常使用 vllm,需使用以下命令编译安装 vllm 和 vllm-ascend。请注意根据机器类型区分安装方式。
|
| 42 |
+
|
| 43 |
+
.. code-block:: bash
|
| 44 |
+
|
| 45 |
+
# vllm
|
| 46 |
+
git clone -b v0.7.3 --depth 1 https://github.com/vllm-project/vllm.git
|
| 47 |
+
cd vllm
|
| 48 |
+
pip install -r requirements-build.txt
|
| 49 |
+
|
| 50 |
+
# for Atlas 200T A2 Box16
|
| 51 |
+
VLLM_TARGET_DEVICE=empty pip install -e . --extra-index https://download.pytorch.org/whl/cpu/
|
| 52 |
+
|
| 53 |
+
# for Atlas 900 A2 PODc
|
| 54 |
+
VLLM_TARGET_DEVICE=empty pip install -e .
|
| 55 |
+
|
| 56 |
+
.. code-block:: bash
|
| 57 |
+
|
| 58 |
+
# vllm-ascend
|
| 59 |
+
git clone -b v0.7.3.post1 --depth 1 https://github.com/vllm-project/vllm-ascend.git
|
| 60 |
+
cd vllm-ascend
|
| 61 |
+
export COMPILE_CUSTOM_KERNELS=1
|
| 62 |
+
python setup.py install
|
| 63 |
+
|
| 64 |
+
安装verl
|
| 65 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 66 |
+
|
| 67 |
+
.. code-block:: bash
|
| 68 |
+
|
| 69 |
+
git clone https://github.com/volcengine/verl.git
|
| 70 |
+
cd verl
|
| 71 |
+
pip install -r requirements-npu.txt
|
| 72 |
+
pip install -e .
|
| 73 |
+
|
| 74 |
+
其他三方库说明
|
| 75 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 76 |
+
|
| 77 |
+
+--------------+---------------+
|
| 78 |
+
| software | description |
|
| 79 |
+
+--------------+---------------+
|
| 80 |
+
| transformers | v4.52.4 |
|
| 81 |
+
+--------------+---------------+
|
| 82 |
+
| flash_attn | not supported |
|
| 83 |
+
+--------------+---------------+
|
| 84 |
+
| liger-kernel | not supported |
|
| 85 |
+
+--------------+---------------+
|
| 86 |
+
|
| 87 |
+
1. 支持通过 transformers 使能 --flash_attention_2, transformers 需等于 4.52.4版本。
|
| 88 |
+
2. 不支持通过 flash_attn 使能 flash attention 加速。
|
| 89 |
+
3. 不支持 liger-kernel 使能。
|
| 90 |
+
4. 针对 x86 服务器,需要安装 cpu 版本的 torchvision。
|
| 91 |
+
|
| 92 |
+
.. code-block:: bash
|
| 93 |
+
|
| 94 |
+
pip install torchvision==0.20.1+cpu --index-url https://download.pytorch.org/whl/cpu
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
快速开始
|
| 98 |
+
-----------------------------------
|
| 99 |
+
正式使用前,建议您通过对Qwen2.5-0.5B GRPO的训练尝试以检验环境准备和安装的正确性。
|
| 100 |
+
|
| 101 |
+
1.下载数据集并将数据集预处理为parquet格式,以便包含计算RL奖励所需的必要字段
|
| 102 |
+
|
| 103 |
+
.. code-block:: bash
|
| 104 |
+
|
| 105 |
+
python3 examples/data_preprocess/gsm8k.py --local_save_dir ~/data/gsm8k
|
| 106 |
+
|
| 107 |
+
2.执行训练
|
| 108 |
+
|
| 109 |
+
.. code-block:: bash
|
| 110 |
+
|
| 111 |
+
set -x
|
| 112 |
+
|
| 113 |
+
export VLLM_ATTENTION_BACKEND=XFORMERS
|
| 114 |
+
|
| 115 |
+
python3 -m verl.trainer.main_ppo \
|
| 116 |
+
algorithm.adv_estimator=grpo \
|
| 117 |
+
data.train_files=$HOME/data/gsm8k/train.parquet \
|
| 118 |
+
data.val_files=$HOME/data/gsm8k/test.parquet \
|
| 119 |
+
data.train_batch_size=128 \
|
| 120 |
+
data.max_prompt_length=512 \
|
| 121 |
+
data.max_response_length=128 \
|
| 122 |
+
data.filter_overlong_prompts=True \
|
| 123 |
+
data.truncation='error' \
|
| 124 |
+
actor_rollout_ref.model.path=Qwen/Qwen2.5-0.5B-Instruct \
|
| 125 |
+
actor_rollout_ref.actor.optim.lr=5e-7 \
|
| 126 |
+
actor_rollout_ref.model.use_remove_padding=False \
|
| 127 |
+
actor_rollout_ref.actor.entropy_coeff=0.001 \
|
| 128 |
+
actor_rollout_ref.actor.ppo_mini_batch_size=64 \
|
| 129 |
+
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=20 \
|
| 130 |
+
actor_rollout_ref.actor.use_kl_loss=True \
|
| 131 |
+
actor_rollout_ref.actor.kl_loss_coef=0.001 \
|
| 132 |
+
actor_rollout_ref.actor.kl_loss_type=low_var_kl \
|
| 133 |
+
actor_rollout_ref.model.enable_gradient_checkpointing=True \
|
| 134 |
+
actor_rollout_ref.actor.fsdp_config.param_offload=False \
|
| 135 |
+
actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
|
| 136 |
+
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=40 \
|
| 137 |
+
actor_rollout_ref.rollout.enable_chunked_prefill=False \
|
| 138 |
+
actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
|
| 139 |
+
actor_rollout_ref.rollout.name=vllm \
|
| 140 |
+
actor_rollout_ref.rollout.gpu_memory_utilization=0.6 \
|
| 141 |
+
actor_rollout_ref.rollout.n=5 \
|
| 142 |
+
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=40 \
|
| 143 |
+
actor_rollout_ref.ref.fsdp_config.param_offload=True \
|
| 144 |
+
algorithm.kl_ctrl.kl_coef=0.001 \
|
| 145 |
+
trainer.critic_warmup=0 \
|
| 146 |
+
trainer.logger=console \
|
| 147 |
+
trainer.project_name='verl_grpo_example_gsm8k' \
|
| 148 |
+
trainer.experiment_name='qwen2_7b_function_rm' \
|
| 149 |
+
trainer.n_gpus_per_node=8 \
|
| 150 |
+
trainer.nnodes=1 \
|
| 151 |
+
trainer.save_freq=-1 \
|
| 152 |
+
trainer.test_freq=5 \
|
| 153 |
+
trainer.total_epochs=1 \
|
| 154 |
+
trainer.device=npu $@
|
| 155 |
+
|
| 156 |
+
(可选) 设置MindSpeed训练后端指导
|
| 157 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 158 |
+
1. 参考 `MindSpeed README <https://gitee.com/ascend/MindSpeed>`_ 说明安装 MindSpeed 加速库。
|
| 159 |
+
|
| 160 |
+
2. 使能 verl worker 模型 ``strategy`` 配置为 ``megatron`` ,例如 ``actor_rollout_ref.actor.strategy=megatron``。
|
| 161 |
+
|
| 162 |
+
3. MindSpeed 自定义入参可通过 ``override_transformer_config`` 参数传入,例如对 actor 模型开启 FA 特性可使用 ``+actor_rollout_ref.actor.megatron.override_transformer_config.use_flash_attn=True``。
|
| 163 |
+
|
| 164 |
+
4. 更多特性信息可参考 `MindSpeed+verl 文档 <https://gitee.com/ascend/MindSpeed/blob/master/docs/user-guide/verl.md>`_ 。
|
| 165 |
+
|
| 166 |
+
支持现状
|
| 167 |
+
-----------------------------------
|
| 168 |
+
|
| 169 |
+
**表1** RL类算法
|
| 170 |
+
|
| 171 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 172 |
+
| algorithm | model | actor.strategy | rollout.name | hardware |
|
| 173 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 174 |
+
| GRPO | Qwen2.5-7B-instruct | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 175 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 176 |
+
| GRPO | Qwen2.5-32B-instruct | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 177 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 178 |
+
| GRPO | Qwen2.5-VL-3B-instruct | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 179 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 180 |
+
| GRPO | Qwen2.5-VL-7B-instruct | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 181 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 182 |
+
| GRPO | Qwen2.5-VL-32B-instruct | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 183 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 184 |
+
| GRPO | Qwen3-8B | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 185 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 186 |
+
| GRPO | Qwen3-32B | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 187 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 188 |
+
| DAPO | Qwen2.5-7B-instruct | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 189 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 190 |
+
| DAPO | Qwen2.5-32B | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 191 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 192 |
+
| DAPO | Qwen3-8B-base | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 193 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 194 |
+
| DAPO | Qwen3-14B-base | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 195 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 196 |
+
| DAPO | Qwen3-30B-A3B-base | FSDP | vllm-ascend | Atlas 200T A2 Box16 |
|
| 197 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 198 |
+
| DAPO | Qwen3-30B-A3B | megatron | vllm-ascend | Atlas 800T A3 |
|
| 199 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 200 |
+
| PPO | Qwen3-8B | FSDP | vllm-ascend | Atlas 900 A2 PODc |
|
| 201 |
+
+-----------+-------------------------+-------------------+-------------------+--------------------------+
|
| 202 |
+
|
| 203 |
+
**表2** SFT类算法
|
| 204 |
+
|
| 205 |
+
+-----------+-------------------------+-------------------+----------------------+
|
| 206 |
+
| algorithm | model | actor.strategy | hardware |
|
| 207 |
+
+-----------+-------------------------+-------------------+----------------------+
|
| 208 |
+
| SFT-PEFT | Qwen3-8B | FSDP | Atlas 900 A2 PODc |
|
| 209 |
+
+-----------+-------------------------+-------------------+----------------------+
|
| 210 |
+
| ReTool-SFT| Qwen2.5-7B-instruct | FSDP | Atlas 900 A2 PODc |
|
| 211 |
+
+-----------+-------------------------+-------------------+----------------------+
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
计划
|
| 216 |
+
-----------------------------------
|
| 217 |
+
|
| 218 |
+
查看 `roadmap <https://github.com/volcengine/verl/discussions/2171>`_ 获取更多特性的支持进度。
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
声明
|
| 223 |
+
-----------------------------------
|
| 224 |
+
verl中提供的ascend支持代码皆为参考样例,如在生产环境中使用请通过官方正式途径沟通,谢谢。
|
verl/docs/ascend_tutorial/ascend_sglang_quick_start.rst
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
verl x Ascend
|
| 2 |
+
===================================
|
| 3 |
+
|
| 4 |
+
Last updated: 09/25/2025.
|
| 5 |
+
|
| 6 |
+
我们在 verl 上增加对华为昇腾设备的支持。
|
| 7 |
+
|
| 8 |
+
硬件支持
|
| 9 |
+
-----------------------------------
|
| 10 |
+
|
| 11 |
+
Atlas 200T A2 Box16
|
| 12 |
+
|
| 13 |
+
Atlas 900 A2 PODc
|
| 14 |
+
|
| 15 |
+
Atlas 800T A3
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
安装
|
| 19 |
+
-----------------------------------
|
| 20 |
+
|
| 21 |
+
基础环境准备
|
| 22 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 23 |
+
|
| 24 |
+
+-----------+-------------+
|
| 25 |
+
| software | version |
|
| 26 |
+
+-----------+-------------+
|
| 27 |
+
| Python | == 3.11 |
|
| 28 |
+
+-----------+-------------+
|
| 29 |
+
| CANN | == 8.3.RC1 |
|
| 30 |
+
+-----------+-------------+
|
| 31 |
+
| HDK | == 25.3.RC1 |
|
| 32 |
+
+-----------+-------------+
|
| 33 |
+
| torch | == 2.6.0 |
|
| 34 |
+
+-----------+-------------+
|
| 35 |
+
| torch_npu | == 2.6.0 |
|
| 36 |
+
+-----------+-------------+
|
| 37 |
+
|
| 38 |
+
**目前verl框架中sglang npu后端仅支持上述HDK、CANN和PTA版本, 商发可用版本预计2025年10月发布**
|
| 39 |
+
|
| 40 |
+
为了能够在 verl 中正常使用 sglang,需使用以下命令安装sglang、torch_memory_saver和verl。
|
| 41 |
+
|
| 42 |
+
sglang
|
| 43 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 44 |
+
.. code-block:: bash
|
| 45 |
+
|
| 46 |
+
# sglang
|
| 47 |
+
git clone https://github.com/sgl-project/sglang.git
|
| 48 |
+
cd sglang
|
| 49 |
+
mv python/pyproject.toml python/pyproject.toml.backup
|
| 50 |
+
mv python/pyproject_other.toml python/pyproject.toml
|
| 51 |
+
pip install -e "python[srt_npu]"
|
| 52 |
+
|
| 53 |
+
安装torch_memory_saver
|
| 54 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 55 |
+
.. code-block:: bash
|
| 56 |
+
|
| 57 |
+
# torch_memory_saver
|
| 58 |
+
git clone https://github.com/sgl-project/sgl-kernel-npu.git
|
| 59 |
+
cd sgl-kernel-npu
|
| 60 |
+
bash build.sh -a memory-saver
|
| 61 |
+
pip install output/torch_memory_saver*.whl
|
| 62 |
+
|
| 63 |
+
安装verl
|
| 64 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 65 |
+
|
| 66 |
+
.. code-block:: bash
|
| 67 |
+
|
| 68 |
+
git clone https://github.com/volcengine/verl.git
|
| 69 |
+
cd verl
|
| 70 |
+
pip install --no-deps -e .
|
| 71 |
+
pip install -r requirements-npu.txt
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
其他三方库说明
|
| 75 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 76 |
+
|
| 77 |
+
+--------------+---------------+
|
| 78 |
+
| software | description |
|
| 79 |
+
+--------------+---------------+
|
| 80 |
+
| transformers | v4.56.1 |
|
| 81 |
+
+--------------+---------------+
|
| 82 |
+
| triton_ascend| v3.2.0 |
|
| 83 |
+
+--------------+---------------+
|
| 84 |
+
|
| 85 |
+
1. sglang依赖 transformers v4.56.1
|
| 86 |
+
2. sglang依赖triton_ascend v3.2.0
|
| 87 |
+
3. 暂不支持多模态模型,卸载相关安装包torchvision、timm
|
| 88 |
+
|
| 89 |
+
.. code-block:: bash
|
| 90 |
+
|
| 91 |
+
pip uninstall torchvision
|
| 92 |
+
pip uninstall timm
|
| 93 |
+
pip uninstall triton
|
| 94 |
+
|
| 95 |
+
pip install transformers==4.56.1
|
| 96 |
+
pip install -i https://test.pypi.org/simple/ triton-ascend==3.2.0.dev20250925
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
快速开始
|
| 100 |
+
-----------------------------------
|
| 101 |
+
正式使用前,建议您通过对Qwen3-8B GRPO的训练尝试以检验环境准备和安装的正确性。
|
| 102 |
+
|
| 103 |
+
1.下载数据集并将数据集预处理为parquet格式,以便包含计算RL奖励所需的必要字段
|
| 104 |
+
|
| 105 |
+
.. code-block:: bash
|
| 106 |
+
|
| 107 |
+
python3 examples/data_preprocess/gsm8k.py --local_save_dir ~/data/gsm8k
|
| 108 |
+
|
| 109 |
+
2.执行训练
|
| 110 |
+
|
| 111 |
+
.. code-block:: bash
|
| 112 |
+
|
| 113 |
+
bash verl/examples/grpo_trainer/run_qwen3_8b_grpo_sglang_1k_npu.sh
|
verl/docs/examples/config.rst
ADDED
|
@@ -0,0 +1,673 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _config-explain-page:
|
| 2 |
+
|
| 3 |
+
Config Explanation
|
| 4 |
+
===================
|
| 5 |
+
|
| 6 |
+
Last updated: 06/18/2025.
|
| 7 |
+
|
| 8 |
+
ppo_trainer.yaml for RL FSDP Backend
|
| 9 |
+
-------------------------------------
|
| 10 |
+
|
| 11 |
+
Data
|
| 12 |
+
~~~~
|
| 13 |
+
|
| 14 |
+
.. code:: yaml
|
| 15 |
+
|
| 16 |
+
data:
|
| 17 |
+
tokenizer: null
|
| 18 |
+
train_files: ~/data/rlhf/gsm8k/train.parquet
|
| 19 |
+
val_files: ~/data/rlhf/gsm8k/test.parquet
|
| 20 |
+
prompt_key: prompt
|
| 21 |
+
max_prompt_length: 512
|
| 22 |
+
max_response_length: 512
|
| 23 |
+
train_batch_size: 1024
|
| 24 |
+
return_raw_input_ids: False # This should be set to true when the tokenizer between policy and rm differs
|
| 25 |
+
return_raw_chat: False
|
| 26 |
+
return_full_prompt: False
|
| 27 |
+
shuffle: True
|
| 28 |
+
filter_overlong_prompts: False
|
| 29 |
+
filter_overlong_prompts_workers: 1
|
| 30 |
+
truncation: error
|
| 31 |
+
image_key: images
|
| 32 |
+
trust_remote_code: True
|
| 33 |
+
custom_cls:
|
| 34 |
+
path: null
|
| 35 |
+
name: null
|
| 36 |
+
|
| 37 |
+
- ``data.train_files``: Training set parquet. Can be a list or a single
|
| 38 |
+
file. The program will read all files into memory, so it can't be too
|
| 39 |
+
large (< 100GB). The path can be either local path or HDFS path. For
|
| 40 |
+
HDFS path, we provide utils to download it to DRAM and convert the
|
| 41 |
+
HDFS path to local path.
|
| 42 |
+
- ``data.val_files``: Validation parquet. Can be a list or a single
|
| 43 |
+
file.
|
| 44 |
+
- ``data.prompt_key``: The field in the dataset where the prompt is
|
| 45 |
+
located. Default is 'prompt'.
|
| 46 |
+
- ``data.max_prompt_length``: Maximum prompt length. All prompts will be
|
| 47 |
+
left-padded to this length. An error will be reported if the length is
|
| 48 |
+
too long
|
| 49 |
+
- ``data.max_response_length``: Maximum response length. Rollout in RL
|
| 50 |
+
algorithms (e.g. PPO) generates up to this length
|
| 51 |
+
- ``data.train_batch_size``: Batch size sampled for one training
|
| 52 |
+
iteration of different RL algorithms.
|
| 53 |
+
- ``data.return_raw_input_ids``: Whether to return the original
|
| 54 |
+
input_ids without adding chat template. This is mainly used to
|
| 55 |
+
accommodate situations where the reward model's chat template differs
|
| 56 |
+
from the policy. It needs to be decoded first, then apply the RM's
|
| 57 |
+
chat template. If using a model-based RM, and the policy and RM
|
| 58 |
+
chat_templates are different, this flag needs to be set
|
| 59 |
+
- ``data.return_raw_chat``: Whether to return the original chat (prompt)
|
| 60 |
+
without applying chat template.
|
| 61 |
+
- ``data.return_full_prompt``: Whether to return the full prompt with chat template
|
| 62 |
+
- ``data.shuffle``: Whether to shuffle the data in the dataloader.
|
| 63 |
+
- ``data.filter_overlong_prompts``: Default don't filter.
|
| 64 |
+
- ``data.filter_overlong_prompts_workers``: For large-scale dataset, filtering
|
| 65 |
+
overlong prompts could be timeconsuming. You cat set the ``filter_overlong_prompts_workers``
|
| 66 |
+
to use multiprocessing for speed up. Default to 1.
|
| 67 |
+
- ``data.truncation``: Truncate the input_ids or prompt length if they
|
| 68 |
+
exceed max_prompt_length. Default is 'error', not allow exceed the
|
| 69 |
+
max_prompt_length. The users should increase the max_prompt_length if
|
| 70 |
+
throwing the error. You can also set ``left``, ``right`` and ``middle``.
|
| 71 |
+
When ``middle`` is selected, the logic splits the allowed max length roughly in half
|
| 72 |
+
and keeps the head and tail of the sequence, effectively discarding the middle section.
|
| 73 |
+
- ``data.image_key``: The field in the multi-modal dataset where the image is
|
| 74 |
+
located. Default is 'images'.
|
| 75 |
+
- ``data.trust_remote_code``: If the remote tokenizer has python file, we can use this field to allow
|
| 76 |
+
using remote tokenizer. For example: moonshotai/Moonlight-16B-A3B-Instruct
|
| 77 |
+
|
| 78 |
+
Customized Dataset
|
| 79 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 80 |
+
|
| 81 |
+
Customized dataset extension is implemented for the SFT trainer and can be extended to other trainers with similar changes.
|
| 82 |
+
|
| 83 |
+
.. code:: yaml
|
| 84 |
+
|
| 85 |
+
custom_cls:
|
| 86 |
+
path: null
|
| 87 |
+
name: null
|
| 88 |
+
|
| 89 |
+
- ``data.custom_cls.path``: The path to the file containing your customized dataset class. If not specified, pre-implemented dataset will be used.
|
| 90 |
+
- ``data.custom_cls.name``: The name of the dataset class within the specified file.
|
| 91 |
+
|
| 92 |
+
Actor/Rollout/Reference Policy
|
| 93 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 94 |
+
|
| 95 |
+
.. code:: yaml
|
| 96 |
+
|
| 97 |
+
actor_rollout_ref:
|
| 98 |
+
hybrid_engine: True
|
| 99 |
+
model:
|
| 100 |
+
path: ~/models/deepseek-llm-7b-chat
|
| 101 |
+
external_lib: null
|
| 102 |
+
override_config:
|
| 103 |
+
model_config: {}
|
| 104 |
+
moe_config: # Megatron only, can adjust moe configuration
|
| 105 |
+
freeze_moe_router: False # Megatron only, can freeze moe router (no grad)
|
| 106 |
+
enable_gradient_checkpointing: False
|
| 107 |
+
enable_activation_offload: False
|
| 108 |
+
trust_remote_code: False
|
| 109 |
+
use_remove_padding: False
|
| 110 |
+
actor:
|
| 111 |
+
strategy: fsdp # This is for backward-compatibility
|
| 112 |
+
ppo_mini_batch_size: 256
|
| 113 |
+
ppo_micro_batch_size: null # will be deprecated, use ppo_micro_batch_size_per_gpu
|
| 114 |
+
ppo_micro_batch_size_per_gpu: 8
|
| 115 |
+
use_dynamic_bsz: False
|
| 116 |
+
ppo_max_token_len_per_gpu: 16384 # n * ${data.max_prompt_length} + ${data.max_response_length}
|
| 117 |
+
grad_clip: 1.0
|
| 118 |
+
clip_ratio: 0.2
|
| 119 |
+
entropy_coeff: 0.0
|
| 120 |
+
use_kl_loss: False # True for GRPO
|
| 121 |
+
tis_imp_ratio_cap: -1 # set to positive values for Truncated Importance Sampling (requires setting `rollout.calculate_log_probs` as True)
|
| 122 |
+
use_torch_compile: True # False to disable torch compile
|
| 123 |
+
kl_loss_coef: 0.001 # for grpo
|
| 124 |
+
kl_loss_type: low_var_kl # for grpo
|
| 125 |
+
ppo_epochs: 1
|
| 126 |
+
data_loader_seed: null
|
| 127 |
+
shuffle: False
|
| 128 |
+
ulysses_sequence_parallel_size: 1 # sp size
|
| 129 |
+
optim:
|
| 130 |
+
lr: 1e-6
|
| 131 |
+
lr_warmup_steps: -1 # Prioritized. Negative values mean delegating to lr_warmup_steps_ratio.
|
| 132 |
+
lr_warmup_steps_ratio: 0. # the total steps will be injected during runtime
|
| 133 |
+
min_lr_ratio: 0.0 # only used with cosine lr scheduler, default to 0.0
|
| 134 |
+
num_cycles: 0.5 # only used with cosine lr scheduler, default to 0.5
|
| 135 |
+
warmup_style: constant # select from constant/cosine
|
| 136 |
+
total_training_steps: -1 # must be override by program
|
| 137 |
+
fsdp_config:
|
| 138 |
+
wrap_policy:
|
| 139 |
+
# transformer_layer_cls_to_wrap: None
|
| 140 |
+
min_num_params: 0
|
| 141 |
+
param_offload: False
|
| 142 |
+
optimizer_offload: False
|
| 143 |
+
fsdp_size: -1
|
| 144 |
+
checkpoint:
|
| 145 |
+
# What to include in saved checkpoints
|
| 146 |
+
# with 'hf_model' you can save whole model as hf format, now only use sharded model checkpoint to save space
|
| 147 |
+
save_contents: ['model', 'optimizer', 'extra']
|
| 148 |
+
# For more flexibility, you can specify the contents to load from the checkpoint.
|
| 149 |
+
load_contents: ${actor_rollout_ref.actor.checkpoint.save_contents}
|
| 150 |
+
ref:
|
| 151 |
+
fsdp_config:
|
| 152 |
+
param_offload: False
|
| 153 |
+
wrap_policy:
|
| 154 |
+
# transformer_layer_cls_to_wrap: None
|
| 155 |
+
min_num_params: 0
|
| 156 |
+
log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu
|
| 157 |
+
log_prob_micro_batch_size_per_gpu: 16
|
| 158 |
+
log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}
|
| 159 |
+
log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}
|
| 160 |
+
ulysses_sequence_parallel_size: ${actor_rollout_ref.actor.ulysses_sequence_parallel_size} # sp size
|
| 161 |
+
rollout:
|
| 162 |
+
name: vllm
|
| 163 |
+
temperature: 1.0
|
| 164 |
+
top_k: -1 # 0 for hf rollout, -1 for vllm rollout
|
| 165 |
+
top_p: 1
|
| 166 |
+
prompt_length: ${data.max_prompt_length} # not use for opensource
|
| 167 |
+
response_length: ${data.max_response_length}
|
| 168 |
+
# for vllm rollout
|
| 169 |
+
dtype: bfloat16 # should align with FSDP
|
| 170 |
+
gpu_memory_utilization: 0.5
|
| 171 |
+
ignore_eos: False
|
| 172 |
+
enforce_eager: True
|
| 173 |
+
free_cache_engine: True
|
| 174 |
+
load_format: dummy_dtensor
|
| 175 |
+
tensor_model_parallel_size: 2
|
| 176 |
+
max_num_batched_tokens: 8192
|
| 177 |
+
max_num_seqs: 1024
|
| 178 |
+
log_prob_micro_batch_size: null # will be deprecated, use log_prob_micro_batch_size_per_gpu
|
| 179 |
+
log_prob_micro_batch_size_per_gpu: 16
|
| 180 |
+
log_prob_use_dynamic_bsz: ${actor_rollout_ref.actor.use_dynamic_bsz}
|
| 181 |
+
log_prob_max_token_len_per_gpu: ${actor_rollout_ref.actor.ppo_max_token_len_per_gpu}
|
| 182 |
+
# for hf rollout
|
| 183 |
+
do_sample: True
|
| 184 |
+
engine_kwargs: # inference engine parameters, please refer vllm/sglang official doc for detail
|
| 185 |
+
vllm: {}
|
| 186 |
+
sglang: {}
|
| 187 |
+
|
| 188 |
+
n: 1 # for each prompt, sample n responses (i.e. num sample times). set it to values > 1 for grpo, rloo
|
| 189 |
+
calculate_log_probs: False # set to True for computing log probs via rollouts
|
| 190 |
+
val_kwargs:
|
| 191 |
+
# sampling parameters for validation
|
| 192 |
+
top_k: -1 # 0 for hf rollout, -1 for vllm rollout
|
| 193 |
+
top_p: 1.0
|
| 194 |
+
temperature: 0
|
| 195 |
+
n: 1
|
| 196 |
+
do_sample: False # default eager for validation
|
| 197 |
+
|
| 198 |
+
agent:
|
| 199 |
+
custom_async_server: # Use custom async server implementation for rollout
|
| 200 |
+
path: null
|
| 201 |
+
name: null
|
| 202 |
+
|
| 203 |
+
**Common config for actor, rollout and reference model**
|
| 204 |
+
|
| 205 |
+
- ``actor_rollout_ref.hybrid_engine``: Whether it's a hybrid engine,
|
| 206 |
+
currently only supports hybrid engine
|
| 207 |
+
- ``actor_rollout_ref.model.path``: Huggingface model path. This can be
|
| 208 |
+
either local path or HDFS path. For HDFS path, we provide utils to
|
| 209 |
+
download it to DRAM and convert the HDFS path to local path.
|
| 210 |
+
- ``actor_rollout_ref.model.external_libs``: Additional Python packages
|
| 211 |
+
that need to be imported. Used to register models or tokenizers into
|
| 212 |
+
the Huggingface system.
|
| 213 |
+
- ``actor_rollout_ref.model.override_config``: Used to override some of
|
| 214 |
+
the model's original configurations, mainly dropout
|
| 215 |
+
- ``actor_rollout_ref.model.enable_gradient_checkpointing``: FSDP only, decide
|
| 216 |
+
Whether to enable gradient checkpointing for the actor,
|
| 217 |
+
Megatron uses recompute options in ``override_transformer_config`` to set this
|
| 218 |
+
- ``actor_rollout_ref.model.enable_activation_offload``: Whether to enable
|
| 219 |
+
activation offloading for the actor
|
| 220 |
+
- ``actor_rollout_ref.model.trust_remote_code``: Whether to enable loading
|
| 221 |
+
a remote code model
|
| 222 |
+
- ``actor_rollout_ref.model.use_fused_kernels``: Whether to use fused
|
| 223 |
+
kernels in the model. If set to True, the following parameters will be
|
| 224 |
+
used.
|
| 225 |
+
- ``actor_rollout_ref.model.fused_kernel_options.impl_backend``: The
|
| 226 |
+
implementation backend for fused kernels. Options: "triton" or
|
| 227 |
+
"torch". Default is "torch".
|
| 228 |
+
While in megatron, we only support "triton" as the
|
| 229 |
+
implementation backend, so there is no need for this option.
|
| 230 |
+
- ``actor_rollout_ref.model.use_remove_padding``: Whether to use remove
|
| 231 |
+
padding in the model. If set to True, the model will remove padding
|
| 232 |
+
tokens in the input_ids and response_ids. This helps a lot in improving model running efficiency.
|
| 233 |
+
|
| 234 |
+
**Actor model**
|
| 235 |
+
|
| 236 |
+
- ``actor_rollout_ref.actor.strategy``: fsdp or megatron. In this
|
| 237 |
+
example, we use fsdp backend.
|
| 238 |
+
|
| 239 |
+
- ``actor_rollout_ref.actor.ppo_mini_batch_size``: One sample is split
|
| 240 |
+
into multiple sub-batches with batch_size=ppo_mini_batch_size for PPO
|
| 241 |
+
updates. The ppo_mini_batch_size is a global num across all workers/gpus
|
| 242 |
+
|
| 243 |
+
- ``actor_rollout_ref.actor.ppo_micro_batch_size``: [Will be deprecated, use ppo_micro_batch_size_per_gpu]
|
| 244 |
+
Similar to gradient accumulation, the micro_batch_size_per_gpu for one forward pass,
|
| 245 |
+
trading speed for GPU memory. The value represent the global view.
|
| 246 |
+
|
| 247 |
+
- ``actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu``: Similar to gradient
|
| 248 |
+
accumulation, the micro_batch_size_per_gpu for one forward pass, trading speed
|
| 249 |
+
for GPU memory. The value represent the local num per gpu.
|
| 250 |
+
|
| 251 |
+
- ``actor_rollout_ref.actor.grad_clip``: Gradient clipping for actor
|
| 252 |
+
updates
|
| 253 |
+
- ``actor_rollout_ref.actor.use_kl_loss``: to use kl loss in actor. When used, we are not applying KL in the reward function.
|
| 254 |
+
|
| 255 |
+
- ``actor_rollout_ref.actor.clip_ratio``: PPO clip ratio
|
| 256 |
+
|
| 257 |
+
- ``actor_rollout_ref.actor.use_torch_compile``: Whether to use torch compile in actor
|
| 258 |
+
|
| 259 |
+
- ``actor_rollout_ref.actor.entropy_coeff``: The weight of entropy when
|
| 260 |
+
calculating PPO loss. The default value is changed to 0.0 since v0.3.x
|
| 261 |
+
|
| 262 |
+
- ``actor_rollout_ref.actor.ppo_epochs``: Number of epochs for PPO
|
| 263 |
+
updates on one set of sampled data
|
| 264 |
+
|
| 265 |
+
- ``actor_rollout_ref.actor.data_loader_seed``: From torch 2.6.0 Megatron backend can get wrong seed generated by pytorch
|
| 266 |
+
between cp ranks and cause misalignment between data on these ranks, so we shall manually set the seed to avoid hanging
|
| 267 |
+
issue. if ``actor_rollout_ref.actor.shuffle`` is not null, this must be set.
|
| 268 |
+
|
| 269 |
+
- ``actor_rollout_ref.actor.shuffle``: Whether to shuffle data when
|
| 270 |
+
there are multiple epochs
|
| 271 |
+
|
| 272 |
+
- ``actor_rollout_ref.actor.optim``: Actor's optimizer parameters
|
| 273 |
+
|
| 274 |
+
- ``actor_rollout_ref.actor.fsdp_config``: FSDP config for actor
|
| 275 |
+
training
|
| 276 |
+
|
| 277 |
+
- ``wrap_policy``: FSDP wrap policy. By default, it uses Huggingface's
|
| 278 |
+
wrap policy, i.e., wrapping by DecoderLayer
|
| 279 |
+
|
| 280 |
+
- No need to set transformer_layer_cls_to_wrap, so we comment it.
|
| 281 |
+
|
| 282 |
+
- ``*_offload``: Whether to enable parameter, gradient and optimizer
|
| 283 |
+
offload
|
| 284 |
+
|
| 285 |
+
- Trading speed for GPU memory.
|
| 286 |
+
|
| 287 |
+
- ``actor_rollout_ref.actor.use_kl_loss``: Whether to enable kl loss. Default is False.
|
| 288 |
+
|
| 289 |
+
- ``actor_rollout_ref.actor.kl_loss_coef``: The coefficient of kl loss. Default is 0.001.
|
| 290 |
+
|
| 291 |
+
- ``actor_rollout_ref.actor.kl_loss_type``: Support ``kl`` (``k1``), ``abs``, ``mse`` (``k2``), ``low_var_kl`` (``k3``) and ``full``. Appending ``+`` in the end (e.g., ``k1+`` and ``k3+``) would use straight-through to employ ``k2`` for unbiased gradient estimation, regardless of the kl value estimation (see https://github.com/volcengine/verl/pull/2953#issuecomment-3162113848 for more details). How to calculate the kl divergence between actor and reference policy. For specific options, refer to `kl_penalty()` in `core_algos.py <https://github.com/volcengine/verl/blob/main/verl/trainer/ppo/core_algos.py>`_ . See this blog post for detailed analysis: http://joschu.net/blog/kl-approx.html
|
| 292 |
+
|
| 293 |
+
- ``actor_rollout_ref.actor.checkpoint``: The configurations of checkpoint function in actor
|
| 294 |
+
|
| 295 |
+
- ``save_contents``: The contents to save in the checkpoint. By default, we save model, optimizer and extra information in the checkpoint.
|
| 296 |
+
The extra information includes Rng states currently, FSDP supported lr_scheduler, and Megatron opt_param_scheduler will coming soon.
|
| 297 |
+
We do not store hf_model in checkpoint by default, but we provide a tool in ``scripts/model_merge.py`` to convert checkpoint format to hf format.
|
| 298 |
+
|
| 299 |
+
- ``load_contents``: The contents to load in the checkpoint, you can specify different checkpoint loading contents. By default, it is the same with ``save_checkpoint``.
|
| 300 |
+
|
| 301 |
+
**Reference Model**
|
| 302 |
+
|
| 303 |
+
Reference model will be enabled when ``actor.use_kl_loss`` or/and ``algorithm.use_kl_in_reward`` is/are True.
|
| 304 |
+
|
| 305 |
+
- ``actor_rollout_ref.ref``: FSDP config same as actor. **For models
|
| 306 |
+
larger than 7B, it's recommended to turn on offload for ref by
|
| 307 |
+
default**
|
| 308 |
+
|
| 309 |
+
- ``actor_rollout_ref.ref.log_prob_micro_batch_size``: [Will be deprecate, use log_prob_micro_batch_size_per_gpu]
|
| 310 |
+
The batch size for one forward pass in the computation of ``ref_log_prob``. The value represent the global num.
|
| 311 |
+
|
| 312 |
+
- ``actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu``: The batch size
|
| 313 |
+
for one forward pass in the computation of ``ref_log_prob``. The value represent the local num per gpu.
|
| 314 |
+
|
| 315 |
+
**Rollout Model**
|
| 316 |
+
|
| 317 |
+
- ``actor_rollout_ref.rollout.name``: hf/vllm/sglang.
|
| 318 |
+
|
| 319 |
+
- Rollout (Auto-regressive) parameters. The key should be equal to the
|
| 320 |
+
property name in vLLM's ``SamplingParams``.
|
| 321 |
+
|
| 322 |
+
- ``temperature``, ``top_k``, ``top_p`` and others: Sampling
|
| 323 |
+
parameters in ``SamplingParams``.
|
| 324 |
+
|
| 325 |
+
- ``actor_rollout_ref.rollout.dtype``: Rollout model parameters type. This should be align with
|
| 326 |
+
the actor model parameter type in FSDP/Megatron backend.
|
| 327 |
+
|
| 328 |
+
- ``actor_rollout_ref.rollout.gpu_memory_utilization``:
|
| 329 |
+
|
| 330 |
+
- For vLLM v0.7.0 and later: The fraction of **total** GPU memory to be used for the vLLM instance.
|
| 331 |
+
- For SGLang: Corresponding to ``mem_fraction_static``, the fraction of the free GPU memory used for **static** memory like model weights and KV cache.
|
| 332 |
+
|
| 333 |
+
- ``actor_rollout_ref.rollout.tensor_model_parallel_size``: TP size for rollout. Only effective
|
| 334 |
+
for vllm.
|
| 335 |
+
|
| 336 |
+
- ``actor_rollout_ref.rollout.log_prob_micro_batch_size``: [Will be deprecate, use log_prob_micro_batch_size_per_gpu]
|
| 337 |
+
The batch size for one forward pass in the computation of ``log_prob``. The value represent the global num.
|
| 338 |
+
|
| 339 |
+
- ``actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu``: Micro batch size per gpu (The batch size for
|
| 340 |
+
one forward pass) for recalculating ``log_prob``. The value represent the local num per gpu.
|
| 341 |
+
|
| 342 |
+
- ``actor_rollout_ref.rollout.do_sample``: Whether to sample during training rollout. If set to False, the rollout model
|
| 343 |
+
will perform greedy sampling.
|
| 344 |
+
|
| 345 |
+
- ``actor_rollout_ref.rollout.val_kwargs```: Sampling parameters used specifically during validation.
|
| 346 |
+
|
| 347 |
+
- ``top_k``: Top-k sampling parameter. Default to -1 for vLLM rollout or 0 for HF rollout.
|
| 348 |
+
- ``top_p``: Top-p sampling parameter. Default is 1.0 (disabled).
|
| 349 |
+
- ``temperature``: Sampling temperature. Default is 0 (deterministic greedy).
|
| 350 |
+
- ``n``: Number of responses to generate during validation. Default is 1.
|
| 351 |
+
- ``do_sample``: Whether to use sampling during validation. Default is False for
|
| 352 |
+
deterministic outputs. When set to True, the rollout will use the ``actor_rollout_ref.rollout.val_kwargs`` parameters
|
| 353 |
+
(top_k, top_p, temperature) to control the sampling behavior.
|
| 354 |
+
|
| 355 |
+
- ``actor_rollout_ref.rollout.engine_kwargs.vllm``: extra vllm engine args, please refer vllm official doc for detail
|
| 356 |
+
|
| 357 |
+
- ``actor_rollout_ref.rollout.engine_kwargs.sglang``: extra sglang engine args, please refer sglang official doc for detail
|
| 358 |
+
|
| 359 |
+
- ``actor_rollout_ref.rollout.ignore_eos``: Whether to ignore the EOS
|
| 360 |
+
token and continue generating tokens after the EOS token is generated.
|
| 361 |
+
|
| 362 |
+
- ``actor_rollout_ref.rollout.free_cache_engine``: Offload the KVCache
|
| 363 |
+
after rollout generation stage. Default is True. When set to True,
|
| 364 |
+
for vllm v0.5.4 and v0.6.3, we need to disable the usage of CUDAGraph
|
| 365 |
+
(set ``enforce_eager`` to True.)
|
| 366 |
+
|
| 367 |
+
- ``actor_rollout_ref.rollout.enforce_eager``: Whether to use CUDAGraph
|
| 368 |
+
in vLLM generation. Default set to True to disable CUDAGraph.
|
| 369 |
+
|
| 370 |
+
- ``actor_rollout_ref.rollout.load_format``: Which weight loader to use
|
| 371 |
+
to load the actor model weights to the rollout model.
|
| 372 |
+
|
| 373 |
+
- ``auto``: Use Megatron weight loader.
|
| 374 |
+
- ``megatron``: Use Megatron weight loader. Deployed with Megatron
|
| 375 |
+
backend. The input model ``state_dict()`` is already partitioned
|
| 376 |
+
along TP dimension and already gathered along PP dimension. This
|
| 377 |
+
weight loader requires that the Rollout model and Actor model's
|
| 378 |
+
parameters shape and name should be identical.
|
| 379 |
+
- ``dtensor``: Default solution when using Huggingface weight loader.
|
| 380 |
+
Deployed with FSDP backend and the state_dict_type is
|
| 381 |
+
``StateDictType.SHARDED_STATE_DICT``. Recommend to use this weight
|
| 382 |
+
loader
|
| 383 |
+
- ``hf``: Use Huggingface weight loader. Deployed with FSDP backend
|
| 384 |
+
and the state_dict_type is ``StateDictType.FULL_STATE_DICT``. This
|
| 385 |
+
solution doesn't need to rewrite the weight loader for each model
|
| 386 |
+
implemented in vLLM but it results in larger peak memory usage.
|
| 387 |
+
- ``dummy_hf``, ``dummy_megatron``, ``dummy_dtensor``: Random
|
| 388 |
+
initialization.
|
| 389 |
+
|
| 390 |
+
.. note:: **NOTED**: In this config field, users only need to select from ``dummy_megatron``, ``dummy_dtensor``, ``dummy_hf`` for rollout initialization and our hybrid engine will select the corresponding weight loader (i.e., ``megatron``, ``dtensor``, ``hf``) during actor/rollout weight synchronization.
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
Megatron Optimizer and Optimizer Parameter Scheduler
|
| 394 |
+
____________________________________________________
|
| 395 |
+
|
| 396 |
+
.. code:: yaml
|
| 397 |
+
|
| 398 |
+
optim:
|
| 399 |
+
optimizer: adam
|
| 400 |
+
lr: 1e-6
|
| 401 |
+
clip_grad: 1.0
|
| 402 |
+
total_training_steps: -1 # must be override by program
|
| 403 |
+
lr_warmup_init: 0.0 # initial learning rate for warmup, default to 0.0
|
| 404 |
+
lr_warmup_steps: -1 # Prioritized. Negative values mean delegating to lr_warmup_steps_ratio.
|
| 405 |
+
lr_warmup_steps_ratio: 0. # the total steps will be injected during runtime
|
| 406 |
+
lr_decay_steps: null
|
| 407 |
+
lr_decay_style: constant # select from constant/linear/cosine/inverse_square_root
|
| 408 |
+
min_lr: 0.0 # minimum learning rate, default to 0.0
|
| 409 |
+
weight_decay: 0.01
|
| 410 |
+
weight_decay_incr_style: constant # select from constant/linear/cosine
|
| 411 |
+
lr_wsd_decay_style: exponential # select from constant/exponential/cosine
|
| 412 |
+
lr_wsd_decay_steps: null
|
| 413 |
+
use_checkpoint_opt_param_scheduler: False # use checkpoint optimizer parameter scheduler
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
Notice that there are some differences in APIs between Megatron optimizer and FSDP optimizer.
|
| 417 |
+
|
| 418 |
+
- Megatron optimizer scheduler names the period after lr_warmup as lr_decay_steps, so the ``warmup_style`` actually means the style of lr decay after warmup.
|
| 419 |
+
- Megatron optimizer also support weight decay decay mechanism
|
| 420 |
+
- ``use_checkpoint_opt_param_scheduler`` determines whether to use the checkpoint optimizer parameter scheduler. If set to True, the optimizer parameter scheduler will be saved in the checkpoint and loaded from the checkpoint during resuming training.
|
| 421 |
+
|
| 422 |
+
For learning rate decay, original Megatron pretrain default option of ``lr_decay_style`` is ``linear``,
|
| 423 |
+
meaning that the learning rate will be linearly decayed from the initial learning rate to ``min_lr`` within the
|
| 424 |
+
``lr_decay_steps``. However, in verl, to align with FSDP's default behavior, we set the default
|
| 425 |
+
``lr_decay_style`` to ``constant``, meaning that the learning rate will be kept constant after the warmup stage.
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
Critic Model
|
| 429 |
+
~~~~~~~~~~~~
|
| 430 |
+
|
| 431 |
+
Most parameters for Critic are similar to Actor Model.
|
| 432 |
+
|
| 433 |
+
Reward Model
|
| 434 |
+
~~~~~~~~~~~~
|
| 435 |
+
|
| 436 |
+
.. code:: yaml
|
| 437 |
+
|
| 438 |
+
reward_model:
|
| 439 |
+
enable: False
|
| 440 |
+
model:
|
| 441 |
+
input_tokenizer: ${actor_rollout_ref.model.path} # set this to null if the chat template is identical
|
| 442 |
+
path: ~/models/Anomy-RM-v0.1
|
| 443 |
+
external_lib: ${actor_rollout_ref.model.external_lib}
|
| 444 |
+
trust_remote_code: False
|
| 445 |
+
fsdp_config:
|
| 446 |
+
min_num_params: 0
|
| 447 |
+
param_offload: False
|
| 448 |
+
micro_batch_size_per_gpu: 16
|
| 449 |
+
max_length: null
|
| 450 |
+
reward_manager: naive
|
| 451 |
+
|
| 452 |
+
- ``reward_model.enable``: Whether to enable reward model. If False, we
|
| 453 |
+
compute the reward only with the user-defined reward functions. In
|
| 454 |
+
GSM8K and Math examples, we disable reward model. For RLHF alignment
|
| 455 |
+
example using full_hh_rlhf, we utilize reward model to assess the
|
| 456 |
+
responses. If False, the following parameters are not effective.
|
| 457 |
+
- ``reward_model.model``
|
| 458 |
+
|
| 459 |
+
- ``input_tokenizer``: Input tokenizer. If the reward model's chat
|
| 460 |
+
template is inconsistent with the policy, we need to first decode to
|
| 461 |
+
plaintext, then apply the rm's chat_template. Then score with RM. If
|
| 462 |
+
chat_templates are consistent, it can be set to null.
|
| 463 |
+
- ``path``: RM's HDFS path or local path. Note that RM only supports
|
| 464 |
+
AutoModelForSequenceClassification. Other model types need to define
|
| 465 |
+
their own RewardModelWorker and pass it from the code.
|
| 466 |
+
- ``trust_remote_code``: Whether to enable loading a remote code model,
|
| 467 |
+
default to False.
|
| 468 |
+
- ``reward_model.reward_manager``: Reward Manager. This defines the mechanism
|
| 469 |
+
of computing rule-based reward and handling different reward sources. Default
|
| 470 |
+
is ``naive``. If all verification functions are multiprocessing-safe, the reward
|
| 471 |
+
manager can be set to ``prime`` for parallel verification.
|
| 472 |
+
|
| 473 |
+
Customized Reward Function
|
| 474 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 475 |
+
|
| 476 |
+
.. code:: yaml
|
| 477 |
+
|
| 478 |
+
custom_reward_function:
|
| 479 |
+
path: null
|
| 480 |
+
name: compute_score
|
| 481 |
+
|
| 482 |
+
- ``custom_reward_function.path``: The path to the file containing your customized reward function. If not specified, pre-implemented reward functions will be used.
|
| 483 |
+
- ``custom_reward_function.name`` (Optional) : The name of the reward function within the specified file. Default is 'compute_score'.
|
| 484 |
+
|
| 485 |
+
Algorithm
|
| 486 |
+
~~~~~~~~~
|
| 487 |
+
|
| 488 |
+
.. code:: yaml
|
| 489 |
+
|
| 490 |
+
algorithm:
|
| 491 |
+
gamma: 1.0
|
| 492 |
+
lam: 1.0
|
| 493 |
+
adv_estimator: gae
|
| 494 |
+
use_kl_in_reward: False
|
| 495 |
+
kl_penalty: kl # how to estimate kl divergence
|
| 496 |
+
kl_ctrl:
|
| 497 |
+
type: fixed
|
| 498 |
+
kl_coef: 0.005
|
| 499 |
+
horizon: 10000
|
| 500 |
+
target_kl: 0.1
|
| 501 |
+
|
| 502 |
+
- ``gamma``: discount factor
|
| 503 |
+
- ``lam``: Trade-off between bias and variance in the GAE estimator
|
| 504 |
+
- ``adv_estimator``: Support ``gae``, ``grpo``, ``reinforce_plus_plus``, ``reinforce_plus_plus_baseline``, ``rloo``, ``rloo_vectorized``, ``grpo_vectorized``
|
| 505 |
+
- ``use_kl_in_reward``: Whether to enable in-reward kl penalty. Default is False.
|
| 506 |
+
- ``kl_penalty``: Support ``kl``, ``abs``, ``mse``, ``low_var_kl`` and ``full``. How to
|
| 507 |
+
calculate the kl divergence between actor and reference policy. For
|
| 508 |
+
specific options, refer to `kl_penalty()` in `core_algos.py <https://github.com/volcengine/verl/blob/main/verl/trainer/ppo/core_algos.py>`_ .
|
| 509 |
+
- ``kl_ctrl``: Config for in-reward kl_penalty controller
|
| 510 |
+
- ``kl_coef``: The (initial) coefficient of in-reward kl_penalty. Default is 0.001.
|
| 511 |
+
- ``type``: 'fixed' for FixedKLController and 'adaptive' for AdaptiveKLController.
|
| 512 |
+
- ``horizon`` and ``target_kl``: See source code of AdaptiveKLController for details.
|
| 513 |
+
|
| 514 |
+
Trainer
|
| 515 |
+
~~~~~~~
|
| 516 |
+
|
| 517 |
+
.. code:: yaml
|
| 518 |
+
|
| 519 |
+
trainer:
|
| 520 |
+
total_epochs: 30
|
| 521 |
+
project_name: verl_examples
|
| 522 |
+
experiment_name: gsm8k
|
| 523 |
+
logger: ['console', 'wandb']
|
| 524 |
+
log_val_generations: 0
|
| 525 |
+
nnodes: 1
|
| 526 |
+
n_gpus_per_node: 8
|
| 527 |
+
save_freq: -1
|
| 528 |
+
val_before_train: True
|
| 529 |
+
test_freq: 2
|
| 530 |
+
critic_warmup: 0
|
| 531 |
+
default_hdfs_dir: null # hdfs checkpoint path
|
| 532 |
+
default_local_dir: checkpoints/${trainer.project_name}/${trainer.experiment_name} # local checkpoint path
|
| 533 |
+
resume_mode: auto # or disable or resume_path if resume_from_path is set
|
| 534 |
+
resume_from_path: null
|
| 535 |
+
remove_previous_ckpt_in_save: False
|
| 536 |
+
del_local_ckpt_after_load: False
|
| 537 |
+
ray_wait_register_center_timeout: 300
|
| 538 |
+
|
| 539 |
+
- ``trainer.total_epochs``: Number of epochs in training.
|
| 540 |
+
- ``trainer.project_name``: For wandb, swanlab, mlflow
|
| 541 |
+
- ``trainer.experiment_name``: For wandb, swanlab, mlflow
|
| 542 |
+
- ``trainer.logger``: Support console and wandb, swanlab, mlflow, tensorboard, trackio
|
| 543 |
+
- ``trainer.log_val_generations``: The number of logged generation during validation (default ``0``)
|
| 544 |
+
- ``trainer.nnodes``: Number of nodes used in the training.
|
| 545 |
+
- ``trainer.n_gpus_per_node``: Number of GPUs per node.
|
| 546 |
+
- ``trainer.save_freq``: The frequency (by iteration) to save checkpoint
|
| 547 |
+
of the actor and critic model.
|
| 548 |
+
- ``trainer.val_before_train``: Whether to run validation before training.
|
| 549 |
+
- ``trainer.test_freq``: The validation frequency (by iteration).
|
| 550 |
+
- ``trainer.critic_warmup``: The number of iteration to train the critic
|
| 551 |
+
model before actual policy learning.
|
| 552 |
+
- ``trainer.resume_mode``: The mode of resuming training. Support
|
| 553 |
+
``disable``, ``auto`` and ``resume_path``. If set to ``auto`` as default, the
|
| 554 |
+
program will automatically resume from the latest checkpoint in the
|
| 555 |
+
``default_local_dir``. If set to ``resume_path``, the program will resume
|
| 556 |
+
from the path specified in ``resume_from_path``.
|
| 557 |
+
- ``trainer.resume_from_path``: The path to resume training from. Only
|
| 558 |
+
effective when ``resume_mode`` is set to ``resume_path``.
|
| 559 |
+
- ``trainer.remove_previous_ckpt_in_save``: Whether to remove previous
|
| 560 |
+
checkpoints in the save directory. Default is False.
|
| 561 |
+
- ``trainer.del_local_ckpt_after_load``: Whether to delete local
|
| 562 |
+
checkpoints after loading them. Default is False.
|
| 563 |
+
- ``trainer.ray_wait_register_center_timeout``: The timeout for waiting
|
| 564 |
+
for the ray register center to be ready. Default is 300 seconds.
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
This figure illustrates how the configurations affect the training.
|
| 568 |
+
|
| 569 |
+
https://excalidraw.com/#json=pfhkRmiLm1jnnRli9VFhb,Ut4E8peALlgAUpr7E5pPCA
|
| 570 |
+
|
| 571 |
+
.. image:: https://github.com/user-attachments/assets/16aebad1-0da6-4eb3-806d-54a74e712c2d
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
evaluation.yaml
|
| 575 |
+
---------------
|
| 576 |
+
|
| 577 |
+
Data
|
| 578 |
+
~~~~
|
| 579 |
+
|
| 580 |
+
.. code:: yaml
|
| 581 |
+
|
| 582 |
+
data:
|
| 583 |
+
path: /tmp/math_Qwen2-7B-Instruct.parquet
|
| 584 |
+
prompt_key: prompt
|
| 585 |
+
response_key: responses
|
| 586 |
+
data_source_key: data_source
|
| 587 |
+
reward_model_key: reward_model
|
| 588 |
+
|
| 589 |
+
- ``data.path``: Path to the dataset file (Parquet format).
|
| 590 |
+
- ``data.prompt_key``: The field in the dataset where the prompt is located. Default is 'prompt'.
|
| 591 |
+
- ``data.response_key``: The key holds the generated responses. This should be a list of strings representing the responses. Default is 'responses'.
|
| 592 |
+
- ``data.data_source_key``: This is used to separate metric calculations for different data sources, ensuring that metrics are calculated independently for each source.
|
| 593 |
+
- ``data.reward_model_key``: The key holds the reference answers. These reference answers typically serve as the ground truth or test cases for the task.
|
| 594 |
+
|
| 595 |
+
Customized Reward Function
|
| 596 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 597 |
+
|
| 598 |
+
.. code:: yaml
|
| 599 |
+
|
| 600 |
+
custom_reward_function:
|
| 601 |
+
path: null
|
| 602 |
+
name: compute_score
|
| 603 |
+
|
| 604 |
+
- ``custom_reward_function.path``: The path to the file containing your customized reward function. If not specified, pre-implemented reward functions will be used.
|
| 605 |
+
- ``custom_reward_function.name`` (Optional) : The name of the reward function within the specified file. Default is 'compute_score'.
|
| 606 |
+
|
| 607 |
+
sft_trainer.yaml for SFT FSDP Backend
|
| 608 |
+
--------------------------------------
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
Optim
|
| 612 |
+
~~~~~~~
|
| 613 |
+
|
| 614 |
+
.. code:: yaml
|
| 615 |
+
|
| 616 |
+
optim:
|
| 617 |
+
lr: 1e-5
|
| 618 |
+
weight_decay: 0.01
|
| 619 |
+
warmup_steps_ratio: 0.1
|
| 620 |
+
clip_grad: 1.0
|
| 621 |
+
lr_scheduler: cosine
|
| 622 |
+
|
| 623 |
+
- ``optim.lr``: Learning rate for the optimizer.
|
| 624 |
+
- ``optim.weight_decay``: Weight decay for the optimizer.
|
| 625 |
+
- ``optim.warmup_steps_ratio``: Ratio of warmup steps to total training steps.
|
| 626 |
+
- ``optim.clip_grad``: Gradient clipping value.
|
| 627 |
+
- ``optim.lr_scheduler``: Learning rate scheduler type. Options:
|
| 628 |
+
|
| 629 |
+
- ``cosine``: Cosine learning rate scheduler with warmup (default).
|
| 630 |
+
- ``wsd``: Warmup-Stable-Decay scheduler that provides a stable learning rate phase between warmup and decay phases.
|
| 631 |
+
|
| 632 |
+
Model
|
| 633 |
+
~~~~~~~~~~~~
|
| 634 |
+
|
| 635 |
+
Most parameters for Model are similar to Reward Model.
|
| 636 |
+
|
| 637 |
+
.. code:: yaml
|
| 638 |
+
|
| 639 |
+
model:
|
| 640 |
+
partial_pretrain: ~/models/gemma-1.1-7b-it
|
| 641 |
+
fsdp_config:
|
| 642 |
+
model_dtype: fp32
|
| 643 |
+
wrap_policy:
|
| 644 |
+
min_num_params: 0
|
| 645 |
+
cpu_offload: False
|
| 646 |
+
offload_params: False
|
| 647 |
+
external_lib: null
|
| 648 |
+
enable_gradient_checkpointing: False
|
| 649 |
+
trust_remote_code: False
|
| 650 |
+
lora_rank: 0
|
| 651 |
+
lora_alpha: 16
|
| 652 |
+
target_modules: all-linear
|
| 653 |
+
use_liger: False
|
| 654 |
+
|
| 655 |
+
- ``partial_pretrain``: HDFS path or local path for the pretrained model.
|
| 656 |
+
- ``fsdp_config``
|
| 657 |
+
|
| 658 |
+
- ``model_dtype``: Model parameters type, default to ``fp32``.
|
| 659 |
+
Support: ``bf16``, ``fp16``, ``fp32``.
|
| 660 |
+
- ``cpu_offload``: Whether to enable CPU offloading for FSDP. If True,
|
| 661 |
+
the offload_params will be used as argument.
|
| 662 |
+
- ``offload_params``: Whether to offload parameters to CPU
|
| 663 |
+
when not involved in computation. If True, then this offloads gradients
|
| 664 |
+
to CPU as well, meaning that the optimizer step runs on CPU.
|
| 665 |
+
|
| 666 |
+
- ``lora_rank``: The rank of the LoRA model, default to 0. If ``lora_rank``>0,
|
| 667 |
+
we will train LoRA modules instead of tuning the full model.
|
| 668 |
+
- ``lora_alpha``: The alpha parameter for LoRA scaling, default to 16.
|
| 669 |
+
- ``target_modules``: The names of the modules to apply the adapter to,
|
| 670 |
+
default to ``all-linear``. See `peft docs <https://huggingface.co/docs/peft/v0.15.0/en/package_reference/lora#peft.LoraConfig.target_modules>`_ for detail.
|
| 671 |
+
|
| 672 |
+
- ``use_liger``: Whether to enable Liger kernel, default to False. If True,
|
| 673 |
+
we apply Liger kernel to the model (depends on `liger-kernel`).
|
verl/docs/examples/gsm8k_example.rst
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GSM8K Example
|
| 2 |
+
=============
|
| 3 |
+
|
| 4 |
+
Last updated: 03/25/2025.
|
| 5 |
+
|
| 6 |
+
Introduction
|
| 7 |
+
------------
|
| 8 |
+
|
| 9 |
+
In this example, we train an LLM to tackle the GSM8k task.
|
| 10 |
+
|
| 11 |
+
Paper: https://arxiv.org/pdf/2110.14168
|
| 12 |
+
|
| 13 |
+
Dataset: https://huggingface.co/datasets/gsm8k
|
| 14 |
+
|
| 15 |
+
Note that the original paper mainly focuses on training a verifier (a
|
| 16 |
+
reward model) to solve math problems via Best-of-N sampling. In this
|
| 17 |
+
example, we train an RLHF agent using a rule-based reward model.
|
| 18 |
+
|
| 19 |
+
Dataset Introduction
|
| 20 |
+
--------------------
|
| 21 |
+
|
| 22 |
+
GSM8k is a math problem dataset. The prompt is an elementary school
|
| 23 |
+
problem. The LLM model is required to answer the math problem.
|
| 24 |
+
|
| 25 |
+
The training set contains 7473 samples and the test set contains 1319
|
| 26 |
+
samples.
|
| 27 |
+
|
| 28 |
+
**An example**
|
| 29 |
+
|
| 30 |
+
Prompt
|
| 31 |
+
|
| 32 |
+
Katy makes coffee using teaspoons of sugar and cups of water in the
|
| 33 |
+
ratio of 7:13. If she used a total of 120 teaspoons of sugar and cups
|
| 34 |
+
of water, calculate the number of teaspoonfuls of sugar she used.
|
| 35 |
+
|
| 36 |
+
Solution
|
| 37 |
+
|
| 38 |
+
The total ratio representing the ingredients she used to make the
|
| 39 |
+
coffee is 7+13 = <<7+13=20>>20 Since the fraction representing the
|
| 40 |
+
number of teaspoons she used is 7/20, she used 7/20\ *120 =
|
| 41 |
+
<<7/20*\ 120=42>>42 #### 42
|
| 42 |
+
|
| 43 |
+
Step 1: Prepare dataset
|
| 44 |
+
-----------------------
|
| 45 |
+
|
| 46 |
+
.. code:: bash
|
| 47 |
+
|
| 48 |
+
cd examples/data_preprocess
|
| 49 |
+
python3 gsm8k.py --local_save_dir ~/data/gsm8k
|
| 50 |
+
|
| 51 |
+
Step 2: Download Model
|
| 52 |
+
----------------------
|
| 53 |
+
|
| 54 |
+
There're three ways to prepare the model checkpoints for post-training:
|
| 55 |
+
|
| 56 |
+
- Download the required models from huggingface or modelscope
|
| 57 |
+
|
| 58 |
+
.. code:: bash
|
| 59 |
+
|
| 60 |
+
huggingface-cli download deepseek-ai/deepseek-math-7b-instruct --local-dir ~/models/deepseek-math-7b-instruct --local-dir-use-symlinks False
|
| 61 |
+
# or
|
| 62 |
+
modelscope download --model deepseek-ai/deepseek-math-7b-instruct --local_dir ~/models/deepseek-math-7b-instruct
|
| 63 |
+
|
| 64 |
+
- Already store your store model in the local directory or HDFS path.
|
| 65 |
+
- Also, you can directly use the model name in huggingface (e.g.,
|
| 66 |
+
deepseek-ai/deepseek-math-7b-instruct) in
|
| 67 |
+
``actor_rollout_ref.model.path`` and ``critic.model.path`` field in
|
| 68 |
+
the run script. You can also download models from modelscope by setting environmental variable ``VERL_USE_MODELSCOPE=True``.
|
| 69 |
+
See examples/ppo_trainer/run_deepseek7b_llm_modelscope.sh for example.
|
| 70 |
+
|
| 71 |
+
Noted that users should prepare checkpoints for actor, critic and reward
|
| 72 |
+
model.
|
| 73 |
+
|
| 74 |
+
[Optional] Step 3: SFT your Model
|
| 75 |
+
---------------------------------
|
| 76 |
+
|
| 77 |
+
We provide a SFT Trainer using PyTorch FSDP in
|
| 78 |
+
`fsdp_sft_trainer.py <https://github.com/volcengine/verl/blob/main/verl/trainer/fsdp_sft_trainer.py>`_.
|
| 79 |
+
Users can customize their own SFT
|
| 80 |
+
script using our FSDP SFT Trainer.
|
| 81 |
+
|
| 82 |
+
We also provide various training scripts for SFT on GSM8K dataset in `gsm8k sft directory <https://github.com/volcengine/verl/blob/main/examples/sft/gsm8k/>`_.
|
| 83 |
+
|
| 84 |
+
.. code:: shell
|
| 85 |
+
|
| 86 |
+
set -x
|
| 87 |
+
|
| 88 |
+
torchrun -m verl.trainer.fsdp_sft_trainer \
|
| 89 |
+
data.train_files=$HOME/data/gsm8k/train.parquet \
|
| 90 |
+
data.val_files=$HOME/data/gsm8k/test.parquet \
|
| 91 |
+
data.prompt_key=question \
|
| 92 |
+
data.response_key=answer \
|
| 93 |
+
data.micro_batch_size_per_gpu=8 \
|
| 94 |
+
model.partial_pretrain=deepseek-ai/deepseek-coder-6.7b-instruct \
|
| 95 |
+
trainer.project_name=gsm8k-sft \
|
| 96 |
+
trainer.experiment_name=gsm8k-sft-deepseek-coder-6.7b-instruct \
|
| 97 |
+
trainer.total_epochs=4 \
|
| 98 |
+
trainer.logger='["console","wandb"]'
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
If you use AMD GPUs (ROCm kernel), you need to add the following environment variables into the run script:
|
| 102 |
+
|
| 103 |
+
.. code-block:: bash
|
| 104 |
+
|
| 105 |
+
export HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
|
| 106 |
+
export ROCR_VISIBLE_DEVICES=$HIP_VISIBLE_DEVICES
|
| 107 |
+
export CUDA_VISIBLE_DEVICES=$HIP_VISIBLE_DEVICES
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
Step 4: Perform PPO training with your model on GSM8K Dataset
|
| 111 |
+
-------------------------------------------------------------
|
| 112 |
+
|
| 113 |
+
- Prepare your own run.sh script. Here's an example for GSM8k dataset
|
| 114 |
+
and deepseek-llm-7b-chat model.
|
| 115 |
+
- Users could replace the ``data.train_files`` ,\ ``data.val_files``,
|
| 116 |
+
``actor_rollout_ref.model.path`` and ``critic.model.path`` based on
|
| 117 |
+
their environment.
|
| 118 |
+
- See :doc:`config` for detailed explanation of each config field.
|
| 119 |
+
|
| 120 |
+
**Reward Model/Function**
|
| 121 |
+
|
| 122 |
+
We use a rule-based reward model. We force the model to produce a final
|
| 123 |
+
answer following 4 “#” as shown in the solution. We extract the final
|
| 124 |
+
answer from both the solution and model's output using regular
|
| 125 |
+
expression matching. We compare them and assign a reward of 1 to correct
|
| 126 |
+
answer, 0.1 to incorrect answer and 0 to no answer.
|
| 127 |
+
|
| 128 |
+
**Training Script**
|
| 129 |
+
|
| 130 |
+
The training script example for FSDP and Megatron-LM backend are stored in examples/ppo_trainer directory.
|
| 131 |
+
|
| 132 |
+
.. code:: bash
|
| 133 |
+
|
| 134 |
+
cd ../ppo_trainer
|
| 135 |
+
bash run_deepseek7b_llm.sh
|
| 136 |
+
|
| 137 |
+
The script of run_deepseek7b_llm.sh
|
| 138 |
+
|
| 139 |
+
.. code:: bash
|
| 140 |
+
|
| 141 |
+
set -x
|
| 142 |
+
|
| 143 |
+
python3 -m verl.trainer.main_ppo \
|
| 144 |
+
data.train_files=$HOME/data/gsm8k/train.parquet \
|
| 145 |
+
data.val_files=$HOME/data/gsm8k/test.parquet \
|
| 146 |
+
data.train_batch_size=1024 \
|
| 147 |
+
data.max_prompt_length=512 \
|
| 148 |
+
data.max_response_length=512 \
|
| 149 |
+
actor_rollout_ref.model.path=deepseek-ai/deepseek-llm-7b-chat \
|
| 150 |
+
actor_rollout_ref.actor.optim.lr=1e-6 \
|
| 151 |
+
actor_rollout_ref.model.use_remove_padding=True \
|
| 152 |
+
actor_rollout_ref.actor.ppo_mini_batch_size=256 \
|
| 153 |
+
actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=16 \
|
| 154 |
+
actor_rollout_ref.actor.fsdp_config.param_offload=False \
|
| 155 |
+
actor_rollout_ref.actor.fsdp_config.optimizer_offload=False \
|
| 156 |
+
actor_rollout_ref.model.enable_gradient_checkpointing=True \
|
| 157 |
+
actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=32 \
|
| 158 |
+
actor_rollout_ref.rollout.tensor_model_parallel_size=4 \
|
| 159 |
+
actor_rollout_ref.rollout.name=vllm \
|
| 160 |
+
actor_rollout_ref.rollout.gpu_memory_utilization=0.5 \
|
| 161 |
+
actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=32 \
|
| 162 |
+
actor_rollout_ref.ref.fsdp_config.param_offload=True \
|
| 163 |
+
critic.optim.lr=1e-5 \
|
| 164 |
+
critic.model.use_remove_padding=True \
|
| 165 |
+
critic.model.path=deepseek-ai/deepseek-llm-7b-chat \
|
| 166 |
+
critic.model.enable_gradient_checkpointing=True \
|
| 167 |
+
critic.ppo_micro_batch_size_per_gpu=32 \
|
| 168 |
+
critic.model.fsdp_config.param_offload=False \
|
| 169 |
+
critic.model.fsdp_config.optimizer_offload=False \
|
| 170 |
+
algorithm.kl_ctrl.kl_coef=0.001 \
|
| 171 |
+
trainer.critic_warmup=0 \
|
| 172 |
+
trainer.logger='["console","wandb"]' \
|
| 173 |
+
trainer.project_name='verl_example_gsm8k' \
|
| 174 |
+
trainer.experiment_name='deepseek_llm_7b_function_rm' \
|
| 175 |
+
trainer.n_gpus_per_node=8 \
|
| 176 |
+
trainer.nnodes=1 \
|
| 177 |
+
trainer.save_freq=-1 \
|
| 178 |
+
trainer.test_freq=1 \
|
| 179 |
+
trainer.total_epochs=15 $@
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
If you use AMD GPUs (ROCm kernel), you need to add the following environment variables into the run script:
|
| 183 |
+
|
| 184 |
+
.. code-block:: bash
|
| 185 |
+
|
| 186 |
+
export HIP_VISIBLE_DEVICES=0,1,2,3,4,5,6,7
|
| 187 |
+
export ROCR_VISIBLE_DEVICES=$HIP_VISIBLE_DEVICES
|
| 188 |
+
export CUDA_VISIBLE_DEVICES=$HIP_VISIBLE_DEVICES
|
| 189 |
+
|
| 190 |
+
If you encounter any issues in using AMD GPUs running VeRL, feel free to contact me - `Yusheng Su <https://yushengsu-thu.github.io/>`_.
|
verl/docs/examples/multi_modal_example.rst
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Multi-Modal Example Architecture
|
| 2 |
+
=================================
|
| 3 |
+
|
| 4 |
+
Last updated: 04/28/2025.
|
| 5 |
+
|
| 6 |
+
Introduction
|
| 7 |
+
------------
|
| 8 |
+
|
| 9 |
+
Now, verl has supported multi-modal training. You can use fsdp and
|
| 10 |
+
vllm/sglang to start a multi-modal RL task. Megatron supports is also
|
| 11 |
+
on the way.
|
| 12 |
+
|
| 13 |
+
Follow the steps below to quickly start a multi-modal RL task.
|
| 14 |
+
|
| 15 |
+
Step 1: Prepare dataset
|
| 16 |
+
-----------------------
|
| 17 |
+
|
| 18 |
+
.. code:: python
|
| 19 |
+
|
| 20 |
+
# it will be saved in the $HOME/data/geo3k folder
|
| 21 |
+
python examples/data_preprocess/geo3k.py
|
| 22 |
+
|
| 23 |
+
Step 2: Download Model
|
| 24 |
+
----------------------
|
| 25 |
+
|
| 26 |
+
.. code:: bash
|
| 27 |
+
|
| 28 |
+
# download the model from huggingface
|
| 29 |
+
python3 -c "import transformers; transformers.pipeline(model='Qwen/Qwen2.5-VL-7B-Instruct')"
|
| 30 |
+
|
| 31 |
+
Step 3: Perform GRPO training with multi-modal model on Geo3K Dataset
|
| 32 |
+
---------------------------------------------------------------------
|
| 33 |
+
|
| 34 |
+
.. code:: bash
|
| 35 |
+
|
| 36 |
+
# run the task
|
| 37 |
+
bash examples/grpo_trainer/run_qwen2_5_vl-7b.sh
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
verl/docs/examples/ppo_code_architecture.rst
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PPO Example Architecture
|
| 2 |
+
========================
|
| 3 |
+
|
| 4 |
+
Last updated: 02/17/2025.
|
| 5 |
+
|
| 6 |
+
Let's start with the Proximal Policy Optimization algorithm, which is
|
| 7 |
+
most widely used algorithm in LLM post-training.
|
| 8 |
+
|
| 9 |
+
The main entry point of the PPO algorithm example is:
|
| 10 |
+
`main_ppo.py <https://github.com/volcengine/verl/blob/main/verl/trainer/main_ppo.py>`_.
|
| 11 |
+
In this tutorial, we will go through the code architecture in `main_ppo.py <https://github.com/volcengine/verl/blob/main/verl/trainer/main_ppo.py>`_.
|
| 12 |
+
|
| 13 |
+
Define the data
|
| 14 |
+
---------------
|
| 15 |
+
|
| 16 |
+
Users need to preprocess and store the dataset in parquet files.
|
| 17 |
+
And we implement `RLHFDataset` to load and tokenize the parquet files.
|
| 18 |
+
|
| 19 |
+
For ``RLHFDataset`` (Default), at least 1 fields are required:
|
| 20 |
+
|
| 21 |
+
- ``prompt``: Contains the string prompt
|
| 22 |
+
|
| 23 |
+
We already provide some examples of processing the datasets to parquet
|
| 24 |
+
files in `data_preprocess directory <https://github.com/volcengine/verl/blob/main/examples/data_preprocess>`_. Currently, we support
|
| 25 |
+
preprocess of GSM8k, MATH, Hellasage, Full_hh_rlhf datasets. See :doc:`../preparation/prepare_data` for
|
| 26 |
+
more information.
|
| 27 |
+
|
| 28 |
+
Define the reward functions for different datasets
|
| 29 |
+
--------------------------------------------------
|
| 30 |
+
|
| 31 |
+
In this main entry point, the users only need to define their own reward
|
| 32 |
+
function based on the datasets (or applications) utilized in PPO
|
| 33 |
+
training.
|
| 34 |
+
|
| 35 |
+
For example, we already provide reward functions for `GSM8k <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score/gsm8k.py>`_
|
| 36 |
+
and `MATH <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score/math.py>`_
|
| 37 |
+
datasets in the ``_select_rm_score_fn``. In the ``RewardManager``, we
|
| 38 |
+
will compute the reward score based on the data_source to select
|
| 39 |
+
corresponding reward functions. For some RLHF datasets (e.g.,
|
| 40 |
+
full_hh_rlhf), the reward model is utilized to assess the responses
|
| 41 |
+
without any reward functions. In this case, the ``RewardManager`` will
|
| 42 |
+
return the ``rm_score`` computed by the reward model directly.
|
| 43 |
+
|
| 44 |
+
See `reward functions <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score>`_ for detailed implementation.
|
| 45 |
+
|
| 46 |
+
Define worker classes
|
| 47 |
+
---------------------
|
| 48 |
+
|
| 49 |
+
.. code:: python
|
| 50 |
+
|
| 51 |
+
if config.actor_rollout_ref.actor.strategy in {"fsdp", "fsdp2"}: # for FSDP backend
|
| 52 |
+
assert config.critic.strategy in {"fsdp", "fsdp2"}
|
| 53 |
+
from verl.workers.fsdp_workers import ActorRolloutRefWorker, CriticWorker
|
| 54 |
+
from verl.single_controller.ray import RayWorkerGroup
|
| 55 |
+
ray_worker_group_cls = RayWorkerGroup
|
| 56 |
+
|
| 57 |
+
elif config.actor_rollout_ref.actor.strategy == 'megatron': # for Megatron backend
|
| 58 |
+
assert config.actor_rollout_ref.actor.strategy == config.critic.strategy
|
| 59 |
+
from verl.workers.megatron_workers import ActorRolloutRefWorker, CriticWorker
|
| 60 |
+
from verl.single_controller.ray.megatron import NVMegatronRayWorkerGroup
|
| 61 |
+
ray_worker_group_cls = NVMegatronRayWorkerGroup # Ray worker class for Megatron-LM
|
| 62 |
+
|
| 63 |
+
else:
|
| 64 |
+
raise NotImplementedError
|
| 65 |
+
|
| 66 |
+
from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role
|
| 67 |
+
|
| 68 |
+
role_worker_mapping = {
|
| 69 |
+
Role.ActorRollout: ActorRolloutRefWorker,
|
| 70 |
+
Role.Critic: CriticWorker,
|
| 71 |
+
Role.RefPolicy: ActorRolloutRefWorker
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
global_pool_id = 'global_pool'
|
| 75 |
+
resource_pool_spec = {
|
| 76 |
+
global_pool_id: [config.trainer.n_gpus_per_node] * config.trainer.nnodes,
|
| 77 |
+
}
|
| 78 |
+
mapping = {
|
| 79 |
+
Role.ActorRollout: global_pool_id,
|
| 80 |
+
Role.Critic: global_pool_id,
|
| 81 |
+
Role.RefPolicy: global_pool_id,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
Step 1: Construct the mapping between roles and workers
|
| 85 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 86 |
+
|
| 87 |
+
A role represents a group of workers in the same process. We have
|
| 88 |
+
pre-defined several roles in `ray_trainer.py <https://github.com/volcengine/verl/blob/main/verl/trainer/ppo/ray_trainer.py#L38>`_.
|
| 89 |
+
|
| 90 |
+
.. code:: python
|
| 91 |
+
|
| 92 |
+
class Role(Enum):
|
| 93 |
+
"""
|
| 94 |
+
To create more roles dynamically, you can subclass Role and add new members
|
| 95 |
+
"""
|
| 96 |
+
Actor = 0 # This worker only has Actor
|
| 97 |
+
Rollout = 1 # This worker only has Rollout
|
| 98 |
+
ActorRollout = 2 # This worker has both actor and rollout, it's a HybridEngine
|
| 99 |
+
Critic = 3 # This worker only has critic
|
| 100 |
+
RefPolicy = 4 # This worker only has reference policy
|
| 101 |
+
RewardModel = 5 # This worker only has reward model
|
| 102 |
+
ActorRolloutRef = 6 # This worker contains actor, rollout and reference policy simultaneously
|
| 103 |
+
|
| 104 |
+
Step 2: Define the worker class corresponding to this role
|
| 105 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 106 |
+
|
| 107 |
+
- We have pre-implemented the ``ActorRolloutRefWorker``. Through
|
| 108 |
+
different configs, it can be a standalone actor, a standalone rollout,
|
| 109 |
+
an ActorRollout HybridEngine, or an ActorRolloutRef HybridEngine
|
| 110 |
+
- We also pre-implemented workers for ``Actor``, ``Rollout``,
|
| 111 |
+
``Critic``, ``Reward Model`` and ``Reference model`` on two different
|
| 112 |
+
backend: PyTorch FSDP
|
| 113 |
+
and Megatron-LM.
|
| 114 |
+
See `FSDP Workers <https://github.com/volcengine/verl/blob/main/verl/workers/fsdp_workers.py>`_
|
| 115 |
+
and `Megatron-LM Workers <https://github.com/volcengine/verl/blob/main/verl/workers/megatron_workers.py>`_
|
| 116 |
+
for more information.
|
| 117 |
+
|
| 118 |
+
Step 3: Define resource pool id and resource pool spec
|
| 119 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 120 |
+
|
| 121 |
+
- Resource pool is a division of global GPU resources,
|
| 122 |
+
``resource_pool_spec`` is a dict, mapping from id to # of GPUs
|
| 123 |
+
|
| 124 |
+
- In the above example, we defined a global resource pool:
|
| 125 |
+
global_pool_id, and then put all roles on this one resource pool
|
| 126 |
+
with all the GPUs in this post-training task. This refers to
|
| 127 |
+
*co-locate* placement where all the models share the same set of
|
| 128 |
+
GPUs.
|
| 129 |
+
|
| 130 |
+
- See resource pool and placement for advance usage.
|
| 131 |
+
|
| 132 |
+
Defining reward model/function
|
| 133 |
+
------------------------------
|
| 134 |
+
|
| 135 |
+
.. code:: python
|
| 136 |
+
|
| 137 |
+
# we should adopt a multi-source reward function here
|
| 138 |
+
# - for rule-based rm, we directly call a reward score
|
| 139 |
+
# - for model-based rm, we call a model
|
| 140 |
+
# - for code related prompt, we send to a sandbox if there are test cases
|
| 141 |
+
# - finally, we combine all the rewards together
|
| 142 |
+
# - The reward type depends on the tag of the data
|
| 143 |
+
if config.reward_model.enable:
|
| 144 |
+
from verl.workers.fsdp_workers import RewardModelWorker
|
| 145 |
+
role_worker_mapping[Role.RewardModel] = RewardModelWorker
|
| 146 |
+
mapping[Role.RewardModel] = global_pool_id
|
| 147 |
+
|
| 148 |
+
reward_fn = RewardManager(tokenizer=tokenizer, num_examine=0)
|
| 149 |
+
|
| 150 |
+
# Note that we always use function-based RM for validation
|
| 151 |
+
val_reward_fn = RewardManager(tokenizer=tokenizer, num_examine=1)
|
| 152 |
+
|
| 153 |
+
resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=mapping)
|
| 154 |
+
|
| 155 |
+
Since not all tasks use model-based RM, users need to define here
|
| 156 |
+
whether it's a model-based RM or a function-based RM
|
| 157 |
+
|
| 158 |
+
- If it's a model-based RM, directly add the ``RewardModel`` role in the
|
| 159 |
+
resource mapping and add it to the resource pool mapping.
|
| 160 |
+
|
| 161 |
+
- Note that the pre-defined ``RewardModelWorker`` only supports models
|
| 162 |
+
with the structure of huggingface
|
| 163 |
+
``AutoModelForSequenceClassification``. If it's not this model, you
|
| 164 |
+
need to define your own RewardModelWorker in `FSDP Workers <https://github.com/volcengine/verl/blob/main/verl/workers/fsdp_workers.py>`_
|
| 165 |
+
and `Megatron-LM Workers <https://github.com/volcengine/verl/blob/main/verl/workers/megatron_workers.py>`_.
|
| 166 |
+
|
| 167 |
+
- If it's a function-based RM, the users are required to classified the
|
| 168 |
+
reward function for each datasets.
|
| 169 |
+
|
| 170 |
+
.. code:: python
|
| 171 |
+
|
| 172 |
+
def _select_rm_score_fn(data_source):
|
| 173 |
+
if data_source == 'openai/gsm8k':
|
| 174 |
+
return gsm8k.compute_score
|
| 175 |
+
elif data_source == 'lighteval/MATH':
|
| 176 |
+
return math.compute_score
|
| 177 |
+
else:
|
| 178 |
+
raise NotImplementedError
|
| 179 |
+
|
| 180 |
+
See reward functions implemented in `directory <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score/>`_
|
| 181 |
+
for more information.
|
| 182 |
+
|
| 183 |
+
Define, init and run the PPO Trainer
|
| 184 |
+
------------------------------------
|
| 185 |
+
|
| 186 |
+
.. code:: python
|
| 187 |
+
|
| 188 |
+
trainer = RayPPOTrainer(config=config,
|
| 189 |
+
tokenizer=tokenizer,
|
| 190 |
+
role_worker_mapping=role_worker_mapping,
|
| 191 |
+
resource_pool_manager=resource_pool_manager,
|
| 192 |
+
ray_worker_group_cls=ray_worker_group_cls,
|
| 193 |
+
reward_fn=reward_fn,
|
| 194 |
+
val_reward_fn=val_reward_fn)
|
| 195 |
+
trainer.init_workers()
|
| 196 |
+
trainer.fit()
|
| 197 |
+
|
| 198 |
+
- We first initialize the ``RayPPOTrainer`` with user config, tokenizer
|
| 199 |
+
and all the above worker mapping, resource pool, worker group and
|
| 200 |
+
reward functions
|
| 201 |
+
- We first call the ``trainer.init_workers()`` to initialize the models
|
| 202 |
+
on the allocated GPUs (in the resource pool)
|
| 203 |
+
- The actual PPO training will be executed in ``trainer.fit()``
|
| 204 |
+
|
| 205 |
+
verl can be easily extended to other RL algorithms by reusing the Ray
|
| 206 |
+
model workers, resource pool and reward functions. See :doc:`extension<../advance/dpo_extension>` for
|
| 207 |
+
more information.
|
| 208 |
+
|
| 209 |
+
Details of the ``RayPPOTrainer`` is discussed in :doc:`Ray Trainer<../workers/ray_trainer>`.
|
verl/docs/examples/sandbox_fusion_example.rst
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Sandbox Fusion Example
|
| 2 |
+
============================
|
| 3 |
+
|
| 4 |
+
Last updated: 06/27/2025.
|
| 5 |
+
|
| 6 |
+
Introduction
|
| 7 |
+
------------
|
| 8 |
+
|
| 9 |
+
Sandbox Fusion is a remote code sandbox service that provides a secure environment for running and evaluating code generated by Large Language Models (LLMs). This example demonstrates how to train an LLM and use Sandbox Fusion to verify generated code, enhancing both security and performance.
|
| 10 |
+
|
| 11 |
+
By leveraging a remote code sandbox service with greater CPU resources for concurrent code verification, you can reduce the reward stage time by 10-30%, depending on the quality of the generated code.
|
| 12 |
+
|
| 13 |
+
Step 1: Prepare the Dataset
|
| 14 |
+
---------------------------
|
| 15 |
+
|
| 16 |
+
We use the Eurus-2-RL-Data dataset for training. This dataset combines math and code questions, making it suitable for LLM training tasks. You can download it from HuggingFace: `Eurus-2-RL-Data Dataset <https://huggingface.co/datasets/PRIME-RL/Eurus-2-RL-Data>`_.
|
| 17 |
+
|
| 18 |
+
Step 2: Set Up the Sandbox Fusion Service
|
| 19 |
+
-----------------------------------------
|
| 20 |
+
|
| 21 |
+
Sandbox Fusion is a remote code sandbox service designed to securely run and evaluate LLM-generated code. To use it:
|
| 22 |
+
|
| 23 |
+
1. **Access Full Documentation**: For detailed setup instructions, refer to the `Sandbox Fusion Documentation <https://bytedance.github.io/SandboxFusion/>`_.
|
| 24 |
+
2. **Deploy the Service**: Choose one of the following deployment methods:
|
| 25 |
+
|
| 26 |
+
- **Local Deployment**: Follow the guide `here <https://bytedance.github.io/SandboxFusion/docs/docs/get-started#local-deployment>`_.
|
| 27 |
+
- **FaaS Instance (Volcengine)**: Create an instance using the `Volcengine Documentation <https://www.volcengine.com/docs/6662/1539235>`_.
|
| 28 |
+
|
| 29 |
+
After deployment, you will receive an API endpoint in the format: ``https://<ip-address-or-domain-name>/run_code``.
|
| 30 |
+
|
| 31 |
+
Step 3: Configure the Training Script
|
| 32 |
+
-------------------------------------
|
| 33 |
+
|
| 34 |
+
To integrate Sandbox Fusion into your training script, configure the following parameters:
|
| 35 |
+
|
| 36 |
+
**Key Settings for Sandbox Fusion**
|
| 37 |
+
|
| 38 |
+
- ``reward_model.sandbox_fusion.url='<API-endpoint>'``: Enable Sandbox Fusion by specifying the API endpoint (must end with ``/run_code``).
|
| 39 |
+
- ``reward_model.sandbox_fusion.max_concurrent=256``: Set the maximum number of concurrent API requests to the Sandbox Fusion service.
|
| 40 |
+
- ``reward_model.sandbox_fusion.memory_limit_mb=1024``: Set the memory limit (in MB) for each sandbox instance. Defaults to 1024MB if not specified.
|
| 41 |
+
|
| 42 |
+
**Additional Optimization**
|
| 43 |
+
|
| 44 |
+
To further reduce code verification time, enable parallel processing with:
|
| 45 |
+
|
| 46 |
+
- ``reward_model.reward_manager=prime``: The Prime reward manager verifies code across multiple subprocesses concurrently.
|
| 47 |
+
|
| 48 |
+
**Example Script**
|
| 49 |
+
|
| 50 |
+
For a practical implementation, refer to the example script:
|
| 51 |
+
|
| 52 |
+
``examples/ppo_trainer/run_deepseek7b_llm_sandbox_fusion.sh``
|
| 53 |
+
|
| 54 |
+
Once you’ve set your API endpoint in the script, you can start the training job.
|
verl/docs/examples/skypilot_examples.rst
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
SkyPilot Examples
|
| 2 |
+
=================
|
| 3 |
+
|
| 4 |
+
Last updated: 09/04/2025.
|
| 5 |
+
|
| 6 |
+
This guide provides examples of running VERL reinforcement learning training on Kubernetes clusters or cloud platforms with GPU nodes using `SkyPilot <https://github.com/skypilot-org/skypilot>`_.
|
| 7 |
+
|
| 8 |
+
Installation and Configuration
|
| 9 |
+
-------------------------------
|
| 10 |
+
|
| 11 |
+
Step 1: Install SkyPilot
|
| 12 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 13 |
+
|
| 14 |
+
Choose the installation based on your target platform:
|
| 15 |
+
|
| 16 |
+
.. code-block:: bash
|
| 17 |
+
|
| 18 |
+
# For Kubernetes only
|
| 19 |
+
pip install "skypilot[kubernetes]"
|
| 20 |
+
|
| 21 |
+
# For AWS
|
| 22 |
+
pip install "skypilot[aws]"
|
| 23 |
+
|
| 24 |
+
# For Google Cloud Platform
|
| 25 |
+
pip install "skypilot[gcp]"
|
| 26 |
+
|
| 27 |
+
# For Azure
|
| 28 |
+
pip install "skypilot[azure]"
|
| 29 |
+
|
| 30 |
+
# For multiple platforms
|
| 31 |
+
pip install "skypilot[kubernetes,aws,gcp,azure]"
|
| 32 |
+
|
| 33 |
+
Step 2: Configure Your Platform
|
| 34 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 35 |
+
|
| 36 |
+
See https://docs.skypilot.co/en/latest/getting-started/installation.html
|
| 37 |
+
|
| 38 |
+
Step 3: Set Up Environment Variables
|
| 39 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 40 |
+
|
| 41 |
+
Export necessary API keys for experiment tracking:
|
| 42 |
+
|
| 43 |
+
.. code-block:: bash
|
| 44 |
+
|
| 45 |
+
# For Weights & Biases tracking
|
| 46 |
+
export WANDB_API_KEY="your-wandb-api-key"
|
| 47 |
+
|
| 48 |
+
# For HuggingFace gated models (if needed)
|
| 49 |
+
export HF_TOKEN="your-huggingface-token"
|
| 50 |
+
|
| 51 |
+
Examples
|
| 52 |
+
--------
|
| 53 |
+
|
| 54 |
+
All example configurations are available in the `examples/skypilot/ <https://github.com/volcengine/verl/tree/main/examples/skypilot>`_ directory on GitHub. See the `README <https://github.com/volcengine/verl/blob/main/examples/skypilot/README.md>`_ for additional details.
|
| 55 |
+
|
| 56 |
+
PPO Training
|
| 57 |
+
~~~~~~~~~~~~
|
| 58 |
+
|
| 59 |
+
.. code-block:: bash
|
| 60 |
+
|
| 61 |
+
sky launch -c verl-ppo verl-ppo.yaml --secret WANDB_API_KEY -y
|
| 62 |
+
|
| 63 |
+
Runs PPO training on GSM8K dataset using Qwen2.5-0.5B-Instruct model across 2 nodes with H100 GPUs. Based on examples in ``examples/ppo_trainer/``.
|
| 64 |
+
|
| 65 |
+
`View verl-ppo.yaml on GitHub <https://github.com/volcengine/verl/blob/main/examples/skypilot/verl-ppo.yaml>`_
|
| 66 |
+
|
| 67 |
+
GRPO Training
|
| 68 |
+
~~~~~~~~~~~~~
|
| 69 |
+
|
| 70 |
+
.. code-block:: bash
|
| 71 |
+
|
| 72 |
+
sky launch -c verl-grpo verl-grpo.yaml --secret WANDB_API_KEY -y
|
| 73 |
+
|
| 74 |
+
Runs GRPO (Group Relative Policy Optimization) training on MATH dataset using Qwen2.5-7B-Instruct model. Memory-optimized configuration for 2 nodes. Based on examples in ``examples/grpo_trainer/``.
|
| 75 |
+
|
| 76 |
+
`View verl-grpo.yaml on GitHub <https://github.com/volcengine/verl/blob/main/examples/skypilot/verl-grpo.yaml>`_
|
| 77 |
+
|
| 78 |
+
Multi-turn Tool Usage Training
|
| 79 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 80 |
+
|
| 81 |
+
.. code-block:: bash
|
| 82 |
+
|
| 83 |
+
sky launch -c verl-multiturn verl-multiturn-tools.yaml \
|
| 84 |
+
--secret WANDB_API_KEY --secret HF_TOKEN -y
|
| 85 |
+
|
| 86 |
+
Single-node training with 8xH100 GPUs for multi-turn tool usage with Qwen2.5-3B-Instruct. Includes tool and interaction configurations for GSM8K. Based on examples in ``examples/sglang_multiturn/`` but uses vLLM instead of sglang.
|
| 87 |
+
|
| 88 |
+
`View verl-multiturn-tools.yaml on GitHub <https://github.com/volcengine/verl/blob/main/examples/skypilot/verl-multiturn-tools.yaml>`_
|
| 89 |
+
|
| 90 |
+
Configuration
|
| 91 |
+
-------------
|
| 92 |
+
|
| 93 |
+
The example YAML files are pre-configured with:
|
| 94 |
+
|
| 95 |
+
- **Infrastructure**: Kubernetes clusters (``infra: k8s``) - can be changed to ``infra: aws`` or ``infra: gcp``, etc.
|
| 96 |
+
- **Docker Image**: VERL's official Docker image with CUDA 12.6 support
|
| 97 |
+
- **Setup**: Automatically clones and installs VERL from source
|
| 98 |
+
- **Datasets**: Downloads required datasets during setup phase
|
| 99 |
+
- **Ray Cluster**: Configures distributed training across nodes
|
| 100 |
+
- **Logging**: Supports Weights & Biases via ``--secret WANDB_API_KEY``
|
| 101 |
+
- **Models**: Supports gated HuggingFace models via ``--secret HF_TOKEN``
|
| 102 |
+
|
| 103 |
+
Launch Command Options
|
| 104 |
+
----------------------
|
| 105 |
+
|
| 106 |
+
- ``-c <name>``: Cluster name for managing the job
|
| 107 |
+
- ``--secret KEY``: Pass secrets for API keys (can be used multiple times)
|
| 108 |
+
- ``-y``: Skip confirmation prompt
|
| 109 |
+
|
| 110 |
+
Monitoring Your Jobs
|
| 111 |
+
--------------------
|
| 112 |
+
|
| 113 |
+
Check Cluster Status
|
| 114 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 115 |
+
|
| 116 |
+
.. code-block:: bash
|
| 117 |
+
|
| 118 |
+
sky status
|
| 119 |
+
|
| 120 |
+
View Logs
|
| 121 |
+
~~~~~~~~~
|
| 122 |
+
|
| 123 |
+
.. code-block:: bash
|
| 124 |
+
|
| 125 |
+
sky logs verl-ppo # View logs for the PPO job
|
| 126 |
+
|
| 127 |
+
SSH into Head Node
|
| 128 |
+
~~~~~~~~~~~~~~~~~~
|
| 129 |
+
|
| 130 |
+
.. code-block:: bash
|
| 131 |
+
|
| 132 |
+
ssh verl-ppo
|
| 133 |
+
|
| 134 |
+
Access Ray Dashboard
|
| 135 |
+
~~~~~~~~~~~~~~~~~~~~
|
| 136 |
+
|
| 137 |
+
.. code-block:: bash
|
| 138 |
+
|
| 139 |
+
sky status --endpoint 8265 verl-ppo # Get dashboard URL
|
| 140 |
+
|
| 141 |
+
Stop a Cluster
|
| 142 |
+
~~~~~~~~~~~~~~
|
| 143 |
+
|
| 144 |
+
.. code-block:: bash
|
| 145 |
+
|
| 146 |
+
sky down verl-ppo
|
verl/docs/faq/faq.rst
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Frequently Asked Questions
|
| 2 |
+
====================================
|
| 3 |
+
|
| 4 |
+
Last updated: 09/24/2025.
|
| 5 |
+
|
| 6 |
+
Ray related
|
| 7 |
+
------------
|
| 8 |
+
|
| 9 |
+
How to add breakpoint for debugging with distributed Ray?
|
| 10 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 11 |
+
|
| 12 |
+
Please checkout the official debugging guide from Ray: https://docs.ray.io/en/latest/ray-observability/ray-distributed-debugger.html
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
"Unable to register worker with raylet"
|
| 16 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 17 |
+
|
| 18 |
+
The cause of this issue is due to some system setting, e.g., SLURM added some constraints on how the CPUs are shared on a node.
|
| 19 |
+
While `ray.init()` tries to launch as many worker processes as the number of CPU cores of the machine,
|
| 20 |
+
some constraints of SLURM restricts the `core-workers` seeing the `raylet` process, leading to the problem.
|
| 21 |
+
|
| 22 |
+
To fix this issue, you can set the config term ``ray_init.num_cpus`` to a number allowed by your system.
|
| 23 |
+
|
| 24 |
+
Distributed training
|
| 25 |
+
------------------------
|
| 26 |
+
|
| 27 |
+
How to run multi-node post-training with Ray?
|
| 28 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 29 |
+
|
| 30 |
+
You can start a ray cluster and submit a ray job, following the official guide from Ray: https://docs.ray.io/en/latest/ray-core/starting-ray.html
|
| 31 |
+
|
| 32 |
+
Then in the configuration, set the ``trainer.nnode`` config to the number of machines for your job.
|
| 33 |
+
|
| 34 |
+
How to use verl on a Slurm-managed cluster?
|
| 35 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 36 |
+
|
| 37 |
+
Ray provides users with `this <https://docs.ray.io/en/latest/cluster/vms/user-guides/community/slurm.html>`_ official
|
| 38 |
+
tutorial to start a Ray cluster on top of Slurm. We have verified the :doc:`GSM8K example<../examples/gsm8k_example>`
|
| 39 |
+
on a Slurm cluster under a multi-node setting with the following steps.
|
| 40 |
+
|
| 41 |
+
1. [Optional] If your cluster support `Apptainer or Singularity <https://apptainer.org/docs/user/main/>`_ and you wish
|
| 42 |
+
to use it, convert verl's Docker image to an Apptainer image. Alternatively, set up the environment with the package
|
| 43 |
+
manager available on your cluster or use other container runtimes (e.g. through `Slurm's OCI support <https://slurm.schedmd.com/containers.html>`_) available to you.
|
| 44 |
+
|
| 45 |
+
.. code:: bash
|
| 46 |
+
|
| 47 |
+
apptainer pull /your/dest/dir/vemlp-th2.4.0-cu124-vllm0.6.3-ray2.10-te1.7-v0.0.3.sif docker://verlai/verl:vemlp-th2.4.0-cu124-vllm0.6.3-ray2.10-te1.7-v0.0.3
|
| 48 |
+
|
| 49 |
+
2. Follow :doc:`GSM8K example<../examples/gsm8k_example>` to prepare the dataset and model checkpoints.
|
| 50 |
+
|
| 51 |
+
3. Modify `examples/slurm/ray_on_slurm.slurm <https://github.com/volcengine/verl/blob/main/examples/slurm/ray_on_slurm.slurm>`_ with your cluster's own information.
|
| 52 |
+
|
| 53 |
+
4. Submit the job script to the Slurm cluster with `sbatch`.
|
| 54 |
+
|
| 55 |
+
Please note that Slurm cluster setup may vary. If you encounter any issues, please refer to Ray's
|
| 56 |
+
`Slurm user guide <https://docs.ray.io/en/latest/cluster/vms/user-guides/community/slurm.html>`_ for common caveats.
|
| 57 |
+
|
| 58 |
+
If you changed Slurm resource specifications, please make sure to update the environment variables in the job script if necessary.
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
Install related
|
| 62 |
+
------------------------
|
| 63 |
+
|
| 64 |
+
NotImplementedError: TensorDict does not support membership checks with the `in` keyword.
|
| 65 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 66 |
+
|
| 67 |
+
Detail error information:
|
| 68 |
+
|
| 69 |
+
.. code:: bash
|
| 70 |
+
|
| 71 |
+
NotImplementedError: TensorDict does not support membership checks with the `in` keyword. If you want to check if a particular key is in your TensorDict, please use `key in tensordict.keys()` instead.
|
| 72 |
+
|
| 73 |
+
Cause of the problem: There is no suitable version of tensordict package for the linux-arm64 platform. The confirmation method is as follows:
|
| 74 |
+
|
| 75 |
+
.. code:: bash
|
| 76 |
+
|
| 77 |
+
pip install tensordict==0.6.2
|
| 78 |
+
|
| 79 |
+
Output example:
|
| 80 |
+
|
| 81 |
+
.. code:: bash
|
| 82 |
+
|
| 83 |
+
ERROR: Could not find a version that satisfies the requirement tensordict==0.6.2 (from versions: 0.0.1a0, 0.0.1b0, 0.0.1rc0, 0.0.2a0, 0.0.2b0, 0.0.3, 0.1.0, 0.1.1, 0.1.2, 0.8.0, 0.8.1, 0.8.2, 0.8.3)
|
| 84 |
+
ERROR: No matching distribution found for tensordict==0.6.2
|
| 85 |
+
|
| 86 |
+
Solution 1st:
|
| 87 |
+
Install tensordict from source code:
|
| 88 |
+
|
| 89 |
+
.. code:: bash
|
| 90 |
+
|
| 91 |
+
pip uninstall tensordict
|
| 92 |
+
git clone https://github.com/pytorch/tensordict.git
|
| 93 |
+
cd tensordict/
|
| 94 |
+
git checkout v0.6.2
|
| 95 |
+
python setup.py develop
|
| 96 |
+
pip install -v -e .
|
| 97 |
+
|
| 98 |
+
Solution 2nd:
|
| 99 |
+
Temperally modify the error takeplace codes: tensordict_var -> tensordict_var.keys()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
Illegal memory access
|
| 103 |
+
---------------------------------
|
| 104 |
+
|
| 105 |
+
If you encounter the error message like ``CUDA error: an illegal memory access was encountered`` during rollout, please check the vLLM documentation for troubleshooting steps specific to your vLLM version.
|
| 106 |
+
|
| 107 |
+
Checkpoints
|
| 108 |
+
------------------------
|
| 109 |
+
|
| 110 |
+
If you want to convert the model checkpoint into huggingface safetensor format, please refer to ``verl/model_merger``.
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
Triton ``compile_module_from_src`` error
|
| 114 |
+
------------------------------------------------
|
| 115 |
+
|
| 116 |
+
If you encounter triton compilation error similar to the stacktrace below, please set the ``use_torch_compile`` flag according to
|
| 117 |
+
https://verl.readthedocs.io/en/latest/examples/config.html to disable just-in-time compilation for fused kernels.
|
| 118 |
+
|
| 119 |
+
.. code:: bash
|
| 120 |
+
|
| 121 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/runtime/jit.py", line 345, in <lambda>
|
| 122 |
+
return lambda *args, **kwargs: self.run(grid=grid, warmup=False, *args, **kwargs)
|
| 123 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/runtime/autotuner.py", line 338, in run
|
| 124 |
+
return self.fn.run(*args, **kwargs)
|
| 125 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/runtime/jit.py", line 607, in run
|
| 126 |
+
device = driver.active.get_current_device()
|
| 127 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/runtime/driver.py", line 23, in __getattr__
|
| 128 |
+
self._initialize_obj()
|
| 129 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/runtime/driver.py", line 20, in _initialize_obj
|
| 130 |
+
self._obj = self._init_fn()
|
| 131 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/runtime/driver.py", line 9, in _create_driver
|
| 132 |
+
return actives[0]()
|
| 133 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/backends/nvidia/driver.py", line 371, in __init__
|
| 134 |
+
self.utils = CudaUtils() # TODO: make static
|
| 135 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/backends/nvidia/driver.py", line 80, in __init__
|
| 136 |
+
mod = compile_module_from_src(Path(os.path.join(dirname, "driver.c")).read_text(), "cuda_utils")
|
| 137 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/backends/nvidia/driver.py", line 57, in compile_module_from_src
|
| 138 |
+
so = _build(name, src_path, tmpdir, library_dirs(), include_dir, libraries)
|
| 139 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/site-packages/triton/runtime/build.py", line 48, in _build
|
| 140 |
+
ret = subprocess.check_call(cc_cmd)
|
| 141 |
+
File "/data/lbh/conda_envs/verl/lib/python3.10/subprocess.py", line 369, in check_call
|
| 142 |
+
raise CalledProcessError(retcode, cmd)
|
| 143 |
+
|
| 144 |
+
What is the meaning of train batch size, mini batch size, and micro batch size?
|
| 145 |
+
------------------------------------------------------------------------------------------
|
| 146 |
+
|
| 147 |
+
This figure illustrates the relationship between different batch size configurations.
|
| 148 |
+
|
| 149 |
+
https://excalidraw.com/#json=pfhkRmiLm1jnnRli9VFhb,Ut4E8peALlgAUpr7E5pPCA
|
| 150 |
+
|
| 151 |
+
.. image:: https://github.com/user-attachments/assets/16aebad1-0da6-4eb3-806d-54a74e712c2d
|
| 152 |
+
|
| 153 |
+
How to generate ray timeline to analyse performance of a training job?
|
| 154 |
+
------------------------------------------------------------------------------------------
|
| 155 |
+
|
| 156 |
+
To generate the ray timeline file, you can set the config term ``ray_init.timeline_file`` to a json file path.
|
| 157 |
+
For example:
|
| 158 |
+
|
| 159 |
+
.. code:: bash
|
| 160 |
+
|
| 161 |
+
ray_init.timeline_file=/tmp/ray_timeline.json
|
| 162 |
+
|
| 163 |
+
The file will be generated in the specified path at the end of a training job.
|
| 164 |
+
You can use tools like chrome://tracing or the Perfetto UI and view the ray timeline file.
|
| 165 |
+
|
| 166 |
+
This figure shows the ray timeline file generated by from a training job on 1 node with 4 GPUs
|
| 167 |
+
|
| 168 |
+
.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/ray_timeline.png?raw=true
|
| 169 |
+
|
| 170 |
+
How to set proxy only for wandb?
|
| 171 |
+
------------------------------------------------------------------------------------------
|
| 172 |
+
|
| 173 |
+
If you need a proxy to access wandb, you can add below config in your training job script.
|
| 174 |
+
Comparing to using global https_proxy env variable, this approach won't mess up other http requests, such as ChatCompletionScheduler.
|
| 175 |
+
|
| 176 |
+
.. code:: bash
|
| 177 |
+
|
| 178 |
+
+trainer.wandb_proxy=http://<your proxy and port>
|
| 179 |
+
|
| 180 |
+
Missmatch between inference and training sequence (high actor/grad_norm)
|
| 181 |
+
------------------------------------------------------------------------------------------
|
| 182 |
+
|
| 183 |
+
If you encounter the issue of actor/grad_norm metric continuously increasing during training, it might be caused by a significant precision mismatching between the inference engine and training. You can use the following parameter to confirm this:
|
| 184 |
+
|
| 185 |
+
.. code:: bash
|
| 186 |
+
|
| 187 |
+
actor_rollout_ref.rollout.calculate_log_probs=True
|
| 188 |
+
|
| 189 |
+
This parameter will add metrics like training/rollout_probs_diff_mean , which can be used to verify if there is a precision difference between inference and training.
|
| 190 |
+
|
| 191 |
+
Under normal circumstances, the value of training/rollout_probs_diff_mean should be below 0.005. If you observe this value to be higher than 0.01, it indicates a precision issue from the inference engine.
|
| 192 |
+
The precision issue is known to occur under the following conditions:
|
| 193 |
+
|
| 194 |
+
1. Using non-Hopper architecture GPUs, such as A100, L20, B200, etc.
|
| 195 |
+
|
| 196 |
+
2. Using vLLM `with issue 22103 <https://github.com/vllm-project/vllm/issues/22103>`_ as the inference engine.
|
| 197 |
+
|
| 198 |
+
3. The input and output texts are long, for example, in multi-turn scenarios using reasioning models like Qwen3 for RL training.
|
| 199 |
+
|
| 200 |
+
If all three conditions above are met and you observe that rollout_probs_diff_mean is too high, it is recommended to add the following parameter to resolve the precision issue:
|
| 201 |
+
|
| 202 |
+
.. code:: bash
|
| 203 |
+
|
| 204 |
+
+actor_rollout_ref.rollout.engine_kwargs.vllm.disable_cascade_attn=True
|
| 205 |
+
|
| 206 |
+
The root cause of this issue is a bug in the flash attention used by vLLM. Although it has been fixed, the fix has not yet been released in the latest version of vLLM (v0.10.2).
|
| 207 |
+
For a more detailed explanation of this issue, please refer to `Fix LSE output error in FA2 kv-split <https://github.com/vllm-project/flash-attention/pull/87>`_.
|
| 208 |
+
|
| 209 |
+
Until vLLM releases a new version with this fix, it is recommended to use the configuration above to disable cascade attention as a workaround.
|
verl/docs/perf/device_tuning.rst
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Hardware Resource Needed for RL
|
| 2 |
+
===============================
|
| 3 |
+
|
| 4 |
+
Last updated: 06/25/2025.
|
| 5 |
+
|
| 6 |
+
Since RL requires more resources compared to regular training,
|
| 7 |
+
determining how much resources are needed to successfully run it before training
|
| 8 |
+
is a relatively difficult task. To provide more people with reference points for
|
| 9 |
+
resource selection when dealing with different models and tasks, this section is
|
| 10 |
+
mainly dedicated to introducing the environmental requirements based on experiments
|
| 11 |
+
we have conducted.
|
| 12 |
+
|
| 13 |
+
However, due to limited staff and equipment resources, we also hope for more
|
| 14 |
+
contributions from the open-source community. When submitting a PR, it is necessary
|
| 15 |
+
to provide a script to be added to the example/tuning scripts.
|
| 16 |
+
|
| 17 |
+
We need two types of scripts: one is the configuration that can run with the **minimum
|
| 18 |
+
resources(min)**, and the other is the configuration that runs with **recommended resources(recommended)**. For the former,
|
| 19 |
+
it can be understood as a script that can run after applying all memory optimization techniques
|
| 20 |
+
(e.g., offload, gradient checkpointing). For the latter, it can be understood as a script that
|
| 21 |
+
can run while avoiding operations that incur additional time overhead as much as possible (targetting best throughput).
|
| 22 |
+
|
| 23 |
+
When defining script names, please follow this format:
|
| 24 |
+
``[model]_[task]_[gpunums]_[device]_[train]_[infer].sh``. This will effectively improve
|
| 25 |
+
the script's recognizability. You can place the script under the ``examples/tuning/`` directory.
|
| 26 |
+
|
| 27 |
+
If you happen to have a configuration that has already been tested, we welcome you to submit
|
| 28 |
+
a PR and include a screenshot from Wandb or other verifiable evidence.
|
| 29 |
+
|
| 30 |
+
----------------------------------------
|
| 31 |
+
|
| 32 |
+
0.5B
|
| 33 |
+
~~~
|
| 34 |
+
|
| 35 |
+
.. list-table::
|
| 36 |
+
:widths: auto
|
| 37 |
+
:header-rows: 1
|
| 38 |
+
|
| 39 |
+
* - Tag
|
| 40 |
+
- Model
|
| 41 |
+
- Task
|
| 42 |
+
- Resource
|
| 43 |
+
- MaxBatch
|
| 44 |
+
- Train
|
| 45 |
+
- Infer
|
| 46 |
+
- Link
|
| 47 |
+
- Contributor
|
| 48 |
+
* - MIN
|
| 49 |
+
- Qwen2.5-0.5B
|
| 50 |
+
- GRPO-LoRA
|
| 51 |
+
- 1*H100
|
| 52 |
+
- 116
|
| 53 |
+
- fsdp
|
| 54 |
+
- vllm0.8.3
|
| 55 |
+
- `qwen2-0.5b_grpo-lora_1_h100_fsdp_vllm.sh <https://github.com/volcengine/verl/blob/main/examples/tuning/0.5b/qwen2-0.5b_grpo-lora_1_h100_fsdp_vllm.sh>`_
|
| 56 |
+
- `SimonHuang <thelongestusernameofall@gmail.com>`_
|
| 57 |
+
|
| 58 |
+
1.5B
|
| 59 |
+
~~~
|
| 60 |
+
|
| 61 |
+
.. list-table::
|
| 62 |
+
:widths: auto
|
| 63 |
+
:header-rows: 1
|
| 64 |
+
|
| 65 |
+
* - Tag
|
| 66 |
+
- Model
|
| 67 |
+
- Task
|
| 68 |
+
- Resource
|
| 69 |
+
- MaxBatch
|
| 70 |
+
- Train
|
| 71 |
+
- Infer
|
| 72 |
+
- Link
|
| 73 |
+
- Contributor
|
| 74 |
+
* - MIN
|
| 75 |
+
- Qwen2.5-1.5B
|
| 76 |
+
- GRPO-LoRA
|
| 77 |
+
- 1*H100
|
| 78 |
+
- 128
|
| 79 |
+
- fsdp
|
| 80 |
+
- vllm0.8.3
|
| 81 |
+
- `qwen2-1.5b_grpo-lora_1_h100_fsdp_vllm.sh <https://github.com/volcengine/verl/blob/main/examples/tuning/1.5b/qwen2-1.5b_grpo-lora_1_h100_fsdp_vllm.sh>`_
|
| 82 |
+
- `SimonHuang <thelongestusernameofall@gmail.com>`_
|
| 83 |
+
|
| 84 |
+
3B
|
| 85 |
+
~~~
|
| 86 |
+
|
| 87 |
+
.. list-table::
|
| 88 |
+
:widths: auto
|
| 89 |
+
:header-rows: 1
|
| 90 |
+
|
| 91 |
+
* - Tag
|
| 92 |
+
- Model
|
| 93 |
+
- Task
|
| 94 |
+
- Resource
|
| 95 |
+
- MaxBatch
|
| 96 |
+
- Train
|
| 97 |
+
- Infer
|
| 98 |
+
- Link
|
| 99 |
+
- Contributor
|
| 100 |
+
* - MIN
|
| 101 |
+
- Qwen2.5-3B
|
| 102 |
+
- GRPO-LoRA
|
| 103 |
+
- 1*H100
|
| 104 |
+
- 62
|
| 105 |
+
- fsdp
|
| 106 |
+
- vllm0.8.3
|
| 107 |
+
- `qwen2-3b_grpo-lora_1_h100_fsdp_vllm.sh <https://github.com/volcengine/verl/blob/main/examples/tuning/3b/qwen2-3b_grpo-lora_1_h100_fsdp_vllm.sh>`_
|
| 108 |
+
- `SimonHuang <thelongestusernameofall@gmail.com>`_
|
| 109 |
+
|
| 110 |
+
7B
|
| 111 |
+
~~~
|
| 112 |
+
|
| 113 |
+
.. list-table::
|
| 114 |
+
:widths: auto
|
| 115 |
+
:header-rows: 1
|
| 116 |
+
|
| 117 |
+
* - Tag
|
| 118 |
+
- Model
|
| 119 |
+
- Task
|
| 120 |
+
- Resource
|
| 121 |
+
- MaxBatch
|
| 122 |
+
- Train
|
| 123 |
+
- Infer
|
| 124 |
+
- Link
|
| 125 |
+
- Contributor
|
| 126 |
+
* - MIN
|
| 127 |
+
- Qwen2-7B
|
| 128 |
+
- GRPO
|
| 129 |
+
- 2*H800
|
| 130 |
+
- \
|
| 131 |
+
- fsdp
|
| 132 |
+
- vllm0.8.2
|
| 133 |
+
- `qwen2-7b_grpo_2_h800_fsdp_vllm <https://github.com/volcengine/verl/blob/main/examples/tuning/7b/qwen2-7b_grpo_2_h800_fsdp_vllm.sh>`_
|
| 134 |
+
- `Xiangyongan <xiangyongan@bytedance.com>`_
|
| 135 |
+
* - MIN
|
| 136 |
+
- Qwen2.5-7B
|
| 137 |
+
- GRPO-LoRA
|
| 138 |
+
- 1*H100
|
| 139 |
+
- 16
|
| 140 |
+
- fsdp
|
| 141 |
+
- vllm0.8.3
|
| 142 |
+
- `qwen2-7b_grpo-lora_1_h100_fsdp_vllm.sh <https://github.com/volcengine/verl/blob/main/examples/tuning/7b/qwen2-7b_grpo-lora_1_h100_fsdp_vllm.sh>`_
|
| 143 |
+
- `SimonHuang <thelongestusernameofall@gmail.com>`_
|
| 144 |
+
|
| 145 |
+
14B
|
| 146 |
+
~~~
|
| 147 |
+
|
| 148 |
+
.. list-table::
|
| 149 |
+
:widths: auto
|
| 150 |
+
:header-rows: 1
|
| 151 |
+
|
| 152 |
+
* - Tag
|
| 153 |
+
- Model
|
| 154 |
+
- Task
|
| 155 |
+
- Resource
|
| 156 |
+
- MaxBatch
|
| 157 |
+
- Train
|
| 158 |
+
- Infer
|
| 159 |
+
- Link
|
| 160 |
+
- Contributor
|
| 161 |
+
* - MIN
|
| 162 |
+
- Qwen2-14B
|
| 163 |
+
- GRPO
|
| 164 |
+
- 4*H800
|
| 165 |
+
- \
|
| 166 |
+
- fsdp
|
| 167 |
+
- vllm0.8.2
|
| 168 |
+
- `qwen2-14b_grpo_4_h800_fsdp_vllm <https://github.com/volcengine/verl/blob/main/examples/tuning/14b/qwen2-14b_grpo_4_h800_fsdp_vllm.sh>`_
|
| 169 |
+
- `Xiangyongan <xiangyongan@bytedance.com>`_
|
| 170 |
+
* - MIN
|
| 171 |
+
- Qwen2.5-14B
|
| 172 |
+
- GRPO-LoRA
|
| 173 |
+
- 2*H100
|
| 174 |
+
- 116
|
| 175 |
+
- fsdp
|
| 176 |
+
- vllm0.8.3
|
| 177 |
+
- `qwen2-14b_grpo-lora_2_h100_fsdp_vllm.sh <https://github.com/volcengine/verl/blob/main/examples/tuning/14b/qwen2-14b_grpo-lora_2_h100_fsdp_vllm.sh>`_
|
| 178 |
+
- `SimonHuang <thelongestusernameofall@gmail.com>`_
|
| 179 |
+
|
| 180 |
+
32B
|
| 181 |
+
~~~
|
| 182 |
+
|
| 183 |
+
.. list-table::
|
| 184 |
+
:widths: auto
|
| 185 |
+
:header-rows: 1
|
| 186 |
+
|
| 187 |
+
* - Tag
|
| 188 |
+
- Model
|
| 189 |
+
- Task
|
| 190 |
+
- Resource
|
| 191 |
+
- MaxBatch
|
| 192 |
+
- Train
|
| 193 |
+
- Infer
|
| 194 |
+
- Link
|
| 195 |
+
- Contributor
|
| 196 |
+
* - MIN
|
| 197 |
+
- Qwen2-32B
|
| 198 |
+
- GRPO
|
| 199 |
+
- 8*H20
|
| 200 |
+
- \
|
| 201 |
+
- megatron
|
| 202 |
+
- vllm0.8.2
|
| 203 |
+
- `qwen2-32b_grpo_8_h20_megatron_vllm <https://github.com/volcengine/verl/tree/main/examples/tuning/32b/qwen2_32B_grpo_8_h20_megatron_vllm.sh>`_
|
| 204 |
+
- `Xiangyongan <xiangyongan@bytedance.com>`_
|
| 205 |
+
* - MIN
|
| 206 |
+
- Qwen2.5-32B
|
| 207 |
+
- GRPO-LoRA
|
| 208 |
+
- 4*H100
|
| 209 |
+
- 180
|
| 210 |
+
- fsdp
|
| 211 |
+
- vllm0.8.3
|
| 212 |
+
- `qwen2-32b_grpo-lora_4_h100_fsdp_vllm.sh <https://github.com/volcengine/verl/blob/main/examples/tuning/32b/qwen2-32b_grpo-lora_4_h100_fsdp_vllm.sh>`_
|
| 213 |
+
- `SimonHuang <thelongestusernameofall@gmail.com>`_
|
| 214 |
+
|
| 215 |
+
70B
|
| 216 |
+
~~~
|
| 217 |
+
|
| 218 |
+
.. list-table::
|
| 219 |
+
:widths: auto
|
| 220 |
+
:header-rows: 1
|
| 221 |
+
|
| 222 |
+
* - Tag
|
| 223 |
+
- Model
|
| 224 |
+
- Task
|
| 225 |
+
- Resource
|
| 226 |
+
- MaxBatch
|
| 227 |
+
- Train
|
| 228 |
+
- Infer
|
| 229 |
+
- Link
|
| 230 |
+
- Contributor
|
| 231 |
+
* - MIN
|
| 232 |
+
- Qwen2-70B
|
| 233 |
+
- GRPO
|
| 234 |
+
- 32*H20
|
| 235 |
+
- \
|
| 236 |
+
- fsdp
|
| 237 |
+
- vllm0.8.2
|
| 238 |
+
- `qwen2-70b_grpo_32_h20_fsdp_vllm <https://github.com/volcengine/verl/blob/main/examples/tuning/70b/qwen2-70b_grpo_32_h20_fsdp_vllm.sh>`_
|
| 239 |
+
- `Xiangyongan <xiangyongan@bytedance.com>`_
|
| 240 |
+
* - MIN
|
| 241 |
+
- Qwen2-70B
|
| 242 |
+
- GRPO
|
| 243 |
+
- 32*H800
|
| 244 |
+
- \
|
| 245 |
+
- fsdp
|
| 246 |
+
- vllm0.8.3
|
| 247 |
+
- `qwen2-70b_grpo_32_h800_fsdp_vllm <https://github.com/volcengine/verl/blob/main/examples/tuning/70b/qwen2-70b_grpo_32_h800_fsdp_vllm.sh>`_
|
| 248 |
+
- `Xiangyongan <xiangyongan@bytedance.com>`_
|
| 249 |
+
* - MIN
|
| 250 |
+
- Qwen2.5-72B
|
| 251 |
+
- GRPO-LoRA
|
| 252 |
+
- 8*H100
|
| 253 |
+
- 176
|
| 254 |
+
- fsdp
|
| 255 |
+
- vllm0.8.3
|
| 256 |
+
- `qwen2-72b_grpo-lora_8_h100_fsdp_vllm.sh <https://github.com/volcengine/verl/blob/main/examples/tuning/70b/qwen2-72b_grpo-lora_8_h100_fsdp_vllm.sh>`_
|
| 257 |
+
- `SimonHuang <thelongestusernameofall@gmail.com>`_
|
| 258 |
+
|
| 259 |
+
405B
|
| 260 |
+
~~~~
|
| 261 |
+
|
| 262 |
+
.. table::
|
| 263 |
+
:widths: auto
|
| 264 |
+
|
| 265 |
+
====== ====== ====== ======== ======== ====== ====== ======
|
| 266 |
+
tag model task resource MaxBatch train infer link
|
| 267 |
+
====== ====== ====== ======== ======== ====== ====== ======
|
| 268 |
+
\ \ \ \ \ \ \
|
| 269 |
+
====== ====== ====== ======== ======== ====== ====== ======
|
| 270 |
+
|
| 271 |
+
671B
|
| 272 |
+
~~~~
|
| 273 |
+
|
| 274 |
+
.. table::
|
| 275 |
+
:widths: auto
|
| 276 |
+
|
| 277 |
+
====== ====== ====== ======== ======== ====== ====== ======
|
| 278 |
+
tag model task resource MaxBatch train infer link
|
| 279 |
+
====== ====== ====== ======== ======== ====== ====== ======
|
| 280 |
+
\ \ \ \ \ \ \
|
| 281 |
+
====== ====== ====== ======== ======== ====== ====== ======
|
verl/docs/perf/dpsk.md
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Training DeepSeek 671b
|
| 2 |
+
|
| 3 |
+
Last updated: 08/20/2025.
|
| 4 |
+
|
| 5 |
+
verl integrates Megatron to support large MoE models such as `Qwen3-235B-A22B` and `deepseek-ai/DeepSeek-V3`. This is an ongoing community effort.
|
| 6 |
+
|
| 7 |
+
In the journey the community added the following features and optimizations that enable verl with larger models:
|
| 8 |
+
- per tensor weight resharding between rollout and training
|
| 9 |
+
- context parallelism and expert parallelism enabled via megatron
|
| 10 |
+
- dynamic batch size (sequence balance) for megatron
|
| 11 |
+
- reduced ray-related serialization overhead
|
| 12 |
+
- optimizer offloading, recomputation, and efficient kernels
|
| 13 |
+
- various debugging metrics and utils
|
| 14 |
+
- hybrid optimizer
|
| 15 |
+
|
| 16 |
+
and the megatron backend now has a wider list of models supported:
|
| 17 |
+
- DeepSeek-V3
|
| 18 |
+
- Moonlight
|
| 19 |
+
- Qwen3
|
| 20 |
+
- Qwen2.5-VL (to be merged soon)
|
| 21 |
+
- Qwen2
|
| 22 |
+
- Mixtral
|
| 23 |
+
|
| 24 |
+
## Getting Started
|
| 25 |
+
|
| 26 |
+
### preparation
|
| 27 |
+
The recommended image with pre-built Megatron dependency is `verlai/verl:app-verl0.4-vllm0.8.5-mcore0.13.0-preview`, which is built using the Dockerfile at [docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.13.preview](https://github.com/volcengine/verl/blob/main/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.13.preview).
|
| 28 |
+
|
| 29 |
+
The image is build in Hopper GPUs with DeepEP. It does not support None-Hopper GPUs, such as A100. You may need to reinstall DeepEP to work with A100.
|
| 30 |
+
|
| 31 |
+
With `OFFLOAD_FRACTION=1`, the system's minimum requirements are lowered. It can run on as few as 96 H20 (96GB) GPUs for DeepSeek-V3, and on as few as 32 H20 (96GB) GPUs for Qwen3-235B-A22B. However, this configuration will use 1.6TB CPU memory per node. If you run out of CPU memory or require faster training speed, you can add more nodes.
|
| 32 |
+
|
| 33 |
+
### DeepSeek 671b
|
| 34 |
+
|
| 35 |
+
For DeepSeek-V3 671b, please refer to [examples/grpo_trainer/run_deepseek671b_math_megatron_96gb.sh](https://github.com/volcengine/verl/blob/main/examples/grpo_trainer/run_deepseek671b_math_megatron_96gb.sh).
|
| 36 |
+
|
| 37 |
+
MTP and quantilization is disabled during RL training.
|
| 38 |
+
|
| 39 |
+
To train your project, configure the following environment variables based on the number of available GPUs. These are recommended settings and can be adjusted based on your specific hardware.
|
| 40 |
+
| num gpus | NNODES | TP | PP | EP | OFFLOAD_FRACTION | OFFLOAD_OPTIM | LAST_LAYER |
|
| 41 |
+
| -- | -- | -- | -- | -- | -- | -- | -- |
|
| 42 |
+
| 96 | 12 | 8 | 12 | 8 | 1. | False | 6 |
|
| 43 |
+
| 128 | 16 | 8 | 16 | 8 | 0.5 | True | 1 |
|
| 44 |
+
| 256 | 32 | 8 | 16 | 8 | 0. | True | 1 |
|
| 45 |
+
| 512 | 64 | 1 | 16 | 32 | 0 | True | 1 |
|
| 46 |
+
|
| 47 |
+
### Qwen3 235b
|
| 48 |
+
|
| 49 |
+
For Qwen3-235b, please refer to [examples/grpo_trainer/run_qwen3-235b_megatron_96gb.sh](https://github.com/volcengine/verl/blob/main/examples/grpo_trainer/run_qwen3-235b_megatron_96gb.sh).
|
| 50 |
+
|
| 51 |
+
To train your project, configure the following environment variables based on the number of available GPUs. These are recommended settings and can be adjusted based on your specific hardware.
|
| 52 |
+
| num gpus | NNODES | TP | PP | EP | OFFLOAD_FRACTION | OFFLOAD_OPTIM | LAST_LAYER |
|
| 53 |
+
| -- | -- | -- | -- | -- | -- | -- | -- |
|
| 54 |
+
| 32 | 4 | 4 | 8 | 4 | 1. | False | 6 |
|
| 55 |
+
| 64 | 8 | 4 | 8 | 4 | 0.5 | True | 6 |
|
| 56 |
+
| 128 | 16 | 4 | 8 | 4 | 0 | True | 6 |
|
| 57 |
+
| 256 | 32 | 4 | 8 | 4 | 0 | True | 6 |
|
| 58 |
+
|
| 59 |
+
### Benchmark
|
| 60 |
+
Here are some benchmark results for DeepSeek / Qwen3-235B. All configurations match the recommended settings based on the number of GPUs.
|
| 61 |
+
|
| 62 |
+
| model | num gpus | mean response length | rollout time(s) | GPU memory(GB) | CPU memory(GB) | MFU | step time(s) |
|
| 63 |
+
| -- | -- | -- | -- | -- | -- | -- | -- |
|
| 64 |
+
| DeepSeek 671b | 96 | 1960 | 1050 | 66 | 1500 | 0.19 | 1700 |
|
| 65 |
+
|
| 66 |
+
### Qwen3-30B-A3B MOE
|
| 67 |
+
|
| 68 |
+
For Qwen3-30b, please refer to [examples/grpo_trainer/run_qwen3moe-30b_megatron_96gb.sh](https://github.com/volcengine/verl/blob/main/examples/grpo_trainer/run_qwen3moe-30b_megatron_96gb.sh).
|
| 69 |
+
|
| 70 |
+
To train your project, configure the following environment variables based on the number of available GPUs. These are recommended settings and can be adjusted based on your specific hardware.
|
| 71 |
+
| num gpus | NNODES | TP | PP | EP | OFFLOAD_FRACTION | OFFLOAD_OPTIM | MFU |
|
| 72 |
+
| -- | -- | -- | -- | -- | -- | -- | -- |
|
| 73 |
+
| 8 | 1 | 1 | 1 | 8 | 1. | True | 0.4 |
|
| 74 |
+
| 16 | 2 | 1 | 1 | 8 | 1. | True | 0.37 |
|
| 75 |
+
| 32 | 4 | 1 | 1 | 8 | 1. | True | 0.31 |
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
## Upcoming Optimizations
|
| 79 |
+
|
| 80 |
+
The community continue to optimize large MoE models further, ongoing efforts include:
|
| 81 |
+
- further optimizing memory consumption, and provide recommended/tuned configurations with various machine types
|
| 82 |
+
- optimizing long context RL training performance
|
| 83 |
+
- performance improvement with SGLang x Megatron
|
| 84 |
+
|
| 85 |
+
We invite the community to try and improve verl together. Get connected with us on [slack](https://join.slack.com/t/verlgroup/shared_invite/zt-2w5p9o4c3-yy0x2Q56s_VlGLsJ93A6vA)/[wechat](https://raw.githubusercontent.com/eric-haibin-lin/verl-community/refs/heads/main/WeChat.JPG)/[Github issues](https://github.com/volcengine/verl/issues/708)!
|
| 86 |
+
|
| 87 |
+
## Acknowledgement
|
| 88 |
+
@vermouth1992 @ISEEKYAN @ETOgaosion @yzlnew @ShareLer @BearBiscuit05 @ccclyu @ann-qin-lu @SwordFaith @zzong2006 @zhaochenyang20 @ocss884 @eric-haibin-lin @chenhaiq @techkang
|
verl/docs/perf/nsight_profiling.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NVIDIA Nsight Systems profiling in verl
|
| 2 |
+
|
| 3 |
+
Last updated: 06/20/2025.
|
| 4 |
+
|
| 5 |
+
This guide explains how to use NVIDIA Nsight Systems for profiling verl training runs.
|
| 6 |
+
|
| 7 |
+
## Configuration
|
| 8 |
+
|
| 9 |
+
Profiling in verl can be configured through several parameters in the trainer configuration file (ppo_trainer.yaml or other files like dapo_trainer.yaml):
|
| 10 |
+
|
| 11 |
+
### Prerequisites
|
| 12 |
+
|
| 13 |
+
Nsight Systems version is important, please reference `docker/Dockerfile.vllm.sglang.megatron` for the version we used.
|
| 14 |
+
|
| 15 |
+
### Global profiling control
|
| 16 |
+
|
| 17 |
+
verl has one single controller process and multiple worker processes. Both controller and worker processes can be profiled. Since the controller process can be executed in any nodes in the cluster, there is a message printed in the logging to indicate the controller process node hostname and process id.
|
| 18 |
+
|
| 19 |
+
In `global_profiler`, three new config entries control the profiler behaviors:
|
| 20 |
+
|
| 21 |
+
* **`global_profiler.steps`**. List of step numbers at which profiling should be performed. For example: [1, 2, 5] will profile steps 1, 2, and 5. And ``null`` means no profiling.
|
| 22 |
+
|
| 23 |
+
* **`global_profiler.profile_continuous_steps`**. If true, and the following `global_profiler.discrete==False`, then the continuous steps in `global_profiler.steps` will be combined into one database. For example the above step 1 and 2 are in one database, and 5 in another. If false, every step occupies at least one database. The reason for this config is to observe the program behaviors between steps.
|
| 24 |
+
|
| 25 |
+
Nsys options in controller nodes and worker nodes are configured in `global_profiler.global_tool_config.nsys`:
|
| 26 |
+
|
| 27 |
+
* **`global_profiler.global_tool_config.nsys.controller_nsight_options`**. This config group is for the single controller. All fields in this config group will be just sent to Nsight Systems when Ray starts the controller process. `ppo_trainer.yaml` provides a workable example. Users can reference [Nsight Systems manual](https://docs.nvidia.com/nsight-systems/UserGuide/index.html) and [Ray user guide](https://docs.ray.io/en/latest/ray-observability/user-guides/profiling.html) for more details.
|
| 28 |
+
* **`global_profiler.global_tool_config.nsys.worker_nsight_options`**. This config group is for the worker processes. Similarly all fields in this config group will be just sent to Nsight Systems when Ray starts the controller process. Capture range is used to control the profiler when to start and stop. So `capture-range: "cudaProfilerApi"` is fixed and does not change it. Users can change `capture-range-end` with some accurate calculation or just leave it `null`.
|
| 29 |
+
|
| 30 |
+
### Worker process profiling
|
| 31 |
+
|
| 32 |
+
Verl manages mulitiple RL roles, _Actor_, _Ref_, _Rollout_, _Critic_, _Reward_, which are implemented in different Worker classes. And these workers can be combined into one Ray Actor, running in a process group. Each RL role has its own profiling config group, `profiler`, which consists of three fields:
|
| 33 |
+
|
| 34 |
+
* **`all_ranks` and `ranks`**. When `all_ranks` is set `True` then all ranks will be profiled; when set `False`, `ranks` will be profiled. By default, verl profiles the whole training process in a series ` worker_process_<PID>.<RID>.nsys-rep` files for each process rank. PID is the process ID; RID is the capture range ID.
|
| 35 |
+
* **`discrete`**. When set `False`, all the roles actions in one training step will be dumped in one database. When set `True`, the actions annotated by `DistProfiler.annotate` will be dumped into a discrete database. In this case, each role's action occupies one `<RID>`.
|
| 36 |
+
* **Verl collocate mode**. Verl can combine two Worker sub classes to one Worker Actor. In this case, the user should take care that the combined Workers have consistent `discrete`. The Nsight Systems profiler uses a `torch.cuda.profiler.start()` and `stop()` pair to dump a `<step>` database anyway.
|
| 37 |
+
|
| 38 |
+
### where to find the profiling data
|
| 39 |
+
|
| 40 |
+
By default the `*.nsys-rep` files are saved in the directory `/tmp/ray/session_latest/logs/nsight/` at each node. According to the Ray manual, this default directory is not changeable. ["however, Ray preserves the `--output` option of the default config"](https://docs.ray.io/en/latest/ray-observability/user-guides/profiling.html).
|
| 41 |
+
|
| 42 |
+
Some users may think it is not convenient, but it is understandable that Ray may start hundreds of processes and it would be a big network file system pressure if we save the files in one central place.
|
| 43 |
+
|
| 44 |
+
## Usage Example
|
| 45 |
+
|
| 46 |
+
To enable profiling for specific components and steps, modify your ppo_trainer.yaml like this:
|
| 47 |
+
|
| 48 |
+
### Disable profiler
|
| 49 |
+
|
| 50 |
+
```yaml
|
| 51 |
+
profiler:
|
| 52 |
+
steps: null # disable profile
|
| 53 |
+
```
|
| 54 |
+
|
| 55 |
+
### Enable profiler and one database for one training step
|
| 56 |
+
|
| 57 |
+
```yaml
|
| 58 |
+
global_profiler:
|
| 59 |
+
steps: [1, 2, 5]
|
| 60 |
+
discrete: False
|
| 61 |
+
actor_rollout_ref:
|
| 62 |
+
actor:
|
| 63 |
+
profiler:
|
| 64 |
+
enable: True
|
| 65 |
+
all_ranks: True
|
| 66 |
+
# rollout & ref follow actor settings
|
| 67 |
+
critic:
|
| 68 |
+
profiler:
|
| 69 |
+
enable: True
|
| 70 |
+
all_ranks: True
|
| 71 |
+
reward_model:
|
| 72 |
+
profiler:
|
| 73 |
+
enable: True
|
| 74 |
+
all_ranks: True
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
### Enable profiler and multiple databases for one training step
|
| 78 |
+
|
| 79 |
+
```yaml
|
| 80 |
+
profiler:
|
| 81 |
+
steps: [1, 2, 5]
|
| 82 |
+
discrete: True
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
## Profiling Output
|
| 86 |
+
|
| 87 |
+
When profiling is enabled, verl will generate Nsight Systems profiles for the specified components and steps. The profiles will include:
|
| 88 |
+
|
| 89 |
+
- CUDA kernel execution
|
| 90 |
+
- Memory operations
|
| 91 |
+
- CPU-GPU synchronization
|
| 92 |
+
- NVTX markers for key operations
|
| 93 |
+
|
| 94 |
+
Nsight Systems supports multi-report view, to open multiple databases together. In this mode, different processes and steps can be aligned in one time line for better analysis.
|
verl/docs/perf/perf_tuning.rst
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Performance Tuning Guide
|
| 2 |
+
==============================
|
| 3 |
+
|
| 4 |
+
Last updated: 07/17/2025.
|
| 5 |
+
|
| 6 |
+
Author: `Guangming Sheng <https://github.com/PeterSH6>`_, `Jiali Zheng <https://github.com/CurryRice233>`_
|
| 7 |
+
|
| 8 |
+
In this section, we will discuss how to tune the performance of all the stages in verl, including:
|
| 9 |
+
|
| 10 |
+
1. Rollout generation throughput.
|
| 11 |
+
|
| 12 |
+
2. Enable ``use_remove_padding=True`` for sequence packing (i.e., data packing and remove padding).
|
| 13 |
+
|
| 14 |
+
3. Batch size tuning for forward and backward computation
|
| 15 |
+
|
| 16 |
+
4. Enable ``use_dynamic_bsz=True`` for higher throughput.
|
| 17 |
+
|
| 18 |
+
5. Utilize Ulysses Sequence Parallel for Long Context Training
|
| 19 |
+
|
| 20 |
+
6. LigerKernel for SFT performance optimization
|
| 21 |
+
|
| 22 |
+
7. Forward prefetch in FSDP training backend
|
| 23 |
+
|
| 24 |
+
8. Memory optimization for entropy calculation from logits
|
| 25 |
+
|
| 26 |
+
Rollout Generation Tuning
|
| 27 |
+
--------------------------
|
| 28 |
+
|
| 29 |
+
verl currently supports two rollout backends: vLLM and TGI (with SGLang support coming soon).
|
| 30 |
+
|
| 31 |
+
Below are key factors for tuning vLLM-based rollout. Before tuning, we recommend setting ``actor_rollout_ref.rollout.disable_log_stats=False`` so that rollout statistics are logged.
|
| 32 |
+
|
| 33 |
+
- Increase ``gpu_memory_utilization``.
|
| 34 |
+
|
| 35 |
+
- For vLLM v0.7.0 and later, the vLLM instance will only use gpu_memory_utilization of the **total** memory.
|
| 36 |
+
- For SGLang, it's the fraction of the free GPU memory used for **static** memory like model weights and KV cache. However, the remaining (1-gpu_memory_utilization) will also be used during inference.
|
| 37 |
+
|
| 38 |
+
However, if model parameters and optimizer states are not offloaded, using too high a fraction can lead to OOM.
|
| 39 |
+
A value between 0.5 and 0.7 often strikes a good balance between high throughput and avoiding OOM.
|
| 40 |
+
|
| 41 |
+
Note: since the definition of ``gpu_memory_utilization`` varies across inference engines, a value that works well for one engine may cause OOM for another.
|
| 42 |
+
|
| 43 |
+
- Adjust ``max_num_seqs`` or ``max_num_batched_tokens``.
|
| 44 |
+
If the GPU cache utilization is relatively low in the log, increase ``max_num_seqs`` or ``max_num_batched_tokens``
|
| 45 |
+
can enlarge the effective batch size in the decoding stage, allowing more concurrent requests per batch.
|
| 46 |
+
We recommend setting ``max_num_batched_tokens > 2048`` for higher throughput.
|
| 47 |
+
|
| 48 |
+
- Use a smaller ``tensor_parallel_size``.
|
| 49 |
+
When GPU resources allow, a smaller tensor parallel size spawns more vLLM replicas.
|
| 50 |
+
Data parallelism (DP) can yield higher throughput than tensor parallelism (TP), but also increases KVCache consumption.
|
| 51 |
+
Carefully balance the trade-off between more replicas and higher memory usage.
|
| 52 |
+
Our experiment in Sec. 8.4 of `HybridFlow paper <https://arxiv.org/pdf/2409.19256v2>`_ evaluate this trade-off.
|
| 53 |
+
|
| 54 |
+
- Balance performance and memory using ``cudagraph_capture_sizes``.
|
| 55 |
+
If ``cudagraph_capture_sizes`` is set, vLLM will try to capture the model execution graph for different batch sizes.
|
| 56 |
+
Since cudagraph memory can not be offloaded to cpu, The memory stay in gpu when update actor is running.
|
| 57 |
+
Using smaller batch sizes can avoid OOM but slightly reduce throughput.
|
| 58 |
+
Must to set ``enforce_eager=False`` to use ``cudagraph_capture_sizes``.
|
| 59 |
+
|
| 60 |
+
More tuning details such as dealing with Preemption and Chunked-prefill
|
| 61 |
+
can be found in `vLLM official tuning guide <https://docs.vllm.ai/en/latest/performance/optimization.html>`_
|
| 62 |
+
|
| 63 |
+
For optimal performance, we recommend using vLLM v0.8.3 or later. See https://github.com/volcengine/verl/blob/main/docs/README_vllm0.8.md for details.
|
| 64 |
+
|
| 65 |
+
Enable remove padding (sequence packing)
|
| 66 |
+
-----------------------------------------
|
| 67 |
+
|
| 68 |
+
Currently, for llama, mistral, gemma1 and qwen based models, users can enable `use_remove_padding=True` to utilize the
|
| 69 |
+
sequence packing implementation provided by transformers library.
|
| 70 |
+
|
| 71 |
+
For other models, transformers library may also support it but we haven't tested it yet.
|
| 72 |
+
Users can add the desired model config to the `test_transformer.py <https://github.com/volcengine/verl/blob/main/tests/models/test_transformer.py#L24>`_ file.
|
| 73 |
+
And test its functionality by running the following command:
|
| 74 |
+
|
| 75 |
+
.. code-block:: bash
|
| 76 |
+
|
| 77 |
+
pytest -s tests/models/test_transformer.py
|
| 78 |
+
|
| 79 |
+
If the test passes, you can add your desired model into the model `registry.py <https://github.com/volcengine/verl/blob/main/verl/models/registry.py#L24>`_ file.
|
| 80 |
+
Then, you can enjoy the performance boost of sequence packing
|
| 81 |
+
and welcome to PR your tested model to verl!
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
Batch Size Tuning
|
| 85 |
+
-----------------
|
| 86 |
+
|
| 87 |
+
To achieve higher throughput in experience preparation (i.e., model fwd) and model update (i.e., actor/critic fwd/bwd),
|
| 88 |
+
users may need to tune the ``*micro_batch_size_per_gpu`` for different computation.
|
| 89 |
+
|
| 90 |
+
In verl, the core principle for setting batch sizes is:
|
| 91 |
+
|
| 92 |
+
- **Algorithmic metrics** (train batch size, PPO mini-batch size) are *global* (from a single-controller perspective),
|
| 93 |
+
normalized in each worker. See the `normalization code <https://github.com/volcengine/verl/blob/main/verl/workers/fsdp_workers.py#L120-L122>`_.
|
| 94 |
+
|
| 95 |
+
- **Performance-related parameters** (micro batch size, max token length for dynamic batch size) are *local* parameters that define the per-GPU data allocations.
|
| 96 |
+
See the `normalization code <https://github.com/volcengine/verl/blob/main/verl/workers/fsdp_workers.py#L127>`_.
|
| 97 |
+
|
| 98 |
+
.. note:: In your training script, please use ``*micro_batch_size_per_gpu`` instead of ``*micro_batch_size``.
|
| 99 |
+
So that you don't need to consider the normalization of the ``micro_batch_size`` and ``micro_batch_size`` will be deprecated.
|
| 100 |
+
|
| 101 |
+
Batch Size Tuning tips
|
| 102 |
+
""""""""""""""""""""""
|
| 103 |
+
|
| 104 |
+
Therefore, users may need to tune the ``*micro_batch_size_per_gpu`` to accelerate training. Here're some tips:
|
| 105 |
+
|
| 106 |
+
1. **Enable gradient checkpointing**:
|
| 107 |
+
Set ``actor_rollout_ref.model.enable_gradient_checkpointing=True`` and ``critic.model.enable_gradient_checkpointing=True``.
|
| 108 |
+
This often allows for larger micro-batch sizes and will be beneficial for large mini-batch training.
|
| 109 |
+
|
| 110 |
+
2. Increase the ``*micro_batch_size_per_gpu`` as much as possible till equals to normalized ``mini_batch_size``.
|
| 111 |
+
|
| 112 |
+
3. **Use larger forward-only parameters**:
|
| 113 |
+
Forward only parameter, such as ``actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu``,
|
| 114 |
+
``actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu``, ``critic.forward_micro_batch_size_per_gpu`` could be larger (e.g., 2x) than training related micro batch sizes,
|
| 115 |
+
such as ``actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu``, ``critic.ppo_micro_batch_size_per_gpu``.
|
| 116 |
+
|
| 117 |
+
4. **Allow larger micro-batch sizes for Critic and Reward models**:
|
| 118 |
+
micro batch size of Critic and Reward model could be larger than Actor model. This is because the actor model has much larger vocab size in the final layer.
|
| 119 |
+
|
| 120 |
+
5. **Enable activation offloading**:
|
| 121 |
+
Set ``actor_rollout_ref.model.enable_activation_offload=True`` and ``critic.model.enable_activation_offload=True``.
|
| 122 |
+
This often works together with gradient checkpointing to get larger micro-batch sizes and it's only available in FSDP backend now.
|
| 123 |
+
|
| 124 |
+
Tuning for Dynamic Batch Size
|
| 125 |
+
-----------------------------
|
| 126 |
+
|
| 127 |
+
Dynamic batch size is a technique that allows the model to process similar number of tokens in a single forward pass (with different actual batch sizes).
|
| 128 |
+
This can significantly improve the training efficiency and reduce the memory usage.
|
| 129 |
+
|
| 130 |
+
To utilize this technique, users can set ``use_dynamic_bsz=True`` in actor, ref, critic and reward models.
|
| 131 |
+
With ``use_dynamic_bsz=True``, users don't need to tune ``*micro_batch_size_per_gpu``.
|
| 132 |
+
Instead, users should tune the following parameters:
|
| 133 |
+
|
| 134 |
+
- ``actor_rollout_ref.actor.ppo_max_token_len_per_gpu``, ``critic.ppo_max_token_len_per_gpu``:
|
| 135 |
+
The maximum number of tokens to be processed in fwd and bwd of ``update_policy`` and ``update_critic``.
|
| 136 |
+
|
| 137 |
+
- ``actor_rollout_ref.ref.log_prob_max_token_len_per_gpu`` and ``actor_rollout_ref.rollout.log_prob_max_token_len_per_gpu``:
|
| 138 |
+
The maximum number of tokens to be processed in a the fwd computation of ``compute_log_prob`` and ``compute_ref_log_prob``.
|
| 139 |
+
|
| 140 |
+
- ``critic.forward_micro_batch_size_per_gpu``, ``reward_model.forward_micro_batch_size_per_gpu``:
|
| 141 |
+
The maximum number of tokens to be processed in a the fwd computation of ``compute_values``, ``compute_rm_score``.
|
| 142 |
+
|
| 143 |
+
Dynamic Batch Size Tuning tips
|
| 144 |
+
""""""""""""""""""""""""""""""
|
| 145 |
+
|
| 146 |
+
Here're some tips to tune the above parameters:
|
| 147 |
+
|
| 148 |
+
1. **Increase** ``actor_rollout_ref.actor.ppo_max_token_len_per_gpu``
|
| 149 |
+
Make it at least 2 x (max_prompt_length + max_response_length). We set it to 3x in `run_qwen2-7b_rm_seq_balance.sh <https://github.com/volcengine/verl/blob/main/examples/ppo_trainer/run_qwen2-7b_rm_seq_balance.sh#L25>`_.
|
| 150 |
+
Try to increase it to get higher throughput.
|
| 151 |
+
|
| 152 |
+
2. **Forward-only parameters can be larger**:
|
| 153 |
+
Similar to the non-dynamic-batch scenario, forward-only token limits can exceed those used in forward/backward operations.
|
| 154 |
+
|
| 155 |
+
3. **Use larger limits for Critic and Reward models**:
|
| 156 |
+
Critic and Reward parameters can be set at least 2× the Actor’s limits. For instance, we set them to 4× here:
|
| 157 |
+
`run_qwen2-7b_rm_seq_balance.sh <https://github.com/volcengine/verl/blob/main/examples/ppo_trainer/run_qwen2-7b_rm_seq_balance.sh#L40>`_
|
| 158 |
+
|
| 159 |
+
.. :math:`\text{critic.ppo_max_token_len_per_gpu} = 2 \times \text{actor.ppo_max_token_len_per_gpu})`.
|
| 160 |
+
|
| 161 |
+
Ulysses Sequence Parallel for Long Context Training
|
| 162 |
+
----------------------------------------------------
|
| 163 |
+
|
| 164 |
+
To utilize this technique, users can set ``ulysses_sequence_parallel_size>1`` in actor, ref, critic and reward models.
|
| 165 |
+
|
| 166 |
+
We support different model utilize different ulysses_sequence_parallel_size sizes.
|
| 167 |
+
|
| 168 |
+
To train long sequence (>32k), users may need to decrease the ``*micro_batch_size_per_gpu`` and ``*max_token_len_per_gpu`` to avoid OOM.
|
| 169 |
+
|
| 170 |
+
LigerKernel for SFT
|
| 171 |
+
----------------------
|
| 172 |
+
|
| 173 |
+
LigerKernel is a high-performance kernel for Supervised Fine-Tuning (SFT) that can improve training efficiency. To enable LigerKernel in your SFT training:
|
| 174 |
+
|
| 175 |
+
1. Install liger-kernel via ``pip3 install liger-kernel``. In your SFT configuration file (e.g., ``verl/trainer/config/sft_trainer.yaml``), set the ``use_liger`` parameter:
|
| 176 |
+
|
| 177 |
+
.. code-block:: yaml
|
| 178 |
+
|
| 179 |
+
model:
|
| 180 |
+
use_liger: True # Enable LigerKernel for SFT
|
| 181 |
+
|
| 182 |
+
2. The default value is ``False``. Enable it only when you want to use LigerKernel's optimizations.
|
| 183 |
+
|
| 184 |
+
3. LigerKernel is particularly useful for improving training performance in SFT scenarios.
|
| 185 |
+
|
| 186 |
+
Forward prefetch in FSDP training backend
|
| 187 |
+
----------------------
|
| 188 |
+
|
| 189 |
+
During the training phase, users can enable forward prefetching in FSDP by setting ``fsdp_config.forward_prefetch=True``. For example, ``actor_rollout_ref.actor.fsdp_config.forward_prefetch=True``. This configuration prefetches the next forward-pass all-gather operation before completing the current forward computation, overlapping communication with computation and improving efficiency. For further details, refer to the `FSDP forward_prefetch <https://docs.pytorch.org/docs/stable/fsdp.html#module-torch.distributed.fsdp>`_ documentation.
|
| 190 |
+
|
| 191 |
+
.. note::
|
| 192 |
+
Backward prefetch is unsupported because the ``BACKWARD_POST`` policy may prefetch incorrectly in nested-module cases. For details, see the `FSDP documentation <https://github.com/pytorch/torchtitan/blob/main/docs/fsdp.md?plain=1#L70>`_
|
| 193 |
+
|
| 194 |
+
Migrating to FSDP2
|
| 195 |
+
----------------------
|
| 196 |
+
|
| 197 |
+
FSDP2 offers notable improvements over FSDP1. According to `PyTorch TorchTitan benchmarks <https://arxiv.org/abs/2410.06511v1>`_:
|
| 198 |
+
|
| 199 |
+
- 7% lower GPU memory usage on average
|
| 200 |
+
- 1.5% throughput improvement with BF16 training
|
| 201 |
+
- Better composability with DTensor and per-parameter sharding
|
| 202 |
+
|
| 203 |
+
**Enabling FSDP2 in VERL:**
|
| 204 |
+
|
| 205 |
+
.. code-block:: python
|
| 206 |
+
|
| 207 |
+
# Enable FSDP2 in actor configuration
|
| 208 |
+
actor_rollout_ref.actor.strategy="fsdp2"
|
| 209 |
+
|
| 210 |
+
.. note::
|
| 211 |
+
FSDP2 requires PyTorch 2.1+ and is recommended for models with transformer architecture.
|
| 212 |
+
|
| 213 |
+
Memory optimization for entropy calculation from logits
|
| 214 |
+
----------------------
|
| 215 |
+
|
| 216 |
+
The ``logits`` tensor (typically of shape ``[bsz*seq_len, voc]``) can consume significant memory. When using ``compute_entropy_from_logits``, memory usage reaches approximately ``[bsz*seq_len, voc] × (4 bytes (float32) + 2 bytes (autocast for softmax+logsumexp) + 1 byte (softmax output))``.
|
| 217 |
+
|
| 218 |
+
To reduce this memory peak, enable chunked computation by setting:
|
| 219 |
+
``actor_rollout_ref.ref.entropy_from_logits_with_chunking = True``
|
| 220 |
+
This processes the tensor in chunks of shape ``[chunk_size, voc]`` (e.g., 2048) rather than the full sequence length, exclusively during the model's forward pass.
|
| 221 |
+
|
| 222 |
+
Additionally, during training, standard gradient checkpointing (``enable_gradient_checkpointing=True``) does not apply to entropy calculations. To reduce memory peaks in this context, set:
|
| 223 |
+
``actor_rollout_ref.actor.entropy_checkpointing = True``
|
| 224 |
+
This enables entropy recomputation specifically for the entropy calculation, lowering memory usage during training.
|
verl/docs/perf/verl_profiler_system.md
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# verl Profiler System
|
| 2 |
+
|
| 3 |
+
Last updated: 08/18/2025.
|
| 4 |
+
|
| 5 |
+
## Architecture
|
| 6 |
+
|
| 7 |
+
The architecture of verl profiler system is like below:
|
| 8 |
+
|
| 9 |
+

|
| 10 |
+
|
| 11 |
+
There is a global profiler and tool configuration to set some common config in single controller level, deciding
|
| 12 |
+
|
| 13 |
+
- `tool`: which tool to use
|
| 14 |
+
- `steps`: which steps to profile
|
| 15 |
+
- `save_path`: results saving path
|
| 16 |
+
|
| 17 |
+
When some tool need to profile behavior of each role, configurations in role-level is needed:
|
| 18 |
+
|
| 19 |
+
- `tool`: which tool to use
|
| 20 |
+
- `enable`: whether enable profiling on this role
|
| 21 |
+
- rank info: `all_ranks` and `rank` to decide which rank to profile or log output
|
| 22 |
+
|
| 23 |
+
For tool config in role-level, there are some detailed behavior needed to control, like the `discrete` mode in nsys profiler.
|
| 24 |
+
|
| 25 |
+
Every role has a profiler config, and by default, rollout/ref/reward models follow the Actor's behavior.
|
| 26 |
+
|
| 27 |
+
## To Add a new profiling tool
|
| 28 |
+
|
| 29 |
+
New added profiling tool shall reuse the current APIs as much as possible.
|
| 30 |
+
|
| 31 |
+
1. The logic of **whether to use the tool**: `tool == [new tool]`.
|
| 32 |
+
2. Add the global and local tool config to `ppo_trainer.yaml`/`ppo_megatron_trainer.yaml` and each `[role].yaml`, under `global_tool_config.[new tool]` and `tool_config.[new tool]`
|
| 33 |
+
3. The tool config should be implemented in `verl/utils/profiler/config.py`, inherit the `BaseConfig` class.
|
| 34 |
+
4. Implement profiling tool initialization logic using configurations in `global_profiler.global_tool_config.[new tool]` and the results saving logics (can also save in role-level profile)
|
| 35 |
+
5. For role function-level profiling, please follow the nsys profiler way in `nvtx_profiler.py`, implement a profiler class inherit `DistProfiler` and import new profiler in `verl/utils/profiler/__init__.py`
|
| 36 |
+
6. Add unit test and examples for others to use in convinience.
|
verl/docs/preparation/prepare_data.rst
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Prepare Data for Post-Training
|
| 2 |
+
========================================
|
| 3 |
+
|
| 4 |
+
Last updated: 02/09/2025.
|
| 5 |
+
|
| 6 |
+
Before starting the post-training job, we need to prepare the data for
|
| 7 |
+
the policy training. The data should be stored in the parquet format.
|
| 8 |
+
|
| 9 |
+
We provide several data preprocess scripts for different datasets,
|
| 10 |
+
including GSM8K, MATH, HelloSwag, Full_hh_rlhf. To prepare other datasets, we need
|
| 11 |
+
to follow the following steps: The data preprocess script can be divided
|
| 12 |
+
into two parts:
|
| 13 |
+
|
| 14 |
+
1. The first part is the common part, which loads the dataset from
|
| 15 |
+
huggingface's ``datasets`` package. Then preprocess the datasets with
|
| 16 |
+
the ``make_map_fn`` and then store in the parquet format.
|
| 17 |
+
|
| 18 |
+
.. code:: python
|
| 19 |
+
|
| 20 |
+
import re
|
| 21 |
+
import os
|
| 22 |
+
import datasets
|
| 23 |
+
|
| 24 |
+
from verl.utils.hdfs_io import copy, makedirs
|
| 25 |
+
import argparse
|
| 26 |
+
|
| 27 |
+
# To extract the solution for each prompts in the dataset
|
| 28 |
+
# def extract_solution(solution_str):
|
| 29 |
+
# ...
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
if __name__ == '__main__':
|
| 33 |
+
parser = argparse.ArgumentParser()
|
| 34 |
+
parser.add_argument('--local_dir', default='/opt/tiger/gsm8k')
|
| 35 |
+
parser.add_argument('--hdfs_dir', default=None)
|
| 36 |
+
|
| 37 |
+
args = parser.parse_args()
|
| 38 |
+
|
| 39 |
+
num_few_shot = 5
|
| 40 |
+
data_source = 'openai/gsm8k'
|
| 41 |
+
|
| 42 |
+
dataset = datasets.load_dataset(data_source, 'main')
|
| 43 |
+
|
| 44 |
+
train_dataset = dataset['train']
|
| 45 |
+
test_dataset = dataset['test']
|
| 46 |
+
|
| 47 |
+
# Construct a `def make_map_fn(split)` for the corresponding datasets.
|
| 48 |
+
# ...
|
| 49 |
+
|
| 50 |
+
train_dataset = train_dataset.map(function=make_map_fn('train'), with_indices=True)
|
| 51 |
+
test_dataset = test_dataset.map(function=make_map_fn('test'), with_indices=True)
|
| 52 |
+
|
| 53 |
+
local_dir = args.local_dir
|
| 54 |
+
hdfs_dir = args.hdfs_dir
|
| 55 |
+
|
| 56 |
+
train_dataset.to_parquet(os.path.join(local_dir, 'train.parquet'))
|
| 57 |
+
test_dataset.to_parquet(os.path.join(local_dir, 'test.parquet'))
|
| 58 |
+
|
| 59 |
+
makedirs(hdfs_dir)
|
| 60 |
+
|
| 61 |
+
copy(src=local_dir, dst=hdfs_dir)
|
| 62 |
+
|
| 63 |
+
2. The users are required to implement the ``make_map_fn()`` function
|
| 64 |
+
(as well as the ``extract_solution``) on their own to support
|
| 65 |
+
different datasets or tasks.
|
| 66 |
+
|
| 67 |
+
We already implemented the data preprocess of GSM8k, MATH, Hellaswag and Full_hh_rlhf
|
| 68 |
+
datasets. And we take the GSM8k dataset as an example:
|
| 69 |
+
|
| 70 |
+
**GSM8K**
|
| 71 |
+
|
| 72 |
+
In the ``make_map_fn``, each data field should consist of the following
|
| 73 |
+
5 fields:
|
| 74 |
+
|
| 75 |
+
1. ``data_source``: The name of the dataset. To index the corresponding
|
| 76 |
+
reward function in the ``RewardModel``
|
| 77 |
+
2. ``prompt``: This field should be constructed in the format of
|
| 78 |
+
huggingface chat_template. The tokenizer in ``RLHFDataset`` will
|
| 79 |
+
apply chat template and tokenize the prompt.
|
| 80 |
+
3. ``ability``: Define the task category.
|
| 81 |
+
4. ``reward_model``: Currently, we only utilize the ``ground_truth``
|
| 82 |
+
field during evaluation. The ``ground_truth`` is computed by the
|
| 83 |
+
``extract_solution`` function. **NOTED** that the implementation of
|
| 84 |
+
the corresponding reward function should align with this extracted
|
| 85 |
+
``ground_truth``.
|
| 86 |
+
5. ``extra_info``: Record some information of the current prompt. Not
|
| 87 |
+
use for now.
|
| 88 |
+
|
| 89 |
+
.. code:: python
|
| 90 |
+
|
| 91 |
+
def extract_solution(solution_str):
|
| 92 |
+
solution = re.search("#### (\\-?[0-9\\.\\,]+)", solution_str) # extract the solution after ####
|
| 93 |
+
assert solution is not None
|
| 94 |
+
final_solution = solution.group(0)
|
| 95 |
+
final_solution = final_solution.split('#### ')[1].replace(',', '')
|
| 96 |
+
return final_solution
|
| 97 |
+
|
| 98 |
+
instruction_following = "Let's think step by step and output the final answer after \"####\"."
|
| 99 |
+
|
| 100 |
+
# add a row to each data item that represents a unique id
|
| 101 |
+
def make_map_fn(split):
|
| 102 |
+
|
| 103 |
+
def process_fn(example, idx):
|
| 104 |
+
question = example.pop('question')
|
| 105 |
+
|
| 106 |
+
question = question + ' ' + instruction_following
|
| 107 |
+
|
| 108 |
+
answer = example.pop('answer')
|
| 109 |
+
solution = extract_solution(answer)
|
| 110 |
+
data = {
|
| 111 |
+
"data_source": data_source,
|
| 112 |
+
"prompt": [{
|
| 113 |
+
"role": "user",
|
| 114 |
+
"content": question
|
| 115 |
+
}],
|
| 116 |
+
"ability": "math",
|
| 117 |
+
"reward_model": {
|
| 118 |
+
"style": "rule",
|
| 119 |
+
"ground_truth": solution
|
| 120 |
+
},
|
| 121 |
+
"extra_info": {
|
| 122 |
+
'split': split,
|
| 123 |
+
'index': idx
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
return data
|
| 127 |
+
|
| 128 |
+
return process_fn
|
verl/docs/preparation/reward_function.rst
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Implement Reward Function for Dataset
|
| 2 |
+
======================================
|
| 3 |
+
|
| 4 |
+
Last updated: 06/02/2025.
|
| 5 |
+
|
| 6 |
+
For each dataset, we need to implement a reward function or utilize a reward model to compute the rewards for the generated responses.
|
| 7 |
+
We already pre-implemented some reward functions in `reward_score directory <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score>`_.
|
| 8 |
+
You can also use customized reward functions.
|
| 9 |
+
|
| 10 |
+
Currently, we support reward functions for GSM8k and MATH datasets. For RLHF datasets (e.g.,
|
| 11 |
+
full_hh_rlhf) and Code Generation (e.g., APPS), we utilize reward model
|
| 12 |
+
and SandBox (will opensource soon) for evaluation respectively.
|
| 13 |
+
|
| 14 |
+
RewardManager
|
| 15 |
+
-------------
|
| 16 |
+
|
| 17 |
+
In the entrypoint of the PPO Post-Training script `main_ppo.py <https://github.com/volcengine/verl/blob/main/verl/trainer/main_ppo.py#L33>`_,
|
| 18 |
+
we implement a ``RewardManager`` that utilize pre-implemented reward functions to compute the scores for each response.
|
| 19 |
+
|
| 20 |
+
In the ``RewardManager``, we implemented a ``__call__`` function to
|
| 21 |
+
compute the score for each response.
|
| 22 |
+
All the reward functions are executed by ``compute_score_fn``.
|
| 23 |
+
The input is a ``DataProto``, which includes:
|
| 24 |
+
|
| 25 |
+
- ``input_ids``, ``attention_mask``: ``input_ids`` and ``attention_mask`` after applying
|
| 26 |
+
chat_template, including prompt and response
|
| 27 |
+
- ``responses``: response tokens
|
| 28 |
+
- ``ground_truth``: The ground truth string of the current prompt.
|
| 29 |
+
Stored in ``non_tensor_batch`` in the ``DataProto``, which should be
|
| 30 |
+
preprocessed in the parquet files.
|
| 31 |
+
- ``data_source``: The dataset name of the current prompt. Stored in
|
| 32 |
+
``non_tensor_batch`` in the ``DataProto``, which should be
|
| 33 |
+
preprocessed in the parquet files.
|
| 34 |
+
|
| 35 |
+
After detokenize the responses, the responses string and the ground
|
| 36 |
+
truth string will be input to the ``compute_score_fn`` to compute the
|
| 37 |
+
score for each response.
|
| 38 |
+
|
| 39 |
+
Reward Functions
|
| 40 |
+
----------------
|
| 41 |
+
|
| 42 |
+
Pre-implemented
|
| 43 |
+
~~~~~~~~~~~~~~~
|
| 44 |
+
|
| 45 |
+
We already pre-implemented some reward functions in `reward_score directory <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score>`_.
|
| 46 |
+
|
| 47 |
+
- In the `GSM8k example <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score/gsm8k.py>`_, we
|
| 48 |
+
force the response to output the final answer after four ####, then
|
| 49 |
+
use string matching to compare with the ground truth. If completely
|
| 50 |
+
correct, score 1 point; if the format is correct, score 0.1 points; if
|
| 51 |
+
the format is incorrect, score 0 points.
|
| 52 |
+
- In the `MATH example <https://github.com/volcengine/verl/blob/main/verl/utils/reward_score/math.py>`_, we follow
|
| 53 |
+
the implementation in `lm-evaluation-harness repository <https://github.com/EleutherAI/lm-evaluation-harness/blob/main/lm_eval/tasks/hendrycks_math/utils.py>`_.
|
| 54 |
+
|
| 55 |
+
Customized
|
| 56 |
+
~~~~~~~~~~
|
| 57 |
+
|
| 58 |
+
You can implement customized reward functions in a separate file and specify them using ``custom_reward_function.path`` and ``custom_reward_function.name``. For the set of them, please refer to :ref:`config-explain-page`.
|
| 59 |
+
|
| 60 |
+
The parameters of your reward function should be ``data_source``, ``solution_str``, ``ground_truth``, and ``extra_info``.
|
| 61 |
+
For example:
|
| 62 |
+
|
| 63 |
+
.. code:: python
|
| 64 |
+
|
| 65 |
+
def my_reward_fn(data_source, solution_str, ground_truth, extra_info=None):
|
| 66 |
+
return len(solution_str)/100
|
| 67 |
+
|
| 68 |
+
If you are testing only a single customized reward function, you can simply name it 'compute_score' and leave ``custom_reward_function.name`` unset.
|
| 69 |
+
|
| 70 |
+
To run multiple tests with different customized reward functions, you can modify both ``custom_reward_function.path`` and ``custom_reward_function.name`` for each trial.
|
| 71 |
+
For instance, you might create a single `my_reward.py` file and implement multiple reward functions within it. This way, for different trials, you only need to adjust ``custom_reward_function.name``, making it more convenient to conduct multiple tests within scripts.
|
verl/docs/sglang_multiturn/interaction_system.rst
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Interaction System for Multi-turn RL Training
|
| 2 |
+
=============================================
|
| 3 |
+
|
| 4 |
+
Last updated: 06/25/2025.
|
| 5 |
+
|
| 6 |
+
Overview
|
| 7 |
+
--------
|
| 8 |
+
|
| 9 |
+
The verl interaction system enables dynamic, multi-turn conversational feedback during reinforcement learning training. This system allows models to engage in iterative problem-solving scenarios where interaction agents can provide corrective feedback, guidance, or evaluation based on the model's responses.
|
| 10 |
+
|
| 11 |
+
**New in Multi-Interaction Support**: The system now supports multiple named interactions within a single training session, enabling sophisticated training scenarios where different samples can use different interaction strategies. This allows for curriculum learning, domain-specific feedback, and flexible agent switching at the sample level.
|
| 12 |
+
|
| 13 |
+
Key features:
|
| 14 |
+
|
| 15 |
+
- **Async-based Architecture**: Non-blocking interaction processing for distributed training
|
| 16 |
+
- **Instance Management**: Stateful session handling with unique instance IDs for concurrent interactions
|
| 17 |
+
- **SGLang Integration**: Seamless integration with SGLang rollout system for multi-turn conversations
|
| 18 |
+
- **Configuration-driven**: Dynamic agent loading via YAML configuration files
|
| 19 |
+
- **Multi-Interaction Support**: Registry system enabling multiple named interactions per rollout
|
| 20 |
+
- **Sample-Level Selection**: Each sample can specify which interaction to use via configuration
|
| 21 |
+
- **Reward Integration**: Turn-level scoring mechanism integrated with verl's reward system
|
| 22 |
+
|
| 23 |
+
Architecture
|
| 24 |
+
------------
|
| 25 |
+
|
| 26 |
+
The interaction system follows a plugin-based architecture with clear separation of concerns:
|
| 27 |
+
|
| 28 |
+
.. code-block::
|
| 29 |
+
|
| 30 |
+
Interaction Registry System
|
| 31 |
+
↓
|
| 32 |
+
BaseInteraction (Abstract Interface)
|
| 33 |
+
↓
|
| 34 |
+
Multiple Named Interactions (e.g., Gsm8kInteraction, CustomInteraction)
|
| 35 |
+
↓
|
| 36 |
+
SGLang Rollout Integration (interaction_map)
|
| 37 |
+
↓
|
| 38 |
+
Sample-Level Interaction Selection
|
| 39 |
+
↓
|
| 40 |
+
Async Request Lifecycle Management
|
| 41 |
+
|
| 42 |
+
Core Components
|
| 43 |
+
~~~~~~~~~~~~~~~
|
| 44 |
+
|
| 45 |
+
**Interaction Registry System**
|
| 46 |
+
|
| 47 |
+
The interaction registry system allows loading and managing multiple named interactions:
|
| 48 |
+
|
| 49 |
+
.. code-block:: python
|
| 50 |
+
|
| 51 |
+
from verl.interactions.utils.interaction_registry import initialize_interactions_from_config
|
| 52 |
+
|
| 53 |
+
# Load multiple interactions from config
|
| 54 |
+
interaction_map = initialize_interactions_from_config("config.yaml")
|
| 55 |
+
|
| 56 |
+
# Access specific interaction by name
|
| 57 |
+
gsm8k_interaction = interaction_map["gsm8k"]
|
| 58 |
+
custom_interaction = interaction_map["custom_solver"]
|
| 59 |
+
|
| 60 |
+
**BaseInteraction Interface**
|
| 61 |
+
|
| 62 |
+
All interaction agents must implement the ``BaseInteraction`` abstract class:
|
| 63 |
+
|
| 64 |
+
.. code-block:: python
|
| 65 |
+
|
| 66 |
+
from verl.interactions.base import BaseInteraction
|
| 67 |
+
from typing import Dict, Any, List, Tuple, Optional
|
| 68 |
+
|
| 69 |
+
class BaseInteraction:
|
| 70 |
+
def __init__(self, config: Dict[str, Any]):
|
| 71 |
+
self.config = config
|
| 72 |
+
self.name: str = config.get("name", "interaction_agent")
|
| 73 |
+
|
| 74 |
+
async def start_interaction(self, instance_id: Optional[str] = None, **kwargs) -> str:
|
| 75 |
+
"""Initialize interaction session, return instance_id"""
|
| 76 |
+
|
| 77 |
+
async def generate_response(self, instance_id: str, messages: List[Dict[str, Any]], **kwargs) -> Tuple[bool, str, float, Dict[str, Any]]:
|
| 78 |
+
"""Generate response, return (should_terminate, response, score, metadata)"""
|
| 79 |
+
|
| 80 |
+
async def calculate_score(self, instance_id: str, **kwargs) -> float:
|
| 81 |
+
"""Calculate turn-level score for RL training"""
|
| 82 |
+
|
| 83 |
+
async def finalize_interaction(self, instance_id: str, **kwargs) -> None:
|
| 84 |
+
"""Clean up resources"""
|
| 85 |
+
|
| 86 |
+
**Request Lifecycle**
|
| 87 |
+
|
| 88 |
+
The interaction system integrates with SGLang's async rollout via state management:
|
| 89 |
+
|
| 90 |
+
1. ``PENDING`` → Initialize interaction via ``start_interaction()``
|
| 91 |
+
2. ``GENERATING`` → Model generates response
|
| 92 |
+
3. ``INTERACTING`` → Process response via ``generate_response()``
|
| 93 |
+
4. ``GENERATING`` → Continue if not terminated, otherwise ``COMPLETED``
|
| 94 |
+
|
| 95 |
+
Configuration
|
| 96 |
+
-------------
|
| 97 |
+
|
| 98 |
+
**Basic Setup**
|
| 99 |
+
|
| 100 |
+
Enable interaction in your rollout configuration:
|
| 101 |
+
|
| 102 |
+
.. code-block:: yaml
|
| 103 |
+
|
| 104 |
+
actor_rollout_ref:
|
| 105 |
+
rollout:
|
| 106 |
+
multi_turn:
|
| 107 |
+
enable: true
|
| 108 |
+
interaction_config_path: "path/to/interaction_config.yaml"
|
| 109 |
+
max_user_turns: 10
|
| 110 |
+
max_assistant_turns: 10
|
| 111 |
+
|
| 112 |
+
**Interaction Configuration File**
|
| 113 |
+
|
| 114 |
+
Create an interaction configuration file (e.g., ``interaction_config.yaml``):
|
| 115 |
+
|
| 116 |
+
**Single Interaction (Legacy Format)**
|
| 117 |
+
|
| 118 |
+
.. code-block:: yaml
|
| 119 |
+
|
| 120 |
+
interaction:
|
| 121 |
+
- name: "gsm8k"
|
| 122 |
+
class_name: "verl.interactions.gsm8k_interaction.Gsm8kInteraction"
|
| 123 |
+
config: {}
|
| 124 |
+
|
| 125 |
+
**Multiple Interactions (New Format)**
|
| 126 |
+
|
| 127 |
+
.. code-block:: yaml
|
| 128 |
+
|
| 129 |
+
interaction:
|
| 130 |
+
- name: "gsm8k"
|
| 131 |
+
class_name: "verl.interactions.gsm8k_interaction.Gsm8kInteraction"
|
| 132 |
+
config: {}
|
| 133 |
+
- name: "custom_solver"
|
| 134 |
+
class_name: "custom.interactions.CustomInteraction"
|
| 135 |
+
config:
|
| 136 |
+
solver_type: "advanced"
|
| 137 |
+
timeout: 30
|
| 138 |
+
- name: "code_verifier"
|
| 139 |
+
class_name: "verl.interactions.base.BaseInteraction"
|
| 140 |
+
config:
|
| 141 |
+
verification_mode: "strict"
|
| 142 |
+
|
| 143 |
+
**Automatic Name Generation**
|
| 144 |
+
|
| 145 |
+
If no ``name`` field is provided, the system will automatically generate one from the class name:
|
| 146 |
+
|
| 147 |
+
.. code-block:: yaml
|
| 148 |
+
|
| 149 |
+
interaction:
|
| 150 |
+
- class_name: "verl.interactions.gsm8k_interaction.Gsm8kInteraction"
|
| 151 |
+
config: {}
|
| 152 |
+
# Automatically generates name: "gsm8k"
|
| 153 |
+
|
| 154 |
+
The system will dynamically load all specified interaction classes and make them available by name.
|
| 155 |
+
|
| 156 |
+
Implementation Example: GSM8K
|
| 157 |
+
-----------------------------
|
| 158 |
+
|
| 159 |
+
The GSM8K interaction demonstrates a complete implementation for math problem-solving scenarios:
|
| 160 |
+
|
| 161 |
+
.. code-block:: python
|
| 162 |
+
|
| 163 |
+
from verl.interactions.base import BaseInteraction
|
| 164 |
+
from verl.utils.reward_score import gsm8k
|
| 165 |
+
from uuid import uuid4
|
| 166 |
+
|
| 167 |
+
class Gsm8kInteraction(BaseInteraction):
|
| 168 |
+
def __init__(self, config: dict):
|
| 169 |
+
super().__init__(config)
|
| 170 |
+
self._instance_dict = {}
|
| 171 |
+
|
| 172 |
+
async def start_interaction(self, instance_id=None, ground_truth=None, **kwargs):
|
| 173 |
+
if instance_id is None:
|
| 174 |
+
instance_id = str(uuid4())
|
| 175 |
+
self._instance_dict[instance_id] = {
|
| 176 |
+
"response": "",
|
| 177 |
+
"ground_truth": ground_truth,
|
| 178 |
+
"reward": 0.0,
|
| 179 |
+
}
|
| 180 |
+
return instance_id
|
| 181 |
+
|
| 182 |
+
async def generate_response(self, instance_id, messages, **kwargs):
|
| 183 |
+
# Extract last assistant message content
|
| 184 |
+
content = ""
|
| 185 |
+
for item in reversed(messages):
|
| 186 |
+
if item.get("role") == "assistant":
|
| 187 |
+
content = item.get("content", "")
|
| 188 |
+
break
|
| 189 |
+
|
| 190 |
+
# Ensure GSM8K format (#### prefix)
|
| 191 |
+
self._instance_dict[instance_id]["response"] = content
|
| 192 |
+
|
| 193 |
+
reward = await self.calculate_score(instance_id)
|
| 194 |
+
if reward == 1.0:
|
| 195 |
+
return True, "Your response is correct!", 1.0, {}
|
| 196 |
+
else:
|
| 197 |
+
return False, "Your response is incorrect! You need to reflect on your answer and try again.", 0.0, {}
|
| 198 |
+
|
| 199 |
+
async def calculate_score(self, instance_id, **kwargs):
|
| 200 |
+
return gsm8k.compute_score(
|
| 201 |
+
self._instance_dict[instance_id]["response"],
|
| 202 |
+
self._instance_dict[instance_id]["ground_truth"],
|
| 203 |
+
method="strict", format_score=0.0, score=1.0,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
async def finalize_interaction(self, instance_id, **kwargs):
|
| 207 |
+
del self._instance_dict[instance_id]
|
| 208 |
+
|
| 209 |
+
Training Integration
|
| 210 |
+
--------------------
|
| 211 |
+
|
| 212 |
+
**Training Script Configuration**
|
| 213 |
+
|
| 214 |
+
Include interaction configuration in your training command:
|
| 215 |
+
|
| 216 |
+
.. code-block:: bash
|
| 217 |
+
|
| 218 |
+
python3 -m verl.trainer.main_ppo \\
|
| 219 |
+
--config-path="$CONFIG_PATH" \\
|
| 220 |
+
--config-name='gsm8k_multiturn_grpo_w_interaction' \\
|
| 221 |
+
algorithm.adv_estimator=grpo \\
|
| 222 |
+
data.train_batch_size=512 \\
|
| 223 |
+
data.return_raw_chat=True \\
|
| 224 |
+
actor_rollout_ref.rollout.name=sglang \\
|
| 225 |
+
actor_rollout_ref.rollout.multi_turn.interaction_config_path="$PROJECT_DIR/examples/sglang_multiturn/config/interaction_config/gsm8k_interaction_config.yaml" \\
|
| 226 |
+
trainer.total_epochs=15
|
| 227 |
+
|
| 228 |
+
**Data Requirements**
|
| 229 |
+
|
| 230 |
+
Ensure your dataset includes interaction parameters with the ``name`` field for interaction selection:
|
| 231 |
+
|
| 232 |
+
.. code-block:: python
|
| 233 |
+
|
| 234 |
+
# Dataset should include interaction_kwargs in non_tensor_batch
|
| 235 |
+
interaction_kwargs = [
|
| 236 |
+
{"name": "gsm8k", "query": "What is 2+2?", "ground_truth": "4"},
|
| 237 |
+
{"name": "custom_solver", "query": "Solve: x^2 + 5x + 6 = 0", "ground_truth": "x = -2, -3"},
|
| 238 |
+
{"name": "gsm8k", "query": "What is 3+3?", "ground_truth": "6"},
|
| 239 |
+
]
|
| 240 |
+
|
| 241 |
+
**Sample-Level Interaction Selection**
|
| 242 |
+
|
| 243 |
+
Each sample can specify which interaction to use via the ``name`` field. This enables flexible training scenarios where different samples use different interaction strategies:
|
| 244 |
+
|
| 245 |
+
.. code-block:: python
|
| 246 |
+
|
| 247 |
+
# Example: Math problems use GSM8K interaction, code problems use code verifier
|
| 248 |
+
data_samples = [
|
| 249 |
+
{
|
| 250 |
+
"prompt": "What is 15% of 200?",
|
| 251 |
+
"interaction_kwargs": {
|
| 252 |
+
"name": "gsm8k",
|
| 253 |
+
"query": "What is 15% of 200?",
|
| 254 |
+
"ground_truth": "30"
|
| 255 |
+
}
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"prompt": "Write a function to check if a number is prime",
|
| 259 |
+
"interaction_kwargs": {
|
| 260 |
+
"name": "code_verifier",
|
| 261 |
+
"code_type": "python",
|
| 262 |
+
"expected_behavior": "return True for prime numbers"
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
]
|
| 266 |
+
|
| 267 |
+
**Backward Compatibility**
|
| 268 |
+
|
| 269 |
+
If no ``name`` field is provided in ``interaction_kwargs``, the system defaults to ``"gsm8k"`` for backward compatibility.
|
| 270 |
+
|
| 271 |
+
Best Practices
|
| 272 |
+
--------------
|
| 273 |
+
|
| 274 |
+
**Resource Management**
|
| 275 |
+
|
| 276 |
+
- Always implement proper cleanup in ``finalize_interaction()``
|
| 277 |
+
- Use unique instance IDs to avoid conflicts in concurrent training
|
| 278 |
+
- Handle edge cases like empty messages or malformed content
|
| 279 |
+
|
| 280 |
+
**Performance Optimization**
|
| 281 |
+
|
| 282 |
+
- Keep interaction logic lightweight to avoid blocking training
|
| 283 |
+
- Use async/await properly to maintain non-blocking behavior
|
| 284 |
+
- Consider caching expensive computations within interaction instances
|
| 285 |
+
|
| 286 |
+
**Testing**
|
| 287 |
+
|
| 288 |
+
Comprehensive testing is essential for interaction systems:
|
| 289 |
+
|
| 290 |
+
.. code-block:: python
|
| 291 |
+
|
| 292 |
+
import pytest
|
| 293 |
+
from unittest.mock import patch
|
| 294 |
+
|
| 295 |
+
@pytest.mark.asyncio
|
| 296 |
+
async def test_interaction_workflow():
|
| 297 |
+
interaction = YourInteraction({})
|
| 298 |
+
|
| 299 |
+
# Test complete workflow
|
| 300 |
+
instance_id = await interaction.start_interaction(ground_truth="expected_answer")
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
messages = [{"role": "user", "content": "user_content"}, {"role": "assistant", "content": "assistant_content"}]
|
| 304 |
+
should_terminate, response, reward, metadata = await interaction.generate_response(instance_id, messages)
|
| 305 |
+
|
| 306 |
+
assert should_terminate in [True, False]
|
| 307 |
+
assert isinstance(reward, float)
|
| 308 |
+
|
| 309 |
+
await interaction.finalize_interaction(instance_id)
|
| 310 |
+
|
| 311 |
+
Advanced Usage
|
| 312 |
+
--------------
|
| 313 |
+
|
| 314 |
+
**Multi-Interaction Training Strategies**
|
| 315 |
+
|
| 316 |
+
You can design sophisticated training scenarios using multiple interactions:
|
| 317 |
+
|
| 318 |
+
.. code-block:: python
|
| 319 |
+
|
| 320 |
+
# Example: Progressive difficulty with different interaction agents
|
| 321 |
+
class MathTrainingPipeline:
|
| 322 |
+
def create_interaction_config(self):
|
| 323 |
+
return {
|
| 324 |
+
"interaction": [
|
| 325 |
+
{
|
| 326 |
+
"name": "basic_math",
|
| 327 |
+
"class_name": "verl.interactions.gsm8k_interaction.Gsm8kInteraction",
|
| 328 |
+
"config": {"difficulty": "easy"}
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"name": "advanced_math",
|
| 332 |
+
"class_name": "custom.interactions.AdvancedMathInteraction",
|
| 333 |
+
"config": {"difficulty": "hard", "allow_hints": True}
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"name": "competition_math",
|
| 337 |
+
"class_name": "custom.interactions.CompetitionMathInteraction",
|
| 338 |
+
"config": {"time_limit": 300, "show_steps": False}
|
| 339 |
+
}
|
| 340 |
+
]
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
def create_curriculum_data(self, epoch):
|
| 344 |
+
if epoch < 5:
|
| 345 |
+
return [{"name": "basic_math", ...} for _ in samples]
|
| 346 |
+
elif epoch < 10:
|
| 347 |
+
return [{"name": "advanced_math", ...} for _ in samples]
|
| 348 |
+
else:
|
| 349 |
+
return [{"name": "competition_math", ...} for _ in samples]
|
| 350 |
+
|
| 351 |
+
**Custom Scoring Functions**
|
| 352 |
+
|
| 353 |
+
You can integrate custom reward functions:
|
| 354 |
+
|
| 355 |
+
.. code-block:: python
|
| 356 |
+
|
| 357 |
+
async def calculate_score(self, instance_id, **kwargs):
|
| 358 |
+
response = self._instance_dict[instance_id]["response"]
|
| 359 |
+
ground_truth = self._instance_dict[instance_id]["ground_truth"]
|
| 360 |
+
|
| 361 |
+
# Custom evaluation logic
|
| 362 |
+
if custom_evaluation_function(response, ground_truth):
|
| 363 |
+
return 1.0
|
| 364 |
+
else:
|
| 365 |
+
return 0.0
|
| 366 |
+
|
| 367 |
+
**Multi-step Interactions**
|
| 368 |
+
|
| 369 |
+
For complex scenarios requiring multiple feedback rounds:
|
| 370 |
+
|
| 371 |
+
.. code-block:: python
|
| 372 |
+
|
| 373 |
+
async def generate_response(self, instance_id, messages, **kwargs):
|
| 374 |
+
instance = self._instance_dict[instance_id]
|
| 375 |
+
instance["attempts"] += 1
|
| 376 |
+
|
| 377 |
+
# Evaluate current response
|
| 378 |
+
reward = await self.calculate_score(instance_id)
|
| 379 |
+
|
| 380 |
+
if reward > 0.8:
|
| 381 |
+
return True, "Excellent work!", reward, {}
|
| 382 |
+
elif instance["attempts"] < 3:
|
| 383 |
+
return False, "Good attempt, but try to improve...", reward, {}
|
| 384 |
+
else:
|
| 385 |
+
return True, "Maximum attempts reached.", reward, {}
|
| 386 |
+
|
| 387 |
+
Troubleshooting
|
| 388 |
+
---------------
|
| 389 |
+
|
| 390 |
+
**Common Issues**
|
| 391 |
+
|
| 392 |
+
1. **Instance ID Conflicts**: Ensure unique instance IDs across concurrent sessions
|
| 393 |
+
2. **Memory Leaks**: Always call ``finalize_interaction()`` to clean up resources
|
| 394 |
+
3. **Blocking Operations**: Keep interaction logic async and non-blocking
|
| 395 |
+
4. **Configuration Errors**: Verify interaction config path and class name are correct
|
| 396 |
+
5. **Interaction Name Conflicts**: Ensure all interactions have unique names in the configuration
|
| 397 |
+
6. **Missing Interaction**: Verify the ``name`` field in ``interaction_kwargs`` matches available interactions
|
| 398 |
+
7. **Backward Compatibility**: When migrating from single to multi-interaction, add ``name`` fields to existing data
|
| 399 |
+
|
| 400 |
+
**Debugging**
|
| 401 |
+
|
| 402 |
+
Enable debug logging to trace interaction flow:
|
| 403 |
+
|
| 404 |
+
.. code-block:: bash
|
| 405 |
+
|
| 406 |
+
export VERL_LOGGING_LEVEL=DEBUG
|
| 407 |
+
|
| 408 |
+
**Performance Monitoring**
|
| 409 |
+
|
| 410 |
+
Monitor interaction performance impact on training throughput and adjust accordingly.
|
| 411 |
+
|
| 412 |
+
Related Documentation
|
| 413 |
+
--------------------
|
| 414 |
+
|
| 415 |
+
- :doc:`multiturn`: Basic multi-turn rollout configuration
|
| 416 |
+
- :doc:`sandbox_fusion`: Tool integration with SGLang
|
| 417 |
+
- :doc:`search_tool_example`: Search tool implementation example
|