File size: 9,553 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
#!/usr/bin/env python3
"""
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  # type: ignore
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)):
        # 获取当前步骤的文本状态
        # text_states[0] 是初始状态, text_states[1] 是 action[0] 之后的状态
        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)."

        # --- 核心修改:使用保存的文本状态并拼接 Question ---
        turn_content = (
            f"\nTurn {t + 1}:\n"
            f"State:\n"
            f"{current_text_state}\n" # text_state 已经包含了 === Blackjack Game State === 等内容
            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}"
        )

        # 追加到上一条 user 消息(如果是第一回合)或者新建 user 消息
        if messages[-1]["role"] == "user":
            messages[-1]["content"] += turn_content
        else:
            messages.append({"role": "user", "content": turn_content})

        # 添加 Assistant 回复
        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 信息
        reward_val = rewards[t] 
        messages.append({"role": "user", "content": f"Reward:\n{reward_val}\n"})

    # 移除最后一条仅包含 Reward 的 User 消息(SFT 数据通常以 Assistant 结尾)
    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 字段
            text_states = traj.get("text_states", [])
            actions = traj.get("actions", [])
            rewards = traj.get("rewards", [])
            
            # 兼容性检查:如果该轨迹是旧代码生成的(没有 text_states),则跳过
            if not text_states:
                # Silently skip or warn
                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()