File size: 4,672 Bytes
6da8440 | 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 | """Scores Bloxy (or the base model) on building + Roblox knowledge.
Building score : runs every prompt in eval/build_prompts.txt, extracts the Luau,
and checks that it compiles, uses Parts, and has a sane size.
Knowledge score: RobloxQA multiple-choice accuracy (held out, never trained on).
python scripts/evaluate.py --model runs/bloxy/lora # fine-tuned
python scripts/evaluate.py --model unsloth/gemma-4-12b-it # base, to compare
"""
from __future__ import annotations
import argparse
import json
import re
import shutil
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
import sys # noqa: E402
sys.path.insert(0, str(ROOT))
from bloxy_data.common import SYSTEM_PROMPT # noqa: E402
LUA = re.compile(r"```(?:lua|luau)\n(.*?)```", re.DOTALL)
def luau_ok(code: str, compiler: str | None):
if not compiler:
return None
with tempfile.NamedTemporaryFile("w", suffix=".luau", delete=False) as f:
f.write(code)
r = subprocess.run([compiler, "--null", f.name], capture_output=True, text=True)
Path(f.name).unlink(missing_ok=True)
return r.returncode == 0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", required=True)
ap.add_argument("--qa", default=str(ROOT / "out" / "robloxqa_test.jsonl"))
ap.add_argument("--qa_n", type=int, default=300)
ap.add_argument("--prompts", default=str(ROOT / "eval" / "build_prompts.txt"))
ap.add_argument("--luau", default=shutil.which("luau-compile"))
ap.add_argument("--out", default=str(ROOT / "runs" / "eval"))
args = ap.parse_args()
import torch
from unsloth import FastModel
model, tokenizer = FastModel.from_pretrained(args.model, max_seq_length=4096, load_in_4bit=True)
FastModel.for_inference(model)
model.config.use_cache = True
def ask(user: str, max_new: int) -> str:
msgs = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user}]
text = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
tok = getattr(tokenizer, "tokenizer", tokenizer)
ids = tok(text, return_tensors="pt", add_special_tokens=False).to(model.device)
with torch.no_grad():
out = model.generate(**ids, max_new_tokens=max_new, do_sample=False, use_cache=True)
return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True)
outdir = Path(args.out)
outdir.mkdir(parents=True, exist_ok=True)
# ---- building
prompts = [l.strip() for l in Path(args.prompts).read_text().splitlines() if l.strip() and not l.startswith("#")]
builds = []
for p in prompts:
ans = ask(p, 3000)
codes = LUA.findall(ans)
code = codes[0] if codes else ""
n_parts = len(re.findall(r'\bP\(|Instance\.new\("(?:Part|WedgePart|TrussPart)"', code))
builds.append({
"prompt": p, "has_code": bool(code), "compiles": luau_ok(code, args.luau) if code else False,
"parts": n_parts, "anchored": "Anchored" in code, "answer": ans,
})
print(f"[build] {p[:50]:50} code={bool(code)} compiles={builds[-1]['compiles']} parts={n_parts}")
(outdir / "builds.jsonl").write_text("\n".join(json.dumps(b) for b in builds))
for i, b in enumerate(builds): # paste-ready files for testing in Studio
for code in LUA.findall(b["answer"])[:1]:
(outdir / f"build_{i:02d}.luau").write_text(f"-- {b['prompt']}\n{code}")
# ---- knowledge
correct = total = 0
qa_path = Path(args.qa)
if qa_path.exists():
rows = [json.loads(l) for l in qa_path.read_text().splitlines()][: args.qa_n]
for r in rows:
opts = "\n".join(f"{'ABCD'[i]}. {c}" for i, c in enumerate(r["choices"]))
a = ask(f"{r['question']}\n\n{opts}\n\nAnswer with the letter only.", 8).strip().upper()
m = re.search(r"[ABCD]", a)
correct += bool(m and "ABCD".index(m.group(0)) == r["answer"])
total += 1
n = max(1, len(builds))
summary = {
"model": args.model,
"build_has_code": sum(b["has_code"] for b in builds) / n,
"build_compiles": (sum(bool(b["compiles"]) for b in builds) / n) if args.luau else "luau-compile not found",
"build_avg_parts": sum(b["parts"] for b in builds) / n,
"robloxqa_accuracy": round(correct / total, 3) if total else None,
"robloxqa_n": total,
}
(outdir / "summary.json").write_text(json.dumps(summary, indent=2))
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
|