File size: 10,716 Bytes
0f42585
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c86f224
 
 
 
0f42585
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c86f224
0f42585
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python3
"""Claim 2 scaled proxy: base Qwen3-Coder-30B-A3B vs FullStack-Learn-LM-30B-A3B.

Prompts each model with ONLY the app instruction; scores the generated code
against HIDDEN requirements (frontend UI tasks, backend API tests, DB entities)
with a deterministic requirement-coverage + structural heuristic. This is a
PROXY (labeled toy): it is NOT the FullStack-Bench harness (no browser/DB tests,
no 480B judge). It probes the direction of Claim 2 on the real released weights.

Modes:
  --selftest                 score a stub codebase (no GPU / no vllm), print, exit
  --generate MODEL OUTFILE   load MODEL with vLLM, generate for all prompts -> OUTFILE
  --run                      (default) generate for BASE + FT via subprocesses, score,
                             write results, upload to the Hub, print summary
"""
import argparse, json, os, re, subprocess, sys, gc, time

# Slim base image has no nvcc/CUDA toolkit, so avoid FlashInfer JIT paths.
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")
RESULT_REPO = os.environ.get("RESULT_REPO", "sandeepbh/fullstack-claim2-proxy")
MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "4096"))
MAX_MODEL_LEN = int(os.environ.get("MAX_MODEL_LEN", "8192"))

def prompts_path():
    for p in (os.environ.get("PROMPTS"), "/work/prompts.jsonl",
              os.path.join(os.path.dirname(__file__), "prompts.jsonl")):
        if p and os.path.exists(p):
            return p
    raise FileNotFoundError("prompts.jsonl not found")

def load_items():
    return [json.loads(l) for l in open(prompts_path(), encoding="utf-8") if l.strip()]

