File size: 17,791 Bytes
fcc38f9 | 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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | #!/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 <answer> 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 <answer> 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>{think}</think><answer>{action_word}</answer>"
if prompt_format == "free_think":
return f"<think> </think><answer>{action_word}</answer>"
if prompt_format == "grounding":
return (
f"<think><observation> </observation><reasoning> </reasoning></think>"
f"<answer>{action_word}</answer>"
)
if prompt_format == "worldmodeling":
return (
f"<think><reasoning> </reasoning><prediction> </prediction></think>"
f"<answer>{action_word}</answer>"
)
if prompt_format == "grounding_worldmodeling":
return (
f"<think><observation> </observation><reasoning> </reasoning><prediction> </prediction></think>"
f"<answer>{action_word}</answer>"
)
raise ValueError(f"Unhandled prompt_format: {prompt_format}")
def _split_text_by_placeholder(text: str, placeholder: str = "<image>") -> 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 = "<image>"
) -> 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 = "<image>"
) -> 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("<image>") + "\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], "<image>") + "\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 <answer> 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 </think> 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()
|