sandeepbh commited on
Commit
6715d2c
·
verified ·
1 Parent(s): 0efd22f

Upload run_eval_v2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. run_eval_v2.py +271 -0
run_eval_v2.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Claim 2 proxy v2 — LLM-as-judge functional pass-rate.
3
+
4
+ base = Qwen/Qwen3-Coder-30B-A3B-Instruct, ft = luzimu/FullStack-Learn-LM-30B-A3B.
5
+ Each model is prompted with ONLY the app instruction (hidden requirements are the
6
+ rubric). A neutral open judge (Qwen2.5-Coder-32B-Instruct) then decides, per hidden
7
+ requirement, whether the generated code would satisfy it -> a pass-rate analogous to
8
+ the paper's per-test-case accuracy. Documented backend substitution for the 480B judge.
9
+ Still a PROXY (toy): static judge (not executed), single-shot (not agentic FullStack-Dev).
10
+
11
+ Modes:
12
+ --selftest parse/aggregate checks on stubs (no GPU)
13
+ --generate MODEL OUTFILE single-shot generate for all prompts
14
+ --judge MODEL BASE_GEN FT_GEN OUTFILE judge each hidden requirement (YES/NO)
15
+ --run orchestrate gen(base,ft) -> upload -> judge -> aggregate -> upload
16
+ """
17
+ import argparse, json, os, re, subprocess, sys, time
18
+
19
+ os.environ.setdefault("VLLM_ATTENTION_BACKEND", "FLASH_ATTN")
20
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
21
+
22
+ BASE_MODEL = os.environ.get("BASE_MODEL", "Qwen/Qwen3-Coder-30B-A3B-Instruct")
23
+ FT_MODEL = os.environ.get("FT_MODEL", "luzimu/FullStack-Learn-LM-30B-A3B")
24
+ JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct")
25
+ RESULT_REPO = os.environ.get("RESULT_REPO", "sandeepbh/fullstack-claim2-proxy")
26
+ GEN_MAX_TOKENS = int(os.environ.get("GEN_MAX_TOKENS", "8192"))
27
+ GEN_MODEL_LEN = int(os.environ.get("GEN_MODEL_LEN", "12288"))
28
+ JUDGE_MAX_TOKENS = int(os.environ.get("JUDGE_MAX_TOKENS", "1200"))
29
+ JUDGE_MODEL_LEN = int(os.environ.get("JUDGE_MODEL_LEN", "13000"))
30
+ CODE_TRUNC_CHARS = int(os.environ.get("CODE_TRUNC_CHARS", "16000"))
31
+ CATS = [("frontend", "frontend_reqs"), ("backend", "backend_reqs"), ("database", "db_reqs")]
32
+
33
+ def prompts_path():
34
+ for p in (os.environ.get("PROMPTS"), "/work/prompts_all.jsonl",
35
+ os.path.join(os.path.dirname(__file__), "prompts_all.jsonl")):
36
+ if p and os.path.exists(p):
37
+ return p
38
+ raise FileNotFoundError("prompts_all.jsonl not found")
39
+
40
+ def load_items():
41
+ return [json.loads(l) for l in open(prompts_path(), encoding="utf-8") if l.strip()]
42
+
43
+ def read_map(path):
44
+ m = {}
45
+ for l in open(path, encoding="utf-8"):
46
+ if l.strip():
47
+ r = json.loads(l); m[r["id"]] = r["output"]
48
+ return m
49
+
50
+ # ---------------- generation ----------------
51
+ def gen_prompt(instruction):
52
+ return (
53
+ "You are an expert full-stack web developer. Build a COMPLETE, working full-stack "
54
+ "web application that satisfies the requirement below. Include all three layers and "
55
+ "output real code in fenced code blocks with file paths:\n"
56
+ " 1. FRONTEND (HTML/CSS/JS or a framework) with the needed UI and interactions.\n"
57
+ " 2. BACKEND server exposing the necessary API endpoints.\n"
58
+ " 3. DATABASE schema/models for the data the app stores.\n"
59
+ "Wire the frontend to the backend APIs. Implement real logic, not stubs.\n\n"
60
+ f"Requirement:\n{instruction}\n"
61
+ )
62
+
63
+ def generate(model_id, outfile):
64
+ from vllm import LLM, SamplingParams
65
+ from transformers import AutoTokenizer
66
+ items = load_items()
67
+ tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
68
+ prompts = [tok.apply_chat_template([{"role": "user", "content": gen_prompt(it["instruction"])}],
69
+ tokenize=False, add_generation_prompt=True) for it in items]
70
+ llm = LLM(model=model_id, dtype="bfloat16", trust_remote_code=True,
71
+ gpu_memory_utilization=0.90, max_model_len=GEN_MODEL_LEN, enforce_eager=True)
72
+ sp = SamplingParams(temperature=0.0, max_tokens=GEN_MAX_TOKENS)
73
+ t0 = time.time(); outs = llm.generate(prompts, sp); dt = time.time() - t0
74
+ with open(outfile, "w", encoding="utf-8") as f:
75
+ for i, it in enumerate(items):
76
+ f.write(json.dumps({"id": it["id"], "output": outs[i].outputs[0].text}, ensure_ascii=False) + "\n")
77
+ print(f"[generate] {model_id}: {len(items)} gens in {dt:.1f}s -> {outfile}", flush=True)
78
+
79
+ # ---------------- judging ----------------
80
+ def judge_prompt(category, code, reqs):
81
+ numbered = "\n".join(f"{i}. {r}" for i, r in enumerate(reqs))
82
+ return (
83
+ "You are a strict senior code reviewer. Below is a candidate full-stack web app "
84
+ f"implementation, then a numbered list of {category.upper()} test requirements. For EACH "
85
+ "requirement decide, based ONLY on what is actually implemented in the code (ignore comments, "
86
+ "TODOs, and stated intentions), whether the implementation would satisfy/pass it.\n"
87
+ 'Output ONLY a JSON array, one object per requirement, e.g. [{"i":0,"pass":true},{"i":1,"pass":false}]. '
88
+ "No prose, no code fences.\n\n"
89
+ f"=== CODE ===\n{code[:CODE_TRUNC_CHARS]}\n=== END CODE ===\n\n"
90
+ f"{category.upper()} REQUIREMENTS:\n{numbered}\n"
91
+ )
92
+
93
+ def parse_judgments(text, n):
94
+ try:
95
+ m = re.search(r"\[.*\]", text, re.S)
96
+ if not m:
97
+ return [False] * n, True
98
+ arr = json.loads(m.group(0))
99
+ by_i = {}
100
+ pos = []
101
+ for idx, el in enumerate(arr):
102
+ if isinstance(el, bool):
103
+ pos.append(el)
104
+ elif isinstance(el, dict):
105
+ val = bool(el.get("pass", el.get("passed", el.get("result", False))))
106
+ if "i" in el:
107
+ try: by_i[int(el["i"])] = val
108
+ except Exception: pos.append(val)
109
+ else:
110
+ pos.append(val)
111
+ if by_i:
112
+ return [bool(by_i.get(i, pos[i] if i < len(pos) else False)) for i in range(n)], False
113
+ return [(pos[i] if i < len(pos) else False) for i in range(n)], (len(pos) != n)
114
+ except Exception:
115
+ return [False] * n, True
116
+
117
+ def judge(model_id, base_gen, ft_gen, outfile):
118
+ from vllm import LLM, SamplingParams
119
+ from transformers import AutoTokenizer
120
+ items = load_items()
121
+ gens = {"base": read_map(base_gen), "ft": read_map(ft_gen)}
122
+ tok = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
123
+ tasks = []
124
+ for it in items:
125
+ for cat, key in CATS:
126
+ reqs = it.get(key) or []
127
+ if not reqs:
128
+ continue
129
+ for mtag in ("base", "ft"):
130
+ code = gens[mtag].get(it["id"], "") or ""
131
+ msgs = [{"role": "user", "content": judge_prompt(cat, code, reqs)}]
132
+ p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
133
+ tasks.append((it["id"], cat, mtag, len(reqs), p))
134
+ llm = LLM(model=model_id, dtype="bfloat16", trust_remote_code=True,
135
+ gpu_memory_utilization=0.90, max_model_len=JUDGE_MODEL_LEN, enforce_eager=True)
136
+ sp = SamplingParams(temperature=0.0, max_tokens=JUDGE_MAX_TOKENS)
137
+ t0 = time.time(); outs = llm.generate([t[4] for t in tasks], sp); dt = time.time() - t0
138
+ fails = 0
139
+ with open(outfile, "w", encoding="utf-8") as f:
140
+ for (id_, cat, mtag, n, _), o in zip(tasks, outs):
141
+ passes, failed = parse_judgments(o.outputs[0].text, n)
142
+ fails += 1 if failed else 0
143
+ f.write(json.dumps({"id": id_, "category": cat, "model": mtag, "passes": passes}) + "\n")
144
+ print(f"[judge] {model_id}: {len(tasks)} calls in {dt:.1f}s, parse_fails={fails} -> {outfile}", flush=True)
145
+
146
+ # ---------------- coverage (context metric, from v1) ----------------
147
+ 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
148
+ system page pages data information test tests verify testing ensure check checks should when then display displays
149
+ show shows return returns correct correctly functionality feature features valid enter entering based all each its
150
+ their such via able website web app application new request response api endpoint send button click view details
151
+ list add create update delete remove select different can will has have""".split())
152
+ 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)
153
+ def covered(req, hay):
154
+ kw = toks(req)
155
+ if not kw: return True
156
+ return len(kw & hay) >= (2 if len(kw) >= 3 else 1)
157
+ def cov_rate(reqs, hay): return (sum(1 for r in reqs if covered(r, hay)) / len(reqs)) if reqs else None
158
+
159
+ # ---------------- orchestration ----------------
160
+ def _agg_passrate(rows, model):
161
+ out = {}
162
+ tot_p = tot_n = 0
163
+ for cat, _ in CATS:
164
+ p = n = 0
165
+ for r in rows:
166
+ if r["model"] == model and r["category"] == cat:
167
+ p += sum(1 for x in r["passes"] if x); n += len(r["passes"])
168
+ out[cat] = round(p / n, 4) if n else None
169
+ out[cat + "_n"] = n
170
+ tot_p += p; tot_n += n
171
+ out["overall"] = round(tot_p / tot_n, 4) if tot_n else None
172
+ out["total_reqs"] = tot_n
173
+ return out
174
+
175
+ def run():
176
+ items = load_items()
177
+ for tag, mid in (("base", BASE_MODEL), ("ft", FT_MODEL)):
178
+ print(f"[run] generate {tag} = {mid}", flush=True)
179
+ subprocess.run([sys.executable, os.path.abspath(__file__), "--generate", mid, f"/tmp/gen_{tag}.jsonl"], check=True)
180
+ # upload generations early (resilience)
181
+ try:
182
+ from huggingface_hub import HfApi
183
+ api = HfApi(); api.create_repo(RESULT_REPO, repo_type="dataset", exist_ok=True)
184
+ for tag in ("base", "ft"):
185
+ api.upload_file(path_or_fileobj=f"/tmp/gen_{tag}.jsonl", path_in_repo=f"results_v2/gen_{tag}.jsonl",
186
+ repo_id=RESULT_REPO, repo_type="dataset")
187
+ print("[run] uploaded generations", flush=True)
188
+ except Exception as e:
189
+ print("[run] gen upload skipped:", e, flush=True)
190
+
191
+ subprocess.run([sys.executable, os.path.abspath(__file__), "--judge", JUDGE_MODEL,
192
+ "/tmp/gen_base.jsonl", "/tmp/gen_ft.jsonl", "/tmp/judge.jsonl"], check=True)
193
+ rows = [json.loads(l) for l in open("/tmp/judge.jsonl", encoding="utf-8") if l.strip()]
194
+
195
+ gens = {"base": read_map("/tmp/gen_base.jsonl"), "ft": read_map("/tmp/gen_ft.jsonl")}
196
+ cov = {}
197
+ for mtag in ("base", "ft"):
198
+ fe = []; be = []; db = []
199
+ for it in items:
200
+ hay = toks(gens[mtag].get(it["id"], ""))
201
+ for lst, key in ((fe, "frontend_reqs"), (be, "backend_reqs"), (db, "db_reqs")):
202
+ r = cov_rate(it.get(key) or [], hay)
203
+ if r is not None: lst.append(r)
204
+ cov[mtag] = {"frontend": round(sum(fe)/len(fe), 4) if fe else None,
205
+ "backend": round(sum(be)/len(be), 4) if be else None,
206
+ "database": round(sum(db)/len(db), 4) if db else None}
207
+
208
+ summary = {
209
+ "experiment": "FullStack-Agent Claim 2 proxy v2 (LLM-judge functional pass-rate; static, single-shot; NOT FullStack-Bench)",
210
+ "base_model": BASE_MODEL, "ft_model": FT_MODEL, "judge_model": JUDGE_MODEL,
211
+ "n_sites": len(items), "gen_max_tokens": GEN_MAX_TOKENS,
212
+ "passrate": {"base": _agg_passrate(rows, "base"), "ft": _agg_passrate(rows, "ft")},
213
+ "coverage_context": cov,
214
+ }
215
+ d = {}
216
+ for cat, _ in CATS + [("overall", None)]:
217
+ b = summary["passrate"]["base"].get(cat); f = summary["passrate"]["ft"].get(cat)
218
+ d[cat] = round(f - b, 4) if (b is not None and f is not None) else None
219
+ summary["passrate_delta_ft_minus_base"] = d
220
+
221
+ os.makedirs("/tmp/out", exist_ok=True)
222
+ json.dump(summary, open("/tmp/out/results_v2.json", "w"), indent=2)
223
+ json.dump(rows, open("/tmp/out/judge_rows.json", "w"), indent=2)
224
+ try:
225
+ from huggingface_hub import HfApi
226
+ api = HfApi()
227
+ for fn in ("results_v2.json", "judge_rows.json"):
228
+ api.upload_file(path_or_fileobj=f"/tmp/out/{fn}", path_in_repo=f"results_v2/{fn}",
229
+ repo_id=RESULT_REPO, repo_type="dataset")
230
+ print("[run] uploaded v2 results", flush=True)
231
+ except Exception as e:
232
+ print("[run] results upload skipped:", e, flush=True)
233
+
234
+ print("===CLAIM2_PROXY_V2_RESULT===", flush=True)
235
+ print(json.dumps(summary, indent=2), flush=True)
236
+ print("===END===", flush=True)
237
+
238
+ def selftest():
239
+ good = ('[{"i":0,"pass":true},{"i":1,"pass":false},{"i":2,"pass":true}]')
240
+ fenced = ('```json\n[{"i":0,"pass":false},{"i":1,"pass":true}]\n```')
241
+ bools = "[true, false, true]"
242
+ print("parse good:", parse_judgments(good, 3))
243
+ print("parse fenced:", parse_judgments(fenced, 2))
244
+ print("parse bools:", parse_judgments(bools, 3))
245
+ print("parse junk:", parse_judgments("the model refused", 2))
246
+ rows = [
247
+ {"id": "a", "category": "backend", "model": "base", "passes": [True, False]},
248
+ {"id": "a", "category": "backend", "model": "ft", "passes": [True, True]},
249
+ {"id": "a", "category": "frontend", "model": "base", "passes": [True, True, False]},
250
+ {"id": "a", "category": "frontend", "model": "ft", "passes": [True, False, False]},
251
+ ]
252
+ print("agg base:", _agg_passrate(rows, "base"))
253
+ print("agg ft:", _agg_passrate(rows, "ft"))
254
+ it = load_items()[0]
255
+ print("judge_prompt sample (first 240 chars):", judge_prompt("backend", "print('x')", it["backend_reqs"])[:240])
256
+ print("SELFTEST OK")
257
+
258
+ def main():
259
+ ap = argparse.ArgumentParser()
260
+ ap.add_argument("--selftest", action="store_true")
261
+ ap.add_argument("--generate", nargs=2, metavar=("MODEL", "OUTFILE"))
262
+ ap.add_argument("--judge", nargs=4, metavar=("MODEL", "BASE_GEN", "FT_GEN", "OUTFILE"))
263
+ ap.add_argument("--run", action="store_true")
264
+ a = ap.parse_args()
265
+ if a.selftest: selftest()
266
+ elif a.generate: generate(a.generate[0], a.generate[1])
267
+ elif a.judge: judge(a.judge[0], a.judge[1], a.judge[2], a.judge[3])
268
+ else: run()
269
+
270
+ if __name__ == "__main__":
271
+ main()