File size: 10,350 Bytes
70a7f67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Convert RL eval trajectories from Rubik's Cube 2x2 into LLM SFT-ready chat data.

Input: runs/<exp>/trajectories/step_XXXXXX/trajectories.jsonl
Output: runs/<exp>/sft/step_XXXXXX_sft.jsonl

Each output JSON line contains:
  - messages: [{role: system|user|assistant, content: str}, ...]
  - meta: {episode_return: float, episode_success: bool, global_step: int}

We mirror the FrozenLake converter structure:
  - system: "You're a helpful assistant. "
  - user: env_instruction + per-turn state blocks
  - assistant: tag-only actions, one per step
  - user: reward after each action
"""

import argparse
import json
from pathlib import Path
from typing import List, Tuple

try:
    import yaml  # type: ignore
except Exception:
    yaml = None


# Rubik's 2x2 actions (env uses 1..12; PPO wrapper stores 0..11)
RUBIK_ACTIONS = [
    "U", "U'", "D", "D'", "L", "L'", "R", "R'", "F", "F'", "B", "B'",
]

COLORS = ['W', 'O', 'G', 'R', 'B', 'Y']


def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, str, bool, int]:
    """Load RubiksCube2x2 env instruction and base agent_proxy configs.
    Returns: (instruction, max_tokens, action_sep, enable_think, max_actions)
    """
    instruction = (
        "You are solving a 2x2 Rubik's Cube (Pocket Cube). The goal is to restore the cube so that each of the faces consists of a single, unique color.\n"
        "Available actions use standard Singmaster notation for face rotations: U, U', D, D', L, L', R, R', F, F', B, B'.\n"
        "- Faces: U (Up), D (Down), L (Left), R (Right), F (Front), B (Back).\n"
        "- Modifiers: A letter alone means 90° clockwise (e.g., 'R'). A letter with prime (') means 90° counter-clockwise (e.g., \"R'\")."
        "Respond with a sequence of actions separated by \"||\".\n"
        "Example: <answer>U</answer>\n\n"
        "Your available actions are:\n"
        "U, U', D, D', L, L', R, R', F, F', B, B'\n"
        "You can make up to 20 actions, separated by the action separator \" || \"\n"
    )
    max_tokens = 96
    action_sep = "||"
    enable_think = True
    max_actions = 20

    if yaml is None:
        return instruction, max_tokens, action_sep, enable_think, max_actions

    # 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 "RubiksCube2x2" in envs["custom_envs"]:
                e = envs["custom_envs"]["RubiksCube2x2"]
                instruction = e.get("env_instruction", instruction)
                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

    return instruction, max_tokens, action_sep, enable_think, max_actions


def decode_state_to_text(state_vec: List[float]) -> str:
    """Decode one-hot length 24*6 vector into sticker letters.
    Returns a compact textual block listing each face in order: U, L, F, R, B, D.
    """
    if not state_vec:
        return ""
    n = len(state_vec)
    if n % len(COLORS) != 0:
        return ""
    n_stickers = n // len(COLORS)
    if n_stickers != 24:
        # Unknown shape; still try to decode row-wise
        pass
    # decode one-hot to color letter per sticker
    stickers: List[str] = []
    for i in range(n_stickers):
        base = i * len(COLORS)
        cell = state_vec[base: base + len(COLORS)]
        idx = max(range(len(COLORS)), key=lambda k: cell[k])
        c = COLORS[idx] if 0 <= idx < len(COLORS) else '?'
        stickers.append(c)
    # format faces (4 stickers per face)
    faces = [stickers[i*4:(i+1)*4] for i in range(6)]
    face_names = ["Up (U)", "Left (L)", "Front (F)", "Right (R)", "Back (B)", "Down (D)"]
    lines = ["=== Rubik's Cube 2x2 State ===\n"]
    for name, face in zip(face_names, faces):
        lines.append(f"{name}: [{face[0]}, {face[1]}] \n [{face[2]}, {face[3]}]")
    lines.append("\nAvailable actions: \n" + ", ".join(RUBIK_ACTIONS))
    return "\n".join(lines)


def build_messages_for_episode(
    states: 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)
    for t, state in enumerate(states):
        state_text = decode_state_to_text(state)
        actions_left = max(0, max_actions - t)
        format_prompt = (
            "<think> [Your thoughts] </think> <answer> [your answer] </answer>"
            if enable_think
            else "<answer> [your answer] </answer>"
        )
        length_prompt = f"Max response length: {max_tokens} words (tokens)."

        messages[-1]["content"] += (
            f"\nTurn {t + 1}:\n"
            f"State:\n{state_text}\n"
            f"\nWhat is your next move?\n"
            f"You have {actions_left} actions left. Always output: {format_prompt}"
            f"with no extra text. {length_prompt}"
        )

        if t < total_actions:
            a = actions[t]
            a_name = RUBIK_ACTIONS[int(a)] if 0 <= int(a) < len(RUBIK_ACTIONS) else str(a)
            if enable_think:
                assistant_text = f"<think> </think><answer>{a_name}</answer>"
            else:
                assistant_text = f"<answer>{a_name}</answer>"
            messages.append({"role": "assistant", "content": assistant_text})
            r = rewards[t] if t < len(rewards) else 0.0
            messages.append({"role": "user", "content": f"Reward:\n{r}\n"})
    # import pdb;pdb.set_trace()
    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", [])
            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"):
            pass
    return out_path


def main():
    parser = argparse.ArgumentParser(description="Convert Rubik's Cube 2x2 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_123456)")
    parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
    parser.add_argument("--max_actions", type=int, default=None, 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()