#!/usr/bin/env python3 import argparse import json import math from pathlib import Path from typing import List, Tuple, Set, Dict def infer_grid_size_from_state_len(n: int) -> int: """Given flattened one-hot length n = G*G*(G+1), solve for integer G.""" for G in range(2, 17): if G * G * (G + 1) == n: return G raise ValueError(f"Cannot infer grid size from state length {n}") def state_to_matrix(state_vec: List[float], G: int) -> List[List[int]]: """Convert one-hot vector to GxG integer matrix.""" cell_dim = G + 1 matrix = [] for r in range(G): row = [] for c in range(G): base = (r * G + c) * cell_dim cell_data = state_vec[base : base + cell_dim] # argmax to find value val = 0 max_v = -1e9 for k, v in enumerate(cell_data): if v > max_v: max_v = v val = k row.append(val) matrix.append(row) return matrix def check_conflict(grid: List[List[int]], r: int, c: int, val: int, G: int) -> bool: """Check if placing val at (r,c) causes a conflict in current grid.""" if val == 0: return False # Row check for j in range(G): if j != c and grid[r][j] == val: return True # Col check for i in range(G): if i != r and grid[i][c] == val: return True # Box check box_size = int(math.sqrt(G)) br, bc = (r // box_size) * box_size, (c // box_size) * box_size for i in range(br, br + box_size): for j in range(bc, bc + box_size): if (i, j) != (r, c) and grid[i][j] == val: return True return False def get_valid_moves(grid: List[List[int]], G: int) -> Dict[Tuple[int, int], List[int]]: """Compute valid numbers for all empty cells.""" valid_moves = {} box_size = int(math.sqrt(G)) for r in range(G): for c in range(G): if grid[r][c] == 0: possibles = [] for v in range(1, G + 1): is_row_ok = all(grid[r][j] != v for j in range(G)) is_col_ok = all(grid[i][c] != v for i in range(G)) br, bc = (r // box_size) * box_size, (c // box_size) * box_size is_box_ok = True for i in range(br, br + box_size): for j in range(bc, bc + box_size): if grid[i][j] == v: is_box_ok = False break if is_row_ok and is_col_ok and is_box_ok: possibles.append(v) if possibles: valid_moves[(r + 1, c + 1)] = possibles # 1-indexed keys return valid_moves def render_ascii_board(grid: List[List[int]], initial_grid: List[List[int]], G: int) -> str: """Render the board in the rich ASCII format seen in logs.""" box_size = int(math.sqrt(G)) lines = [] header = "=" * 50 + "\nSUDOKU PUZZLE\n" + "=" * 50 lines.append(header) for r in range(G): if r > 0 and r % box_size == 0: row_sep = [] for c in range(G): if c > 0 and c % box_size == 0: row_sep.append("-") row_sep.append("----") lines.append("-" * (G * 4 + int(G/box_size)*2)) row_str = [] for c in range(G): if c > 0 and c % box_size == 0: row_str.append("|") val = grid[r][c] is_init = (initial_grid[r][c] != 0) if val == 0: cell_str = " . " else: is_conflict = check_conflict(grid, r, c, val, G) if is_conflict and not is_init: cell_str = f"*{val}*" elif is_init: cell_str = f"[{val}]" else: cell_str = f" {val} " # User placed row_str.append(cell_str) lines.append("".join(row_str)) lines.append("\nLegend: [N]=initial cell, N=user-placed, *N*=conflict, .=empty") return "\n".join(lines) def decode_action(action_id: int, G: int) -> Tuple[int, int, int]: """Map discrete id -> 1-indexed (row, col, num).""" row0 = action_id // (G * G) rem = action_id % (G * G) col0 = rem // G num = (rem % G) + 1 return row0 + 1, col0 + 1, num def build_messages_for_episode( states: List[List[float]], actions: List[int], rewards: List[float], max_tokens: int, max_actions: int, ) -> List[dict]: # Infer G from first state G = infer_grid_size_from_state_len(len(states[0])) box_size = int(math.sqrt(G)) grid_history = [state_to_matrix(s, G) for s in states] initial_grid = grid_history[0] sys_msg = "You're a helpful assistant. " intro_prompt = ( f"You are solving a Sudoku puzzle. Fill in the grid so that every row, column, " f"and {box_size}x{box_size} box contains the numbers 1-{G} without repetition.\n" "Initial cells are shown in [brackets] and cannot be modified. Empty cells are shown as dots (.).\n" "Place numbers one at a time using the format: place 1 at row 2 col 3 or 1,2,3\n" "The environment will provide feedback on valid/invalid moves and show conflicts if any occur.\n" ) messages = [ {"role": "system", "content": sys_msg}, {"role": "user", "content": intro_prompt}, ] # Main loop iterates over steps for t in range(len(states)): # If this state corresponds to a step where no action was taken (end of episode), stop if t >= len(actions): break current_grid = grid_history[t] actions_left = max(0, max_actions - t) # --- 1. Prepare Reward String (Combined into this User turn) --- # If t > 0, we have a reward from the previous action (at t-1) reward_prefix = "" if t > 0: prev_reward = rewards[t-1] if (t-1) < len(rewards) else 0.0 # Double newline to separate from the previous content logically reward_prefix = f"Reward:\n{prev_reward}\n\n" # --- 2. Render Board --- board_str = render_ascii_board(current_grid, initial_grid, G) # --- 3. Calc Valid Moves --- valid_map = get_valid_moves(current_grid, G) valid_str_lines = ["\n💡 VALID NUMBERS FOR EMPTY CELLS:"] sorted_keys = sorted(valid_map.keys()) if not sorted_keys: valid_str_lines.append(" (None)") else: count = 0 for (r, c) in sorted_keys: vals = valid_map[(r,c)] valid_str_lines.append(f" - ({r},{c}): {vals}") count += 1 if count > 15: valid_str_lines.append(" ... (list truncated)") break # valid_section = "\n".join(valid_str_lines) valid_section = "" # --- 4. Stats --- total_cells = G * G filled_cells = sum(1 for r in range(G) for c in range(G) if current_grid[r][c] != 0) init_cells = sum(1 for r in range(G) for c in range(G) if initial_grid[r][c] != 0) placed_cells = filled_cells - init_cells if placed_cells < 0: placed_cells = 0 stats_section = ( f"\nProgress: {filled_cells}/{total_cells} cells filled ({init_cells} initial, {placed_cells} placed)\n" f"Steps: {t}/{max_actions}" ) # --- 5. Construct User Content --- turn_header = f"Turn {t + 1}:\nState:" constraint_prompt = ( f"You have {actions_left} actions left. Always output: [Your thoughts] " f" [your answer] with no extra text. Strictly follow this format. " f"Max response length: {max_tokens} words (tokens)." ) # COMBINE: Reward + Header + Board + Valid + Stats + Constraint full_user_text = ( f"{reward_prefix}{turn_header}\n" f"{board_str}{valid_section}\n{stats_section}\n{constraint_prompt}" ) # --- 6. Append to Messages --- if t == 0: # First turn: Append to the "Intro" user message messages[-1]["content"] += ("\n" + full_user_text) else: # Subsequent turns: New User message containing (Reward + State) messages.append({"role": "user", "content": full_user_text}) # --- 7. Assistant Response --- r_act, c_act, n_act = decode_action(actions[t], G) ans_text = f"place {n_act} at row {r_act} col {c_act}" assistant_text = f" {ans_text}" messages.append({"role": "assistant", "content": assistant_text}) return messages def convert_file(step_dir: Path, output_dir: Path, include_failed: bool = False, max_actions_override: int | None = None) -> Path: traj_path = step_dir / "trajectories.jsonl" metrics_path = step_dir / "metrics.json" if not traj_path.exists(): raise FileNotFoundError(f"Missing trajectories.jsonl at {traj_path}") max_tokens = 150 output_dir.mkdir(parents=True, exist_ok=True) out_path = output_dir / f"{step_dir.name}_sft.jsonl" global_step = None if metrics_path.exists(): try: with open(metrics_path, "r", encoding="utf-8") as f: m = json.load(f) global_step = m.get("global_step") except Exception: pass written = 0 with open(traj_path, "r", encoding="utf-8") as fin, open(out_path, "w", encoding="utf-8") as fout: for line in fin: line = line.strip() if not line: continue traj = json.loads(line) ep_success = bool(traj.get("episode_success", False)) if (not include_failed) and (not ep_success): continue states = traj.get("states", []) actions = traj.get("actions", []) rewards = traj.get("rewards", []) if not states: continue G = infer_grid_size_from_state_len(len(states[0])) if max_actions_override is not None: eff_max = max_actions_override else: eff_max = 20 if G == 4 else int(G*G * 1.5) messages = build_messages_for_episode( states=states, actions=actions, rewards=rewards, max_tokens=max_tokens, max_actions=eff_max, ) record = { "messages": messages, "meta": { "episode_return": traj.get("episode_return", None), "episode_success": ep_success, "global_step": global_step, }, } fout.write(json.dumps(record, ensure_ascii=False) + "\n") written += 1 return out_path def find_latest_step_dir(traj_root: Path) -> Path: step_dirs = [p for p in traj_root.iterdir() if p.is_dir() and p.name.startswith("step_")] if not step_dirs: raise FileNotFoundError(f"No step_* directories under {traj_root}") step_dirs.sort(key=lambda p: int(p.name.split("_")[-1])) return step_dirs[-1] def main(): parser = argparse.ArgumentParser(description="Convert Sudoku RL trajectories to LLM SFT chat JSONL (Rich Format, Merged Reward)") parser.add_argument("run_dir", help="Path to the run directory (contains trajectories/)") parser.add_argument("--step", default=None, help="Specific step directory name") parser.add_argument("--include_failed", action="store_true", help="Include failed episodes") parser.add_argument("--max_actions", type=int, default=None, help="Max actions cap display") args = parser.parse_args() run_dir = Path(args.run_dir) traj_root = run_dir / "trajectories" if not traj_root.exists(): raise FileNotFoundError(f"Not found trajectories directory: {traj_root}") step_dir = traj_root / args.step if args.step else find_latest_step_dir(traj_root) output_dir = run_dir / "sft" out_path = convert_file( step_dir=step_dir, output_dir=output_dir, include_failed=args.include_failed, max_actions_override=args.max_actions ) print(f"SFT data written to: {out_path}") if __name__ == "__main__": main()