#!/usr/bin/env python3 import argparse import json import os from pathlib import Path from typing import List, Tuple try: import yaml # type: ignore except Exception: yaml = None # Sokoban tokens and actions (as used by SokobanWrapper) TOKENS = ['#', '_', 'O', '√', 'X', 'P', 'S'] ACTION_LOOKUP = {1: 'Up', 2: 'Down', 3: 'Left', 4: 'Right'} def infer_grid_dims(state_arr: List[List[List[float]]]) -> Tuple[int, int, int]: c = len(state_arr) h = len(state_arr[0]) if c > 0 else 0 w = len(state_arr[0][0]) if (c > 0 and h > 0) else 0 return c, h, w def decode_state_to_grid_text(state_arr: List[List[List[float]]]) -> str: c, h, w = infer_grid_dims(state_arr) lines = [] for i in range(h): row = [] for j in range(w): argmax_k = 0 vmax = -1e9 for k in range(c): v = state_arr[k][i][j] if v > vmax: vmax = v argmax_k = k ch = TOKENS[argmax_k] if 0 <= argmax_k < len(TOKENS) else '_' row.append(ch) lines.append(''.join(row)) return '\n'.join(lines) def parse_positions_from_state(state_arr: List[List[List[float]]]): """Extract board size, targets, boxes, and player coordinates from one-hot state. - Tokens index mapping per TOKENS: 0 '#', 1 '_', 2 'O'(target), 3 '√'(box on target), 4 'X'(box), 5 'P'(player), 6 'S'(player on target) - Targets include cells with 'O' or '√'. - Boxes include cells with 'X' or '√'. - Player is where token is 'P' or 'S'. Returns: (rows, cols, targets: List[(r,c)], boxes: List[(r,c)], player: (r,c) or None) """ c, h, w = infer_grid_dims(state_arr) targets: List[Tuple[int, int]] = [] boxes: List[Tuple[int, int]] = [] player: Tuple[int, int] | None = None for i in range(h): for j in range(w): # argmax over channels argk = 0 vmax = -1e9 for k in range(c): v = state_arr[k][i][j] if v > vmax: vmax = v argk = k if argk == 2: # 'O' target targets.append((i, j)) elif argk == 3: # '√' box on target (both a box and a target) targets.append((i, j)) boxes.append((i, j)) elif argk == 4: # 'X' box boxes.append((i, j)) elif argk == 5 or argk == 6: # 'P' or 'S' (player or player on target) player = (i, j) return h, w, targets, boxes, player def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool]: instruction = ( "You are solving the Sokoban puzzle. You are the player and you need to push all boxes to targets. " "When you are right next to a box, you can push it by moving in the same direction. " "You cannot push a box through a wall, and you cannot pull a box. " "The answer should be a sequence of actions, like Right || Right || Up\n" "\nThe meaning of each symbol in the state is:\n" "#: wall, _: empty, O: target, √: box on target, X: box, P: player, S: player on target\n" "Your available actions are:\n" "Up, Down, Left, Right\n" "You can make up to 10 actions, separated by the action separator \" || \"\n" ) max_tokens = 100 action_sep = "||" enable_think = True if yaml is None: return instruction, max_tokens, action_sep, enable_think envs_yaml = repo_root / "config" / "envs.yaml" if envs_yaml.exists(): try: with open(envs_yaml, "r", encoding="utf-8") as f: envs = yaml.safe_load(f) custom_envs = envs.get("custom_envs", {}) if isinstance(envs, dict) else {} if isinstance(custom_envs, dict): # Prefer CoordSokoban, fallback to SimpleSokoban, then LargerSokoban for key in ["CoordSokoban", "SimpleSokoban", "LargerSokoban", "SokobanDifferentGridVocab"]: if key in custom_envs: cfg = custom_envs[key] instruction = cfg.get("env_instruction", instruction) max_tokens = int(cfg.get("max_tokens", max_tokens)) break except Exception: pass base_yaml = repo_root / "config" / "base.yaml" if base_yaml.exists(): try: with open(base_yaml, "r", encoding="utf-8") as f: base_cfg = yaml.safe_load(f) ap = base_cfg.get("agent_proxy", {}) if isinstance(base_cfg, dict) else {} action_sep = ap.get("action_sep", action_sep) enable_think = bool(ap.get("enable_think", enable_think)) except Exception: pass return instruction, max_tokens, action_sep, enable_think def build_messages_for_episode( states: List[List[List[List[float]]]], actions: List[int], rewards: List[float], instruction: str, max_tokens: int, action_sep: str, enable_think: bool, max_actions: int, ) -> List[dict]: messages = [ {"role": "system", "content": "You're a helpful assistant. "}, {"role": "user", "content": instruction}, ] total_actions = len(actions) # states contain T+1 elements typically; we iterate over min(len(states), len(actions)) turns for t, state in enumerate(states): grid_text = decode_state_to_grid_text(state) rows, cols, targets_pos, boxes_pos, player_pos = parse_positions_from_state(state) actions_left = max(0, max_actions - t) if enable_think: format_prompt = " [Your thoughts] [your answer] " else: format_prompt = " [your answer] " length_prompt = f"Max response length: {max_tokens} words (tokens)." messages[-1]["content"] += ( f"\nTurn {t + 1}:\n" f"State:\n" f"Coordinates:\n" f"Board size: {rows} rows x {cols} cols (zero-indexed).\n" f"Targets: {targets_pos}\n" f"Boxes: {boxes_pos}\n" f"Player: {player_pos if player_pos is not None else (-1, -1)}\n" f"Grid Map:\n{grid_text}\n" f"You have {actions_left} actions left. Always output: {format_prompt}" f"with no extra text. Strictly follow this format. {length_prompt}" ) if t < total_actions: action_id = actions[t] + 1 # map 0..3 -> 1..4 action_name = ACTION_LOOKUP.get(action_id, "unknown") assistant_text = f"{action_name}" if not enable_think else f"{action_name}" messages.append({"role": "assistant", "content": assistant_text}) reward_val = rewards[t] if t < len(rewards) else 0.0 messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"}) return messages[:-1] def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False, max_actions: int = 10) -> Path: traj_path = step_dir / "trajectories.jsonl" metrics_path = step_dir / "metrics.json" if not traj_path.exists(): raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") instruction, max_tokens, action_sep, enable_think = load_env_instruction_and_cfg(repo_root) output_dir.mkdir(parents=True, exist_ok=True) out_path = output_dir / f"{step_dir.name}_sft.jsonl" global_step = None if metrics_path.exists(): try: with open(metrics_path, "r", encoding="utf-8") as f: m = json.load(f) global_step = m.get("global_step") except Exception: pass written = 0 with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: for line in fin: line = line.strip() if not line: continue traj = json.loads(line) ep_success = bool(traj.get("episode_success", False)) if (not include_failed) and (not ep_success): continue states = traj.get("states", []) actions = traj.get("actions", []) rewards = traj.get("rewards", []) if len(actions) > max_actions: continue messages = build_messages_for_episode( states=states, actions=actions, rewards=rewards, instruction=instruction, max_tokens=max_tokens, action_sep=action_sep, enable_think=enable_think, max_actions=max_actions, ) record = { "messages": messages, "meta": { "episode_return": traj.get("episode_return", None), "episode_success": ep_success, "global_step": global_step, }, } fout.write(json.dumps(record, ensure_ascii=False) + "\n") written += 1 if written == 0: with open(out_path, "w", encoding="utf-8") as f: pass return out_path def find_latest_step_dir(traj_root: Path) -> Path: step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] if not step_dirs: raise FileNotFoundError(f"No step_* directories under {traj_root}") step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) return step_dirs[-1] def main(): parser = argparse.ArgumentParser(description="Convert Sokoban RL trajectories to LLM SFT chat JSONL") parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)") parser.add_argument("--step", default=None, help="Specific step directory name (e.g., step_993280)") parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data") parser.add_argument("--max_actions", type=int, default=15, help="Max actions cap for filtering and counter display") args = parser.parse_args() repo_root = Path(__file__).resolve().parents[1] run_dir = Path(args.run_dir) traj_root = run_dir / "trajectories" if not traj_root.exists(): raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) output_dir = run_dir / "sft" out_path = convert_file(step_dir=step_dir, output_dir=output_dir, repo_root=repo_root, include_failed=args.include_failed, max_actions=args.max_actions) print(f"SFT data written to: {out_path}") if __name__ == "__main__": main()