Download train/build_sft.py from RightNowAI/RightNow-Mini: direct link, hf CLI and curl.
- Browser
- Download file 4.69 kB
-
https://huggingface.co/RightNowAI/RightNow-Mini/resolve/main/train/build_sft.py
- Command line
-
hf download hf://RightNowAI/RightNow-Mini/train/build_sft.py
-
curl -L -o build_sft.py https://huggingface.co/RightNowAI/RightNow-Mini/resolve/main/train/build_sft.py
4.69 kB
| """Turn graded attempts into fine-tuning data: per task, the shortest attempt whose patch passed the task's tests. | |
| python train/build_sft.py /data/train/mini/results/gen /data/train/mini/results/sft | |
| Reads <gen>/att-<k>/<instance>/<instance>.traj.json the agent's messages (the stock model's own outputs only) | |
| <gen>/att-<k>/resolved.json {"resolved": [instance ids]} written by train/collect_grades.py | |
| Writes <out>/sft.jsonl one conversation per kept task, in the model's chat format | |
| <out>/stats.json the counts that go into results/train.md | |
| No closed model's output is in this data: every assistant message was generated by the stock model on this node. | |
| """ | |
| import collections | |
| import glob | |
| import hashlib | |
| import json | |
| import os | |
| import sys | |
| BASH_TOOL = None # filled from the harness, so training sees the exact tool declaration the agent sends | |
| def clean(messages): | |
| out = [] | |
| for m in messages: | |
| role = m["role"] | |
| if role in ("system", "user"): | |
| out.append({"role": role, "content": m["content"]}) | |
| elif role == "tool": | |
| out.append({"role": "tool", "content": m["content"], "tool_call_id": m.get("tool_call_id")}) | |
| elif role == "assistant": | |
| a = {"role": "assistant", "content": m.get("content") or ""} | |
| if m.get("reasoning_content"): | |
| a["reasoning_content"] = m["reasoning_content"] | |
| calls = [] | |
| for tc in m.get("tool_calls") or []: | |
| args = tc["function"].get("arguments") or "{}" | |
| calls.append({"id": tc.get("id"), "type": "function", | |
| "function": {"name": tc["function"]["name"], "arguments": json.loads(args) if isinstance(args, str) else args}}) | |
| if calls: | |
| a["tool_calls"] = calls | |
| out.append(a) | |
| return out | |
| def size_of(traj): | |
| last = 0 | |
| for m in traj["messages"]: | |
| u = ((m.get("extra") or {}).get("response") or {}).get("usage") if m["role"] == "assistant" else None | |
| if u: | |
| last = u.get("prompt_tokens", 0) + u.get("completion_tokens", 0) | |
| return last | |
| def main(): | |
| gen, out = sys.argv[1], sys.argv[2] | |
| os.makedirs(out, exist_ok=True) | |
| from minisweagent.models.utils.actions_toolcall import BASH_TOOL as tool # the harness's own declaration | |
| attempts = sorted(glob.glob(gen + "/att-*")) | |
| per_task = collections.defaultdict(list) | |
| counts = collections.Counter() | |
| for a in attempts: | |
| try: | |
| resolved = set(json.load(open(a + "/resolved.json"))["resolved"]) | |
| except OSError: | |
| counts["attempts_not_graded"] += 1 | |
| continue | |
| counts["attempts_graded"] += 1 | |
| for f in glob.glob(a + "/*/*.traj.json"): | |
| iid = os.path.basename(os.path.dirname(f)) | |
| counts["trajectories"] += 1 | |
| if iid not in resolved: | |
| continue | |
| counts["trajectories_passed"] += 1 | |
| try: | |
| t = json.load(open(f)) | |
| except ValueError: | |
| counts["unreadable"] += 1 | |
| continue | |
| if t["info"].get("exit_status") != "Submitted": | |
| counts["passed_but_not_submitted"] += 1 | |
| continue | |
| patch = (t["info"].get("submission") or "").strip() | |
| per_task[iid].append((size_of(t), os.path.basename(a), hashlib.sha256(patch.encode()).hexdigest()[:16], t)) | |
| kept = [] | |
| distinct_patches = 0 | |
| for iid, xs in sorted(per_task.items()): | |
| distinct_patches += len({x[2] for x in xs}) | |
| size, att, ph, t = min(xs, key=lambda x: (x[0], x[1])) | |
| kept.append({"instance_id": iid, "attempt": att, "tokens_at_end": size, "patch_sha": ph, "passing_attempts": len(xs), | |
| "messages": clean(t["messages"])}) | |
| with open(out + "/sft.jsonl", "w", encoding="utf-8") as f: | |
| for k in kept: | |
| f.write(json.dumps(k) + "\n") | |
| json.dump(tool, open(out + "/tool.json", "w")) | |
| stats = {"attempt_folders": len(attempts), **counts, "tasks_with_a_passing_attempt": len(per_task), | |
| "kept_conversations": len(kept), "distinct_passing_patches": distinct_patches, | |
| "median_tokens_at_end": sorted(k["tokens_at_end"] for k in kept)[len(kept) // 2] if kept else None, | |
| "max_tokens_at_end": max((k["tokens_at_end"] for k in kept), default=None), | |
| "assistant_turns_total": sum(sum(1 for m in k["messages"] if m["role"] == "assistant") for k in kept)} | |
| json.dump(stats, open(out + "/stats.json", "w"), indent=1) | |
| print(json.dumps(stats)) | |
| if __name__ == "__main__": | |
| main() | |