#!/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.
Returns: (instruction, max_tokens, action_sep, enable_think, max_actions)
"""
# Defaults
max_tokens = 8192 # Adjusted to match your log (was 64)
action_sep = " || " # Adjusted spacing to match your log
enable_think = True
max_actions = 1000 # Default limit
# We construct the instruction to strictly match the environment text
# Note: The dynamic parts (like max_actions) are inserted here.
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: Up\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
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"]
# If you want to use the yaml instruction, uncomment below.
# But for strict matching of your provided text, we prefer the hardcoded template above.
# instruction = e.get("env_instruction", instruction)
# We still load configs
# max_tokens = int(e.get("max_tokens", max_tokens))
max_actions = int(e.get("max_actions_per_traj", max_actions))
except Exception:
pass
# base.yaml
base_yaml = repo_root / "config" / "base.yaml"
if base_yaml.exists():
try:
with open(base_yaml, "r", encoding="utf-8") as f:
base_cfg = yaml.safe_load(f)
ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {}
# action_sep = ap.get("action_sep", action_sep)
enable_think = bool(ap.get("enable_think", enable_think))
except Exception:
pass
instruction = instruction_template.format(max_actions=max_actions, action_sep=action_sep)
return instruction, max_tokens, action_sep, enable_think, max_actions
def decode_state_to_grid_text(state: List[List[List[float]]]) -> str:
"""Decode 2048 CNN one-hot channels (C x 4 x 4) back to a grid string."""
if not state or not isinstance(state, list):
return ""
# Expect shape (C, 4, 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: List[List[int]] = [[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
lines = ["Current 2048 Grid:"]
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 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):
grid_text = decode_state_to_grid_text(state)
actions_left = max(0, max_actions - t)
# Matches: " ... ... with no extra text."
# Note the space before 'with'.
format_prompt = (
" [Your thoughts] [your answer] "
if enable_think
else " [your answer] "
)
# Matches: "Max response length: 4096 words (tokens)."
length_prompt = f"Max response length: {max_tokens} words (tokens)."
# Construct the User content block strictly matching the target format
# Note: Your target text has blank lines represented by unicode non-breaking spaces or just empty lines.
# We use standard \n for separation.
turn_content = (
f"\n\nTurn {t + 1}:\n"
f"State:\n"
f"{grid_text}\n\n"
f"Valid Actions: 0(Up), 1(Right), 2(Down), 3(Left).\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" {a_name}"
else:
assistant_text = f"{a_name}"
messages.append({"role": "assistant", "content": assistant_text})
r = rewards[t] if t < len(rewards) else 0.0
# Update score for the NEXT turn display
current_score += r
messages.append({"role": "user", "content": f"Reward:\n{float(np.log2(r + 1.0)) * 0.1}"})
# The last element is a user reward message for the final step; trim if needed for SFT
return messages[:-1]
def find_latest_step_dir(traj_root: Path) -> Path:
step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")]
if not step_dirs:
raise FileNotFoundError(f"No step_* directories under {traj_root}")
step_dirs.sort(key=lambda p: int(p.name.split("_")[-1]))
return step_dirs[-1]
def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool, max_actions_cap: int | None) -> Path:
traj_path = step_dir / "trajectories.jsonl"
metrics_path = step_dir / "metrics.json"
if not traj_path.exists():
raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}")
instruction, max_tokens, action_sep, enable_think, default_max_actions = load_env_instruction_and_cfg(repo_root)
max_actions = int(max_actions_cap) if max_actions_cap is not None else int(default_max_actions)
output_dir.mkdir(parents=True, exist_ok=True)
out_path = output_dir / f"{step_dir.name}_sft.jsonl"
# Read global step from metrics if available
global_step = None
if metrics_path.exists():
try:
with open(metrics_path, "r", encoding="utf-8") as f:
m = json.load(f)
global_step = m.get("global_step")
except Exception:
pass
written = 0
with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout:
for line in fin:
line = line.strip()
if not line:
continue
traj = json.loads(line)
ep_success = bool(traj.get("episode_success", False))
if (not include_failed) and (not ep_success):
continue
states = traj.get("states", [])
actions = traj.get("actions", [])
rewards = traj.get("rewards", [])
# Simple length check
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,
},
}
# Filter condition from your original script
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:
# write empty file to indicate execution
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=1000, 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()