Harryis commited on
Commit
70a7f67
·
verified ·
1 Parent(s): 8fb9f5e

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. scripts/convert_rl_to_sft_blackjack.py +250 -0
  2. scripts/convert_rl_to_sft_frozenlake.py +267 -0
  3. scripts/convert_rl_to_sft_frozenlake_daoshuaction.py +300 -0
  4. scripts/convert_rl_to_sft_rubikscube.py +266 -0
  5. scripts/convert_rl_to_sft_sokoban.py +273 -0
  6. scripts/convert_rl_to_sft_sudoku.py +342 -0
  7. scripts/download_data.py +38 -0
  8. scripts/nothink_dataset.py +58 -0
  9. scripts/ppl_2048.py +105 -0
  10. scripts/ppy_cube.py +0 -0
  11. scripts/runs/bandit_jobs.sh +227 -0
  12. scripts/runs/frozenlake_jobs.sh +247 -0
  13. scripts/runs/sokoban_jobs.sh +226 -0
  14. scripts/runs/webshop_budget_jobs.sh +57 -0
  15. scripts/runs/webshop_jobs.sh +165 -0
  16. scripts/setup_ragen.md +26 -0
  17. scripts/setup_ragen.sh +151 -0
  18. scripts/setup_ragen_webshop.sh.old +144 -0
  19. scripts/setup_webshop.sh +50 -0
  20. scripts/synthesize_bon.sh +69 -0
  21. scripts/synthesize_think_bon.py +827 -0
  22. scripts/synthesize_think_bon_traj_sa.py +884 -0
  23. scripts/synthesize_think_bon_v2.py +854 -0
  24. scripts/train_sokoban.py +356 -0
  25. scripts/visualize.py +692 -0
  26. tests/env/test_sokoban_render.py +41 -0
  27. tests/es_manager/test_seed_iteration.py +34 -0
  28. tests/llm_agent/test_context_window.py +84 -0
  29. tests/test_rollout_filter.py +137 -0
  30. verl/.gemini/config.yaml +10 -0
  31. verl/.github/CODEOWNERS +30 -0
  32. verl/.github/ISSUE_TEMPLATE/bug-report.yml +65 -0
  33. verl/.github/ISSUE_TEMPLATE/config.yml +2 -0
  34. verl/.github/ISSUE_TEMPLATE/feature-request.yml +32 -0
  35. verl/.github/PULL_REQUEST_TEMPLATE.md +40 -0
  36. verl/.github/dependabot.yml +9 -0
  37. verl/.github/workflows/.deprecate/e2e_eval_aime24.yml +147 -0
  38. verl/.github/workflows/.deprecate/e2e_ppo_trainer.yml +133 -0
  39. verl/.github/workflows/.deprecate/e2e_ppo_trainer_megatron_sglang.yml +155 -0
  40. verl/.github/workflows/.deprecate/e2e_prime.yml +66 -0
  41. verl/.github/workflows/.deprecate/e2e_spin.yml +119 -0
  42. verl/.github/workflows/.deprecate/e2e_sppo.yml +118 -0
  43. verl/.github/workflows/README.md +73 -0
  44. verl/.github/workflows/check-pr-title.yml +58 -0
  45. verl/.github/workflows/checkpoint_converter.yml +175 -0
  46. verl/.github/workflows/cpu_unit_tests.yml +89 -0
  47. verl/.github/workflows/doc.yml +100 -0
  48. verl/.github/workflows/e2e_ascend.yml +156 -0
  49. verl/.github/workflows/e2e_dapo.yml +145 -0
  50. verl/.github/workflows/e2e_genrm_remote.yml +138 -0
scripts/convert_rl_to_sft_blackjack.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert RL test trajectories from Blackjack into LLM SFT-ready language trajectories.
4
+ Uses pre-recorded text_states from the training script to ensure exact match with environment feedback.
5
+
6
+ Input: runs/<exp>/trajectories/step_XXXXXX/trajectories.jsonl
7
+ Output: runs/<exp>/sft/step_XXXXXX_sft.jsonl
8
+ """
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ from typing import List, Tuple
15
+
16
+ try:
17
+ import yaml # type: ignore
18
+ except Exception:
19
+ yaml = None
20
+
21
+ ACTION_LOOKUP = {0: "Stick", 1: "Hit"}
22
+
23
+
24
+ def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, bool, str, int]:
25
+ """Load Blackjack env_instruction, max_tokens, enable_think, action_sep, max_actions.
26
+ Fallbacks are provided if YAML is unavailable or keys are missing.
27
+ """
28
+ instruction = (
29
+ "You are playing Blackjack against a dealer. The dealer must hit on 16 or less and stand on 17 or more.\n"
30
+ "Choose either Stick or Hit. Respond with a single action.\n"
31
+ "Example: <answer>Hit</answer>"
32
+ )
33
+ max_tokens = 64
34
+ enable_think = True
35
+ action_sep = "||"
36
+ max_actions = 10
37
+
38
+ if yaml is None:
39
+ instruction += (
40
+ "\nYour available actions are:\n"
41
+ "Stick, Hit\n"
42
+ f"You can make up to {max_actions} actions, separated by the action separator \" " + action_sep + " \"\n"
43
+ )
44
+ return instruction, max_tokens, enable_think, action_sep, max_actions
45
+
46
+ envs_yaml = repo_root / "config" / "envs.yaml"
47
+ if envs_yaml.exists():
48
+ try:
49
+ with open(envs_yaml, "r", encoding="utf-8") as f:
50
+ envs = yaml.safe_load(f)
51
+ if isinstance(envs, dict):
52
+ bj = envs.get("Blackjack", {})
53
+ if isinstance(bj, dict):
54
+ instruction = bj.get("env_instruction", instruction)
55
+ max_tokens = int(bj.get("max_tokens", max_tokens))
56
+ max_actions = int(bj.get("max_actions_per_traj", max_actions))
57
+ except Exception:
58
+ pass
59
+
60
+ base_yaml = repo_root / "config" / "base.yaml"
61
+ if base_yaml.exists():
62
+ try:
63
+ with open(base_yaml, "r", encoding="utf-8") as f:
64
+ base_cfg = yaml.safe_load(f)
65
+ ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {}
66
+ action_sep = ap.get("action_sep", action_sep)
67
+ enable_think = bool(ap.get("enable_think", enable_think))
68
+ except Exception:
69
+ pass
70
+
71
+ instruction += (
72
+ "\nYour available actions are:\n"
73
+ "Stick, Hit\n"
74
+ f"You can make up to {max_actions} actions, separated by the action separator \" " + action_sep + " \"\n"
75
+ )
76
+ return instruction, max_tokens, enable_think, action_sep, max_actions
77
+
78
+
79
+ def build_messages_for_episode(
80
+ text_states: List[str],
81
+ actions: List[int],
82
+ rewards: List[float],
83
+ instruction: str,
84
+ max_tokens: int,
85
+ enable_think: bool,
86
+ max_actions: int,
87
+ ) -> List[dict]:
88
+ messages = [
89
+ {"role": "system", "content": "You're a helpful assistant. "},
90
+ {"role": "user", "content": instruction},
91
+ ]
92
+
93
+ total_actions = len(actions)
94
+
95
+ # 遍历每一步动作
96
+ for t in range(len(actions)):
97
+ # 获取当前步骤的文本状态
98
+ # text_states[0] 是初始状态, text_states[1] 是 action[0] 之后的状态
99
+ current_text_state = text_states[t]
100
+
101
+ actions_left = max(0, max_actions - t)
102
+ format_prompt = (
103
+ "<think> [Your thoughts] </think> <answer> [your answer] </answer>"
104
+ if enable_think
105
+ else "<answer> [your answer] </answer>"
106
+ )
107
+ length_prompt = f"Max response length: {max_tokens} words (tokens)."
108
+
109
+ # --- 核心修改:使用保存的文本状态并拼接 Question ---
110
+ turn_content = (
111
+ f"\nTurn {t + 1}:\n"
112
+ f"State:\n"
113
+ f"{current_text_state}\n" # text_state 已经包含了 === Blackjack Game State === 等内容
114
+ f"What is your next move?\n"
115
+ f"You have {actions_left} actions left. Always output: {format_prompt}"
116
+ f" with no extra text. Strictly follow this format. {length_prompt}"
117
+ )
118
+
119
+ # 追加到上一条 user 消息(如果是第一回合)或者新建 user 消息
120
+ if messages[-1]["role"] == "user":
121
+ messages[-1]["content"] += turn_content
122
+ else:
123
+ messages.append({"role": "user", "content": turn_content})
124
+
125
+ # 添加 Assistant 回复
126
+ action_id = int(actions[t])
127
+ action_name = ACTION_LOOKUP.get(action_id, "unknown")
128
+ assistant_text = (
129
+ f"<think></think><answer>{action_name}</answer>" if enable_think else f"<answer>{action_name}</answer>"
130
+ )
131
+ messages.append({"role": "assistant", "content": assistant_text})
132
+
133
+ # 添加 Reward 信息
134
+ reward_val = rewards[t]
135
+ messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"})
136
+
137
+ # 移除最后一条仅包含 Reward 的 User 消息(SFT 数据通常以 Assistant 结尾)
138
+ if messages[-1]["role"] == "user":
139
+ messages.pop()
140
+
141
+ return messages
142
+
143
+
144
+ def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False, max_actions: int = 10) -> Path:
145
+ traj_path = step_dir / "trajectories.jsonl"
146
+ metrics_path = step_dir / "metrics.json"
147
+ if not traj_path.exists():
148
+ raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
149
+
150
+ instruction, max_tokens, enable_think, action_sep, cfg_max_actions = load_env_instruction_and_cfg(repo_root)
151
+ if max_actions is None:
152
+ max_actions = cfg_max_actions
153
+
154
+ output_dir.mkdir(parents=True, exist_ok=True)
155
+ out_path = output_dir / f"{step_dir.name}_sft.jsonl"
156
+
157
+ global_step = None
158
+ if metrics_path.exists():
159
+ try:
160
+ with open(metrics_path, "r", encoding="utf-8") as f:
161
+ m = json.load(f)
162
+ global_step = m.get("global_step")
163
+ except Exception:
164
+ pass
165
+
166
+ written = 0
167
+ with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
168
+ for line in fin:
169
+ line = line.strip()
170
+ if not line:
171
+ continue
172
+ traj = json.loads(line)
173
+
174
+ ep_success = bool(traj.get("episode_success", False))
175
+ if (not include_failed) and (not ep_success):
176
+ continue
177
+
178
+ # 读取新的 text_states 字段
179
+ text_states = traj.get("text_states", [])
180
+ actions = traj.get("actions", [])
181
+ rewards = traj.get("rewards", [])
182
+
183
+ # 兼容性检查:如果该轨迹是旧代码生成的(没有 text_states),则跳过
184
+ if not text_states:
185
+ # Silently skip or warn
186
+ continue
187
+
188
+ if len(actions) > max_actions:
189
+ continue
190
+
191
+ messages = build_messages_for_episode(
192
+ text_states=text_states,
193
+ actions=actions,
194
+ rewards=rewards,
195
+ instruction=instruction,
196
+ max_tokens=max_tokens,
197
+ enable_think=enable_think,
198
+ max_actions=max_actions,
199
+ )
200
+
201
+ record = {
202
+ "messages": messages,
203
+ "meta": {
204
+ "episode_return": traj.get("episode_return", None),
205
+ "episode_success": ep_success,
206
+ "global_step": global_step,
207
+ },
208
+ }
209
+ fout.write(json.dumps(record, ensure_ascii=False) + "\n")
210
+ written += 1
211
+
212
+ if written == 0:
213
+ # 创建空文件以防报错,或者写入一个空数组
214
+ with open(out_path, "w", encoding="utf-8") as f:
215
+ pass
216
+ print("Warning: No trajectories converted. Check if input file has 'text_states' or if filtering is too strict.")
217
+
218
+ return out_path
219
+
220
+
221
+ def find_latest_step_dir(traj_root: Path) -> Path:
222
+ step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
223
+ if not step_dirs:
224
+ raise FileNotFoundError(f"No step_* directories under {traj_root}")
225
+ step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
226
+ return step_dirs[-1]
227
+
228
+
229
+ def main():
230
+ parser = argparse.ArgumentParser(description="Convert Blackjack RL trajectories to LLM SFT chat JSONL")
231
+ parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)")
232
+ parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_499712)")
233
+ parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
234
+ parser.add_argument("--max_actions", type=int, default=None, help="Max actions cap for filtering and counter display")
235
+ args = parser.parse_args()
236
+
237
+ repo_root = Path(__file__).resolve().parents[1]
238
+ run_dir = Path(args.run_dir)
239
+ traj_root = run_dir / "trajectories"
240
+ if not traj_root.exists():
241
+ raise FileNotFoundError(f"Not found trajectories directory: {traj_root}")
242
+
243
+ step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root)
244
+ output_dir = run_dir / "sft"
245
+ 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)
246
+ print(f"SFT data written to: {out_path}")
247
+
248
+
249
+ if __name__ == "__main__":
250
+ main()
scripts/convert_rl_to_sft_frozenlake.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert RL test trajectories (numeric states/actions) from FrozenLake into
4
+ LLM SFT-ready language trajectories in chat-style messages.
5
+
6
+ Input: runs/<exp>/trajectories/step_XXXXXX/trajectories.jsonl
7
+ Output: runs/<exp>/sft/step_XXXXXX_sft.jsonl
8
+
9
+ Each output JSON line contains:
10
+ - messages: [{role: system|user|assistant, content: str}, ...]
11
+ - meta: {episode_return: float, episode_success: bool, global_step: int}
12
+
13
+ We mirror RAGEN ContextManager’s prompt format as much as possible:
14
+ - system: "You're a helpful assistant. "
15
+ - user: env_instruction + per-turn state blocks with action constraints
16
+ - assistant: "<think></think><answer>Action</answer>" (or without think if disabled)
17
+ - user (reward): "Reward:\n{reward}\n"
18
+ """
19
+
20
+ import argparse
21
+ import json
22
+ import math
23
+ import os
24
+ from pathlib import Path
25
+ from typing import List, Tuple
26
+
27
+ try:
28
+ import yaml # type: ignore
29
+ except Exception:
30
+ yaml = None
31
+
32
+
33
+ ACTION_LOOKUP = {1: "Left", 2: "Down", 3: "Right", 4: "Up"}
34
+
35
+
36
+ def infer_grid_dims(state_vec: List[float]) -> Tuple[int, int]:
37
+ """Infer (rows, cols) from flattened one-hot grid length.
38
+ Our PPO wrapper encodes each cell as one-hot over 6 tokens: ['P','_','O','G','X','√'].
39
+ """
40
+ n = len(state_vec)
41
+ assert n % 6 == 0, f"State length {n} not divisible by 6 (channels)"
42
+ n_cells = n // 6
43
+ r = int(math.isqrt(n_cells))
44
+ assert r * r == n_cells, f"Grid is not square: {n_cells} cells"
45
+ return r, r
46
+
47
+
48
+ def decode_state_to_grid_text(state_vec: List[float]) -> str:
49
+ """Decode numeric state vector back to textual grid.
50
+
51
+ Encoding per PPO wrapper:
52
+ One-hot per cell over tokens = ['P', '_', 'O', 'G', 'X', '√'] in this order.
53
+ The wrapper already encodes P/X/√ directly in the grid; no separate coords needed.
54
+ """
55
+ tokens = ['P', '_', 'O', 'G', 'X', '√']
56
+ rows, cols = infer_grid_dims(state_vec)
57
+ lines = []
58
+ for i in range(rows):
59
+ row_chars = []
60
+ for j in range(cols):
61
+ base = (i * cols + j) * 6
62
+ cell = state_vec[base: base + 6]
63
+ idx = max(range(6), key=lambda k: cell[k])
64
+ ch = tokens[idx] if 0 <= idx < len(tokens) else '_'
65
+ row_chars.append(ch)
66
+ lines.append("".join(row_chars))
67
+ return "\n".join(lines)
68
+
69
+
70
+ def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool]:
71
+ """Load FrozenLake env_instruction, max_tokens, action_sep, enable_think from config.
72
+ Fallbacks are provided if YAML is unavailable.
73
+ """
74
+ default_instruction = (
75
+ "You are solving the FrozenLake puzzle. Forbid the hole and go to the target. "
76
+ "You may move to unintended directions due to slippery ice. "
77
+ "Example answer format: <think>To forbid the hole and go to the target, I should go left then go up.</think><answer>Left || Up</answer>"
78
+ "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 ' || '"
79
+ )
80
+ instruction = default_instruction
81
+ max_tokens = 100
82
+ action_sep = "||"
83
+ enable_think = True
84
+
85
+ if yaml is None:
86
+ return instruction, max_tokens, action_sep, enable_think
87
+
88
+ # envs.yaml
89
+ envs_yaml = repo_root / "config" / "envs.yaml"
90
+ if envs_yaml.exists():
91
+ try:
92
+ with open(envs_yaml, "r", encoding="utf-8") as f:
93
+ envs = yaml.safe_load(f)
94
+ if isinstance(envs, dict) and "FrozenLake" in envs:
95
+ fl = envs["FrozenLake"]
96
+ instruction = fl.get("env_instruction", instruction)
97
+ max_tokens = int(fl.get("max_tokens", max_tokens))
98
+ except Exception:
99
+ pass
100
+
101
+ # base.yaml
102
+ base_yaml = repo_root / "config" / "base.yaml"
103
+ if base_yaml.exists():
104
+ try:
105
+ with open(base_yaml, "r", encoding="utf-8") as f:
106
+ base_cfg = yaml.safe_load(f)
107
+ ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {}
108
+ action_sep = ap.get("action_sep", action_sep)
109
+ enable_think = bool(ap.get("enable_think", enable_think))
110
+ except Exception:
111
+ pass
112
+
113
+ return instruction, max_tokens, action_sep, enable_think
114
+
115
+
116
+ def build_messages_for_episode(
117
+ states: List[List[float]],
118
+ actions: List[int],
119
+ rewards: List[float],
120
+ instruction: str,
121
+ max_tokens: int,
122
+ action_sep: str,
123
+ enable_think: bool,
124
+ ) -> List[dict]:
125
+ """Construct chat messages mirroring ContextManager format.
126
+
127
+ - First system message.
128
+ - One user message containing the instruction and per-turn state blocks.
129
+ - Assistant messages per executed action with tag-only outputs.
130
+ - User messages for rewards.
131
+ """
132
+ messages = [
133
+ {"role": "system", "content": "You're a helpful assistant. "},
134
+ {"role": "user", "content": instruction},
135
+ ]
136
+
137
+ total_actions = len(actions)
138
+ # Append state blocks into the initial user content
139
+ for t, state in enumerate(states):
140
+ grid_text = decode_state_to_grid_text(state)
141
+ actions_left = max(0, total_actions - t) # before taking action at turn t
142
+ format_prompt = (
143
+ "<think> [Your thoughts] </think> <answer> [your answer] </answer>"
144
+ if enable_think
145
+ else "<answer> [your answer] </answer>"
146
+ )
147
+ length_prompt = f"Max response length: {max_tokens} words (tokens)."
148
+
149
+ messages[-1]["content"] += (
150
+ f"\nTurn {t + 1}:\n"
151
+ f"State:\n{grid_text}\n"
152
+ f"You have {actions_left} actions left. Always output: {format_prompt} "
153
+ f"with no extra text. Strictly follow this format. {length_prompt}\n"
154
+ )
155
+ # If action exists for this turn, add assistant + reward
156
+ if t < total_actions:
157
+ # Map RL action (0..3) -> RAGEN action (1..4) -> text
158
+ action_id = actions[t] + 1
159
+ action_name = ACTION_LOOKUP.get(action_id, "unknown")
160
+ if enable_think:
161
+ assistant_text = f"<think></think><answer>{action_name}</answer>"
162
+ else:
163
+ assistant_text = f"<answer>{action_name}</answer>"
164
+ messages.append({"role": "assistant", "content": assistant_text})
165
+ # Reward message
166
+ reward_val = rewards[t] if t < len(rewards) else 0.0
167
+ messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"})
168
+ # import pdb;pdb.set_trace()
169
+ messages.append({"role": "assistant", "content": "<think>"})
170
+ return messages
171
+
172
+
173
+ def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False) -> Path:
174
+ traj_path = step_dir / "trajectories.jsonl"
175
+ metrics_path = step_dir / "metrics.json"
176
+ if not traj_path.exists():
177
+ raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
178
+
179
+ instruction, max_tokens, action_sep, enable_think = load_env_instruction_and_cfg(repo_root)
180
+
181
+ output_dir.mkdir(parents=True, exist_ok=True)
182
+ out_path = output_dir / f"{step_dir.name}_sft.jsonl"
183
+
184
+ # Read global step from metrics if available
185
+ global_step = None
186
+ if metrics_path.exists():
187
+ try:
188
+ with open(metrics_path, "r", encoding="utf-8") as f:
189
+ m = json.load(f)
190
+ global_step = m.get("global_step")
191
+ except Exception:
192
+ pass
193
+
194
+ written = 0
195
+ with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
196
+ for line in fin:
197
+ line = line.strip()
198
+ if not line:
199
+ continue
200
+ traj = json.loads(line)
201
+ # Filter if requested
202
+ ep_success = bool(traj.get("episode_success", False))
203
+ if (not include_failed) and (not ep_success):
204
+ continue
205
+
206
+ states = traj.get("states", [])
207
+ actions = traj.get("actions", [])
208
+ rewards = traj.get("rewards", [])
209
+ messages = build_messages_for_episode(
210
+ states=states,
211
+ actions=actions,
212
+ rewards=rewards,
213
+ instruction=instruction,
214
+ max_tokens=max_tokens,
215
+ action_sep=action_sep,
216
+ enable_think=enable_think,
217
+ )
218
+
219
+ record = {
220
+ "messages": messages,
221
+ "meta": {
222
+ "episode_return": traj.get("episode_return", None),
223
+ "episode_success": ep_success,
224
+ "global_step": global_step,
225
+ },
226
+ }
227
+ fout.write(json.dumps(record, ensure_ascii=False) + "\n")
228
+ written += 1
229
+
230
+ if written == 0:
231
+ # Still write an empty file to signal conversion executed
232
+ with open(out_path, "w", encoding="utf-8") as f:
233
+ pass
234
+ return out_path
235
+
236
+
237
+ def find_latest_step_dir(traj_root: Path) -> Path:
238
+ step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
239
+ if not step_dirs:
240
+ raise FileNotFoundError(f"No step_* directories under {traj_root}")
241
+ # Sort by numeric suffix
242
+ step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
243
+ return step_dirs[-1]
244
+
245
+
246
+ def main():
247
+ parser = argparse.ArgumentParser(description="Convert FrozenLake RL trajectories to LLM SFT chat JSONL")
248
+ parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)" )
249
+ parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)")
250
+ parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
251
+ args = parser.parse_args()
252
+
253
+ repo_root = Path(__file__).resolve().parents[1]
254
+ run_dir = Path(args.run_dir)
255
+ traj_root = run_dir / "trajectories"
256
+ if not traj_root.exists():
257
+ raise FileNotFoundError(f"Not found trajectories directory: {traj_root}")
258
+
259
+ step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root)
260
+ output_dir = run_dir / "sft"
261
+ out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed)
262
+ print(f"SFT data written to: {out_path}")
263
+
264
+
265
+ if __name__ == "__main__":
266
+ main()
267
+
scripts/convert_rl_to_sft_frozenlake_daoshuaction.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import json
5
+ import math
6
+ import os
7
+ from pathlib import Path
8
+ from typing import List, Tuple
9
+
10
+ try:
11
+ import yaml # type: ignore
12
+ except Exception:
13
+ yaml = None
14
+
15
+
16
+ ACTION_LOOKUP = {1: "Left", 2: "Down", 3: "Right", 4: "Up"}
17
+
18
+
19
+ def infer_grid_dims(state_vec: List[float]) -> Tuple[int, int]:
20
+ """Infer (rows, cols) from flattened one-hot grid length.
21
+ Our PPO wrapper encodes each cell as one-hot over 6 tokens: ['P','_','O','G','X','√'].
22
+ """
23
+ n = len(state_vec)
24
+ assert n % 6 == 0, f"State length {n} not divisible by 6 (channels)"
25
+ n_cells = n // 6
26
+ r = int(math.isqrt(n_cells))
27
+ assert r * r == n_cells, f"Grid is not square: {n_cells} cells"
28
+ return r, r
29
+
30
+
31
+ def decode_state_to_grid_text(state_vec: List[float]) -> str:
32
+ """Decode numeric state vector back to textual grid.
33
+
34
+ Encoding per PPO wrapper:
35
+ One-hot per cell over tokens = ['P', '_', 'O', 'G', 'X', '√'] in this order.
36
+ The wrapper already encodes P/X/√ directly in the grid; no separate coords needed.
37
+ """
38
+ tokens = ['P', '_', 'O', 'G', 'X', '√']
39
+ rows, cols = infer_grid_dims(state_vec)
40
+ lines = []
41
+ for i in range(rows):
42
+ row_chars = []
43
+ for j in range(cols):
44
+ base = (i * cols + j) * 6
45
+ cell = state_vec[base: base + 6]
46
+ idx = max(range(6), key=lambda k: cell[k])
47
+ ch = tokens[idx] if 0 <= idx < len(tokens) else '_'
48
+ row_chars.append(ch)
49
+ lines.append("".join(row_chars))
50
+ return "\n".join(lines)
51
+
52
+
53
+ def parse_positions_from_state(state_vec: List[float]):
54
+ """Extract board size, player, goal, and holes positions from one-hot state.
55
+ - Player is where token is one of ['P','X','√'].
56
+ - Goal is where token is 'G'.
57
+ - Holes include all 'O' cells; if player is on hole ('X'), include that cell as a hole as well.
58
+ Returns: (rows, cols, (pr, pc), (gr, gc) or None, holes: List[(r,c)])
59
+ """
60
+ tokens = ['P', '_', 'O', 'G', 'X', '√']
61
+ rows, cols = infer_grid_dims(state_vec)
62
+ player = None
63
+ goal = None
64
+ holes: List[Tuple[int, int]] = []
65
+ for i in range(rows):
66
+ for j in range(cols):
67
+ base = (i * cols + j) * 6
68
+ cell = state_vec[base: base + 6]
69
+ idx = max(range(6), key=lambda k: cell[k])
70
+ if idx == 0 or idx == 4 or idx == 5: # P or X or √
71
+ player = (i, j)
72
+ if idx == 4: # X means on a hole
73
+ holes.append((i, j))
74
+ elif idx == 2: # O
75
+ holes.append((i, j))
76
+ elif idx == 3: # G
77
+ goal = (i, j)
78
+ return rows, cols, player, goal, holes
79
+
80
+
81
+ def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool]:
82
+ """Load FrozenLake env_instruction, max_tokens, action_sep, enable_think from config.
83
+ Fallbacks are provided if YAML is unavailable.
84
+ """
85
+ default_instruction = (
86
+ "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"
87
+ "Coordinates range from the top-left corner (0, 0) to the bottom-right corner (5, 5).\n"
88
+ "Beware that the ice is slippery, so the agent might slide and end up in an unintended tile.\n"
89
+ "Respond with a sequence of actions such as <answer>Left || Up || Up</answer>.\n"
90
+ "\nThe meaning of each symbol in the state is:\n"
91
+ "P: player, _: empty, O: hole, G: goal, X: player in hole, √: player on goal\n"
92
+ "Your available actions are:\n"
93
+ "Left, Down, Right, Up\n"
94
+ "You can make up to 25 actions, separated by the action separator \" || \"\n"
95
+ )
96
+ instruction = default_instruction
97
+ max_tokens = 100
98
+ action_sep = "||"
99
+ enable_think = True
100
+
101
+ if yaml is None:
102
+ return instruction, max_tokens, action_sep, enable_think
103
+
104
+ # envs.yaml
105
+ envs_yaml = repo_root / "config" / "envs.yaml"
106
+ if envs_yaml.exists():
107
+ try:
108
+ with open(envs_yaml, "r", encoding="utf-8") as f:
109
+ envs = yaml.safe_load(f)
110
+ if isinstance(envs, dict) and "FrozenLake" in envs:
111
+ fl = envs["FrozenLake"]
112
+ instruction = fl.get("env_instruction", instruction)
113
+ max_tokens = int(fl.get("max_tokens", max_tokens))
114
+ except Exception:
115
+ pass
116
+
117
+ # base.yaml
118
+ base_yaml = repo_root / "config" / "base.yaml"
119
+ if base_yaml.exists():
120
+ try:
121
+ with open(base_yaml, "r", encoding="utf-8") as f:
122
+ base_cfg = yaml.safe_load(f)
123
+ ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {}
124
+ action_sep = ap.get("action_sep", action_sep)
125
+ enable_think = bool(ap.get("enable_think", enable_think))
126
+ except Exception:
127
+ pass
128
+
129
+ return instruction, max_tokens, action_sep, enable_think
130
+
131
+
132
+ def build_messages_for_episode(
133
+ states: List[List[float]],
134
+ actions: List[int],
135
+ rewards: List[float],
136
+ instruction: str,
137
+ max_tokens: int,
138
+ action_sep: str,
139
+ enable_think: bool,
140
+ max_actions: int,
141
+ ) -> List[dict]:
142
+ """Construct chat messages mirroring ContextManager format.
143
+
144
+ - First system message.
145
+ - One user message containing the instruction and per-turn state blocks.
146
+ - Assistant messages per executed action with tag-only outputs.
147
+ - User messages for rewards.
148
+ """
149
+ messages = [
150
+ {"role": "system", "content": "You're a helpful assistant. "},
151
+ {"role": "user", "content": instruction},
152
+ ]
153
+
154
+ total_actions = len(actions)
155
+ # Determine start position from the first state's player
156
+ start_rows, start_cols, start_player, start_goal, start_holes = parse_positions_from_state(states[0]) if states else (0, 0, None, None, [])
157
+ # Append state blocks into the initial user content
158
+ for t, state in enumerate(states):
159
+ grid_text = decode_state_to_grid_text(state)
160
+ rows, cols, player_pos, goal_pos, holes_pos = parse_positions_from_state(state)
161
+ # Start counter from max_actions (e.g., 25) regardless of episode length
162
+ actions_left = max(0, max_actions - t)
163
+ format_prompt = (
164
+ "<think> [Your thoughts] </think> <answer> [your answer] </answer>"
165
+ if enable_think
166
+ else "<answer> [your answer] </answer>"
167
+ )
168
+ length_prompt = f"Max response length: {max_tokens} words (tokens)."
169
+
170
+ messages[-1]["content"] += (
171
+ f"\nTurn {t + 1}:\n"
172
+ f"State:\n"
173
+ f"Coordinates:\n"
174
+ f"Board size: {rows} rows x {cols} cols (zero-indexed).\n"
175
+ f"Start: {start_player if start_player is not None else (-1, -1)}\n"
176
+ f"Goal: {goal_pos if goal_pos is not None else (-1, -1)}\n"
177
+ f"Player: {player_pos if player_pos is not None else (-1, -1)}\n"
178
+ f"Holes: {holes_pos}\n"
179
+ f"Grid Map:\n{grid_text}\n"
180
+ f"You have {actions_left} actions left. Always output: {format_prompt}"
181
+ f"with no extra text. Strictly follow this format. {length_prompt}"
182
+ )
183
+ # If action exists for this turn, add assistant + reward
184
+ if t < total_actions:
185
+ # Map RL action (0..3) -> RAGEN action (1..4) -> text
186
+ action_id = actions[t] + 1
187
+ action_name = ACTION_LOOKUP.get(action_id, "unknown")
188
+ if enable_think:
189
+ assistant_text = f"<think></think><answer>{action_name}</answer>"
190
+ else:
191
+ assistant_text = f"<answer>{action_name}</answer>"
192
+ messages.append({"role": "assistant", "content": assistant_text})
193
+ # Reward message
194
+ reward_val = rewards[t] if t < len(rewards) else 0.0
195
+ messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"})
196
+ # import pdb;pdb.set_trace()
197
+
198
+ return messages[:-1]
199
+
200
+
201
+ def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False, max_actions: int = 25) -> Path:
202
+ traj_path = step_dir / "trajectories.jsonl"
203
+ metrics_path = step_dir / "metrics.json"
204
+ if not traj_path.exists():
205
+ raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
206
+
207
+ instruction, max_tokens, action_sep, enable_think = load_env_instruction_and_cfg(repo_root)
208
+
209
+ output_dir.mkdir(parents=True, exist_ok=True)
210
+ out_path = output_dir / f"{step_dir.name}_sft.jsonl"
211
+
212
+ # Read global step from metrics if available
213
+ global_step = None
214
+ if metrics_path.exists():
215
+ try:
216
+ with open(metrics_path, "r", encoding="utf-8") as f:
217
+ m = json.load(f)
218
+ global_step = m.get("global_step")
219
+ except Exception:
220
+ pass
221
+
222
+ written = 0
223
+ with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
224
+ for line in fin:
225
+ line = line.strip()
226
+ if not line:
227
+ continue
228
+ traj = json.loads(line)
229
+ # Filter if requested
230
+ ep_success = bool(traj.get("episode_success", False))
231
+ if (not include_failed) and (not ep_success):
232
+ continue
233
+
234
+ states = traj.get("states", [])
235
+ actions = traj.get("actions", [])
236
+ rewards = traj.get("rewards", [])
237
+ # Filter: keep only episodes with total actions <= max_actions
238
+ if len(actions) > max_actions:
239
+ continue
240
+ messages = build_messages_for_episode(
241
+ states=states,
242
+ actions=actions,
243
+ rewards=rewards,
244
+ instruction=instruction,
245
+ max_tokens=max_tokens,
246
+ action_sep=action_sep,
247
+ enable_think=enable_think,
248
+ max_actions=max_actions,
249
+ )
250
+
251
+ record = {
252
+ "messages": messages,
253
+ "meta": {
254
+ "episode_return": traj.get("episode_return", None),
255
+ "episode_success": ep_success,
256
+ "global_step": global_step,
257
+ },
258
+ }
259
+ fout.write(json.dumps(record, ensure_ascii=False) + "\n")
260
+ written += 1
261
+
262
+ if written == 0:
263
+ # Still write an empty file to signal conversion executed
264
+ with open(out_path, "w", encoding="utf-8") as f:
265
+ pass
266
+ return out_path
267
+
268
+
269
+ def find_latest_step_dir(traj_root: Path) -> Path:
270
+ step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
271
+ if not step_dirs:
272
+ raise FileNotFoundError(f"No step_* directories under {traj_root}")
273
+ # Sort by numeric suffix
274
+ step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
275
+ return step_dirs[-1]
276
+
277
+
278
+ def main():
279
+ parser = argparse.ArgumentParser(description="Convert FrozenLake RL trajectories to LLM SFT chat JSONL")
280
+ parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)" )
281
+ parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)")
282
+ parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
283
+ parser.add_argument("--max_actions", type=int, default=25, help="Max actions cap for filtering and counter display")
284
+ args = parser.parse_args()
285
+
286
+ repo_root = Path(__file__).resolve().parents[1]
287
+ run_dir = Path(args.run_dir)
288
+ traj_root = run_dir / "trajectories"
289
+ if not traj_root.exists():
290
+ raise FileNotFoundError(f"Not found trajectories directory: {traj_root}")
291
+
292
+ step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root)
293
+ output_dir = run_dir / "sft"
294
+ 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)
295
+ print(f"SFT data written to: {out_path}")
296
+
297
+
298
+ if __name__ == "__main__":
299
+ main()
300
+
scripts/convert_rl_to_sft_rubikscube.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert RL eval trajectories from Rubik's Cube 2x2 into LLM SFT-ready chat data.
4
+
5
+ Input: runs/<exp>/trajectories/step_XXXXXX/trajectories.jsonl
6
+ Output: runs/<exp>/sft/step_XXXXXX_sft.jsonl
7
+
8
+ Each output JSON line contains:
9
+ - messages: [{role: system|user|assistant, content: str}, ...]
10
+ - meta: {episode_return: float, episode_success: bool, global_step: int}
11
+
12
+ We mirror the FrozenLake converter structure:
13
+ - system: "You're a helpful assistant. "
14
+ - user: env_instruction + per-turn state blocks
15
+ - assistant: tag-only actions, one per step
16
+ - user: reward after each action
17
+ """
18
+
19
+ import argparse
20
+ import json
21
+ from pathlib import Path
22
+ from typing import List, Tuple
23
+
24
+ try:
25
+ import yaml # type: ignore
26
+ except Exception:
27
+ yaml = None
28
+
29
+
30
+ # Rubik's 2x2 actions (env uses 1..12; PPO wrapper stores 0..11)
31
+ RUBIK_ACTIONS = [
32
+ "U", "U'", "D", "D'", "L", "L'", "R", "R'", "F", "F'", "B", "B'",
33
+ ]
34
+
35
+ COLORS = ['W', 'O', 'G', 'R', 'B', 'Y']
36
+
37
+
38
+ def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool, int]:
39
+ """Load RubiksCube2x2 env instruction and base agent_proxy configs.
40
+ Returns: (instruction, max_tokens, action_sep, enable_think, max_actions)
41
+ """
42
+ instruction = (
43
+ "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"
44
+ "Available actions use standard Singmaster notation for face rotations: U, U', D, D', L, L', R, R', F, F', B, B'.\n"
45
+ "- Faces: U (Up), D (Down), L (Left), R (Right), F (Front), B (Back).\n"
46
+ "- Modifiers: A letter alone means 90° clockwise (e.g., 'R'). A letter with prime (') means 90° counter-clockwise (e.g., \"R'\")."
47
+ "Respond with a sequence of actions separated by \"||\".\n"
48
+ "Example: <answer>U</answer>\n\n"
49
+ "Your available actions are:\n"
50
+ "U, U', D, D', L, L', R, R', F, F', B, B'\n"
51
+ "You can make up to 20 actions, separated by the action separator \" || \"\n"
52
+ )
53
+ max_tokens = 96
54
+ action_sep = "||"
55
+ enable_think = True
56
+ max_actions = 20
57
+
58
+ if yaml is None:
59
+ return instruction, max_tokens, action_sep, enable_think, max_actions
60
+
61
+ # envs.yaml
62
+ envs_yaml = repo_root / "config" / "envs.yaml"
63
+ if envs_yaml.exists():
64
+ try:
65
+ with open(envs_yaml, "r", encoding="utf-8") as f:
66
+ envs = yaml.safe_load(f)
67
+ if isinstance(envs, dict) and "custom_envs" in envs and "RubiksCube2x2" in envs["custom_envs"]:
68
+ e = envs["custom_envs"]["RubiksCube2x2"]
69
+ instruction = e.get("env_instruction", instruction)
70
+ max_tokens = int(e.get("max_tokens", max_tokens))
71
+ max_actions = int(e.get("max_actions_per_traj", max_actions))
72
+ except Exception:
73
+ pass
74
+
75
+ # base.yaml
76
+ base_yaml = repo_root / "config" / "base.yaml"
77
+ if base_yaml.exists():
78
+ try:
79
+ with open(base_yaml, "r", encoding="utf-8") as f:
80
+ base_cfg = yaml.safe_load(f)
81
+ ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {}
82
+ action_sep = ap.get("action_sep", action_sep)
83
+ enable_think = bool(ap.get("enable_think", enable_think))
84
+ except Exception:
85
+ pass
86
+
87
+ return instruction, max_tokens, action_sep, enable_think, max_actions
88
+
89
+
90
+ def decode_state_to_text(state_vec: List[float]) -> str:
91
+ """Decode one-hot length 24*6 vector into sticker letters.
92
+ Returns a compact textual block listing each face in order: U, L, F, R, B, D.
93
+ """
94
+ if not state_vec:
95
+ return ""
96
+ n = len(state_vec)
97
+ if n % len(COLORS) != 0:
98
+ return ""
99
+ n_stickers = n // len(COLORS)
100
+ if n_stickers != 24:
101
+ # Unknown shape; still try to decode row-wise
102
+ pass
103
+ # decode one-hot to color letter per sticker
104
+ stickers: List[str] = []
105
+ for i in range(n_stickers):
106
+ base = i * len(COLORS)
107
+ cell = state_vec[base: base + len(COLORS)]
108
+ idx = max(range(len(COLORS)), key=lambda k: cell[k])
109
+ c = COLORS[idx] if 0 <= idx < len(COLORS) else '?'
110
+ stickers.append(c)
111
+ # format faces (4 stickers per face)
112
+ faces = [stickers[i*4:(i+1)*4] for i in range(6)]
113
+ face_names = ["Up (U)", "Left (L)", "Front (F)", "Right (R)", "Back (B)", "Down (D)"]
114
+ lines = ["=== Rubik's Cube 2x2 State ===\n"]
115
+ for name, face in zip(face_names, faces):
116
+ lines.append(f"{name}: [{face[0]}, {face[1]}] \n [{face[2]}, {face[3]}]")
117
+ lines.append("\nAvailable actions: \n" + ", ".join(RUBIK_ACTIONS))
118
+ return "\n".join(lines)
119
+
120
+
121
+ def build_messages_for_episode(
122
+ states: List[List[float]],
123
+ actions: List[int],
124
+ rewards: List[float],
125
+ instruction: str,
126
+ max_tokens: int,
127
+ action_sep: str,
128
+ enable_think: bool,
129
+ max_actions: int,
130
+ ) -> List[dict]:
131
+ messages = [
132
+ {"role": "system", "content": "You're a helpful assistant. "},
133
+ {"role": "user", "content": instruction},
134
+ ]
135
+
136
+ total_actions = len(actions)
137
+ for t, state in enumerate(states):
138
+ state_text = decode_state_to_text(state)
139
+ actions_left = max(0, max_actions - t)
140
+ format_prompt = (
141
+ "<think> [Your thoughts] </think> <answer> [your answer] </answer>"
142
+ if enable_think
143
+ else "<answer> [your answer] </answer>"
144
+ )
145
+ length_prompt = f"Max response length: {max_tokens} words (tokens)."
146
+
147
+ messages[-1]["content"] += (
148
+ f"\nTurn {t + 1}:\n"
149
+ f"State:\n{state_text}\n"
150
+ f"\nWhat is your next move?\n"
151
+ f"You have {actions_left} actions left. Always output: {format_prompt}"
152
+ f"with no extra text. {length_prompt}"
153
+ )
154
+
155
+ if t < total_actions:
156
+ a = actions[t]
157
+ a_name = RUBIK_ACTIONS[int(a)] if 0 <= int(a) < len(RUBIK_ACTIONS) else str(a)
158
+ if enable_think:
159
+ assistant_text = f"<think> </think><answer>{a_name}</answer>"
160
+ else:
161
+ assistant_text = f"<answer>{a_name}</answer>"
162
+ messages.append({"role": "assistant", "content": assistant_text})
163
+ r = rewards[t] if t < len(rewards) else 0.0
164
+ messages.append({"role": "user", "content": f"Reward:\n{r}\n"})
165
+ # import pdb;pdb.set_trace()
166
+ return messages[:-1]
167
+
168
+
169
+ def find_latest_step_dir(traj_root: Path) -> Path:
170
+ step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
171
+ if not step_dirs:
172
+ raise FileNotFoundError(f"No step_* directories under {traj_root}")
173
+ step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
174
+ return step_dirs[-1]
175
+
176
+
177
+ def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool, max_actions_cap: int | None) -> Path:
178
+ traj_path = step_dir / "trajectories.jsonl"
179
+ metrics_path = step_dir / "metrics.json"
180
+ if not traj_path.exists():
181
+ raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
182
+
183
+ instruction, max_tokens, action_sep, enable_think, default_max_actions = load_env_instruction_and_cfg(repo_root)
184
+ max_actions = int(max_actions_cap) if max_actions_cap is not None else int(default_max_actions)
185
+
186
+ output_dir.mkdir(parents=True, exist_ok=True)
187
+ out_path = output_dir / f"{step_dir.name}_sft.jsonl"
188
+
189
+ # Read global step from metrics if available
190
+ global_step = None
191
+ if metrics_path.exists():
192
+ try:
193
+ with open(metrics_path, "r", encoding="utf-8") as f:
194
+ m = json.load(f)
195
+ global_step = m.get("global_step")
196
+ except Exception:
197
+ pass
198
+
199
+ written = 0
200
+ with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
201
+ for line in fin:
202
+ line = line.strip()
203
+ if not line:
204
+ continue
205
+ traj = json.loads(line)
206
+
207
+ ep_success = bool(traj.get("episode_success", False))
208
+ if (not include_failed) and (not ep_success):
209
+ continue
210
+
211
+ states = traj.get("states", [])
212
+ actions = traj.get("actions", [])
213
+ rewards = traj.get("rewards", [])
214
+ if len(actions) > max_actions:
215
+ continue
216
+
217
+ messages = build_messages_for_episode(
218
+ states=states,
219
+ actions=actions,
220
+ rewards=rewards,
221
+ instruction=instruction,
222
+ max_tokens=max_tokens,
223
+ action_sep=action_sep,
224
+ enable_think=enable_think,
225
+ max_actions=max_actions,
226
+ )
227
+
228
+ record = {
229
+ "messages": messages,
230
+ "meta": {
231
+ "episode_return": traj.get("episode_return", None),
232
+ "episode_success": ep_success,
233
+ "global_step": global_step,
234
+ },
235
+ }
236
+ fout.write(json.dumps(record, ensure_ascii=False) + "\n")
237
+ written += 1
238
+
239
+ if written == 0:
240
+ with open(out_path, "w", encoding="utf-8"):
241
+ pass
242
+ return out_path
243
+
244
+
245
+ def main():
246
+ parser = argparse.ArgumentParser(description="Convert Rubik's Cube 2x2 RL trajectories to LLM SFT chat JSONL")
247
+ parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)")
248
+ parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_123456)")
249
+ parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
250
+ parser.add_argument("--max_actions", type=int, default=None, help="Override max actions cap (default from envs.yaml)")
251
+ args = parser.parse_args()
252
+
253
+ repo_root = Path(__file__).resolve().parents[1]
254
+ run_dir = Path(args.run_dir)
255
+ traj_root = run_dir / "trajectories"
256
+ if not traj_root.exists():
257
+ raise FileNotFoundError(f"Not found trajectories directory: {traj_root}")
258
+
259
+ step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root)
260
+ output_dir = run_dir / "sft"
261
+ 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)
262
+ print(f"SFT data written to: {out_path}")
263
+
264
+
265
+ if __name__ == "__main__":
266
+ main()
scripts/convert_rl_to_sft_sokoban.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ from typing import List, Tuple
7
+
8
+ try:
9
+ import yaml # type: ignore
10
+ except Exception:
11
+ yaml = None
12
+
13
+ # Sokoban tokens and actions (as used by SokobanWrapper)
14
+ TOKENS = ['#', '_', 'O', '√', 'X', 'P', 'S']
15
+ ACTION_LOOKUP = {1: 'Up', 2: 'Down', 3: 'Left', 4: 'Right'}
16
+
17
+
18
+ def infer_grid_dims(state_arr: List[List[List[float]]]) -> Tuple[int, int, int]:
19
+ c = len(state_arr)
20
+ h = len(state_arr[0]) if c > 0 else 0
21
+ w = len(state_arr[0][0]) if (c > 0 and h > 0) else 0
22
+ return c, h, w
23
+
24
+
25
+ def decode_state_to_grid_text(state_arr: List[List[List[float]]]) -> str:
26
+ c, h, w = infer_grid_dims(state_arr)
27
+ lines = []
28
+ for i in range(h):
29
+ row = []
30
+ for j in range(w):
31
+ argmax_k = 0
32
+ vmax = -1e9
33
+ for k in range(c):
34
+ v = state_arr[k][i][j]
35
+ if v > vmax:
36
+ vmax = v
37
+ argmax_k = k
38
+ ch = TOKENS[argmax_k] if 0 <= argmax_k < len(TOKENS) else '_'
39
+ row.append(ch)
40
+ lines.append(''.join(row))
41
+ return '\n'.join(lines)
42
+
43
+
44
+ def parse_positions_from_state(state_arr: List[List[List[float]]]):
45
+ """Extract board size, targets, boxes, and player coordinates from one-hot state.
46
+ - 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)
47
+ - Targets include cells with 'O' or '√'.
48
+ - Boxes include cells with 'X' or '√'.
49
+ - Player is where token is 'P' or 'S'.
50
+ Returns: (rows, cols, targets: List[(r,c)], boxes: List[(r,c)], player: (r,c) or None)
51
+ """
52
+ c, h, w = infer_grid_dims(state_arr)
53
+ targets: List[Tuple[int, int]] = []
54
+ boxes: List[Tuple[int, int]] = []
55
+ player: Tuple[int, int] | None = None
56
+ for i in range(h):
57
+ for j in range(w):
58
+ # argmax over channels
59
+ argk = 0
60
+ vmax = -1e9
61
+ for k in range(c):
62
+ v = state_arr[k][i][j]
63
+ if v > vmax:
64
+ vmax = v
65
+ argk = k
66
+ if argk == 2: # 'O' target
67
+ targets.append((i, j))
68
+ elif argk == 3: # '√' box on target (both a box and a target)
69
+ targets.append((i, j))
70
+ boxes.append((i, j))
71
+ elif argk == 4: # 'X' box
72
+ boxes.append((i, j))
73
+ elif argk == 5 or argk == 6: # 'P' or 'S' (player or player on target)
74
+ player = (i, j)
75
+ return h, w, targets, boxes, player
76
+
77
+
78
+ def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool]:
79
+ instruction = (
80
+ "You are solving the Sokoban puzzle. You are the player and you need to push all boxes to targets. "
81
+ "When you are right next to a box, you can push it by moving in the same direction. "
82
+ "You cannot push a box through a wall, and you cannot pull a box. "
83
+ "The answer should be a sequence of actions, like <answer>Right || Right || Up</answer>\n"
84
+ "\nThe meaning of each symbol in the state is:\n"
85
+ "#: wall, _: empty, O: target, √: box on target, X: box, P: player, S: player on target\n"
86
+ "Your available actions are:\n"
87
+ "Up, Down, Left, Right\n"
88
+ "You can make up to 10 actions, separated by the action separator \" || \"\n"
89
+ )
90
+ max_tokens = 100
91
+ action_sep = "||"
92
+ enable_think = True
93
+
94
+ if yaml is None:
95
+ return instruction, max_tokens, action_sep, enable_think
96
+
97
+ envs_yaml = repo_root / "config" / "envs.yaml"
98
+ if envs_yaml.exists():
99
+ try:
100
+ with open(envs_yaml, "r", encoding="utf-8") as f:
101
+ envs = yaml.safe_load(f)
102
+ custom_envs = envs.get("custom_envs", {}) if isinstance(envs, dict) else {}
103
+ if isinstance(custom_envs, dict):
104
+ # Prefer CoordSokoban, fallback to SimpleSokoban, then LargerSokoban
105
+ for key in ["CoordSokoban", "SimpleSokoban", "LargerSokoban", "SokobanDifferentGridVocab"]:
106
+ if key in custom_envs:
107
+ cfg = custom_envs[key]
108
+ instruction = cfg.get("env_instruction", instruction)
109
+ max_tokens = int(cfg.get("max_tokens", max_tokens))
110
+ break
111
+ except Exception:
112
+ pass
113
+
114
+ base_yaml = repo_root / "config" / "base.yaml"
115
+ if base_yaml.exists():
116
+ try:
117
+ with open(base_yaml, "r", encoding="utf-8") as f:
118
+ base_cfg = yaml.safe_load(f)
119
+ ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {}
120
+ action_sep = ap.get("action_sep", action_sep)
121
+ enable_think = bool(ap.get("enable_think", enable_think))
122
+ except Exception:
123
+ pass
124
+
125
+ return instruction, max_tokens, action_sep, enable_think
126
+
127
+
128
+ def build_messages_for_episode(
129
+ states: List[List[List[List[float]]]],
130
+ actions: List[int],
131
+ rewards: List[float],
132
+ instruction: str,
133
+ max_tokens: int,
134
+ action_sep: str,
135
+ enable_think: bool,
136
+ max_actions: int,
137
+ ) -> List[dict]:
138
+ messages = [
139
+ {"role": "system", "content": "You're a helpful assistant. "},
140
+ {"role": "user", "content": instruction},
141
+ ]
142
+
143
+ total_actions = len(actions)
144
+ # states contain T+1 elements typically; we iterate over min(len(states), len(actions)) turns
145
+ for t, state in enumerate(states):
146
+ grid_text = decode_state_to_grid_text(state)
147
+ rows, cols, targets_pos, boxes_pos, player_pos = parse_positions_from_state(state)
148
+ actions_left = max(0, max_actions - t)
149
+ if enable_think:
150
+ format_prompt = "<think> [Your thoughts] </think> <answer> [your answer] </answer>"
151
+ else:
152
+ format_prompt = "<answer> [your answer] </answer>"
153
+ length_prompt = f"Max response length: {max_tokens} words (tokens)."
154
+
155
+ messages[-1]["content"] += (
156
+ f"\nTurn {t + 1}:\n"
157
+ f"State:\n"
158
+ f"Coordinates:\n"
159
+ f"Board size: {rows} rows x {cols} cols (zero-indexed).\n"
160
+ f"Targets: {targets_pos}\n"
161
+ f"Boxes: {boxes_pos}\n"
162
+ f"Player: {player_pos if player_pos is not None else (-1, -1)}\n"
163
+ f"Grid Map:\n{grid_text}\n"
164
+ f"You have {actions_left} actions left. Always output: {format_prompt}"
165
+ f"with no extra text. Strictly follow this format. {length_prompt}"
166
+ )
167
+
168
+ if t < total_actions:
169
+ action_id = actions[t] + 1 # map 0..3 -> 1..4
170
+ action_name = ACTION_LOOKUP.get(action_id, "unknown")
171
+ assistant_text = f"<answer>{action_name}</answer>" if not enable_think else f"<think></think><answer>{action_name}</answer>"
172
+ messages.append({"role": "assistant", "content": assistant_text})
173
+ reward_val = rewards[t] if t < len(rewards) else 0.0
174
+ messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"})
175
+
176
+ return messages[:-1]
177
+
178
+
179
+ def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False, max_actions: int = 10) -> Path:
180
+ traj_path = step_dir / "trajectories.jsonl"
181
+ metrics_path = step_dir / "metrics.json"
182
+ if not traj_path.exists():
183
+ raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
184
+
185
+ instruction, max_tokens, action_sep, enable_think = load_env_instruction_and_cfg(repo_root)
186
+
187
+ output_dir.mkdir(parents=True, exist_ok=True)
188
+ out_path = output_dir / f"{step_dir.name}_sft.jsonl"
189
+
190
+ global_step = None
191
+ if metrics_path.exists():
192
+ try:
193
+ with open(metrics_path, "r", encoding="utf-8") as f:
194
+ m = json.load(f)
195
+ global_step = m.get("global_step")
196
+ except Exception:
197
+ pass
198
+
199
+ written = 0
200
+ with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
201
+ for line in fin:
202
+ line = line.strip()
203
+ if not line:
204
+ continue
205
+ traj = json.loads(line)
206
+ ep_success = bool(traj.get("episode_success", False))
207
+ if (not include_failed) and (not ep_success):
208
+ continue
209
+
210
+ states = traj.get("states", [])
211
+ actions = traj.get("actions", [])
212
+ rewards = traj.get("rewards", [])
213
+ if len(actions) > max_actions:
214
+ continue
215
+
216
+ messages = build_messages_for_episode(
217
+ states=states,
218
+ actions=actions,
219
+ rewards=rewards,
220
+ instruction=instruction,
221
+ max_tokens=max_tokens,
222
+ action_sep=action_sep,
223
+ enable_think=enable_think,
224
+ max_actions=max_actions,
225
+ )
226
+
227
+ record = {
228
+ "messages": messages,
229
+ "meta": {
230
+ "episode_return": traj.get("episode_return", None),
231
+ "episode_success": ep_success,
232
+ "global_step": global_step,
233
+ },
234
+ }
235
+ fout.write(json.dumps(record, ensure_ascii=False) + "\n")
236
+ written += 1
237
+
238
+ if written == 0:
239
+ with open(out_path, "w", encoding="utf-8") as f:
240
+ pass
241
+ return out_path
242
+
243
+
244
+ def find_latest_step_dir(traj_root: Path) -> Path:
245
+ step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
246
+ if not step_dirs:
247
+ raise FileNotFoundError(f"No step_* directories under {traj_root}")
248
+ step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
249
+ return step_dirs[-1]
250
+
251
+
252
+ def main():
253
+ parser = argparse.ArgumentParser(description="Convert Sokoban RL trajectories to LLM SFT chat JSONL")
254
+ parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)")
255
+ parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)")
256
+ parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
257
+ parser.add_argument("--max_actions", type=int, default=15, help="Max actions cap for filtering and counter display")
258
+ args = parser.parse_args()
259
+
260
+ repo_root = Path(__file__).resolve().parents[1]
261
+ run_dir = Path(args.run_dir)
262
+ traj_root = run_dir / "trajectories"
263
+ if not traj_root.exists():
264
+ raise FileNotFoundError(f"Not found trajectories directory: {traj_root}")
265
+
266
+ step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root)
267
+ output_dir = run_dir / "sft"
268
+ 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)
269
+ print(f"SFT data written to: {out_path}")
270
+
271
+
272
+ if __name__ == "__main__":
273
+ main()
scripts/convert_rl_to_sft_sudoku.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import argparse
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+ from typing import List, Tuple, Set, Dict
7
+
8
+ def infer_grid_size_from_state_len(n: int) -> int:
9
+ """Given flattened one-hot length n = G*G*(G+1), solve for integer G."""
10
+ for G in range(2, 17):
11
+ if G * G * (G + 1) == n:
12
+ return G
13
+ raise ValueError(f"Cannot infer grid size from state length {n}")
14
+
15
+ def state_to_matrix(state_vec: List[float], G: int) -> List[List[int]]:
16
+ """Convert one-hot vector to GxG integer matrix."""
17
+ cell_dim = G + 1
18
+ matrix = []
19
+ for r in range(G):
20
+ row = []
21
+ for c in range(G):
22
+ base = (r * G + c) * cell_dim
23
+ cell_data = state_vec[base : base + cell_dim]
24
+ # argmax to find value
25
+ val = 0
26
+ max_v = -1e9
27
+ for k, v in enumerate(cell_data):
28
+ if v > max_v:
29
+ max_v = v
30
+ val = k
31
+ row.append(val)
32
+ matrix.append(row)
33
+ return matrix
34
+
35
+ def check_conflict(grid: List[List[int]], r: int, c: int, val: int, G: int) -> bool:
36
+ """Check if placing val at (r,c) causes a conflict in current grid."""
37
+ if val == 0:
38
+ return False
39
+
40
+ # Row check
41
+ for j in range(G):
42
+ if j != c and grid[r][j] == val:
43
+ return True
44
+ # Col check
45
+ for i in range(G):
46
+ if i != r and grid[i][c] == val:
47
+ return True
48
+ # Box check
49
+ box_size = int(math.sqrt(G))
50
+ br, bc = (r // box_size) * box_size, (c // box_size) * box_size
51
+ for i in range(br, br + box_size):
52
+ for j in range(bc, bc + box_size):
53
+ if (i, j) != (r, c) and grid[i][j] == val:
54
+ return True
55
+ return False
56
+
57
+ def get_valid_moves(grid: List[List[int]], G: int) -> Dict[Tuple[int, int], List[int]]:
58
+ """Compute valid numbers for all empty cells."""
59
+ valid_moves = {}
60
+ box_size = int(math.sqrt(G))
61
+
62
+ for r in range(G):
63
+ for c in range(G):
64
+ if grid[r][c] == 0:
65
+ possibles = []
66
+ for v in range(1, G + 1):
67
+ is_row_ok = all(grid[r][j] != v for j in range(G))
68
+ is_col_ok = all(grid[i][c] != v for i in range(G))
69
+ br, bc = (r // box_size) * box_size, (c // box_size) * box_size
70
+ is_box_ok = True
71
+ for i in range(br, br + box_size):
72
+ for j in range(bc, bc + box_size):
73
+ if grid[i][j] == v:
74
+ is_box_ok = False
75
+ break
76
+ if is_row_ok and is_col_ok and is_box_ok:
77
+ possibles.append(v)
78
+ if possibles:
79
+ valid_moves[(r + 1, c + 1)] = possibles # 1-indexed keys
80
+ return valid_moves
81
+
82
+ def render_ascii_board(grid: List[List[int]], initial_grid: List[List[int]], G: int) -> str:
83
+ """Render the board in the rich ASCII format seen in logs."""
84
+ box_size = int(math.sqrt(G))
85
+ lines = []
86
+
87
+ header = "=" * 50 + "\nSUDOKU PUZZLE\n" + "=" * 50
88
+ lines.append(header)
89
+
90
+ for r in range(G):
91
+ if r > 0 and r % box_size == 0:
92
+ row_sep = []
93
+ for c in range(G):
94
+ if c > 0 and c % box_size == 0:
95
+ row_sep.append("-")
96
+ row_sep.append("----")
97
+ lines.append("-" * (G * 4 + int(G/box_size)*2))
98
+
99
+ row_str = []
100
+ for c in range(G):
101
+ if c > 0 and c % box_size == 0:
102
+ row_str.append("|")
103
+
104
+ val = grid[r][c]
105
+ is_init = (initial_grid[r][c] != 0)
106
+
107
+ if val == 0:
108
+ cell_str = " . "
109
+ else:
110
+ is_conflict = check_conflict(grid, r, c, val, G)
111
+ if is_conflict and not is_init:
112
+ cell_str = f"*{val}*"
113
+ elif is_init:
114
+ cell_str = f"[{val}]"
115
+ else:
116
+ cell_str = f" {val} " # User placed
117
+
118
+ row_str.append(cell_str)
119
+
120
+ lines.append("".join(row_str))
121
+
122
+ lines.append("\nLegend: [N]=initial cell, N=user-placed, *N*=conflict, .=empty")
123
+ return "\n".join(lines)
124
+
125
+ def decode_action(action_id: int, G: int) -> Tuple[int, int, int]:
126
+ """Map discrete id -> 1-indexed (row, col, num)."""
127
+ row0 = action_id // (G * G)
128
+ rem = action_id % (G * G)
129
+ col0 = rem // G
130
+ num = (rem % G) + 1
131
+ return row0 + 1, col0 + 1, num
132
+
133
+ def build_messages_for_episode(
134
+ states: List[List[float]],
135
+ actions: List[int],
136
+ rewards: List[float],
137
+ max_tokens: int,
138
+ max_actions: int,
139
+ ) -> List[dict]:
140
+
141
+ # Infer G from first state
142
+ G = infer_grid_size_from_state_len(len(states[0]))
143
+ box_size = int(math.sqrt(G))
144
+
145
+ grid_history = [state_to_matrix(s, G) for s in states]
146
+ initial_grid = grid_history[0]
147
+
148
+ sys_msg = "You're a helpful assistant. "
149
+
150
+ intro_prompt = (
151
+ f"You are solving a Sudoku puzzle. Fill in the grid so that every row, column, "
152
+ f"and {box_size}x{box_size} box contains the numbers 1-{G} without repetition.\n"
153
+ "Initial cells are shown in [brackets] and cannot be modified. Empty cells are shown as dots (.).\n"
154
+ "Place numbers one at a time using the format: <answer>place 1 at row 2 col 3</answer> or <answer>1,2,3</answer>\n"
155
+ "The environment will provide feedback on valid/invalid moves and show conflicts if any occur.\n"
156
+ )
157
+
158
+ messages = [
159
+ {"role": "system", "content": sys_msg},
160
+ {"role": "user", "content": intro_prompt},
161
+ ]
162
+
163
+ # Main loop iterates over steps
164
+ for t in range(len(states)):
165
+ # If this state corresponds to a step where no action was taken (end of episode), stop
166
+ if t >= len(actions):
167
+ break
168
+
169
+ current_grid = grid_history[t]
170
+ actions_left = max(0, max_actions - t)
171
+
172
+ # --- 1. Prepare Reward String (Combined into this User turn) ---
173
+ # If t > 0, we have a reward from the previous action (at t-1)
174
+ reward_prefix = ""
175
+ if t > 0:
176
+ prev_reward = rewards[t-1] if (t-1) < len(rewards) else 0.0
177
+ # Double newline to separate from the previous content logically
178
+ reward_prefix = f"Reward:\n{prev_reward}\n\n"
179
+
180
+ # --- 2. Render Board ---
181
+ board_str = render_ascii_board(current_grid, initial_grid, G)
182
+
183
+ # --- 3. Calc Valid Moves ---
184
+ valid_map = get_valid_moves(current_grid, G)
185
+ valid_str_lines = ["\n💡 VALID NUMBERS FOR EMPTY CELLS:"]
186
+ sorted_keys = sorted(valid_map.keys())
187
+ if not sorted_keys:
188
+ valid_str_lines.append(" (None)")
189
+ else:
190
+ count = 0
191
+ for (r, c) in sorted_keys:
192
+ vals = valid_map[(r,c)]
193
+ valid_str_lines.append(f" - ({r},{c}): {vals}")
194
+ count += 1
195
+ if count > 15:
196
+ valid_str_lines.append(" ... (list truncated)")
197
+ break
198
+ # valid_section = "\n".join(valid_str_lines)
199
+ valid_section = ""
200
+
201
+ # --- 4. Stats ---
202
+ total_cells = G * G
203
+ filled_cells = sum(1 for r in range(G) for c in range(G) if current_grid[r][c] != 0)
204
+ init_cells = sum(1 for r in range(G) for c in range(G) if initial_grid[r][c] != 0)
205
+ placed_cells = filled_cells - init_cells
206
+ if placed_cells < 0: placed_cells = 0
207
+
208
+ stats_section = (
209
+ f"\nProgress: {filled_cells}/{total_cells} cells filled ({init_cells} initial, {placed_cells} placed)\n"
210
+ f"Steps: {t}/{max_actions}"
211
+ )
212
+
213
+ # --- 5. Construct User Content ---
214
+ turn_header = f"Turn {t + 1}:\nState:"
215
+
216
+ constraint_prompt = (
217
+ f"You have {actions_left} actions left. Always output: <think> [Your thoughts] </think> "
218
+ f"<answer> [your answer] </answer> with no extra text. Strictly follow this format. "
219
+ f"Max response length: {max_tokens} words (tokens)."
220
+ )
221
+
222
+ # COMBINE: Reward + Header + Board + Valid + Stats + Constraint
223
+ full_user_text = (
224
+ f"{reward_prefix}{turn_header}\n"
225
+ f"{board_str}{valid_section}\n{stats_section}\n{constraint_prompt}"
226
+ )
227
+
228
+ # --- 6. Append to Messages ---
229
+ if t == 0:
230
+ # First turn: Append to the "Intro" user message
231
+ messages[-1]["content"] += ("\n" + full_user_text)
232
+ else:
233
+ # Subsequent turns: New User message containing (Reward + State)
234
+ messages.append({"role": "user", "content": full_user_text})
235
+
236
+ # --- 7. Assistant Response ---
237
+ r_act, c_act, n_act = decode_action(actions[t], G)
238
+ ans_text = f"place {n_act} at row {r_act} col {c_act}"
239
+ assistant_text = f"<think> </think><answer>{ans_text}</answer>"
240
+ messages.append({"role": "assistant", "content": assistant_text})
241
+
242
+ return messages
243
+
244
+ def convert_file(step_dir: Path, output_dir: Path, include_failed: bool = False, max_actions_override: int | None = None) -> Path:
245
+ traj_path = step_dir / "trajectories.jsonl"
246
+ metrics_path = step_dir / "metrics.json"
247
+
248
+ if not traj_path.exists():
249
+ raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
250
+
251
+ max_tokens = 150
252
+
253
+ output_dir.mkdir(parents=True, exist_ok=True)
254
+ out_path = output_dir / f"{step_dir.name}_sft.jsonl"
255
+
256
+ global_step = None
257
+ if metrics_path.exists():
258
+ try:
259
+ with open(metrics_path, "r", encoding="utf-8") as f:
260
+ m = json.load(f)
261
+ global_step = m.get("global_step")
262
+ except Exception:
263
+ pass
264
+
265
+ written = 0
266
+ with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
267
+ for line in fin:
268
+ line = line.strip()
269
+ if not line:
270
+ continue
271
+ traj = json.loads(line)
272
+ ep_success = bool(traj.get("episode_success", False))
273
+ if (not include_failed) and (not ep_success):
274
+ continue
275
+
276
+ states = traj.get("states", [])
277
+ actions = traj.get("actions", [])
278
+ rewards = traj.get("rewards", [])
279
+
280
+ if not states:
281
+ continue
282
+
283
+ G = infer_grid_size_from_state_len(len(states[0]))
284
+ if max_actions_override is not None:
285
+ eff_max = max_actions_override
286
+ else:
287
+ eff_max = 20 if G == 4 else int(G*G * 1.5)
288
+
289
+ messages = build_messages_for_episode(
290
+ states=states,
291
+ actions=actions,
292
+ rewards=rewards,
293
+ max_tokens=max_tokens,
294
+ max_actions=eff_max,
295
+ )
296
+
297
+ record = {
298
+ "messages": messages,
299
+ "meta": {
300
+ "episode_return": traj.get("episode_return", None),
301
+ "episode_success": ep_success,
302
+ "global_step": global_step,
303
+ },
304
+ }
305
+ fout.write(json.dumps(record, ensure_ascii=False) + "\n")
306
+ written += 1
307
+
308
+ return out_path
309
+
310
+ def find_latest_step_dir(traj_root: Path) -> Path:
311
+ step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
312
+ if not step_dirs:
313
+ raise FileNotFoundError(f"No step_* directories under {traj_root}")
314
+ step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
315
+ return step_dirs[-1]
316
+
317
+ def main():
318
+ parser = argparse.ArgumentParser(description="Convert Sudoku RL trajectories to LLM SFT chat JSONL (Rich Format, Merged Reward)")
319
+ parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)")
320
+ parser.add_argument("--step", default=None, help="Specific step directory name")
321
+ parser.add_argument("--include_failed", action="store_true", help="Include failed episodes")
322
+ parser.add_argument("--max_actions", type=int, default=None, help="Max actions cap display")
323
+ args = parser.parse_args()
324
+
325
+ run_dir = Path(args.run_dir)
326
+ traj_root = run_dir / "trajectories"
327
+ if not traj_root.exists():
328
+ raise FileNotFoundError(f"Not found trajectories directory: {traj_root}")
329
+
330
+ step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root)
331
+ output_dir = run_dir / "sft"
332
+
333
+ out_path = convert_file(
334
+ step_dir=step_dir,
335
+ output_dir=output_dir,
336
+ include_failed=args.include_failed,
337
+ max_actions_override=args.max_actions
338
+ )
339
+ print(f"SFT data written to: {out_path}")
340
+
341
+ if __name__ == "__main__":
342
+ main()
scripts/download_data.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import os
4
+ from huggingface_hub import snapshot_download
5
+
6
+ def download_datasets(repo_id="ZihanWang314/ragen-datasets", local_dir="data"):
7
+ """
8
+ Download all datasets from Hugging Face Hub to local directory.
9
+
10
+ Args:
11
+ repo_id (str): Hugging Face repository ID
12
+ local_dir (str): Local directory to save datasets
13
+ """
14
+ print(f"Downloading datasets from {repo_id}...")
15
+
16
+ url = "https://huggingface.co/datasets/Jiayi-Pan/Countdown-Tasks-3to4/resolve/main/data/train-00000-of-00001.parquet"
17
+ os.makedirs("data/countdown", exist_ok=True)
18
+ os.system(f"wget {url} -O data/countdown/train.parquet")
19
+
20
+ # Create the data directory if it doesn't exist
21
+ os.makedirs(local_dir, exist_ok=True)
22
+
23
+ try:
24
+ # Download the entire repository
25
+ snapshot_download(
26
+ repo_id=repo_id,
27
+ repo_type="dataset",
28
+ local_dir=local_dir,
29
+ local_dir_use_symlinks=False
30
+ )
31
+ print(f"\nDatasets successfully downloaded to {local_dir}/")
32
+
33
+ except Exception as e:
34
+ print(f"Error downloading datasets: {e}")
35
+ return False
36
+
37
+ if __name__ == "__main__":
38
+ download_datasets()
scripts/nothink_dataset.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ # with open("/mnt/general/wanghy/RAGEN/runs/Game2048NoisyDQN__noisy_dqn_2048_refined__1__1765041200/sft/step_300000_sft_singleturn_slidewindows5_7000score.json") as f:
4
+ # dataset1 = json.load(f)
5
+
6
+ with open("/mnt/general/wanghy/RAGEN/runs/BanditDQN__dqn_bandit_nochangeenv__1__1764233298/sft/step_50000_sft.json") as f:
7
+ dataset2 = json.load(f)
8
+
9
+ with open("/mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube1_1218/sft/step_999424_sft_singleturn.json") as f:
10
+ dataset3 = json.load(f)
11
+
12
+ with open("/mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube2_1219_turn5/sft/step_999424_sft_singleturn.json") as f:
13
+ dataset4 = json.load(f)
14
+
15
+ with open("/mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube3_1219_turn5_6000/sft/step_999424_sft_singleturn.json") as f:
16
+ dataset5 = json.load(f)
17
+
18
+ with open("/mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__p0.9_slippery/sft/step_1986560_sft_slippery_singleturn.json") as f:
19
+ dataset6 = json.load(f)
20
+
21
+ with open("/mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155447/sft/step_1000000_sft_singleturn.json") as f:
22
+ dataset7 = json.load(f)
23
+
24
+ with open("/mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155464/sft/step_1000000_sft_singleturn.json") as f:
25
+ dataset8 = json.load(f)
26
+
27
+ with open("/mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json") as f:
28
+ dataset9 = json.load(f)
29
+
30
+
31
+ data = dataset2 +dataset3 +dataset4 +dataset5 +dataset6 +dataset7 +dataset8 +dataset9
32
+
33
+ target_user_str = " <think> [Your thoughts] </think>"
34
+ target_assistant_str1 = "<think></think>"
35
+ target_assistant_str2 = "<think> </think>"
36
+
37
+ # 2. 遍历数据并进行替换
38
+ # 假设 data 是一个列表,列表里每个元素都有 "messages" 字段
39
+ if isinstance(data, list):
40
+ for entry in data:
41
+ if "messages" in entry:
42
+ for msg in entry["messages"]:
43
+ role = msg.get("role")
44
+ content = msg.get("content", "")
45
+
46
+ # 处理 User
47
+ if role == "user":
48
+ if target_user_str in content:
49
+ msg["content"] = content.replace(target_user_str, "")
50
+
51
+ # 处理 Assistant
52
+ elif role == "assistant":
53
+ if (target_assistant_str1 in content) or (target_assistant_str2 in content):
54
+ msg["content"] = content.replace(target_assistant_str1, "").replace(target_assistant_str2, "")
55
+ import pdb;pdb.set_trace()
56
+ # 3. 将修改后的数据保存为新文件
57
+ with open("/mnt/general/wanghy/RAGEN/runs/multitask_nothink/sft_no2048.json", 'w', encoding='utf-8') as f:
58
+ json.dump(data, f, ensure_ascii=False, indent=2)
scripts/ppl_2048.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import math
4
+
5
+ # 1. 加载模型和分词器
6
+ # 注意:第一次运行会自动从 Hugging Face 下载模型,约需 3GB 显存或内存
7
+ model_name = "Qwen/Qwen2.5-1.5B-Instruct"
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+
10
+ print(f"Loading {model_name} on {device}...")
11
+ try:
12
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
13
+ model = AutoModelForCausalLM.from_pretrained(model_name, device_map=device, trust_remote_code=True)
14
+ model.eval() # 设置为评估模式
15
+ except Exception as e:
16
+ print(f"Error loading model: {e}")
17
+ exit()
18
+
19
+ def calculate_perplexity(text):
20
+ """
21
+ 计算给定文本字符串的困惑度 (PPL)
22
+ """
23
+ # 对输入文本进行编码
24
+ encodings = tokenizer(text, return_tensors="pt")
25
+ input_ids = encodings.input_ids.to(device)
26
+
27
+ # 计算 Loss (NLL)
28
+ # labels=input_ids 会让模型自动计算 CrossEntropyLoss
29
+ with torch.no_grad():
30
+ outputs = model(input_ids, labels=input_ids)
31
+ loss = outputs.loss
32
+
33
+ # PPL = exp(Loss)
34
+ ppl = torch.exp(loss).item()
35
+ return ppl
36
+
37
+ # ==========================================
38
+ # 场景 1: 2048 游戏
39
+ # ==========================================
40
+ def run_2048_test():
41
+ # 模拟一个 2048 的原始符号状态 (Raw Symbolic State)
42
+ # 论文指出这种原始数字矩阵通常具有较高的 PPL
43
+ state_2048 = (
44
+ "Turn 15:"
45
+ "#2 #4 #8 #2 \n . "
46
+ " #16 #64 #32 #512 \n "
47
+ ". #0 #2 #0 #256. . #0 #128 #0 #4 "
48
+ )
49
+ "\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"
50
+ # 2048 的随机基准:数字种类 (0, 2, 4, 8... 2048) 约为 12 种
51
+ baseline_2048 = 12
52
+
53
+ ppl = calculate_perplexity(state_2048)
54
+
55
+ print("-" * 30)
56
+ print("TASK: 2048 Game")
57
+ print(f"Input State:\n{state_2048}")
58
+ print(f"\nRandom Guess Baseline (#States): ~{baseline_2048}")
59
+ print(f"Model Perplexity (PPL): {ppl:.2f}")
60
+
61
+ if ppl > baseline_2048: # 简单的倍数阈值判断
62
+ print(">> 结论: OOD 环境 (模型看不懂这个数字矩阵)")
63
+ else:
64
+ print(">> 结论: In-Domain 环境 (模型对这种排列很熟悉)")
65
+
66
+ # ==========================================
67
+ # 场景 2: 二阶魔方 (2x2 Rubik's Cube)
68
+ # ==========================================
69
+ def run_cube_test():
70
+ # 模拟一个二阶魔方的展开图状态 (Raw Symbolic State)
71
+ # U=Up, F=Front, R=Right, D=Down, L=Left, B=Back
72
+ # 这里模拟一个打乱后的状态
73
+ state_cube = (
74
+ "Cube State:\n"
75
+ " U R\n"
76
+ " F U\n"
77
+ "L D F R B U\n"
78
+ "L B R D F L\n"
79
+ " D B\n"
80
+ " R B"
81
+ )
82
+
83
+ # 魔方的随机基准:只有 6 种颜色
84
+ baseline_cube = 6
85
+
86
+ ppl = calculate_perplexity(state_cube)
87
+
88
+ print("-" * 30)
89
+ print("TASK: 2x2 Rubik's Cube")
90
+ print(f"Input State:\n{state_cube}")
91
+ print(f"\nRandom Guess Baseline (#States): {baseline_cube}")
92
+ print(f"Model Perplexity (PPL): {ppl:.2f}")
93
+
94
+ if ppl > baseline_cube * 2:
95
+ print(">> 结论: OOD 环境 (模型难以解析空间展开图)")
96
+ else:
97
+ print(">> 结论: In-Domain 环境")
98
+
99
+ # ==========================================
100
+ # 执行测试
101
+ # ==========================================
102
+ if __name__ == "__main__":
103
+ print("Starting PPL Calculation based on paper methodology[cite: 174]...")
104
+ run_2048_test()
105
+ run_cube_test()
scripts/ppy_cube.py ADDED
File without changes
scripts/runs/bandit_jobs.sh ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Experiments: Bandit 3B base PPO/GRPO contrast (normal vs StarPO-S) with entropy and instruct ablations.
3
+ # 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.
4
+
5
+ # set -u -o pipefail
6
+ set +e
7
+
8
+ GPUS=(0 1 2 3 4 5 6 7)
9
+ TOTAL_GPUS=${#GPUS[@]}
10
+ gpu_idx=0
11
+
12
+ maybe_flush() {
13
+ local needed=$1
14
+ if (( gpu_idx + needed > TOTAL_GPUS )); then
15
+ wait
16
+ gpu_idx=0
17
+ sleep 10
18
+ fi
19
+ }
20
+
21
+ init_singleton() {
22
+ local tag=${1:-$(basename "$0")}
23
+ local dir="/blob/v-zihanwang/tmp"
24
+ mkdir -p "$dir"
25
+ export SGL_FILE="${dir}/${tag}.lock"
26
+
27
+ local ts
28
+ ts=$(date +%s)
29
+
30
+ if [[ -f "$SGL_FILE" ]]; then
31
+ local last_modified
32
+ last_modified=$(stat -c %Y "$SGL_FILE")
33
+ if (( ts - last_modified < 60 )); then
34
+ echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting."
35
+ exit 0
36
+ fi
37
+ fi
38
+
39
+ echo "$ts" > "$SGL_FILE"
40
+ touch -d "@$ts" "$SGL_FILE"
41
+
42
+ export SGL_TS="$ts"
43
+
44
+ echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS"
45
+ }
46
+
47
+ check_singleton() {
48
+ if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then
49
+ echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting."
50
+ exit 0
51
+ fi
52
+
53
+ if [[ ! -f "$SGL_FILE" ]]; then
54
+ echo "[singleton] check: lock file missing -> taken over by another script. exiting."
55
+ exit 0
56
+ fi
57
+
58
+ local mtime
59
+ mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0)
60
+
61
+ if [[ "$mtime" != "$SGL_TS" ]]; then
62
+ echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting."
63
+ exit 0
64
+ fi
65
+ }
66
+
67
+ wait_sleep_reset_check() {
68
+ wait
69
+ sleep 15
70
+ gpu_idx=0
71
+ check_singleton
72
+ }
73
+
74
+ launch_bandit() {
75
+ local run_name=$1
76
+ local think=$2
77
+ local algo=$3
78
+ local mode=$4
79
+ local n_gpus=${5:-2}
80
+ local total_training_steps=${6:-200}
81
+ shift 6
82
+ local overrides=("$@")
83
+
84
+ maybe_flush ${n_gpus}
85
+
86
+ local estimator
87
+ if [[ "$algo" == "ppo" ]]; then
88
+ estimator="gae"
89
+ else
90
+ estimator="$algo"
91
+ fi
92
+
93
+ local assigned=(${GPUS[@]:$gpu_idx:$n_gpus})
94
+ local visible=""
95
+ for id in "${assigned[@]}"; do
96
+ if [[ -n "$visible" ]]; then
97
+ visible+=","
98
+ fi
99
+ visible+="$id"
100
+ done
101
+ gpu_idx=$((gpu_idx + n_gpus))
102
+
103
+ local storage_args=(
104
+ "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}"
105
+ "trainer.max_actor_ckpt_to_keep=1"
106
+ "trainer.max_critic_ckpt_to_keep=1"
107
+ )
108
+
109
+ local mode_overrides=()
110
+ case "$mode" in
111
+ normal)
112
+ mode_overrides=(
113
+ "algorithm.kl_ctrl.kl_coef=0.001"
114
+ "actor_rollout_ref.actor.clip_ratio_high=0.20"
115
+ "actor_rollout_ref.rollout.rollout_filter_ratio=1"
116
+ "actor_rollout_ref.actor.use_ref=True"
117
+ )
118
+ ;;
119
+ s)
120
+ mode_overrides=(
121
+ "actor_rollout_ref.actor.use_ref=False"
122
+ "algorithm.kl_ctrl.kl_coef=0.0"
123
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.5"
124
+ )
125
+ ;;
126
+ det)
127
+ mode_overrides=(
128
+ "algorithm.kl_ctrl.kl_coef=0.001"
129
+ "actor_rollout_ref.actor.clip_ratio_high=0.20"
130
+ "actor_rollout_ref.rollout.rollout_filter_ratio=1"
131
+ "actor_rollout_ref.actor.use_ref=True"
132
+ "agent_proxy.max_turn=1"
133
+ "agent_proxy.max_actions_per_turn=1"
134
+ "custom_envs.Bandit.max_actions_per_traj=1"
135
+ "+custom_envs.Bandit.env_config.hi_arm_loscore=0.25"
136
+ "+custom_envs.Bandit.env_config.hi_arm_hiscore=0.25"
137
+ )
138
+ ;;
139
+ *)
140
+ echo "[bandit_jobs] Unknown mode: $mode" >&2
141
+ return 1
142
+ ;;
143
+ esac
144
+
145
+ local base_args=(
146
+ "system.CUDA_VISIBLE_DEVICES=\"${visible}\""
147
+ "trainer.n_gpus_per_node=${n_gpus}"
148
+ "trainer.experiment_name=${run_name}"
149
+ "trainer.total_training_steps=${total_training_steps}"
150
+ "trainer.save_freq=50"
151
+ "model_path=Qwen/Qwen2.5-3B"
152
+ "lora.rank=0"
153
+ "actor_rollout_ref.actor.optim.lr=1e-6"
154
+ "critic.optim.lr=1e-5"
155
+ "micro_batch_size_per_gpu=1"
156
+ "algorithm.adv_estimator=${estimator}"
157
+ "agent_proxy.enable_think=${think}"
158
+ "agent_proxy.max_turn=1"
159
+ "agent_proxy.max_actions_per_turn=1"
160
+ "es_manager.train.env_configs.tags=[Bandit]"
161
+ "es_manager.val.env_configs.tags=[Bandit,BanditTest]"
162
+ "es_manager.val.env_configs.n_groups=[32,32]"
163
+ "es_manager.val.env_groups=64"
164
+ )
165
+
166
+ local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2)
167
+ mkdir -p "$log_dir"
168
+
169
+ echo "=== Running ${run_name} on GPUs ${visible} ==="
170
+ CUDA_VISIBLE_DEVICES="${visible}" \
171
+ WANDB_RUN_ID=${run_name} \
172
+ python train.py \
173
+ "${base_args[@]}" \
174
+ "${mode_overrides[@]}" \
175
+ "${storage_args[@]}" \
176
+ "${overrides[@]}" \
177
+ 2>&1 | tee -a "$log_dir/log.log" &
178
+
179
+ sleep 5
180
+ }
181
+
182
+ kl_coef_overrides=(
183
+ "algorithm.kl_ctrl.kl_coef=0.001"
184
+ "actor_rollout_ref.actor.use_ref=True"
185
+ )
186
+
187
+ entropy_filter_overrides=(
188
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.5"
189
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy"
190
+ )
191
+
192
+ entvar_filter_overrides=(
193
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance"
194
+ )
195
+
196
+ instruct_overrides=("model_path=Qwen/Qwen2.5-3B-Instruct")
197
+
198
+ init_singleton "$(basename "${BASH_SOURCE[0]}")" # create a lock file with the name of the script
199
+
200
+ # launch_bandit "bandit_3b_base_ppo_think_s_entvarfilter" True ppo s 8 400 "${entvar_filter_overrides[@]}"
201
+
202
+ # launch_bandit "bandit_3b_base_grpo_think_normal_1" True grpo normal 8 200
203
+
204
+ launch_bandit "bandit_3b_base_ppo_think_s_2" True ppo s 8 400
205
+
206
+ # launch_bandit "bandit_3b_base_ppo_think_normal_2" True ppo normal 4 200
207
+ # launch_bandit "bandit_3b_base_ppo_nothink_normal_2" False ppo normal 4 200
208
+
209
+ wait_sleep_reset_check
210
+
211
+ # launch_bandit "bandit_3b_base_ppo_think_s" True ppo s 4
212
+ # launch_bandit "bandit_3b_base_ppo_think_det" True ppo det 4
213
+
214
+ # wait_sleep_reset_check
215
+
216
+ # launch_bandit "bandit_3b_base_ppo_think_s_klcoef0.001" True ppo s 4 "${kl_coef_overrides[@]}"
217
+ # launch_bandit "bandit_3b_base_ppo_think_s_entropyfilter" True ppo s 4 "${entropy_filter_overrides[@]}"
218
+
219
+ # wait_sleep_reset_check
220
+
221
+ # launch_bandit "bandit_3b_instruct_ppo_think_s" True ppo s 4 "${instruct_overrides[@]}"
222
+ # launch_bandit "bandit_3b_base_grpo_nothink_normal" False grpo normal 4 200
223
+
224
+ # wait_sleep_reset_check
225
+
226
+ # launch_bandit "bandit_3b_base_grpo_nothink_normal" False grpo normal 4
227
+ # launch_bandit "bandit_3b_base_ppo_think_s" True ppo s 8 400
scripts/runs/frozenlake_jobs.sh ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Experiments: FrozenLake 3B base PPO/GRPO (normal no-think) and StarPO-S variants including deterministic, entropy, and instruct ablations.
3
+ # 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.
4
+
5
+ # set -u -o pipefail
6
+ set +e
7
+
8
+ GPUS=(0 1 2 3 4 5 6 7)
9
+ TOTAL_GPUS=${#GPUS[@]}
10
+ gpu_idx=0
11
+
12
+ maybe_flush() {
13
+ local needed=$1
14
+ if (( gpu_idx + needed > TOTAL_GPUS )); then
15
+ wait
16
+ gpu_idx=0
17
+ sleep 10
18
+ fi
19
+ }
20
+
21
+ init_singleton() {
22
+ local tag=${1:-$(basename "$0")}
23
+ local dir="/blob/v-zihanwang/tmp"
24
+ mkdir -p "$dir"
25
+ export SGL_FILE="${dir}/${tag}.lock"
26
+
27
+ local ts
28
+ ts=$(date +%s)
29
+
30
+ if [[ -f "$SGL_FILE" ]]; then
31
+ local last_modified
32
+ last_modified=$(stat -c %Y "$SGL_FILE")
33
+ if (( ts - last_modified < 60 )); then
34
+ echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting."
35
+ exit 0
36
+ fi
37
+ fi
38
+
39
+ echo "$ts" > "$SGL_FILE"
40
+ touch -d "@$ts" "$SGL_FILE"
41
+
42
+ export SGL_TS="$ts"
43
+
44
+ echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS"
45
+ }
46
+
47
+ check_singleton() {
48
+ if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then
49
+ echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting."
50
+ exit 0
51
+ fi
52
+
53
+ if [[ ! -f "$SGL_FILE" ]]; then
54
+ echo "[singleton] check: lock file missing -> taken over by another script. exiting."
55
+ exit 0
56
+ fi
57
+
58
+ local mtime
59
+ mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0)
60
+
61
+ if [[ "$mtime" != "$SGL_TS" ]]; then
62
+ echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting."
63
+ exit 0
64
+ fi
65
+ }
66
+
67
+ wait_sleep_reset_check() {
68
+ wait
69
+ sleep 15
70
+ gpu_idx=0
71
+ check_singleton
72
+ }
73
+
74
+ launch_frozenlake() {
75
+ local run_name=$1
76
+ local think=$2
77
+ local algo=$3
78
+ local mode=$4
79
+ local n_gpus=${5:-2}
80
+ local total_training_steps=${6:-200}
81
+ shift 6
82
+ local overrides=("$@")
83
+
84
+ maybe_flush ${n_gpus}
85
+
86
+ local estimator
87
+ if [[ "$algo" == "ppo" ]]; then
88
+ estimator="gae"
89
+ else
90
+ estimator="$algo"
91
+ fi
92
+
93
+ local assigned=(${GPUS[@]:$gpu_idx:$n_gpus})
94
+ local visible=""
95
+ for id in "${assigned[@]}"; do
96
+ if [[ -n "$visible" ]]; then
97
+ visible+=","
98
+ fi
99
+ visible+="$id"
100
+ done
101
+ gpu_idx=$((gpu_idx + n_gpus))
102
+
103
+ local storage_args=(
104
+ "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}"
105
+ "trainer.max_actor_ckpt_to_keep=1"
106
+ "trainer.max_critic_ckpt_to_keep=1"
107
+ )
108
+
109
+ local mode_overrides=()
110
+ case "$mode" in
111
+ normal)
112
+ mode_overrides=(
113
+ "algorithm.kl_ctrl.kl_coef=0.001"
114
+ "actor_rollout_ref.actor.clip_ratio_high=0.20"
115
+ "actor_rollout_ref.rollout.rollout_filter_ratio=1"
116
+ "actor_rollout_ref.actor.use_ref=True"
117
+ )
118
+ ;;
119
+ s)
120
+ mode_overrides=(
121
+ "actor_rollout_ref.actor.use_ref=False"
122
+ "algorithm.kl_ctrl.kl_coef=0.0"
123
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.5"
124
+ )
125
+ ;;
126
+ det)
127
+ mode_overrides=(
128
+ "algorithm.kl_ctrl.kl_coef=0.001"
129
+ "actor_rollout_ref.actor.clip_ratio_high=0.20"
130
+ "actor_rollout_ref.rollout.rollout_filter_ratio=1"
131
+ "actor_rollout_ref.actor.use_ref=True"
132
+ "agent_proxy.max_turn=1"
133
+ "agent_proxy.max_actions_per_turn=10"
134
+ "+custom_envs.CoordFrozenLake.max_actions_per_traj=10"
135
+ "+custom_envs.CoordFrozenLake.env_config.is_slippery=False"
136
+ )
137
+ ;;
138
+ void)
139
+ mode_overrides=(
140
+ "actor_rollout_ref.actor.use_ref=False"
141
+ "algorithm.kl_ctrl.kl_coef=0.0"
142
+ )
143
+ ;;
144
+ *)
145
+ echo "[frozenlake_jobs] Unknown mode: $mode" >&2
146
+ return 1
147
+ ;;
148
+ esac
149
+
150
+ local base_args=(
151
+ "system.CUDA_VISIBLE_DEVICES=\"${visible}\""
152
+ "trainer.n_gpus_per_node=${n_gpus}"
153
+ "trainer.experiment_name=${run_name}"
154
+ "trainer.total_training_steps=${total_training_steps}"
155
+ "trainer.save_freq=50"
156
+ "model_path=Qwen/Qwen2.5-3B"
157
+ "lora.rank=0"
158
+ "actor_rollout_ref.actor.optim.lr=1e-6"
159
+ "critic.optim.lr=1e-5"
160
+ "micro_batch_size_per_gpu=1"
161
+ "algorithm.adv_estimator=${estimator}"
162
+ "agent_proxy.enable_think=${think}"
163
+ "es_manager.train.env_configs.tags=[CoordFrozenLake]"
164
+ "es_manager.val.env_configs.tags=[CoordFrozenLake]"
165
+ )
166
+
167
+ local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2)
168
+ mkdir -p "$log_dir"
169
+
170
+ echo "=== Running ${run_name} on GPUs ${visible} ==="
171
+ CUDA_VISIBLE_DEVICES="${visible}" \
172
+ WANDB_RUN_ID=${run_name} \
173
+ python train.py \
174
+ "${base_args[@]}" \
175
+ "${mode_overrides[@]}" \
176
+ "${storage_args[@]}" \
177
+ "${overrides[@]}" \
178
+ 2>&1 | tee -a "$log_dir/log.log" &
179
+
180
+ sleep 5
181
+ }
182
+
183
+ wait_and_sleep() {
184
+ wait
185
+ sleep 15
186
+ gpu_idx=0
187
+ }
188
+
189
+ kl_coef_overrides=(
190
+ "algorithm.kl_ctrl.kl_coef=0.001"
191
+ "actor_rollout_ref.actor.use_ref=True"
192
+ )
193
+
194
+ entropy_filter_overrides=(
195
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.5"
196
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy"
197
+ )
198
+
199
+ entvar_filter_overrides=(
200
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance"
201
+ )
202
+
203
+ filter_ratio_0_25_overrides=(
204
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.25"
205
+ )
206
+
207
+ filter_ratio_0_75_overrides=(
208
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.75"
209
+ )
210
+
211
+ instruct_overrides=("model_path=Qwen/Qwen2.5-3B-Instruct")
212
+
213
+ init_singleton "$(basename "${BASH_SOURCE[0]}")"
214
+
215
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_rolloutfilterratio0.25" True ppo void 8 1600 "${filter_ratio_0_25_overrides[@]}"
216
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_rolloutfilterratio0.75" True ppo void 8 800 "${filter_ratio_0_75_overrides[@]}"
217
+ launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_5" True ppo s 8 800
218
+ wait_sleep_reset_check
219
+
220
+ # Submitted experiments:
221
+
222
+
223
+
224
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_entvarfilter" True ppo s 8 800 "${entvar_filter_overrides[@]}"
225
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_det" True ppo det 4
226
+
227
+
228
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_nothink_normal" False ppo normal 4
229
+ # launch_frozenlake "frozenlake_coord_3b_base_grpo_nothink_normal" False grpo normal 4
230
+ # wait_sleep_reset_check
231
+
232
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_normal" True ppo normal 4
233
+ # launch_frozenlake "frozenlake_coord_3b_base_grpo_think_normal" True grpo normal 4
234
+ # wait_sleep_reset_check
235
+
236
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_klcoef0.001" True ppo s 4 400 "${kl_coef_overrides[@]}"
237
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_entropyfilter" True ppo s 4 400 "${entropy_filter_overrides[@]}"
238
+ # wait_sleep_reset_check
239
+
240
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_normal_2" True ppo normal 4 400
241
+ # launch_frozenlake "frozenlake_coord_3b_base_grpo_think_normal_2" True grpo normal 4 400
242
+ # wait_sleep_reset_check
243
+
244
+
245
+ # launch_frozenlake "frozenlake_coord_3b_base_ppo_think_s_2" True ppo s 4 800
246
+ # launch_frozenlake "frozenlake_coord_3b_base_grpo_nothink_normal_2" False grpo normal 4 400
247
+ # wait_sleep_reset_check
scripts/runs/sokoban_jobs.sh ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Experiments: Sokoban 3B base PPO normal vs StarPO-S variants (think/no-think, deterministic, entropy ablations).
3
+ # 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.
4
+
5
+ # set -u -o pipefail
6
+ set +e
7
+
8
+
9
+ GPUS=(0 1 2 3 4 5 6 7)
10
+ TOTAL_GPUS=${#GPUS[@]}
11
+ gpu_idx=0
12
+
13
+ maybe_flush() {
14
+ local needed=$1
15
+ if (( gpu_idx + needed > TOTAL_GPUS )); then
16
+ wait
17
+ gpu_idx=0
18
+ sleep 10
19
+ fi
20
+ }
21
+
22
+ init_singleton() {
23
+ local tag=${1:-$(basename "$0")}
24
+ local dir="/blob/v-zihanwang/tmp"
25
+ mkdir -p "$dir"
26
+ export SGL_FILE="${dir}/${tag}.lock"
27
+
28
+ local ts
29
+ ts=$(date +%s)
30
+
31
+ if [[ -f "$SGL_FILE" ]]; then
32
+ local last_modified
33
+ last_modified=$(stat -c %Y "$SGL_FILE")
34
+ if (( ts - last_modified < 60 )); then
35
+ echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting."
36
+ exit 0
37
+ fi
38
+ fi
39
+
40
+ echo "$ts" > "$SGL_FILE"
41
+ touch -d "@$ts" "$SGL_FILE"
42
+
43
+ export SGL_TS="$ts"
44
+
45
+ echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS"
46
+ }
47
+
48
+ check_singleton() {
49
+ if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then
50
+ echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting."
51
+ exit 0
52
+ fi
53
+
54
+ if [[ ! -f "$SGL_FILE" ]]; then
55
+ echo "[singleton] check: lock file missing -> taken over by another script. exiting."
56
+ exit 0
57
+ fi
58
+
59
+ local mtime
60
+ mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0)
61
+
62
+ if [[ "$mtime" != "$SGL_TS" ]]; then
63
+ echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting."
64
+ exit 0
65
+ fi
66
+ }
67
+
68
+ wait_sleep_reset_check() {
69
+ wait
70
+ sleep 15
71
+ gpu_idx=0
72
+ check_singleton
73
+ }
74
+
75
+ launch_sokoban() {
76
+ local run_name=$1
77
+ local think=$2
78
+ local algo=$3
79
+ local mode=$4
80
+ local n_gpus=${5:-2}
81
+ local total_training_steps=${6:-200}
82
+ shift 6
83
+ local overrides=("$@")
84
+
85
+ maybe_flush ${n_gpus}
86
+
87
+ local estimator
88
+ if [[ "$algo" == "ppo" ]]; then
89
+ estimator="gae"
90
+ else
91
+ estimator="$algo"
92
+ fi
93
+
94
+ local assigned=(${GPUS[@]:$gpu_idx:$n_gpus})
95
+ local visible=""
96
+ for id in "${assigned[@]}"; do
97
+ if [[ -n "$visible" ]]; then
98
+ visible+=","
99
+ fi
100
+ visible+="$id"
101
+ done
102
+ gpu_idx=$((gpu_idx + n_gpus))
103
+
104
+ local storage_args=(
105
+ "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}"
106
+ "trainer.max_actor_ckpt_to_keep=1"
107
+ "trainer.max_critic_ckpt_to_keep=1"
108
+ )
109
+
110
+ local mode_overrides=()
111
+ case "$mode" in
112
+ normal)
113
+ mode_overrides=(
114
+ "algorithm.kl_ctrl.kl_coef=0.001"
115
+ "actor_rollout_ref.actor.clip_ratio_high=0.20"
116
+ "actor_rollout_ref.rollout.rollout_filter_ratio=1"
117
+ "actor_rollout_ref.actor.use_ref=True"
118
+ )
119
+ ;;
120
+ s)
121
+ mode_overrides=(
122
+ "actor_rollout_ref.actor.use_ref=False"
123
+ "algorithm.kl_ctrl.kl_coef=0.0"
124
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.5"
125
+ )
126
+ ;;
127
+ det)
128
+ mode_overrides=(
129
+ "algorithm.kl_ctrl.kl_coef=0.001"
130
+ "actor_rollout_ref.actor.clip_ratio_high=0.20"
131
+ "actor_rollout_ref.rollout.rollout_filter_ratio=1"
132
+ "actor_rollout_ref.actor.use_ref=True"
133
+ "agent_proxy.max_turn=1"
134
+ "agent_proxy.max_actions_per_turn=10"
135
+ "custom_envs.CoordSokoban.max_actions_per_traj=10"
136
+ )
137
+ ;;
138
+ *)
139
+ echo "[sokoban_jobs] Unknown mode: $mode" >&2
140
+ return 1
141
+ ;;
142
+ esac
143
+
144
+ local base_args=(
145
+ "system.CUDA_VISIBLE_DEVICES=\"${visible}\""
146
+ "trainer.n_gpus_per_node=${n_gpus}"
147
+ "trainer.experiment_name=${run_name}"
148
+ "trainer.total_training_steps=${total_training_steps}"
149
+ "trainer.save_freq=50"
150
+ "model_path=Qwen/Qwen2.5-3B"
151
+ "lora.rank=0"
152
+ "actor_rollout_ref.actor.optim.lr=1e-6"
153
+ "critic.optim.lr=1e-5"
154
+ "micro_batch_size_per_gpu=1"
155
+ "algorithm.adv_estimator=${estimator}"
156
+ "agent_proxy.enable_think=${think}"
157
+ "es_manager.train.env_configs.tags=[CoordSokoban]"
158
+ "es_manager.val.env_configs.tags=[CoordSokoban]"
159
+ )
160
+
161
+ local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2)
162
+ mkdir -p "$log_dir"
163
+
164
+ echo "=== Running ${run_name} on GPUs ${visible} ==="
165
+ CUDA_VISIBLE_DEVICES="${visible}" \
166
+ WANDB_RUN_ID=${run_name} \
167
+ python train.py \
168
+ "${base_args[@]}" \
169
+ "${mode_overrides[@]}" \
170
+ "${storage_args[@]}" \
171
+ "${overrides[@]}" \
172
+ 2>&1 | tee -a "$log_dir/log.log" &
173
+
174
+ sleep 5
175
+ }
176
+
177
+ # gpu_idx=0
178
+ # # Wave 2: entropy ablations and instruct comparison
179
+ kl_coef_overrides=(
180
+ "algorithm.kl_ctrl.kl_coef=0.001"
181
+ "actor_rollout_ref.actor.use_ref=True"
182
+ )
183
+
184
+ entropy_filter_overrides=(
185
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.5"
186
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy"
187
+ )
188
+
189
+ entvar_filter_overrides=(
190
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance"
191
+ )
192
+
193
+ instruct_overrides=("model_path=Qwen/Qwen2.5-3B-Instruct")
194
+
195
+
196
+ lora_overrides=(
197
+ "lora.rank=64"
198
+ "lora.alpha=64"
199
+ "actor_rollout_ref.actor.optim.lr=1e-5"
200
+ "critic.optim.lr=1e-4"
201
+ "micro_batch_size_per_gpu=8"
202
+ )
203
+
204
+ init_singleton "$(basename "${BASH_SOURCE[0]}")"
205
+
206
+ launch_sokoban "sokoban_coord_3b_base_ppo_think_s_entvarfilter" True ppo s 8 800 "${entvar_filter_overrides[@]}"
207
+
208
+ # launch_sokoban "sokoban_coord_3b_base_ppo_think_normal" True ppo normal 4
209
+ # launch_sokoban "sokoban_coord_3b_base_ppo_nothink_normal" False ppo normal 4
210
+ # wait_sleep_reset_check
211
+
212
+ # launch_sokoban "sokoban_coord_3b_base_ppo_think_det" True ppo det 4
213
+ # launch_sokoban "sokoban_coord_3b_base_ppo_think_normal_lora" True ppo normal 4 "${lora_overrides[@]}"
214
+ # wait_sleep_reset_check
215
+
216
+
217
+ # launch_sokoban "sokoban_coord_3b_instruct_ppo_think_s" True ppo s 4 400 "${instruct_overrides[@]}"
218
+ # launch_sokoban "sokoban_coord_3b_base_ppo_think_s_2" True ppo s 8 800
219
+ # wait_sleep_reset_check
220
+
221
+
222
+ # launch_sokoban "sokoban_coord_3b_base_ppo_think_s_klcoef0.001" True ppo s 4 400 "${kl_coef_overrides[@]}"
223
+ # launch_sokoban "sokoban_coord_3b_base_ppo_think_s_entropyfilter" True ppo s 4 400 "${entropy_filter_overrides[@]}"
224
+ # wait_sleep_reset_check
225
+
226
+
scripts/runs/webshop_budget_jobs.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ MODEL="Qwen/Qwen2.5-3B-Instruct"
5
+ PROJ="budget_main"
6
+ BASE_DIR="/blob/v-zihanwang/budget_checkpoints"
7
+ DEVICES=\"0,1,2,3,4,5,6,7\"
8
+
9
+ run_experiment() {
10
+ local turns=$1
11
+ local exp_name=$2
12
+ local out_dir="${BASE_DIR}/${exp_name}"
13
+
14
+ if [[ "$turns" -ge 7 ]]; then
15
+ local max_len=15000
16
+ local max_tok=15000
17
+ else
18
+ local max_len=10000
19
+ local max_tok=10000
20
+ fi
21
+
22
+ echo "=== Running ${exp_name} ==="
23
+ mkdir -p "${BASE_DIR}/${exp_name}"
24
+
25
+ CUDA_VISIBLE_DEVICES="${DEVICES}" \
26
+ WANDB_RUN_ID=${exp_name} \
27
+ python train.py --config-name _6_webshop ${USE_PPO:-} \
28
+ model_path="${MODEL}" \
29
+ actor_rollout_ref.rollout.rollout_filter_ratio=1 \
30
+ trainer.project_name="${PROJ}" \
31
+ micro_batch_size_per_gpu=1 \
32
+ trainer.experiment_name="${exp_name}" \
33
+ es_manager.train.env_groups=8 es_manager.train.group_size=16 es_manager.train.env_configs.n_groups='[8]' \
34
+ es_manager.val.env_groups=64 es_manager.val.group_size=8 es_manager.val.env_configs.n_groups='[64]' \
35
+ system.CUDA_VISIBLE_DEVICES="${DEVICES}" trainer.n_gpus_per_node=8 actor_rollout_ref.rollout.tensor_model_parallel_size=8 \
36
+ trainer.resume_mode=disable \
37
+ trainer.total_training_steps=200 \
38
+ trainer.save_freq=50 \
39
+ agent_proxy.max_turn="${turns}" \
40
+ actor_rollout_ref.rollout.max_model_len="${max_len}" actor_rollout_ref.rollout.max_num_batched_tokens="${max_tok}" \
41
+ trainer.default_local_dir="${out_dir}" \
42
+ trainer.max_actor_ckpt_to_keep=4 \
43
+ trainer.max_critic_ckpt_to_keep=4 \
44
+ custom_envs.WebShop.max_actions_per_traj="${turns}" \
45
+ actor_rollout_ref.actor.use_ref=False \
46
+ trainer.nnodes=1
47
+ }
48
+
49
+ main() {
50
+ # run_experiment 3 "webshop_starpos_grpo_3b_small_max_3turns"
51
+ # run_experiment 4 "webshop_starpos_grpo_3b_small_max_4turns"
52
+ # run_experiment 5 "webshop_starpos_grpo_3b_small_max_5turns"
53
+ # run_experiment 6 "webshop_starpos_grpo_3b_small_max_6turns"
54
+ # run_experiment 7 "webshop_starpos_grpo_3b_small_max_7turns"
55
+ }
56
+
57
+ main "$@"
scripts/runs/webshop_jobs.sh ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Experiments: WebShop 3B StarPO-S sweeps (base vs instruct, entropy/n-gram filtering, entropy ablation).
3
+ # 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.
4
+
5
+ # set -u -o pipefail
6
+ set +e
7
+
8
+
9
+ GPUS=(0 1 2 3 4 5 6 7)
10
+ TOTAL_GPUS=${#GPUS[@]}
11
+ gpu_idx=0
12
+
13
+ maybe_flush() {
14
+ local needed=$1
15
+ if (( gpu_idx + needed > TOTAL_GPUS )); then
16
+ wait
17
+ gpu_idx=0
18
+ sleep 10
19
+ fi
20
+ }
21
+
22
+ init_singleton() {
23
+ local tag=${1:-$(basename "$0")}
24
+ local dir="/blob/v-zihanwang/tmp"
25
+ mkdir -p "$dir"
26
+ export SGL_FILE="${dir}/${tag}.lock"
27
+
28
+ local ts
29
+ ts=$(date +%s)
30
+
31
+ if [[ -f "$SGL_FILE" ]]; then
32
+ local last_modified
33
+ last_modified=$(stat -c %Y "$SGL_FILE")
34
+ if (( ts - last_modified < 60 )); then
35
+ echo "[singleton] newer process already active (lock updated $(date -d @$last_modified)). exiting."
36
+ exit 0
37
+ fi
38
+ fi
39
+
40
+ echo "$ts" > "$SGL_FILE"
41
+ touch -d "@$ts" "$SGL_FILE"
42
+
43
+ export SGL_TS="$ts"
44
+
45
+ echo "[singleton] init: file=$SGL_FILE ts=$SGL_TS"
46
+ }
47
+
48
+ check_singleton() {
49
+ if [[ -z "${SGL_FILE:-}" || -z "${SGL_TS:-}" ]]; then
50
+ echo "[singleton] check: env not initialized (SGL_FILE/SGL_TS empty) -> exiting."
51
+ exit 0
52
+ fi
53
+
54
+ if [[ ! -f "$SGL_FILE" ]]; then
55
+ echo "[singleton] check: lock file missing -> taken over by another script. exiting."
56
+ exit 0
57
+ fi
58
+
59
+ local mtime
60
+ mtime=$(stat -c %Y "$SGL_FILE" 2>/dev/null || echo 0)
61
+
62
+ if [[ "$mtime" != "$SGL_TS" ]]; then
63
+ echo "[singleton] check: lock updated (was $SGL_TS, now $mtime). exiting."
64
+ exit 0
65
+ fi
66
+ }
67
+
68
+ wait_sleep_reset_check() {
69
+ wait
70
+ sleep 15
71
+ gpu_idx=0
72
+ check_singleton
73
+ }
74
+
75
+ launch_webshop_s() {
76
+ local run_name=$1
77
+ local n_gpus=${2:-4}
78
+ local total_training_steps=${3:-200}
79
+ shift 3
80
+ local overrides=("$@")
81
+
82
+ maybe_flush ${n_gpus}
83
+
84
+ local assigned=(${GPUS[@]:$gpu_idx:$n_gpus})
85
+ local visible=""
86
+ for id in "${assigned[@]}"; do
87
+ if [[ -n "$visible" ]]; then
88
+ visible+=","
89
+ fi
90
+ visible+="$id"
91
+ done
92
+ gpu_idx=$((gpu_idx + n_gpus))
93
+
94
+ local storage_args=(
95
+ "trainer.default_local_dir=/blob/v-zihanwang/ragen_checkpoints/${run_name}"
96
+ "trainer.max_actor_ckpt_to_keep=1"
97
+ "trainer.max_critic_ckpt_to_keep=1"
98
+ )
99
+
100
+ local base_args=(
101
+ "system.CUDA_VISIBLE_DEVICES=\"${visible}\""
102
+ "trainer.n_gpus_per_node=${n_gpus}"
103
+ "trainer.experiment_name=${run_name}"
104
+ "trainer.total_training_steps=${total_training_steps}"
105
+ "trainer.save_freq=25"
106
+ "model_path=Qwen/Qwen2.5-3B"
107
+ "lora.rank=0"
108
+ "actor_rollout_ref.actor.optim.lr=1e-6"
109
+ "critic.optim.lr=1e-5"
110
+ "micro_batch_size_per_gpu=1"
111
+ "algorithm.adv_estimator=gae"
112
+ "agent_proxy.enable_think=True"
113
+ "agent_proxy.max_turn=8"
114
+ "agent_proxy.max_actions_per_turn=1"
115
+ "actor_rollout_ref.actor.use_ref=False"
116
+ "algorithm.kl_ctrl.kl_coef=0.0"
117
+ "actor_rollout_ref.rollout.rollout_filter_ratio=0.5"
118
+ "actor_rollout_ref.rollout.max_model_len=15000"
119
+ "actor_rollout_ref.rollout.max_num_batched_tokens=15000"
120
+ "es_manager.train.env_configs.tags=[WebShop]"
121
+ "es_manager.val.env_configs.tags=[WebShop]"
122
+ )
123
+
124
+ local log_dir=$(echo "${storage_args[0]}" | cut -d'=' -f2)
125
+ mkdir -p "$log_dir"
126
+
127
+ echo "=== Running ${run_name} on GPUs ${visible} ==="
128
+ CUDA_VISIBLE_DEVICES="${visible}" \
129
+ WANDB_RUN_ID=${run_name} \
130
+ python train.py \
131
+ "${base_args[@]}" \
132
+ "${mode_overrides[@]}" \
133
+ "${storage_args[@]}" \
134
+ "${overrides[@]}" \
135
+ 2>&1 | tee -a "$log_dir/log.log" &
136
+
137
+ sleep 5
138
+ }
139
+
140
+ kl_coef_overrides=(
141
+ "algorithm.kl_ctrl.kl_coef=0.001"
142
+ "actor_rollout_ref.actor.use_ref=True"
143
+ )
144
+
145
+ entropy_filter_overrides=(
146
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy"
147
+ )
148
+
149
+ entvar_filter_overrides=(
150
+ "actor_rollout_ref.rollout.rollout_filter_metric=entropy_variance"
151
+ )
152
+
153
+ init_singleton "$(basename "${BASH_SOURCE[0]}")"
154
+ launch_webshop_s "webshop_3b_base_ppo_think_s_entvarfilter" 8 400 "${entvar_filter_overrides[@]}"
155
+ wait_sleep_reset_check
156
+
157
+ # launch_webshop_s "webshop_3b_base_ppo_think_s" 8 400
158
+ # wait_sleep_reset_check
159
+
160
+ # launch_webshop_s "webshop_3b_base_ppo_think_s_entropyfilter" 8 400 "${entropy_filter_overrides[@]}"
161
+ # wait_sleep_reset_check
162
+
163
+ # launch_webshop_s "webshop_3b_base_ppo_think_s_klcoef0.001" 8 400 "${kl_coef_overrides[@]}"
164
+ # wait_sleep_reset_check
165
+
scripts/setup_ragen.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Manual Scripts to Setup Environment
2
+ ```bash
3
+ conda create -n ragen python=3.9 -y
4
+ conda activate ragen
5
+
6
+
7
+ git clone git@github.com:ZihanWang314/ragen.git
8
+ cd ragen
9
+
10
+ pip install -e .
11
+ pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124
12
+
13
+ # Optional: to install flash-attn, you may need to install cuda-toolkit first if you don't have
14
+ conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y
15
+ export CUDA_HOME=$CONDA_PREFIX # /opt/conda/envs/zero
16
+ pip3 install flash-attn --no-build-isolation
17
+
18
+ pip install -r requirements.txt
19
+
20
+ git submodule init
21
+ git submodule update
22
+ cd verl
23
+ pip install -e .
24
+ cd ..
25
+
26
+ ```
scripts/setup_ragen.sh ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Exit on error
4
+ set -e
5
+
6
+ # Function to check if CUDA is available
7
+ check_cuda() {
8
+ if command -v nvidia-smi &> /dev/null; then
9
+ echo "CUDA GPU detected"
10
+ return 0
11
+ else
12
+ echo "No CUDA GPU detected"
13
+ return 1
14
+ fi
15
+ }
16
+
17
+ # Function to check if conda is available
18
+ check_conda() {
19
+ if command -v conda &> /dev/null; then
20
+ echo "Conda is available"
21
+ return 0
22
+ else
23
+ echo "Conda is not installed. Please install Conda first."
24
+ return 1
25
+ fi
26
+ }
27
+
28
+ # Colors for output
29
+ GREEN='\033[0;32m'
30
+ BLUE='\033[0;34m'
31
+ NC='\033[0m' # No Color
32
+
33
+ # Print step with color
34
+ print_step() {
35
+ echo -e "${BLUE}[Step] ${1}${NC}"
36
+ }
37
+
38
+ # Main installation process
39
+ main() {
40
+ # Check prerequisites
41
+ check_conda || exit 1
42
+
43
+ # Create and activate conda environment
44
+ # if not exists, create it
45
+ if ! conda env list | grep -q "ragen"; then
46
+ print_step "Creating conda environment 'ragen' with Python 3.12..."
47
+ conda create -n ragen python=3.12 -y
48
+ else
49
+ print_step "Conda environment 'ragen' already exists"
50
+ fi
51
+
52
+ # Need to source conda for script environment
53
+ eval "$(conda shell.bash hook)"
54
+ conda activate ragen
55
+
56
+ # Install package in editable mode
57
+ print_step "setting up verl..."
58
+ git submodule init
59
+ git submodule update
60
+ cd verl
61
+ pip install -e . --no-dependencies # we put dependencies in requirements.txt
62
+ cd ..
63
+
64
+ # Install package in editable mode
65
+ print_step "Installing ragen package..."
66
+ pip install -e .
67
+
68
+ # Install PyTorch with CUDA if available
69
+ if check_cuda; then
70
+ print_step "CUDA detected, checking CUDA version..."
71
+
72
+ if command -v nvcc &> /dev/null; then
73
+ nvcc_version=$(nvcc --version | grep "release" | awk '{print $6}' | cut -c2-)
74
+ nvcc_major=$(echo $nvcc_version | cut -d. -f1)
75
+ nvcc_minor=$(echo $nvcc_version | cut -d. -f2)
76
+
77
+ print_step "Found NVCC version: $nvcc_version"
78
+
79
+ if [[ "$nvcc_major" -gt 12 || ("$nvcc_major" -eq 12 && "$nvcc_minor" -ge 1) ]]; then
80
+ print_step "CUDA $nvcc_version is already installed and meets requirements (>=12.4)"
81
+ export CUDA_HOME=${CUDA_HOME:-$(dirname $(dirname $(which nvcc)))}
82
+ else
83
+ print_step "CUDA version < 12.4, installing CUDA toolkit 12.4..."
84
+ conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y
85
+ export CUDA_HOME=$CONDA_PREFIX
86
+ fi
87
+ else
88
+ print_step "NVCC not found, installing CUDA toolkit 12.4..."
89
+ conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y
90
+ export CUDA_HOME=$CONDA_PREFIX
91
+ fi
92
+
93
+ print_step "Installing PyTorch with CUDA support..."
94
+ pip install torch==2.5.0 --index-url https://download.pytorch.org/whl/cu124
95
+
96
+ print_step "Installing flash-attention..."
97
+ # pip3 install flash-attn==2.7.4.post1 --no-build-isolation
98
+ else
99
+ print_step "Installing PyTorch without CUDA support..."
100
+ pip install torch==2.4.0
101
+ fi
102
+
103
+ # Install remaining requirements
104
+ print_step "Installing additional requirements..."
105
+ pip install -r requirements.txt
106
+
107
+ print_step "Downloading data..."
108
+ python scripts/download_data.py
109
+
110
+ echo -e "${GREEN}Installation completed successfully!${NC}"
111
+ echo "To activate the environment, run: conda activate ragen"
112
+
113
+ # export CMAKE_POLICY_VERSION_MINIMUM=3.5 && pip install alfworld[full]
114
+ # alfworld-download
115
+
116
+ # installing webshop
117
+ print_step "Installing webshop dependencies..."
118
+ conda install -c pytorch faiss-cpu -y
119
+ sudo apt update
120
+ sudo apt install default-jdk -y
121
+ conda install -c conda-forge openjdk=21 maven -y
122
+
123
+ # Install remaining requirements
124
+ print_step "Installing additional requirements..."
125
+ pip install -r requirements.txt
126
+
127
+ # webshop installation, model loading
128
+ pip install -e external/webshop-minimal/ --no-dependencies
129
+ python -m spacy download en_core_web_sm
130
+ python -m spacy download en_core_web_lg
131
+
132
+ print_step "Downloading data..."
133
+ python scripts/download_data.py
134
+
135
+ # Optional: download full data set
136
+ print_step "Downloading full data set..."
137
+ conda install conda-forge::gdown
138
+ mkdir -p external/webshop-minimal/webshop_minimal/data/full
139
+ cd external/webshop-minimal/webshop_minimal/data/full
140
+ # gdown https://drive.google.com/uc?id=1A2whVgOO0euk5O13n2iYDM0bQRkkRduB # items_shuffle
141
+ # gdown https://drive.google.com/uc?id=1s2j6NgHljiZzQNL3veZaAiyW_qDEgBNi # items_ins_v2
142
+ cd ../../../../..
143
+
144
+ echo -e "${GREEN}Installation completed successfully!${NC}"
145
+ echo "To activate the environment, run: conda activate ragen"
146
+
147
+
148
+ }
149
+
150
+ # Run main installation
151
+ main
scripts/setup_ragen_webshop.sh.old ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Exit on error
4
+ set -e
5
+
6
+ # Function to check if CUDA is available
7
+ check_cuda() {
8
+ if command -v nvidia-smi &> /dev/null; then
9
+ echo "CUDA GPU detected"
10
+ return 0
11
+ else
12
+ echo "No CUDA GPU detected"
13
+ return 1
14
+ fi
15
+ }
16
+
17
+ # Function to check if conda is available
18
+ check_conda() {
19
+ if command -v conda &> /dev/null; then
20
+ echo "Conda is available"
21
+ return 0
22
+ else
23
+ echo "Conda is not installed. Please install Conda first."
24
+ return 1
25
+ fi
26
+ }
27
+
28
+ # Colors for output
29
+ GREEN='\033[0;32m'
30
+ BLUE='\033[0;34m'
31
+ NC='\033[0m' # No Color
32
+
33
+ # Print step with color
34
+ print_step() {
35
+ echo -e "${BLUE}[Step] ${1}${NC}"
36
+ }
37
+
38
+ # Main installation process
39
+ main() {
40
+ # Check prerequisites
41
+ check_conda || exit 1
42
+
43
+ # Create and activate conda environment
44
+ # if not exists, create it
45
+ if ! conda env list | grep -q "ragen"; then
46
+ print_step "Creating conda environment 'ragen' with Python 3.12..."
47
+ conda create -n ragen python=3.12 -y
48
+ else
49
+ print_step "Conda environment 'ragen' already exists"
50
+ fi
51
+
52
+ # Need to source conda for script environment
53
+ eval "$(conda shell.bash hook)"
54
+ conda activate ragen
55
+
56
+ # Clone repository
57
+ # print_step "Cloning ragen repository..."
58
+ # git clone git@github.com:ZihanWang314/ragen.git
59
+ # cd ragen
60
+
61
+ # Install package in editable mode
62
+ print_step "setting up verl..."
63
+ git submodule init
64
+ git submodule update
65
+ cd verl
66
+ pip install -e . --no-dependencies # we put dependencies in RAGEN/requirements.txt
67
+ cd ..
68
+
69
+ # Install package in editable mode
70
+ print_step "Installing ragen package..."
71
+ pip install -e .
72
+
73
+ # Install PyTorch with CUDA if available
74
+ if check_cuda; then
75
+ print_step "CUDA detected, checking CUDA version..."
76
+
77
+ if command -v nvcc &> /dev/null; then
78
+ nvcc_version=$(nvcc --version | grep "release" | awk '{print $6}' | cut -c2-)
79
+ nvcc_major=$(echo $nvcc_version | cut -d. -f1)
80
+ nvcc_minor=$(echo $nvcc_version | cut -d. -f2)
81
+
82
+ print_step "Found NVCC version: $nvcc_version"
83
+
84
+ if [[ "$nvcc_major" -gt 12 || ("$nvcc_major" -eq 12 && "$nvcc_minor" -ge 1) ]]; then
85
+ print_step "CUDA $nvcc_version is already installed and meets requirements (>=12.4)"
86
+ export CUDA_HOME=${CUDA_HOME:-$(dirname $(dirname $(which nvcc)))}
87
+ else
88
+ print_step "CUDA version < 12.4, installing CUDA toolkit 12.4..."
89
+ conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y
90
+ export CUDA_HOME=$CONDA_PREFIX
91
+ fi
92
+ else
93
+ print_step "NVCC not found, installing CUDA toolkit 12.4..."
94
+ conda install -c "nvidia/label/cuda-12.4.0" cuda-toolkit -y
95
+ export CUDA_HOME=$CONDA_PREFIX
96
+ fi
97
+
98
+ print_step "Installing PyTorch with CUDA support..."
99
+ pip install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124
100
+
101
+ print_step "Installing flash-attention..."
102
+ pip3 install flash-attn --no-build-isolation
103
+ else
104
+ print_step "Installing PyTorch without CUDA support..."
105
+ pip install torch==2.6.0
106
+ fi
107
+
108
+ # TODO: merge this with the main setup script with an option to install webshop
109
+ # Install if you want to use webshop
110
+ conda install -c pytorch faiss-cpu -y
111
+ sudo apt update
112
+ sudo apt install default-jdk
113
+ conda install -c conda-forge openjdk=21 maven -y
114
+
115
+ # Install remaining requirements
116
+ print_step "Installing additional requirements..."
117
+ pip install -r requirements.txt
118
+
119
+ # webshop installation, model loading
120
+ pip install -e external/webshop-minimal/ --no-dependencies
121
+ python -m spacy download en_core_web_sm
122
+ python -m spacy download en_core_web_lg
123
+
124
+ print_step "Downloading data..."
125
+ python scripts/download_data.py
126
+
127
+ # Optional: download full data set
128
+ print_step "Downloading full data set..."
129
+ conda install conda-forge::gdown
130
+ mkdir -p external/webshop-minimal/webshop_minimal/data/full
131
+ cd external/webshop-minimal/webshop_minimal/data/full
132
+ gdown https://drive.google.com/uc?id=1A2whVgOO0euk5O13n2iYDM0bQRkkRduB # items_shuffle
133
+ gdown https://drive.google.com/uc?id=1s2j6NgHljiZzQNL3veZaAiyW_qDEgBNi # items_ins_v2
134
+ cd ../../../../..
135
+
136
+ echo -e "${GREEN}Installation completed successfully!${NC}"
137
+ echo "To activate the environment, run: conda activate ragen"
138
+
139
+ # export CMAKE_POLICY_VERSION_MINIMUM=3.5 && pip install alfworld[full]
140
+ # alfworld-download
141
+ }
142
+
143
+ # Run main installation
144
+ main
scripts/setup_webshop.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Exit on error
4
+ set -e
5
+
6
+ echo "Setting up webshop..."
7
+ echo "NOTE: please run scripts/setup_ragen.sh before running this script"
8
+
9
+ # Colors for output
10
+ GREEN='\033[0;32m'
11
+ BLUE='\033[0;34m'
12
+ NC='\033[0m' # No Color
13
+
14
+ # Print step with color
15
+ print_step() {
16
+ echo -e "${BLUE}[Step] ${1}${NC}"
17
+ }
18
+
19
+ # Main installation process
20
+ # TODO: merge this with the main setup script with an option to install webshop
21
+ # Install if you want to use webshop
22
+ conda install -c pytorch faiss-cpu -y
23
+ sudo apt update
24
+ sudo apt install default-jdk -y
25
+ conda install -c conda-forge openjdk=21 maven -y
26
+
27
+ # Install remaining requirements
28
+ print_step "Installing additional requirements..."
29
+ pip install -r requirements.txt
30
+
31
+ # webshop installation, model loading
32
+ pip install -e external/webshop-minimal/ --no-dependencies
33
+ python -m spacy download en_core_web_sm
34
+ python -m spacy download en_core_web_lg
35
+
36
+ print_step "Downloading data..."
37
+ python scripts/download_data.py
38
+
39
+ # Optional: download full data set
40
+ print_step "Downloading full data set..."
41
+ conda install conda-forge::gdown
42
+ mkdir -p external/webshop-minimal/webshop_minimal/data/full
43
+ cd external/webshop-minimal/webshop_minimal/data/full
44
+ gdown https://drive.google.com/uc?id=1A2whVgOO0euk5O13n2iYDM0bQRkkRduB # items_shuffle
45
+ gdown https://drive.google.com/uc?id=1s2j6NgHljiZzQNL3veZaAiyW_qDEgBNi # items_ins_v2
46
+ cd ../../../../..
47
+
48
+ echo -e "${GREEN}Installation completed successfully!${NC}"
49
+ echo "To activate the environment, run: conda activate ragen"
50
+
scripts/synthesize_bon.sh ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \
2
+ # --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn.json \
3
+ # --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \
4
+ # --output-prefix withthink_fulltraj_sa \
5
+ # --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
6
+ # --tensor-parallel-size 4 \
7
+ # --n 8 \
8
+ # --batch-size 32 \
9
+ # --judge-batch-size 32
10
+
11
+ # python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \
12
+ # --input /mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155447/sft/step_1000000_sft_singleturn.json \
13
+ # --output-dir /mnt/general/wanghy/RAGEN/runs/SokobanNoisyDQN__noisy_dqn_sokoban__1__1764155447/sft/ \
14
+ # --output-prefix withthink_fulltraj_sa \
15
+ # --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
16
+ # --tensor-parallel-size 4 \
17
+ # --n 8 \
18
+ # --batch-size 32 \
19
+ # --judge-batch-size 32
20
+
21
+ # python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \
22
+ # --input /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__p0.9_slippery/sft/step_1986560_sft_slippery_singleturn.json \
23
+ # --output-dir /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__p0.9_slippery/sft/ \
24
+ # --output-prefix withthink_fulltraj_sa \
25
+ # --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
26
+ # --tensor-parallel-size 4 \
27
+ # --n 8 \
28
+ # --batch-size 32 \
29
+ # --judge-batch-size 32
30
+
31
+ # python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \
32
+ # --input /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__1__1763646695/sft/step_1986560_sft_noslippery_singleturn.json \
33
+ # --output-dir /mnt/general/wanghy/RAGEN/runs/FrozenLake__ppo_frozenlake_nochangeenv__1__1763646695/sft/ \
34
+ # --output-prefix withthink_fulltraj_sa \
35
+ # --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
36
+ # --tensor-parallel-size 4 \
37
+ # --n 8 \
38
+ # --batch-size 32 \
39
+ # --judge-batch-size 32
40
+
41
+ # python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \
42
+ # --input /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube1_1218/sft/step_999424_sft_singleturn.json \
43
+ # --output-dir /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube1_1218/sft/ \
44
+ # --output-prefix withthink_fulltraj_sa \
45
+ # --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
46
+ # --tensor-parallel-size 4 \
47
+ # --n 8 \
48
+ # --batch-size 32 \
49
+ # --judge-batch-size 32
50
+
51
+ python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \
52
+ --input /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube2_1219_turn5/sft/step_999424_sft_singleturn.json \
53
+ --output-dir /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube2_1219_turn5/sft/ \
54
+ --output-prefix withthink_fulltraj_sa \
55
+ --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
56
+ --tensor-parallel-size 4 \
57
+ --n 8 \
58
+ --batch-size 32 \
59
+ --judge-batch-size 32
60
+
61
+ # python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_traj_sa.py \
62
+ # --input /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube3_1219_turn5_6000/sft/step_999424_sft_singleturn.json \
63
+ # --output-dir /mnt/general/wanghy/RAGEN/runs/RubiksCube2x2__ppo_rubikscube3_1219_turn5_6000/sft/ \
64
+ # --output-prefix withthink_fulltraj_sa \
65
+ # --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
66
+ # --tensor-parallel-size 4 \
67
+ # --n 8 \
68
+ # --batch-size 32 \
69
+ # --judge-batch-size 32
scripts/synthesize_think_bon.py ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Synthesize <think> traces for SFT singleturn trajectories with BoN + judge.
3
+
4
+ This script is intentionally environment-agnostic. It assumes a JSON list of rows
5
+ with the common RAGEN SFT shape:
6
+
7
+ {"messages": [{"role": "system"}, {"role": "user"}, {"role": "assistant"}, ...],
8
+ "meta": {"source_id": ..., "turns": ..., "total_turns": ...}}
9
+
10
+ For each source_id, the complete trajectory row is selected, one reasoning trace
11
+ is synthesized per turn, and the selected traces are written back to every
12
+ cumulative singleturn prefix while keeping every original <answer>...</answer>
13
+ block exactly unchanged.
14
+
15
+
16
+ python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon.py \
17
+ --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json \
18
+ --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \
19
+ --output-prefix step_999424_sft_singleturn_withthink \
20
+ --versions sa,sas \
21
+ --model /mnt/general/share/model/Qwen/Qwen2.5-7B-Instruct \
22
+ --tensor-parallel-size 4 \
23
+ --n 8 \
24
+ --batch-size 32 \
25
+ --judge-batch-size 32 \
26
+ --limit-sources 50
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import copy
33
+ import json
34
+ import re
35
+ from dataclasses import dataclass
36
+ from pathlib import Path
37
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
38
+
39
+
40
+ ANSWER_RE = re.compile(r"<answer>.*?</answer>", re.IGNORECASE | re.DOTALL)
41
+ THINK_RE = re.compile(r"<think>(.*?)</think>", re.IGNORECASE | re.DOTALL)
42
+ JSON_OBJ_RE = re.compile(r"\{.*\}", re.DOTALL)
43
+
44
+
45
+ @dataclass
46
+ class TurnExample:
47
+ source_id: Any
48
+ turn_idx: int
49
+ total_turns: int
50
+ user_content: str
51
+ assistant_content: str
52
+ answer_block: str
53
+ next_user_content: Optional[str]
54
+
55
+
56
+ @dataclass
57
+ class FullTrajectory:
58
+ source_id: Any
59
+ sys_prefix: List[Dict[str, Any]]
60
+ pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]]
61
+ meta: Dict[str, Any]
62
+
63
+
64
+ def parse_args() -> argparse.Namespace:
65
+ parser = argparse.ArgumentParser(
66
+ description="Synthesize expert-action thinking traces with per-turn BoN and LLM judge."
67
+ )
68
+ parser.add_argument("--input", "-i", type=Path, required=True, help="Input SFT JSON list.")
69
+ parser.add_argument(
70
+ "--output-dir",
71
+ type=Path,
72
+ default=None,
73
+ help="Directory for output files. Defaults to input parent.",
74
+ )
75
+ parser.add_argument(
76
+ "--output-prefix",
77
+ default=None,
78
+ help="Output filename prefix. Defaults to input stem.",
79
+ )
80
+ parser.add_argument(
81
+ "--versions",
82
+ default="sa,sas",
83
+ help="Comma-separated versions: sa and/or sas. sa uses s,a; sas uses s,a,s'.",
84
+ )
85
+ parser.add_argument("--model", default=None, help="HF model path for tokenizer + vLLM.")
86
+ parser.add_argument("--judge-model", default=None, help="Optional separate judge model path.")
87
+ parser.add_argument("--n", type=int, default=8, help="BoN candidates per turn.")
88
+ parser.add_argument(
89
+ "--mode",
90
+ default="per_turn",
91
+ choices=["per_turn"],
92
+ help="BoN mode. Currently only independent per-turn BoN is implemented.",
93
+ )
94
+ parser.add_argument("--limit-sources", type=int, default=None, help="Pilot limit by source_id count.")
95
+ parser.add_argument("--source-ids", default="", help="Optional comma-separated source_id allowlist.")
96
+ parser.add_argument("--batch-size", type=int, default=64, help="Prompt batch size for generation.")
97
+ parser.add_argument("--judge-batch-size", type=int, default=64, help="Prompt batch size for judge.")
98
+ parser.add_argument("--temperature", type=float, default=0.7)
99
+ parser.add_argument("--top-p", type=float, default=0.95)
100
+ parser.add_argument("--top-k", type=int, default=-1)
101
+ parser.add_argument("--max-tokens", type=int, default=160, help="Max tokens for think generation.")
102
+ parser.add_argument("--judge-temperature", type=float, default=0.0)
103
+ parser.add_argument("--judge-max-tokens", type=int, default=768)
104
+ parser.add_argument("--tensor-parallel-size", type=int, default=1)
105
+ parser.add_argument("--judge-tensor-parallel-size", type=int, default=None)
106
+ parser.add_argument("--dtype", default="auto")
107
+ parser.add_argument("--gpu-memory-utilization", type=float, default=0.9)
108
+ parser.add_argument("--max-model-len", type=int, default=None)
109
+ parser.add_argument("--trust-remote-code", action="store_true")
110
+ parser.add_argument("--min-judge-score", type=float, default=3.0)
111
+ parser.add_argument("--save-candidates", action="store_true", help="Store all candidates in report.")
112
+ parser.add_argument(
113
+ "--selected-only",
114
+ action="store_true",
115
+ help="Write only rows whose source_id was selected by --limit-sources/--source-ids.",
116
+ )
117
+ parser.add_argument("--no-cache", action="store_true", help="Disable JSONL cache/resume.")
118
+ parser.add_argument("--dry-run", action="store_true", help="Do not load vLLM; create deterministic mock thinks.")
119
+ parser.add_argument("--indent", type=int, default=2, help="JSON output indent. Use -1 for compact.")
120
+ return parser.parse_args()
121
+
122
+
123
+ def load_json_list(path: Path) -> List[Dict[str, Any]]:
124
+ with path.open("r", encoding="utf-8") as f:
125
+ data = json.load(f)
126
+ if not isinstance(data, list):
127
+ raise ValueError(f"Expected JSON list at {path}, got {type(data).__name__}")
128
+ if not all(isinstance(row, dict) for row in data):
129
+ raise ValueError(f"Expected all rows to be objects in {path}")
130
+ return data
131
+
132
+
133
+ def dump_json(path: Path, data: Any, indent: int) -> None:
134
+ path.parent.mkdir(parents=True, exist_ok=True)
135
+ kwargs = {"ensure_ascii": False}
136
+ if indent >= 0:
137
+ kwargs["indent"] = indent
138
+ with path.open("w", encoding="utf-8") as f:
139
+ json.dump(data, f, **kwargs)
140
+
141
+
142
+ def extract_system_prefix(messages: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
143
+ out: List[Dict[str, Any]] = []
144
+ for msg in messages:
145
+ if msg.get("role") == "system":
146
+ out.append(copy.deepcopy(msg))
147
+ else:
148
+ break
149
+ return out
150
+
151
+
152
+ def collect_pairs(messages: Sequence[Dict[str, Any]], start_idx: int = 0) -> List[Tuple[Dict[str, Any], Dict[str, Any]]]:
153
+ pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
154
+ idx = start_idx
155
+ while idx < len(messages):
156
+ while idx < len(messages) and messages[idx].get("role") != "user":
157
+ idx += 1
158
+ if idx >= len(messages):
159
+ break
160
+ if idx + 1 < len(messages) and messages[idx + 1].get("role") == "assistant":
161
+ pairs.append((copy.deepcopy(messages[idx]), copy.deepcopy(messages[idx + 1])))
162
+ idx += 2
163
+ else:
164
+ idx += 1
165
+ return pairs
166
+
167
+
168
+ def to_int(value: Any, default: int = 0) -> int:
169
+ try:
170
+ return int(value)
171
+ except (TypeError, ValueError):
172
+ return default
173
+
174
+
175
+ def source_key(source_id: Any) -> str:
176
+ return str(source_id)
177
+
178
+
179
+ def group_rows(rows: Sequence[Dict[str, Any]]) -> Dict[Any, List[Dict[str, Any]]]:
180
+ groups: Dict[Any, List[Dict[str, Any]]] = {}
181
+ for idx, row in enumerate(rows):
182
+ meta = row.get("meta") or {}
183
+ source_id = meta.get("source_id", f"missing_source_{idx}")
184
+ groups.setdefault(source_id, []).append(row)
185
+ for items in groups.values():
186
+ items.sort(key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))
187
+ return groups
188
+
189
+
190
+ def select_full_row(source_id: Any, items: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
191
+ exact = [
192
+ row
193
+ for row in items
194
+ if to_int((row.get("meta") or {}).get("turns"), -1)
195
+ == to_int((row.get("meta") or {}).get("total_turns"), -2)
196
+ ]
197
+ if exact:
198
+ return exact[-1]
199
+ return max(items, key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))
200
+
201
+
202
+ def build_full_trajectories(rows: Sequence[Dict[str, Any]]) -> Dict[Any, FullTrajectory]:
203
+ groups = group_rows(rows)
204
+ full: Dict[Any, FullTrajectory] = {}
205
+ for source_id, items in groups.items():
206
+ row = select_full_row(source_id, items)
207
+ messages = row.get("messages") or []
208
+ if not isinstance(messages, list):
209
+ continue
210
+ sys_prefix = extract_system_prefix(messages)
211
+ pairs = collect_pairs(messages, start_idx=len(sys_prefix))
212
+ if not pairs:
213
+ continue
214
+ full[source_id] = FullTrajectory(
215
+ source_id=source_id,
216
+ sys_prefix=sys_prefix,
217
+ pairs=pairs,
218
+ meta=dict(row.get("meta") or {}),
219
+ )
220
+ return full
221
+
222
+
223
+ def extract_answer_block(text: str) -> str:
224
+ match = ANSWER_RE.search(text or "")
225
+ return match.group(0) if match is not None else ""
226
+
227
+
228
+ def clean_think(text: str) -> str:
229
+ text = (text or "").strip()
230
+ think_match = THINK_RE.search(text)
231
+ if think_match is not None:
232
+ text = think_match.group(1).strip()
233
+ text = re.split(r"<\s*/?\s*answer\s*>", text, flags=re.IGNORECASE)[0]
234
+ text = re.sub(r"</?think>", "", text, flags=re.IGNORECASE)
235
+ text = re.sub(r"\s+", " ", text).strip()
236
+ text = text.strip('` \t\n\r"')
237
+ return text
238
+
239
+
240
+ def make_response(think: str, answer_block: str) -> str:
241
+ return f"<think>{think.strip()}</think>{answer_block}"
242
+
243
+
244
+ def iter_turns(full: Dict[Any, FullTrajectory]) -> List[TurnExample]:
245
+ turns: List[TurnExample] = []
246
+ for source_id, traj in full.items():
247
+ total_turns = len(traj.pairs)
248
+ for i, (user_msg, asst_msg) in enumerate(traj.pairs):
249
+ answer_block = extract_answer_block(str(asst_msg.get("content", "")))
250
+ next_user = None
251
+ if i + 1 < total_turns:
252
+ next_user = str(traj.pairs[i + 1][0].get("content", ""))
253
+ turns.append(
254
+ TurnExample(
255
+ source_id=source_id,
256
+ turn_idx=i + 1,
257
+ total_turns=total_turns,
258
+ user_content=str(user_msg.get("content", "")),
259
+ assistant_content=str(asst_msg.get("content", "")),
260
+ answer_block=answer_block,
261
+ next_user_content=next_user,
262
+ )
263
+ )
264
+ return turns
265
+
266
+
267
+ def build_generation_messages(example: TurnExample, version: str) -> List[Dict[str, str]]:
268
+ if version not in {"sa", "sas"}:
269
+ raise ValueError(f"Unknown version: {version}")
270
+ sas_available = version == "sas" and example.next_user_content is not None
271
+ parts = [
272
+ "We are creating high-quality SFT reasoning for an expert trajectory.",
273
+ "The expert action is fixed. Your job is only to write the inner text for <think>...</think>.",
274
+ "Do not output <think>, </think>, <answer>, JSON, bullets, or any extra wrapper.",
275
+ "Do not change or restate a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.",
276
+ "Keep it concise: 1-3 English sentences explaining why the fixed action is reasonable from the visible context.",
277
+ "",
278
+ "Current observation/state s:",
279
+ "```text",
280
+ example.user_content.strip(),
281
+ "```",
282
+ "",
283
+ "Fixed expert action a:",
284
+ "```text",
285
+ example.answer_block.strip() or example.assistant_content.strip(),
286
+ "```",
287
+ ]
288
+ if sas_available:
289
+ parts.extend(
290
+ [
291
+ "",
292
+ "Observed next state/feedback s' after executing the fixed action:",
293
+ "```text",
294
+ str(example.next_user_content).strip(),
295
+ "```",
296
+ "Use s' only to ground the explanation of the observed transition; never alter the fixed action.",
297
+ ]
298
+ )
299
+ elif version == "sas":
300
+ parts.extend(
301
+ [
302
+ "",
303
+ "No next state s' is available for this final turn, so explain using only s and a.",
304
+ ]
305
+ )
306
+ return [
307
+ {
308
+ "role": "system",
309
+ "content": "You write faithful, concise reasoning for fixed expert actions.",
310
+ },
311
+ {"role": "user", "content": "\n".join(parts)},
312
+ ]
313
+
314
+
315
+ def build_judge_messages(example: TurnExample, version: str, candidates: Sequence[str]) -> List[Dict[str, str]]:
316
+ candidate_text = "\n".join(f"[{i + 1}] {cand}" for i, cand in enumerate(candidates))
317
+ sas_available = version == "sas" and example.next_user_content is not None
318
+ parts = [
319
+ "You are auditing candidate <think> texts for an expert SFT trajectory.",
320
+ "The expert action is fixed. Select the candidate that best explains it while staying faithful to the visible context.",
321
+ "Penalize unsupported factual claims, contradicted claims, changing the action, excessive certainty such as 'only'/'optimal' without clear support, verbosity, and format pollution.",
322
+ "Return strict JSON only, with no markdown.",
323
+ "",
324
+ "Current observation/state s:",
325
+ "```text",
326
+ example.user_content.strip(),
327
+ "```",
328
+ "",
329
+ "Fixed expert action a:",
330
+ "```text",
331
+ example.answer_block.strip() or example.assistant_content.strip(),
332
+ "```",
333
+ ]
334
+ if sas_available:
335
+ parts.extend(
336
+ [
337
+ "",
338
+ "Observed next state/feedback s' after executing a:",
339
+ "```text",
340
+ str(example.next_user_content).strip(),
341
+ "```",
342
+ ]
343
+ )
344
+ elif version == "sas":
345
+ parts.append("\nNo next state s' is available for this final turn.")
346
+ parts.extend(
347
+ [
348
+ "",
349
+ "Candidates:",
350
+ candidate_text,
351
+ "",
352
+ "Use this JSON schema:",
353
+ '{"best_index": 1, "scores": [{"index": 1, "score": 1, "unsupported_claims": 0, "contradictions": 0, "reason": "short reason"}], "selected_reason": "short reason", "low_quality": false}',
354
+ "Scores are from 1 to 5. Set low_quality=true if the best candidate is still weak or generic.",
355
+ ]
356
+ )
357
+ return [
358
+ {"role": "system", "content": "You are a strict factuality judge for reasoning traces."},
359
+ {"role": "user", "content": "\n".join(parts)},
360
+ ]
361
+
362
+
363
+ def render_prompt(tokenizer: Any, messages: List[Dict[str, str]]) -> str:
364
+ return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
365
+
366
+
367
+ def load_vllm_model(
368
+ model_path: str,
369
+ args: argparse.Namespace,
370
+ tensor_parallel_size: Optional[int] = None,
371
+ ) -> Tuple[Any, Any]:
372
+ try:
373
+ from transformers import AutoTokenizer
374
+ from vllm import LLM
375
+ except ImportError as exc:
376
+ raise RuntimeError("This script requires `vllm` and `transformers`.") from exc
377
+
378
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=bool(args.trust_remote_code))
379
+ llm_kwargs: Dict[str, Any] = {
380
+ "model": model_path,
381
+ "tensor_parallel_size": int(tensor_parallel_size or args.tensor_parallel_size),
382
+ "dtype": args.dtype,
383
+ "gpu_memory_utilization": float(args.gpu_memory_utilization),
384
+ "trust_remote_code": bool(args.trust_remote_code),
385
+ }
386
+ if args.max_model_len is not None:
387
+ llm_kwargs["max_model_len"] = int(args.max_model_len)
388
+ return LLM(**llm_kwargs), tokenizer
389
+
390
+
391
+ def make_sampling_params(args: argparse.Namespace, *, judge: bool = False) -> Any:
392
+ try:
393
+ from vllm import SamplingParams
394
+ except ImportError as exc:
395
+ raise RuntimeError("This script requires `vllm`.") from exc
396
+ if judge:
397
+ return SamplingParams(
398
+ temperature=float(args.judge_temperature),
399
+ top_p=1.0,
400
+ max_tokens=int(args.judge_max_tokens),
401
+ )
402
+ return SamplingParams(
403
+ n=int(args.n),
404
+ temperature=float(args.temperature),
405
+ top_p=float(args.top_p),
406
+ top_k=int(args.top_k),
407
+ max_tokens=int(args.max_tokens),
408
+ )
409
+
410
+
411
+ def chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]:
412
+ if size <= 0:
413
+ yield items
414
+ return
415
+ for start in range(0, len(items), size):
416
+ yield items[start : start + size]
417
+
418
+
419
+ def parse_judge_json(text: str) -> Dict[str, Any]:
420
+ text = (text or "").strip()
421
+ match = JSON_OBJ_RE.search(text)
422
+ if match is not None:
423
+ text = match.group(0)
424
+ try:
425
+ obj = json.loads(text)
426
+ if isinstance(obj, dict):
427
+ return obj
428
+ except json.JSONDecodeError:
429
+ pass
430
+ return {}
431
+
432
+
433
+ def selected_score(judge_obj: Dict[str, Any], best_index: int) -> float:
434
+ for item in judge_obj.get("scores") or []:
435
+ if isinstance(item, dict) and to_int(item.get("index"), -1) == best_index:
436
+ try:
437
+ return float(item.get("score", 0.0))
438
+ except (TypeError, ValueError):
439
+ return 0.0
440
+ return 0.0
441
+
442
+
443
+ def fallback_think(version: str) -> str:
444
+ if version == "sas":
445
+ return (
446
+ "The expert action is kept fixed and is explained using the current observation "
447
+ "together with the observed next-state feedback, without changing the action."
448
+ )
449
+ return (
450
+ "The expert action is kept fixed and is chosen based on the current observation "
451
+ "and task constraints, aiming to make progress without changing the demonstrated action."
452
+ )
453
+
454
+
455
+ def cache_key(version: str, source_id: Any, turn_idx: int) -> str:
456
+ return json.dumps(
457
+ {"version": version, "source_id": source_id, "turn_idx": turn_idx},
458
+ ensure_ascii=False,
459
+ sort_keys=True,
460
+ )
461
+
462
+
463
+ def load_cache(path: Path) -> Dict[str, Dict[str, Any]]:
464
+ cache: Dict[str, Dict[str, Any]] = {}
465
+ if not path.exists():
466
+ return cache
467
+ with path.open("r", encoding="utf-8") as f:
468
+ for line_no, line in enumerate(f, start=1):
469
+ line = line.strip()
470
+ if not line:
471
+ continue
472
+ try:
473
+ row = json.loads(line)
474
+ except json.JSONDecodeError:
475
+ print(f"Warning: skipped invalid cache line {path}:{line_no}")
476
+ continue
477
+ key = row.get("cache_key")
478
+ if isinstance(key, str):
479
+ cache[key] = row
480
+ return cache
481
+
482
+
483
+ def append_cache(path: Path, rows: Sequence[Dict[str, Any]]) -> None:
484
+ if not rows:
485
+ return
486
+ path.parent.mkdir(parents=True, exist_ok=True)
487
+ with path.open("a", encoding="utf-8") as f:
488
+ for row in rows:
489
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
490
+
491
+
492
+ def dry_candidates(example: TurnExample, version: str, n: int) -> List[str]:
493
+ base = "This fixed expert action is explained from the visible state while preserving the demonstrated answer."
494
+ if version == "sas" and example.next_user_content is not None:
495
+ base = "This fixed expert action is explained from the visible state and the observed next-state feedback."
496
+ return [f"{base} Candidate {i + 1}." for i in range(n)]
497
+
498
+
499
+ def synthesize_version(
500
+ *,
501
+ version: str,
502
+ turns: Sequence[TurnExample],
503
+ args: argparse.Namespace,
504
+ output_dir: Path,
505
+ output_prefix: str,
506
+ llm: Any,
507
+ tokenizer: Any,
508
+ judge_llm: Any,
509
+ judge_tokenizer: Any,
510
+ ) -> Dict[Tuple[Any, int], Dict[str, Any]]:
511
+ cache_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.cache.jsonl"
512
+ cache = {} if args.no_cache else load_cache(cache_path)
513
+ results: Dict[Tuple[Any, int], Dict[str, Any]] = {}
514
+ missing: List[TurnExample] = []
515
+ for ex in turns:
516
+ key = cache_key(version, ex.source_id, ex.turn_idx)
517
+ cached = cache.get(key)
518
+ if cached is not None and cached.get("selected_think"):
519
+ results[(ex.source_id, ex.turn_idx)] = cached
520
+ else:
521
+ missing.append(ex)
522
+
523
+ print(f"[{version}] turns={len(turns)} cached={len(results)} missing={len(missing)}")
524
+ gen_params = None if args.dry_run else make_sampling_params(args, judge=False)
525
+ judge_params = None if args.dry_run else make_sampling_params(args, judge=True)
526
+
527
+ for batch_no, batch in enumerate(chunks(missing, int(args.batch_size)), start=1):
528
+ batch = list(batch)
529
+ if args.dry_run:
530
+ all_candidates = [dry_candidates(ex, version, int(args.n)) for ex in batch]
531
+ else:
532
+ prompts = [render_prompt(tokenizer, build_generation_messages(ex, version)) for ex in batch]
533
+ outputs = llm.generate(prompts, sampling_params=gen_params)
534
+ all_candidates = []
535
+ for out in outputs:
536
+ candidates = [clean_think(candidate.text) for candidate in out.outputs]
537
+ candidates = [cand for cand in candidates if cand]
538
+ all_candidates.append(candidates)
539
+
540
+ judge_inputs: List[Tuple[TurnExample, List[str]]] = []
541
+ batch_rows: List[Dict[str, Any]] = []
542
+ for ex, candidates in zip(batch, all_candidates):
543
+ if not candidates:
544
+ selected = fallback_think(version)
545
+ row = {
546
+ "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
547
+ "version": version,
548
+ "source_id": ex.source_id,
549
+ "turn_idx": ex.turn_idx,
550
+ "total_turns": ex.total_turns,
551
+ "selected_think": selected,
552
+ "selected_index": None,
553
+ "score": 0.0,
554
+ "low_quality": True,
555
+ "fallback": True,
556
+ "missing_next_state": version == "sas" and ex.next_user_content is None,
557
+ "selected_reason": "No valid generation candidates; used fallback.",
558
+ }
559
+ if args.save_candidates:
560
+ row["candidates"] = []
561
+ batch_rows.append(row)
562
+ else:
563
+ judge_inputs.append((ex, candidates))
564
+
565
+ judge_texts: List[str] = []
566
+ if judge_inputs:
567
+ if args.dry_run:
568
+ judge_texts = [
569
+ json.dumps(
570
+ {
571
+ "best_index": 1,
572
+ "scores": [
573
+ {
574
+ "index": 1,
575
+ "score": 3,
576
+ "unsupported_claims": 0,
577
+ "contradictions": 0,
578
+ "reason": "dry run",
579
+ }
580
+ ],
581
+ "selected_reason": "dry run",
582
+ "low_quality": False,
583
+ }
584
+ )
585
+ for _ in judge_inputs
586
+ ]
587
+ else:
588
+ judge_prompts = [
589
+ render_prompt(judge_tokenizer, build_judge_messages(ex, version, candidates))
590
+ for ex, candidates in judge_inputs
591
+ ]
592
+ judge_texts = []
593
+ for judge_chunk in chunks(judge_prompts, int(args.judge_batch_size)):
594
+ judge_outputs = judge_llm.generate(list(judge_chunk), sampling_params=judge_params)
595
+ judge_texts.extend(out.outputs[0].text for out in judge_outputs)
596
+
597
+ for (ex, candidates), judge_text in zip(judge_inputs, judge_texts):
598
+ judge_obj = parse_judge_json(judge_text)
599
+ best_index = to_int(judge_obj.get("best_index"), 1)
600
+ if best_index < 1 or best_index > len(candidates):
601
+ best_index = 1
602
+ selected = candidates[best_index - 1]
603
+ score = selected_score(judge_obj, best_index)
604
+ if score <= 0.0:
605
+ score = 3.0 if selected else 0.0
606
+ low_quality = bool(judge_obj.get("low_quality", False)) or score < float(args.min_judge_score)
607
+ row = {
608
+ "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
609
+ "version": version,
610
+ "source_id": ex.source_id,
611
+ "turn_idx": ex.turn_idx,
612
+ "total_turns": ex.total_turns,
613
+ "selected_think": selected or fallback_think(version),
614
+ "selected_index": best_index,
615
+ "score": score,
616
+ "low_quality": low_quality,
617
+ "fallback": not bool(selected),
618
+ "missing_next_state": version == "sas" and ex.next_user_content is None,
619
+ "selected_reason": str(judge_obj.get("selected_reason", "")),
620
+ }
621
+ if args.save_candidates:
622
+ row["candidates"] = candidates
623
+ row["judge"] = judge_obj
624
+ row["judge_raw"] = judge_text
625
+ batch_rows.append(row)
626
+
627
+ append_cache(cache_path, batch_rows) if not args.no_cache else None
628
+ for row in batch_rows:
629
+ results[(row["source_id"], int(row["turn_idx"]))] = row
630
+ print(f"[{version}] batch {batch_no}: wrote {len(batch_rows)} turn results")
631
+ return results
632
+
633
+
634
+ def rebuild_rows(
635
+ rows: Sequence[Dict[str, Any]],
636
+ full: Dict[Any, FullTrajectory],
637
+ result_map: Dict[Tuple[Any, int], Dict[str, Any]],
638
+ ) -> List[Dict[str, Any]]:
639
+ rebuilt_by_source: Dict[Any, List[Tuple[Dict[str, Any], Dict[str, Any]]]] = {}
640
+ for source_id, traj in full.items():
641
+ new_pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
642
+ for idx, (user_msg, asst_msg) in enumerate(traj.pairs, start=1):
643
+ answer_block = extract_answer_block(str(asst_msg.get("content", "")))
644
+ result = result_map.get((source_id, idx))
645
+ think = str(result.get("selected_think", "")) if result else fallback_think("sa")
646
+ new_user = copy.deepcopy(user_msg)
647
+ new_asst = copy.deepcopy(asst_msg)
648
+ if answer_block:
649
+ new_asst["content"] = make_response(think, answer_block)
650
+ else:
651
+ new_asst["content"] = str(asst_msg.get("content", ""))
652
+ new_pairs.append((new_user, new_asst))
653
+ rebuilt_by_source[source_id] = new_pairs
654
+
655
+ output: List[Dict[str, Any]] = []
656
+ for idx, row in enumerate(rows):
657
+ meta = row.get("meta") or {}
658
+ source_id = meta.get("source_id", f"missing_source_{idx}")
659
+ turns = to_int(meta.get("turns"), 0)
660
+ new_row = copy.deepcopy(row)
661
+ traj = full.get(source_id)
662
+ pairs = rebuilt_by_source.get(source_id)
663
+ if traj is None or pairs is None or turns <= 0:
664
+ output.append(new_row)
665
+ continue
666
+ turns = min(turns, len(pairs))
667
+ new_row["messages"] = copy.deepcopy(traj.sys_prefix) + [
668
+ copy.deepcopy(msg) for pair in pairs[:turns] for msg in pair
669
+ ]
670
+ output.append(new_row)
671
+ return output
672
+
673
+
674
+ def validate_answer_unchanged(original: Sequence[Dict[str, Any]], rebuilt: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
675
+ if len(original) != len(rebuilt):
676
+ raise ValueError(f"Row count changed: original={len(original)} rebuilt={len(rebuilt)}")
677
+ checked = 0
678
+ mismatches: List[Dict[str, Any]] = []
679
+ for row_idx, (old_row, new_row) in enumerate(zip(original, rebuilt)):
680
+ old_pairs = collect_pairs(old_row.get("messages") or [], start_idx=len(extract_system_prefix(old_row.get("messages") or [])))
681
+ new_pairs = collect_pairs(new_row.get("messages") or [], start_idx=len(extract_system_prefix(new_row.get("messages") or [])))
682
+ if len(old_pairs) != len(new_pairs):
683
+ mismatches.append({"row_idx": row_idx, "reason": "pair_count_changed"})
684
+ continue
685
+ for turn_idx, ((_, old_asst), (_, new_asst)) in enumerate(zip(old_pairs, new_pairs), start=1):
686
+ old_answer = extract_answer_block(str(old_asst.get("content", "")))
687
+ new_answer = extract_answer_block(str(new_asst.get("content", "")))
688
+ checked += 1
689
+ if old_answer != new_answer:
690
+ mismatches.append(
691
+ {
692
+ "row_idx": row_idx,
693
+ "turn_idx": turn_idx,
694
+ "old_answer": old_answer,
695
+ "new_answer": new_answer,
696
+ }
697
+ )
698
+ if len(mismatches) >= 20:
699
+ break
700
+ if len(mismatches) >= 20:
701
+ break
702
+ if mismatches:
703
+ raise ValueError(f"Answer validation failed, examples: {mismatches[:3]}")
704
+ return {"checked_assistant_messages": checked, "answer_mismatches": 0}
705
+
706
+
707
+ def filter_full_by_args(full: Dict[Any, FullTrajectory], args: argparse.Namespace) -> Dict[Any, FullTrajectory]:
708
+ selected = dict(full)
709
+ if args.source_ids.strip():
710
+ allow = {item.strip() for item in args.source_ids.split(",") if item.strip()}
711
+ selected = {sid: traj for sid, traj in selected.items() if source_key(sid) in allow}
712
+ if args.limit_sources is not None:
713
+ limited: Dict[Any, FullTrajectory] = {}
714
+ for sid in list(selected.keys())[: int(args.limit_sources)]:
715
+ limited[sid] = selected[sid]
716
+ selected = limited
717
+ return selected
718
+
719
+
720
+ def report_from_results(
721
+ *,
722
+ version: str,
723
+ result_map: Dict[Tuple[Any, int], Dict[str, Any]],
724
+ validation: Dict[str, Any],
725
+ args: argparse.Namespace,
726
+ ) -> Dict[str, Any]:
727
+ values = list(result_map.values())
728
+ low_quality = sum(1 for row in values if row.get("low_quality"))
729
+ fallback = sum(1 for row in values if row.get("fallback"))
730
+ missing_next = sum(1 for row in values if row.get("missing_next_state"))
731
+ scores = [float(row.get("score", 0.0)) for row in values]
732
+ summary = {
733
+ "version": version,
734
+ "n": int(args.n),
735
+ "turn_results": len(values),
736
+ "low_quality": low_quality,
737
+ "fallback": fallback,
738
+ "missing_next_state": missing_next,
739
+ "avg_score": sum(scores) / len(scores) if scores else 0.0,
740
+ "min_score": min(scores) if scores else 0.0,
741
+ "max_score": max(scores) if scores else 0.0,
742
+ **validation,
743
+ }
744
+ per_turn: List[Dict[str, Any]] = []
745
+ for row in values:
746
+ item = {
747
+ "source_id": row.get("source_id"),
748
+ "turn_idx": row.get("turn_idx"),
749
+ "total_turns": row.get("total_turns"),
750
+ "selected_index": row.get("selected_index"),
751
+ "score": row.get("score"),
752
+ "low_quality": row.get("low_quality"),
753
+ "fallback": row.get("fallback"),
754
+ "missing_next_state": row.get("missing_next_state"),
755
+ "selected_reason": row.get("selected_reason", ""),
756
+ }
757
+ if args.save_candidates:
758
+ item["selected_think"] = row.get("selected_think")
759
+ item["candidates"] = row.get("candidates", [])
760
+ item["judge"] = row.get("judge", {})
761
+ per_turn.append(item)
762
+ return {"summary": summary, "per_turn": per_turn}
763
+
764
+
765
+ def main() -> None:
766
+ args = parse_args()
767
+ versions = [v.strip() for v in args.versions.split(",") if v.strip()]
768
+ if not versions or any(v not in {"sa", "sas"} for v in versions):
769
+ raise ValueError("--versions must contain only sa and/or sas")
770
+ if not args.dry_run and not args.model:
771
+ raise ValueError("--model is required unless --dry-run is set")
772
+
773
+ input_path = args.input.expanduser().resolve()
774
+ output_dir = (args.output_dir or input_path.parent).expanduser().resolve()
775
+ output_prefix = args.output_prefix or input_path.stem
776
+
777
+ print(f"Loading input: {input_path}")
778
+ rows = load_json_list(input_path)
779
+ full_all = build_full_trajectories(rows)
780
+ full_selected = filter_full_by_args(full_all, args)
781
+ if not full_selected:
782
+ raise ValueError("No usable trajectories selected.")
783
+ turns = iter_turns(full_selected)
784
+ print(f"Rows={len(rows)} sources={len(full_all)} selected_sources={len(full_selected)} selected_turns={len(turns)}")
785
+
786
+ llm = tokenizer = judge_llm = judge_tokenizer = None
787
+ if not args.dry_run:
788
+ llm, tokenizer = load_vllm_model(args.model, args, tensor_parallel_size=args.tensor_parallel_size)
789
+ judge_model = args.judge_model or args.model
790
+ if judge_model == args.model:
791
+ judge_llm, judge_tokenizer = llm, tokenizer
792
+ else:
793
+ judge_tp = args.judge_tensor_parallel_size or args.tensor_parallel_size
794
+ judge_llm, judge_tokenizer = load_vllm_model(judge_model, args, tensor_parallel_size=judge_tp)
795
+
796
+ for version in versions:
797
+ result_map = synthesize_version(
798
+ version=version,
799
+ turns=turns,
800
+ args=args,
801
+ output_dir=output_dir,
802
+ output_prefix=output_prefix,
803
+ llm=llm,
804
+ tokenizer=tokenizer,
805
+ judge_llm=judge_llm,
806
+ judge_tokenizer=judge_tokenizer,
807
+ )
808
+ rows_for_output = [
809
+ row
810
+ for idx, row in enumerate(rows)
811
+ if not args.selected_only
812
+ or (row.get("meta") or {}).get("source_id", f"missing_source_{idx}") in full_selected
813
+ ]
814
+ rebuilt = rebuild_rows(rows_for_output, full_selected, result_map)
815
+ validation = validate_answer_unchanged(rows_for_output, rebuilt)
816
+ out_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.json"
817
+ report_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.report.json"
818
+ dump_json(out_path, rebuilt, indent=int(args.indent))
819
+ report = report_from_results(version=version, result_map=result_map, validation=validation, args=args)
820
+ dump_json(report_path, report, indent=2)
821
+ print(f"[{version}] wrote SFT: {out_path}")
822
+ print(f"[{version}] wrote report: {report_path}")
823
+ print(f"[{version}] summary: {json.dumps(report['summary'], ensure_ascii=False)}")
824
+
825
+
826
+ if __name__ == "__main__":
827
+ main()
scripts/synthesize_think_bon_traj_sa.py ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Synthesize <think> traces for SFT singleturn trajectories with BoN + judge.
3
+
4
+ This script is intentionally environment-agnostic. It assumes a JSON list of rows
5
+ with the common RAGEN SFT shape:
6
+
7
+ {"messages": [{"role": "system"}, {"role": "user"}, {"role": "assistant"}, ...],
8
+ "meta": {"source_id": ..., "turns": ..., "total_turns": ...}}
9
+
10
+ For each source_id, the complete trajectory row is selected, one reasoning trace
11
+ is synthesized per turn, and the selected traces are written back to every
12
+ cumulative singleturn prefix while keeping every original <answer>...</answer>
13
+ block exactly unchanged.
14
+
15
+
16
+ python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_v2.py \
17
+ --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json \
18
+ --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \
19
+ --output-prefix step_999424_sft_singleturn_withthink \
20
+ --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
21
+ --tensor-parallel-size 4 \
22
+ --n 8 \
23
+ --batch-size 32 \
24
+ --judge-batch-size 32
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import copy
31
+ import json
32
+ import re
33
+ from dataclasses import dataclass
34
+ from pathlib import Path
35
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
36
+
37
+
38
+ ANSWER_RE = re.compile(r"<answer>.*?</answer>", re.IGNORECASE | re.DOTALL)
39
+ THINK_RE = re.compile(r"<think>(.*?)</think>", re.IGNORECASE | re.DOTALL)
40
+ JSON_OBJ_RE = re.compile(r"\{.*\}", re.DOTALL)
41
+ META_REASONING_RE = re.compile(
42
+ r"\b("
43
+ r"expert action|fixed action|given action|provided action|target action|"
44
+ r"demonstrated action|demonstrated answer|known action|chosen by (?:the )?expert|"
45
+ r"the action (?:was|is) (?:given|fixed|provided|known)"
46
+ r")\b",
47
+ re.IGNORECASE,
48
+ )
49
+
50
+
51
+ @dataclass
52
+ class TurnExample:
53
+ source_id: Any
54
+ turn_idx: int
55
+ total_turns: int
56
+ user_content: str
57
+ assistant_content: str
58
+ answer_block: str
59
+ next_user_content: Optional[str]
60
+ trajectory_context: str
61
+
62
+
63
+ @dataclass
64
+ class FullTrajectory:
65
+ source_id: Any
66
+ sys_prefix: List[Dict[str, Any]]
67
+ pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]]
68
+ meta: Dict[str, Any]
69
+
70
+
71
+ def parse_args() -> argparse.Namespace:
72
+ parser = argparse.ArgumentParser(
73
+ description="Synthesize first-person target-action thinking traces with per-turn BoN and LLM judge."
74
+ )
75
+ parser.add_argument("--input", "-i", type=Path, required=True, help="Input SFT JSON list.")
76
+ parser.add_argument(
77
+ "--output-dir",
78
+ type=Path,
79
+ default=None,
80
+ help="Directory for output files. Defaults to input parent.",
81
+ )
82
+ parser.add_argument(
83
+ "--output-prefix",
84
+ default=None,
85
+ help="Output filename prefix. Defaults to input stem.",
86
+ )
87
+ parser.add_argument(
88
+ "--versions",
89
+ default="traj_sa",
90
+ help="Comma-separated versions. This script supports only traj_sa: full trajectory in system, current s,a in user.",
91
+ )
92
+ parser.add_argument("--model", default=None, help="HF model path for tokenizer + vLLM.")
93
+ parser.add_argument("--judge-model", default=None, help="Optional separate judge model path.")
94
+ parser.add_argument("--n", type=int, default=8, help="BoN candidates per turn.")
95
+ parser.add_argument(
96
+ "--mode",
97
+ default="per_turn",
98
+ choices=["per_turn"],
99
+ help="BoN mode. Currently only independent per-turn BoN is implemented.",
100
+ )
101
+ parser.add_argument("--limit-sources", type=int, default=None, help="Pilot limit by source_id count.")
102
+ parser.add_argument("--source-ids", default="", help="Optional comma-separated source_id allowlist.")
103
+ parser.add_argument("--batch-size", type=int, default=64, help="Prompt batch size for generation.")
104
+ parser.add_argument("--judge-batch-size", type=int, default=64, help="Prompt batch size for judge.")
105
+ parser.add_argument("--temperature", type=float, default=0.7)
106
+ parser.add_argument("--top-p", type=float, default=0.95)
107
+ parser.add_argument("--top-k", type=int, default=-1)
108
+ parser.add_argument("--max-tokens", type=int, default=160, help="Max tokens for think generation.")
109
+ parser.add_argument("--judge-temperature", type=float, default=0.0)
110
+ parser.add_argument("--judge-max-tokens", type=int, default=768)
111
+ parser.add_argument("--tensor-parallel-size", type=int, default=1)
112
+ parser.add_argument("--judge-tensor-parallel-size", type=int, default=None)
113
+ parser.add_argument("--dtype", default="auto")
114
+ parser.add_argument("--gpu-memory-utilization", type=float, default=0.9)
115
+ parser.add_argument("--max-model-len", type=int, default=None)
116
+ parser.add_argument("--trust-remote-code", action="store_true")
117
+ parser.add_argument("--min-judge-score", type=float, default=3.0)
118
+ parser.add_argument("--save-candidates", action="store_true", help="Store all candidates in report.")
119
+ parser.add_argument(
120
+ "--trajectory-state-max-chars",
121
+ type=int,
122
+ default=1200,
123
+ help="Max characters kept for each state in the compact trajectory context. Use -1 to disable truncation.",
124
+ )
125
+ parser.add_argument(
126
+ "--trajectory-action-max-chars",
127
+ type=int,
128
+ default=200,
129
+ help="Max characters kept for each action in the compact trajectory context. Use -1 to disable truncation.",
130
+ )
131
+ parser.add_argument(
132
+ "--selected-only",
133
+ action="store_true",
134
+ help="Write only rows whose source_id was selected by --limit-sources/--source-ids.",
135
+ )
136
+ parser.add_argument("--no-cache", action="store_true", help="Disable JSONL cache/resume.")
137
+ parser.add_argument("--dry-run", action="store_true", help="Do not load vLLM; create deterministic mock thinks.")
138
+ parser.add_argument("--indent", type=int, default=2, help="JSON output indent. Use -1 for compact.")
139
+ return parser.parse_args()
140
+
141
+
142
+ def load_json_list(path: Path) -> List[Dict[str, Any]]:
143
+ with path.open("r", encoding="utf-8") as f:
144
+ data = json.load(f)
145
+ if not isinstance(data, list):
146
+ raise ValueError(f"Expected JSON list at {path}, got {type(data).__name__}")
147
+ if not all(isinstance(row, dict) for row in data):
148
+ raise ValueError(f"Expected all rows to be objects in {path}")
149
+ return data
150
+
151
+
152
+ def dump_json(path: Path, data: Any, indent: int) -> None:
153
+ path.parent.mkdir(parents=True, exist_ok=True)
154
+ kwargs = {"ensure_ascii": False}
155
+ if indent >= 0:
156
+ kwargs["indent"] = indent
157
+ with path.open("w", encoding="utf-8") as f:
158
+ json.dump(data, f, **kwargs)
159
+
160
+
161
+ def extract_system_prefix(messages: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
162
+ out: List[Dict[str, Any]] = []
163
+ for msg in messages:
164
+ if msg.get("role") == "system":
165
+ out.append(copy.deepcopy(msg))
166
+ else:
167
+ break
168
+ return out
169
+
170
+
171
+ def collect_pairs(messages: Sequence[Dict[str, Any]], start_idx: int = 0) -> List[Tuple[Dict[str, Any], Dict[str, Any]]]:
172
+ pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
173
+ idx = start_idx
174
+ while idx < len(messages):
175
+ while idx < len(messages) and messages[idx].get("role") != "user":
176
+ idx += 1
177
+ if idx >= len(messages):
178
+ break
179
+ if idx + 1 < len(messages) and messages[idx + 1].get("role") == "assistant":
180
+ pairs.append((copy.deepcopy(messages[idx]), copy.deepcopy(messages[idx + 1])))
181
+ idx += 2
182
+ else:
183
+ idx += 1
184
+ return pairs
185
+
186
+
187
+ def to_int(value: Any, default: int = 0) -> int:
188
+ try:
189
+ return int(value)
190
+ except (TypeError, ValueError):
191
+ return default
192
+
193
+
194
+ def source_key(source_id: Any) -> str:
195
+ return str(source_id)
196
+
197
+
198
+ def group_rows(rows: Sequence[Dict[str, Any]]) -> Dict[Any, List[Dict[str, Any]]]:
199
+ groups: Dict[Any, List[Dict[str, Any]]] = {}
200
+ for idx, row in enumerate(rows):
201
+ meta = row.get("meta") or {}
202
+ source_id = meta.get("source_id", f"missing_source_{idx}")
203
+ groups.setdefault(source_id, []).append(row)
204
+ for items in groups.values():
205
+ items.sort(key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))
206
+ return groups
207
+
208
+
209
+ def select_full_row(source_id: Any, items: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
210
+ exact = [
211
+ row
212
+ for row in items
213
+ if to_int((row.get("meta") or {}).get("turns"), -1)
214
+ == to_int((row.get("meta") or {}).get("total_turns"), -2)
215
+ ]
216
+ if exact:
217
+ return exact[-1]
218
+ return max(items, key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))
219
+
220
+
221
+ def build_full_trajectories(rows: Sequence[Dict[str, Any]]) -> Dict[Any, FullTrajectory]:
222
+ groups = group_rows(rows)
223
+ full: Dict[Any, FullTrajectory] = {}
224
+ for source_id, items in groups.items():
225
+ row = select_full_row(source_id, items)
226
+ messages = row.get("messages") or []
227
+ if not isinstance(messages, list):
228
+ continue
229
+ sys_prefix = extract_system_prefix(messages)
230
+ pairs = collect_pairs(messages, start_idx=len(sys_prefix))
231
+ if not pairs:
232
+ continue
233
+ full[source_id] = FullTrajectory(
234
+ source_id=source_id,
235
+ sys_prefix=sys_prefix,
236
+ pairs=pairs,
237
+ meta=dict(row.get("meta") or {}),
238
+ )
239
+ return full
240
+
241
+
242
+ def extract_answer_block(text: str) -> str:
243
+ match = ANSWER_RE.search(text or "")
244
+ return match.group(0) if match is not None else ""
245
+
246
+
247
+ def clean_think(text: str) -> str:
248
+ text = (text or "").strip()
249
+ think_match = THINK_RE.search(text)
250
+ if think_match is not None:
251
+ text = think_match.group(1).strip()
252
+ text = re.split(r"<\s*/?\s*answer\s*>", text, flags=re.IGNORECASE)[0]
253
+ text = re.sub(r"</?think>", "", text, flags=re.IGNORECASE)
254
+ text = re.sub(r"\s+", " ", text).strip()
255
+ text = text.strip('` \t\n\r"')
256
+ return text
257
+
258
+
259
+ def make_response(think: str, answer_block: str) -> str:
260
+ return f"<think>{think.strip()}</think>{answer_block}"
261
+
262
+
263
+ def has_meta_reasoning(text: str) -> bool:
264
+ return META_REASONING_RE.search(text or "") is not None
265
+
266
+
267
+ def extract_answer_payload(text: str) -> str:
268
+ answer_block = extract_answer_block(text)
269
+ if not answer_block:
270
+ return (text or "").strip()
271
+ return re.sub(
272
+ r"^\s*<\s*answer\s*>|<\s*/\s*answer\s*>\s*$",
273
+ "",
274
+ answer_block,
275
+ flags=re.IGNORECASE | re.DOTALL,
276
+ ).strip()
277
+
278
+
279
+ def compact_for_trajectory(text: str, max_chars: int) -> str:
280
+ text = (text or "").strip()
281
+ text = re.sub(r"\n{3,}", "\n\n", text)
282
+ text = text.replace("```", "'''")
283
+ if max_chars >= 0 and len(text) > max_chars:
284
+ text = text[:max_chars].rstrip() + " ...[truncated]"
285
+ return text
286
+
287
+
288
+ def build_trajectory_context(traj: FullTrajectory, state_max_chars: int, action_max_chars: int) -> str:
289
+ chunks: List[str] = []
290
+ for idx, (user_msg, asst_msg) in enumerate(traj.pairs):
291
+ state = compact_for_trajectory(str(user_msg.get("content", "")), state_max_chars)
292
+ action = compact_for_trajectory(extract_answer_payload(str(asst_msg.get("content", ""))), action_max_chars)
293
+ chunks.append(f"(s{idx}: {state}, a{idx}: {action})")
294
+ return " -> ".join(chunks)
295
+
296
+
297
+ def iter_turns(full: Dict[Any, FullTrajectory], state_max_chars: int, action_max_chars: int) -> List[TurnExample]:
298
+ turns: List[TurnExample] = []
299
+ for source_id, traj in full.items():
300
+ total_turns = len(traj.pairs)
301
+ trajectory_context = build_trajectory_context(traj, state_max_chars, action_max_chars)
302
+ for i, (user_msg, asst_msg) in enumerate(traj.pairs):
303
+ answer_block = extract_answer_block(str(asst_msg.get("content", "")))
304
+ next_user = None
305
+ if i + 1 < total_turns:
306
+ next_user = str(traj.pairs[i + 1][0].get("content", ""))
307
+ turns.append(
308
+ TurnExample(
309
+ source_id=source_id,
310
+ turn_idx=i + 1,
311
+ total_turns=total_turns,
312
+ user_content=str(user_msg.get("content", "")),
313
+ assistant_content=str(asst_msg.get("content", "")),
314
+ answer_block=answer_block,
315
+ next_user_content=next_user,
316
+ trajectory_context=trajectory_context,
317
+ )
318
+ )
319
+ return turns
320
+
321
+
322
+ def build_generation_messages(example: TurnExample, version: str) -> List[Dict[str, str]]:
323
+ if version != "traj_sa":
324
+ raise ValueError(f"Unknown version for this script: {version}")
325
+ target_action = extract_answer_payload(example.assistant_content) or example.answer_block.strip()
326
+ system_parts = [
327
+ "You write faithful, concise first-person reasoning for your own next action.",
328
+ "You are given the full trajectory as compact ordered (state, action) tuples in the form (s0, a0) -> (s1, a1) -> ... .",
329
+ "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.",
330
+ "",
331
+ "Full compressed trajectory:",
332
+ "```text",
333
+ example.trajectory_context,
334
+ "```",
335
+ ]
336
+ parts = [
337
+ "You are the assistant acting in this environment at the current turn.",
338
+ "You have already decided which action to output; now write the private inner reasoning that naturally leads to that action.",
339
+ "Write from your own first-person decision-making perspective, as if you are solving the task, not evaluating another model or an expert.",
340
+ "Only output the inner text for <think>...</think>. Do not output <think>, </think>, <answer>, JSON, bullets, or any extra wrapper.",
341
+ "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'.",
342
+ "Do not change to a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.",
343
+ "Keep it concise: 1-3 English sentences with step-by-step reasoning grounded in the current state/action and the compressed trajectory context.",
344
+ "",
345
+ "Current observation/state s:",
346
+ "```text",
347
+ example.user_content.strip(),
348
+ "```",
349
+ "",
350
+ "Action a that your reasoning should lead to:",
351
+ "```text",
352
+ target_action,
353
+ "```",
354
+ ]
355
+ return [
356
+ {"role": "system", "content": "\n".join(system_parts)},
357
+ {"role": "user", "content": "\n".join(parts)},
358
+ ]
359
+
360
+
361
+ def build_judge_messages(example: TurnExample, version: str, candidates: Sequence[str]) -> List[Dict[str, str]]:
362
+ if version != "traj_sa":
363
+ raise ValueError(f"Unknown version for this script: {version}")
364
+ candidate_text = "\n".join(f"[{i + 1}] {cand}" for i, cand in enumerate(candidates))
365
+ target_action = extract_answer_payload(example.assistant_content) or example.answer_block.strip()
366
+ system_parts = [
367
+ "You are a strict factuality judge for reasoning traces.",
368
+ "You are given the full trajectory as compact ordered (state, action) tuples in the form (s0, a0) -> (s1, a1) -> ... .",
369
+ "Use it only to judge whether candidate reasoning is faithful to the current state/action and trajectory context.",
370
+ "",
371
+ "Full compressed trajectory:",
372
+ "```text",
373
+ example.trajectory_context,
374
+ "```",
375
+ ]
376
+ parts = [
377
+ "You are auditing candidate <think> texts for an SFT trajectory.",
378
+ "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.",
379
+ "Strongly penalize meta-reasoning that says or implies the action was given, fixed, known, demonstrated, provided, or chosen by an expert.",
380
+ "Also penalize unsupported factual claims, contradicted claims, changing the action, excessive certainty such as 'only'/'optimal' without clear support, verbosity, and format pollution.",
381
+ "Return strict JSON only, with no markdown.",
382
+ "",
383
+ "Current observation/state s:",
384
+ "```text",
385
+ example.user_content.strip(),
386
+ "```",
387
+ "",
388
+ "Target action a that the reasoning should lead to:",
389
+ "```text",
390
+ target_action,
391
+ "```",
392
+ "",
393
+ "Candidates:",
394
+ candidate_text,
395
+ "",
396
+ "Use this JSON schema:",
397
+ '{"best_index": 1, "scores": [{"index": 1, "score": 1, "unsupported_claims": 0, "contradictions": 0, "reason": "short reason"}], "selected_reason": "short reason", "low_quality": false}',
398
+ "Scores are from 1 to 5. Set low_quality=true if the best candidate is still weak or generic.",
399
+ ]
400
+ return [
401
+ {"role": "system", "content": "\n".join(system_parts)},
402
+ {"role": "user", "content": "\n".join(parts)},
403
+ ]
404
+
405
+
406
+ def render_prompt(tokenizer: Any, messages: List[Dict[str, str]]) -> str:
407
+ return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
408
+
409
+
410
+ def load_vllm_model(
411
+ model_path: str,
412
+ args: argparse.Namespace,
413
+ tensor_parallel_size: Optional[int] = None,
414
+ ) -> Tuple[Any, Any]:
415
+ try:
416
+ from transformers import AutoTokenizer
417
+ from vllm import LLM
418
+ except ImportError as exc:
419
+ raise RuntimeError("This script requires `vllm` and `transformers`.") from exc
420
+
421
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=bool(args.trust_remote_code))
422
+ llm_kwargs: Dict[str, Any] = {
423
+ "model": model_path,
424
+ "tensor_parallel_size": int(tensor_parallel_size or args.tensor_parallel_size),
425
+ "dtype": args.dtype,
426
+ "gpu_memory_utilization": float(args.gpu_memory_utilization),
427
+ "trust_remote_code": bool(args.trust_remote_code),
428
+ }
429
+ if args.max_model_len is not None:
430
+ llm_kwargs["max_model_len"] = int(args.max_model_len)
431
+ return LLM(**llm_kwargs), tokenizer
432
+
433
+
434
+ def make_sampling_params(args: argparse.Namespace, *, judge: bool = False) -> Any:
435
+ try:
436
+ from vllm import SamplingParams
437
+ except ImportError as exc:
438
+ raise RuntimeError("This script requires `vllm`.") from exc
439
+ if judge:
440
+ return SamplingParams(
441
+ temperature=float(args.judge_temperature),
442
+ top_p=1.0,
443
+ max_tokens=int(args.judge_max_tokens),
444
+ )
445
+ return SamplingParams(
446
+ n=int(args.n),
447
+ temperature=float(args.temperature),
448
+ top_p=float(args.top_p),
449
+ top_k=int(args.top_k),
450
+ max_tokens=int(args.max_tokens),
451
+ )
452
+
453
+
454
+ def chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]:
455
+ if size <= 0:
456
+ yield items
457
+ return
458
+ for start in range(0, len(items), size):
459
+ yield items[start : start + size]
460
+
461
+
462
+ def parse_judge_json(text: str) -> Dict[str, Any]:
463
+ text = (text or "").strip()
464
+ match = JSON_OBJ_RE.search(text)
465
+ if match is not None:
466
+ text = match.group(0)
467
+ try:
468
+ obj = json.loads(text)
469
+ if isinstance(obj, dict):
470
+ return obj
471
+ except json.JSONDecodeError:
472
+ pass
473
+ return {}
474
+
475
+
476
+ def selected_score(judge_obj: Dict[str, Any], best_index: int) -> float:
477
+ for item in judge_obj.get("scores") or []:
478
+ if isinstance(item, dict) and to_int(item.get("index"), -1) == best_index:
479
+ try:
480
+ return float(item.get("score", 0.0))
481
+ except (TypeError, ValueError):
482
+ return 0.0
483
+ return 0.0
484
+
485
+
486
+ def fallback_think(version: str) -> str:
487
+ if version == "sas":
488
+ return (
489
+ "I compare the current observation with the next-state feedback and choose the move "
490
+ "that is consistent with making progress under the task constraints."
491
+ )
492
+ return (
493
+ "I inspect the current observation and choose the move that best follows the task constraints "
494
+ "while aiming to make progress from this state."
495
+ )
496
+
497
+
498
+ def cache_key(version: str, source_id: Any, turn_idx: int) -> str:
499
+ return json.dumps(
500
+ {"version": version, "source_id": source_id, "turn_idx": turn_idx},
501
+ ensure_ascii=False,
502
+ sort_keys=True,
503
+ )
504
+
505
+
506
+ def load_cache(path: Path) -> Dict[str, Dict[str, Any]]:
507
+ cache: Dict[str, Dict[str, Any]] = {}
508
+ if not path.exists():
509
+ return cache
510
+ with path.open("r", encoding="utf-8") as f:
511
+ for line_no, line in enumerate(f, start=1):
512
+ line = line.strip()
513
+ if not line:
514
+ continue
515
+ try:
516
+ row = json.loads(line)
517
+ except json.JSONDecodeError:
518
+ print(f"Warning: skipped invalid cache line {path}:{line_no}")
519
+ continue
520
+ key = row.get("cache_key")
521
+ if isinstance(key, str):
522
+ cache[key] = row
523
+ return cache
524
+
525
+
526
+ def append_cache(path: Path, rows: Sequence[Dict[str, Any]]) -> None:
527
+ if not rows:
528
+ return
529
+ path.parent.mkdir(parents=True, exist_ok=True)
530
+ with path.open("a", encoding="utf-8") as f:
531
+ for row in rows:
532
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
533
+
534
+
535
+ def dry_candidates(example: TurnExample, version: str, n: int) -> List[str]:
536
+ base = "I inspect the visible state and the compressed trajectory context to reason step by step toward the next move."
537
+ return [f"{base} Candidate {i + 1}." for i in range(n)]
538
+
539
+
540
+ def synthesize_version(
541
+ *,
542
+ version: str,
543
+ turns: Sequence[TurnExample],
544
+ args: argparse.Namespace,
545
+ output_dir: Path,
546
+ output_prefix: str,
547
+ llm: Any,
548
+ tokenizer: Any,
549
+ judge_llm: Any,
550
+ judge_tokenizer: Any,
551
+ ) -> Dict[Tuple[Any, int], Dict[str, Any]]:
552
+ cache_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.cache.jsonl"
553
+ cache = {} if args.no_cache else load_cache(cache_path)
554
+ results: Dict[Tuple[Any, int], Dict[str, Any]] = {}
555
+ missing: List[TurnExample] = []
556
+ for ex in turns:
557
+ key = cache_key(version, ex.source_id, ex.turn_idx)
558
+ cached = cache.get(key)
559
+ if cached is not None and cached.get("selected_think"):
560
+ results[(ex.source_id, ex.turn_idx)] = cached
561
+ else:
562
+ missing.append(ex)
563
+
564
+ print(f"[{version}] turns={len(turns)} cached={len(results)} missing={len(missing)}")
565
+ gen_params = None if args.dry_run else make_sampling_params(args, judge=False)
566
+ judge_params = None if args.dry_run else make_sampling_params(args, judge=True)
567
+
568
+ for batch_no, batch in enumerate(chunks(missing, int(args.batch_size)), start=1):
569
+ batch = list(batch)
570
+ if args.dry_run:
571
+ all_candidates = [dry_candidates(ex, version, int(args.n)) for ex in batch]
572
+ else:
573
+ prompts = [render_prompt(tokenizer, build_generation_messages(ex, version)) for ex in batch]
574
+ outputs = llm.generate(prompts, sampling_params=gen_params)
575
+ all_candidates = []
576
+ for out in outputs:
577
+ raw_candidates = [clean_think(candidate.text) for candidate in out.outputs]
578
+ candidates = [cand for cand in raw_candidates if cand and not has_meta_reasoning(cand)]
579
+ if not candidates:
580
+ candidates = [cand for cand in raw_candidates if cand]
581
+ all_candidates.append(candidates)
582
+
583
+ judge_inputs: List[Tuple[TurnExample, List[str]]] = []
584
+ batch_rows: List[Dict[str, Any]] = []
585
+ for ex, candidates in zip(batch, all_candidates):
586
+ if not candidates:
587
+ selected = fallback_think(version)
588
+ row = {
589
+ "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
590
+ "version": version,
591
+ "source_id": ex.source_id,
592
+ "turn_idx": ex.turn_idx,
593
+ "total_turns": ex.total_turns,
594
+ "selected_think": selected,
595
+ "selected_index": None,
596
+ "score": 0.0,
597
+ "low_quality": True,
598
+ "meta_language": False,
599
+ "fallback": True,
600
+ "missing_next_state": False,
601
+ "selected_reason": "No valid generation candidates; used fallback.",
602
+ }
603
+ if args.save_candidates:
604
+ row["candidates"] = []
605
+ batch_rows.append(row)
606
+ else:
607
+ judge_inputs.append((ex, candidates))
608
+
609
+ judge_texts: List[str] = []
610
+ if judge_inputs:
611
+ if args.dry_run:
612
+ judge_texts = [
613
+ json.dumps(
614
+ {
615
+ "best_index": 1,
616
+ "scores": [
617
+ {
618
+ "index": 1,
619
+ "score": 3,
620
+ "unsupported_claims": 0,
621
+ "contradictions": 0,
622
+ "reason": "dry run",
623
+ }
624
+ ],
625
+ "selected_reason": "dry run",
626
+ "low_quality": False,
627
+ }
628
+ )
629
+ for _ in judge_inputs
630
+ ]
631
+ else:
632
+ judge_prompts = [
633
+ render_prompt(judge_tokenizer, build_judge_messages(ex, version, candidates))
634
+ for ex, candidates in judge_inputs
635
+ ]
636
+ judge_texts = []
637
+ for judge_chunk in chunks(judge_prompts, int(args.judge_batch_size)):
638
+ judge_outputs = judge_llm.generate(list(judge_chunk), sampling_params=judge_params)
639
+ judge_texts.extend(out.outputs[0].text for out in judge_outputs)
640
+
641
+ for (ex, candidates), judge_text in zip(judge_inputs, judge_texts):
642
+ judge_obj = parse_judge_json(judge_text)
643
+ best_index = to_int(judge_obj.get("best_index"), 1)
644
+ if best_index < 1 or best_index > len(candidates):
645
+ best_index = 1
646
+ selected = candidates[best_index - 1]
647
+ meta_language = has_meta_reasoning(selected)
648
+ score = selected_score(judge_obj, best_index)
649
+ if score <= 0.0:
650
+ score = 3.0 if selected else 0.0
651
+ low_quality = (
652
+ bool(judge_obj.get("low_quality", False))
653
+ or score < float(args.min_judge_score)
654
+ or meta_language
655
+ )
656
+ row = {
657
+ "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
658
+ "version": version,
659
+ "source_id": ex.source_id,
660
+ "turn_idx": ex.turn_idx,
661
+ "total_turns": ex.total_turns,
662
+ "selected_think": selected or fallback_think(version),
663
+ "selected_index": best_index,
664
+ "score": score,
665
+ "low_quality": low_quality,
666
+ "meta_language": meta_language,
667
+ "fallback": not bool(selected),
668
+ "missing_next_state": False,
669
+ "selected_reason": str(judge_obj.get("selected_reason", "")),
670
+ }
671
+ if args.save_candidates:
672
+ row["candidates"] = candidates
673
+ row["judge"] = judge_obj
674
+ row["judge_raw"] = judge_text
675
+ batch_rows.append(row)
676
+
677
+ append_cache(cache_path, batch_rows) if not args.no_cache else None
678
+ for row in batch_rows:
679
+ results[(row["source_id"], int(row["turn_idx"]))] = row
680
+ print(f"[{version}] batch {batch_no}: wrote {len(batch_rows)} turn results")
681
+ return results
682
+
683
+
684
+ def rebuild_rows(
685
+ rows: Sequence[Dict[str, Any]],
686
+ full: Dict[Any, FullTrajectory],
687
+ result_map: Dict[Tuple[Any, int], Dict[str, Any]],
688
+ ) -> List[Dict[str, Any]]:
689
+ rebuilt_by_source: Dict[Any, List[Tuple[Dict[str, Any], Dict[str, Any]]]] = {}
690
+ for source_id, traj in full.items():
691
+ new_pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
692
+ for idx, (user_msg, asst_msg) in enumerate(traj.pairs, start=1):
693
+ answer_block = extract_answer_block(str(asst_msg.get("content", "")))
694
+ result = result_map.get((source_id, idx))
695
+ think = str(result.get("selected_think", "")) if result else fallback_think("traj_sa")
696
+ new_user = copy.deepcopy(user_msg)
697
+ new_asst = copy.deepcopy(asst_msg)
698
+ if answer_block:
699
+ new_asst["content"] = make_response(think, answer_block)
700
+ else:
701
+ new_asst["content"] = str(asst_msg.get("content", ""))
702
+ new_pairs.append((new_user, new_asst))
703
+ rebuilt_by_source[source_id] = new_pairs
704
+
705
+ output: List[Dict[str, Any]] = []
706
+ for idx, row in enumerate(rows):
707
+ meta = row.get("meta") or {}
708
+ source_id = meta.get("source_id", f"missing_source_{idx}")
709
+ turns = to_int(meta.get("turns"), 0)
710
+ new_row = copy.deepcopy(row)
711
+ traj = full.get(source_id)
712
+ pairs = rebuilt_by_source.get(source_id)
713
+ if traj is None or pairs is None or turns <= 0:
714
+ output.append(new_row)
715
+ continue
716
+ turns = min(turns, len(pairs))
717
+ new_row["messages"] = copy.deepcopy(traj.sys_prefix) + [
718
+ copy.deepcopy(msg) for pair in pairs[:turns] for msg in pair
719
+ ]
720
+ output.append(new_row)
721
+ return output
722
+
723
+
724
+ def validate_answer_unchanged(original: Sequence[Dict[str, Any]], rebuilt: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
725
+ if len(original) != len(rebuilt):
726
+ raise ValueError(f"Row count changed: original={len(original)} rebuilt={len(rebuilt)}")
727
+ checked = 0
728
+ mismatches: List[Dict[str, Any]] = []
729
+ for row_idx, (old_row, new_row) in enumerate(zip(original, rebuilt)):
730
+ old_pairs = collect_pairs(old_row.get("messages") or [], start_idx=len(extract_system_prefix(old_row.get("messages") or [])))
731
+ new_pairs = collect_pairs(new_row.get("messages") or [], start_idx=len(extract_system_prefix(new_row.get("messages") or [])))
732
+ if len(old_pairs) != len(new_pairs):
733
+ mismatches.append({"row_idx": row_idx, "reason": "pair_count_changed"})
734
+ continue
735
+ for turn_idx, ((_, old_asst), (_, new_asst)) in enumerate(zip(old_pairs, new_pairs), start=1):
736
+ old_answer = extract_answer_block(str(old_asst.get("content", "")))
737
+ new_answer = extract_answer_block(str(new_asst.get("content", "")))
738
+ checked += 1
739
+ if old_answer != new_answer:
740
+ mismatches.append(
741
+ {
742
+ "row_idx": row_idx,
743
+ "turn_idx": turn_idx,
744
+ "old_answer": old_answer,
745
+ "new_answer": new_answer,
746
+ }
747
+ )
748
+ if len(mismatches) >= 20:
749
+ break
750
+ if len(mismatches) >= 20:
751
+ break
752
+ if mismatches:
753
+ raise ValueError(f"Answer validation failed, examples: {mismatches[:3]}")
754
+ return {"checked_assistant_messages": checked, "answer_mismatches": 0}
755
+
756
+
757
+ def filter_full_by_args(full: Dict[Any, FullTrajectory], args: argparse.Namespace) -> Dict[Any, FullTrajectory]:
758
+ selected = dict(full)
759
+ if args.source_ids.strip():
760
+ allow = {item.strip() for item in args.source_ids.split(",") if item.strip()}
761
+ selected = {sid: traj for sid, traj in selected.items() if source_key(sid) in allow}
762
+ if args.limit_sources is not None:
763
+ limited: Dict[Any, FullTrajectory] = {}
764
+ for sid in list(selected.keys())[: int(args.limit_sources)]:
765
+ limited[sid] = selected[sid]
766
+ selected = limited
767
+ return selected
768
+
769
+
770
+ def report_from_results(
771
+ *,
772
+ version: str,
773
+ result_map: Dict[Tuple[Any, int], Dict[str, Any]],
774
+ validation: Dict[str, Any],
775
+ args: argparse.Namespace,
776
+ ) -> Dict[str, Any]:
777
+ values = list(result_map.values())
778
+ low_quality = sum(1 for row in values if row.get("low_quality"))
779
+ fallback = sum(1 for row in values if row.get("fallback"))
780
+ meta_language = sum(1 for row in values if row.get("meta_language"))
781
+ missing_next = sum(1 for row in values if row.get("missing_next_state"))
782
+ scores = [float(row.get("score", 0.0)) for row in values]
783
+ summary = {
784
+ "version": version,
785
+ "n": int(args.n),
786
+ "turn_results": len(values),
787
+ "low_quality": low_quality,
788
+ "fallback": fallback,
789
+ "meta_language": meta_language,
790
+ "missing_next_state": missing_next,
791
+ "avg_score": sum(scores) / len(scores) if scores else 0.0,
792
+ "min_score": min(scores) if scores else 0.0,
793
+ "max_score": max(scores) if scores else 0.0,
794
+ **validation,
795
+ }
796
+ per_turn: List[Dict[str, Any]] = []
797
+ for row in values:
798
+ item = {
799
+ "source_id": row.get("source_id"),
800
+ "turn_idx": row.get("turn_idx"),
801
+ "total_turns": row.get("total_turns"),
802
+ "selected_index": row.get("selected_index"),
803
+ "score": row.get("score"),
804
+ "low_quality": row.get("low_quality"),
805
+ "fallback": row.get("fallback"),
806
+ "meta_language": row.get("meta_language", False),
807
+ "missing_next_state": row.get("missing_next_state"),
808
+ "selected_reason": row.get("selected_reason", ""),
809
+ }
810
+ if args.save_candidates:
811
+ item["selected_think"] = row.get("selected_think")
812
+ item["candidates"] = row.get("candidates", [])
813
+ item["judge"] = row.get("judge", {})
814
+ per_turn.append(item)
815
+ return {"summary": summary, "per_turn": per_turn}
816
+
817
+
818
+ def main() -> None:
819
+ args = parse_args()
820
+ versions = [v.strip() for v in args.versions.split(",") if v.strip()]
821
+ if not versions or any(v != "traj_sa" for v in versions):
822
+ raise ValueError("--versions must contain only traj_sa for this script")
823
+ if not args.dry_run and not args.model:
824
+ raise ValueError("--model is required unless --dry-run is set")
825
+
826
+ input_path = args.input.expanduser().resolve()
827
+ output_dir = (args.output_dir or input_path.parent).expanduser().resolve()
828
+ output_prefix = args.output_prefix or input_path.stem
829
+
830
+ print(f"Loading input: {input_path}")
831
+ rows = load_json_list(input_path)
832
+ full_all = build_full_trajectories(rows)
833
+ full_selected = filter_full_by_args(full_all, args)
834
+ if not full_selected:
835
+ raise ValueError("No usable trajectories selected.")
836
+ turns = iter_turns(
837
+ full_selected,
838
+ state_max_chars=int(args.trajectory_state_max_chars),
839
+ action_max_chars=int(args.trajectory_action_max_chars),
840
+ )
841
+ print(f"Rows={len(rows)} sources={len(full_all)} selected_sources={len(full_selected)} selected_turns={len(turns)}")
842
+
843
+ llm = tokenizer = judge_llm = judge_tokenizer = None
844
+ if not args.dry_run:
845
+ llm, tokenizer = load_vllm_model(args.model, args, tensor_parallel_size=args.tensor_parallel_size)
846
+ judge_model = args.judge_model or args.model
847
+ if judge_model == args.model:
848
+ judge_llm, judge_tokenizer = llm, tokenizer
849
+ else:
850
+ judge_tp = args.judge_tensor_parallel_size or args.tensor_parallel_size
851
+ judge_llm, judge_tokenizer = load_vllm_model(judge_model, args, tensor_parallel_size=judge_tp)
852
+
853
+ for version in versions:
854
+ result_map = synthesize_version(
855
+ version=version,
856
+ turns=turns,
857
+ args=args,
858
+ output_dir=output_dir,
859
+ output_prefix=output_prefix,
860
+ llm=llm,
861
+ tokenizer=tokenizer,
862
+ judge_llm=judge_llm,
863
+ judge_tokenizer=judge_tokenizer,
864
+ )
865
+ rows_for_output = [
866
+ row
867
+ for idx, row in enumerate(rows)
868
+ if not args.selected_only
869
+ or (row.get("meta") or {}).get("source_id", f"missing_source_{idx}") in full_selected
870
+ ]
871
+ rebuilt = rebuild_rows(rows_for_output, full_selected, result_map)
872
+ validation = validate_answer_unchanged(rows_for_output, rebuilt)
873
+ out_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.json"
874
+ report_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.report.json"
875
+ dump_json(out_path, rebuilt, indent=int(args.indent))
876
+ report = report_from_results(version=version, result_map=result_map, validation=validation, args=args)
877
+ dump_json(report_path, report, indent=2)
878
+ print(f"[{version}] wrote SFT: {out_path}")
879
+ print(f"[{version}] wrote report: {report_path}")
880
+ print(f"[{version}] summary: {json.dumps(report['summary'], ensure_ascii=False)}")
881
+
882
+
883
+ if __name__ == "__main__":
884
+ main()
scripts/synthesize_think_bon_v2.py ADDED
@@ -0,0 +1,854 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Synthesize <think> traces for SFT singleturn trajectories with BoN + judge.
3
+
4
+ This script is intentionally environment-agnostic. It assumes a JSON list of rows
5
+ with the common RAGEN SFT shape:
6
+
7
+ {"messages": [{"role": "system"}, {"role": "user"}, {"role": "assistant"}, ...],
8
+ "meta": {"source_id": ..., "turns": ..., "total_turns": ...}}
9
+
10
+ For each source_id, the complete trajectory row is selected, one reasoning trace
11
+ is synthesized per turn, and the selected traces are written back to every
12
+ cumulative singleturn prefix while keeping every original <answer>...</answer>
13
+ block exactly unchanged.
14
+
15
+
16
+ python3 /mnt/general/wanghy/RAGEN/scripts/synthesize_think_bon_v2.py \
17
+ --input /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/step_999424_sft_singleturn_nohint.json \
18
+ --output-dir /mnt/general/wanghy/RAGEN/runs/Sudoku__ppo_sudoku_actionmask__4x4/sft/ \
19
+ --output-prefix step_999424_sft_singleturn_withthink \
20
+ --versions sa,sas \
21
+ --model /mnt/general/share/model/Qwen/Qwen2-72B-Instruct \
22
+ --tensor-parallel-size 4 \
23
+ --n 8 \
24
+ --batch-size 32 \
25
+ --judge-batch-size 32 \
26
+ --limit-sources 50
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import copy
33
+ import json
34
+ import re
35
+ from dataclasses import dataclass
36
+ from pathlib import Path
37
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
38
+
39
+
40
+ ANSWER_RE = re.compile(r"<answer>.*?</answer>", re.IGNORECASE | re.DOTALL)
41
+ THINK_RE = re.compile(r"<think>(.*?)</think>", re.IGNORECASE | re.DOTALL)
42
+ JSON_OBJ_RE = re.compile(r"\{.*\}", re.DOTALL)
43
+ META_REASONING_RE = re.compile(
44
+ r"\b("
45
+ r"expert action|fixed action|given action|provided action|target action|"
46
+ r"demonstrated action|demonstrated answer|known action|chosen by (?:the )?expert|"
47
+ r"the action (?:was|is) (?:given|fixed|provided|known)"
48
+ r")\b",
49
+ re.IGNORECASE,
50
+ )
51
+
52
+
53
+ @dataclass
54
+ class TurnExample:
55
+ source_id: Any
56
+ turn_idx: int
57
+ total_turns: int
58
+ user_content: str
59
+ assistant_content: str
60
+ answer_block: str
61
+ next_user_content: Optional[str]
62
+
63
+
64
+ @dataclass
65
+ class FullTrajectory:
66
+ source_id: Any
67
+ sys_prefix: List[Dict[str, Any]]
68
+ pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]]
69
+ meta: Dict[str, Any]
70
+
71
+
72
+ def parse_args() -> argparse.Namespace:
73
+ parser = argparse.ArgumentParser(
74
+ description="Synthesize first-person target-action thinking traces with per-turn BoN and LLM judge."
75
+ )
76
+ parser.add_argument("--input", "-i", type=Path, required=True, help="Input SFT JSON list.")
77
+ parser.add_argument(
78
+ "--output-dir",
79
+ type=Path,
80
+ default=None,
81
+ help="Directory for output files. Defaults to input parent.",
82
+ )
83
+ parser.add_argument(
84
+ "--output-prefix",
85
+ default=None,
86
+ help="Output filename prefix. Defaults to input stem.",
87
+ )
88
+ parser.add_argument(
89
+ "--versions",
90
+ default="sa,sas",
91
+ help="Comma-separated versions: sa and/or sas. sa uses s,a; sas uses s,a,s'.",
92
+ )
93
+ parser.add_argument("--model", default=None, help="HF model path for tokenizer + vLLM.")
94
+ parser.add_argument("--judge-model", default=None, help="Optional separate judge model path.")
95
+ parser.add_argument("--n", type=int, default=8, help="BoN candidates per turn.")
96
+ parser.add_argument(
97
+ "--mode",
98
+ default="per_turn",
99
+ choices=["per_turn"],
100
+ help="BoN mode. Currently only independent per-turn BoN is implemented.",
101
+ )
102
+ parser.add_argument("--limit-sources", type=int, default=None, help="Pilot limit by source_id count.")
103
+ parser.add_argument("--source-ids", default="", help="Optional comma-separated source_id allowlist.")
104
+ parser.add_argument("--batch-size", type=int, default=64, help="Prompt batch size for generation.")
105
+ parser.add_argument("--judge-batch-size", type=int, default=64, help="Prompt batch size for judge.")
106
+ parser.add_argument("--temperature", type=float, default=0.7)
107
+ parser.add_argument("--top-p", type=float, default=0.95)
108
+ parser.add_argument("--top-k", type=int, default=-1)
109
+ parser.add_argument("--max-tokens", type=int, default=160, help="Max tokens for think generation.")
110
+ parser.add_argument("--judge-temperature", type=float, default=0.0)
111
+ parser.add_argument("--judge-max-tokens", type=int, default=768)
112
+ parser.add_argument("--tensor-parallel-size", type=int, default=1)
113
+ parser.add_argument("--judge-tensor-parallel-size", type=int, default=None)
114
+ parser.add_argument("--dtype", default="auto")
115
+ parser.add_argument("--gpu-memory-utilization", type=float, default=0.9)
116
+ parser.add_argument("--max-model-len", type=int, default=None)
117
+ parser.add_argument("--trust-remote-code", action="store_true")
118
+ parser.add_argument("--min-judge-score", type=float, default=3.0)
119
+ parser.add_argument("--save-candidates", action="store_true", help="Store all candidates in report.")
120
+ parser.add_argument(
121
+ "--selected-only",
122
+ action="store_true",
123
+ help="Write only rows whose source_id was selected by --limit-sources/--source-ids.",
124
+ )
125
+ parser.add_argument("--no-cache", action="store_true", help="Disable JSONL cache/resume.")
126
+ parser.add_argument("--dry-run", action="store_true", help="Do not load vLLM; create deterministic mock thinks.")
127
+ parser.add_argument("--indent", type=int, default=2, help="JSON output indent. Use -1 for compact.")
128
+ return parser.parse_args()
129
+
130
+
131
+ def load_json_list(path: Path) -> List[Dict[str, Any]]:
132
+ with path.open("r", encoding="utf-8") as f:
133
+ data = json.load(f)
134
+ if not isinstance(data, list):
135
+ raise ValueError(f"Expected JSON list at {path}, got {type(data).__name__}")
136
+ if not all(isinstance(row, dict) for row in data):
137
+ raise ValueError(f"Expected all rows to be objects in {path}")
138
+ return data
139
+
140
+
141
+ def dump_json(path: Path, data: Any, indent: int) -> None:
142
+ path.parent.mkdir(parents=True, exist_ok=True)
143
+ kwargs = {"ensure_ascii": False}
144
+ if indent >= 0:
145
+ kwargs["indent"] = indent
146
+ with path.open("w", encoding="utf-8") as f:
147
+ json.dump(data, f, **kwargs)
148
+
149
+
150
+ def extract_system_prefix(messages: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]:
151
+ out: List[Dict[str, Any]] = []
152
+ for msg in messages:
153
+ if msg.get("role") == "system":
154
+ out.append(copy.deepcopy(msg))
155
+ else:
156
+ break
157
+ return out
158
+
159
+
160
+ def collect_pairs(messages: Sequence[Dict[str, Any]], start_idx: int = 0) -> List[Tuple[Dict[str, Any], Dict[str, Any]]]:
161
+ pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
162
+ idx = start_idx
163
+ while idx < len(messages):
164
+ while idx < len(messages) and messages[idx].get("role") != "user":
165
+ idx += 1
166
+ if idx >= len(messages):
167
+ break
168
+ if idx + 1 < len(messages) and messages[idx + 1].get("role") == "assistant":
169
+ pairs.append((copy.deepcopy(messages[idx]), copy.deepcopy(messages[idx + 1])))
170
+ idx += 2
171
+ else:
172
+ idx += 1
173
+ return pairs
174
+
175
+
176
+ def to_int(value: Any, default: int = 0) -> int:
177
+ try:
178
+ return int(value)
179
+ except (TypeError, ValueError):
180
+ return default
181
+
182
+
183
+ def source_key(source_id: Any) -> str:
184
+ return str(source_id)
185
+
186
+
187
+ def group_rows(rows: Sequence[Dict[str, Any]]) -> Dict[Any, List[Dict[str, Any]]]:
188
+ groups: Dict[Any, List[Dict[str, Any]]] = {}
189
+ for idx, row in enumerate(rows):
190
+ meta = row.get("meta") or {}
191
+ source_id = meta.get("source_id", f"missing_source_{idx}")
192
+ groups.setdefault(source_id, []).append(row)
193
+ for items in groups.values():
194
+ items.sort(key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))
195
+ return groups
196
+
197
+
198
+ def select_full_row(source_id: Any, items: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
199
+ exact = [
200
+ row
201
+ for row in items
202
+ if to_int((row.get("meta") or {}).get("turns"), -1)
203
+ == to_int((row.get("meta") or {}).get("total_turns"), -2)
204
+ ]
205
+ if exact:
206
+ return exact[-1]
207
+ return max(items, key=lambda r: to_int((r.get("meta") or {}).get("turns"), 0))
208
+
209
+
210
+ def build_full_trajectories(rows: Sequence[Dict[str, Any]]) -> Dict[Any, FullTrajectory]:
211
+ groups = group_rows(rows)
212
+ full: Dict[Any, FullTrajectory] = {}
213
+ for source_id, items in groups.items():
214
+ row = select_full_row(source_id, items)
215
+ messages = row.get("messages") or []
216
+ if not isinstance(messages, list):
217
+ continue
218
+ sys_prefix = extract_system_prefix(messages)
219
+ pairs = collect_pairs(messages, start_idx=len(sys_prefix))
220
+ if not pairs:
221
+ continue
222
+ full[source_id] = FullTrajectory(
223
+ source_id=source_id,
224
+ sys_prefix=sys_prefix,
225
+ pairs=pairs,
226
+ meta=dict(row.get("meta") or {}),
227
+ )
228
+ return full
229
+
230
+
231
+ def extract_answer_block(text: str) -> str:
232
+ match = ANSWER_RE.search(text or "")
233
+ return match.group(0) if match is not None else ""
234
+
235
+
236
+ def clean_think(text: str) -> str:
237
+ text = (text or "").strip()
238
+ think_match = THINK_RE.search(text)
239
+ if think_match is not None:
240
+ text = think_match.group(1).strip()
241
+ text = re.split(r"<\s*/?\s*answer\s*>", text, flags=re.IGNORECASE)[0]
242
+ text = re.sub(r"</?think>", "", text, flags=re.IGNORECASE)
243
+ text = re.sub(r"\s+", " ", text).strip()
244
+ text = text.strip('` \t\n\r"')
245
+ return text
246
+
247
+
248
+ def make_response(think: str, answer_block: str) -> str:
249
+ return f"<think>{think.strip()}</think>{answer_block}"
250
+
251
+
252
+ def has_meta_reasoning(text: str) -> bool:
253
+ return META_REASONING_RE.search(text or "") is not None
254
+
255
+
256
+ def iter_turns(full: Dict[Any, FullTrajectory]) -> List[TurnExample]:
257
+ turns: List[TurnExample] = []
258
+ for source_id, traj in full.items():
259
+ total_turns = len(traj.pairs)
260
+ for i, (user_msg, asst_msg) in enumerate(traj.pairs):
261
+ answer_block = extract_answer_block(str(asst_msg.get("content", "")))
262
+ next_user = None
263
+ if i + 1 < total_turns:
264
+ next_user = str(traj.pairs[i + 1][0].get("content", ""))
265
+ turns.append(
266
+ TurnExample(
267
+ source_id=source_id,
268
+ turn_idx=i + 1,
269
+ total_turns=total_turns,
270
+ user_content=str(user_msg.get("content", "")),
271
+ assistant_content=str(asst_msg.get("content", "")),
272
+ answer_block=answer_block,
273
+ next_user_content=next_user,
274
+ )
275
+ )
276
+ return turns
277
+
278
+
279
+ def build_generation_messages(example: TurnExample, version: str) -> List[Dict[str, str]]:
280
+ if version not in {"sa", "sas"}:
281
+ raise ValueError(f"Unknown version: {version}")
282
+ sas_available = version == "sas" and example.next_user_content is not None
283
+ parts = [
284
+ "You are the assistant acting in this environment at the current turn.",
285
+ "You have already decided which action to output; now write the private inner reasoning that naturally leads to that action.",
286
+ "Write from your own first-person decision-making perspective, as if you are solving the task, not evaluating another model or an expert.",
287
+ "Only output the inner text for <think>...</think>. Do not output <think>, </think>, <answer>, JSON, bullets, or any extra wrapper.",
288
+ "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'.",
289
+ "Do not change to a different action. Do not invent hidden facts, future rewards, or unsupported optimality claims.",
290
+ "Keep it concise: 1-3 English sentences with step-by-step reasoning grounded in the visible context.",
291
+ "",
292
+ "Current observation/state s:",
293
+ "```text",
294
+ example.user_content.strip(),
295
+ "```",
296
+ "",
297
+ "Action that your reasoning should lead to:",
298
+ "```text",
299
+ example.answer_block.strip() or example.assistant_content.strip(),
300
+ "```",
301
+ ]
302
+ if sas_available:
303
+ parts.extend(
304
+ [
305
+ "",
306
+ "Observed next state/feedback s' after taking this action:",
307
+ "```text",
308
+ str(example.next_user_content).strip(),
309
+ "```",
310
+ "Use s' only to ground the explanation of the observed transition; do not switch to another action.",
311
+ ]
312
+ )
313
+ elif version == "sas":
314
+ parts.extend(
315
+ [
316
+ "",
317
+ "No next state s' is available for this final turn, so explain using only s and a.",
318
+ ]
319
+ )
320
+ return [
321
+ {
322
+ "role": "system",
323
+ "content": "You write faithful, concise first-person reasoning for your own next action.",
324
+ },
325
+ {"role": "user", "content": "\n".join(parts)},
326
+ ]
327
+
328
+
329
+ def build_judge_messages(example: TurnExample, version: str, candidates: Sequence[str]) -> List[Dict[str, str]]:
330
+ candidate_text = "\n".join(f"[{i + 1}] {cand}" for i, cand in enumerate(candidates))
331
+ sas_available = version == "sas" and example.next_user_content is not None
332
+ parts = [
333
+ "You are auditing candidate <think> texts for an SFT trajectory.",
334
+ "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.",
335
+ "Strongly penalize meta-reasoning that says or implies the action was given, fixed, known, demonstrated, provided, or chosen by an expert.",
336
+ "Also penalize unsupported factual claims, contradicted claims, changing the action, excessive certainty such as 'only'/'optimal' without clear support, verbosity, and format pollution.",
337
+ "Return strict JSON only, with no markdown.",
338
+ "",
339
+ "Current observation/state s:",
340
+ "```text",
341
+ example.user_content.strip(),
342
+ "```",
343
+ "",
344
+ "Target action a that the reasoning should lead to:",
345
+ "```text",
346
+ example.answer_block.strip() or example.assistant_content.strip(),
347
+ "```",
348
+ ]
349
+ if sas_available:
350
+ parts.extend(
351
+ [
352
+ "",
353
+ "Observed next state/feedback s' after taking action a:",
354
+ "```text",
355
+ str(example.next_user_content).strip(),
356
+ "```",
357
+ ]
358
+ )
359
+ elif version == "sas":
360
+ parts.append("\nNo next state s' is available for this final turn.")
361
+ parts.extend(
362
+ [
363
+ "",
364
+ "Candidates:",
365
+ candidate_text,
366
+ "",
367
+ "Use this JSON schema:",
368
+ '{"best_index": 1, "scores": [{"index": 1, "score": 1, "unsupported_claims": 0, "contradictions": 0, "reason": "short reason"}], "selected_reason": "short reason", "low_quality": false}',
369
+ "Scores are from 1 to 5. Set low_quality=true if the best candidate is still weak or generic.",
370
+ ]
371
+ )
372
+ return [
373
+ {"role": "system", "content": "You are a strict factuality judge for reasoning traces."},
374
+ {"role": "user", "content": "\n".join(parts)},
375
+ ]
376
+
377
+
378
+ def render_prompt(tokenizer: Any, messages: List[Dict[str, str]]) -> str:
379
+ return tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
380
+
381
+
382
+ def load_vllm_model(
383
+ model_path: str,
384
+ args: argparse.Namespace,
385
+ tensor_parallel_size: Optional[int] = None,
386
+ ) -> Tuple[Any, Any]:
387
+ try:
388
+ from transformers import AutoTokenizer
389
+ from vllm import LLM
390
+ except ImportError as exc:
391
+ raise RuntimeError("This script requires `vllm` and `transformers`.") from exc
392
+
393
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=bool(args.trust_remote_code))
394
+ llm_kwargs: Dict[str, Any] = {
395
+ "model": model_path,
396
+ "tensor_parallel_size": int(tensor_parallel_size or args.tensor_parallel_size),
397
+ "dtype": args.dtype,
398
+ "gpu_memory_utilization": float(args.gpu_memory_utilization),
399
+ "trust_remote_code": bool(args.trust_remote_code),
400
+ }
401
+ if args.max_model_len is not None:
402
+ llm_kwargs["max_model_len"] = int(args.max_model_len)
403
+ return LLM(**llm_kwargs), tokenizer
404
+
405
+
406
+ def make_sampling_params(args: argparse.Namespace, *, judge: bool = False) -> Any:
407
+ try:
408
+ from vllm import SamplingParams
409
+ except ImportError as exc:
410
+ raise RuntimeError("This script requires `vllm`.") from exc
411
+ if judge:
412
+ return SamplingParams(
413
+ temperature=float(args.judge_temperature),
414
+ top_p=1.0,
415
+ max_tokens=int(args.judge_max_tokens),
416
+ )
417
+ return SamplingParams(
418
+ n=int(args.n),
419
+ temperature=float(args.temperature),
420
+ top_p=float(args.top_p),
421
+ top_k=int(args.top_k),
422
+ max_tokens=int(args.max_tokens),
423
+ )
424
+
425
+
426
+ def chunks(items: Sequence[Any], size: int) -> Iterable[Sequence[Any]]:
427
+ if size <= 0:
428
+ yield items
429
+ return
430
+ for start in range(0, len(items), size):
431
+ yield items[start : start + size]
432
+
433
+
434
+ def parse_judge_json(text: str) -> Dict[str, Any]:
435
+ text = (text or "").strip()
436
+ match = JSON_OBJ_RE.search(text)
437
+ if match is not None:
438
+ text = match.group(0)
439
+ try:
440
+ obj = json.loads(text)
441
+ if isinstance(obj, dict):
442
+ return obj
443
+ except json.JSONDecodeError:
444
+ pass
445
+ return {}
446
+
447
+
448
+ def selected_score(judge_obj: Dict[str, Any], best_index: int) -> float:
449
+ for item in judge_obj.get("scores") or []:
450
+ if isinstance(item, dict) and to_int(item.get("index"), -1) == best_index:
451
+ try:
452
+ return float(item.get("score", 0.0))
453
+ except (TypeError, ValueError):
454
+ return 0.0
455
+ return 0.0
456
+
457
+
458
+ def fallback_think(version: str) -> str:
459
+ if version == "sas":
460
+ return (
461
+ "I compare the current observation with the next-state feedback and choose the move "
462
+ "that is consistent with making progress under the task constraints."
463
+ )
464
+ return (
465
+ "I inspect the current observation and choose the move that best follows the task constraints "
466
+ "while aiming to make progress from this state."
467
+ )
468
+
469
+
470
+ def cache_key(version: str, source_id: Any, turn_idx: int) -> str:
471
+ return json.dumps(
472
+ {"version": version, "source_id": source_id, "turn_idx": turn_idx},
473
+ ensure_ascii=False,
474
+ sort_keys=True,
475
+ )
476
+
477
+
478
+ def load_cache(path: Path) -> Dict[str, Dict[str, Any]]:
479
+ cache: Dict[str, Dict[str, Any]] = {}
480
+ if not path.exists():
481
+ return cache
482
+ with path.open("r", encoding="utf-8") as f:
483
+ for line_no, line in enumerate(f, start=1):
484
+ line = line.strip()
485
+ if not line:
486
+ continue
487
+ try:
488
+ row = json.loads(line)
489
+ except json.JSONDecodeError:
490
+ print(f"Warning: skipped invalid cache line {path}:{line_no}")
491
+ continue
492
+ key = row.get("cache_key")
493
+ if isinstance(key, str):
494
+ cache[key] = row
495
+ return cache
496
+
497
+
498
+ def append_cache(path: Path, rows: Sequence[Dict[str, Any]]) -> None:
499
+ if not rows:
500
+ return
501
+ path.parent.mkdir(parents=True, exist_ok=True)
502
+ with path.open("a", encoding="utf-8") as f:
503
+ for row in rows:
504
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
505
+
506
+
507
+ def dry_candidates(example: TurnExample, version: str, n: int) -> List[str]:
508
+ base = "I inspect the visible state and reason step by step toward the next move."
509
+ if version == "sas" and example.next_user_content is not None:
510
+ base = "I inspect the visible state and the observed next-state feedback to reason toward the next move."
511
+ return [f"{base} Candidate {i + 1}." for i in range(n)]
512
+
513
+
514
+ def synthesize_version(
515
+ *,
516
+ version: str,
517
+ turns: Sequence[TurnExample],
518
+ args: argparse.Namespace,
519
+ output_dir: Path,
520
+ output_prefix: str,
521
+ llm: Any,
522
+ tokenizer: Any,
523
+ judge_llm: Any,
524
+ judge_tokenizer: Any,
525
+ ) -> Dict[Tuple[Any, int], Dict[str, Any]]:
526
+ cache_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.cache.jsonl"
527
+ cache = {} if args.no_cache else load_cache(cache_path)
528
+ results: Dict[Tuple[Any, int], Dict[str, Any]] = {}
529
+ missing: List[TurnExample] = []
530
+ for ex in turns:
531
+ key = cache_key(version, ex.source_id, ex.turn_idx)
532
+ cached = cache.get(key)
533
+ if cached is not None and cached.get("selected_think"):
534
+ results[(ex.source_id, ex.turn_idx)] = cached
535
+ else:
536
+ missing.append(ex)
537
+
538
+ print(f"[{version}] turns={len(turns)} cached={len(results)} missing={len(missing)}")
539
+ gen_params = None if args.dry_run else make_sampling_params(args, judge=False)
540
+ judge_params = None if args.dry_run else make_sampling_params(args, judge=True)
541
+
542
+ for batch_no, batch in enumerate(chunks(missing, int(args.batch_size)), start=1):
543
+ batch = list(batch)
544
+ if args.dry_run:
545
+ all_candidates = [dry_candidates(ex, version, int(args.n)) for ex in batch]
546
+ else:
547
+ prompts = [render_prompt(tokenizer, build_generation_messages(ex, version)) for ex in batch]
548
+ outputs = llm.generate(prompts, sampling_params=gen_params)
549
+ all_candidates = []
550
+ for out in outputs:
551
+ raw_candidates = [clean_think(candidate.text) for candidate in out.outputs]
552
+ candidates = [cand for cand in raw_candidates if cand and not has_meta_reasoning(cand)]
553
+ if not candidates:
554
+ candidates = [cand for cand in raw_candidates if cand]
555
+ all_candidates.append(candidates)
556
+
557
+ judge_inputs: List[Tuple[TurnExample, List[str]]] = []
558
+ batch_rows: List[Dict[str, Any]] = []
559
+ for ex, candidates in zip(batch, all_candidates):
560
+ if not candidates:
561
+ selected = fallback_think(version)
562
+ row = {
563
+ "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
564
+ "version": version,
565
+ "source_id": ex.source_id,
566
+ "turn_idx": ex.turn_idx,
567
+ "total_turns": ex.total_turns,
568
+ "selected_think": selected,
569
+ "selected_index": None,
570
+ "score": 0.0,
571
+ "low_quality": True,
572
+ "meta_language": False,
573
+ "fallback": True,
574
+ "missing_next_state": version == "sas" and ex.next_user_content is None,
575
+ "selected_reason": "No valid generation candidates; used fallback.",
576
+ }
577
+ if args.save_candidates:
578
+ row["candidates"] = []
579
+ batch_rows.append(row)
580
+ else:
581
+ judge_inputs.append((ex, candidates))
582
+
583
+ judge_texts: List[str] = []
584
+ if judge_inputs:
585
+ if args.dry_run:
586
+ judge_texts = [
587
+ json.dumps(
588
+ {
589
+ "best_index": 1,
590
+ "scores": [
591
+ {
592
+ "index": 1,
593
+ "score": 3,
594
+ "unsupported_claims": 0,
595
+ "contradictions": 0,
596
+ "reason": "dry run",
597
+ }
598
+ ],
599
+ "selected_reason": "dry run",
600
+ "low_quality": False,
601
+ }
602
+ )
603
+ for _ in judge_inputs
604
+ ]
605
+ else:
606
+ judge_prompts = [
607
+ render_prompt(judge_tokenizer, build_judge_messages(ex, version, candidates))
608
+ for ex, candidates in judge_inputs
609
+ ]
610
+ judge_texts = []
611
+ for judge_chunk in chunks(judge_prompts, int(args.judge_batch_size)):
612
+ judge_outputs = judge_llm.generate(list(judge_chunk), sampling_params=judge_params)
613
+ judge_texts.extend(out.outputs[0].text for out in judge_outputs)
614
+
615
+ for (ex, candidates), judge_text in zip(judge_inputs, judge_texts):
616
+ judge_obj = parse_judge_json(judge_text)
617
+ best_index = to_int(judge_obj.get("best_index"), 1)
618
+ if best_index < 1 or best_index > len(candidates):
619
+ best_index = 1
620
+ selected = candidates[best_index - 1]
621
+ meta_language = has_meta_reasoning(selected)
622
+ score = selected_score(judge_obj, best_index)
623
+ if score <= 0.0:
624
+ score = 3.0 if selected else 0.0
625
+ low_quality = (
626
+ bool(judge_obj.get("low_quality", False))
627
+ or score < float(args.min_judge_score)
628
+ or meta_language
629
+ )
630
+ row = {
631
+ "cache_key": cache_key(version, ex.source_id, ex.turn_idx),
632
+ "version": version,
633
+ "source_id": ex.source_id,
634
+ "turn_idx": ex.turn_idx,
635
+ "total_turns": ex.total_turns,
636
+ "selected_think": selected or fallback_think(version),
637
+ "selected_index": best_index,
638
+ "score": score,
639
+ "low_quality": low_quality,
640
+ "meta_language": meta_language,
641
+ "fallback": not bool(selected),
642
+ "missing_next_state": version == "sas" and ex.next_user_content is None,
643
+ "selected_reason": str(judge_obj.get("selected_reason", "")),
644
+ }
645
+ if args.save_candidates:
646
+ row["candidates"] = candidates
647
+ row["judge"] = judge_obj
648
+ row["judge_raw"] = judge_text
649
+ batch_rows.append(row)
650
+
651
+ append_cache(cache_path, batch_rows) if not args.no_cache else None
652
+ for row in batch_rows:
653
+ results[(row["source_id"], int(row["turn_idx"]))] = row
654
+ print(f"[{version}] batch {batch_no}: wrote {len(batch_rows)} turn results")
655
+ return results
656
+
657
+
658
+ def rebuild_rows(
659
+ rows: Sequence[Dict[str, Any]],
660
+ full: Dict[Any, FullTrajectory],
661
+ result_map: Dict[Tuple[Any, int], Dict[str, Any]],
662
+ ) -> List[Dict[str, Any]]:
663
+ rebuilt_by_source: Dict[Any, List[Tuple[Dict[str, Any], Dict[str, Any]]]] = {}
664
+ for source_id, traj in full.items():
665
+ new_pairs: List[Tuple[Dict[str, Any], Dict[str, Any]]] = []
666
+ for idx, (user_msg, asst_msg) in enumerate(traj.pairs, start=1):
667
+ answer_block = extract_answer_block(str(asst_msg.get("content", "")))
668
+ result = result_map.get((source_id, idx))
669
+ think = str(result.get("selected_think", "")) if result else fallback_think("sa")
670
+ new_user = copy.deepcopy(user_msg)
671
+ new_asst = copy.deepcopy(asst_msg)
672
+ if answer_block:
673
+ new_asst["content"] = make_response(think, answer_block)
674
+ else:
675
+ new_asst["content"] = str(asst_msg.get("content", ""))
676
+ new_pairs.append((new_user, new_asst))
677
+ rebuilt_by_source[source_id] = new_pairs
678
+
679
+ output: List[Dict[str, Any]] = []
680
+ for idx, row in enumerate(rows):
681
+ meta = row.get("meta") or {}
682
+ source_id = meta.get("source_id", f"missing_source_{idx}")
683
+ turns = to_int(meta.get("turns"), 0)
684
+ new_row = copy.deepcopy(row)
685
+ traj = full.get(source_id)
686
+ pairs = rebuilt_by_source.get(source_id)
687
+ if traj is None or pairs is None or turns <= 0:
688
+ output.append(new_row)
689
+ continue
690
+ turns = min(turns, len(pairs))
691
+ new_row["messages"] = copy.deepcopy(traj.sys_prefix) + [
692
+ copy.deepcopy(msg) for pair in pairs[:turns] for msg in pair
693
+ ]
694
+ output.append(new_row)
695
+ return output
696
+
697
+
698
+ def validate_answer_unchanged(original: Sequence[Dict[str, Any]], rebuilt: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
699
+ if len(original) != len(rebuilt):
700
+ raise ValueError(f"Row count changed: original={len(original)} rebuilt={len(rebuilt)}")
701
+ checked = 0
702
+ mismatches: List[Dict[str, Any]] = []
703
+ for row_idx, (old_row, new_row) in enumerate(zip(original, rebuilt)):
704
+ old_pairs = collect_pairs(old_row.get("messages") or [], start_idx=len(extract_system_prefix(old_row.get("messages") or [])))
705
+ new_pairs = collect_pairs(new_row.get("messages") or [], start_idx=len(extract_system_prefix(new_row.get("messages") or [])))
706
+ if len(old_pairs) != len(new_pairs):
707
+ mismatches.append({"row_idx": row_idx, "reason": "pair_count_changed"})
708
+ continue
709
+ for turn_idx, ((_, old_asst), (_, new_asst)) in enumerate(zip(old_pairs, new_pairs), start=1):
710
+ old_answer = extract_answer_block(str(old_asst.get("content", "")))
711
+ new_answer = extract_answer_block(str(new_asst.get("content", "")))
712
+ checked += 1
713
+ if old_answer != new_answer:
714
+ mismatches.append(
715
+ {
716
+ "row_idx": row_idx,
717
+ "turn_idx": turn_idx,
718
+ "old_answer": old_answer,
719
+ "new_answer": new_answer,
720
+ }
721
+ )
722
+ if len(mismatches) >= 20:
723
+ break
724
+ if len(mismatches) >= 20:
725
+ break
726
+ if mismatches:
727
+ raise ValueError(f"Answer validation failed, examples: {mismatches[:3]}")
728
+ return {"checked_assistant_messages": checked, "answer_mismatches": 0}
729
+
730
+
731
+ def filter_full_by_args(full: Dict[Any, FullTrajectory], args: argparse.Namespace) -> Dict[Any, FullTrajectory]:
732
+ selected = dict(full)
733
+ if args.source_ids.strip():
734
+ allow = {item.strip() for item in args.source_ids.split(",") if item.strip()}
735
+ selected = {sid: traj for sid, traj in selected.items() if source_key(sid) in allow}
736
+ if args.limit_sources is not None:
737
+ limited: Dict[Any, FullTrajectory] = {}
738
+ for sid in list(selected.keys())[: int(args.limit_sources)]:
739
+ limited[sid] = selected[sid]
740
+ selected = limited
741
+ return selected
742
+
743
+
744
+ def report_from_results(
745
+ *,
746
+ version: str,
747
+ result_map: Dict[Tuple[Any, int], Dict[str, Any]],
748
+ validation: Dict[str, Any],
749
+ args: argparse.Namespace,
750
+ ) -> Dict[str, Any]:
751
+ values = list(result_map.values())
752
+ low_quality = sum(1 for row in values if row.get("low_quality"))
753
+ fallback = sum(1 for row in values if row.get("fallback"))
754
+ meta_language = sum(1 for row in values if row.get("meta_language"))
755
+ missing_next = sum(1 for row in values if row.get("missing_next_state"))
756
+ scores = [float(row.get("score", 0.0)) for row in values]
757
+ summary = {
758
+ "version": version,
759
+ "n": int(args.n),
760
+ "turn_results": len(values),
761
+ "low_quality": low_quality,
762
+ "fallback": fallback,
763
+ "meta_language": meta_language,
764
+ "missing_next_state": missing_next,
765
+ "avg_score": sum(scores) / len(scores) if scores else 0.0,
766
+ "min_score": min(scores) if scores else 0.0,
767
+ "max_score": max(scores) if scores else 0.0,
768
+ **validation,
769
+ }
770
+ per_turn: List[Dict[str, Any]] = []
771
+ for row in values:
772
+ item = {
773
+ "source_id": row.get("source_id"),
774
+ "turn_idx": row.get("turn_idx"),
775
+ "total_turns": row.get("total_turns"),
776
+ "selected_index": row.get("selected_index"),
777
+ "score": row.get("score"),
778
+ "low_quality": row.get("low_quality"),
779
+ "fallback": row.get("fallback"),
780
+ "meta_language": row.get("meta_language", False),
781
+ "missing_next_state": row.get("missing_next_state"),
782
+ "selected_reason": row.get("selected_reason", ""),
783
+ }
784
+ if args.save_candidates:
785
+ item["selected_think"] = row.get("selected_think")
786
+ item["candidates"] = row.get("candidates", [])
787
+ item["judge"] = row.get("judge", {})
788
+ per_turn.append(item)
789
+ return {"summary": summary, "per_turn": per_turn}
790
+
791
+
792
+ def main() -> None:
793
+ args = parse_args()
794
+ versions = [v.strip() for v in args.versions.split(",") if v.strip()]
795
+ if not versions or any(v not in {"sa", "sas"} for v in versions):
796
+ raise ValueError("--versions must contain only sa and/or sas")
797
+ if not args.dry_run and not args.model:
798
+ raise ValueError("--model is required unless --dry-run is set")
799
+
800
+ input_path = args.input.expanduser().resolve()
801
+ output_dir = (args.output_dir or input_path.parent).expanduser().resolve()
802
+ output_prefix = args.output_prefix or input_path.stem
803
+
804
+ print(f"Loading input: {input_path}")
805
+ rows = load_json_list(input_path)
806
+ full_all = build_full_trajectories(rows)
807
+ full_selected = filter_full_by_args(full_all, args)
808
+ if not full_selected:
809
+ raise ValueError("No usable trajectories selected.")
810
+ turns = iter_turns(full_selected)
811
+ print(f"Rows={len(rows)} sources={len(full_all)} selected_sources={len(full_selected)} selected_turns={len(turns)}")
812
+
813
+ llm = tokenizer = judge_llm = judge_tokenizer = None
814
+ if not args.dry_run:
815
+ llm, tokenizer = load_vllm_model(args.model, args, tensor_parallel_size=args.tensor_parallel_size)
816
+ judge_model = args.judge_model or args.model
817
+ if judge_model == args.model:
818
+ judge_llm, judge_tokenizer = llm, tokenizer
819
+ else:
820
+ judge_tp = args.judge_tensor_parallel_size or args.tensor_parallel_size
821
+ judge_llm, judge_tokenizer = load_vllm_model(judge_model, args, tensor_parallel_size=judge_tp)
822
+
823
+ for version in versions:
824
+ result_map = synthesize_version(
825
+ version=version,
826
+ turns=turns,
827
+ args=args,
828
+ output_dir=output_dir,
829
+ output_prefix=output_prefix,
830
+ llm=llm,
831
+ tokenizer=tokenizer,
832
+ judge_llm=judge_llm,
833
+ judge_tokenizer=judge_tokenizer,
834
+ )
835
+ rows_for_output = [
836
+ row
837
+ for idx, row in enumerate(rows)
838
+ if not args.selected_only
839
+ or (row.get("meta") or {}).get("source_id", f"missing_source_{idx}") in full_selected
840
+ ]
841
+ rebuilt = rebuild_rows(rows_for_output, full_selected, result_map)
842
+ validation = validate_answer_unchanged(rows_for_output, rebuilt)
843
+ out_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.json"
844
+ report_path = output_dir / f"{output_prefix}_with_think_{version}_bon{args.n}.report.json"
845
+ dump_json(out_path, rebuilt, indent=int(args.indent))
846
+ report = report_from_results(version=version, result_map=result_map, validation=validation, args=args)
847
+ dump_json(report_path, report, indent=2)
848
+ print(f"[{version}] wrote SFT: {out_path}")
849
+ print(f"[{version}] wrote report: {report_path}")
850
+ print(f"[{version}] summary: {json.dumps(report['summary'], ensure_ascii=False)}")
851
+
852
+
853
+ if __name__ == "__main__":
854
+ main()
scripts/train_sokoban.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import time
4
+ from dataclasses import dataclass
5
+ from typing import Tuple, Dict, List
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.optim as optim
11
+ from torch.distributions import Categorical
12
+
13
+ from ragen.env.sokoban.env import SokobanEnv
14
+ from ragen.env.sokoban.config import SokobanEnvConfig
15
+ from ragen.utils import all_seed
16
+
17
+
18
+ # ===== Observation parsing (text grid -> 7xHxW one-hot) =====
19
+ SYMBOLS = ["#", "_", "O", "√", "X", "P", "S"]
20
+ SYMBOL_TO_IDX: Dict[str, int] = {s: i for i, s in enumerate(SYMBOLS)}
21
+
22
+
23
+ def parse_grid_text(obs_text: str, board_shape: Tuple[int, int]) -> torch.Tensor:
24
+ lines = obs_text.splitlines()
25
+ H, W = board_shape
26
+ assert len(lines) == H, f"Grid height mismatch: expected {H}, got {len(lines)}"
27
+ grid = [[c for c in line] for line in lines]
28
+ assert all(len(row) == W for row in grid), "Grid width mismatch"
29
+ out = np.zeros((len(SYMBOLS), H, W), dtype=np.float32)
30
+ for r in range(H):
31
+ for c in range(W):
32
+ ch = grid[r][c]
33
+ idx = SYMBOL_TO_IDX.get(ch, None)
34
+ if idx is None:
35
+ raise ValueError(f"Unknown grid symbol '{ch}' at {(r, c)}")
36
+ out[idx, r, c] = 1.0
37
+ return torch.from_numpy(out)
38
+
39
+
40
+ # ===== Small CNN Policy-Value Net =====
41
+ class SmallSokobanCNN(nn.Module):
42
+ def __init__(self, in_channels: int, num_actions: int):
43
+ super().__init__()
44
+ # 6x6 is tiny; use minimal convs
45
+ self.encoder = nn.Sequential(
46
+ nn.Conv2d(in_channels, 32, kernel_size=3, padding=1),
47
+ nn.ReLU(inplace=True),
48
+ nn.Conv2d(32, 64, kernel_size=3, padding=1),
49
+ nn.ReLU(inplace=True),
50
+ nn.Flatten(),
51
+ )
52
+ # compute flat size for 6x6 grids at runtime
53
+ self._feat_dim = None
54
+ self.policy_head = nn.Linear(64 * 6 * 6, num_actions)
55
+ self.value_head = nn.Linear(64 * 6 * 6, 1)
56
+
57
+ def forward(self, x: torch.Tensor):
58
+ # x: [B, C, H, W]
59
+ z = self.encoder(x)
60
+ logits = self.policy_head(z)
61
+ value = self.value_head(z).squeeze(-1)
62
+ return logits, value
63
+
64
+
65
+ @dataclass
66
+ class PPOConfig:
67
+ total_steps: int = 200_000
68
+ rollout_steps: int = 256
69
+ batch_size: int = 256
70
+ update_epochs: int = 4
71
+ gamma: float = 0.99
72
+ gae_lambda: float = 0.95
73
+ clip_coef: float = 0.2
74
+ ent_coef: float = 0.01
75
+ vf_coef: float = 0.5
76
+ max_grad_norm: float = 0.5
77
+ lr: float = 2.5e-4
78
+ device: str = "cpu"
79
+
80
+
81
+ def compute_gae(rewards, dones, values, next_value, cfg: PPOConfig):
82
+ T = len(rewards)
83
+ adv = np.zeros(T, dtype=np.float32)
84
+ lastgaelam = 0.0
85
+ for t in reversed(range(T)):
86
+ nonterminal = 1.0 - float(dones[t])
87
+ delta = rewards[t] + cfg.gamma * next_value * nonterminal - values[t]
88
+ lastgaelam = delta + cfg.gamma * cfg.gae_lambda * nonterminal * lastgaelam
89
+ adv[t] = lastgaelam
90
+ next_value = values[t]
91
+ returns = adv + values
92
+ return adv, returns
93
+
94
+
95
+ def collect_rollout(env: SokobanEnv, policy: SmallSokobanCNN, cfg: PPOConfig, board_shape: Tuple[int, int], device: str):
96
+ obs_buf = []
97
+ act_buf = []
98
+ logp_buf = []
99
+ rew_buf = []
100
+ done_buf = []
101
+ val_buf = []
102
+
103
+ policy.eval()
104
+
105
+ obs_text = env.render() # current text observation
106
+ for _ in range(cfg.rollout_steps):
107
+ obs_t = parse_grid_text(obs_text, board_shape).unsqueeze(0).to(device)
108
+ with torch.no_grad():
109
+ logits, value = policy(obs_t)
110
+ dist = Categorical(logits=logits)
111
+ act_model = dist.sample()[0].item() # 0..3
112
+ logp = dist.log_prob(torch.tensor([act_model], device=device)).item()
113
+ val = value[0].item()
114
+ act_env = act_model + 1 # map to 1..4
115
+ next_obs_text, reward, done, _ = env.step(act_env)
116
+
117
+ obs_buf.append(obs_t.squeeze(0).cpu().numpy())
118
+ act_buf.append(act_model)
119
+ logp_buf.append(logp)
120
+ rew_buf.append(reward)
121
+ done_buf.append(done)
122
+ val_buf.append(val)
123
+
124
+ obs_text = next_obs_text
125
+ if done:
126
+ obs_text = env.reset()
127
+
128
+ # bootstrap value
129
+ with torch.no_grad():
130
+ obs_t = parse_grid_text(obs_text, board_shape).unsqueeze(0).to(device)
131
+ _, next_value = policy(obs_t)
132
+ next_value = next_value[0].item()
133
+
134
+ adv, ret = compute_gae(
135
+ np.array(rew_buf, dtype=np.float32),
136
+ np.array(done_buf, dtype=np.bool_),
137
+ np.array(val_buf, dtype=np.float32),
138
+ next_value,
139
+ cfg,
140
+ )
141
+
142
+ data = {
143
+ "obs": torch.from_numpy(np.stack(obs_buf)).to(device),
144
+ "actions": torch.tensor(act_buf, dtype=torch.long, device=device),
145
+ "logp": torch.tensor(logp_buf, dtype=torch.float32, device=device),
146
+ "advantages": torch.tensor(adv, dtype=torch.float32, device=device),
147
+ "returns": torch.tensor(ret, dtype=torch.float32, device=device),
148
+ "values": torch.tensor(val_buf, dtype=torch.float32, device=device),
149
+ }
150
+ return data
151
+
152
+
153
+ def ppo_update(policy, optimizer, data, cfg: PPOConfig):
154
+ policy.train()
155
+ obs = data["obs"]
156
+ actions = data["actions"]
157
+ old_logp = data["logp"]
158
+ advantages = data["advantages"]
159
+ returns = data["returns"]
160
+
161
+ advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
162
+
163
+ N = obs.shape[0]
164
+ idxs = np.arange(N)
165
+
166
+ for _ in range(cfg.update_epochs):
167
+ np.random.shuffle(idxs)
168
+ for start in range(0, N, cfg.batch_size):
169
+ end = start + cfg.batch_size
170
+ mb_idx = idxs[start:end]
171
+ mb_obs = obs[mb_idx]
172
+ mb_act = actions[mb_idx]
173
+ mb_old_logp = old_logp[mb_idx]
174
+ mb_adv = advantages[mb_idx]
175
+ mb_ret = returns[mb_idx]
176
+
177
+ logits, values = policy(mb_obs)
178
+ dist = Categorical(logits=logits)
179
+ new_logp = dist.log_prob(mb_act)
180
+ entropy = dist.entropy().mean()
181
+
182
+ ratio = (new_logp - mb_old_logp).exp()
183
+ pg_loss1 = -mb_adv * ratio
184
+ pg_loss2 = -mb_adv * torch.clamp(ratio, 1.0 - cfg.clip_coef, 1.0 + cfg.clip_coef)
185
+ pg_loss = torch.max(pg_loss1, pg_loss2).mean()
186
+
187
+ v_loss = 0.5 * (mb_ret - values).pow(2).mean()
188
+ loss = pg_loss + cfg.vf_coef * v_loss - cfg.ent_coef * entropy
189
+
190
+ optimizer.zero_grad(set_to_none=True)
191
+ loss.backward()
192
+ nn.utils.clip_grad_norm_(policy.parameters(), cfg.max_grad_norm)
193
+ optimizer.step()
194
+
195
+ with torch.no_grad():
196
+ approx_kl = (old_logp - new_logp).mean().item()
197
+ clipfrac = (torch.gt(torch.abs(ratio - 1.0), cfg.clip_coef)).float().mean().item()
198
+ return {
199
+ "loss": float(loss.item()),
200
+ "pg_loss": float(pg_loss.mean().item()),
201
+ "v_loss": float(v_loss.item()),
202
+ "entropy": float(entropy.item()),
203
+ "approx_kl": approx_kl,
204
+ "clipfrac": clipfrac,
205
+ }
206
+
207
+
208
+ def evaluate(env: SokobanEnv, policy: SmallSokobanCNN, board_shape: Tuple[int, int], device: str, episodes: int = 5):
209
+ policy.eval()
210
+ returns = []
211
+ with torch.no_grad():
212
+ for _ in range(episodes):
213
+ obs_text = env.reset()
214
+ done = False
215
+ ep_ret = 0.0
216
+ steps = 0
217
+ while not done and steps < 200:
218
+ obs_t = parse_grid_text(obs_text, board_shape).unsqueeze(0).to(device)
219
+ logits, _ = policy(obs_t)
220
+ dist = Categorical(logits=logits)
221
+ act_model = torch.argmax(dist.probs, dim=-1)[0].item()
222
+ act_env = act_model + 1
223
+ obs_text, reward, done, info = env.step(act_env)
224
+ ep_ret += reward
225
+ steps += 1
226
+ returns.append(ep_ret)
227
+ return float(np.mean(returns)), float(np.std(returns))
228
+
229
+
230
+ def main():
231
+ parser = argparse.ArgumentParser()
232
+ # Sokoban config flags to preserve exact environment
233
+ parser.add_argument("--dim_x", type=int, default=None)
234
+ parser.add_argument("--dim_y", type=int, default=None)
235
+ parser.add_argument("--max_steps", type=int, default=None)
236
+ parser.add_argument("--num_boxes", type=int, default=None)
237
+ parser.add_argument("--search_depth", type=int, default=None)
238
+ parser.add_argument("--render_mode", type=str, default=None, choices=[None, "text", "rgb_array"])
239
+ parser.add_argument("--observation_format", type=str, default=None, choices=[None, "grid", "coord", "grid_coord"])
240
+
241
+ # PPO/training
242
+ parser.add_argument("--total_steps", type=int, default=200_000)
243
+ parser.add_argument("--rollout_steps", type=int, default=256)
244
+ parser.add_argument("--batch_size", type=int, default=256)
245
+ parser.add_argument("--update_epochs", type=int, default=4)
246
+ parser.add_argument("--gamma", type=float, default=0.99)
247
+ parser.add_argument("--gae_lambda", type=float, default=0.95)
248
+ parser.add_argument("--clip_coef", type=float, default=0.2)
249
+ parser.add_argument("--ent_coef", type=float, default=0.01)
250
+ parser.add_argument("--vf_coef", type=float, default=0.5)
251
+ parser.add_argument("--max_grad_norm", type=float, default=0.5)
252
+ parser.add_argument("--lr", type=float, default=2.5e-4)
253
+ parser.add_argument("--device", type=str, default="cpu")
254
+ parser.add_argument("--seed", type=int, default=42)
255
+ parser.add_argument("--eval_interval", type=int, default=5000)
256
+ parser.add_argument("--eval_episodes", type=int, default=5)
257
+ parser.add_argument("--save_path", type=str, default="runs/sokoban_small_ppo.pt")
258
+ parser.add_argument("--sanity_rollout", action="store_true", help="Run a short rollout to validate parsing & action mapping, then exit")
259
+
260
+ args = parser.parse_args()
261
+
262
+ # Build Sokoban config strictly following defaults unless explicitly overridden
263
+ env_cfg = SokobanEnvConfig()
264
+ if args.dim_x is not None and args.dim_y is not None:
265
+ env_cfg.dim_room = (args.dim_x, args.dim_y)
266
+ if args.max_steps is not None:
267
+ env_cfg.max_steps = args.max_steps
268
+ if args.num_boxes is not None:
269
+ env_cfg.num_boxes = args.num_boxes
270
+ if args.search_depth is not None:
271
+ env_cfg.search_depth = args.search_depth
272
+ if args.render_mode is not None:
273
+ env_cfg.render_mode = args.render_mode
274
+ if args.observation_format is not None:
275
+ env_cfg.observation_format = args.observation_format
276
+
277
+ # Enforce text + grid parsing, which matches LLM environment training by default
278
+ assert env_cfg.render_mode == "text", "Training expects text observations"
279
+ assert env_cfg.observation_format == "grid", "Training expects 'grid' observation format"
280
+
281
+ device = torch.device(args.device)
282
+
283
+ with all_seed(args.seed):
284
+ env = SokobanEnv(env_cfg)
285
+ # derive board shape from config
286
+ board_shape = env_cfg.dim_room
287
+ obs_text = env.reset()
288
+
289
+ policy = SmallSokobanCNN(in_channels=len(SYMBOLS), num_actions=4).to(device)
290
+ optimizer = optim.Adam(policy.parameters(), lr=args.lr)
291
+
292
+ if args.sanity_rollout:
293
+ print("[Sanity] Running 10 steps...")
294
+ obs = obs_text
295
+ for t in range(10):
296
+ obs_t = parse_grid_text(obs, board_shape).unsqueeze(0).to(device)
297
+ with torch.no_grad():
298
+ logits, _ = policy(obs_t)
299
+ dist = Categorical(logits=logits)
300
+ a = dist.sample()[0].item()
301
+ obs, r, d, info = env.step(a + 1)
302
+ print(f"t={t} r={r} done={d} info={info}")
303
+ if d:
304
+ obs = env.reset()
305
+ return
306
+
307
+ cfg = PPOConfig(
308
+ total_steps=args.total_steps,
309
+ rollout_steps=args.rollout_steps,
310
+ batch_size=args.batch_size,
311
+ update_epochs=args.update_epochs,
312
+ gamma=args.gamma,
313
+ gae_lambda=args.gae_lambda,
314
+ clip_coef=args.clip_coef,
315
+ ent_coef=args.ent_coef,
316
+ vf_coef=args.vf_coef,
317
+ max_grad_norm=args.max_grad_norm,
318
+ lr=args.lr,
319
+ device=args.device,
320
+ )
321
+
322
+ steps_done = 0
323
+ last_eval = 0
324
+ start_time = time.time()
325
+
326
+ while steps_done < cfg.total_steps:
327
+ data = collect_rollout(env, policy, cfg, board_shape, device)
328
+ steps_done += cfg.rollout_steps
329
+
330
+ stats = ppo_update(policy, optimizer, data, cfg)
331
+
332
+ if steps_done - last_eval >= args.eval_interval:
333
+ with all_seed(args.seed + 123):
334
+ eval_env = SokobanEnv(env_cfg)
335
+ mean_ret, std_ret = evaluate(eval_env, policy, board_shape, device, episodes=args.eval_episodes)
336
+ last_eval = steps_done
337
+ elapsed = time.time() - start_time
338
+ print(
339
+ f"steps={steps_done} elapsed={elapsed:.1f}s loss={stats['loss']:.3f} "
340
+ f"pg={stats['pg_loss']:.3f} v={stats['v_loss']:.3f} ent={stats['entropy']:.3f} "
341
+ f"kl={stats['approx_kl']:.4f} clipfrac={stats['clipfrac']:.3f} eval_ret={mean_ret:.2f}±{std_ret:.2f}"
342
+ )
343
+ # Save
344
+ os.makedirs(os.path.dirname(args.save_path), exist_ok=True)
345
+ torch.save({
346
+ "model_state": policy.state_dict(),
347
+ "env_cfg": env_cfg.__dict__,
348
+ "steps": steps_done,
349
+ "seed": args.seed,
350
+ }, args.save_path)
351
+
352
+ print(f"Training finished. Model saved to {args.save_path}")
353
+
354
+
355
+ if __name__ == "__main__":
356
+ main()
scripts/visualize.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Local rollout visualizer.
4
+
5
+ Usage:
6
+ python scripts/visualize.py --rollout_path results/ [--host 127.0.0.1] [--port 8000]
7
+
8
+ The script launches a small HTTP server that lets you inspect .pkl files
9
+ (containing verl.DataProto dumps) inside the rollout path. Open the printed
10
+ URL in a browser to explore directories, select a file, and view its
11
+ meta information and non-tensor batches entry by entry.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import logging
19
+ import threading
20
+ from functools import lru_cache
21
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
22
+ from pathlib import Path
23
+ from typing import Any, Dict, List
24
+ from urllib.parse import parse_qs, urlparse
25
+ import webbrowser
26
+
27
+ import numpy as np
28
+
29
+ from verl import DataProto
30
+
31
+ LOGGER = logging.getLogger(__name__)
32
+
33
+
34
+ def parse_args() -> argparse.Namespace:
35
+ parser = argparse.ArgumentParser(description="Launch a local rollout visualizer")
36
+ parser.add_argument("--rollout_path", required=True, help="Directory containing rollout .pkl files")
37
+ parser.add_argument("--host", default="127.0.0.1", help="Host to bind (default: 127.0.0.1)")
38
+ parser.add_argument("--port", type=int, default=8000, help="Port to bind (default: 8000)")
39
+ parser.add_argument("--no-browser", action="store_true", help="Do not attempt to open a browser automatically")
40
+ return parser.parse_args()
41
+
42
+
43
+ def ensure_within(path: Path, root: Path) -> Path:
44
+ resolved = path.resolve()
45
+ try:
46
+ resolved.relative_to(root)
47
+ except ValueError as exc:
48
+ raise ValueError(f"Path {path} escapes the rollout root {root}") from exc
49
+ return resolved
50
+
51
+
52
+ def numpy_summary(array: np.ndarray) -> Dict[str, Any]:
53
+ array = np.asarray(array)
54
+ summary: Dict[str, Any] = {
55
+ "__type__": "ndarray",
56
+ "dtype": str(array.dtype),
57
+ "shape": list(array.shape),
58
+ "size": int(array.size),
59
+ }
60
+ preview_limit = 32
61
+ flat = array.reshape(-1)
62
+ preview = flat[:preview_limit].tolist()
63
+ summary["preview"] = preview
64
+ summary["preview_count"] = len(preview)
65
+ if array.size <= preview_limit and array.size <= 10_000:
66
+ summary["values"] = array.tolist()
67
+ return summary
68
+
69
+
70
+ def serialize_for_view(value: Any, depth: int = 0) -> Any:
71
+ if depth > 6:
72
+ return repr(value)
73
+
74
+ if value is None or isinstance(value, (str, int, float, bool)):
75
+ return value
76
+
77
+ if isinstance(value, (np.integer, np.floating, np.bool_)):
78
+ return value.item()
79
+
80
+ if isinstance(value, dict):
81
+ return {str(key): serialize_for_view(val, depth + 1) for key, val in value.items()}
82
+
83
+ if isinstance(value, (list, tuple, set)):
84
+ return [serialize_for_view(val, depth + 1) for val in value]
85
+
86
+ if isinstance(value, np.ndarray):
87
+ return numpy_summary(value)
88
+
89
+ return repr(value)
90
+
91
+
92
+ def build_tree(root: Path) -> Dict[str, Any]:
93
+ root_node: Dict[str, Any] = {"name": root.name, "path": "", "type": "dir", "children": []}
94
+ nodes: Dict[str, Dict[str, Any]] = {"": root_node}
95
+
96
+ for file_path in sorted(root.rglob("*.pkl")):
97
+ rel_path = file_path.relative_to(root)
98
+ rel_path_posix = rel_path.as_posix()
99
+ parts = rel_path.parts
100
+ if not parts:
101
+ continue
102
+
103
+ cumulative = []
104
+ for part in parts[:-1]:
105
+ cumulative.append(part)
106
+ current_key = "/".join(cumulative)
107
+ parent_key = "/".join(cumulative[:-1]) if len(cumulative) > 1 else ""
108
+ if current_key not in nodes:
109
+ node = {"name": part, "path": current_key, "type": "dir", "children": []}
110
+ nodes[current_key] = node
111
+ nodes[parent_key]["children"].append(node)
112
+ file_parent_key = "/".join(parts[:-1]) if len(parts) > 1 else ""
113
+ file_node = {"name": parts[-1], "path": rel_path_posix, "type": "file"}
114
+ nodes[file_parent_key]["children"].append(file_node)
115
+
116
+ def sort_children(node: Dict[str, Any]) -> None:
117
+ children = node.get("children")
118
+ if not children:
119
+ return
120
+ children.sort(key=lambda item: (item.get("type") != "dir", item.get("name", "")))
121
+ for child in children:
122
+ if child.get("type") == "dir":
123
+ sort_children(child)
124
+
125
+ sort_children(root_node)
126
+ return root_node
127
+
128
+
129
+ def data_proto_to_payload(file_path: Path) -> Dict[str, Any]:
130
+ data = DataProto.load_from_disk(str(file_path))
131
+ length = len(data)
132
+ items: List[Dict[str, Any]] = []
133
+ for idx in range(length):
134
+ try:
135
+ item = data[idx]
136
+ except Exception as exc: # pragma: no cover - defensive guard
137
+ LOGGER.warning("Failed to read item %s from %s: %s", idx, file_path, exc)
138
+ continue
139
+ items.append(
140
+ {
141
+ "index": idx,
142
+ "meta_info": serialize_for_view(item.meta_info),
143
+ "non_tensor_batch": serialize_for_view(item.non_tensor_batch),
144
+ }
145
+ )
146
+
147
+ return {
148
+ "path": str(file_path),
149
+ "length": length,
150
+ "meta_info": serialize_for_view(data.meta_info),
151
+ "items": items,
152
+ }
153
+
154
+
155
+ class RolloutExplorer:
156
+ def __init__(self, root: Path):
157
+ self.root = root
158
+ self._tree_cache: Dict[str, Any] | None = None
159
+ self._lock = threading.Lock()
160
+
161
+ def tree(self) -> Dict[str, Any]:
162
+ with self._lock:
163
+ if self._tree_cache is None:
164
+ self._tree_cache = build_tree(self.root)
165
+ return self._tree_cache
166
+
167
+ @lru_cache(maxsize=32)
168
+ def load_file(self, relative_path: str) -> Dict[str, Any]:
169
+ normalized_path = Path(relative_path)
170
+ target = ensure_within(self.root / normalized_path, self.root)
171
+ if not target.exists() or not target.is_file():
172
+ raise FileNotFoundError(f"File {relative_path} not found under {self.root}")
173
+ payload = data_proto_to_payload(target)
174
+ payload["relative_path"] = target.relative_to(self.root).as_posix()
175
+ return payload
176
+
177
+
178
+ HTML_PAGE = """<!DOCTYPE html>
179
+ <html lang=\"en\">
180
+ <head>
181
+ <meta charset=\"utf-8\" />
182
+ <title>Rollout Visualizer</title>
183
+ <style>
184
+ :root {
185
+ color-scheme: light dark;
186
+ --bg: #f7f7fb;
187
+ --panel: #ffffffcc;
188
+ --accent: #4a6cff;
189
+ --accent-soft: #e6ebff;
190
+ --text: #1d1d25;
191
+ --border: #d9d9e3;
192
+ }
193
+ * { box-sizing: border-box; }
194
+ body {
195
+ margin: 0;
196
+ font-family: "Segoe UI", Tahoma, sans-serif;
197
+ background: var(--bg);
198
+ color: var(--text);
199
+ }
200
+ header {
201
+ padding: 14px 24px;
202
+ background: linear-gradient(135deg, var(--accent), #7f9bff);
203
+ color: white;
204
+ font-weight: 600;
205
+ letter-spacing: 0.4px;
206
+ }
207
+ #layout {
208
+ display: flex;
209
+ height: calc(100vh - 56px);
210
+ }
211
+ #sidebar {
212
+ width: 28%;
213
+ max-width: 360px;
214
+ min-width: 240px;
215
+ border-right: 1px solid var(--border);
216
+ background: var(--panel);
217
+ padding: 12px 16px;
218
+ overflow-y: auto;
219
+ }
220
+ #content {
221
+ flex: 1;
222
+ overflow-y: auto;
223
+ padding: 20px 28px;
224
+ }
225
+ .tree-node {
226
+ margin-left: 12px;
227
+ }
228
+ .tree-toggle {
229
+ cursor: pointer;
230
+ user-select: none;
231
+ display: inline-flex;
232
+ align-items: center;
233
+ gap: 6px;
234
+ padding: 4px 6px;
235
+ border-radius: 6px;
236
+ }
237
+ .tree-toggle:hover {
238
+ background: var(--accent-soft);
239
+ }
240
+ .file-entry {
241
+ cursor: pointer;
242
+ display: block;
243
+ padding: 4px 8px;
244
+ margin: 2px 0;
245
+ border-radius: 6px;
246
+ }
247
+ .file-entry:hover,
248
+ .file-entry.active {
249
+ background: var(--accent-soft);
250
+ color: var(--accent);
251
+ }
252
+ .panel {
253
+ background: var(--panel);
254
+ border: 1px solid var(--border);
255
+ border-radius: 12px;
256
+ padding: 16px 20px;
257
+ box-shadow: 0 4px 16px rgba(76, 96, 255, 0.05);
258
+ }
259
+ .section-title {
260
+ font-weight: 600;
261
+ margin-bottom: 12px;
262
+ font-size: 18px;
263
+ }
264
+ .meta-grid {
265
+ display: grid;
266
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
267
+ gap: 12px;
268
+ }
269
+ .section-subtitle {
270
+ font-weight: 600;
271
+ margin: 18px 0 10px;
272
+ color: var(--accent);
273
+ font-size: 16px;
274
+ }
275
+ .kv-block {
276
+ border: 1px solid var(--border);
277
+ border-radius: 10px;
278
+ padding: 12px;
279
+ background: #fff;
280
+ }
281
+ .kv-header {
282
+ font-weight: 600;
283
+ margin-bottom: 8px;
284
+ color: var(--accent);
285
+ }
286
+ .kv-body {
287
+ font-size: 14px;
288
+ line-height: 1.5;
289
+ white-space: pre-wrap;
290
+ }
291
+ details {
292
+ border: 1px solid var(--border);
293
+ border-radius: 10px;
294
+ padding: 10px 14px;
295
+ margin-bottom: 10px;
296
+ background: #fff;
297
+ }
298
+ details[open] {
299
+ border-color: var(--accent);
300
+ box-shadow: 0 4px 12px rgba(74, 108, 255, 0.08);
301
+ }
302
+ summary {
303
+ cursor: pointer;
304
+ font-weight: 600;
305
+ color: var(--accent);
306
+ }
307
+ .message-card {
308
+ border: 1px solid var(--border);
309
+ border-radius: 8px;
310
+ padding: 10px 12px;
311
+ margin: 6px 0;
312
+ background: #fbfbff;
313
+ }
314
+ .message-meta {
315
+ font-size: 13px;
316
+ opacity: 0.7;
317
+ margin-bottom: 4px;
318
+ }
319
+ .message-content {
320
+ white-space: pre-wrap;
321
+ font-family: "Fira Code", "Consolas", monospace;
322
+ font-size: 14px;
323
+ }
324
+ .messages-section {
325
+ border: 1px solid var(--border);
326
+ border-radius: 12px;
327
+ padding: 14px 16px;
328
+ background: #f3f5ff;
329
+ margin-bottom: 14px;
330
+ box-shadow: inset 0 0 0 1px rgba(74, 108, 255, 0.05);
331
+ }
332
+ .messages-section .section-subtitle {
333
+ margin-top: 0;
334
+ color: var(--accent);
335
+ }
336
+ .placeholder {
337
+ opacity: 0.6;
338
+ font-style: italic;
339
+ }
340
+ </style>
341
+ </head>
342
+ <body>
343
+ <header>Rollout Visualizer</header>
344
+ <div id="layout">
345
+ <aside id="sidebar">
346
+ <div id="tree"></div>
347
+ </aside>
348
+ <main id="content">
349
+ <div class="panel placeholder">Select a file to inspect its rollout details.</div>
350
+ </main>
351
+ </div>
352
+ <script>
353
+ let activePath = null;
354
+
355
+ async function fetchJSON(url) {
356
+ const res = await fetch(url);
357
+ if (!res.ok) {
358
+ const text = await res.text();
359
+ throw new Error(text || res.statusText);
360
+ }
361
+ return res.json();
362
+ }
363
+
364
+ function createElement(tag, options = {}) {
365
+ const el = document.createElement(tag);
366
+ if (options.className) el.className = options.className;
367
+ if (options.text) el.textContent = options.text;
368
+ if (options.html) el.innerHTML = options.html;
369
+ return el;
370
+ }
371
+
372
+ function renderTree(node, container) {
373
+ const wrapper = createElement('div', { className: 'tree-node' });
374
+ const hasChildren = Array.isArray(node.children) && node.children.length > 0;
375
+
376
+ if (node.type === 'dir') {
377
+ const summary = createElement('div', { className: 'tree-toggle' });
378
+ const icon = createElement('span', { text: hasChildren ? '▸' : '•' });
379
+ icon.dataset.state = 'collapsed';
380
+ const label = createElement('span', { text: node.name || '(root)' });
381
+ summary.append(icon, label);
382
+ wrapper.appendChild(summary);
383
+ const childrenContainer = createElement('div');
384
+ childrenContainer.style.display = 'none';
385
+ if (node.path === '') {
386
+ childrenContainer.style.display = 'block';
387
+ icon.textContent = '▾';
388
+ }
389
+ summary.addEventListener('click', () => {
390
+ if (!hasChildren) return;
391
+ if (childrenContainer.style.display === 'none') {
392
+ childrenContainer.style.display = 'block';
393
+ icon.textContent = '▾';
394
+ } else {
395
+ childrenContainer.style.display = 'none';
396
+ icon.textContent = '▸';
397
+ }
398
+ });
399
+ wrapper.appendChild(childrenContainer);
400
+ node.children.forEach(child => renderTree(child, childrenContainer));
401
+ } else if (node.type === 'file') {
402
+ const entry = createElement('div', { className: 'file-entry', text: node.name });
403
+ entry.dataset.path = node.path;
404
+ entry.addEventListener('click', () => loadFile(node.path, entry));
405
+ wrapper.appendChild(entry);
406
+ }
407
+ container.appendChild(wrapper);
408
+ }
409
+
410
+ function renderKeyValue(container, key, value) {
411
+ const block = createElement('div', { className: 'kv-block' });
412
+ block.appendChild(createElement('div', { className: 'kv-header', text: key }));
413
+ const body = createElement('div', { className: 'kv-body' });
414
+ body.appendChild(renderValue(value, key));
415
+ block.appendChild(body);
416
+ container.appendChild(block);
417
+ }
418
+
419
+ function renderMessages(messages) {
420
+ const wrapper = createElement('div');
421
+ messages.forEach((msg, idx) => {
422
+ const card = createElement('div', { className: 'message-card' });
423
+ const role = msg.role || msg.author || `Message ${idx}`;
424
+ const meta = createElement('div', { className: 'message-meta', text: `${role}` });
425
+ if (msg.timestamp) {
426
+ meta.textContent += ` · ${msg.timestamp}`;
427
+ }
428
+ const contentContainer = createElement('div', { className: 'message-content' });
429
+ let content = msg.content;
430
+ if (Array.isArray(content)) {
431
+ content = content.map(part => typeof part === 'string' ? part : JSON.stringify(part, null, 2)).join('\\n');
432
+ }
433
+ contentContainer.textContent = content ?? '';
434
+ card.append(meta, contentContainer);
435
+ wrapper.appendChild(card);
436
+ });
437
+ return wrapper;
438
+ }
439
+
440
+ function renderNdArray(info) {
441
+ const wrapper = createElement('div');
442
+ const summary = `dtype=${info.dtype} · shape=[${info.shape.join(', ')}] · size=${info.size}`;
443
+ wrapper.appendChild(createElement('div', { text: summary }));
444
+ if (info.preview && info.preview.length) {
445
+ const preview = createElement('pre');
446
+ preview.textContent = JSON.stringify(info.preview, null, 2);
447
+ wrapper.appendChild(preview);
448
+ }
449
+ if (info.values) {
450
+ const details = document.createElement('details');
451
+ details.appendChild(createElement('summary', { text: 'Show full values' }));
452
+ const pre = createElement('pre');
453
+ pre.textContent = JSON.stringify(info.values, null, 2);
454
+ details.appendChild(pre);
455
+ wrapper.appendChild(details);
456
+ }
457
+ return wrapper;
458
+ }
459
+
460
+ function renderValue(value, key = '') {
461
+ if (value === null || typeof value === 'undefined') {
462
+ return createElement('span', { text: '—' });
463
+ }
464
+ if (typeof value !== 'object') {
465
+ return createElement('span', { text: String(value) });
466
+ }
467
+ if (Array.isArray(value)) {
468
+ if (key === 'messages') {
469
+ return renderMessages(value.map(item => typeof item === 'object' ? item : { content: String(item) }));
470
+ }
471
+ const details = document.createElement('details');
472
+ details.appendChild(createElement('summary', { text: `List [${value.length}]` }));
473
+ value.forEach((item, idx) => {
474
+ const line = createElement('div');
475
+ line.appendChild(createElement('strong', { text: `#${idx}` }));
476
+ line.appendChild(createElement('div', { className: 'kv-body' }));
477
+ line.lastChild.appendChild(renderValue(item));
478
+ details.appendChild(line);
479
+ });
480
+ return details;
481
+ }
482
+ if (value.__type__ === 'ndarray') {
483
+ return renderNdArray(value);
484
+ }
485
+ const entries = Object.entries(value);
486
+ const container = createElement('div');
487
+ entries.forEach(([childKey, childValue]) => {
488
+ const block = createElement('div');
489
+ block.appendChild(createElement('strong', { text: childKey }));
490
+ const inner = createElement('div', { className: 'kv-body' });
491
+ inner.appendChild(renderValue(childValue, childKey));
492
+ block.appendChild(inner);
493
+ container.appendChild(block);
494
+ });
495
+ return container;
496
+ }
497
+
498
+ function markActive(entry) {
499
+ document.querySelectorAll('.file-entry.active').forEach(el => el.classList.remove('active'));
500
+ entry.classList.add('active');
501
+ }
502
+
503
+ async function loadFile(path, entryEl) {
504
+ try {
505
+ activePath = path;
506
+ markActive(entryEl);
507
+ const data = await fetchJSON(`/api/file?path=${encodeURIComponent(path)}`);
508
+ renderContent(data);
509
+ } catch (error) {
510
+ console.error(error);
511
+ const panel = createElement('div', { className: 'panel' });
512
+ panel.appendChild(createElement('h2', { text: 'Failed to load file' }));
513
+ panel.appendChild(createElement('pre', { text: error.message }));
514
+ const content = document.getElementById('content');
515
+ content.innerHTML = '';
516
+ content.appendChild(panel);
517
+ }
518
+ }
519
+
520
+ function renderContent(data) {
521
+ const content = document.getElementById('content');
522
+ content.innerHTML = '';
523
+ const panel = createElement('div', { className: 'panel' });
524
+ const title = createElement('div', { className: 'section-title', text: data.relative_path || data.path });
525
+ panel.appendChild(title);
526
+ panel.appendChild(createElement('div', { text: `Entries: ${data.length}` }));
527
+
528
+ const metaSection = createElement('div', { className: 'section-title', text: 'Meta Info (global)' });
529
+ panel.appendChild(metaSection);
530
+ const metaGrid = createElement('div', { className: 'meta-grid' });
531
+ Object.entries(data.meta_info || {}).forEach(([key, value]) => {
532
+ renderKeyValue(metaGrid, key, value);
533
+ });
534
+ if (!Object.keys(data.meta_info || {}).length) {
535
+ metaGrid.appendChild(createElement('div', { className: 'placeholder', text: 'No meta info available.' }));
536
+ }
537
+ panel.appendChild(metaGrid);
538
+
539
+ const itemsSection = createElement('div', { className: 'section-title', text: 'Entries' });
540
+ panel.appendChild(itemsSection);
541
+ if (!data.items.length) {
542
+ panel.appendChild(createElement('div', { className: 'placeholder', text: 'No entries in this DataProto.' }));
543
+ }
544
+ data.items.forEach(item => {
545
+ const details = document.createElement('details');
546
+ const summary = createElement('summary', { text: `Item #${item.index}` });
547
+ details.appendChild(summary);
548
+
549
+ const metaBlock = createElement('div', { className: 'meta-grid' });
550
+ Object.entries(item.meta_info || {}).forEach(([key, value]) => {
551
+ renderKeyValue(metaBlock, key, value);
552
+ });
553
+ if (!Object.keys(item.meta_info || {}).length) {
554
+ metaBlock.appendChild(createElement('div', { className: 'placeholder', text: 'No item-level meta info.' }));
555
+ }
556
+ details.appendChild(metaBlock);
557
+
558
+ const nonTensorEntries = Object.entries(item.non_tensor_batch || {});
559
+ let messagesHandled = false;
560
+ if (nonTensorEntries.length) {
561
+ nonTensorEntries.forEach(([key, value]) => {
562
+ if (key === 'messages_list') {
563
+ const messagesSection = createElement('div', { className: 'messages-section' });
564
+ messagesSection.appendChild(createElement('div', { className: 'section-subtitle', text: 'Messages' }));
565
+ messagesSection.appendChild(renderValue(value, key));
566
+ details.appendChild(messagesSection);
567
+ messagesHandled = true;
568
+ }
569
+ });
570
+ const others = nonTensorEntries.filter(([key]) => key !== 'messages_list');
571
+ if (others.length) {
572
+ const ntBlock = createElement('div', { className: 'meta-grid' });
573
+ others.forEach(([key, value]) => {
574
+ renderKeyValue(ntBlock, key, value);
575
+ });
576
+ details.appendChild(ntBlock);
577
+ }
578
+ if (!messagesHandled && !others.length) {
579
+ details.appendChild(createElement('div', { className: 'placeholder', text: 'No non-tensor batch data.' }));
580
+ }
581
+ } else {
582
+ details.appendChild(createElement('div', { className: 'placeholder', text: 'No non-tensor batch data.' }));
583
+ }
584
+
585
+ panel.appendChild(details);
586
+ });
587
+
588
+ content.appendChild(panel);
589
+ }
590
+
591
+ async function init() {
592
+ try {
593
+ const treeData = await fetchJSON('/api/tree');
594
+ const treeRoot = document.getElementById('tree');
595
+ treeRoot.innerHTML = '';
596
+ renderTree(treeData, treeRoot);
597
+ } catch (error) {
598
+ const treeRoot = document.getElementById('tree');
599
+ treeRoot.textContent = 'Failed to load file tree.';
600
+ console.error(error);
601
+ }
602
+ }
603
+
604
+ init();
605
+ </script>
606
+ </body>
607
+ </html>
608
+ """
609
+
610
+
611
+ class VisualizerHandler(BaseHTTPRequestHandler):
612
+ explorer: RolloutExplorer
613
+
614
+ def do_GET(self) -> None: # noqa: N802 - http.server signature
615
+ parsed = urlparse(self.path)
616
+ if parsed.path == "/":
617
+ self.respond_html(HTML_PAGE)
618
+ return
619
+ if parsed.path == "/api/tree":
620
+ payload = VisualizerHandler.explorer.tree()
621
+ self.respond_json(payload)
622
+ return
623
+ if parsed.path == "/api/file":
624
+ query = parse_qs(parsed.query)
625
+ relative = query.get("path", [None])[0]
626
+ if not relative:
627
+ self.respond_json({"error": "Missing path query parameter"}, status=400)
628
+ return
629
+ try:
630
+ payload = VisualizerHandler.explorer.load_file(relative)
631
+ except FileNotFoundError:
632
+ self.respond_json({"error": "File not found"}, status=404)
633
+ return
634
+ except Exception as exc: # pragma: no cover - defensive guard
635
+ LOGGER.exception("Failed to load %s", relative)
636
+ self.respond_json({"error": str(exc)}, status=500)
637
+ return
638
+ self.respond_json(payload)
639
+ return
640
+
641
+ self.respond_json({"error": "Not found"}, status=404)
642
+
643
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A003 - inherited name
644
+ LOGGER.info("%s - %s", self.address_string(), format % args)
645
+
646
+ def respond_json(self, payload: Any, status: int = 200) -> None:
647
+ body = json.dumps(payload).encode("utf-8")
648
+ self.send_response(status)
649
+ self.send_header("Content-Type", "application/json; charset=utf-8")
650
+ self.send_header("Content-Length", str(len(body)))
651
+ self.end_headers()
652
+ self.wfile.write(body)
653
+
654
+ def respond_html(self, html: str, status: int = 200) -> None:
655
+ body = html.encode("utf-8")
656
+ self.send_response(status)
657
+ self.send_header("Content-Type", "text/html; charset=utf-8")
658
+ self.send_header("Content-Length", str(len(body)))
659
+ self.end_headers()
660
+ self.wfile.write(body)
661
+
662
+
663
+ def main() -> None:
664
+ logging.basicConfig(level=logging.INFO, format="[%(levelname)s] %(message)s")
665
+ args = parse_args()
666
+ root = Path(args.rollout_path).expanduser().resolve()
667
+ if not root.exists() or not root.is_dir():
668
+ raise SystemExit(f"Rollout path {root} does not exist or is not a directory")
669
+
670
+ explorer = RolloutExplorer(root)
671
+ VisualizerHandler.explorer = explorer
672
+
673
+ server = ThreadingHTTPServer((args.host, args.port), VisualizerHandler)
674
+
675
+ address = f"http://{args.host}:{args.port}/"
676
+ print(f"Serving rollout visualizer for {root} at {address}")
677
+ if not args.no_browser:
678
+ try:
679
+ webbrowser.open(address)
680
+ except Exception as exc: # pragma: no cover - best effort
681
+ LOGGER.info("Could not open browser automatically: %s", exc)
682
+
683
+ try:
684
+ server.serve_forever()
685
+ except KeyboardInterrupt:
686
+ print("\nShutting down...")
687
+ finally:
688
+ server.server_close()
689
+
690
+
691
+ if __name__ == "__main__":
692
+ main()
tests/env/test_sokoban_render.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from ragen.env.sokoban.config import SokobanEnvConfig
4
+ from ragen.env.sokoban.env import SokobanEnv
5
+
6
+
7
+ def test_sokoban_render_supports_grid_and_coord():
8
+ seed = 1234
9
+ grid_config = SokobanEnvConfig(
10
+ dim_room=(5, 5),
11
+ num_boxes=1,
12
+ max_steps=10,
13
+ search_depth=20,
14
+ observation_format="grid",
15
+ )
16
+ coord_config = SokobanEnvConfig(
17
+ dim_room=(5, 5),
18
+ num_boxes=1,
19
+ max_steps=10,
20
+ search_depth=20,
21
+ observation_format="coord",
22
+ )
23
+
24
+ grid_env = SokobanEnv(grid_config)
25
+ coord_env = SokobanEnv(coord_config)
26
+
27
+ try:
28
+ grid_obs = grid_env.reset(seed=seed)
29
+ coord_obs = coord_env.reset(seed=seed)
30
+
31
+ assert isinstance(grid_obs, str)
32
+ assert isinstance(coord_obs, str)
33
+
34
+ assert "Board size:" in coord_obs
35
+ assert re.search(r"Walls: \(\d+, \d+\)", coord_obs)
36
+
37
+ assert isinstance(coord_env.render(mode="grid"), str)
38
+ assert "Board size:" in grid_env.render(mode="coord")
39
+ finally:
40
+ grid_env.close()
41
+ coord_env.close()
tests/es_manager/test_seed_iteration.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from omegaconf import OmegaConf
3
+ from ragen.llm_agent.es_manager import EnvStateManager
4
+
5
+
6
+ def make_cfg():
7
+ return OmegaConf.create({
8
+ 'seed': {'train': 7},
9
+ 'es_manager': {
10
+ 'train': {
11
+ 'env_groups': 1,
12
+ 'group_size': 1,
13
+ 'env_configs': {'tags': ['Bandit'], 'n_groups': [1]},
14
+ }
15
+ },
16
+ 'custom_envs': {
17
+ 'Bandit': {
18
+ 'env_type': 'bandit',
19
+ 'max_actions_per_traj': 1,
20
+ 'env_config': None
21
+ }
22
+ }
23
+ })
24
+
25
+
26
+ def test_seed_iteration():
27
+ cfg = make_cfg()
28
+ es = EnvStateManager(cfg, mode='train')
29
+ es.reset()
30
+ first_seed = es.envs[0]['status'].seed
31
+ es.reset()
32
+ second_seed = es.envs[0]['status'].seed
33
+ assert first_seed == 7
34
+ assert second_seed == 8
tests/llm_agent/test_context_window.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from ragen.llm_agent.ctx_manager import ContextManager
3
+ from omegaconf import OmegaConf
4
+ from verl.verl.protocol import DataProto
5
+
6
+ class DummyTokenizer:
7
+ name_or_path = "qwen" # or "llama-3" or any string your code expects
8
+
9
+ def apply_chat_template(self, messages, add_generation_prompt, tokenize):
10
+ return " ".join([msg["content"] for msg in messages])
11
+
12
+ def __call__(self, texts, return_tensors, padding, padding_side, truncation):
13
+ import torch
14
+ class DummyOutput:
15
+ input_ids = torch.tensor([[1, 2, 3]])
16
+ attention_mask = torch.tensor([[1, 1, 1]])
17
+ return DummyOutput()
18
+
19
+ def encode(self, text):
20
+ # Return a dummy list of token ids; must be at least length 1 for [0] indexing
21
+ return [42, 43]
22
+
23
+ @pytest.fixture
24
+ def dummy_config():
25
+ cfg = OmegaConf.create({
26
+ "agent_proxy": {
27
+ "max_context_window": 2,
28
+ "enable_think": False,
29
+ "use_turn_scores": False,
30
+ "action_sep": "|",
31
+ "reward_normalization": {
32
+ "grouping": "batch",
33
+ "method": "identity"
34
+ }
35
+ },
36
+ "enable_response_mask": False,
37
+ "es_manager": {
38
+ "train": {
39
+ "env_configs": {
40
+ "n_groups": [1],
41
+ "tags": ["sokoban"]
42
+ },
43
+ "group_size": 1
44
+ }
45
+ },
46
+ "custom_envs": {
47
+ "sokoban": {
48
+ "env_type": "sokoban",
49
+ "max_actions_per_traj": 10
50
+ }
51
+ },
52
+ "actor_rollout_ref": {
53
+ "rollout": {
54
+ "response_length": 128
55
+ }
56
+ }
57
+ })
58
+ return cfg
59
+
60
+ def test_context_window_truncation(dummy_config):
61
+ tokenizer = DummyTokenizer()
62
+ ctx = ContextManager(config=dummy_config, tokenizer=tokenizer, mode="train")
63
+ ctx.prefix_lookup = {0: "Initial prompt"}
64
+ ctx.env_config_lookup = {0: {"max_tokens": 128}}
65
+ ctx.env_nums = {"": 1} # For metrics
66
+
67
+ env_outputs = [{
68
+ "env_id": 0,
69
+ "group_id": 0,
70
+ "history": [
71
+ {"state": "S1", "llm_response": "R1", "reward": 0.1, "actions_left": 5},
72
+ {"state": "S2", "llm_response": "R2", "reward": 0.2, "actions_left": 4},
73
+ {"state": "S3", "llm_response": "R3", "reward": 0.3, "actions_left": 3},
74
+ ],
75
+ "metrics": {},
76
+ }]
77
+
78
+ lm_inputs: DataProto = ctx.get_lm_inputs(env_outputs, prepare_for_update=True)
79
+ messages = lm_inputs.non_tensor_batch["messages_list"][0]
80
+
81
+ # Ensure only last 2 turns are present
82
+ assert "S1" not in str(messages)
83
+ assert "S2" in str(messages)
84
+ assert "S3" in str(messages)
tests/test_rollout_filter.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import types
3
+
4
+ import numpy as np
5
+ import torch
6
+ from tensordict import TensorDict
7
+
8
+
9
+ if "verl" not in sys.modules:
10
+ stub = types.ModuleType("verl")
11
+
12
+ class DummyDataProto:
13
+ def __init__(self, batch=None, non_tensor_batch=None, meta_info=None):
14
+ self.batch = batch
15
+ self.non_tensor_batch = non_tensor_batch or {}
16
+ self.meta_info = meta_info or {}
17
+
18
+ def union(self, other):
19
+ if other.batch is not None:
20
+ for key, value in other.batch.items():
21
+ self.batch[key] = value
22
+ if other.non_tensor_batch:
23
+ self.non_tensor_batch.update(other.non_tensor_batch)
24
+ if other.meta_info:
25
+ self.meta_info.update(other.meta_info)
26
+ return self
27
+
28
+ stub.DataProto = DummyDataProto
29
+ sys.modules["verl"] = stub
30
+
31
+
32
+ from ragen.trainer.rollout_filter import (
33
+ RolloutFilterConfig,
34
+ RewardRolloutFilter,
35
+ EntropyRolloutFilter,
36
+ )
37
+
38
+
39
+ def _make_reward_batch(num_groups: int, group_size: int, traj_len: int):
40
+ total = num_groups * group_size
41
+ rm_scores = torch.arange(total * traj_len, dtype=torch.float32).reshape(total, traj_len)
42
+ loss_mask = torch.ones(total, traj_len)
43
+ batch = TensorDict(
44
+ {
45
+ "original_rm_scores": rm_scores,
46
+ "loss_mask": loss_mask,
47
+ },
48
+ batch_size=[total],
49
+ )
50
+ non_tensor_batch = {"uids": np.arange(total)}
51
+ return sys.modules["verl"].DataProto(batch=batch, non_tensor_batch=non_tensor_batch, meta_info={})
52
+
53
+
54
+ def test_reward_variance_filter_reduces_batch_size():
55
+ num_groups, group_size, traj_len = 4, 2, 3
56
+ batch = _make_reward_batch(num_groups, group_size, traj_len)
57
+
58
+ rollout_filter = RewardRolloutFilter(
59
+ RolloutFilterConfig(
60
+ ratio=0.5,
61
+ filter_type="largest",
62
+ num_groups=num_groups,
63
+ group_size=group_size,
64
+ )
65
+ )
66
+
67
+ filtered_batch, metrics = rollout_filter.filter(batch)
68
+
69
+ assert filtered_batch.batch["original_rm_scores"].shape[0] == group_size * max(int(0.5 * num_groups), 1)
70
+ assert "rollout/in_group_std" in metrics
71
+
72
+
73
+ def test_entropy_variance_filter_uses_compute_log_prob():
74
+ num_groups, group_size, traj_len = 2, 3, 4
75
+ batch = _make_reward_batch(num_groups, group_size, traj_len)
76
+
77
+ entropies = torch.linspace(0.1, 1.0, steps=num_groups * group_size * traj_len).reshape(num_groups * group_size, traj_len)
78
+ old_log_probs = -entropies
79
+
80
+ def fake_compute_log_prob(data_proto):
81
+ td = TensorDict(
82
+ {
83
+ "old_log_probs": old_log_probs,
84
+ "entropys": entropies,
85
+ },
86
+ batch_size=[num_groups * group_size],
87
+ )
88
+ return sys.modules["verl"].DataProto(batch=td, non_tensor_batch={}, meta_info={})
89
+
90
+ rollout_filter = EntropyRolloutFilter(
91
+ RolloutFilterConfig(
92
+ ratio=0.5,
93
+ filter_type="largest",
94
+ num_groups=num_groups,
95
+ group_size=group_size,
96
+ metric="entropy",
97
+ ),
98
+ compute_log_prob=fake_compute_log_prob,
99
+ )
100
+
101
+ filtered_batch, metrics = rollout_filter.filter(batch)
102
+
103
+ expected = group_size * max(int(0.5 * num_groups), 1)
104
+ assert filtered_batch.batch["loss_mask"].shape[0] == expected
105
+ assert "old_log_probs" in filtered_batch.batch.keys()
106
+ assert "rollout/in_group_entropy_std" in metrics
107
+
108
+
109
+ def test_reward_metric_selects_high_mean_group():
110
+ num_groups, group_size, traj_len = 2, 2, 1
111
+ batch = _make_reward_batch(num_groups, group_size, traj_len)
112
+
113
+ # Overwrite scores: first group has higher mean, second has higher variance.
114
+ batch.batch["original_rm_scores"] = torch.tensor(
115
+ [
116
+ [10.0],
117
+ [11.0],
118
+ [0.0],
119
+ [5.0],
120
+ ]
121
+ )
122
+
123
+ rollout_filter = RewardRolloutFilter(
124
+ RolloutFilterConfig(
125
+ ratio=0.5,
126
+ filter_type="largest",
127
+ num_groups=num_groups,
128
+ group_size=group_size,
129
+ metric="reward",
130
+ )
131
+ )
132
+
133
+ filtered_batch, _ = rollout_filter.filter(batch)
134
+
135
+ # Highest mean group is the first one, so we expect its entries to remain.
136
+ retained = filtered_batch.batch["original_rm_scores"].squeeze(-1)
137
+ assert torch.allclose(retained, torch.tensor([10.0, 11.0]))
verl/.gemini/config.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ have_fun: false
2
+ code_review:
3
+ disable: false
4
+ comment_severity_threshold: HIGH
5
+ max_review_comments: -1
6
+ pull_request_opened:
7
+ help: false
8
+ summary: false
9
+ code_review: true
10
+ ignore_patterns: []
verl/.github/CODEOWNERS ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /docs @eric-haibin-lin @zhaochenyang20 @hongpeng-guo
2
+ /docs/amd_tutorial @yushengsu-thu
3
+ /docs/slang_multiturn @zhaochenyang20 @SwordFaith
4
+ /docs/ascend_tutorial @FightingZhen
5
+
6
+ /recipe/dapo @tongyx361 @PeterSH6 @vermouth1992 @tardis-key @FightingZhen @ji-huazhong
7
+ /recipe/spin @zhaochenyang20
8
+ /recipe/sppo @zhaochenyang20
9
+
10
+ /third_party/sglang @zhaochenyang20 @SwordFaith
11
+ /third_party/vllm @PeterSH6 @wuxibin89
12
+
13
+ /examples/grpo_trainer @vermouth1992 @PeterSH6 @tardis-key @FightingZhen @ji-huazhong
14
+
15
+ /verl/single_controller @zw0610 @wuxibin89 @hongpeng-guo
16
+ /verl/trainer @eric-haibin-lin @vermouth1992 @tongyx361 @PeterSH6
17
+ /verl/models/mcore @ISEEKYAN @vermouth1992
18
+ /verl/models/transformers @vermouth1992 @PeterSH6 @tardis-key @FightingZhen @ji-huazhong
19
+ /verl/workers/engine @eric-haibin-lin @vermouth1992 @ZihengJiang
20
+ /verl/workers/roles @eric-haibin-lin @vermouth1992 @ZihengJiang
21
+ /verl/workers/engine/fsdp @eric-haibin-lin @vermouth1992 @ZihengJiang
22
+ /verl/workers/rollout/vllm_rollout @wuxibin89 @PeterSH6 @chenhaiq
23
+ /verl/workers/rollout/sglang_rollout @zhaochenyang20 @SwordFaith @chenhaiq
24
+ /verl/workers/actor/megatron_actor.py @ISEEKYAN @vermouth1992
25
+ /verl/workers/critic/megatron_critic.py @ISEEKYAN @vermouth1992
26
+ /verl/workers/megatron_workers.py @ISEEKYAN @vermouth1992
27
+
28
+ /tests/single_controller @zw0610 @wuxibin89
29
+ /tests/trainer @eric-haibin-lin @vermouth1992 @tongyx361 @PeterSH6
30
+ /tests/workers/rollout/vllm_rollout @wuxibin89 @PeterSH6 @chenhaiq
verl/.github/ISSUE_TEMPLATE/bug-report.yml ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/huggingface/transformers/blob/main/.github/ISSUE_TEMPLATE/bug-report.yml?plain=1
2
+ name: "\U0001F41B Bug Report"
3
+ description: Submit a bug report to help us improve verl
4
+ labels: [ "bug" ]
5
+ body:
6
+ - type: markdown
7
+ attributes:
8
+ value: |
9
+ Thanks for taking the time to fill out this bug report! 🤗
10
+
11
+ - type: textarea
12
+ id: system-info
13
+ attributes:
14
+ label: System Info
15
+ description: Please share your system info with us. You can run the command `python scripts/diagnose.py` and copy-paste its output below.
16
+ placeholder: verl version, platform, python version, ...
17
+ validations:
18
+ required: true
19
+
20
+ - type: checkboxes
21
+ id: information-scripts-examples
22
+ attributes:
23
+ label: Information
24
+ description: 'The problem arises when using:'
25
+ options:
26
+ - label: "The official example scripts"
27
+ - label: "My own modified scripts"
28
+
29
+ - type: checkboxes
30
+ id: information-tasks
31
+ attributes:
32
+ label: Tasks
33
+ description: "The tasks I am working on are:"
34
+ options:
35
+ - label: "An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)"
36
+ - label: "My own task or dataset (give details below)"
37
+
38
+ - type: textarea
39
+ id: reproduction
40
+ validations:
41
+ required: true
42
+ attributes:
43
+ label: Reproduction
44
+ description: |
45
+ Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet.
46
+ Please include relevant config information with your code.
47
+ If you have code snippets, error messages, stack traces please provide them here as well.
48
+ 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
49
+ Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code.
50
+
51
+ placeholder: |
52
+ Steps to reproduce the behavior:
53
+
54
+ 1.
55
+ 2.
56
+ 3.
57
+
58
+
59
+ - type: textarea
60
+ id: expected-behavior
61
+ validations:
62
+ required: true
63
+ attributes:
64
+ label: Expected behavior
65
+ description: "A clear and concise description of what you would expect to happen."
verl/.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ blank_issues_enabled: true
2
+ version: 0.1
verl/.github/ISSUE_TEMPLATE/feature-request.yml ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/huggingface/transformers/blob/main/.github/ISSUE_TEMPLATE/feature-request.yml?plain=1
2
+ name: "\U0001F680 Feature request"
3
+ description: Submit a proposal/request for a new verl feature
4
+ labels: [ "Feature request" ]
5
+ body:
6
+ - type: textarea
7
+ id: feature-request
8
+ validations:
9
+ required: true
10
+ attributes:
11
+ label: Feature request
12
+ description: |
13
+ A clear and concise description of the feature proposal. Please provide a link to the paper and code in case they exist.
14
+
15
+ - type: textarea
16
+ id: motivation
17
+ validations:
18
+ required: true
19
+ attributes:
20
+ label: Motivation
21
+ description: |
22
+ 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.
23
+
24
+
25
+ - type: textarea
26
+ id: contribution
27
+ validations:
28
+ required: true
29
+ attributes:
30
+ label: Your contribution
31
+ description: |
32
+ 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)
verl/.github/PULL_REQUEST_TEMPLATE.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### What does this PR do?
2
+
3
+ > Add **concise** overview of what this PR aims to achieve or accomplish. Reference related GitHub issues and PRs that help with the review.
4
+
5
+ ### Checklist Before Starting
6
+
7
+ - [ ] Search for similar PRs. Paste at least one query link here: ...
8
+ - [ ] Format the PR title as `[{modules}] {type}: {description}` (This will be checked by the CI)
9
+ - `{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`
10
+ - If this PR involves multiple modules, separate them with `,` like `[megatron, fsdp, doc]`
11
+ - `{type}` is in `feat`, `fix`, `refactor`, `chore`, `test`
12
+ - If this PR breaks any API (CLI arguments, config, function signature, etc.), add `[BREAKING]` to the beginning of the title.
13
+ - Example: `[BREAKING][fsdp, megatron] feat: dynamic batching`
14
+
15
+ ### Test
16
+
17
+ > 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.
18
+
19
+ ### API and Usage Example
20
+
21
+ > Demonstrate how the API changes if any, and provide usage example(s) if possible.
22
+
23
+ ```python
24
+ # Add code snippet or script demonstrating how to use this
25
+ ```
26
+
27
+ ### Design & Code Changes
28
+
29
+ > Demonstrate the high-level design if this PR is complex, and list the specific changes.
30
+
31
+ ### Checklist Before Submitting
32
+
33
+ > [!IMPORTANT]
34
+ > Please check all the following items before requesting a review, otherwise the reviewer might deprioritize this PR for review.
35
+
36
+ - [ ] Read the [Contribute Guide](https://github.com/volcengine/verl/blob/main/CONTRIBUTING.md).
37
+ - [ ] 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`
38
+ - [ ] Add / Update [the documentation](https://github.com/volcengine/verl/tree/main/docs).
39
+ - [ ] 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: ...
40
+ - [ ] 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).)
verl/.github/dependabot.yml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ## Enabled the dependabot to check the dependencies of the project
2
+ ## Dependabot will open pull requests to update dependencies automatically
3
+
4
+ version: 2
5
+ updates:
6
+ - package-ecosystem: pip
7
+ directory: "/"
8
+ schedule:
9
+ interval: weekly
verl/.github/workflows/.deprecate/e2e_eval_aime24.yml ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+
33
+ name: e2e_eval_aime24
34
+
35
+ on:
36
+ # Trigger the workflow on push or pull request,
37
+ # but only for the main branch
38
+ # For push, for now only anti-patterns are specified so it is more conservative
39
+ # and achieves higher coverage.
40
+ push:
41
+ branches:
42
+ - main
43
+ - v0.*
44
+ paths:
45
+ - "**/*.py"
46
+ # Other entrypoints
47
+ - "!*.md"
48
+ - "!docker/**"
49
+ - "!docs/**"
50
+ - "!examples/**"
51
+ - "!tests/**"
52
+ - "!verl/trainer/main_*.py"
53
+ - "!verl/trainer/fsdp_sft_trainer.py"
54
+ - "!recipe/**"
55
+ - "recipe/r1"
56
+ - "!recipe/r1/README.md"
57
+ pull_request:
58
+ branches:
59
+ - main
60
+ paths:
61
+ - "**/*.py"
62
+ # Other entrypoints
63
+ - "!*.md"
64
+ - "!docker/**"
65
+ - "!docs/**"
66
+ - "!examples/**"
67
+ - "!tests/**"
68
+ - "!verl/trainer/main_*.py"
69
+ - "!verl/trainer/fsdp_sft_trainer.py"
70
+ # Home
71
+ - "recipe/r1"
72
+ - "!recipe/r1/README.md"
73
+ # Other recipes
74
+ - "!recipe/**"
75
+ # Entrypoints
76
+ - ".github/workflows/e2e_eval_aime24.yml"
77
+ - "tests/special_e2e/run_r1_distill_qwen_aime24_eval.sh"
78
+ - "verl/trainer/main_generation.py"
79
+ - "verl/trainer/config/generation.yaml"
80
+
81
+ # Cancel jobs on the same ref if a new one is triggered
82
+ concurrency:
83
+ group: ${{ github.workflow }}-${{ github.ref }}
84
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
85
+
86
+ # Declare permissions just read content.
87
+ permissions:
88
+ contents: read
89
+
90
+ env:
91
+ IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2"
92
+ DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner"
93
+
94
+ jobs:
95
+ setup:
96
+ if: github.repository_owner == 'volcengine'
97
+ runs-on: ubuntu-latest
98
+ outputs:
99
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
100
+ mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }}
101
+ steps:
102
+ - uses: actions/checkout@v4
103
+ - id: create-runner
104
+ uses: volcengine/vemlp-github-runner@v1
105
+ with:
106
+ mode: "create"
107
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
108
+ mlp-image: "${{ env.IMAGE }}"
109
+
110
+ e2e_eval_aime24:
111
+ needs: setup
112
+ runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"]
113
+ timeout-minutes: 40 # Increase this timeout value as needed
114
+ env:
115
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
116
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
117
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
118
+ HF_ENDPOINT: "https://hf-mirror.com"
119
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
120
+ steps:
121
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
122
+ with:
123
+ fetch-depth: 0
124
+ - name: Install the current repository
125
+ run: |
126
+ pip3 install --no-deps -e .[test,gpu,math]
127
+ pip3 install math-verify transformers==4.56.2
128
+ - name: Prepare aime24 dataset
129
+ run: |
130
+ ray stop --force
131
+ python3 recipe/r1/data_process.py --task aime2024
132
+ - name: Running generation and evaluation in AIME 2024
133
+ run: |
134
+ ray stop --force
135
+ bash tests/special_e2e/run_r1_distill_qwen_aime24_eval.sh
136
+
137
+ cleanup:
138
+ runs-on: ubuntu-latest
139
+ needs: [setup, e2e_eval_aime24]
140
+ if: always()
141
+ steps:
142
+ - id: destroy-runner
143
+ uses: volcengine/vemlp-github-runner@v1
144
+ with:
145
+ mode: "destroy"
146
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
147
+ mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}"
verl/.github/workflows/.deprecate/e2e_ppo_trainer.yml ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: e2e_ppo_trainer_deprecate
2
+
3
+ on:
4
+ # Trigger the workflow on push or pull request,
5
+ # but only for the main branch
6
+ # For push, for now only anti-patterns are specified so it is more conservative
7
+ # and achieves higher coverage.
8
+ push:
9
+ branches:
10
+ - disabled_ci
11
+ pull_request:
12
+ branches:
13
+ - disabled_ci
14
+ paths:
15
+ - "**/*.py"
16
+ # Other entrypoints
17
+ - "!**/*.md"
18
+ - "!docker/**"
19
+ - "!examples/**"
20
+ - "!tests/**"
21
+ - "!verl/trainer/main_*.py"
22
+ - "!verl/trainer/fsdp_sft_trainer.py"
23
+ # Docs
24
+ - "!docs/**"
25
+ # Recipes
26
+ - "!recipe/**"
27
+ # Megatron
28
+ - "!verl/workers/**/megatron_*.py"
29
+ # Entrypoints
30
+ - ".github/workflows/e2e_ppo_trainer.yml"
31
+ - "examples/data_preprocess/gsm8k.py"
32
+ - "examples/data_preprocess/geo3k.py"
33
+ - "tests/special_e2e/ppo_trainer"
34
+ - "verl/trainer/main_ppo.py"
35
+ - "verl/trainer/config/ppo_trainer.yaml"
36
+
37
+ # Cancel jobs on the same ref if a new one is triggered
38
+ concurrency:
39
+ group: ${{ github.workflow }}-${{ github.ref }}
40
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
41
+
42
+ # Declare permissions just read content.
43
+ permissions:
44
+ contents: read
45
+
46
+ jobs:
47
+ pre_commit_for_ppo:
48
+ runs-on: ubuntu-latest
49
+ strategy:
50
+ matrix:
51
+ python-version: ["3.12"]
52
+ steps:
53
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
54
+ - name: Set up Python ${{ matrix.python-version }}
55
+ uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0
56
+ with:
57
+ python-version: ${{ matrix.python-version }}
58
+ - name: Install the current repository
59
+ run: |
60
+ pip install -e .
61
+ - name: Set ruff --output-format=github
62
+ run: |
63
+ sed -i 's/--output-format=full/--output-format=github/' .pre-commit-config.yaml
64
+ git add .pre-commit-config.yaml
65
+ - uses: pre-commit/action@v3.0.1
66
+ with:
67
+ extra_args: "" # Overriding default "--all-files"
68
+
69
+ e2e_ppo_trainer_sglang_multiturn_with_tool:
70
+ runs-on: [L20x8]
71
+ needs: pre_commit_for_ppo
72
+ timeout-minutes: 40 # Increase this timeout value as needed
73
+ env:
74
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
75
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
76
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
77
+ HF_ENDPOINT: "https://hf-mirror.com"
78
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
79
+ container:
80
+ image: verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2
81
+ options: --gpus all --shm-size=10g
82
+ steps:
83
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
84
+ with:
85
+ fetch-depth: 0
86
+ - name: Install the current repository
87
+ run: |
88
+ pip3 install -e .[test,gpu,sglang]
89
+ - name: Prepare gsm8k dataset with tool
90
+ run: |
91
+ ray stop --force
92
+ python3 examples/data_preprocess/gsm8k_multiturn_w_tool.py --local_save_dir $HOME/data/gsm8k_verl_sgl_multi_turn_preprocessed
93
+ - name: Running GSM8K with tool E2E training tests on 8 L20 GPUs with rmpad using function rm and save ckpt with sglang
94
+ run: |
95
+ ray stop --force
96
+ bash tests/special_e2e/run_gsm8k_fsdp_sgl_multiturn_w_tool.sh
97
+ - name: Running GSM8K with tool E2E training tests with FSDP2
98
+ run: |
99
+ ray stop --force
100
+ FSDP_STRATEGY=fsdp2 bash tests/special_e2e/run_gsm8k_fsdp_sgl_multiturn_w_tool.sh
101
+
102
+ e2e_ppo_trainer_sglang_vlm_multiturn_with_tool:
103
+ runs-on: [L20x8]
104
+ needs: pre_commit_for_ppo
105
+ timeout-minutes: 40 # Increase this timeout value as needed
106
+ env:
107
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
108
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
109
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
110
+ HF_ENDPOINT: "https://hf-mirror.com"
111
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
112
+ container:
113
+ image: verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2
114
+ options: --gpus all --shm-size=10g
115
+ steps:
116
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
117
+ with:
118
+ fetch-depth: 0
119
+ - name: Install the current repository
120
+ run: |
121
+ pip3 install -e .[test,geo,gpu,sglang]
122
+ - name: Prepare geo3k dataset with tool
123
+ run: |
124
+ ray stop --force
125
+ python3 examples/data_preprocess/geo3k_multiturn_w_tool.py --local_dir $HOME/data/geo3k_verl_sgl_multi_turn_preprocessed
126
+ - name: Running GEO3K with tool E2E training tests on 8 L20 GPUs with rmpad using function rm and save ckpt with sglang
127
+ run: |
128
+ ray stop --force
129
+ bash tests/special_e2e/run_geo3k_fsdp_sgl_multiturn_w_tool.sh
130
+ - name: Running GEO3K with tool E2E training tests with FSDP2
131
+ run: |
132
+ ray stop --force
133
+ FSDP_STRATEGY=fsdp2 bash tests/special_e2e/run_geo3k_fsdp_sgl_multiturn_w_tool.sh
verl/.github/workflows/.deprecate/e2e_ppo_trainer_megatron_sglang.yml ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+ name: e2e_ppo_trainer_megatron_sglang_deprecate
33
+
34
+ on:
35
+ # Trigger the workflow on push or pull request,
36
+ # but only for the main branch.
37
+ # For push, for now only anti-patterns are specified so it is more conservative
38
+ # and achieves higher coverage.
39
+ push:
40
+ branches:
41
+ - disabled_ci
42
+ pull_request:
43
+ branches:
44
+ - disabled_ci
45
+ paths:
46
+ - "**/*.py"
47
+ # Other entrypoints
48
+ - "!docker/**"
49
+ # Docs
50
+ - "!**/*.md"
51
+ - "!docs/**"
52
+ - "!examples/**"
53
+ - "!tests/**"
54
+ - "!verl/trainer/main_*.py"
55
+ - "!verl/trainer/fsdp_sft_trainer.py"
56
+ # Recipes
57
+ - "!recipe/**"
58
+ # FSDP
59
+ - "!verl/workers/**/*dp_*.py"
60
+ # Entrypoints
61
+ - ".github/workflows/e2e_ppo_trainer_megatron_sglang.yml"
62
+ - "examples/data_preprocess/gsm8k.py"
63
+ - "examples/data_preprocess/geo3k.py"
64
+ - "tests/special_e2e/run_ppo_trainer_megatron.sh"
65
+ - "verl/trainer/main_ppo.py"
66
+ - "verl/trainer/config/ppo_megatron_trainer.yaml"
67
+
68
+ # Cancel jobs on the same ref if a new one is triggered
69
+ concurrency:
70
+ group: ${{ github.workflow }}-${{ github.ref }}
71
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
72
+
73
+ # Declare permissions just read content.
74
+ permissions:
75
+ contents: read
76
+
77
+ env:
78
+ IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2"
79
+ DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner"
80
+
81
+ jobs:
82
+ setup:
83
+ if: github.repository_owner == 'volcengine'
84
+ runs-on: ubuntu-latest
85
+ outputs:
86
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
87
+ mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }}
88
+ steps:
89
+ - uses: actions/checkout@v4
90
+ - id: create-runner
91
+ uses: volcengine/vemlp-github-runner@v1
92
+ with:
93
+ mode: "create"
94
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
95
+ mlp-image: "${{ env.IMAGE }}"
96
+
97
+ e2e_ppo_trainer_megatron-qwen3:
98
+ needs: setup
99
+ runs-on: ["${{ needs.setup.outputs.runner-label || 'L20x8' }}"]
100
+ timeout-minutes: 60 # Increase this timeout value as needed
101
+ env:
102
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
103
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
104
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
105
+ HF_ENDPOINT: "https://hf-mirror.com"
106
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
107
+ steps:
108
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
109
+ with:
110
+ fetch-depth: 0
111
+ - name: Install the current repository
112
+ run: |
113
+ pip3 install --no-deps -e .[test]
114
+ - name: Prepare GSM8K dataset
115
+ run: |
116
+ python3 examples/data_preprocess/gsm8k.py
117
+ - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen3) with validation and saving
118
+ run: |
119
+ ray stop --force
120
+ 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
121
+ - name: Running GSM8K E2E training tests with 3D parallelism on 8 L20 GPUs with Megatron (Qwen3) testing learning rate scheduler
122
+ run: |
123
+ ray stop --force
124
+ 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
125
+
126
+ - name: Test Megatron checkpoints merging function (Qwen3 Actor and Critic)
127
+ run: |
128
+ exp_name="qwen3-0.6b-megatron-gsm8k-minimal"
129
+ 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
130
+ 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
131
+ - name: clean up
132
+ run: |
133
+ rm -rf checkpoints
134
+
135
+ cleanup:
136
+ runs-on: ubuntu-latest
137
+ needs:
138
+ [
139
+ setup,
140
+ e2e_ppo_trainer_megatron-deepseek,
141
+ e2e_ppo_trainer_megatron-qwen3,
142
+ e2e_ppo_trainer_megatron-different-train-infer-tp-qwen-tie-embedding,
143
+ e2e_ppo_trainer_megatron-qwen-override-transformer-config,
144
+ e2e_ppo_trainer_megatron-deepseek-override-transformer-config,
145
+ e2e_ppo_trainer_megatron-moe-expert-parallel,
146
+ e2e_ppo_trainer_megatron-qwen2_5vl-3b,
147
+ ]
148
+ if: always()
149
+ steps:
150
+ - id: destroy-runner
151
+ uses: volcengine/vemlp-github-runner@v1
152
+ with:
153
+ mode: "destroy"
154
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
155
+ mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}"
verl/.github/workflows/.deprecate/e2e_prime.yml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: e2e_prime_deprecate
2
+
3
+ on:
4
+ # Trigger the workflow on push or pull request,
5
+ # but only for the main branch
6
+ push:
7
+ branches:
8
+ - disabled_ci
9
+ pull_request:
10
+ branches:
11
+ - disabled_ci
12
+ paths:
13
+ - "**/*.py"
14
+ # Other entrypoints
15
+ - "!examples/**"
16
+ - "!tests/**"
17
+ - "!verl/trainer/main_*.py"
18
+ - "!verl/trainer/fsdp_sft_trainer.py"
19
+ # Other recipes
20
+ - "!recipe/**"
21
+ # Megatron
22
+ - "!verl/workers/**/megatron_*.py"
23
+ # Home
24
+ - "recipe/prime"
25
+ # Entrypoints
26
+ - ".github/workflows/e2e_prime.yml"
27
+ - "examples/data_preprocess/gsm8k.py"
28
+ - "tests/special_e2e/run_prime.sh"
29
+
30
+ # Cancel jobs on the same ref if a new one is triggered
31
+ concurrency:
32
+ group: ${{ github.workflow }}-${{ github.ref }}
33
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
34
+
35
+ # Declare permissions just read content.
36
+ permissions:
37
+ contents: read
38
+
39
+ jobs:
40
+ e2e_prime:
41
+ runs-on: [L20x8]
42
+ timeout-minutes: 50 # Increase this timeout value as needed
43
+ env:
44
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
45
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
46
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
47
+ HF_ENDPOINT: "https://hf-mirror.com"
48
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
49
+ container:
50
+ image: whatcanyousee/verl:ngc-cu124-vllm0.8.5-sglang0.4.6.post5-mcore0.12.0-te2.3
51
+ options: --gpus all --shm-size=10g
52
+ steps:
53
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
54
+ with:
55
+ fetch-depth: 0
56
+ - name: Install the current repository
57
+ run: |
58
+ pip3 install --no-deps -e .[test,gpu]
59
+ - name: Prepare gsm8k dataset
60
+ run: |
61
+ ray stop --force
62
+ python3 examples/data_preprocess/gsm8k.py
63
+ - name: Running GSM8K E2E with prime alg
64
+ run: |
65
+ ray stop --force
66
+ bash tests/special_e2e/run_prime.sh
verl/.github/workflows/.deprecate/e2e_spin.yml ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: e2e_spin
2
+
3
+ on:
4
+ # Trigger the workflow on push or pull request,
5
+ # but only for the main branch
6
+ push:
7
+ branches:
8
+ - main
9
+ - v0.*
10
+ paths:
11
+ - "**/*.py"
12
+ # Other entrypoints
13
+ - "!examples/**"
14
+ - "!tests/**"
15
+ - "!verl/trainer/main_*.py"
16
+ - "!verl/trainer/fsdp_sft_trainer.py"
17
+ # Other recipes
18
+ - "!recipe/**"
19
+ # Megatron
20
+ - "!verl/workers/**/megatron_*.py"
21
+ # Home
22
+ - "recipe/spin"
23
+ # Entrypoints
24
+ - ".github/workflows/e2e_spin.yml"
25
+ - "examples/data_preprocess/gsm8k.py"
26
+ - "tests/special_e2e/run_spin.sh"
27
+ - "!examples"
28
+ pull_request:
29
+ branches:
30
+ - main
31
+ - v0.*
32
+ paths:
33
+ - "**/*.py"
34
+ # Other entrypoints
35
+ - "!examples/**"
36
+ - "!tests/**"
37
+ - "!verl/trainer/main_*.py"
38
+ - "!verl/trainer/fsdp_sft_trainer.py"
39
+ # Other recipes
40
+ - "!recipe/**"
41
+ # Megatron
42
+ - "!verl/workers/**/megatron_*.py"
43
+ # Home
44
+ - "recipe/spin"
45
+ # Entrypoints
46
+ - ".github/workflows/e2e_spin.yml"
47
+ - "examples/data_preprocess/gsm8k.py"
48
+ - "tests/special_e2e/run_spin.sh"
49
+ - "!examples"
50
+
51
+ # Declare permissions just read content.
52
+ permissions:
53
+ contents: read
54
+
55
+ env:
56
+ IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2"
57
+ DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner"
58
+
59
+ # Cancel jobs on the same ref if a new one is triggered
60
+ concurrency:
61
+ group: ${{ github.workflow }}-${{ github.ref }}
62
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
63
+
64
+ jobs:
65
+ setup:
66
+ if: github.repository_owner == 'volcengine'
67
+ runs-on: ubuntu-latest
68
+ outputs:
69
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
70
+ mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }}
71
+ steps:
72
+ - uses: actions/checkout@v4
73
+ - id: create-runner
74
+ uses: volcengine/vemlp-github-runner@v1
75
+ with:
76
+ mode: "create"
77
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
78
+ mlp-image: "${{ env.IMAGE }}"
79
+
80
+ e2e_spin:
81
+ needs: setup
82
+ runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ]
83
+ timeout-minutes: 40 # Increase this timeout value as needed
84
+ env:
85
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
86
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
87
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
88
+ HF_ENDPOINT: "https://hf-mirror.com"
89
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
90
+ steps:
91
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
92
+ with:
93
+ fetch-depth: 0
94
+ - name: Install the current repository
95
+ run: |
96
+ pip3 install -e .[test,gpu,sglang]
97
+ - name: Prepare GSM8K dataset
98
+ run: |
99
+ python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k
100
+ - name: Running the E2E test with the spin algorithm
101
+ run: |
102
+ ray stop --force
103
+ bash tests/special_e2e/run_spin.sh
104
+
105
+ cleanup:
106
+ runs-on: ubuntu-latest
107
+ needs:
108
+ [
109
+ setup,
110
+ e2e_spin
111
+ ]
112
+ if: always()
113
+ steps:
114
+ - id: destroy-runner
115
+ uses: volcengine/vemlp-github-runner@v1
116
+ with:
117
+ mode: "destroy"
118
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
119
+ mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}"
verl/.github/workflows/.deprecate/e2e_sppo.yml ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: e2e_sppo
2
+
3
+ on:
4
+ # Trigger the workflow on push or pull request,
5
+ # but only for the main branch
6
+ push:
7
+ branches:
8
+ - main
9
+ - v0.*
10
+ paths:
11
+ - "**/*.py"
12
+ # Other entrypoints
13
+ - "!examples/**"
14
+ - "!tests/**"
15
+ - "!verl/trainer/main_*.py"
16
+ - "!verl/trainer/fsdp_sft_trainer.py"
17
+ # Other recipes
18
+ - "!recipe/**"
19
+ # Megatron
20
+ - "!verl/workers/**/megatron_*.py"
21
+ # Home
22
+ - "recipe/sppo"
23
+ # Entrypoints
24
+ - ".github/workflows/e2e_sppo.yml"
25
+ - "examples/data_preprocess/gsm8k.py"
26
+ - "tests/special_e2e/run_sppo.sh"
27
+ pull_request:
28
+ branches:
29
+ - main
30
+ - v0.*
31
+ paths:
32
+ - "**/*.py"
33
+ # Other entrypoints
34
+ - "!examples/**"
35
+ - "!tests/**"
36
+ - "!verl/trainer/main_*.py"
37
+ - "!verl/trainer/fsdp_sft_trainer.py"
38
+ # Other recipes
39
+ - "!recipe/**"
40
+ # Megatron
41
+ - "!verl/workers/**/megatron_*.py"
42
+ # Home
43
+ - "recipe/sppo"
44
+ # Entrypoints
45
+ - ".github/workflows/e2e_sppo.yml"
46
+ - "examples/data_preprocess/gsm8k.py"
47
+ - "tests/special_e2e/run_sppo.sh"
48
+
49
+ # Declare permissions just read content.
50
+ permissions:
51
+ contents: read
52
+
53
+ # Cancel jobs on the same ref if a new one is triggered
54
+ concurrency:
55
+ group: ${{ github.workflow }}-${{ github.ref }}
56
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
57
+
58
+ env:
59
+ IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2"
60
+ DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner"
61
+ TRANSFORMERS_VERSION: "4.56.2"
62
+
63
+ jobs:
64
+ setup:
65
+ if: github.repository_owner == 'volcengine'
66
+ runs-on: ubuntu-latest
67
+ outputs:
68
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
69
+ mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }}
70
+ steps:
71
+ - uses: actions/checkout@v4
72
+ - id: create-runner
73
+ uses: volcengine/vemlp-github-runner@v1
74
+ with:
75
+ mode: "create"
76
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
77
+ mlp-image: "${{ env.IMAGE }}"
78
+
79
+ e2e_sppo:
80
+ needs: setup
81
+ runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ]
82
+ timeout-minutes: 40 # Increase this timeout value as needed
83
+ env:
84
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
85
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
86
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
87
+ HF_ENDPOINT: "https://hf-mirror.com"
88
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
89
+ steps:
90
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
91
+ with:
92
+ fetch-depth: 0
93
+ - name: Install the current repository
94
+ run: |
95
+ pip3 install -e .[test,gpu,sglang]
96
+ - name: Prepare MATH dataset
97
+ run: |
98
+ python3 examples/data_preprocess/math_dataset.py --local_dataset_path $HOME/models/hf_data/DigitalLearningGmbH/MATH-lighteval
99
+ - name: Running the E2E test with the SPPO algorithm
100
+ run: |
101
+ ray stop --force
102
+ bash tests/special_e2e/run_sppo.sh
103
+
104
+ cleanup:
105
+ runs-on: ubuntu-latest
106
+ needs:
107
+ [
108
+ setup,
109
+ e2e_sppo
110
+ ]
111
+ if: always()
112
+ steps:
113
+ - id: destroy-runner
114
+ uses: volcengine/vemlp-github-runner@v1
115
+ with:
116
+ mode: "destroy"
117
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
118
+ mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}"
verl/.github/workflows/README.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Adding a New Workflow
2
+
3
+ When adding a new workflow for continuous integration (CI), you have two runner options: a fixed runner or a machine from the vemlp.
4
+
5
+ - **Fixed Runner**: To use a fixed runner, specify it in your workflow using the `runs-on` keyword, like `runs-on: [L20x8]`.
6
+ - **Vemlp Runner**: Opting for a Vemlp machine allows you to launch tasks elastically.
7
+
8
+ 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`.
9
+
10
+ ```yaml
11
+ name: Your Default Workflow
12
+
13
+ on:
14
+ push:
15
+ branches:
16
+ - main
17
+ - v0.*
18
+ pull_request:
19
+ branches:
20
+ - main
21
+ - v0.*
22
+ paths:
23
+ - "**/*.py"
24
+ - ".github/workflows/template.yml"
25
+
26
+ concurrency:
27
+ group: ${{ github.workflow }}-${{ github.ref }}
28
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
29
+
30
+ permissions:
31
+ contents: read
32
+
33
+ env:
34
+ IMAGE: "your vemlp image" # e.g. "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.4-vllm0.8.5-mcore0.12.2"
35
+ DYNAMIC_RUNNER_URL: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner" # public veFaas api
36
+
37
+ jobs:
38
+ setup:
39
+ if: github.repository_owner == 'volcengine'
40
+ runs-on: ubuntu-latest
41
+ outputs:
42
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
43
+ task-id: ${{ steps.create-runner.outputs.task-id }}
44
+ steps:
45
+ - uses: actions/checkout@v4
46
+ - id: create-runner
47
+ uses: volcengine/vemlp-github-runner@v1
48
+ with:
49
+ mode: "create"
50
+ faas-url: "${{ env.DYNAMIC_RUNNER_URL }}"
51
+ image: "${{ env.DEFAULT_IMAGE }}"
52
+
53
+ your_job:
54
+ needs: setup
55
+ runs-on: ["${{ needs.setup.outputs.runner-label || 'default-runner' }}"]
56
+ steps:
57
+ xxxx # your jobs
58
+
59
+ cleanup:
60
+ runs-on: ubuntu-latest
61
+ needs: [setup, your_job]
62
+ if: always()
63
+ steps:
64
+ - id: destroy-runner
65
+ uses: volcengine/vemlp-github-runner@v1
66
+ with:
67
+ mode: "destroy"
68
+ faas-url: "${{ env.DYNAMIC_RUNNER_URL }}"
69
+ task-id: "${{ needs.setup.outputs.task-id }}"
70
+ ```
71
+
72
+ ### Model and Dataset
73
+ 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.
verl/.github/workflows/check-pr-title.yml ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+
33
+ on:
34
+ pull_request:
35
+ types: [opened, edited, synchronize]
36
+
37
+ jobs:
38
+ check-title:
39
+ runs-on: ubuntu-latest
40
+ steps:
41
+ - name: Checkout code
42
+ uses: actions/checkout@v4
43
+
44
+ - name: Set up Python
45
+ uses: actions/setup-python@v5
46
+ with:
47
+ python-version: '3.11'
48
+
49
+ - name: Run PR title checker
50
+ run: python3 tests/special_sanity/check_pr_title.py
51
+ env:
52
+ PR_TITLE: ${{ github.event.pull_request.title }}
53
+
54
+ - name: Run PR description checker
55
+ run: python3 tests/special_sanity/check_pr_description.py
56
+ env:
57
+ PR_TITLE: ${{ github.event.pull_request.title }}
58
+ GITHUB_EVENT_PATH: ${{ github.event_path }}
verl/.github/workflows/checkpoint_converter.yml ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+ name: checkpoint_converter
33
+ # latest version: Megatron-LM core_r0.11.0 https://github.com/NVIDIA/Megatron-LM/tree/core_r0.11.0
34
+
35
+ on:
36
+ # Trigger the workflow on push or pull request,
37
+ # but only for the main branch
38
+ push:
39
+ branches:
40
+ - main
41
+ - v0.*
42
+ pull_request:
43
+ branches:
44
+ - main
45
+ - v0.*
46
+ paths:
47
+ - "**/*.py"
48
+ # Other entrypoints
49
+ - "!examples/**"
50
+ - "!tests/**"
51
+ - "!verl/trainer/main_*.py"
52
+ - "!verl/trainer/fsdp_sft_trainer.py"
53
+ # Recipes
54
+ - "!recipe/**"
55
+ # FSDP
56
+ - "!verl/workers/**/*dp_*.py"
57
+ # Entrypoints
58
+ - ".github/workflows/checkpoint_converter.yml"
59
+ - ".github/workflows/e2e_ppo_trainer_megatron.yml"
60
+ - "examples/data_preprocess/gsm8k.py"
61
+ - "tests/special_e2e/run_ppo_trainer_megatron.sh"
62
+ - "verl/trainer/main_ppo.py"
63
+ - "verl/trainer/config/ppo_megatron_trainer.yaml"
64
+
65
+ # Cancel jobs on the same ref if a new one is triggered
66
+ concurrency:
67
+ group: ${{ github.workflow }}-${{ github.ref }}
68
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
69
+
70
+ # Declare permissions just read content.
71
+ permissions:
72
+ contents: read
73
+
74
+ env:
75
+ IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.6-transformers4.56.1-sglang0.5.2-mcore0.13.0-te2.2"
76
+ DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner"
77
+
78
+ jobs:
79
+ setup:
80
+ if: github.repository_owner == 'volcengine'
81
+ runs-on: ubuntu-latest
82
+ outputs:
83
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
84
+ mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }}
85
+ steps:
86
+ - uses: actions/checkout@v4
87
+ - id: create-runner
88
+ uses: volcengine/vemlp-github-runner@v1
89
+ with:
90
+ mode: "create"
91
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
92
+ mlp-image: "${{ env.IMAGE }}"
93
+
94
+ checkpoint_converter:
95
+ needs: setup
96
+ runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ]
97
+ timeout-minutes: 20 # Increase this timeout value as needed
98
+ env:
99
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
100
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
101
+ NO_PROXY: "localhost,127.0.0.1"
102
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
103
+ steps:
104
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
105
+ with:
106
+ fetch-depth: 0
107
+ - name: Install the current repository
108
+ run: |
109
+ pip3 install -e .[test]
110
+ # - name: Download Model to Use
111
+ # run: |
112
+ # huggingface-cli download Qwen/Qwen2.5-0.5B --local-dir ${HOME}/models/Qwen/Qwen2.5-0.5B
113
+ # huggingface-cli download deepseek-ai/deepseek-coder-1.3b-instruct --local-dir ${HOME}/models/deepseek-ai/deepseek-coder-1.3b-instruct
114
+ # export HF_HUB_OFFLINE=1
115
+ - name: Running Huggingface to Megatron dist_ckpt converter (Qwen/Qwen2.5-0.5B)
116
+ run: |
117
+ ray stop --force
118
+ 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
119
+ - name: Running Huggingface to Megatron dist_ckpt converter (deepseek-ai/deepseek-coder-1.3b-instruct)
120
+ run: |
121
+ ray stop --force
122
+ 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
123
+ - name: Clean up
124
+ run: |
125
+ rm -rf checkpoints
126
+
127
+ checkpoint_converter_large_moe_models:
128
+ needs: setup
129
+ runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ]
130
+ timeout-minutes: 30 # Increase this timeout value as needed
131
+ env:
132
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
133
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
134
+ NO_PROXY: "localhost,127.0.0.1"
135
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
136
+ HF_ENDPOINT: "https://hf-mirror.com"
137
+ steps:
138
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
139
+ with:
140
+ fetch-depth: 0
141
+ - name: Install the current repository
142
+ run: |
143
+ pip3 install -e .[test]
144
+ # - name: Download Model to Use
145
+ # run: |
146
+ # huggingface-cli download Qwen/Qwen1.5-MoE-A2.7B-Chat --local-dir ${HOME}/models/Qwen/Qwen1.5-MoE-A2.7B-Chat
147
+ # export HF_HUB_OFFLINE=1
148
+ - name: Running Huggingface to Megatron dist_ckpt CPU converter (Qwen/Qwen1.5-MoE-A2.7B-Chat)
149
+ run: |
150
+ ray stop --force
151
+ 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
152
+ - name: Running distributed Huggingface to Megatron dist_ckpt CPU converter (Qwen/Qwen1.5-MoE-A2.7B-Chat)
153
+ run: |
154
+ ray stop --force
155
+ 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
156
+ - name: clean up
157
+ run: |
158
+ rm -rf checkpoints
159
+
160
+ cleanup:
161
+ runs-on: ubuntu-latest
162
+ needs:
163
+ [
164
+ setup,
165
+ checkpoint_converter,
166
+ checkpoint_converter_large_moe_models
167
+ ]
168
+ if: always()
169
+ steps:
170
+ - id: destroy-runner
171
+ uses: volcengine/vemlp-github-runner@v1
172
+ with:
173
+ mode: "destroy"
174
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
175
+ mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}"
verl/.github/workflows/cpu_unit_tests.yml ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+
33
+ name: cpu_unit_tests
34
+
35
+ on:
36
+ # Trigger the workflow on push or pull request,
37
+ # but only for the main branch
38
+ push:
39
+ branches:
40
+ - main
41
+ - v0.*
42
+ pull_request:
43
+ branches:
44
+ - main
45
+ - v0.*
46
+ paths:
47
+ - "**/*.py"
48
+ - .github/workflows/cpu_unit_tests.yml
49
+ - "!recipe/**/*.py"
50
+
51
+ # Cancel jobs on the same ref if a new one is triggered
52
+ concurrency:
53
+ group: ${{ github.workflow }}-${{ github.ref }}
54
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
55
+
56
+ # Declare permissions just read content.
57
+ permissions:
58
+ contents: read
59
+
60
+ jobs:
61
+ cpu_unit_tests:
62
+ if: github.repository_owner == 'volcengine'
63
+ runs-on: [L20x8]
64
+ timeout-minutes: 20 # Increase this timeout value as needed
65
+ env:
66
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
67
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
68
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
69
+ HF_ENDPOINT: "https://hf-mirror.com"
70
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
71
+ container:
72
+ image: verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2
73
+ steps:
74
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
75
+ with:
76
+ fetch-depth: 0
77
+ - name: Install the current repository
78
+ run: |
79
+ pip install -e .[test,prime,geo]
80
+ pip install --upgrade "ray>=2.40.0" pillow
81
+ - name: Download datasets
82
+ run: |
83
+ huggingface-cli download verl-team/gsm8k-v0.4.1 --repo-type dataset --local-dir ~/verl-data/gsm8k
84
+ python3 examples/data_preprocess/geo3k.py
85
+ - name: Running CPU unit tests
86
+ run: |
87
+ echo '[pytest]' > pytest.ini
88
+ echo 'python_files = *_on_cpu.py' >> pytest.ini
89
+ pytest -s -x --asyncio-mode=auto tests/
verl/.github/workflows/doc.yml ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+
33
+ name: doc_test
34
+
35
+ on:
36
+ # Trigger the workflow on push or pull request,
37
+ # but only for the main branch
38
+ push:
39
+ branches:
40
+ - main
41
+ - v0.*
42
+ pull_request:
43
+ branches:
44
+ - main
45
+ - v0.*
46
+ paths:
47
+ - "**/*.py"
48
+ - "docs/**"
49
+ - .github/workflows/doc.yml
50
+
51
+ # Cancel jobs on the same ref if a new one is triggered
52
+ concurrency:
53
+ group: ${{ github.workflow }}-${{ github.ref }}
54
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
55
+
56
+ # Declare permissions just read content.
57
+ permissions:
58
+ contents: read # for checkout
59
+ pages: write # for deploy-pages
60
+ id-token: write # for deploy-pages
61
+
62
+ jobs:
63
+ doc_test:
64
+ runs-on: ubuntu-latest
65
+ timeout-minutes: 5 # Increase this timeout value as needed
66
+ strategy:
67
+ matrix:
68
+ python-version: ["3.10"]
69
+ steps:
70
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
71
+ - name: Set up Python ${{ matrix.python-version }}
72
+ uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0
73
+ with:
74
+ python-version: ${{ matrix.python-version }}
75
+ - name: Install the current repository
76
+ run: |
77
+ pip install -e .[test] --no-deps
78
+ pip install -r docs/requirements-docs.txt
79
+
80
+ - name: Run doc make html
81
+ run: |
82
+ cd docs
83
+ make clean
84
+ make html SPHINXOPTS="--keep-going -w _build/sphinx.log"
85
+ if grep -q ": ERROR:" _build/sphinx.log; then
86
+ echo "🚨 Sphinx doc build contained ERRORs - see _build/sphinx.log"
87
+ exit 1
88
+ fi
89
+ if grep -q "WARNING: document isn't included in any toctree" _build/sphinx.log; then
90
+ echo "🚨 Sphinx doc build contained WARNING. Please include newly added docs in index.rst. See _build/sphinx.log for details"
91
+ exit 1
92
+ fi
93
+ if grep -q "WARNING: Inline emphasis" _build/sphinx.log; then
94
+ echo "🚨 Sphinx doc build contained WARNING. Please check inline emphasis is correct. See _build/sphinx.log for details"
95
+ exit 1
96
+ fi
97
+ if grep -q "WARNING: Definition list ends without a blank line" _build/sphinx.log; then
98
+ echo "🚨 Sphinx doc build contained WARNING. Please check if the indentation is correct. See _build/sphinx.log for details"
99
+ exit 1
100
+ fi
verl/.github/workflows/e2e_ascend.yml ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+
33
+ name: e2e_ascend
34
+
35
+ on:
36
+ # Trigger the workflow on push or pull request,
37
+ # but only for the main branch
38
+ push:
39
+ branches:
40
+ - main
41
+ - v0.*
42
+ pull_request:
43
+ branches:
44
+ - main
45
+ paths:
46
+ - ".github/workflows/e2e_ascend.yml"
47
+ - "**/*.py"
48
+ - "docs/ascend_tutorial/**"
49
+ - "examples/**"
50
+ - "recipe/**"
51
+ - "tests/special_npu/**"
52
+ - "tests/special_sanity/**"
53
+ - "verl/**"
54
+ - "pyproject.toml"
55
+ - "requirements-npu.txt"
56
+ - "setup.py"
57
+
58
+ # Cancel jobs on the same ref if a new one is triggered
59
+ concurrency:
60
+ group: ${{ github.workflow }}-${{ github.ref }}
61
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
62
+
63
+ permissions:
64
+ contents: read
65
+
66
+ jobs:
67
+ test:
68
+ if: github.repository_owner == 'volcengine'
69
+ name: verl Ascend test (self-host)
70
+ runs-on: [self-hosted, npu-0]
71
+ timeout-minutes: 40 # Increase this timeout value as needed
72
+ container:
73
+ image: crispig/verl_npu:cann8.1rc1-py3.10-torch2.5.1-vllm-ascend0.7.3.post1-mindspeed0121-250731
74
+ volumes:
75
+ - /usr/local/dcmi:/usr/local/dcmi
76
+ - /usr/local/bin/npu-smi:/usr/local/bin/npu-smi
77
+ - /usr/local/Ascend/driver/lib64/:/usr/local/Ascend/driver/lib64/
78
+ - /usr/local/Ascend/driver/version.info:/usr/local/Ascend/driver/version.info
79
+ - /etc/ascend_install.info:/etc/ascend_install.info
80
+ - /data00/dataset:/github/home/dataset
81
+ - /data00/models:/github/home/models
82
+ # Use self-host cache speed up pip and model download
83
+ # - /home/action/actions-runner/_work/cache:/github/home/.cache/
84
+ options: >-
85
+ --device /dev/davinci0
86
+ --device /dev/davinci_manager
87
+ --device /dev/devmm_svm
88
+ --device /dev/hisi_hdc
89
+ --network host
90
+ --privileged
91
+ --shm-size 16g
92
+ env:
93
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
94
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
95
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
96
+ HF_ENDPOINT: "https://hf-mirror.com"
97
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
98
+ steps:
99
+ - name: Check npu and CANN info
100
+ run: |
101
+ cat /usr/local/Ascend/ascend-toolkit/latest/"$(uname -i)"-linux/ascend_toolkit_install.info
102
+ npu-smi info
103
+ - name: Checkout volcengine/verl repo
104
+ uses: actions/checkout@v4
105
+ - name: Install the current repository
106
+ run: |
107
+ pip3 install hf_transfer peft
108
+ pip3 install -r requirements-npu.txt
109
+ pip install -e .
110
+ - name: Install torchvision
111
+ run: |
112
+ pip install torchvision==0.20.1+cpu --index-url https://download.pytorch.org/whl/cpu
113
+ - name: Uninstall Triton
114
+ run: |
115
+ pip uninstall -y triton
116
+ - name: Preprocess gsm8k dataset
117
+ run: |
118
+ python examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/dataset/openai/gsm8k
119
+ - name: Preprocess geo3k dataset
120
+ run: |
121
+ python examples/data_preprocess/geo3k.py --local_dataset_path ${HOME}/dataset/hiyouga/geometry3k
122
+ - name: Running gsm8k e2e qwen3 training tests with PPO on ASCEND NPU
123
+ run: |
124
+ ray stop --force
125
+ bash tests/special_npu/run_qwen3_06b_ppo.sh
126
+ rm -rf $HOME/ckpts
127
+ - name: Running gsm8k e2e training tests with peft sft on ASCEND NPU
128
+ run: |
129
+ ray stop --force
130
+ bash tests/special_npu/run_qwen2_5_05b_sft_peft_sp2.sh
131
+ rm -rf $HOME/ckpts
132
+ - name: Running gsm8k e2e training tests with GRPO on ASCEND NPU
133
+ run: |
134
+ ray stop --force
135
+ bash tests/special_npu/run_qwen2_5_05b_grpo.sh
136
+ rm -rf $HOME/ckpts
137
+ - name: Running geo3k e2e training tests with GRPO on ASCEND NPU
138
+ run: |
139
+ ray stop --force
140
+ bash tests/special_npu/run_qwen2_5_vl_3b_npu.sh
141
+ rm -rf $HOME/ckpts
142
+ - name: Running gsm8k e2e training tests with DAPO on ASCEND NPU
143
+ run: |
144
+ ray stop --force
145
+ bash tests/special_npu/run_qwen2_5_05b_dapo.sh
146
+ rm -rf $HOME/ckpts
147
+ - name: Running gsm8k e2e training tests with GRPO MindSpeed on ASCEND NPU
148
+ run: |
149
+ ray stop --force
150
+ USE_DIST_CKPT=True bash tests/special_npu/run_qwen2_5_05b_grpo_mindspeed.sh
151
+ rm -rf $HOME/dist_ckpt/qwen2_5_05b_grpo_mindspeed
152
+ rm -rf $HOME/ckpts
153
+ - name: Running NPU profiling unit tests
154
+ run: |
155
+ ray stop --force
156
+ pytest -s -x tests/utils/test_special_mstx_profile.py
verl/.github/workflows/e2e_dapo.yml ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+
33
+ name: e2e_dapo
34
+
35
+ on:
36
+ # Trigger the workflow on push or pull request,
37
+ # but only for the main branch
38
+ # For push, for now only anti-patterns are specified so it is more conservative
39
+ # and achieves higher coverage.
40
+ push:
41
+ branches:
42
+ - main
43
+ - v0.*
44
+ paths:
45
+ - "verl/*.py"
46
+ # Other entrypoints
47
+ - "!examples/*trainer*"
48
+ - "!tests/**"
49
+ - "!verl/trainer/main_*.py"
50
+ - "!verl/trainer/fsdp_sft_trainer.py"
51
+ # Megatron
52
+ - "!verl/workers/**/megatron_*.py"
53
+ - "!recipe/**"
54
+ - "recipe/dapo"
55
+ pull_request:
56
+ branches:
57
+ - main
58
+ - v0.*
59
+ paths:
60
+ - "**/*.py"
61
+ # Other entrypoints
62
+ - "!examples/**"
63
+ - "!tests/**"
64
+ - "!verl/trainer/main_*.py"
65
+ - "!verl/trainer/fsdp_sft_trainer.py"
66
+ # Other recipes
67
+ - "!recipe/**"
68
+ # Megatron
69
+ - "!verl/workers/**/megatron_*.py"
70
+ # Home
71
+ - "recipe/dapo"
72
+ # Entrypoints
73
+ - ".github/workflows/e2e_dapo.yml"
74
+ - "examples/data_preprocess/gsm8k.py"
75
+ - "tests/special_e2e/run_dapo.sh"
76
+
77
+ # Cancel jobs on the same ref if a new one is triggered
78
+ concurrency:
79
+ group: ${{ github.workflow }}-${{ github.ref }}
80
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
81
+
82
+ # Declare permissions just read content.
83
+ permissions:
84
+ contents: read
85
+
86
+ env:
87
+ IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2"
88
+ DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner"
89
+
90
+ jobs:
91
+ setup:
92
+ if: github.repository_owner == 'volcengine'
93
+ runs-on: ubuntu-latest
94
+ outputs:
95
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
96
+ mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }}
97
+ steps:
98
+ - uses: actions/checkout@v4
99
+ - id: create-runner
100
+ uses: volcengine/vemlp-github-runner@v1
101
+ with:
102
+ mode: "create"
103
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
104
+ mlp-image: "${{ env.IMAGE }}"
105
+
106
+ e2e_dapo:
107
+ needs: setup
108
+ runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ]
109
+ timeout-minutes: 40 # Increase this timeout value as needed
110
+ env:
111
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
112
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
113
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
114
+ HF_ENDPOINT: "https://hf-mirror.com"
115
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
116
+ steps:
117
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
118
+ with:
119
+ fetch-depth: 0
120
+ - name: Install the current repository
121
+ run: |
122
+ pip3 install --no-deps -e .[test,gpu]
123
+ - name: Prepare GSM8K dataset
124
+ run: |
125
+ python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k
126
+ - name: Running the E2E test with the DAPO algorithm
127
+ run: |
128
+ ray stop --force
129
+ bash tests/special_e2e/run_dapo.sh
130
+
131
+ cleanup:
132
+ runs-on: ubuntu-latest
133
+ needs:
134
+ [
135
+ setup,
136
+ e2e_dapo
137
+ ]
138
+ if: always()
139
+ steps:
140
+ - id: destroy-runner
141
+ uses: volcengine/vemlp-github-runner@v1
142
+ with:
143
+ mode: "destroy"
144
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
145
+ mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}"
verl/.github/workflows/e2e_genrm_remote.yml ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Tests layout
2
+
3
+ # Each folder under tests/ corresponds to a test category for a sub-namespace in verl. For instance:
4
+ # - `tests/trainer` for testing functionality related to `verl/trainer`
5
+ # - `tests/models` for testing functionality related to `verl/models`
6
+ # - ...
7
+
8
+ # There are a few folders with `special_` prefix, created for special purposes:
9
+ # - `special_distributed`: unit tests that must run with multiple GPUs
10
+ # - `special_e2e`: end-to-end tests with training/generation scripts
11
+ # - `special_npu`: tests for NPUs
12
+ # - `special_sanity`: a suite of quick sanity tests
13
+ # - `special_standalone`: a set of test that are designed to run in dedicated environments
14
+
15
+ # Accelerators for tests
16
+ # - 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`.
17
+ # - For test scripts with `on_cpu.py` name suffix would be tested on CPU resources in linux environment.
18
+
19
+ # # Workflow layout
20
+
21
+ # All CI tests are configured by yaml files in `.github/workflows/`. Here's an overview of all test configs:
22
+ # 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`
23
+ # 2. Some heavy multi-GPU unit tests, such as `model.yml`, `vllm.yml`, `sgl.yml`
24
+ # 3. End-to-end tests: `e2e_*.yml`
25
+ # 4. Unit tests
26
+ # - `cpu_unit_tests.yml`, run pytest on all scripts with file name pattern `tests/**/test_*_on_cpu.py`
27
+ # - `gpu_unit_tests.yml`, run pytest on all scripts with file without the `on_cpu.py` suffix.
28
+ # - Since cpu/gpu unit tests by default runs all tests under `tests`, please make sure tests are manually excluded in them when
29
+ # - new workflow yaml is added to `.github/workflows`
30
+ # - new tests are added to workflow mentioned in 2.
31
+
32
+
33
+ name: e2e_genrm_remote
34
+
35
+ on:
36
+ # Trigger the workflow on push or pull request,
37
+ # but only for the main branch
38
+ push:
39
+ branches:
40
+ - main
41
+ - v0.*
42
+ paths:
43
+ - "**/*.py"
44
+ - "tests/**"
45
+ - "!recipe/**"
46
+ - "recipe/genrm_remote"
47
+ pull_request:
48
+ branches:
49
+ - main
50
+ - v0.*
51
+ paths:
52
+ - "**/*.py"
53
+ # Other entrypoints
54
+ - "!examples/**"
55
+ - "!tests/**"
56
+ - "!verl/trainer/main_*.py"
57
+ - "!verl/trainer/fsdp_sft_trainer.py"
58
+ # Other recipes
59
+ - "!recipe/**"
60
+ # Megatron
61
+ - "!verl/workers/**/megatron_*.py"
62
+ # Home
63
+ - "recipe/genrm_remote"
64
+ - "!recipe/genrm_remote/README.md"
65
+ # Entrypoints
66
+ - ".github/workflows/e2e_genrm_remote.yml"
67
+ - "examples/data_preprocess/gsm8k.py"
68
+ - "tests/special_e2e/run_genrm_remote.sh"
69
+
70
+ # Cancel jobs on the same ref if a new one is triggered
71
+ concurrency:
72
+ group: ${{ github.workflow }}-${{ github.ref }}
73
+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
74
+
75
+ # Declare permissions just read content.
76
+ permissions:
77
+ contents: read
78
+
79
+ env:
80
+ IMAGE: "verl-ci-cn-beijing.cr.volces.com/verlai/verl:app-verl0.5-transformers4.55.4-vllm0.10.0-mcore0.13.0-te2.2"
81
+ DYNAMIC_RUNNER_ENDPOINT: "https://sd10g3clalm04ug7alq90.apigateway-cn-beijing.volceapi.com/runner"
82
+
83
+ jobs:
84
+ setup:
85
+ if: github.repository_owner == 'volcengine'
86
+ runs-on: ubuntu-latest
87
+ outputs:
88
+ runner-label: ${{ steps.create-runner.outputs.runner-label }}
89
+ mlp-task-id: ${{ steps.create-runner.outputs.mlp-task-id }}
90
+ steps:
91
+ - uses: actions/checkout@v4
92
+ - id: create-runner
93
+ uses: volcengine/vemlp-github-runner@v1
94
+ with:
95
+ mode: "create"
96
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
97
+ mlp-image: "${{ env.IMAGE }}"
98
+
99
+ e2e_genrm_remote:
100
+ needs: setup
101
+ runs-on: [ "${{ needs.setup.outputs.runner-label || 'L20x8' }}" ]
102
+ timeout-minutes: 40 # Increase this timeout value as needed
103
+ env:
104
+ HTTP_PROXY: ${{ secrets.PROXY_HTTP }}
105
+ HTTPS_PROXY: ${{ secrets.PROXY_HTTPS }}
106
+ NO_PROXY: "localhost,127.0.0.1,hf-mirror.com"
107
+ HF_ENDPOINT: "https://hf-mirror.com"
108
+ HF_HUB_ENABLE_HF_TRANSFER: "0" # This is more stable
109
+ steps:
110
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
111
+ with:
112
+ fetch-depth: 0
113
+ - name: Install the current repository
114
+ run: |
115
+ pip3 install --no-deps -e .[test,gpu]
116
+ - name: Prepare GSM8K dataset
117
+ run: |
118
+ python3 examples/data_preprocess/gsm8k.py --local_dataset_path ${HOME}/models/hf_data/gsm8k
119
+ - name: Running the E2E test with the Generative Reward Model
120
+ run: |
121
+ ray stop --force
122
+ bash tests/special_e2e/run_genrm_remote.sh
123
+
124
+ cleanup:
125
+ runs-on: ubuntu-latest
126
+ needs:
127
+ [
128
+ setup,
129
+ e2e_genrm_remote
130
+ ]
131
+ if: always()
132
+ steps:
133
+ - id: destroy-runner
134
+ uses: volcengine/vemlp-github-runner@v1
135
+ with:
136
+ mode: "destroy"
137
+ faas-url: "${{ env.DYNAMIC_RUNNER_ENDPOINT }}"
138
+ mlp-task-id: "${{ needs.setup.outputs.mlp-task-id }}"