File size: 4,688 Bytes
aa1df78 | 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 | """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()
|