Skip to content

Official Codebase of 3DCodeVerse

Python

finetune: sync scripts, configs, eval stack and docs

gaoypeng51b2737e4b4c
diff --git a/finetune/3dcodeverse_eval/README.md b/finetune/3dcodeverse_eval/README.md
new file mode 100644
index 00000000..1a04fe94
--- /dev/null
+++ b/finetune/3dcodeverse_eval/README.md
@@ -0,0 +1,52 @@
+# 3DCodeVerse evaluation
+
+Scores a model by **executing what it generates**, not by comparing text. A 3D program either runs and
+produces the geometry or it does not, so every number here is a pass rate from a real interpreter.
+
+```bash
+source env.sh # optional on this box; all vars already default to these values
+GPUS=0 TP=1 ./run_eval.sh /path/to/model my_run
+GPUS=0 TP=1 ./run_eval.sh /path/to/model my_run --temp 0.7 --seed 1 # sampled decoding
+GPUS=0 TP=1 ./run_eval.sh /path/to/model my_run --suites blender threejs
+```
+
+Results: `$EVAL_OUT/<name>_<suite>/summary.json`, aggregated into `$EVAL_OUT/<name>_report.json`.
+
+## Suites
+
+| suite | what runs the code | pass = |
+|---|---|---|
+| `bench` | Blender 5.0.1 (+scipy) | script executes **and** geometry matches ground truth |
+| `blender` | Blender 5.0.1 | script executes, scene is non-empty |
+| `cadquery` | CadQuery | solid builds and exports |
+| `openscad` | OpenSCAD CLI | compiles to a non-empty mesh |
+| `glsl` | `glslangValidator` | shader compiles |
+| `threejs` | headless Chromium, WebGL2 | page renders without a JS error and draws something |
+
+## Layout
+
+`run_eval.sh` is the only entry point. It generates once with **one vLLM engine for all suites** (loading a
+large model per suite costs more than the generation itself), then executes and scores each suite.
+
+- generation — `generate_multi.py` (all suites, one engine), `generate_vllm.py` (single suite),
+ `generate_vllm_img.py` (image → code), `generate.py` (HF fallback, no vLLM)
+- extraction — `extract.py`, dialect-aware: what counts as the answer differs per dialect
+- execution — `dialect_runners.py`, `blender_runner.py`, `threejs_runner.py`, `glsl_render.py`, `render_glb.py`
+- scoring — `run_bench.py` + `metrics.py` (bench), `dialect_eval.py`, `blender_dialect_eval.py`,
+ `threejs_eval.py`, aggregation in `results_all.py`
+- `free_gpus.sh` — lists cards with enough free memory (the box is shared)
+
+## Two guards that are there for a reason
+
+**It refuses to score an empty generation directory.** An engine that never started leaves no generations,
+and every scorer reports that as 0%. A real 0% and a failed launch then look identical — which is how a
+rescore of two healthy models once came back as 0/200 on every suite.
+
+**It re-checks the GPU right before launching.** On a shared box a card that was free when it was picked can
+be full by the time vLLM starts; the harness switches to whichever card is free now, or waits.
+
+## Reading the numbers
+
+Report long-output dialects under **both** greedy and sampled decoding. A fine-tuned model that scores 6% on
+OpenSCAD greedy and 44% sampled has not forgotten the dialect — it is in a repetition loop and never emits
+the closing token. Preference pairs on termination fix it, and afterwards greedy beats sampling again.
diff --git a/finetune/3dcodeverse_eval/blender_dialect_eval.py b/finetune/3dcodeverse_eval/blender_dialect_eval.py
new file mode 100644
index 00000000..e242a475
--- /dev/null
+++ b/finetune/3dcodeverse_eval/blender_dialect_eval.py
@@ -0,0 +1,44 @@
+"""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 = os.environ.get("BLENDER_BIN", "/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/3dcodeverse_eval/blender_runner.py b/finetune/3dcodeverse_eval/blender_runner.py
new file mode 100644
index 00000000..1da13185
--- /dev/null
+++ b/finetune/3dcodeverse_eval/blender_runner.py
@@ -0,0 +1,72 @@
+"""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/3dcodeverse_eval/dialect_eval.py b/finetune/3dcodeverse_eval/dialect_eval.py
new file mode 100644
index 00000000..92f87a02
--- /dev/null
+++ b/finetune/3dcodeverse_eval/dialect_eval.py
@@ -0,0 +1,43 @@
+"""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/3dcodeverse_eval/dialect_runners.py b/finetune/3dcodeverse_eval/dialect_runners.py
new file mode 100644
index 00000000..cd988489
--- /dev/null
+++ b/finetune/3dcodeverse_eval/dialect_runners.py
@@ -0,0 +1,101 @@
+"""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 = os.environ.get("OPENSCAD_BIN", "/wekafs/ict/hx_624/tools/openscad/squashfs-root/AppRun")
+GLSLANG = os.environ.get("GLSLANG_BIN", "/wekafs/ict/hx_624/anaconda3/envs/llmft/bin/glslangValidator")
+PY = os.environ.get("EVAL_PYTHON", "/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/3dcodeverse_eval/env.sh b/finetune/3dcodeverse_eval/env.sh
new file mode 100644
index 00000000..6f1aad09
--- /dev/null
+++ b/finetune/3dcodeverse_eval/env.sh
@@ -0,0 +1,12 @@
+# Tool locations for 3DCodeVerse evaluation. `source env.sh` before run_eval.sh, or export your own.
+# Every variable already defaults to the value below, so on this box sourcing it is optional.
+export PROJECT_ROOT=${PROJECT_ROOT:-/wekafs/ict/hx_624/llm-ft} # holds data/multidialect, data/sft_v1
+export EVAL_OUT=${EVAL_OUT:-$PROJECT_ROOT/eval/out} # generations + summaries land here
+export BENCH_DATA=${BENCH_DATA:-/wekafs/ict/hx_624/data/3dcodebench/data}
+export BLENDER_BIN=${BLENDER_BIN:-/wekafs/ict/hx_624/tools/blender-5.0.1-linux-x64/blender}
+export OPENSCAD_BIN=${OPENSCAD_BIN:-/wekafs/ict/hx_624/tools/openscad/squashfs-root/AppRun}
+export GLSLANG_BIN=${GLSLANG_BIN:-/wekafs/ict/hx_624/anaconda3/envs/llmft/bin/glslangValidator}
+export EVAL_PYTHON=${EVAL_PYTHON:-/wekafs/ict/hx_624/anaconda3/envs/llmft/bin/python}
+export PLAYWRIGHT_BROWSERS_PATH=${PLAYWRIGHT_BROWSERS_PATH:-/wekafs/ict/hx_624/cache/ms-playwright}
+export VLLM_ENV=${VLLM_ENV:-vllm} # conda env with vLLM (generation)
+export EXEC_ENV=${EXEC_ENV:-llmft} # conda env with the runners (execution + scoring)
diff --git a/finetune/3dcodeverse_eval/extract.py b/finetune/3dcodeverse_eval/extract.py
new file mode 100644
index 00000000..55eaa783
--- /dev/null
+++ b/finetune/3dcodeverse_eval/extract.py
@@ -0,0 +1,220 @@
+"""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/3dcodeverse_eval/free_gpus.sh b/finetune/3dcodeverse_eval/free_gpus.sh
new file mode 100755
index 00000000..b61c9376
--- /dev/null
+++ b/finetune/3dcodeverse_eval/free_gpus.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+# Print the GPUs with at least <need_free_mib> free — other users share this box, so "completely empty" is the
+# wrong test; what matters is whether OUR job fits.
+# scripts/free_gpus.sh [need_free_mib] [gpu_list] default 60000 (a 9B LoRA at cutoff 8192), all GPUs
+# The list used to be hardcoded to 0-3 from when this box exposed four cards, which silently hid 4-7 from every
+# script that auto-selects a GPU.
+NEED=${1:-60000}
+LIST=${2:-$(nvidia-smi --query-gpu=index --format=csv,noheader | tr '\n' ' ')}
+OUT=""
+for i in $LIST; do
+ read -r TOT USED <<< "$(nvidia-smi --query-gpu=memory.total,memory.used --format=csv,noheader,nounits -i $i | tr ',' ' ')"
+ [ -z "${TOT:-}" ] && continue
+ FREE=$((TOT - USED))
+ [ "$FREE" -ge "$NEED" ] && OUT="$OUT,$i"
+done
+echo "${OUT#,}"
diff --git a/finetune/3dcodeverse_eval/generate.py b/finetune/3dcodeverse_eval/generate.py
new file mode 100644
index 00000000..cabaf670
--- /dev/null
+++ b/finetune/3dcodeverse_eval/generate.py
@@ -0,0 +1,81 @@
+"""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/3dcodeverse_eval/generate_multi.py b/finetune/3dcodeverse_eval/generate_multi.py
new file mode 100644
index 00000000..db6f08f8
--- /dev/null
+++ b/finetune/3dcodeverse_eval/generate_multi.py
@@ -0,0 +1,114 @@
+"""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/3dcodeverse_eval/generate_vllm.py b/finetune/3dcodeverse_eval/generate_vllm.py
new file mode 100644
index 00000000..d0593ba9
--- /dev/null
+++ b/finetune/3dcodeverse_eval/generate_vllm.py
@@ -0,0 +1,82 @@
+"""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/3dcodeverse_eval/generate_vllm_img.py b/finetune/3dcodeverse_eval/generate_vllm_img.py
new file mode 100644
index 00000000..123c682b
--- /dev/null
+++ b/finetune/3dcodeverse_eval/generate_vllm_img.py
@@ -0,0 +1,98 @@
+"""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/3dcodeverse_eval/glsl_render.py b/finetune/3dcodeverse_eval/glsl_render.py
new file mode 100644
index 00000000..5061be39
--- /dev/null
+++ b/finetune/3dcodeverse_eval/glsl_render.py
@@ -0,0 +1,119 @@
+"""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/3dcodeverse_eval/metrics.py b/finetune/3dcodeverse_eval/metrics.py
new file mode 100644
index 00000000..c3c9160e
--- /dev/null
+++ b/finetune/3dcodeverse_eval/metrics.py
@@ -0,0 +1,77 @@
+"""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 = os.environ.get("BENCH_DATA", "/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/3dcodeverse_eval/render_glb.py b/finetune/3dcodeverse_eval/render_glb.py
new file mode 100644
index 00000000..21fc6e21
--- /dev/null
+++ b/finetune/3dcodeverse_eval/render_glb.py
@@ -0,0 +1,29 @@
+"""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/3dcodeverse_eval/results_all.py b/finetune/3dcodeverse_eval/results_all.py
new file mode 100644
index 00000000..64a9273e
--- /dev/null
+++ b/finetune/3dcodeverse_eval/results_all.py
@@ -0,0 +1,59 @@
+"""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 = os.environ.get("EVAL_OUT", "/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/3dcodeverse_eval/run_bench.py b/finetune/3dcodeverse_eval/run_bench.py
new file mode 100644
index 00000000..e1409d7a
--- /dev/null
+++ b/finetune/3dcodeverse_eval/run_bench.py
@@ -0,0 +1,49 @@
+"""Execute every <gen_dir>/<task>/code.py in headless Blender (parallel), export GLB, collect reports -> <gen_dir>/exec_results.jsonl"""
+import os
+import argparse, json, os, subprocess, sys, time
+from concurrent.futures import ThreadPoolExecutor, as_completed
+BLENDER = os.environ.get("BLENDER_BIN", "/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/3dcodeverse_eval/run_eval.sh b/finetune/3dcodeverse_eval/run_eval.sh
new file mode 100755
index 00000000..20d315c1
--- /dev/null
+++ b/finetune/3dcodeverse_eval/run_eval.sh
@@ -0,0 +1,112 @@
+#!/bin/bash
+# 3DCodeVerse evaluation: one command scores ANY model by EXECUTING what it generates -- 3DCodeBench
+# (Blender exec + geometry against ground truth) and five held-out dialect sets (CadQuery / OpenSCAD /
+# GLSL / Blender / three.js), with dialect-aware code extraction.
+#
+# GPUS=0 TP=1 ./run_eval.sh <model_dir> <name> [--think] [--temp 0.7] [--seed 1] [--max_new 32768] [--suites ...]
+#
+# --think keep the model's reasoning on (default: enable_thinking=false)
+# --temp/--seed sampling (default greedy). Report long-output dialects under BOTH -- greedy alone
+# understates them badly when a model runs away.
+# --suites subset of: bench cadquery openscad glsl blender threejs (default: all)
+#
+# Paths are env vars so this folder runs on another box: PROJECT_ROOT (holds data/), EVAL_OUT,
+# BLENDER_BIN, OPENSCAD_BIN, GLSLANG_BIN, BENCH_DATA, VLLM_ENV, EXEC_ENV. See env.sh and README.md.
+# results: $EVAL_OUT/<name>_<suite>/summary.json + $EVAL_OUT/<name>_report.json (one row per suite)
+set -uo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="${PROJECT_ROOT:-/wekafs/ict/hx_624/llm-ft}"
+export EVAL_OUT="${EVAL_OUT:-$PROJECT_ROOT/eval/out}"
+VLLM_ENV="${VLLM_ENV:-vllm}"; EXEC_ENV="${EXEC_ENV:-llmft}"
+CONDA_SH="${CONDA_SH:-/wekafs/ict/hx_624/anaconda3/etc/profile.d/conda.sh}"
+mkdir -p "$EVAL_OUT"
+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 "$PROJECT_ROOT"
+source "$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_ENV"
+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"{os.environ['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 = os.environ["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=$("$HERE"/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 "$HERE"/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 "$EXEC_ENV"
+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 "$HERE"/run_bench.py --gen_dir $OUT --workers 32 --timeout 300 2>&1 | grep -E "status counts" | tail -1
+ python "$HERE"/metrics.py --gen_dir $OUT 2>&1 | tail -1;;
+ blender) python "$HERE"/blender_dialect_eval.py --test data/multidialect/blender/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;
+ threejs) python "$HERE"/threejs_eval.py --gen_dir $OUT 2>&1 | tail -2;;
+ *) python "$HERE"/dialect_eval.py --dialect $S --test data/multidialect/$S/test.jsonl --gen_dir $OUT --workers 32 2>&1 | tail -1;;
+ esac
+done
+python "$HERE"/results_all.py $NAME
+echo "[eval_all] DONE $NAME"
diff --git a/finetune/3dcodeverse_eval/threejs_eval.py b/finetune/3dcodeverse_eval/threejs_eval.py
new file mode 100644
index 00000000..ab969ad3
--- /dev/null
+++ b/finetune/3dcodeverse_eval/threejs_eval.py
@@ -0,0 +1,17 @@
+"""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/3dcodeverse_eval/threejs_runner.py b/finetune/3dcodeverse_eval/threejs_runner.py
new file mode 100644
index 00000000..c44f6a36
--- /dev/null
+++ b/finetune/3dcodeverse_eval/threejs_runner.py
@@ -0,0 +1,56 @@
+"""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 f6f6e130..421440b5 100755
--- a/finetune/scripts/sync_repo.sh
+++ b/finetune/scripts/sync_repo.sh
@@ -22,7 +22,10 @@ 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/"
-rsync -a --delete --exclude '__pycache__' --exclude 'out' --exclude '_test' --exclude 'ref_oracle' --exclude '*.pyc' "$SRC/eval/" "$DST/eval/"
+# 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' \
+ /wekafs/ict/hx_624/tools/LLaMA-Factory/3dcodeverse_eval/ "$DST/3dcodeverse_eval/"
cp "$SRC/env.sh" "$DST/env.sh"
cp "$SRC/REPORT.md" "$DST/docs/REPORT.md"
cp "$SRC/README.md" "$DST/docs/PROJECT_README.md" 2>/dev/null || true
diff --git a/finetune/scripts/train_when_free.sh b/finetune/scripts/train_when_free.sh
index a2ad2723..d3860854 100755
--- a/finetune/scripts/train_when_free.sh
+++ b/finetune/scripts/train_when_free.sh
@@ -5,8 +5,9 @@
# scripts/train_when_free.sh <config.yaml> [need_free_mib] [logfile]
set -u
CFG=$1; NEED=${2:-60000}; LOG=${3:-logs/$(basename "${CFG%.yaml}").log}
+ONLY=${GPU_LIST:-} # optional: restrict to these cards, e.g. GPU_LIST=6,7
for attempt in $(seq 1 200); do
- G=$(scripts/free_gpus.sh "$NEED" | cut -d, -f1)
+ G=$(scripts/free_gpus.sh "$NEED" ${ONLY:+"$ONLY"} | cut -d, -f1)
if [ -n "$G" ]; then
sleep 45 # let any competing job finish allocating
STILL=$(scripts/free_gpus.sh "$NEED" "$G" | cut -d, -f1) # ...and confirm the card is still free