diff --git a/scripts/convert_rl_to_sft_blackjack.py b/scripts/convert_rl_to_sft_blackjack.py new file mode 100644 index 0000000000000000000000000000000000000000..c19b7d986f5c75a002b0571914964058d1b530d6 --- /dev/null +++ b/scripts/convert_rl_to_sft_blackjack.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +""" +Convert RL test trajectories from Blackjack into LLM SFT-ready language trajectories. +Uses pre-recorded text_states from the training script to ensure exact match with environment feedback. + +Input: runs//trajectories/step_XXXXXX/trajectories.jsonl +Output: runs//sft/step_XXXXXX_sft.jsonl +""" + +import argparse +import json +import os +from pathlib import Path +from typing import List, Tuple + +try: + import yaml # type: ignore +except Exception: + yaml = None + +ACTION_LOOKUP = {0: "Stick", 1: "Hit"} + + +def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, bool, str, int]: + """Load Blackjack env_instruction, max_tokens, enable_think, action_sep, max_actions. + Fallbacks are provided if YAML is unavailable or keys are missing. + """ + instruction = ( + "You are playing Blackjack against a dealer. The dealer must hit on 16 or less and stand on 17 or more.\n" + "Choose either Stick or Hit. Respond with a single action.\n" + "Example: Hit" + ) + max_tokens = 64 + enable_think = True + action_sep = "||" + max_actions = 10 + + if yaml is None: + instruction += ( + "\nYour available actions are:\n" + "Stick, Hit\n" + f"You can make up to {max_actions} actions, separated by the action separator \" " + action_sep + " \"\n" + ) + return instruction, max_tokens, enable_think, action_sep, max_actions + + envs_yaml = repo_root / "config" / "envs.yaml" + if envs_yaml.exists(): + try: + with open(envs_yaml, "r", encoding="utf-8") as f: + envs = yaml.safe_load(f) + if isinstance(envs, dict): + bj = envs.get("Blackjack", {}) + if isinstance(bj, dict): + instruction = bj.get("env_instruction", instruction) + max_tokens = int(bj.get("max_tokens", max_tokens)) + max_actions = int(bj.get("max_actions_per_traj", max_actions)) + except Exception: + pass + + base_yaml = repo_root / "config" / "base.yaml" + if base_yaml.exists(): + try: + with open(base_yaml, "r", encoding="utf-8") as f: + base_cfg = yaml.safe_load(f) + ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {} + action_sep = ap.get("action_sep", action_sep) + enable_think = bool(ap.get("enable_think", enable_think)) + except Exception: + pass + + instruction += ( + "\nYour available actions are:\n" + "Stick, Hit\n" + f"You can make up to {max_actions} actions, separated by the action separator \" " + action_sep + " \"\n" + ) + return instruction, max_tokens, enable_think, action_sep, max_actions + + +def build_messages_for_episode( + text_states: List[str], + actions: List[int], + rewards: List[float], + instruction: str, + max_tokens: int, + enable_think: bool, + max_actions: int, +) -> List[dict]: + messages = [ + {"role": "system", "content": "You're a helpful assistant. "}, + {"role": "user", "content": instruction}, + ] + + total_actions = len(actions) + + # 遍历每一步动作 + for t in range(len(actions)): + # 获取当前步骤的文本状态 + # text_states[0] 是初始状态, text_states[1] 是 action[0] 之后的状态 + current_text_state = text_states[t] + + actions_left = max(0, max_actions - t) + format_prompt = ( + " [Your thoughts] [your answer] " + if enable_think + else " [your answer] " + ) + length_prompt = f"Max response length: {max_tokens} words (tokens)." + + # --- 核心修改:使用保存的文本状态并拼接 Question --- + turn_content = ( + f"\nTurn {t + 1}:\n" + f"State:\n" + f"{current_text_state}\n" # text_state 已经包含了 === Blackjack Game State === 等内容 + f"What is your next move?\n" + f"You have {actions_left} actions left. Always output: {format_prompt}" + f" with no extra text. Strictly follow this format. {length_prompt}" + ) + + # 追加到上一条 user 消息(如果是第一回合)或者新建 user 消息 + if messages[-1]["role"] == "user": + messages[-1]["content"] += turn_content + else: + messages.append({"role": "user", "content": turn_content}) + + # 添加 Assistant 回复 + action_id = int(actions[t]) + action_name = ACTION_LOOKUP.get(action_id, "unknown") + assistant_text = ( + f"{action_name}" if enable_think else f"{action_name}" + ) + messages.append({"role": "assistant", "content": assistant_text}) + + # 添加 Reward 信息 + reward_val = rewards[t] + messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"}) + + # 移除最后一条仅包含 Reward 的 User 消息(SFT 数据通常以 Assistant 结尾) + if messages[-1]["role"] == "user": + messages.pop() + + return messages + + +def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False, max_actions: int = 10) -> Path: + traj_path = step_dir / "trajectories.jsonl" + metrics_path = step_dir / "metrics.json" + if not traj_path.exists(): + raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") + + instruction, max_tokens, enable_think, action_sep, cfg_max_actions = load_env_instruction_and_cfg(repo_root) + if max_actions is None: + max_actions = cfg_max_actions + + output_dir.mkdir(parents=True, exist_ok=True) + out_path = output_dir / f"{step_dir.name}_sft.jsonl" + + global_step = None + if metrics_path.exists(): + try: + with open(metrics_path, "r", encoding="utf-8") as f: + m = json.load(f) + global_step = m.get("global_step") + except Exception: + pass + + written = 0 + with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: + for line in fin: + line = line.strip() + if not line: + continue + traj = json.loads(line) + + ep_success = bool(traj.get("episode_success", False)) + if (not include_failed) and (not ep_success): + continue + + # 读取新的 text_states 字段 + text_states = traj.get("text_states", []) + actions = traj.get("actions", []) + rewards = traj.get("rewards", []) + + # 兼容性检查:如果该轨迹是旧代码生成的(没有 text_states),则跳过 + if not text_states: + # Silently skip or warn + continue + + if len(actions) > max_actions: + continue + + messages = build_messages_for_episode( + text_states=text_states, + actions=actions, + rewards=rewards, + instruction=instruction, + max_tokens=max_tokens, + enable_think=enable_think, + max_actions=max_actions, + ) + + record = { + "messages": messages, + "meta": { + "episode_return": traj.get("episode_return", None), + "episode_success": ep_success, + "global_step": global_step, + }, + } + fout.write(json.dumps(record, ensure_ascii=False) + "\n") + written += 1 + + if written == 0: + # 创建空文件以防报错,或者写入一个空数组 + with open(out_path, "w", encoding="utf-8") as f: + pass + print("Warning: No trajectories converted. Check if input file has 'text_states' or if filtering is too strict.") + + return out_path + + +def find_latest_step_dir(traj_root: Path) -> Path: + step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] + if not step_dirs: + raise FileNotFoundError(f"No step_* directories under {traj_root}") + step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) + return step_dirs[-1] + + +def main(): + parser = argparse.ArgumentParser(description="Convert Blackjack RL trajectories to LLM SFT chat JSONL") + parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)") + parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_499712)") + parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data") + parser.add_argument("--max_actions", type=int, default=None, help="Max actions cap for filtering and counter display") + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + run_dir = Path(args.run_dir) + traj_root = run_dir / "trajectories" + if not traj_root.exists(): + raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") + + step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) + output_dir = run_dir / "sft" + out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed, max_actions=args.max_actions) + print(f"SFT data written to: {out_path}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/convert_rl_to_sft_frozenlake.py b/scripts/convert_rl_to_sft_frozenlake.py new file mode 100644 index 0000000000000000000000000000000000000000..347a149f7a4dee7bd0d2657ed97841f24122bd3d --- /dev/null +++ b/scripts/convert_rl_to_sft_frozenlake.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python3 +""" +Convert RL test trajectories (numeric states/actions) from FrozenLake into +LLM SFT-ready language trajectories in chat-style messages. + +Input: runs//trajectories/step_XXXXXX/trajectories.jsonl +Output: runs//sft/step_XXXXXX_sft.jsonl + +Each output JSON line contains: + - messages: [{role: system|user|assistant, content: str}, ...] + - meta: {episode_return: float, episode_success: bool, global_step: int} + +We mirror RAGEN ContextManager’s prompt format as much as possible: + - system: "You're a helpful assistant. " + - user: env_instruction + per-turn state blocks with action constraints + - assistant: "Action" (or without think if disabled) + - user (reward): "Reward:\n{reward}\n" +""" + +import argparse +import json +import math +import os +from pathlib import Path +from typing import List, Tuple + +try: + import yaml # type: ignore +except Exception: + yaml = None + + +ACTION_LOOKUP = {1: "Left", 2: "Down", 3: "Right", 4: "Up"} + + +def infer_grid_dims(state_vec: List[float]) -> Tuple[int, int]: + """Infer (rows, cols) from flattened one-hot grid length. + Our PPO wrapper encodes each cell as one-hot over 6 tokens: ['P','_','O','G','X','√']. + """ + n = len(state_vec) + assert n % 6 == 0, f"State length {n} not divisible by 6 (channels)" + n_cells = n // 6 + r = int(math.isqrt(n_cells)) + assert r * r == n_cells, f"Grid is not square: {n_cells} cells" + return r, r + + +def decode_state_to_grid_text(state_vec: List[float]) -> str: + """Decode numeric state vector back to textual grid. + + Encoding per PPO wrapper: + One-hot per cell over tokens = ['P', '_', 'O', 'G', 'X', '√'] in this order. + The wrapper already encodes P/X/√ directly in the grid; no separate coords needed. + """ + tokens = ['P', '_', 'O', 'G', 'X', '√'] + rows, cols = infer_grid_dims(state_vec) + lines = [] + for i in range(rows): + row_chars = [] + for j in range(cols): + base = (i * cols + j) * 6 + cell = state_vec[base: base + 6] + idx = max(range(6), key=lambda k: cell[k]) + ch = tokens[idx] if 0 <= idx < len(tokens) else '_' + row_chars.append(ch) + lines.append("".join(row_chars)) + return "\n".join(lines) + + +def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool]: + """Load FrozenLake env_instruction, max_tokens, action_sep, enable_think from config. + Fallbacks are provided if YAML is unavailable. + """ + default_instruction = ( + "You are solving the FrozenLake puzzle. Forbid the hole and go to the target. " + "You may move to unintended directions due to slippery ice. " + "Example answer format: To forbid the hole and go to the target, I should go left then go up.Left || Up" + "The meaning of each symbol in the state is:\nP: player, _: empty, O: hole, G: goal, X: player in hole, √: player on goal \nYour available actions are: \nLeft, Down, Right, Up \nYou can make up to 10 actions, separated by the action separator ' || '" + ) + instruction = default_instruction + max_tokens = 100 + action_sep = "||" + enable_think = True + + if yaml is None: + return instruction, max_tokens, action_sep, enable_think + + # envs.yaml + envs_yaml = repo_root / "config" / "envs.yaml" + if envs_yaml.exists(): + try: + with open(envs_yaml, "r", encoding="utf-8") as f: + envs = yaml.safe_load(f) + if isinstance(envs, dict) and "FrozenLake" in envs: + fl = envs["FrozenLake"] + instruction = fl.get("env_instruction", instruction) + max_tokens = int(fl.get("max_tokens", max_tokens)) + except Exception: + pass + + # base.yaml + base_yaml = repo_root / "config" / "base.yaml" + if base_yaml.exists(): + try: + with open(base_yaml, "r", encoding="utf-8") as f: + base_cfg = yaml.safe_load(f) + ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {} + action_sep = ap.get("action_sep", action_sep) + enable_think = bool(ap.get("enable_think", enable_think)) + except Exception: + pass + + return instruction, max_tokens, action_sep, enable_think + + +def build_messages_for_episode( + states: List[List[float]], + actions: List[int], + rewards: List[float], + instruction: str, + max_tokens: int, + action_sep: str, + enable_think: bool, +) -> List[dict]: + """Construct chat messages mirroring ContextManager format. + + - First system message. + - One user message containing the instruction and per-turn state blocks. + - Assistant messages per executed action with tag-only outputs. + - User messages for rewards. + """ + messages = [ + {"role": "system", "content": "You're a helpful assistant. "}, + {"role": "user", "content": instruction}, + ] + + total_actions = len(actions) + # Append state blocks into the initial user content + for t, state in enumerate(states): + grid_text = decode_state_to_grid_text(state) + actions_left = max(0, total_actions - t) # before taking action at turn t + format_prompt = ( + " [Your thoughts] [your answer] " + if enable_think + else " [your answer] " + ) + length_prompt = f"Max response length: {max_tokens} words (tokens)." + + messages[-1]["content"] += ( + f"\nTurn {t + 1}:\n" + f"State:\n{grid_text}\n" + f"You have {actions_left} actions left. Always output: {format_prompt} " + f"with no extra text. Strictly follow this format. {length_prompt}\n" + ) + # If action exists for this turn, add assistant + reward + if t < total_actions: + # Map RL action (0..3) -> RAGEN action (1..4) -> text + action_id = actions[t] + 1 + action_name = ACTION_LOOKUP.get(action_id, "unknown") + if enable_think: + assistant_text = f"{action_name}" + else: + assistant_text = f"{action_name}" + messages.append({"role": "assistant", "content": assistant_text}) + # Reward message + reward_val = rewards[t] if t < len(rewards) else 0.0 + messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"}) + # import pdb;pdb.set_trace() + messages.append({"role": "assistant", "content": ""}) + return messages + + +def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False) -> Path: + traj_path = step_dir / "trajectories.jsonl" + metrics_path = step_dir / "metrics.json" + if not traj_path.exists(): + raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") + + instruction, max_tokens, action_sep, enable_think = load_env_instruction_and_cfg(repo_root) + + output_dir.mkdir(parents=True, exist_ok=True) + out_path = output_dir / f"{step_dir.name}_sft.jsonl" + + # Read global step from metrics if available + global_step = None + if metrics_path.exists(): + try: + with open(metrics_path, "r", encoding="utf-8") as f: + m = json.load(f) + global_step = m.get("global_step") + except Exception: + pass + + written = 0 + with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: + for line in fin: + line = line.strip() + if not line: + continue + traj = json.loads(line) + # Filter if requested + ep_success = bool(traj.get("episode_success", False)) + if (not include_failed) and (not ep_success): + continue + + states = traj.get("states", []) + actions = traj.get("actions", []) + rewards = traj.get("rewards", []) + messages = build_messages_for_episode( + states=states, + actions=actions, + rewards=rewards, + instruction=instruction, + max_tokens=max_tokens, + action_sep=action_sep, + enable_think=enable_think, + ) + + record = { + "messages": messages, + "meta": { + "episode_return": traj.get("episode_return", None), + "episode_success": ep_success, + "global_step": global_step, + }, + } + fout.write(json.dumps(record, ensure_ascii=False) + "\n") + written += 1 + + if written == 0: + # Still write an empty file to signal conversion executed + with open(out_path, "w", encoding="utf-8") as f: + pass + return out_path + + +def find_latest_step_dir(traj_root: Path) -> Path: + step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] + if not step_dirs: + raise FileNotFoundError(f"No step_* directories under {traj_root}") + # Sort by numeric suffix + step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) + return step_dirs[-1] + + +def main(): + parser = argparse.ArgumentParser(description="Convert FrozenLake RL trajectories to LLM SFT chat JSONL") + parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)" ) + parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)") + parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data") + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + run_dir = Path(args.run_dir) + traj_root = run_dir / "trajectories" + if not traj_root.exists(): + raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") + + step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) + output_dir = run_dir / "sft" + out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed) + print(f"SFT data written to: {out_path}") + + +if __name__ == "__main__": + main() + diff --git a/scripts/convert_rl_to_sft_frozenlake_daoshuaction.py b/scripts/convert_rl_to_sft_frozenlake_daoshuaction.py new file mode 100644 index 0000000000000000000000000000000000000000..5ecdc13bcfcfaceaf7e5ce709c8147a3a7e7828d --- /dev/null +++ b/scripts/convert_rl_to_sft_frozenlake_daoshuaction.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 + +import argparse +import json +import math +import os +from pathlib import Path +from typing import List, Tuple + +try: + import yaml # type: ignore +except Exception: + yaml = None + + +ACTION_LOOKUP = {1: "Left", 2: "Down", 3: "Right", 4: "Up"} + + +def infer_grid_dims(state_vec: List[float]) -> Tuple[int, int]: + """Infer (rows, cols) from flattened one-hot grid length. + Our PPO wrapper encodes each cell as one-hot over 6 tokens: ['P','_','O','G','X','√']. + """ + n = len(state_vec) + assert n % 6 == 0, f"State length {n} not divisible by 6 (channels)" + n_cells = n // 6 + r = int(math.isqrt(n_cells)) + assert r * r == n_cells, f"Grid is not square: {n_cells} cells" + return r, r + + +def decode_state_to_grid_text(state_vec: List[float]) -> str: + """Decode numeric state vector back to textual grid. + + Encoding per PPO wrapper: + One-hot per cell over tokens = ['P', '_', 'O', 'G', 'X', '√'] in this order. + The wrapper already encodes P/X/√ directly in the grid; no separate coords needed. + """ + tokens = ['P', '_', 'O', 'G', 'X', '√'] + rows, cols = infer_grid_dims(state_vec) + lines = [] + for i in range(rows): + row_chars = [] + for j in range(cols): + base = (i * cols + j) * 6 + cell = state_vec[base: base + 6] + idx = max(range(6), key=lambda k: cell[k]) + ch = tokens[idx] if 0 <= idx < len(tokens) else '_' + row_chars.append(ch) + lines.append("".join(row_chars)) + return "\n".join(lines) + + +def parse_positions_from_state(state_vec: List[float]): + """Extract board size, player, goal, and holes positions from one-hot state. + - Player is where token is one of ['P','X','√']. + - Goal is where token is 'G'. + - Holes include all 'O' cells; if player is on hole ('X'), include that cell as a hole as well. + Returns: (rows, cols, (pr, pc), (gr, gc) or None, holes: List[(r,c)]) + """ + tokens = ['P', '_', 'O', 'G', 'X', '√'] + rows, cols = infer_grid_dims(state_vec) + player = None + goal = None + holes: List[Tuple[int, int]] = [] + for i in range(rows): + for j in range(cols): + base = (i * cols + j) * 6 + cell = state_vec[base: base + 6] + idx = max(range(6), key=lambda k: cell[k]) + if idx == 0 or idx == 4 or idx == 5: # P or X or √ + player = (i, j) + if idx == 4: # X means on a hole + holes.append((i, j)) + elif idx == 2: # O + holes.append((i, j)) + elif idx == 3: # G + goal = (i, j) + return rows, cols, player, goal, holes + + +def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool]: + """Load FrozenLake env_instruction, max_tokens, action_sep, enable_think from config. + Fallbacks are provided if YAML is unavailable. + """ + default_instruction = ( + "You are solving the FrozenLake puzzle. The observation includes both a symbol grid and zero-indexed coordinates for the start, goal, player, and any holes.\n" + "Coordinates range from the top-left corner (0, 0) to the bottom-right corner (5, 5).\n" + "Beware that the ice is slippery, so the agent might slide and end up in an unintended tile.\n" + "Respond with a sequence of actions such as Left || Up || Up.\n" + "\nThe meaning of each symbol in the state is:\n" + "P: player, _: empty, O: hole, G: goal, X: player in hole, √: player on goal\n" + "Your available actions are:\n" + "Left, Down, Right, Up\n" + "You can make up to 25 actions, separated by the action separator \" || \"\n" + ) + instruction = default_instruction + max_tokens = 100 + action_sep = "||" + enable_think = True + + if yaml is None: + return instruction, max_tokens, action_sep, enable_think + + # envs.yaml + envs_yaml = repo_root / "config" / "envs.yaml" + if envs_yaml.exists(): + try: + with open(envs_yaml, "r", encoding="utf-8") as f: + envs = yaml.safe_load(f) + if isinstance(envs, dict) and "FrozenLake" in envs: + fl = envs["FrozenLake"] + instruction = fl.get("env_instruction", instruction) + max_tokens = int(fl.get("max_tokens", max_tokens)) + except Exception: + pass + + # base.yaml + base_yaml = repo_root / "config" / "base.yaml" + if base_yaml.exists(): + try: + with open(base_yaml, "r", encoding="utf-8") as f: + base_cfg = yaml.safe_load(f) + ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {} + action_sep = ap.get("action_sep", action_sep) + enable_think = bool(ap.get("enable_think", enable_think)) + except Exception: + pass + + return instruction, max_tokens, action_sep, enable_think + + +def build_messages_for_episode( + states: List[List[float]], + actions: List[int], + rewards: List[float], + instruction: str, + max_tokens: int, + action_sep: str, + enable_think: bool, + max_actions: int, +) -> List[dict]: + """Construct chat messages mirroring ContextManager format. + + - First system message. + - One user message containing the instruction and per-turn state blocks. + - Assistant messages per executed action with tag-only outputs. + - User messages for rewards. + """ + messages = [ + {"role": "system", "content": "You're a helpful assistant. "}, + {"role": "user", "content": instruction}, + ] + + total_actions = len(actions) + # Determine start position from the first state's player + start_rows, start_cols, start_player, start_goal, start_holes = parse_positions_from_state(states[0]) if states else (0, 0, None, None, []) + # Append state blocks into the initial user content + for t, state in enumerate(states): + grid_text = decode_state_to_grid_text(state) + rows, cols, player_pos, goal_pos, holes_pos = parse_positions_from_state(state) + # Start counter from max_actions (e.g., 25) regardless of episode length + actions_left = max(0, max_actions - t) + format_prompt = ( + " [Your thoughts] [your answer] " + if enable_think + else " [your answer] " + ) + length_prompt = f"Max response length: {max_tokens} words (tokens)." + + messages[-1]["content"] += ( + f"\nTurn {t + 1}:\n" + f"State:\n" + f"Coordinates:\n" + f"Board size: {rows} rows x {cols} cols (zero-indexed).\n" + f"Start: {start_player if start_player is not None else (-1, -1)}\n" + f"Goal: {goal_pos if goal_pos is not None else (-1, -1)}\n" + f"Player: {player_pos if player_pos is not None else (-1, -1)}\n" + f"Holes: {holes_pos}\n" + f"Grid Map:\n{grid_text}\n" + f"You have {actions_left} actions left. Always output: {format_prompt}" + f"with no extra text. Strictly follow this format. {length_prompt}" + ) + # If action exists for this turn, add assistant + reward + if t < total_actions: + # Map RL action (0..3) -> RAGEN action (1..4) -> text + action_id = actions[t] + 1 + action_name = ACTION_LOOKUP.get(action_id, "unknown") + if enable_think: + assistant_text = f"{action_name}" + else: + assistant_text = f"{action_name}" + messages.append({"role": "assistant", "content": assistant_text}) + # Reward message + reward_val = rewards[t] if t < len(rewards) else 0.0 + messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"}) + # import pdb;pdb.set_trace() + + return messages[:-1] + + +def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False, max_actions: int = 25) -> Path: + traj_path = step_dir / "trajectories.jsonl" + metrics_path = step_dir / "metrics.json" + if not traj_path.exists(): + raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") + + instruction, max_tokens, action_sep, enable_think = load_env_instruction_and_cfg(repo_root) + + output_dir.mkdir(parents=True, exist_ok=True) + out_path = output_dir / f"{step_dir.name}_sft.jsonl" + + # Read global step from metrics if available + global_step = None + if metrics_path.exists(): + try: + with open(metrics_path, "r", encoding="utf-8") as f: + m = json.load(f) + global_step = m.get("global_step") + except Exception: + pass + + written = 0 + with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: + for line in fin: + line = line.strip() + if not line: + continue + traj = json.loads(line) + # Filter if requested + ep_success = bool(traj.get("episode_success", False)) + if (not include_failed) and (not ep_success): + continue + + states = traj.get("states", []) + actions = traj.get("actions", []) + rewards = traj.get("rewards", []) + # Filter: keep only episodes with total actions <= max_actions + if len(actions) > max_actions: + continue + messages = build_messages_for_episode( + states=states, + actions=actions, + rewards=rewards, + instruction=instruction, + max_tokens=max_tokens, + action_sep=action_sep, + enable_think=enable_think, + max_actions=max_actions, + ) + + record = { + "messages": messages, + "meta": { + "episode_return": traj.get("episode_return", None), + "episode_success": ep_success, + "global_step": global_step, + }, + } + fout.write(json.dumps(record, ensure_ascii=False) + "\n") + written += 1 + + if written == 0: + # Still write an empty file to signal conversion executed + with open(out_path, "w", encoding="utf-8") as f: + pass + return out_path + + +def find_latest_step_dir(traj_root: Path) -> Path: + step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] + if not step_dirs: + raise FileNotFoundError(f"No step_* directories under {traj_root}") + # Sort by numeric suffix + step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) + return step_dirs[-1] + + +def main(): + parser = argparse.ArgumentParser(description="Convert FrozenLake RL trajectories to LLM SFT chat JSONL") + parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)" ) + parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)") + parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data") + parser.add_argument("--max_actions", type=int, default=25, help="Max actions cap for filtering and counter display") + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + run_dir = Path(args.run_dir) + traj_root = run_dir / "trajectories" + if not traj_root.exists(): + raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") + + step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) + output_dir = run_dir / "sft" + out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed, max_actions=args.max_actions) + print(f"SFT data written to: {out_path}") + + +if __name__ == "__main__": + main() + diff --git a/scripts/convert_rl_to_sft_rubikscube.py b/scripts/convert_rl_to_sft_rubikscube.py new file mode 100644 index 0000000000000000000000000000000000000000..33b334f49e15485160f616b64e4884259ed45e5a --- /dev/null +++ b/scripts/convert_rl_to_sft_rubikscube.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +""" +Convert RL eval trajectories from Rubik's Cube 2x2 into LLM SFT-ready chat data. + +Input: runs//trajectories/step_XXXXXX/trajectories.jsonl +Output: runs//sft/step_XXXXXX_sft.jsonl + +Each output JSON line contains: + - messages: [{role: system|user|assistant, content: str}, ...] + - meta: {episode_return: float, episode_success: bool, global_step: int} + +We mirror the FrozenLake converter structure: + - system: "You're a helpful assistant. " + - user: env_instruction + per-turn state blocks + - assistant: tag-only actions, one per step + - user: reward after each action +""" + +import argparse +import json +from pathlib import Path +from typing import List, Tuple + +try: + import yaml # type: ignore +except Exception: + yaml = None + + +# Rubik's 2x2 actions (env uses 1..12; PPO wrapper stores 0..11) +RUBIK_ACTIONS = [ + "U", "U'", "D", "D'", "L", "L'", "R", "R'", "F", "F'", "B", "B'", +] + +COLORS = ['W', 'O', 'G', 'R', 'B', 'Y'] + + +def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool, int]: + """Load RubiksCube2x2 env instruction and base agent_proxy configs. + Returns: (instruction, max_tokens, action_sep, enable_think, max_actions) + """ + instruction = ( + "You are solving a 2x2 Rubik's Cube (Pocket Cube). The goal is to restore the cube so that each of the faces consists of a single, unique color.\n" + "Available actions use standard Singmaster notation for face rotations: U, U', D, D', L, L', R, R', F, F', B, B'.\n" + "- Faces: U (Up), D (Down), L (Left), R (Right), F (Front), B (Back).\n" + "- Modifiers: A letter alone means 90° clockwise (e.g., 'R'). A letter with prime (') means 90° counter-clockwise (e.g., \"R'\")." + "Respond with a sequence of actions separated by \"||\".\n" + "Example: U\n\n" + "Your available actions are:\n" + "U, U', D, D', L, L', R, R', F, F', B, B'\n" + "You can make up to 20 actions, separated by the action separator \" || \"\n" + ) + max_tokens = 96 + action_sep = "||" + enable_think = True + max_actions = 20 + + if yaml is None: + return instruction, max_tokens, action_sep, enable_think, max_actions + + # envs.yaml + envs_yaml = repo_root / "config" / "envs.yaml" + if envs_yaml.exists(): + try: + with open(envs_yaml, "r", encoding="utf-8") as f: + envs = yaml.safe_load(f) + if isinstance(envs, dict) and "custom_envs" in envs and "RubiksCube2x2" in envs["custom_envs"]: + e = envs["custom_envs"]["RubiksCube2x2"] + instruction = e.get("env_instruction", instruction) + max_tokens = int(e.get("max_tokens", max_tokens)) + max_actions = int(e.get("max_actions_per_traj", max_actions)) + except Exception: + pass + + # base.yaml + base_yaml = repo_root / "config" / "base.yaml" + if base_yaml.exists(): + try: + with open(base_yaml, "r", encoding="utf-8") as f: + base_cfg = yaml.safe_load(f) + ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {} + action_sep = ap.get("action_sep", action_sep) + enable_think = bool(ap.get("enable_think", enable_think)) + except Exception: + pass + + return instruction, max_tokens, action_sep, enable_think, max_actions + + +def decode_state_to_text(state_vec: List[float]) -> str: + """Decode one-hot length 24*6 vector into sticker letters. + Returns a compact textual block listing each face in order: U, L, F, R, B, D. + """ + if not state_vec: + return "" + n = len(state_vec) + if n % len(COLORS) != 0: + return "" + n_stickers = n // len(COLORS) + if n_stickers != 24: + # Unknown shape; still try to decode row-wise + pass + # decode one-hot to color letter per sticker + stickers: List[str] = [] + for i in range(n_stickers): + base = i * len(COLORS) + cell = state_vec[base: base + len(COLORS)] + idx = max(range(len(COLORS)), key=lambda k: cell[k]) + c = COLORS[idx] if 0 <= idx < len(COLORS) else '?' + stickers.append(c) + # format faces (4 stickers per face) + faces = [stickers[i*4:(i+1)*4] for i in range(6)] + face_names = ["Up (U)", "Left (L)", "Front (F)", "Right (R)", "Back (B)", "Down (D)"] + lines = ["=== Rubik's Cube 2x2 State ===\n"] + for name, face in zip(face_names, faces): + lines.append(f"{name}: [{face[0]}, {face[1]}] \n [{face[2]}, {face[3]}]") + lines.append("\nAvailable actions: \n" + ", ".join(RUBIK_ACTIONS)) + return "\n".join(lines) + + +def build_messages_for_episode( + states: List[List[float]], + actions: List[int], + rewards: List[float], + instruction: str, + max_tokens: int, + action_sep: str, + enable_think: bool, + max_actions: int, +) -> List[dict]: + messages = [ + {"role": "system", "content": "You're a helpful assistant. "}, + {"role": "user", "content": instruction}, + ] + + total_actions = len(actions) + for t, state in enumerate(states): + state_text = decode_state_to_text(state) + actions_left = max(0, max_actions - t) + format_prompt = ( + " [Your thoughts] [your answer] " + if enable_think + else " [your answer] " + ) + length_prompt = f"Max response length: {max_tokens} words (tokens)." + + messages[-1]["content"] += ( + f"\nTurn {t + 1}:\n" + f"State:\n{state_text}\n" + f"\nWhat is your next move?\n" + f"You have {actions_left} actions left. Always output: {format_prompt}" + f"with no extra text. {length_prompt}" + ) + + if t < total_actions: + a = actions[t] + a_name = RUBIK_ACTIONS[int(a)] if 0 <= int(a) < len(RUBIK_ACTIONS) else str(a) + if enable_think: + assistant_text = f" {a_name}" + else: + assistant_text = f"{a_name}" + messages.append({"role": "assistant", "content": assistant_text}) + r = rewards[t] if t < len(rewards) else 0.0 + messages.append({"role": "user", "content": f"Reward:\n{r}\n"}) + # import pdb;pdb.set_trace() + return messages[:-1] + + +def find_latest_step_dir(traj_root: Path) -> Path: + step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] + if not step_dirs: + raise FileNotFoundError(f"No step_* directories under {traj_root}") + step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) + return step_dirs[-1] + + +def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool, max_actions_cap: int | None) -> Path: + traj_path = step_dir / "trajectories.jsonl" + metrics_path = step_dir / "metrics.json" + if not traj_path.exists(): + raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") + + instruction, max_tokens, action_sep, enable_think, default_max_actions = load_env_instruction_and_cfg(repo_root) + max_actions = int(max_actions_cap) if max_actions_cap is not None else int(default_max_actions) + + output_dir.mkdir(parents=True, exist_ok=True) + out_path = output_dir / f"{step_dir.name}_sft.jsonl" + + # Read global step from metrics if available + global_step = None + if metrics_path.exists(): + try: + with open(metrics_path, "r", encoding="utf-8") as f: + m = json.load(f) + global_step = m.get("global_step") + except Exception: + pass + + written = 0 + with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: + for line in fin: + line = line.strip() + if not line: + continue + traj = json.loads(line) + + ep_success = bool(traj.get("episode_success", False)) + if (not include_failed) and (not ep_success): + continue + + states = traj.get("states", []) + actions = traj.get("actions", []) + rewards = traj.get("rewards", []) + if len(actions) > max_actions: + continue + + messages = build_messages_for_episode( + states=states, + actions=actions, + rewards=rewards, + instruction=instruction, + max_tokens=max_tokens, + action_sep=action_sep, + enable_think=enable_think, + max_actions=max_actions, + ) + + record = { + "messages": messages, + "meta": { + "episode_return": traj.get("episode_return", None), + "episode_success": ep_success, + "global_step": global_step, + }, + } + fout.write(json.dumps(record, ensure_ascii=False) + "\n") + written += 1 + + if written == 0: + with open(out_path, "w", encoding="utf-8"): + pass + return out_path + + +def main(): + parser = argparse.ArgumentParser(description="Convert Rubik's Cube 2x2 RL trajectories to LLM SFT chat JSONL") + parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)") + parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_123456)") + parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data") + parser.add_argument("--max_actions", type=int, default=None, help="Override max actions cap (default from envs.yaml)") + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + run_dir = Path(args.run_dir) + traj_root = run_dir / "trajectories" + if not traj_root.exists(): + raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") + + step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) + output_dir = run_dir / "sft" + out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed, max_actions_cap=args.max_actions) + print(f"SFT data written to: {out_path}") + + +if __name__ == "__main__": + main() diff --git a/scripts/convert_rl_to_sft_sokoban.py b/scripts/convert_rl_to_sft_sokoban.py new file mode 100644 index 0000000000000000000000000000000000000000..166f059b55a2172c023c02060e62088b7bb9c1af --- /dev/null +++ b/scripts/convert_rl_to_sft_sokoban.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +import argparse +import json +import os +from pathlib import Path +from typing import List, Tuple + +try: + import yaml # type: ignore +except Exception: + yaml = None + +# Sokoban tokens and actions (as used by SokobanWrapper) +TOKENS = ['#', '_', 'O', '√', 'X', 'P', 'S'] +ACTION_LOOKUP = {1: 'Up', 2: 'Down', 3: 'Left', 4: 'Right'} + + +def infer_grid_dims(state_arr: List[List[List[float]]]) -> Tuple[int, int, int]: + c = len(state_arr) + h = len(state_arr[0]) if c > 0 else 0 + w = len(state_arr[0][0]) if (c > 0 and h > 0) else 0 + return c, h, w + + +def decode_state_to_grid_text(state_arr: List[List[List[float]]]) -> str: + c, h, w = infer_grid_dims(state_arr) + lines = [] + for i in range(h): + row = [] + for j in range(w): + argmax_k = 0 + vmax = -1e9 + for k in range(c): + v = state_arr[k][i][j] + if v > vmax: + vmax = v + argmax_k = k + ch = TOKENS[argmax_k] if 0 <= argmax_k < len(TOKENS) else '_' + row.append(ch) + lines.append(''.join(row)) + return '\n'.join(lines) + + +def parse_positions_from_state(state_arr: List[List[List[float]]]): + """Extract board size, targets, boxes, and player coordinates from one-hot state. + - Tokens index mapping per TOKENS: 0 '#', 1 '_', 2 'O'(target), 3 '√'(box on target), 4 'X'(box), 5 'P'(player), 6 'S'(player on target) + - Targets include cells with 'O' or '√'. + - Boxes include cells with 'X' or '√'. + - Player is where token is 'P' or 'S'. + Returns: (rows, cols, targets: List[(r,c)], boxes: List[(r,c)], player: (r,c) or None) + """ + c, h, w = infer_grid_dims(state_arr) + targets: List[Tuple[int, int]] = [] + boxes: List[Tuple[int, int]] = [] + player: Tuple[int, int] | None = None + for i in range(h): + for j in range(w): + # argmax over channels + argk = 0 + vmax = -1e9 + for k in range(c): + v = state_arr[k][i][j] + if v > vmax: + vmax = v + argk = k + if argk == 2: # 'O' target + targets.append((i, j)) + elif argk == 3: # '√' box on target (both a box and a target) + targets.append((i, j)) + boxes.append((i, j)) + elif argk == 4: # 'X' box + boxes.append((i, j)) + elif argk == 5 or argk == 6: # 'P' or 'S' (player or player on target) + player = (i, j) + return h, w, targets, boxes, player + + +def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool]: + instruction = ( + "You are solving the Sokoban puzzle. You are the player and you need to push all boxes to targets. " + "When you are right next to a box, you can push it by moving in the same direction. " + "You cannot push a box through a wall, and you cannot pull a box. " + "The answer should be a sequence of actions, like Right || Right || Up\n" + "\nThe meaning of each symbol in the state is:\n" + "#: wall, _: empty, O: target, √: box on target, X: box, P: player, S: player on target\n" + "Your available actions are:\n" + "Up, Down, Left, Right\n" + "You can make up to 10 actions, separated by the action separator \" || \"\n" + ) + max_tokens = 100 + action_sep = "||" + enable_think = True + + if yaml is None: + return instruction, max_tokens, action_sep, enable_think + + envs_yaml = repo_root / "config" / "envs.yaml" + if envs_yaml.exists(): + try: + with open(envs_yaml, "r", encoding="utf-8") as f: + envs = yaml.safe_load(f) + custom_envs = envs.get("custom_envs", {}) if isinstance(envs, dict) else {} + if isinstance(custom_envs, dict): + # Prefer CoordSokoban, fallback to SimpleSokoban, then LargerSokoban + for key in ["CoordSokoban", "SimpleSokoban", "LargerSokoban", "SokobanDifferentGridVocab"]: + if key in custom_envs: + cfg = custom_envs[key] + instruction = cfg.get("env_instruction", instruction) + max_tokens = int(cfg.get("max_tokens", max_tokens)) + break + except Exception: + pass + + base_yaml = repo_root / "config" / "base.yaml" + if base_yaml.exists(): + try: + with open(base_yaml, "r", encoding="utf-8") as f: + base_cfg = yaml.safe_load(f) + ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {} + action_sep = ap.get("action_sep", action_sep) + enable_think = bool(ap.get("enable_think", enable_think)) + except Exception: + pass + + return instruction, max_tokens, action_sep, enable_think + + +def build_messages_for_episode( + states: List[List[List[List[float]]]], + actions: List[int], + rewards: List[float], + instruction: str, + max_tokens: int, + action_sep: str, + enable_think: bool, + max_actions: int, +) -> List[dict]: + messages = [ + {"role": "system", "content": "You're a helpful assistant. "}, + {"role": "user", "content": instruction}, + ] + + total_actions = len(actions) + # states contain T+1 elements typically; we iterate over min(len(states), len(actions)) turns + for t, state in enumerate(states): + grid_text = decode_state_to_grid_text(state) + rows, cols, targets_pos, boxes_pos, player_pos = parse_positions_from_state(state) + actions_left = max(0, max_actions - t) + if enable_think: + format_prompt = " [Your thoughts] [your answer] " + else: + format_prompt = " [your answer] " + length_prompt = f"Max response length: {max_tokens} words (tokens)." + + messages[-1]["content"] += ( + f"\nTurn {t + 1}:\n" + f"State:\n" + f"Coordinates:\n" + f"Board size: {rows} rows x {cols} cols (zero-indexed).\n" + f"Targets: {targets_pos}\n" + f"Boxes: {boxes_pos}\n" + f"Player: {player_pos if player_pos is not None else (-1, -1)}\n" + f"Grid Map:\n{grid_text}\n" + f"You have {actions_left} actions left. Always output: {format_prompt}" + f"with no extra text. Strictly follow this format. {length_prompt}" + ) + + if t < total_actions: + action_id = actions[t] + 1 # map 0..3 -> 1..4 + action_name = ACTION_LOOKUP.get(action_id, "unknown") + assistant_text = f"{action_name}" if not enable_think else f"{action_name}" + messages.append({"role": "assistant", "content": assistant_text}) + reward_val = rewards[t] if t < len(rewards) else 0.0 + messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"}) + + return messages[:-1] + + +def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False, max_actions: int = 10) -> Path: + traj_path = step_dir / "trajectories.jsonl" + metrics_path = step_dir / "metrics.json" + if not traj_path.exists(): + raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") + + instruction, max_tokens, action_sep, enable_think = load_env_instruction_and_cfg(repo_root) + + output_dir.mkdir(parents=True, exist_ok=True) + out_path = output_dir / f"{step_dir.name}_sft.jsonl" + + global_step = None + if metrics_path.exists(): + try: + with open(metrics_path, "r", encoding="utf-8") as f: + m = json.load(f) + global_step = m.get("global_step") + except Exception: + pass + + written = 0 + with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: + for line in fin: + line = line.strip() + if not line: + continue + traj = json.loads(line) + ep_success = bool(traj.get("episode_success", False)) + if (not include_failed) and (not ep_success): + continue + + states = traj.get("states", []) + actions = traj.get("actions", []) + rewards = traj.get("rewards", []) + if len(actions) > max_actions: + continue + + messages = build_messages_for_episode( + states=states, + actions=actions, + rewards=rewards, + instruction=instruction, + max_tokens=max_tokens, + action_sep=action_sep, + enable_think=enable_think, + max_actions=max_actions, + ) + + record = { + "messages": messages, + "meta": { + "episode_return": traj.get("episode_return", None), + "episode_success": ep_success, + "global_step": global_step, + }, + } + fout.write(json.dumps(record, ensure_ascii=False) + "\n") + written += 1 + + if written == 0: + with open(out_path, "w", encoding="utf-8") as f: + pass + return out_path + + +def find_latest_step_dir(traj_root: Path) -> Path: + step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] + if not step_dirs: + raise FileNotFoundError(f"No step_* directories under {traj_root}") + step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) + return step_dirs[-1] + + +def main(): + parser = argparse.ArgumentParser(description="Convert Sokoban RL trajectories to LLM SFT chat JSONL") + parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)") + parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)") + parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data") + parser.add_argument("--max_actions", type=int, default=15, help="Max actions cap for filtering and counter display") + args = parser.parse_args() + + repo_root = Path(__file__).resolve().parents[1] + run_dir = Path(args.run_dir) + traj_root = run_dir / "trajectories" + if not traj_root.exists(): + raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") + + step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) + output_dir = run_dir / "sft" + out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed, max_actions=args.max_actions) + print(f"SFT data written to: {out_path}") + + +if __name__ == "__main__": + main() diff --git a/scripts/convert_rl_to_sft_sudoku.py b/scripts/convert_rl_to_sft_sudoku.py new file mode 100644 index 0000000000000000000000000000000000000000..f86254d4ddb3783b500a1a14eea3418b25eef6bb --- /dev/null +++ b/scripts/convert_rl_to_sft_sudoku.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +import argparse +import json +import math +from pathlib import Path +from typing import List, Tuple, Set, Dict + +def infer_grid_size_from_state_len(n: int) -> int: + """Given flattened one-hot length n = G*G*(G+1), solve for integer G.""" + for G in range(2, 17): + if G * G * (G + 1) == n: + return G + raise ValueError(f"Cannot infer grid size from state length {n}") + +def state_to_matrix(state_vec: List[float], G: int) -> List[List[int]]: + """Convert one-hot vector to GxG integer matrix.""" + cell_dim = G + 1 + matrix = [] + for r in range(G): + row = [] + for c in range(G): + base = (r * G + c) * cell_dim + cell_data = state_vec[base : base + cell_dim] + # argmax to find value + val = 0 + max_v = -1e9 + for k, v in enumerate(cell_data): + if v > max_v: + max_v = v + val = k + row.append(val) + matrix.append(row) + return matrix + +def check_conflict(grid: List[List[int]], r: int, c: int, val: int, G: int) -> bool: + """Check if placing val at (r,c) causes a conflict in current grid.""" + if val == 0: + return False + + # Row check + for j in range(G): + if j != c and grid[r][j] == val: + return True + # Col check + for i in range(G): + if i != r and grid[i][c] == val: + return True + # Box check + box_size = int(math.sqrt(G)) + br, bc = (r // box_size) * box_size, (c // box_size) * box_size + for i in range(br, br + box_size): + for j in range(bc, bc + box_size): + if (i, j) != (r, c) and grid[i][j] == val: + return True + return False + +def get_valid_moves(grid: List[List[int]], G: int) -> Dict[Tuple[int, int], List[int]]: + """Compute valid numbers for all empty cells.""" + valid_moves = {} + box_size = int(math.sqrt(G)) + + for r in range(G): + for c in range(G): + if grid[r][c] == 0: + possibles = [] + for v in range(1, G + 1): + is_row_ok = all(grid[r][j] != v for j in range(G)) + is_col_ok = all(grid[i][c] != v for i in range(G)) + br, bc = (r // box_size) * box_size, (c // box_size) * box_size + is_box_ok = True + for i in range(br, br + box_size): + for j in range(bc, bc + box_size): + if grid[i][j] == v: + is_box_ok = False + break + if is_row_ok and is_col_ok and is_box_ok: + possibles.append(v) + if possibles: + valid_moves[(r + 1, c + 1)] = possibles # 1-indexed keys + return valid_moves + +def render_ascii_board(grid: List[List[int]], initial_grid: List[List[int]], G: int) -> str: + """Render the board in the rich ASCII format seen in logs.""" + box_size = int(math.sqrt(G)) + lines = [] + + header = "=" * 50 + "\nSUDOKU PUZZLE\n" + "=" * 50 + lines.append(header) + + for r in range(G): + if r > 0 and r % box_size == 0: + row_sep = [] + for c in range(G): + if c > 0 and c % box_size == 0: + row_sep.append("-") + row_sep.append("----") + lines.append("-" * (G * 4 + int(G/box_size)*2)) + + row_str = [] + for c in range(G): + if c > 0 and c % box_size == 0: + row_str.append("|") + + val = grid[r][c] + is_init = (initial_grid[r][c] != 0) + + if val == 0: + cell_str = " . " + else: + is_conflict = check_conflict(grid, r, c, val, G) + if is_conflict and not is_init: + cell_str = f"*{val}*" + elif is_init: + cell_str = f"[{val}]" + else: + cell_str = f" {val} " # User placed + + row_str.append(cell_str) + + lines.append("".join(row_str)) + + lines.append("\nLegend: [N]=initial cell, N=user-placed, *N*=conflict, .=empty") + return "\n".join(lines) + +def decode_action(action_id: int, G: int) -> Tuple[int, int, int]: + """Map discrete id -> 1-indexed (row, col, num).""" + row0 = action_id // (G * G) + rem = action_id % (G * G) + col0 = rem // G + num = (rem % G) + 1 + return row0 + 1, col0 + 1, num + +def build_messages_for_episode( + states: List[List[float]], + actions: List[int], + rewards: List[float], + max_tokens: int, + max_actions: int, +) -> List[dict]: + + # Infer G from first state + G = infer_grid_size_from_state_len(len(states[0])) + box_size = int(math.sqrt(G)) + + grid_history = [state_to_matrix(s, G) for s in states] + initial_grid = grid_history[0] + + sys_msg = "You're a helpful assistant. " + + intro_prompt = ( + f"You are solving a Sudoku puzzle. Fill in the grid so that every row, column, " + f"and {box_size}x{box_size} box contains the numbers 1-{G} without repetition.\n" + "Initial cells are shown in [brackets] and cannot be modified. Empty cells are shown as dots (.).\n" + "Place numbers one at a time using the format: place 1 at row 2 col 3 or 1,2,3\n" + "The environment will provide feedback on valid/invalid moves and show conflicts if any occur.\n" + ) + + messages = [ + {"role": "system", "content": sys_msg}, + {"role": "user", "content": intro_prompt}, + ] + + # Main loop iterates over steps + for t in range(len(states)): + # If this state corresponds to a step where no action was taken (end of episode), stop + if t >= len(actions): + break + + current_grid = grid_history[t] + actions_left = max(0, max_actions - t) + + # --- 1. Prepare Reward String (Combined into this User turn) --- + # If t > 0, we have a reward from the previous action (at t-1) + reward_prefix = "" + if t > 0: + prev_reward = rewards[t-1] if (t-1) < len(rewards) else 0.0 + # Double newline to separate from the previous content logically + reward_prefix = f"Reward:\n{prev_reward}\n\n" + + # --- 2. Render Board --- + board_str = render_ascii_board(current_grid, initial_grid, G) + + # --- 3. Calc Valid Moves --- + valid_map = get_valid_moves(current_grid, G) + valid_str_lines = ["\n💡 VALID NUMBERS FOR EMPTY CELLS:"] + sorted_keys = sorted(valid_map.keys()) + if not sorted_keys: + valid_str_lines.append(" (None)") + else: + count = 0 + for (r, c) in sorted_keys: + vals = valid_map[(r,c)] + valid_str_lines.append(f" - ({r},{c}): {vals}") + count += 1 + if count > 15: + valid_str_lines.append(" ... (list truncated)") + break + # valid_section = "\n".join(valid_str_lines) + valid_section = "" + + # --- 4. Stats --- + total_cells = G * G + filled_cells = sum(1 for r in range(G) for c in range(G) if current_grid[r][c] != 0) + init_cells = sum(1 for r in range(G) for c in range(G) if initial_grid[r][c] != 0) + placed_cells = filled_cells - init_cells + if placed_cells < 0: placed_cells = 0 + + stats_section = ( + f"\nProgress: {filled_cells}/{total_cells} cells filled ({init_cells} initial, {placed_cells} placed)\n" + f"Steps: {t}/{max_actions}" + ) + + # --- 5. Construct User Content --- + turn_header = f"Turn {t + 1}:\nState:" + + constraint_prompt = ( + f"You have {actions_left} actions left. Always output: [Your thoughts] " + f" [your answer] with no extra text. Strictly follow this format. " + f"Max response length: {max_tokens} words (tokens)." + ) + + # COMBINE: Reward + Header + Board + Valid + Stats + Constraint + full_user_text = ( + f"{reward_prefix}{turn_header}\n" + f"{board_str}{valid_section}\n{stats_section}\n{constraint_prompt}" + ) + + # --- 6. Append to Messages --- + if t == 0: + # First turn: Append to the "Intro" user message + messages[-1]["content"] += ("\n" + full_user_text) + else: + # Subsequent turns: New User message containing (Reward + State) + messages.append({"role": "user", "content": full_user_text}) + + # --- 7. Assistant Response --- + r_act, c_act, n_act = decode_action(actions[t], G) + ans_text = f"place {n_act} at row {r_act} col {c_act}" + assistant_text = f" {ans_text}" + messages.append({"role": "assistant", "content": assistant_text}) + + return messages + +def convert_file(step_dir: Path, output_dir: Path, include_failed: bool = False, max_actions_override: int | None = None) -> Path: + traj_path = step_dir / "trajectories.jsonl" + metrics_path = step_dir / "metrics.json" + + if not traj_path.exists(): + raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") + + max_tokens = 150 + + output_dir.mkdir(parents=True, exist_ok=True) + out_path = output_dir / f"{step_dir.name}_sft.jsonl" + + global_step = None + if metrics_path.exists(): + try: + with open(metrics_path, "r", encoding="utf-8") as f: + m = json.load(f) + global_step = m.get("global_step") + except Exception: + pass + + written = 0 + with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: + for line in fin: + line = line.strip() + if not line: + continue + traj = json.loads(line) + ep_success = bool(traj.get("episode_success", False)) + if (not include_failed) and (not ep_success): + continue + + states = traj.get("states", []) + actions = traj.get("actions", []) + rewards = traj.get("rewards", []) + + if not states: + continue + + G = infer_grid_size_from_state_len(len(states[0])) + if max_actions_override is not None: + eff_max = max_actions_override + else: + eff_max = 20 if G == 4 else int(G*G * 1.5) + + messages = build_messages_for_episode( + states=states, + actions=actions, + rewards=rewards, + max_tokens=max_tokens, + max_actions=eff_max, + ) + + record = { + "messages": messages, + "meta": { + "episode_return": traj.get("episode_return", None), + "episode_success": ep_success, + "global_step": global_step, + }, + } + fout.write(json.dumps(record, ensure_ascii=False) + "\n") + written += 1 + + return out_path + +def find_latest_step_dir(traj_root: Path) -> Path: + step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] + if not step_dirs: + raise FileNotFoundError(f"No step_* directories under {traj_root}") + step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) + return step_dirs[-1] + +def main(): + parser = argparse.ArgumentParser(description="Convert Sudoku RL trajectories to LLM SFT chat JSONL (Rich Format, Merged Reward)") + parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)") + parser.add_argument("--step", default=None, help="Specific step directory name") + parser.add_argument("--include_failed", action="store_true", help="Include failed episodes") + parser.add_argument("--max_actions", type=int, default=None, help="Max actions cap display") + args = parser.parse_args() + + run_dir = Path(args.run_dir) + traj_root = run_dir / "trajectories" + if not traj_root.exists(): + raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") + + step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) + output_dir = run_dir / "sft" + + out_path = convert_file( + step_dir=step_dir, + output_dir=output_dir, + include_failed=args.include_failed, + max_actions_override=args.max_actions + ) + print(f"SFT data written to: {out_path}") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/download_data.py b/scripts/download_data.py new file mode 100644 index 0000000000000000000000000000000000000000..49e725acb91b9a41b2a9cf51392119d73dfa56a0 --- /dev/null +++ b/scripts/download_data.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 + +import os +from huggingface_hub import snapshot_download + +def download_datasets(repo_id="ZihanWang314/ragen-datasets", local_dir="data"): + """ + Download all datasets from Hugging Face Hub to local directory. + + Args: + repo_id (str): Hugging Face repository ID + local_dir (str): Local directory to save datasets + """ + print(f"Downloading datasets from {repo_id}...") + + url = "https://huggingface.co/datasets/Jiayi-Pan/Countdown-Tasks-3to4/resolve/main/data/train-00000-of-00001.parquet" + os.makedirs("data/countdown", exist_ok=True) + os.system(f"wget {url} -O data/countdown/train.parquet") + + # Create the data directory if it doesn't exist + os.makedirs(local_dir, exist_ok=True) + + try: + # Download the entire repository + snapshot_download( + repo_id=repo_id, + repo_type="dataset", + local_dir=local_dir, + local_dir_use_symlinks=False + ) + print(f"\nDatasets successfully downloaded to {local_dir}/") + + except Exception as e: + print(f"Error downloading datasets: {e}") + return False + +if __name__ == "__main__": + download_datasets() \ No newline at end of file diff --git a/scripts/nothink_dataset.py b/scripts/nothink_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..38ff28a378dca0bad2abd4bc07470d964bd7d2a8 --- /dev/null +++ b/scripts/nothink_dataset.py @@ -0,0 +1,58 @@ +import json + +# with open("/mnt/general/wanghy/RAGEN/runs/Game2048NoisyDQN__noisy_dqn_2048_refined__1__1765041200/sft/step_300000_sft_singleturn_slidewindows5_7000score.json") as f: +# dataset1 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/BanditDQN__dqn_bandit_nochangeenv__1__1764233298/sft/step_50000_sft.json") as f: + dataset2 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube1_1218/sft/step_999424_sft_singleturn.json") as f: + dataset3 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube2_1219_turn5/sft/step_999424_sft_singleturn.json") as f: + dataset4 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube3_1219_turn5_6000/sft/step_999424_sft_singleturn.json") as f: + dataset5 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__p0.9_slippery/sft/step_1986560_sft_slippery_singleturn.json") as f: + dataset6 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155447/sft/step_1000000_sft_singleturn.json") as f: + dataset7 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155464/sft/step_1000000_sft_singleturn.json") as f: + dataset8 = json.load(f) + +with open("/mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json") as f: + dataset9 = json.load(f) + + +data = dataset2 +dataset3 +dataset4 +dataset5 +dataset6 +dataset7 +dataset8 +dataset9 + +target_user_str = " [Your thoughts] " +target_assistant_str1 = "" +target_assistant_str2 = " " + +# 2. 遍历数据并进行替换 +# 假设 data 是一个列表,列表里每个元素都有 "messages" 字段 +if isinstance(data, list): + for entry in data: + if "messages" in entry: + for msg in entry["messages"]: + role = msg.get("role") + content = msg.get("content", "") + + # 处理 User + if role == "user": + if target_user_str in content: + msg["content"] = content.replace(target_user_str, "") + + # 处理 Assistant + elif role == "assistant": + if (target_assistant_str1 in content) or (target_assistant_str2 in content): + msg["content"] = content.replace(target_assistant_str1, "").replace(target_assistant_str2, "") +import pdb;pdb.set_trace() +# 3. 将修改后的数据保存为新文件 +with open("/mnt/general/wanghy/RAGEN/runs/multitask_nothink/sft_no2048.json", 'w', encoding='utf-8') as f: + json.dump(data, f, ensure_ascii=False, indent=2) diff --git a/scripts/ppl_2048.py b/scripts/ppl_2048.py new file mode 100644 index 0000000000000000000000000000000000000000..b9e1b3c938de060541d112693705b74258951cd1 --- /dev/null +++ b/scripts/ppl_2048.py @@ -0,0 +1,105 @@ +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer +import math + +# 1. 加载模型和分词器 +# 注意:第一次运行会自动从 Hugging Face 下载模型,约需 3GB 显存或内存 +model_name = "Qwen/Qwen2.5-1.5B-Instruct" +device = "cuda" if torch.cuda.is_available() else "cpu" + +print(f"Loading {model_name} on {device}...") +try: + tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) + model = AutoModelForCausalLM.from_pretrained(model_name, device_map=device, trust_remote_code=True) + model.eval() # 设置为评估模式 +except Exception as e: + print(f"Error loading model: {e}") + exit() + +def calculate_perplexity(text): + """ + 计算给定文本字符串的困惑度 (PPL) + """ + # 对输入文本进行编码 + encodings = tokenizer(text, return_tensors="pt") + input_ids = encodings.input_ids.to(device) + + # 计算 Loss (NLL) + # labels=input_ids 会让模型自动计算 CrossEntropyLoss + with torch.no_grad(): + outputs = model(input_ids, labels=input_ids) + loss = outputs.loss + + # PPL = exp(Loss) + ppl = torch.exp(loss).item() + return ppl + +# ========================================== +# 场景 1: 2048 游戏 +# ========================================== +def run_2048_test(): + # 模拟一个 2048 的原始符号状态 (Raw Symbolic State) + # 论文指出这种原始数字矩阵通常具有较高的 PPL + state_2048 = ( + "Turn 15:" + "#2 #4 #8 #2 \n . " + " #16 #64 #32 #512 \n " + ". #0 #2 #0 #256. . #0 #128 #0 #4 " + ) + "\nCurrent 2048 Grid:\nRow 1: [2, 4, 8, 2]\nRow 2: [16, 64, 32, 512]\nRow 3: [0, 2, 0, 256]\nRow 4: [0, 128, 0 4]\n" + # 2048 的随机基准:数字种类 (0, 2, 4, 8... 2048) 约为 12 种 + baseline_2048 = 12 + + ppl = calculate_perplexity(state_2048) + + print("-" * 30) + print("TASK: 2048 Game") + print(f"Input State:\n{state_2048}") + print(f"\nRandom Guess Baseline (#States): ~{baseline_2048}") + print(f"Model Perplexity (PPL): {ppl:.2f}") + + if ppl > baseline_2048: # 简单的倍数阈值判断 + print(">> 结论: OOD 环境 (模型看不懂这个数字矩阵)") + else: + print(">> 结论: In-Domain 环境 (模型对这种排列很熟悉)") + +# ========================================== +# 场景 2: 二阶魔方 (2x2 Rubik's Cube) +# ========================================== +def run_cube_test(): + # 模拟一个二阶魔方的展开图状态 (Raw Symbolic State) + # U=Up, F=Front, R=Right, D=Down, L=Left, B=Back + # 这里模拟一个打乱后的状态 + state_cube = ( + "Cube State:\n" + " U R\n" + " F U\n" + "L D F R B U\n" + "L B R D F L\n" + " D B\n" + " R B" + ) + + # 魔方的随机基准:只有 6 种颜色 + baseline_cube = 6 + + ppl = calculate_perplexity(state_cube) + + print("-" * 30) + print("TASK: 2x2 Rubik's Cube") + print(f"Input State:\n{state_cube}") + print(f"\nRandom Guess Baseline (#States): {baseline_cube}") + print(f"Model Perplexity (PPL): {ppl:.2f}") + + if ppl > baseline_cube * 2: + print(">> 结论: OOD 环境 (模型难以解析空间展开图)") + else: + print(">> 结论: In-Domain 环境") + +# ========================================== +# 执行测试 +# ========================================== +if __name__ == "__main__": + print("Starting PPL Calculation based on paper methodology[cite: 174]...") + run_2048_test() + run_cube_test() \ No newline at end of file diff --git a/scripts/ppy_cube.py b/scripts/ppy_cube.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/scripts/runs/bandit_jobs.sh b/scripts/runs/bandit_jobs.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3b4fbb3483748dd26d818b3e1e329e685f1cc6e --- /dev/null +++ b/scripts/runs/bandit_jobs.sh @@ -0,0 +1,227 @@ +#!/bin/bash +# Experiments: Bandit 3B base PPO/GRPO contrast (normal vs StarPO-S) with entropy and instruct ablations. +# Args: 400 steps, lr_actor=1e-6, lr_critic=1e-5, micro_batch=1, env tags=[Bandit] with BanditTest validation; StarPO-S disables reference, optional entropy/filter tweaks. + +# set -u -o pipefail +set +e + +GPUS=(0 1 2 3 4 5 6 7) +TOTAL_GPUS=${#GPUS[@]} +gpu_idx=0 + +maybe_flush() { + local needed=$1 + if (( gpu_idx + needed > TOTAL_GPUS )); then + wait + gpu_idx=0 + sleep 10 + fi +} + +init_singleton() { + local tag=${1:-$(basename "$0")} + local dir="/blob/v-zihanwang/tmp" + mkdir -p "$dir" + export SGL_FILE="${dir}/${tag}.lock" + + local ts + ts=$(date +%s) + + if [[ -f "$SGL_FILE" ]]; then + local last_modified + last_modified=$(stat -c %Y "$SGL_FILE") + if (( ts - last_modified < 60 )); then + echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting." + exit 0 + fi + fi + + echo "$ts" > "$SGL_FILE" + touch -d "@$ts" "$SGL_FILE" + + export SGL_TS="$ts" + + echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS" +} + +check_singleton() { + if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then + echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting." + exit 0 + fi + + if [[ ! -f "$SGL_FILE" ]]; then + echo "[singleton] check: lock file missing -> taken over by another script. exiting." + exit 0 + fi + + local mtime + mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0) + + if [[ "$mtime" != "$SGL_TS" ]]; then + echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting." + exit 0 + fi +} + +wait_sleep_reset_check() { + wait + sleep 15 + gpu_idx=0 + check_singleton +} + +launch_bandit() { + local run_name=$1 + local think=$2 + local algo=$3 + local mode=$4 + local n_gpus=${5:-2} + local total_training_steps=${6:-200} + shift 6 + local overrides=("$@") + + maybe_flush ${n_gpus} + + local estimator + if [[ "$algo" == "ppo" ]]; then + estimator="gae" + else + estimator="$algo" + fi + + local assigned=(${GPUS[@]:$gpu_idx:$n_gpus}) + local visible="" + for id in "${assigned[@]}"; do + if [[ -n "$visible" ]]; then + visible+="," + fi + visible+="$id" + done + gpu_idx=$((gpu_idx + n_gpus)) + + local storage_args=( + "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}" + "trainer.max_actor_ckpt_to_keep=1" + "trainer.max_critic_ckpt_to_keep=1" + ) + + local mode_overrides=() + case "$mode" in + normal) + mode_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.clip_ratio_high=0.20" + "actor_rollout_ref.rollout.rollout_filter_ratio=1" + "actor_rollout_ref.actor.use_ref=True" + ) + ;; + s) + mode_overrides=( + "actor_rollout_ref.actor.use_ref=False" + "algorithm.kl_ctrl.kl_coef=0.0" + "actor_rollout_ref.rollout.rollout_filter_ratio=0.5" + ) + ;; + det) + mode_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.clip_ratio_high=0.20" + "actor_rollout_ref.rollout.rollout_filter_ratio=1" + "actor_rollout_ref.actor.use_ref=True" + "agent_proxy.max_turn=1" + "agent_proxy.max_actions_per_turn=1" + "custom_envs.Bandit.max_actions_per_traj=1" + "+custom_envs.Bandit.env_config.hi_arm_loscore=0.25" + "+custom_envs.Bandit.env_config.hi_arm_hiscore=0.25" + ) + ;; + *) + echo "[bandit_jobs] Unknown mode: $mode" >&2 + return 1 + ;; + esac + + local base_args=( + "system.CUDA_VISIBLE_DEVICES=\"${visible}\"" + "trainer.n_gpus_per_node=${n_gpus}" + "trainer.experiment_name=${run_name}" + "trainer.total_training_steps=${total_training_steps}" + "trainer.save_freq=50" + "model_path=Qwen/Qwen2.5-3B" + "lora.rank=0" + "actor_rollout_ref.actor.optim.lr=1e-6" + "critic.optim.lr=1e-5" + "micro_batch_size_per_gpu=1" + "algorithm.adv_estimator=${estimator}" + "agent_proxy.enable_think=${think}" + "agent_proxy.max_turn=1" + "agent_proxy.max_actions_per_turn=1" + "es_manager.train.env_configs.tags=[Bandit]" + "es_manager.val.env_configs.tags=[Bandit,BanditTest]" + "es_manager.val.env_configs.n_groups=[32,32]" + "es_manager.val.env_groups=64" + ) + + local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2) + mkdir -p "$log_dir" + + echo "=== Running ${run_name} on GPUs ${visible} ===" + CUDA_VISIBLE_DEVICES="${visible}" \ + WANDB_RUN_ID=${run_name} \ + python train.py \ + "${base_args[@]}" \ + "${mode_overrides[@]}" \ + "${storage_args[@]}" \ + "${overrides[@]}" \ + 2>&1 | tee -a "$log_dir/log.log" & + + sleep 5 +} + +kl_coef_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.use_ref=True" +) + +entropy_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_ratio=0.5" + "actor_rollout_ref.rollout.rollout_filter_metric=entropy" +) + +entvar_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance" +) + +instruct_overrides=("model_path=Qwen/Qwen2.5-3B-Instruct") + +init_singleton "$(basename "${BASH_SOURCE[0]}")" # create a lock file with the name of the script + +# launch_bandit "bandit_3b_base_ppo_think_s_entvarfilter" True ppo s 8 400 "${entvar_filter_overrides[@]}" + +# launch_bandit "bandit_3b_base_grpo_think_normal_1" True grpo normal 8 200 + +launch_bandit "bandit_3b_base_ppo_think_s_2" True ppo s 8 400 + +# launch_bandit "bandit_3b_base_ppo_think_normal_2" True ppo normal 4 200 +# launch_bandit "bandit_3b_base_ppo_nothink_normal_2" False ppo normal 4 200 + +wait_sleep_reset_check + +# launch_bandit "bandit_3b_base_ppo_think_s" True ppo s 4 +# launch_bandit "bandit_3b_base_ppo_think_det" True ppo det 4 + +# wait_sleep_reset_check + +# launch_bandit "bandit_3b_base_ppo_think_s_klcoef0.001" True ppo s 4 "${kl_coef_overrides[@]}" +# launch_bandit "bandit_3b_base_ppo_think_s_entropyfilter" True ppo s 4 "${entropy_filter_overrides[@]}" + +# wait_sleep_reset_check + +# launch_bandit "bandit_3b_instruct_ppo_think_s" True ppo s 4 "${instruct_overrides[@]}" +# launch_bandit "bandit_3b_base_grpo_nothink_normal" False grpo normal 4 200 + +# wait_sleep_reset_check + +# launch_bandit "bandit_3b_base_grpo_nothink_normal" False grpo normal 4 +# launch_bandit "bandit_3b_base_ppo_think_s" True ppo s 8 400 diff --git a/scripts/runs/frozenlake_jobs.sh b/scripts/runs/frozenlake_jobs.sh new file mode 100644 index 0000000000000000000000000000000000000000..bc834f1d417be8a2df5e6610abcfbce0676a0da5 --- /dev/null +++ b/scripts/runs/frozenlake_jobs.sh @@ -0,0 +1,247 @@ +#!/bin/bash +# Experiments: FrozenLake 3B base PPO/GRPO (normal no-think) and StarPO-S variants including deterministic, entropy, and instruct ablations. +# Args: 400 steps, lr_actor=1e-6, lr_critic=1e-5, micro_batch=1, env tags=CoordFrozenLake; StarPO-S disables reference and optionally tweaks entropy/filtering. + +# set -u -o pipefail +set +e + +GPUS=(0 1 2 3 4 5 6 7) +TOTAL_GPUS=${#GPUS[@]} +gpu_idx=0 + +maybe_flush() { + local needed=$1 + if (( gpu_idx + needed > TOTAL_GPUS )); then + wait + gpu_idx=0 + sleep 10 + fi +} + +init_singleton() { + local tag=${1:-$(basename "$0")} + local dir="/blob/v-zihanwang/tmp" + mkdir -p "$dir" + export SGL_FILE="${dir}/${tag}.lock" + + local ts + ts=$(date +%s) + + if [[ -f "$SGL_FILE" ]]; then + local last_modified + last_modified=$(stat -c %Y "$SGL_FILE") + if (( ts - last_modified < 60 )); then + echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting." + exit 0 + fi + fi + + echo "$ts" > "$SGL_FILE" + touch -d "@$ts" "$SGL_FILE" + + export SGL_TS="$ts" + + echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS" +} + +check_singleton() { + if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then + echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting." + exit 0 + fi + + if [[ ! -f "$SGL_FILE" ]]; then + echo "[singleton] check: lock file missing -> taken over by another script. exiting." + exit 0 + fi + + local mtime + mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0) + + if [[ "$mtime" != "$SGL_TS" ]]; then + echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting." + exit 0 + fi +} + +wait_sleep_reset_check() { + wait + sleep 15 + gpu_idx=0 + check_singleton +} + +launch_frozenlake() { + local run_name=$1 + local think=$2 + local algo=$3 + local mode=$4 + local n_gpus=${5:-2} + local total_training_steps=${6:-200} + shift 6 + local overrides=("$@") + + maybe_flush ${n_gpus} + + local estimator + if [[ "$algo" == "ppo" ]]; then + estimator="gae" + else + estimator="$algo" + fi + + local assigned=(${GPUS[@]:$gpu_idx:$n_gpus}) + local visible="" + for id in "${assigned[@]}"; do + if [[ -n "$visible" ]]; then + visible+="," + fi + visible+="$id" + done + gpu_idx=$((gpu_idx + n_gpus)) + + local storage_args=( + "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}" + "trainer.max_actor_ckpt_to_keep=1" + "trainer.max_critic_ckpt_to_keep=1" + ) + + local mode_overrides=() + case "$mode" in + normal) + mode_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.clip_ratio_high=0.20" + "actor_rollout_ref.rollout.rollout_filter_ratio=1" + "actor_rollout_ref.actor.use_ref=True" + ) + ;; + s) + mode_overrides=( + "actor_rollout_ref.actor.use_ref=False" + "algorithm.kl_ctrl.kl_coef=0.0" + "actor_rollout_ref.rollout.rollout_filter_ratio=0.5" + ) + ;; + det) + mode_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.clip_ratio_high=0.20" + "actor_rollout_ref.rollout.rollout_filter_ratio=1" + "actor_rollout_ref.actor.use_ref=True" + "agent_proxy.max_turn=1" + "agent_proxy.max_actions_per_turn=10" + "+custom_envs.CoordFrozenLake.max_actions_per_traj=10" + "+custom_envs.CoordFrozenLake.env_config.is_slippery=False" + ) + ;; + void) + mode_overrides=( + "actor_rollout_ref.actor.use_ref=False" + "algorithm.kl_ctrl.kl_coef=0.0" + ) + ;; + *) + echo "[frozenlake_jobs] Unknown mode: $mode" >&2 + return 1 + ;; + esac + + local base_args=( + "system.CUDA_VISIBLE_DEVICES=\"${visible}\"" + "trainer.n_gpus_per_node=${n_gpus}" + "trainer.experiment_name=${run_name}" + "trainer.total_training_steps=${total_training_steps}" + "trainer.save_freq=50" + "model_path=Qwen/Qwen2.5-3B" + "lora.rank=0" + "actor_rollout_ref.actor.optim.lr=1e-6" + "critic.optim.lr=1e-5" + "micro_batch_size_per_gpu=1" + "algorithm.adv_estimator=${estimator}" + "agent_proxy.enable_think=${think}" + "es_manager.train.env_configs.tags=[CoordFrozenLake]" + "es_manager.val.env_configs.tags=[CoordFrozenLake]" + ) + + local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2) + mkdir -p "$log_dir" + + echo "=== Running ${run_name} on GPUs ${visible} ===" + CUDA_VISIBLE_DEVICES="${visible}" \ + WANDB_RUN_ID=${run_name} \ + python train.py \ + "${base_args[@]}" \ + "${mode_overrides[@]}" \ + "${storage_args[@]}" \ + "${overrides[@]}" \ + 2>&1 | tee -a "$log_dir/log.log" & + + sleep 5 +} + +wait_and_sleep() { + wait + sleep 15 + gpu_idx=0 +} + +kl_coef_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.use_ref=True" +) + +entropy_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_ratio=0.5" + "actor_rollout_ref.rollout.rollout_filter_metric=entropy" +) + +entvar_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance" +) + +filter_ratio_0_25_overrides=( + "actor_rollout_ref.rollout.rollout_filter_ratio=0.25" +) + +filter_ratio_0_75_overrides=( + "actor_rollout_ref.rollout.rollout_filter_ratio=0.75" +) + +instruct_overrides=("model_path=Qwen/Qwen2.5-3B-Instruct") + +init_singleton "$(basename "${BASH_SOURCE[0]}")" + +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_rolloutfilterratio0.25" True ppo void 8 1600 "${filter_ratio_0_25_overrides[@]}" +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_rolloutfilterratio0.75" True ppo void 8 800 "${filter_ratio_0_75_overrides[@]}" +launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_5" True ppo s 8 800 +wait_sleep_reset_check + +# Submitted experiments: + + + +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_entvarfilter" True ppo s 8 800 "${entvar_filter_overrides[@]}" +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_det" True ppo det 4 + + +# launch_frozenlake "frozenlake_coord_3b_base_ppo_nothink_normal" False ppo normal 4 +# launch_frozenlake "frozenlake_coord_3b_base_grpo_nothink_normal" False grpo normal 4 +# wait_sleep_reset_check + +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_normal" True ppo normal 4 +# launch_frozenlake "frozenlake_coord_3b_base_grpo_think_normal" True grpo normal 4 +# wait_sleep_reset_check + +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_klcoef0.001" True ppo s 4 400 "${kl_coef_overrides[@]}" +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_entropyfilter" True ppo s 4 400 "${entropy_filter_overrides[@]}" +# wait_sleep_reset_check + +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_normal_2" True ppo normal 4 400 +# launch_frozenlake "frozenlake_coord_3b_base_grpo_think_normal_2" True grpo normal 4 400 +# wait_sleep_reset_check + + +# launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_2" True ppo s 4 800 +# launch_frozenlake "frozenlake_coord_3b_base_grpo_nothink_normal_2" False grpo normal 4 400 +# wait_sleep_reset_check diff --git a/scripts/runs/sokoban_jobs.sh b/scripts/runs/sokoban_jobs.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1db6424240cc0481bd9f9c801151dd18b6515b1 --- /dev/null +++ b/scripts/runs/sokoban_jobs.sh @@ -0,0 +1,226 @@ +#!/bin/bash +# Experiments: Sokoban 3B base PPO normal vs StarPO-S variants (think/no-think, deterministic, entropy ablations). +# Args: 400 steps, lr_actor=1e-6, lr_critic=1e-5, micro_batch=2, env tags=CoordSokoban; StarPO-S disables reference, optional entropy coeff/filter overrides. + +# set -u -o pipefail +set +e + + +GPUS=(0 1 2 3 4 5 6 7) +TOTAL_GPUS=${#GPUS[@]} +gpu_idx=0 + +maybe_flush() { + local needed=$1 + if (( gpu_idx + needed > TOTAL_GPUS )); then + wait + gpu_idx=0 + sleep 10 + fi +} + +init_singleton() { + local tag=${1:-$(basename "$0")} + local dir="/blob/v-zihanwang/tmp" + mkdir -p "$dir" + export SGL_FILE="${dir}/${tag}.lock" + + local ts + ts=$(date +%s) + + if [[ -f "$SGL_FILE" ]]; then + local last_modified + last_modified=$(stat -c %Y "$SGL_FILE") + if (( ts - last_modified < 60 )); then + echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting." + exit 0 + fi + fi + + echo "$ts" > "$SGL_FILE" + touch -d "@$ts" "$SGL_FILE" + + export SGL_TS="$ts" + + echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS" +} + +check_singleton() { + if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then + echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting." + exit 0 + fi + + if [[ ! -f "$SGL_FILE" ]]; then + echo "[singleton] check: lock file missing -> taken over by another script. exiting." + exit 0 + fi + + local mtime + mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0) + + if [[ "$mtime" != "$SGL_TS" ]]; then + echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting." + exit 0 + fi +} + +wait_sleep_reset_check() { + wait + sleep 15 + gpu_idx=0 + check_singleton +} + +launch_sokoban() { + local run_name=$1 + local think=$2 + local algo=$3 + local mode=$4 + local n_gpus=${5:-2} + local total_training_steps=${6:-200} + shift 6 + local overrides=("$@") + + maybe_flush ${n_gpus} + + local estimator + if [[ "$algo" == "ppo" ]]; then + estimator="gae" + else + estimator="$algo" + fi + + local assigned=(${GPUS[@]:$gpu_idx:$n_gpus}) + local visible="" + for id in "${assigned[@]}"; do + if [[ -n "$visible" ]]; then + visible+="," + fi + visible+="$id" + done + gpu_idx=$((gpu_idx + n_gpus)) + + local storage_args=( + "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}" + "trainer.max_actor_ckpt_to_keep=1" + "trainer.max_critic_ckpt_to_keep=1" + ) + + local mode_overrides=() + case "$mode" in + normal) + mode_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.clip_ratio_high=0.20" + "actor_rollout_ref.rollout.rollout_filter_ratio=1" + "actor_rollout_ref.actor.use_ref=True" + ) + ;; + s) + mode_overrides=( + "actor_rollout_ref.actor.use_ref=False" + "algorithm.kl_ctrl.kl_coef=0.0" + "actor_rollout_ref.rollout.rollout_filter_ratio=0.5" + ) + ;; + det) + mode_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.clip_ratio_high=0.20" + "actor_rollout_ref.rollout.rollout_filter_ratio=1" + "actor_rollout_ref.actor.use_ref=True" + "agent_proxy.max_turn=1" + "agent_proxy.max_actions_per_turn=10" + "custom_envs.CoordSokoban.max_actions_per_traj=10" + ) + ;; + *) + echo "[sokoban_jobs] Unknown mode: $mode" >&2 + return 1 + ;; + esac + + local base_args=( + "system.CUDA_VISIBLE_DEVICES=\"${visible}\"" + "trainer.n_gpus_per_node=${n_gpus}" + "trainer.experiment_name=${run_name}" + "trainer.total_training_steps=${total_training_steps}" + "trainer.save_freq=50" + "model_path=Qwen/Qwen2.5-3B" + "lora.rank=0" + "actor_rollout_ref.actor.optim.lr=1e-6" + "critic.optim.lr=1e-5" + "micro_batch_size_per_gpu=1" + "algorithm.adv_estimator=${estimator}" + "agent_proxy.enable_think=${think}" + "es_manager.train.env_configs.tags=[CoordSokoban]" + "es_manager.val.env_configs.tags=[CoordSokoban]" + ) + + local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2) + mkdir -p "$log_dir" + + echo "=== Running ${run_name} on GPUs ${visible} ===" + CUDA_VISIBLE_DEVICES="${visible}" \ + WANDB_RUN_ID=${run_name} \ + python train.py \ + "${base_args[@]}" \ + "${mode_overrides[@]}" \ + "${storage_args[@]}" \ + "${overrides[@]}" \ + 2>&1 | tee -a "$log_dir/log.log" & + + sleep 5 +} + +# gpu_idx=0 +# # Wave 2: entropy ablations and instruct comparison +kl_coef_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.use_ref=True" +) + +entropy_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_ratio=0.5" + "actor_rollout_ref.rollout.rollout_filter_metric=entropy" +) + +entvar_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance" +) + +instruct_overrides=("model_path=Qwen/Qwen2.5-3B-Instruct") + + +lora_overrides=( + "lora.rank=64" + "lora.alpha=64" + "actor_rollout_ref.actor.optim.lr=1e-5" + "critic.optim.lr=1e-4" + "micro_batch_size_per_gpu=8" +) + +init_singleton "$(basename "${BASH_SOURCE[0]}")" + +launch_sokoban "sokoban_coord_3b_base_ppo_think_s_entvarfilter" True ppo s 8 800 "${entvar_filter_overrides[@]}" + +# launch_sokoban "sokoban_coord_3b_base_ppo_think_normal" True ppo normal 4 +# launch_sokoban "sokoban_coord_3b_base_ppo_nothink_normal" False ppo normal 4 +# wait_sleep_reset_check + +# launch_sokoban "sokoban_coord_3b_base_ppo_think_det" True ppo det 4 +# launch_sokoban "sokoban_coord_3b_base_ppo_think_normal_lora" True ppo normal 4 "${lora_overrides[@]}" +# wait_sleep_reset_check + + +# launch_sokoban "sokoban_coord_3b_instruct_ppo_think_s" True ppo s 4 400 "${instruct_overrides[@]}" +# launch_sokoban "sokoban_coord_3b_base_ppo_think_s_2" True ppo s 8 800 +# wait_sleep_reset_check + + +# launch_sokoban "sokoban_coord_3b_base_ppo_think_s_klcoef0.001" True ppo s 4 400 "${kl_coef_overrides[@]}" +# launch_sokoban "sokoban_coord_3b_base_ppo_think_s_entropyfilter" True ppo s 4 400 "${entropy_filter_overrides[@]}" +# wait_sleep_reset_check + + diff --git a/scripts/runs/webshop_budget_jobs.sh b/scripts/runs/webshop_budget_jobs.sh new file mode 100644 index 0000000000000000000000000000000000000000..607737883fcb502fba5c27a5236362e600ef7b00 --- /dev/null +++ b/scripts/runs/webshop_budget_jobs.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail + +MODEL="Qwen/Qwen2.5-3B-Instruct" +PROJ="budget_main" +BASE_DIR="/blob/v-zihanwang/budget_checkpoints" +DEVICES=\"0,1,2,3,4,5,6,7\" + +run_experiment() { + local turns=$1 + local exp_name=$2 + local out_dir="${BASE_DIR}/${exp_name}" + + if [[ "$turns" -ge 7 ]]; then + local max_len=15000 + local max_tok=15000 + else + local max_len=10000 + local max_tok=10000 + fi + + echo "=== Running ${exp_name} ===" + mkdir -p "${BASE_DIR}/${exp_name}" + + CUDA_VISIBLE_DEVICES="${DEVICES}" \ + WANDB_RUN_ID=${exp_name} \ + python train.py --config-name _6_webshop ${USE_PPO:-} \ + model_path="${MODEL}" \ + actor_rollout_ref.rollout.rollout_filter_ratio=1 \ + trainer.project_name="${PROJ}" \ + micro_batch_size_per_gpu=1 \ + trainer.experiment_name="${exp_name}" \ + es_manager.train.env_groups=8 es_manager.train.group_size=16 es_manager.train.env_configs.n_groups='[8]' \ + es_manager.val.env_groups=64 es_manager.val.group_size=8 es_manager.val.env_configs.n_groups='[64]' \ + system.CUDA_VISIBLE_DEVICES="${DEVICES}" trainer.n_gpus_per_node=8 actor_rollout_ref.rollout.tensor_model_parallel_size=8 \ + trainer.resume_mode=disable \ + trainer.total_training_steps=200 \ + trainer.save_freq=50 \ + agent_proxy.max_turn="${turns}" \ + actor_rollout_ref.rollout.max_model_len="${max_len}" actor_rollout_ref.rollout.max_num_batched_tokens="${max_tok}" \ + trainer.default_local_dir="${out_dir}" \ + trainer.max_actor_ckpt_to_keep=4 \ + trainer.max_critic_ckpt_to_keep=4 \ + custom_envs.WebShop.max_actions_per_traj="${turns}" \ + actor_rollout_ref.actor.use_ref=False \ + trainer.nnodes=1 +} + +main() { + # run_experiment 3 "webshop_starpos_grpo_3b_small_max_3turns" + # run_experiment 4 "webshop_starpos_grpo_3b_small_max_4turns" + # run_experiment 5 "webshop_starpos_grpo_3b_small_max_5turns" + # run_experiment 6 "webshop_starpos_grpo_3b_small_max_6turns" + # run_experiment 7 "webshop_starpos_grpo_3b_small_max_7turns" +} + +main "$@" diff --git a/scripts/runs/webshop_jobs.sh b/scripts/runs/webshop_jobs.sh new file mode 100644 index 0000000000000000000000000000000000000000..22b4891b172164ac13018845527bb5c3fc201258 --- /dev/null +++ b/scripts/runs/webshop_jobs.sh @@ -0,0 +1,165 @@ +#!/bin/bash +# Experiments: WebShop 3B StarPO-S sweeps (base vs instruct, entropy/n-gram filtering, entropy ablation). +# Args: 400 steps, lr_actor=1e-6, lr_critic=1e-5, micro_batch=1, actor rollout max_len=15000, env tags=WebShop, StarPO-S disables reference. + +# set -u -o pipefail +set +e + + +GPUS=(0 1 2 3 4 5 6 7) +TOTAL_GPUS=${#GPUS[@]} +gpu_idx=0 + +maybe_flush() { + local needed=$1 + if (( gpu_idx + needed > TOTAL_GPUS )); then + wait + gpu_idx=0 + sleep 10 + fi +} + +init_singleton() { + local tag=${1:-$(basename "$0")} + local dir="/blob/v-zihanwang/tmp" + mkdir -p "$dir" + export SGL_FILE="${dir}/${tag}.lock" + + local ts + ts=$(date +%s) + + if [[ -f "$SGL_FILE" ]]; then + local last_modified + last_modified=$(stat -c %Y "$SGL_FILE") + if (( ts - last_modified < 60 )); then + echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting." + exit 0 + fi + fi + + echo "$ts" > "$SGL_FILE" + touch -d "@$ts" "$SGL_FILE" + + export SGL_TS="$ts" + + echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS" +} + +check_singleton() { + if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then + echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting." + exit 0 + fi + + if [[ ! -f "$SGL_FILE" ]]; then + echo "[singleton] check: lock file missing -> taken over by another script. exiting." + exit 0 + fi + + local mtime + mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0) + + if [[ "$mtime" != "$SGL_TS" ]]; then + echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting." + exit 0 + fi +} + +wait_sleep_reset_check() { + wait + sleep 15 + gpu_idx=0 + check_singleton +} + +launch_webshop_s() { + local run_name=$1 + local n_gpus=${2:-4} + local total_training_steps=${3:-200} + shift 3 + local overrides=("$@") + + maybe_flush ${n_gpus} + + local assigned=(${GPUS[@]:$gpu_idx:$n_gpus}) + local visible="" + for id in "${assigned[@]}"; do + if [[ -n "$visible" ]]; then + visible+="," + fi + visible+="$id" + done + gpu_idx=$((gpu_idx + n_gpus)) + + local storage_args=( + "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}" + "trainer.max_actor_ckpt_to_keep=1" + "trainer.max_critic_ckpt_to_keep=1" + ) + + local base_args=( + "system.CUDA_VISIBLE_DEVICES=\"${visible}\"" + "trainer.n_gpus_per_node=${n_gpus}" + "trainer.experiment_name=${run_name}" + "trainer.total_training_steps=${total_training_steps}" + "trainer.save_freq=25" + "model_path=Qwen/Qwen2.5-3B" + "lora.rank=0" + "actor_rollout_ref.actor.optim.lr=1e-6" + "critic.optim.lr=1e-5" + "micro_batch_size_per_gpu=1" + "algorithm.adv_estimator=gae" + "agent_proxy.enable_think=True" + "agent_proxy.max_turn=8" + "agent_proxy.max_actions_per_turn=1" + "actor_rollout_ref.actor.use_ref=False" + "algorithm.kl_ctrl.kl_coef=0.0" + "actor_rollout_ref.rollout.rollout_filter_ratio=0.5" + "actor_rollout_ref.rollout.max_model_len=15000" + "actor_rollout_ref.rollout.max_num_batched_tokens=15000" + "es_manager.train.env_configs.tags=[WebShop]" + "es_manager.val.env_configs.tags=[WebShop]" + ) + + local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2) + mkdir -p "$log_dir" + + echo "=== Running ${run_name} on GPUs ${visible} ===" + CUDA_VISIBLE_DEVICES="${visible}" \ + WANDB_RUN_ID=${run_name} \ + python train.py \ + "${base_args[@]}" \ + "${mode_overrides[@]}" \ + "${storage_args[@]}" \ + "${overrides[@]}" \ + 2>&1 | tee -a "$log_dir/log.log" & + + sleep 5 +} + +kl_coef_overrides=( + "algorithm.kl_ctrl.kl_coef=0.001" + "actor_rollout_ref.actor.use_ref=True" +) + +entropy_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_metric=entropy" +) + +entvar_filter_overrides=( + "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance" +) + +init_singleton "$(basename "${BASH_SOURCE[0]}")" +launch_webshop_s "webshop_3b_base_ppo_think_s_entvarfilter" 8 400 "${entvar_filter_overrides[@]}" +wait_sleep_reset_check + +# launch_webshop_s "webshop_3b_base_ppo_think_s" 8 400 +# wait_sleep_reset_check + +# launch_webshop_s "webshop_3b_base_ppo_think_s_entropyfilter" 8 400 "${entropy_filter_overrides[@]}" +# wait_sleep_reset_check + +# launch_webshop_s "webshop_3b_base_ppo_think_s_klcoef0.001" 8 400 "${kl_coef_overrides[@]}" +# wait_sleep_reset_check + diff --git a/scripts/setup_ragen.md b/scripts/setup_ragen.md new file mode 100644 index 0000000000000000000000000000000000000000..08e362efd827866c48c3c703147b7366f1b3eb8d --- /dev/null +++ b/scripts/setup_ragen.md @@ -0,0 +1,26 @@ +# Manual Scripts to Setup Environment +```bash +conda create -n ragen python=3.9 -y +conda activate ragen + + +git clone git@github.com:ZihanWang314/ragen.git +cd ragen + +pip install -e . +pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124 + +# Optional: to install flash-attn, you may need to install cuda-toolkit first if you don't have +conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y +export CUDA_HOME=$CONDA_PREFIX # /opt/conda/envs/zero +pip3 install flash-attn --no-build-isolation + +pip install -r requirements.txt + +git submodule init +git submodule update +cd verl +pip install -e . +cd .. + +``` diff --git a/scripts/setup_ragen.sh b/scripts/setup_ragen.sh new file mode 100644 index 0000000000000000000000000000000000000000..85a93c4eacfcc24e4d311528b2335c4e98f81ba6 --- /dev/null +++ b/scripts/setup_ragen.sh @@ -0,0 +1,151 @@ +#!/bin/bash + +# Exit on error +set -e + +# Function to check if CUDA is available +check_cuda() { + if command -v nvidia-smi &> /dev/null; then + echo "CUDA GPU detected" + return 0 + else + echo "No CUDA GPU detected" + return 1 + fi +} + +# Function to check if conda is available +check_conda() { + if command -v conda &> /dev/null; then + echo "Conda is available" + return 0 + else + echo "Conda is not installed. Please install Conda first." + return 1 + fi +} + +# Colors for output +GREEN='\033[0;32m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Print step with color +print_step() { + echo -e "${BLUE}[Step] ${1}${NC}" +} + +# Main installation process +main() { + # Check prerequisites + check_conda || exit 1 + + # Create and activate conda environment + # if not exists, create it + if ! conda env list | grep -q "ragen"; then + print_step "Creating conda environment 'ragen' with Python 3.12..." + conda create -n ragen python=3.12 -y + else + print_step "Conda environment 'ragen' already exists" + fi + + # Need to source conda for script environment + eval "$(conda shell.bash hook)" + conda activate ragen + + # Install package in editable mode + print_step "setting up verl..." + git submodule init + git submodule update + cd verl + pip install -e . --no-dependencies # we put dependencies in requirements.txt + cd .. + + # Install package in editable mode + print_step "Installing ragen package..." + pip install -e . + + # Install PyTorch with CUDA if available + if check_cuda; then + print_step "CUDA detected, checking CUDA version..." + + if command -v nvcc &> /dev/null; then + nvcc_version=$(nvcc --version | grep "release" | awk '{print $6}' | cut -c2-) + nvcc_major=$(echo $nvcc_version | cut -d. -f1) + nvcc_minor=$(echo $nvcc_version | cut -d. -f2) + + print_step "Found NVCC version: $nvcc_version" + + if [[ "$nvcc_major" -gt 12 || ("$nvcc_major" -eq 12 && "$nvcc_minor" -ge 1) ]]; then + print_step "CUDA $nvcc_version is already installed and meets requirements (>=12.4)" + export CUDA_HOME=${CUDA_HOME:-$(dirname $(dirname $(which nvcc)))} + else + print_step "CUDA version < 12.4, installing CUDA toolkit 12.4..." + conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y + export CUDA_HOME=$CONDA_PREFIX + fi + else + print_step "NVCC not found, installing CUDA toolkit 12.4..." + conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y + export CUDA_HOME=$CONDA_PREFIX + fi + + print_step "Installing PyTorch with CUDA support..." + pip install torch==2.5.0 --index-url https://download.pytorch.org/whl/cu124 + + print_step "Installing flash-attention..." + # pip3 install flash-attn==2.7.4.post1 --no-build-isolation + else + print_step "Installing PyTorch without CUDA support..." + pip install torch==2.4.0 + fi + + # Install remaining requirements + print_step "Installing additional requirements..." + pip install -r requirements.txt + + print_step "Downloading data..." + python scripts/download_data.py + + echo -e "${GREEN}Installation completed successfully!${NC}" + echo "To activate the environment, run: conda activate ragen" + + # export CMAKE_POLICY_VERSION_MINIMUM=3.5 && pip install alfworld[full] + # alfworld-download + + # installing webshop + print_step "Installing webshop dependencies..." + conda install -c pytorch faiss-cpu -y + sudo apt update + sudo apt install default-jdk -y + conda install -c conda-forge openjdk=21 maven -y + + # Install remaining requirements + print_step "Installing additional requirements..." + pip install -r requirements.txt + + # webshop installation, model loading + pip install -e external/webshop-minimal/ --no-dependencies + python -m spacy download en_core_web_sm + python -m spacy download en_core_web_lg + + print_step "Downloading data..." + python scripts/download_data.py + + # Optional: download full data set + print_step "Downloading full data set..." + conda install conda-forge::gdown + mkdir -p external/webshop-minimal/webshop_minimal/data/full + cd external/webshop-minimal/webshop_minimal/data/full + # gdown https://drive.google.com/uc?id=1A2whVgOO0euk5O13n2iYDM0bQRkkRduB # items_shuffle + # gdown https://drive.google.com/uc?id=1s2j6NgHljiZzQNL3veZaAiyW_qDEgBNi # items_ins_v2 + cd ../../../../.. + + echo -e "${GREEN}Installation completed successfully!${NC}" + echo "To activate the environment, run: conda activate ragen" + + +} + +# Run main installation +main diff --git a/scripts/setup_ragen_webshop.sh.old b/scripts/setup_ragen_webshop.sh.old new file mode 100644 index 0000000000000000000000000000000000000000..0344e511c1fbc72fcf6afb3e368ab49de5a82bea --- /dev/null +++ b/scripts/setup_ragen_webshop.sh.old @@ -0,0 +1,144 @@ +#!/bin/bash + +# Exit on error +set -e + +# Function to check if CUDA is available +check_cuda() { + if command -v nvidia-smi &> /dev/null; then + echo "CUDA GPU detected" + return 0 + else + echo "No CUDA GPU detected" + return 1 + fi +} + +# Function to check if conda is available +check_conda() { + if command -v conda &> /dev/null; then + echo "Conda is available" + return 0 + else + echo "Conda is not installed. Please install Conda first." + return 1 + fi +} + +# Colors for output +GREEN='\033[0;32m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Print step with color +print_step() { + echo -e "${BLUE}[Step] ${1}${NC}" +} + +# Main installation process +main() { + # Check prerequisites + check_conda || exit 1 + + # Create and activate conda environment + # if not exists, create it + if ! conda env list | grep -q "ragen"; then + print_step "Creating conda environment 'ragen' with Python 3.12..." + conda create -n ragen python=3.12 -y + else + print_step "Conda environment 'ragen' already exists" + fi + + # Need to source conda for script environment + eval "$(conda shell.bash hook)" + conda activate ragen + + # Clone repository + # print_step "Cloning ragen repository..." + # git clone git@github.com:ZihanWang314/ragen.git + # cd ragen + + # Install package in editable mode + print_step "setting up verl..." + git submodule init + git submodule update + cd verl + pip install -e . --no-dependencies # we put dependencies in RAGEN/requirements.txt + cd .. + + # Install package in editable mode + print_step "Installing ragen package..." + pip install -e . + + # Install PyTorch with CUDA if available + if check_cuda; then + print_step "CUDA detected, checking CUDA version..." + + if command -v nvcc &> /dev/null; then + nvcc_version=$(nvcc --version | grep "release" | awk '{print $6}' | cut -c2-) + nvcc_major=$(echo $nvcc_version | cut -d. -f1) + nvcc_minor=$(echo $nvcc_version | cut -d. -f2) + + print_step "Found NVCC version: $nvcc_version" + + if [[ "$nvcc_major" -gt 12 || ("$nvcc_major" -eq 12 && "$nvcc_minor" -ge 1) ]]; then + print_step "CUDA $nvcc_version is already installed and meets requirements (>=12.4)" + export CUDA_HOME=${CUDA_HOME:-$(dirname $(dirname $(which nvcc)))} + else + print_step "CUDA version < 12.4, installing CUDA toolkit 12.4..." + conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y + export CUDA_HOME=$CONDA_PREFIX + fi + else + print_step "NVCC not found, installing CUDA toolkit 12.4..." + conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y + export CUDA_HOME=$CONDA_PREFIX + fi + + print_step "Installing PyTorch with CUDA support..." + pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124 + + print_step "Installing flash-attention..." + pip3 install flash-attn --no-build-isolation + else + print_step "Installing PyTorch without CUDA support..." + pip install torch==2.6.0 + fi + + # TODO: merge this with the main setup script with an option to install webshop + # Install if you want to use webshop + conda install -c pytorch faiss-cpu -y + sudo apt update + sudo apt install default-jdk + conda install -c conda-forge openjdk=21 maven -y + + # Install remaining requirements + print_step "Installing additional requirements..." + pip install -r requirements.txt + + # webshop installation, model loading + pip install -e external/webshop-minimal/ --no-dependencies + python -m spacy download en_core_web_sm + python -m spacy download en_core_web_lg + + print_step "Downloading data..." + python scripts/download_data.py + + # Optional: download full data set + print_step "Downloading full data set..." + conda install conda-forge::gdown + mkdir -p external/webshop-minimal/webshop_minimal/data/full + cd external/webshop-minimal/webshop_minimal/data/full + gdown https://drive.google.com/uc?id=1A2whVgOO0euk5O13n2iYDM0bQRkkRduB # items_shuffle + gdown https://drive.google.com/uc?id=1s2j6NgHljiZzQNL3veZaAiyW_qDEgBNi # items_ins_v2 + cd ../../../../.. + + echo -e "${GREEN}Installation completed successfully!${NC}" + echo "To activate the environment, run: conda activate ragen" + + # export CMAKE_POLICY_VERSION_MINIMUM=3.5 && pip install alfworld[full] + # alfworld-download +} + +# Run main installation +main diff --git a/scripts/setup_webshop.sh b/scripts/setup_webshop.sh new file mode 100644 index 0000000000000000000000000000000000000000..6486dd82ab3b2b1c63c881426740fbb2362db270 --- /dev/null +++ b/scripts/setup_webshop.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +# Exit on error +set -e + +echo "Setting up webshop..." +echo "NOTE: please run scripts/setup_ragen.sh before running this script" + +# Colors for output +GREEN='\033[0;32m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Print step with color +print_step() { + echo -e "${BLUE}[Step] ${1}${NC}" +} + +# Main installation process +# TODO: merge this with the main setup script with an option to install webshop +# Install if you want to use webshop +conda install -c pytorch faiss-cpu -y +sudo apt update +sudo apt install default-jdk -y +conda install -c conda-forge openjdk=21 maven -y + +# Install remaining requirements +print_step "Installing additional requirements..." +pip install -r requirements.txt + +# webshop installation, model loading +pip install -e external/webshop-minimal/ --no-dependencies +python -m spacy download en_core_web_sm +python -m spacy download en_core_web_lg + +print_step "Downloading data..." +python scripts/download_data.py + +# Optional: download full data set +print_step "Downloading full data set..." +conda install conda-forge::gdown +mkdir -p external/webshop-minimal/webshop_minimal/data/full +cd external/webshop-minimal/webshop_minimal/data/full +gdown https://drive.google.com/uc?id=1A2whVgOO0euk5O13n2iYDM0bQRkkRduB # items_shuffle +gdown https://drive.google.com/uc?id=1s2j6NgHljiZzQNL3veZaAiyW_qDEgBNi # items_ins_v2 +cd ../../../../.. + +echo -e "${GREEN}Installation completed successfully!${NC}" +echo "To activate the environment, run: conda activate ragen" + diff --git a/scripts/synthesize_bon.sh b/scripts/synthesize_bon.sh new file mode 100644 index 0000000000000000000000000000000000000000..e9335530a53cdbf2a609af0be803604d9948ea9e --- /dev/null +++ b/scripts/synthesize_bon.sh @@ -0,0 +1,69 @@ +# python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \ +# --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn.json \ +# --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \ +# --output-prefix withthink_fulltraj_sa \ +# --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ +# --tensor-parallel-size 4 \ +# --n 8 \ +# --batch-size 32 \ +# --judge-batch-size 32 + +# python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \ +# --input /mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155447/sft/step_1000000_sft_singleturn.json \ +# --output-dir /mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155447/sft/ \ +# --output-prefix withthink_fulltraj_sa \ +# --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ +# --tensor-parallel-size 4 \ +# --n 8 \ +# --batch-size 32 \ +# --judge-batch-size 32 + +# python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \ +# --input /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__p0.9_slippery/sft/step_1986560_sft_slippery_singleturn.json \ +# --output-dir /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__p0.9_slippery/sft/ \ +# --output-prefix withthink_fulltraj_sa \ +# --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ +# --tensor-parallel-size 4 \ +# --n 8 \ +# --batch-size 32 \ +# --judge-batch-size 32 + +# python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \ +# --input /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__1__1763646695/sft/step_1986560_sft_noslippery_singleturn.json \ +# --output-dir /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__1__1763646695/sft/ \ +# --output-prefix withthink_fulltraj_sa \ +# --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ +# --tensor-parallel-size 4 \ +# --n 8 \ +# --batch-size 32 \ +# --judge-batch-size 32 + +# python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \ +# --input /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube1_1218/sft/step_999424_sft_singleturn.json \ +# --output-dir /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube1_1218/sft/ \ +# --output-prefix withthink_fulltraj_sa \ +# --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ +# --tensor-parallel-size 4 \ +# --n 8 \ +# --batch-size 32 \ +# --judge-batch-size 32 + +python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \ + --input /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube2_1219_turn5/sft/step_999424_sft_singleturn.json \ + --output-dir /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube2_1219_turn5/sft/ \ + --output-prefix withthink_fulltraj_sa \ + --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ + --tensor-parallel-size 4 \ + --n 8 \ + --batch-size 32 \ + --judge-batch-size 32 + +# python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \ +# --input /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube3_1219_turn5_6000/sft/step_999424_sft_singleturn.json \ +# --output-dir /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube3_1219_turn5_6000/sft/ \ +# --output-prefix withthink_fulltraj_sa \ +# --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ +# --tensor-parallel-size 4 \ +# --n 8 \ +# --batch-size 32 \ +# --judge-batch-size 32 diff --git a/scripts/synthesize_think_bon.py b/scripts/synthesize_think_bon.py new file mode 100644 index 0000000000000000000000000000000000000000..a08db6b511d6c43f90f30096da55ab0ed9c6b6bf --- /dev/null +++ b/scripts/synthesize_think_bon.py @@ -0,0 +1,827 @@ +#!/usr/bin/env python3 +"""Synthesize traces for SFT singleturn trajectories with BoN + judge. + +This script is intentionally environment-agnostic. It assumes a JSON list of rows +with the common RAGEN SFT shape: + + {"messages": [{"role": "system"}, {"role": "user"}, {"role": "assistant"}, ...], + "meta": {"source_id": ..., "turns": ..., "total_turns": ...}} + +For each source_id, the complete trajectory row is selected, one reasoning trace +is synthesized per turn, and the selected traces are written back to every +cumulative singleturn prefix while keeping every original ... +block exactly unchanged. + + +python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon.py \ + --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json \ + --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \ + --output-prefix step_999424_sft_singleturn_withthink \ + --versions sa,sas \ + --model /mnt/general/share/model/Qwen/Qwen2.5-7B-Instruct \ + --tensor-parallel-size 4 \ + --n 8 \ + --batch-size 32 \ + --judge-batch-size 32 \ + --limit-sources 50 +""" + +from __future__ import annotations + +import argparse +import copy +import json +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple + + +ANSWER_RE = re.compile(r".*?", re.IGNORECASE | re.DOTALL) +THINK_RE = re.compile(r"(.*?)", re.IGNORECASE | re.DOTALL) +JSON_OBJ_RE = re.compile(r"\{.*\}", re.DOTALL) + + +@dataclass +class TurnExample: + source_id: Any + turn_idx: int + total_turns: int + user_content: str + assistant_content: str + answer_block: str + next_user_content: Optional[str] + + +@dataclass +class FullTrajectory: + source_id: Any + sys_prefix: List[Dict[str, Any]] + pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] + meta: Dict[str, Any] + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Synthesize expert-action thinking traces with per-turn BoN and LLM judge." + ) + parser.add_argument("--input", "-i", type=Path, required=True, help="Input SFT JSON list.") + parser.add_argument( + "--output-dir", + type=Path, + default=None, + help="Directory for output files. Defaults to input parent.", + ) + parser.add_argument( + "--output-prefix", + default=None, + help="Output filename prefix. Defaults to input stem.", + ) + parser.add_argument( + "--versions", + default="sa,sas", + help="Comma-separated versions: sa and/or sas. sa uses s,a; sas uses s,a,s'.", + ) + parser.add_argument("--model", default=None, help="HF model path for tokenizer + vLLM.") + parser.add_argument("--judge-model", default=None, help="Optional separate judge model path.") + parser.add_argument("--n", type=int, default=8, help="BoN candidates per turn.") + parser.add_argument( + "--mode", + default="per_turn", + choices=["per_turn"], + help="BoN mode. Currently only independent per-turn BoN is implemented.", + ) + parser.add_argument("--limit-sources", type=int, default=None, help="Pilot limit by source_id count.") + parser.add_argument("--source-ids", default="", help="Optional comma-separated source_id allowlist.") + parser.add_argument("--batch-size", type=int, default=64, help="Prompt batch size for generation.") + parser.add_argument("--judge-batch-size", type=int, default=64, help="Prompt batch size for judge.") + parser.add_argument("--temperature", type=float, default=0.7) + parser.add_argument("--top-p", type=float, default=0.95) + parser.add_argument("--top-k", type=int, default=-1) + parser.add_argument("--max-tokens", type=int, default=160, help="Max tokens for think generation.") + parser.add_argument("--judge-temperature", type=float, default=0.0) + parser.add_argument("--judge-max-tokens", type=int, default=768) + parser.add_argument("--tensor-parallel-size", type=int, default=1) + parser.add_argument("--judge-tensor-parallel-size", type=int, default=None) + parser.add_argument("--dtype", default="auto") + parser.add_argument("--gpu-memory-utilization", type=float, default=0.9) + parser.add_argument("--max-model-len", type=int, default=None) + parser.add_argument("--trust-remote-code", action="store_true") + parser.add_argument("--min-judge-score", type=float, default=3.0) + parser.add_argument("--save-candidates", action="store_true", help="Store all candidates in report.") + parser.add_argument( + "--selected-only", + action="store_true", + help="Write only rows whose source_id was selected by --limit-sources/--source-ids.", + ) + parser.add_argument("--no-cache", action="store_true", help="Disable JSONL cache/resume.") + parser.add_argument("--dry-run", action="store_true", help="Do not load vLLM; create deterministic mock thinks.") + parser.add_argument("--indent", type=int, default=2, help="JSON output indent. Use -1 for compact.") + return parser.parse_args() + + +def load_json_list(path: Path) -> List[Dict[str, Any]]: + with path.open("r", encoding="utf-8") as f: + data = json.load(f) + if not isinstance(data, list): + raise ValueError(f"Expected JSON list at {path}, got {type(data).__name__}") + if not all(isinstance(row, dict) for row in data): + raise ValueError(f"Expected all rows to be objects in {path}") + return data + + +def dump_json(path: Path, data: Any, indent: int) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + kwargs = {"ensure_ascii": False} + if indent >= 0: + kwargs["indent"] = indent + with path.open("w", encoding="utf-8") as f: + json.dump(data, f, **kwargs) + + +def extract_system_prefix(messages: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for msg in messages: + if msg.get("role") == "system": + out.append(copy.deepcopy(msg)) + else: + break + return out + + +def collect_pairs(messages: Sequence[Dict[str, Any]], start_idx: int = 0) -> List[Tuple[Dict[str, Any], Dict[str, Any]]]: + pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = [] + idx = start_idx + while idx < len(messages): + while idx < len(messages) and messages[idx].get("role") != "user": + idx += 1 + if idx >= len(messages): + break + if idx + 1 < len(messages) and messages[idx + 1].get("role") == "assistant": + pairs.append((copy.deepcopy(messages[idx]), copy.deepcopy(messages[idx + 1]))) + idx += 2 + else: + idx += 1 + return pairs + + +def to_int(value: Any, default: int = 0) -> int: + try: + return int(value) + except (TypeError, ValueError): + return default + + +def source_key(source_id: Any) -> str: + return str(source_id) + + +def group_rows(rows: Sequence[Dict[str, Any]]) -> Dict[Any, List[Dict[str, Any]]]: + groups: Dict[Any, List[Dict[str, Any]]] = {} + for idx, row in enumerate(rows): + meta = row.get("meta") or {} + source_id = meta.get("source_id", f"missing_source_{idx}") + groups.setdefault(source_id, []).append(row) + for items in groups.values(): + items.sort(key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0)) + return groups + + +def select_full_row(source_id: Any, items: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + exact = [ + row + for row in items + if to_int((row.get("meta") or {}).get("turns"), -1) + == to_int((row.get("meta") or {}).get("total_turns"), -2) + ] + if exact: + return exact[-1] + return max(items, key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0)) + + +def build_full_trajectories(rows: Sequence[Dict[str, Any]]) -> Dict[Any, FullTrajectory]: + groups = group_rows(rows) + full: Dict[Any, FullTrajectory] = {} + for source_id, items in groups.items(): + row = select_full_row(source_id, items) + messages = row.get("messages") or [] + if not isinstance(messages, list): + continue + sys_prefix = extract_system_prefix(messages) + pairs = collect_pairs(messages, start_idx=len(sys_prefix)) + if not pairs: + continue + full[source_id] = FullTrajectory( + source_id=source_id, + sys_prefix=sys_prefix, + pairs=pairs, + meta=dict(row.get("meta") or {}), + ) + return full + + +def extract_answer_block(text: str) -> str: + match = ANSWER_RE.search(text or "") + return match.group(0) if match is not None else "" + + +def clean_think(text: str) -> str: + text = (text or "").strip() + think_match = THINK_RE.search(text) + if think_match is not None: + text = think_match.group(1).strip() + text = re.split(r"<\s*/?\s*answer\s*>", text, flags=re.IGNORECASE)[0] + text = re.sub(r"", "", text, flags=re.IGNORECASE) + text = re.sub(r"\s+", " ", text).strip() + text = text.strip('` \t\n\r"') + return text + + +def make_response(think: str, answer_block: str) -> str: + return f"{think.strip()}{answer_block}" + + +def iter_turns(full: Dict[Any, FullTrajectory]) -> List[TurnExample]: + turns: List[TurnExample] = [] + for source_id, traj in full.items(): + total_turns = len(traj.pairs) + for i, (user_msg, asst_msg) in enumerate(traj.pairs): + answer_block = extract_answer_block(str(asst_msg.get("content", ""))) + next_user = None + if i + 1 < total_turns: + next_user = str(traj.pairs[i + 1][0].get("content", "")) + turns.append( + TurnExample( + source_id=source_id, + turn_idx=i + 1, + total_turns=total_turns, + user_content=str(user_msg.get("content", "")), + assistant_content=str(asst_msg.get("content", "")), + answer_block=answer_block, + next_user_content=next_user, + ) + ) + return turns + + +def build_generation_messages(example: TurnExample, version: str) -> List[Dict[str, str]]: + if version not in {"sa", "sas"}: + raise ValueError(f"Unknown version: {version}") + sas_available = version == "sas" and example.next_user_content is not None + parts = [ + "We are creating high-quality SFT reasoning for an expert trajectory.", + "The expert action is fixed. Your job is only to write the inner text for ....", + "Do not output , , , JSON, bullets, or any extra wrapper.", + "Do not change or restate a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.", + "Keep it concise: 1-3 English sentences explaining why the fixed action is reasonable from the visible context.", + "", + "Current observation/state s:", + "```text", + example.user_content.strip(), + "```", + "", + "Fixed expert action a:", + "```text", + example.answer_block.strip() or example.assistant_content.strip(), + "```", + ] + if sas_available: + parts.extend( + [ + "", + "Observed next state/feedback s' after executing the fixed action:", + "```text", + str(example.next_user_content).strip(), + "```", + "Use s' only to ground the explanation of the observed transition; never alter the fixed action.", + ] + ) + elif version == "sas": + parts.extend( + [ + "", + "No next state s' is available for this final turn, so explain using only s and a.", + ] + ) + return [ + { + "role": "system", + "content": "You write faithful, concise reasoning for fixed expert actions.", + }, + {"role": "user", "content": "\n".join(parts)}, + ] + + +def build_judge_messages(example: TurnExample, version: str, candidates: Sequence[str]) -> List[Dict[str, str]]: + candidate_text = "\n".join(f"[{i + 1}] {cand}" for i, cand in enumerate(candidates)) + sas_available = version == "sas" and example.next_user_content is not None + parts = [ + "You are auditing candidate texts for an expert SFT trajectory.", + "The expert action is fixed. Select the candidate that best explains it while staying faithful to the visible context.", + "Penalize unsupported factual claims, contradicted claims, changing the action, excessive certainty such as 'only'/'optimal' without clear support, verbosity, and format pollution.", + "Return strict JSON only, with no markdown.", + "", + "Current observation/state s:", + "```text", + example.user_content.strip(), + "```", + "", + "Fixed expert action a:", + "```text", + example.answer_block.strip() or example.assistant_content.strip(), + "```", + ] + if sas_available: + parts.extend( + [ + "", + "Observed next state/feedback s' after executing a:", + "```text", + str(example.next_user_content).strip(), + "```", + ] + ) + elif version == "sas": + parts.append("\nNo next state s' is available for this final turn.") + parts.extend( + [ + "", + "Candidates:", + candidate_text, + "", + "Use this JSON schema:", + '{"best_index": 1, "scores": [{"index": 1, "score": 1, "unsupported_claims": 0, "contradictions": 0, "reason": "short reason"}], "selected_reason": "short reason", "low_quality": false}', + "Scores are from 1 to 5. Set low_quality=true if the best candidate is still weak or generic.", + ] + ) + return [ + {"role": "system", "content": "You are a strict factuality judge for reasoning traces."}, + {"role": "user", "content": "\n".join(parts)}, + ] + + +def render_prompt(tokenizer: Any, messages: List[Dict[str, str]]) -> str: + return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) + + +def load_vllm_model( + model_path: str, + args: argparse.Namespace, + tensor_parallel_size: Optional[int] = None, +) -> Tuple[Any, Any]: + try: + from transformers import AutoTokenizer + from vllm import LLM + except ImportError as exc: + raise RuntimeError("This script requires `vllm` and `transformers`.") from exc + + tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=bool(args.trust_remote_code)) + llm_kwargs: Dict[str, Any] = { + "model": model_path, + "tensor_parallel_size": int(tensor_parallel_size or args.tensor_parallel_size), + "dtype": args.dtype, + "gpu_memory_utilization": float(args.gpu_memory_utilization), + "trust_remote_code": bool(args.trust_remote_code), + } + if args.max_model_len is not None: + llm_kwargs["max_model_len"] = int(args.max_model_len) + return LLM(**llm_kwargs), tokenizer + + +def make_sampling_params(args: argparse.Namespace, *, judge: bool = False) -> Any: + try: + from vllm import SamplingParams + except ImportError as exc: + raise RuntimeError("This script requires `vllm`.") from exc + if judge: + return SamplingParams( + temperature=float(args.judge_temperature), + top_p=1.0, + max_tokens=int(args.judge_max_tokens), + ) + return SamplingParams( + n=int(args.n), + temperature=float(args.temperature), + top_p=float(args.top_p), + top_k=int(args.top_k), + max_tokens=int(args.max_tokens), + ) + + +def chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]: + if size <= 0: + yield items + return + for start in range(0, len(items), size): + yield items[start : start + size] + + +def parse_judge_json(text: str) -> Dict[str, Any]: + text = (text or "").strip() + match = JSON_OBJ_RE.search(text) + if match is not None: + text = match.group(0) + try: + obj = json.loads(text) + if isinstance(obj, dict): + return obj + except json.JSONDecodeError: + pass + return {} + + +def selected_score(judge_obj: Dict[str, Any], best_index: int) -> float: + for item in judge_obj.get("scores") or []: + if isinstance(item, dict) and to_int(item.get("index"), -1) == best_index: + try: + return float(item.get("score", 0.0)) + except (TypeError, ValueError): + return 0.0 + return 0.0 + + +def fallback_think(version: str) -> str: + if version == "sas": + return ( + "The expert action is kept fixed and is explained using the current observation " + "together with the observed next-state feedback, without changing the action." + ) + return ( + "The expert action is kept fixed and is chosen based on the current observation " + "and task constraints, aiming to make progress without changing the demonstrated action." + ) + + +def cache_key(version: str, source_id: Any, turn_idx: int) -> str: + return json.dumps( + {"version": version, "source_id": source_id, "turn_idx": turn_idx}, + ensure_ascii=False, + sort_keys=True, + ) + + +def load_cache(path: Path) -> Dict[str, Dict[str, Any]]: + cache: Dict[str, Dict[str, Any]] = {} + if not path.exists(): + return cache + with path.open("r", encoding="utf-8") as f: + for line_no, line in enumerate(f, start=1): + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except json.JSONDecodeError: + print(f"Warning: skipped invalid cache line {path}:{line_no}") + continue + key = row.get("cache_key") + if isinstance(key, str): + cache[key] = row + return cache + + +def append_cache(path: Path, rows: Sequence[Dict[str, Any]]) -> None: + if not rows: + return + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + + +def dry_candidates(example: TurnExample, version: str, n: int) -> List[str]: + base = "This fixed expert action is explained from the visible state while preserving the demonstrated answer." + if version == "sas" and example.next_user_content is not None: + base = "This fixed expert action is explained from the visible state and the observed next-state feedback." + return [f"{base} Candidate {i + 1}." for i in range(n)] + + +def synthesize_version( + *, + version: str, + turns: Sequence[TurnExample], + args: argparse.Namespace, + output_dir: Path, + output_prefix: str, + llm: Any, + tokenizer: Any, + judge_llm: Any, + judge_tokenizer: Any, +) -> Dict[Tuple[Any, int], Dict[str, Any]]: + cache_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.cache.jsonl" + cache = {} if args.no_cache else load_cache(cache_path) + results: Dict[Tuple[Any, int], Dict[str, Any]] = {} + missing: List[TurnExample] = [] + for ex in turns: + key = cache_key(version, ex.source_id, ex.turn_idx) + cached = cache.get(key) + if cached is not None and cached.get("selected_think"): + results[(ex.source_id, ex.turn_idx)] = cached + else: + missing.append(ex) + + print(f"[{version}] turns={len(turns)} cached={len(results)} missing={len(missing)}") + gen_params = None if args.dry_run else make_sampling_params(args, judge=False) + judge_params = None if args.dry_run else make_sampling_params(args, judge=True) + + for batch_no, batch in enumerate(chunks(missing, int(args.batch_size)), start=1): + batch = list(batch) + if args.dry_run: + all_candidates = [dry_candidates(ex, version, int(args.n)) for ex in batch] + else: + prompts = [render_prompt(tokenizer, build_generation_messages(ex, version)) for ex in batch] + outputs = llm.generate(prompts, sampling_params=gen_params) + all_candidates = [] + for out in outputs: + candidates = [clean_think(candidate.text) for candidate in out.outputs] + candidates = [cand for cand in candidates if cand] + all_candidates.append(candidates) + + judge_inputs: List[Tuple[TurnExample, List[str]]] = [] + batch_rows: List[Dict[str, Any]] = [] + for ex, candidates in zip(batch, all_candidates): + if not candidates: + selected = fallback_think(version) + row = { + "cache_key": cache_key(version, ex.source_id, ex.turn_idx), + "version": version, + "source_id": ex.source_id, + "turn_idx": ex.turn_idx, + "total_turns": ex.total_turns, + "selected_think": selected, + "selected_index": None, + "score": 0.0, + "low_quality": True, + "fallback": True, + "missing_next_state": version == "sas" and ex.next_user_content is None, + "selected_reason": "No valid generation candidates; used fallback.", + } + if args.save_candidates: + row["candidates"] = [] + batch_rows.append(row) + else: + judge_inputs.append((ex, candidates)) + + judge_texts: List[str] = [] + if judge_inputs: + if args.dry_run: + judge_texts = [ + json.dumps( + { + "best_index": 1, + "scores": [ + { + "index": 1, + "score": 3, + "unsupported_claims": 0, + "contradictions": 0, + "reason": "dry run", + } + ], + "selected_reason": "dry run", + "low_quality": False, + } + ) + for _ in judge_inputs + ] + else: + judge_prompts = [ + render_prompt(judge_tokenizer, build_judge_messages(ex, version, candidates)) + for ex, candidates in judge_inputs + ] + judge_texts = [] + for judge_chunk in chunks(judge_prompts, int(args.judge_batch_size)): + judge_outputs = judge_llm.generate(list(judge_chunk), sampling_params=judge_params) + judge_texts.extend(out.outputs[0].text for out in judge_outputs) + + for (ex, candidates), judge_text in zip(judge_inputs, judge_texts): + judge_obj = parse_judge_json(judge_text) + best_index = to_int(judge_obj.get("best_index"), 1) + if best_index < 1 or best_index > len(candidates): + best_index = 1 + selected = candidates[best_index - 1] + score = selected_score(judge_obj, best_index) + if score <= 0.0: + score = 3.0 if selected else 0.0 + low_quality = bool(judge_obj.get("low_quality", False)) or score < float(args.min_judge_score) + row = { + "cache_key": cache_key(version, ex.source_id, ex.turn_idx), + "version": version, + "source_id": ex.source_id, + "turn_idx": ex.turn_idx, + "total_turns": ex.total_turns, + "selected_think": selected or fallback_think(version), + "selected_index": best_index, + "score": score, + "low_quality": low_quality, + "fallback": not bool(selected), + "missing_next_state": version == "sas" and ex.next_user_content is None, + "selected_reason": str(judge_obj.get("selected_reason", "")), + } + if args.save_candidates: + row["candidates"] = candidates + row["judge"] = judge_obj + row["judge_raw"] = judge_text + batch_rows.append(row) + + append_cache(cache_path, batch_rows) if not args.no_cache else None + for row in batch_rows: + results[(row["source_id"], int(row["turn_idx"]))] = row + print(f"[{version}] batch {batch_no}: wrote {len(batch_rows)} turn results") + return results + + +def rebuild_rows( + rows: Sequence[Dict[str, Any]], + full: Dict[Any, FullTrajectory], + result_map: Dict[Tuple[Any, int], Dict[str, Any]], +) -> List[Dict[str, Any]]: + rebuilt_by_source: Dict[Any, List[Tuple[Dict[str, Any], Dict[str, Any]]]] = {} + for source_id, traj in full.items(): + new_pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = [] + for idx, (user_msg, asst_msg) in enumerate(traj.pairs, start=1): + answer_block = extract_answer_block(str(asst_msg.get("content", ""))) + result = result_map.get((source_id, idx)) + think = str(result.get("selected_think", "")) if result else fallback_think("sa") + new_user = copy.deepcopy(user_msg) + new_asst = copy.deepcopy(asst_msg) + if answer_block: + new_asst["content"] = make_response(think, answer_block) + else: + new_asst["content"] = str(asst_msg.get("content", "")) + new_pairs.append((new_user, new_asst)) + rebuilt_by_source[source_id] = new_pairs + + output: List[Dict[str, Any]] = [] + for idx, row in enumerate(rows): + meta = row.get("meta") or {} + source_id = meta.get("source_id", f"missing_source_{idx}") + turns = to_int(meta.get("turns"), 0) + new_row = copy.deepcopy(row) + traj = full.get(source_id) + pairs = rebuilt_by_source.get(source_id) + if traj is None or pairs is None or turns <= 0: + output.append(new_row) + continue + turns = min(turns, len(pairs)) + new_row["messages"] = copy.deepcopy(traj.sys_prefix) + [ + copy.deepcopy(msg) for pair in pairs[:turns] for msg in pair + ] + output.append(new_row) + return output + + +def validate_answer_unchanged(original: Sequence[Dict[str, Any]], rebuilt: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + if len(original) != len(rebuilt): + raise ValueError(f"Row count changed: original={len(original)} rebuilt={len(rebuilt)}") + checked = 0 + mismatches: List[Dict[str, Any]] = [] + for row_idx, (old_row, new_row) in enumerate(zip(original, rebuilt)): + old_pairs = collect_pairs(old_row.get("messages") or [], start_idx=len(extract_system_prefix(old_row.get("messages") or []))) + new_pairs = collect_pairs(new_row.get("messages") or [], start_idx=len(extract_system_prefix(new_row.get("messages") or []))) + if len(old_pairs) != len(new_pairs): + mismatches.append({"row_idx": row_idx, "reason": "pair_count_changed"}) + continue + for turn_idx, ((_, old_asst), (_, new_asst)) in enumerate(zip(old_pairs, new_pairs), start=1): + old_answer = extract_answer_block(str(old_asst.get("content", ""))) + new_answer = extract_answer_block(str(new_asst.get("content", ""))) + checked += 1 + if old_answer != new_answer: + mismatches.append( + { + "row_idx": row_idx, + "turn_idx": turn_idx, + "old_answer": old_answer, + "new_answer": new_answer, + } + ) + if len(mismatches) >= 20: + break + if len(mismatches) >= 20: + break + if mismatches: + raise ValueError(f"Answer validation failed, examples: {mismatches[:3]}") + return {"checked_assistant_messages": checked, "answer_mismatches": 0} + + +def filter_full_by_args(full: Dict[Any, FullTrajectory], args: argparse.Namespace) -> Dict[Any, FullTrajectory]: + selected = dict(full) + if args.source_ids.strip(): + allow = {item.strip() for item in args.source_ids.split(",") if item.strip()} + selected = {sid: traj for sid, traj in selected.items() if source_key(sid) in allow} + if args.limit_sources is not None: + limited: Dict[Any, FullTrajectory] = {} + for sid in list(selected.keys())[: int(args.limit_sources)]: + limited[sid] = selected[sid] + selected = limited + return selected + + +def report_from_results( + *, + version: str, + result_map: Dict[Tuple[Any, int], Dict[str, Any]], + validation: Dict[str, Any], + args: argparse.Namespace, +) -> Dict[str, Any]: + values = list(result_map.values()) + low_quality = sum(1 for row in values if row.get("low_quality")) + fallback = sum(1 for row in values if row.get("fallback")) + missing_next = sum(1 for row in values if row.get("missing_next_state")) + scores = [float(row.get("score", 0.0)) for row in values] + summary = { + "version": version, + "n": int(args.n), + "turn_results": len(values), + "low_quality": low_quality, + "fallback": fallback, + "missing_next_state": missing_next, + "avg_score": sum(scores) / len(scores) if scores else 0.0, + "min_score": min(scores) if scores else 0.0, + "max_score": max(scores) if scores else 0.0, + **validation, + } + per_turn: List[Dict[str, Any]] = [] + for row in values: + item = { + "source_id": row.get("source_id"), + "turn_idx": row.get("turn_idx"), + "total_turns": row.get("total_turns"), + "selected_index": row.get("selected_index"), + "score": row.get("score"), + "low_quality": row.get("low_quality"), + "fallback": row.get("fallback"), + "missing_next_state": row.get("missing_next_state"), + "selected_reason": row.get("selected_reason", ""), + } + if args.save_candidates: + item["selected_think"] = row.get("selected_think") + item["candidates"] = row.get("candidates", []) + item["judge"] = row.get("judge", {}) + per_turn.append(item) + return {"summary": summary, "per_turn": per_turn} + + +def main() -> None: + args = parse_args() + versions = [v.strip() for v in args.versions.split(",") if v.strip()] + if not versions or any(v not in {"sa", "sas"} for v in versions): + raise ValueError("--versions must contain only sa and/or sas") + if not args.dry_run and not args.model: + raise ValueError("--model is required unless --dry-run is set") + + input_path = args.input.expanduser().resolve() + output_dir = (args.output_dir or input_path.parent).expanduser().resolve() + output_prefix = args.output_prefix or input_path.stem + + print(f"Loading input: {input_path}") + rows = load_json_list(input_path) + full_all = build_full_trajectories(rows) + full_selected = filter_full_by_args(full_all, args) + if not full_selected: + raise ValueError("No usable trajectories selected.") + turns = iter_turns(full_selected) + print(f"Rows={len(rows)} sources={len(full_all)} selected_sources={len(full_selected)} selected_turns={len(turns)}") + + llm = tokenizer = judge_llm = judge_tokenizer = None + if not args.dry_run: + llm, tokenizer = load_vllm_model(args.model, args, tensor_parallel_size=args.tensor_parallel_size) + judge_model = args.judge_model or args.model + if judge_model == args.model: + judge_llm, judge_tokenizer = llm, tokenizer + else: + judge_tp = args.judge_tensor_parallel_size or args.tensor_parallel_size + judge_llm, judge_tokenizer = load_vllm_model(judge_model, args, tensor_parallel_size=judge_tp) + + for version in versions: + result_map = synthesize_version( + version=version, + turns=turns, + args=args, + output_dir=output_dir, + output_prefix=output_prefix, + llm=llm, + tokenizer=tokenizer, + judge_llm=judge_llm, + judge_tokenizer=judge_tokenizer, + ) + rows_for_output = [ + row + for idx, row in enumerate(rows) + if not args.selected_only + or (row.get("meta") or {}).get("source_id", f"missing_source_{idx}") in full_selected + ] + rebuilt = rebuild_rows(rows_for_output, full_selected, result_map) + validation = validate_answer_unchanged(rows_for_output, rebuilt) + out_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.json" + report_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.report.json" + dump_json(out_path, rebuilt, indent=int(args.indent)) + report = report_from_results(version=version, result_map=result_map, validation=validation, args=args) + dump_json(report_path, report, indent=2) + print(f"[{version}] wrote SFT: {out_path}") + print(f"[{version}] wrote report: {report_path}") + print(f"[{version}] summary: {json.dumps(report['summary'], ensure_ascii=False)}") + + +if __name__ == "__main__": + main() diff --git a/scripts/synthesize_think_bon_traj_sa.py b/scripts/synthesize_think_bon_traj_sa.py new file mode 100644 index 0000000000000000000000000000000000000000..c27301cf58906701bdaf343f338311a5cf256cbd --- /dev/null +++ b/scripts/synthesize_think_bon_traj_sa.py @@ -0,0 +1,884 @@ +#!/usr/bin/env python3 +"""Synthesize traces for SFT singleturn trajectories with BoN + judge. + +This script is intentionally environment-agnostic. It assumes a JSON list of rows +with the common RAGEN SFT shape: + + {"messages": [{"role": "system"}, {"role": "user"}, {"role": "assistant"}, ...], + "meta": {"source_id": ..., "turns": ..., "total_turns": ...}} + +For each source_id, the complete trajectory row is selected, one reasoning trace +is synthesized per turn, and the selected traces are written back to every +cumulative singleturn prefix while keeping every original ... +block exactly unchanged. + + +python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_v2.py \ + --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json \ + --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \ + --output-prefix step_999424_sft_singleturn_withthink \ + --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ + --tensor-parallel-size 4 \ + --n 8 \ + --batch-size 32 \ + --judge-batch-size 32 +""" + +from __future__ import annotations + +import argparse +import copy +import json +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple + + +ANSWER_RE = re.compile(r".*?", re.IGNORECASE | re.DOTALL) +THINK_RE = re.compile(r"(.*?)", re.IGNORECASE | re.DOTALL) +JSON_OBJ_RE = re.compile(r"\{.*\}", re.DOTALL) +META_REASONING_RE = re.compile( + r"\b(" + r"expert action|fixed action|given action|provided action|target action|" + r"demonstrated action|demonstrated answer|known action|chosen by (?:the )?expert|" + r"the action (?:was|is) (?:given|fixed|provided|known)" + r")\b", + re.IGNORECASE, +) + + +@dataclass +class TurnExample: + source_id: Any + turn_idx: int + total_turns: int + user_content: str + assistant_content: str + answer_block: str + next_user_content: Optional[str] + trajectory_context: str + + +@dataclass +class FullTrajectory: + source_id: Any + sys_prefix: List[Dict[str, Any]] + pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] + meta: Dict[str, Any] + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Synthesize first-person target-action thinking traces with per-turn BoN and LLM judge." + ) + parser.add_argument("--input", "-i", type=Path, required=True, help="Input SFT JSON list.") + parser.add_argument( + "--output-dir", + type=Path, + default=None, + help="Directory for output files. Defaults to input parent.", + ) + parser.add_argument( + "--output-prefix", + default=None, + help="Output filename prefix. Defaults to input stem.", + ) + parser.add_argument( + "--versions", + default="traj_sa", + help="Comma-separated versions. This script supports only traj_sa: full trajectory in system, current s,a in user.", + ) + parser.add_argument("--model", default=None, help="HF model path for tokenizer + vLLM.") + parser.add_argument("--judge-model", default=None, help="Optional separate judge model path.") + parser.add_argument("--n", type=int, default=8, help="BoN candidates per turn.") + parser.add_argument( + "--mode", + default="per_turn", + choices=["per_turn"], + help="BoN mode. Currently only independent per-turn BoN is implemented.", + ) + parser.add_argument("--limit-sources", type=int, default=None, help="Pilot limit by source_id count.") + parser.add_argument("--source-ids", default="", help="Optional comma-separated source_id allowlist.") + parser.add_argument("--batch-size", type=int, default=64, help="Prompt batch size for generation.") + parser.add_argument("--judge-batch-size", type=int, default=64, help="Prompt batch size for judge.") + parser.add_argument("--temperature", type=float, default=0.7) + parser.add_argument("--top-p", type=float, default=0.95) + parser.add_argument("--top-k", type=int, default=-1) + parser.add_argument("--max-tokens", type=int, default=160, help="Max tokens for think generation.") + parser.add_argument("--judge-temperature", type=float, default=0.0) + parser.add_argument("--judge-max-tokens", type=int, default=768) + parser.add_argument("--tensor-parallel-size", type=int, default=1) + parser.add_argument("--judge-tensor-parallel-size", type=int, default=None) + parser.add_argument("--dtype", default="auto") + parser.add_argument("--gpu-memory-utilization", type=float, default=0.9) + parser.add_argument("--max-model-len", type=int, default=None) + parser.add_argument("--trust-remote-code", action="store_true") + parser.add_argument("--min-judge-score", type=float, default=3.0) + parser.add_argument("--save-candidates", action="store_true", help="Store all candidates in report.") + parser.add_argument( + "--trajectory-state-max-chars", + type=int, + default=1200, + help="Max characters kept for each state in the compact trajectory context. Use -1 to disable truncation.", + ) + parser.add_argument( + "--trajectory-action-max-chars", + type=int, + default=200, + help="Max characters kept for each action in the compact trajectory context. Use -1 to disable truncation.", + ) + parser.add_argument( + "--selected-only", + action="store_true", + help="Write only rows whose source_id was selected by --limit-sources/--source-ids.", + ) + parser.add_argument("--no-cache", action="store_true", help="Disable JSONL cache/resume.") + parser.add_argument("--dry-run", action="store_true", help="Do not load vLLM; create deterministic mock thinks.") + parser.add_argument("--indent", type=int, default=2, help="JSON output indent. Use -1 for compact.") + return parser.parse_args() + + +def load_json_list(path: Path) -> List[Dict[str, Any]]: + with path.open("r", encoding="utf-8") as f: + data = json.load(f) + if not isinstance(data, list): + raise ValueError(f"Expected JSON list at {path}, got {type(data).__name__}") + if not all(isinstance(row, dict) for row in data): + raise ValueError(f"Expected all rows to be objects in {path}") + return data + + +def dump_json(path: Path, data: Any, indent: int) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + kwargs = {"ensure_ascii": False} + if indent >= 0: + kwargs["indent"] = indent + with path.open("w", encoding="utf-8") as f: + json.dump(data, f, **kwargs) + + +def extract_system_prefix(messages: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for msg in messages: + if msg.get("role") == "system": + out.append(copy.deepcopy(msg)) + else: + break + return out + + +def collect_pairs(messages: Sequence[Dict[str, Any]], start_idx: int = 0) -> List[Tuple[Dict[str, Any], Dict[str, Any]]]: + pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = [] + idx = start_idx + while idx < len(messages): + while idx < len(messages) and messages[idx].get("role") != "user": + idx += 1 + if idx >= len(messages): + break + if idx + 1 < len(messages) and messages[idx + 1].get("role") == "assistant": + pairs.append((copy.deepcopy(messages[idx]), copy.deepcopy(messages[idx + 1]))) + idx += 2 + else: + idx += 1 + return pairs + + +def to_int(value: Any, default: int = 0) -> int: + try: + return int(value) + except (TypeError, ValueError): + return default + + +def source_key(source_id: Any) -> str: + return str(source_id) + + +def group_rows(rows: Sequence[Dict[str, Any]]) -> Dict[Any, List[Dict[str, Any]]]: + groups: Dict[Any, List[Dict[str, Any]]] = {} + for idx, row in enumerate(rows): + meta = row.get("meta") or {} + source_id = meta.get("source_id", f"missing_source_{idx}") + groups.setdefault(source_id, []).append(row) + for items in groups.values(): + items.sort(key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0)) + return groups + + +def select_full_row(source_id: Any, items: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + exact = [ + row + for row in items + if to_int((row.get("meta") or {}).get("turns"), -1) + == to_int((row.get("meta") or {}).get("total_turns"), -2) + ] + if exact: + return exact[-1] + return max(items, key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0)) + + +def build_full_trajectories(rows: Sequence[Dict[str, Any]]) -> Dict[Any, FullTrajectory]: + groups = group_rows(rows) + full: Dict[Any, FullTrajectory] = {} + for source_id, items in groups.items(): + row = select_full_row(source_id, items) + messages = row.get("messages") or [] + if not isinstance(messages, list): + continue + sys_prefix = extract_system_prefix(messages) + pairs = collect_pairs(messages, start_idx=len(sys_prefix)) + if not pairs: + continue + full[source_id] = FullTrajectory( + source_id=source_id, + sys_prefix=sys_prefix, + pairs=pairs, + meta=dict(row.get("meta") or {}), + ) + return full + + +def extract_answer_block(text: str) -> str: + match = ANSWER_RE.search(text or "") + return match.group(0) if match is not None else "" + + +def clean_think(text: str) -> str: + text = (text or "").strip() + think_match = THINK_RE.search(text) + if think_match is not None: + text = think_match.group(1).strip() + text = re.split(r"<\s*/?\s*answer\s*>", text, flags=re.IGNORECASE)[0] + text = re.sub(r"", "", text, flags=re.IGNORECASE) + text = re.sub(r"\s+", " ", text).strip() + text = text.strip('` \t\n\r"') + return text + + +def make_response(think: str, answer_block: str) -> str: + return f"{think.strip()}{answer_block}" + + +def has_meta_reasoning(text: str) -> bool: + return META_REASONING_RE.search(text or "") is not None + + +def extract_answer_payload(text: str) -> str: + answer_block = extract_answer_block(text) + if not answer_block: + return (text or "").strip() + return re.sub( + r"^\s*<\s*answer\s*>|<\s*/\s*answer\s*>\s*$", + "", + answer_block, + flags=re.IGNORECASE | re.DOTALL, + ).strip() + + +def compact_for_trajectory(text: str, max_chars: int) -> str: + text = (text or "").strip() + text = re.sub(r"\n{3,}", "\n\n", text) + text = text.replace("```", "'''") + if max_chars >= 0 and len(text) > max_chars: + text = text[:max_chars].rstrip() + " ...[truncated]" + return text + + +def build_trajectory_context(traj: FullTrajectory, state_max_chars: int, action_max_chars: int) -> str: + chunks: List[str] = [] + for idx, (user_msg, asst_msg) in enumerate(traj.pairs): + state = compact_for_trajectory(str(user_msg.get("content", "")), state_max_chars) + action = compact_for_trajectory(extract_answer_payload(str(asst_msg.get("content", ""))), action_max_chars) + chunks.append(f"(s{idx}: {state}, a{idx}: {action})") + return " -> ".join(chunks) + + +def iter_turns(full: Dict[Any, FullTrajectory], state_max_chars: int, action_max_chars: int) -> List[TurnExample]: + turns: List[TurnExample] = [] + for source_id, traj in full.items(): + total_turns = len(traj.pairs) + trajectory_context = build_trajectory_context(traj, state_max_chars, action_max_chars) + for i, (user_msg, asst_msg) in enumerate(traj.pairs): + answer_block = extract_answer_block(str(asst_msg.get("content", ""))) + next_user = None + if i + 1 < total_turns: + next_user = str(traj.pairs[i + 1][0].get("content", "")) + turns.append( + TurnExample( + source_id=source_id, + turn_idx=i + 1, + total_turns=total_turns, + user_content=str(user_msg.get("content", "")), + assistant_content=str(asst_msg.get("content", "")), + answer_block=answer_block, + next_user_content=next_user, + trajectory_context=trajectory_context, + ) + ) + return turns + + +def build_generation_messages(example: TurnExample, version: str) -> List[Dict[str, str]]: + if version != "traj_sa": + raise ValueError(f"Unknown version for this script: {version}") + target_action = extract_answer_payload(example.assistant_content) or example.answer_block.strip() + system_parts = [ + "You write faithful, concise first-person reasoning for your own next action.", + "You are given the full trajectory as compact ordered (state, action) tuples in the form (s0, a0) -> (s1, a1) -> ... .", + "Use the full trajectory only as context for understanding the current decision. Do not copy future information as if it were known at the current turn.", + "", + "Full compressed trajectory:", + "```text", + example.trajectory_context, + "```", + ] + parts = [ + "You are the assistant acting in this environment at the current turn.", + "You have already decided which action to output; now write the private inner reasoning that naturally leads to that action.", + "Write from your own first-person decision-making perspective, as if you are solving the task, not evaluating another model or an expert.", + "Only output the inner text for .... Do not output , , , JSON, bullets, or any extra wrapper.", + "Do not say or imply that the action was given, fixed, known, demonstrated, provided, or chosen by an expert. Avoid meta phrases such as 'the expert action', 'the fixed action', 'given action', or 'demonstrated answer', 'the expert'.", + "Do not change to a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.", + "Keep it concise: 1-3 English sentences with step-by-step reasoning grounded in the current state/action and the compressed trajectory context.", + "", + "Current observation/state s:", + "```text", + example.user_content.strip(), + "```", + "", + "Action a that your reasoning should lead to:", + "```text", + target_action, + "```", + ] + return [ + {"role": "system", "content": "\n".join(system_parts)}, + {"role": "user", "content": "\n".join(parts)}, + ] + + +def build_judge_messages(example: TurnExample, version: str, candidates: Sequence[str]) -> List[Dict[str, str]]: + if version != "traj_sa": + raise ValueError(f"Unknown version for this script: {version}") + candidate_text = "\n".join(f"[{i + 1}] {cand}" for i, cand in enumerate(candidates)) + target_action = extract_answer_payload(example.assistant_content) or example.answer_block.strip() + system_parts = [ + "You are a strict factuality judge for reasoning traces.", + "You are given the full trajectory as compact ordered (state, action) tuples in the form (s0, a0) -> (s1, a1) -> ... .", + "Use it only to judge whether candidate reasoning is faithful to the current state/action and trajectory context.", + "", + "Full compressed trajectory:", + "```text", + example.trajectory_context, + "```", + ] + parts = [ + "You are auditing candidate texts for an SFT trajectory.", + "Select the candidate that reads like the assistant's own private step-by-step reasoning leading to the target action, while staying faithful to the visible context.", + "Strongly penalize meta-reasoning that says or implies the action was given, fixed, known, demonstrated, provided, or chosen by an expert.", + "Also penalize unsupported factual claims, contradicted claims, changing the action, excessive certainty such as 'only'/'optimal' without clear support, verbosity, and format pollution.", + "Return strict JSON only, with no markdown.", + "", + "Current observation/state s:", + "```text", + example.user_content.strip(), + "```", + "", + "Target action a that the reasoning should lead to:", + "```text", + target_action, + "```", + "", + "Candidates:", + candidate_text, + "", + "Use this JSON schema:", + '{"best_index": 1, "scores": [{"index": 1, "score": 1, "unsupported_claims": 0, "contradictions": 0, "reason": "short reason"}], "selected_reason": "short reason", "low_quality": false}', + "Scores are from 1 to 5. Set low_quality=true if the best candidate is still weak or generic.", + ] + return [ + {"role": "system", "content": "\n".join(system_parts)}, + {"role": "user", "content": "\n".join(parts)}, + ] + + +def render_prompt(tokenizer: Any, messages: List[Dict[str, str]]) -> str: + return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) + + +def load_vllm_model( + model_path: str, + args: argparse.Namespace, + tensor_parallel_size: Optional[int] = None, +) -> Tuple[Any, Any]: + try: + from transformers import AutoTokenizer + from vllm import LLM + except ImportError as exc: + raise RuntimeError("This script requires `vllm` and `transformers`.") from exc + + tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=bool(args.trust_remote_code)) + llm_kwargs: Dict[str, Any] = { + "model": model_path, + "tensor_parallel_size": int(tensor_parallel_size or args.tensor_parallel_size), + "dtype": args.dtype, + "gpu_memory_utilization": float(args.gpu_memory_utilization), + "trust_remote_code": bool(args.trust_remote_code), + } + if args.max_model_len is not None: + llm_kwargs["max_model_len"] = int(args.max_model_len) + return LLM(**llm_kwargs), tokenizer + + +def make_sampling_params(args: argparse.Namespace, *, judge: bool = False) -> Any: + try: + from vllm import SamplingParams + except ImportError as exc: + raise RuntimeError("This script requires `vllm`.") from exc + if judge: + return SamplingParams( + temperature=float(args.judge_temperature), + top_p=1.0, + max_tokens=int(args.judge_max_tokens), + ) + return SamplingParams( + n=int(args.n), + temperature=float(args.temperature), + top_p=float(args.top_p), + top_k=int(args.top_k), + max_tokens=int(args.max_tokens), + ) + + +def chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]: + if size <= 0: + yield items + return + for start in range(0, len(items), size): + yield items[start : start + size] + + +def parse_judge_json(text: str) -> Dict[str, Any]: + text = (text or "").strip() + match = JSON_OBJ_RE.search(text) + if match is not None: + text = match.group(0) + try: + obj = json.loads(text) + if isinstance(obj, dict): + return obj + except json.JSONDecodeError: + pass + return {} + + +def selected_score(judge_obj: Dict[str, Any], best_index: int) -> float: + for item in judge_obj.get("scores") or []: + if isinstance(item, dict) and to_int(item.get("index"), -1) == best_index: + try: + return float(item.get("score", 0.0)) + except (TypeError, ValueError): + return 0.0 + return 0.0 + + +def fallback_think(version: str) -> str: + if version == "sas": + return ( + "I compare the current observation with the next-state feedback and choose the move " + "that is consistent with making progress under the task constraints." + ) + return ( + "I inspect the current observation and choose the move that best follows the task constraints " + "while aiming to make progress from this state." + ) + + +def cache_key(version: str, source_id: Any, turn_idx: int) -> str: + return json.dumps( + {"version": version, "source_id": source_id, "turn_idx": turn_idx}, + ensure_ascii=False, + sort_keys=True, + ) + + +def load_cache(path: Path) -> Dict[str, Dict[str, Any]]: + cache: Dict[str, Dict[str, Any]] = {} + if not path.exists(): + return cache + with path.open("r", encoding="utf-8") as f: + for line_no, line in enumerate(f, start=1): + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except json.JSONDecodeError: + print(f"Warning: skipped invalid cache line {path}:{line_no}") + continue + key = row.get("cache_key") + if isinstance(key, str): + cache[key] = row + return cache + + +def append_cache(path: Path, rows: Sequence[Dict[str, Any]]) -> None: + if not rows: + return + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + + +def dry_candidates(example: TurnExample, version: str, n: int) -> List[str]: + base = "I inspect the visible state and the compressed trajectory context to reason step by step toward the next move." + return [f"{base} Candidate {i + 1}." for i in range(n)] + + +def synthesize_version( + *, + version: str, + turns: Sequence[TurnExample], + args: argparse.Namespace, + output_dir: Path, + output_prefix: str, + llm: Any, + tokenizer: Any, + judge_llm: Any, + judge_tokenizer: Any, +) -> Dict[Tuple[Any, int], Dict[str, Any]]: + cache_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.cache.jsonl" + cache = {} if args.no_cache else load_cache(cache_path) + results: Dict[Tuple[Any, int], Dict[str, Any]] = {} + missing: List[TurnExample] = [] + for ex in turns: + key = cache_key(version, ex.source_id, ex.turn_idx) + cached = cache.get(key) + if cached is not None and cached.get("selected_think"): + results[(ex.source_id, ex.turn_idx)] = cached + else: + missing.append(ex) + + print(f"[{version}] turns={len(turns)} cached={len(results)} missing={len(missing)}") + gen_params = None if args.dry_run else make_sampling_params(args, judge=False) + judge_params = None if args.dry_run else make_sampling_params(args, judge=True) + + for batch_no, batch in enumerate(chunks(missing, int(args.batch_size)), start=1): + batch = list(batch) + if args.dry_run: + all_candidates = [dry_candidates(ex, version, int(args.n)) for ex in batch] + else: + prompts = [render_prompt(tokenizer, build_generation_messages(ex, version)) for ex in batch] + outputs = llm.generate(prompts, sampling_params=gen_params) + all_candidates = [] + for out in outputs: + raw_candidates = [clean_think(candidate.text) for candidate in out.outputs] + candidates = [cand for cand in raw_candidates if cand and not has_meta_reasoning(cand)] + if not candidates: + candidates = [cand for cand in raw_candidates if cand] + all_candidates.append(candidates) + + judge_inputs: List[Tuple[TurnExample, List[str]]] = [] + batch_rows: List[Dict[str, Any]] = [] + for ex, candidates in zip(batch, all_candidates): + if not candidates: + selected = fallback_think(version) + row = { + "cache_key": cache_key(version, ex.source_id, ex.turn_idx), + "version": version, + "source_id": ex.source_id, + "turn_idx": ex.turn_idx, + "total_turns": ex.total_turns, + "selected_think": selected, + "selected_index": None, + "score": 0.0, + "low_quality": True, + "meta_language": False, + "fallback": True, + "missing_next_state": False, + "selected_reason": "No valid generation candidates; used fallback.", + } + if args.save_candidates: + row["candidates"] = [] + batch_rows.append(row) + else: + judge_inputs.append((ex, candidates)) + + judge_texts: List[str] = [] + if judge_inputs: + if args.dry_run: + judge_texts = [ + json.dumps( + { + "best_index": 1, + "scores": [ + { + "index": 1, + "score": 3, + "unsupported_claims": 0, + "contradictions": 0, + "reason": "dry run", + } + ], + "selected_reason": "dry run", + "low_quality": False, + } + ) + for _ in judge_inputs + ] + else: + judge_prompts = [ + render_prompt(judge_tokenizer, build_judge_messages(ex, version, candidates)) + for ex, candidates in judge_inputs + ] + judge_texts = [] + for judge_chunk in chunks(judge_prompts, int(args.judge_batch_size)): + judge_outputs = judge_llm.generate(list(judge_chunk), sampling_params=judge_params) + judge_texts.extend(out.outputs[0].text for out in judge_outputs) + + for (ex, candidates), judge_text in zip(judge_inputs, judge_texts): + judge_obj = parse_judge_json(judge_text) + best_index = to_int(judge_obj.get("best_index"), 1) + if best_index < 1 or best_index > len(candidates): + best_index = 1 + selected = candidates[best_index - 1] + meta_language = has_meta_reasoning(selected) + score = selected_score(judge_obj, best_index) + if score <= 0.0: + score = 3.0 if selected else 0.0 + low_quality = ( + bool(judge_obj.get("low_quality", False)) + or score < float(args.min_judge_score) + or meta_language + ) + row = { + "cache_key": cache_key(version, ex.source_id, ex.turn_idx), + "version": version, + "source_id": ex.source_id, + "turn_idx": ex.turn_idx, + "total_turns": ex.total_turns, + "selected_think": selected or fallback_think(version), + "selected_index": best_index, + "score": score, + "low_quality": low_quality, + "meta_language": meta_language, + "fallback": not bool(selected), + "missing_next_state": False, + "selected_reason": str(judge_obj.get("selected_reason", "")), + } + if args.save_candidates: + row["candidates"] = candidates + row["judge"] = judge_obj + row["judge_raw"] = judge_text + batch_rows.append(row) + + append_cache(cache_path, batch_rows) if not args.no_cache else None + for row in batch_rows: + results[(row["source_id"], int(row["turn_idx"]))] = row + print(f"[{version}] batch {batch_no}: wrote {len(batch_rows)} turn results") + return results + + +def rebuild_rows( + rows: Sequence[Dict[str, Any]], + full: Dict[Any, FullTrajectory], + result_map: Dict[Tuple[Any, int], Dict[str, Any]], +) -> List[Dict[str, Any]]: + rebuilt_by_source: Dict[Any, List[Tuple[Dict[str, Any], Dict[str, Any]]]] = {} + for source_id, traj in full.items(): + new_pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = [] + for idx, (user_msg, asst_msg) in enumerate(traj.pairs, start=1): + answer_block = extract_answer_block(str(asst_msg.get("content", ""))) + result = result_map.get((source_id, idx)) + think = str(result.get("selected_think", "")) if result else fallback_think("traj_sa") + new_user = copy.deepcopy(user_msg) + new_asst = copy.deepcopy(asst_msg) + if answer_block: + new_asst["content"] = make_response(think, answer_block) + else: + new_asst["content"] = str(asst_msg.get("content", "")) + new_pairs.append((new_user, new_asst)) + rebuilt_by_source[source_id] = new_pairs + + output: List[Dict[str, Any]] = [] + for idx, row in enumerate(rows): + meta = row.get("meta") or {} + source_id = meta.get("source_id", f"missing_source_{idx}") + turns = to_int(meta.get("turns"), 0) + new_row = copy.deepcopy(row) + traj = full.get(source_id) + pairs = rebuilt_by_source.get(source_id) + if traj is None or pairs is None or turns <= 0: + output.append(new_row) + continue + turns = min(turns, len(pairs)) + new_row["messages"] = copy.deepcopy(traj.sys_prefix) + [ + copy.deepcopy(msg) for pair in pairs[:turns] for msg in pair + ] + output.append(new_row) + return output + + +def validate_answer_unchanged(original: Sequence[Dict[str, Any]], rebuilt: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + if len(original) != len(rebuilt): + raise ValueError(f"Row count changed: original={len(original)} rebuilt={len(rebuilt)}") + checked = 0 + mismatches: List[Dict[str, Any]] = [] + for row_idx, (old_row, new_row) in enumerate(zip(original, rebuilt)): + old_pairs = collect_pairs(old_row.get("messages") or [], start_idx=len(extract_system_prefix(old_row.get("messages") or []))) + new_pairs = collect_pairs(new_row.get("messages") or [], start_idx=len(extract_system_prefix(new_row.get("messages") or []))) + if len(old_pairs) != len(new_pairs): + mismatches.append({"row_idx": row_idx, "reason": "pair_count_changed"}) + continue + for turn_idx, ((_, old_asst), (_, new_asst)) in enumerate(zip(old_pairs, new_pairs), start=1): + old_answer = extract_answer_block(str(old_asst.get("content", ""))) + new_answer = extract_answer_block(str(new_asst.get("content", ""))) + checked += 1 + if old_answer != new_answer: + mismatches.append( + { + "row_idx": row_idx, + "turn_idx": turn_idx, + "old_answer": old_answer, + "new_answer": new_answer, + } + ) + if len(mismatches) >= 20: + break + if len(mismatches) >= 20: + break + if mismatches: + raise ValueError(f"Answer validation failed, examples: {mismatches[:3]}") + return {"checked_assistant_messages": checked, "answer_mismatches": 0} + + +def filter_full_by_args(full: Dict[Any, FullTrajectory], args: argparse.Namespace) -> Dict[Any, FullTrajectory]: + selected = dict(full) + if args.source_ids.strip(): + allow = {item.strip() for item in args.source_ids.split(",") if item.strip()} + selected = {sid: traj for sid, traj in selected.items() if source_key(sid) in allow} + if args.limit_sources is not None: + limited: Dict[Any, FullTrajectory] = {} + for sid in list(selected.keys())[: int(args.limit_sources)]: + limited[sid] = selected[sid] + selected = limited + return selected + + +def report_from_results( + *, + version: str, + result_map: Dict[Tuple[Any, int], Dict[str, Any]], + validation: Dict[str, Any], + args: argparse.Namespace, +) -> Dict[str, Any]: + values = list(result_map.values()) + low_quality = sum(1 for row in values if row.get("low_quality")) + fallback = sum(1 for row in values if row.get("fallback")) + meta_language = sum(1 for row in values if row.get("meta_language")) + missing_next = sum(1 for row in values if row.get("missing_next_state")) + scores = [float(row.get("score", 0.0)) for row in values] + summary = { + "version": version, + "n": int(args.n), + "turn_results": len(values), + "low_quality": low_quality, + "fallback": fallback, + "meta_language": meta_language, + "missing_next_state": missing_next, + "avg_score": sum(scores) / len(scores) if scores else 0.0, + "min_score": min(scores) if scores else 0.0, + "max_score": max(scores) if scores else 0.0, + **validation, + } + per_turn: List[Dict[str, Any]] = [] + for row in values: + item = { + "source_id": row.get("source_id"), + "turn_idx": row.get("turn_idx"), + "total_turns": row.get("total_turns"), + "selected_index": row.get("selected_index"), + "score": row.get("score"), + "low_quality": row.get("low_quality"), + "fallback": row.get("fallback"), + "meta_language": row.get("meta_language", False), + "missing_next_state": row.get("missing_next_state"), + "selected_reason": row.get("selected_reason", ""), + } + if args.save_candidates: + item["selected_think"] = row.get("selected_think") + item["candidates"] = row.get("candidates", []) + item["judge"] = row.get("judge", {}) + per_turn.append(item) + return {"summary": summary, "per_turn": per_turn} + + +def main() -> None: + args = parse_args() + versions = [v.strip() for v in args.versions.split(",") if v.strip()] + if not versions or any(v != "traj_sa" for v in versions): + raise ValueError("--versions must contain only traj_sa for this script") + if not args.dry_run and not args.model: + raise ValueError("--model is required unless --dry-run is set") + + input_path = args.input.expanduser().resolve() + output_dir = (args.output_dir or input_path.parent).expanduser().resolve() + output_prefix = args.output_prefix or input_path.stem + + print(f"Loading input: {input_path}") + rows = load_json_list(input_path) + full_all = build_full_trajectories(rows) + full_selected = filter_full_by_args(full_all, args) + if not full_selected: + raise ValueError("No usable trajectories selected.") + turns = iter_turns( + full_selected, + state_max_chars=int(args.trajectory_state_max_chars), + action_max_chars=int(args.trajectory_action_max_chars), + ) + print(f"Rows={len(rows)} sources={len(full_all)} selected_sources={len(full_selected)} selected_turns={len(turns)}") + + llm = tokenizer = judge_llm = judge_tokenizer = None + if not args.dry_run: + llm, tokenizer = load_vllm_model(args.model, args, tensor_parallel_size=args.tensor_parallel_size) + judge_model = args.judge_model or args.model + if judge_model == args.model: + judge_llm, judge_tokenizer = llm, tokenizer + else: + judge_tp = args.judge_tensor_parallel_size or args.tensor_parallel_size + judge_llm, judge_tokenizer = load_vllm_model(judge_model, args, tensor_parallel_size=judge_tp) + + for version in versions: + result_map = synthesize_version( + version=version, + turns=turns, + args=args, + output_dir=output_dir, + output_prefix=output_prefix, + llm=llm, + tokenizer=tokenizer, + judge_llm=judge_llm, + judge_tokenizer=judge_tokenizer, + ) + rows_for_output = [ + row + for idx, row in enumerate(rows) + if not args.selected_only + or (row.get("meta") or {}).get("source_id", f"missing_source_{idx}") in full_selected + ] + rebuilt = rebuild_rows(rows_for_output, full_selected, result_map) + validation = validate_answer_unchanged(rows_for_output, rebuilt) + out_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.json" + report_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.report.json" + dump_json(out_path, rebuilt, indent=int(args.indent)) + report = report_from_results(version=version, result_map=result_map, validation=validation, args=args) + dump_json(report_path, report, indent=2) + print(f"[{version}] wrote SFT: {out_path}") + print(f"[{version}] wrote report: {report_path}") + print(f"[{version}] summary: {json.dumps(report['summary'], ensure_ascii=False)}") + + +if __name__ == "__main__": + main() diff --git a/scripts/synthesize_think_bon_v2.py b/scripts/synthesize_think_bon_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..f6aee7b330e0cdffead1b3f145a140a7455ab1f5 --- /dev/null +++ b/scripts/synthesize_think_bon_v2.py @@ -0,0 +1,854 @@ +#!/usr/bin/env python3 +"""Synthesize traces for SFT singleturn trajectories with BoN + judge. + +This script is intentionally environment-agnostic. It assumes a JSON list of rows +with the common RAGEN SFT shape: + + {"messages": [{"role": "system"}, {"role": "user"}, {"role": "assistant"}, ...], + "meta": {"source_id": ..., "turns": ..., "total_turns": ...}} + +For each source_id, the complete trajectory row is selected, one reasoning trace +is synthesized per turn, and the selected traces are written back to every +cumulative singleturn prefix while keeping every original ... +block exactly unchanged. + + +python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_v2.py \ + --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json \ + --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \ + --output-prefix step_999424_sft_singleturn_withthink \ + --versions sa,sas \ + --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \ + --tensor-parallel-size 4 \ + --n 8 \ + --batch-size 32 \ + --judge-batch-size 32 \ + --limit-sources 50 +""" + +from __future__ import annotations + +import argparse +import copy +import json +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple + + +ANSWER_RE = re.compile(r".*?", re.IGNORECASE | re.DOTALL) +THINK_RE = re.compile(r"(.*?)", re.IGNORECASE | re.DOTALL) +JSON_OBJ_RE = re.compile(r"\{.*\}", re.DOTALL) +META_REASONING_RE = re.compile( + r"\b(" + r"expert action|fixed action|given action|provided action|target action|" + r"demonstrated action|demonstrated answer|known action|chosen by (?:the )?expert|" + r"the action (?:was|is) (?:given|fixed|provided|known)" + r")\b", + re.IGNORECASE, +) + + +@dataclass +class TurnExample: + source_id: Any + turn_idx: int + total_turns: int + user_content: str + assistant_content: str + answer_block: str + next_user_content: Optional[str] + + +@dataclass +class FullTrajectory: + source_id: Any + sys_prefix: List[Dict[str, Any]] + pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] + meta: Dict[str, Any] + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Synthesize first-person target-action thinking traces with per-turn BoN and LLM judge." + ) + parser.add_argument("--input", "-i", type=Path, required=True, help="Input SFT JSON list.") + parser.add_argument( + "--output-dir", + type=Path, + default=None, + help="Directory for output files. Defaults to input parent.", + ) + parser.add_argument( + "--output-prefix", + default=None, + help="Output filename prefix. Defaults to input stem.", + ) + parser.add_argument( + "--versions", + default="sa,sas", + help="Comma-separated versions: sa and/or sas. sa uses s,a; sas uses s,a,s'.", + ) + parser.add_argument("--model", default=None, help="HF model path for tokenizer + vLLM.") + parser.add_argument("--judge-model", default=None, help="Optional separate judge model path.") + parser.add_argument("--n", type=int, default=8, help="BoN candidates per turn.") + parser.add_argument( + "--mode", + default="per_turn", + choices=["per_turn"], + help="BoN mode. Currently only independent per-turn BoN is implemented.", + ) + parser.add_argument("--limit-sources", type=int, default=None, help="Pilot limit by source_id count.") + parser.add_argument("--source-ids", default="", help="Optional comma-separated source_id allowlist.") + parser.add_argument("--batch-size", type=int, default=64, help="Prompt batch size for generation.") + parser.add_argument("--judge-batch-size", type=int, default=64, help="Prompt batch size for judge.") + parser.add_argument("--temperature", type=float, default=0.7) + parser.add_argument("--top-p", type=float, default=0.95) + parser.add_argument("--top-k", type=int, default=-1) + parser.add_argument("--max-tokens", type=int, default=160, help="Max tokens for think generation.") + parser.add_argument("--judge-temperature", type=float, default=0.0) + parser.add_argument("--judge-max-tokens", type=int, default=768) + parser.add_argument("--tensor-parallel-size", type=int, default=1) + parser.add_argument("--judge-tensor-parallel-size", type=int, default=None) + parser.add_argument("--dtype", default="auto") + parser.add_argument("--gpu-memory-utilization", type=float, default=0.9) + parser.add_argument("--max-model-len", type=int, default=None) + parser.add_argument("--trust-remote-code", action="store_true") + parser.add_argument("--min-judge-score", type=float, default=3.0) + parser.add_argument("--save-candidates", action="store_true", help="Store all candidates in report.") + parser.add_argument( + "--selected-only", + action="store_true", + help="Write only rows whose source_id was selected by --limit-sources/--source-ids.", + ) + parser.add_argument("--no-cache", action="store_true", help="Disable JSONL cache/resume.") + parser.add_argument("--dry-run", action="store_true", help="Do not load vLLM; create deterministic mock thinks.") + parser.add_argument("--indent", type=int, default=2, help="JSON output indent. Use -1 for compact.") + return parser.parse_args() + + +def load_json_list(path: Path) -> List[Dict[str, Any]]: + with path.open("r", encoding="utf-8") as f: + data = json.load(f) + if not isinstance(data, list): + raise ValueError(f"Expected JSON list at {path}, got {type(data).__name__}") + if not all(isinstance(row, dict) for row in data): + raise ValueError(f"Expected all rows to be objects in {path}") + return data + + +def dump_json(path: Path, data: Any, indent: int) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + kwargs = {"ensure_ascii": False} + if indent >= 0: + kwargs["indent"] = indent + with path.open("w", encoding="utf-8") as f: + json.dump(data, f, **kwargs) + + +def extract_system_prefix(messages: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]: + out: List[Dict[str, Any]] = [] + for msg in messages: + if msg.get("role") == "system": + out.append(copy.deepcopy(msg)) + else: + break + return out + + +def collect_pairs(messages: Sequence[Dict[str, Any]], start_idx: int = 0) -> List[Tuple[Dict[str, Any], Dict[str, Any]]]: + pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = [] + idx = start_idx + while idx < len(messages): + while idx < len(messages) and messages[idx].get("role") != "user": + idx += 1 + if idx >= len(messages): + break + if idx + 1 < len(messages) and messages[idx + 1].get("role") == "assistant": + pairs.append((copy.deepcopy(messages[idx]), copy.deepcopy(messages[idx + 1]))) + idx += 2 + else: + idx += 1 + return pairs + + +def to_int(value: Any, default: int = 0) -> int: + try: + return int(value) + except (TypeError, ValueError): + return default + + +def source_key(source_id: Any) -> str: + return str(source_id) + + +def group_rows(rows: Sequence[Dict[str, Any]]) -> Dict[Any, List[Dict[str, Any]]]: + groups: Dict[Any, List[Dict[str, Any]]] = {} + for idx, row in enumerate(rows): + meta = row.get("meta") or {} + source_id = meta.get("source_id", f"missing_source_{idx}") + groups.setdefault(source_id, []).append(row) + for items in groups.values(): + items.sort(key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0)) + return groups + + +def select_full_row(source_id: Any, items: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + exact = [ + row + for row in items + if to_int((row.get("meta") or {}).get("turns"), -1) + == to_int((row.get("meta") or {}).get("total_turns"), -2) + ] + if exact: + return exact[-1] + return max(items, key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0)) + + +def build_full_trajectories(rows: Sequence[Dict[str, Any]]) -> Dict[Any, FullTrajectory]: + groups = group_rows(rows) + full: Dict[Any, FullTrajectory] = {} + for source_id, items in groups.items(): + row = select_full_row(source_id, items) + messages = row.get("messages") or [] + if not isinstance(messages, list): + continue + sys_prefix = extract_system_prefix(messages) + pairs = collect_pairs(messages, start_idx=len(sys_prefix)) + if not pairs: + continue + full[source_id] = FullTrajectory( + source_id=source_id, + sys_prefix=sys_prefix, + pairs=pairs, + meta=dict(row.get("meta") or {}), + ) + return full + + +def extract_answer_block(text: str) -> str: + match = ANSWER_RE.search(text or "") + return match.group(0) if match is not None else "" + + +def clean_think(text: str) -> str: + text = (text or "").strip() + think_match = THINK_RE.search(text) + if think_match is not None: + text = think_match.group(1).strip() + text = re.split(r"<\s*/?\s*answer\s*>", text, flags=re.IGNORECASE)[0] + text = re.sub(r"", "", text, flags=re.IGNORECASE) + text = re.sub(r"\s+", " ", text).strip() + text = text.strip('` \t\n\r"') + return text + + +def make_response(think: str, answer_block: str) -> str: + return f"{think.strip()}{answer_block}" + + +def has_meta_reasoning(text: str) -> bool: + return META_REASONING_RE.search(text or "") is not None + + +def iter_turns(full: Dict[Any, FullTrajectory]) -> List[TurnExample]: + turns: List[TurnExample] = [] + for source_id, traj in full.items(): + total_turns = len(traj.pairs) + for i, (user_msg, asst_msg) in enumerate(traj.pairs): + answer_block = extract_answer_block(str(asst_msg.get("content", ""))) + next_user = None + if i + 1 < total_turns: + next_user = str(traj.pairs[i + 1][0].get("content", "")) + turns.append( + TurnExample( + source_id=source_id, + turn_idx=i + 1, + total_turns=total_turns, + user_content=str(user_msg.get("content", "")), + assistant_content=str(asst_msg.get("content", "")), + answer_block=answer_block, + next_user_content=next_user, + ) + ) + return turns + + +def build_generation_messages(example: TurnExample, version: str) -> List[Dict[str, str]]: + if version not in {"sa", "sas"}: + raise ValueError(f"Unknown version: {version}") + sas_available = version == "sas" and example.next_user_content is not None + parts = [ + "You are the assistant acting in this environment at the current turn.", + "You have already decided which action to output; now write the private inner reasoning that naturally leads to that action.", + "Write from your own first-person decision-making perspective, as if you are solving the task, not evaluating another model or an expert.", + "Only output the inner text for .... Do not output , , , JSON, bullets, or any extra wrapper.", + "Do not say or imply that the action was given, fixed, known, demonstrated, provided, or chosen by an expert. Avoid meta phrases such as 'the expert action', 'the fixed action', 'given action', or 'demonstrated answer', 'the expert'.", + "Do not change to a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.", + "Keep it concise: 1-3 English sentences with step-by-step reasoning grounded in the visible context.", + "", + "Current observation/state s:", + "```text", + example.user_content.strip(), + "```", + "", + "Action that your reasoning should lead to:", + "```text", + example.answer_block.strip() or example.assistant_content.strip(), + "```", + ] + if sas_available: + parts.extend( + [ + "", + "Observed next state/feedback s' after taking this action:", + "```text", + str(example.next_user_content).strip(), + "```", + "Use s' only to ground the explanation of the observed transition; do not switch to another action.", + ] + ) + elif version == "sas": + parts.extend( + [ + "", + "No next state s' is available for this final turn, so explain using only s and a.", + ] + ) + return [ + { + "role": "system", + "content": "You write faithful, concise first-person reasoning for your own next action.", + }, + {"role": "user", "content": "\n".join(parts)}, + ] + + +def build_judge_messages(example: TurnExample, version: str, candidates: Sequence[str]) -> List[Dict[str, str]]: + candidate_text = "\n".join(f"[{i + 1}] {cand}" for i, cand in enumerate(candidates)) + sas_available = version == "sas" and example.next_user_content is not None + parts = [ + "You are auditing candidate texts for an SFT trajectory.", + "Select the candidate that reads like the assistant's own private step-by-step reasoning leading to the target action, while staying faithful to the visible context.", + "Strongly penalize meta-reasoning that says or implies the action was given, fixed, known, demonstrated, provided, or chosen by an expert.", + "Also penalize unsupported factual claims, contradicted claims, changing the action, excessive certainty such as 'only'/'optimal' without clear support, verbosity, and format pollution.", + "Return strict JSON only, with no markdown.", + "", + "Current observation/state s:", + "```text", + example.user_content.strip(), + "```", + "", + "Target action a that the reasoning should lead to:", + "```text", + example.answer_block.strip() or example.assistant_content.strip(), + "```", + ] + if sas_available: + parts.extend( + [ + "", + "Observed next state/feedback s' after taking action a:", + "```text", + str(example.next_user_content).strip(), + "```", + ] + ) + elif version == "sas": + parts.append("\nNo next state s' is available for this final turn.") + parts.extend( + [ + "", + "Candidates:", + candidate_text, + "", + "Use this JSON schema:", + '{"best_index": 1, "scores": [{"index": 1, "score": 1, "unsupported_claims": 0, "contradictions": 0, "reason": "short reason"}], "selected_reason": "short reason", "low_quality": false}', + "Scores are from 1 to 5. Set low_quality=true if the best candidate is still weak or generic.", + ] + ) + return [ + {"role": "system", "content": "You are a strict factuality judge for reasoning traces."}, + {"role": "user", "content": "\n".join(parts)}, + ] + + +def render_prompt(tokenizer: Any, messages: List[Dict[str, str]]) -> str: + return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) + + +def load_vllm_model( + model_path: str, + args: argparse.Namespace, + tensor_parallel_size: Optional[int] = None, +) -> Tuple[Any, Any]: + try: + from transformers import AutoTokenizer + from vllm import LLM + except ImportError as exc: + raise RuntimeError("This script requires `vllm` and `transformers`.") from exc + + tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=bool(args.trust_remote_code)) + llm_kwargs: Dict[str, Any] = { + "model": model_path, + "tensor_parallel_size": int(tensor_parallel_size or args.tensor_parallel_size), + "dtype": args.dtype, + "gpu_memory_utilization": float(args.gpu_memory_utilization), + "trust_remote_code": bool(args.trust_remote_code), + } + if args.max_model_len is not None: + llm_kwargs["max_model_len"] = int(args.max_model_len) + return LLM(**llm_kwargs), tokenizer + + +def make_sampling_params(args: argparse.Namespace, *, judge: bool = False) -> Any: + try: + from vllm import SamplingParams + except ImportError as exc: + raise RuntimeError("This script requires `vllm`.") from exc + if judge: + return SamplingParams( + temperature=float(args.judge_temperature), + top_p=1.0, + max_tokens=int(args.judge_max_tokens), + ) + return SamplingParams( + n=int(args.n), + temperature=float(args.temperature), + top_p=float(args.top_p), + top_k=int(args.top_k), + max_tokens=int(args.max_tokens), + ) + + +def chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]: + if size <= 0: + yield items + return + for start in range(0, len(items), size): + yield items[start : start + size] + + +def parse_judge_json(text: str) -> Dict[str, Any]: + text = (text or "").strip() + match = JSON_OBJ_RE.search(text) + if match is not None: + text = match.group(0) + try: + obj = json.loads(text) + if isinstance(obj, dict): + return obj + except json.JSONDecodeError: + pass + return {} + + +def selected_score(judge_obj: Dict[str, Any], best_index: int) -> float: + for item in judge_obj.get("scores") or []: + if isinstance(item, dict) and to_int(item.get("index"), -1) == best_index: + try: + return float(item.get("score", 0.0)) + except (TypeError, ValueError): + return 0.0 + return 0.0 + + +def fallback_think(version: str) -> str: + if version == "sas": + return ( + "I compare the current observation with the next-state feedback and choose the move " + "that is consistent with making progress under the task constraints." + ) + return ( + "I inspect the current observation and choose the move that best follows the task constraints " + "while aiming to make progress from this state." + ) + + +def cache_key(version: str, source_id: Any, turn_idx: int) -> str: + return json.dumps( + {"version": version, "source_id": source_id, "turn_idx": turn_idx}, + ensure_ascii=False, + sort_keys=True, + ) + + +def load_cache(path: Path) -> Dict[str, Dict[str, Any]]: + cache: Dict[str, Dict[str, Any]] = {} + if not path.exists(): + return cache + with path.open("r", encoding="utf-8") as f: + for line_no, line in enumerate(f, start=1): + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except json.JSONDecodeError: + print(f"Warning: skipped invalid cache line {path}:{line_no}") + continue + key = row.get("cache_key") + if isinstance(key, str): + cache[key] = row + return cache + + +def append_cache(path: Path, rows: Sequence[Dict[str, Any]]) -> None: + if not rows: + return + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + + +def dry_candidates(example: TurnExample, version: str, n: int) -> List[str]: + base = "I inspect the visible state and reason step by step toward the next move." + if version == "sas" and example.next_user_content is not None: + base = "I inspect the visible state and the observed next-state feedback to reason toward the next move." + return [f"{base} Candidate {i + 1}." for i in range(n)] + + +def synthesize_version( + *, + version: str, + turns: Sequence[TurnExample], + args: argparse.Namespace, + output_dir: Path, + output_prefix: str, + llm: Any, + tokenizer: Any, + judge_llm: Any, + judge_tokenizer: Any, +) -> Dict[Tuple[Any, int], Dict[str, Any]]: + cache_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.cache.jsonl" + cache = {} if args.no_cache else load_cache(cache_path) + results: Dict[Tuple[Any, int], Dict[str, Any]] = {} + missing: List[TurnExample] = [] + for ex in turns: + key = cache_key(version, ex.source_id, ex.turn_idx) + cached = cache.get(key) + if cached is not None and cached.get("selected_think"): + results[(ex.source_id, ex.turn_idx)] = cached + else: + missing.append(ex) + + print(f"[{version}] turns={len(turns)} cached={len(results)} missing={len(missing)}") + gen_params = None if args.dry_run else make_sampling_params(args, judge=False) + judge_params = None if args.dry_run else make_sampling_params(args, judge=True) + + for batch_no, batch in enumerate(chunks(missing, int(args.batch_size)), start=1): + batch = list(batch) + if args.dry_run: + all_candidates = [dry_candidates(ex, version, int(args.n)) for ex in batch] + else: + prompts = [render_prompt(tokenizer, build_generation_messages(ex, version)) for ex in batch] + outputs = llm.generate(prompts, sampling_params=gen_params) + all_candidates = [] + for out in outputs: + raw_candidates = [clean_think(candidate.text) for candidate in out.outputs] + candidates = [cand for cand in raw_candidates if cand and not has_meta_reasoning(cand)] + if not candidates: + candidates = [cand for cand in raw_candidates if cand] + all_candidates.append(candidates) + + judge_inputs: List[Tuple[TurnExample, List[str]]] = [] + batch_rows: List[Dict[str, Any]] = [] + for ex, candidates in zip(batch, all_candidates): + if not candidates: + selected = fallback_think(version) + row = { + "cache_key": cache_key(version, ex.source_id, ex.turn_idx), + "version": version, + "source_id": ex.source_id, + "turn_idx": ex.turn_idx, + "total_turns": ex.total_turns, + "selected_think": selected, + "selected_index": None, + "score": 0.0, + "low_quality": True, + "meta_language": False, + "fallback": True, + "missing_next_state": version == "sas" and ex.next_user_content is None, + "selected_reason": "No valid generation candidates; used fallback.", + } + if args.save_candidates: + row["candidates"] = [] + batch_rows.append(row) + else: + judge_inputs.append((ex, candidates)) + + judge_texts: List[str] = [] + if judge_inputs: + if args.dry_run: + judge_texts = [ + json.dumps( + { + "best_index": 1, + "scores": [ + { + "index": 1, + "score": 3, + "unsupported_claims": 0, + "contradictions": 0, + "reason": "dry run", + } + ], + "selected_reason": "dry run", + "low_quality": False, + } + ) + for _ in judge_inputs + ] + else: + judge_prompts = [ + render_prompt(judge_tokenizer, build_judge_messages(ex, version, candidates)) + for ex, candidates in judge_inputs + ] + judge_texts = [] + for judge_chunk in chunks(judge_prompts, int(args.judge_batch_size)): + judge_outputs = judge_llm.generate(list(judge_chunk), sampling_params=judge_params) + judge_texts.extend(out.outputs[0].text for out in judge_outputs) + + for (ex, candidates), judge_text in zip(judge_inputs, judge_texts): + judge_obj = parse_judge_json(judge_text) + best_index = to_int(judge_obj.get("best_index"), 1) + if best_index < 1 or best_index > len(candidates): + best_index = 1 + selected = candidates[best_index - 1] + meta_language = has_meta_reasoning(selected) + score = selected_score(judge_obj, best_index) + if score <= 0.0: + score = 3.0 if selected else 0.0 + low_quality = ( + bool(judge_obj.get("low_quality", False)) + or score < float(args.min_judge_score) + or meta_language + ) + row = { + "cache_key": cache_key(version, ex.source_id, ex.turn_idx), + "version": version, + "source_id": ex.source_id, + "turn_idx": ex.turn_idx, + "total_turns": ex.total_turns, + "selected_think": selected or fallback_think(version), + "selected_index": best_index, + "score": score, + "low_quality": low_quality, + "meta_language": meta_language, + "fallback": not bool(selected), + "missing_next_state": version == "sas" and ex.next_user_content is None, + "selected_reason": str(judge_obj.get("selected_reason", "")), + } + if args.save_candidates: + row["candidates"] = candidates + row["judge"] = judge_obj + row["judge_raw"] = judge_text + batch_rows.append(row) + + append_cache(cache_path, batch_rows) if not args.no_cache else None + for row in batch_rows: + results[(row["source_id"], int(row["turn_idx"]))] = row + print(f"[{version}] batch {batch_no}: wrote {len(batch_rows)} turn results") + return results + + +def rebuild_rows( + rows: Sequence[Dict[str, Any]], + full: Dict[Any, FullTrajectory], + result_map: Dict[Tuple[Any, int], Dict[str, Any]], +) -> List[Dict[str, Any]]: + rebuilt_by_source: Dict[Any, List[Tuple[Dict[str, Any], Dict[str, Any]]]] = {} + for source_id, traj in full.items(): + new_pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = [] + for idx, (user_msg, asst_msg) in enumerate(traj.pairs, start=1): + answer_block = extract_answer_block(str(asst_msg.get("content", ""))) + result = result_map.get((source_id, idx)) + think = str(result.get("selected_think", "")) if result else fallback_think("sa") + new_user = copy.deepcopy(user_msg) + new_asst = copy.deepcopy(asst_msg) + if answer_block: + new_asst["content"] = make_response(think, answer_block) + else: + new_asst["content"] = str(asst_msg.get("content", "")) + new_pairs.append((new_user, new_asst)) + rebuilt_by_source[source_id] = new_pairs + + output: List[Dict[str, Any]] = [] + for idx, row in enumerate(rows): + meta = row.get("meta") or {} + source_id = meta.get("source_id", f"missing_source_{idx}") + turns = to_int(meta.get("turns"), 0) + new_row = copy.deepcopy(row) + traj = full.get(source_id) + pairs = rebuilt_by_source.get(source_id) + if traj is None or pairs is None or turns <= 0: + output.append(new_row) + continue + turns = min(turns, len(pairs)) + new_row["messages"] = copy.deepcopy(traj.sys_prefix) + [ + copy.deepcopy(msg) for pair in pairs[:turns] for msg in pair + ] + output.append(new_row) + return output + + +def validate_answer_unchanged(original: Sequence[Dict[str, Any]], rebuilt: Sequence[Dict[str, Any]]) -> Dict[str, Any]: + if len(original) != len(rebuilt): + raise ValueError(f"Row count changed: original={len(original)} rebuilt={len(rebuilt)}") + checked = 0 + mismatches: List[Dict[str, Any]] = [] + for row_idx, (old_row, new_row) in enumerate(zip(original, rebuilt)): + old_pairs = collect_pairs(old_row.get("messages") or [], start_idx=len(extract_system_prefix(old_row.get("messages") or []))) + new_pairs = collect_pairs(new_row.get("messages") or [], start_idx=len(extract_system_prefix(new_row.get("messages") or []))) + if len(old_pairs) != len(new_pairs): + mismatches.append({"row_idx": row_idx, "reason": "pair_count_changed"}) + continue + for turn_idx, ((_, old_asst), (_, new_asst)) in enumerate(zip(old_pairs, new_pairs), start=1): + old_answer = extract_answer_block(str(old_asst.get("content", ""))) + new_answer = extract_answer_block(str(new_asst.get("content", ""))) + checked += 1 + if old_answer != new_answer: + mismatches.append( + { + "row_idx": row_idx, + "turn_idx": turn_idx, + "old_answer": old_answer, + "new_answer": new_answer, + } + ) + if len(mismatches) >= 20: + break + if len(mismatches) >= 20: + break + if mismatches: + raise ValueError(f"Answer validation failed, examples: {mismatches[:3]}") + return {"checked_assistant_messages": checked, "answer_mismatches": 0} + + +def filter_full_by_args(full: Dict[Any, FullTrajectory], args: argparse.Namespace) -> Dict[Any, FullTrajectory]: + selected = dict(full) + if args.source_ids.strip(): + allow = {item.strip() for item in args.source_ids.split(",") if item.strip()} + selected = {sid: traj for sid, traj in selected.items() if source_key(sid) in allow} + if args.limit_sources is not None: + limited: Dict[Any, FullTrajectory] = {} + for sid in list(selected.keys())[: int(args.limit_sources)]: + limited[sid] = selected[sid] + selected = limited + return selected + + +def report_from_results( + *, + version: str, + result_map: Dict[Tuple[Any, int], Dict[str, Any]], + validation: Dict[str, Any], + args: argparse.Namespace, +) -> Dict[str, Any]: + values = list(result_map.values()) + low_quality = sum(1 for row in values if row.get("low_quality")) + fallback = sum(1 for row in values if row.get("fallback")) + meta_language = sum(1 for row in values if row.get("meta_language")) + missing_next = sum(1 for row in values if row.get("missing_next_state")) + scores = [float(row.get("score", 0.0)) for row in values] + summary = { + "version": version, + "n": int(args.n), + "turn_results": len(values), + "low_quality": low_quality, + "fallback": fallback, + "meta_language": meta_language, + "missing_next_state": missing_next, + "avg_score": sum(scores) / len(scores) if scores else 0.0, + "min_score": min(scores) if scores else 0.0, + "max_score": max(scores) if scores else 0.0, + **validation, + } + per_turn: List[Dict[str, Any]] = [] + for row in values: + item = { + "source_id": row.get("source_id"), + "turn_idx": row.get("turn_idx"), + "total_turns": row.get("total_turns"), + "selected_index": row.get("selected_index"), + "score": row.get("score"), + "low_quality": row.get("low_quality"), + "fallback": row.get("fallback"), + "meta_language": row.get("meta_language", False), + "missing_next_state": row.get("missing_next_state"), + "selected_reason": row.get("selected_reason", ""), + } + if args.save_candidates: + item["selected_think"] = row.get("selected_think") + item["candidates"] = row.get("candidates", []) + item["judge"] = row.get("judge", {}) + per_turn.append(item) + return {"summary": summary, "per_turn": per_turn} + + +def main() -> None: + args = parse_args() + versions = [v.strip() for v in args.versions.split(",") if v.strip()] + if not versions or any(v not in {"sa", "sas"} for v in versions): + raise ValueError("--versions must contain only sa and/or sas") + if not args.dry_run and not args.model: + raise ValueError("--model is required unless --dry-run is set") + + input_path = args.input.expanduser().resolve() + output_dir = (args.output_dir or input_path.parent).expanduser().resolve() + output_prefix = args.output_prefix or input_path.stem + + print(f"Loading input: {input_path}") + rows = load_json_list(input_path) + full_all = build_full_trajectories(rows) + full_selected = filter_full_by_args(full_all, args) + if not full_selected: + raise ValueError("No usable trajectories selected.") + turns = iter_turns(full_selected) + print(f"Rows={len(rows)} sources={len(full_all)} selected_sources={len(full_selected)} selected_turns={len(turns)}") + + llm = tokenizer = judge_llm = judge_tokenizer = None + if not args.dry_run: + llm, tokenizer = load_vllm_model(args.model, args, tensor_parallel_size=args.tensor_parallel_size) + judge_model = args.judge_model or args.model + if judge_model == args.model: + judge_llm, judge_tokenizer = llm, tokenizer + else: + judge_tp = args.judge_tensor_parallel_size or args.tensor_parallel_size + judge_llm, judge_tokenizer = load_vllm_model(judge_model, args, tensor_parallel_size=judge_tp) + + for version in versions: + result_map = synthesize_version( + version=version, + turns=turns, + args=args, + output_dir=output_dir, + output_prefix=output_prefix, + llm=llm, + tokenizer=tokenizer, + judge_llm=judge_llm, + judge_tokenizer=judge_tokenizer, + ) + rows_for_output = [ + row + for idx, row in enumerate(rows) + if not args.selected_only + or (row.get("meta") or {}).get("source_id", f"missing_source_{idx}") in full_selected + ] + rebuilt = rebuild_rows(rows_for_output, full_selected, result_map) + validation = validate_answer_unchanged(rows_for_output, rebuilt) + out_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.json" + report_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.report.json" + dump_json(out_path, rebuilt, indent=int(args.indent)) + report = report_from_results(version=version, result_map=result_map, validation=validation, args=args) + dump_json(report_path, report, indent=2) + print(f"[{version}] wrote SFT: {out_path}") + print(f"[{version}] wrote report: {report_path}") + print(f"[{version}] summary: {json.dumps(report['summary'], ensure_ascii=False)}") + + +if __name__ == "__main__": + main() diff --git a/scripts/train_sokoban.py b/scripts/train_sokoban.py new file mode 100644 index 0000000000000000000000000000000000000000..dbfb8487fab0185cb06729fcf04ffaee6b2f2d0d --- /dev/null +++ b/scripts/train_sokoban.py @@ -0,0 +1,356 @@ +import argparse +import os +import time +from dataclasses import dataclass +from typing import Tuple, Dict, List + +import numpy as np +import torch +import torch.nn as nn +import torch.optim as optim +from torch.distributions import Categorical + +from ragen.env.sokoban.env import SokobanEnv +from ragen.env.sokoban.config import SokobanEnvConfig +from ragen.utils import all_seed + + +# ===== Observation parsing (text grid -> 7xHxW one-hot) ===== +SYMBOLS = ["#", "_", "O", "√", "X", "P", "S"] +SYMBOL_TO_IDX: Dict[str, int] = {s: i for i, s in enumerate(SYMBOLS)} + + +def parse_grid_text(obs_text: str, board_shape: Tuple[int, int]) -> torch.Tensor: + lines = obs_text.splitlines() + H, W = board_shape + assert len(lines) == H, f"Grid height mismatch: expected {H}, got {len(lines)}" + grid = [[c for c in line] for line in lines] + assert all(len(row) == W for row in grid), "Grid width mismatch" + out = np.zeros((len(SYMBOLS), H, W), dtype=np.float32) + for r in range(H): + for c in range(W): + ch = grid[r][c] + idx = SYMBOL_TO_IDX.get(ch, None) + if idx is None: + raise ValueError(f"Unknown grid symbol '{ch}' at {(r, c)}") + out[idx, r, c] = 1.0 + return torch.from_numpy(out) + + +# ===== Small CNN Policy-Value Net ===== +class SmallSokobanCNN(nn.Module): + def __init__(self, in_channels: int, num_actions: int): + super().__init__() + # 6x6 is tiny; use minimal convs + self.encoder = nn.Sequential( + nn.Conv2d(in_channels, 32, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(32, 64, kernel_size=3, padding=1), + nn.ReLU(inplace=True), + nn.Flatten(), + ) + # compute flat size for 6x6 grids at runtime + self._feat_dim = None + self.policy_head = nn.Linear(64 * 6 * 6, num_actions) + self.value_head = nn.Linear(64 * 6 * 6, 1) + + def forward(self, x: torch.Tensor): + # x: [B, C, H, W] + z = self.encoder(x) + logits = self.policy_head(z) + value = self.value_head(z).squeeze(-1) + return logits, value + + +@dataclass +class PPOConfig: + total_steps: int = 200_000 + rollout_steps: int = 256 + batch_size: int = 256 + update_epochs: int = 4 + gamma: float = 0.99 + gae_lambda: float = 0.95 + clip_coef: float = 0.2 + ent_coef: float = 0.01 + vf_coef: float = 0.5 + max_grad_norm: float = 0.5 + lr: float = 2.5e-4 + device: str = "cpu" + + +def compute_gae(rewards, dones, values, next_value, cfg: PPOConfig): + T = len(rewards) + adv = np.zeros(T, dtype=np.float32) + lastgaelam = 0.0 + for t in reversed(range(T)): + nonterminal = 1.0 - float(dones[t]) + delta = rewards[t] + cfg.gamma * next_value * nonterminal - values[t] + lastgaelam = delta + cfg.gamma * cfg.gae_lambda * nonterminal * lastgaelam + adv[t] = lastgaelam + next_value = values[t] + returns = adv + values + return adv, returns + + +def collect_rollout(env: SokobanEnv, policy: SmallSokobanCNN, cfg: PPOConfig, board_shape: Tuple[int, int], device: str): + obs_buf = [] + act_buf = [] + logp_buf = [] + rew_buf = [] + done_buf = [] + val_buf = [] + + policy.eval() + + obs_text = env.render() # current text observation + for _ in range(cfg.rollout_steps): + obs_t = parse_grid_text(obs_text, board_shape).unsqueeze(0).to(device) + with torch.no_grad(): + logits, value = policy(obs_t) + dist = Categorical(logits=logits) + act_model = dist.sample()[0].item() # 0..3 + logp = dist.log_prob(torch.tensor([act_model], device=device)).item() + val = value[0].item() + act_env = act_model + 1 # map to 1..4 + next_obs_text, reward, done, _ = env.step(act_env) + + obs_buf.append(obs_t.squeeze(0).cpu().numpy()) + act_buf.append(act_model) + logp_buf.append(logp) + rew_buf.append(reward) + done_buf.append(done) + val_buf.append(val) + + obs_text = next_obs_text + if done: + obs_text = env.reset() + + # bootstrap value + with torch.no_grad(): + obs_t = parse_grid_text(obs_text, board_shape).unsqueeze(0).to(device) + _, next_value = policy(obs_t) + next_value = next_value[0].item() + + adv, ret = compute_gae( + np.array(rew_buf, dtype=np.float32), + np.array(done_buf, dtype=np.bool_), + np.array(val_buf, dtype=np.float32), + next_value, + cfg, + ) + + data = { + "obs": torch.from_numpy(np.stack(obs_buf)).to(device), + "actions": torch.tensor(act_buf, dtype=torch.long, device=device), + "logp": torch.tensor(logp_buf, dtype=torch.float32, device=device), + "advantages": torch.tensor(adv, dtype=torch.float32, device=device), + "returns": torch.tensor(ret, dtype=torch.float32, device=device), + "values": torch.tensor(val_buf, dtype=torch.float32, device=device), + } + return data + + +def ppo_update(policy, optimizer, data, cfg: PPOConfig): + policy.train() + obs = data["obs"] + actions = data["actions"] + old_logp = data["logp"] + advantages = data["advantages"] + returns = data["returns"] + + advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) + + N = obs.shape[0] + idxs = np.arange(N) + + for _ in range(cfg.update_epochs): + np.random.shuffle(idxs) + for start in range(0, N, cfg.batch_size): + end = start + cfg.batch_size + mb_idx = idxs[start:end] + mb_obs = obs[mb_idx] + mb_act = actions[mb_idx] + mb_old_logp = old_logp[mb_idx] + mb_adv = advantages[mb_idx] + mb_ret = returns[mb_idx] + + logits, values = policy(mb_obs) + dist = Categorical(logits=logits) + new_logp = dist.log_prob(mb_act) + entropy = dist.entropy().mean() + + ratio = (new_logp - mb_old_logp).exp() + pg_loss1 = -mb_adv * ratio + pg_loss2 = -mb_adv * torch.clamp(ratio, 1.0 - cfg.clip_coef, 1.0 + cfg.clip_coef) + pg_loss = torch.max(pg_loss1, pg_loss2).mean() + + v_loss = 0.5 * (mb_ret - values).pow(2).mean() + loss = pg_loss + cfg.vf_coef * v_loss - cfg.ent_coef * entropy + + optimizer.zero_grad(set_to_none=True) + loss.backward() + nn.utils.clip_grad_norm_(policy.parameters(), cfg.max_grad_norm) + optimizer.step() + + with torch.no_grad(): + approx_kl = (old_logp - new_logp).mean().item() + clipfrac = (torch.gt(torch.abs(ratio - 1.0), cfg.clip_coef)).float().mean().item() + return { + "loss": float(loss.item()), + "pg_loss": float(pg_loss.mean().item()), + "v_loss": float(v_loss.item()), + "entropy": float(entropy.item()), + "approx_kl": approx_kl, + "clipfrac": clipfrac, + } + + +def evaluate(env: SokobanEnv, policy: SmallSokobanCNN, board_shape: Tuple[int, int], device: str, episodes: int = 5): + policy.eval() + returns = [] + with torch.no_grad(): + for _ in range(episodes): + obs_text = env.reset() + done = False + ep_ret = 0.0 + steps = 0 + while not done and steps < 200: + obs_t = parse_grid_text(obs_text, board_shape).unsqueeze(0).to(device) + logits, _ = policy(obs_t) + dist = Categorical(logits=logits) + act_model = torch.argmax(dist.probs, dim=-1)[0].item() + act_env = act_model + 1 + obs_text, reward, done, info = env.step(act_env) + ep_ret += reward + steps += 1 + returns.append(ep_ret) + return float(np.mean(returns)), float(np.std(returns)) + + +def main(): + parser = argparse.ArgumentParser() + # Sokoban config flags to preserve exact environment + parser.add_argument("--dim_x", type=int, default=None) + parser.add_argument("--dim_y", type=int, default=None) + parser.add_argument("--max_steps", type=int, default=None) + parser.add_argument("--num_boxes", type=int, default=None) + parser.add_argument("--search_depth", type=int, default=None) + parser.add_argument("--render_mode", type=str, default=None, choices=[None, "text", "rgb_array"]) + parser.add_argument("--observation_format", type=str, default=None, choices=[None, "grid", "coord", "grid_coord"]) + + # PPO/training + parser.add_argument("--total_steps", type=int, default=200_000) + parser.add_argument("--rollout_steps", type=int, default=256) + parser.add_argument("--batch_size", type=int, default=256) + parser.add_argument("--update_epochs", type=int, default=4) + parser.add_argument("--gamma", type=float, default=0.99) + parser.add_argument("--gae_lambda", type=float, default=0.95) + parser.add_argument("--clip_coef", type=float, default=0.2) + parser.add_argument("--ent_coef", type=float, default=0.01) + parser.add_argument("--vf_coef", type=float, default=0.5) + parser.add_argument("--max_grad_norm", type=float, default=0.5) + parser.add_argument("--lr", type=float, default=2.5e-4) + parser.add_argument("--device", type=str, default="cpu") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--eval_interval", type=int, default=5000) + parser.add_argument("--eval_episodes", type=int, default=5) + parser.add_argument("--save_path", type=str, default="runs/sokoban_small_ppo.pt") + parser.add_argument("--sanity_rollout", action="store_true", help="Run a short rollout to validate parsing & action mapping, then exit") + + args = parser.parse_args() + + # Build Sokoban config strictly following defaults unless explicitly overridden + env_cfg = SokobanEnvConfig() + if args.dim_x is not None and args.dim_y is not None: + env_cfg.dim_room = (args.dim_x, args.dim_y) + if args.max_steps is not None: + env_cfg.max_steps = args.max_steps + if args.num_boxes is not None: + env_cfg.num_boxes = args.num_boxes + if args.search_depth is not None: + env_cfg.search_depth = args.search_depth + if args.render_mode is not None: + env_cfg.render_mode = args.render_mode + if args.observation_format is not None: + env_cfg.observation_format = args.observation_format + + # Enforce text + grid parsing, which matches LLM environment training by default + assert env_cfg.render_mode == "text", "Training expects text observations" + assert env_cfg.observation_format == "grid", "Training expects 'grid' observation format" + + device = torch.device(args.device) + + with all_seed(args.seed): + env = SokobanEnv(env_cfg) + # derive board shape from config + board_shape = env_cfg.dim_room + obs_text = env.reset() + + policy = SmallSokobanCNN(in_channels=len(SYMBOLS), num_actions=4).to(device) + optimizer = optim.Adam(policy.parameters(), lr=args.lr) + + if args.sanity_rollout: + print("[Sanity] Running 10 steps...") + obs = obs_text + for t in range(10): + obs_t = parse_grid_text(obs, board_shape).unsqueeze(0).to(device) + with torch.no_grad(): + logits, _ = policy(obs_t) + dist = Categorical(logits=logits) + a = dist.sample()[0].item() + obs, r, d, info = env.step(a + 1) + print(f"t={t} r={r} done={d} info={info}") + if d: + obs = env.reset() + return + + cfg = PPOConfig( + total_steps=args.total_steps, + rollout_steps=args.rollout_steps, + batch_size=args.batch_size, + update_epochs=args.update_epochs, + gamma=args.gamma, + gae_lambda=args.gae_lambda, + clip_coef=args.clip_coef, + ent_coef=args.ent_coef, + vf_coef=args.vf_coef, + max_grad_norm=args.max_grad_norm, + lr=args.lr, + device=args.device, + ) + + steps_done = 0 + last_eval = 0 + start_time = time.time() + + while steps_done < cfg.total_steps: + data = collect_rollout(env, policy, cfg, board_shape, device) + steps_done += cfg.rollout_steps + + stats = ppo_update(policy, optimizer, data, cfg) + + if steps_done - last_eval >= args.eval_interval: + with all_seed(args.seed + 123): + eval_env = SokobanEnv(env_cfg) + mean_ret, std_ret = evaluate(eval_env, policy, board_shape, device, episodes=args.eval_episodes) + last_eval = steps_done + elapsed = time.time() - start_time + print( + f"steps={steps_done} elapsed={elapsed:.1f}s loss={stats['loss']:.3f} " + f"pg={stats['pg_loss']:.3f} v={stats['v_loss']:.3f} ent={stats['entropy']:.3f} " + f"kl={stats['approx_kl']:.4f} clipfrac={stats['clipfrac']:.3f} eval_ret={mean_ret:.2f}±{std_ret:.2f}" + ) + # Save + os.makedirs(os.path.dirname(args.save_path), exist_ok=True) + torch.save({ + "model_state": policy.state_dict(), + "env_cfg": env_cfg.__dict__, + "steps": steps_done, + "seed": args.seed, + }, args.save_path) + + print(f"Training finished. Model saved to {args.save_path}") + + +if __name__ == "__main__": + main() diff --git a/scripts/visualize.py b/scripts/visualize.py new file mode 100644 index 0000000000000000000000000000000000000000..fddc2b90aba73e47ce3d8689dcddad796bb7853d --- /dev/null +++ b/scripts/visualize.py @@ -0,0 +1,692 @@ +#!/usr/bin/env python3 +""" +Local rollout visualizer. + +Usage: + python scripts/visualize.py --rollout_path results/ [--host 127.0.0.1] [--port 8000] + +The script launches a small HTTP server that lets you inspect .pkl files +(containing verl.DataProto dumps) inside the rollout path. Open the printed +URL in a browser to explore directories, select a file, and view its +meta information and non-tensor batches entry by entry. +""" + +from __future__ import annotations + +import argparse +import json +import logging +import threading +from functools import lru_cache +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Dict, List +from urllib.parse import parse_qs, urlparse +import webbrowser + +import numpy as np + +from verl import DataProto + +LOGGER = logging.getLogger(__name__) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Launch a local rollout visualizer") + parser.add_argument("--rollout_path", required=True, help="Directory containing rollout .pkl files") + parser.add_argument("--host", default="127.0.0.1", help="Host to bind (default: 127.0.0.1)") + parser.add_argument("--port", type=int, default=8000, help="Port to bind (default: 8000)") + parser.add_argument("--no-browser", action="store_true", help="Do not attempt to open a browser automatically") + return parser.parse_args() + + +def ensure_within(path: Path, root: Path) -> Path: + resolved = path.resolve() + try: + resolved.relative_to(root) + except ValueError as exc: + raise ValueError(f"Path {path} escapes the rollout root {root}") from exc + return resolved + + +def numpy_summary(array: np.ndarray) -> Dict[str, Any]: + array = np.asarray(array) + summary: Dict[str, Any] = { + "__type__": "ndarray", + "dtype": str(array.dtype), + "shape": list(array.shape), + "size": int(array.size), + } + preview_limit = 32 + flat = array.reshape(-1) + preview = flat[:preview_limit].tolist() + summary["preview"] = preview + summary["preview_count"] = len(preview) + if array.size <= preview_limit and array.size <= 10_000: + summary["values"] = array.tolist() + return summary + + +def serialize_for_view(value: Any, depth: int = 0) -> Any: + if depth > 6: + return repr(value) + + if value is None or isinstance(value, (str, int, float, bool)): + return value + + if isinstance(value, (np.integer, np.floating, np.bool_)): + return value.item() + + if isinstance(value, dict): + return {str(key): serialize_for_view(val, depth + 1) for key, val in value.items()} + + if isinstance(value, (list, tuple, set)): + return [serialize_for_view(val, depth + 1) for val in value] + + if isinstance(value, np.ndarray): + return numpy_summary(value) + + return repr(value) + + +def build_tree(root: Path) -> Dict[str, Any]: + root_node: Dict[str, Any] = {"name": root.name, "path": "", "type": "dir", "children": []} + nodes: Dict[str, Dict[str, Any]] = {"": root_node} + + for file_path in sorted(root.rglob("*.pkl")): + rel_path = file_path.relative_to(root) + rel_path_posix = rel_path.as_posix() + parts = rel_path.parts + if not parts: + continue + + cumulative = [] + for part in parts[:-1]: + cumulative.append(part) + current_key = "/".join(cumulative) + parent_key = "/".join(cumulative[:-1]) if len(cumulative) > 1 else "" + if current_key not in nodes: + node = {"name": part, "path": current_key, "type": "dir", "children": []} + nodes[current_key] = node + nodes[parent_key]["children"].append(node) + file_parent_key = "/".join(parts[:-1]) if len(parts) > 1 else "" + file_node = {"name": parts[-1], "path": rel_path_posix, "type": "file"} + nodes[file_parent_key]["children"].append(file_node) + + def sort_children(node: Dict[str, Any]) -> None: + children = node.get("children") + if not children: + return + children.sort(key=lambda item: (item.get("type") != "dir", item.get("name", ""))) + for child in children: + if child.get("type") == "dir": + sort_children(child) + + sort_children(root_node) + return root_node + + +def data_proto_to_payload(file_path: Path) -> Dict[str, Any]: + data = DataProto.load_from_disk(str(file_path)) + length = len(data) + items: List[Dict[str, Any]] = [] + for idx in range(length): + try: + item = data[idx] + except Exception as exc: # pragma: no cover - defensive guard + LOGGER.warning("Failed to read item %s from %s: %s", idx, file_path, exc) + continue + items.append( + { + "index": idx, + "meta_info": serialize_for_view(item.meta_info), + "non_tensor_batch": serialize_for_view(item.non_tensor_batch), + } + ) + + return { + "path": str(file_path), + "length": length, + "meta_info": serialize_for_view(data.meta_info), + "items": items, + } + + +class RolloutExplorer: + def __init__(self, root: Path): + self.root = root + self._tree_cache: Dict[str, Any] | None = None + self._lock = threading.Lock() + + def tree(self) -> Dict[str, Any]: + with self._lock: + if self._tree_cache is None: + self._tree_cache = build_tree(self.root) + return self._tree_cache + + @lru_cache(maxsize=32) + def load_file(self, relative_path: str) -> Dict[str, Any]: + normalized_path = Path(relative_path) + target = ensure_within(self.root / normalized_path, self.root) + if not target.exists() or not target.is_file(): + raise FileNotFoundError(f"File {relative_path} not found under {self.root}") + payload = data_proto_to_payload(target) + payload["relative_path"] = target.relative_to(self.root).as_posix() + return payload + + +HTML_PAGE = """ + + + + Rollout Visualizer + + + +
Rollout Visualizer
+
+ +
+
Select a file to inspect its rollout details.
+
+
+ + + +""" + + +class VisualizerHandler(BaseHTTPRequestHandler): + explorer: RolloutExplorer + + def do_GET(self) -> None: # noqa: N802 - http.server signature + parsed = urlparse(self.path) + if parsed.path == "/": + self.respond_html(HTML_PAGE) + return + if parsed.path == "/api/tree": + payload = VisualizerHandler.explorer.tree() + self.respond_json(payload) + return + if parsed.path == "/api/file": + query = parse_qs(parsed.query) + relative = query.get("path", [None])[0] + if not relative: + self.respond_json({"error": "Missing path query parameter"}, status=400) + return + try: + payload = VisualizerHandler.explorer.load_file(relative) + except FileNotFoundError: + self.respond_json({"error": "File not found"}, status=404) + return + except Exception as exc: # pragma: no cover - defensive guard + LOGGER.exception("Failed to load %s", relative) + self.respond_json({"error": str(exc)}, status=500) + return + self.respond_json(payload) + return + + self.respond_json({"error": "Not found"}, status=404) + + def log_message(self, format: str, *args: Any) -> None: # noqa: A003 - inherited name + LOGGER.info("%s - %s", self.address_string(), format % args) + + def respond_json(self, payload: Any, status: int = 200) -> None: + body = json.dumps(payload).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def respond_html(self, html: str, status: int = 200) -> None: + body = html.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +def main() -> None: + logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s") + args = parse_args() + root = Path(args.rollout_path).expanduser().resolve() + if not root.exists() or not root.is_dir(): + raise SystemExit(f"Rollout path {root} does not exist or is not a directory") + + explorer = RolloutExplorer(root) + VisualizerHandler.explorer = explorer + + server = ThreadingHTTPServer((args.host, args.port), VisualizerHandler) + + address = f"http://{args.host}:{args.port}/" + print(f"Serving rollout visualizer for {root} at {address}") + if not args.no_browser: + try: + webbrowser.open(address) + except Exception as exc: # pragma: no cover - best effort + LOGGER.info("Could not open browser automatically: %s", exc) + + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nShutting down...") + finally: + server.server_close() + + +if __name__ == "__main__": + main() diff --git a/tests/env/test_sokoban_render.py b/tests/env/test_sokoban_render.py new file mode 100644 index 0000000000000000000000000000000000000000..dcfa748fe92452f1e4f99a93bce8ecdc38975f19 --- /dev/null +++ b/tests/env/test_sokoban_render.py @@ -0,0 +1,41 @@ +import re + +from ragen.env.sokoban.config import SokobanEnvConfig +from ragen.env.sokoban.env import SokobanEnv + + +def test_sokoban_render_supports_grid_and_coord(): + seed = 1234 + grid_config = SokobanEnvConfig( + dim_room=(5, 5), + num_boxes=1, + max_steps=10, + search_depth=20, + observation_format="grid", + ) + coord_config = SokobanEnvConfig( + dim_room=(5, 5), + num_boxes=1, + max_steps=10, + search_depth=20, + observation_format="coord", + ) + + grid_env = SokobanEnv(grid_config) + coord_env = SokobanEnv(coord_config) + + try: + grid_obs = grid_env.reset(seed=seed) + coord_obs = coord_env.reset(seed=seed) + + assert isinstance(grid_obs, str) + assert isinstance(coord_obs, str) + + assert "Board size:" in coord_obs + assert re.search(r"Walls: \(\d+, \d+\)", coord_obs) + + assert isinstance(coord_env.render(mode="grid"), str) + assert "Board size:" in grid_env.render(mode="coord") + finally: + grid_env.close() + coord_env.close() diff --git a/tests/es_manager/test_seed_iteration.py b/tests/es_manager/test_seed_iteration.py new file mode 100644 index 0000000000000000000000000000000000000000..70d3350f67ccb88ade958a5154993a112163e51e --- /dev/null +++ b/tests/es_manager/test_seed_iteration.py @@ -0,0 +1,34 @@ +import pytest +from omegaconf import OmegaConf +from ragen.llm_agent.es_manager import EnvStateManager + + +def make_cfg(): + return OmegaConf.create({ + 'seed': {'train': 7}, + 'es_manager': { + 'train': { + 'env_groups': 1, + 'group_size': 1, + 'env_configs': {'tags': ['Bandit'], 'n_groups': [1]}, + } + }, + 'custom_envs': { + 'Bandit': { + 'env_type': 'bandit', + 'max_actions_per_traj': 1, + 'env_config': None + } + } + }) + + +def test_seed_iteration(): + cfg = make_cfg() + es = EnvStateManager(cfg, mode='train') + es.reset() + first_seed = es.envs[0]['status'].seed + es.reset() + second_seed = es.envs[0]['status'].seed + assert first_seed == 7 + assert second_seed == 8 diff --git a/tests/llm_agent/test_context_window.py b/tests/llm_agent/test_context_window.py new file mode 100644 index 0000000000000000000000000000000000000000..830143f4d5d74b288f6911a022f15beaaee3df8e --- /dev/null +++ b/tests/llm_agent/test_context_window.py @@ -0,0 +1,84 @@ +import pytest +from ragen.llm_agent.ctx_manager import ContextManager +from omegaconf import OmegaConf +from verl.verl.protocol import DataProto + +class DummyTokenizer: + name_or_path = "qwen" # or "llama-3" or any string your code expects + + def apply_chat_template(self, messages, add_generation_prompt, tokenize): + return " ".join([msg["content"] for msg in messages]) + + def __call__(self, texts, return_tensors, padding, padding_side, truncation): + import torch + class DummyOutput: + input_ids = torch.tensor([[1, 2, 3]]) + attention_mask = torch.tensor([[1, 1, 1]]) + return DummyOutput() + + def encode(self, text): + # Return a dummy list of token ids; must be at least length 1 for [0] indexing + return [42, 43] + +@pytest.fixture +def dummy_config(): + cfg = OmegaConf.create({ + "agent_proxy": { + "max_context_window": 2, + "enable_think": False, + "use_turn_scores": False, + "action_sep": "|", + "reward_normalization": { + "grouping": "batch", + "method": "identity" + } + }, + "enable_response_mask": False, + "es_manager": { + "train": { + "env_configs": { + "n_groups": [1], + "tags": ["sokoban"] + }, + "group_size": 1 + } + }, + "custom_envs": { + "sokoban": { + "env_type": "sokoban", + "max_actions_per_traj": 10 + } + }, + "actor_rollout_ref": { + "rollout": { + "response_length": 128 + } + } + }) + return cfg + +def test_context_window_truncation(dummy_config): + tokenizer = DummyTokenizer() + ctx = ContextManager(config=dummy_config, tokenizer=tokenizer, mode="train") + ctx.prefix_lookup = {0: "Initial prompt"} + ctx.env_config_lookup = {0: {"max_tokens": 128}} + ctx.env_nums = {"": 1} # For metrics + + env_outputs = [{ + "env_id": 0, + "group_id": 0, + "history": [ + {"state": "S1", "llm_response": "R1", "reward": 0.1, "actions_left": 5}, + {"state": "S2", "llm_response": "R2", "reward": 0.2, "actions_left": 4}, + {"state": "S3", "llm_response": "R3", "reward": 0.3, "actions_left": 3}, + ], + "metrics": {}, + }] + + lm_inputs: DataProto = ctx.get_lm_inputs(env_outputs, prepare_for_update=True) + messages = lm_inputs.non_tensor_batch["messages_list"][0] + + # Ensure only last 2 turns are present + assert "S1" not in str(messages) + assert "S2" in str(messages) + assert "S3" in str(messages) diff --git a/tests/test_rollout_filter.py b/tests/test_rollout_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..380beceac6f1dc6a2b168e1759d7c17e68b5cd2e --- /dev/null +++ b/tests/test_rollout_filter.py @@ -0,0 +1,137 @@ +import sys +import types + +import numpy as np +import torch +from tensordict import TensorDict + + +if "verl" not in sys.modules: + stub = types.ModuleType("verl") + + class DummyDataProto: + def __init__(self, batch=None, non_tensor_batch=None, meta_info=None): + self.batch = batch + self.non_tensor_batch = non_tensor_batch or {} + self.meta_info = meta_info or {} + + def union(self, other): + if other.batch is not None: + for key, value in other.batch.items(): + self.batch[key] = value + if other.non_tensor_batch: + self.non_tensor_batch.update(other.non_tensor_batch) + if other.meta_info: + self.meta_info.update(other.meta_info) + return self + + stub.DataProto = DummyDataProto + sys.modules["verl"] = stub + + +from ragen.trainer.rollout_filter import ( + RolloutFilterConfig, + RewardRolloutFilter, + EntropyRolloutFilter, +) + + +def _make_reward_batch(num_groups: int, group_size: int, traj_len: int): + total = num_groups * group_size + rm_scores = torch.arange(total * traj_len, dtype=torch.float32).reshape(total, traj_len) + loss_mask = torch.ones(total, traj_len) + batch = TensorDict( + { + "original_rm_scores": rm_scores, + "loss_mask": loss_mask, + }, + batch_size=[total], + ) + non_tensor_batch = {"uids": np.arange(total)} + return sys.modules["verl"].DataProto(batch=batch, non_tensor_batch=non_tensor_batch, meta_info={}) + + +def test_reward_variance_filter_reduces_batch_size(): + num_groups, group_size, traj_len = 4, 2, 3 + batch = _make_reward_batch(num_groups, group_size, traj_len) + + rollout_filter = RewardRolloutFilter( + RolloutFilterConfig( + ratio=0.5, + filter_type="largest", + num_groups=num_groups, + group_size=group_size, + ) + ) + + filtered_batch, metrics = rollout_filter.filter(batch) + + assert filtered_batch.batch["original_rm_scores"].shape[0] == group_size * max(int(0.5 * num_groups), 1) + assert "rollout/in_group_std" in metrics + + +def test_entropy_variance_filter_uses_compute_log_prob(): + num_groups, group_size, traj_len = 2, 3, 4 + batch = _make_reward_batch(num_groups, group_size, traj_len) + + entropies = torch.linspace(0.1, 1.0, steps=num_groups * group_size * traj_len).reshape(num_groups * group_size, traj_len) + old_log_probs = -entropies + + def fake_compute_log_prob(data_proto): + td = TensorDict( + { + "old_log_probs": old_log_probs, + "entropys": entropies, + }, + batch_size=[num_groups * group_size], + ) + return sys.modules["verl"].DataProto(batch=td, non_tensor_batch={}, meta_info={}) + + rollout_filter = EntropyRolloutFilter( + RolloutFilterConfig( + ratio=0.5, + filter_type="largest", + num_groups=num_groups, + group_size=group_size, + metric="entropy", + ), + compute_log_prob=fake_compute_log_prob, + ) + + filtered_batch, metrics = rollout_filter.filter(batch) + + expected = group_size * max(int(0.5 * num_groups), 1) + assert filtered_batch.batch["loss_mask"].shape[0] == expected + assert "old_log_probs" in filtered_batch.batch.keys() + assert "rollout/in_group_entropy_std" in metrics + + +def test_reward_metric_selects_high_mean_group(): + num_groups, group_size, traj_len = 2, 2, 1 + batch = _make_reward_batch(num_groups, group_size, traj_len) + + # Overwrite scores: first group has higher mean, second has higher variance. + batch.batch["original_rm_scores"] = torch.tensor( + [ + [10.0], + [11.0], + [0.0], + [5.0], + ] + ) + + rollout_filter = RewardRolloutFilter( + RolloutFilterConfig( + ratio=0.5, + filter_type="largest", + num_groups=num_groups, + group_size=group_size, + metric="reward", + ) + ) + + filtered_batch, _ = rollout_filter.filter(batch) + + # Highest mean group is the first one, so we expect its entries to remain. + retained = filtered_batch.batch["original_rm_scores"].squeeze(-1) + assert torch.allclose(retained, torch.tensor([10.0, 11.0])) diff --git a/verl/.gemini/config.yaml b/verl/.gemini/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..66015ad30ed6768e06dceb91f11004be8a74bb04 --- /dev/null +++ b/verl/.gemini/config.yaml @@ -0,0 +1,10 @@ +have_fun: false +code_review: + disable: false + comment_severity_threshold: HIGH + max_review_comments: -1 + pull_request_opened: + help: false + summary: false + code_review: true +ignore_patterns: [] diff --git a/verl/.github/CODEOWNERS b/verl/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..a44436d719126c6322ae4c495f74087359af5aa2 --- /dev/null +++ b/verl/.github/CODEOWNERS @@ -0,0 +1,30 @@ +/docs @eric-haibin-lin @zhaochenyang20 @hongpeng-guo +/docs/amd_tutorial @yushengsu-thu +/docs/slang_multiturn @zhaochenyang20 @SwordFaith +/docs/ascend_tutorial @FightingZhen + +/recipe/dapo @tongyx361 @PeterSH6 @vermouth1992 @tardis-key @FightingZhen @ji-huazhong +/recipe/spin @zhaochenyang20 +/recipe/sppo @zhaochenyang20 + +/third_party/sglang @zhaochenyang20 @SwordFaith +/third_party/vllm @PeterSH6 @wuxibin89 + +/examples/grpo_trainer @vermouth1992 @PeterSH6 @tardis-key @FightingZhen @ji-huazhong + +/verl/single_controller @zw0610 @wuxibin89 @hongpeng-guo +/verl/trainer @eric-haibin-lin @vermouth1992 @tongyx361 @PeterSH6 +/verl/models/mcore @ISEEKYAN @vermouth1992 +/verl/models/transformers @vermouth1992 @PeterSH6 @tardis-key @FightingZhen @ji-huazhong +/verl/workers/engine @eric-haibin-lin @vermouth1992 @ZihengJiang +/verl/workers/roles @eric-haibin-lin @vermouth1992 @ZihengJiang +/verl/workers/engine/fsdp @eric-haibin-lin @vermouth1992 @ZihengJiang +/verl/workers/rollout/vllm_rollout @wuxibin89 @PeterSH6 @chenhaiq +/verl/workers/rollout/sglang_rollout @zhaochenyang20 @SwordFaith @chenhaiq +/verl/workers/actor/megatron_actor.py @ISEEKYAN @vermouth1992 +/verl/workers/critic/megatron_critic.py @ISEEKYAN @vermouth1992 +/verl/workers/megatron_workers.py @ISEEKYAN @vermouth1992 + +/tests/single_controller @zw0610 @wuxibin89 +/tests/trainer @eric-haibin-lin @vermouth1992 @tongyx361 @PeterSH6 +/tests/workers/rollout/vllm_rollout @wuxibin89 @PeterSH6 @chenhaiq diff --git a/verl/.github/ISSUE_TEMPLATE/bug-report.yml b/verl/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000000000000000000000000000000000000..67341f4139d9a5348f3887242b7c6accf10abc7b --- /dev/null +++ b/verl/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,65 @@ +# modified from https://github.com/huggingface/transformers/blob/main/.github/ISSUE_TEMPLATE/bug-report.yml?plain=1 +name: "\U0001F41B Bug Report" +description: Submit a bug report to help us improve verl +labels: [ "bug" ] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! 🤗 + + - type: textarea + id: system-info + attributes: + label: System Info + description: Please share your system info with us. You can run the command `python scripts/diagnose.py` and copy-paste its output below. + placeholder: verl version, platform, python version, ... + validations: + required: true + + - type: checkboxes + id: information-scripts-examples + attributes: + label: Information + description: 'The problem arises when using:' + options: + - label: "The official example scripts" + - label: "My own modified scripts" + + - type: checkboxes + id: information-tasks + attributes: + label: Tasks + description: "The tasks I am working on are:" + options: + - label: "An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)" + - label: "My own task or dataset (give details below)" + + - type: textarea + id: reproduction + validations: + required: true + attributes: + label: Reproduction + description: | + Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet. + Please include relevant config information with your code. + If you have code snippets, error messages, stack traces please provide them here as well. + Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting + Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code. + + placeholder: | + Steps to reproduce the behavior: + + 1. + 2. + 3. + + + - type: textarea + id: expected-behavior + validations: + required: true + attributes: + label: Expected behavior + description: "A clear and concise description of what you would expect to happen." \ No newline at end of file diff --git a/verl/.github/ISSUE_TEMPLATE/config.yml b/verl/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..ac09e8636d7a7577999a55ffdf7095dd0b656e52 --- /dev/null +++ b/verl/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,2 @@ +blank_issues_enabled: true +version: 0.1 diff --git a/verl/.github/ISSUE_TEMPLATE/feature-request.yml b/verl/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 0000000000000000000000000000000000000000..18e0615b9ecd01bf1cead1155ff8124865e07d24 --- /dev/null +++ b/verl/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,32 @@ +# modified from https://github.com/huggingface/transformers/blob/main/.github/ISSUE_TEMPLATE/feature-request.yml?plain=1 +name: "\U0001F680 Feature request" +description: Submit a proposal/request for a new verl feature +labels: [ "Feature request" ] +body: + - type: textarea + id: feature-request + validations: + required: true + attributes: + label: Feature request + description: | + A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist. + + - type: textarea + id: motivation + validations: + required: true + attributes: + label: Motivation + description: | + Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too. + + + - type: textarea + id: contribution + validations: + required: true + attributes: + label: Your contribution + description: | + Is there any way that you could help, e.g. by submitting a PR? Make sure to read the CONTRIBUTING.MD [readme](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md) \ No newline at end of file diff --git a/verl/.github/PULL_REQUEST_TEMPLATE.md b/verl/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..4f092f174f01b08144069b5004b328e9562cb1a2 --- /dev/null +++ b/verl/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,40 @@ +### What does this PR do? + +> Add **concise** overview of what this PR aims to achieve or accomplish. Reference related GitHub issues and PRs that help with the review. + +### Checklist Before Starting + +- [ ] Search for similar PRs. Paste at least one query link here: ... +- [ ] Format the PR title as `[{modules}] {type}: {description}` (This will be checked by the CI) + - `{modules}` include `fsdp`, `megatron`, `sglang`, `vllm`, `rollout`, `trainer`, `ci`, `training_utils`, `recipe`, `hardware`, `deployment`, `ray`, `worker`, `single_controller`, `misc`, `perf`, `model`, `algo`, `env`, `tool`, `ckpt`, `doc`, `data` + - If this PR involves multiple modules, separate them with `,` like `[megatron, fsdp, doc]` + - `{type}` is in `feat`, `fix`, `refactor`, `chore`, `test` + - If this PR breaks any API (CLI arguments, config, function signature, etc.), add `[BREAKING]` to the beginning of the title. + - Example: `[BREAKING][fsdp, megatron] feat: dynamic batching` + +### Test + +> For changes that can not be tested by CI (e.g., algorithm implementation, new model support), validate by experiment(s) and show results like training curve plots, evaluation results, etc. + +### API and Usage Example + +> Demonstrate how the API changes if any, and provide usage example(s) if possible. + +```python +# Add code snippet or script demonstrating how to use this +``` + +### Design & Code Changes + +> Demonstrate the high-level design if this PR is complex, and list the specific changes. + +### Checklist Before Submitting + +> [!IMPORTANT] +> Please check all the following items before requesting a review, otherwise the reviewer might deprioritize this PR for review. + +- [ ] Read the [Contribute Guide](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md). +- [ ] Apply [pre-commit checks](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md#code-linting-and-formatting): `pre-commit install && pre-commit run --all-files --show-diff-on-failure --color=always` +- [ ] Add / Update [the documentation](https://github.com/volcengine/verl/tree/main/docs). +- [ ] Add unit or end-to-end test(s) to [the CI workflow](https://github.com/volcengine/verl/tree/main/.github/workflows) to cover all the code. If not feasible, explain why: ... +- [ ] Once your PR is ready for CI, send a message in [the `ci-request` channel](https://verl-project.slack.com/archives/C091TCESWB1) in [the `verl` Slack workspace](https://join.slack.com/t/verl-project/shared_invite/zt-3855yhg8g-CTkqXu~hKojPCmo7k_yXTQ). (If not accessible, please try [the Feishu group (飞书群)](https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=772jd4f1-cd91-441e-a820-498c6614126a).) diff --git a/verl/.github/dependabot.yml b/verl/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..24a3571c620c9c1e5ef7b4011851124c7a020626 --- /dev/null +++ b/verl/.github/dependabot.yml @@ -0,0 +1,9 @@ +## Enabled the dependabot to check the dependencies of the project +## Dependabot will open pull requests to update dependencies automatically + +version: 2 +updates: + - package-ecosystem: pip + directory: "/" + schedule: + interval: weekly \ No newline at end of file diff --git a/verl/.github/workflows/.deprecate/e2e_eval_aime24.yml b/verl/.github/workflows/.deprecate/e2e_eval_aime24.yml new file mode 100644 index 0000000000000000000000000000000000000000..e674fd10cbde674d94053e9ceecf0ca3eddfeb76 --- /dev/null +++ b/verl/.github/workflows/.deprecate/e2e_eval_aime24.yml @@ -0,0 +1,147 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +name: e2e_eval_aime24 + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!*.md" + - "!docker/**" + - "!docs/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + - "!recipe/**" + - "recipe/r1" + - "!recipe/r1/README.md" + pull_request: + branches: + - main + paths: + - "**/*.py" + # Other entrypoints + - "!*.md" + - "!docker/**" + - "!docs/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Home + - "recipe/r1" + - "!recipe/r1/README.md" + # Other recipes + - "!recipe/**" + # Entrypoints + - ".github/workflows/e2e_eval_aime24.yml" + - "tests/special_e2e/run_r1_distill_qwen_aime24_eval.sh" + - "verl/trainer/main_generation.py" + - "verl/trainer/config/generation.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_eval_aime24: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,gpu,math] + pip3 install math-verify transformers==4.56.2 + - name: Prepare aime24 dataset + run: | + ray stop --force + python3 recipe/r1/data_process.py --task aime2024 + - name: Running generation and evaluation in AIME 2024 + run: | + ray stop --force + bash tests/special_e2e/run_r1_distill_qwen_aime24_eval.sh + + cleanup: + runs-on: ubuntu-latest + needs: [setup, e2e_eval_aime24] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/.deprecate/e2e_ppo_trainer.yml b/verl/.github/workflows/.deprecate/e2e_ppo_trainer.yml new file mode 100644 index 0000000000000000000000000000000000000000..fa6fef0bd144b64cc02179aae4ea711f6e477c63 --- /dev/null +++ b/verl/.github/workflows/.deprecate/e2e_ppo_trainer.yml @@ -0,0 +1,133 @@ +name: e2e_ppo_trainer_deprecate + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - disabled_ci + pull_request: + branches: + - disabled_ci + paths: + - "**/*.py" + # Other entrypoints + - "!**/*.md" + - "!docker/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Docs + - "!docs/**" + # Recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Entrypoints + - ".github/workflows/e2e_ppo_trainer.yml" + - "examples/data_preprocess/gsm8k.py" + - "examples/data_preprocess/geo3k.py" + - "tests/special_e2e/ppo_trainer" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +jobs: + pre_commit_for_ppo: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.12"] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install the current repository + run: | + pip install -e . + - name: Set ruff --output-format=github + run: | + sed -i 's/--output-format=full/--output-format=github/' .pre-commit-config.yaml + git add .pre-commit-config.yaml + - uses: pre-commit/action@v3.0.1 + with: + extra_args: "" # Overriding default "--all-files" + + e2e_ppo_trainer_sglang_multiturn_with_tool: + runs-on: [L20x8] + needs: pre_commit_for_ppo + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + container: + image: verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2 + options: --gpus all --shm-size=10g + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test,gpu,sglang] + - name: Prepare gsm8k dataset with tool + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k_multiturn_w_tool.py --local_save_dir $HOME/data/gsm8k_verl_sgl_multi_turn_preprocessed + - name: Running GSM8K with tool E2E training tests on 8 L20 GPUs with rmpad using function rm and save ckpt with sglang + run: | + ray stop --force + bash tests/special_e2e/run_gsm8k_fsdp_sgl_multiturn_w_tool.sh + - name: Running GSM8K with tool E2E training tests with FSDP2 + run: | + ray stop --force + FSDP_STRATEGY=fsdp2 bash tests/special_e2e/run_gsm8k_fsdp_sgl_multiturn_w_tool.sh + + e2e_ppo_trainer_sglang_vlm_multiturn_with_tool: + runs-on: [L20x8] + needs: pre_commit_for_ppo + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + container: + image: verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2 + options: --gpus all --shm-size=10g + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test,geo,gpu,sglang] + - name: Prepare geo3k dataset with tool + run: | + ray stop --force + python3 examples/data_preprocess/geo3k_multiturn_w_tool.py --local_dir $HOME/data/geo3k_verl_sgl_multi_turn_preprocessed + - name: Running GEO3K with tool E2E training tests on 8 L20 GPUs with rmpad using function rm and save ckpt with sglang + run: | + ray stop --force + bash tests/special_e2e/run_geo3k_fsdp_sgl_multiturn_w_tool.sh + - name: Running GEO3K with tool E2E training tests with FSDP2 + run: | + ray stop --force + FSDP_STRATEGY=fsdp2 bash tests/special_e2e/run_geo3k_fsdp_sgl_multiturn_w_tool.sh diff --git a/verl/.github/workflows/.deprecate/e2e_ppo_trainer_megatron_sglang.yml b/verl/.github/workflows/.deprecate/e2e_ppo_trainer_megatron_sglang.yml new file mode 100644 index 0000000000000000000000000000000000000000..30c22d9948226055e255b9c4a71d3fa9bec07c74 --- /dev/null +++ b/verl/.github/workflows/.deprecate/e2e_ppo_trainer_megatron_sglang.yml @@ -0,0 +1,155 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: e2e_ppo_trainer_megatron_sglang_deprecate + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch. + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - disabled_ci + pull_request: + branches: + - disabled_ci + paths: + - "**/*.py" + # Other entrypoints + - "!docker/**" + # Docs + - "!**/*.md" + - "!docs/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Entrypoints + - ".github/workflows/e2e_ppo_trainer_megatron_sglang.yml" + - "examples/data_preprocess/gsm8k.py" + - "examples/data_preprocess/geo3k.py" + - "tests/special_e2e/run_ppo_trainer_megatron.sh" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_megatron_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_ppo_trainer_megatron-qwen3: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen3) with validation and saving + run: | + ray stop --force + ENGINE=sglang ALL_OFFLOAD=True VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 MODEL_ID=Qwen/Qwen3-0.6B bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen3) testing learning rate scheduler + run: | + ray stop --force + ENGINE=sglang LR_WARMUP_STEPS=1 TOTAL_TRAIN_STEPS=2 MODEL_ID=Qwen/Qwen3-0.6B bash tests/special_e2e/run_ppo_trainer_megatron.sh + + - name: Test Megatron checkpoints merging function (Qwen3 Actor and Critic) + run: | + exp_name="qwen3-0.6b-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --tie-word-embedding --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints/verl-test/${exp_name}/global_step_1/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/critic/huggingface + - name: clean up + run: | + rm -rf checkpoints + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_ppo_trainer_megatron-deepseek, + e2e_ppo_trainer_megatron-qwen3, + e2e_ppo_trainer_megatron-different-train-infer-tp-qwen-tie-embedding, + e2e_ppo_trainer_megatron-qwen-override-transformer-config, + e2e_ppo_trainer_megatron-deepseek-override-transformer-config, + e2e_ppo_trainer_megatron-moe-expert-parallel, + e2e_ppo_trainer_megatron-qwen2_5vl-3b, + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/.deprecate/e2e_prime.yml b/verl/.github/workflows/.deprecate/e2e_prime.yml new file mode 100644 index 0000000000000000000000000000000000000000..694591b9c6c810d4b61e48767ccb6e7d791fa369 --- /dev/null +++ b/verl/.github/workflows/.deprecate/e2e_prime.yml @@ -0,0 +1,66 @@ +name: e2e_prime_deprecate + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - disabled_ci + pull_request: + branches: + - disabled_ci + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Home + - "recipe/prime" + # Entrypoints + - ".github/workflows/e2e_prime.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_prime.sh" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +jobs: + e2e_prime: + runs-on: [L20x8] + timeout-minutes: 50 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + container: + image: whatcanyousee/verl:ngc-cu124-vllm0.8.5-sglang0.4.6.post5-mcore0.12.0-te2.3 + options: --gpus all --shm-size=10g + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,gpu] + - name: Prepare gsm8k dataset + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k.py + - name: Running GSM8K E2E with prime alg + run: | + ray stop --force + bash tests/special_e2e/run_prime.sh diff --git a/verl/.github/workflows/.deprecate/e2e_spin.yml b/verl/.github/workflows/.deprecate/e2e_spin.yml new file mode 100644 index 0000000000000000000000000000000000000000..b3c8a85e070168ac4d0cc5d3df6ce8c7d2754c06 --- /dev/null +++ b/verl/.github/workflows/.deprecate/e2e_spin.yml @@ -0,0 +1,119 @@ +name: e2e_spin + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Home + - "recipe/spin" + # Entrypoints + - ".github/workflows/e2e_spin.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_spin.sh" + - "!examples" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Home + - "recipe/spin" + # Entrypoints + - ".github/workflows/e2e_spin.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_spin.sh" + - "!examples" + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_spin: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test,gpu,sglang] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running the E2E test with the spin algorithm + run: | + ray stop --force + bash tests/special_e2e/run_spin.sh + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_spin + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/.deprecate/e2e_sppo.yml b/verl/.github/workflows/.deprecate/e2e_sppo.yml new file mode 100644 index 0000000000000000000000000000000000000000..0dddd849cb0df51f394db60aa27eec65dced1e8e --- /dev/null +++ b/verl/.github/workflows/.deprecate/e2e_sppo.yml @@ -0,0 +1,118 @@ +name: e2e_sppo + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Home + - "recipe/sppo" + # Entrypoints + - ".github/workflows/e2e_sppo.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_sppo.sh" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Home + - "recipe/sppo" + # Entrypoints + - ".github/workflows/e2e_sppo.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_sppo.sh" + +# Declare permissions just read content. +permissions: + contents: read + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + TRANSFORMERS_VERSION: "4.56.2" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_sppo: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test,gpu,sglang] + - name: Prepare MATH dataset + run: | + python3 examples/data_preprocess/math_dataset.py --local_dataset_path $HOME/models/hf_data/DigitalLearningGmbH/MATH-lighteval + - name: Running the E2E test with the SPPO algorithm + run: | + ray stop --force + bash tests/special_e2e/run_sppo.sh + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_sppo + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/README.md b/verl/.github/workflows/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aab56302a3000a36353cd8a0fcacdcb254ab7508 --- /dev/null +++ b/verl/.github/workflows/README.md @@ -0,0 +1,73 @@ +### Adding a New Workflow + +When adding a new workflow for continuous integration (CI), you have two runner options: a fixed runner or a machine from the vemlp. + +- **Fixed Runner**: To use a fixed runner, specify it in your workflow using the `runs-on` keyword, like `runs-on: [L20x8]`. +- **Vemlp Runner**: Opting for a Vemlp machine allows you to launch tasks elastically. + +Here is a template to assist you. This template is designed for using Vemlp machines. Currently, for each workflow, you need to create a `setup` and a `cleanup` job. When using this template, the main parts you need to modify are the `IMAGE` environment variable and the specific `job steps`. + +```yaml +name: Your Default Workflow + +on: + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + - ".github/workflows/template.yml" + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +permissions: + contents: read + +env: + IMAGE: "your vemlp image" # e.g. "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.4-vllm0.8.5-mcore0.12.2" + DYNAMIC_RUNNER_URL: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" # public veFaas api + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + task-id: ${{ steps.create-runner.outputs.task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_URL }}" + image: "${{ env.DEFAULT_IMAGE }}" + + your_job: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'default-runner' }}"] + steps: + xxxx # your jobs + + cleanup: + runs-on: ubuntu-latest + needs: [setup, your_job] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_URL }}" + task-id: "${{ needs.setup.outputs.task-id }}" +``` + +### Model and Dataset +To avoid CI relies on network, we pre-download dataset on a NFS on the CI machine. The path for models are \${HOME}/models and the path for dataset is \${HOME}/models/hf_data. \ No newline at end of file diff --git a/verl/.github/workflows/check-pr-title.yml b/verl/.github/workflows/check-pr-title.yml new file mode 100644 index 0000000000000000000000000000000000000000..948ce5e3f01498ce4f569230cdb2dd384fc0cbfd --- /dev/null +++ b/verl/.github/workflows/check-pr-title.yml @@ -0,0 +1,58 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +on: + pull_request: + types: [opened, edited, synchronize] + +jobs: + check-title: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.11' + + - name: Run PR title checker + run: python3 tests/special_sanity/check_pr_title.py + env: + PR_TITLE: ${{ github.event.pull_request.title }} + + - name: Run PR description checker + run: python3 tests/special_sanity/check_pr_description.py + env: + PR_TITLE: ${{ github.event.pull_request.title }} + GITHUB_EVENT_PATH: ${{ github.event_path }} diff --git a/verl/.github/workflows/checkpoint_converter.yml b/verl/.github/workflows/checkpoint_converter.yml new file mode 100644 index 0000000000000000000000000000000000000000..014d06fd4bd8bd1cc15c9e279fa1eb78c37f9bcc --- /dev/null +++ b/verl/.github/workflows/checkpoint_converter.yml @@ -0,0 +1,175 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: checkpoint_converter +# latest version: Megatron-LM core_r0.11.0 https://github.com/NVIDIA/Megatron-LM/tree/core_r0.11.0 + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Entrypoints + - ".github/workflows/checkpoint_converter.yml" + - ".github/workflows/e2e_ppo_trainer_megatron.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_ppo_trainer_megatron.sh" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_megatron_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + checkpoint_converter: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 20 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test] +# - name: Download Model to Use +# run: | +# huggingface-cli download Qwen/Qwen2.5-0.5B --local-dir ${HOME}/models/Qwen/Qwen2.5-0.5B +# huggingface-cli download deepseek-ai/deepseek-coder-1.3b-instruct --local-dir ${HOME}/models/deepseek-ai/deepseek-coder-1.3b-instruct +# export HF_HUB_OFFLINE=1 + - name: Running Huggingface to Megatron dist_ckpt converter (Qwen/Qwen2.5-0.5B) + run: | + ray stop --force + python scripts/converter_hf_to_mcore.py --hf_model_path=${HOME}/models/Qwen/Qwen2.5-0.5B --output_path checkpoints/Qwen/Qwen2.5-0.5B --test + - name: Running Huggingface to Megatron dist_ckpt converter (deepseek-ai/deepseek-coder-1.3b-instruct) + run: | + ray stop --force + python scripts/converter_hf_to_mcore.py --hf_model_path=${HOME}/models/deepseek-ai/deepseek-coder-1.3b-instruct --output_path checkpoints/deepseek-ai/deepseek-coder-1.3b-instruct --test + - name: Clean up + run: | + rm -rf checkpoints + + checkpoint_converter_large_moe_models: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 30 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + HF_ENDPOINT: "https://hf-mirror.com" + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test] +# - name: Download Model to Use +# run: | +# huggingface-cli download Qwen/Qwen1.5-MoE-A2.7B-Chat --local-dir ${HOME}/models/Qwen/Qwen1.5-MoE-A2.7B-Chat +# export HF_HUB_OFFLINE=1 + - name: Running Huggingface to Megatron dist_ckpt CPU converter (Qwen/Qwen1.5-MoE-A2.7B-Chat) + run: | + ray stop --force + python scripts/converter_hf_to_mcore.py --hf_model_path=${HOME}/models/Qwen/Qwen1.5-MoE-A2.7B-Chat --output_path checkpoints/Qwen/Qwen1.5-MoE-A2.7B-Chat --use_cpu_initialization + - name: Running distributed Huggingface to Megatron dist_ckpt CPU converter (Qwen/Qwen1.5-MoE-A2.7B-Chat) + run: | + ray stop --force + torchrun --nproc_per_node 8 --nnodes 1 scripts/converter_hf_to_mcore.py --hf_model_path=${HOME}/models/Qwen/Qwen1.5-MoE-A2.7B-Chat --output_path checkpoints/Qwen/Qwen1.5-MoE-A2.7B-Chat_dist --use_cpu_initialization + - name: clean up + run: | + rm -rf checkpoints + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + checkpoint_converter, + checkpoint_converter_large_moe_models + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/cpu_unit_tests.yml b/verl/.github/workflows/cpu_unit_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..afa61b851924e1c72ab10b20788e6be146579a3e --- /dev/null +++ b/verl/.github/workflows/cpu_unit_tests.yml @@ -0,0 +1,89 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +name: cpu_unit_tests + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + - .github/workflows/cpu_unit_tests.yml + - "!recipe/**/*.py" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +jobs: + cpu_unit_tests: + if: github.repository_owner == 'volcengine' + runs-on: [L20x8] + timeout-minutes: 20 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + container: + image: verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip install -e .[test,prime,geo] + pip install --upgrade "ray>=2.40.0" pillow + - name: Download datasets + run: | + huggingface-cli download verl-team/gsm8k-v0.4.1 --repo-type dataset --local-dir ~/verl-data/gsm8k + python3 examples/data_preprocess/geo3k.py + - name: Running CPU unit tests + run: | + echo '[pytest]' > pytest.ini + echo 'python_files = *_on_cpu.py' >> pytest.ini + pytest -s -x --asyncio-mode=auto tests/ \ No newline at end of file diff --git a/verl/.github/workflows/doc.yml b/verl/.github/workflows/doc.yml new file mode 100644 index 0000000000000000000000000000000000000000..f006b737c10292471068f9d0e83781e9e9ae1370 --- /dev/null +++ b/verl/.github/workflows/doc.yml @@ -0,0 +1,100 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +name: doc_test + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + - "docs/**" + - .github/workflows/doc.yml + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read # for checkout + pages: write # for deploy-pages + id-token: write # for deploy-pages + +jobs: + doc_test: + runs-on: ubuntu-latest + timeout-minutes: 5 # Increase this timeout value as needed + strategy: + matrix: + python-version: ["3.10"] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install the current repository + run: | + pip install -e .[test] --no-deps + pip install -r docs/requirements-docs.txt + + - name: Run doc make html + run: | + cd docs + make clean + make html SPHINXOPTS="--keep-going -w _build/sphinx.log" + if grep -q ": ERROR:" _build/sphinx.log; then + echo "🚨 Sphinx doc build contained ERRORs - see _build/sphinx.log" + exit 1 + fi + if grep -q "WARNING: document isn't included in any toctree" _build/sphinx.log; then + echo "🚨 Sphinx doc build contained WARNING. Please include newly added docs in index.rst. See _build/sphinx.log for details" + exit 1 + fi + if grep -q "WARNING: Inline emphasis" _build/sphinx.log; then + echo "🚨 Sphinx doc build contained WARNING. Please check inline emphasis is correct. See _build/sphinx.log for details" + exit 1 + fi + if grep -q "WARNING: Definition list ends without a blank line" _build/sphinx.log; then + echo "🚨 Sphinx doc build contained WARNING. Please check if the indentation is correct. See _build/sphinx.log for details" + exit 1 + fi diff --git a/verl/.github/workflows/e2e_ascend.yml b/verl/.github/workflows/e2e_ascend.yml new file mode 100644 index 0000000000000000000000000000000000000000..9a67533040edcd84b142af8b1306429097a978f3 --- /dev/null +++ b/verl/.github/workflows/e2e_ascend.yml @@ -0,0 +1,156 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +name: e2e_ascend + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + paths: + - ".github/workflows/e2e_ascend.yml" + - "**/*.py" + - "docs/ascend_tutorial/**" + - "examples/**" + - "recipe/**" + - "tests/special_npu/**" + - "tests/special_sanity/**" + - "verl/**" + - "pyproject.toml" + - "requirements-npu.txt" + - "setup.py" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +permissions: + contents: read + +jobs: + test: + if: github.repository_owner == 'volcengine' + name: verl Ascend test (self-host) + runs-on: [self-hosted, npu-0] + timeout-minutes: 40 # Increase this timeout value as needed + container: + image: crispig/verl_npu:cann8.1rc1-py3.10-torch2.5.1-vllm-ascend0.7.3.post1-mindspeed0121-250731 + volumes: + - /usr/local/dcmi:/usr/local/dcmi + - /usr/local/bin/npu-smi:/usr/local/bin/npu-smi + - /usr/local/Ascend/driver/lib64/:/usr/local/Ascend/driver/lib64/ + - /usr/local/Ascend/driver/version.info:/usr/local/Ascend/driver/version.info + - /etc/ascend_install.info:/etc/ascend_install.info + - /data00/dataset:/github/home/dataset + - /data00/models:/github/home/models + # Use self-host cache speed up pip and model download + # - /home/action/actions-runner/_work/cache:/github/home/.cache/ + options: >- + --device /dev/davinci0 + --device /dev/davinci_manager + --device /dev/devmm_svm + --device /dev/hisi_hdc + --network host + --privileged + --shm-size 16g + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - name: Check npu and CANN info + run: | + cat /usr/local/Ascend/ascend-toolkit/latest/"$(uname -i)"-linux/ascend_toolkit_install.info + npu-smi info + - name: Checkout volcengine/verl repo + uses: actions/checkout@v4 + - name: Install the current repository + run: | + pip3 install hf_transfer peft + pip3 install -r requirements-npu.txt + pip install -e . + - name: Install torchvision + run: | + pip install torchvision==0.20.1+cpu --index-url https://download.pytorch.org/whl/cpu + - name: Uninstall Triton + run: | + pip uninstall -y triton + - name: Preprocess gsm8k dataset + run: | + python examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/dataset/openai/gsm8k + - name: Preprocess geo3k dataset + run: | + python examples/data_preprocess/geo3k.py --local_dataset_path ${HOME}/dataset/hiyouga/geometry3k + - name: Running gsm8k e2e qwen3 training tests with PPO on ASCEND NPU + run: | + ray stop --force + bash tests/special_npu/run_qwen3_06b_ppo.sh + rm -rf $HOME/ckpts + - name: Running gsm8k e2e training tests with peft sft on ASCEND NPU + run: | + ray stop --force + bash tests/special_npu/run_qwen2_5_05b_sft_peft_sp2.sh + rm -rf $HOME/ckpts + - name: Running gsm8k e2e training tests with GRPO on ASCEND NPU + run: | + ray stop --force + bash tests/special_npu/run_qwen2_5_05b_grpo.sh + rm -rf $HOME/ckpts + - name: Running geo3k e2e training tests with GRPO on ASCEND NPU + run: | + ray stop --force + bash tests/special_npu/run_qwen2_5_vl_3b_npu.sh + rm -rf $HOME/ckpts + - name: Running gsm8k e2e training tests with DAPO on ASCEND NPU + run: | + ray stop --force + bash tests/special_npu/run_qwen2_5_05b_dapo.sh + rm -rf $HOME/ckpts + - name: Running gsm8k e2e training tests with GRPO MindSpeed on ASCEND NPU + run: | + ray stop --force + USE_DIST_CKPT=True bash tests/special_npu/run_qwen2_5_05b_grpo_mindspeed.sh + rm -rf $HOME/dist_ckpt/qwen2_5_05b_grpo_mindspeed + rm -rf $HOME/ckpts + - name: Running NPU profiling unit tests + run: | + ray stop --force + pytest -s -x tests/utils/test_special_mstx_profile.py \ No newline at end of file diff --git a/verl/.github/workflows/e2e_dapo.yml b/verl/.github/workflows/e2e_dapo.yml new file mode 100644 index 0000000000000000000000000000000000000000..0c1e8e3478dc37646e114288e37dc55a656cffd8 --- /dev/null +++ b/verl/.github/workflows/e2e_dapo.yml @@ -0,0 +1,145 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +name: e2e_dapo + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "verl/*.py" + # Other entrypoints + - "!examples/*trainer*" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Megatron + - "!verl/workers/**/megatron_*.py" + - "!recipe/**" + - "recipe/dapo" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Home + - "recipe/dapo" + # Entrypoints + - ".github/workflows/e2e_dapo.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_dapo.sh" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_dapo: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,gpu] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running the E2E test with the DAPO algorithm + run: | + ray stop --force + bash tests/special_e2e/run_dapo.sh + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_dapo + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/e2e_genrm_remote.yml b/verl/.github/workflows/e2e_genrm_remote.yml new file mode 100644 index 0000000000000000000000000000000000000000..48544bbe5bafb7301d669d4b8aa4438242c1deda --- /dev/null +++ b/verl/.github/workflows/e2e_genrm_remote.yml @@ -0,0 +1,138 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +name: e2e_genrm_remote + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + - "tests/**" + - "!recipe/**" + - "recipe/genrm_remote" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Home + - "recipe/genrm_remote" + - "!recipe/genrm_remote/README.md" + # Entrypoints + - ".github/workflows/e2e_genrm_remote.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_genrm_remote.sh" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_genrm_remote: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,gpu] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running the E2E test with the Generative Reward Model + run: | + ray stop --force + bash tests/special_e2e/run_genrm_remote.sh + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_genrm_remote + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/e2e_one_step_off_policy.yml b/verl/.github/workflows/e2e_one_step_off_policy.yml new file mode 100644 index 0000000000000000000000000000000000000000..025a86f0b36428dd9f03ed3cabb62173d2b629bc --- /dev/null +++ b/verl/.github/workflows/e2e_one_step_off_policy.yml @@ -0,0 +1,178 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + + +name: e2e_one_step_off_policy + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + - "!**/*.md" + - "!**/*.sh" + # Other entrypoints + - "!examples/*trainer*" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + - "!recipe/**" + - "recipe/one_step_off_policy" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + - "!**/*.md" + - "!**/*.sh" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Other recipes + - "!recipe/**" + # Home + - "recipe/one_step_off_policy" + # Entrypoints + - ".github/workflows/e2e_one_step_off_policy.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/run_one_step_off_policy.sh" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + TRANSFORMERS_VERSION: "4.56.2" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + # Test FSDP2 strategy + e2e_one_step_off_policy_fsdp2: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 10 # Increase timeout for async training + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + ACTOR_STRATEGY: "fsdp2" + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,gpu] + pip3 install transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running the E2E test with one_step_off_policy algorithm (FSDP2) + run: | + ray stop --force + bash tests/special_e2e/run_one_step_off_policy.sh + + # Test Megatron strategy + e2e_one_step_off_policy_megatron: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 10 # Increase timeout for async training + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + ACTOR_STRATEGY: "megatron" + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,gpu] + pip3 install transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running the E2E test with one_step_off_policy algorithm (Megatron) + run: | + ray stop --force + bash tests/special_e2e/run_one_step_off_policy.sh + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_one_step_off_policy_fsdp2, + e2e_one_step_off_policy_megatron + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/e2e_ppo_trainer.yml b/verl/.github/workflows/e2e_ppo_trainer.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a7b062cf606b612e05922e23ca55a896311115b --- /dev/null +++ b/verl/.github/workflows/e2e_ppo_trainer.yml @@ -0,0 +1,79 @@ +name: e2e_ppo_trainer + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!**/*.md" + - "!docker/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Docs + - "!docs/**" + # Recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Entrypoints + - ".github/workflows/e2e_ppo_trainer.yml" + - "examples/data_preprocess/gsm8k.py" + - "examples/data_preprocess/geo3k.py" + - "tests/special_e2e/ppo_trainer" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +jobs: + pre_commit_for_ppo: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.12"] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install the current repository + run: | + pip install -e . + - name: Set ruff --output-format=github + run: | + sed -i 's/--output-format=full/--output-format=github/' .pre-commit-config.yaml + git add .pre-commit-config.yaml + - uses: pre-commit/action@v3.0.1 + with: + extra_args: "" # Overriding default "--all-files" + diff --git a/verl/.github/workflows/e2e_ppo_trainer_megatron_sglang.yml b/verl/.github/workflows/e2e_ppo_trainer_megatron_sglang.yml new file mode 100644 index 0000000000000000000000000000000000000000..cf7b2599d42235657875fe9a592b3bafd3e67a35 --- /dev/null +++ b/verl/.github/workflows/e2e_ppo_trainer_megatron_sglang.yml @@ -0,0 +1,281 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: e2e_ppo_trainer_megatron_sglang + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch. + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!docker/**" + # Docs + - "!**/*.md" + - "!docs/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Entrypoints + - "verl/worksers/rollout/sglang_rollout/*" + - ".github/workflows/e2e_ppo_trainer_megatron_sglang.yml" + - "examples/data_preprocess/gsm8k.py" + - "examples/data_preprocess/geo3k.py" + - "tests/special_e2e/run_ppo_trainer_megatron.sh" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_megatron_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_ppo_trainer_megatron-deepseek: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (DeepSeek) + run: | + ray stop --force + OPTIM_MEMORY_EFFICIENT=True ENGINE=sglang SAVE_FREQ=1 MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (DeepSeek) + run: | + ray stop --force + export VLLM_USE_V1=1 + ray start --head + ENGINE=sglang MODE=async RESUME_MODE=auto MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct TOTAL_TRAIN_STEPS=2 bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Test Megatron checkpoints merging function (DeepSeek Actor and Critic) + run: | + exp_name="deepseek-coder-1.3b-instruct-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints/verl-test/${exp_name}/global_step_1/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/critic/huggingface + - name: Profiling GRPO GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Deepseek) + run: | + ray stop --force + PROFILE_ENABLE=True ENGINE=sglang ADV_ESTIMATOR=grpo USE_DYNAMIC_BSZ=False MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct bash tests/special_e2e/run_ppo_trainer_megatron.sh + if [ -z "$( ls -A '/tmp/ray/session_latest/logs/nsight/' )" ]; then + echo "[ERROR] not found any profiling files" + exit 1 + else + echo "[SUCCESS] profile success" + fi + - name: clean up + run: | + rm -rf checkpoints + + e2e_ppo_trainer_megatron-different-train-infer-tp-qwen-tie-embedding: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with tie-embedding Megatron (Qwen) with train tp > infer tp + run: | + ray stop --force + ENGINE=sglang VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 TRAIN_TP=2 INFER_TP=1 MODEL_ID=Qwen/Qwen2.5-1.5B bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen) with train tp < infer tp + run: | + ray stop --force + ENGINE=sglang VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 TRAIN_TP=1 INFER_TP=2 MODEL_ID=Qwen/Qwen2.5-1.5B bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: clean up + run: | + rm -rf checkpoints + + e2e_ppo_trainer_megatron-qwen-override-transformer-config: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k +# - name: Download Model to Use +# run: | +# huggingface-cli download Qwen/Qwen2.5-0.5B --local-dir ${HOME}/models/Qwen/Qwen2.5-0.5B +# export HF_HUB_OFFLINE=1 + - name: Prepare dist_ckpt of Qwen2.5-0.5B, uneven layer distribution only supports dist_ckpt + run: | + python3 scripts/converter_hf_to_mcore.py --hf_model_path ${HOME}/models/Qwen/Qwen2.5-0.5B --output_path checkpoints/verl-test/qwen2.5-0.5b-megatron + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen) + run: | + ray stop --force + ENGINE=sglang SAVE_FREQ=1 COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 SKIP_SAVE_HF_MODEL=1 bash tests/special_e2e/run_ppo_trainer_megatron.sh +actor_rollout_ref.actor.megatron.override_transformer_config.num_layers_in_first_pipeline_stage=8 +actor_rollout_ref.actor.megatron.override_transformer_config.num_layers_in_last_pipeline_stage=4 actor_rollout_ref.actor.megatron.use_dist_checkpointing=true actor_rollout_ref.actor.megatron.dist_checkpointing_path=checkpoints/verl-test/qwen2.5-0.5b-megatron actor_rollout_ref.ref.megatron.use_dist_checkpointing=true actor_rollout_ref.ref.megatron.dist_checkpointing_path=checkpoints/verl-test/qwen2.5-0.5b-megatron critic.megatron.use_dist_checkpointing=true critic.megatron.dist_checkpointing_path=checkpoints/verl-test/qwen2.5-0.5b-megatron reward_model.megatron.use_dist_checkpointing=true reward_model.megatron.dist_checkpointing_path=checkpoints/verl-test/qwen2.5-0.5b-megatron + cp -r checkpoints checkpoints-dut + ENGINE=sglang SAVE_FREQ=1 COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Test Megatron checkpoints merging function (Qwen Actor and Critic) + run: | + exp_name="qwen2.5-0.5b-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --tie-word-embedding --local_dir checkpoints-dut/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints-dut/verl-test/${exp_name}/global_step_1/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/critic/huggingface + - name: clean up + run: | + rm -rf checkpoints + + e2e_ppo_trainer_megatron-deepseek-override-transformer-config: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (DeepSeek) + run: | + ray stop --force + ENGINE=sglang SAVE_FREQ=1 MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct COMMON_PP=2 COMMON_VPP=null bash tests/special_e2e/run_ppo_trainer_megatron.sh +actor_rollout_ref.actor.megatron.override_transformer_config.account_for_embedding_in_pipeline_split=true +actor_rollout_ref.actor.megatron.override_transformer_config.account_for_loss_in_pipeline_split=true + - name: Test Megatron checkpoints merging function (DeepSeek Actor and Critic) + run: | + exp_name="deepseek-coder-1.3b-instruct-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints/verl-test/${exp_name}/global_step_1/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/critic/huggingface + - name: clean up + run: | + rm -rf checkpoints + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_ppo_trainer_megatron-deepseek, + e2e_ppo_trainer_megatron-different-train-infer-tp-qwen-tie-embedding, + e2e_ppo_trainer_megatron-qwen-override-transformer-config, + e2e_ppo_trainer_megatron-deepseek-override-transformer-config, + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/e2e_ppo_trainer_megatron_sglang_2.yml b/verl/.github/workflows/e2e_ppo_trainer_megatron_sglang_2.yml new file mode 100644 index 0000000000000000000000000000000000000000..7c4cba92c1d19cf7af5780cd8bf63187dec0f1a8 --- /dev/null +++ b/verl/.github/workflows/e2e_ppo_trainer_megatron_sglang_2.yml @@ -0,0 +1,275 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: e2e_ppo_trainer_megatron_sglang_2 + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch. + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!docker/**" + # Docs + - "!**/*.md" + - "!docs/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Entrypoints + - "verl/worksers/rollout/sglang_rollout/*" + - ".github/workflows/e2e_ppo_trainer_megatron_sglang.yml" + - "examples/data_preprocess/gsm8k.py" + - "examples/data_preprocess/geo3k.py" + - "tests/special_e2e/run_ppo_trainer_megatron.sh" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_megatron_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_ppo_trainer_megatron-moe-expert-parallel: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (DeepSeek) + run: | + ray stop --force + MEGATRON_CI_DISABLE_EXPANDABLE_SEGMENTS=1 \ + ADV_ESTIMATOR=grpo USE_DUMMY_MODEL=True DUMMY_MODEL_CONFIG_PATH=tests/special_e2e/ppo_trainer/expert_parallel/qwen2moe_minimal.json \ + PPO_MAX_TOKEN_LEN=512 FWD_MAX_TOKEN_LEN=512 \ + MAX_PROMPT_LENGTH=256 MAX_RESPONSE_LENGTH=256 \ + MODEL_ID=Qwen/Qwen1.5-MoE-A2.7B-Chat \ + ENGINE=sglang COMMON_PP=2 COMMON_VPP=null COMMON_CP=1 COMMON_TP=4 COMMON_EP=4 COMMON_ETP=1 INFER_TP=8 \ + USE_DIST_CKPT=True ALL_OFFLOAD=True SKIP_SAVE_HF_MODEL=1 bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: clean up + run: | + rm -rf checkpoints + + e2e_ppo_trainer_megatron-qwen2_5vl-3b: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + - name: Prepare Geo3k dataset + run: | + python3 examples/data_preprocess/geo3k.py --local_dataset_path ${HOME}/models/hf_data/hiyouga/geometry3k/ + - name: Prepare dist_ckpt of Qwen2.5-VL-3B, only supports dist_ckpt + run: | + python3 scripts/converter_hf_to_mcore.py --hf_model_path ${HOME}/models/Qwen/Qwen2.5-VL-3B-Instruct --output_path checkpoints/verl-test/qwen2.5-vl-3b-megatron + - name: Running Geo3k E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen) + run: | + ray stop --force + ENGINE=sglang TRAIN_FILES=${HOME}/data/geo3k/train.parquet VAL_FILES=${HOME}/data/geo3k/test.parquet MAX_PROMPT_LENGTH=1024 MAX_RESPONSE_LENGTH=2048 MODEL_ID=Qwen/Qwen2.5-VL-3B-Instruct ADV_ESTIMATOR=grpo USE_DYNAMIC_BSZ=False SKIP_SAVE_HF_MODEL=1 COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 COMMON_TP=2 USE_DIST_CKPT=true DIST_CKPT_PATH=checkpoints/verl-test/qwen2.5-vl-3b-megatron bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: clean up + run: | + rm -rf checkpoints + + e2e_ppo_trainer_sglang: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test,gpu,sglang] + - name: Prepare gsm8k dataset + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm and save ckpt + run: | + ray stop --force + ENGINE=sglang bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E training tests on sglang async + run: | + ray stop --force + TOTAL_TRAIN_STEPS=2 ENGINE=sglang ROLLOUT_MODE=async bash tests/special_e2e/ppo_trainer/run_function_reward.sh + + e2e_ppo_trainer_sglang_vlm: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test,geo,gpu,sglang] --no-deps + # Geo3k + - name: Prepare GEO3K dataset + run: | + ray stop --force + python3 examples/data_preprocess/geo3k.py --local_dataset_path ${HOME}/models/hf_data/hiyouga/geometry3k/ + - name: Running GEO3K VLM E2E training tests on 8 L20 GPUs with rmpad using function rm + run: | + ray stop --force + TRAIN_FILES=$HOME/data/geo3k/train.parquet VAL_FILES=$HOME/data/geo3k/test.parquet \ + MAX_PROMPT_LEN=1536 MAX_RESPONSE_LEN=1536 \ + MODEL_ID=Qwen/Qwen2-VL-2B-Instruct \ + ADV_ESTIMATOR=grpo RM_PAD=True USE_KL=True ENABLE_CHUNKED_PREFILL=False \ + ENGINE=sglang GPU_MEMORY_UTILIZATION=0.6 ACTOR_FSDP_PARAM_OFFLOAD=True \ + ACTOR_FSDP_OPTIMIZER_OFFLOAD=True REF_FSDP_PARAM_OFFLOAD=True \ + bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GEO3K VLM E2E with rmpad using torch fused kernel (Qwen2.5-VL) + run: | + ray stop --force + FUSED_KERNELS=True TRAIN_FILES=$HOME/data/geo3k/train.parquet VAL_FILES=$HOME/data/geo3k/test.parquet \ + MAX_PROMPT_LEN=1536 MAX_RESPONSE_LEN=1536 \ + MODEL_ID=Qwen/Qwen2.5-VL-3B-Instruct \ + ADV_ESTIMATOR=grpo RM_PAD=True USE_KL=True ENABLE_CHUNKED_PREFILL=False \ + ENGINE=sglang GPU_MEMORY_UTILIZATION=0.6 ACTOR_FSDP_PARAM_OFFLOAD=True \ + ACTOR_FSDP_OPTIMIZER_OFFLOAD=True REF_FSDP_PARAM_OFFLOAD=True \ + bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GEO3K VLM E2E with rmpad using triton fused kernel (Qwen2.5-VL) + run: | + ray stop --force + FUSED_KERNELS=True FUSED_KERNEL_BACKEND=triton \ + TRAIN_FILES=$HOME/data/geo3k/train.parquet VAL_FILES=$HOME/data/geo3k/test.parquet \ + MAX_PROMPT_LEN=1536 MAX_RESPONSE_LEN=1536 \ + MODEL_ID=Qwen/Qwen2.5-VL-3B-Instruct \ + ADV_ESTIMATOR=grpo RM_PAD=True USE_KL=True ENABLE_CHUNKED_PREFILL=False \ + ENGINE=sglang GPU_MEMORY_UTILIZATION=0.6 ACTOR_FSDP_PARAM_OFFLOAD=True \ + ACTOR_FSDP_OPTIMIZER_OFFLOAD=True REF_FSDP_PARAM_OFFLOAD=True \ + bash tests/special_e2e/ppo_trainer/run_function_reward.sh + + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_ppo_trainer_megatron-moe-expert-parallel, + e2e_ppo_trainer_megatron-qwen2_5vl-3b, + e2e_ppo_trainer_sglang, + e2e_ppo_trainer_sglang_vlm + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/e2e_ppo_trainer_megatron_vllm.yml b/verl/.github/workflows/e2e_ppo_trainer_megatron_vllm.yml new file mode 100644 index 0000000000000000000000000000000000000000..b2966e795c3476f64d44c9bd71bfbb15d1837603 --- /dev/null +++ b/verl/.github/workflows/e2e_ppo_trainer_megatron_vllm.yml @@ -0,0 +1,292 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: e2e_ppo_trainer_megatron_vllm + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch. + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!docker/**" + # Docs + - "!**/*.md" + - "!docs/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Entrypoints + - ".github/workflows/e2e_ppo_trainer_megatron_vllm.yml" + - "examples/data_preprocess/gsm8k.py" + - "examples/data_preprocess/geo3k.py" + - "tests/special_e2e/run_ppo_trainer_megatron.sh" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_megatron_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + TRANSFORMERS_VERSION: "4.56.2" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_ppo_trainer_megatron-deepseek: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install math-verify transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron, use mbridge e2e to pre-load and save (Deepseek) + run: | + ray stop --force + ALL_OFFLOAD=True SAVE_FREQ=1 MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 USE_MBRIDGE=True USE_DIST_CKPT=False \ + bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron, use mbridge e2e to pre-load and save (Deepseek) + run: | + ray stop --force + RESUME_MODE=auto MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct TOTAL_TRAIN_STEPS=2 SAVE_FREQ=1 COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 USE_MBRIDGE=True USE_DIST_CKPT=False \ + bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (DeepSeek) + run: | + ray stop --force + export VLLM_USE_V1=1 + ray start --head + MODE=async USE_FUSED_KERNELS=True MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct TOTAL_TRAIN_STEPS=2 SAVE_FREQ=2 bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Test Megatron checkpoints merging function (DeepSeek Actor and Critic) + run: | + exp_name="deepseek-coder-1.3b-instruct-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --local_dir checkpoints/verl-test/${exp_name}/global_step_2/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_2/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints/verl-test/${exp_name}/global_step_2/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_2/critic/huggingface + - name: Test Megatron distributed checkpoints merging function (DeepSeek) + run: | + exp_name="deepseek-coder-1.3b-instruct-megatron-gsm8k-minimal" + torchrun --nproc_per_node 4 --nnodes 1 -m verl.model_merger merge --backend megatron --local_dir checkpoints/verl-test/${exp_name}/global_step_2/actor --target_dir checkpoints/verl-test/${exp_name}/global_step_2/actor/hf_model + - name: Running GRPO GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Deepseek) + run: | + ray stop --force + ADV_ESTIMATOR=grpo USE_DYNAMIC_BSZ=False MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: clean up + run: | + rm -rf checkpoints + e2e_ppo_trainer_megatron-qwen3: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install math-verify transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen3) with validation and saving + run: | + ray stop --force + ALL_OFFLOAD=True VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 MODEL_ID=Qwen/Qwen3-0.6B bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen3) testing learning rate scheduler + run: | + ray stop --force + LR_WARMUP_STEPS=1 TOTAL_TRAIN_STEPS=2 MODEL_ID=Qwen/Qwen3-0.6B bash tests/special_e2e/run_ppo_trainer_megatron.sh + + - name: Test Megatron checkpoints merging function (Qwen3 Actor and Critic) + run: | + exp_name="qwen3-0.6b-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --tie-word-embedding --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints/verl-test/${exp_name}/global_step_1/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/critic/huggingface + - name: clean up + run: | + rm -rf checkpoints + e2e_ppo_trainer_megatron-different-train-infer-tp-qwen-tie-embedding: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install math-verify transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with tie-embedding Megatron (Qwen) with train tp > infer tp + run: | + ray stop --force + VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 TRAIN_TP=2 INFER_TP=1 MODEL_ID=Qwen/Qwen2.5-1.5B bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen) with train tp < infer tp + run: | + ray stop --force + VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 TRAIN_TP=1 INFER_TP=2 ALL_OFFLOAD=True MODEL_ID=Qwen/Qwen2.5-1.5B bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: clean up + run: | + rm -rf checkpoints + e2e_ppo_trainer_megatron-qwen-override-transformer-config: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install math-verify transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k +# - name: Download Model to Use +# run: | +# huggingface-cli download Qwen/Qwen2.5-0.5B --local-dir ${HOME}/models/Qwen/Qwen2.5-0.5B +# export HF_HUB_OFFLINE=1 + - name: Prepare dist_ckpt of Qwen2.5-0.5B, uneven layer distribution only supports dist_ckpt + run: | + python3 scripts/converter_hf_to_mcore.py --hf_model_path ${HOME}/models/Qwen/Qwen2.5-0.5B --output_path checkpoints/verl-test/qwen2.5-0.5b-megatron + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen) + run: | + ray stop --force + SAVE_FREQ=1 COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 SKIP_SAVE_HF_MODEL=1 USE_DIST_CKPT=True DIST_CKPT_PATH=checkpoints/verl-test/qwen2.5-0.5b-megatron \ + bash tests/special_e2e/run_ppo_trainer_megatron.sh +actor_rollout_ref.actor.megatron.override_transformer_config.num_layers_in_first_pipeline_stage=8 +actor_rollout_ref.actor.megatron.override_transformer_config.num_layers_in_last_pipeline_stage=4 + cp -r checkpoints checkpoints-dut + SAVE_FREQ=1 COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: Test Megatron checkpoints merging function (Qwen Actor and Critic) + run: | + exp_name="qwen2.5-0.5b-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --tie-word-embedding --local_dir checkpoints-dut/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints-dut/verl-test/${exp_name}/global_step_1/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/critic/huggingface + - name: clean up + run: | + rm -rf checkpoints + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_ppo_trainer_megatron-deepseek, + e2e_ppo_trainer_megatron-qwen3, + e2e_ppo_trainer_megatron-different-train-infer-tp-qwen-tie-embedding, + e2e_ppo_trainer_megatron-qwen-override-transformer-config, + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/e2e_ppo_trainer_megatron_vllm_2.yml b/verl/.github/workflows/e2e_ppo_trainer_megatron_vllm_2.yml new file mode 100644 index 0000000000000000000000000000000000000000..3183210de1f9f50164379ace6f1b9a256586b84d --- /dev/null +++ b/verl/.github/workflows/e2e_ppo_trainer_megatron_vllm_2.yml @@ -0,0 +1,420 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: e2e_ppo_trainer_megatron_vllm_2 + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch. + # For push, for now only anti-patterns are specified so it is more conservative + # and achieves higher coverage. + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!docker/**" + # Docs + - "!**/*.md" + - "!docs/**" + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Entrypoints + - ".github/workflows/e2e_ppo_trainer_megatron_vllm.yml" + - "examples/data_preprocess/gsm8k.py" + - "examples/data_preprocess/geo3k.py" + - "tests/special_e2e/run_ppo_trainer_megatron.sh" + - "verl/trainer/main_ppo.py" + - "verl/trainer/config/ppo_megatron_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + TRANSFORMERS_VERSION: "4.56.2" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + e2e_ppo_trainer_megatron-deepseek-override-transformer-config: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (DeepSeek) + run: | + ray stop --force + SAVE_FREQ=1 MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct COMMON_PP=2 COMMON_VPP=null bash tests/special_e2e/run_ppo_trainer_megatron.sh +actor_rollout_ref.actor.megatron.override_transformer_config.account_for_embedding_in_pipeline_split=true +actor_rollout_ref.actor.megatron.override_transformer_config.account_for_loss_in_pipeline_split=true + - name: Test Megatron checkpoints merging function (DeepSeek Actor and Critic) + run: | + exp_name="deepseek-coder-1.3b-instruct-megatron-gsm8k-minimal" + python -m verl.model_merger test --backend megatron --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + python -m verl.model_merger test --backend megatron --is-value-model --local_dir checkpoints/verl-test/${exp_name}/global_step_1/critic --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/critic/huggingface + - name: clean up + run: | + rm -rf checkpoints + e2e_ppo_trainer_megatron-moe-expert-parallel: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install mbridge + pip3 install transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (DeepSeek) + run: | + ray stop --force + ADV_ESTIMATOR=grpo USE_DUMMY_MODEL=True DUMMY_MODEL_CONFIG_PATH=tests/special_e2e/ppo_trainer/expert_parallel/qwen2moe_minimal.json \ + PPO_MAX_TOKEN_LEN=512 FWD_MAX_TOKEN_LEN=512 \ + MAX_PROMPT_LENGTH=256 MAX_RESPONSE_LENGTH=256 \ + MODEL_ID=Qwen/Qwen1.5-MoE-A2.7B-Chat USE_MBRIDGE=True \ + COMMON_PP=2 COMMON_VPP=null COMMON_CP=1 COMMON_TP=4 COMMON_EP=4 COMMON_ETP=1 INFER_TP=8 \ + USE_DIST_CKPT=True ALL_OFFLOAD=True SKIP_SAVE_HF_MODEL=1 bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: clean up + run: | + rm -rf checkpoints + e2e_ppo_trainer_megatron-qwen2_5vl-3b: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install transformers==$TRANSFORMERS_VERSION + - name: Prepare Geo3k dataset + run: | + python3 examples/data_preprocess/geo3k.py --local_dataset_path ${HOME}/models/hf_data/hiyouga/geometry3k/ + - name: Prepare dist_ckpt of Qwen2.5-VL-3B, only supports dist_ckpt + run: | + python3 scripts/converter_hf_to_mcore.py --hf_model_path ${HOME}/models/Qwen/Qwen2.5-VL-3B-Instruct --output_path checkpoints/verl-test/qwen2.5-vl-3b-megatron + - name: Running Geo3k E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen) + run: | + ray stop --force + TRAIN_FILES=${HOME}/data/geo3k/train.parquet VAL_FILES=${HOME}/data/geo3k/test.parquet \ + MAX_PROMPT_LENGTH=1024 MAX_RESPONSE_LENGTH=2048 MODEL_ID=Qwen/Qwen2.5-VL-3B-Instruct ADV_ESTIMATOR=grpo \ + USE_DYNAMIC_BSZ=False USE_FUSED_KERNELS=True SKIP_SAVE_HF_MODEL=1 \ + COMMON_PP=4 COMMON_VPP=null COMMON_CP=1 COMMON_TP=2 USE_DIST_CKPT=true \ + DIST_CKPT_PATH=checkpoints/verl-test/qwen2.5-vl-3b-megatron bash tests/special_e2e/run_ppo_trainer_megatron.sh + - name: clean up + run: | + rm -rf checkpoints + e2e_ppo_trainer_vllm: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,vllm] + pip3 install transformers==$TRANSFORMERS_VERSION + - name: Prepare GSM8K dataset + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + # HF sanity +# - name: Running GSM8K E2E training tests on 1 L20 GPU with hf for sanity +# run: | +# ray stop --force +# bash tests/special_e2e/ppo_trainer/run_single_gpu.sh +# # HF sanity +# - name: Running GSM8K E2E training tests on 1 L20 GPU with engine interface for sanity. +# run: | +# ray stop --force +# bash tests/special_e2e/ppo_trainer/run_single_gpu_with_engine.sh + # Function RM + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm with validation and saving (FSDP_SIZE=8) + run: | + ray stop --force + VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 SAVE_HF_MODEL=True VERL_EXP_NAME="qwen2.5-0.5b-function-reward-minimal-fsdp-size8" bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm after resuming + run: | + ray stop --force + RESUME_MODE=auto VERL_EXP_NAME="qwen2.5-0.5b-function-reward-minimal-fsdp-size8" bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Test merging FSDP checkpoints (Qwen Actor) + run: | + exp_name="qwen2.5-0.5b-function-reward-minimal-fsdp-size8" + python -m verl.model_merger test --backend fsdp --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm with validation and saving (DDP_SIZE=2, FSDP_SIZE=4) + run: | + ray stop --force + VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 SAVE_HF_MODEL=True FSDP_SIZE=4 VERL_EXP_NAME="qwen2.5-0.5b-function-reward-minimal-ddp-size2-fsdp-size4" bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Test merging DDP+FSDP checkpoints (Qwen Actor) + run: | + exp_name="qwen2.5-0.5b-function-reward-minimal-ddp-size2-fsdp-size4" + python -m verl.model_merger test --backend fsdp --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm with validation and saving (FSDP2) + run: | + ray stop --force + VAL_BEFORE_TRAIN=True TEST_FREQ=1 SAVE_FREQ=1 SAVE_HF_MODEL=True VERL_EXP_NAME="qwen2.5-0.5b-function-reward-minimal-fsdp2-size8" STRATEGY=fsdp2 bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Test merging FSDP2 checkpoints (Qwen Actor) + run: | + exp_name="qwen2.5-0.5b-function-reward-minimal-fsdp2-size8" + python -m verl.model_merger test --backend fsdp --local_dir checkpoints/verl-test/${exp_name}/global_step_1/actor --test_hf_dir checkpoints/verl-test/${exp_name}/global_step_1/actor/huggingface + - name: Running GSM8K E2E without rmpad using function rm + run: | + ray stop --force + RM_PAD=False bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm (GRPO) + run: | + ray stop --force + ADV_ESTIMATOR=grpo USE_KL=True bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm (ReMax) + run: | + ray stop --force + ADV_ESTIMATOR=remax USE_KL=True bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using customized reward function + run: | + ray stop --force + CUSTOM_REWARD_FN=True bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm with in-reward kl and kl loss + run: | + ray stop --force + USE_KL=True bash tests/special_e2e/ppo_trainer/run_function_reward.sh + # LoRA tests + - name: Running GSM8K E2E training tests on 8 L20 GPUs with grpo lora using function rm with use_shm + run: | + ray stop --force + ADV_ESTIMATOR=grpo USE_SHM=True LORA_RANK=32 LOAD_FORMAT=safetensors bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with grpo lora using function rm with use_shm and layered_summon + run: | + ray stop --force + ADV_ESTIMATOR=grpo USE_SHM=True LORA_RANK=32 LOAD_FORMAT=safetensors LAYERED_SUMMON=True TOTAL_TRAIN_STEPS=1 SAVE_FREQ=1 FSDP_SIZE=4 VERL_EXP_NAME="qwen2.5-0.5b-function-reward-minimal" bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Test GRPO LoRA checkpoints merging function + run: | + export EXP_NAME="qwen2.5-0.5b-function-reward-minimal" + ls checkpoints/verl-test/${EXP_NAME}/global_step_1/actor + cat checkpoints/verl-test/${EXP_NAME}/global_step_1/actor/huggingface/config.json + python3 -m verl.model_merger merge --backend fsdp --local_dir checkpoints/verl-test/${EXP_NAME}/global_step_1/actor/ --target_dir checkpoints/verl-test/${EXP_NAME}/global_step_1/actor/huggingface + - name: Running GSM8K E2E training tests on 8 L20 GPUs with grpo lora using function rm with use_shm and layered_summon with fsdp2 + run: | + ray stop --force + ADV_ESTIMATOR=grpo USE_SHM=True LORA_RANK=32 LOAD_FORMAT=safetensors LAYERED_SUMMON=True STRATEGY=fsdp2 bash tests/special_e2e/ppo_trainer/run_function_reward.sh + # Model RM + - name: Running GRPO GSM8K E2E training tests with FSDP on 8 L20 GPUs (DeepSeek) + run: | + ray stop --force + MODEL_ID=deepseek-ai/deepseek-coder-1.3b-instruct bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GSM8K E2E with rmpad using model rm + run: | + ray stop --force + bash tests/special_e2e/ppo_trainer/run_model_reward.sh + - name: Running GSM8K E2E without rmpad using model rm + run: | + ray stop --force + RM_PAD=False bash tests/special_e2e/ppo_trainer/run_model_reward.sh + - name: Running GSM8K E2E with rmpad using model rm and ulysses sp=2 + run: | + ray stop --force + SP_SIZE=2 bash tests/special_e2e/ppo_trainer/run_model_reward.sh + - name: Running GSM8K E2E with rmpad using model rm and dynamic batch size + run: | + ray stop --force + SEQ_BALANCE=True bash tests/special_e2e/ppo_trainer/run_model_reward.sh + - name: Running GSM8K E2E with rmpad using model rm with Liger Kernel enabled + run: | + ray stop --force + LIGER=True bash tests/special_e2e/ppo_trainer/run_model_reward.sh + - name: Running GSM8K E2E with rmpad using model rm with Fused Kernel enabled + run: | + ray stop --force + FUSED_KERNELS=True bash tests/special_e2e/ppo_trainer/run_model_reward.sh + - name: Running GSM8K E2E with rmpad using model rm with Fused Kernel enabled + run: | + ray stop --force + FUSED_KERNEL=True FUSED_KERNEL_BACKEND=triton bash tests/special_e2e/ppo_trainer/run_model_reward.sh + - name: Running GSM8K E2E training tests on vllm async + run: | + ray stop --force + export VLLM_USE_V1=1 + ray start --head + TOTAL_TRAIN_STEPS=2 ENGINE=vllm ROLLOUT_MODE=async bash tests/special_e2e/ppo_trainer/run_function_reward.sh + + e2e_ppo_trainer_vllm_vlm: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 40 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test,gpu,vllm,geo,trl] + pip3 install transformers==$TRANSFORMERS_VERSION + # Geo3k + - name: Prepare GEO3K dataset + run: | + python3 examples/data_preprocess/geo3k.py --local_dataset_path ${HOME}/models/hf_data/hiyouga/geometry3k/ + - name: Running GEO3K VLM GRPO E2E training tests on 8 L20 GPUs with rmpad using function rm + run: | + ray stop --force + TRAIN_FILES=$HOME/data/geo3k/train.parquet VAL_FILES=$HOME/data/geo3k/test.parquet \ + MAX_PROMPT_LEN=1536 MAX_RESPONSE_LEN=1536 \ + MODEL_ID=Qwen/Qwen2-VL-2B-Instruct \ + ADV_ESTIMATOR=grpo RM_PAD=True USE_KL=True ENABLE_CHUNKED_PREFILL=False \ + SP_SIZE=2 \ + bash tests/special_e2e/ppo_trainer/run_function_reward.sh + + - name: Running GEO3K VLM PPO E2E training tests on 8 L20 GPUs with rmpad using function rm + run: | + ray stop --force + TRAIN_FILES=$HOME/data/geo3k/train.parquet VAL_FILES=$HOME/data/geo3k/test.parquet \ + MAX_PROMPT_LEN=1536 MAX_RESPONSE_LEN=1536 \ + MODEL_ID=Qwen/Qwen2-VL-2B-Instruct \ + ADV_ESTIMATOR=gae RM_PAD=True USE_KL=True ENABLE_CHUNKED_PREFILL=False \ + SP_SIZE=2 \ + bash tests/special_e2e/ppo_trainer/run_function_reward.sh + - name: Running GEO3K VLM GRPO E2E lora training tests on 8 L20 GPUs with rmpad using function rm + run: | + ray stop --force + TRAIN_FILES=$HOME/data/geo3k/train.parquet VAL_FILES=$HOME/data/geo3k/test.parquet \ + MAX_PROMPT_LEN=1536 MAX_RESPONSE_LEN=1536 \ + MODEL_ID=Qwen/Qwen2-VL-2B-Instruct \ + ADV_ESTIMATOR=grpo RM_PAD=True USE_KL=True ENABLE_CHUNKED_PREFILL=False \ + SP_SIZE=2 \ + LORA_RANK=32 LORA_EXCLUDE=".*visual.*" \ + bash tests/special_e2e/ppo_trainer/run_function_reward.sh + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + e2e_ppo_trainer_megatron-deepseek-override-transformer-config, + e2e_ppo_trainer_megatron-moe-expert-parallel, + e2e_ppo_trainer_megatron-qwen2_5vl-3b, + e2e_ppo_trainer_vllm, + e2e_ppo_trainer_vllm_vlm + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/e2e_sft.yml b/verl/.github/workflows/e2e_sft.yml new file mode 100644 index 0000000000000000000000000000000000000000..75153d06c25772ecc6d57b165e5d539e76a3d3d3 --- /dev/null +++ b/verl/.github/workflows/e2e_sft.yml @@ -0,0 +1,161 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: e2e_sft + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # Megatron + - "!verl/workers/**/megatron_*.py" + # Entrypoints + - ".github/workflows/e2e_sft.yml" + - "examples/data_preprocess/gsm8k.py" + - "tests/special_e2e/sft" + - "verl/trainer/fsdp_sft_trainer.py" + - "verl/trainer/config/sft_trainer.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + e2e_sft: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 25 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install peft + pip3 install --no-deps -e .[test,gpu] + - name: Prepare gsm8k dataset + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests on 8 L20 GPUs with rmpad using function rm + run: | + ray stop --force + bash tests/special_e2e/sft/run_sft.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs w/o rmpad using function rm + run: | + ray stop --force + RM_PAD=False bash tests/special_e2e/sft/run_sft.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with sequence parallism + run: | + ray stop --force + SP_SIZE=2 bash tests/special_e2e/sft/run_sft.sh + - name: Check loss difference between sequence parallel vs. default implementation + run: | + ray stop --force + ENTRYPOINT="tests/special_e2e/sft/test_sp_loss_match.py" SP_SIZE=2 bash tests/special_e2e/sft/run_sft.sh + - name: Running GSM8K E2E training tests on 8 L20 GPUs with sequence parallism and liger + run: | + ray stop --force + SP_SIZE=2 LIGER=True bash tests/special_e2e/sft/run_sft.sh + - name: Running GSM8K E2E training tests with LoRA + run: | + ray stop --force + LORA_RANK=32 bash tests/special_e2e/sft/run_sft.sh + - name: Run GSM8K E2E training and resume tests resuming from the checkpoint manager + run: | + ray stop --force + LORA_RANK=32 RESUME_MODE=auto TOTAL_TRAIN_STEP=2 bash tests/special_e2e/sft/run_sft.sh + # TODO: multiturn + - name: Prepare gsm8k dataset + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k_multiturn_sft.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Running GSM8K E2E training tests with multiturn and various configs and compare results + run: | + bash tests/special_e2e/sft/test_sft_engine_all.sh + + + cleanup: + runs-on: ubuntu-latest + needs: [setup, e2e_sft] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" diff --git a/verl/.github/workflows/gpu_unit_tests.yml b/verl/.github/workflows/gpu_unit_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..bd800c58a36fdbd61e79f5cf953bf5b636720a26 --- /dev/null +++ b/verl/.github/workflows/gpu_unit_tests.yml @@ -0,0 +1,113 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: GPU unit tests + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.4.x + paths: + - "**/*.py" + - .github/workflows/gpu_unit_tests.yml + pull_request: + branches: + - main + - v0.4.x + paths: + # The order that you define paths patterns matters: + # A matching negative pattern (prefixed with !) after a positive match will exclude the path. + # A matching positive pattern after a negative match will include the path again. + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + - "!recipe/**" + # Entrypoints + - .github/workflows/gpu_unit_tests.yml + - "tests/**test_*.py" + # Ignore CPU tests + - "!tests/*_on_cpu.py" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +jobs: + gpu_unit_tests: + if: github.repository_owner == 'volcengine' + runs-on: [L20x8] + timeout-minutes: 60 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1" + HF_HUB_ENABLE_HF_TRANSFER: 1 + container: + image: verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2 + options: --gpus all --shm-size=10g + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install hf_transfer + pip3 install --no-deps -e .[test] + pip3 install --upgrade "ray>=2.40.0" + pip3 install cupy-cuda12x + - name: Download Model to Use + run: | + huggingface-cli download Qwen/Qwen2.5-0.5B-Instruct + huggingface-cli download Qwen/Qwen2.5-1.5B-Instruct + export HF_HUB_OFFLINE=1 + # Disable requests to avoid network errors + - name: Run all GPU unit tests + run: | + pytest -s -x --ignore-glob="*test_special_*.py" --ignore-glob='*on_cpu.py' --ignore-glob="*test_vllm*" --ignore-glob="*_sglang*" --ignore-glob="*_hf_rollout*" --ignore-glob="tests/models/" --ignore-glob='tests/special*' --ignore-glob="tests/experimental" --ignore-glob="tests/workers/reward_model" tests/ + - name: Testing LinearCrossEntropyTP Correctness, Computation Time and Memory Consumption + run: | + LOW_MEMORY=True torchrun --standalone --nnodes=1 --nproc-per-node=8 tests/utils/test_special_linear_cross_entropy_tp.py + - name: Testing FSDP2 actor functionality + run: | + torchrun --standalone --nnodes=1 --nproc-per-node=2 tests/workers/actor/test_special_dp_actor.py + - name: Testing FSDP2 critic functionality + run: | + torchrun --standalone --nnodes=1 --nproc-per-node=2 tests/workers/critic/test_special_dp_critic.py diff --git a/verl/.github/workflows/model.yml b/verl/.github/workflows/model.yml new file mode 100644 index 0000000000000000000000000000000000000000..54856b8d914dbe5aa3d087ebc057d89ac384c84b --- /dev/null +++ b/verl/.github/workflows/model.yml @@ -0,0 +1,230 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. +# name: Check PR Title + +name: model + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "verl/**/*.py" + # Entrypoints + - ".github/workflows/model.yml" + - "tests/special_distributed/test_fsdp_ckpt.py" + - "tests/special_distributed/test_mcore_config_converter.py" + - "tests/special_distributed/test_tensor_dict.py" + - "tests/models/**" + - "tests/special_distributed/run_all.sh" + +# Declare permissions just read content. +permissions: + contents: read + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + model_rmpad: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 20 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository and upgrade to latest transformers(4.54.0)/flash_attn, transformers 4.55.0 has strange behavior with model backward + run: | + pip3 install --no-deps -e .[test] + pip3 install --upgrade transformers + - name: Running rmpad model tests on 8 L20 GPUs + flash_attn 2.5.8 + run: | + pytest -s tests/models/test_transformer.py + - name: Running rmpad model tests on 8 L20 GPUs + latest flash_attn + run: | + pytest -s tests/models/test_transformer.py + - name: Running FSDP rmpad model tests on 8 L20 GPUs + latest flash_attn + run: | + STRATEGY=fsdp torchrun --nproc_per_node=8 tests/special_distributed/test_fsdp_ckpt.py + - name: Running transformers ulysses tests on 8 L20 GPUs + latest transformers + run: | + torchrun --nproc_per_node=8 -m pytest tests/models/test_transformers_ulysses.py + - name: Running transformers ulysses tests on 8 L20 GPUs + transformers 4.54.1 + run: | + pip3 install transformers==4.54.1 + torchrun --nproc_per_node=8 -m pytest tests/models/test_transformers_ulysses.py + - name: Running transformers ulysses tests on 8 L20 GPUs + transformers 4.53.2 + run: | + pip3 install transformers==4.53.2 + torchrun --nproc_per_node=8 -m pytest tests/models/test_transformers_ulysses.py + - name: Running transformers ulysses tests on 8 L20 GPUs + transformers 4.52.0 + run: | + pip3 install transformers==4.52.0 + torchrun --nproc_per_node=8 -m pytest tests/models/test_transformers_ulysses.py + - name: Run distributed test + run: | + bash tests/special_distributed/run_all.sh + + # TODO: Move this back to model_rmpad once FSDP2 is stable. + # NOTE: List as an independent job to make rerun easier. + model_rmpad_fsdp2_unstable: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 20 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository and upgrade to latest transformers/flash_attn + run: | + pip3 install --no-deps -e .[test] + pip3 install --upgrade transformers + - name: Running FSDP2 rmpad model tests on 8 L20 GPUs + latest flash_attn + run: | + STRATEGY=fsdp2 torchrun --nproc_per_node=8 tests/special_distributed/test_fsdp_ckpt.py + + mcore_config_converter: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 20 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip install --upgrade "huggingface_hub[cli]" +# - name: Download model config files +# run: | +# hf download Qwen/Qwen2.5-7B config.json --local-dir $HOME/configs/Qwen/Qwen2.5-7B +# hf download Qwen/Qwen3-8B config.json --local-dir $HOME/configs/Qwen/Qwen3-8B +# hf download deepseek-ai/deepseek-coder-1.3b-instruct config.json --local-dir $HOME/configs/deepseek-ai/deepseek-coder-1.3b-instruct +# hf download Qwen/Qwen2-57B-A14B config.json --local-dir $HOME/configs/Qwen/Qwen2-57B-A14B +# hf download Qwen/Qwen3-30B-A3B config.json --local-dir $HOME/configs/Qwen/Qwen3-30B-A3B +# hf download deepseek-ai/DeepSeek-V3-Base config.json --local-dir $HOME/configs/deepseek-ai/DeepSeek-V3-Base + - name: Running mcore config converter tests on 8 L20 GPUs + run: | + torchrun --nproc_per_node=8 tests/special_distributed/test_mcore_config_converter.py + + model_engine: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 20 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install --no-deps -e .[test] + pip3 install --upgrade tensordict transformers + pip install --upgrade "huggingface_hub[cli]" + - name: Download model config files + run: | + hf download Qwen/Qwen2.5-0.5B-Instruct --local-dir $HOME/models/Qwen/Qwen2.5-0.5B-Instruct + + - name: Running mcore engine tests on 8 L20 GPUs + run: | + pytest -s -x tests/models/test_engine.py + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + model_rmpad, + model_rmpad_fsdp2_unstable, + mcore_config_converter, + model_engine + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/pre-commit.yml b/verl/.github/workflows/pre-commit.yml new file mode 100644 index 0000000000000000000000000000000000000000..6d9bb0293b64d57254ce1a31fb10a2adfd407b13 --- /dev/null +++ b/verl/.github/workflows/pre-commit.yml @@ -0,0 +1,40 @@ +# c.f. https://github.com/pre-commit/action?tab=readme-ov-file#using-this-action +name: pre-commit + +# No need to avoid / cancel lightweight pre-commit jobs +on: + schedule: + - cron: "0 0 * * 0" + pull_request: + push: + branches: + - main + - v0.* + # Allow manual triggering + workflow_dispatch: + +# Declare permissions just read content. +permissions: + contents: read + +jobs: + pre-commit: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.12"] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install the current repository + run: | + pip install -e . + - name: Set ruff --output-format=github + run: | + sed -i 's/--output-format=full/--output-format=github/' .pre-commit-config.yaml + git add .pre-commit-config.yaml + # Check "--all-files" by default + - uses: pre-commit/action@v3.0.1 diff --git a/verl/.github/workflows/reward_model.yml b/verl/.github/workflows/reward_model.yml new file mode 100644 index 0000000000000000000000000000000000000000..7ba377194e0fd154d56e6246885f293a19fcb283 --- /dev/null +++ b/verl/.github/workflows/reward_model.yml @@ -0,0 +1,131 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. +# name: Check PR Title + +name: reward_model + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "verl/**/*.py" + # Entrypoints + - ".github/workflows/reward_model.yml" + - "tests/workers/reward_model/**" + +# Declare permissions just read content. +permissions: + contents: read + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-sglang0.4.10.post2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + TRANSFORMERS_VERSION: "4.56.2" + + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + reward_model: + needs: setup + runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ] + timeout-minutes: 20 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + SGL_DISABLE_TP_MEMORY_INBALANCE_CHECK: "True" + NCCL_SHM_DISABLE: "1" + NCCL_P2P_DISABLE: "1" + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test] +# - name: Download model config files +# run: | +# hf download Skywork/Skywork-Reward-V2-Llama-3.2-1B --local-dir $HOME/models/Skywork/Skywork-Reward-V2-Llama-3.2-1B +# hf download verl-team/GenRM-CI-Test-1.5B --local-dir $HOME/models/verl-team/GenRM-CI-Test-1.5B + - name: Running discriminative reward model tests on 8 L20 GPUs + run: | + unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY + pytest -s -x tests/workers/reward_model/test_discriminative_reward_model.py + - name: Running generative reward model tests on 8 L20 GPUs + run: | + unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY + pytest -s -x tests/workers/reward_model/test_generative_reward_model.py + + cleanup: + runs-on: ubuntu-latest + needs: + [ + setup, + reward_model + ] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" \ No newline at end of file diff --git a/verl/.github/workflows/sanity.yml b/verl/.github/workflows/sanity.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3bd7766135aaf8ee5d3aab7ce16c6272265152d --- /dev/null +++ b/verl/.github/workflows/sanity.yml @@ -0,0 +1,109 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. +# name: Check PR Title + +name: sanity + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + - .github/workflows/sanity.yml + - "tests/special_sanity/**" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +jobs: + sanity: + runs-on: ubuntu-latest + timeout-minutes: 5 # Increase this timeout value as needed + strategy: + matrix: + python-version: ["3.10"] + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: ${{ matrix.python-version }} + - name: Install the current repository + run: | + pip3 install torch torchvision --index-url https://download.pytorch.org/whl/cpu + pip3 install -r requirements.txt + pip install -e .[test] + - name: Run sanity test + run: | + pytest -s -x tests/special_sanity + - name: Run license test + run: | + python3 tests/special_sanity/check_license.py --directories . + - name: Assert naming convention + run: | + if grep -rIn --exclude-dir=.git --exclude-dir=.github --exclude-dir=venv --exclude-dir=__pycache__ 'veRL' .; then + echo "Please use verl instead of veRL in the codebase" + exit 1 + fi + - name: Assert SGLang naming convention + run: | + if grep -rIn --exclude-dir=.git --exclude-dir=.github --exclude-dir=venv --exclude-dir=__pycache__ -E 'Sglang|sgLang|sglAng|sglaNg|sglanG' .; then + echo "Please use SGLang or sglang as the formal name of SGLang rollout engine" + exit 1 + fi + - name: Validate test folder structure + run: python3 tests/special_sanity/validate_structure.py + - name: Assert documentation requirement for functions + run: python3 tests/special_sanity/validate_imported_docs.py + - name: Assert device api usage in verl/recipe + run: python3 tests/special_sanity/check_device_api_usage.py --directory ./recipe + - name: Assert device api usage in verl/verl + run: python3 tests/special_sanity/check_device_api_usage.py --directory ./verl + - name: Assert documentation time info + run: python3 tests/special_sanity/check_docs_time_info.py + - name: Check docstrings for specified files + run: python3 tests/special_sanity/check_docstrings.py + - name: Check DataProto for specified folders + run: python3 tests/special_sanity/check_dataproto_usage.py -d ./verl/workers/engine diff --git a/verl/.github/workflows/scorecard.yml b/verl/.github/workflows/scorecard.yml new file mode 100644 index 0000000000000000000000000000000000000000..176d15ae2bd470752daaf138fa5aaa90641738e9 --- /dev/null +++ b/verl/.github/workflows/scorecard.yml @@ -0,0 +1,66 @@ +# This workflow uses actions that are not certified by GitHub. They are provided +# by a third-party and are governed by separate terms of service, privacy +# policy, and support documentation. + +name: Scorecard supply-chain security +on: + # For Branch-Protection check. Only the default branch is supported. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection + branch_protection_rule: + # To guarantee Maintained check is occasionally updated. See + # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained + schedule: + - cron: "27 7 * * 1" + push: + branches: + - main + - v0.* + +# Declare default permissions as read only. +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + permissions: + # Needed to upload the results to code-scanning dashboard. + security-events: write + # Needed to publish results and get a badge (see publish_results below). + id-token: write + # Uncomment the permissions below if installing in a private repository. + # contents: read + # actions: read + + steps: + - name: "Checkout code" + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + with: + persist-credentials: false + + - name: "Run analysis" + uses: ossf/scorecard-action@0864cf19026789058feabb7e87baa5f140aac736 # v2.3.1 + with: + results_file: results.sarif + results_format: sarif + # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: + # - you want to enable the Branch-Protection check on a *public* repository, or + # - you are installing Scorecard on a *private* repository + # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action?tab=readme-ov-file#authentication-with-fine-grained-pat-optional. + # repo_token: ${{ secrets.SCORECARD_TOKEN }} + + # Public repositories: + # - Publish results to OpenSSF REST API for easy access by consumers + # - Allows the repository to include the Scorecard badge. + # - See https://github.com/ossf/scorecard-action#publishing-results. + # For private repositories: + # - `publish_results` will always be set to `false`, regardless + # of the value entered here. + publish_results: true + + # Upload the results to GitHub's code scanning dashboard (optional). + # Commenting out will disable upload of results to your repo's Code Scanning dashboard + - name: "Upload to code-scanning" + uses: github/codeql-action/upload-sarif@9e8d0789d4a0fa9ceb6b1738f7e269594bdd67f0 #v3.28.9 + with: + sarif_file: results.sarif diff --git a/verl/.github/workflows/secrets_scan.yml b/verl/.github/workflows/secrets_scan.yml new file mode 100644 index 0000000000000000000000000000000000000000..298ed16c668c67facdb6af2119878da576f5bdf5 --- /dev/null +++ b/verl/.github/workflows/secrets_scan.yml @@ -0,0 +1,22 @@ +on: + push: + branches: + - main + - v0.* + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + with: + fetch-depth: 0 + - name: Secret Scanning + uses: trufflesecurity/trufflehog@7dc056a193116ba8d82154bf0549381c8fb8545c # v3.88.14 + with: + extra_args: --results=verified,unknown diff --git a/verl/.github/workflows/sgl.yml b/verl/.github/workflows/sgl.yml new file mode 100644 index 0000000000000000000000000000000000000000..1f490ddfb8f025f116e4e975ba67dead4d779322 --- /dev/null +++ b/verl/.github/workflows/sgl.yml @@ -0,0 +1,178 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: sgl + +on: +# workflow_dispatch: # Manual + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + paths: + - "**/*.py" + - .github/workflows/sgl.yml + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Megatron + - "!verl/workers/**/megatron_*.py" + # vLLM + - "!**/*vllm*" + # Recipes + - "!recipe/**" + # Entrypoints + - ".github/workflows/sgl.yml" + - "tests/rollout/*sglang*" + - "tests/rollout/async_rollout_utils.py" + - "tests/workers/rollout/*interaction*" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + sgl: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 35 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: 1 + SGL_DISABLE_TP_MEMORY_INBALANCE_CHECK: "True" + NCCL_SHM_DISABLE: "1" + NCCL_P2P_DISABLE: "1" + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install hf_transfer fastmcp + pip3 install -e .[test] +# - name: Download Model to Use +# run: | +# huggingface-cli download Qwen/Qwen2.5-0.5B --local-dir ${HOME}/models/Qwen/Qwen2.5-0.5B +# huggingface-cli download Qwen/Qwen2.5-1.5B-Instruct --local-dir ${HOME}/models/Qwen/Qwen2.5-1.5B-Instruct +# huggingface-cli download Qwen/Qwen2.5-VL-3B-Instruct --local-dir ${HOME}/models/Qwen/Qwen2.5-VL-3B-Instruct +# export HF_HUB_OFFLINE=1 + - name: Prepare gsm8k dataset + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Test the latest SGLang Rollout async with agent loop + run: | + ROLLOUT_NAME=sglang pytest -svvv tests/experimental/agent_loop +# huggingface-cli download verl-team/gsm8k-v0.4.1 --repo-type dataset --local-dir ~/verl-data/gsm8k + - name: Test the latest SGLang + run: | + cd tests/workers/rollout + torchrun --nnodes=1 --nproc_per_node=2 $(which pytest) -s test_sglang_spmd.py + - name: Test the latest SGLang Rollout async with interaction + run: | + cd tests/workers/rollout + torchrun --nnodes=1 --nproc_per_node=2 $(which pytest) -s test_sglang_async_rollout_w_interaction.py + - name: Test the latest SGLang Multi Interaction + run: | + cd tests/workers/rollout + torchrun --nnodes=1 --nproc_per_node=2 $(which pytest) -s test_sglang_multi_interaction.py + - name: Test the latest SGLang Rollout async with tool + run: | + cd tests/workers/rollout + torchrun --nnodes=1 --nproc_per_node=2 $(which pytest) -s test_sglang_async_rollout_w_tools.py + - name: Test the latest SGLang Rollout async with sandbox fusion tool + run: | + cd tests/workers/rollout + pytest -s test_sglang_async_rollout_sf_tools.py + - name: Test the latest SGLang Rollout async with search tool + run: | + cd tests/workers/rollout + pytest -s test_sglang_async_rollout_search_tools.py + - name: Test the latest SGLang Rollout async with mcp search tool + run: | + cd tests/workers/rollout + pytest -s test_sglang_async_rollout_mcp_tools.py + # Note(haibin.lin): for any new test, please update gpu_unit_tests.yaml to avoid repeated tests + - name: Test the latest SGLang Rollout async with multimodal delta + run: | + cd tests/workers/rollout + pytest -s test_sglang_async_rollout_multimodal_delta.py + + cleanup: + runs-on: ubuntu-latest + needs: [setup, sgl] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" diff --git a/verl/.github/workflows/type-coverage-check.yml b/verl/.github/workflows/type-coverage-check.yml new file mode 100644 index 0000000000000000000000000000000000000000..aa8c03a54b62f02292152e58d04c89087b9454b5 --- /dev/null +++ b/verl/.github/workflows/type-coverage-check.yml @@ -0,0 +1,31 @@ +name: Type Annotation and Docstring Coverage + +on: + pull_request: + paths: + - '**/*.py' + - '.github/workflows/type-coverage-check.yml' + +jobs: + type-coverage-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # 🚨 Important: fetch full history so `origin/main` is available + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.10' + + - name: Install dependencies + run: | + pip3 install torch torchvision --index-url https://download.pytorch.org/whl/cpu + pip3 install -r requirements.txt + pip3 install -e . --no-deps + - name: Run type annotation coverage check + run: | + python3 tests/special_sanity/type_coverage_check.py + - name: Run docstring coverage check + run: | + python3 tests/special_sanity/check_api_docs.py verl diff --git a/verl/.github/workflows/vllm.yml b/verl/.github/workflows/vllm.yml new file mode 100644 index 0000000000000000000000000000000000000000..7e2bc563fd34148d9bd333ea19544688611bb7c6 --- /dev/null +++ b/verl/.github/workflows/vllm.yml @@ -0,0 +1,145 @@ +# # Tests layout + +# Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance: +# - `tests/trainer` for testing functionality related to `verl/trainer` +# - `tests/models` for testing functionality related to `verl/models` +# - ... + +# There are a few folders with `special_` prefix, created for special purposes: +# - `special_distributed`: unit tests that must run with multiple GPUs +# - `special_e2e`: end-to-end tests with training/generation scripts +# - `special_npu`: tests for NPUs +# - `special_sanity`: a suite of quick sanity tests +# - `special_standalone`: a set of test that are designed to run in dedicated environments + +# Accelerators for tests +# - By default tests are run with GPU available, except for the ones under `special_npu`, and any test script whose name ends with `on_cpu.py`. +# - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment. + +# # Workflow layout + +# All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs: +# 1. A list of always triggered CPU sanity tests: `check-pr-title.yml`, `secrets_scan.yml`, `check-pr-title,yml`, `pre-commit.yml`, `doc.yml` +# 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml` +# 3. End-to-end tests: `e2e_*.yml` +# 4. Unit tests +# - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py` +# - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix. +# - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when +# - new workflow yaml is added to `.github/workflows` +# - new tests are added to workflow mentioned in 2. + +name: vllm + +on: + # Trigger the workflow on push or pull request, + # but only for the main branch + push: + branches: + - main + - v0.* + pull_request: + branches: + - main + - v0.* + paths: + - "**/*.py" + # Other entrypoints + - "!examples/**" + - "!tests/**" + - "!verl/trainer/main_*.py" + - "!verl/trainer/fsdp_sft_trainer.py" + # Recipes + - "!recipe/**" + # FSDP + - "!verl/workers/**/*dp_*.py" + # Megatron + - "!verl/workers/**/megatron_*.py" + # SGLang + - "!**/*sglang*" + # Entrypoints + - ".github/workflows/vllm.yml" + - "tests/special_e2e/generation" + - "tests/workers/rollout" + - "verl/trainer/main_generation.py" + - "verl/trainer/config/generation.yaml" + +# Cancel jobs on the same ref if a new one is triggered +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Declare permissions just read content. +permissions: + contents: read + +env: + IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2" + DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" + +jobs: + setup: + if: github.repository_owner == 'volcengine' + runs-on: ubuntu-latest + outputs: + runner-label: ${{ steps.create-runner.outputs.runner-label }} + mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }} + steps: + - uses: actions/checkout@v4 + - id: create-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "create" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-image: "${{ env.IMAGE }}" + + vllm: + needs: setup + runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"] + timeout-minutes: 35 # Increase this timeout value as needed + env: + HTTP_PROXY: ${{ secrets.PROXY_HTTP }} + HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }} + NO_PROXY: "localhost,127.0.0.1,hf-mirror.com" + HF_ENDPOINT: "https://hf-mirror.com" + HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + fetch-depth: 0 + - name: Install the current repository + run: | + pip3 install -e .[test] +# - name: Download Model to Use +# run: | +# huggingface-cli download Qwen/Qwen2.5-0.5B-Instruct --local-dir ${HOME}/models/Qwen/Qwen2.5-0.5B-Instruct +# huggingface-cli download Qwen/Qwen2.5-1.5B-Instruct --local-dir ${HOME}/models/Qwen/Qwen2.5-1.5B-Instruct +# huggingface-cli download Qwen/Qwen2.5-VL-3B-Instruct --local-dir ${HOME}/models/Qwen/Qwen2.5-VL-3B-Instruct +# huggingface-cli download OldKingMeister/Qwen2.5-1.5B-Instruct-YaRN --local-dir ${HOME}/models/OldKingMeister/Qwen2.5-1.5B-Instruct-YaRN +# export HF_HUB_OFFLINE=1 + - name: Prepare gsm8k dataset + run: | + ray stop --force + python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k + - name: Test the latest vLLM Rollout async with agent loop + run: | + ROLLOUT_NAME=vllm pytest -svvv tests/experimental/agent_loop + - name: Test the latest vLLM + run: | + torchrun --standalone --nnodes=1 --nproc_per_node=4 $(which pytest) -s tests/workers/rollout/rollout_vllm/test_vllm_spmd.py + - name: Test the latest vLLM on model with rope scaling + run: | + torchrun --standalone --nnodes=1 --nproc_per_node=4 $(which pytest) -s tests/workers/rollout/rollout_vllm/test_vllm_model_rope_scaling.py + # Note(haibin.lin): for any new test, please update gpu_unit_tests.yaml to avoid repeated tests + + cleanup: + runs-on: ubuntu-latest + needs: [setup, vllm] + if: always() + steps: + - id: destroy-runner + uses: volcengine/vemlp-github-runner@v1 + with: + mode: "destroy" + faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}" + mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}" diff --git a/verl/.gitignore b/verl/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..d77a5b43ffc6887b2569fcde32bfa4bb86f7ef20 --- /dev/null +++ b/verl/.gitignore @@ -0,0 +1,128 @@ + +**/*.pt +**/checkpoints +**/wget-log +**/_build/ +**/*.ckpt +**/outputs +**/*.tar.gz +**/playground +**/wandb + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class +dataset/* +tensorflow/my_graph/* +.idea/ +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +tmp/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +pytest.ini +output.txt + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# dotenv +.env + +# virtualenv +venv/ +.venv/ +ENV/ + +# Spyder project settings +.spyderproject + +# Rope project settings +.ropeproject + +# vscode +.vscode + +# Mac +.DS_Store + +# vim +*.swp + +# ckpt +*.lock + +# data +*.parquet + + +# local logs +logs +log +outputs +.history diff --git a/verl/.pre-commit-config.yaml b/verl/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd77c362015f6e97767a18aa63cc50916fae12c0 --- /dev/null +++ b/verl/.pre-commit-config.yaml @@ -0,0 +1,37 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: "v0.12.2" + hooks: + - id: ruff + args: ["--fix", "--show-fixes", "--output-format=full"] + exclude: ^.*\.(ipynb)$ + - id: ruff-format + + - repo: https://github.com/pre-commit/mirrors-mypy + rev: 'v1.17.0' + hooks: + - id: mypy + + - repo: local + hooks: + - id: autogen-trainer-cfg + name: Generate and verify verl/trainer/config/_generated_*.yaml + entry: scripts/generate_trainer_config.sh + language: script + pass_filenames: false + + - repo: local + hooks: + - id: check-docstrings + name: Check doc string coverage + entry: python3 tests/special_sanity/check_docstrings.py + language: python + pass_filenames: false + + - repo: local + hooks: + - id: check-license + name: Check license + entry: python3 tests/special_sanity/check_license.py --directories examples recipe scripts tests verl setup.py + language: python + pass_filenames: false diff --git a/verl/.readthedocs.yaml b/verl/.readthedocs.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0016868541a2a0667ef40ae6a9d861bcd26b9316 --- /dev/null +++ b/verl/.readthedocs.yaml @@ -0,0 +1,19 @@ +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.11" + rust: "1.70" + +sphinx: + configuration: docs/conf.py + +python: + install: + - requirements: docs/requirements-docs.txt + - method: pip + path: . diff --git a/verl/.vscode/settings.json b/verl/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..705533538d75025d58f108b0d5ae1ec7b5a470b5 --- /dev/null +++ b/verl/.vscode/settings.json @@ -0,0 +1,15 @@ +{ + "[python]": { + "editor.defaultFormatter": "charliermarsh.ruff", + "editor.codeActionsOnSave": { + "source.organizeImports": "always", + } + }, + "files.associations": { + "array": "cpp", + "string_view": "cpp", + "initializer_list": "cpp", + "utility": "cpp" + }, + "iis.configDir": "" +} \ No newline at end of file diff --git a/verl/CONTRIBUTING.md b/verl/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..e953f113ed2e5665acd03d5ee93774baeb0049c9 --- /dev/null +++ b/verl/CONTRIBUTING.md @@ -0,0 +1,89 @@ +# Contributing to verl + +Thank you for considering a contribution to verl! We welcome contributions of any kind - bug fixes, enhancements, documentation improvements, or even just feedback. Whether you're an experienced developer or this is your first open-source project, your help is invaluable. + +Your support can take many forms: +- Report issues or unexpected behaviors. +- Suggest or implement new features. +- Improve or expand documentation. +- Review pull requests and assist other contributors. +- Spread the word: share verl in blog posts, social media, or give the repo a ⭐. + +## Finding Issues to Contribute + +Looking for ways to dive in? Check out these issues: +- [Good first issues](https://github.com/volcengine/verl/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22) +- [Call for contribution](https://github.com/volcengine/verl/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22call%20for%20contribution%22) +Furthermore, you can learn the development plan and roadmap via [RFC](https://github.com/volcengine/verl/issues?q=is%3Aissue%20state%3Aopen%20label%3ARFC) and [Roadmap](https://github.com/volcengine/verl/issues?q=state%3Aopen%20label%3A%22roadmap%22). + + +## Developing + +- **Python-only**: install verl via `pip install -e .[test,vllm]` or `pip install -e .[test,sglang]` and iterate quickly. For full dependency setup, check out the verl [installation doc](https://verl.readthedocs.io/en/latest/start/install.html). + +## Code Linting and Formatting + +We rely on pre-commit to keep our code consistent. To set it up: + +```bash +pip install pre-commit +pre-commit install +# for staged changes +pre-commit run +# for all files in the repo +pre-commit run --all-files +# run a specific hook with pre-commit +# pre-commit run --all-files --show-diff-on-failure --color=always +pre-commit run --all-files --show-diff-on-failure --color=always ruff +pre-commit run --all-files --show-diff-on-failure --color=always autogen-trainer-cfg +``` + +## Testing + +Our test suites run on GitHub Actions. Check these workflows for details: +- [GPU unit tests](https://github.com/volcengine/verl/blob/main/.github/workflows/gpu_unit_tests.yml) +- [CPU unit tests](https://github.com/volcengine/verl/blob/main/.github/workflows/cpu_unit_tests.yml) +- [vLLM tests](https://github.com/volcengine/verl/blob/main/.github/workflows/vllm.yml) +- [SGLang tests](https://github.com/volcengine/verl/blob/main/.github/workflows/sgl.yml) + +### Adding CI tests + +If possible, please add CI test(s) for your new feature: + +1. Find the most relevant workflow yml file, which usually corresponds to a `hydra` default config (e.g. `ppo_trainer`, `ppo_megatron_trainer`, `sft_trainer`, etc). +2. Add related path patterns to the `paths` section if not already included. +3. Minimize the workload of the test script(s) (see existing scripts for examples). + +## Building the Docs +``` +# Ensure verl is on your PYTHONPATH, e.g.: +pip install -e .[test] + +# Install documentation dependencies +pip install -r requirements-docs.txt + +# Generate HTML docs +make clean +make html + +# Preview locally +python -m http.server -d _build/html/ +``` +Open your browser at http://localhost:8000 to explore the docs. + +## Pull Requests & Code Reviews + +Thanks for submitting a PR! To streamline reviews: +- Follow our Pull Request Template for title format and checklist. +- Adhere to our pre-commit lint rules and ensure all checks pass. +- Update docs for any user-facing changes. +- Add or update tests in the CI workflows, or explain why tests aren't applicable. + +## License + +See the [LICENSE](https://github.com/volcengine/verl/blob/main/LICENSE) file for full details. + +## Thank You + +We appreciate your contributions to verl. Your efforts help make the project stronger and more user-friendly. Happy coding! + diff --git a/verl/LICENSE b/verl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/verl/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/verl/Notice.txt b/verl/Notice.txt new file mode 100644 index 0000000000000000000000000000000000000000..ade439da525ac3f82936e131a1ae386f43207fd8 --- /dev/null +++ b/verl/Notice.txt @@ -0,0 +1 @@ +Copyright 2023-2024 Bytedance Ltd. and/or its affiliates \ No newline at end of file diff --git a/verl/README.md b/verl/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f41bbedc8aa5b05b4eafe02814d8cdd14335c4a6 --- /dev/null +++ b/verl/README.md @@ -0,0 +1,264 @@ +
+ 👋 Hi, everyone! + verl is a RL training library initiated by ByteDance Seed team and maintained by the verl community. +
+
+
+ +
+ +Ask DeepWiki.com +[![GitHub Repo stars](https://img.shields.io/github/stars/volcengine/verl)](https://github.com/volcengine/verl/stargazers) +[![Twitter](https://img.shields.io/twitter/follow/verl_project)](https://twitter.com/verl_project) + + +[![Documentation](https://img.shields.io/badge/documentation-blue)](https://verl.readthedocs.io/en/latest/) + + +
+ +![seed logo](https://github.com/user-attachments/assets/c42e675e-497c-4508-8bb9-093ad4d1f216) + +

verl: Volcano Engine Reinforcement Learning for LLMs

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

+ +## News +- [2025/08] verl is presented in the [PyTorch Expert Exchange Webinar](https://www.youtube.com/watch?v=Vd79NmmqY3Q&t=2s). [Slides](https://github.com/eric-haibin-lin/verl-community/blob/main/slides/verl_talk_pytorch_2025_08.pdf) available. +- [2025/07] The [ReTool](https://arxiv.org/pdf/2504.11536) recipe is fully open sourced. [Blog](https://www.notion.so/verl-reTool-recipe-Using-multi-round-conversations-and-code-sandboxing-to-improve-the-math-of-large-23a8b5b7feba80b386b2e5b5e3c1cde0) +- [2025/07] The first verl meetup will be held at ICML Vancouver on July 16th! Please [join us](https://lu.ma/0ek2nyao) if you are at ICML! (onsite only) +- [2025/06] verl with Megatron backend enables large MoE models such as [DeepSeek-671B and Qwen3-235B](https://verl.readthedocs.io/en/latest/perf/dpsk.html). +- [2025/03] [DAPO](https://dapo-sia.github.io/) is the open-sourced SOTA RL algorithm that achieves 50 points on AIME 2024 based on the Qwen2.5-32B pre-trained model, surpassing the previous SOTA achieved by DeepSeek's GRPO (DeepSeek-R1-Zero-Qwen-32B). DAPO's training is fully powered by verl and the reproduction code is available in `recipe/dapo` now. +
more... +
    +
  • [2025/04] [Seed-Thinking-v1.5](https://github.com/ByteDance-Seed/Seed-Thinking-v1.5/blob/main/seed-thinking-v1.5.pdf) tech report is released! Trained with verl, Seed-Thinking-v1.5 achieves 86.7 on AIME 2024, 55.0 on Codeforces and 77.3 on GPQA, demonstrating excellent reasoning abilities in STEM and coding. Beyond reasoning tasks, the method demonstrates notable generalization across diverse domains.
  • +
  • [2025/07] verl keynote at [AWS AI Hours Singapore](https://pages.awscloud.com/aws-ai-hours-sg.html#agenda) on 7/8, verl & verl-agent project updates at [Agent for SWE meetup](https://lu.ma/e498qhsi) by LF AI & Data Singapore on 7/11.
  • +
  • [2025/06] verl team will provide latest project updates at [PyTorch Day China](https://www.lfasiallc.com/pytorch-day-china/) on June 7th. Meet our dev team in Beijing!
  • +
  • [2025/04] [VAPO](https://arxiv.org/pdf/2504.05118) (value-based augmented PPO) paper covers our latest RL method for reasoning models. Trained from Qwen-32B-base model, VAPO achieves 60.4 on AIME 2024, outperforming DAPO-32B.
  • +
  • [2025/05] [PF-PPO](https://arxiv.org/abs/2409.06957), accepted to ICML 2025, is now supported in verl! PF-PPO enhances policy learning efficiency and robustness by filtering potentially noisy reward signals and reusing high-quality experiences via a replay buffer.
  • +
  • [2025/04] We will give a tutorial about latest post-training techniques and programming guide for verl at [ICLR 2025 Expo](https://iclr.cc/virtual/2025/calendar?filter_events=Expo+Talk+Panel&filter_rooms=), [SCI-FM workshop](https://open-foundation-model.github.io/) and [LMSys afterparty](https://lu.ma/d23nyynm). Talk materials available [here](https://github.com/eric-haibin-lin/verl-community/tree/main/iclr25).
  • +
  • [2025/03] verl v0.3.0.post1 is released! See [release note](https://github.com/volcengine/verl/releases/) for details. It achieves [~1.4x speedup](https://tongyx361.github.io/blogs/posts/verl-intro/#/verl-flexible-and-efficient-rl-for-llms) compared to prev versions.
  • +
  • [2025/05] verl will be presented at [A2M Shanghai](https://a2m.msup.com.cn/home/?aid=4488&city=shanghai) on 5/16 - 5/17.
  • +
  • [2025/05] verl will be presented at [GOSIM x PyTorch Day 2025](https://paris2025.gosim.org/). See you in Paris!
  • +
  • [2025/03] We introduced the programming model of verl at the [vLLM Beijing Meetup](https://mp.weixin.qq.com/s/n77GibL2corAtQHtVEAzfg) and [verl intro and updates](https://github.com/eric-haibin-lin/verl-community/blob/main/slides/verl-lmsys-meetup.pdf) at the [SGLang-LMSYS Org Meetup](https://lu.ma/ntjrr7ig) in Sunnyvale mid-March.
  • +
  • [2025/03] We will present verl(HybridFlow) at EuroSys 2025. See you in Rotterdam!
  • +
  • [2025/02] verl v0.2.0.post2 is released!
  • +
  • [2025/02] We presented verl in the Bytedance/NVIDIA/Anyscale Ray Meetup. See you in San Jose!
  • +
  • [2025/01] [Doubao-1.5-pro](https://team.doubao.com/zh/special/doubao_1_5_pro) is released with SOTA-level performance on LLM & VLM. The RL scaling preview model is trained using verl, reaching OpenAI O1-level performance on math benchmarks (70.0 pass@1 on AIME).
  • +
  • [2024/12] verl is presented at Ray Forward 2024. Slides available here
  • +
  • [2024/12] The team presented Post-training LLMs: From Algorithms to Infrastructure at NeurIPS 2024. Slides and video available.
  • +
  • [2024/10] verl is presented at Ray Summit. Youtube video available.
  • +
  • [2024/08] HybridFlow (verl) is accepted to EuroSys 2025.
  • +
+
+ +## Key Features + +- **FSDP**, **FSDP2** and **Megatron-LM** for training. +- **vLLM**, **SGLang** and **HF Transformers** for rollout generation. +- Compatible with Hugging Face Transformers and Modelscope Hub: [Qwen-3](https://github.com/volcengine/verl/blob/main/examples/grpo_trainer/run_qwen3-8b.sh), Qwen-2.5, Llama3.1, Gemma2, DeepSeek-LLM, etc +- Supervised fine-tuning. +- Reinforcement learning with [PPO](examples/ppo_trainer/), [GRPO](examples/grpo_trainer/), [GSPO](recipe/gspo/), [ReMax](examples/remax_trainer/), [REINFORCE++](https://verl.readthedocs.io/en/latest/examples/config.html#algorithm), [RLOO](examples/rloo_trainer/), [PRIME](recipe/prime/), [DAPO](recipe/dapo/), [DrGRPO](recipe/drgrpo), [KL_Cov & Clip_Cov](recipe/entropy) etc. + - Support model-based reward and function-based reward (verifiable reward) for math, [coding](https://github.com/volcengine/verl/tree/main/recipe/dapo), etc + - Support vision-language models (VLMs) and [multi-modal RL](examples/grpo_trainer/run_qwen2_5_vl-7b.sh) with Qwen2.5-vl, Kimi-VL + - [Multi-turn with tool calling](https://github.com/volcengine/verl/tree/main/examples/sglang_multiturn) +- LLM alignment recipes such as [Self-play preference optimization (SPPO)](https://github.com/volcengine/verl/tree/main/recipe/sppo) +- Flash attention 2, [sequence packing](examples/ppo_trainer/run_qwen2-7b_seq_balance.sh), [sequence parallelism](examples/ppo_trainer/run_deepseek7b_llm_sp2.sh) support via DeepSpeed Ulysses, [LoRA](examples/sft/gsm8k/run_qwen_05_peft.sh), [Liger-kernel](examples/sft/gsm8k/run_qwen_05_sp2_liger.sh). +- Scales up to 671B models and hundreds of GPUs with [expert parallelism](https://github.com/volcengine/verl/pull/1467) +- Multi-gpu [LoRA RL](https://verl.readthedocs.io/en/latest/advance/ppo_lora.html) support to save memory. +- Experiment tracking with wandb, swanlab, mlflow and tensorboard. + +## Upcoming Features and Changes + +- Q3 Roadmap https://github.com/volcengine/verl/issues/2388 +- DeepSeek 671b optimizations with Megatron https://github.com/volcengine/verl/issues/1033 +- Multi-turn rollout and tools using optimizations https://github.com/volcengine/verl/issues/1882 +- [Agent integration](https://github.com/volcengine/verl/tree/main/verl/experimental/agent_loop) +- Async and off-policy architecture https://github.com/volcengine/verl/pull/2231 +- List of breaking changes since v0.4 https://github.com/volcengine/verl/discussions/2270 + +## Getting Started + +Documentation + +**Quickstart:** + +- [Installation](https://verl.readthedocs.io/en/latest/start/install.html) +- [Quickstart](https://verl.readthedocs.io/en/latest/start/quickstart.html) +- [Programming Guide](https://verl.readthedocs.io/en/latest/hybrid_flow.html) & [Tech Talk](https://hcqnc.xetlk.com/sl/3vACOK) (in Chinese) +- [PPO in verl](https://verl.readthedocs.io/en/latest/algo/ppo.html) +- [GRPO in verl](https://verl.readthedocs.io/en/latest/algo/grpo.html) + +**Running a PPO example step-by-step:** + +- [Prepare Data for Post-Training](https://verl.readthedocs.io/en/latest/preparation/prepare_data.html) +- [Implement Reward Function for Dataset](https://verl.readthedocs.io/en/latest/preparation/reward_function.html) +- [PPO Example Architecture](https://verl.readthedocs.io/en/latest/examples/ppo_code_architecture.html) +- [Config Explanation](https://verl.readthedocs.io/en/latest/examples/config.html) + +**Reproducible algorithm baselines:** + +- [RL performance on coding, math](https://verl.readthedocs.io/en/latest/algo/baseline.html) + +**For code explanation and advance usage (extension):** + +- PPO Trainer and Workers + - [PPO Ray Trainer](https://verl.readthedocs.io/en/latest/workers/ray_trainer.html) + - [PyTorch FSDP Backend](https://verl.readthedocs.io/en/latest/workers/fsdp_workers.html) + - [Megatron-LM Backend](https://verl.readthedocs.io/en/latest/index.html) + +- Advanced Usage and Extension + - [Add Models with the FSDP Backend](https://verl.readthedocs.io/en/latest/advance/fsdp_extension.html) + - [Add Models with the Megatron-LM Backend](https://verl.readthedocs.io/en/latest/advance/megatron_extension.html) + - [Multi-turn Rollout Support](https://verl.readthedocs.io/en/latest/sglang_multiturn/multiturn.html) + - [Search Tool Integration](https://verl.readthedocs.io/en/latest/sglang_multiturn/search_tool_example.html) + - [Sandbox Fusion Integration](https://verl.readthedocs.io/en/latest/examples/sandbox_fusion_example.html) + - [Deployment using Separate GPU Resources](https://github.com/volcengine/verl/tree/main/examples/split_placement) + - [Extend to Other RL(HF) algorithms](https://verl.readthedocs.io/en/latest/advance/dpo_extension.html) + - [Ray API design tutorial](https://verl.readthedocs.io/en/latest/advance/placement.html) + +**Blogs from the community** + +- [When Reasoning Models Break Tokenization: The Hidden Complexity of Multiturn Training](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/multi-turn/fast_tokenization/multiturn_tokenization_and_masking.md) +- [verl deployment on AWS SageMaker](https://medium.com/@kaige.yang0110/run-verl-on-sagemaker-using-4x8-l40s-gpus-8e6d5c3c61d3) +- [verl x SGLang Multi-turn Code Walkthrough](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/multi-turn/code-walk-through/readme_EN.md) +- [Optimizing SGLang Memory Usage in verl](https://hebiao064.github.io/rl-memory-management) +- [SGLang, verl, OpenBMB and Tsinghua University: Pioneering End-to-End Multi-Turn RLHF](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/multi-turn/verl-multiturn-rollout-Release.md) +- [Reinforcement Learning from Human Feedback on AMD GPUs with verl and ROCm Integration](https://rocm.blogs.amd.com/artificial-intelligence/verl-large-scale/README.html) +- [veMLP x verl :玩转强化学习训练](https://mp.weixin.qq.com/s/7nbqxk4knMGd-hQE9ls2tA) +- [使用 verl 进行 GRPO 分布式强化学习训练最佳实践](https://www.volcengine.com/docs/6459/1463942) +- [HybridFlow verl 原文浅析](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/verl/readme.md) +- [最高提升 20 倍吞吐量!豆包大模型团队发布全新 RLHF 框架,现已开源!](https://team.doubao.com/en/blog/%E6%9C%80%E9%AB%98%E6%8F%90%E5%8D%8720%E5%80%8D%E5%90%9E%E5%90%90%E9%87%8F-%E8%B1%86%E5%8C%85%E5%A4%A7%E6%A8%A1%E5%9E%8B%E5%9B%A2%E9%98%9F%E5%8F%91%E5%B8%83%E5%85%A8%E6%96%B0-rlhf-%E6%A1%86%E6%9E%B6-%E7%8E%B0%E5%B7%B2%E5%BC%80%E6%BA%90) + +## Performance Tuning Guide + +The performance is essential for on-policy RL algorithm. We have written a detailed [performance tuning guide](https://verl.readthedocs.io/en/latest/perf/perf_tuning.html) to help you optimize performance. + +## Upgrade to vLLM >= v0.8.2 + +verl now supports vLLM>=0.8.2 when using FSDP as the training backend. Please refer to [this document](https://github.com/volcengine/verl/blob/main/docs/README_vllm0.8.md) for the installation guide and more information. Please avoid vllm 0.7.x, which contains bugs that may lead to OOMs and unexpected errors. + +## Use Latest SGLang + +SGLang is fully supported with verl, and SGLang RL Group is working extensively on building unique features, including multi-turn agentic RL, VLM RLHF, server-based RL, and partial rollout. Please refer to [this document](https://verl.readthedocs.io/en/latest/workers/sglang_worker.html) for the installation guide and more information. + +## Upgrade to FSDP2 + +verl is fully embracing FSDP2! FSDP2 is recommended by torch distributed team, providing better throughput and memory usage, and is composible with other features (e.g. torch.compile). To enable FSDP2, simply use verl main and set the following options: +``` +actor_rollout_ref.ref.strategy=fsdp2 +actor_rollout_ref.actor.strategy=fsdp2 +critic.strategy=fsdp2 +reward_model.strategy=fsdp2 +``` +Furthermore, FSDP2 cpu offloading is compatible with gradient accumulation. You can turn it on to save memory with `actor_rollout_ref.actor.fsdp_config.offload_policy=True`. For more details, see https://github.com/volcengine/verl/pull/1026 + +## AMD Support (ROCm Kernel) + +verl now supports FSDP as the training engine (Megatron support coming soon) and both integrates with vLLM and SGLang as inference engines. Please refer to [this document](https://github.com/volcengine/verl/blob/main/docs/amd_tutorial/amd_build_dockerfile_page.rst) for the installation guide and more information, and [this document](https://github.com/volcengine/verl/blob/main/docs/amd_tutorial/amd_vllm_page.rst) for the vLLM performance tuning for ROCm. + + +## Citation and acknowledgement + +If you find the project helpful, please cite: + +- [HybridFlow: A Flexible and Efficient RLHF Framework](https://arxiv.org/abs/2409.19256v2) +- [A Framework for Training Large Language Models for Code Generation via Proximal Policy Optimization](https://i.cs.hku.hk/~cwu/papers/gmsheng-NL2Code24.pdf) + +```bibtex +@article{sheng2024hybridflow, + title = {HybridFlow: A Flexible and Efficient RLHF Framework}, + author = {Guangming Sheng and Chi Zhang and Zilingfeng Ye and Xibin Wu and Wang Zhang and Ru Zhang and Yanghua Peng and Haibin Lin and Chuan Wu}, + year = {2024}, + journal = {arXiv preprint arXiv: 2409.19256} +} +``` + +verl is inspired by the design of Nemo-Aligner, Deepspeed-chat and OpenRLHF. The project is adopted and contributed by Bytedance, Anyscale, LMSys.org, [Alibaba Qwen team](https://github.com/QwenLM/), Shanghai AI Lab, Tsinghua University, UC Berkeley, UCLA, UIUC, University of Hong Kong, ke.com, [All Hands AI](https://www.all-hands.dev/), [ModelBest](http://modelbest.cn/), JD AI Lab, Microsoft Research, [StepFun](https://www.stepfun.com/), Amazon, LinkedIn, Meituan, [Camel-AI](https://www.camel-ai.org/), [OpenManus](https://github.com/OpenManus), Xiaomi, NVIDIA research, [Baichuan](https://www.baichuan-ai.com/home), [RedNote](https://www.xiaohongshu.com/), [SwissAI](https://www.swiss-ai.org/), [Moonshot AI (Kimi)](https://www.moonshot-ai.com/), Baidu, Snowflake, Skywork.ai, JetBrains, [IceSword Lab](https://www.iceswordlab.com), and many more. + +## Awesome work using verl + +- [TinyZero](https://github.com/Jiayi-Pan/TinyZero): a reproduction of **DeepSeek R1 Zero** recipe for reasoning tasks ![GitHub Repo stars](https://img.shields.io/github/stars/Jiayi-Pan/TinyZero) +- [SkyThought](https://github.com/NovaSky-AI/SkyThought): RL training for Sky-T1-7B by NovaSky AI team. ![GitHub Repo stars](https://img.shields.io/github/stars/NovaSky-AI/SkyThought) +- [simpleRL-reason](https://github.com/hkust-nlp/simpleRL-reason): SimpleRL-Zoo: Investigating and Taming Zero Reinforcement Learning for Open Base Models in the Wild ![GitHub Repo stars](https://img.shields.io/github/stars/hkust-nlp/simpleRL-reason) +- [Easy-R1](https://github.com/hiyouga/EasyR1): **Multi-modal** RL training framework ![GitHub Repo stars](https://img.shields.io/github/stars/hiyouga/EasyR1) +- [OpenManus-RL](https://github.com/OpenManus/OpenManus-RL): LLM Agents RL tunning framework for multiple agent environments. ![GitHub Repo stars](https://img.shields.io/github/stars/OpenManus/OpenManus-RL) +- [rllm](https://github.com/agentica-project/rllm): async RL training with [verl-pipeline](https://github.com/agentica-project/verl-pipeline) ![GitHub Repo stars](https://img.shields.io/github/stars/agentica-project/rllm) +- [RAGEN](https://github.com/ZihanWang314/ragen): a general-purpose reasoning **agent** training framework ![GitHub Repo stars](https://img.shields.io/github/stars/ZihanWang314/ragen) +- [Search-R1](https://github.com/PeterGriffinJin/Search-R1): RL with reasoning and **searching (tool-call)** interleaved LLMs ![GitHub Repo stars](https://img.shields.io/github/stars/PeterGriffinJin/Search-R1) +- [ReSearch](https://github.com/Agent-RL/ReSearch): Learning to **Re**ason with **Search** for LLMs via Reinforcement Learning ![GitHub Repo stars](https://img.shields.io/github/stars/Agent-RL/ReSearch) +- [Skywork-OR1](https://github.com/SkyworkAI/Skywork-OR1): Skywork open reaonser series ![GitHub Repo stars](https://img.shields.io/github/stars/SkyworkAI/Skywork-OR1) +- [ToRL](https://github.com/GAIR-NLP/ToRL): Scaling tool-integrated RL ![GitHub Repo stars](https://img.shields.io/github/stars/GAIR-NLP/ToRL) +- [Absolute Zero Reasoner](https://github.com/LeapLabTHU/Absolute-Zero-Reasoner): [A no human curated data self-play framework for reasoning](https://arxiv.org/abs/2505.03335) ![GitHub Repo stars](https://img.shields.io/github/stars/LeapLabTHU/Absolute-Zero-Reasoner) +- [verl-agent](https://github.com/langfengQ/verl-agent): A scalable training framework for **long-horizon LLM/VLM agents**, along with a new algorithm **GiGPO** ![GitHub Repo stars](https://img.shields.io/github/stars/langfengQ/verl-agent) +- [RL-Factory](https://github.com/Simple-Efficient/RL-Factory): An easy and efficient RL post-training framework for Agentic Learning ![GitHub Repo stars](https://img.shields.io/github/stars/Simple-Efficient/RL-Factory) +- [ReTool](https://retool-rl.github.io/): ReTool: reinforcement learning for strategic tool use in LLMs. Code release is in progress... +- [verl-tool](https://github.com/TIGER-AI-Lab/verl-tool): An unified and easy-to-extend tool-agent training framework based on verl![GitHub Repo stars](https://img.shields.io/github/stars/TIGER-AI-Lab/verl-tool) +- [PRIME](https://github.com/PRIME-RL/PRIME): Process reinforcement through implicit rewards ![GitHub Repo stars](https://img.shields.io/github/stars/PRIME-RL/PRIME) +- [MemAgent](https://github.com/BytedTsinghua-SIA/MemAgent): MemAgent: Reshaping Long-Context LLM with Multi-Conv RL based Memory Agent ![GitHub Repo stars](https://img.shields.io/github/stars/BytedTsinghua-SIA/MemAgent) +- [POLARIS](https://github.com/ChenxinAn-fdu/POLARIS): A Post-training recipe for scaling RL on Advanced Reasoning models ![GitHub Repo stars](https://img.shields.io/github/stars/ChenxinAn-fdu/POLARIS) +- [GUI-R1](https://github.com/ritzz-ai/GUI-R1): **GUI-R1**: A Generalist R1-style Vision-Language Action Model For **GUI Agents** ![GitHub Repo stars](https://img.shields.io/github/stars/ritzz-ai/GUI-R1) +- [DeepRetrieval](https://github.com/pat-jj/DeepRetrieval): RL Training of **Search Agent** with **Search/Retrieval Outcome** ![GitHub Repo stars](https://img.shields.io/github/stars/pat-jj/DeepRetrieval) +- [Code-R1](https://github.com/ganler/code-r1): Reproducing R1 for **Code** with Reliable Rewards ![GitHub Repo stars](https://img.shields.io/github/stars/ganler/code-r1) +- [DeepResearcher](https://github.com/GAIR-NLP/DeepResearcher): Scaling deep research via reinforcement learning in real-world environments ![GitHub Repo stars](https://img.shields.io/github/stars/GAIR-NLP/DeepResearcher) +- [VAGEN](https://github.com/RAGEN-AI/VAGEN): Training VLM agents with multi-turn reinforcement learning ![GitHub Repo stars](https://img.shields.io/github/stars/RAGEN-AI/VAGEN) +- [RM-R1](https://arxiv.org/abs/2505.02387): RL training of reasoning reward models ![GitHub Repo stars](https://img.shields.io/github/stars/RM-R1-UIUC/RM-R1) +- [LUFFY](https://arxiv.org/pdf/2504.14945): Learning to Reason under Off-Policy Guidance![GitHub Repo stars](https://img.shields.io/github/stars/ElliottYan/LUFFY) +- [DeepMath](https://github.com/zwhe99/DeepMath): DeepMath-103K data and series models for math reasoning![GitHub Repo stars](https://img.shields.io/github/stars/zwhe99/DeepMath) +- [PACS](https://github.com/ritzz-ai/PACS): Implicit Actor Critic Coupling via a Supervised Learning Framework for RLVR ![GitHub Repo stars](https://img.shields.io/github/stars/ritzz-ai/PACS) +- [Entropy Mechanism of RL](https://github.com/PRIME-RL/Entropy-Mechanism-of-RL): The Entropy Mechanism of Reinforcement Learning for Large Language Model Reasoning![GitHub Repo stars](https://img.shields.io/github/stars/PRIME-RL/Entropy-Mechanism-of-RL) +- [LLaSA-TTS-GRPO](https://github.com/channel-io/ch-tts-llasa-rl-grpo): TTS fine-tuning with GRPO optimization based on LLASA models ![GitHub Repo stars](https://img.shields.io/github/stars/channel-io/ch-tts-llasa-rl-grpo) +- [PF-PPO](https://arxiv.org/abs/2409.06957): Policy Filtration for PPO based on the reliability of reward signals for more efficient and robust RLHF. +- [RACRO](https://github.com/gyhdog99/RACRO2): Build multi-modal reasoning models via decoupling it into query-conditioned captioning and text-only reasoning ![GitHub Repo stars](https://img.shields.io/github/stars/gyhdog99/RACRO2) +- [Agent Lightning](https://github.com/microsoft/agent-lightning): A flexible and extensible framework that enables seamless agent optimization for any existing agent framework. ![GitHub Repo stars](https://img.shields.io/github/stars/microsoft/agent-lightning) +- [VTool-R1](https://github.com/VTOOL-R1/vtool-r1): VLMs Learn to Think with Images via Reinforcement Learning on Multimodal Tool Use. ![GitHub Repo stars](https://img.shields.io/github/stars/VTOOL-R1/vtool-r1) +- [Kimina-Prover-RL](https://github.com/project-numina/kimina-prover-rl/tree/main/recipe/kimina_prover_rl): Training pipeline for formal theorem proving, based on a paradigm inspired by DeepSeek-R1. +- [RL-PLUS](https://github.com/YihongDong/RL-PLUS): Countering Capability Boundary Collapse of LLMs in Reinforcement Learning with Hybrid-policy Optimization. +- [rStar2-Agent](https://github.com/microsoft/rStar): Using reinforcement learning with multi-step tool-calling for math tasks, rStar2-Agent-14B reaches frontier-level math reasoning in just 510 RL training steps ![GitHub Repo stars](https://img.shields.io/github/stars/microsoft/rStar) +- [Vision-SR1](https://github.com/zli12321/Vision-SR1): Self-Rewarding Vision-Language Model via Reasoning Decomposition ![GitHub Repo stars](https://img.shields.io/github/stars/zli12321/Vision-SR1) +- [SimpleVLA-RL](https://github.com/PRIME-RL/SimpleVLA-RL): SimpleVLA-RL: A Simple yet Effective Vision-Language Action Model for Reinforcement Learning ![GitHub Repo stars](https://img.shields.io/github/stars/PRIME-RL/SimpleVLA-RL) +- [Table-R1](https://github.com/Table-R1/Table-R1): Table-R1: Inference-Time Scaling for Table Reasoning ![GitHub Repo stars](https://img.shields.io/github/stars/Table-R1/Table-R1) + +and many more awesome work listed in [recipe](recipe/README.md). + +## Contribution Guide + +See [contributions guide](CONTRIBUTING.md) + +## About [ByteDance Seed Team](https://team.doubao.com/) + +Founded in 2023, ByteDance Seed Team is dedicated to crafting the industry's most advanced AI foundation models. The team aspires to become a world-class research team and make significant contributions to the advancement of science and society. You can get to know Bytedance Seed better through the following channels👇 +
+ + + + + + + + + +
+--- + +We are HIRING! Send us an [email](mailto:the.verl.project@gmail.com) if you are interested in internship/FTE opportunities in RL for agents. diff --git a/verl/docker/Apptainerfile.rocm b/verl/docker/Apptainerfile.rocm new file mode 100644 index 0000000000000000000000000000000000000000..02596218726a60fc105bad7dc3653655ae164e93 --- /dev/null +++ b/verl/docker/Apptainerfile.rocm @@ -0,0 +1,57 @@ +Bootstrap: docker + +# Support - Traing: fsdp; Inference: vllm +# FROM: rocm/vllm:rocm6.2_mi300_ubuntu20.04_py3.9_vllm_0.6.4 +# Support - Traing: fsdp; Inference: vllm, sglang +FROM lmsysorg/sglang:v0.4.5-rocm630 + +%environment + export PYTORCH_ROCM_ARCH="gfx90a;gfx942" + + export HIPCC_COMPILE_FLAGS_APPEND="--amdgpu-target=gfx90a;gfx942 -D__HIP_PLATFORM_AMD__" + export CFLAGS="-D__HIP_PLATFORM_AMD__" + export CXXFLAGS="-D__HIP_PLATFORM_AMD__" + +%post + # Create source directory + mkdir -p /opt/src + + # Uninstall and reinstall vllm + pip uninstall -y vllm + cd /opt/src + git clone -b v0.6.3 https://github.com/vllm-project/vllm.git + cd vllm + MAX_JOBS=$(nproc) python3 setup.py install + cd /opt + rm -rf /opt/src/vllm + + # Install dependencies + pip install "tensordict<0.6" --no-deps + pip install accelerate \ + codetiming \ + datasets \ + dill \ + hydra-core \ + liger-kernel \ + numpy \ + pandas \ + peft \ + "pyarrow>=15.0.0" \ + pylatexenc \ + "ray[data,train,tune,serve]" \ + torchdata \ + transformers \ + wandb \ + orjson \ + pybind11 + + # Clone and install verl from GitHub + cd /opt + git clone https://github.com/volcengine/verl.git + cd verl + # Uncomment to use a specific version + # git checkout v0.3.0.post0 + pip install -e . --no-deps + + # Install torch_memory_saver + pip install git+https://github.com/ExtremeViscent/torch_memory_saver.git --no-deps \ No newline at end of file diff --git a/verl/docker/Dockerfile.extention.awsefa b/verl/docker/Dockerfile.extention.awsefa new file mode 100644 index 0000000000000000000000000000000000000000..ba3bc67311977050d1d368d2bfac38fa0278cb0f --- /dev/null +++ b/verl/docker/Dockerfile.extention.awsefa @@ -0,0 +1,55 @@ +# Base Image support aws EFA +# Build Image with frameworks based on this +FROM verlai/verl:app-verl0.5-sglang0.4.6.post5-mcore0.12.2 + +# For aws instances with EFA net interface (Sagemaker AI Pod) +# install EFA driver: +######## AWS EFA ############ +ENV NCCL_VERSION=2.25.1-1 +ENV DEBIAN_FRONTEND=noninteractive +ENV EFA_INSTALLER_VERSION=1.40.0 +ENV AWS_OFI_NCCL_VERSION=1.14.2 +ENV FI_EFA_SET_CUDA_SYNC_MEMOPS=0 +ENV FI_PROVIDER=efa + +RUN apt update && apt install -y linux-image-generic libhwloc-dev + +RUN cd /tmp && \ + curl -O https://efa-installer.amazonaws.com/aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz && \ + tar -xf aws-efa-installer-${EFA_INSTALLER_VERSION}.tar.gz && \ + cd aws-efa-installer && \ + ./efa_installer.sh -y -g --skip-kmod --skip-limit-conf --no-verify && \ + ldconfig && \ + rm -rf /tmp/aws-efa-installer /var/lib/apt/lists/* + +# NCCL EFA Plugin +RUN cd /tmp && \ + curl -LO https://github.com/aws/aws-ofi-nccl/archive/refs/tags/v${AWS_OFI_NCCL_VERSION}.tar.gz && \ + tar -xzf /tmp/v${AWS_OFI_NCCL_VERSION}.tar.gz && \ + rm /tmp/v${AWS_OFI_NCCL_VERSION}.tar.gz && \ + mv aws-ofi-nccl-${AWS_OFI_NCCL_VERSION} aws-ofi-nccl && \ + cd /tmp/aws-ofi-nccl && \ + ./autogen.sh && \ + ./configure --prefix=/opt/amazon/efa \ + --with-libfabric=/opt/amazon/efa \ + --with-cuda=/usr/local/cuda \ + --enable-platform-aws \ + --with-mpi=/opt/amazon/openmpi && \ + make -j$(nproc) install && \ + rm -rf /tmp/aws-ofi/nccl + +# NCCL +RUN echo "/usr/local/lib" >> /etc/ld.so.conf.d/local.conf && \ + echo "/opt/amazon/openmpi/lib" >> /etc/ld.so.conf.d/efa.conf && \ + ldconfig + +ENV OMPI_MCA_pml=^cm,ucx \ + OMPI_MCA_btl=tcp,self \ + OMPI_MCA_btl_tcp_if_exclude=lo,docker0,veth_def_agent \ + OPAL_PREFIX=/opt/amazon/openmpi \ + NCCL_SOCKET_IFNAME=^docker,lo,veth_def_agent \ + FI_EFA_USE_HUGE_PAGE=0 + +# docker build -t verl:awsefa --label "commit=$(git rev-parse --short HEAD)" . +# on aws: +# docker run --ipc=host --privileged --name verldev --gpus all --network=host --shm-size=1800gb -itd verl:awsefa diff --git a/verl/docker/Dockerfile.ngc.vllm b/verl/docker/Dockerfile.ngc.vllm new file mode 100644 index 0000000000000000000000000000000000000000..fa0ebbb2c04ed842c729f91ddbce9dd7803bd87d --- /dev/null +++ b/verl/docker/Dockerfile.ngc.vllm @@ -0,0 +1,48 @@ +# docker buildx build --platform linux/x86_64 -t "verlai/verl:ngc-th2.4.0-cu124-vllm0.6.3-ray2.4-te1.7-v0.0.6" -f docker/Dockerfile.ngc.vllm . --builder cloud-verlai-verl-builder --progress=plain --push +FROM nvcr.io/nvidia/pytorch:24.05-py3 + +# uninstall nv-pytorch fork +RUN pip3 uninstall pytorch-quantization \ + pytorch-triton \ + torch \ + torch-tensorrt \ + torchvision \ + xgboost transformer_engine flash_attn \ + apex megatron-core -y + +RUN pip3 install torch==2.4.0 torchvision==0.19.0 torchaudio==2.4.0 --index-url https://download.pytorch.org/whl/cu124 + +# =============== Megatron dependencies (optional) ================= +# install apex, set MAX_JOBS to avoid OOMs +RUN MAX_JOBS=4 pip3 install -v --disable-pip-version-check --no-cache-dir --no-build-isolation \ + --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" \ + git+https://github.com/NVIDIA/apex +# =============== End of Megatron dependencies (optional) ================= + +RUN pip3 install --no-cache-dir \ + accelerate \ + codetiming \ + datasets \ + dill \ + hydra-core \ + numpy \ + 'pandas' \ + 'peft' \ + 'pyarrow>=15.0.0' \ + 'pybind11' \ + 'pylatexenc' \ + 'ray>=2.10' \ + 'tensordict<0.6' \ + 'transformers' \ + 'vllm==0.6.3.post1' \ + 'wandb' \ + 'tensorboard' + +# full dependencies +RUN pip3 install pytest pre-commit py-spy pyext liger-kernel + +# =============== Megatron dependencies (optional) ================= +# install Transformer Engine, which requires FA 2.5.8. Do it in a separate step for docker cache +RUN MAX_JOBS=4 NINJA_FLAGS="-j4" pip3 install flash-attn==2.5.8 --no-cache-dir --no-build-isolation +RUN MAX_JOBS=1 NINJA_FLAGS="-j1" TE_BUILD_WITH_NINJA=0 pip3 install git+https://github.com/eric-haibin-lin/TransformerEngine.git@v1.7.0 +# =============== End of Megatron dependencies (optional) ================= diff --git a/verl/docker/Dockerfile.ngc.vllm0.8 b/verl/docker/Dockerfile.ngc.vllm0.8 new file mode 100644 index 0000000000000000000000000000000000000000..f6ff8fe80b24a413ee57321296f60cedada14563 --- /dev/null +++ b/verl/docker/Dockerfile.ngc.vllm0.8 @@ -0,0 +1,75 @@ +# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + xgboost transformer_engine flash_attn apex megatron-core grpcio + +# Install torch-2.6.0+cu124 + vllm-0.8.3 +# torch-2.6.0+cu124: cxx11abi=False +# torch-2.6.0+cu126: cxx11abi=True +# see https://github.com/flashinfer-ai/flashinfer/issues/911 +RUN pip install --no-cache-dir "vllm==0.8.3" "torch==2.6.0" "torchvision==0.21.0" "torchaudio==2.6.0" "tensordict==0.6.2" torchdata \ + "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=15.0.0" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler \ + pytest py-spy pyext pre-commit ruff tensorboard + +# Install flash-attn-2.7.4.post1 (cxx11abi=False) +RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \ + pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl + +# Install flashinfer-0.2.2.post1+cu124 (cxx11abi=False) +# vllm-0.8.3 does not support flashinfer>=0.2.3 +# see https://github.com/vllm-project/vllm/pull/15777 +RUN wget -nv https://github.com/flashinfer-ai/flashinfer/releases/download/v0.2.2.post1/flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \ + pip install --no-cache-dir flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl + +# Fix packages +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +# Install verl +RUN pip install --no-cache-dir verl[vllm] -U + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url diff --git a/verl/docker/Dockerfile.ngc.vllm0.8.sagemaker b/verl/docker/Dockerfile.ngc.vllm0.8.sagemaker new file mode 100644 index 0000000000000000000000000000000000000000..2746fa9f8e115c0c6ad43627b2d4200df75d597b --- /dev/null +++ b/verl/docker/Dockerfile.ngc.vllm0.8.sagemaker @@ -0,0 +1,46 @@ +# Using a pre-built image from AWS DLC which contains the current version of python (3.10) and supported cuda version (12.1) +FROM 763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:2.1.0-transformers4.36.0-gpu-py310-cu121-ubuntu20.04 + +# uninstall nv-pytorch fork +RUN pip3 uninstall -y pytorch-quantization \ + pytorch-triton torch torch-tensorrt torchvision \ + xgboost transformer_engine flash_attn apex megatron-core + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini && \ + apt-get clean + +# Install torch-2.6.0 + vllm-0.8.2 +RUN pip install --no-cache-dir vllm==0.8.2 torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 tensordict torchdata==0.11.0 \ + transformers>=4.49.0 accelerate datasets peft hf-transfer \ + ray[default] codetiming hydra-core pandas pyarrow>=15.0.0 pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler \ + pytest pre-commit py-spy pyext ruff tensorboard + +# Install flash_attn-2.7.4.post1 +RUN pip uninstall -y transformer-engine flash-attn && \ + pip install flash-attn==2.7.4.post1 --no-build-isolation + +# Fix cv2 +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --no-cache-dir nvidia-ml-py>=12.560.30 opencv-python-headless==4.8.0.74 fastapi==0.115.6 && \ + pip install --no-cache-dir --upgrade optree>=0.13.0 + +# Install verl +RUN pip install --no-cache-dir verl[vllm] -U + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url diff --git a/verl/docker/Dockerfile.rocm b/verl/docker/Dockerfile.rocm new file mode 100644 index 0000000000000000000000000000000000000000..16c99aa0540169e0165bc47394f6faa45e007093 --- /dev/null +++ b/verl/docker/Dockerfile.rocm @@ -0,0 +1,322 @@ +# FROM "compute-artifactory.amd.com:5000/rocm-plus-docker/framework/compute-rocm-rel-6.4:94_ubuntu22.04_py3.10_pytorch_release-2.7_575e247" +# FROM "rlfoundation.azurecr.io/rocm6.3.4:vllm-0.8.5-numa-patch-ubuntu-22.04" +FROM "rlsys/rocm-6.3.4-patch:rocm6.3.4-numa-patch_ubuntu-22.04" + +SHELL ["/bin/bash", "-ceuxo", "pipefail"] + +ENV MAX_JOBS=512 + +ENV PATH="/usr/local/python3.12/bin:$PATH" +RUN ln -sf /usr/bin/python3.12 /usr/bin/python && \ + ln -sf /usr/bin/pip3.12 /usr/bin/pip + +############################################ +############################################ +RUN apt-get update +RUN apt-get install -y pkg-config liblzma-dev +############################################ +############################################ + + +########################################### +##########Install TransformerEngine######## +########################################### +WORKDIR /workspace/ +# transformer-engine install +# https://github.com/ROCm/TransformerEngine + +RUN rm -rf TransformerEngine +RUN git clone --recursive https://github.com/ROCm/TransformerEngine.git +WORKDIR /workspace/TransformerEngine +RUN git checkout 236178e5 +# git checkout bb061ade +# git checkout 864405c + +ENV NVTE_FRAMEWORK=pytorch +ENV NVTE_ROCM_ARCH=gfx942 +ENV NVTE_USE_HIPBLASLT=1 +ENV NVTE_USE_ROCM=1 + +# export CMAKE_PREFIX_PATH="/opt/rocm:/opt/rocm/hip:/usr/local:/usr:${CMAKE_PREFIX_PATH:-}" +ENV CMAKE_PREFIX_PATH="/opt/rocm:/opt/rocm/hip:/usr/local:/usr" + + +# ENV NVTE_BUILD_MAX_JOBS=$(MAX_JOBS) + +RUN MAX_JOBS=$(MAX_JOBS) pip install . -vvv + +WORKDIR /workspace/ +########################################### +########################################### +########################################### + + + + + +#################################################################################### +################Install vllm - sglang require vllm 0.6.7 dependency################# +#################################################################################### +#### Require vllm 0.6.7 - checkout 113274a0 +WORKDIR /workspace/ +RUN rm -rf vllm +RUN pip uninstall -y vllm +# Refer to here (down-grade vllm to 0.6.3): https://docs.vllm.ai/en/v0.6.3/getting_started/amd-installation.html +RUN git clone https://github.com/ROCm/vllm.git +# git clone https://github.com/vllm-project/vllm.git +WORKDIR /workspace/vllm +RUN git checkout 113274a0 +ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942" +#ENV MAX_JOBS=512 +ENV MAX_JOBS=${MAX_JOBS} +RUN pip install "boto3>=1.26.0" +RUN pip install setuptools_scm +# will add src into py. You can delete the repo +RUN python3 setup.py install +WORKDIR /workspace/ +#################################################################################### +#################################################################################### +#################################################################################### + + + +########################################### +############For hack docker################ +########################################### +RUN pip install setuptools==75.8.0 +########################################### +########################################### +########################################### + + + +########################################### +############build sgalng################### +########################################### +# Set environment variables +ENV BASE_DIR=/sgl-workspace +ENV BUILD_TYPE=all +ENV SGL_REPO=https://github.com/sgl-project/sglang +ENV SGL_BRANCH=v0.4.6.post5 +ENV TRITON_REPO=https://github.com/ROCm/triton.git +ENV TRITON_COMMIT=improve_fa_decode_3.0.0 +ENV AITER_REPO=https://github.com/ROCm/aiter.git +ENV AITER_COMMIT=v0.1.2 +# v0.1.2 version - commit id: 9d11f47 +# ENV AITER_COMMIT=9d11f47 + +ENV HIP_FORCE_DEV_KERNARG=1 +ENV HSA_NO_SCRATCH_RECLAIM=1 +ENV SGLANG_SET_CPU_AFFINITY=1 +ENV SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 +ENV NCCL_MIN_NCHANNELS=112 +ENV MOE_PADDING=1 +ENV VLLM_FP8_PADDING=1 +ENV VLLM_FP8_ACT_PADDING=1 +ENV VLLM_FP8_WEIGHT_PADDING=1 +ENV VLLM_FP8_REDUCE_CONV=1 +ENV TORCHINDUCTOR_MAX_AUTOTUNE=1 +ENV TORCHINDUCTOR_MAX_AUTOTUNE_POINTWISE=1 +ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942" +ENV AMDGPU_TARGETS=gfx942 +ENV ROCM_ARCH=gfx942 +ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942" + +# Switch to working directory +WORKDIR /sgl-workspace + +# Clean and create directory +RUN rm -rf /sgl-workspace && mkdir -p /sgl-workspace + +# Clone and build sglang +RUN git clone ${SGL_REPO} \ + && cd sglang \ + && git checkout ${SGL_BRANCH} || echo "Using default branch" \ + && cd sgl-kernel \ + && rm -f pyproject.toml \ + && mv pyproject_rocm.toml pyproject.toml \ + && python setup_rocm.py install \ + && cd .. \ + && if [ "$BUILD_TYPE" = "srt" ]; then \ + python -m pip --no-cache-dir install -e "python[srt_hip]"; \ + else \ + python -m pip --no-cache-dir install -e "python[all_hip]"; \ + fi \ + && cd /sgl-workspace \ + && cp -r /sgl-workspace/sglang /sglang \ + && python -m pip cache purge + +# Install common Python packages +RUN pip install IPython orjson python-multipart torchao pybind11 + +# Rebuild Triton +RUN pip uninstall -y triton || true \ + && git clone ${TRITON_REPO} \ + && cd triton \ + && git checkout ${TRITON_COMMIT} \ + && cd python \ + && python3 setup.py install \ + && cd /sgl-workspace + + +# ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942 --amdgpu-lower-module-lds-strategy=1" +# ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942" + +# Build aiter +#version: Commit 9d11f47 + # && git checkout ${AITER_COMMIT} \ +RUN pip uninstall -y aiter || true +RUN git clone ${AITER_REPO} \ + && cd aiter \ + && git checkout ${AITER_COMMIT} \ + && git submodule sync \ + && git submodule update --init --recursive \ + && PREBUILD_KERNELS=1 GPU_ARCHS=gfx942 python3 setup.py install \ + && cd /sgl-workspace + # && PREBUILD_KERNELS=1 GPU_ARCHS=gfx942 python3 setup.py develop \ + # && PREBUILD_KERNELS=1 GPU_ARCHS=gfx942 python3 setup.py develop \ + +# Copy MI300X config +RUN find /sgl-workspace/sglang/python/sglang/srt/layers/quantization/configs/ \ + /sgl-workspace/sglang/python/sglang/srt/layers/moe/fused_moe_triton/configs/ \ + -type f -name '*MI300X*' | \ + xargs -I {} sh -c 'vf_config=$(echo "$1" | sed "s/MI300X/MI300X_VF/"); cp "$1" "$vf_config"' -- {} + +# Environment setup complete. +RUN echo "Environment setup complete." + +WORKDIR /workspace/ +########################################### +########################################### +########################################### + + + + + + +########################################### +###############vllm v0.8.5################# +########################################### +# ENV GITHUB_USERNAME=yushengsu-thu +# ENV GITHUB_MAIL=yushengsu@gmail.com + +# RUN git config --global user.name "${GITHUB_USERNAME}" \ +# && git config --global user.email "${GITHUB_MAIL}" + +WORKDIR /workspace/ + +ENV VLLM_TARGET_DEVICE=rocm +ENV ROCM_PATH=/opt/rocm +ENV SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev + +# Find the repo path in: DockerFile/Dockerfile.rocm_yang +# RUN git clone https://github.com/RLFoundation/vllm-patch.git +RUN pip uninstall -y vllm || true +RUN rm -rf vllm-patch +RUN git clone https://github.com/RLFoundation/vllm-patch.git \ + && cd vllm-patch \ + && git checkout v0.8.5-sleep-numa \ + && rm -rf build/ dist/ *.egg-info \ + && ln -sf /opt/rocm/lib/libamdhip64.so /usr/lib/libamdhip64.so \ + && SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev PYTORCH_ROCM_ARCH="gfx90a;gfx942" MAX_JOBS=${MAX_JOBS} python3 setup.py install + # RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev PYTORCH_ROCM_ARCH="gfx90a;gfx942" MAX_JOBS=${MAX_JOBS} python3 setup.py develop + +WORKDIR /workspace/ +########################################### +########################################### +########################################### + + + + +######################################### +#### Install megatron-core############### +######################################### +RUN pip uninstall -y megatron-core && \ + git clone https://github.com/yushengsu-thu/Megatron-LM-amd_version.git && \ + cd Megatron-LM-amd_version && \ + pip install -vvv -e . && \ + cd /workspace/ +######################################### +######################################### +######################################### + + + + +####################################### +################apex################### +####################################### +WORKDIR /workspace/ +RUN pip uninstall -y apex && \ + git clone https://github.com/ROCm/apex.git && \ + cd apex && \ + python setup.py install && \ + cd /workspace/ +####################################### +####################################### +####################################### + + + + +################################################################################ +###########################Add torch_memory_saver############################### +################################################################################ +# Set environment variables +ENV HIPCC_COMPILE_FLAGS_APPEND="--amdgpu-target=gfx90a;gfx942 -D__HIP_PLATFORM_AMD__" +ENV CFLAGS="-D__HIP_PLATFORM_AMD__" +ENV CXXFLAGS="-D__HIP_PLATFORM_AMD__" +RUN pip install "git+https://github.com/YangWang92/torch_memory_saver_numa.git@numa" +################################################################################ +################################################################################ +################################################################################ + + + +######################################## +######Install ray####################### +######################################## +# need to add this patch: https://github.com/ray-project/ray/pull/53531/files +RUN pip uninstall ray -y +RUN pip install "ray[data,train,tune,serve]>=2.47.0" +######################################## +######################################## +######################################## + + + +########################################## +#######Install other dependencies######### +########################################## +RUN pip install "tensordict==0.6.2" --no-deps && \ + pip install accelerate \ + codetiming \ + datasets \ + dill \ + hydra-core \ + liger-kernel \ + numpy \ + pandas \ + peft \ + "pyarrow>=15.0.0" \ + pylatexenc \ + torchdata \ + wandb \ + orjson \ + pybind11 + +WORKDIR /workspace/ +RUN git clone https://github.com/volcengine/verl.git && \ + cd verl && \ + pip install -e . +########################################## +########################################## +########################################## + + + +WORKDIR /workspace/ + +CMD ["/usr/bin/bash"] diff --git a/verl/docker/Dockerfile.rocm7 b/verl/docker/Dockerfile.rocm7 new file mode 100644 index 0000000000000000000000000000000000000000..d92001b3f98b263887b2989872bbd35c436ed28a --- /dev/null +++ b/verl/docker/Dockerfile.rocm7 @@ -0,0 +1,141 @@ +# default base image +ARG REMOTE_VLLM="1" +ARG COMMON_WORKDIR=/app +ARG BASE_IMAGE=rocm/vllm-dev:base_rocm7_0930_rc1_20250916_tuned_20250917 + +FROM ${BASE_IMAGE} AS base + +ARG ARG_PYTORCH_ROCM_ARCH +ENV PYTORCH_ROCM_ARCH=${ARG_PYTORCH_ROCM_ARCH:-${PYTORCH_ROCM_ARCH}} + +# Install some basic utilities +RUN apt-get update -q -y && apt-get install -q -y \ + sqlite3 libsqlite3-dev libfmt-dev libmsgpack-dev libsuitesparse-dev \ + apt-transport-https ca-certificates wget curl +# Remove sccache +RUN python3 -m pip install --upgrade pip +RUN apt-get purge -y sccache; python3 -m pip uninstall -y sccache; rm -f "$(which sccache)" +ARG COMMON_WORKDIR +WORKDIR ${COMMON_WORKDIR} + + +# ----------------------- +# vLLM fetch stages +FROM base AS fetch_vllm_0 +ONBUILD COPY ./ vllm/ +FROM base AS fetch_vllm_1 +#ARG VLLM_REPO="https://github.com/ROCm/vllm.git" +#ARG VLLM_BRANCH="main" +ARG VLLM_REPO=https://github.com/HollowMan6/vllm.git +ARG VLLM_BRANCH="sleep_amd" +ONBUILD RUN git clone ${VLLM_REPO} \ + && cd vllm \ + && git checkout ${VLLM_BRANCH} +FROM fetch_vllm_${REMOTE_VLLM} AS fetch_vllm + +# ----------------------- +# vLLM build stages +FROM fetch_vllm AS build_vllm +# Build vLLM +RUN cd vllm \ + && python3 -m pip install -r requirements/rocm.txt \ + && python3 setup.py clean --all \ + && ln -sf /opt/rocm/lib/libamdhip64.so /usr/lib/libamdhip64.so \ + && VLLM_TARGET_DEVICE=rocm ROCM_PATH=/opt/rocm/ VLLM_GPU_LANG=HIP SETUPTOOLS_SCM_PRETEND_VERSION=0.8.4.dev python3 setup.py bdist_wheel --dist-dir=dist + #&& python3 setup.py bdist_wheel --dist-dir=dist +FROM scratch AS export_vllm +ARG COMMON_WORKDIR +COPY --from=build_vllm ${COMMON_WORKDIR}/vllm/dist/*.whl / +COPY --from=build_vllm ${COMMON_WORKDIR}/vllm/requirements /requirements +COPY --from=build_vllm ${COMMON_WORKDIR}/vllm/benchmarks /benchmarks +COPY --from=build_vllm ${COMMON_WORKDIR}/vllm/tests /tests +COPY --from=build_vllm ${COMMON_WORKDIR}/vllm/examples /examples +COPY --from=build_vllm ${COMMON_WORKDIR}/vllm/.buildkite /.buildkite + +# ----------------------- +# Test vLLM image +FROM base AS test + +RUN python3 -m pip install --upgrade pip && rm -rf /var/lib/apt/lists/* + +# Install vLLM +RUN --mount=type=bind,from=export_vllm,src=/,target=/install \ + cd /install \ + && pip install -U -r requirements/rocm.txt \ + && pip install -U -r requirements/rocm-test.txt \ + && pip uninstall -y vllm \ + && pip install *.whl + +WORKDIR /vllm-workspace +ARG COMMON_WORKDIR +COPY --from=build_vllm ${COMMON_WORKDIR}/vllm /vllm-workspace + +# install development dependencies (for testing) +RUN cd /vllm-workspace \ + && rm -rf vllm \ + && python3 -m pip install -e tests/vllm_test_utils \ + && python3 -m pip install lm-eval[api]==0.4.4 \ + && python3 -m pip install pytest-shard + +# ----------------------- +# Final vLLM image +FROM base AS final + +RUN python3 -m pip install --upgrade pip && rm -rf /var/lib/apt/lists/* +# Error related to odd state for numpy 1.20.3 where there is no METADATA etc, but an extra LICENSES_bundled.txt. +# Manually remove it so that later steps of numpy upgrade can continue +RUN case "$(which python3)" in \ + *"/opt/conda/envs/py_3.9"*) \ + rm -rf /opt/conda/envs/py_3.9/lib/python3.9/site-packages/numpy-1.20.3.dist-info/;; \ + *) ;; esac + +RUN python3 -m pip install --upgrade huggingface-hub[cli] + +# Install vLLM +RUN --mount=type=bind,from=export_vllm,src=/,target=/install \ + cd /install \ + && pip install -U -r requirements/rocm.txt \ + && pip uninstall -y vllm \ + && pip install *.whl + +ARG COMMON_WORKDIR + +# Copy over the benchmark scripts as well +COPY --from=export_vllm /benchmarks ${COMMON_WORKDIR}/vllm/benchmarks +COPY --from=export_vllm /examples ${COMMON_WORKDIR}/vllm/examples + +ENV RAY_EXPERIMENTAL_NOSET_ROCR_VISIBLE_DEVICES=1 +ENV TOKENIZERS_PARALLELISM=false + +# ENV that can improve safe tensor loading, and end-to-end time +ENV SAFETENSORS_FAST_GPU=1 + +# Performance environment variable. +ENV HIP_FORCE_DEV_KERNARG=1 + +# ----------------------- +# Install verl +RUN pip install "tensordict==0.6.2" --no-deps && \ + pip install accelerate \ + codetiming \ + datasets \ + dill \ + hydra-core \ + liger-kernel \ + numpy \ + pandas \ + peft \ + "pyarrow>=15.0.0" \ + pylatexenc \ + torchdata \ + wandb \ + orjson \ + pybind11 + +WORKDIR /workspace/ +RUN git clone https://github.com/volcengine/verl.git && \ + cd verl && \ + pip install -e . + +CMD ["/bin/bash"] + diff --git a/verl/docker/Dockerfile.rocm_verl-0.3.0.post1 b/verl/docker/Dockerfile.rocm_verl-0.3.0.post1 new file mode 100644 index 0000000000000000000000000000000000000000..185096d9d2e83fc235f04e70260fd3dbfca7dd1c --- /dev/null +++ b/verl/docker/Dockerfile.rocm_verl-0.3.0.post1 @@ -0,0 +1,58 @@ +# Build the docker in the repo dir: +# docker build -f docker/Dockerfile.rocm -t verl-rocm:03.04.2015 . +# docker images # you can find your built docker + + +# Support - Traing: fsdp; Inference: vllm +# FROM rocm/vllm:rocm6.2_mi300_ubuntu20.04_py3.9_vllm_0.6.4 +# Support - Traing: fsdp; Inference: vllm, sglang +FROM lmsysorg/sglang:v0.4.6.post5-rocm630 + +# Set working directory +# WORKDIR $PWD/app + +# Set environment variables +ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942" + +ENV HIPCC_COMPILE_FLAGS_APPEND="--amdgpu-target=gfx90a;gfx942 -D__HIP_PLATFORM_AMD__" +ENV CFLAGS="-D__HIP_PLATFORM_AMD__" +ENV CXXFLAGS="-D__HIP_PLATFORM_AMD__" + +# Install vllm +RUN pip uninstall -y vllm && \ + rm -rf vllm && \ + git clone -b v0.6.3 https://github.com/vllm-project/vllm.git && \ + cd vllm && \ + MAX_JOBS=$(nproc) python3 setup.py install && \ + cd .. && \ + rm -rf vllm + +# Copy the entire project directory +COPY . . + +# Install dependencies +RUN pip install "tensordict==0.6.2" --no-deps && \ + pip install accelerate \ + codetiming \ + datasets \ + dill \ + hydra-core \ + liger-kernel \ + numpy \ + pandas \ + peft \ + "pyarrow>=15.0.0" \ + pylatexenc \ + "ray[data,train,tune,serve]<2.45.0" \ + torchdata \ + transformers \ + wandb \ + orjson \ + pybind11 + +RUN git clone https://github.com/volcengine/verl.git && \ + cd verl && \ + pip install -e . + +# Install torch_memory_saver +RUN pip install git+https://github.com/ExtremeViscent/torch_memory_saver.git --no-deps diff --git a/verl/docker/Dockerfile.rocm_verl-0.4.1 b/verl/docker/Dockerfile.rocm_verl-0.4.1 new file mode 100644 index 0000000000000000000000000000000000000000..57621b248ce8cab819c748df42e0e056b489062f --- /dev/null +++ b/verl/docker/Dockerfile.rocm_verl-0.4.1 @@ -0,0 +1,323 @@ +# FROM "compute-artifactory.amd.com:5000/rocm-plus-docker/framework/compute-rocm-rel-6.4:94_ubuntu22.04_py3.10_pytorch_release-2.7_575e247" +# FROM "rlfoundation.azurecr.io/rocm6.3.4:vllm-0.8.5-numa-patch-ubuntu-22.04" +FROM "rlsys/rocm-6.3.4-patch:rocm6.3.4-numa-patch_ubuntu-22.04" + +SHELL ["/bin/bash", "-ceuxo", "pipefail"] + +ENV MAX_JOBS=512 + +ENV PATH="/usr/local/python3.12/bin:$PATH" +RUN ln -sf /usr/bin/python3.12 /usr/bin/python && \ + ln -sf /usr/bin/pip3.12 /usr/bin/pip + +############################################ +############################################ +RUN apt-get update +RUN apt-get install -y pkg-config liblzma-dev +############################################ +############################################ + + +########################################### +##########Install TransformerEngine######## +########################################### +WORKDIR /workspace/ +# transformer-engine install +# https://github.com/ROCm/TransformerEngine + +RUN rm -rf TransformerEngine +RUN git clone --recursive https://github.com/ROCm/TransformerEngine.git +WORKDIR /workspace/TransformerEngine +RUN git checkout 236178e5 +# git checkout bb061ade +# git checkout 864405c + +ENV NVTE_FRAMEWORK=pytorch +ENV NVTE_ROCM_ARCH=gfx942 +ENV NVTE_USE_HIPBLASLT=1 +ENV NVTE_USE_ROCM=1 + +# export CMAKE_PREFIX_PATH="/opt/rocm:/opt/rocm/hip:/usr/local:/usr:${CMAKE_PREFIX_PATH:-}" +ENV CMAKE_PREFIX_PATH="/opt/rocm:/opt/rocm/hip:/usr/local:/usr" + + +# ENV NVTE_BUILD_MAX_JOBS=$(MAX_JOBS) + +RUN MAX_JOBS=$(MAX_JOBS) pip install . -vvv + +WORKDIR /workspace/ +########################################### +########################################### +########################################### + + + + + +#################################################################################### +################Install vllm - sglang require vllm 0.6.7 dependency################# +#################################################################################### +#### Require vllm 0.6.7 - checkout 113274a0 +WORKDIR /workspace/ +RUN rm -rf vllm +RUN pip uninstall -y vllm +# Refer to here (down-grade vllm to 0.6.3): https://docs.vllm.ai/en/v0.6.3/getting_started/amd-installation.html +RUN git clone https://github.com/ROCm/vllm.git +# git clone https://github.com/vllm-project/vllm.git +WORKDIR /workspace/vllm +RUN git checkout 113274a0 +ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942" +#ENV MAX_JOBS=512 +ENV MAX_JOBS=${MAX_JOBS} +RUN pip install "boto3>=1.26.0" +RUN pip install setuptools_scm +# will add src into py. You can delete the repo +RUN python3 setup.py install +WORKDIR /workspace/ +#################################################################################### +#################################################################################### +#################################################################################### + + + +########################################### +############For hack docker################ +########################################### +RUN pip install setuptools==75.8.0 +########################################### +########################################### +########################################### + + + +########################################### +############build sgalng################### +########################################### +# Set environment variables +ENV BASE_DIR=/sgl-workspace +ENV BUILD_TYPE=all +ENV SGL_REPO=https://github.com/sgl-project/sglang +ENV SGL_BRANCH=v0.4.6.post5 +ENV TRITON_REPO=https://github.com/ROCm/triton.git +ENV TRITON_COMMIT=improve_fa_decode_3.0.0 +ENV AITER_REPO=https://github.com/ROCm/aiter.git +ENV AITER_COMMIT=v0.1.2 +# v0.1.2 version - commit id: 9d11f47 +# ENV AITER_COMMIT=9d11f47 + +ENV HIP_FORCE_DEV_KERNARG=1 +ENV HSA_NO_SCRATCH_RECLAIM=1 +ENV SGLANG_SET_CPU_AFFINITY=1 +ENV SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 +ENV NCCL_MIN_NCHANNELS=112 +ENV MOE_PADDING=1 +ENV VLLM_FP8_PADDING=1 +ENV VLLM_FP8_ACT_PADDING=1 +ENV VLLM_FP8_WEIGHT_PADDING=1 +ENV VLLM_FP8_REDUCE_CONV=1 +ENV TORCHINDUCTOR_MAX_AUTOTUNE=1 +ENV TORCHINDUCTOR_MAX_AUTOTUNE_POINTWISE=1 +ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942" +ENV AMDGPU_TARGETS=gfx942 +ENV ROCM_ARCH=gfx942 +ENV PYTORCH_ROCM_ARCH="gfx90a;gfx942" + +# Switch to working directory +WORKDIR /sgl-workspace + +# Clean and create directory +RUN rm -rf /sgl-workspace && mkdir -p /sgl-workspace + +# Clone and build sglang +RUN git clone ${SGL_REPO} \ + && cd sglang \ + && git checkout ${SGL_BRANCH} || echo "Using default branch" \ + && cd sgl-kernel \ + && rm -f pyproject.toml \ + && mv pyproject_rocm.toml pyproject.toml \ + && python setup_rocm.py install \ + && cd .. \ + && if [ "$BUILD_TYPE" = "srt" ]; then \ + python -m pip --no-cache-dir install -e "python[srt_hip]"; \ + else \ + python -m pip --no-cache-dir install -e "python[all_hip]"; \ + fi \ + && cd /sgl-workspace \ + && cp -r /sgl-workspace/sglang /sglang \ + && python -m pip cache purge + +# Install common Python packages +RUN pip install IPython orjson python-multipart torchao pybind11 + +# Rebuild Triton +RUN pip uninstall -y triton || true \ + && git clone ${TRITON_REPO} \ + && cd triton \ + && git checkout ${TRITON_COMMIT} \ + && cd python \ + && python3 setup.py install \ + && cd /sgl-workspace + + +# ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942 --amdgpu-lower-module-lds-strategy=1" +# ENV HIPCC_COMPILE_FLAGS_APPEND="--offload-arch=gfx942" + +# Build aiter +#version: Commit 9d11f47 + # && git checkout ${AITER_COMMIT} \ +RUN pip uninstall -y aiter || true +RUN git clone ${AITER_REPO} \ + && cd aiter \ + && git checkout ${AITER_COMMIT} \ + && git submodule sync \ + && git submodule update --init --recursive \ + && PREBUILD_KERNELS=1 GPU_ARCHS=gfx942 python3 setup.py install \ + && cd /sgl-workspace + # && PREBUILD_KERNELS=1 GPU_ARCHS=gfx942 python3 setup.py develop \ + # && PREBUILD_KERNELS=1 GPU_ARCHS=gfx942 python3 setup.py develop \ + +# Copy MI300X config +RUN find /sgl-workspace/sglang/python/sglang/srt/layers/quantization/configs/ \ + /sgl-workspace/sglang/python/sglang/srt/layers/moe/fused_moe_triton/configs/ \ + -type f -name '*MI300X*' | \ + xargs -I {} sh -c 'vf_config=$(echo "$1" | sed "s/MI300X/MI300X_VF/"); cp "$1" "$vf_config"' -- {} + +# Environment setup complete. +RUN echo "Environment setup complete." + +WORKDIR /workspace/ +########################################### +########################################### +########################################### + + + + + + +########################################### +###############vllm v0.8.5################# +########################################### +# ENV GITHUB_USERNAME=yushengsu-thu +# ENV GITHUB_MAIL=yushengsu@gmail.com + +# RUN git config --global user.name "${GITHUB_USERNAME}" \ +# && git config --global user.email "${GITHUB_MAIL}" + +WORKDIR /workspace/ + +ENV VLLM_TARGET_DEVICE=rocm +ENV ROCM_PATH=/opt/rocm +ENV SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev + +# Find the repo path in: DockerFile/Dockerfile.rocm_yang +# RUN git clone https://github.com/RLFoundation/vllm-patch.git +RUN pip uninstall -y vllm || true +RUN rm -rf vllm-patch +RUN git clone https://github.com/RLFoundation/vllm-patch.git \ + && cd vllm-patch \ + && git checkout v0.8.5-sleep-numa \ + && rm -rf build/ dist/ *.egg-info \ + && ln -sf /opt/rocm/lib/libamdhip64.so /usr/lib/libamdhip64.so \ + && SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev PYTORCH_ROCM_ARCH="gfx90a;gfx942" MAX_JOBS=${MAX_JOBS} python3 setup.py install + # RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.8.5.dev PYTORCH_ROCM_ARCH="gfx90a;gfx942" MAX_JOBS=${MAX_JOBS} python3 setup.py develop + +WORKDIR /workspace/ +########################################### +########################################### +########################################### + + + + +######################################### +#### Install megatron-core############### +######################################### +RUN pip uninstall -y megatron-core && \ + git clone https://github.com/yushengsu-thu/Megatron-LM-amd_version.git && \ + cd Megatron-LM-amd_version && \ + pip install -vvv -e . && \ + cd /workspace/ +######################################### +######################################### +######################################### + + + + +####################################### +################apex################### +####################################### +WORKDIR /workspace/ +RUN pip uninstall -y apex && \ + git clone https://github.com/ROCm/apex.git && \ + cd apex && \ + python setup.py install && \ + cd /workspace/ +####################################### +####################################### +####################################### + + + + +################################################################################ +###########################Add torch_memory_saver############################### +################################################################################ +# Set environment variables +ENV HIPCC_COMPILE_FLAGS_APPEND="--amdgpu-target=gfx90a;gfx942 -D__HIP_PLATFORM_AMD__" +ENV CFLAGS="-D__HIP_PLATFORM_AMD__" +ENV CXXFLAGS="-D__HIP_PLATFORM_AMD__" +RUN pip install "git+https://github.com/YangWang92/torch_memory_saver_numa.git@numa" +################################################################################ +################################################################################ +################################################################################ + + + +######################################## +######Install ray####################### +######################################## +# need to add this patch: https://github.com/ray-project/ray/pull/53531/files +RUN pip uninstall ray -y +RUN pip install "ray[data,train,tune,serve]>=2.47.0" +######################################## +######################################## +######################################## + + + +########################################## +#######Install other dependencies######### +########################################## +RUN pip install "tensordict==0.6.2" --no-deps && \ + pip install accelerate \ + codetiming \ + datasets \ + dill \ + hydra-core \ + liger-kernel \ + numpy \ + pandas \ + peft \ + "pyarrow>=15.0.0" \ + pylatexenc \ + torchdata \ + wandb \ + orjson \ + pybind11 + +WORKDIR /workspace/ +RUN git clone https://github.com/volcengine/verl.git && \ + cd verl && \ + pip install -e . +########################################## +########################################## +########################################## + + + +WORKDIR /workspace/ + +CMD ["/usr/bin/bash"] +CMD ["/usr/bin/bash"] diff --git a/verl/docker/Dockerfile.sglang b/verl/docker/Dockerfile.sglang new file mode 100644 index 0000000000000000000000000000000000000000..11ad4a77da682e1f0de33bbed1007e9aefed7b21 --- /dev/null +++ b/verl/docker/Dockerfile.sglang @@ -0,0 +1,55 @@ +# Start from the NVIDIA official image (ubuntu-22.04 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 + +# Define environments +ENV MAX_JOBS=32 +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.ustc.edu.cn/ubuntu/ + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini && \ + apt-get clean + +# Change pip source +ARG PIP_INDEX=https://mirrors.aliyun.com/pypi/simple/ + +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Install sglang-0.4.6.post5 and torch-memory-saver +RUN pip uninstall -y cuda-python && pip install "sglang[all]==0.4.6.post5" --no-cache-dir --find-links https://flashinfer.ai/whl/cu124/torch2.6/flashinfer-python && pip install torch-memory-saver --no-cache-dir + +# Install torch-2.6.0 +RUN pip install --no-cache-dir torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 tensordict torchdata \ + transformers>=4.49.0 accelerate datasets peft hf_transfer \ + ray[default] codetiming hydra-core pandas pyarrow>=15.0.0 pylatexenc qwen-vl-utils wandb liger-kernel \ + pytest pre-commit py-spy pyext + +# Install flash_attn-2.7.4.post1 +RUN pip uninstall -y transformer-engine flash-attn && \ + wget -v https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \ + pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl + +# Fix cv2 +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --no-cache-dir nvidia-ml-py>=12.560.30 opencv-python-headless==4.8.0.74 fastapi==0.115.6 diff --git a/verl/docker/Dockerfile.vemlp.vllm.te b/verl/docker/Dockerfile.vemlp.vllm.te new file mode 100644 index 0000000000000000000000000000000000000000..361fb2084ff4ecea1f48d22acda487d620080ca4 --- /dev/null +++ b/verl/docker/Dockerfile.vemlp.vllm.te @@ -0,0 +1,41 @@ +# docker buildx build --platform linux/x86_64 -t "verlai/verl:$TAG" -f docker/$FILE . + +# the one in docker.io is an alias for the one veturbo +# FROM vemlp-cn-beijing.cr.volces.com/veturbo/pytorch:2.4-cu124 +FROM docker.io/haibinlin/verl:v0.0.5-th2.4.0-cu124-base + +# only config pip index with https://pypi.tuna.tsinghua.edu.cn/simple if needed +# unset for now +RUN pip3 config unset global.index-url + +# transformers 4.47.0 contains the following bug: +# AttributeError: 'Gemma2Attention' object has no attribute '_flash_attn_uses_top_left_mask' +RUN pip3 install --no-cache-dir \ + torch==2.4.0 \ + accelerate \ + codetiming \ + dill \ + hydra-core \ + numpy \ + pybind11 \ + tensordict \ + "transformers <= 4.46.0" + +RUN pip3 install --no-cache-dir flash-attn==2.7.0.post2 --no-build-isolation + +# vllm depends on ray +RUN pip3 install --no-cache-dir vllm==0.6.3 ray==2.10 + +# install apex +RUN MAX_JOBS=4 pip3 install -v --disable-pip-version-check --no-cache-dir --no-build-isolation \ + --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" \ + git+https://github.com/NVIDIA/apex + +# install Transformer Engine +# - flash-attn pinned to 2.5.3 by TransformerEngine, switch to eric-haibin-lin/TransformerEngine.git@v1.7.0 to relax version req +# - install with: MAX_JOBS=1 NINJA_FLAGS="-j1" TE_BUILD_WITH_NINJA=0 to avoid OOM +# - cudnn is required by TransformerEngine +# RUN CUDNN_PATH=/opt/conda/lib/python3.11/site-packages/nvidia/cudnn \ +# pip3 install git+https://github.com/eric-haibin-lin/TransformerEngine.git@v1.7.0 +RUN MAX_JOBS=1 NINJA_FLAGS="-j1" pip3 install flash-attn==2.5.3 --no-cache-dir --no-build-isolation +RUN MAX_JOBS=1 NINJA_FLAGS="-j1" pip3 install git+https://github.com/NVIDIA/TransformerEngine.git@v1.7 diff --git a/verl/docker/Dockerfile.vllm.sglang.megatron.deepseek b/verl/docker/Dockerfile.vllm.sglang.megatron.deepseek new file mode 100644 index 0000000000000000000000000000000000000000..366286f882f7b393ee2c79304b1b659449d4b1ae --- /dev/null +++ b/verl/docker/Dockerfile.vllm.sglang.megatron.deepseek @@ -0,0 +1,115 @@ +# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini aria2 && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + xgboost transformer_engine flash_attn apex megatron-core grpcio + +# Reinstall CUDA 12.4 +RUN aria2c https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin && \ + mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 + +RUN aria2c --always-resume=true --max-tries=99999 https://developer.download.nvidia.com/compute/cuda/12.4.1/local_installers/cuda-repo-ubuntu2204-12-4-local_12.4.1-550.54.15-1_amd64.deb && \ + dpkg -i cuda-repo-ubuntu2204-12-4-local_12.4.1-550.54.15-1_amd64.deb && \ + cp /var/cuda-repo-ubuntu2204-12-4-local/cuda-*-keyring.gpg /usr/share/keyrings/ && \ + apt-get update && \ + apt-get -y install cuda-toolkit-12-4 && \ + rm cuda-repo-ubuntu2204-12-4-local_12.4.1-550.54.15-1_amd64.deb && \ + update-alternatives --set cuda /usr/local/cuda-12.4 && \ + rm -rf /usr/local/cuda-12.6 + +# Install torch-2.6.0+cu124 + vllm-0.8.5.post1 + sglang-0.4.6.post5 +# torch-2.6.0+cu124: cxx11abi=False +# torch-2.6.0+cu126: cxx11abi=True +# see https://github.com/flashinfer-ai/flashinfer/issues/911 +# Install sglang-0.4.6.post1 and torch-memory-saver +RUN pip install --resume-retries 999 "sglang[all]==0.4.6.post5" --no-cache-dir --find-links https://flashinfer.ai/whl/cu124/torch2.6/flashinfer-python && pip install --resume-retries 999 torch-memory-saver --no-cache-dir + +RUN pip install --resume-retries 999 --no-cache-dir "vllm==0.8.5.post1" "torch==2.6.0" "torchvision==0.21.0" "torchaudio==2.6.0" "tensordict==0.6.2" torchdata + +RUN pip install --resume-retries 999 --no-cache-dir "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=15.0.0" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile \ + pytest py-spy pyext pre-commit ruff + +# Install flash-attn-2.7.4.post1 (cxx11abi=False) +RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \ + pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl + +# Fix packages +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +# Install cudnn +RUN aria2c --max-tries=9999 https://developer.download.nvidia.com/compute/cudnn/9.8.0/local_installers/cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + dpkg -i cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + cp /var/cudnn-local-repo-ubuntu2204-9.8.0/cudnn-*-keyring.gpg /usr/share/keyrings/ && \ + apt-get update && \ + apt-get -y install cudnn-cuda-12 && \ + rm cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install Apex +RUN git clone https://github.com/NVIDIA/apex.git && \ + cd apex && \ + pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" ./ + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --no-deps --no-cache-dir git+https://github.com/NVIDIA/TransformerEngine.git@v2.3 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Fix opencv +RUN pip install opencv-python + +RUN pip install opencv-fixer && \ + python -c "from opencv_fixer import AutoFix; AutoFix()" + +# Install verl + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url + + RUN apt-get update && \ + apt-get install -y aria2 libfreeimage3 libfreeimage-dev zlib1g \ No newline at end of file diff --git a/verl/docker/README.md b/verl/docker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c392923bbfbc3ebcd8516c4ed22afdfab64d1a05 --- /dev/null +++ b/verl/docker/README.md @@ -0,0 +1,70 @@ +# Dockerfiles of verl + +We provide pre-built Docker images for quick setup. And from this version, we utilize a new image release hierarchy for productivity and stability. + +The image types are divided into three large categories: + +- **Base Image**: Without inference and training frameworks, only basic dependencies are installed. Can directly install vllm or SGLang on top of it, without need of reinstall torch or CUDA. +- **Application Image**: Stable version with inference and training frameworks installed. +- **Preview Image**: Unstable version with the latest frameworks and features. + +The first two types of images are hosted on dockerhub [verlai/verl](https://hub.docker.com/r/verlai/verl) repository, while the preview images are hosted on community repository. + +> The image versions are mapped with verl releases, for example, image with tag ``verl0.4`` is built for verl release ``v0.4.x``. + +## Base Image + +The stable base image is ``verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.7.4`` with different CUDA versions. + +The update of base image is not frequent, and the app image can be built on top of it without reinstalling base packages. + +## Application Image + +From this version, we divide images built for vLLM and SGLang as the divergence of dependent packages like FlashInfer. +There are 2 types of application images available: + +- **vLLM with FSDP and Megatron**: ``verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2`` +- **SGLang with FSDP and Megatron**: `verlai/verl:app-verl0.5-transformers4.55.4-sglang0.4.10.post2-mcore0.13.0-te2.2` + +Docker images with Megatron backends are runnable with large language model like ``Qwen/Qwen3-235B-A22B``, ``deepseek-ai/DeepSeek-V3-0324`` post-training. Refer to the :doc:`Large Language Model Post-Training documentation<../perf/dpsk>` for more details. + +Application images can be updated frequently, and the Dockerfile can be found in ``docker/verl[version]-[packages]/Dockerfile.app.[frameworks]``. Based on the base image, it is easy to build your own application image with the desired inference and training frameworks. + +## Community Image + +For vLLM with FSDP, please refer to [hiyouga/verl](https://hub.docker.com/r/hiyouga/verl) repository and the latest version is ``hiyouga/verl:ngc-th2.6.0-cu126-vllm0.8.4-flashinfer0.2.2-cxx11abi0``. + +For SGLang with FSDP, please refer to [ocss884/verl-sglang](https://hub.docker.com/r/ocss884/verl-sglang) repository and the latest version is ``ocss884/verl-sglang:ngc-th2.6.0-cu126-sglang0.4.6.post5`` which is provided by SGLang RL Group. + +See files under ``docker/`` for NGC-based image or if you want to build your own. + +Note that For aws instances with EFA net interface (Sagemaker AI Pod), you need to install EFA driver as shown in ``docker/Dockerfile.extenstion.awsefa`` + +## Installation from Docker + +After pulling the desired Docker image and installing desired inference and training frameworks, you can run it with the following steps: + +1. Launch the desired Docker image and attach into it: + +```sh +docker create --runtime=nvidia --gpus all --net=host --shm-size="10g" --cap-add=SYS_ADMIN -v .:/workspace/verl --name verl sleep infinity +docker start verl +docker exec -it verl bash +``` + +2. If you use the images provided, you only need to install verl itself without dependencies: + +```sh +# install the nightly version (recommended) +git clone https://github.com/volcengine/verl && cd verl +pip3 install --no-deps -e . +``` + +[Optional] If you hope to switch between different frameworks, you can install verl with the following command: + +```sh +# install the nightly version (recommended) +git clone https://github.com/volcengine/verl && cd verl +pip3 install -e .[vllm] +pip3 install -e .[sglang] +``` diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.12 b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.12 new file mode 100644 index 0000000000000000000000000000000000000000..68c3e1a043b3955f3773ca1665de5d8d1dd4fc17 --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.12 @@ -0,0 +1,41 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.4-cu124-cudnn9.8-torch2.6-fa2.7.4 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.6.post5 and torch-memory-saver +RUN pip install --resume-retries 999 "sglang[all]==0.4.6.post5" --no-cache-dir --find-links https://flashinfer.ai/whl/cu124/torch2.6/flashinfer-python && pip install torch-memory-saver --no-cache-dir + +# Some sglang operations in 0.4.6.post5 require vllm +# [Warning] vllm can have some packages not compatible with sglang, for example, flashinfer +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.8.5.post1 + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Fix for transformers 4.53.0 +RUN pip3 install --no-cache-dir "transformers[hf_xet]<4.52.0" + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge \ No newline at end of file diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.12.deepep b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.12.deepep new file mode 100644 index 0000000000000000000000000000000000000000..f08aeee9c7389f036e4b8ca032209495d9f5bffe --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.12.deepep @@ -0,0 +1,82 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.4-cu124-cudnn9.8-torch2.6-fa2.7.4 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.6.post5 and torch-memory-saver +RUN pip install --resume-retries 999 "sglang[all]==0.4.6.post5" --no-cache-dir --find-links https://flashinfer.ai/whl/cu124/torch2.6/flashinfer-python && pip install torch-memory-saver --no-cache-dir + +# Some sglang operations in 0.4.6.post5 require vllm +# [Warning] vllm can have some packages not compatible with sglang, for example, flashinfer +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.8.5.post1 + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Fix for transformers 4.53.0 +RUN pip3 install --no-cache-dir "transformers[hf_xet]<4.52.0" + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge + +# Install DeepEP +## the dependency of IBGDA +RUN ln -s /usr/lib/x86_64-linux-gnu/libmlx5.so.1 /usr/lib/x86_64-linux-gnu/libmlx5.so + +## Clone and build deepep and deepep-nvshmem +RUN git clone -b v2.3.1 https://github.com/NVIDIA/gdrcopy.git && \ + git clone https://github.com/deepseek-ai/DeepEP.git && \ + cd DeepEP && git checkout a84a248 + +# Prepare nvshmem +RUN wget https://developer.nvidia.com/downloads/assets/secure/nvshmem/nvshmem_src_3.2.5-1.txz && \ + tar -xvf nvshmem_src_3.2.5-1.txz && mv nvshmem_src deepep-nvshmem && \ + cd deepep-nvshmem && git apply ../DeepEP/third-party/nvshmem.patch + +ENV CUDA_HOME=/usr/local/cuda +### Set MPI environment variables. Having errors when not set. +ENV CPATH=/usr/local/mpi/include:$CPATH +ENV LD_LIBRARY_PATH=/usr/local/mpi/lib:$LD_LIBRARY_PATH +ENV LD_LIBRARY_PATH=/usr/local/x86_64-linux-gnu:$LD_LIBRARY_PATH +ENV GDRCOPY_HOME=/workspace/gdrcopy + +## Build deepep-nvshmem +RUN cd deepep-nvshmem && \ + NVSHMEM_SHMEM_SUPPORT=0 \ + NVSHMEM_UCX_SUPPORT=0 \ + NVSHMEM_USE_NCCL=0 \ + NVSHMEM_MPI_SUPPORT=0 \ + NVSHMEM_IBGDA_SUPPORT=1 \ + NVSHMEM_PMIX_SUPPORT=0 \ + NVSHMEM_TIMEOUT_DEVICE_POLLING=0 \ + NVSHMEM_USE_GDRCOPY=1 \ + cmake -G Ninja -S . -B build/ -DCMAKE_INSTALL_PREFIX=/workspace/deepep-nvshmem/install && cmake --build build/ --target install + +ENV NVSHMEM_DIR=/workspace/deepep-nvshmem/install +ENV LD_LIBRARY_PATH=$NVSHMEM_DIR/lib:$LD_LIBRARY_PATH +ENV PATH=$NVSHMEM_DIR/bin:$PATH + +## Build deepep +RUN cd DeepEP && \ + python setup.py install \ No newline at end of file diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.13.preview b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.13.preview new file mode 100644 index 0000000000000000000000000000000000000000..0e0bdd43fec1eac3e4a85de5416e34fad4ac7c69 --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.sglang.vllm.mcore0.13.preview @@ -0,0 +1,82 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.4-cu124-cudnn9.8-torch2.6-fa2.7.4 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.6.post5 and torch-memory-saver +RUN pip install --resume-retries 999 "sglang[all]==0.4.6.post5" --no-cache-dir --find-links https://flashinfer.ai/whl/cu124/torch2.6/flashinfer-python && pip install torch-memory-saver --no-cache-dir + +# Some sglang operations in 0.4.6.post5 require vllm +# [Warning] vllm can have some packages not compatible with sglang, for example, flashinfer +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.8.5.post1 + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@release_v2.5 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_r0.13.0 + +# Fix for transformers 4.53.0 +RUN pip3 install --no-cache-dir "transformers[hf_xet]<4.52.0" + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge + +# Install DeepEP +## the dependency of IBGDA +RUN ln -s /usr/lib/x86_64-linux-gnu/libmlx5.so.1 /usr/lib/x86_64-linux-gnu/libmlx5.so + +## Clone and build deepep and deepep-nvshmem +RUN git clone -b v2.3.1 https://github.com/NVIDIA/gdrcopy.git && \ + git clone https://github.com/deepseek-ai/DeepEP.git && \ + cd DeepEP && git checkout a84a248 + +# Prepare nvshmem +RUN wget https://developer.nvidia.com/downloads/assets/secure/nvshmem/nvshmem_src_3.2.5-1.txz && \ + tar -xvf nvshmem_src_3.2.5-1.txz && mv nvshmem_src deepep-nvshmem && \ + cd deepep-nvshmem && git apply ../DeepEP/third-party/nvshmem.patch + +ENV CUDA_HOME=/usr/local/cuda +### Set MPI environment variables. Having errors when not set. +ENV CPATH=/usr/local/mpi/include:$CPATH +ENV LD_LIBRARY_PATH=/usr/local/mpi/lib:$LD_LIBRARY_PATH +ENV LD_LIBRARY_PATH=/usr/local/x86_64-linux-gnu:$LD_LIBRARY_PATH +ENV GDRCOPY_HOME=/workspace/gdrcopy + +## Build deepep-nvshmem +RUN cd deepep-nvshmem && \ + NVSHMEM_SHMEM_SUPPORT=0 \ + NVSHMEM_UCX_SUPPORT=0 \ + NVSHMEM_USE_NCCL=0 \ + NVSHMEM_MPI_SUPPORT=0 \ + NVSHMEM_IBGDA_SUPPORT=1 \ + NVSHMEM_PMIX_SUPPORT=0 \ + NVSHMEM_TIMEOUT_DEVICE_POLLING=0 \ + NVSHMEM_USE_GDRCOPY=1 \ + cmake -G Ninja -S . -B build/ -DCMAKE_INSTALL_PREFIX=/workspace/deepep-nvshmem/install && cmake --build build/ --target install + +ENV NVSHMEM_DIR=/workspace/deepep-nvshmem/install +ENV LD_LIBRARY_PATH=$NVSHMEM_DIR/lib:$LD_LIBRARY_PATH +ENV PATH=$NVSHMEM_DIR/bin:$PATH + +## Build deepep +RUN cd DeepEP && \ + python setup.py install \ No newline at end of file diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.12 b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.12 new file mode 100644 index 0000000000000000000000000000000000000000..616c701c523a76eb11cfe8364a40ca7329023f73 --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.12 @@ -0,0 +1,47 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.4-cu124-cudnn9.8-torch2.6-fa2.7.4 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install torch-2.6.0+cu124 + vllm-0.8.5.post1 +# torch-2.6.0+cu124: cxx11abi=False +# torch-2.6.0+cu126: cxx11abi=True +# see https://github.com/flashinfer-ai/flashinfer/issues/911 +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.8.5.post1 + +# Install flashinfer-0.2.2.post1+cu126 (cxx11abi=True) +# vllm-0.8.3 does not support flashinfer>=0.2.3 +# see https://github.com/vllm-project/vllm/pull/15777 +RUN aria2c --max-tries=9999 https://github.com/flashinfer-ai/flashinfer/releases/download/v0.2.2.post1/flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \ + pip install --no-cache-dir flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \ + rm flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Fix for transformers 4.53.0 +RUN pip3 install --no-cache-dir "transformers[hf_xet]<4.52.0" + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge \ No newline at end of file diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.12.deepep b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.12.deepep new file mode 100644 index 0000000000000000000000000000000000000000..a2be5e998dd32a2bcfbdcc63bedd2dd1ae634943 --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.12.deepep @@ -0,0 +1,88 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.4-cu124-cudnn9.8-torch2.6-fa2.7.4 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install torch-2.6.0+cu124 + vllm-0.8.5.post1 +# torch-2.6.0+cu124: cxx11abi=False +# torch-2.6.0+cu126: cxx11abi=True +# see https://github.com/flashinfer-ai/flashinfer/issues/911 +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.8.5.post1 + +# Install flashinfer-0.2.2.post1+cu126 (cxx11abi=True) +# vllm-0.8.3 does not support flashinfer>=0.2.3 +# see https://github.com/vllm-project/vllm/pull/15777 +RUN aria2c --max-tries=9999 https://github.com/flashinfer-ai/flashinfer/releases/download/v0.2.2.post1/flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \ + pip install --no-cache-dir flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \ + rm flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Fix for transformers 4.53.0 +RUN pip3 install --no-cache-dir "transformers[hf_xet]<4.52.0" + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge + +# Install DeepEP +## the dependency of IBGDA +RUN ln -s /usr/lib/x86_64-linux-gnu/libmlx5.so.1 /usr/lib/x86_64-linux-gnu/libmlx5.so + +## Clone and build deepep and deepep-nvshmem +RUN git clone -b v2.3.1 https://github.com/NVIDIA/gdrcopy.git && \ + git clone https://github.com/deepseek-ai/DeepEP.git && \ + cd DeepEP && git checkout a84a248 + +# Prepare nvshmem +RUN wget https://developer.nvidia.com/downloads/assets/secure/nvshmem/nvshmem_src_3.2.5-1.txz && \ + tar -xvf nvshmem_src_3.2.5-1.txz && mv nvshmem_src deepep-nvshmem && \ + cd deepep-nvshmem && git apply ../DeepEP/third-party/nvshmem.patch + +ENV CUDA_HOME=/usr/local/cuda +### Set MPI environment variables. Having errors when not set. +ENV CPATH=/usr/local/mpi/include:$CPATH +ENV LD_LIBRARY_PATH=/usr/local/mpi/lib:$LD_LIBRARY_PATH +ENV LD_LIBRARY_PATH=/usr/local/x86_64-linux-gnu:$LD_LIBRARY_PATH +ENV GDRCOPY_HOME=/workspace/gdrcopy + +## Build deepep-nvshmem +RUN cd deepep-nvshmem && \ + NVSHMEM_SHMEM_SUPPORT=0 \ + NVSHMEM_UCX_SUPPORT=0 \ + NVSHMEM_USE_NCCL=0 \ + NVSHMEM_MPI_SUPPORT=0 \ + NVSHMEM_IBGDA_SUPPORT=1 \ + NVSHMEM_PMIX_SUPPORT=0 \ + NVSHMEM_TIMEOUT_DEVICE_POLLING=0 \ + NVSHMEM_USE_GDRCOPY=1 \ + cmake -G Ninja -S . -B build/ -DCMAKE_INSTALL_PREFIX=/workspace/deepep-nvshmem/install && cmake --build build/ --target install + +ENV NVSHMEM_DIR=/workspace/deepep-nvshmem/install +ENV LD_LIBRARY_PATH=$NVSHMEM_DIR/lib:$LD_LIBRARY_PATH +ENV PATH=$NVSHMEM_DIR/bin:$PATH + +## Build deepep +RUN cd DeepEP && \ + python setup.py install \ No newline at end of file diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.13.preview b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.13.preview new file mode 100644 index 0000000000000000000000000000000000000000..be6183a8479fe3e379f7ddaa06034c3e1ff64278 --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.app.vllm.mcore0.13.preview @@ -0,0 +1,85 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.4-cu124-cudnn9.8-torch2.6-fa2.7.4 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install torch-2.6.0+cu124 + vllm-0.8.5.post1 +# torch-2.6.0+cu124: cxx11abi=False +# torch-2.6.0+cu126: cxx11abi=True +# see https://github.com/flashinfer-ai/flashinfer/issues/911 +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.8.5.post1 + +# Install flashinfer-0.2.2.post1+cu126 (cxx11abi=True) +# vllm-0.8.3 does not support flashinfer>=0.2.3 +# see https://github.com/vllm-project/vllm/pull/15777 +RUN aria2c --max-tries=9999 https://github.com/flashinfer-ai/flashinfer/releases/download/v0.2.2.post1/flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \ + pip install --no-cache-dir flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl && \ + rm flashinfer_python-0.2.2.post1+cu124torch2.6-cp38-abi3-linux_x86_64.whl + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@release_v2.5 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge + +# Install DeepEP +## the dependency of IBGDA +RUN ln -s /usr/lib/x86_64-linux-gnu/libmlx5.so.1 /usr/lib/x86_64-linux-gnu/libmlx5.so + +## Clone and build deepep and deepep-nvshmem +RUN git clone -b v2.3.1 https://github.com/NVIDIA/gdrcopy.git && \ + git clone https://github.com/deepseek-ai/DeepEP.git && \ + cd DeepEP && git checkout a84a248 + +# Prepare nvshmem +RUN wget https://developer.nvidia.com/downloads/assets/secure/nvshmem/nvshmem_src_3.2.5-1.txz && \ + tar -xvf nvshmem_src_3.2.5-1.txz && mv nvshmem_src deepep-nvshmem && \ + cd deepep-nvshmem && git apply ../DeepEP/third-party/nvshmem.patch + +ENV CUDA_HOME=/usr/local/cuda +### Set MPI environment variables. Having errors when not set. +ENV CPATH=/usr/local/mpi/include:$CPATH +ENV LD_LIBRARY_PATH=/usr/local/mpi/lib:$LD_LIBRARY_PATH +ENV LD_LIBRARY_PATH=/usr/local/x86_64-linux-gnu:$LD_LIBRARY_PATH +ENV GDRCOPY_HOME=/workspace/gdrcopy + +## Build deepep-nvshmem +RUN cd deepep-nvshmem && \ + NVSHMEM_SHMEM_SUPPORT=0 \ + NVSHMEM_UCX_SUPPORT=0 \ + NVSHMEM_USE_NCCL=0 \ + NVSHMEM_MPI_SUPPORT=0 \ + NVSHMEM_IBGDA_SUPPORT=1 \ + NVSHMEM_PMIX_SUPPORT=0 \ + NVSHMEM_TIMEOUT_DEVICE_POLLING=0 \ + NVSHMEM_USE_GDRCOPY=1 \ + cmake -G Ninja -S . -B build/ -DCMAKE_INSTALL_PREFIX=/workspace/deepep-nvshmem/install && cmake --build build/ --target install + +ENV NVSHMEM_DIR=/workspace/deepep-nvshmem/install +ENV LD_LIBRARY_PATH=$NVSHMEM_DIR/lib:$LD_LIBRARY_PATH +ENV PATH=$NVSHMEM_DIR/bin:$PATH + +## Build deepep +RUN cd DeepEP && \ + python setup.py install \ No newline at end of file diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.base b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.base new file mode 100644 index 0000000000000000000000000000000000000000..25b1d9431e237287bfd720788974894d1c07873e --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/Dockerfile.base @@ -0,0 +1,113 @@ +# Base Docker Image of verl, with CUDA/Torch/FlashAttn/Apex/TransformerEngine, without other frameworks +# Target: verlai/verl:base-v2-cu124-cudnn9.8-torch2.6-fa2.8.0-te2.3 +# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 + +# Define environments +ENV MAX_JOBS=16 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini aria2 && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + xgboost transformer_engine flash_attn apex megatron-core grpcio + +# Reinstall CUDA 12.4 +RUN aria2c https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin && \ + mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 + +RUN aria2c --always-resume=true --max-tries=99999 https://developer.download.nvidia.com/compute/cuda/12.4.1/local_installers/cuda-repo-ubuntu2204-12-4-local_12.4.1-550.54.15-1_amd64.deb && \ + dpkg -i cuda-repo-ubuntu2204-12-4-local_12.4.1-550.54.15-1_amd64.deb && \ + cp /var/cuda-repo-ubuntu2204-12-4-local/cuda-*-keyring.gpg /usr/share/keyrings/ && \ + apt-get update && \ + apt-get -y install cuda-toolkit-12-4 && \ + rm cuda-repo-ubuntu2204-12-4-local_12.4.1-550.54.15-1_amd64.deb && \ + update-alternatives --set cuda /usr/local/cuda-12.4 && \ + rm -rf /usr/local/cuda-12.6 + +RUN pip install --resume-retries 999 --no-cache-dir torch==2.6.0 torchvision==0.21.0 torchaudio==2.6.0 + +RUN pip install --resume-retries 999 --no-cache-dir "tensordict==0.6.2" torchdata "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +# Install flash-attn-2.7.4.post1 (cxx11abi=False) +RUN wget -nv https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl && \ + pip install --no-cache-dir flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl + +# Fix packages +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +# Install cudnn +RUN aria2c --max-tries=9999 https://developer.download.nvidia.com/compute/cudnn/9.8.0/local_installers/cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + dpkg -i cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + cp /var/cudnn-local-repo-ubuntu2204-9.8.0/cudnn-*-keyring.gpg /usr/share/keyrings/ && \ + apt-get update && \ + apt-get -y install cudnn-cuda-12 && \ + rm cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb + +# Install Apex +RUN git clone https://github.com/NVIDIA/apex.git && \ + cd apex && \ + pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" ./ + +# Profiling tools +RUN aria2c --always-resume=true --max-tries=99999 https://developer.nvidia.com/downloads/assets/tools/secure/nsight-systems/2025_3/nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + apt-get update && apt-get install -y libxcb-cursor0 && \ + dpkg -i ./nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + rm -rf /usr/local/cuda/bin/nsys && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys /usr/local/cuda/bin/nsys && \ + rm -rf /usr/local/cuda/bin/nsys-ui && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys-ui /usr/local/cuda/bin/nsys-ui && \ + rm nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb + +# Fix opencv +RUN pip install --resume-retries 999 --no-cache-dir opencv-python + +RUN pip install --resume-retries 999 --no-cache-dir opencv-fixer && \ + python -c "from opencv_fixer import AutoFix; AutoFix()" + +RUN pip install --resume-retries 999 --no-cache-dir cuda-bindings + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url + +RUN apt-get update && \ + apt-get install -y libfreeimage3 libfreeimage-dev zlib1g htop + diff --git a/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/README.md b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/README.md new file mode 100644 index 0000000000000000000000000000000000000000..022fb47784730b723f2113eedd370dc20085f4bc --- /dev/null +++ b/verl/docker/verl0.4-cu124-torch2.6-fa2.7.4/README.md @@ -0,0 +1,31 @@ +# verl image with verl v0.4.x + +## Important packages version + +```txt +cuda==12.4 +cudnn==9.8.0 +torch==2.6.0 +flash_attn=2.7.4 +sglang==0.4.6.post5 +vllm==0.8.5.post1 +vidia-cudnn-cu12==9.8.0.87 +transformer_engine==2.3 +megatron.core==core_v0.12.2 +# Preview +transformer_engine==2.5 +megatron.core==core_r0.13.0 +``` + +## Target + +- Base image: + - `verlai/verl:base-verl0.4-cu124-cudnn9.8-torch2.6-fa2.7.4` +- App image: + - `verlai/verl:app-verl0.4-sglang0.4.6.post5-vllm0.8.5-mcore0.12.2-te2.2`: SGLang requires vLLM in 0.4.6.post5 version, vLLM can have some package conflicts with SGLang + - `verlai/verl:app-verl0.4-sglang0.4.6.post5-vllm0.8.5-mcore0.12.2-te2.2-deepep`: Built with deepep + - `verlai/verl:app-verl0.4-vllm0.8.5-mcore0.12.2-te2.2` + - `verlai/verl:app-verl0.4-vllm0.8.5-mcore0.12.2-te2.2-deepep`: Built with deepep +- Preview image: + - `verlai/verl:app-verl0.4-sglang0.4.6.post5-vllm0.8.5-mcore0.13.0-te2.2-preview` + - `verlai/verl:app-verl0.4-vllm0.8.5-mcore0.13.0-te2.2-preview` \ No newline at end of file diff --git a/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.sglang0.4.10.post2.mcore0.13 b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.sglang0.4.10.post2.mcore0.13 new file mode 100644 index 0000000000000000000000000000000000000000..d1be8fb450bf0fe62fcf3d2cc3a140867ce99827 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.sglang0.4.10.post2.mcore0.13 @@ -0,0 +1,37 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.7.4 + +# Define environments +ENV MAX_JOBS=8 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.10 +# Install FlashInfer Python package +RUN pip install --upgrade pip setuptools packaging +RUN pip install --resume-retries 999 --no-cache-dir --no-build-isolation flashinfer-python==0.2.9rc1 +RUN pip install --resume-retries 999 --no-cache-dir --no-build-isolation "sglang[all]==0.4.10.post2" + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]==4.55.4" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.13.0 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge diff --git a/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.sglang0.4.9.post6.mcore0.13 b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.sglang0.4.9.post6.mcore0.13 new file mode 100644 index 0000000000000000000000000000000000000000..d79201a92eec3d778e32a023cfa3a3b32bf3ac55 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.sglang0.4.9.post6.mcore0.13 @@ -0,0 +1,37 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.7.4 + +# Define environments +ENV MAX_JOBS=8 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.10 +# Install FlashInfer Python package +RUN pip install --upgrade pip setuptools packaging +RUN pip install --resume-retries 999 --no-cache-dir --no-build-isolation flashinfer-python==0.2.9rc1 +RUN pip install --resume-retries 999 --no-cache-dir --no-build-isolation "sglang[all]==0.4.9.post6" + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]==4.55.4" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.13.0 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge \ No newline at end of file diff --git a/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.vllm.mcore0.13 b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.vllm.mcore0.13 new file mode 100644 index 0000000000000000000000000000000000000000..9d73e0ffeeb1c8d17c6d9022d5e5411dc5d70cc1 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.vllm.mcore0.13 @@ -0,0 +1,38 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.7.4 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install torch-2.7.1+cu126 + vllm-0.10.0 +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.10.0 + +# Fix packages +# transformers 4.54.0 still not support +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.55.4" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.13.0 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge + +# Fix qwen vl +RUN pip3 install --no-cache-dir --no-deps trl \ No newline at end of file diff --git a/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.vllm.mcore0.15 b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.vllm.mcore0.15 new file mode 100644 index 0000000000000000000000000000000000000000..296fd3b74f641efce2c90d6aec81fdcb81b8a867 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.app.vllm.mcore0.15 @@ -0,0 +1,39 @@ +# Start from the verl base image +# Dockerfile.base +FROM iseekyan/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.7.4-h100 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install torch-2.7.1+cu126 + vllm-0.10.0 +RUN pip install --resume-retries 999 --no-cache-dir vllm==0.10.0 + +# Fix packages +# transformers 4.54.0 still not support +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.55.4" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@release_v2.7 +RUN pip install onnxscript + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.15.0rc4 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge==v0.15.0 + +# Fix qwen vl +RUN pip3 install --no-cache-dir --no-deps trl \ No newline at end of file diff --git a/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.base.torch2.7.1 b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.base.torch2.7.1 new file mode 100644 index 0000000000000000000000000000000000000000..6d85cf512016e4cc0988da3d099230d5d0c2b5d7 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/Dockerfile.base.torch2.7.1 @@ -0,0 +1,133 @@ +# Base Docker Image of verl, with CUDA/Torch/FlashAttn/Apex/TransformerEngine, without other frameworks +# Target: verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.8.0-fi0.2.6 +# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 + +# Define environments +ENV MAX_JOBS=16 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini aria2 libfreeimage3 libfreeimage-dev zlib1g htop && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + xgboost transformer_engine flash_attn apex megatron-core grpcio + +RUN pip install --resume-retries 999 --no-cache-dir torch==2.7.1 torchvision==0.22.1 torchaudio==2.7.1 + +# Install flash-attn-2.7.4.post1, although built with torch2.6, it is compatible with torch2.7 +# https://github.com/Dao-AILab/flash-attention/issues/1644#issuecomment-2899396361 +RUN ABI_FLAG=$(python -c "import torch; print('TRUE' if torch._C._GLIBCXX_USE_CXX11_ABI else 'FALSE')") && \ + URL="https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abi${ABI_FLAG}-cp310-cp310-linux_x86_64.whl" && \ + FILE="flash_attn-2.7.4.post1+cu12torch2.6cxx11abi${ABI_FLAG}-cp310-cp310-linux_x86_64.whl" && \ + wget -nv "${URL}" && \ + pip install --no-cache-dir "${FILE}" + +# Fix packages +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +# Install cudnn +RUN aria2c --max-tries=9999 https://developer.download.nvidia.com/compute/cudnn/9.8.0/local_installers/cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + dpkg -i cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + cp /var/cudnn-local-repo-ubuntu2204-9.8.0/cudnn-*-keyring.gpg /usr/share/keyrings/ && \ + apt-get update && \ + apt-get -y install cudnn-cuda-12 && \ + rm cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb + +# Install Apex +RUN pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" --resume-retries 999 git+https://github.com/NVIDIA/apex.git + +# Profiling tools +RUN aria2c --always-resume=true --max-tries=99999 https://developer.nvidia.com/downloads/assets/tools/secure/nsight-systems/2025_3/nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + apt-get update && apt-get install -y libxcb-cursor0 + +RUN apt-get install -y ./nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + rm -rf /usr/local/cuda/bin/nsys && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys /usr/local/cuda/bin/nsys && \ + rm -rf /usr/local/cuda/bin/nsys-ui && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys-ui /usr/local/cuda/bin/nsys-ui && \ + rm nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb + +RUN pip install --resume-retries 999 --no-cache-dir "tensordict==0.6.2" torchdata "transformers[hf_xet]>=4.52.3" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas cuda-bindings \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +# Install DeepEP +## the dependency of IBGDA +RUN ln -s /usr/lib/x86_64-linux-gnu/libmlx5.so.1 /usr/lib/x86_64-linux-gnu/libmlx5.so + +## Clone and build deepep and deepep-nvshmem +RUN git clone -b v2.3.1 https://github.com/NVIDIA/gdrcopy.git && \ + git clone https://github.com/deepseek-ai/DeepEP.git && \ + cd DeepEP && git checkout a84a248 + +# Prepare nvshmem +RUN wget https://developer.nvidia.com/downloads/assets/secure/nvshmem/nvshmem_src_3.2.5-1.txz && \ + tar -xvf nvshmem_src_3.2.5-1.txz && mv nvshmem_src deepep-nvshmem && \ + cd deepep-nvshmem && git apply ../DeepEP/third-party/nvshmem.patch + +ENV CUDA_HOME=/usr/local/cuda +### Set MPI environment variables. Having errors when not set. +ENV CPATH=/usr/local/mpi/include:$CPATH +ENV LD_LIBRARY_PATH=/usr/local/mpi/lib:$LD_LIBRARY_PATH +ENV LD_LIBRARY_PATH=/usr/local/x86_64-linux-gnu:$LD_LIBRARY_PATH +ENV GDRCOPY_HOME=/workspace/gdrcopy + +## Build deepep-nvshmem +RUN cd deepep-nvshmem && \ + NVSHMEM_SHMEM_SUPPORT=0 \ + NVSHMEM_UCX_SUPPORT=0 \ + NVSHMEM_USE_NCCL=0 \ + NVSHMEM_MPI_SUPPORT=0 \ + NVSHMEM_IBGDA_SUPPORT=1 \ + NVSHMEM_PMIX_SUPPORT=0 \ + NVSHMEM_TIMEOUT_DEVICE_POLLING=0 \ + NVSHMEM_USE_GDRCOPY=1 \ + cmake -G Ninja -S . -B build/ -DCMAKE_INSTALL_PREFIX=/workspace/deepep-nvshmem/install && cmake --build build/ --target install + +ENV NVSHMEM_DIR=/workspace/deepep-nvshmem/install +ENV LD_LIBRARY_PATH=$NVSHMEM_DIR/lib:$LD_LIBRARY_PATH +ENV PATH=$NVSHMEM_DIR/bin:$PATH + +## Build deepep +RUN cd DeepEP && \ + python setup.py install + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url + diff --git a/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/README.md b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3327050e4f2a4a44751e9f483a635b580b2630e4 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7-fa2.7.4/README.md @@ -0,0 +1,27 @@ +# verl image with verl v0.5 + +## Important packages version + +```txt +cuda==12.6 +cudnn==9.8.0 +torch==2.7.1 +flash_attn=2.7.4.post1 +sglang==0.4.9.post6 +vllm==0.8.5.post1 +vidia-cudnn-cu12==9.8.0.87 +transformer_engine==2.3 +megatron.core==core_v0.12.2 +# Preview +transformer_engine==2.5 +megatron.core==core_r0.13.0 +``` + +## Target + +- Base image: + - `verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.7.4`: We offer a base image with deep ep built in, for vllm/sglang +- App image: + - `verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2` + - `verlai/verl:app-verl0.5-transformers4.55.4-sglang0.4.10.post2-mcore0.13.0-te2.2` + - `iseekyan/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.15.0-te2.7` diff --git a/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.mcore0.12 b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.mcore0.12 new file mode 100644 index 0000000000000000000000000000000000000000..205814a234bf4d1162a2fa89f1cd051d6463fb47 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.mcore0.12 @@ -0,0 +1,37 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.8.0 + +# Define environments +ENV MAX_JOBS=8 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.8 and torch-memory-saver +# Install FlashInfer Python package +RUN pip install --upgrade pip setuptools packaging +RUN pip install --resume-retries 999 --no-cache-dir --no-build-isolation flashinfer-python==0.2.6.post1 +RUN pip install --resume-retries 999 --no-cache-dir "sglang[all]==0.4.8" && pip install torch-memory-saver --no-cache-dir + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.3 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge \ No newline at end of file diff --git a/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.mcore0.13.preview b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.mcore0.13.preview new file mode 100644 index 0000000000000000000000000000000000000000..5704813d9eee80a7ca790b204a836e81d58cbf1a --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.mcore0.13.preview @@ -0,0 +1,37 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.8.0 + +# Define environments +ENV MAX_JOBS=8 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.8 and torch-memory-saver +# Install FlashInfer Python package +RUN pip install --upgrade pip setuptools packaging +RUN pip install --resume-retries 999 --no-cache-dir --no-build-isolation flashinfer-python==0.2.6.post1 +RUN pip install --resume-retries 999 --no-cache-dir "sglang[all]==0.4.8" && pip install torch-memory-saver --no-cache-dir + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@release_v2.5 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_v0.12.2 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge \ No newline at end of file diff --git a/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.base b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.base new file mode 100644 index 0000000000000000000000000000000000000000..53089fba400d56a3a37e1e943439c367ee40df55 --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/Dockerfile.base @@ -0,0 +1,132 @@ +# Base Docker Image of verl, with CUDA/Torch/FlashAttn/Apex/TransformerEngine, without other frameworks +# Target: verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.8.0-fi0.2.6 +# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:24.08-py3 + +# Define environments +ENV MAX_JOBS=16 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini aria2 libfreeimage3 libfreeimage-dev zlib1g htop && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + xgboost transformer_engine flash_attn apex megatron-core grpcio + +RUN pip install --resume-retries 999 --no-cache-dir torch==2.7.1 torchvision==0.22.1 torchaudio==2.7.1 + +# Install flash-attn-2.8.0.post2 (cxx11abi=True) +RUN ABI_FLAG=$(python -c "import torch; print('TRUE' if torch._C._GLIBCXX_USE_CXX11_ABI else 'FALSE')") && \ + URL="https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.0.post2/flash_attn-2.8.0.post2+cu12torch2.7cxx11abi${ABI_FLAG}-cp310-cp310-linux_x86_64.whl" && \ + FILE="flash_attn-2.8.0.post2+cu12torch2.7cxx11abi${ABI_FLAG}-cp310-cp310-linux_x86_64.whl" && \ + wget -nv "${URL}" && \ + pip install --no-cache-dir "${FILE}" + +# Fix packages +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +# Install cudnn +RUN aria2c --max-tries=9999 https://developer.download.nvidia.com/compute/cudnn/9.8.0/local_installers/cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + dpkg -i cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + cp /var/cudnn-local-repo-ubuntu2204-9.8.0/cudnn-*-keyring.gpg /usr/share/keyrings/ && \ + apt-get update && \ + apt-get -y install cudnn-cuda-12 && \ + rm cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb + +# Install Apex +RUN pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" --resume-retries 999 git+https://github.com/NVIDIA/apex.git + +# Profiling tools +RUN aria2c --always-resume=true --max-tries=99999 https://developer.nvidia.com/downloads/assets/tools/secure/nsight-systems/2025_3/nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + apt-get update && apt-get install -y libxcb-cursor0 + +RUN apt-get install -y ./nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + rm -rf /usr/local/cuda/bin/nsys && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys /usr/local/cuda/bin/nsys && \ + rm -rf /usr/local/cuda/bin/nsys-ui && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys-ui /usr/local/cuda/bin/nsys-ui && \ + rm nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb + +RUN pip install --resume-retries 999 --no-cache-dir "tensordict==0.6.2" torchdata "transformers[hf_xet]>=4.53" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas cuda-bindings \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pyext pre-commit ruff + +# Install DeepEP +## the dependency of IBGDA +RUN ln -s /usr/lib/x86_64-linux-gnu/libmlx5.so.1 /usr/lib/x86_64-linux-gnu/libmlx5.so + +## Clone and build deepep and deepep-nvshmem +RUN git clone -b v2.3.1 https://github.com/NVIDIA/gdrcopy.git && \ + git clone https://github.com/deepseek-ai/DeepEP.git && \ + cd DeepEP && git checkout a84a248 + +# Prepare nvshmem +RUN wget https://developer.nvidia.com/downloads/assets/secure/nvshmem/nvshmem_src_3.2.5-1.txz && \ + tar -xvf nvshmem_src_3.2.5-1.txz && mv nvshmem_src deepep-nvshmem && \ + cd deepep-nvshmem && git apply ../DeepEP/third-party/nvshmem.patch + +ENV CUDA_HOME=/usr/local/cuda +### Set MPI environment variables. Having errors when not set. +ENV CPATH=/usr/local/mpi/include:$CPATH +ENV LD_LIBRARY_PATH=/usr/local/mpi/lib:$LD_LIBRARY_PATH +ENV LD_LIBRARY_PATH=/usr/local/x86_64-linux-gnu:$LD_LIBRARY_PATH +ENV GDRCOPY_HOME=/workspace/gdrcopy + +## Build deepep-nvshmem +RUN cd deepep-nvshmem && \ + NVSHMEM_SHMEM_SUPPORT=0 \ + NVSHMEM_UCX_SUPPORT=0 \ + NVSHMEM_USE_NCCL=0 \ + NVSHMEM_MPI_SUPPORT=0 \ + NVSHMEM_IBGDA_SUPPORT=1 \ + NVSHMEM_PMIX_SUPPORT=0 \ + NVSHMEM_TIMEOUT_DEVICE_POLLING=0 \ + NVSHMEM_USE_GDRCOPY=1 \ + cmake -G Ninja -S . -B build/ -DCMAKE_INSTALL_PREFIX=/workspace/deepep-nvshmem/install && cmake --build build/ --target install + +ENV NVSHMEM_DIR=/workspace/deepep-nvshmem/install +ENV LD_LIBRARY_PATH=$NVSHMEM_DIR/lib:$LD_LIBRARY_PATH +ENV PATH=$NVSHMEM_DIR/bin:$PATH + +## Build deepep +RUN cd DeepEP && \ + python setup.py install + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url + diff --git a/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/README.md b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f8c5459a29e31dd91d3ddb1d1eb418bdb21e05eb --- /dev/null +++ b/verl/docker/verl0.5-cu126-torch2.7.1-fa2.8.0/README.md @@ -0,0 +1,27 @@ +# verl image with verl v0.5 + +## Important packages version + +```txt +cuda==12.6 +cudnn==9.8.0 +torch==2.7.1 +flash_attn=2.8.0 ## +sglang==0.4.8 +vllm==0.8.5.post1 +vidia-cudnn-cu12==9.8.0.87 +transformer_engine==2.3 +megatron.core==core_v0.12.2 +# Preview +transformer_engine==2.5 +megatron.core==core_r0.13.0 +``` + +## Target + +- Base image: + - `verlai/verl:base-verl0.5-cu126-cudnn9.8-torch2.7.1-fa2.8.0`: We offer a base image with deep ep built in +- App image: + - `verlai/verl:app-verl0.5-sglang0.4.9-mcore0.12.2` + - `verlai/verl:app-verl0.5-sglang0.4.9-mcore0.13.0-preview` +- vllm temporarily not support latest version \ No newline at end of file diff --git a/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.megatron b/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.megatron new file mode 100644 index 0000000000000000000000000000000000000000..d41ea19d69bccb39436a79a0798a9cb0cbefec04 --- /dev/null +++ b/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/Dockerfile.app.sglang.megatron @@ -0,0 +1,36 @@ +# Start from the verl base image +# Dockerfile.base +FROM verlai/verl:base-verl0.5-preview-cu128-cudnn9.8-torch2.7.1-fa2.8.0-fi0.2.6 + +# Define environments +ENV MAX_JOBS=8 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Install sglang-0.4.8 and torch-memory-saver +# Install FlashInfer Python package +RUN pip install --resume-retries 999 --no-cache-dir --no-build-isolation flashinfer-python==0.2.6.post1 +RUN pip install --resume-retries 999 --no-cache-dir "sglang[all]==0.4.8" && pip install torch-memory-saver --no-cache-dir + +# Fix packages +RUN pip install --no-cache-dir "tensordict==0.6.2" "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pre-commit ruff + +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --resume-retries 999 --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +RUN pip install --resume-retries 999 --no-cache-dir nvidia-cudnn-cu12==9.8.0.87 + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --resume-retries 999 --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@release_v2.5 + +# Install Megatron-LM +RUN pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/Megatron-LM.git@core_r0.13.0 + +# Install mbridge +RUN pip3 install --no-cache-dir mbridge \ No newline at end of file diff --git a/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/Dockerfile.base b/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/Dockerfile.base new file mode 100644 index 0000000000000000000000000000000000000000..29c49faa848c0e15350abaf48cad7f8a899f4eb6 --- /dev/null +++ b/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/Dockerfile.base @@ -0,0 +1,91 @@ +# Base Docker Image of verl, with CUDA/Torch/FlashAttn/Apex/TransformerEngine, without other frameworks +# Target: verlai/verl:base-verl0.5-preview-cu128-cudnn9.8-torch2.7.1-fa2.8.0-fi0.2.6 +# Start from the NVIDIA official image (ubuntu-22.04 + cuda-12.6 + python-3.10) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-24-08.html +FROM nvcr.io/nvidia/pytorch:25.02-py3 + +# Define environments +ENV MAX_JOBS=16 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" + +# Define installation arguments +ARG APT_SOURCE=https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Set apt source +RUN cp /etc/apt/sources.list /etc/apt/sources.list.bak && \ + { \ + echo "deb ${APT_SOURCE} jammy main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-updates main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-backports main restricted universe multiverse"; \ + echo "deb ${APT_SOURCE} jammy-security main restricted universe multiverse"; \ + } > /etc/apt/sources.list + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install tini +RUN apt-get update && \ + apt-get install -y tini aria2 libfreeimage3 libfreeimage-dev zlib1g htop && \ + apt-get clean + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + python -m pip install --upgrade pip + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + xgboost transformer_engine flash_attn apex megatron-core grpcio + +RUN pip install --resume-retries 999 --no-cache-dir torch==2.7.1 torchvision==0.22.1 torchaudio==2.7.1 --index-url https://download.pytorch.org/whl/cu128 + +# Install flash-attn-2.8.0.post2 (cxx11abi=True) +RUN ABI_FLAG=$(python -c "import torch; print('TRUE' if torch._C._GLIBCXX_USE_CXX11_ABI else 'FALSE')") && \ + URL="https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.0.post2/flash_attn-2.8.0.post2+cu12torch2.7cxx11abi${ABI_FLAG}-cp312-cp312-linux_x86_64.whl" && \ + FILE="flash_attn-2.8.0.post2+cu12torch2.7cxx11abi${ABI_FLAG}-cp312-cp312-linux_x86_64.whl" && \ + wget -nv "${URL}" && \ + pip install --no-cache-dir "${FILE}" + +# Fix packages +RUN pip uninstall -y pynvml nvidia-ml-py && \ + pip install --no-cache-dir --upgrade "nvidia-ml-py>=12.560.30" "fastapi[standard]>=0.115.0" "optree>=0.13.0" "pydantic>=2.9" "grpcio>=1.62.1" + +# Install cudnn +RUN aria2c --max-tries=9999 https://developer.download.nvidia.com/compute/cudnn/9.8.0/local_installers/cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + dpkg -i cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb && \ + cp /var/cudnn-local-repo-ubuntu2204-9.8.0/cudnn-*-keyring.gpg /usr/share/keyrings/ && \ + apt-get update && \ + apt-get -y install cudnn-cuda-12 && \ + rm cudnn-local-repo-ubuntu2204-9.8.0_1.0-1_amd64.deb + +# Install Apex +RUN pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" --resume-retries 999 git+https://github.com/NVIDIA/apex.git + +# Profiling tools +RUN aria2c --always-resume=true --max-tries=99999 https://developer.nvidia.com/downloads/assets/tools/secure/nsight-systems/2025_3/nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + apt-get update && apt-get install -y libxcb-cursor0 + +RUN apt-get install -y ./nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb && \ + rm -rf /usr/local/cuda/bin/nsys && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys /usr/local/cuda/bin/nsys && \ + rm -rf /usr/local/cuda/bin/nsys-ui && \ + ln -s /opt/nvidia/nsight-systems/2025.3.1/target-linux-x64/nsys-ui /usr/local/cuda/bin/nsys-ui && \ + rm nsight-systems-2025.3.1_2025.3.1.90-1_amd64.deb + +RUN pip install --resume-retries 999 --no-cache-dir "tensordict==0.6.2" torchdata "transformers[hf_xet]>=4.51.0" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas cuda-bindings \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pre-commit ruff + +# Reset pip config +RUN pip config unset global.index-url && \ + pip config unset global.extra-index-url + diff --git a/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/README.md b/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/README.md new file mode 100644 index 0000000000000000000000000000000000000000..07d68977f25c788132845c4051566eafbb902b18 --- /dev/null +++ b/verl/docker/verl0.5-preview-cu128-torch2.7.1-fa2.8.0/README.md @@ -0,0 +1,26 @@ +# verl image with verl v0.5 + +## Important packages version + +```txt +cuda==12.8 +cudnn==9.8.0 +torch==2.7.1 +flash_attn=2.8.0 ## +sglang==0.4.8 +transformer_engine==2.5 +megatron.core==core_r0.13.0 +vidia-cudnn-cu12==9.8.0.87 +``` + +## Target + +- Base image: + - `verlai/verl:base-verl0.5-preview-cu128-cudnn9.8-torch2.7.1-fa2.8.0`: We offer a base image with flash infer 0.2.6.post1 built in +- App image: + - `verlai/verl:app-verl0.5-preview-sglang0.4.8-mcore0.13.0-preview` +- vllm temporarily not support latest version + +## !!!Notice!!! + +- pyext is lack of maintainace and cannot work with python 3.12, consider using replacement and deprecating this package. \ No newline at end of file diff --git a/verl/docker/verl0.6-cu128-torch2.8.0-fa2.7.4/Dockerfile.app.sglang b/verl/docker/verl0.6-cu128-torch2.8.0-fa2.7.4/Dockerfile.app.sglang new file mode 100644 index 0000000000000000000000000000000000000000..23dbea72ccce3030beb76691ba1832fc04dcdc76 --- /dev/null +++ b/verl/docker/verl0.6-cu128-torch2.8.0-fa2.7.4/Dockerfile.app.sglang @@ -0,0 +1,4 @@ +FROM verlai/verl:base-verl0.6-cu128-cudnn9.8-torch2.8.0-fa2.7.4 + +RUN pip install --no-cache-dir "sglang[all]==0.5.2" +RUN pip install --no-cache-dir "torch-memory-saver==0.0.9rc1" diff --git a/verl/docker/verl0.6-cu128-torch2.8.0-fa2.7.4/Dockerfile.base b/verl/docker/verl0.6-cu128-torch2.8.0-fa2.7.4/Dockerfile.base new file mode 100644 index 0000000000000000000000000000000000000000..7bfd48169cc0ed666507d6560669e4c6f3511a11 --- /dev/null +++ b/verl/docker/verl0.6-cu128-torch2.8.0-fa2.7.4/Dockerfile.base @@ -0,0 +1,108 @@ +# Start from the NVIDIA official image (ubuntu-24.04 + cuda-12.8 + python-3.12) +# https://docs.nvidia.com/deeplearning/frameworks/pytorch-release-notes/rel-25-03.html +FROM nvcr.io/nvidia/pytorch:25.03-py3 + +# Define environments +ENV MAX_JOBS=32 +ENV VLLM_WORKER_MULTIPROC_METHOD=spawn +ENV DEBIAN_FRONTEND=noninteractive +ENV NODE_OPTIONS="" +ENV PIP_ROOT_USER_ACTION=ignore +ENV HF_HUB_ENABLE_HF_TRANSFER="1" +ENV PIP_CONSTRAINT="" + +ARG PIP_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple + +# Change pip source +RUN pip config set global.index-url "${PIP_INDEX}" && \ + pip config set global.extra-index-url "${PIP_INDEX}" && \ + pip config set global.no-cache-dir "true" && \ + python -m pip install --upgrade pip + +# Install systemctl +RUN apt-get update && \ + apt-get install -y -o Dpkg::Options::="--force-confdef" systemd && \ + apt-get clean + +# Install libxml2 +RUN apt-get update && \ + apt-get install -y libxml2 aria2 && \ + apt-get clean + +# Uninstall nv-pytorch fork +RUN pip uninstall -y torch torchvision torchaudio \ + pytorch-quantization pytorch-triton torch-tensorrt \ + transformer_engine flash_attn apex megatron-core \ + xgboost opencv grpcio + +# Fix packages +RUN pip install --no-cache-dir tensordict torchdata "transformers[hf_xet]==4.55.4" accelerate datasets peft hf-transfer \ + "numpy<2.0.0" "pyarrow>=19.0.1" pandas \ + ray[default] codetiming hydra-core pylatexenc qwen-vl-utils wandb dill pybind11 liger-kernel mathruler blobfile xgrammar \ + pytest py-spy pre-commit ruff + +# Fix cv2 +RUN rm -rf /usr/local/lib/python3.11/dist-packages/cv2 + +# Install torch +RUN pip install --no-cache-dir torch==2.8.0 --index-url https://download.pytorch.org/whl/cu128 + +# Install flash-attn +RUN pip install --no-cache-dir --no-build-isolation flash_attn==2.7.4.post1 + +# Install DeepEP +# the dependency of IBGDA +RUN ln -s /usr/lib/x86_64-linux-gnu/libmlx5.so.1 /usr/lib/x86_64-linux-gnu/libmlx5.so + +# Clone and build deepep and deepep-nvshmem +RUN git clone -b v2.3.1 https://github.com/NVIDIA/gdrcopy.git && \ + git clone https://github.com/deepseek-ai/DeepEP.git && \ + cd DeepEP && git checkout a84a248 + +# Prepare nvshmem +RUN wget https://developer.nvidia.com/downloads/assets/secure/nvshmem/nvshmem_src_3.2.5-1.txz && \ + tar -xvf nvshmem_src_3.2.5-1.txz && mv nvshmem_src deepep-nvshmem && \ + cd deepep-nvshmem && git apply ../DeepEP/third-party/nvshmem.patch + +## Build deepep-nvshmem +RUN apt-get install -y ninja-build cmake + +ENV CUDA_HOME=/usr/local/cuda +### Set MPI environment variables. Having errors when not set. +ENV CPATH=/usr/local/mpi/include:$CPATH +ENV LD_LIBRARY_PATH=/usr/local/mpi/lib:$LD_LIBRARY_PATH +ENV LD_LIBRARY_PATH=/usr/local/x86_64-linux-gnu:$LD_LIBRARY_PATH +ENV GDRCOPY_HOME=/workspace/gdrcopy +ENV GDRCOPY_INCLUDE=/workspace/gdrcopy/include + +RUN cd deepep-nvshmem && \ + NVSHMEM_SHMEM_SUPPORT=0 \ + NVSHMEM_UCX_SUPPORT=0 \ + NVSHMEM_USE_NCCL=0 \ + NVSHMEM_MPI_SUPPORT=0 \ + NVSHMEM_IBGDA_SUPPORT=1 \ + NVSHMEM_PMIX_SUPPORT=0 \ + NVSHMEM_TIMEOUT_DEVICE_POLLING=0 \ + NVSHMEM_USE_GDRCOPY=1 \ + cmake -G Ninja -S . -B build/ -DCMAKE_INSTALL_PREFIX=/workspace/deepep-nvshmem/install && cmake --build build/ --target install + +ENV NVSHMEM_DIR=/workspace/deepep-nvshmem/install +ENV LD_LIBRARY_PATH=$NVSHMEM_DIR/lib:$LD_LIBRARY_PATH +ENV PATH=$NVSHMEM_DIR/bin:$PATH + +## Build deepep +RUN cd DeepEP && \ + python setup.py install + +# Install Apex +RUN pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings "--build-option=--cpp_ext" --config-settings "--build-option=--cuda_ext" git+https://github.com/NVIDIA/apex.git + +# Install TransformerEngine +RUN export NVTE_FRAMEWORK=pytorch && pip3 install --no-deps --no-cache-dir --no-build-isolation git+https://github.com/NVIDIA/TransformerEngine.git@v2.2.1 + +# Install Megatron-LM +RUN git clone -b core_v0.13.0 https://github.com/NVIDIA/Megatron-LM.git && \ + cd Megatron-LM && pip3 install --no-deps -e . + +# Install mbridge +RUN pip3 install --no-cache-dir git+https://github.com/ISEEKYAN/mbridge.git diff --git a/verl/docs/Makefile b/verl/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..8bda904a9b0b29dfcf538cb52b806dd910710a4a --- /dev/null +++ b/verl/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = verl +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/verl/docs/README.md b/verl/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8c5db04874138435ef986342a7b8be668b81d0b0 --- /dev/null +++ b/verl/docs/README.md @@ -0,0 +1,22 @@ +# verl documentations + +## Build the docs + +```bash +# If you want to view auto-generated API docstring, please make sure verl is available in python path. For instance, install verl via: +# pip install .. -e[test] + +# Install dependencies needed for building docs. +pip install -r requirements-docs.txt + +# Build the docs. +make clean +make html +``` + +## Open the docs with your browser + +```bash +python -m http.server -d _build/html/ +``` +Launch your browser and navigate to http://localhost:8000 to view the documentation. Alternatively you could drag the file `_build/html/index.html` to your local browser and view directly. diff --git a/verl/docs/README_vllm0.7.md b/verl/docs/README_vllm0.7.md new file mode 100644 index 0000000000000000000000000000000000000000..e84feddd7537b0cadb1157993a3819bfc5e52042 --- /dev/null +++ b/verl/docs/README_vllm0.7.md @@ -0,0 +1,73 @@ +# Upgrading to vllm >= 0.7 + +Note: verl+vllm 0.8.3 is now stable. Please see ``docs/README_vllm0.8.md`` for upgrade guide. + +## Installation + +Note: At time of writing, verl+vllm 0.7.x supports **FSDP** for training and **vLLM** for rollout. + +``` +# Create the conda environment +conda create -n verl python==3.10 +conda activate verl + +# Install verl +git clone https://github.com/volcengine/verl.git +cd verl +pip3 install -e . + +# Install the latest stable version of vLLM +pip3 install vllm==0.7.3 + +# Install flash-attn +pip3 install flash-attn --no-build-isolation + +``` + +Note that if you are installing lower versions of vLLM (0.7.0, 0.7.1, 0.7.2), you need to make some tiny patches manually on vllm (/path/to/site-packages/vllm after installation) after the above steps: + +- vllm/distributed/parallel_state.py: Remove the assertion below: + +``` +if (world_size + != tensor_model_parallel_size * pipeline_model_parallel_size): + raise RuntimeError( + f"world_size ({world_size}) is not equal to " + f"tensor_model_parallel_size ({tensor_model_parallel_size}) x " + f"pipeline_model_parallel_size ({pipeline_model_parallel_size})") + +``` + +- vllm/executor/uniproc_executor.py: change `local_rank = rank` to `local_rank = int(os.environ["LOCAL_RANK"])` +- vllm/model_executor/model_loader/weight_utils.py: remove the `torch.cuda.empty_cache()` in `pt_weights_iterator` + +## Features + +### Use cuda graph + +After installation, examples using FSDP as training backends can be used. By default, the `enforce_eager` is set to True, which disables the cuda graph. To enjoy cuda graphs and the sleep mode of vLLM>=0.7, add the following lines to the bash script: + +``` +actor_rollout_ref.rollout.enforce_eager=False \ +actor_rollout_ref.rollout.free_cache_engine=True \ + +``` + +For a typical job like examples/ppo_trainer/run_qwen2-7b_seq_balance.sh, the rollout generation time is 85 seconds with vLLM0.7.0. By enabling the cudagraph, the generation duration is further reduced to 62 seconds. + +**Note:** Currently, if the `n` is greater than 1 in `SamplingParams` in vLLM>=0.7, there is a potential performance issue on the stability of rollout generation time (Some iterations would see generation time bursts) using vLLM's V0 Engine. + +### Use vLLM V1 Engine + +Using the vLLM V1 engine can avoid instability issues and achieve additional performance improvements. To use the V1 engine, you can first uninstall the previously installed vLLM and then follow the steps below to install the newer version. + +``` +git clone https://github.com/vllm-project/vllm.git +cd vllm +git checkout 2275784 +sed -i "903a\ data_parallel_size = world_size // pipeline_model_parallel_size // tensor_model_parallel_size" ./vllm/distributed/parallel_state.py +VLLM_USE_PRECOMPILED=1 pip install --editable . +``` + +Then you can enable the V1 engine by setting `export VLLM_USE_V1=1`. In some benchmark tests, the V1 engine demonstrates a 1.5x speed improvement over the vLLM V0 engine. +The stable support of the vLLM V1 engine is available on verl main. diff --git a/verl/docs/README_vllm0.8.md b/verl/docs/README_vllm0.8.md new file mode 100644 index 0000000000000000000000000000000000000000..d4f509f19f780a4e8b3edec6bb256d2aa964639a --- /dev/null +++ b/verl/docs/README_vllm0.8.md @@ -0,0 +1,52 @@ +# Upgrading to vLLM >= 0.8 + +Last updated: 05/04/2025. + +## Installation + +Note: This version of verl+vLLM 0.8+ supports **FSDP** for training and **vLLM** for rollout. + +```bash +# Create the conda environment +conda create -n verl python==3.10 +conda activate verl + +# Install verl +git clone https://github.com/volcengine/verl.git +cd verl +pip3 install -e . + +# Install the latest stable version of vLLM +pip3 install vllm==0.8.3 + +# Install flash-attn +pip3 install flash-attn --no-build-isolation + +``` + +We have a pre-built docker image for verl+vLLM 0.8.3. You can direct import it with the following command: + +```bash +docker pull hiyouga/verl:ngc-th2.6.0-cu126-vllm0.8.3-flashinfer0.2.2-cxx11abi0 +``` + +## Features + +vLLM 0.8+ supports cuda graph and V1 engine by default in verl. To enable these features, remember to add the following lines to the bash script: + +```bash +actor_rollout_ref.rollout.enforce_eager=False \ +actor_rollout_ref.rollout.free_cache_engine=True \ +``` + +and also **remove** the environment variable if it exists: + +## Notes + +When you just directly upgrade vllm>=0.8, some dependency packages may undergo version changes. If you encounter the following problems: + +```bash +in from torch.multiprocessing.reductions import ForkingPickler ImportError: cannot import name 'ForkingPickler' from 'torch.multiprocessing.reductions' (/opt/conda/lib/python3.11/site-packages/torch/multiprocessing/reductions.py) +``` + +You need to upgrade `tensordict` to version 0.6.2 using the command `pip install tensordict==0.6.2`. diff --git a/verl/docs/conf.py b/verl/docs/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..1c780182c04f4ae9cc2f0c31286cbb5b8e6b37ae --- /dev/null +++ b/verl/docs/conf.py @@ -0,0 +1,106 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- Project information ----------------------------------------------------- + +project = "verl" +copyright = "2024 ByteDance Seed Foundation MLSys Team" +author = "Guangming Sheng, Chi Zhang, Yanghua Peng, Haibin Lin" + + +# -- General configuration --------------------------------------------------- +# The master toctree document. +master_doc = "index" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "myst_parser", + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.autosectionlabel", + "sphinx.ext.napoleon", + "sphinx.ext.viewcode", +] +# Use Google style docstrings instead of NumPy docstrings. +napoleon_google_docstring = True +napoleon_numpy_docstring = False + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +source_suffix = { + ".rst": "restructuredtext", + ".md": "markdown", +} + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = "en" + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "sphinx_rtd_theme" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add the JavaScript file +html_js_files = [ + "js/runllm-widget.js", + "js/resizable-sidebar.js", +] + +# Add custom CSS file for full-width layout +html_css_files = [ + "custom.css", +] + +exclude_patterns += ["README.md", "README_vllm0.7.md"] + +suppress_warnings = ["ref.duplicate", "ref.myst"] diff --git a/verl/docs/hybrid_flow.rst b/verl/docs/hybrid_flow.rst new file mode 100644 index 0000000000000000000000000000000000000000..3aa5a4a97cb88e564babc11392899149338a5b49 --- /dev/null +++ b/verl/docs/hybrid_flow.rst @@ -0,0 +1,266 @@ +========================================================= +HybridFlow Programming Guide +========================================================= + +Last updated: 06/02/2025. + +.. _vermouth: https://github.com/vermouth1992 + +Author: `Chi Zhang `_ + +verl is an open source implementation of the paper `HybridFlow `_ [1]_. In this section, we will introduce the basic concepts of HybridFlow, the motivation and how to program with verl APIs. + +Motivation and Design +------------------------ +We use dataflow to represent RL systems. [4]_. + +DataFlow +~~~~~~~~~~~~~~~~~~~~ + +Dataflow is an abstraction of computations. Neural Network training is a typical dataflow. It can be represented by computational graph. + +.. image:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/dataflow.jpeg?raw=true + :alt: The dataflow graph from CS231n 2024 lecture 4 + +This figure [2]_ represents the computation graph of a polynomial function followed by a sigmoid function. In the data flow of neural network computation, each node represents an operator, and each edge represents the direction of forward/backward propagation. The computation graph determines the architecture of the neural network. + +RL as a dataflow problem +++++++++++++++++++++++++++++++++++++++++++++++ + +Reinforcement learning (RL) training can also be represented as a dataflow. Below is the dataflow graph that represents the PPO algorithm used in RLHF [3]_: + +.. image:: https://picx.zhimg.com/70/v2-cb8ab5ee946a105aab6a563e92682ffa_1440w.avis?source=172ae18b&biz_tag=Post + :alt: PPO dataflow graph, credit to Zhihu 低级炼丹师 + +However, the dataflow of RL has fundamental differences compared with dataflow of neural network training as follows: + ++--------------------------+--------------------------------------------------+---------------------+ +| Workload | Node | Edge | ++--------------------------+--------------------------------------------------+---------------------+ +| Neural Network Training | Operator (+/-/matmul/softmax) | Tensor movement | ++--------------------------+--------------------------------------------------+---------------------+ +| Reinforcement Learning | High-level operators (rollout/model forward) | Data Movement | ++--------------------------+--------------------------------------------------+---------------------+ + +In the case of tabular reinforcement learning, each operator is a simple scalar math operation (e.g., bellman update). In deep reinforcement learning(DRL), each operator is a high-level neural network computation such as model inference/update. This makes RL a two-level dataflow problem: + +- Control flow: defines how the high-level operators are executed (e.g., In PPO, we first perform rollout. Then, we perform advantage computation. Finally, we perform training). It expresses the **core logics of RL algorithms**. +- Computation flow: defines the dataflow of **neural network computation** (e.g., model forward/backward/optimizer). + + +Design Choices +~~~~~~~~~~~~~~~~~~~~ +The model size used in DRL before the LLM era is typically small. Thus, the high-level neural network computation can be done in a single process. This enables embedding the computation flow inside the control flow as a single process. + +However, in the LLM era, the computation flow (e.g., training neural network) becomes a multi-process program. This naturally leads to two design choices: + +1. Convert the control flow into a multi-process program as well. Then colocate with computation flow (unified multi-controller) + +- Advantages: + + - Achieves the **optimal performance** under fixed computation flow and control flow as the communication overhead in both training and data transfer is minimized. + +- Disadvantages: + + - The computation and/or control flow is **hard to reuse** from software perspective as computation code is coupled with specific controller code. For example, the training loop of PPO is generic. Say we have an PPO training flow implemented with a specific computation flow such as FSDP. Neither the control flow or computation flow can be reused if we want to switch the computation flow from FSDP to Megatron, due to the coupling of control and computation flows. + - Requires more efforts from the user under flexible and dynamic control flows, due to the multi-process nature of the program. + +2. Separate the flows: single process for the control flow and multi-process for computation flow + +- Advantages: + + - The computation flow defined elsewhere can be **easily reused** after the decoupling. + - The controller runs on a single process. Implementing a new RL algorithm with a **different control flow is simple and easy**. + +- Disadvantages: + + - Additional **data communication overhead** each time the controller process and computatation processes interact. The data has to be sent back and forth. + +In verl, the latter strategy with separate control flow and computation flow is adopted. verl is designed to decouple the control flow of RL algorithms, and the implementation of computation engines. + +Overall Execution Diagram +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Below is a simplified diagram denoting the execution of a reinforcement learning job. In the diagram, the controller runs on a single process, while the generator/actor workers, critic workers run on multiple processes, placed with specific resource groups. For rollout, the controller passes the data to the generator to perform sample generation. When the rollout is done, the data is passed back to controller for the next step of the algorithm. Similar execution is done for other workers. With the hybrid controller design, the data flow and computation is decoupled to provide both efficiency in computation and flexibility in defining algorithm training loops. + +.. figure:: https://github.com/eric-haibin-lin/verl-community/blob/main/docs/driver_worker.png?raw=true + :alt: The execution diagram + +Codebase walkthrough (PPO) +------------------------------------------------ + +Entry function +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Code: https://github.com/volcengine/verl/blob/main/verl/trainer/main_ppo.py + +In this file, we define a remote function `main_task` that serves as the controller (driver) process as shown in the above figure. We also define a ``RewardManager``, where users can customize their reward function based on the data source in the dataset. Note that `RewardManager` should return the final token-level reward that is optimized by RL algorithms. Note that users can combine model-based rewards and rule-based rewards. +The ``main_task`` constructs a RayPPOTrainer instance and launch the fit. Note that ``main_task`` **runs as a single process**. + +We highly recommend that the ``main_task`` is NOT scheduled on the head of the ray cluster because ``main_task`` will consume a lot of memory but the head usually contains very few resources. + +Ray trainer +~~~~~~~~~~~~~~~~~~~~ +Code: https://github.com/volcengine/verl/blob/main/verl/trainer/ppo/ray_trainer.py + +The RayPPOTrainer manages + +- Worker and WorkerGroup construction +- Runs the main loop of PPO algorithm + +Note that, the fit function of RayPPOTrainer **runs as a single process**. + +Worker and WorkerGroup construction +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Each workerGroup manages a list of workers that runs remotely. Note that the worker group runs in the process of its constructor. +Each worker inside the WorkerGroup runs on a GPU. The worker group serves as a proxy for the controller process to interact with a list of workers, in order to perform certain computations. **In order to do so, we have to bind the methods of the worker into the method of the WorkerGroup and define the data dispatch and data collection**. This is done via simple decoration that will be introduced in the Worker definition section. + +For example, in PPO, we define 3 worker groups: + +- ActorRolloutRef: manages actor, rollout and reference policy. ActorRolloutRefWorker can be instantiated as a single actor, a single rollout, a single reference policy, a combined actor/rollout or a combined actor/rollout/ref. This design is aimed for the maximum code reuse in various scenarios. The reason for colocating actor and rollout is for fast weight transfer using nccl. The reason for coloating actor and reference is to implement an efficient lora PPO as the reference policy is simply the base model of PPO in lora. The colocation is done via ``verl.single_controller.ray.base.create_colocated_worker_cls``, where it creates a single ray remote class exposing all class methods from these roles. +- Critic: manages the critic model +- Reward: manages the reward model + +The worker group will be constructed on the resource pool it designates. The resource pool is a set of GPUs in the ray cluster. + +Worker definition +~~~~~~~~~~~~~~~~~~~~ + +.. _ActorRolloutRefWorker: https://github.com/volcengine/verl/blob/main/verl/workers/fsdp_workers.py + +We take `ActorRolloutRefWorker `_ for an example. +The APIs it should expose to the controller process are: + +- init_model: build the underlying model +- generate_sequences: given prompts, generate responses +- compute_log_prob: compute the log-probability of a generated sequence using actor +- compute_ref_log_prob: compute the log-probability of a generated sequence using reference policy +- save_checkpoint: save the checkpoint + +Note that these methods are defined in the worker that can only be invoked via remote calls. For example, if the controller process wants to initialize the model, it has to call + +.. code-block:: python + + for worker in actor_rollout_ref_wg: + worker.init_model.remote() + +If the controller process wants to generate sequences, it has to call + +.. code-block:: python + + data = xxx + # split the data into dp chunks + data_dp_lst = data.split(dp_size) + output_dp_lst = [] + for i, worker in enumerate(actor_rollout_ref_wg): + output_future = worker.generate_sequences.remote(data_dp_lst[i]) + output_dp_lst.append(output_future) + output = torch.cat(ray.get(output_dp_lst), dim=0) + +We observe that controller process calling worker group methods in general can be divided into 3 parts: + +- Split the data into data parallel sizes +- Dispatch the corresponding data into each worker +- Collect and concatenate the data when the computation finishes + +In verl, we design a syntax sugar to encapsulate the 3 processes into a single call from the controller process. + +.. code-block:: python + + @register(dispatch_mode=Dispatch.DP_COMPUTE_PROTO) + def generate_sequences(data): + ... + + # on the driver + output = actor_rollout_ref_wg.generate_sequences(data) + +We decorate the method of the worker with a ``register`` that explicitly defines how the input data should be split and dispatched to each worker, and how the output data should be collected and concatenated by the controller. For example, ``Dispatch.DP_COMPUTE_PROTO`` splits the input data into dp chunks, dispatch each data to each worker, collect the output and concatenate the results. Note that this function requires the input and output to be a DataProto defined here (https://github.com/volcengine/verl/blob/main/verl/protocol.py). + + +PPO main loop +~~~~~~~~~~~~~~~~~~~~ +With the aforementioned APIs, we can implement the main loop of PPO as if it is a single process program + +.. code-block:: python + + for prompt in dataloader: + output = actor_rollout_ref_wg.generate_sequences(prompt) + old_log_prob = actor_rollout_ref_wg.compute_log_prob(output) + ref_log_prob = actor_rollout_ref_wg.compute_ref_log_prob(output) + values = critic_wg.compute_values(output) + rewards = reward_wg.compute_scores(output) + # compute_advantages is running directly on the control process + advantages = compute_advantages(values, rewards) + output = output.union(old_log_prob) + output = output.union(ref_log_prob) + output = output.union(values) + output = output.union(rewards) + output = output.union(advantages) + # update actor + actor_rollout_ref_wg.update_actor(output) + critic.update_critic(output) + +Takeaways +~~~~~~~~~~~~~~~~~~~~ +- This programming paradigm enables users to use different computation backend without modification of the control process. +- This programming paradigm enables flexible placement (by changing the mapping of WorkerGroup and ResourcePool) without modification of the control process. + +Repository organization +------------------------------------------------ + +Important code files in the repository are organized as below: + +.. code-block:: bash + + verl # the verl package + trainer + main_ppo.py # the entrypoint for RL training + ppo + ray_trainer.py # the training loop for RL algorithms such as PPO + fsdp_sft_trainer.py # the SFT trainer with FSDP backend + config + generation.yaml # configuration template for rollout + ppo_trainer.yaml # configuration template for the RL trainer + workers + protocol.py # the interface of DataProto + fsdp_workers.py # the FSDP worker interfaces: ActorRolloutRefWorker, CriticWorker, RewardModelWorker + megatron_workers.py # the Megatron worker interfaces: ActorRolloutRefWorker, CriticWorker, RewardModelWorker + actor + dp_actor.py # data parallel actor with FSDP backend + megatron_actor.py # nD parallel actor with Megatron backend + critic + dp_critic.py # data parallel critic with FSDP backend + megatron_critic.py # nD parallel critic with FSDP backend + reward_model + megatron + reward_model.py # reward model with Megatron backend + rollout + vllm + vllm_rollout.py # rollout with vllm backend + hf_rollout.py # rollout with huggingface TGI backend + sharding_manager + fsdp_ulysses.py # data and model resharding when using FSDP + ulysses + fsdp_vllm.py # data and model resharding when using FSDP + ulysses + vllm + megatron_vllm.py # data and model resharding when using Megatron + vllm + utils + dataset # datasets for SFT/RM/RL + reward_score # function based reward + gsm8k.py # reward function for gsm8k dataset + math.py # reward function for math dataset + seqlen_balancing.py # the sequence balance optimization + models + llama # Megatron implementation for llama, deepseek, mistral, etc + transformers # ulysses integration with transformer models such as llama, qwen, etc + weight_loader_registery.py # registry of weight loaders for loading hf ckpt into Megatron + third_party + vllm # adaptor for vllm's usage in RL + vllm_spmd # vllm >= v0.7 adaptor + examples # example scripts + tests # integration and unit tests + .github # the configuration of continuous integration tests + + +.. [1] HybridFlow: A Flexible and Efficient RLHF Framework: https://arxiv.org/abs/2409.19256v2 +.. [2] Data flow graph credit to CS231n 2024 lecture 4: https://cs231n.stanford.edu/slides/2024/lecture_4.pdf +.. [3] PPO dataflow graph credit to 低级炼丹师 from Zhihu​: https://zhuanlan.zhihu.com/p/635757674 +.. [4] RLFlow diff --git a/verl/docs/index.rst b/verl/docs/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..0c3dd3ca873916239b8b0a8f190c0a2345d3bd68 --- /dev/null +++ b/verl/docs/index.rst @@ -0,0 +1,194 @@ +Welcome to verl's documentation! +================================================ + +verl is a flexible, efficient and production-ready RL training framework designed for large language models (LLMs) post-training. It is an open source implementation of the `HybridFlow `_ paper. + +verl is flexible and easy to use with: + +- **Easy extension of diverse RL algorithms**: The hybrid programming model combines the strengths of single-controller and multi-controller paradigms to enable flexible representation and efficient execution of complex Post-Training dataflows. Allowing users to build RL dataflows in a few lines of code. + +- **Seamless integration of existing LLM infra with modular APIs**: Decouples computation and data dependencies, enabling seamless integration with existing LLM frameworks, such as PyTorch FSDP, Megatron-LM, vLLM and SGLang. Moreover, users can easily extend to other LLM training and inference frameworks. + +- **Flexible device mapping and parallelism**: Supports various placement of models onto different sets of GPUs for efficient resource utilization and scalability across different cluster sizes. + +- Ready integration with popular HuggingFace models + + +verl is fast with: + +- **State-of-the-art throughput**: By seamlessly integrating existing SOTA LLM training and inference frameworks, verl achieves high generation and training throughput. + +- **Efficient actor model resharding with 3D-HybridEngine**: Eliminates memory redundancy and significantly reduces communication overhead during transitions between training and generation phases. + +-------------------------------------------- + +.. _Contents: + +.. toctree:: + :maxdepth: 2 + :caption: Quickstart + + start/install + start/quickstart + start/multinode + start/ray_debug_tutorial + start/more_resources + start/agentic_rl + +.. toctree:: + :maxdepth: 2 + :caption: Programming guide + + hybrid_flow + single_controller + +.. toctree:: + :maxdepth: 1 + :caption: Data Preparation + + preparation/prepare_data + preparation/reward_function + +.. toctree:: + :maxdepth: 2 + :caption: Configurations + + examples/config + +.. toctree:: + :maxdepth: 1 + :caption: PPO Example + + examples/ppo_code_architecture + examples/gsm8k_example + examples/multi_modal_example + examples/skypilot_examples + +.. toctree:: + :maxdepth: 1 + :caption: Algorithms + + algo/ppo.md + algo/grpo.md + algo/collabllm.md + algo/dapo.md + algo/spin.md + algo/sppo.md + algo/entropy.md + algo/opo.md + algo/baseline.md + algo/gpg.md + +.. toctree:: + :maxdepth: 1 + :caption: PPO Trainer and Workers + + workers/ray_trainer + workers/fsdp_workers + workers/megatron_workers + workers/sglang_worker + workers/model_engine + +.. toctree:: + :maxdepth: 1 + :caption: Performance Tuning Guide + + perf/dpsk.md + perf/perf_tuning + README_vllm0.8.md + perf/device_tuning + perf/verl_profiler_system.md + perf/nsight_profiling.md + +.. toctree:: + :maxdepth: 1 + :caption: Adding new models + + advance/fsdp_extension + advance/megatron_extension + +.. toctree:: + :maxdepth: 1 + :caption: Advanced Features + + advance/checkpoint + advance/rope + advance/ppo_lora.rst + sglang_multiturn/multiturn.rst + sglang_multiturn/interaction_system.rst + advance/placement + advance/dpo_extension + examples/sandbox_fusion_example + advance/rollout_trace.rst + advance/rollout_skip.rst + advance/one_step_off + advance/agent_loop + +.. toctree:: + :maxdepth: 1 + :caption: Hardware Support + + amd_tutorial/amd_build_dockerfile_page.rst + amd_tutorial/amd_vllm_page.rst + ascend_tutorial/ascend_quick_start.rst + ascend_tutorial/ascend_profiling_zh.rst + ascend_tutorial/ascend_profiling_en.rst + ascend_tutorial/ascend_sglang_quick_start.rst + +.. toctree:: + :maxdepth: 1 + :caption: API References + + api/data + api/single_controller.rst + api/trainer.rst + api/utils.rst + + +.. toctree:: + :maxdepth: 2 + :caption: FAQ + + faq/faq + +.. toctree:: + :maxdepth: 1 + :caption: Development Notes + + sglang_multiturn/sandbox_fusion.rst + +Contribution +------------- + +verl is free software; you can redistribute it and/or modify it under the terms +of the Apache License 2.0. We welcome contributions. +Join us on `GitHub `_, `Slack `_ and `Wechat `_ for discussions. + +Contributions from the community are welcome! Please check out our `project roadmap `_ and `good first issues `_ to see where you can contribute. + +Code Linting and Formatting +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +We use pre-commit to help improve code quality. To initialize pre-commit, run: + +.. code-block:: bash + + pip install pre-commit + pre-commit install + +To resolve CI errors locally, you can also manually run pre-commit by: + +.. code-block:: bash + + pre-commit run + +Adding CI tests +^^^^^^^^^^^^^^^^^^^^^^^^ + +If possible, please add CI test(s) for your new feature: + +1. Find the most relevant workflow yml file, which usually corresponds to a ``hydra`` default config (e.g. ``ppo_trainer``, ``ppo_megatron_trainer``, ``sft_trainer``, etc). +2. Add related path patterns to the ``paths`` section if not already included. +3. Minimize the workload of the test script(s) (see existing scripts for examples). + +We are HIRING! Send us an `email `_ if you are interested in internship/FTE opportunities in MLSys/LLM reasoning/multimodal alignment. diff --git a/verl/docs/requirements-docs.txt b/verl/docs/requirements-docs.txt new file mode 100644 index 0000000000000000000000000000000000000000..55ccdb8f7149bd6b774b592dca068e63e87256db --- /dev/null +++ b/verl/docs/requirements-docs.txt @@ -0,0 +1,13 @@ +# markdown support +recommonmark +myst_parser +# markdown table support +sphinx-markdown-tables + +# theme default rtd + +# crate-docs-theme +sphinx-rtd-theme + +# pin tokenizers version to avoid env_logger version req +tokenizers==0.21 diff --git a/verl/pyproject.toml b/verl/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1426b507b0e06d6025f004248848cef730b53325 --- /dev/null +++ b/verl/pyproject.toml @@ -0,0 +1,113 @@ +# ------------------------------- +# build-system +# ------------------------------- +[build-system] +requires = [ + "setuptools>=61.0", + "wheel" +] +build-backend = "setuptools.build_meta" + +# ------------------------------- +# project (PEP 621 metadata) +# ------------------------------- +[project] +name = "verl" +# We'll mark the version as "dynamic" because it's read from the file "verl/version/version" +# (PEP 621 calls this "dynamic version"). +# The actual version is specified in the [tool.setuptools.dynamic] section below. +dynamic = ["version", "dependencies", "optional-dependencies", "authors", "urls"] + +description = "verl: Volcano Engine Reinforcement Learning for LLM" +license = {text = "Apache-2.0"} # Changed from file to text format +readme = {file = "README.md", content-type = "text/markdown"} +requires-python = ">=3.10" + +# ------------------------------- +# tool.ruff - Linting configuration +# ------------------------------- +[tool.ruff] +# Note: While the formatter will attempt to format lines such that they remain within the line-length, +# it isn't a hard upper bound, and formatted lines may exceed the line-length. +line-length = 120 +exclude = ["tests/workers/rollout/test_sglang_async_rollout_sf_tools.py", "scripts/legacy_model_merger.py"] + +[tool.ruff.lint] +isort = {known-first-party = ["verl"]} +# c.f. https://github.com/vllm-project/vllm/blob/ce8d6b75fc0586045df75ee1568a5b5f9957251b/pyproject.toml +select = [ + # pycodestyle + "E", + # Pyflakes + "F", + # pyupgrade + "UP", + # flake8-bugbear + "B", + # isort + "I", + "G", +] +ignore = [ + # star imports + "F405", "F403", + # lambda expression assignment + "E731", + # Loop control variable not used within loop body + "B007", + # f-string format + "UP032", + # `.log()` statement uses f-string + "G004", + # X | None for type annotations + "UP045", + # deprecated import + "UP035", +] + +# ------------------------------- +# tool.mypy - typechecking config +# ------------------------------- +[tool.mypy] +pretty = true +ignore_missing_imports = true +explicit_package_bases = true +follow_imports = "skip" + +# Blanket silence +ignore_errors = true + +[[tool.mypy.overrides]] +module = [ +"verl.trainer.config.algorithm", +"verl.trainer.ppo.core_algos", +"verl.trainer.ppo.reward", +"verl.workers.reward_manager", +"verl.workers.reward_manager.*", +] +ignore_errors = false + +# ------------------------------- +# tool.setuptools - Additional config +# ------------------------------- +[tool.setuptools] +# True means `setuptools` will attempt to include all relevant files in package_data automatically. +# This corresponds to `include_package_data=True` in setup.py. +include-package-data = true + +# We read the version from a file in 'verl/version/version' +[tool.setuptools.dynamic] +version = {file = "verl/version/version"} + +# If you need to mimic `package_dir={'': '.'}`: +[tool.setuptools.package-dir] +"" = "." + +# If you need to include specific non-Python data (like YAML files or version file): +# This is the rough equivalent of package_data={'': ['version/*'], 'verl': ['trainer/config/*.yaml']} +[tool.setuptools.package-data] +verl = [ + "version/*", + "trainer/config/*.yaml", + "trainer/config/*/*.yaml", +] diff --git a/verl/requirements-cuda.txt b/verl/requirements-cuda.txt new file mode 100644 index 0000000000000000000000000000000000000000..7bfe8efeb555b9f509c7584045461076993424ce --- /dev/null +++ b/verl/requirements-cuda.txt @@ -0,0 +1 @@ +flash-attn \ No newline at end of file diff --git a/verl/requirements-npu.txt b/verl/requirements-npu.txt new file mode 100644 index 0000000000000000000000000000000000000000..ae9ed11615696ffe3302a0b958ccab40d02e1de2 --- /dev/null +++ b/verl/requirements-npu.txt @@ -0,0 +1,21 @@ +# requirements.txt records the full set of dependencies for development +accelerate +codetiming +datasets +dill +hydra-core +numpy<2.0.0 +pandas +peft>=0.15.2 +pyarrow>=15.0.0 +pybind11 +pylatexenc +tensordict>=0.8.0,<=0.10.0,!=0.9.0 +transformers==4.52.4 +ray==2.46.0 +wandb +mathruler +torchdata +einops +qwen_vl_utils +torchvision==0.20.1 diff --git a/verl/requirements.txt b/verl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d4f236ea5d654408a5ab94c25e9b9a6c7621d3f --- /dev/null +++ b/verl/requirements.txt @@ -0,0 +1,26 @@ +# requirements.txt records the full set of dependencies for development +accelerate +codetiming +datasets +dill +hydra-core +liger-kernel +numpy<2.0.0 +pandas +peft +pyarrow>=19.0.0 +pybind11 +pylatexenc +pre-commit +ray[default] +tensordict>=0.8.0,<=0.10.0,!=0.9.0 +torchdata +transformers +# vllm==0.8.4 +wandb +packaging>=20.0 +uvicorn +fastapi +latex2sympy2_extended +math_verify +tensorboard \ No newline at end of file diff --git a/verl/requirements_sglang.txt b/verl/requirements_sglang.txt new file mode 100644 index 0000000000000000000000000000000000000000..113bca0d3e7ee9b976a854b48d271b3d27a88e81 --- /dev/null +++ b/verl/requirements_sglang.txt @@ -0,0 +1,21 @@ +# requirements.txt records the full set of dependencies for development +accelerate +codetiming +datasets +dill +flash-attn +hydra-core +numpy<2.0.0 +pandas +peft +pyarrow>=19.0.0 +pybind11 +pylatexenc +ray[default]>=2.10 +tensordict>=0.8.0,<=0.10.0,!=0.9.0 +torchdata +torchvision +transformers +wandb +sglang[all]==0.5.2 +huggingface_hub diff --git a/verl/setup.py b/verl/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..4a86f035d094c0612e534575441f531497ccbad7 --- /dev/null +++ b/verl/setup.py @@ -0,0 +1,96 @@ +# Copyright 2024 Bytedance Ltd. and/or its affiliates +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# setup.py is the fallback installation script when pyproject.toml does not work +import os +from pathlib import Path + +from setuptools import find_packages, setup + +version_folder = os.path.dirname(os.path.join(os.path.abspath(__file__))) + +with open(os.path.join(version_folder, "verl/version/version")) as f: + __version__ = f.read().strip() + +install_requires = [ + "accelerate", + "codetiming", + "datasets", + "dill", + "hydra-core", + "numpy<2.0.0", + "pandas", + "peft", + "pyarrow>=19.0.0", + "pybind11", + "pylatexenc", + "ray[default]>=2.41.0", + "torchdata", + "tensordict>=0.8.0,<=0.10.0,!=0.9.0", + "transformers", + "wandb", + "packaging>=20.0", + "tensorboard", +] + +TEST_REQUIRES = ["pytest", "pre-commit", "py-spy", "pytest-asyncio"] +PRIME_REQUIRES = ["pyext"] +GEO_REQUIRES = ["mathruler", "torchvision", "qwen_vl_utils"] +GPU_REQUIRES = ["liger-kernel", "flash-attn"] +MATH_REQUIRES = ["math-verify"] # Add math-verify as an optional dependency +VLLM_REQUIRES = ["tensordict>=0.8.0,<=0.10.0,!=0.9.0", "vllm>=0.7.3,<=0.9.1"] +SGLANG_REQUIRES = [ + "tensordict>=0.8.0,<=0.10.0,!=0.9.0", + "sglang[srt,openai]==0.5.2", + "torch==2.8.0", +] +TRL_REQUIRES = ["trl<=0.9.6"] +MCORE_REQUIRES = ["mbridge"] + +extras_require = { + "test": TEST_REQUIRES, + "prime": PRIME_REQUIRES, + "geo": GEO_REQUIRES, + "gpu": GPU_REQUIRES, + "math": MATH_REQUIRES, + "vllm": VLLM_REQUIRES, + "sglang": SGLANG_REQUIRES, + "trl": TRL_REQUIRES, + "mcore": MCORE_REQUIRES, +} + + +this_directory = Path(__file__).parent +long_description = (this_directory / "README.md").read_text() + +setup( + name="verl", + version=__version__, + package_dir={"": "."}, + packages=find_packages(where="."), + url="https://github.com/volcengine/verl", + license="Apache 2.0", + author="Bytedance - Seed - MLSys", + author_email="zhangchi.usc1992@bytedance.com, gmsheng@connect.hku.hk", + description="verl: Volcano Engine Reinforcement Learning for LLM", + install_requires=install_requires, + extras_require=extras_require, + package_data={ + "": ["version/*"], + "verl": ["trainer/config/*.yaml"], + }, + include_package_data=True, + long_description=long_description, + long_description_content_type="text/markdown", +)