# ---------------- scoring (deterministic) ----------------
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 displaying show shows return returns returning correct correctly correct functionality feature
features valid enter entering based all each its their such via able website web app application new using
request response api endpoint send sending button click clicking view details detail list add create update
delete remove select selecting different various can will has have""".split())

def toks(text):
    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)

def covered(req, hay):
    kw = toks(req)
    if not kw:
        return True
    hit = len(kw & hay)
    need = 2 if len(kw) >= 3 else 1
    return hit >= need

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)
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)
FRONTEND_PAT = re.compile(r"<!doctype|<html|<div|<form|<script|useState|reactdom|react|document\.(get|query)|addeventlistener|v-model|<template|<button|render\(", re.I)
WIRED_PAT = re.compile(r"fetch\(|axios|xmlhttprequest|\$\.ajax|/api/|http://|https://localhost|:\d{4}/", re.I)

def score_site(out, item):
    hay = toks(out)
    def cov(reqs):
        if not reqs:
            return None
        return sum(1 for r in reqs if covered(r, hay)) / len(reqs)
    fe = cov(item.get("frontend_reqs"))
    be = cov(item.get("backend_reqs"))
    db = cov(item.get("db_reqs"))
    sig = {
        "has_backend": bool(BACKEND_PAT.search(out or "")),
        "has_db": bool(DB_PAT.search(out or "")),
        "has_frontend": bool(FRONTEND_PAT.search(out or "")),
        "wired": bool(WIRED_PAT.search(out or "")),
    }
    parts = [x for x in (fe, be, db) if x is not None]
    overall = sum(parts) / len(parts) if parts else 0.0
    return {"id": item.get("id"), "frontend_cov": fe, "backend_cov": be, "db_cov": db,
            "overall_cov": overall, "gen_chars": len(out or ""), **sig}

def aggregate(rows):
    def mean(key):
        vals = [r[key] for r in rows if r.get(key) is not None]
        return round(sum(vals) / len(vals), 4) if vals else None
    def frac(key):
        return round(sum(1 for r in rows if r.get(key)) / len(rows), 4) if rows else 0.0
    return {
        "n_sites": len(rows),
        "frontend_cov": mean("frontend_cov"),
        "backend_cov": mean("backend_cov"),
        "db_cov": mean("db_cov"),
        "overall_cov": mean("overall_cov"),
        "pct_has_backend": frac("has_backend"),
        "pct_has_db": frac("has_db"),
        "pct_has_frontend": frac("has_frontend"),
        "pct_wired": frac("wired"),
    }

# ---------------- generation (vLLM) ----------------
def build_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. Do not omit layers.\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 = []
    for it in items:
        msgs = [{"role": "user", "content": build_prompt(it["instruction"])}]
        prompts.append(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True))
    llm = LLM(model=model_id, dtype="bfloat16", trust_remote_code=True,
              gpu_memory_utilization=0.90, max_model_len=MAX_MODEL_LEN, enforce_eager=True)
    sp = SamplingParams(temperature=0.0, max_tokens=MAX_TOKENS)
    t0 = time.time()
    outs = llm.generate(prompts, sp)
    dt = time.time() - t0
    res = [{"id": items[i]["id"], "output": outs[i].outputs[0].text} for i in range(len(items))]
    with open(outfile, "w", encoding="utf-8") as f:
        for r in res:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    print(f"[generate] {model_id}: {len(res)} generations in {dt:.1f}s -> {outfile}", flush=True)

# ---------------- orchestration ----------------
def run():
    items = load_items()
    gens = {}
    for tag, mid in (("base", BASE_MODEL), ("ft", FT_MODEL)):
        outf = f"/tmp/gen_{tag}.jsonl"
        print(f"[run] generating with {tag} = {mid}", flush=True)
        subprocess.run([sys.executable, os.path.abspath(__file__), "--generate", mid, outf], check=True)
        gens[tag] = {json.loads(l)["id"]: json.loads(l)["output"]
                     for l in open(outf, encoding="utf-8") if l.strip()}
    per = {"base": [], "ft": []}
    for it in items:
        for tag in ("base", "ft"):
            per[tag].append(score_site(gens[tag].get(it["id"], ""), it))
    summary = {
        "experiment": "FullStack-Agent Claim 2 scaled proxy (requirement-coverage; NOT FullStack-Bench)",
        "base_model": BASE_MODEL, "ft_model": FT_MODEL,
        "n_sites": len(items), "max_tokens": MAX_TOKENS,
        "base": aggregate(per["base"]), "ft": aggregate(per["ft"]),
    }
    for k in ("frontend_cov", "backend_cov", "db_cov", "overall_cov"):
        b, f = summary["base"][k], summary["ft"][k]
        summary.setdefault("delta_ft_minus_base", {})[k] = round((f - b), 4) if (b is not None and f is not None) else None

    os.makedirs("/tmp/out", exist_ok=True)
    json.dump(summary, open("/tmp/out/results.json", "w"), indent=2)
    json.dump({"base": per["base"], "ft": per["ft"]}, open("/tmp/out/per_site.json", "w"), indent=2)
    for tag in ("base", "ft"):
        if os.path.exists(f"/tmp/gen_{tag}.jsonl"):
            os.replace(f"/tmp/gen_{tag}.jsonl", f"/tmp/out/gen_{tag}.jsonl")

    # upload artifacts to the Hub (best-effort)
    try:
        from huggingface_hub import HfApi
        api = HfApi()
        api.create_repo(RESULT_REPO, repo_type="dataset", exist_ok=True)
        for fn in ("results.json", "per_site.json", "gen_base.jsonl", "gen_ft.jsonl"):
            p = f"/tmp/out/{fn}"
            if os.path.exists(p):
                api.upload_file(path_or_fileobj=p, path_in_repo=f"results/{fn}",
                                repo_id=RESULT_REPO, repo_type="dataset")
        print(f"[run] uploaded artifacts to dataset {RESULT_REPO}/results/", flush=True)
    except Exception as e:
        print(f"[run] upload skipped: {e}", flush=True)

    print("===CLAIM2_PROXY_RESULT===", flush=True)
    print(json.dumps(summary, indent=2), flush=True)
    print("===END===", flush=True)

def selftest():
    stub_full = ("```python\nfrom flask import Flask, request, jsonify\napp = Flask(__name__)\n"
                 "import sqlalchemy\nclass Stock(db.Model):\n Column(name)\n"
                 "@app.route('/api/search')\ndef search(): return jsonify(stock information)\n```\n"
                 "```html\n<!DOCTYPE html><html><form><button>Search</button></form>"
                 "<script>fetch('/api/search')</script></html>\n```")
    stub_frontend_only = ("```html\n<!DOCTYPE html><html><div>Stock report</div>"
                          "<script>const x=1;</script></html>\n```")
    items = load_items()
    it = items[0]
    print("site:", it["id"], "| reqs fe/be/db =",
          len(it["frontend_reqs"]), len(it["backend_reqs"]), len(it["db_reqs"]))
    print("FULL-STACK stub score:", json.dumps(score_site(stub_full, it)))
    print("FRONTEND-ONLY stub score:", json.dumps(score_site(stub_frontend_only, it)))
    print("aggregate(full x3):", json.dumps(aggregate([score_site(stub_full, x) for x in items[:3]])))
    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("--run", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        selftest()
    elif a.generate:
        generate(a.generate[0], a.generate[1])
    else:
        run()

if __name__ == "__main__":
    main()