Datasets:
Download code/score.py from drawais/circuitqa: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/score.py
- Command line
-
hf download hf://datasets/drawais/circuitqa/code/score.py
-
curl -L -o score.py https://huggingface.co/datasets/drawais/circuitqa/resolve/main/code/score.py
15 kB
| #!/usr/bin/env python3 | |
| """Shared scorer for CircuitQA. | |
| Takes raw model predictions and prints the metrics per category and overall. Pure standard library: no installs, so it | |
| runs identically on every lab machine. | |
| python score.py --pred preds/claude-opus-5.5.B.jsonl \ | |
| --ref corpus/eval_sample.jsonl \ | |
| --model "Claude Opus 5.5" --condition B | |
| Prediction file: one JSON object per line, {"question_hash": str, "prediction": str}. | |
| Every percentage is printed next to the integer count it came from (k/n), so any | |
| row in the final table can be audited. A percentage that is not k/n*100 for | |
| integer k did not come from this script. | |
| python score.py --verify-csv results_template_per_category.csv | |
| checks a filled-in table for exactly that. | |
| """ | |
| import argparse, json, math, re, sys, collections, hashlib, os | |
| CATS = ["structural_analysis","design_quality","functional_behavior", | |
| "code_understanding","optimization","cross_stage"] | |
| # ---------------------------------------------------------------- normalisation | |
| UNITS = [ | |
| (r'\bnanoseconds?\b|\bnsec\b', 'ns'), (r'\bpicoseconds?\b|\bpsec\b', 'ps'), | |
| (r'\bmicroseconds?\b|\busec\b', 'us'), (r'\bmilliseconds?\b|\bmsec\b', 'ms'), | |
| (r'\bmilliwatts?\b', 'mw'), (r'\bmicrowatts?\b', 'uw'), | |
| (r'\bnanowatts?\b', 'nw'), (r'\bwatts?\b', 'w'), | |
| (r'\bmegahertz\b', 'mhz'), (r'\bgigahertz\b', 'ghz'), (r'\bkilohertz\b', 'khz'), | |
| (r'\bsquare micrometer?s?\b|\bmicrometer\^?2\b|\bum\^?2\b|\bµm\^?2\b', 'um2'), | |
| (r'\bflip[- ]?flops?\b|\bffs?\b', 'ff'), | |
| (r'\bregisters?\b', 'reg'), (r'\bwires?\b', 'wire'), (r'\bparameters?\b', 'param'), | |
| (r'\bgates?\b', 'gate'), (r'\bcells?\b', 'cell'), | |
| ] | |
| def squash(s): | |
| """Lowercase, strip punctuation noise, collapse whitespace.""" | |
| s = (s or "").strip().lower() | |
| s = s.replace('−', '-').replace('µ', 'u') | |
| s = s.replace('²', '2').replace('³', '3') # um2 / um3 superscripts | |
| s = re.sub(r'[`*_"\']', '', s) | |
| s = re.sub(r'\s*=\s*', '=', s) # "a = b" -> "a=b" | |
| s = re.sub(r'\s*,\s*', ' ', s) # commas are not content | |
| s = re.sub(r'\band\b', '', s) # list conjunction | |
| s = re.sub(r'\s+', ' ', s) | |
| return s.strip(' .') | |
| def normalise(s): | |
| """squash + canonical units + canonical number formatting. | |
| Makes '2.5ns', '2.50 ns' and '2.5 nanoseconds' identical, and 0.0020 == 0.002. | |
| """ | |
| s = squash(s) | |
| for pat, rep in UNITS: | |
| s = re.sub(pat, rep, s) | |
| s = re.sub(r'(\d)\s+([a-z]{1,4}\d?)\b', r'\1\2', s) # "2.5 ns" -> "2.5ns" | |
| s = re.sub(r'(?<![\w.])(\d+\.?\d*)', lambda m: fmtnum(m.group(1)), s) | |
| s = re.sub(r'\s+', ' ', s) | |
| return s.strip(' .') | |
| def fmtnum(t): | |
| try: v = float(t) | |
| except ValueError: return t | |
| if v == int(v) and abs(v) < 1e15: return str(int(v)) | |
| return f"{v:.6f}".rstrip('0').rstrip('.') | |
| def numbers(s): | |
| return [float(x) for x in re.findall(r'-?\d+\.?\d*(?:[eE][-+]?\d+)?', s or "")] | |
| def toks(s): | |
| return re.findall(r'[a-z0-9_.\[\]:]+', normalise(s)) | |
| # ---------------------------------------------------------------------- metrics | |
| def num_match(pred, ref, rtol=1e-3): | |
| """Do the reference's numbers all appear in the prediction (within rtol)?""" | |
| rn, pn = numbers(ref), numbers(pred) | |
| if not rn: return None # no numeric content: not applicable | |
| for r in rn: | |
| if not any(abs(p - r) <= rtol * max(1.0, abs(r)) for p in pn): return False | |
| return True | |
| def f1(pred, ref): | |
| p, r = toks(pred), toks(ref) | |
| if not p or not r: return 0.0 | |
| common = collections.Counter(p) & collections.Counter(r) | |
| ov = sum(common.values()) | |
| if ov == 0: return 0.0 | |
| prec, rec = ov/len(p), ov/len(r) | |
| return 2*prec*rec/(prec+rec) | |
| def partial(pred, ref, thr=0.60): | |
| return f1(pred, ref) >= thr | |
| def bleu4(pred, ref): | |
| p, r = toks(pred), toks(ref) | |
| if not p: return 0.0 | |
| logs, nonzero = 0.0, 0 | |
| for n in (1,2,3,4): | |
| pg = collections.Counter(tuple(p[i:i+n]) for i in range(len(p)-n+1)) | |
| rg = collections.Counter(tuple(r[i:i+n]) for i in range(len(r)-n+1)) | |
| tot = sum(pg.values()) | |
| if tot == 0: continue | |
| clip = sum(min(c, rg[g]) for g, c in pg.items()) | |
| if clip == 0: return 0.0 | |
| logs += math.log(clip/tot); nonzero += 1 | |
| if nonzero == 0: return 0.0 | |
| bp = 1.0 if len(p) > len(r) else math.exp(1 - len(r)/max(1, len(p))) | |
| return 100 * bp * math.exp(logs/nonzero) | |
| def rouge_l(pred, ref): | |
| p, r = toks(pred), toks(ref) | |
| if not p or not r: return 0.0 | |
| dp = [[0]*(len(r)+1) for _ in range(len(p)+1)] | |
| for i in range(1, len(p)+1): | |
| for j in range(1, len(r)+1): | |
| dp[i][j] = dp[i-1][j-1]+1 if p[i-1]==r[j-1] else max(dp[i-1][j], dp[i][j-1]) | |
| l = dp[-1][-1] | |
| if l == 0: return 0.0 | |
| prec, rec = l/len(p), l/len(r) | |
| return 100 * 2*prec*rec/(prec+rec) | |
| STOP = set("a an the is are was were of to in on at for with and or by from " | |
| "this that these those it its as be been has have had does do did " | |
| "module modules can could should would will shall may might".split()) | |
| def content_toks(s): | |
| """Content words of an answer: no stopwords, no pure punctuation.""" | |
| return [t for t in re.findall(r"[a-z0-9_.]+", squash(s)) if t not in STOP] | |
| def recall(pred, gold): | |
| """Fraction of the gold answer's content tokens present in the prediction. | |
| Verbose predictions are not penalised. This measures whether the model | |
| said what the gold answer says, not whether it said only that. | |
| """ | |
| g = content_toks(gold) | |
| if not g: return None | |
| p = set(content_toks(pred)) | |
| return sum(1 for t in g if t in p) / len(g) | |
| def slot_match(pred, gold, module): | |
| """Template-slot accuracy: every number in the gold answer, plus the module | |
| name, appears in the prediction. | |
| Gold answers in this corpus are a small set of fixed templates with the | |
| module name and a few numbers substituted in. Slot match asks whether the | |
| model recovered those substituted values -- the part that carries the | |
| information -- and ignores the template wording, which exact match scores | |
| and which no model can guess without having been trained on the generator. | |
| """ | |
| gn = numbers(gold) | |
| if not gn: return None | |
| pn = numbers(pred) | |
| if not all(x in pn for x in gn): return False | |
| if module and squash(module) not in squash(pred): return False | |
| return True | |
| def wilson(k, n, z=1.96): | |
| if n == 0: return (0.0, 0.0) | |
| ph = k/n; d = 1 + z*z/n | |
| c = (ph + z*z/(2*n))/d | |
| h = z*math.sqrt(ph*(1-ph)/n + z*z/(4*n*n))/d | |
| return (100*max(0, c-h), 100*min(1, c+h)) | |
| # ------------------------------------------------------------------------- main | |
| def score(pred_path, ref_path, model, condition, out_json=None, bitvec=None): | |
| ref = {} | |
| for line in open(ref_path): | |
| d = json.loads(line); ref[d["question_hash"]] = d | |
| sha = hashlib.sha256(open(ref_path,'rb').read()).hexdigest() | |
| preds, dup = {}, 0 | |
| for ln, line in enumerate(open(pred_path), 1): | |
| line = line.strip() | |
| if not line: continue | |
| try: d = json.loads(line) | |
| except json.JSONDecodeError: | |
| sys.exit(f"FATAL {pred_path}:{ln}: not valid JSON") | |
| h = d.get("question_hash") | |
| if h is None: sys.exit(f"FATAL {pred_path}:{ln}: missing question_hash") | |
| if h in preds: dup += 1 | |
| preds[h] = d.get("prediction", "") | |
| missing = set(ref) - set(preds) | |
| extra = set(preds) - set(ref) | |
| print(f"reference : {ref_path}") | |
| print(f" {len(ref)} samples, sha256 {sha[:16]}…") | |
| print(f"prediction: {pred_path}") | |
| print(f" {len(preds)} unique hashes, {dup} duplicate lines") | |
| if extra: print(f" WARNING {len(extra)} predictions not in the reference (ignored)") | |
| if missing: | |
| print(f" WARNING {len(missing)} reference samples have NO prediction.") | |
| print(f" Scored as incorrect. Rerun those before reporting.") | |
| print() | |
| per = {c: collections.defaultdict(int) for c in CATS} | |
| agg = collections.defaultdict(float) | |
| correct = {} | |
| nall = 0 | |
| for h, r in ref.items(): | |
| cat, gold = r["category"], r["answer"] | |
| p = preds.get(h, "") | |
| per[cat]["n"] += 1; nall += 1 | |
| ok = squash(p) == squash(gold) | |
| correct[h] = ok | |
| if ok: per[cat]["em_strict"] += 1 | |
| if normalise(p) == normalise(gold): per[cat]["em_norm"] += 1 | |
| if partial(p, gold): per[cat]["partial"] += 1 | |
| nm = num_match(p, gold) | |
| if nm is not None: | |
| per[cat]["num_n"] += 1 | |
| if nm: per[cat]["num_ok"] += 1 | |
| sm = slot_match(p, gold, r.get("module_name", "")) | |
| if sm is not None: | |
| per[cat]["slot_n"] += 1 | |
| if sm: per[cat]["slot_ok"] += 1 | |
| rc = recall(p, gold) | |
| if rc is not None: | |
| per[cat]["rec_n"] += 1 | |
| per[cat]["rec_sum"] += rc | |
| if rc >= 0.8: per[cat]["rec80"] += 1 | |
| agg["bleu"] += bleu4(p, gold); agg["rouge"] += rouge_l(p, gold); agg["f1"] += f1(p, gold) | |
| print("PRIMARY slot = every gold number + the module name present in the prediction") | |
| print(" rec80 = >=80% of the gold answer's content words present") | |
| print("SECONDARY EM = byte-identical after normalisation; scores template wording,") | |
| print(" not content, and reads ~0 for any model not trained on the generator") | |
| print() | |
| print(f"{'category':22s} {'n':>4} {'slot':>14} {'rec80':>14} {'mean rec':>9} {'EM':>14}") | |
| macro_s = macro_n = 0.0; micro_s = micro_n = 0; present = 0 | |
| for c in CATS: | |
| n = per[c]["n"] | |
| if not n: continue | |
| present += 1 | |
| ks, kn = per[c]["em_strict"], per[c]["em_norm"] | |
| lo, hi = wilson(ks, n) | |
| sn, sk = per[c]["slot_n"], per[c]["slot_ok"] | |
| rn, r8 = per[c]["rec_n"], per[c]["rec80"] | |
| mrec = per[c]["rec_sum"]/rn if rn else 0.0 | |
| slo, shi = wilson(sk, sn) if sn else (0.0, 0.0) | |
| print(f"{c:22s} {n:>4} " | |
| f"{(f'{sk:>3}/{sn:<3} {100*sk/sn:5.1f}%' if sn else ' n/a '):>14} " | |
| f"{(f'{r8:>3}/{rn:<3} {100*r8/rn:5.1f}%' if rn else ' n/a '):>14} " | |
| f"{100*mrec:8.1f}% " | |
| f"{ks:>3}/{n:<3} {100*ks/n:5.1f}%" | |
| f" slot95[{slo:.0f}, {shi:.0f}]") | |
| macro_s += 100*ks/n; macro_n += 100*kn/n | |
| micro_s += ks; micro_n += kn | |
| agg["slot_n"] += sn; agg["slot_ok"] += sk | |
| agg["rec_n"] += rn; agg["rec80"] += r8; agg["rec_sum"] += per[c]["rec_sum"] | |
| lo, hi = wilson(micro_s, nall) | |
| print() | |
| print(f"MACRO avg EM strict {macro_s/present:5.2f}% EM normalised {macro_n/present:5.2f}%") | |
| print(f"MICRO avg EM strict {micro_s}/{nall} = {100*micro_s/nall:5.2f}% [95% CI {lo:.1f}, {hi:.1f}]") | |
| print(f" EM normalised {micro_n}/{nall} = {100*micro_n/nall:5.2f}%") | |
| SN, SK = int(agg["slot_n"]), int(agg["slot_ok"]) | |
| RN, R8 = int(agg["rec_n"]), int(agg["rec80"]) | |
| if SN: | |
| lo2, hi2 = wilson(SK, SN) | |
| print(f"SLOT micro {SK}/{SN} = {100*SK/SN:5.2f}% [95% CI {lo2:.1f}, {hi2:.1f}]" | |
| f" ({nall-SN} samples have no numeric slot)") | |
| if RN: | |
| print(f"REC80 micro {R8}/{RN} = {100*R8/RN:5.2f}% mean content recall " | |
| f"{100*agg['rec_sum']/RN:5.2f}%") | |
| print(f"BLEU-4 {agg['bleu']/nall:5.2f} ROUGE-L {agg['rouge']/nall:5.2f} F1 {100*agg['f1']/nall:5.2f}") | |
| print() | |
| print("paste into results_template_per_category.csv:") | |
| cells = ",".join(f"{100*per[c]['em_strict']/per[c]['n']:.1f}" if per[c]['n'] else "" for c in CATS) | |
| print(f" {model},{condition},{cells},{macro_s/present:.2f},{100*micro_s/nall:.2f}") | |
| if bitvec: | |
| # Per-sample correctness only. Contains no model output, no Verilog and | |
| # no question text -- one bit per evaluation sample, in sorted | |
| # question_hash order. Enough to recompute every number above and to run | |
| # McNemar between systems; not enough to reconstruct a prediction. | |
| order = sorted(ref) | |
| bits = "".join("1" if correct.get(h) else "0" for h in order) | |
| osha = hashlib.sha256("\n".join(order).encode()).hexdigest() | |
| with open(bitvec, "w") as f: | |
| f.write(f"# model {model}\n") | |
| f.write(f"# condition {condition}\n") | |
| f.write(f"# ref_sha256 {sha}\n") | |
| f.write(f"# order_sha256 {osha}\n") | |
| f.write(f"# n {len(order)} correct {bits.count('1')}\n") | |
| f.write(bits + "\n") | |
| print(f"wrote {bitvec} ({bits.count('1')}/{len(order)} correct)") | |
| if out_json: | |
| json.dump({"model":model,"condition":condition,"ref_sha256":sha, | |
| "n":nall,"missing":len(missing),"duplicates":dup, | |
| "per_category":{c:dict(per[c]) for c in CATS}, | |
| "macro_em_strict":macro_s/present,"micro_em_strict":100*micro_s/nall, | |
| "macro_em_norm":macro_n/present,"micro_em_norm":100*micro_n/nall, | |
| "bleu4":agg['bleu']/nall,"rouge_l":agg['rouge']/nall,"f1":100*agg['f1']/nall}, | |
| open(out_json,"w"), indent=2) | |
| print(f"\nwrote {out_json}") | |
| def verify_csv(path): | |
| """Flag any cell that cannot be a count over the stated n.""" | |
| import csv | |
| rows = list(csv.DictReader(open(path))) | |
| if not rows: sys.exit("empty csv") | |
| hdr = {} | |
| for c in CATS: | |
| k = next((k for k in rows[0] if k.startswith(c)), None) | |
| if k: | |
| m = re.search(r'n=(\d+)', k); hdr[c] = (k, int(m.group(1)) if m else None) | |
| bad = 0; checked = 0 | |
| for r in rows: | |
| for c, (k, n) in hdr.items(): | |
| v = (r.get(k) or "").strip() | |
| if not v or n is None: continue | |
| checked += 1 | |
| kk = float(v)*n/100.0 | |
| if abs(kk-round(kk)) > 1e-6: | |
| bad += 1 | |
| print(f" IMPOSSIBLE row {r.get('row','?'):>3} {r.get('model','?')[:26]:26s}" | |
| f" {r.get('condition','?')} {c:22s} {v}% of n={n} -> {kk:.3f} correct") | |
| print(f"\nchecked {checked} cells, {bad} impossible.") | |
| print("A clean table reports 0. Anything else was not produced by score.py." if bad | |
| else "All cells are realisable as integer counts.") | |
| return 1 if bad else 0 | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--pred"); ap.add_argument("--ref", default="corpus/eval_sample.jsonl") | |
| ap.add_argument("--model", default="?"); ap.add_argument("--condition", default="?") | |
| ap.add_argument("--out-json"); ap.add_argument("--verify-csv") | |
| ap.add_argument("--bitvector", help="write per-sample 0/1 correctness (no model text)") | |
| a = ap.parse_args() | |
| if a.verify_csv: sys.exit(verify_csv(a.verify_csv)) | |
| if not a.pred: ap.error("--pred is required (or use --verify-csv)") | |
| score(a.pred, a.ref, a.model, a.condition, a.out_json, a.bitvector) | |