fullstack-claim2-proxy / run_eval_v2.py
sandeepbh's picture
Upload run_eval_v2.py with huggingface_hub
6715d2c verified
Raw History Blame Contribute Delete
13.8 kB
#!/usr/bin/env python3
"""Claim 2 proxy v2 — LLM-as-judge functional pass-rate.
base = Qwen/Qwen3-Coder-30B-A3B-Instruct, ft = luzimu/FullStack-Learn-LM-30B-A3B.
Each model is prompted with ONLY the app instruction (hidden requirements are the
rubric). A neutral open judge (Qwen2.5-Coder-32B-Instruct) then decides, per hidden
requirement, whether the generated code would satisfy it -> a pass-rate analogous to
the paper's per-test-case accuracy. Documented backend substitution for the 480B judge.
Still a PROXY (toy): static judge (not executed), single-shot (not agentic FullStack-Dev).
Modes:
--selftest parse/aggregate checks on stubs (no GPU)
--generate MODEL OUTFILE single-shot generate for all prompts
--judge MODEL BASE_GEN FT_GEN OUTFILE judge each hidden requirement (YES/NO)
--run orchestrate gen(base,ft) -> upload -> judge -> aggregate -> upload
"""
import argparse, json, os, re, subprocess, sys, time
os.environ.setdefault("VLLM_ATTENTION_BACKEND", "FLASH_ATTN")
os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
BASE_MODEL = os.environ.get("BASE_MODEL", "Qwen/Qwen3-Coder-30B-A3B-Instruct")
FT_MODEL = os.environ.get("FT_MODEL", "luzimu/FullStack-Learn-LM-30B-A3B")
JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct")
RESULT_REPO = os.environ.get("RESULT_REPO", "sandeepbh/fullstack-claim2-proxy")
GEN_MAX_TOKENS = int(os.environ.get("GEN_MAX_TOKENS", "8192"))
GEN_MODEL_LEN = int(os.environ.get("GEN_MODEL_LEN", "12288"))
JUDGE_MAX_TOKENS = int(os.environ.get("JUDGE_MAX_TOKENS", "1200"))
JUDGE_MODEL_LEN = int(os.environ.get("JUDGE_MODEL_LEN", "13000"))
CODE_TRUNC_CHARS = int(os.environ.get("CODE_TRUNC_CHARS", "16000"))
CATS = [("frontend", "frontend_reqs"), ("backend", "backend_reqs"), ("database", "db_reqs")]
def prompts_path():
for p in (os.environ.get("PROMPTS"), "/work/prompts_all.jsonl",
os.path.join(os.path.dirname(__file__), "prompts_all.jsonl")):
if p and os.path.exists(p):
return p
raise FileNotFoundError("prompts_all.jsonl not found")
def load_items():
return [json.loads(l) for l in open(prompts_path(), encoding="utf-8") if l.strip()]
def read_map(path):
m = {}
for l in open(path, encoding="utf-8"):
if l.strip():
r = json.loads(l); m[r["id"]] = r["output"]
return m
# ---------------- generation ----------------
def gen_prompt(instruction):
return (
"You are an expert full-stack web developer. Build a COMPLETE, working full-stack "
"web application that satisfies the requirement below. Include all three layers and "
"output real code in fenced code blocks with file paths:\n"
" 1. FRONTEND (HTML/CSS/JS or a framework) with the needed UI and interactions.\n"
" 2. BACKEND server exposing the necessary API endpoints.\n"
" 3. DATABASE schema/models for the data the app stores.\n"
"Wire the frontend to the backend APIs. Implement real logic, not stubs.\n\n"
f"Requirement:\n{instruction}\n"
)
def generate(model_id, outfile):
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
items = load_items()
tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
prompts = [tok.apply_chat_template([{"role": "user", "content": gen_prompt(it["instruction"])}],
tokenize=False, add_generation_prompt=True) for it in items]
llm = LLM(model=model_id, dtype="bfloat16", trust_remote_code=True,
gpu_memory_utilization=0.90, max_model_len=GEN_MODEL_LEN, enforce_eager=True)
sp = SamplingParams(temperature=0.0, max_tokens=GEN_MAX_TOKENS)
t0 = time.time(); outs = llm.generate(prompts, sp); dt = time.time() - t0
with open(outfile, "w", encoding="utf-8") as f:
for i, it in enumerate(items):
f.write(json.dumps({"id": it["id"], "output": outs[i].outputs[0].text}, ensure_ascii=False) + "\n")
print(f"[generate] {model_id}: {len(items)} gens in {dt:.1f}s -> {outfile}", flush=True)
# ---------------- judging ----------------
def judge_prompt(category, code, reqs):
numbered = "\n".join(f"{i}. {r}" for i, r in enumerate(reqs))
return (
"You are a strict senior code reviewer. Below is a candidate full-stack web app "
f"implementation, then a numbered list of {category.upper()} test requirements. For EACH "
"requirement decide, based ONLY on what is actually implemented in the code (ignore comments, "
"TODOs, and stated intentions), whether the implementation would satisfy/pass it.\n"
'Output ONLY a JSON array, one object per requirement, e.g. [{"i":0,"pass":true},{"i":1,"pass":false}]. '
"No prose, no code fences.\n\n"
f"=== CODE ===\n{code[:CODE_TRUNC_CHARS]}\n=== END CODE ===\n\n"
f"{category.upper()} REQUIREMENTS:\n{numbered}\n"
)
def parse_judgments(text, n):
try:
m = re.search(r"\[.*\]", text, re.S)
if not m:
return [False] * n, True
arr = json.loads(m.group(0))
by_i = {}
pos = []
for idx, el in enumerate(arr):
if isinstance(el, bool):
pos.append(el)
elif isinstance(el, dict):
val = bool(el.get("pass", el.get("passed", el.get("result", False))))
if "i" in el:
try: by_i[int(el["i"])] = val
except Exception: pos.append(val)
else:
pos.append(val)
if by_i:
return [bool(by_i.get(i, pos[i] if i < len(pos) else False)) for i in range(n)], False
return [(pos[i] if i < len(pos) else False) for i in range(n)], (len(pos) != n)
except Exception:
return [False] * n, True
def judge(model_id, base_gen, ft_gen, outfile):
from vllm import LLM, SamplingParams
from transformers import AutoTokenizer
items = load_items()
gens = {"base": read_map(base_gen), "ft": read_map(ft_gen)}
tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
tasks = []
for it in items:
for cat, key in CATS:
reqs = it.get(key) or []
if not reqs:
continue
for mtag in ("base", "ft"):
code = gens[mtag].get(it["id"], "") or ""
msgs = [{"role": "user", "content": judge_prompt(cat, code, reqs)}]
p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
tasks.append((it["id"], cat, mtag, len(reqs), p))
llm = LLM(model=model_id, dtype="bfloat16", trust_remote_code=True,
gpu_memory_utilization=0.90, max_model_len=JUDGE_MODEL_LEN, enforce_eager=True)
sp = SamplingParams(temperature=0.0, max_tokens=JUDGE_MAX_TOKENS)
t0 = time.time(); outs = llm.generate([t[4] for t in tasks], sp); dt = time.time() - t0
fails = 0
with open(outfile, "w", encoding="utf-8") as f:
for (id_, cat, mtag, n, _), o in zip(tasks, outs):
passes, failed = parse_judgments(o.outputs[0].text, n)
fails += 1 if failed else 0
f.write(json.dumps({"id": id_, "category": cat, "model": mtag, "passes": passes}) + "\n")
print(f"[judge] {model_id}: {len(tasks)} calls in {dt:.1f}s, parse_fails={fails} -> {outfile}", flush=True)
# ---------------- coverage (context metric, from v1) ----------------
STOP = set("""the a an and or to of in for with on by is are be that this it as at from into using use user users
system page pages data information test tests verify testing ensure check checks should when then display displays
show shows return returns correct correctly functionality feature features valid enter entering based all each its
their such via able website web app application new request response api endpoint send button click view details
list add create update delete remove select different can will has have""".split())
def toks(t): return set(x for x in re.split(r"[^a-zA-Z0-9]+", (t or "").lower()) if len(x) >= 4 and x not in STOP)
def covered(req, hay):
kw = toks(req)
if not kw: return True
return len(kw & hay) >= (2 if len(kw) >= 3 else 1)
def cov_rate(reqs, hay): return (sum(1 for r in reqs if covered(r, hay)) / len(reqs)) if reqs else None
# ---------------- orchestration ----------------
def _agg_passrate(rows, model):
out = {}
tot_p = tot_n = 0
for cat, _ in CATS:
p = n = 0
for r in rows:
if r["model"] == model and r["category"] == cat:
p += sum(1 for x in r["passes"] if x); n += len(r["passes"])
out[cat] = round(p / n, 4) if n else None
out[cat + "_n"] = n
tot_p += p; tot_n += n
out["overall"] = round(tot_p / tot_n, 4) if tot_n else None
out["total_reqs"] = tot_n
return out
def run():
items = load_items()
for tag, mid in (("base", BASE_MODEL), ("ft", FT_MODEL)):
print(f"[run] generate {tag} = {mid}", flush=True)
subprocess.run([sys.executable, os.path.abspath(__file__), "--generate", mid, f"/tmp/gen_{tag}.jsonl"], check=True)
# upload generations early (resilience)
try:
from huggingface_hub import HfApi
api = HfApi(); api.create_repo(RESULT_REPO, repo_type="dataset", exist_ok=True)
for tag in ("base", "ft"):
api.upload_file(path_or_fileobj=f"/tmp/gen_{tag}.jsonl", path_in_repo=f"results_v2/gen_{tag}.jsonl",
repo_id=RESULT_REPO, repo_type="dataset")
print("[run] uploaded generations", flush=True)
except Exception as e:
print("[run] gen upload skipped:", e, flush=True)
subprocess.run([sys.executable, os.path.abspath(__file__), "--judge", JUDGE_MODEL,
"/tmp/gen_base.jsonl", "/tmp/gen_ft.jsonl", "/tmp/judge.jsonl"], check=True)
rows = [json.loads(l) for l in open("/tmp/judge.jsonl", encoding="utf-8") if l.strip()]
gens = {"base": read_map("/tmp/gen_base.jsonl"), "ft": read_map("/tmp/gen_ft.jsonl")}
cov = {}
for mtag in ("base", "ft"):
fe = []; be = []; db = []
for it in items:
hay = toks(gens[mtag].get(it["id"], ""))
for lst, key in ((fe, "frontend_reqs"), (be, "backend_reqs"), (db, "db_reqs")):
r = cov_rate(it.get(key) or [], hay)
if r is not None: lst.append(r)
cov[mtag] = {"frontend": round(sum(fe)/len(fe), 4) if fe else None,
"backend": round(sum(be)/len(be), 4) if be else None,
"database": round(sum(db)/len(db), 4) if db else None}
summary = {
"experiment": "FullStack-Agent Claim 2 proxy v2 (LLM-judge functional pass-rate; static, single-shot; NOT FullStack-Bench)",
"base_model": BASE_MODEL, "ft_model": FT_MODEL, "judge_model": JUDGE_MODEL,
"n_sites": len(items), "gen_max_tokens": GEN_MAX_TOKENS,
"passrate": {"base": _agg_passrate(rows, "base"), "ft": _agg_passrate(rows, "ft")},
"coverage_context": cov,
}
d = {}
for cat, _ in CATS + [("overall", None)]:
b = summary["passrate"]["base"].get(cat); f = summary["passrate"]["ft"].get(cat)
d[cat] = round(f - b, 4) if (b is not None and f is not None) else None
summary["passrate_delta_ft_minus_base"] = d
os.makedirs("/tmp/out", exist_ok=True)
json.dump(summary, open("/tmp/out/results_v2.json", "w"), indent=2)
json.dump(rows, open("/tmp/out/judge_rows.json", "w"), indent=2)
try:
from huggingface_hub import HfApi
api = HfApi()
for fn in ("results_v2.json", "judge_rows.json"):
api.upload_file(path_or_fileobj=f"/tmp/out/{fn}", path_in_repo=f"results_v2/{fn}",
repo_id=RESULT_REPO, repo_type="dataset")
print("[run] uploaded v2 results", flush=True)
except Exception as e:
print("[run] results upload skipped:", e, flush=True)
print("===CLAIM2_PROXY_V2_RESULT===", flush=True)
print(json.dumps(summary, indent=2), flush=True)
print("===END===", flush=True)
def selftest():
good = ('[{"i":0,"pass":true},{"i":1,"pass":false},{"i":2,"pass":true}]')
fenced = ('```json\n[{"i":0,"pass":false},{"i":1,"pass":true}]\n```')
bools = "[true, false, true]"
print("parse good:", parse_judgments(good, 3))
print("parse fenced:", parse_judgments(fenced, 2))
print("parse bools:", parse_judgments(bools, 3))
print("parse junk:", parse_judgments("the model refused", 2))
rows = [
{"id": "a", "category": "backend", "model": "base", "passes": [True, False]},
{"id": "a", "category": "backend", "model": "ft", "passes": [True, True]},
{"id": "a", "category": "frontend", "model": "base", "passes": [True, True, False]},
{"id": "a", "category": "frontend", "model": "ft", "passes": [True, False, False]},
]
print("agg base:", _agg_passrate(rows, "base"))
print("agg ft:", _agg_passrate(rows, "ft"))
it = load_items()[0]
print("judge_prompt sample (first 240 chars):", judge_prompt("backend", "print('x')", it["backend_reqs"])[:240])
print("SELFTEST OK")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--selftest", action="store_true")
ap.add_argument("--generate", nargs=2, metavar=("MODEL", "OUTFILE"))
ap.add_argument("--judge", nargs=4, metavar=("MODEL", "BASE_GEN", "FT_GEN", "OUTFILE"))
ap.add_argument("--run", action="store_true")
a = ap.parse_args()
if a.selftest: selftest()
elif a.generate: generate(a.generate[0], a.generate[1])
elif a.judge: judge(a.judge[0], a.judge[1], a.judge[2], a.judge[3])
else: run()
if __name__ == "__main__":
main()