astra-cadfem-failures / scripts /astra_batch.py
Conditiondark's picture
Astra CAD+FEM failures v0.1: 51 cases from CADFEM-Bench v1.9 (part 3)
6d52e65 verified
Raw History Blame Contribute Delete
14.2 kB
"""Astra on the buckle-trap tasks through the OpenAI Batch API (half price), then local sandbox replay and scoring.
The request text is built exactly as in scripts/astra_v18_trial.py (same system prompt, runtime line and inlined
faces.json), with medium reasoning and one code-generation call per task; nothing about the solver issue is said.
Subcommands:
prepare --tasks ID,ID,.. --run NAME write batch.jsonl and a cost reservation in the OpenAI ledger
submit --run NAME upload and create the batch (no automatic retries)
collect --run NAME download outputs, store submission/main.py and usage per task
replay --run NAME [--workers 3] sandbox replay + score.py per task (local, no API)
summary --run NAME pass/fail table with the trap classification
"""
import argparse, hashlib, json, math, os, re, shutil, subprocess, sys, urllib.request, uuid
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] # cvpr2027
PKG = Path(os.environ.get('CADFEM_BUCKLE_PACKAGE',str(ROOT / "output/datasets/astra-buckle-traps-v0.1"))).resolve()
PY = ROOT / "tmp/cq-env/bin/python"
LEDGER = ROOT / "output/datasets/cadfem-challenge-trials/astra-openai-svgnew-20261027.json"
SYSTEM = ("Solve the CAD+FEM task. Return only a complete runnable Python main.py, no markdown. Never fabricate geometry, fields, "
"convergence or reference results. Your code will execute locally. Do not use recalled published results.")
CAP = int(os.environ.get("ASTRA_CAP", "12000"))
PRICE = {"input": 10.0 / 2, "cached": 1.0 / 2, "output": 50.0 / 2} # USD per million tokens, batch discount
def key():
return next(l.split("=", 1)[1].strip().strip("\"'") for l in (ROOT.parent / ".env.svg_new").read_text().splitlines()
if l.strip().startswith("OPENAI_API_KEY_SVG_NEW="))
def api(path, data=None, ctype="application/json"):
req = urllib.request.Request("https://api.openai.com/v1" + path, data=data,
headers={"Authorization": "Bearer " + key(), **({"Content-Type": ctype} if data else {})})
with urllib.request.urlopen(req, timeout=120) as r:
return r.read()
def task_text(task):
text = task["prompt"] + ("\nRUNTIME: Python cadquery (OCP), gmsh, numpy/scipy, meshio, skfem, and ccx (CalculiX 2.23). No FreeCAD or ANSYS. "
"Read inputs from CADFEM_INPUT_DIR; write into CADFEM_OUTPUT_DIR. No network/evaluator access. Available inputs: "
+ json.dumps([Path(x["path"]).name for x in task["inputs"]]) +
". 600 seconds, 2 CPU threads, 6000 MB RAM. Use feasible meshes, record honest refinement. main.py is preserved by "
"evaluator. Request all required fields and retain solver logs. Do not hardcode target answers. Use supplied source "
"drawing images for reconstruction, not hidden source CAD.")
for f in task["inputs"]:
p = PKG / "candidate" / f["path"]
if p.suffix in (".json", ".csv", ".fee") and len(p.read_text()) < 12000:
text += "\nINPUT " + p.name + ":\n" + p.read_text()
return text
def task_images(task):
"""Source figures as data URLs, prepared as in astra_v18_trial.py (RGB, longest side 1800 px)."""
import base64, io
from PIL import Image
out = []
for f in task["inputs"]:
p = PKG / "candidate" / f["path"]
if p.suffix.lower() in (".png", ".jpg", ".jpeg"):
im = Image.open(p).convert("RGB"); im.thumbnail((1800, 1800)); buf = io.BytesIO(); im.save(buf, "PNG")
out.append("data:image/png;base64," + base64.b64encode(buf.getvalue()).decode())
return out
def run_dir(name):
return ROOT / "runs" / name
def prepare(a):
tasks = {t["task_id"]: t for t in map(json.loads, (PKG / "candidate/tasks.jsonl").read_text().splitlines())}
ids = a.tasks.split(",")
if len(ids)!=len(set(ids)) or any(tasks[t].get('status')!='active' for t in ids):
raise ValueError('Only unique, admitted active tasks may be dispatched')
rd = run_dir(a.run); rd.mkdir(parents=True, exist_ok=False)
lines, bound = [], 0
for tid in ids:
for item in tasks[tid]['inputs']:
if hashlib.sha256((PKG/'candidate'/item['path']).read_bytes()).hexdigest()!=item['sha256']:
raise ValueError('Input checksum mismatch')
text = task_text(tasks[tid]); imgs = task_images(tasks[tid]); bound += len((SYSTEM + text).encode()) + 512 + 3000 * len(imgs)
content = text if not imgs else [{"type": "text", "text": text}] + [{"type": "image_url", "image_url": {"url": u, "detail": "high"}} for u in imgs]
lines.append(json.dumps({"custom_id": tid, "method": "POST", "url": "/v1/chat/completions",
"body": {"model": "gpt-6-astra", "messages": [{"role": "system", "content": SYSTEM}, {"role": "user", "content": content}],
"reasoning_effort": "medium", "max_completion_tokens": CAP, "store": False}}))
(rd / "batch.jsonl").write_text("\n".join(lines) + "\n")
reservation = bound * PRICE["input"] / 1e6 + len(ids) * CAP * PRICE["output"] / 1e6
d = json.loads(LEDGER.read_text())
if d["session_cost_upper_bound_usd"] + reservation > d["budget_usd"]:
shutil.rmtree(rd); raise SystemExit(f"reservation {reservation:.2f} exceeds the ledger budget")
d["session_cost_upper_bound_usd"] += reservation
d["hunt_trials"].append({"run": a.run, "tasks": ids, "status": "batch_reserved", "cost_usd_conservative": reservation})
LEDGER.write_text(json.dumps(d, indent=2) + "\n")
(rd / "protocol.json").write_text(json.dumps({"tasks": ids, "model": "gpt-6-astra", "reasoning": "medium", "token_cap": CAP,
"api": "OpenAI Batch, /v1/chat/completions, 24h window", "reservation_usd": reservation,
"system": SYSTEM, "model_side_tools": False, "feedback": None,
'package':str(PKG),'tasks_manifest_sha256':hashlib.sha256((PKG/'candidate/tasks.jsonl').read_bytes()).hexdigest()}, indent=2) + "\n")
print(len(ids), "requests; reservation", round(reservation, 3))
def submit(a):
rd = run_dir(a.run); b = "----" + uuid.uuid4().hex
intent=rd/'dispatch-intent.json'
with intent.open('x') as handle:
json.dump({'status':'dispatch_started_no_automatic_retry'},handle)
body = (f"--{b}\r\nContent-Disposition: form-data; name=\"purpose\"\r\n\r\nbatch\r\n--{b}\r\nContent-Disposition: form-data; "
f"name=\"file\"; filename=\"batch.jsonl\"\r\nContent-Type: application/jsonl\r\n\r\n").encode() + (rd / "batch.jsonl").read_bytes() + f"\r\n--{b}--\r\n".encode()
f = json.loads(api("/files", body, "multipart/form-data; boundary=" + b))
bt = json.loads(api("/batches", json.dumps({"input_file_id": f["id"], "endpoint": "/v1/chat/completions", "completion_window": "24h"}).encode()))
(rd / "batch.json").write_text(json.dumps(bt, indent=2) + "\n"); print(bt["id"], bt["status"])
def collect(a):
rd = run_dir(a.run); bt = json.loads(api("/batches/" + json.loads((rd / "batch.json").read_text())["id"]))
(rd / "batch.json").write_text(json.dumps(bt, indent=2) + "\n")
if bt["status"] != "completed":
raise SystemExit("batch status " + bt["status"])
cost = 0.0
for name in ("output_file_id", "error_file_id"):
if bt.get(name):
(rd / (name + ".jsonl")).write_bytes(api(f"/files/{bt[name]}/content"))
for line in (rd / "output_file_id.jsonl").read_text().splitlines():
r = json.loads(line); tid = r["custom_id"]; td = rd / tid; td.mkdir(exist_ok=True)
body = (r.get("response") or {}).get("body") or {}
(td / "response.json").write_text(json.dumps(body, indent=2) + "\n")
u = body.get("usage") or {}; cached = (u.get("prompt_tokens_details") or {}).get("cached_tokens", 0) or 0
c = ((u.get("prompt_tokens", 0) - cached) * PRICE["input"] + cached * PRICE["cached"] + u.get("completion_tokens", 0) * PRICE["output"]) / 1e6
c += (u.get("prompt_tokens_details") or {}).get("cache_write_tokens",0) * PRICE["input"] * .25 / 1e6
cost += c
ch = (body.get("choices") or [{}])[0]; code = ((ch.get("message") or {}).get("content") or "").strip()
gen = {"finish_reason": ch.get("finish_reason"), "usage": u, "cost_usd": c}
if ch.get("finish_reason") == "stop" and code:
if code.startswith("```"):
code = "\n".join(code.splitlines()[1:-1])
(td / "submission").mkdir(exist_ok=True); (td / "submission/main.py").write_text(code + "\n")
gen["code_sha256"] = hashlib.sha256((code + "\n").encode()).hexdigest()
(td / "generation.json").write_text(json.dumps(gen, indent=2) + "\n")
d = json.loads(LEDGER.read_text())
for t in d["hunt_trials"]:
if t.get("run") == a.run and t["status"] == "batch_reserved":
d["session_cost_upper_bound_usd"] += cost - t["cost_usd_conservative"]
t.update(status="batch_collected", cost_usd_conservative=cost, cost_status="usage_based_batch_price")
LEDGER.write_text(json.dumps(d, indent=2) + "\n")
print("collected; batch cost", round(cost, 4), "ledger", round(d["session_cost_upper_bound_usd"], 4))
def replay_one(rd, tid):
td = rd / tid
if not (td / "submission/main.py").exists() or (td / "scoring/score.json").exists():
return
runner = PKG / "evaluator/sandbox_runner.py"
def run(cmd, log):
with open(td / log, "w") as f:
return subprocess.run(list(map(str, cmd)), stdout=f, stderr=subprocess.STDOUT).returncode
if run([PY, runner, "prepare", "--package", PKG, "--job", td / "replay", "--task-id", tid, "--submission", td / "submission",
"--model-id", "gpt-6-astra", "--run-id", rd.name, "--python", PY], "prepare.log"):
return
run([PY, runner, "replay", "--package", PKG, "--job", td / "replay", "--python", PY, "--extra-runtime", ROOT / "tmp/calculix-contact-env",
"--wall-seconds", 600, "--cpu-seconds", 600, "--ram-mb", 6000], "replay.log")
sc = td / "scoring"; (sc / "submissions" / tid).mkdir(parents=True, exist_ok=True)
if (td / "replay/outputs").exists():
shutil.copytree(td / "replay/outputs", sc / "submissions" / tid, dirs_exist_ok=True)
for name, src in [("tasks", PKG / "candidate/tasks.jsonl"), ("references", PKG / "evaluator/references.jsonl")]:
(sc / (name + ".jsonl")).write_text("".join(l + "\n" for l in src.read_text().splitlines() if json.loads(l)["task_id"] == tid))
ref = json.loads((sc / "references.jsonl").read_text())
if ref.get("geometry_check"): # the scorer resolves the reference solid next to the reference file
rel = Path(ref["geometry_check"]["reference_step"]); (sc / rel).parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(PKG / "evaluator" / rel, sc / rel)
run([PY, PKG / "evaluator/score.py", "--refs", sc / "references.jsonl", "--tasks", sc / "tasks.jsonl", "--submissions", sc / "submissions",
"--run-id", rd.name, "--out", sc / "score.json"], "score.log")
def replay(a):
rd = run_dir(a.run); ids = json.loads((rd / "protocol.json").read_text())["tasks"]
with ThreadPoolExecutor(a.workers) as ex:
list(ex.map(lambda t: replay_one(rd, t), ids))
print("replayed", len(ids))
def summary(a):
rd = run_dir(a.run); ids = json.loads((rd / "protocol.json").read_text())["tasks"]
refs = {json.loads(l)["task_id"]: json.loads(l) for l in (PKG / "evaluator/references.jsonl").read_text().splitlines()}
rows = []
for tid in ids:
td = rd / tid; gen = json.loads((td / "generation.json").read_text()) if (td / "generation.json").exists() else {}
ex = json.loads((td / "replay/execution.json").read_text()) if (td / "replay/execution.json").exists() else {}
res = None
try:
res = json.loads((td / "replay/outputs/results.json").read_text())["outputs"]["lambda1"]
except Exception:
pass
ref = refs[tid]["references"]["lambda1"]["value"]; trap = refs[tid]["trap"]["naive_ccx_factors"]
uses_ccx = (td / "submission/main.py").exists() and bool(re.search(r"\bccx\b|BUCKLE", (td / "submission/main.py").read_text()))
if not gen.get("code_sha256"):
verdict = "no_code_" + str(gen.get("finish_reason"))
elif res is None:
verdict = "no_result_exit_" + str(ex.get("exit_code"))
elif type(res) not in (int,float) or not math.isfinite(res):
verdict = 'invalid_scalar_output'
else:
err = abs(res / ref - 1); verdict = "pass" if err <= 0.05 else ("trap_mode" if trap and abs(res / trap[0] - 1) <= 0.05 else "wrong")
rows.append(dict(task=tid, verdict=verdict, lambda1=res, reference=ref, naive_ccx_first=trap[0] if trap else None,
uses_calculix=uses_ccx, cost_usd=gen.get("cost_usd"),
full_workflow_verified=False, adjudication='pending trusted setup/field/mode review; numerical pass is not a joint pass',
protocol='one code-generation call, medium reasoning, no execution feedback; local replay'))
(rd / "summary.json").write_text(json.dumps(rows, indent=2) + "\n")
from collections import Counter
print(Counter(r["verdict"] for r in rows), "cost", round(sum(r["cost_usd"] or 0 for r in rows), 3))
for r in rows:
print(r["task"], r["verdict"], r["lambda1"], round(r["reference"], 4), r["naive_ccx_first"], "ccx" if r["uses_calculix"] else "own")
if __name__ == "__main__":
ap = argparse.ArgumentParser(); ap.add_argument("cmd", choices=["prepare", "submit", "collect", "replay", "summary"])
ap.add_argument("--run", required=True); ap.add_argument("--tasks"); ap.add_argument("--workers", type=int, default=3)
a = ap.parse_args(); globals()[a.cmd](a)