nnai-bench / benchmark.py
vynly's picture
Publish NNAI-Bench v0.1 and non-neural leaderboard
f3f832d verified
Raw History Blame Contribute Delete
17 kB
"""NNAI-Bench v0.1: deterministic synthetic tasks, scoring and CPU baselines.
Python 3.10+, standard library only. No CAEL dependencies or neural models.
"""
from __future__ import annotations
import argparse
from collections import Counter, defaultdict
import hashlib
import json
import math
from pathlib import Path
import random
import re
import time
VERSION = "nnai-bench-0.1"
ROOT = Path(__file__).resolve().parent
DATASET = ROOT / "dataset" if (ROOT / "dataset").is_dir() else ROOT
ARTIFACTS = ROOT / "space" if (ROOT / "space").is_dir() else ROOT
CATEGORIES = ("arithmetic", "logic", "ordering", "state_tracking", "strings", "tables")
LETTERS = "ABCD"
SPLITS = {"train": 100, "validation": 50, "test": 150}
def dump(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n")
def write_rows(path, rows):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows), encoding="utf-8", newline="\n")
def read_rows(path):
return [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]
def numeric_choices(answer, rng):
options = {str(answer)}
while len(options) < 4:
options.add(str(answer + rng.choice((-1, 1)) * rng.randint(1, 19)))
return sorted(options)
def make_task(category, tier, rng, tag):
"""Return a prompt, four distinct options, answer and independently auditable program."""
size = (3, 5, 8)[tier - 1]
if category == "arithmetic":
a, b, c = (rng.randint(3, 99) for _ in range(3))
if tier == 1:
answer, expression = a + b, f"{a} + {b}"
elif tier == 2:
answer, expression = a * b - c, f"({a} * {b}) - {c}"
else:
answer, expression = (a + b) * c - a, f"(({a} + {b}) * {c}) - {a}"
prompt = rng.choice((f"Calculate {expression}. What is the result?", f"Using standard arithmetic, evaluate {expression}."))
return prompt, numeric_choices(answer, rng), str(answer), {"expression": expression, "value": answer}
if category == "logic":
predicates = [f"kind_{tag}_{i}" for i in range(size + 2)]
entity = f"object_{tag}"
edges = list(zip(predicates[:size], predicates[1:size + 1]))
mode = rng.randrange(3)
target = predicates[size] if mode != 2 else predicates[-1]
facts = [f"{entity} is a {predicates[0]}."]
facts += [f"Every {a} is a {b}." for a, b in edges]
negatives = [target] if mode == 1 else []
if negatives:
# Make negative-only cases consistent: remove the final implication.
edges = edges[:-1]
facts = [facts[0]] + [f"Every {a} is a {b}." for a, b in edges]
facts.append(f"{entity} is not a {target}.")
rng.shuffle(facts)
answer = ("true", "false", "unknown")[mode]
prompt = "\n".join(facts) + f"\nUnder open-world logic, is '{entity} is a {target}' true, false, or unknown? No fact implies its converse."
return prompt, ["true", "false", "unknown", "inconsistent"], answer, {"start": predicates[0], "edges": edges, "negatives": negatives, "target": target}
if category == "ordering":
objects = [f"item_{tag}_{i}" for i in range(size + 1)]
order = rng.sample(objects, len(objects))
rules = [f"{a} comes before {b}." for a, b in zip(order, order[1:])]
rng.shuffle(rules)
if tier == 1:
index, question = 0, "Which item comes first?"
elif tier == 2:
index, question = len(order) - 1, "Which item comes last?"
else:
index = rng.randint(1, len(order) - 2)
question = f"Which item comes immediately after {order[index - 1]}?"
answer = order[index]
options = [answer] + rng.sample([x for x in order if x != answer], 3)
return "\n".join(rules + [question]), options, answer, {"order": order, "index": index}
if category == "state_tracking":
people = [f"person_{tag}_{i}" for i in range(4)]
rooms = [f"room_{tag}_{i}" for i in range(4)]
events = []
for person, room in zip(people, rng.sample(rooms, 4)):
events.append([person, room])
for _ in range(size * 2):
events.append([rng.choice(people), rng.choice(rooms)])
target = rng.choice(people)
state = {p: r for p, r in events}
prompt = "Events are listed from earliest to latest.\n" + "\n".join(f"{p} went to {r}." for p, r in events)
prompt += f"\nWhere is {target} now?"
return prompt, rooms, state[target], {"events": events, "target": target}
if category == "strings":
text = "".join(rng.choice("abcdefghjkmnpqrstuvwxyz") for _ in range(size + 2))
if tier == 1:
answer, operation = text[::-1], "reverse"
question = f'Reverse the string "{text}".'
elif tier == 2:
answer, operation = text[1::2], "even_positions"
question = f'From "{text}", keep characters at positions 2, 4, 6, and so on (1-based).'
else:
k = rng.randint(1, len(text) - 1)
answer, operation = (text[k:] + text[:k])[::-1], "rotate_reverse"
question = f'Rotate "{text}" left by {k} characters, then reverse the result.'
options = {answer, text, text[::-1], text[::2], text[1::2]}
while len(options) < 4:
options.add(text + rng.choice("xyz"))
options = [answer] + rng.sample(sorted(options - {answer}), 3)
return question, options, answer, {"text": text, "operation": operation, "k": k if tier == 3 else 0}
if category == "tables":
records = [{"item": f"row_{tag}_{i}", "group": rng.choice(("red", "blue")), "units": rng.randint(1, 40), "price": rng.randint(2, 20)} for i in range(size + 1)]
group = rng.choice(("red", "blue"))
selected = [r for r in records if r["group"] == group]
if tier == 1:
answer, operation = len(selected), "count"
question = f"How many rows have group {group}?"
elif tier == 2:
answer, operation = sum(r["units"] for r in selected), "sum"
question = f"What is the total units for group {group}?"
else:
answer, operation = sum(r["units"] * r["price"] for r in selected), "weighted_sum"
question = f"What is the sum of units * price for group {group}?"
table = "item | group | units | price\n" + "\n".join(f'{r["item"]} | {r["group"]} | {r["units"]} | {r["price"]}' for r in records)
return table + "\n" + question, numeric_choices(answer, rng), str(answer), {"records": records, "group": group, "operation": operation}
raise ValueError(category)
def audit_answer(category, program):
"""A separate ground-truth checker; never a model input or ranked solver."""
p = program
if category == "arithmetic":
# Only generator-owned numeric expressions; never evaluate submitted code.
import ast
import operator
operators = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul}
def calc(node):
if isinstance(node, ast.Constant) and type(node.value) is int:
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in operators:
return operators[type(node.op)](calc(node.left), calc(node.right))
raise ValueError("Unsupported expression")
return str(calc(ast.parse(p["expression"], mode="eval").body))
if category == "logic":
known = {p["start"]}
while True:
expanded = known | {b for a, b in p["edges"] if a in known}
if expanded == known:
break
known = expanded
pos, neg = p["target"] in known, p["target"] in p["negatives"]
return "inconsistent" if pos and neg else "true" if pos else "false" if neg else "unknown"
if category == "ordering":
return p["order"][p["index"]]
if category == "state_tracking":
return next(room for person, room in reversed(p["events"]) if person == p["target"])
if category == "strings":
text = p["text"]
if p["operation"] == "reverse":
return "".join(reversed(text))
if p["operation"] == "even_positions":
return "".join(c for i, c in enumerate(text, 1) if i % 2 == 0)
return "".join(reversed(text[p["k"]:] + text[:p["k"]]))
selected = [r for r in p["records"] if r["group"] == p["group"]]
if p["operation"] == "count":
return str(len(selected))
if p["operation"] == "sum":
return str(sum(r["units"] for r in selected))
return str(sum(r["units"] * r["price"] for r in selected))
def generate():
output = DATASET
seen = set()
audits = []
for split_index, (split, count) in enumerate(SPLITS.items()):
rng = random.Random(20261018 + split_index)
rows = []
for category in CATEGORIES:
positions = [(len(rows) + i) % 4 for i in range(count)]
rng.shuffle(positions)
for i in range(count):
tier = i % 3 + 1
while True:
tag = f"{split[0]}{rng.getrandbits(28):07x}"
prompt, choices, answer, program = make_task(category, tier, rng, tag)
if prompt not in seen:
seen.add(prompt)
break
assert answer == audit_answer(category, program)
wrong = sorted(set(choices) - {answer})
rng.shuffle(wrong)
label = positions[i]
wrong.insert(label, answer)
row = {"id": f"{split}-{category}-{i:04d}", "split": split, "category": category,
"difficulty": tier, "prompt": prompt, "choices": wrong, "answer": LETTERS[label]}
rows.append(row)
audits.append({"id": row["id"], "category": category, "program": program, "answer_text": answer})
rng.shuffle(rows)
write_rows(output / "data" / f"{split}.jsonl", rows)
questions = [{k: v for k, v in r.items() if k != "answer"} for r in rows]
write_rows(output / "questions" / f"{split}.jsonl", questions)
if split == "test" and (ROOT / "space").is_dir():
dump(ROOT / "space" / "test.json", rows)
write_rows(output / "audit.jsonl", audits)
checksums = {str(p.relative_to(output)).replace("\\", "/"): hashlib.sha256(p.read_bytes()).hexdigest()
for p in sorted(output.rglob("*.jsonl"))}
manifest = {"benchmark_version": VERSION, "seed": 20261018,
"split_sizes": {s: n * len(CATEGORIES) for s, n in SPLITS.items()},
"categories": list(CATEGORIES), "sha256": checksums}
dump(output / "manifest.json", manifest)
if (ROOT / "space").is_dir():
dump(ROOT / "space" / "manifest.json", manifest)
dump(output / "example_predictions.json", [{"id": r["id"], "prediction": "ABSTAIN"} for r in read_rows(output / "data/test.jsonl")])
print(json.dumps(manifest, indent=2))
def normalise_predictions(predictions, questions):
if not isinstance(predictions, list):
raise ValueError("Predictions must be a JSON array of {id, prediction} objects.")
expected = {r["id"] for r in questions}
got = {}
for row in predictions:
if not isinstance(row, dict) or set(row) != {"id", "prediction"}:
raise ValueError("Each prediction must contain exactly id and prediction.")
ident, pred = row["id"], row["prediction"]
if not isinstance(ident, str) or ident not in expected or ident in got:
raise ValueError(f"Unknown or duplicate ID: {ident!r}")
if not isinstance(pred, str) or pred not in (*LETTERS, "ABSTAIN"):
raise ValueError(f"Invalid prediction for {ident}; use A, B, C, D or ABSTAIN.")
got[ident] = pred
if set(got) != expected:
raise ValueError(f"Expected {len(expected)} unique IDs, received {len(got)}. Use ABSTAIN for unanswered items.")
return got
def score(predictions, questions):
got = normalise_predictions(predictions, questions)
counts = defaultdict(lambda: {"correct": 0, "answered": 0, "total": 0})
for row in questions:
c = counts[row["category"]]
c["total"] += 1
c["answered"] += got[row["id"]] != "ABSTAIN"
c["correct"] += got[row["id"]] == row["answer"]
categories = {k: {**v, "accuracy": 100 * v["correct"] / v["total"]} for k, v in sorted(counts.items())}
total = len(questions)
correct = sum(v["correct"] for v in counts.values())
answered = sum(v["answered"] for v in counts.values())
return {"benchmark_version": VERSION, "macro_accuracy": sum(v["accuracy"] for v in categories.values()) / len(categories),
"accuracy": 100 * correct / total, "coverage": 100 * answered / total,
"answered_accuracy": 100 * correct / answered if answered else 0,
"correct": correct, "total": total, "categories": categories}
def tokens(row):
return re.findall(r"[a-z]+|\d+", row["prompt"].lower())
def baseline_predictions(kind, train, test):
rng = random.Random(314159)
if kind == "seeded-random":
return [{"id": r["id"], "prediction": rng.choice(LETTERS)} for r in test]
if kind == "train-majority":
# Deterministic tie-break; no test labels or test-derived label frequencies.
counts = Counter(r["answer"] for r in train)
best = max(LETTERS, key=lambda x: (counts[x], -LETTERS.index(x)))
return [{"id": r["id"], "prediction": best} for r in test]
# Unigram BM25 nearest training prompt, returning the neighbour's answer letter.
# Deliberately simple retrieval baseline, without embeddings or test labels.
docs = [Counter(tokens(r)) for r in train]
df = Counter(t for d in docs for t in d)
average = sum(sum(d.values()) for d in docs) / len(docs)
index = defaultdict(list)
for i, d in enumerate(docs):
for term, tf in d.items():
idf = math.log(1 + (len(docs) - df[term] + .5) / (df[term] + .5))
weight = idf * tf * 2.5 / (tf + 1.5 * (.25 + .75 * sum(d.values()) / average))
index[term].append((i, weight))
predictions = []
for row in test:
values = defaultdict(float)
for term in sorted(set(tokens(row))):
for i, weight in index[term]:
values[i] += weight
best = max(values, key=lambda i: (values[i], -i)) if values else 0
predictions.append({"id": row["id"], "prediction": train[best]["answer"]})
return predictions
def baselines():
train = read_rows(DATASET / "data/train.jsonl")
labelled = read_rows(DATASET / "data/test.jsonl")
inputs = [{k: v for k, v in r.items() if k != "answer"} for r in labelled]
entries = []
for kind in ("seeded-random", "train-majority", "bm25-nearest-training"):
started = time.perf_counter()
predictions = baseline_predictions(kind, train, inputs)
elapsed = time.perf_counter() - started
report = score(predictions, labelled)
dump(ARTIFACTS / f"baselines/{kind}.predictions.json", predictions)
dump(ARTIFACTS / f"baselines/{kind}.report.json", report)
entries.append({"id": kind, "name": kind.replace("-", " ").title(), "kind": "baseline",
"status": "reproduced", "architecture": "BM25" if kind.startswith("bm25") else "statistical control",
"track": "closed-book", "training_provenance": "no neural assistance",
"source_url": "https://huggingface.co/datasets/vynly/nnai-bench/blob/main/benchmark.py",
"revision": VERSION, "runtime_seconds": round(elapsed, 5), "score": report})
dump(ARTIFACTS / "leaderboard.json", {"benchmark_version": VERSION, "entries": entries})
print(json.dumps([{r["name"]: r["score"]["macro_accuracy"]} for r in entries]))
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("generate")
sub.add_parser("baselines")
ev = sub.add_parser("score")
ev.add_argument("predictions")
ev.add_argument("--questions", default=str(DATASET / "data/test.jsonl"))
ev.add_argument("--output")
args = parser.parse_args()
if args.command == "generate":
generate()
elif args.command == "baselines":
baselines()
else:
report = score(json.loads(Path(args.predictions).read_text(encoding="utf-8")), read_rows(args.questions))
if args.output:
dump(args.output, report)
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()