Upload 13 files
Browse filesFiles changed (13)
- train/build_sft.pyAdded+104
- train/collect_grades.pyAdded+31
- train/expert_usage.pyAdded+79
- train/gen.shAdded+33
- train/grade.shAdded+27
- train/graft.pyAdded+152
- train/make_pool.pyAdded+88
- train/make_task_states.pyAdded+33
- train/merge_test.pyAdded+34
- train/prefetch_branches.shAdded+40
- train/prune_experts.pyAdded+72
- train/pull_pool.shAdded+27
- train/sft.pyAdded+113
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""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.pyWrites <out>/sft.jsonl one conversation per kept task, in the model's chat format <out>/stats.json the counts that go into results/train.mdNo closed model's output is in this data: every assistant message was generated by the stock model on this node."""import collectionsimport globimport hashlibimport jsonimport osimport 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()12345678910111213141516171819202122232425262728293031"""Read SWE-smith's grading report of each attempt and write att-<k>/resolved.json for train/build_sft.py.
python train/collect_grades.py /data/train/mini/results/gen"""import globimport jsonimport osimport sys
def main(): gen = sys.argv[1] total = {} for a in sorted(glob.glob(gen + "/att-*")): reports = glob.glob(a + "/grade/logs/run_evaluation/*/report.json") if not reports: print(os.path.basename(a), "no grading report") continue r = json.load(open(reports[0])) resolved = sorted(r.get("ids_resolved") or []) preds = json.load(open(a + "/preds.json")) with_patch = sum(1 for v in preds.values() if (v.get("model_patch") or "").strip()) json.dump({"resolved": resolved, "graded": r.get("total"), "attempted": len(preds), "with_patch": with_patch}, open(a + "/resolved.json", "w")) total[os.path.basename(a)] = {"attempted": len(preds), "with_patch": with_patch, "graded": r.get("total"), "resolved": len(resolved)} print(json.dumps(total)) json.dump(total, open(gen + "/grades.json", "w"), indent=1)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Count how often each routed expert is chosen on coding traffic.
python train/expert_usage.py --model <released dir> --data <dir with sft.jsonl and tool.json> --out usage.json [--convs 60]
Runs the model forward (no training) over kept coding conversations and records, at every layer, which 8 of the128 experts the router picks for each token. The looped layers are visited three times per token; their visits areadded together, because the three passes share one set of experts."""import argparseimport jsonimport time
from unsloth import FastModel # noqa: E402import torch
def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--data", required=True) ap.add_argument("--out", required=True) ap.add_argument("--convs", type=int, default=60) ap.add_argument("--max-len", type=int, default=24000) a = ap.parse_args() model, tok = FastModel.from_pretrained(model_name=a.model, max_seq_length=a.max_len, load_in_4bit=False, full_finetuning=False) model.eval() gates = [(n, m) for n, m in model.named_modules() if type(m).__name__.endswith("TopKRouter")] # one per layer: `mlp.gate` if not gates: raise SystemExit("no router found: " + str([n for n, _ in model.named_modules() if "mlp" in n][:10])) topk = int(getattr(getattr(model.config, "text_config", model.config), "num_experts_per_tok", 8)) counts = {n: torch.zeros(128, dtype=torch.long) for n, _ in gates} calls = {n: 0 for n, _ in gates}
def hook(name): def f(_m, _inp, out): # the router returns its logits, its scores and the chosen expert indices: take the integer tensor idx = next(o for o in out if torch.is_tensor(o) and not o.is_floating_point()).detach().reshape(-1).cpu() counts[name] += torch.bincount(idx, minlength=128) calls[name] += 1 return f hs = [m.register_forward_hook(hook(n)) for n, m in gates] tool = json.load(open(a.data + "/tool.json")) rows = [json.loads(line) for line in open(a.data + "/sft.jsonl", encoding="utf-8")] tokens, used, t0 = 0, 0, time.time() with torch.no_grad(): for r in rows: enc = tok.apply_chat_template(r["messages"], tools=[tool], tokenize=True, add_generation_prompt=False, return_dict=True) ids = enc["input_ids"] if ids and isinstance(ids[0], (list, tuple)): ids = ids[0] if len(ids) > a.max_len: continue model(input_ids=torch.tensor([ids], device=model.device)) tokens += len(ids) used += 1 if used >= a.convs: break for h in hs: h.remove() layers = {} for n, c in counts.items(): share = (c.float() / c.sum().clamp(min=1)).tolist() order = sorted(range(128), key=lambda i: -c[i].item()) layers[n] = {"router_calls": calls[n], "counts": c.tolist(), "order_most_used_first": order, "share_of_top_96": round(sum(share[i] for i in order[:96]), 5), "share_of_top_64": round(sum(share[i] for i in order[:64]), 5), "never_used": int((c == 0).sum())} json.dump({"model": a.model, "conversations": used, "tokens": tokens, "topk": topk, "seconds": round(time.time() - t0, 1), "layers": layers}, open(a.out, "w")) s96 = sorted(v["share_of_top_96"] for v in layers.values()) s64 = sorted(v["share_of_top_64"] for v in layers.values()) print("USAGE", json.dumps({"routers": len(layers), "conversations": used, "tokens": tokens, "seconds": round(time.time() - t0, 1), "calls_per_router": sorted(set(calls.values())), "share kept by the 96 most used, per layer (min/median/max)": [s96[0], s96[len(s96) // 2], s96[-1]], "share kept by the 64 most used": [s64[0], s64[len(s64) // 2], s64[-1]], "router names": [n for n, _ in gates][:3]}))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233#!/usr/bin/env bash# Best-of-N data generation: sampled attempts of the stock model on every pool task, with the same bash-only agent# as the evaluation. Attempts run side by side, spread over the generation servers.# ATTEMPTS="1 2 3" PORTS="9003 9004 9005" bash train/gen.sh# Output: /data/train/mini/results/gen/att-<k>/{preds.json, <instance>/<instance>.traj.json}## A SWE-smith task is the repository with one bug put in. STARTUP builds that state in the container before the# agent starts, from files written by train/make_task_states.py (no network needed; the official way is a branch# fetched from GitHub, which failed while the data center's network was down on 2026-12-01).# (A first run that day built no state at all, so the agents worked on repositories without the bug: thrown away.)set -uR=/data/train/miniATTEMPTS=${ATTEMPTS:-1 2 3}; PORTS=(${PORTS:-9003 9004 9005})TEMP=${TEMP:-0.8}; STEPS=${STEPS:-75}; WORKERS=${WORKERS:-40}; MODEL=${MODEL:-hosted_vllm/inkling-2-mini}POOL=${POOL:-$R/src/train/pool/pool.json}; TAG=${TAG:-gen}DATA=${DATA:-smith}; SPLIT=${SPLIT:-train}; MAXTOK=${MAXTOK:-8192}if [ "$DATA" = smith ]; then STARTUP=${STARTUP:-'cd /testbed && git apply /patches/{{instance_id}}.diff 2>/dev/null && (git apply --numstat /patches/{{instance_id}}.diff | cut -f3 | xargs -r git add --) && (xargs -r git rm -q -f --ignore-unmatch -- < /patches/{{instance_id}}.rm) && git -c user.email=task@local -c user.name=task commit -qm task-state'}else STARTUP=${STARTUP:-}fiexport STARTUPi=0echo "== $TAG start $(date -u +%FT%TZ): attempts [$ATTEMPTS] on ports [${PORTS[*]}] temp=$TEMP steps=$STEPS workers=$WORKERS maxtok=$MAXTOK data=$DATA"for k in $ATTEMPTS; do port=${PORTS[$((i % ${#PORTS[@]}))]}; i=$((i + 1)) ( LABEL=$TAG-att-$k OUT=$R/results/$TAG/att-$k URL=http://127.0.0.1:$port/v1 MODEL=$MODEL WORKERS=$WORKERS TEMP=$TEMP \ STEPS=$STEPS SUBSET=$POOL DATA=$DATA SPLIT=$SPLIT MAXTOK=$MAXTOK taskset -c 32-255 bash $R/src/eval/run_agent.sh > $R/logs/$TAG-att-$k.log 2>&1 echo "attempt $k done $(date -u +%TZ): $(tail -1 $R/logs/$TAG-att-$k.log | cut -c1-200)" ) & sleep 5donewaitecho "== $TAG done $(date -u +%FT%TZ)"123456789101112131415161718192021222324252627#!/usr/bin/env bash# Grade every generated attempt with SWE-smith's own harness (the task's FAIL_TO_PASS and PASS_TO_PASS tests).# ATTEMPTS="1 2 ..." bash train/grade.sh# Output per attempt: /data/train/mini/results/gen/att-<k>/grade/ (the harness's logs and report)# PAR attempts are graded side by side, each with W workers.set -uR=/data/train/miniATTEMPTS=${ATTEMPTS:-1 2 3 4 5 6 7 8}; TAG=${TAG:-gen}; W=${W:-16}; PAR=${PAR:-3}INST=${INST:-$R/src/train/pool/pool_instances.json}one() { k=$1; D=$R/results/$TAG/att-$k [ -s $D/preds.json ] || { echo "attempt $k: no preds.json"; return; } sudo -n rm -rf $D/grade # the harness skips tasks it already has logs for: never grade on top of an older run mkdir -p $D/grade && cd $D/grade echo "== grade att-$k start $(date -u +%TZ)" sudo -n env PATH=$R/venv-smith/bin:/usr/bin:/bin HF_HOME=$R/hf MINI_ASSUME_PUBLIC=1 $R/venv-smith/bin/python -m swesmith.harness.eval \ -d "$INST" -p $D/preds.json --run_id $TAG-att-$k -w $W > $D/grade/eval.log 2>&1 sudo -n chown -R "$USER":"$USER" $D/grade $R/hf 2>/dev/null echo "== grade att-$k done $(date -u +%TZ): $(tail -3 $D/grade/eval.log | tr '\n' ' ' | cut -c1-200)"}n=0for k in $ATTEMPTS; do one "$k" & n=$((n + 1)) [ $((n % PAR)) = 0 ] && waitdonewait123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Put fine-tuned weights back into the released checkpoint's own format.
The trainer's tool writes a merged model with the routed experts in 16-bit. The serving engine on this GPU familytakes the experts only as released (4-bit NVFP4 and 8-bit MXFP8, declared per tensor in hf_quant_config.json), sothat merged folder cannot be served. The fine-tune here changes attention weights only, so the fix is exact: takethe released checkpoint and replace just the tensors the fine-tune changed. Everything else, the experts and theirquantization included, stays byte for byte as released.
python train/graft.py map --stock <released dir> --identity <merge of untrained adapters> --out map.json python train/graft.py apply --stock <released dir> --identity <same> --merged <fine-tuned merge> --map map.json --lora <adapter dir> --out <dir>
`map` finds which released tensor is which merged tensor by content: a merge of untrained adapters changes nothing,so equal shape and equal bytes identify a pair. `apply` refuses to go on if the fine-tune changed a tensor that hasno released counterpart (an expert, for one): nothing is then written."""import argparseimport globimport hashlibimport jsonimport osimport shutilimport sys
import torchfrom safetensors import safe_openfrom safetensors.torch import save_file
def digest(t): t = t.contiguous() raw = t.view(torch.uint8) if t.dtype == torch.uint8 else t.view(-1).view(torch.int16 if t.element_size() == 2 else torch.int32 if t.element_size() == 4 else torch.int8 if t.element_size() == 1 else torch.int64) return hashlib.sha1(raw.numpy().tobytes()).hexdigest()
def tensors(folder, pattern="model*.safetensors"): for f in sorted(glob.glob(os.path.join(folder, pattern))): with safe_open(f, framework="pt") as sf: for k in sf.keys(): yield f, k, sf.get_tensor(k)
def cmd_map(a): by = {} n_id = 0 for _f, k, t in tensors(a.identity): n_id += 1 by.setdefault((tuple(t.shape), str(t.dtype), digest(t)), []).append(k) mapping, unmatched, ambiguous = {}, [], 0 used = set() n_stock = 0 for _f, k, t in tensors(a.stock): n_stock += 1 cands = [c for c in by.get((tuple(t.shape), str(t.dtype), digest(t)), []) if c not in used] if not cands: unmatched.append([k, list(t.shape), str(t.dtype)]) continue if len(cands) > 1: ambiguous += 1 tail = k.split(".")[-2:] cands.sort(key=lambda c: (c.split(".")[-2:] != tail, c)) mapping[k] = cands[0] used.add(cands[0]) json.dump({"stock_tensors": n_stock, "identity_tensors": n_id, "matched": len(mapping), "ambiguous_by_content": ambiguous, "unmatched_stock": unmatched, "map": mapping}, open(a.out, "w"), indent=1) kinds = sorted({".".join(k[0].split(".")[-2:]) for k in unmatched}) print(json.dumps({"stock_tensors": n_stock, "identity_tensors": n_id, "matched": len(mapping), "ambiguous_by_content": ambiguous, "unmatched_stock": len(unmatched), "unmatched_kinds": kinds[:20]}))
def cmd_apply(a): m = json.load(open(a.map))["map"] back = {v: k for k, v in m.items()} ident = {k: (tuple(t.shape), digest(t)) for _f, k, t in tensors(a.identity)} changed = {} for _f, k, t in tensors(a.merged): if k not in ident: sys.exit(f"REFUSED: the fine-tuned merge has a tensor the untrained merge does not: {k}") if ident[k] != (tuple(t.shape), digest(t)): changed[k] = t no_home = sorted(k for k in changed if k not in back) if no_home and a.lora: # The merge writes the experts dequantized, and two merges need not round them alike. That is no change of # the model if the adapters hold no expert weight: read the adapter file itself to know. import re trained = [] for f in glob.glob(os.path.join(a.lora, "*.safetensors")): with safe_open(f, framework="pt") as sf: trained += list(sf.keys()) if not trained: sys.exit(f"REFUSED: no adapter weights found in {a.lora}. Nothing written.") on_experts = sorted(k for k in trained if ".self_attn." not in k) # every adapter weight must sit on an attention module if on_experts: sys.exit(f"REFUSED: {len(on_experts)} adapter weights are not on attention modules (first: {on_experts[:3]}). Nothing written.") ignored = [k for k in no_home if re.search(r"\.experts\.w(?:13|2)_weight$", k)] no_home = [k for k in no_home if k not in ignored] for k in ignored: changed.pop(k) print(json.dumps({"adapter_tensors": len(trained), "adapter_tensors_on_experts": 0, "expert_tensors_left_as_released": len(ignored)})) if no_home: sys.exit(f"REFUSED: {len(no_home)} changed tensors have no released counterpart (first: {no_home[:5]}). Nothing written.") os.makedirs(a.out, exist_ok=True) files = sorted(glob.glob(os.path.join(a.stock, "model*.safetensors"))) report = {"changed_tensors": len(changed), "changed": {}} for f in files: out, meta = {}, None with safe_open(f, framework="pt") as sf: meta = sf.metadata() for k in sf.keys(): t = sf.get_tensor(k) mk = m.get(k) if mk in changed: new = changed[mk] if tuple(new.shape) != tuple(t.shape) or new.dtype != t.dtype: sys.exit(f"REFUSED: {k}: released {tuple(t.shape)} {t.dtype}, fine-tuned {tuple(new.shape)} {new.dtype}") d = (new.float() - t.float()).abs() report["changed"][k] = {"merged_name": mk, "shape": list(t.shape), "max_abs_change": float(d.max()), "mean_abs_change": float(d.mean())} t = new out[k] = t save_file(out, os.path.join(a.out, os.path.basename(f)), metadata=meta) for f in os.listdir(a.stock): src = os.path.join(a.stock, f) if f.startswith("model") and f.endswith(".safetensors") or f in ("README.md", ".gitattributes") or f.startswith("."): continue dst = os.path.join(a.out, f) if os.path.isdir(src): shutil.copytree(src, dst, dirs_exist_ok=True) else: shutil.copy(src, dst) report["files"] = {f: os.path.getsize(os.path.join(a.out, f)) for f in sorted(os.listdir(a.out)) if os.path.isfile(os.path.join(a.out, f))} json.dump(report, open(os.path.join(a.out, "graft_report.json"), "w"), indent=1) print(json.dumps({"changed_tensors": len(changed), "gb": round(sum(report["files"].values()) / 1e9, 2), "largest_change": max((v["max_abs_change"] for v in report["changed"].values()), default=0.0)}))
def main(): ap = argparse.ArgumentParser() sub = ap.add_subparsers(dest="cmd", required=True) p = sub.add_parser("map") p.add_argument("--stock", required=True) p.add_argument("--identity", required=True) p.add_argument("--out", required=True) q = sub.add_parser("apply") for x in ("--stock", "--identity", "--merged", "--map", "--out"): q.add_argument(x, required=True) q.add_argument("--lora", default="", help="the adapter folder: lets the tool confirm that no expert weight was trained") a = ap.parse_args() cmd_map(a) if a.cmd == "map" else cmd_apply(a)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788"""The training pool: SWE-smith tasks (MIT) from repositories that share nothing with the evaluation benchmark.
python train/make_pool.py eval/subset.json train/pool # writes pool.json, pool_instances.json, disjoint.json
Rules, checked here and written to disjoint.json: - a training repository is never a repository of SWE-bench Verified (owner/name or bare name, case ignored); - only tasks with a problem statement, and only repositories whose tests run with pytest; - the draw is fixed: the REPOS largest eligible repositories, PER_REPO tasks each, one seed.Run with the SWE-smith environment's Python (it holds the repository profiles)."""import collectionsimport jsonimport randomimport reimport sysfrom pathlib import Path
from datasets import load_datasetfrom swesmith.profiles import registry
SEED, REPOS, PER_REPO = 20261201, 30, 8DATASET = "SWE-bench/SWE-smith"
def owner_name(repo): # "swesmith/oauthlib__oauthlib.1fd52536" -> "oauthlib/oauthlib" m = re.fullmatch(r"swesmith/(.+?)__(.+)\.[0-9a-f]{8}", repo) return (m.group(1) + "/" + m.group(2)).lower() if m else None
def main(): subset, out = json.load(open(sys.argv[1])), Path(sys.argv[2]) out.mkdir(parents=True, exist_ok=True) bench = [r.lower() for r in subset["all_repos_of_the_benchmark"]] bench_names = {r.split("/")[1] for r in bench} ds = load_dataset(DATASET, split="train") by_repo = collections.defaultdict(list) skipped = collections.Counter() for i, (iid, repo, ps) in enumerate(zip(ds["instance_id"], ds["repo"], ds["problem_statement"])): on = owner_name(repo) if on is None: skipped["name not understood"] += 1 elif on in bench or on.split("/")[1] in bench_names: skipped["repository of the benchmark"] += 1 elif not (ps and ps.strip()): skipped["no problem statement"] += 1 else: by_repo[repo].append(i) eligible = {} for repo, rows in by_repo.items(): try: prof = registry.get(repo) cmd = prof.test_cmd except Exception: skipped["no profile"] += len(rows) continue if "pytest" not in cmd: skipped["tests are not pytest"] += len(rows) continue eligible[repo] = (rows, prof.image_name) chosen = sorted(eligible, key=lambda r: (-len(eligible[r][0]), r))[:REPOS] rng = random.Random(SEED) rows, images = [], {} for repo in chosen: idx, image = eligible[repo] pick = sorted(rng.sample(sorted(idx), min(PER_REPO, len(idx)))) rows += pick images[repo] = {"harness_image": image, "dataset_image": ds[pick[0]]["image_name"], "tasks": len(pick), "eligible_tasks": len(idx)} inst = [ds[i] for i in rows] ids = sorted(x["instance_id"] for x in inst) train_repos = sorted({owner_name(r) for r in chosen}) overlap = sorted(set(train_repos) & set(bench)) + sorted({r.split("/")[1] for r in train_repos} & bench_names) (out / "pool.json").write_text(json.dumps({ "dataset": DATASET, "license": "mit", "split": "train", "dataset_fingerprint": ds._fingerprint, "seed": SEED, "method": f"the {REPOS} largest eligible repositories, random.Random(seed).sample of {PER_REPO} tasks each", "n": len(ids), "instance_ids": ids, "repositories": images, "skipped": dict(skipped)}, indent=1) + "\n", encoding="utf-8") (out / "pool_instances.json").write_text(json.dumps(inst) + "\n", encoding="utf-8") (out / "disjoint.json").write_text(json.dumps({ "evaluation_benchmark": subset["dataset"], "evaluation_repositories": bench, "evaluation_instance_ids": subset["instance_ids"], "training_dataset": DATASET, "training_repositories": train_repos, "training_instance_ids": ids, "repositories_in_both": overlap, "instance_ids_in_both": sorted(set(ids) & set(subset["instance_ids"])), "disjoint": not overlap and not (set(ids) & set(subset["instance_ids"]))}, indent=1) + "\n", encoding="utf-8") print(f"{len(ids)} tasks from {len(chosen)} repositories; skipped {dict(skipped)}; in both: {overlap}") if overlap: raise SystemExit("TRAINING AND EVALUATION SHARE A REPOSITORY")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233"""Write, for every pool task, what its container needs to reach the task's buggy state without the network.
python train/make_task_states.py train/pool/pool_instances.json /data/train/mini/pool_patches
A SWE-smith task is the repository with one bug put in and the tests that catch it taken out. Its official form is abranch on GitHub, which a container must fetch. While the data center's network was down that fetch failed, so thestate is rebuilt from the dataset itself: <id>.diff the bug itself (the dataset's `patch` is the change that puts the bug in), applied to the clean repository <id>.rm the test files that catch the bug (from FAIL_TO_PASS), removed so the agent cannot read themThe grading still uses the official branch (train/grade.sh), so a patch only counts if it fixes the real task."""import astimport jsonimport osimport sys
def main(): inst, out = json.load(open(sys.argv[1])), sys.argv[2] os.makedirs(out, exist_ok=True) for x in inst: i = x["instance_id"] patch = x["patch"] open(f"{out}/{i}.diff", "w", encoding="utf-8", newline="\n").write(patch if patch.endswith("\n") else patch + "\n") f2p = x["FAIL_TO_PASS"] f2p = ast.literal_eval(f2p) if isinstance(f2p, str) else list(f2p) files = sorted({t.split("::")[0] for t in f2p if t.split("::")[0].endswith(".py")}) open(f"{out}/{i}.rm", "w", encoding="utf-8", newline="\n").write("".join(f + "\n" for f in files)) print(f"{len(inst)} task states written to {out}")
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334"""Check the road a fine-tuned model takes after training, before the training itself: adapters, merge, save.
python train/merge_test.py --model /data/train/mini/models/Inkling-2-Mini --out /data/train/mini/models/mergetest-16bit
It attaches fresh adapters (which change nothing: their second matrix starts at zero) and writes the merged 16-bitmodel. Serving that folder with the engine then shows whether a merged model loads and answers. A check of thetools, never a result."""import argparseimport jsonimport osimport time
from unsloth import FastModel # noqa: E402
def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--out", required=True) a = ap.parse_args() t0 = time.time() model, tok = FastModel.from_pretrained(model_name=a.model, max_seq_length=4096, load_in_4bit=False, full_finetuning=False) model = FastModel.get_peft_model(model, finetune_vision_layers=False, finetune_language_layers=True, finetune_attention_modules=True, finetune_mlp_modules=True, r=16, lora_alpha=16, lora_dropout=0, bias="none", random_state=3407) t1 = time.time() model.save_pretrained_merged(a.out, tok, save_method="merged_16bit") files = {f: os.path.getsize(os.path.join(a.out, f)) for f in sorted(os.listdir(a.out))} print("MERGE_TEST", json.dumps({"load_s": round(t1 - t0, 1), "merge_s": round(time.time() - t1, 1), "gb": round(sum(files.values()) / 1e9, 2), "files": {k: v for k, v in files.items() if v > 1e6 or k.endswith(".json")}}))
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940#!/usr/bin/env bash# Put every task branch of the training repositories into their images, so the grading harness can check a task# out without the network (its own `git fetch` may fail; its `git checkout <task>` then still finds the branch).# Run on the node while GitHub is reachable. The image keeps its name and its default command; only fetched git# objects are added.## A commit of a container keeps the command the container ran as the image's default. The first run of this script# on 2026-12-01 left 18 images starting `bash -c <the fetch>` for 90 seconds, and task containers started in that# time failed. So: the config is put back with a one-line build right after the commit, under a temporary name, and# the real name is moved to the result only at the end.set -uR=/data/train/miniD=/usr/bin/dockerpython3 - <<'EOF' > /tmp/mini_pool_harness_images.txtimport jsonfor r, v in json.load(open("/data/train/mini/src/train/pool/pool.json"))["repositories"].items(): print(v["harness_image"], v["dataset_image"])EOFone() { img=$1; alt=$2; name=prefetch-$(echo "$img" | tr -c 'a-zA-Z0-9' '-' | cut -c1-60); tmp="mini-prefetch-tmp:$(echo "$img" | tr -c 'a-zA-Z0-9' '-' | cut -c1-80)" have=$($D run --rm "$img" bash -c 'cd /testbed && git branch -r | wc -l' 2>/dev/null | tr -d ' \n') if [ "${have:-0}" -ge 300 ]; then echo "ok $img: already $have remote branches"; return 0; fi $D rm -f "$name" >/dev/null 2>&1 $D run -d --name "$name" "$img" bash -c 'cd /testbed && for t in 1 2 3 4 5; do git fetch -q origin "+refs/heads/*:refs/remotes/origin/*" && break; sleep 20; done; git branch -r | wc -l > /tmp/branches.txt' >/dev/null || { echo "FAILED start $img"; return 1; } $D wait "$name" >/dev/null n=$($D cp "$name":/tmp/branches.txt - 2>/dev/null | tar -xO 2>/dev/null | tr -d ' \n') $D commit "$name" "$tmp" >/dev/null || { echo "FAILED commit $img"; $D rm -f "$name" >/dev/null 2>&1; return 1; } $D rm -f "$name" >/dev/null 2>&1 printf 'FROM %s\nENTRYPOINT []\nCMD ["/bin/bash"]\n' "$tmp" | $D build -q -t "$tmp-final" - >/dev/null 2>&1 || { echo "FAILED config $img"; return 1; } ep=$($D image inspect --format '{{json .Config.Entrypoint}} {{json .Config.Cmd}}' "$tmp-final") [ "$ep" = 'null ["/bin/bash"]' ] || { echo "FAILED config check $img: $ep"; return 1; } $D tag "$tmp-final" "$img" && $D tag "$img" "$alt" && $D tag "$img" "docker.io/$alt" $D rmi "$tmp" "$tmp-final" >/dev/null 2>&1 echo "ok $img: $n remote branches in the image"}export -f one; export Decho "== prefetch start $(date -u +%TZ)"xargs -P 4 -L 1 bash -c 'one "$0" "$1"' < /tmp/mini_pool_harness_images.txtecho "== prefetch done $(date -u +%TZ)"while read img alt; do echo "$($D image inspect --format 'EP={{json .Config.Entrypoint}} CMD={{json .Config.Cmd}}' "$img")"; done < /tmp/mini_pool_harness_images.txt | sort | uniq -c123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Drop the least-used routed experts of every layer, in the released checkpoint's own format.
python train/prune_experts.py --stock <released dir> --usage usage.json --keep 96 --out <dir>
Every expert tensor of the released checkpoint has the expert as its first dimension (the packed 4-bit or 8-bitweights, their scales, their per-expert maxima) and so has the router (`gate.weight`, `gate.bias`). Keeping anexpert is keeping its rows; nothing is re-quantized and no weight changes value. `n_routed_experts` in config.jsonis set to the number kept. The draft head (mtp.safetensors) and everything else are copied as they are."""import argparseimport globimport jsonimport osimport reimport shutil
import torchfrom safetensors import safe_openfrom safetensors.torch import save_file
def main(): ap = argparse.ArgumentParser() ap.add_argument("--stock", required=True) ap.add_argument("--usage", required=True) ap.add_argument("--keep", type=int, required=True) ap.add_argument("--out", required=True) a = ap.parse_args() usage = json.load(open(a.usage))["layers"] keep = {} for name, v in usage.items(): m = re.search(r"layers\.(\d+)\.", name) keep[int(m.group(1))] = sorted(v["order_most_used_first"][:a.keep]) os.makedirs(a.out, exist_ok=True) sliced, kept_share = 0, [] for f in sorted(glob.glob(os.path.join(a.stock, "model*.safetensors"))): out = {} with safe_open(f, framework="pt") as sf: meta = sf.metadata() for k in sf.keys(): t = sf.get_tensor(k) m = re.match(r"model\.llm\.layers\.(\d+)\.mlp\.(experts\.|gate\.)", k) if m and t.dim() >= 1 and t.shape[0] == 128: layer = int(m.group(1)) if layer not in keep: raise SystemExit(f"no usage for layer {layer}") t = t.index_select(0, torch.tensor(keep[layer])).contiguous() sliced += 1 out[k] = t save_file(out, os.path.join(a.out, os.path.basename(f)), metadata=meta) for f in os.listdir(a.stock): src = os.path.join(a.stock, f) if (f.startswith("model") and f.endswith(".safetensors")) or f in ("README.md", "graft_report.json") or f.startswith("."): continue dst = os.path.join(a.out, f) shutil.copytree(src, dst, dirs_exist_ok=True) if os.path.isdir(src) else shutil.copy(src, dst) cfg = json.load(open(os.path.join(a.out, "config.json"))) was = cfg["text_config"]["n_routed_experts"] cfg["text_config"]["n_routed_experts"] = a.keep json.dump(cfg, open(os.path.join(a.out, "config.json"), "w"), indent=2) for name, v in usage.items(): kept_share.append(v["share_of_top_%d" % a.keep] if "share_of_top_%d" % a.keep in v else None) size = sum(os.path.getsize(os.path.join(a.out, f)) for f in os.listdir(a.out) if os.path.isfile(os.path.join(a.out, f))) stock = sum(os.path.getsize(os.path.join(a.stock, f)) for f in os.listdir(a.stock) if os.path.isfile(os.path.join(a.stock, f))) rep = {"experts_before": was, "experts_kept": a.keep, "tensors_sliced": sliced, "layers": len(keep), "gb": round(size / 1e9, 2), "stock_gb": round(stock / 1e9, 2), "kept_per_layer": {str(k): v for k, v in sorted(keep.items())}} json.dump(rep, open(os.path.join(a.out, "prune_report.json"), "w")) print("PRUNED", json.dumps({k: v for k, v in rep.items() if k != "kept_per_layer"}))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627#!/usr/bin/env bash# Pull the test image of every training repository once (the harness's name) and tag it with the dataset's name too.# bash train/pull_pool.sh train/pool/pool.jsonset -uPOOL=${1:?pool.json}python3 - "$POOL" <<'EOF' > /tmp/mini_pool_images.txtimport json, sysfor r, v in json.load(open(sys.argv[1]))["repositories"].items(): print(v["harness_image"], v["dataset_image"])EOFpull_one() { h=$1; d=$2 for try in $(seq 1 30); do if sudo -n docker image inspect "$h" >/dev/null 2>&1 || sudo -n docker pull -q "$h" >/dev/null 2>&1; then sudo -n docker tag "$h" "$d" 2>/dev/null; sudo -n docker tag "$h" "docker.io/$d" 2>/dev/null echo "ok $h"; return 0 fi # the harness's name may not be published: fall back to the dataset's name if sudo -n docker pull -q "$d" >/dev/null 2>&1; then sudo -n docker tag "$d" "$h"; echo "ok(dataset name) $d"; return 0; fi sleep $((15 + try * 10)) done echo "FAILED $h"; return 1}export -f pull_oneecho "== pool pull start $(date -u +%FT%TZ): $(wc -l < /tmp/mini_pool_images.txt) images"xargs -P 6 -L 1 bash -c 'pull_one "$0" "$1"' < /tmp/mini_pool_images.txtecho "== pool pull done $(date -u +%FT%TZ): $(grep -c . /tmp/mini_pool_images.txt) asked"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""Fine-tune Inkling 2 Mini on the kept conversations, with Unsloth (LoRA on the attention weights; the routed experts stay as released).
python train/sft.py --model /data/train/mini/models/Inkling-2-Mini --data /data/train/mini/results/sft \ --out /data/train/mini/runs/sft-r1 [--smoke]
Only the assistant's own tokens carry loss (its reasoning, its text, its tool calls); the task text and the tooloutputs are context. The mask comes from the model's chat template, which marks every assistant span.`--smoke` loads the model, builds the first batch, runs three steps and stops: a check of the tool, not a result."""import argparseimport jsonimport osimport time
from unsloth import FastModel # noqa: E402 (must be imported before transformers)import torchfrom torch.utils.data import Datasetfrom transformers import Trainer, TrainingArguments
class Conversations(Dataset): def __init__(self, path, tokenizer, tool, max_len, effort): self.rows, self.skipped = [], 0 for line in open(path + "/sft.jsonl", encoding="utf-8"): r = json.loads(line) enc = tokenizer.apply_chat_template(r["messages"], tools=[tool], tokenize=True, add_generation_prompt=False, return_dict=True, return_assistant_tokens_mask=True, reasoning_effort=effort) ids, mask = enc["input_ids"], enc["assistant_masks"] if ids and isinstance(ids[0], (list, tuple)): # some templates return a batch of one ids, mask = ids[0], mask[0] ids, mask = [int(t) for t in ids], [int(m) for m in mask] if len(ids) > max_len or not any(mask): self.skipped += 1 continue labels = [t if m else -100 for t, m in zip(ids, mask)] self.rows.append({"input_ids": ids, "labels": labels, "id": r["instance_id"]})
def __len__(self): return len(self.rows)
def __getitem__(self, i): r = self.rows[i] return {"input_ids": torch.tensor(r["input_ids"]), "labels": torch.tensor(r["labels"]), "attention_mask": torch.ones(len(r["input_ids"]), dtype=torch.long)}
def collate(batch): assert len(batch) == 1, "batch size 1: the 200K vocabulary makes the logits the largest allocation" return {k: v.unsqueeze(0) for k, v in batch[0].items()}
def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--data", required=True) ap.add_argument("--out", required=True) ap.add_argument("--max-len", type=int, default=32768) ap.add_argument("--rank", type=int, default=16) ap.add_argument("--alpha", type=int, default=16) ap.add_argument("--lr", type=float, default=1e-4) ap.add_argument("--epochs", type=float, default=2.0) ap.add_argument("--accum", type=int, default=8) ap.add_argument("--effort", default="high") ap.add_argument("--smoke", action="store_true") ap.add_argument("--train-experts", action="store_true", help="also adapt the routed experts. Off by default: the serving engine on this GPU family takes the experts " "only in their released 4-bit and 8-bit form, so a model whose experts changed could not be served by it") ap.add_argument("--merge", action="store_true", help="after training, also write the merged 16-bit model") a = ap.parse_args() os.makedirs(a.out, exist_ok=True) t0 = time.time() model, tokenizer = FastModel.from_pretrained(model_name=a.model, max_seq_length=a.max_len, load_in_4bit=False, full_finetuning=False) model = FastModel.get_peft_model(model, finetune_vision_layers=False, finetune_language_layers=True, finetune_attention_modules=True, finetune_mlp_modules=a.train_experts, r=a.rank, lora_alpha=a.alpha, lora_dropout=0, bias="none", use_gradient_checkpointing="unsloth", random_state=3407) tool = json.load(open(a.data + "/tool.json")) data = Conversations(a.data, tokenizer, tool, a.max_len, a.effort) lens = sorted(len(r["input_ids"]) for r in data.rows) trained = sum(sum(1 for t in r["labels"] if t != -100) for r in data.rows) info = {"conversations": len(data), "skipped_too_long_or_empty": data.skipped, "tokens_total": sum(lens), "tokens_with_loss": trained, "len_median": lens[len(lens) // 2] if lens else 0, "len_max": lens[-1] if lens else 0, "load_s": round(time.time() - t0, 1), "args": vars(a), "trainable_params": sum(p.numel() for p in model.parameters() if p.requires_grad), "total_params": sum(p.numel() for p in model.parameters())} print("DATA", json.dumps(info), flush=True) steps = 3 if a.smoke else -1 args = TrainingArguments(output_dir=a.out, per_device_train_batch_size=1, gradient_accumulation_steps=1 if a.smoke else a.accum, warmup_steps=0 if a.smoke else 3, max_steps=steps, num_train_epochs=a.epochs, learning_rate=a.lr, logging_steps=1, optim="adamw_8bit", weight_decay=0.001, lr_scheduler_type="cosine", seed=3407, report_to="none", save_strategy="no", dataloader_num_workers=0, remove_unused_columns=False) trainer = Trainer(model=model, args=args, train_dataset=data, data_collator=collate) stats = trainer.train() info.update({"train_runtime_s": round(stats.metrics.get("train_runtime", 0), 1), "train_loss": stats.metrics.get("train_loss"), "steps": stats.global_step, "log": [{k: v for k, v in h.items() if k in ("step", "loss", "learning_rate", "epoch")} for h in trainer.state.log_history if "loss" in h], "peak_gpu_gib": round(torch.cuda.max_memory_allocated() / 2**30, 1)}) if not trainer.is_world_process_zero(): # with several GPUs, one process writes the results return json.dump(info, open(a.out + "/train_info.json", "w"), indent=1) print("TRAINED", json.dumps({k: info[k] for k in ("steps", "train_loss", "train_runtime_s", "peak_gpu_gib")}), flush=True) if a.smoke: return model.save_pretrained(a.out + "/lora") tokenizer.save_pretrained(a.out + "/lora") if a.merge: model.save_pretrained_merged(a.out + "/merged-16bit", tokenizer, save_method="merged_16bit") print("MERGED", a.out + "/merged-16bit", flush=True)
if __name__ == "__main__": main()train/build_sft.pyAdded+104
train/collect_grades.pyAdded+31
train/expert_usage.pyAdded+79
train/gen.shAdded+33
train/grade.shAdded+27
train/graft.pyAdded+152
train/make_pool.pyAdded+88
train/make_task_states.pyAdded+33
train/merge_test.pyAdded+34
train/prefetch_branches.shAdded+40
train/prune_experts.pyAdded+72
train/pull_pool.shAdded+27
train/sft.pyAdded+113