#!/usr/bin/env python3 """ Convert Rubik's Cube DQN trajectories to SFT JSON. Prompt layout follows VAGEN_old/vagen/env/rubikscube/prompt.py (FORMAT_CONFIGS + templates). By default, actions in and "Last valid action(s)" use natural language aligned with the reasoning style in FORMAT_CONFIGS (e.g. "Rotate Up clockwise"); use --action_repr token for canonical symbols (UpCW, UpCCW, ...). """ from __future__ import annotations import argparse import importlib.util import json from pathlib import Path from typing import Any, Dict, List, Optional, Tuple _REPO_ROOT = Path(__file__).resolve().parents[1] def _load_prompt_module(rel_path: str) -> Any: """Load vagen/env/*/prompt.py without importing vagen.env package __init__ (avoids side effects).""" path = _REPO_ROOT / rel_path name = "vagen_prompt_" + rel_path.replace("/", "_").replace(".py", "") spec = importlib.util.spec_from_file_location(name, path) if spec is None or spec.loader is None: raise ImportError(f"Cannot load prompt module from {path}") mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod _rc_prompt = _load_prompt_module("vagen/env/rubikscube/prompt.py") rc_action_template = _rc_prompt.action_template rc_format_prompt = _rc_prompt.format_prompt rc_init_observation_template = _rc_prompt.init_observation_template rc_system_prompt = _rc_prompt.system_prompt # Keep transfer robust if prompt.py changes/gets swapped. # We only append this block when the base system prompt lacks the face-name mapping. _NET_MAPPING_BLOCK = """\nVision observation (IMPORTANT):\n- The image shows the cube as a 2D unfolded net (a cross) with 6 faces, each face is a 2x2 grid.\n- Face names in the unfolded net are fixed as:\n\n [U]\n[L] [F] [R] [B]\n [D]\n\n Where:\n - U = Up (top face)\n - D = Down (bottom face)\n - F = Front (facing you)\n - B = Back (opposite of Front)\n - L = Left (left of Front)\n - R = Right (right of Front)\n\n- Sticker positions inside each 2x2 face in the image are:\n - index 0: top-left\n - index 1: top-right\n - index 2: bottom-left\n - index 3: bottom-right\n""" # --- Same action order as visual_scout/dqn_rubikscube.VagenRubiksCubeVisionWrapper.ACTIONS --- ACTION_ID_TO_WORD = { 0: "UpCW", 1: "UpCCW", 2: "DownCW", 3: "DownCCW", 4: "LeftCW", 5: "LeftCCW", 6: "RightCW", 7: "RightCCW", 8: "FrontCW", 9: "FrontCCW", 10: "BackCW", 11: "BackCCW", } PROMPT_FORMAT_CHOICES = tuple(rc_format_prompt.keys()) def _token_to_natural(token: str) -> str: """Natural phrasing consistent with rubikscube/prompt.py worldmodeling example ('Rotate Up clockwise.').""" if token.endswith("CCW"): face = token[:-3] return f"Rotate {face} counter-clockwise" if token.endswith("CW"): face = token[:-2] return f"Rotate {face} clockwise" raise ValueError(f"Unexpected action token: {token}") def _action_text(action_id: int, *, action_repr: str) -> str: """Text inside and in Last valid action(s).""" if int(action_id) not in ACTION_ID_TO_WORD: raise ValueError(f"Unknown action id: {action_id}") token = ACTION_ID_TO_WORD[int(action_id)] if action_repr == "token": return token if action_repr == "natural": return _token_to_natural(token) raise ValueError(f"Unknown action_repr: {action_repr}") def build_system_text(prompt_format: str, max_actions_per_step: int, action_sep: str) -> str: if prompt_format not in PROMPT_FORMAT_CHOICES: raise ValueError(f"Unknown prompt_format: {prompt_format}, expected one of {PROMPT_FORMAT_CHOICES}") fmt_block = rc_format_prompt[prompt_format](max_actions_per_step, action_sep, add_example=True) base = rc_system_prompt() # Append mapping block only if not already present (avoid duplication). if "Face names in the unfolded net are fixed as" not in base: base = base.rstrip() + "\n" + _NET_MAPPING_BLOCK.lstrip("\n") return base + "\n" + fmt_block def format_block_only(prompt_format: str, max_actions_per_step: int, action_sep: str) -> str: return rc_format_prompt[prompt_format](max_actions_per_step, action_sep, add_example=False) def _assistant_action_text(action_word: str, prompt_format: str, think: str = "") -> str: if think: return f"{think}{action_word}" if prompt_format == "free_think": return f" {action_word}" if prompt_format == "grounding": return ( f" " f"{action_word}" ) if prompt_format == "worldmodeling": return ( f" " f"{action_word}" ) if prompt_format == "grounding_worldmodeling": return ( f" " f"{action_word}" ) raise ValueError(f"Unhandled prompt_format: {prompt_format}") def _split_text_by_placeholder(text: str, placeholder: str = "") -> List[Dict[str, Any]]: parts = text.split(placeholder) if len(parts) == 1: return [{"type": "text", "text": text}] content: List[Dict[str, Any]] = [] for i, p in enumerate(parts): if p: content.append({"type": "text", "text": p}) if i < len(parts) - 1: content.append({"type": "image"}) return content def _fill_image_blocks(content: List[Dict[str, Any]], image_path: str) -> List[Dict[str, Any]]: out: List[Dict[str, Any]] = [] for block in content: if block.get("type") == "image" and "image" not in block: out.append({"type": "image", "image": image_path}) else: out.append(block) return out def _blocks_to_sharegpt_content_and_images( blocks: List[Dict[str, Any]], image_placeholder: str = "" ) -> Tuple[str, List[str]]: parts: List[str] = [] images: List[str] = [] for b in blocks: btype = b.get("type") if btype == "text": parts.append(str(b.get("text", ""))) elif btype == "image": parts.append(image_placeholder) img = b.get("image") if img is not None: images.append(str(img)) else: parts.append(str(b)) return "".join(parts), images def messages_to_llamafactory_sharegpt( messages: List[Dict[str, Any]], *, image_placeholder: str = "" ) -> Dict[str, Any]: out_messages: List[Dict[str, Any]] = [] out_images: List[str] = [] for m in messages: role = m.get("role") content = m.get("content") if isinstance(content, list): text, imgs = _blocks_to_sharegpt_content_and_images(content, image_placeholder=image_placeholder) out_messages.append({"role": role, "content": text}) out_images.extend(imgs) else: out_messages.append({"role": role, "content": "" if content is None else str(content)}) return {"messages": out_messages, "images": out_images} def build_messages_for_episode( frames: List[str], actions: List[int], rewards: Optional[List[float]] = None, *, action_repr: str, prompt_format: str, max_actions_per_step: int, action_sep: str, include_reward: bool, assistant_think: str, ) -> List[Dict[str, Any]]: if len(frames) != len(actions) + 1: raise ValueError(f"Expected len(frames)=len(actions)+1, got {len(frames)} vs {len(actions)}") sys_text = build_system_text(prompt_format, max_actions_per_step, action_sep) user_format_suffix = format_block_only(prompt_format, max_actions_per_step, action_sep) messages: List[Dict[str, Any]] = [{"role": "system", "content": sys_text}] init_text = rc_init_observation_template("") + "\n" + user_format_suffix init_content = _fill_image_blocks(_split_text_by_placeholder(init_text), frames[0]) messages.append({"role": "user", "content": init_content}) for t, act_id in enumerate(actions): act_word = _action_text(act_id, action_repr=action_repr) messages.append( { "role": "assistant", "content": _assistant_action_text(act_word, prompt_format, think=assistant_think), } ) obs_text = rc_action_template([act_word], "") + "\n" + user_format_suffix if include_reward: r = 0.0 if rewards is not None and t < len(rewards): try: r = float(rewards[t]) except Exception: r = 0.0 obs_text = f"Reward:\n{r}\n\n" + obs_text obs_content = _fill_image_blocks(_split_text_by_placeholder(obs_text), frames[t + 1]) messages.append({"role": "user", "content": obs_content}) return messages def extract_system_prefix(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: sys_msgs: List[Dict[str, Any]] = [] for m in messages: if m.get("role") == "system": sys_msgs.append(m) else: break return sys_msgs def collect_user_assistant_pairs(messages: List[Dict[str, Any]], start_idx: int = 0) -> List[List[Dict[str, Any]]]: pairs: List[List[Dict[str, Any]]] = [] i = int(start_idx) n = len(messages) while i < n: while i < n and messages[i].get("role") != "user": i += 1 if i >= n: break j = i + 1 if j < n and messages[j].get("role") == "assistant": pairs.append([messages[i], messages[j]]) i = j + 1 else: i += 1 return pairs def split_conversation_cumulative(messages: List[Dict[str, Any]], source_id: int) -> List[Dict[str, Any]]: sys_prefix = extract_system_prefix(messages) start_idx = len(sys_prefix) pairs = collect_user_assistant_pairs(messages, start_idx=start_idx) outputs: List[Dict[str, Any]] = [] total_turns = len(pairs) for k in range(1, total_turns + 1): out_msgs = sys_prefix + [m for pair in pairs[:k] for m in pair] outputs.append( { "messages": out_msgs, "meta": { "source_id": int(source_id), "turns": int(k), "total_turns": int(total_turns), }, } ) return outputs 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_step_dir( step_dir: Path, output_dir: Path, *, include_failed: bool, action_repr: str, prompt_format: str, max_actions_per_step: int, action_sep: str, include_reward: bool, assistant_think: str, strip_prefix: Optional[str], split_multiturn: bool, output_format: str, ) -> 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}") output_dir.mkdir(parents=True, exist_ok=True) out_path = output_dir / f"{step_dir.name}_sft.json" global_step = None if metrics_path.exists(): try: global_step = json.loads(metrics_path.read_text()).get("global_step") except Exception: global_step = None prefix = str(Path(strip_prefix)) if strip_prefix else None out_items: List[Dict[str, Any]] = [] source_id = 0 with traj_path.open("r", encoding="utf-8") as fin: 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 frames = traj.get("frames", []) actions = traj.get("actions", []) rewards = traj.get("rewards", []) if not frames or not actions: continue frames = [str(Path(p).resolve()) for p in frames] if prefix: new_frames = [] for p in frames: ps = str(p) if ps.startswith(prefix): ps = ps[len(prefix) :] if ps.startswith("/"): ps = ps[1:] new_frames.append(ps) frames = new_frames messages = build_messages_for_episode( frames=frames, actions=actions, rewards=rewards, action_repr=action_repr, prompt_format=prompt_format, max_actions_per_step=max_actions_per_step, action_sep=action_sep, include_reward=include_reward, assistant_think=assistant_think, ) meta: Dict[str, Any] = { "episode_return": traj.get("episode_return", None), "episode_success": ep_success, "global_step": global_step, } if split_multiturn: split_records = split_conversation_cumulative(messages, source_id=source_id) for sr in split_records: merged_meta = dict(meta) merged_meta.update(sr.get("meta", {})) if output_format == "llamafactory_sharegpt": rec = messages_to_llamafactory_sharegpt(sr["messages"]) out_items.append({**rec, "meta": merged_meta}) else: out_items.append({"messages": sr["messages"], "meta": merged_meta}) else: if output_format == "llamafactory_sharegpt": rec = messages_to_llamafactory_sharegpt(messages) out_items.append({**rec, "meta": meta}) else: out_items.append({"messages": messages, "meta": meta}) source_id += 1 out_path.write_text(json.dumps(out_items, ensure_ascii=False, indent=2), encoding="utf-8") return out_path def main(): parser = argparse.ArgumentParser( description="Convert visual Rubik's Cube eval trajectories to SFT JSON (vagen/env/rubikscube/prompt.py)." ) 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_400000)") parser.add_argument("--include_failed", action="store_true", help="Include failed episodes") parser.add_argument( "--action_repr", type=str, default="natural", choices=["natural", "token"], help='How to write each action in and "Last valid action(s)": ' 'natural = "Rotate Up clockwise" style (matches rubikscube/prompt.py examples); ' "token = UpCW, UpCCW, ... (canonical symbols from system prompt).", ) parser.add_argument( "--prompt_format", type=str, default="grounding_worldmodeling", choices=PROMPT_FORMAT_CHOICES, help="Must match a key in rubikscube/prompt.py FORMAT_CONFIGS", ) parser.add_argument("--max_actions_per_step", type=int, default=1, help="max_actions_per_step (format block)") parser.add_argument("--action_sep", type=str, default=",", help="Action separator in multi-action examples") parser.add_argument("--include_reward", action="store_true", help="Prefix each observation turn with reward") parser.add_argument("--assistant_think", type=str, default="", help="Assistant content (optional)") parser.add_argument("--strip_prefix", type=str, default=None, help="Optional path prefix to strip from frame paths") parser.add_argument( "--output_format", type=str, default="llamafactory_sharegpt", choices=["llamafactory_sharegpt", "internal_blocks"], help="Output JSON format. Use llamafactory_sharegpt for LLaMAFactory (messages+images).", ) parser.add_argument( "--no_split_multiturn", action="store_true", help="Disable cumulative multi-turn splitting; output one sample per episode.", ) 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_step_dir( step_dir=step_dir, output_dir=output_dir, include_failed=args.include_failed, action_repr=args.action_repr, prompt_format=args.prompt_format, max_actions_per_step=args.max_actions_per_step, action_sep=args.action_sep, include_reward=args.include_reward, assistant_think=args.assistant_think, strip_prefix=args.strip_prefix, split_multiturn=(not args.no_split_multiturn), output_format=args.output_format, ) print(f"SFT data written to: {out_path}") if __name__ == "__main__": main()