| |
| """ |
| Convert RL test trajectories from Blackjack into LLM SFT-ready language trajectories. |
| Uses pre-recorded text_states from the training script to ensure exact match with environment feedback. |
| |
| Input: runs/<exp>/trajectories/step_XXXXXX/trajectories.jsonl |
| Output: runs/<exp>/sft/step_XXXXXX_sft.jsonl |
| """ |
|
|
| import argparse |
| import json |
| import os |
| from pathlib import Path |
| from typing import List, Tuple |
|
|
| try: |
| import yaml |
| except Exception: |
| yaml = None |
|
|
| ACTION_LOOKUP = {0: "Stick", 1: "Hit"} |
|
|
|
|
| def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, bool, str, int]: |
| """Load Blackjack env_instruction, max_tokens, enable_think, action_sep, max_actions. |
| Fallbacks are provided if YAML is unavailable or keys are missing. |
| """ |
| instruction = ( |
| "You are playing Blackjack against a dealer. The dealer must hit on 16 or less and stand on 17 or more.\n" |
| "Choose either Stick or Hit. Respond with a single action.\n" |
| "Example: <answer>Hit</answer>" |
| ) |
| max_tokens = 64 |
| enable_think = True |
| action_sep = "||" |
| max_actions = 10 |
|
|
| if yaml is None: |
| instruction += ( |
| "\nYour available actions are:\n" |
| "Stick, Hit\n" |
| f"You can make up to {max_actions} actions, separated by the action separator \" " + action_sep + " \"\n" |
| ) |
| return instruction, max_tokens, enable_think, action_sep, max_actions |
|
|
| 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): |
| bj = envs.get("Blackjack", {}) |
| if isinstance(bj, dict): |
| instruction = bj.get("env_instruction", instruction) |
| max_tokens = int(bj.get("max_tokens", max_tokens)) |
| max_actions = int(bj.get("max_actions_per_traj", max_actions)) |
| 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 |
| |
| instruction += ( |
| "\nYour available actions are:\n" |
| "Stick, Hit\n" |
| f"You can make up to {max_actions} actions, separated by the action separator \" " + action_sep + " \"\n" |
| ) |
| return instruction, max_tokens, enable_think, action_sep, max_actions |
|
|
|
|
| def build_messages_for_episode( |
| text_states: List[str], |
| actions: List[int], |
| rewards: List[float], |
| instruction: str, |
| max_tokens: int, |
| 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 in range(len(actions)): |
| |
| |
| current_text_state = text_states[t] |
| |
| 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)." |
|
|
| |
| turn_content = ( |
| f"\nTurn {t + 1}:\n" |
| f"State:\n" |
| f"{current_text_state}\n" |
| f"What is your next move?\n" |
| f"You have {actions_left} actions left. Always output: {format_prompt}" |
| f" with no extra text. Strictly follow this format. {length_prompt}" |
| ) |
|
|
| |
| if messages[-1]["role"] == "user": |
| messages[-1]["content"] += turn_content |
| else: |
| messages.append({"role": "user", "content": turn_content}) |
|
|
| |
| action_id = int(actions[t]) |
| action_name = ACTION_LOOKUP.get(action_id, "unknown") |
| assistant_text = ( |
| f"<think></think><answer>{action_name}</answer>" if enable_think else f"<answer>{action_name}</answer>" |
| ) |
| messages.append({"role": "assistant", "content": assistant_text}) |
| |
| |
| reward_val = rewards[t] |
| messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"}) |
|
|
| |
| if messages[-1]["role"] == "user": |
| messages.pop() |
|
|
| return messages |
|
|
|
|
| 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, enable_think, action_sep, cfg_max_actions = load_env_instruction_and_cfg(repo_root) |
| if max_actions is None: |
| max_actions = cfg_max_actions |
|
|
| 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 |
| |
| |
| text_states = traj.get("text_states", []) |
| actions = traj.get("actions", []) |
| rewards = traj.get("rewards", []) |
| |
| |
| if not text_states: |
| |
| continue |
|
|
| if len(actions) > max_actions: |
| continue |
|
|
| messages = build_messages_for_episode( |
| text_states=text_states, |
| actions=actions, |
| rewards=rewards, |
| instruction=instruction, |
| max_tokens=max_tokens, |
| 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 |
| print("Warning: No trajectories converted. Check if input file has 'text_states' or if filtering is too strict.") |
| |
| 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 Blackjack 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_499712)") |
| 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="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() |