sandeepbh commited on
Commit
0f42585
·
verified ·
1 Parent(s): 67e321c

Upload run_eval.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. run_eval.py +210 -0
run_eval.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Claim 2 scaled proxy: base Qwen3-Coder-30B-A3B vs FullStack-Learn-LM-30B-A3B.
3
+
4
+ Prompts each model with ONLY the app instruction; scores the generated code
5
+ against HIDDEN requirements (frontend UI tasks, backend API tests, DB entities)
6
+ with a deterministic requirement-coverage + structural heuristic. This is a
7
+ PROXY (labeled toy): it is NOT the FullStack-Bench harness (no browser/DB tests,
8
+ no 480B judge). It probes the direction of Claim 2 on the real released weights.
9
+
10
+ Modes:
11
+ --selftest score a stub codebase (no GPU / no vllm), print, exit
12
+ --generate MODEL OUTFILE load MODEL with vLLM, generate for all prompts -> OUTFILE
13
+ --run (default) generate for BASE + FT via subprocesses, score,
14
+ write results, upload to the Hub, print summary
15
+ """
16
+ import argparse, json, os, re, subprocess, sys, gc, time
17
+
18
+ BASE_MODEL = os.environ.get("BASE_MODEL", "Qwen/Qwen3-Coder-30B-A3B-Instruct")
19
+ FT_MODEL = os.environ.get("FT_MODEL", "luzimu/FullStack-Learn-LM-30B-A3B")
20
+ RESULT_REPO = os.environ.get("RESULT_REPO", "sandeepbh/fullstack-claim2-proxy")
21
+ MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "4096"))
22
+ MAX_MODEL_LEN = int(os.environ.get("MAX_MODEL_LEN", "8192"))
23
+
24
+ def prompts_path():
25
+ for p in (os.environ.get("PROMPTS"), "/work/prompts.jsonl",
26
+ os.path.join(os.path.dirname(__file__), "prompts.jsonl")):
27
+ if p and os.path.exists(p):
28
+ return p
29
+ raise FileNotFoundError("prompts.jsonl not found")
30
+
31
+ def load_items():
32
+ return [json.loads(l) for l in open(prompts_path(), encoding="utf-8") if l.strip()]
33
+
34
+ # ---------------- scoring (deterministic) ----------------
35
+ 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
36
+ user users system page pages data information test tests verify testing ensure check checks should when then
37
+ display displays displaying show shows return returns returning correct correctly correct functionality feature
38
+ features valid enter entering based all each its their such via able website web app application new using
39
+ request response api endpoint send sending button click clicking view details detail list add create update
40
+ delete remove select selecting different various can will has have""".split())
41
+
42
+ def toks(text):
43
+ return set(t for t in re.split(r"[^a-zA-Z0-9]+", (text or "").lower()) if len(t) >= 4 and t not in STOP)
44
+
45
+ def covered(req, hay):
46
+ kw = toks(req)
47
+ if not kw:
48
+ return True
49
+ hit = len(kw & hay)
50
+ need = 2 if len(kw) >= 3 else 1
51
+ return hit >= need
52
+
53
+ BACKEND_PAT = re.compile(r"@app\.route|@router\.(get|post|put|delete|patch)|app\.(get|post|put|delete|patch)\s*\(|router\.(get|post|put|delete|patch)|APIRouter|fastapi|from flask|express\(\)|urlpatterns|path\(|@(get|post|put|delete)\(|def \w+\([^)]*request", re.I)
54
+ DB_PAT = re.compile(r"create table|db\.Model|models\.Model|mongoose\.Schema|new Schema|Column\(|sqlalchemy|sequelize|prisma|ForeignKey|primary key|db\.session|createConnection|sqlite3|psycopg2|pymongo|collection\(", re.I)
55
+ FRONTEND_PAT = re.compile(r"<!doctype|<html|<div|<form|<script|useState|reactdom|react|document\.(get|query)|addeventlistener|v-model|<template|<button|render\(", re.I)
56
+ WIRED_PAT = re.compile(r"fetch\(|axios|xmlhttprequest|\$\.ajax|/api/|http://|https://localhost|:\d{4}/", re.I)
57
+
58
+ def score_site(out, item):
59
+ hay = toks(out)
60
+ def cov(reqs):
61
+ if not reqs:
62
+ return None
63
+ return sum(1 for r in reqs if covered(r, hay)) / len(reqs)
64
+ fe = cov(item.get("frontend_reqs"))
65
+ be = cov(item.get("backend_reqs"))
66
+ db = cov(item.get("db_reqs"))
67
+ sig = {
68
+ "has_backend": bool(BACKEND_PAT.search(out or "")),
69
+ "has_db": bool(DB_PAT.search(out or "")),
70
+ "has_frontend": bool(FRONTEND_PAT.search(out or "")),
71
+ "wired": bool(WIRED_PAT.search(out or "")),
72
+ }
73
+ parts = [x for x in (fe, be, db) if x is not None]
74
+ overall = sum(parts) / len(parts) if parts else 0.0
75
+ return {"id": item.get("id"), "frontend_cov": fe, "backend_cov": be, "db_cov": db,
76
+ "overall_cov": overall, "gen_chars": len(out or ""), **sig}
77
+
78
+ def aggregate(rows):
79
+ def mean(key):
80
+ vals = [r[key] for r in rows if r.get(key) is not None]
81
+ return round(sum(vals) / len(vals), 4) if vals else None
82
+ def frac(key):
83
+ return round(sum(1 for r in rows if r.get(key)) / len(rows), 4) if rows else 0.0
84
+ return {
85
+ "n_sites": len(rows),
86
+ "frontend_cov": mean("frontend_cov"),
87
+ "backend_cov": mean("backend_cov"),
88
+ "db_cov": mean("db_cov"),
89
+ "overall_cov": mean("overall_cov"),
90
+ "pct_has_backend": frac("has_backend"),
91
+ "pct_has_db": frac("has_db"),
92
+ "pct_has_frontend": frac("has_frontend"),
93
+ "pct_wired": frac("wired"),
94
+ }
95
+
96
+ # ---------------- generation (vLLM) ----------------
97
+ def build_prompt(instruction):
98
+ return (
99
+ "You are an expert full-stack web developer. Build a COMPLETE, working full-stack "
100
+ "web application that satisfies the requirement below. Include all three layers and "
101
+ "output real code in fenced code blocks with file paths:\n"
102
+ " 1. FRONTEND (HTML/CSS/JS or a framework) with the needed UI and interactions.\n"
103
+ " 2. BACKEND server exposing the necessary API endpoints.\n"
104
+ " 3. DATABASE schema/models for the data the app stores.\n"
105
+ "Wire the frontend to the backend APIs. Do not omit layers.\n\n"
106
+ f"Requirement:\n{instruction}\n"
107
+ )
108
+
109
+ def generate(model_id, outfile):
110
+ from vllm import LLM, SamplingParams
111
+ from transformers import AutoTokenizer
112
+ items = load_items()
113
+ tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
114
+ prompts = []
115
+ for it in items:
116
+ msgs = [{"role": "user", "content": build_prompt(it["instruction"])}]
117
+ prompts.append(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True))
118
+ llm = LLM(model=model_id, dtype="bfloat16", trust_remote_code=True,
119
+ gpu_memory_utilization=0.90, max_model_len=MAX_MODEL_LEN)
120
+ sp = SamplingParams(temperature=0.0, max_tokens=MAX_TOKENS)
121
+ t0 = time.time()
122
+ outs = llm.generate(prompts, sp)
123
+ dt = time.time() - t0
124
+ res = [{"id": items[i]["id"], "output": outs[i].outputs[0].text} for i in range(len(items))]
125
+ with open(outfile, "w", encoding="utf-8") as f:
126
+ for r in res:
127
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
128
+ print(f"[generate] {model_id}: {len(res)} generations in {dt:.1f}s -> {outfile}", flush=True)
129
+
130
+ # ---------------- orchestration ----------------
131
+ def run():
132
+ items = load_items()
133
+ gens = {}
134
+ for tag, mid in (("base", BASE_MODEL), ("ft", FT_MODEL)):
135
+ outf = f"/tmp/gen_{tag}.jsonl"
136
+ print(f"[run] generating with {tag} = {mid}", flush=True)
137
+ subprocess.run([sys.executable, os.path.abspath(__file__), "--generate", mid, outf], check=True)
138
+ gens[tag] = {json.loads(l)["id"]: json.loads(l)["output"]
139
+ for l in open(outf, encoding="utf-8") if l.strip()}
140
+ per = {"base": [], "ft": []}
141
+ for it in items:
142
+ for tag in ("base", "ft"):
143
+ per[tag].append(score_site(gens[tag].get(it["id"], ""), it))
144
+ summary = {
145
+ "experiment": "FullStack-Agent Claim 2 scaled proxy (requirement-coverage; NOT FullStack-Bench)",
146
+ "base_model": BASE_MODEL, "ft_model": FT_MODEL,
147
+ "n_sites": len(items), "max_tokens": MAX_TOKENS,
148
+ "base": aggregate(per["base"]), "ft": aggregate(per["ft"]),
149
+ }
150
+ for k in ("frontend_cov", "backend_cov", "db_cov", "overall_cov"):
151
+ b, f = summary["base"][k], summary["ft"][k]
152
+ summary.setdefault("delta_ft_minus_base", {})[k] = round((f - b), 4) if (b is not None and f is not None) else None
153
+
154
+ os.makedirs("/tmp/out", exist_ok=True)
155
+ json.dump(summary, open("/tmp/out/results.json", "w"), indent=2)
156
+ json.dump({"base": per["base"], "ft": per["ft"]}, open("/tmp/out/per_site.json", "w"), indent=2)
157
+ for tag in ("base", "ft"):
158
+ if os.path.exists(f"/tmp/gen_{tag}.jsonl"):
159
+ os.replace(f"/tmp/gen_{tag}.jsonl", f"/tmp/out/gen_{tag}.jsonl")
160
+
161
+ # upload artifacts to the Hub (best-effort)
162
+ try:
163
+ from huggingface_hub import HfApi
164
+ api = HfApi()
165
+ api.create_repo(RESULT_REPO, repo_type="dataset", exist_ok=True)
166
+ for fn in ("results.json", "per_site.json", "gen_base.jsonl", "gen_ft.jsonl"):
167
+ p = f"/tmp/out/{fn}"
168
+ if os.path.exists(p):
169
+ api.upload_file(path_or_fileobj=p, path_in_repo=f"results/{fn}",
170
+ repo_id=RESULT_REPO, repo_type="dataset")
171
+ print(f"[run] uploaded artifacts to dataset {RESULT_REPO}/results/", flush=True)
172
+ except Exception as e:
173
+ print(f"[run] upload skipped: {e}", flush=True)
174
+
175
+ print("===CLAIM2_PROXY_RESULT===", flush=True)
176
+ print(json.dumps(summary, indent=2), flush=True)
177
+ print("===END===", flush=True)
178
+
179
+ def selftest():
180
+ stub_full = ("```python\nfrom flask import Flask, request, jsonify\napp = Flask(__name__)\n"
181
+ "import sqlalchemy\nclass Stock(db.Model):\n Column(name)\n"
182
+ "@app.route('/api/search')\ndef search(): return jsonify(stock information)\n```\n"
183
+ "```html\n<!DOCTYPE html><html><form><button>Search</button></form>"
184
+ "<script>fetch('/api/search')</script></html>\n```")
185
+ stub_frontend_only = ("```html\n<!DOCTYPE html><html><div>Stock report</div>"
186
+ "<script>const x=1;</script></html>\n```")
187
+ items = load_items()
188
+ it = items[0]
189
+ print("site:", it["id"], "| reqs fe/be/db =",
190
+ len(it["frontend_reqs"]), len(it["backend_reqs"]), len(it["db_reqs"]))
191
+ print("FULL-STACK stub score:", json.dumps(score_site(stub_full, it)))
192
+ print("FRONTEND-ONLY stub score:", json.dumps(score_site(stub_frontend_only, it)))
193
+ print("aggregate(full x3):", json.dumps(aggregate([score_site(stub_full, x) for x in items[:3]])))
194
+ print("SELFTEST OK")
195
+
196
+ def main():
197
+ ap = argparse.ArgumentParser()
198
+ ap.add_argument("--selftest", action="store_true")
199
+ ap.add_argument("--generate", nargs=2, metavar=("MODEL", "OUTFILE"))
200
+ ap.add_argument("--run", action="store_true")
201
+ a = ap.parse_args()
202
+ if a.selftest:
203
+ selftest()
204
+ elif a.generate:
205
+ generate(a.generate[0], a.generate[1])
206
+ else:
207
+ run()
208
+
209
+ if __name__ == "__main__":
210
+ main()