Skip to content

Official Codebase of 3DCodeVerse

Python

finetune: sync scripts, configs, eval stack and docs

gaoypeng323bb31b4338
diff --git a/finetune/eval/.vllm_ok b/finetune/eval/.vllm_ok
deleted file mode 100644
index e69de29b..00000000
diff --git a/finetune/eval/all_results.json b/finetune/eval/all_results.json
deleted file mode 100644
index 5e0e6ce2..00000000
--- a/finetune/eval/all_results.json
+++ /dev/null
@@ -1,262 +0,0 @@
-[
- {
- "name": "qwen25coder7b_base",
- "exec_ok": 18,
- "exec_rate": 0.0849,
- "cd": 0.312,
- "f05": 0.2312,
- "f10": 0.3936,
- "f05_all": 0.0142,
- "f10_all": 0.0241,
- "avg_tok": 1040,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_base_nothink",
- "exec_ok": 0,
- "exec_rate": 0.0,
- "cd": null,
- "f05": null,
- "f10": null,
- "f05_all": 0.0,
- "f10_all": 0.0,
- "avg_tok": 3520,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_base_nothink_lenient",
- "exec_ok": 4,
- "exec_rate": 0.0189,
- "cd": 0.2648,
- "f05": 0.2389,
- "f10": 0.4858,
- "f05_all": 0.0045,
- "f10_all": 0.0092,
- "avg_tok": 0,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_full_v1_ckpt60",
- "exec_ok": 151,
- "exec_rate": 0.7123,
- "cd": 0.1996,
- "f05": 0.3806,
- "f10": 0.6036,
- "f05_all": 0.2693,
- "f10_all": 0.427,
- "avg_tok": 874,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_lora_v1",
- "exec_ok": 159,
- "exec_rate": 0.75,
- "cd": 0.2012,
- "f05": 0.3823,
- "f10": 0.5979,
- "f05_all": 0.2849,
- "f10_all": 0.4456,
- "avg_tok": 774,
- "train_loss": 0.26390162311376086,
- "train_min": 30.171525
- },
- {
- "name": "qwen35_9b_lora_v1_T07_s1",
- "exec_ok": 162,
- "exec_rate": 0.7642,
- "cd": 0.2008,
- "f05": 0.3716,
- "f10": 0.5925,
- "f05_all": 0.2787,
- "f10_all": 0.4444,
- "avg_tok": 562,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_lora_v1_T07_s2",
- "exec_ok": 141,
- "exec_rate": 0.6651,
- "cd": 0.1974,
- "f05": 0.3822,
- "f10": 0.6028,
- "f05_all": 0.2524,
- "f10_all": 0.3981,
- "avg_tok": 643,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_lora_v1_T07_s3",
- "exec_ok": 137,
- "exec_rate": 0.6462,
- "cd": 0.195,
- "f05": 0.4005,
- "f10": 0.6189,
- "f05_all": 0.2588,
- "f10_all": 0.3999,
- "avg_tok": 969,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_lora_v1_T07_s4",
- "exec_ok": 159,
- "exec_rate": 0.75,
- "cd": 0.1994,
- "f05": 0.3862,
- "f10": 0.6118,
- "f05_all": 0.286,
- "f10_all": 0.4531,
- "avg_tok": 666,
- "train_loss": null,
- "train_min": 0.0
- },
- {
- "name": "qwen35_9b_lora_v1_ckpt100",
- "exec_ok": 168,
- "exec_rate": 0.7925,
- "cd": 0.198,
- "f05": 0.3848,
- "f10": 0.5995,
- "f05_all": 0.3013,
- "f10_all": 0.4694,
- "avg_tok": 705,
- "train_loss": 0.26390162311376086,
- "train_min": 30.171525
- },
- {
- "name": "qwen35_9b_lora_v2_indist",
- "exec_ok": 131,
- "exec_rate": 0.6179,
- "cd": 0.1864,
- "f05": 0.4112,
- "f10": 0.6422,
- "f05_all": 0.2521,
- "f10_all": 0.3938,
- "avg_tok": 1360,
- "train_loss": 0.29489868678725684,
- "train_min": 37.09996666666667
- },
- {
- "name": "qwen35_9b_lora_v2b_indist16k",
- "exec_ok": 114,
- "exec_rate": 0.5377,
- "cd": 0.1969,
- "f05": 0.4144,
- "f10": 0.622,
- "f05_all": 0.2229,
- "f10_all": 0.3345,
- "avg_tok": 2579,
- "train_loss": 0.34209747883406555,
- "train_min": 58.625461666666666
- },
- {
- "name": "qwen35_9b_lora_v3_bio",
- "exec_ok": 156,
- "exec_rate": 0.7358,
- "cd": 0.205,
- "f05": 0.3804,
- "f10": 0.5968,
- "f05_all": 0.2781,
- "f10_all": 0.4363,
- "avg_tok": 539,
- "train_loss": 0.202895405292511,
- "train_min": 24.804971666666667
- },
- {
- "name": "qwen35_9b_lora_v3_bio_ckpt100",
- "exec_ok": 154,
- "exec_rate": 0.7264,
- "cd": 0.2149,
- "f05": 0.3683,
- "f10": 0.588,
- "f05_all": 0.264,
- "f10_all": 0.4216,
- "avg_tok": 563,
- "train_loss": 0.202895405292511,
- "train_min": 24.804971666666667
- },
- {
- "name": "qwen35_9b_lora_v3_bio_ckpt50",
- "exec_ok": 152,
- "exec_rate": 0.717,
- "cd": 0.211,
- "f05": 0.3753,
- "f10": 0.5863,
- "f05_all": 0.2673,
- "f10_all": 0.4176,
- "avg_tok": 523,
- "train_loss": 0.202895405292511,
- "train_min": 24.804971666666667
- },
- {
- "name": "qwen35_9b_lora_v4_cq",
- "exec_ok": 157,
- "exec_rate": 0.7406,
- "cd": 0.2008,
- "f05": 0.3751,
- "f10": 0.5956,
- "f05_all": 0.2742,
- "f10_all": 0.4355,
- "avg_tok": 694,
- "train_loss": 0.18613976782018488,
- "train_min": 67.80998000000001
- },
- {
- "name": "qwen35_9b_lora_v5_instr",
- "exec_ok": 143,
- "exec_rate": 0.6745,
- "cd": 0.1988,
- "f05": 0.4025,
- "f10": 0.6094,
- "f05_all": 0.2696,
- "f10_all": 0.4082,
- "avg_tok": 876,
- "train_loss": 0.26363916967123274,
- "train_min": 31.889743333333335
- },
- {
- "name": "qwen35_9b_lora_v6_detail",
- "exec_ok": 139,
- "exec_rate": 0.6557,
- "cd": 0.2077,
- "f05": 0.3688,
- "f10": 0.5878,
- "f05_all": 0.2401,
- "f10_all": 0.3826,
- "avg_tok": 1128,
- "train_loss": 0.2620609815304096,
- "train_min": 33.901199999999996
- },
- {
- "name": "qwen35_9b_lora_v7_ep4",
- "exec_ok": 147,
- "exec_rate": 0.6934,
- "cd": 0.2052,
- "f05": 0.3799,
- "f10": 0.6022,
- "f05_all": 0.2616,
- "f10_all": 0.4147,
- "avg_tok": 857,
- "train_loss": 0.20162874489786134,
- "train_min": 61.887908333333336
- },
- {
- "name": "qwen35_9b_lora_v8_r16",
- "exec_ok": 162,
- "exec_rate": 0.7642,
- "cd": 0.2096,
- "f05": 0.3717,
- "f10": 0.5902,
- "f05_all": 0.284,
- "f10_all": 0.451,
- "avg_tok": 667,
- "train_loss": 0.31294202780912794,
- "train_min": 31.807015
- }
-]
\ No newline at end of file
diff --git a/finetune/eval/analyze_runs.py b/finetune/eval/analyze_runs.py
deleted file mode 100644
index 8d6d2edc..00000000
--- a/finetune/eval/analyze_runs.py
+++ /dev/null
@@ -1,32 +0,0 @@
-"""Cross-run analysis: per-task success overlap, code length vs success, per-category success. Usage: analyze_runs.py run1 run2 ..."""
-import json, os, sys, collections, numpy as np
-OUT = "/wekafs/ict/hx_624/llm-ft/eval/out"
-runs = sys.argv[1:]
-data = {}
-for r in runs:
- ex = {json.loads(l)["task"]: json.loads(l) for l in open(f"{OUT}/{r}/exec_results.jsonl")}
- gens = {json.loads(l)["task"]: json.loads(l) for f in os.listdir(f"{OUT}/{r}") if f.startswith("gens_shard") for l in open(f"{OUT}/{r}/{f}")}
- met = {json.loads(l)["task"]: json.loads(l) for l in open(f"{OUT}/{r}/metrics.jsonl")} if os.path.exists(f"{OUT}/{r}/metrics.jsonl") else {}
- data[r] = (ex, gens, met)
-tasks = sorted(next(iter(data.values()))[0].keys())
-print("=== success by output length bucket (tokens) ===")
-for r in runs:
- ex, gens, met = data[r]; b = collections.defaultdict(lambda: [0, 0])
- for t in tasks:
- n = gens.get(t, {}).get("n_new_tokens", 0); k = "<500" if n < 500 else "<1000" if n < 1000 else "<2000" if n < 2000 else "<4000" if n < 4000 else ">=4000"
- b[k][1] += 1; b[k][0] += ex[t]["status"] == "OK"
- print(f"{r:32s}", {k: f"{v[0]}/{v[1]}" for k, v in sorted(b.items())})
-print("\n=== pairwise overlap of OK tasks ===")
-oks = {r: {t for t in tasks if data[r][0][t]["status"] == "OK"} for r in runs}
-for i, a in enumerate(runs):
- for b_ in runs[i+1:]:
- print(f"{a} ∩ {b_}: {len(oks[a] & oks[b_])} | only {a}: {len(oks[a]-oks[b_])} | only {b_}: {len(oks[b_]-oks[a])}")
-print("\n=== per-task category (first word of task name) success counts for each run ===")
-cats = collections.defaultdict(list)
-for t in tasks: cats[t[:1]].append(t)
-print("(by first letter, just to eyeball)")
-for r in runs:
- ex = data[r][0]; print(f"{r:32s}", " ".join(f"{c}:{sum(ex[t]['status']=='OK' for t in ts)}/{len(ts)}" for c, ts in sorted(cats.items())))
-print("\n=== best/worst tasks ([email protected]) in", runs[-1], "===")
-met = data[runs[-1]][2]; sc = sorted([(m.get("[email protected]", -1), t) for t, m in met.items() if "[email protected]" in m], reverse=True)
-print("best:", sc[:8]); print("worst:", sc[-8:])
diff --git a/finetune/eval/best_of_n.sh b/finetune/eval/best_of_n.sh
deleted file mode 100755
index f244e922..00000000
--- a/finetune/eval/best_of_n.sh
+++ /dev/null
@@ -1,17 +0,0 @@
-#!/bin/bash
-# usage: GPUS=0 eval/best_of_n.sh <model_dir> <out_prefix> <N> [temperature]
-# N sampled generations (different seeds) -> exec each -> pass@N (union) via eval/pass_at_n.py
-set -uo pipefail
-MODEL=$(readlink -f "$1"); PFX=$2; N=$3; T=${4:-0.7}
-source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate vllm
-export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING CUDA_VISIBLE_DEVICES=${GPUS:-0}
-cd /wekafs/ict/hx_624/llm-ft
-for i in $(seq 1 $N); do
- OUT=eval/out/${PFX}_s$i; mkdir -p $OUT
- python eval/generate_vllm.py --model $MODEL --prompts data/sft_v1/bench_prompts.jsonl --out $OUT --tp 1 --no_think --max_new_tokens 6144 --temperature $T --seed $i 2>&1 | grep -E "gen-vllm|Error" | tail -2
- cp $OUT/gens_shard0.jsonl $OUT/gens.jsonl
-done
-conda activate llmft
-for i in $(seq 1 $N); do OUT=eval/out/${PFX}_s$i; python eval/run_bench.py --gen_dir $OUT --workers 32 --timeout 300 > $OUT/exec.log 2>&1; python eval/metrics.py --gen_dir $OUT > $OUT/metrics.log 2>&1; grep "status counts" $OUT/exec.log; done
-python eval/pass_at_n.py $PFX $N
-echo BEST_OF_N_DONE
diff --git a/finetune/eval/blender_dialect_eval.py b/finetune/eval/blender_dialect_eval.py
deleted file mode 100644
index 0b2a257c..00000000
--- a/finetune/eval/blender_dialect_eval.py
+++ /dev/null
@@ -1,44 +0,0 @@
-"""Held-out Blender test (bioinspired3d-style): execute generated & reference scripts in Blender, compare meshes."""
-import argparse, json, os, re, subprocess, sys, numpy as np
-from concurrent.futures import ThreadPoolExecutor
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from metrics import load_points, chamfer_f, rot_y
-BLENDER = "/wekafs/ict/hx_624/tools/blender-5.0.1-linux-x64/blender"; RUNNER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "blender_runner.py")
-ap = argparse.ArgumentParser(); ap.add_argument("--test", required=True); ap.add_argument("--gen_dir", required=True); ap.add_argument("--workers", type=int, default=32); a = ap.parse_args()
-tests = [json.loads(l) for l in open(a.test)]; ref_cache = os.path.join(os.path.dirname(a.test), "ref_exec_blender")
-def code_of(msg):
- m = re.findall(r"```[a-zA-Z]*\n(.*?)```", msg, flags=re.S); return (max(m, key=len) if m else msg).strip()
-def run_blender(code, d):
- d = os.path.abspath(d); os.makedirs(d, exist_ok=True); sp = os.path.join(d, "code.py"); glb = os.path.join(d, "out.glb"); rp = os.path.join(d, "exec.json")
- if not os.path.exists(sp): open(sp, "w").write(code)
- try:
- subprocess.run([BLENDER, "-b", "--factory-startup", "-noaudio", "--python", RUNNER, "--", "--script", sp, "--out", glb, "--report", rp], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180, env={**os.environ, "HOME": "/tmp"})
- r = json.load(open(rp)) if os.path.exists(rp) else {"status": "CRASH"}
- except subprocess.TimeoutExpired: r = {"status": "TIMEOUT"}
- r["mesh"] = glb if r.get("status") == "OK" else None; return r
-def ref_job(t):
- tid = t["id"].replace("/", "__"); d = os.path.join(ref_cache, tid)
- if os.path.exists(os.path.join(d, "rep.json")): return tid, json.load(open(os.path.join(d, "rep.json")))
- rep = run_blender(code_of(t["messages"][-1]["content"]), d); json.dump(rep, open(os.path.join(d, "rep.json"), "w")); return tid, rep
-def gen_job(t):
- tid = t["id"].replace("/", "__"); d = os.path.join(a.gen_dir, tid)
- if not os.path.exists(os.path.join(d, "code.py")): return tid, {"status": "MISSING", "mesh": None}
- return tid, run_blender(None, d)
-with ThreadPoolExecutor(a.workers) as ex: refs = dict(ex.map(ref_job, tests)); gens = dict(ex.map(gen_job, tests))
-rows = []
-for t in tests:
- tid = t["id"].replace("/", "__"); r = {"id": tid, "ref": refs[tid].get("status"), "gen": gens[tid].get("status"), "gen_error": (gens[tid].get("error") or "")[:200]}
- if r["ref"] == "OK" and r["gen"] == "OK":
- try:
- pr = load_points(refs[tid]["mesh"], 5000); pg = load_points(gens[tid]["mesh"], 5000)
- if pr is not None and pg is not None:
- best = min((chamfer_f(rot_y(pg, k), pr) for k in range(4)), key=lambda x: x[0]); r["chamfer"] = best[0]; r.update(best[1])
- except Exception as e: r["metric_error"] = str(e)[:100]
- rows.append(r)
-n = len(rows); sc = [r for r in rows if "[email protected]" in r]
-summary = {"dialect": "blender_heldout", "n": n, "ref_exec_ok": sum(r["ref"] == "OK" for r in rows), "gen_exec_ok": sum(r["gen"] == "OK" for r in rows), "gen_exec_rate": round(sum(r["gen"] == "OK" for r in rows) / n, 4),
- "n_scored": len(sc), "[email protected]_mean_scored": round(float(np.mean([r["[email protected]"] for r in sc])), 4) if sc else None, "[email protected]_mean_all": round(float(sum(r.get("[email protected]", 0) for r in rows) / n), 4), "chamfer_mean_scored": round(float(np.mean([r["chamfer"] for r in sc])), 4) if sc else None}
-os.makedirs(a.gen_dir, exist_ok=True)
-with open(os.path.join(a.gen_dir, "dialect_metrics.jsonl"), "w") as f:
- for r in rows: f.write(json.dumps(r) + "\n")
-json.dump(summary, open(os.path.join(a.gen_dir, "summary.json"), "w"), indent=2); print(json.dumps(summary))
diff --git a/finetune/eval/blender_runner.py b/finetune/eval/blender_runner.py
deleted file mode 100644
index 1da13185..00000000
--- a/finetune/eval/blender_runner.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""Run ONE generated Blender-Python script headlessly inside Blender and export a GLB + JSON report.
-
-Usage (inside blender):
- blender -b --factory-startup --python blender_runner.py -- --script gen.py --out out.glb --report out.json
-"""
-import sys, json, time, traceback, argparse, runpy, os, io, contextlib
-
-def parse():
- argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
- ap = argparse.ArgumentParser()
- ap.add_argument("--script", required=True)
- ap.add_argument("--out", required=True)
- ap.add_argument("--report", required=True)
- return ap.parse_args(argv)
-
-def main():
- args = parse()
- import bpy
- t0 = time.time()
- rep = {"script": args.script, "out_glb": args.out, "status": "FAIL", "error": None,
- "n_meshes": 0, "n_verts": 0, "n_faces": 0, "size_kb": 0.0, "latency_s": 0.0}
- # factory startup scene (keeps the default 'Collection' in the view layer, like the official export),
- # but remove the default Cube/Light/Camera so an empty generation cannot pass as "OK"
- # NOTE: do not call read_factory_settings() here (leaves bpy.context.view_layer stale); rely on --factory-startup
- for ob in list(bpy.data.objects):
- bpy.data.objects.remove(ob, do_unlink=True)
- for coll_name in ("meshes", "materials", "lights", "cameras", "curves"):
- coll = getattr(bpy.data, coll_name)
- for blk in list(coll):
- if blk.users == 0: coll.remove(blk)
- bpy.context.view_layer.update()
- log = io.StringIO()
- try:
- # Make the script dir importable & chdir so relative asset paths resolve
- sdir = os.path.dirname(os.path.abspath(args.script))
- sys.path.insert(0, sdir); os.chdir(sdir)
- with contextlib.redirect_stdout(log):
- runpy.run_path(args.script, run_name="__main__")
- # collect meshes (evaluate modifiers)
- bpy.context.view_layer.update()
- deps = bpy.context.evaluated_depsgraph_get()
- vl_objs = list(bpy.context.view_layer.objects) # only objects actually in the scene/view layer count
- nm = nv = nf = 0
- for ob in vl_objs:
- if ob.type == "MESH":
- ev = ob.evaluated_get(deps)
- me = ev.to_mesh()
- if me is not None:
- nm += 1; nv += len(me.vertices); nf += len(me.polygons)
- ev.to_mesh_clear()
- rep.update(n_meshes=nm, n_verts=nv, n_faces=nf)
- if nm == 0 or nv == 0:
- rep["status"] = "EMPTY"; rep["error"] = "no mesh geometry produced"
- else:
- for ob in vl_objs:
- try: ob.select_set(ob.type == "MESH" and not ob.hide_viewport and not ob.hide_render)
- except Exception: pass
- bpy.ops.export_scene.gltf(filepath=args.out, export_format="GLB", use_selection=True,
- export_apply=True, export_materials="EXPORT", export_yup=True)
- rep["size_kb"] = round(os.path.getsize(args.out) / 1024, 1)
- rep["status"] = "OK"
- except BaseException as e: # noqa (catch SystemExit too)
- tb = traceback.format_exc()
- rep["error"] = (type(e).__name__ + ": " + str(e))[:2000]
- rep["traceback"] = tb[-3000:]
- rep["latency_s"] = round(time.time() - t0, 2)
- rep["stdout_tail"] = log.getvalue()[-1500:]
- with open(args.report, "w") as f:
- json.dump(rep, f, indent=2)
- print("RUNNER_STATUS", rep["status"], rep["error"] or "")
-
-main()
diff --git a/finetune/eval/compare.py b/finetune/eval/compare.py
deleted file mode 100644
index 4971b0e3..00000000
--- a/finetune/eval/compare.py
+++ /dev/null
@@ -1,15 +0,0 @@
-"""Tabulate eval/out/*/summary.json (+ generation stats) into one table."""
-import glob, json, os, sys
-rows = []
-for d in sorted(glob.glob("/wekafs/ict/hx_624/llm-ft/eval/out/*/")):
- sp = os.path.join(d, "summary.json")
- if not os.path.exists(sp): continue
- s = json.load(open(sp))
- gens = [json.loads(l) for f in glob.glob(os.path.join(d, "gens_shard*.jsonl")) for l in open(f)]
- ntok = sum(g["n_new_tokens"] for g in gens) / max(len(gens), 1)
- fin = sum(g["finished"] for g in gens) / max(len(gens), 1)
- rows.append((os.path.basename(d.rstrip("/")), s["exec_ok"], s["n_tasks"], s["exec_ok_rate"], s["chamfer_mean_scored"], s["chamfer_median_scored"], s["[email protected]_mean_scored"], s["[email protected]_mean_scored"], s["[email protected]_mean_all(fail=0)"], s["[email protected]_mean_all(fail=0)"], ntok, fin))
-hdr = ("run", "exec_ok", "n", "ok_rate", "CD_mean", "CD_med", "[email protected](ok)", "[email protected](ok)", "[email protected](all)", "[email protected](all)", "avg_tok", "finished")
-print("| " + " | ".join(hdr) + " |"); print("|" + "---|" * len(hdr))
-for r in rows:
- print("| " + " | ".join(f"{x:.3f}" if isinstance(x, float) else str(x) for x in r) + " |")
diff --git a/finetune/eval/dialect_eval.py b/finetune/eval/dialect_eval.py
deleted file mode 100644
index 92f87a02..00000000
--- a/finetune/eval/dialect_eval.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Evaluate a model on a non-Blender dialect test set: generate (vLLM, done separately) -> execute generated & reference -> geometry metrics vs reference mesh.
-usage: dialect_eval.py --dialect cadquery --test data/multidialect/cadquery/test.jsonl --gen_dir <dir with <id>/code.py> [--workers 32]"""
-import argparse, json, os, re, sys, numpy as np
-from concurrent.futures import ThreadPoolExecutor
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from dialect_runners import RUNNERS
-from metrics import load_points, chamfer_f, rot_y
-ap = argparse.ArgumentParser(); ap.add_argument("--dialect", required=True); ap.add_argument("--test", required=True); ap.add_argument("--gen_dir", required=True); ap.add_argument("--workers", type=int, default=32); ap.add_argument("--ref_cache", default=None)
-a = ap.parse_args()
-run = RUNNERS[a.dialect]
-tests = [json.loads(l) for l in open(a.test)]
-ref_cache = a.ref_cache or os.path.join(os.path.dirname(a.test), f"ref_exec_{a.dialect}")
-def code_of(msg):
- m = re.findall(r"```[a-zA-Z]*\n(.*?)```", msg, flags=re.S); return (max(m, key=len) if m else msg).strip()
-def ref_job(t):
- tid = t["id"].replace("/", "__"); d = os.path.join(ref_cache, tid)
- if os.path.exists(os.path.join(d, "rep.json")): return tid, json.load(open(os.path.join(d, "rep.json")))
- rep = run(code_of(t["messages"][-1]["content"]), d); json.dump(rep, open(os.path.join(d, "rep.json"), "w")); return tid, rep
-def gen_job(t):
- tid = t["id"].replace("/", "__"); d = os.path.join(a.gen_dir, tid); cp = os.path.join(d, "code.py")
- if not os.path.exists(cp): return tid, {"status": "MISSING", "error": "no generation", "mesh": None}
- rep = run(open(cp).read(), os.path.join(d, "exec")); return tid, rep
-with ThreadPoolExecutor(a.workers) as ex:
- refs = dict(ex.map(ref_job, tests)); gens = dict(ex.map(gen_job, tests))
-rows = []; np.random.seed(0)
-for t in tests:
- tid = t["id"].replace("/", "__"); r = {"id": tid, "ref": refs[tid]["status"], "gen": gens[tid]["status"], "gen_error": (gens[tid].get("error") or "")[:200]}
- if a.dialect != "glsl" and refs[tid]["status"] == "OK" and gens[tid]["status"] == "OK":
- try:
- pr = load_points(refs[tid]["mesh"], 5000); pg = load_points(gens[tid]["mesh"], 5000)
- if pr is not None and pg is not None:
- best = min((chamfer_f(rot_y(pg, k), pr) for k in range(4)), key=lambda x: x[0]); r["chamfer"] = best[0]; r.update(best[1])
- except Exception as e: r["metric_error"] = str(e)[:100]
- rows.append(r)
-n = len(rows); ref_ok = sum(r["ref"] == "OK" for r in rows); gen_ok = sum(r["gen"] == "OK" for r in rows); sc = [r for r in rows if "[email protected]" in r]
-summary = {"dialect": a.dialect, "n": n, "ref_exec_ok": ref_ok, "gen_exec_ok": gen_ok, "gen_exec_rate": round(gen_ok / n, 4), "n_scored": len(sc),
- "[email protected]_mean_scored": round(float(np.mean([r["[email protected]"] for r in sc])), 4) if sc else None, "[email protected]_mean_scored": round(float(np.mean([r["[email protected]"] for r in sc])), 4) if sc else None,
- "[email protected]_mean_all": round(float(sum(r.get("[email protected]", 0) for r in rows) / n), 4), "chamfer_mean_scored": round(float(np.mean([r["chamfer"] for r in sc])), 4) if sc else None}
-os.makedirs(a.gen_dir, exist_ok=True)
-with open(os.path.join(a.gen_dir, "dialect_metrics.jsonl"), "w") as f:
- for r in rows: f.write(json.dumps(r) + "\n")
-json.dump(summary, open(os.path.join(a.gen_dir, "summary.json"), "w"), indent=2); print(json.dumps(summary))
-from collections import Counter; print("gen failure modes:", Counter(re.sub(r"'[^']*'", "'<x>'", (r["gen_error"] or r["gen"]).split("\n")[0][:70]) for r in rows if r["gen"] != "OK").most_common(8))
diff --git a/finetune/eval/dialect_runners.py b/finetune/eval/dialect_runners.py
deleted file mode 100644
index d58dfec0..00000000
--- a/finetune/eval/dialect_runners.py
+++ /dev/null
@@ -1,101 +0,0 @@
-"""Executors for non-Blender dialects. Each run_* returns dict(status, error, mesh_path or None, latency_s)."""
-import os, subprocess, sys, time, json, tempfile, re
-OPENSCAD = "/wekafs/ict/hx_624/tools/openscad/squashfs-root/AppRun"
-GLSLANG = "/wekafs/ict/hx_624/anaconda3/envs/llmft/bin/glslangValidator"
-PY = "/wekafs/ict/hx_624/anaconda3/envs/llmft/bin/python"
-CQ_RUNNER = r'''
-import sys, json, runpy, traceback, os
-os.environ.setdefault("OMP_NUM_THREADS","1")
-script, out_stl = sys.argv[1], sys.argv[2]
-rep = {"status":"FAIL","error":None}
-try:
- import cadquery as cq
- sys.argv = [script, out_stl]
- _orig_export = cq.exporters.export
- captured = []
- def _capture(o, *a, **k): captured.append(o)
- # neutralise export calls (the scripts export STEP/STL to arbitrary paths) but remember the exported object
- for modname in ("cadquery.occ_impl.exporters", "cadquery.exporters"):
- try:
- import importlib; _m = importlib.import_module(modname); _m.export = _capture
- except Exception: pass
- try: cq.exporters.export = _capture
- except Exception: pass
- g = runpy.run_path(script, run_name="__main__", init_globals={"show_object": _capture, "debug": _capture})
- obj = None
- for c in reversed(captured):
- if isinstance(c, (cq.Workplane, cq.Shape, cq.Assembly)): obj = c; break
- if obj is None:
- for name in ("result", "final", "model", "part", "solid", "shape", "body", "assembly", "assy", "obj", "res"):
- if isinstance(g.get(name), (cq.Workplane, cq.Shape, cq.Assembly)): obj = g[name]; break
- if obj is None:
- cands = [v for v in g.values() if isinstance(v, (cq.Workplane, cq.Shape, cq.Assembly))]
- obj = cands[-1] if cands else None
- if obj is None: raise RuntimeError("no CadQuery result object found (expected variable `result`)")
- if isinstance(obj, cq.Assembly): obj = obj.toCompound()
- if isinstance(obj, cq.Workplane):
- vals = obj.vals()
- if not vals: raise RuntimeError("empty workplane")
- obj = vals[0] if len(vals)==1 else cq.Compound.makeCompound([v for v in vals if isinstance(v, cq.Shape)])
- if not isinstance(obj, cq.Shape): raise RuntimeError(f"unsupported object {type(obj)}")
- if obj.Volume() <= 1e-9 and not obj.Faces(): raise RuntimeError("empty shape")
- _orig_export(obj, out_stl, tolerance=0.01, angularTolerance=0.1)
- rep["status"]="OK"
-except BaseException as e:
- rep["error"]=(type(e).__name__+": "+str(e))[:500]; rep["traceback"]=traceback.format_exc()[-1500:]
-print("CQ_REPORT "+json.dumps(rep))
-'''
-def run_cadquery(code, workdir, timeout=90):
- workdir = os.path.abspath(workdir); os.makedirs(workdir, exist_ok=True); sp = os.path.join(workdir, "script.py"); stl = os.path.join(workdir, "out.stl"); rp = os.path.join(workdir, "runner.py")
- open(sp, "w").write(code); open(rp, "w").write(CQ_RUNNER)
- t0 = time.time()
- try:
- p = subprocess.run([PY, rp, sp, stl], cwd=workdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, text=True, errors="replace")
- m = re.search(r"CQ_REPORT (\{.*\})", p.stdout)
- rep = json.loads(m.group(1)) if m else {"status": "CRASH", "error": p.stdout[-800:]}
- except subprocess.TimeoutExpired:
- rep = {"status": "TIMEOUT", "error": f"timeout {timeout}s"}
- rep["latency_s"] = round(time.time() - t0, 1); rep["mesh"] = stl if rep["status"] == "OK" and os.path.exists(stl) else None
- if rep["status"] == "OK" and rep["mesh"] is None: rep["status"] = "EMPTY"
- return rep
-def run_openscad(code, workdir, timeout=120):
- workdir = os.path.abspath(workdir); os.makedirs(workdir, exist_ok=True); sc = os.path.join(workdir, "model.scad"); stl = os.path.join(workdir, "out.stl")
- open(sc, "w").write(code); t0 = time.time()
- try:
- p = subprocess.run([OPENSCAD, "-o", stl, "--export-format", "binstl", sc], cwd=workdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, text=True, errors="replace",
- env={**os.environ, "HOME": workdir, "QT_QPA_PLATFORM": "offscreen"})
- ok = p.returncode == 0 and os.path.exists(stl) and os.path.getsize(stl) > 100
- rep = {"status": "OK" if ok else ("EMPTY" if p.returncode == 0 else "FAIL"), "error": None if ok else p.stdout[-800:]}
- except subprocess.TimeoutExpired:
- rep = {"status": "TIMEOUT", "error": f"timeout {timeout}s"}
- rep["latency_s"] = round(time.time() - t0, 1); rep["mesh"] = stl if rep["status"] == "OK" else None
- return rep
-GLSL_PRELUDE = """#version 300 es
-precision highp float; precision highp int;
-uniform vec3 iResolution; uniform float iTime; uniform float iTimeDelta; uniform int iFrame; uniform vec4 iMouse; uniform vec4 iDate; uniform float iSampleRate;
-uniform sampler2D iChannel0; uniform sampler2D iChannel1; uniform sampler2D iChannel2; uniform sampler2D iChannel3;
-uniform vec3 iChannelResolution[4]; uniform float iChannelTime[4];
-out vec4 _outColor;
-"""
-GLSL_MAIN = "\nvoid main(){ vec4 c = vec4(0.0); mainImage(c, gl_FragCoord.xy); _outColor = c; }\n"
-def run_glsl(code, workdir, timeout=30):
- workdir = os.path.abspath(workdir); os.makedirs(workdir, exist_ok=True); fp = os.path.join(workdir, "shader.frag")
- # normalise: drop #version / precision lines and re-declarations of Shadertoy uniforms / the out variable (the prelude provides them)
- import re as _re
- lines = []
- for ln in code.splitlines():
- if _re.match(r"\s*#\s*version\b", ln) or _re.match(r"\s*precision\s+(low|medium|high)p\s+", ln): continue
- if _re.match(r"\s*uniform\s+.*\b(iResolution|iTime|iTimeDelta|iFrame|iMouse|iDate|iSampleRate|iChannel[0-3]|iChannelResolution|iChannelTime)\b", ln): continue
- if _re.match(r"\s*out\s+vec4\s+\w+\s*;", ln): continue
- lines.append(ln)
- src = "\n".join(lines)
- if "mainImage" not in src: return {"status": "FAIL", "error": "no mainImage()", "latency_s": 0, "mesh": None}
- open(fp, "w").write(GLSL_PRELUDE + src + GLSL_MAIN); t0 = time.time()
- try:
- p = subprocess.run([GLSLANG, "-S", "frag", fp], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, text=True, errors="replace")
- rep = {"status": "OK" if p.returncode == 0 else "FAIL", "error": None if p.returncode == 0 else p.stdout[-600:]}
- except subprocess.TimeoutExpired:
- rep = {"status": "TIMEOUT", "error": "timeout"}
- rep["latency_s"] = round(time.time() - t0, 2); rep["mesh"] = None
- return rep
-RUNNERS = {"cadquery": run_cadquery, "openscad": run_openscad, "glsl": run_glsl}
diff --git a/finetune/eval/eval_all.sh b/finetune/eval/eval_all.sh
deleted file mode 100755
index 0042a8fd..00000000
--- a/finetune/eval/eval_all.sh
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/bin/bash
-# One command to evaluate ANY model on everything: 3DCodeBench (Blender exec + geometry vs GT) and the five
-# held-out dialect sets (CadQuery / OpenSCAD / GLSL / Blender / three.js), with dialect-aware code extraction.
-#
-# GPUS=0 TP=1 eval/eval_all.sh <model_dir> <name> [--think] [--temp 0.7] [--seed 1] [--max_new 8192] [--suites ...]
-#
-# --think keep the model's reasoning on (default: enable_thinking=false)
-# --temp/--seed sampling (default greedy)
-# --suites space-separated subset of: bench cadquery openscad glsl blender threejs (default: all)
-# results: eval/out/<name>_<suite>/summary.json + eval/out/<name>_report.json (one row per suite)
-set -uo pipefail
-MODEL=$(readlink -f "$1"); NAME=$2; shift 2
-GPU=${GPUS:-0}; TP=${TP:-1}; THINK=""; TEMP=0.0; SEED=0; MAXNEW=32768
-SUITES="bench cadquery openscad glsl blender threejs"
-while [ $# -gt 0 ]; do
- case "$1" in
- --think) THINK="1"; shift;;
- --temp) TEMP=$2; shift 2;;
- --seed) SEED=$2; shift 2;;
- --max_new) MAXNEW=$2; shift 2;;
- --suites) shift; SUITES=""; while [ $# -gt 0 ] && [[ "$1" != --* ]]; do SUITES="$SUITES $1"; shift; done;;
- *) echo "unknown arg $1"; exit 2;;
- esac
-done
-cd /wekafs/ict/hx_624/llm-ft
-source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh
-export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING
-export PLAYWRIGHT_BROWSERS_PATH=/wekafs/ict/hx_624/cache/ms-playwright CUDA_VISIBLE_DEVICES=$GPU
-NOTHINK="--no_think"; [ -n "$THINK" ] && NOTHINK=""
-MAXLEN=$((MAXNEW + 4096))
-echo "[eval_all] $(date) model=$MODEL name=$NAME gpus=$GPU tp=$TP think=${THINK:-0} temp=$TEMP suites=$SUITES"
-
-# ---------- generation: ONE engine for all suites (loading a 27B per suite costs more than generating) ----------
-conda activate vllm
-SPEC=$(mktemp /tmp/hx_624_evalspec_XXXX.json)
-python - "$NAME" "$SUITES" "$SPEC" <<'PY'
-import json, sys, os
-name, suites, spec_path = sys.argv[1], sys.argv[2].split(), sys.argv[3]
-jobs = []
-for s in suites:
- out = f"eval/out/{name}_{s}"; os.makedirs(out, exist_ok=True)
- if s == "bench":
- prompts, dia = "data/sft_v1/bench_prompts.jsonl", "blender"
- elif s == "threejs":
- prompts, dia = "eval/out/_3js_prompts.jsonl", "threejs"
- else:
- prompts, dia = f"{out}/prompts.jsonl", s
- with open(prompts, "w") as f:
- for l in open(f"data/multidialect/{s}/test.jsonl"):
- r = json.loads(l); f.write(json.dumps({"task": r["id"].replace("/", "__"), "messages": r["messages"][:2]}) + "\n")
- jobs.append({"name": s, "prompts": prompts, "out": out, "dialect": dia})
-json.dump(jobs, open(spec_path, "w"))
-print("[eval_all] suites:", [j["name"] for j in jobs])
-PY
-python eval/generate_multi.py --model $MODEL --spec @$SPEC --tp $TP $NOTHINK \
- --max_new_tokens $MAXNEW --max_model_len $MAXLEN --temperature $TEMP --seed $SEED 2>&1 \
- | grep -E "gen-multi|extract\]|Error|Traceback" | tail -40
-rm -f $SPEC
-
-# ---------- execution + metrics (llmft env) ----------
-conda activate llmft
-for S in $SUITES; do
- OUT=eval/out/${NAME}_${S}
- echo "[eval_all] exec $S"
- case $S in
- bench) python eval/run_bench.py --gen_dir $OUT --workers 32 --timeout 300 2>&1 | grep -E "status counts" | tail -1
- python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1;;
- blender) python eval/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;
- threejs) python eval/threejs_eval.py --gen_dir $OUT 2>&1 | tail -2;;
- *) python eval/dialect_eval.py --dialect $S --test data/multidialect/$S/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;
- esac
-done
-python eval/results_all.py $NAME
-echo "[eval_all] DONE $NAME"
diff --git a/finetune/eval/eval_all_run2.sh b/finetune/eval/eval_all_run2.sh
deleted file mode 100755
index 478c0316..00000000
--- a/finetune/eval/eval_all_run2.sh
+++ /dev/null
@@ -1,101 +0,0 @@
-#!/bin/bash
-# One command to evaluate ANY model on everything: 3DCodeBench (Blender exec + geometry vs GT) and the five
-# held-out dialect sets (CadQuery / OpenSCAD / GLSL / Blender / three.js), with dialect-aware code extraction.
-#
-# GPUS=0 TP=1 eval/eval_all.sh <model_dir> <name> [--think] [--temp 0.7] [--seed 1] [--max_new 8192] [--suites ...]
-#
-# --think keep the model's reasoning on (default: enable_thinking=false)
-# --temp/--seed sampling (default greedy)
-# --suites space-separated subset of: bench cadquery openscad glsl blender threejs (default: all)
-# results: eval/out/<name>_<suite>/summary.json + eval/out/<name>_report.json (one row per suite)
-set -uo pipefail
-MODEL=$(readlink -f "$1"); NAME=$2; shift 2
-GPU=${GPUS:-0}; TP=${TP:-1}; THINK=""; TEMP=0.0; SEED=0; MAXNEW=32768 # the models take 262k context and our prompts are ~300 tokens; a low cap silently turns "unfinished" into "wrong"
-SUITES="bench cadquery openscad glsl blender threejs"
-while [ $# -gt 0 ]; do
- case "$1" in
- --think) THINK="1"; shift;;
- --temp) TEMP=$2; shift 2;;
- --seed) SEED=$2; shift 2;;
- --max_new) MAXNEW=$2; shift 2;;
- --suites) shift; SUITES=""; while [ $# -gt 0 ] && [[ "$1" != --* ]]; do SUITES="$SUITES $1"; shift; done;;
- *) echo "unknown arg $1"; exit 2;;
- esac
-done
-cd /wekafs/ict/hx_624/llm-ft
-source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh
-export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING
-export PLAYWRIGHT_BROWSERS_PATH=/wekafs/ict/hx_624/cache/ms-playwright CUDA_VISIBLE_DEVICES=$GPU
-NOTHINK="--no_think"; [ -n "$THINK" ] && NOTHINK=""
-MAXLEN=$((MAXNEW + 4096))
-echo "[eval_all] $(date) model=$MODEL name=$NAME gpus=$GPU tp=$TP think=${THINK:-0} temp=$TEMP suites=$SUITES"
-
-# ---------- generation: ONE engine for all suites (loading a 27B per suite costs more than generating) ----------
-conda activate vllm
-SPEC=$(mktemp /tmp/hx_624_evalspec_XXXX.json)
-python - "$NAME" "$SUITES" "$SPEC" <<'PY'
-import json, sys, os
-name, suites, spec_path = sys.argv[1], sys.argv[2].split(), sys.argv[3]
-jobs = []
-for s in suites:
- out = f"eval/out/{name}_{s}"; os.makedirs(out, exist_ok=True)
- if s == "bench":
- prompts, dia = "data/sft_v1/bench_prompts.jsonl", "blender"
- elif s == "threejs":
- prompts, dia = "eval/out/_3js_prompts.jsonl", "threejs"
- else:
- prompts, dia = f"{out}/prompts.jsonl", s
- with open(prompts, "w") as f:
- for l in open(f"data/multidialect/{s}/test.jsonl"):
- r = json.loads(l); f.write(json.dumps({"task": r["id"].replace("/", "__"), "messages": r["messages"][:2]}) + "\n")
- jobs.append({"name": s, "prompts": prompts, "out": out, "dialect": dia})
-json.dump(jobs, open(spec_path, "w"))
-print("[eval_all] suites:", [j["name"] for j in jobs])
-PY
-# On a shared box a card that was free when it was picked can be full by the time vLLM starts, and the engine
-# dies with no generations at all. Re-check right before launching, and fall back to whichever card is free now.
-for ATTEMPT in 1 2 3; do
- FREE_NOW=$(scripts/free_gpus.sh 40000)
- case ",$FREE_NOW," in
- *",$GPU,"*) ;;
- *) NEW=$(echo "$FREE_NOW" | cut -d, -f1)
- if [ -n "$NEW" ]; then
- echo "[eval_all] GPU $GPU filled up since it was picked; switching to $NEW"
- GPU=$NEW; export CUDA_VISIBLE_DEVICES=$GPU
- else
- echo "[eval_all] no card has 40 GB free; waiting 120s (attempt $ATTEMPT/3)"; sleep 120; continue
- fi;;
- esac
- python eval/generate_multi.py --model $MODEL --spec @$SPEC --tp $TP $NOTHINK \
- --max_new_tokens $MAXNEW --max_model_len $MAXLEN --temperature $TEMP --seed $SEED 2>&1 \
- | grep -E "gen-multi|extract\]|Error|Traceback" | tail -40
- # one generation directory per task; anything less means the engine never ran
- if [ "$(find eval/out/${NAME}_$(echo $SUITES | awk '{print $1}') -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)" -ge 5 ]; then break; fi
- echo "[eval_all] generation produced nothing on attempt $ATTEMPT; retrying"
- sleep 60
-done
-rm -f $SPEC
-
-# ---------- execution + metrics (llmft env) ----------
-conda activate llmft
-for S in $SUITES; do
- OUT=eval/out/${NAME}_${S}
- # An engine that never started leaves an empty directory, and every scorer below reports that as 0%. A real
- # 0% and a failed launch then look identical -- which is how a rescore of two healthy models came back as
- # 0/200 on every suite. Refuse to score instead.
- NGEN=$(find $OUT -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)
- if [ "${NGEN:-0}" -lt 5 ]; then
- echo "[eval_all] $S PRODUCED NOTHING ($NGEN generations) — not scoring. See the generation log above."
- continue
- fi
- echo "[eval_all] exec $S"
- case $S in
- bench) python eval/run_bench.py --gen_dir $OUT --workers 32 --timeout 300 2>&1 | grep -E "status counts" | tail -1
- python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1;;
- blender) python eval/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;
- threejs) python eval/threejs_eval.py --gen_dir $OUT 2>&1 | tail -2;;
- *) python eval/dialect_eval.py --dialect $S --test data/multidialect/$S/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;
- esac
-done
-python eval/results_all.py $NAME
-echo "[eval_all] DONE $NAME"
diff --git a/finetune/eval/exec_suites.sh b/finetune/eval/exec_suites.sh
deleted file mode 100755
index de3db938..00000000
--- a/finetune/eval/exec_suites.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/bash
-# Execute + score already-generated suites (no GPU): eval/exec_suites.sh <name> [suites...]
-set -uo pipefail; cd /wekafs/ict/hx_624/llm-ft
-NAME=$1; shift; SUITES=${@:-bench cadquery openscad glsl blender threejs}
-source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate llmft
-export PLAYWRIGHT_BROWSERS_PATH=/wekafs/ict/hx_624/cache/ms-playwright
-for S in $SUITES; do
- OUT=eval/out/${NAME}_${S}; [ -d $OUT ] || continue
- echo "[exec] $NAME/$S"
- case $S in
- bench) python eval/run_bench.py --gen_dir $OUT --workers 24 --timeout 300 2>&1 | grep -E "status counts" | tail -1
- python eval/metrics.py --gen_dir $OUT 2>&1 | tail -1;;
- blender) python eval/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 24 2>&1 | tail -1;;
- threejs) python eval/threejs_eval.py --gen_dir $OUT 2>&1 | tail -2;;
- *) python eval/dialect_eval.py --dialect $S --test data/multidialect/$S/test.jsonl --gen_dir $OUT --workers 24 2>&1 | tail -1;;
- esac
-done
-python eval/results_all.py $NAME
-echo "[exec] DONE $NAME"
diff --git a/finetune/eval/extract.py b/finetune/eval/extract.py
deleted file mode 100644
index 55eaa783..00000000
--- a/finetune/eval/extract.py
+++ /dev/null
@@ -1,220 +0,0 @@
-"""Dialect-aware code extraction from free-form model output.
-
-Why this exists: instruct/reasoning models do not answer with bare code. A single response may contain
-a <think> block (often with *draft* code), prose, several fenced blocks (setup shell commands, a JSON
-snippet, the real program, then a "here's a variant" block), or no fence at all. Taking "the longest
-fenced block" (the old rule) picks the draft or the variant often enough to matter.
-
-extract(text, dialect) -> (code, meta)
- * strips reasoning blocks (<think>…</think>, <thinking>…</thinking>, <reasoning>…</reasoning>);
- if the model never closed the block the answer is considered truncated-in-thought and we fall back
- to mining the thought itself (meta["from_think"]=True) so we can still score something.
- * collects candidates: every fenced block (closed or trailing-unterminated), plus the whole visible
- text as a last resort.
- * scores each candidate by: dialect markers (import bpy / cq. / mainImage / THREE. / module …),
- language tag on the fence, syntax validity (ast.parse for python dialects, structural checks
- otherwise), and penalises obvious non-answers (shell commands, pip installs, json, error logs).
- * ties are broken toward the LAST high-scoring block (models put the final program last), then length.
-
-meta keys: n_blocks, chosen, score, lang, had_think, think_chars, from_think, no_fence, valid, markers.
-"""
-import ast
-import json
-import re
-
-THINK_RE = re.compile(r"<(think|thinking|reasoning)>(.*?)</\1>", re.S | re.I)
-THINK_OPEN_RE = re.compile(r"<(think|thinking|reasoning)>(.*)$", re.S | re.I)
-FENCE_RE = re.compile(r"```([A-Za-z0-9_+.#-]*)[ \t]*\r?\n(.*?)```", re.S)
-FENCE_OPEN_RE = re.compile(r"```([A-Za-z0-9_+.#-]*)[ \t]*\r?\n(.*)$", re.S)
-
-# per-dialect: fence language tags, regexes that prove the block is that dialect, and how to syntax-check
-DIALECTS = {
- "blender": {
- "langs": {"python", "py", "python3", "blender", "bpy"},
- "markers": [r"^\s*import\s+bpy\b", r"\bbpy\.(ops|data|context)\b"],
- "check": "python",
- },
- "cadquery": {
- "langs": {"python", "py", "python3", "cadquery", "cq"},
- "markers": [r"^\s*import\s+cadquery\b", r"^\s*from\s+cadquery\b", r"\bcq\.Workplane\b", r"\bcadquery\.Workplane\b"],
- "check": "python",
- },
- "openscad": {
- "langs": {"openscad", "scad"},
- "markers": [r"^\s*module\s+\w+\s*\(", r"\b(cube|cylinder|sphere|polyhedron|linear_extrude|rotate_extrude|hull|minkowski)\s*\("],
- "check": "scad",
- },
- "glsl": {
- "langs": {"glsl", "frag", "fragment", "fs", "c", "cpp"},
- "markers": [r"void\s+mainImage\s*\(", r"\bgl_FragColor\b", r"^\s*#version\b", r"\bfragColor\b"],
- "check": "glsl",
- },
- "threejs": {
- "langs": {"html", "htm", "javascript", "js", "jsx"},
- "markers": [r"<!DOCTYPE\s+html", r"<html", r"\bnew\s+THREE\.", r"\bTHREE\.[A-Z]\w+"],
- "check": "html",
- },
- # generic python (used by "auto" when nothing dialect-specific matches)
- "python": {"langs": {"python", "py", "python3"}, "markers": [r"^\s*(import|from|def|class)\s+\w"], "check": "python"},
-}
-
-# blocks that are never the answer
-NEGATIVE = [
- (re.compile(r"^\s*(pip|conda|apt|sudo|blender|python)\s+(install|-m|-b)\b", re.M), 4),
- (re.compile(r"^\s*[$#>]\s+\w"), 3), # shell prompt
- (re.compile(r"^\s*\{[\s\S]*\}\s*$"), 2), # bare JSON
- (re.compile(r"^\s*(Traceback|Error:|error:)", re.M), 3), # pasted error log
-]
-
-
-def _syntax_ok(code, kind):
- if kind == "python":
- try:
- ast.parse(code)
- return True
- except SyntaxError:
- return False
- except Exception:
- return False
- if kind == "scad":
- return code.count("{") == code.count("}") and code.count("(") == code.count(")") and bool(re.search(r"[;{]", code))
- if kind == "glsl":
- return code.count("{") == code.count("}") and "void" in code
- if kind == "html":
- return ("<" in code and ">" in code) or "THREE" in code
- return True
-
-
-def _candidates(text):
- """[(lang, code, start_index)] for every fenced block, plus a trailing unterminated one."""
- out, last_end = [], 0
- for m in FENCE_RE.finditer(text):
- out.append((m.group(1).lower(), m.group(2), m.start()))
- last_end = m.end()
- tail = text[last_end:]
- m = FENCE_OPEN_RE.search(tail)
- if m and m.group(2).strip():
- out.append((m.group(1).lower(), m.group(2), last_end + m.start()))
- return out
-
-
-def _first_code_line(text):
- """No fence anywhere: drop the prose preamble, keep from the first code-looking line on."""
- pat = re.compile(r"^\s*(import\s+\w|from\s+\w|def\s+\w|class\s+\w|#\s*!|#version|module\s+\w|void\s+\w|<!DOCTYPE|<html|const\s+\w|let\s+\w|var\s+\w|function\s+\w|\$fn\s*=)")
- lines = text.splitlines()
- for i, ln in enumerate(lines):
- if pat.match(ln):
- return "\n".join(lines[i:])
- return text
-
-
-def _score(lang, code, spec):
- s, markers = 0.0, 0
- for pat in spec["markers"]:
- if re.search(pat, code, re.M):
- markers += 1
- s += 3.0 * min(markers, 2)
- if lang in spec["langs"]:
- s += 2.0
- elif lang == "":
- s += 0.5
- valid = _syntax_ok(code, spec["check"])
- if valid:
- s += 2.0
- for pat, pen in NEGATIVE:
- if pat.search(code):
- s -= pen
- if len(code.strip()) < 40:
- s -= 2.0
- return s, valid, markers
-
-
-def extract(text, dialect="auto"):
- meta = {"n_blocks": 0, "chosen": None, "score": None, "lang": None, "had_think": False,
- "think_chars": 0, "from_think": False, "no_fence": False, "valid": False, "markers": 0,
- "dialect": dialect}
- if not text:
- return "", meta
-
- # 1) reasoning blocks
- thinks = THINK_RE.findall(text)
- visible = THINK_RE.sub("", text)
- if thinks:
- meta["had_think"] = True
- meta["think_chars"] = sum(len(t[1]) for t in thinks)
- m = THINK_OPEN_RE.search(visible)
- if m: # unterminated <think>: everything after it is thought
- meta["had_think"] = True
- meta["think_chars"] += len(m.group(2))
- visible = visible[: m.start()]
-
- def _pick(src):
- cands = _candidates(src)
- if not cands:
- return None, None
- specs = [DIALECTS[dialect]] if dialect in DIALECTS else list(DIALECTS.values())
- best = None
- for i, (lang, code, _pos) in enumerate(cands):
- sc = max((_score(lang, code, sp) for sp in specs), key=lambda x: x[0])
- key = (round(sc[0], 3), i, len(code)) # score, then LAST block, then length
- if best is None or key > best[0]:
- best = (key, i, lang, code, sc)
- return cands, best
-
- cands, best = _pick(visible)
- if best is None and visible.strip(): # no fence in the visible answer
- code = _first_code_line(visible)
- specs = [DIALECTS[dialect]] if dialect in DIALECTS else list(DIALECTS.values())
- sc = max((_score("", code, sp) for sp in specs), key=lambda x: x[0])
- meta.update(n_blocks=0, no_fence=True, chosen=-1, score=round(sc[0], 2), lang="", valid=sc[1], markers=sc[2])
- return code.strip("\n"), meta
- if best is None: # nothing visible: mine the thought
- cands, best = _pick(text)
- meta["from_think"] = True
- if best is None:
- return "", meta
-
- meta.update(n_blocks=len(cands), chosen=best[1], score=round(best[4][0], 2), lang=best[2],
- valid=best[4][1], markers=best[4][2])
- return best[3].strip("\n"), meta
-
-
-def extract_code(text, dialect="auto"):
- """Backwards-compatible single-value API (old callers import this name from generate.py)."""
- return extract(text, dialect)[0]
-
-
-def summarize(metas):
- """Aggregate extraction metadata over a run -> dict for extract_stats.json."""
- n = max(1, len(metas))
- return {
- "n": len(metas),
- "with_think": sum(m.get("had_think", False) for m in metas),
- "mean_think_chars": round(sum(m.get("think_chars", 0) for m in metas) / n, 1),
- "no_fence": sum(m.get("no_fence", False) for m in metas),
- "from_think_fallback": sum(m.get("from_think", False) for m in metas),
- "multi_block": sum((m.get("n_blocks") or 0) > 1 for m in metas),
- "mean_blocks": round(sum(m.get("n_blocks") or 0 for m in metas) / n, 2),
- "chosen_not_last": sum(m.get("chosen") is not None and m.get("n_blocks") and m["chosen"] != m["n_blocks"] - 1 for m in metas),
- "syntax_valid": sum(m.get("valid", False) for m in metas),
- "no_dialect_marker": sum((m.get("markers") or 0) == 0 for m in metas),
- "empty": sum((m.get("score") is None) for m in metas),
- }
-
-
-if __name__ == "__main__": # tiny self-test: python eval/extract.py
- T = [
- ("<think>let me draft\n```python\nimport bpy\nbpy.ops.mesh.primitive_cube_add() # draft\n```\nno, better</think>\n"
- "Here is the script:\n```python\nimport bpy\nbpy.ops.mesh.primitive_uv_sphere_add(radius=2)\n```\nThat creates a sphere.",
- "blender", "uv_sphere"),
- ("First install:\n```bash\npip install cadquery\n```\nThen:\n```python\nimport cadquery as cq\nresult = cq.Workplane('XY').box(1,2,3)\n```",
- "cadquery", "Workplane"),
- ("Sure!\nimport bpy\nbpy.ops.mesh.primitive_cone_add()\n", "blender", "cone"),
- ("```\n$fn = 64;\nmodule part(){ cube([10,10,2]); }\npart();\n```", "openscad", "module part"),
- ("```glsl\nvoid mainImage(out vec4 O, in vec2 U){ O = vec4(1.0); }\n```", "glsl", "mainImage"),
- ("<think>thinking forever without closing\n```python\nimport bpy\nbpy.ops.mesh.primitive_torus_add()\n```",
- "blender", "torus"),
- ]
- for text, d, needle in T:
- code, meta = extract(text, d)
- print(("OK " if needle in code else "FAIL"), d, json.dumps({k: meta[k] for k in ("n_blocks", "chosen", "score", "had_think", "from_think", "no_fence", "valid")}))
diff --git a/finetune/eval/generate.py b/finetune/eval/generate.py
deleted file mode 100644
index cabaf670..00000000
--- a/finetune/eval/generate.py
+++ /dev/null
@@ -1,81 +0,0 @@
-"""Batched generation for the 3DCodeBench prompts with a HF causal LM. Writes <out>/<task>/code.py + gens.jsonl"""
-import argparse, json, os, re, time, torch
-from transformers import AutoTokenizer, AutoModelForCausalLM
-
-def extract_code(text):
- m = re.findall(r"```[a-zA-Z0-9_+.-]*[ \t]*\n(.*?)```", text, flags=re.S) # any language fence (python/glsl/openscad/...)
- if m:
- return max(m, key=len).strip("\n")
- m = re.search(r"```[a-zA-Z0-9_+.-]*[ \t]*\n(.*)$", text, flags=re.S) # unterminated block
- if m: return m.group(1).strip("\n")
- return text.strip()
-
-def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--model", required=True)
- ap.add_argument("--prompts", required=True)
- ap.add_argument("--out", required=True)
- ap.add_argument("--batch_size", type=int, default=16)
- ap.add_argument("--max_new_tokens", type=int, default=6144)
- ap.add_argument("--temperature", type=float, default=0.0)
- ap.add_argument("--top_p", type=float, default=0.95)
- ap.add_argument("--shard", type=int, default=0); ap.add_argument("--num_shards", type=int, default=1)
- ap.add_argument("--attn", default="auto")
- ap.add_argument("--limit", type=int, default=None)
- ap.add_argument("--no_think", action="store_true", help="pass enable_thinking=False to the chat template (Qwen3/3.5)")
- a = ap.parse_args()
- os.makedirs(a.out, exist_ok=True)
- attn = a.attn
- if attn == "auto":
- try: import flash_attn; attn = "flash_attention_2" # noqa
- except Exception: attn = "sdpa"
- tok = AutoTokenizer.from_pretrained(a.model, padding_side="left")
- if tok.pad_token is None: tok.pad_token = tok.eos_token
- try:
- model = AutoModelForCausalLM.from_pretrained(a.model, dtype=torch.bfloat16, attn_implementation=attn, device_map="cuda")
- except Exception as e: # multimodal wrappers (e.g. Qwen3.5 = Qwen3_5ForConditionalGeneration)
- print("[gen] AutoModelForCausalLM failed (%s); falling back to AutoModelForImageTextToText" % str(e)[:200], flush=True)
- from transformers import AutoModelForImageTextToText
- model = AutoModelForImageTextToText.from_pretrained(a.model, dtype=torch.bfloat16, attn_implementation=attn, device_map="cuda")
- model.eval()
- rows = [json.loads(l) for l in open(a.prompts)]
- rows = rows[a.shard::a.num_shards]
- if a.limit: rows = rows[:a.limit]
- # skip already-done
- done = set()
- outf = f"{a.out}/gens_shard{a.shard}.jsonl"
- if os.path.exists(outf):
- done = {json.loads(l)["task"] for l in open(outf)}
- rows = [r for r in rows if r["task"] not in done]
- print(f"[gen] {len(rows)} prompts to do (shard {a.shard}/{a.num_shards}) attn={attn}", flush=True)
- # sort by prompt length for efficient batching
- tmpl_kwargs = {"enable_thinking": False} if a.no_think else {}
- texts = [tok.apply_chat_template(r["messages"], tokenize=False, add_generation_prompt=True, **tmpl_kwargs) for r in rows]
- if texts: print("[gen] prompt tail example:", repr(texts[0][-200:]), flush=True)
- order = sorted(range(len(rows)), key=lambda i: len(texts[i]))
- gen_kwargs = dict(max_new_tokens=a.max_new_tokens, pad_token_id=tok.pad_token_id)
- if a.temperature > 0: gen_kwargs.update(do_sample=True, temperature=a.temperature, top_p=a.top_p)
- else: gen_kwargs.update(do_sample=False)
- t0 = time.time(); ntok = 0
- with open(outf, "a") as f:
- for b in range(0, len(order), a.batch_size):
- idx = order[b:b + a.batch_size]
- enc = tok([texts[i] for i in idx], return_tensors="pt", padding=True).to("cuda")
- with torch.no_grad():
- out = model.generate(**enc, **gen_kwargs)
- gen = out[:, enc["input_ids"].shape[1]:]
- for j, i in enumerate(idx):
- ids = gen[j]
- n = int((ids != tok.pad_token_id).sum())
- text = tok.decode(ids, skip_special_tokens=True)
- code = extract_code(text)
- finished = bool((ids == tok.eos_token_id).any()) or any((ids == t).any() for t in tok.all_special_ids if t != tok.pad_token_id) if n < a.max_new_tokens else False
- task = rows[i]["task"]; d = f"{a.out}/{task}"; os.makedirs(d, exist_ok=True)
- open(f"{d}/code.py", "w").write(code + "\n"); open(f"{d}/raw.txt", "w").write(text)
- f.write(json.dumps({"task": task, "n_new_tokens": n, "finished": finished, "has_code_block": "```" in text}) + "\n"); f.flush()
- ntok += n
- el = time.time() - t0
- print(f"[gen] {min(b + a.batch_size, len(order))}/{len(order)} done | {ntok} tok | {ntok/el:.0f} tok/s | {el/60:.1f} min", flush=True)
-
-if __name__ == "__main__":
- main()
diff --git a/finetune/eval/generate_multi.py b/finetune/eval/generate_multi.py
deleted file mode 100644
index db6f08f8..00000000
--- a/finetune/eval/generate_multi.py
+++ /dev/null
@@ -1,114 +0,0 @@
-"""Run several evaluation suites through ONE vLLM engine (loading a 27B twice costs more than generating).
-
- python eval/generate_multi.py --model M --tp 2 --spec '[{"name":"bench","prompts":"...","out":"...","dialect":"blender"}, ...]'
- [--no_think] [--temperature 0.7] [--seed 1] [--max_new_tokens 12288] [--max_model_len 16384] [--limit N]
-
-Writes, per job: <out>/<task>/{code.py,raw.txt}, <out>/gens_shard0.jsonl, <out>/extract_stats.json — identical to
-generate_vllm.py, so every downstream executor/metric script works unchanged.
-"""
-import argparse
-import json
-import os
-import sys
-import time
-
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from extract import extract, summarize
-
-
-
-def auto_gpu_mem(requested, tp=1, headroom_gib=4.0, model_dir=None):
- """`gpu_memory_utilization` is a fraction of the card's TOTAL memory, but this box is shared — asking for
- 0.88 of a card that another user already half fills makes vLLM refuse to start, and asking for exactly what
- is free makes its KV-cache profiling OOM instead. Derive the fraction from what is actually free, and scale
- the headroom with the model: a 51 GB checkpoint needs far more slack than a 18 GB one."""
- try:
- import subprocess, glob, os
- if model_dir and os.path.isdir(model_dir):
- gib = sum(os.path.getsize(f) for f in glob.glob(os.path.join(model_dir, "*.safetensors"))) / 1024**3
- if gib > 30:
- headroom_gib = max(headroom_gib, 10.0)
- out = subprocess.run(["nvidia-smi", "--query-gpu=memory.total,memory.used", "--format=csv,noheader,nounits"],
- capture_output=True, text=True, timeout=30).stdout.strip().splitlines()
- vis = os.environ.get("CUDA_VISIBLE_DEVICES", "")
- idx = [int(x) for x in vis.split(",") if x.strip().isdigit()] or list(range(len(out)))
- worst = 1.0
- for i in idx[:max(1, tp)]:
- tot, used = (int(v) for v in out[i].split(","))
- free_gib = (tot - used) / 1024.0
- worst = min(worst, max(0.10, (free_gib - headroom_gib) / (tot / 1024.0)))
- if worst < requested:
- print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (shared card, {headroom_gib:.0f} GiB headroom)", flush=True)
- return round(worst, 2)
- except Exception as e:
- print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
- return requested
-
-
-def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--model", required=True)
- ap.add_argument("--spec", required=True, help="JSON list (or @file) of {name,prompts,out,dialect}")
- ap.add_argument("--max_new_tokens", type=int, default=8192)
- ap.add_argument("--max_model_len", type=int, default=12288)
- ap.add_argument("--temperature", type=float, default=0.0)
- ap.add_argument("--seed", type=int, default=0)
- ap.add_argument("--no_think", action="store_true")
- ap.add_argument("--tp", type=int, default=1)
- ap.add_argument("--gpu_mem", type=float, default=0.88)
- # Qwen3.5/3.8 carry linear-attention layers and vLLM needs one Mamba cache block per concurrent sequence;
- # the default 1024 exceeds the blocks a 27B leaves free and the engine refuses to start
- ap.add_argument("--max_num_seqs", type=int, default=None)
- ap.add_argument("--limit", type=int, default=None)
- a = ap.parse_args()
- spec = json.load(open(a.spec[1:])) if a.spec.startswith("@") else json.loads(a.spec)
-
- from vllm import LLM, SamplingParams
- t_load = time.time()
- llm = LLM(model=a.model, dtype="bfloat16", tensor_parallel_size=a.tp, max_model_len=a.max_model_len,
- gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1), model_dir=a.model), enable_prefix_caching=True,
- limit_mm_per_prompt={"image": 0, "video": 0}, trust_remote_code=True,
- **({"max_num_seqs": a.max_num_seqs} if a.max_num_seqs else {}))
- print(f"[gen-multi] engine up in {time.time()-t_load:.0f}s | jobs: {[j['name'] for j in spec]}", flush=True)
- sp = SamplingParams(temperature=a.temperature, top_p=0.95 if a.temperature > 0 else 1.0,
- max_tokens=a.max_new_tokens, seed=a.seed)
- kw = {"chat_template_kwargs": {"enable_thinking": False}} if a.no_think else {}
-
- for job in spec:
- rows = [json.loads(l) for l in open(job["prompts"])]
- if a.limit:
- rows = rows[: a.limit]
- os.makedirs(job["out"], exist_ok=True)
- t0 = time.time()
- outs = llm.chat([r["messages"] for r in rows], sp, use_tqdm=True, **kw)
- el = time.time() - t0
- ntok, metas = 0, []
- with open(f"{job['out']}/gens_shard0.jsonl", "w") as f:
- for r, o in zip(rows, outs):
- text = o.outputs[0].text
- n = len(o.outputs[0].token_ids)
- ntok += n
- d = f"{job['out']}/{r['task']}"
- os.makedirs(d, exist_ok=True)
- code, meta = extract(text, job.get("dialect", "auto"))
- metas.append(meta)
- open(f"{d}/code.py", "w").write(code + "\n")
- open(f"{d}/raw.txt", "w").write(text)
- f.write(json.dumps({"task": r["task"], "n_new_tokens": n,
- "finished": o.outputs[0].finish_reason == "stop",
- "has_code_block": "```" in text, "extract": meta}) + "\n")
- stats = summarize(metas)
- stats.update({"model": a.model, "dialect": job.get("dialect"), "temperature": a.temperature,
- "no_think": a.no_think, "max_new_tokens": a.max_new_tokens,
- "tok_per_s": round(ntok / max(el, 1e-6), 1), "mean_new_tokens": round(ntok / max(1, len(rows)), 1),
- "truncated": sum(1 for r, o in zip(rows, outs) if o.outputs[0].finish_reason != "stop")})
- json.dump(stats, open(f"{job['out']}/extract_stats.json", "w"), indent=2)
- print(f"[gen-multi] {job['name']}: {len(rows)} prompts | {ntok} tok | {ntok/el:.0f} tok/s | {el/60:.1f} min", flush=True)
- print("[extract] " + json.dumps({k: stats[k] for k in ("with_think", "no_fence", "from_think_fallback",
- "multi_block", "chosen_not_last", "syntax_valid",
- "no_dialect_marker", "truncated")}), flush=True)
- print("[gen-multi] ALL GENERATION DONE", flush=True)
-
-
-if __name__ == "__main__":
- main()
diff --git a/finetune/eval/generate_vllm.py b/finetune/eval/generate_vllm.py
deleted file mode 100644
index d0593ba9..00000000
--- a/finetune/eval/generate_vllm.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""vLLM version of generate.py: same outputs (<out>/<task>/code.py + raw.txt, <out>/gens_shard0.jsonl)."""
-import argparse, json, os, re, time, sys
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from generate import extract_code as extract_code_legacy
-from extract import extract, summarize
-
-
-def auto_gpu_mem(requested, tp=1, headroom_gib=4.0, model_dir=None):
- """`gpu_memory_utilization` is a fraction of the card's TOTAL memory, but this box is shared — asking for
- 0.88 of a card that another user already half fills makes vLLM refuse to start, and asking for exactly what
- is free makes its KV-cache profiling OOM instead. Derive the fraction from what is actually free, and scale
- the headroom with the model: a 51 GB checkpoint needs far more slack than a 18 GB one."""
- try:
- import subprocess, glob, os
- if model_dir and os.path.isdir(model_dir):
- gib = sum(os.path.getsize(f) for f in glob.glob(os.path.join(model_dir, "*.safetensors"))) / 1024**3
- if gib > 30:
- headroom_gib = max(headroom_gib, 10.0)
- out = subprocess.run(["nvidia-smi", "--query-gpu=memory.total,memory.used", "--format=csv,noheader,nounits"],
- capture_output=True, text=True, timeout=30).stdout.strip().splitlines()
- vis = os.environ.get("CUDA_VISIBLE_DEVICES", "")
- idx = [int(x) for x in vis.split(",") if x.strip().isdigit()] or list(range(len(out)))
- worst = 1.0
- for i in idx[:max(1, tp)]:
- tot, used = (int(v) for v in out[i].split(","))
- free_gib = (tot - used) / 1024.0
- worst = min(worst, max(0.10, (free_gib - headroom_gib) / (tot / 1024.0)))
- if worst < requested:
- print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (shared card, {headroom_gib:.0f} GiB headroom)", flush=True)
- return round(worst, 2)
- except Exception as e:
- print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
- return requested
-
-
-def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--model", required=True); ap.add_argument("--prompts", required=True); ap.add_argument("--out", required=True)
- ap.add_argument("--max_new_tokens", type=int, default=6144); ap.add_argument("--temperature", type=float, default=0.0)
- ap.add_argument("--max_model_len", type=int, default=12288); ap.add_argument("--no_think", action="store_true")
- ap.add_argument("--dialect", default="auto", help="blender|cadquery|openscad|glsl|threejs|auto — steers code extraction from free-form answers")
- ap.add_argument("--legacy_extract", action="store_true", help="use the old longest-fenced-block rule")
- ap.add_argument("--tp", type=int, default=1); ap.add_argument("--gpu_mem", type=float, default=0.88)
- # Qwen3.5/3.8 carry linear-attention layers and vLLM needs one Mamba cache block per concurrent sequence;
- # the default 1024 exceeds the blocks a 27B leaves free and the engine refuses to start
- ap.add_argument("--max_num_seqs", type=int, default=None); ap.add_argument("--limit", type=int, default=None); ap.add_argument("--seed", type=int, default=0)
- a = ap.parse_args()
- from vllm import LLM, SamplingParams
- os.makedirs(a.out, exist_ok=True)
- rows = [json.loads(l) for l in open(a.prompts)]
- if a.limit: rows = rows[:a.limit]
- llm = LLM(model=a.model, dtype="bfloat16", tensor_parallel_size=a.tp, max_model_len=a.max_model_len, gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1), model_dir=a.model),
- enable_prefix_caching=True, limit_mm_per_prompt={"image": 0, "video": 0}, trust_remote_code=True,
- **({"max_num_seqs": a.max_num_seqs} if a.max_num_seqs else {}))
- sp = SamplingParams(temperature=a.temperature, top_p=0.95 if a.temperature > 0 else 1.0, max_tokens=a.max_new_tokens, seed=a.seed)
- kw = {"chat_template_kwargs": {"enable_thinking": False}} if a.no_think else {}
- t0 = time.time()
- outs = llm.chat([r["messages"] for r in rows], sp, use_tqdm=True, **kw)
- el = time.time() - t0; ntok = 0
- metas = []
- with open(f"{a.out}/gens_shard0.jsonl", "w") as f:
- for r, o in zip(rows, outs):
- text = o.outputs[0].text; n = len(o.outputs[0].token_ids); ntok += n
- d = f"{a.out}/{r['task']}"; os.makedirs(d, exist_ok=True)
- if a.legacy_extract:
- code, meta = extract_code_legacy(text), {}
- else:
- code, meta = extract(text, a.dialect)
- metas.append(meta)
- open(f"{d}/code.py", "w").write(code + "\n"); open(f"{d}/raw.txt", "w").write(text)
- f.write(json.dumps({"task": r["task"], "n_new_tokens": n, "finished": o.outputs[0].finish_reason == "stop",
- "has_code_block": "```" in text, "extract": meta}) + "\n")
- stats = summarize(metas) if not a.legacy_extract else {"legacy": True}
- stats.update({"model": a.model, "dialect": a.dialect, "temperature": a.temperature, "no_think": a.no_think,
- "max_new_tokens": a.max_new_tokens, "tok_per_s": round(ntok / el, 1), "mean_new_tokens": round(ntok / max(1, len(rows)), 1)})
- json.dump(stats, open(f"{a.out}/extract_stats.json", "w"), indent=2)
- print(f"[gen-vllm] {len(rows)} prompts | {ntok} tok | {ntok/el:.0f} tok/s | {el/60:.1f} min", flush=True)
- if not a.legacy_extract:
- print("[extract] " + json.dumps({k: stats[k] for k in ("with_think", "no_fence", "from_think_fallback", "multi_block", "chosen_not_last", "syntax_valid", "no_dialect_marker")}), flush=True)
-
-if __name__ == "__main__":
- main()
diff --git a/finetune/eval/generate_vllm_img.py b/finetune/eval/generate_vllm_img.py
deleted file mode 100644
index 123c682b..00000000
--- a/finetune/eval/generate_vllm_img.py
+++ /dev/null
@@ -1,98 +0,0 @@
-"""vLLM generation with image inputs (multimodal prompts), same outputs as generate_vllm.py.
-
-Prompt file rows: {"task", "images": [paths], "messages": [{role, content}]} where the user content contains one
-`<image>` per image. The images are attached as multi_modal_data so the model actually sees them.
-"""
-import argparse, json, os, sys, time
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from extract import extract, summarize
-
-
-def auto_gpu_mem(requested, tp=1, headroom_gib=4.0, model_dir=None):
- """`gpu_memory_utilization` is a fraction of the card's TOTAL memory, but this box is shared — asking for
- 0.88 of a card that another user already half fills makes vLLM refuse to start, and asking for exactly what
- is free makes its KV-cache profiling OOM instead. Derive the fraction from what is actually free, and scale
- the headroom with the model: a 51 GB checkpoint needs far more slack than a 18 GB one."""
- try:
- import subprocess, glob, os
- if model_dir and os.path.isdir(model_dir):
- gib = sum(os.path.getsize(f) for f in glob.glob(os.path.join(model_dir, "*.safetensors"))) / 1024**3
- if gib > 30:
- headroom_gib = max(headroom_gib, 10.0)
- out = subprocess.run(["nvidia-smi", "--query-gpu=memory.total,memory.used", "--format=csv,noheader,nounits"],
- capture_output=True, text=True, timeout=30).stdout.strip().splitlines()
- vis = os.environ.get("CUDA_VISIBLE_DEVICES", "")
- idx = [int(x) for x in vis.split(",") if x.strip().isdigit()] or list(range(len(out)))
- worst = 1.0
- for i in idx[:max(1, tp)]:
- tot, used = (int(v) for v in out[i].split(","))
- free_gib = (tot - used) / 1024.0
- worst = min(worst, max(0.10, (free_gib - headroom_gib) / (tot / 1024.0)))
- if worst < requested:
- print(f"[gen] gpu_memory_utilization {requested} -> {worst:.2f} (shared card, {headroom_gib:.0f} GiB headroom)", flush=True)
- return round(worst, 2)
- except Exception as e:
- print(f"[gen] auto_gpu_mem failed ({e}); keeping {requested}", flush=True)
- return requested
-
-
-def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--model", required=True); ap.add_argument("--prompts", required=True); ap.add_argument("--out", required=True)
- ap.add_argument("--max_new_tokens", type=int, default=32768); ap.add_argument("--max_model_len", type=int, default=12288)
- ap.add_argument("--temperature", type=float, default=0.0); ap.add_argument("--seed", type=int, default=0)
- ap.add_argument("--tp", type=int, default=1); ap.add_argument("--gpu_mem", type=float, default=0.88)
- # Qwen3.5/3.8 carry linear-attention layers and vLLM needs one Mamba cache block per concurrent sequence;
- # the default 1024 exceeds the blocks a 27B leaves free and the engine refuses to start
- ap.add_argument("--max_num_seqs", type=int, default=None)
- ap.add_argument("--presence_penalty", type=float, default=0.0)
- ap.add_argument("--repetition_penalty", type=float, default=1.0)
- ap.add_argument("--dialect", default="blender"); ap.add_argument("--limit", type=int, default=None)
- a = ap.parse_args()
- from vllm import LLM, SamplingParams
- from PIL import Image
- rows = [json.loads(l) for l in open(a.prompts) if l.strip()]
- if a.limit: rows = rows[:a.limit]
- os.makedirs(a.out, exist_ok=True)
- llm = LLM(model=a.model, dtype="bfloat16", tensor_parallel_size=a.tp, max_model_len=a.max_model_len,
- gpu_memory_utilization=auto_gpu_mem(a.gpu_mem, getattr(a, 'tp', 1), model_dir=a.model), limit_mm_per_prompt={"image": 4, "video": 0}, trust_remote_code=True,
- **({"max_num_seqs": a.max_num_seqs} if a.max_num_seqs else {}))
- sp = SamplingParams(temperature=a.temperature, top_p=0.95 if a.temperature > 0 else 1.0,
- presence_penalty=a.presence_penalty, repetition_penalty=a.repetition_penalty,
- max_tokens=a.max_new_tokens, seed=a.seed)
- import base64, io
- def data_url(path):
- im = Image.open(path).convert("RGB")
- im.thumbnail((768, 768))
- b = io.BytesIO(); im.save(b, "JPEG", quality=88)
- return "data:image/jpeg;base64," + base64.b64encode(b.getvalue()).decode()
- convs = []
- for r in rows:
- msgs = []
- for m in r["messages"]:
- if m["role"] == "user" and r.get("images"):
- parts = [{"type": "image_url", "image_url": {"url": data_url(p)}} for p in r["images"]]
- parts.append({"type": "text", "text": m["content"].replace("<image>", "").strip()})
- msgs.append({"role": "user", "content": parts})
- else:
- msgs.append(m)
- convs.append(msgs)
- t0 = time.time()
- outs = llm.chat(convs, sp, use_tqdm=True, chat_template_kwargs={"enable_thinking": False})
- el = time.time() - t0; ntok = 0; metas = []
- with open(f"{a.out}/gens_shard0.jsonl", "w") as f:
- for r, o in zip(rows, outs):
- text = o.outputs[0].text; n = len(o.outputs[0].token_ids); ntok += n
- d = f"{a.out}/{r['task']}"; os.makedirs(d, exist_ok=True)
- code, meta = extract(text, a.dialect); metas.append(meta)
- open(f"{d}/code.py", "w").write(code + "\n"); open(f"{d}/raw.txt", "w").write(text)
- f.write(json.dumps({"task": r["task"], "n_new_tokens": n,
- "finished": o.outputs[0].finish_reason == "stop",
- "has_code_block": "```" in text, "extract": meta}) + "\n")
- st = summarize(metas); st.update({"model": a.model, "images": True, "tok_per_s": round(ntok/max(el,1e-6), 1),
- "mean_new_tokens": round(ntok/max(1, len(rows)), 1)})
- json.dump(st, open(f"{a.out}/extract_stats.json", "w"), indent=2)
- print(f"[gen-vllm-img] {len(rows)} prompts | {ntok} tok | {ntok/el:.0f} tok/s | {el/60:.1f} min", flush=True)
-
-if __name__ == "__main__":
- main()
diff --git a/finetune/eval/glsl_render.py b/finetune/eval/glsl_render.py
deleted file mode 100644
index 5061be39..00000000
--- a/finetune/eval/glsl_render.py
+++ /dev/null
@@ -1,119 +0,0 @@
-"""Render a Shadertoy fragment shader in a real WebGL2 context and check that it draws something.
-
-Compiling is necessary but not sufficient: a shader can compile and still paint a constant colour. This runs the
-shader in headless Chromium (the same browser the three.js runner uses), samples two frames (iTime = 0 and 1.7 s)
-and reports, per frame, how many distinct quantised colours the canvas holds and its pixel standard deviation.
-
- render_glsl(code, workdir) -> {status, error, distinct, std, changed, shot}
- status OK renders a non-uniform image
- STATIC renders, but the image is (near) uniform — usually a black screen
- FAIL shader/link error inside the browser, or the page threw
- changed True if frame(1.7s) differs from frame(0) — i.e. the shader animates
-
-usage as a script: python eval/glsl_render.py file1.glsl [file2.glsl ...]
-"""
-import json
-import os
-import sys
-
-HTML = """<!doctype html><html><body style="margin:0">
-<canvas id=c width=320 height=240></canvas>
-<script>
-const FS_BODY = %s;
-const vs = `#version 300 es
-in vec2 p; void main(){ gl_Position = vec4(p,0.,1.); }`;
-const fsHead = `#version 300 es
-precision highp float; precision highp int;
-uniform vec3 iResolution; uniform float iTime; uniform float iTimeDelta; uniform int iFrame;
-uniform vec4 iMouse; uniform vec4 iDate; uniform float iSampleRate; uniform float iFrameRate;
-uniform float iChannelTime[4]; uniform vec3 iChannelResolution[4];
-uniform sampler2D iChannel0; uniform sampler2D iChannel1; uniform sampler2D iChannel2; uniform sampler2D iChannel3;
-out vec4 _fragColor;
-`;
-const fsTail = `
-void main(){ mainImage(_fragColor, gl_FragCoord.xy); }`;
-window.__result = {ok:false, err:null};
-(function(){
- const c = document.getElementById('c');
- const gl = c.getContext('webgl2', {preserveDrawingBuffer:true});
- if (!gl) { window.__result.err = 'no webgl2'; return; }
- function sh(t, src){ const s = gl.createShader(t); gl.shaderSource(s, src); gl.compileShader(s);
- if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s).split('\\n')[0]); return s; }
- try {
- const body = FS_BODY.replace(/^\\s*#version[^\\n]*\\n/, '');
- const p = gl.createProgram();
- gl.attachShader(p, sh(gl.VERTEX_SHADER, vs));
- gl.attachShader(p, sh(gl.FRAGMENT_SHADER, fsHead + body + fsTail));
- gl.linkProgram(p);
- if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p).split('\\n')[0]);
- gl.useProgram(p);
- const buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 3,-1, -1,3]), gl.STATIC_DRAW);
- const loc = gl.getAttribLocation(p, 'p'); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
- const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([128,128,128,255]));
- for (let i=0;i<4;i++){ const u = gl.getUniformLocation(p, 'iChannel'+i); if (u) gl.uniform1i(u, 0); }
- window.__draw = function(t){
- gl.uniform3f(gl.getUniformLocation(p,'iResolution'), c.width, c.height, 1);
- gl.uniform1f(gl.getUniformLocation(p,'iTime'), t);
- gl.uniform1f(gl.getUniformLocation(p,'iTimeDelta'), 1/60);
- gl.uniform1i(gl.getUniformLocation(p,'iFrame'), Math.floor(t*60));
- gl.uniform1f(gl.getUniformLocation(p,'iFrameRate'), 60);
- gl.viewport(0,0,c.width,c.height); gl.drawArrays(gl.TRIANGLES, 0, 3);
- const px = new Uint8Array(c.width*c.height*4);
- gl.readPixels(0,0,c.width,c.height, gl.RGBA, gl.UNSIGNED_BYTE, px);
- const seen = new Set(); let sum=0, sum2=0, n=0;
- for (let i=0;i<px.length;i+=4*7){ const r=px[i]>>4, g=px[i+1]>>4, b=px[i+2]>>4;
- seen.add((r<<8)|(g<<4)|b); const v=(px[i]+px[i+1]+px[i+2])/3; sum+=v; sum2+=v*v; n++; }
- const mean=sum/n; return {distinct: seen.size, std: Math.sqrt(Math.max(0, sum2/n - mean*mean)), mean};
- };
- window.__result.ok = true;
- } catch(e) { window.__result.err = String(e.message || e); }
-})();
-</script></body></html>"""
-
-
-def render_glsl(code, workdir, timeout=40):
- os.makedirs(workdir, exist_ok=True)
- html = HTML % json.dumps(code)
- p = os.path.join(workdir, "index.html")
- open(p, "w").write(html)
- rep = {"status": "FAIL", "error": None, "distinct": 0, "std": 0.0, "changed": False, "shot": None}
- try:
- from playwright.sync_api import sync_playwright
- with sync_playwright() as pw:
- b = pw.chromium.launch(args=["--use-gl=swiftshader", "--enable-unsafe-swiftshader", "--no-sandbox"])
- pg = b.new_page()
- errs = []
- pg.on("pageerror", lambda e: errs.append(str(e)[:200]))
- pg.goto("file://" + os.path.abspath(p), wait_until="load", timeout=timeout * 1000)
- res = pg.evaluate("window.__result")
- if not res or not res.get("ok"):
- rep["error"] = (res or {}).get("err") or (errs[0] if errs else "no result")
- b.close()
- return rep
- a = pg.evaluate("window.__draw(0.0)")
- c = pg.evaluate("window.__draw(1.7)")
- try: # a screenshot failure must not discard a good render
- shot = os.path.join(workdir, "frame.png")
- pg.screenshot(path=shot)
- rep["shot"] = shot
- except Exception:
- rep["shot"] = None
- b.close()
- rep["distinct"] = max(a["distinct"], c["distinct"])
- rep["std"] = round(max(a["std"], c["std"]), 2)
- rep["changed"] = abs(a["mean"] - c["mean"]) > 0.5 or a["distinct"] != c["distinct"]
- rep["status"] = "OK" if (rep["distinct"] > 3 and rep["std"] > 2.0) else "STATIC"
- if rep["status"] == "STATIC":
- rep["error"] = f"uniform image (distinct={rep['distinct']}, std={rep['std']})"
- except Exception as e:
- rep["error"] = str(e)[:200]
- return rep
-
-
-if __name__ == "__main__":
- import tempfile
- for f in sys.argv[1:]:
- r = render_glsl(open(f).read(), tempfile.mkdtemp())
- print(f"{r['status']:6s} distinct={r['distinct']:3d} std={r['std']:6.2f} animated={r['changed']} {os.path.basename(f)} {r['error'] or ''}")
diff --git a/finetune/eval/glsl_render_batch.py b/finetune/eval/glsl_render_batch.py
deleted file mode 100644
index 0fab900a..00000000
--- a/finetune/eval/glsl_render_batch.py
+++ /dev/null
@@ -1,143 +0,0 @@
-"""Render many Shadertoy shaders in ONE persistent WebGL2 context.
-
-Launching a browser per shader costs 3-5 s and dominates everything (the first version of this check ran for
-3h43m without finishing 250 shaders). The page below compiles a new fragment program in place, so each shader
-costs ~50-150 ms. Two frames are sampled (iTime 0 and 1.7 s) and the canvas is read back with readPixels — no
-screenshots, which is what silently discarded good renders in the first version.
-
- with BatchRenderer() as r:
- rep = r.run(shader_source) # {status: OK|STATIC|FAIL, distinct, std, changed, error}
-"""
-import os
-
-HARNESS = """<!doctype html><html><body style="margin:0"><canvas id=c width=320 height=240></canvas><script>
-const c = document.getElementById('c');
-const gl = c.getContext('webgl2', {preserveDrawingBuffer:true});
-const VS = `#version 300 es
-in vec2 p; void main(){ gl_Position = vec4(p,0.,1.); }`;
-const HEAD = `#version 300 es
-precision highp float; precision highp int;
-uniform vec3 iResolution; uniform float iTime; uniform float iTimeDelta; uniform int iFrame;
-uniform vec4 iMouse; uniform vec4 iDate; uniform float iSampleRate; uniform float iFrameRate;
-uniform float iChannelTime[4]; uniform vec3 iChannelResolution[4];
-uniform sampler2D iChannel0; uniform sampler2D iChannel1; uniform sampler2D iChannel2; uniform sampler2D iChannel3;
-out vec4 _fragColor;
-`;
-const TAIL = `
-void main(){ mainImage(_fragColor, gl_FragCoord.xy); }`;
-let vs = null, buf = null, tex = null;
-if (gl) {
- vs = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vs, VS); gl.compileShader(vs);
- buf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 3,-1, -1,3]), gl.STATIC_DRAW);
- tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([128,128,128,255]));
-}
-function measure(){
- const px = new Uint8Array(c.width*c.height*4);
- gl.readPixels(0,0,c.width,c.height, gl.RGBA, gl.UNSIGNED_BYTE, px);
- const seen = new Set(); let sum=0, sum2=0, n=0;
- for (let i=0;i<px.length;i+=4*7){ const r=px[i]>>4, g=px[i+1]>>4, b=px[i+2]>>4;
- seen.add((r<<8)|(g<<4)|b); const v=(px[i]+px[i+1]+px[i+2])/3; sum+=v; sum2+=v*v; n++; }
- const mean=sum/n; return {distinct: seen.size, std: Math.sqrt(Math.max(0, sum2/n-mean*mean)), mean};
-}
-window.__run = function(src){
- if (!gl) return {status:'FAIL', error:'no webgl2', distinct:0, std:0, changed:false};
- let prog = null, fs = null;
- try {
- const body = src.replace(/^\\s*#version[^\\n]*\\n/, '');
- fs = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fs, HEAD + body + TAIL); gl.compileShader(fs);
- if (!gl.getShaderParameter(fs, gl.COMPILE_STATUS))
- return {status:'FAIL', error:(gl.getShaderInfoLog(fs)||'').split('\\n')[0].slice(0,140), distinct:0, std:0, changed:false};
- prog = gl.createProgram(); gl.attachShader(prog, vs); gl.attachShader(prog, fs); gl.linkProgram(prog);
- if (!gl.getProgramParameter(prog, gl.LINK_STATUS))
- return {status:'FAIL', error:(gl.getProgramInfoLog(prog)||'').split('\\n')[0].slice(0,140), distinct:0, std:0, changed:false};
- gl.useProgram(prog);
- gl.bindBuffer(gl.ARRAY_BUFFER, buf);
- const loc = gl.getAttribLocation(prog, 'p');
- if (loc >= 0) { gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); }
- gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, tex);
- for (let i=0;i<4;i++){ const u = gl.getUniformLocation(prog,'iChannel'+i); if (u) gl.uniform1i(u, 0); }
- const out = [];
- for (const t of [0.0, 1.7]) {
- gl.uniform3f(gl.getUniformLocation(prog,'iResolution'), c.width, c.height, 1);
- gl.uniform1f(gl.getUniformLocation(prog,'iTime'), t);
- gl.uniform1f(gl.getUniformLocation(prog,'iTimeDelta'), 1/60);
- gl.uniform1i(gl.getUniformLocation(prog,'iFrame'), Math.floor(t*60));
- gl.uniform1f(gl.getUniformLocation(prog,'iFrameRate'), 60);
- gl.clearColor(0,0,0,1); gl.clear(gl.COLOR_BUFFER_BIT);
- gl.viewport(0,0,c.width,c.height); gl.drawArrays(gl.TRIANGLES, 0, 3);
- out.push(measure());
- }
- const a = out[0], b = out[1];
- const distinct = Math.max(a.distinct, b.distinct), std = Math.max(a.std, b.std);
- return {status: (distinct > 3 && std > 2.0) ? 'OK' : 'STATIC', distinct: distinct, std: std,
- changed: Math.abs(a.mean-b.mean) > 0.5 || a.distinct !== b.distinct, error: null};
- } catch(e) {
- return {status:'FAIL', error:String((e && e.message) || e).slice(0,140), distinct:0, std:0, changed:false};
- } finally { if (prog) gl.deleteProgram(prog); if (fs) gl.deleteShader(fs); }
-};
-window.__ready = true;
-</script></body></html>"""
-
-
-class BatchRenderer:
- def __init__(self, timeout_ms=20000):
- self.timeout_ms = timeout_ms
- self._pw = self._b = self._pg = None
-
- def _new_page(self):
- self._pg = self._b.new_page()
- self._pg.set_default_timeout(self.timeout_ms)
- self._pg.set_content(HARNESS, wait_until="load")
- self._pg.wait_for_function("window.__ready === true", timeout=self.timeout_ms)
-
- def __enter__(self):
- os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", "/wekafs/ict/hx_624/cache/ms-playwright")
- from playwright.sync_api import sync_playwright
- self._pw = sync_playwright().start()
- self._b = self._pw.chromium.launch(args=["--use-gl=swiftshader", "--enable-unsafe-swiftshader", "--no-sandbox"])
- self._new_page()
- return self
-
- def _relaunch(self):
- """a crashed page can be replaced; a crashed browser cannot — rebuild whichever died, so that one bad
- shader cannot turn every later shader handled by this worker into a false FAIL"""
- for x in (self._pg, self._b):
- try:
- x.close()
- except Exception:
- pass
- self._b = self._pw.chromium.launch(args=["--use-gl=swiftshader", "--enable-unsafe-swiftshader", "--no-sandbox"])
- self._new_page()
-
- def run(self, src, _retry=True):
- try:
- return self._pg.evaluate("s => window.__run(s)", src)
- except Exception as e:
- msg = str(e)[:140]
- try:
- self._new_page()
- except Exception:
- try:
- self._relaunch()
- except Exception:
- return {"status": "FAIL", "error": "renderer unrecoverable: " + msg,
- "distinct": 0, "std": 0.0, "changed": False}
- if _retry: # one honest second chance on a fresh context
- try:
- return self.run(src, _retry=False)
- except Exception:
- pass
- return {"status": "FAIL", "error": msg, "distinct": 0, "std": 0.0, "changed": False}
-
- def __exit__(self, *a):
- for x in (self._pg, self._b):
- try:
- x.close()
- except Exception:
- pass
- try:
- self._pw.stop()
- except Exception:
- pass
diff --git a/finetune/eval/metrics.py b/finetune/eval/metrics.py
deleted file mode 100644
index b2229a24..00000000
--- a/finetune/eval/metrics.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""Geometry metrics between generated GLB and the 3DCodeBench ground-truth GLB.
-Normalisation: center at bbox center, scale so max bbox extent = 1. Metrics: symmetric Chamfer-L2 distance (mean NN distance),
-F-score @0.05 / @0.1, best over 4 yaw rotations (objects may face any direction). Writes <gen_dir>/metrics.jsonl + summary.json"""
-import argparse, json, os, numpy as np
-import trimesh
-from scipy.spatial import cKDTree
-
-BENCH = "/wekafs/ict/hx_624/data/3dcodebench/data"
-
-def load_points(path, n):
- m = trimesh.load(path, force="mesh")
- if isinstance(m, trimesh.Scene): m = trimesh.util.concatenate(list(m.geometry.values()))
- if m.is_empty or len(m.faces) == 0: return None
- v = m.vertices
- c = (v.max(0) + v.min(0)) / 2; s = (v.max(0) - v.min(0)).max()
- if s <= 0: return None
- m.apply_translation(-c); m.apply_scale(1.0 / s)
- pts, _ = trimesh.sample.sample_surface(m, n)
- return np.asarray(pts)
-
-def chamfer_f(a, b, taus=(0.05, 0.1)):
- ta, tb = cKDTree(a), cKDTree(b)
- da, _ = tb.query(a); db, _ = ta.query(b)
- cd = float(da.mean() + db.mean())
- fs = {}
- for t in taus:
- p = float((da < t).mean()); r = float((db < t).mean())
- fs[f"f@{t}"] = 2 * p * r / (p + r) if p + r > 0 else 0.0
- return cd, fs
-
-def rot_y(p, k):
- th = np.pi / 2 * k; c, s = np.cos(th), np.sin(th)
- R = np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
- return p @ R.T
-
-def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--gen_dir", required=True)
- ap.add_argument("--n_points", type=int, default=10000)
- a = ap.parse_args()
- np.random.seed(0)
- ex = {json.loads(l)["task"]: json.loads(l) for l in open(os.path.join(a.gen_dir, "exec_results.jsonl"))}
- tasks = sorted(os.listdir(BENCH))
- rows = []
- for t in tasks:
- r = {"task": t, "exec": ex.get(t, {}).get("status", "MISSING")}
- gen_glb = os.path.join(a.gen_dir, t, "out.glb"); gt_glb = os.path.join(BENCH, t, "glb", f"{t}.glb")
- if r["exec"] == "OK" and os.path.exists(gen_glb) and os.path.exists(gt_glb):
- try:
- pg = load_points(gen_glb, a.n_points); pt = load_points(gt_glb, a.n_points)
- if pg is not None and pt is not None:
- best = None
- for k in range(4):
- cd, fs = chamfer_f(rot_y(pg, k), pt)
- if best is None or cd < best[0]: best = (cd, fs)
- r.update(chamfer=best[0], **best[1])
- except Exception as e:
- r["metric_error"] = str(e)[:200]
- rows.append(r)
- with open(os.path.join(a.gen_dir, "metrics.jsonl"), "w") as f:
- for r in rows: f.write(json.dumps(r) + "\n")
- n = len(rows); ok = [r for r in rows if r["exec"] == "OK"]; sc = [r for r in rows if "chamfer" in r]
- # Failed / empty generations get the worst score for the aggregate (chamfer: mean of worst-10 for penalty; f: 0)
- summary = {
- "n_tasks": n, "exec_ok": len(ok), "exec_ok_rate": round(len(ok) / n, 4), "n_scored": len(sc),
- "chamfer_mean_scored": round(float(np.mean([r["chamfer"] for r in sc])), 4) if sc else None,
- "chamfer_median_scored": round(float(np.median([r["chamfer"] for r in sc])), 4) if sc else None,
- "[email protected]_mean_scored": round(float(np.mean([r["[email protected]"] for r in sc])), 4) if sc else None,
- "[email protected]_mean_scored": round(float(np.mean([r["[email protected]"] for r in sc])), 4) if sc else None,
- "[email protected]_mean_all(fail=0)": round(float(sum(r.get("[email protected]", 0) for r in rows) / n), 4),
- "[email protected]_mean_all(fail=0)": round(float(sum(r.get("[email protected]", 0) for r in rows) / n), 4),
- }
- json.dump(summary, open(os.path.join(a.gen_dir, "summary.json"), "w"), indent=2)
- print(json.dumps(summary, indent=2))
-
-if __name__ == "__main__":
- main()
diff --git a/finetune/eval/pass_at_n.py b/finetune/eval/pass_at_n.py
deleted file mode 100644
index fde16843..00000000
--- a/finetune/eval/pass_at_n.py
+++ /dev/null
@@ -1,10 +0,0 @@
-import json, sys
-pfx, n = sys.argv[1], int(sys.argv[2])
-ok = {}; best = {}
-for i in range(1, n + 1):
- for l in open(f"/wekafs/ict/hx_624/llm-ft/eval/out/{pfx}_s{i}/metrics.jsonl"):
- r = json.loads(l); t = r["task"]
- ok.setdefault(t, 0); ok[t] += r["exec"] == "OK"
- if "[email protected]" in r: best[t] = max(best.get(t, 0), r["[email protected]"])
-T = len(ok)
-print(f"pass@1 (avg over samples): {sum(ok.values())/(n*T):.3f} | pass@{n} (any sample OK): {sum(v>0 for v in ok.values())/T:.3f} | best-of-{n} [email protected] (all, fail=0): {sum(best.values())/T:.3f}")
diff --git a/finetune/eval/reextract.py b/finetune/eval/reextract.py
deleted file mode 100644
index 1fdb3789..00000000
--- a/finetune/eval/reextract.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""Re-extract code.py from raw.txt in a generation dir (after extractor fixes)."""
-import sys, os, glob
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
-from generate import extract_code
-for d in sys.argv[1:]:
- n=0
- for raw in glob.glob(os.path.join(d, "*", "raw.txt")):
- code = extract_code(open(raw).read()); open(os.path.join(os.path.dirname(raw), "code.py"), "w").write(code + "\n"); n+=1
- print(d, "re-extracted", n)
diff --git a/finetune/eval/render_glb.py b/finetune/eval/render_glb.py
deleted file mode 100644
index 21fc6e21..00000000
--- a/finetune/eval/render_glb.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""Blender headless: render a GLB to PNG with an auto-framed 3/4 camera (workbench, solid shading).
-usage: blender -b --factory-startup -noaudio --python eval/render_glb.py -- --glb in.glb --out out.png [--size 320]"""
-import bpy, sys, math, argparse
-from mathutils import Vector
-argv = sys.argv[sys.argv.index("--")+1:] if "--" in sys.argv else []
-ap = argparse.ArgumentParser(); ap.add_argument("--glb"); ap.add_argument("--out"); ap.add_argument("--size", type=int, default=320); a = ap.parse_args(argv)
-bpy.ops.wm.read_factory_settings(use_empty=True)
-bpy.ops.import_scene.gltf(filepath=a.glb)
-meshes = [o for o in bpy.context.scene.objects if o.type == "MESH"]
-if not meshes: raise SystemExit("no mesh")
-# bounds
-pts = [o.matrix_world @ Vector(c) for o in meshes for c in o.bound_box]
-mn = Vector((min(p.x for p in pts), min(p.y for p in pts), min(p.z for p in pts))); mx = Vector((max(p.x for p in pts), max(p.y for p in pts), max(p.z for p in pts)))
-center = (mn + mx) / 2; radius = max((mx - mn).length / 2, 1e-3)
-cam_data = bpy.data.cameras.new("cam"); cam = bpy.data.objects.new("cam", cam_data); bpy.context.scene.collection.objects.link(cam)
-direction = Vector((1.0, -1.2, 0.8)).normalized(); cam.location = center + direction * radius * 2.6
-cam.rotation_euler = (center - cam.location).to_track_quat("-Z", "Y").to_euler(); cam_data.lens = 40; cam_data.clip_end = radius * 100
-bpy.context.scene.camera = cam
-sc = bpy.context.scene; sc.render.engine = "CYCLES"; sc.cycles.device = "CPU"; sc.cycles.samples = 32; sc.cycles.use_denoising = False
-sc.render.resolution_x = a.size; sc.render.resolution_y = a.size; sc.render.film_transparent = False
-w = bpy.data.worlds.new("w"); w.use_nodes = True; bg = w.node_tree.nodes["Background"]; bg.inputs[0].default_value = (0.92, 0.92, 0.92, 1); bg.inputs[1].default_value = 1.0; sc.world = w
-sun_d = bpy.data.lights.new("sun", "SUN"); sun_d.energy = 3.0; sun = bpy.data.objects.new("sun", sun_d); sc.collection.objects.link(sun)
-sun.rotation_euler = (math.radians(45), math.radians(20), math.radians(30))
-import random; random.seed(0)
-for o in meshes:
- mat = bpy.data.materials.new(f"m_{o.name}"); mat.use_nodes = True; bsdf = mat.node_tree.nodes.get("Principled BSDF")
- if bsdf: bsdf.inputs["Base Color"].default_value = (random.uniform(0.25, 0.85), random.uniform(0.25, 0.85), random.uniform(0.25, 0.85), 1); bsdf.inputs["Roughness"].default_value = 0.6
- o.data.materials.clear(); o.data.materials.append(mat)
-sc.render.filepath = a.out; bpy.ops.render.render(write_still=True)
diff --git a/finetune/eval/results_all.py b/finetune/eval/results_all.py
deleted file mode 100644
index dcbab515..00000000
--- a/finetune/eval/results_all.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""Aggregate every suite of one eval_all run (or compare several runs) into a table.
-
- python eval/results_all.py <name> [<name2> ...] -> markdown table + eval/out/<name>_report.json
-"""
-import json
-import os
-import sys
-
-SUITES = [("bench", "3DCodeBench (212)"), ("blender", "Blender held-out (103)"), ("cadquery", "CadQuery (200)"),
- ("openscad", "OpenSCAD (50)"), ("glsl", "GLSL (200)"), ("threejs", "three.js (40)")]
-ROOT = "/wekafs/ict/hx_624/llm-ft/eval/out"
-
-
-def suite_row(name, suite):
- d = os.path.join(ROOT, f"{name}_{suite}")
- s_path, x_path = os.path.join(d, "summary.json"), os.path.join(d, "extract_stats.json")
- if not os.path.exists(s_path):
- return None
- s = json.load(open(s_path))
- x = json.load(open(x_path)) if os.path.exists(x_path) else {}
- if suite == "bench":
- rate, f05, f01 = s.get("exec_ok_rate"), s.get("[email protected]_mean_all(fail=0)"), s.get("[email protected]_mean_scored")
- n_ok, n = s.get("exec_ok"), s.get("n_tasks")
- elif suite == "threejs":
- rate, f05, f01 = s.get("exec_rate"), None, None
- n_ok, n = s.get("exec_ok"), s.get("n")
- else:
- rate, f05, f01 = s.get("gen_exec_rate"), s.get("[email protected]_mean_all"), s.get("[email protected]_mean_scored")
- n_ok, n = s.get("gen_exec_ok"), s.get("n")
- return {"suite": suite, "n": n, "exec_ok": n_ok, "exec_rate": rate, "[email protected]_all": f05, "[email protected]_scored": f01,
- "mean_new_tokens": x.get("mean_new_tokens"), "with_think": x.get("with_think"), "no_fence": x.get("no_fence"),
- "multi_block": x.get("multi_block"), "chosen_not_last": x.get("chosen_not_last"),
- "syntax_valid": x.get("syntax_valid"), "no_dialect_marker": x.get("no_dialect_marker"),
- "from_think_fallback": x.get("from_think_fallback")}
-
-
-def main(names):
- print("| model | suite | exec | rate | [email protected](all) | [email protected](ok) | out tok | think | no-fence | multi-blk | not-last | no-marker |")
- print("|---|---|---|---|---|---|---|---|---|---|---|---|")
- for name in names:
- rows = []
- for suite, _label in SUITES:
- r = suite_row(name, suite)
- if not r:
- continue
- rows.append(r)
- pct = f"{100*r['exec_rate']:.1f}%" if r["exec_rate"] is not None else "–"
- f05 = f"{r['[email protected]_all']:.3f}" if r["[email protected]_all"] is not None else "–"
- f01 = f"{r['[email protected]_scored']:.3f}" if r["[email protected]_scored"] is not None else "–"
- print(f"| {name} | {suite} | {r['exec_ok']}/{r['n']} | {pct} | {f05} | {f01} | "
- f"{r['mean_new_tokens'] or '–'} | {r['with_think'] if r['with_think'] is not None else '–'} | "
- f"{r['no_fence'] if r['no_fence'] is not None else '–'} | {r['multi_block'] if r['multi_block'] is not None else '–'} | "
- f"{r['chosen_not_last'] if r['chosen_not_last'] is not None else '–'} | {r['no_dialect_marker'] if r['no_dialect_marker'] is not None else '–'} |")
- if rows:
- json.dump({"name": name, "suites": rows}, open(os.path.join(ROOT, f"{name}_report.json"), "w"), indent=2)
-
-
-if __name__ == "__main__":
- main(sys.argv[1:] or ["md_xl"])
diff --git a/finetune/eval/results_table.py b/finetune/eval/results_table.py
deleted file mode 100644
index db0d0176..00000000
--- a/finetune/eval/results_table.py
+++ /dev/null
@@ -1,20 +0,0 @@
-"""Collect all eval/out/*/summary.json + training stats into a single JSON (for the final report)."""
-import glob, json, os
-OUT = "/wekafs/ict/hx_624/llm-ft/eval/out"; RUNS = "/wekafs/ict/hx_624/llm-ft/runs"
-rows = []
-for d in sorted(glob.glob(f"{OUT}/*/")):
- name = os.path.basename(d.rstrip("/"))
- if name.startswith("_"): continue
- sp = os.path.join(d, "summary.json")
- if not os.path.exists(sp): continue
- s = json.load(open(sp))
- gens = [json.loads(l) for f in glob.glob(os.path.join(d, "gens_shard*.jsonl")) for l in open(f)]
- avg_tok = sum(g["n_new_tokens"] for g in gens) / max(len(gens), 1)
- run = name.replace("qwen35_9b_lora_", "lf_qwen35_9b_lora_").replace("qwen35_9b_full_v1", "lf_qwen35_9b_full_v1")
- tr = {}
- trp = os.path.join(RUNS, run.split("_ckpt")[0], "train_results.json")
- if os.path.exists(trp): tr = json.load(open(trp))
- rows.append(dict(name=name, exec_ok=s["exec_ok"], exec_rate=s["exec_ok_rate"], cd=s["chamfer_mean_scored"], f05=s["[email protected]_mean_scored"], f10=s["[email protected]_mean_scored"],
- f05_all=s["[email protected]_mean_all(fail=0)"], f10_all=s["[email protected]_mean_all(fail=0)"], avg_tok=round(avg_tok), train_loss=tr.get("train_loss"), train_min=(tr.get("train_runtime") or 0) / 60))
-json.dump(rows, open("/wekafs/ict/hx_624/llm-ft/eval/all_results.json", "w"), indent=1)
-for r in rows: print(f"{r['name']:36s} exec={r['exec_ok']:3d} ({r['exec_rate']*100:4.1f}%) CD={r['cd'] if r['cd'] is None else round(r['cd'],3)} F05={r['f05'] if r['f05'] is None else round(r['f05'],3)} F05all={round(r['f05_all'],3)} tok={r['avg_tok']} loss={r['train_loss'] if r['train_loss'] is None else round(r['train_loss'],3)} {r['train_min']:.0f}min")
diff --git a/finetune/eval/run_bench.py b/finetune/eval/run_bench.py
deleted file mode 100644
index ad02c77a..00000000
--- a/finetune/eval/run_bench.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""Execute every <gen_dir>/<task>/code.py in headless Blender (parallel), export GLB, collect reports -> <gen_dir>/exec_results.jsonl"""
-import argparse, json, os, subprocess, sys, time
-from concurrent.futures import ThreadPoolExecutor, as_completed
-BLENDER = "/wekafs/ict/hx_624/tools/blender-5.0.1-linux-x64/blender"
-RUNNER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "blender_runner.py")
-
-def run_one(task_dir, timeout):
- task = os.path.basename(task_dir)
- script = os.path.join(task_dir, "code.py"); glb = os.path.join(task_dir, "out.glb"); rep = os.path.join(task_dir, "exec.json")
- if os.path.exists(glb): os.remove(glb)
- cmd = [BLENDER, "-b", "--factory-startup", "-noaudio", "--python", RUNNER, "--", "--script", script, "--out", glb, "--report", rep]
- t0 = time.time()
- try:
- p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, text=True, errors="replace",
- env={**os.environ, "HOME": "/tmp", "XDG_CONFIG_HOME": "/tmp/.bcfg"})
- if os.path.exists(rep):
- r = json.load(open(rep))
- else:
- r = {"status": "CRASH", "error": p.stdout[-1500:], "latency_s": round(time.time() - t0, 1)}
- except subprocess.TimeoutExpired:
- r = {"status": "TIMEOUT", "error": f"timeout {timeout}s", "latency_s": timeout}
- r["task"] = task
- return r
-
-def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--gen_dir", required=True)
- ap.add_argument("--workers", type=int, default=16)
- ap.add_argument("--timeout", type=int, default=300)
- a = ap.parse_args()
- a.gen_dir = os.path.abspath(a.gen_dir) # the Blender runner chdir()s into the script dir -> all paths must be absolute
- tasks = sorted(d for d in os.listdir(a.gen_dir) if os.path.isfile(os.path.join(a.gen_dir, d, "code.py")))
- print(f"[exec] {len(tasks)} scripts, {a.workers} workers", flush=True)
- res = []
- with ThreadPoolExecutor(a.workers) as ex:
- futs = {ex.submit(run_one, os.path.join(a.gen_dir, t), a.timeout): t for t in tasks}
- for i, fu in enumerate(as_completed(futs)):
- r = fu.result(); res.append(r)
- if (i + 1) % 20 == 0: print(f"[exec] {i+1}/{len(tasks)}", flush=True)
- res.sort(key=lambda r: r["task"])
- with open(os.path.join(a.gen_dir, "exec_results.jsonl"), "w") as f:
- for r in res: f.write(json.dumps(r) + "\n")
- from collections import Counter
- c = Counter(r["status"] for r in res)
- print("[exec] status counts:", dict(c), f"| OK rate = {c.get('OK',0)}/{len(res)} = {100*c.get('OK',0)/max(len(res),1):.1f}%")
-
-if __name__ == "__main__":
- main()
diff --git a/finetune/eval/run_dialect_eval.sh b/finetune/eval/run_dialect_eval.sh
deleted file mode 100755
index 99df059e..00000000
--- a/finetune/eval/run_dialect_eval.sh
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/bash
-# usage: GPUS=2 eval/run_dialect_eval.sh <model_dir> <name> [dialects...] -> eval/out/md_<name>_<dialect>/summary.json
-set -uo pipefail; MODEL=$(readlink -f "$1"); NAME=$2; shift 2; DIALECTS=${@:-cadquery openscad glsl blender}
-cd /wekafs/ict/hx_624/llm-ft; source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate vllm
-export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING CUDA_VISIBLE_DEVICES=${GPUS:-0}
-for D in $DIALECTS; do
- OUT=eval/out/md_${NAME}_$D; mkdir -p $OUT
- python - "$D" "$OUT" <<PY
-import json,sys
-D,OUT=sys.argv[1],sys.argv[2]
-with open(f"{OUT}/prompts.jsonl","w") as f:
- for l in open(f"data/multidialect/{D}/test.jsonl"):
- r=json.loads(l); f.write(json.dumps({"task": r["id"].replace("/","__"), "messages": r["messages"][:2]})+"\n")
-PY
- python eval/generate_vllm.py --model $MODEL --prompts $OUT/prompts.jsonl --out $OUT --tp 1 --no_think --max_new_tokens 8192 2>&1 | grep -E "gen-vllm|Error" | tail -2
-done
-conda activate llmft
-for D in $DIALECTS; do
- OUT=eval/out/md_${NAME}_$D
- if [ "$D" = "blender" ]; then
- # blender held-out test: run in Blender and compare to reference via the same exec harness (reference meshes cached)
- python eval/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -2
- else
- python eval/dialect_eval.py --dialect $D --test data/multidialect/$D/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -2
- fi
-done
-echo "[md-eval $NAME] DONE"
diff --git a/finetune/eval/run_eval.sh b/finetune/eval/run_eval.sh
deleted file mode 100755
index 2834a350..00000000
--- a/finetune/eval/run_eval.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/bash
-# End-to-end 3DCodeBench eval: generate (sharded over GPUS) -> execute in Blender -> geometry metrics
-# usage: GPUS=0,1 ./run_eval.sh <model_path> <out_dir> [extra generate.py args]
-set -euo pipefail
-source /wekafs/ict/hx_624/llm-ft/env.sh
-MODEL=$(readlink -f "$1"); OUT=$(readlink -m "$2"); shift 2
-GPUS=${GPUS:-0}
-PROMPTS=/wekafs/ict/hx_624/llm-ft/data/sft_v1/bench_prompts.jsonl
-[ -f $PROMPTS ] || PROMPTS=/wekafs/ict/hx_624/llm-ft/data/sft_v0/bench_prompts.jsonl
-mkdir -p $OUT
-IFS=',' read -ra G <<< "$GPUS"; N=${#G[@]}
-echo "[eval] model=$MODEL out=$OUT gpus=$GPUS shards=$N"
-pids=()
-for i in "${!G[@]}"; do
- CUDA_VISIBLE_DEVICES=${G[$i]} python /wekafs/ict/hx_624/llm-ft/eval/generate.py --model $MODEL --prompts $PROMPTS --out $OUT --shard $i --num_shards $N "$@" > $OUT/gen_shard$i.log 2>&1 &
- pids+=($!)
-done
-for p in "${pids[@]}"; do wait $p; done
-cat $OUT/gens_shard*.jsonl > $OUT/gens.jsonl
-echo "[eval] generation done: $(wc -l < $OUT/gens.jsonl) samples"
-python /wekafs/ict/hx_624/llm-ft/eval/run_bench.py --gen_dir $OUT --workers ${WORKERS:-32} --timeout ${TIMEOUT:-300} 2>&1 | tee $OUT/exec.log
-python /wekafs/ict/hx_624/llm-ft/eval/metrics.py --gen_dir $OUT 2>&1 | tee $OUT/metrics.log
diff --git a/finetune/eval/run_eval_vllm.sh b/finetune/eval/run_eval_vllm.sh
deleted file mode 100755
index 524ddc90..00000000
--- a/finetune/eval/run_eval_vllm.sh
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/bin/bash
-# usage: GPUS=0 ./run_eval_vllm.sh <model_path> <out_dir> [extra generate_vllm.py args] (TP = number of GPUs listed)
-set -euo pipefail
-source /wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh; conda activate vllm
-source /wekafs/ict/hx_624/.secrets/hf.env; export VLLM_CACHE_ROOT=/wekafs/ict/hx_624/cache/vllm HF_HOME=/wekafs/ict/hx_624/cache/huggingface VLLM_LOGGING_LEVEL=WARNING TOKENIZERS_PARALLELISM=false
-MODEL=$(readlink -f "$1"); OUT=$(readlink -m "$2"); shift 2
-export CUDA_VISIBLE_DEVICES=${GPUS:-0}; TP=$(echo $CUDA_VISIBLE_DEVICES | tr ',' '\n' | wc -l)
-PROMPTS=${PROMPTS:-/wekafs/ict/hx_624/llm-ft/data/sft_v1/bench_prompts.jsonl}
-mkdir -p $OUT; echo "[eval-vllm] model=$MODEL out=$OUT gpus=$CUDA_VISIBLE_DEVICES tp=$TP"
-python /wekafs/ict/hx_624/llm-ft/eval/generate_vllm.py --model $MODEL --prompts $PROMPTS --out $OUT --tp $TP "$@" 2>&1 | grep -vE "^\s*$" | tail -n 40
-cp $OUT/gens_shard0.jsonl $OUT/gens.jsonl
-conda activate llmft
-python /wekafs/ict/hx_624/llm-ft/eval/run_bench.py --gen_dir $OUT --workers ${WORKERS:-32} --timeout ${TIMEOUT:-300} 2>&1 | tee $OUT/exec.log
-python /wekafs/ict/hx_624/llm-ft/eval/metrics.py --gen_dir $OUT 2>&1 | tee $OUT/metrics.log
diff --git a/finetune/eval/threejs_eval.py b/finetune/eval/threejs_eval.py
deleted file mode 100644
index ab969ad3..00000000
--- a/finetune/eval/threejs_eval.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""Run every <gen_dir>/<task>/code.py (HTML) through the headless-browser runner (parallel) and summarise."""
-import argparse, json, os, sys
-from concurrent.futures import ThreadPoolExecutor
-sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))); from threejs_runner import run_threejs
-ap = argparse.ArgumentParser(); ap.add_argument("--gen_dir", required=True); ap.add_argument("--workers", type=int, default=8); a = ap.parse_args()
-tasks = sorted(d for d in os.listdir(a.gen_dir) if os.path.isfile(os.path.join(a.gen_dir, d, "code.py")))
-def job(t):
- html = open(os.path.join(a.gen_dir, t, "code.py")).read()
- r = run_threejs(html, os.path.join(a.gen_dir, t, "exec")); r["task"] = t; r.pop("shot", None); return r
-with ThreadPoolExecutor(a.workers) as ex: res = list(ex.map(job, tasks))
-from collections import Counter
-c = Counter(r["status"] for r in res)
-with open(os.path.join(a.gen_dir, "threejs_results.jsonl"), "w") as f:
- for r in res: f.write(json.dumps(r) + "\n")
-summ = {"dialect": "threejs", "n": len(res), "exec_ok": c.get("OK", 0), "exec_rate": round(c.get("OK", 0) / max(1, len(res)), 4), "counts": dict(c)}
-json.dump(summ, open(os.path.join(a.gen_dir, "summary.json"), "w"), indent=2); print(json.dumps(summ))
-print("failure modes:", Counter((r["error"] or r["status"])[:80] for r in res if r["status"] != "OK").most_common(6))
diff --git a/finetune/eval/threejs_runner.py b/finetune/eval/threejs_runner.py
deleted file mode 100644
index c44f6a36..00000000
--- a/finetune/eval/threejs_runner.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""Headless-Chromium executor for single-file three.js HTML (Playwright). Returns dict(status, error, console_errors, canvas_nonblank, latency_s, shot).
-status OK = page loaded, no uncaught JS error / failed module import, a <canvas> exists and its rendered pixels are not (nearly) uniform."""
-import os, sys, json, time, base64, io
-def run_threejs(html, workdir, timeout=40, settle_ms=4000):
- os.environ.setdefault("PLAYWRIGHT_BROWSERS_PATH", "/wekafs/ict/hx_624/cache/ms-playwright")
- workdir = os.path.abspath(workdir); os.makedirs(workdir, exist_ok=True)
- hp = os.path.join(workdir, "index.html"); open(hp, "w").write(html)
- rep = {"status": "FAIL", "error": None, "console_errors": [], "canvas_nonblank": None, "latency_s": 0, "shot": None}
- t0 = time.time()
- try:
- from playwright.sync_api import sync_playwright
- with sync_playwright() as p:
- browser = p.chromium.launch(headless=True, args=["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist", "--no-sandbox", "--disable-dev-shm-usage"])
- page = browser.new_page(viewport={"width": 640, "height": 480})
- errs = []
- page.on("pageerror", lambda e: errs.append("pageerror: " + str(e)[:300]))
- page.on("console", lambda m: errs.append("console.error: " + m.text[:300]) if m.type == "error" else None)
- page.on("requestfailed", lambda r: errs.append("requestfailed: " + r.url[:200]))
- page.goto("file://" + hp, wait_until="load", timeout=timeout * 1000)
- page.wait_for_timeout(settle_ms)
- # canvas check: count distinct pixels over a downsampled grid
- info = page.evaluate("""() => {
- const cs = document.querySelectorAll('canvas'); if (!cs.length) return {n:0};
- const c = cs[0]; const w=c.width, h=c.height; if (!w||!h) return {n:cs.length, w, h, distinct:0};
- let gl = c.getContext('webgl2') || c.getContext('webgl');
- let pix = null;
- if (gl) { pix = new Uint8Array(w*h*4); try { gl.readPixels(0,0,w,h,gl.RGBA,gl.UNSIGNED_BYTE,pix); } catch(e) { pix=null; } }
- if (!pix) { try { const t=document.createElement('canvas'); t.width=w; t.height=h; const ctx=t.getContext('2d'); ctx.drawImage(c,0,0); pix=ctx.getImageData(0,0,w,h).data; } catch(e) { return {n:cs.length, w, h, distinct:-1, err:String(e)}; } }
- const seen = new Set(); const step = Math.max(1, Math.floor((w*h)/4000));
- for (let i=0;i<w*h;i+=step){ const o=i*4; seen.add((pix[o]>>3)+','+(pix[o+1]>>3)+','+(pix[o+2]>>3)); if (seen.size>64) break; }
- return {n:cs.length, w, h, distinct:seen.size};
- }""")
- shot = os.path.join(workdir, "shot.png"); page.screenshot(path=shot); rep["shot"] = shot
- browser.close()
- rep["console_errors"] = errs[:10]
- fatal = [e for e in errs if e.startswith("pageerror") or "Failed to resolve module" in e or "Uncaught" in e or e.startswith("requestfailed")]
- # blank check from the composited screenshot (the WebGL drawing buffer is cleared after compositing, so in-page readPixels is unreliable)
- try:
- from PIL import Image; import numpy as np
- im = np.array(Image.open(shot).convert("RGB")); q = (im[::6, ::6].reshape(-1, 3) // 16)
- distinct = len(set(map(tuple, q))); rep["shot_distinct"] = distinct; rep["shot_std"] = float(im.std())
- nonblank = distinct > 6 and float(im.std()) > 4.0
- except Exception as e:
- nonblank = info.get("distinct", 0) > 3
- rep["canvas_nonblank"] = bool(info.get("n", 0)) and nonblank
- if fatal: rep["status"] = "FAIL"; rep["error"] = fatal[0]
- elif not info.get("n"): rep["status"] = "EMPTY"; rep["error"] = "no <canvas>"
- elif not rep["canvas_nonblank"]: rep["status"] = "EMPTY"; rep["error"] = f"blank canvas (shot distinct={rep.get('shot_distinct')})"
- else: rep["status"] = "OK"
- except Exception as e:
- rep["error"] = (type(e).__name__ + ": " + str(e))[:400]
- if "Timeout" in rep["error"]: rep["status"] = "TIMEOUT"
- rep["latency_s"] = round(time.time() - t0, 1)
- return rep
-if __name__ == "__main__":
- print(json.dumps(run_threejs(open(sys.argv[1]).read(), sys.argv[2]), indent=1))
diff --git a/finetune/scripts/sync_repo.sh b/finetune/scripts/sync_repo.sh
index 421440b5..8f3f5a67 100755
--- a/finetune/scripts/sync_repo.sh
+++ b/finetune/scripts/sync_repo.sh
@@ -22,6 +22,7 @@ rsync -a --delete --exclude '__pycache__' --exclude '*.pyc' "$SRC/scripts/" "$DS
# --delete on configs too: without it a config retired into configs/lf/archive/ was copied to its new
# location but the old copy lingered in the repo forever, so a tidy-up never actually reached GitHub.
rsync -a --delete --exclude '__pycache__' "$SRC/configs/" "$DST/configs/"
+rm -rf "$DST/eval" # superseded by 3dcodeverse_eval/; without this the old copy lingers forever
# The evaluation stack is managed as a self-contained folder under LLaMA-Factory now; llm-ft/eval keeps the
# working generations (out/) and is no longer what the repo mirrors.
rsync -a --delete --exclude '__pycache__' --exclude '*.pyc' \