File size: 9,094 Bytes
8fb9f5e | 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 | #!/usr/bin/env python3
import argparse
import json
import re
from pathlib import Path
from typing import List, Tuple, Optional
try:
import yaml # type: ignore
except Exception:
yaml = None
DEFAULT_BANDIT_INSTRUCTION = (
"""Turn 1:
State:
You are playing a bandit game. Goal: Maximize your total reward by choosing which arm to pull.
Game Rules:
""")
def load_env_instruction_and_cfg(repo_root: Path) -> Tuple[str, int, bool]:
instruction = DEFAULT_BANDIT_INSTRUCTION
max_tokens = 100
enable_think = True
if yaml is None:
return instruction, max_tokens, enable_think
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)
custom_envs = envs.get("custom_envs", {}) if isinstance(envs, dict) else {}
if isinstance(custom_envs, dict):
# Prefer Bandit, fallback to BanditTest
for key in ["Bandit", "BanditTest"]:
if key in custom_envs:
cfg = custom_envs[key]
instruction = cfg.get("env_instruction", instruction) or instruction
max_tokens = int(cfg.get("max_tokens", max_tokens))
break
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 {}
enable_think = bool(ap.get("enable_think", enable_think))
except Exception:
pass
return instruction, max_tokens, enable_think
def parse_names_from_text(text: str) -> Optional[Tuple[str, str]]:
# Heuristic similar to BanditWrapper: find segment after "named " and split by " and "
try:
anchor = "named "
if anchor in text:
segment = text.split(anchor, 1)[1]
segment = segment.split("\n", 1)[0]
parts = segment.split(" and ")
if len(parts) >= 2:
name_a = parts[0].strip().strip(' .!?,')
name_b = parts[1].strip().strip(' .!?,')
if name_a and name_b:
return name_a, name_b
except Exception:
pass
# Secondary regex attempt: capture two capitalized tokens joined by and
m = re.search(r"([A-Za-z][\w]*)\s+and\s+([A-Za-z][\w]*)", text)
if m:
return m.group(1), m.group(2)
return None
def build_messages_for_episode(
names: Tuple[str, str],
actions: List[int],
rewards: List[float],
instruction: str,
max_tokens: int,
enable_think: bool,
) -> List[dict]:
name_a, name_b = names
# Enrich instruction with the two arm names so the SFT sample is self-contained
enriched_instr = (
f"{instruction}\n"
f"1. There are 2 arms, named {name_a} and {name_b}\n"
f"""2. Each arm has its own reward distribution, related to their names.
3. Analyze the symbolic meaning of each arm's name to guess how their reward distribution might behave.\n"""
f"4. Based on the symbolic meaning of their names, which arm do you think is more likely to give higher rewards on average? Choose between {name_a} and {name_b}, and output like <answer> {name_a} </answer> or <answer> {name_b} </answer>.\n"
)
messages = [
{"role": "system", "content": "You're a helpful assistant. "},
{"role": "user", "content": enriched_instr},
]
# Bandit is single-step in our setup; still handle lists robustly
turns = max(len(actions), 1)
for t in range(turns):
# Only one turn state block; reiterate arms for clarity
length_prompt = f"Max response length: {max_tokens} words (tokens)."
fmt = "<answer> [your answer] </answer>" if not enable_think else "<think> [Your thoughts] </think> <answer> [your answer] </answer>"
messages[-1]["content"] += (
f"\nYou have 1 action left. Always output: {fmt} with no extra text. Strictly follow this format. {length_prompt}"
)
if t < len(actions):
act = int(actions[t])
# RL action space is {0,1}; env expects {1,2}, but for chat we emit the chosen name
chosen = name_a if act == 0 else name_b
assistant_text = f"<answer>{chosen}</answer>" if not enable_think else f"<think></think><answer>{chosen}</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"})
return messages[:-1]
def convert_file(step_dir: Path, output_dir: Path, repo_root: Path, include_failed: bool = False) -> 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 = load_env_instruction_and_cfg(repo_root)
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
# Try to obtain the two arm names from the trajectory
names_tuple: Optional[Tuple[str, str]] = None
if isinstance(traj.get("prompt"), str):
names_tuple = parse_names_from_text(traj["prompt"]) # if prompt field exists
if names_tuple is None and isinstance(traj.get("states_text"), list) and len(traj["states_text"]) > 0:
names_tuple = parse_names_from_text(traj["states_text"][0])
if names_tuple is None and isinstance(traj.get("names"), list) and len(traj["names"]) >= 2:
names_tuple = (str(traj["names"][0]), str(traj["names"][1]))
if names_tuple is None:
# Fallback placeholders; this loses semantic meaning but still yields a valid SFT record
names_tuple = ("ArmA", "ArmB")
actions = traj.get("actions", []) or []
rewards = traj.get("rewards", []) or []
messages = build_messages_for_episode(
names=names_tuple,
actions=actions,
rewards=rewards,
instruction=instruction,
max_tokens=max_tokens,
enable_think=enable_think,
)
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
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 Bandit 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_10000)")
parser.add_argument("--include_failed", action="store_true", help="Include failed episodes in SFT data")
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)
print(f"SFT data written to: {out_path}")
if __name__ == "__main__":
main()
|