File size: 12,276 Bytes
8fb9f5e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | #!/usr/bin/env python3
"""
Convert RL eval trajectories from Game 2048 into LLM SFT-ready chat data.
Matches the specific text format of the RAGEN/Maniskill environment runner.
"""
import argparse
import json
import math
from pathlib import Path
from typing import List, Tuple
import numpy as np
try:
import yaml # type: ignore
except Exception:
yaml = None
# 2048 action lookup from config (0..3)
ACTION_LOOKUP_2048 = {0: "Up", 1: "Right", 2: "Down", 3: "Left"}
def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool, int]:
"""Load 2048 env instruction and base agent_proxy configs."""
max_tokens = 8192
action_sep = " || "
enable_think = True
max_actions = 700
instruction_template = (
"You are playing the 2048 game on a 4x4 grid. Merge equal tiles by sliding Up, Right, Down, or Left.\n"
"If a move is invalid (no tiles move), a small penalty is applied. Respond with a single action.\n"
"Example: <answer>Up</answer>\n\n"
"Your available actions are:\n"
"Up, Right, Down, Left\n"
"You can make up to {max_actions} actions, separated by the action separator \"{action_sep}\""
)
if yaml is not None:
envs_yaml = repo_root / "config" / "envs.yaml"
if envs_yaml.exists():
try:
with open(envs_yaml, "r", encoding="utf-8") as f:
envs = yaml.safe_load(f)
if isinstance(envs, dict) and "custom_envs" in envs and "game_2048" in envs["custom_envs"]:
e = envs["custom_envs"]["game_2048"]
max_actions = int(e.get("max_actions_per_traj", max_actions))
except Exception:
pass
base_yaml = repo_root / "config" / "base.yaml"
if base_yaml.exists():
try:
with open(base_yaml, "r", encoding="utf-8") as f:
base_cfg = yaml.safe_load(f)
ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {}
enable_think = bool(ap.get("enable_think", enable_think))
except Exception:
pass
instruction = instruction_template.format(max_actions=max_actions, action_sep=action_sep)
return instruction, max_tokens, action_sep, enable_think, max_actions
def get_grid_matrix(state: List[List[List[float]]]) -> List[List[int]]:
"""Decode 2048 CNN one-hot channels (C x 4 x 4) into a 4x4 integer matrix."""
if not state or not isinstance(state, list):
return [[0]*4 for _ in range(4)]
C = len(state)
H = len(state[0]) if C > 0 else 0
W = len(state[0][0]) if (C > 0 and H > 0) else 0
grid_vals = [[0 for _ in range(W)] for __ in range(H)]
for i in range(H):
for j in range(W):
max_c = 0
max_v = -float("inf")
for c in range(C):
v = state[c][i][j]
if v > max_v:
max_v = v
max_c = c
if max_c <= 0:
grid_vals[i][j] = 0
else:
try:
grid_vals[i][j] = int(2 ** max_c)
except Exception:
grid_vals[i][j] = 0
return grid_vals
def grid_to_text(grid_vals: List[List[int]]) -> str:
"""Convert 4x4 matrix to text representation."""
lines = ["Current 2048 Grid:"]
H = len(grid_vals)
W = len(grid_vals[0]) if H > 0 else 0
for r in range(H):
row_str = ", ".join(str(grid_vals[r][c]) for c in range(W))
lines.append(f"Row {r+1}: [{row_str}]")
return "\n".join(lines)
def get_valid_actions(grid: List[List[int]]) -> List[int]:
"""
Determine valid moves for a 4x4 grid.
Returns a list of action indices: 0(Up), 1(Right), 2(Down), 3(Left)
"""
valid_actions = []
def can_move_left_row(row: List[int]) -> bool:
"""Check if a single row can compress or merge to the left."""
# Check 1: Can merge? (Adjacent equal non-zeros)
tiles = [x for x in row if x != 0]
for i in range(len(tiles) - 1):
if tiles[i] == tiles[i+1]:
return True
# Check 2: Can slide? (Is there a 0 to the left of a non-0?)
# Logic: If we see a 0, then subsequently see a non-0, we can move.
seen_zero = False
for x in row:
if x == 0:
seen_zero = True
elif seen_zero: # x != 0 and seen_zero is True
return True
return False
# 0: Up (Check columns effectively moving "left" if transposed)
# Transpose grid to treat columns as rows
cols = [[grid[r][c] for r in range(4)] for c in range(4)]
if any(can_move_left_row(col) for col in cols):
valid_actions.append(0)
# 1: Right (Check rows reversed)
if any(can_move_left_row(row[::-1]) for row in grid):
valid_actions.append(1)
# 2: Down (Check columns reversed)
cols_rev = [[grid[r][c] for r in reversed(range(4))] for c in range(4)]
if any(can_move_left_row(col) for col in cols_rev):
valid_actions.append(2)
# 3: Left (Check rows normal)
if any(can_move_left_row(row) for row in grid):
valid_actions.append(3)
return valid_actions
def build_messages_for_episode(
states: List[List[List[List[float]]]],
actions: List[int],
rewards: List[float],
instruction: str,
max_tokens: int,
action_sep: str,
enable_think: bool,
max_actions: int,
) -> List[dict]:
messages = [
{"role": "system", "content": "You're a helpful assistant. "},
{"role": "user", "content": instruction},
]
total_actions = len(actions)
current_score = 0.0
for t, state in enumerate(states):
# 1. Decode Matrix
grid_matrix = get_grid_matrix(state)
# 2. Convert to Text
grid_text = grid_to_text(grid_matrix)
# 3. Calculate Valid Actions
valid_idxs = get_valid_actions(grid_matrix)
# Fallback: if somehow no actions are valid (game over state), strictly speaking the game ends.
# But if the log continues, we default to all or keep empty.
# Usually we format whatever is valid.
valid_actions_str_parts = []
for idx in sorted(valid_idxs):
name = ACTION_LOOKUP_2048.get(idx, str(idx))
valid_actions_str_parts.append(f"{idx}({name})")
if valid_actions_str_parts:
valid_actions_str = ", ".join(valid_actions_str_parts) + "."
else:
# Should imply Game Over, but for prompting consistency:
valid_actions_str = "None (Game Over)."
actions_left = max(0, max_actions - t)
format_prompt = (
"<think> [Your thoughts] </think> <answer> [your answer] </answer>"
if enable_think
else "<answer> [your answer] </answer>"
)
length_prompt = f"Max response length: {max_tokens} words (tokens)."
turn_content = (
f"\n\nTurn {t + 1}:\n"
f"State:\n"
f"{grid_text}\n\n"
f"Valid Actions: {valid_actions_str}\n"
f"Goal: Merge same numbers to reach 2048.\n"
f"Current Score: {int(current_score)}\n"
f"What is your next move?\n"
f"You have {actions_left} actions left. Always output: {format_prompt} "
f"with no extra text. Strictly follow this format. {length_prompt}"
)
messages[-1]["content"] += turn_content
if t < total_actions:
a = actions[t]
a_name = ACTION_LOOKUP_2048.get(int(a), str(a))
if enable_think:
assistant_text = f"<think> </think><answer>{a_name}</answer>"
else:
assistant_text = f"<answer>{a_name}</answer>"
messages.append({"role": "assistant", "content": assistant_text})
r = rewards[t] if t < len(rewards) else 0.0
current_score += r
messages.append({"role": "user", "content": f"Reward:\n{float(np.log2(r + 1.0)) * 0.1}"})
return messages[:-1]
def find_latest_step_dir(traj_root: Path) -> Path:
step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
if not step_dirs:
raise FileNotFoundError(f"No step_* directories under {traj_root}")
step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
return step_dirs[-1]
def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool, max_actions_cap: int | None) -> Path:
traj_path = step_dir / "trajectories.jsonl"
metrics_path = step_dir / "metrics.json"
if not traj_path.exists():
raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
instruction, max_tokens, action_sep, enable_think, default_max_actions = load_env_instruction_and_cfg(repo_root)
max_actions = int(max_actions_cap) if max_actions_cap is not None else int(default_max_actions)
output_dir.mkdir(parents=True, exist_ok=True)
out_path = output_dir / f"{step_dir.name}_sft.jsonl"
global_step = None
if metrics_path.exists():
try:
with open(metrics_path, "r", encoding="utf-8") as f:
m = json.load(f)
global_step = m.get("global_step")
except Exception:
pass
written = 0
with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
for line in fin:
line = line.strip()
if not line:
continue
traj = json.loads(line)
ep_success = bool(traj.get("episode_success", False))
if (not include_failed) and (not ep_success):
continue
states = traj.get("states", [])
actions = traj.get("actions", [])
rewards = traj.get("rewards", [])
if len(actions) > max_actions:
continue
messages = build_messages_for_episode(
states=states,
actions=actions,
rewards=rewards,
instruction=instruction,
max_tokens=max_tokens,
action_sep=action_sep,
enable_think=enable_think,
max_actions=max_actions,
)
record = {
"messages": messages,
"meta": {
"episode_return": traj.get("episode_return", None),
"episode_success": ep_success,
"global_step": global_step,
},
}
# Threshold check
if traj.get("episode_return", 0) > 7000:
fout.write(json.dumps(record, ensure_ascii=False) + "\n")
written += 1
import pdb;pdb.set_trace()
if written == 0:
with open(out_path, "w", encoding="utf-8"):
pass
return out_path
def main():
parser = argparse.ArgumentParser(description="Convert 2048 RL trajectories to LLM SFT chat JSONL")
parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)")
parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)")
parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
parser.add_argument("--max_actions", type=int, default=700, help="Override max actions cap (default from envs.yaml)")
args = parser.parse_args()
repo_root = Path(__file__).resolve().parents[1]
run_dir = Path(args.run_dir)
traj_root = run_dir / "trajectories"
if not traj_root.exists():
raise FileNotFoundError(f"Not found trajectories directory: {traj_root}")
step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root)
output_dir = run_dir / "sft"
out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed, max_actions_cap=args.max_actions)
print(f"SFT data written to: {out_path}")
if __name__ == "__main__":
main() |