Supra-microBench / evaluate.py
LH-Tech-AI's picture
Upload 2 files
2421ce3 verified
Raw History Blame Contribute Delete
26.5 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Supra-μBench — evaluation suite for very small base language models (<100M parameters).
Usage:
python evaluate.py --model_dir path/to/model
[--batch_size 16] [--device auto] [--dtype float32]
[--max_length 512] [--tasks 1a,4b] [--output results.json]
[--show_levels] [--trust_remote_code] [--list_tasks]
All tasks are scored purely via log-likelihood (no generation).
"""
import argparse
import importlib.util
import json
import math
import sys
import time
from collections import defaultdict
from pathlib import Path
import torch
import torch.nn.functional as F
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
from tasks import BENCHMARK_NAME, VERSION, DOMAINS, DOMAIN_WEIGHTS, build_tasks
DTYPES = {"float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16}
# ----------------------------------------------------------------------------
# Model wrapper
# ----------------------------------------------------------------------------
class _LogitsOut:
def __init__(self, logits):
self.logits = logits
class _CausalAdapter(torch.nn.Module):
"""Make a custom module look like a causal LM: forward(input_ids=...).logits."""
def __init__(self, inner, context):
super().__init__()
self.inner = inner
self.config = type("Cfg", (), {
"max_position_embeddings": context,
"n_positions": context,
"n_ctx": context,
"seq_length": context,
})()
def forward(self, input_ids=None, attention_mask=None, **kwargs):
ids = input_ids if input_ids is not None else kwargs.get("ids")
try:
out = self.inner(input_ids=ids, attention_mask=attention_mask)
except Exception:
try:
out = self.inner(ids)
except Exception:
out = self.inner(ids=ids)
if torch.is_tensor(out):
logits = out
elif isinstance(out, dict):
logits = out.get("logits", out.get("logit"))
if not torch.is_tensor(logits):
raise TypeError(f"forward dict has no logits/logit tensor, keys={list(out)}")
else:
logits = getattr(out, "logits", None)
if not torch.is_tensor(logits):
raise TypeError(f"unsupported forward return: {type(out)}")
return _LogitsOut(logits)
def _snapshot(model_dir):
path = Path(model_dir)
if path.is_dir():
return path
from huggingface_hub import snapshot_download
return Path(snapshot_download(model_dir))
def _import_py(repo, filename):
path = Path(repo) / filename
spec = importlib.util.spec_from_file_location(f"_supra_{path.stem}", path)
mod = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = mod # dataclasses looks the class up in sys.modules during class body
sys.path.insert(0, str(repo))
try:
spec.loader.exec_module(mod)
except Exception:
sys.modules.pop(spec.name, None)
raise
finally:
sys.path.pop(0)
return mod
def _load_state(model, repo):
names = ("model.safetensors", "pytorch_model.bin", "model.bin", "model.pt", "model.pth")
weight = next((Path(repo) / n for n in names if (Path(repo) / n).is_file()), None)
if weight is None:
cands = [p for p in Path(repo).iterdir()
if p.suffix in {".safetensors", ".bin", ".pt", ".pth"}
and "optim" not in p.name and "sched" not in p.name]
if len(cands) != 1:
raise FileNotFoundError(f"No unique weight file in {repo}: {cands}")
weight = cands[0]
if weight.suffix == ".safetensors":
from safetensors.torch import load_file
state = load_file(str(weight))
else:
state = torch.load(weight, map_location="cpu")
if isinstance(state, dict):
for key in ("state_dict", "model", "module"):
if key in state and isinstance(state[key], dict):
state = state[key]
break
# Strip a wrapper prefix only when every key has it (may be nested).
for prefix in ("module.", "_orig_mod.", "model."):
while state and all(k.startswith(prefix) for k in state):
state = {k[len(prefix):]: v for k, v in state.items()}
missing, unexpected = model.load_state_dict(state, strict=False)
if missing or unexpected:
print(f" weight load: missing={len(missing)} unexpected={len(unexpected)} (kept)")
return model
def _load_tokenizer(repo, trust_remote_code):
repo = Path(repo)
try:
return AutoTokenizer.from_pretrained(repo, trust_remote_code=trust_remote_code)
except Exception as exc:
tok_json = repo / "tokenizer.json"
if tok_json.is_file():
from tokenizers import Tokenizer
from transformers import PreTrainedTokenizerFast
return PreTrainedTokenizerFast(tokenizer_object=Tokenizer.from_file(str(tok_json)))
spm = repo / "tokenizer.model"
if spm.is_file():
from transformers import LlamaTokenizer
return LlamaTokenizer(vocab_file=str(spm), legacy=False)
vocab, merges = repo / "vocab.json", repo / "merges.txt"
if vocab.is_file() and merges.is_file():
from transformers import GPT2TokenizerFast
return GPT2TokenizerFast(vocab_file=str(vocab), merges_file=str(merges))
raise SystemExit(
f"No usable tokenizer in {repo} ({exc}). "
"Need tokenizer.json, tokenizer.model, or vocab.json+merges.txt."
) from exc
def _load_custom_repo(model_dir, dtype, trust_remote_code):
repo = _snapshot(model_dir)
cfg = json.loads((repo / "config.json").read_text(encoding="utf-8"))
if (repo / "model.py").is_file():
mod = _import_py(repo, "model.py")
if hasattr(mod, "WorkspaceConfig") and hasattr(mod, "RecurrentWorkspace"):
fields = {f.name for f in mod.WorkspaceConfig.__dataclass_fields__.values()}
kwargs = {k: v for k, v in cfg.items() if k in fields}
inner = mod.RecurrentWorkspace(mod.WorkspaceConfig(**kwargs))
context = int(getattr(inner.cfg, "context", cfg.get("context", 512)))
_load_state(inner, repo)
tok = _load_tokenizer(repo, trust_remote_code)
eos = cfg.get("eos_id", cfg.get("eos_token_id"))
if tok.eos_token_id is None and eos is not None:
tok.eos_token_id = int(eos)
if tok.pad_token_id is None and tok.eos_token_id is not None:
tok.pad_token_id = tok.eos_token_id
return tok, _CausalAdapter(inner, context)
for path in sorted(repo.glob("modeling_*.py")):
mod = _import_py(repo, path.name)
for obj in vars(mod).values():
if isinstance(obj, type) and hasattr(obj, "from_pretrained"):
model = obj.from_pretrained(repo, torch_dtype=dtype, trust_remote_code=True)
return _load_tokenizer(repo, trust_remote_code), model
raise ValueError(
f"{model_dir} is not a Transformers model (no model_type) and has no loadable "
"model.py (WorkspaceConfig/RecurrentWorkspace) or modeling_*.py."
)
def load_causal_lm(model_dir, dtype, trust_remote_code):
try:
AutoConfig.from_pretrained(model_dir, trust_remote_code=trust_remote_code)
tok = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=trust_remote_code)
model = AutoModelForCausalLM.from_pretrained(
model_dir, torch_dtype=dtype, trust_remote_code=trust_remote_code
)
return tok, model
except Exception as exc:
text = str(exc)
custom = "model_type" in text or "Unrecognized model" in text or "trust_remote_code" in text
if not trust_remote_code or not custom:
raise
print(f" standard HF load failed ({exc.__class__.__name__}). Loading custom repo code ...")
return _load_custom_repo(model_dir, dtype, trust_remote_code)
class LMScorer:
def __init__(self, model_dir, device, dtype, max_length, batch_size, trust_remote_code=False):
self.tokenizer, self.model = load_causal_lm(model_dir, dtype, trust_remote_code)
try:
self.model.to(device=device, dtype=dtype)
except Exception as exc:
print(f" model.to(dtype=...) failed ({exc.__class__.__name__}); casting floating parameters only")
self.model.to(device)
with torch.no_grad():
for p in self.model.parameters():
if p.is_floating_point() and p.dtype != dtype:
p.data = p.data.to(dtype=dtype)
self.model.eval()
self.device = device
self.batch_size = batch_size
# Every sequence starts with a prefix token (BOS, or EOS as fallback, like lm-eval).
prefix = self.tokenizer.bos_token_id
if prefix is None:
prefix = self.tokenizer.eos_token_id
if prefix is None:
raise ValueError("Tokenizer has neither a BOS nor an EOS token; cannot build a start prefix.")
self.prefix_id = prefix
model_max = None
for attr in ("max_position_embeddings", "n_positions", "n_ctx", "seq_length"):
v = getattr(self.model.config, attr, None)
if isinstance(v, int) and v > 0:
model_max = v
break
self.max_length = min(max_length, model_max) if model_max else max_length
self.n_params = sum(p.numel() for p in self.model.parameters())
self._cache = {}
# -- tokenization ---------------------------------------------------------
def _encode(self, text):
if not text:
return []
return self.tokenizer.encode(text, add_special_tokens=False)
@staticmethod
def _split_ws(context, continuation):
"""Move trailing whitespace of the context to the continuation (lm-eval convention)."""
n = len(context) - len(context.rstrip())
if n > 0:
continuation = context[-n:] + continuation
context = context[:-n]
return context, continuation
def _prepare(self, context, continuation):
context, continuation = self._split_ws(context, continuation)
if context:
whole = self._encode(context + continuation)
ctx = self._encode(context)
if whole[: len(ctx)] == ctx and len(whole) > len(ctx):
cont = whole[len(ctx):]
else: # tokenizer merged across the boundary -> fallback
cont = self._encode(continuation)
else:
ctx, cont = [], self._encode(continuation)
if not cont:
raise ValueError(f"Empty continuation for context {context!r}")
full = [self.prefix_id] + ctx + cont
if len(full) - 1 > self.max_length:
if len(cont) >= self.max_length:
raise ValueError("Continuation is longer than max_length.")
full = full[-(self.max_length + 1):] # left-truncate the context
return full, len(cont)
# -- scoring ---------------------------------------------------------------
@torch.inference_mode()
def loglikelihood(self, requests):
"""requests: list of (context, continuation) -> list of summed log-probs (nats)."""
unique = {}
for i, req in enumerate(requests):
unique.setdefault(req, []).append(i)
keys = [k for k in unique if k not in self._cache]
prepared = [self._prepare(c, x) for c, x in keys]
order = sorted(range(len(keys)), key=lambda j: -len(prepared[j][0]))
for b in range(0, len(order), self.batch_size):
idx = order[b: b + self.batch_size]
inputs = [prepared[j][0][:-1] for j in idx]
T = max(len(x) for x in inputs)
input_ids = torch.full((len(idx), T), self.prefix_id, dtype=torch.long)
attn = torch.zeros((len(idx), T), dtype=torch.long)
for r, x in enumerate(inputs):
input_ids[r, : len(x)] = torch.tensor(x, dtype=torch.long)
attn[r, : len(x)] = 1
def _store(row_logits, j):
full, n_cont = prepared[j]
L = len(full) - 1
lp = F.log_softmax(row_logits[L - n_cont: L].float(), dim=-1)
tgt = torch.tensor(full[-n_cont:], device=lp.device).unsqueeze(1)
self._cache[keys[j]] = lp.gather(1, tgt).sum().item()
try:
logits = self.model(input_ids=input_ids.to(self.device),
attention_mask=attn.to(self.device)).logits
for r, j in enumerate(idx):
_store(logits[r], j)
except Exception as exc:
print(f" batch forward failed ({exc.__class__.__name__}); retrying one sequence at a time")
for r, j in enumerate(idx):
one = torch.tensor([inputs[r]], device=self.device)
_store(self.model(input_ids=one).logits[0], j)
results = [None] * len(requests)
for req, idxs in unique.items():
for i in idxs:
results[i] = self._cache[req]
return results
@torch.inference_mode()
def rolling_loglikelihood(self, text):
"""Sliding-window log-likelihood of a full text (nats), stride = max_length / 2."""
seq = [self.prefix_id] + self._encode(text)
L = self.max_length
stride = max(1, L // 2)
total, s = 0.0, 1
while s < len(seq):
e = min(s + stride, len(seq))
start = max(0, e - L)
inp = torch.tensor([seq[start:e]], device=self.device)
logits = self.model(input_ids=inp).logits[0].float()
lp = F.log_softmax(logits[s - 1 - start: e - 1 - start], dim=-1)
tgt = torch.tensor(seq[s:e], device=self.device).unsqueeze(1)
total += lp.gather(1, tgt).sum().item()
s = e
return total
# ----------------------------------------------------------------------------
# Task evaluation
# ----------------------------------------------------------------------------
def _softmax_prob(scores, label):
m = max(scores)
exps = [math.exp(s - m) for s in scores]
return exps[label] / sum(exps)
def aggregate(records, metric):
if metric == "group_acc":
groups = defaultdict(list)
for i, r in enumerate(records):
# items without a group are scored as single units
groups[r["group"] if r["group"] is not None else f"__single_{i}"].append(r)
units = [{
"correct": all(x["correct"] for x in g),
"chance": math.prod(x["chance"] for x in g),
"p_correct": math.prod(x["p_correct"] for x in g),
"rr": sum(x["rr"] for x in g) / len(g),
"level": max(x["level"] for x in g),
} for g in groups.values()]
else:
units = records
n = len(units)
acc = sum(u["correct"] for u in units) / n
chance = sum(u["chance"] for u in units) / n
score = max(0.0, (acc - chance) / (1.0 - chance)) * 100.0
se_acc = math.sqrt(acc * (1.0 - acc) / n)
se_score = se_acc / (1.0 - chance) * 100.0
by_lvl = defaultdict(list)
for u in units:
by_lvl[u["level"]].append(u)
levels = {}
for lvl in sorted(by_lvl):
us = by_lvl[lvl]
levels[lvl] = {
"n": len(us),
"acc": sum(u["correct"] for u in us) / len(us),
"chance": sum(u["chance"] for u in us) / len(us),
}
return {
"kind": "choice", "n_items": len(records), "n_units": n,
"item_acc": sum(r["correct"] for r in records) / len(records),
"acc": acc, "chance": chance, "score": score, "se": se_score,
"p_correct": sum(u["p_correct"] for u in units) / n,
"mrr": sum(u["rr"] for u in units) / n,
"levels": levels,
}
def evaluate_choice_task(scorer, task, dump=None):
scoring = task["scoring"]
default_null = task.get("null_context", "Answer:")
requests, plan = [], []
for it in task["items"]:
entries = []
if "contexts" in it: # multi-context (partial scoring, Winograd style)
nb = len(it["continuation"].encode("utf-8"))
for ctx in it["contexts"]:
requests.append((ctx, it["continuation"]))
entries.append((len(requests) - 1, None, nb))
else:
for ch in it["choices"]:
requests.append((it.get("context", ""), ch))
ci, ni = len(requests) - 1, None
if scoring == "pmi":
requests.append((it.get("null_context", default_null), ch))
ni = len(requests) - 1
entries.append((ci, ni, len(ch.encode("utf-8"))))
plan.append(entries)
lls = scorer.loglikelihood(requests)
records = []
for it, entries in zip(task["items"], plan):
scores = []
for ci, ni, nb in entries:
ll = lls[ci]
if scoring == "sum":
scores.append(ll)
elif scoring == "mean_byte":
scores.append(ll / max(nb, 1))
elif scoring == "pmi":
scores.append(ll - lls[ni])
else:
raise ValueError(f"Unknown scoring: {scoring}")
label = it["label"]
pred = max(range(len(scores)), key=lambda k: scores[k])
rank = 1 + sum(1 for s in scores if s > scores[label])
# mean_byte scores are per byte -> rescale to sequence level, otherwise P(corr) is ~uniform
scale = sum(nb for _, _, nb in entries) / len(entries) if scoring == "mean_byte" else 1.0
records.append({
"level": it["level"],
"correct": pred == label,
"chance": 1.0 / len(scores),
"p_correct": _softmax_prob([s * scale for s in scores], label),
"rr": 1.0 / rank,
"group": it.get("group"),
})
if dump is not None:
dump.append({
"task": task["name"], "level": it["level"], "group": it.get("group"),
"context": it.get("context", it.get("contexts")),
"choices": it.get("choices", it.get("continuation")),
"scores": [round(s, 4) for s in scores], "label": label, "pred": pred,
"correct": pred == label,
})
return aggregate(records, task.get("metric", "acc"))
def evaluate_bpb_task(scorer, task):
total_ll, total_bytes, per_text = 0.0, 0, []
for text in task["texts"]:
ll = scorer.rolling_loglikelihood(text)
nb = len(text.encode("utf-8"))
total_ll += ll
total_bytes += nb
per_text.append(-ll / (math.log(2) * nb))
bpb = -total_ll / (math.log(2) * total_bytes)
lo, hi = task["anchors"]["floor"], task["anchors"]["ceiling"]
score = 100.0 * (math.log(lo) - math.log(bpb)) / (math.log(lo) - math.log(hi))
return {"kind": "bpb", "n_items": len(task["texts"]), "bpb": bpb,
"bpb_per_text": per_text, "score": min(100.0, max(0.0, score)), "se": 0.0}
# ----------------------------------------------------------------------------
# Index
# ----------------------------------------------------------------------------
def compute_index(tasks, results):
by_dom = defaultdict(list)
for t in tasks:
by_dom[t["domain"]].append(results[t["name"]])
dom_scores, dom_se = {}, {}
for d, rs in by_dom.items():
k = len(rs)
dom_scores[d] = sum(r["score"] for r in rs) / k
dom_se[d] = math.sqrt(sum(r["se"] ** 2 for r in rs)) / k
wsum = sum(DOMAIN_WEIGHTS[d] for d in dom_scores)
index = sum(DOMAIN_WEIGHTS[d] * s for d, s in dom_scores.items()) / wsum
index_se = math.sqrt(sum((DOMAIN_WEIGHTS[d] / wsum) ** 2 * dom_se[d] ** 2 for d in dom_scores))
return dom_scores, dom_se, index, index_se
# ----------------------------------------------------------------------------
# Reporting
# ----------------------------------------------------------------------------
def print_report(meta, tasks, results, dom_scores, dom_se, index, index_se, show_levels):
line = "=" * 96
print("\n" + line)
print(f"{BENCHMARK_NAME} v{VERSION}")
print(f"Model: {meta['model_dir']} | Params: {meta['n_params'] / 1e6:.1f}M | "
f"max_length: {meta['max_length']} | device: {meta['device']} | {meta['runtime_s']:.1f}s")
print(line)
print(f"{'Task':<32}{'Dom':<5}{'N':>5}{'Acc%':>8}{'Chance%':>9}{'NormAcc':>9}{'±SE':>7}"
f"{'P(corr)':>9}{'MRR':>7}")
print("-" * 96)
for t in tasks:
r = results[t["name"]]
if r["kind"] == "bpb":
print(f"{t['name']:<32}{t['domain']:<5}{r['n_items']:>5} BPB = {r['bpb']:.4f}"
f"{'':>6}{r['score']:>9.1f} (anchor-normalized)")
continue
print(f"{t['name']:<32}{t['domain']:<5}{r['n_units']:>5}{r['acc'] * 100:>8.1f}"
f"{r['chance'] * 100:>9.1f}{r['score']:>9.1f}{r['se']:>7.1f}"
f"{r['p_correct']:>9.3f}{r['mrr']:>7.3f}")
if show_levels:
lv = " ".join(f"L{l}: {v['acc'] * 100:.0f}% (n={v['n']}, c={v['chance'] * 100:.0f}%)"
for l, v in r["levels"].items())
print(f"{'':<6}{lv}")
print("-" * 96)
print("Domain scores (0-100, chance-normalized):")
for d in DOMAINS:
if d in dom_scores:
print(f" {d} {DOMAINS[d]:<34} w={DOMAIN_WEIGHTS[d]:.2f} "
f"{dom_scores[d]:6.1f} ± {dom_se[d]:.1f}")
print(line)
print(f" μBench-Intelligence-Index: {index:.2f} ± {index_se:.2f} (SE, item sampling)")
print(line)
print("Note: treat index differences < 2*sqrt(SE_a^2 + SE_b^2) as noise.\n")
# ----------------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------------
def resolve_device(arg):
if arg != "auto":
return torch.device(arg)
if torch.cuda.is_available():
return torch.device("cuda")
if getattr(torch.backends, "mps", None) is not None and torch.backends.mps.is_available():
return torch.device("mps")
return torch.device("cpu")
def parse_args():
p = argparse.ArgumentParser(description=f"{BENCHMARK_NAME} evaluation suite")
p.add_argument("--model_dir", help="Local model folder or Hugging Face model id (e.g. org/name); must include the tokenizer")
p.add_argument("--batch_size", type=int, default=16)
p.add_argument("--device", default="auto", help="auto | cpu | cuda | cuda:0 | mps")
p.add_argument("--dtype", default="float32", choices=list(DTYPES))
p.add_argument("--max_length", type=int, default=512)
p.add_argument("--tasks", default=None, help="Comma-separated task names or prefixes, e.g. '1a,4b'")
p.add_argument("--output", default=None, help="Write results as JSON to this path")
p.add_argument("--dump", default=None, help="Write per-item predictions as JSONL to this path")
p.add_argument("--show_levels", action="store_true", help="Print accuracy per difficulty level")
p.add_argument("--trust_remote_code", action="store_true",
help="Load custom modeling code (configuration_*.py, modeling_*.py) from a local folder or the HF Hub")
p.add_argument("--list_tasks", action="store_true", help="List tasks and exit")
return p.parse_args()
def main():
args = parse_args()
tasks = build_tasks()
if args.list_tasks:
for t in tasks:
n = len(t.get("items", t.get("texts", [])))
print(f"{t['name']:<32}{t['domain']:<5}{n:>4} {t['description']}")
return
if not args.model_dir:
raise SystemExit("--model_dir is required (local folder or HF model id).")
if args.tasks:
wanted = [w.strip() for w in args.tasks.split(",") if w.strip()]
tasks = [t for t in tasks if t["name"] in wanted or t["name"].split("_")[0] in wanted]
if not tasks:
raise SystemExit(f"No tasks match {wanted}.")
device = resolve_device(args.device)
print(f"Loading model from {args.model_dir} on {device} ({args.dtype}) ...")
scorer = LMScorer(args.model_dir, device, DTYPES[args.dtype], args.max_length,
args.batch_size, args.trust_remote_code)
results, t0 = {}, time.time()
dump_rows = [] if args.dump else None
for t in tasks:
ts = time.time()
if t.get("kind") == "bpb":
results[t["name"]] = evaluate_bpb_task(scorer, t)
else:
results[t["name"]] = evaluate_choice_task(scorer, t, dump_rows)
print(f" [{t['name']}] score={results[t['name']]['score']:.1f} ({time.time() - ts:.1f}s)")
dom_scores, dom_se, index, index_se = compute_index(tasks, results)
meta = {
"benchmark": BENCHMARK_NAME, "version": VERSION, "model_dir": args.model_dir,
"n_params": scorer.n_params, "max_length": scorer.max_length, "device": str(device),
"dtype": args.dtype, "runtime_s": time.time() - t0,
}
print_report(meta, tasks, results, dom_scores, dom_se, index, index_se, args.show_levels)
if args.output:
out = {
"meta": meta,
"tasks": {t["name"]: {"domain": t["domain"], "format": t["format"],
"scoring": t.get("scoring"), **results[t["name"]]} for t in tasks},
"domains": {d: {"name": DOMAINS[d], "weight": DOMAIN_WEIGHTS[d],
"score": dom_scores[d], "se": dom_se[d]} for d in dom_scores},
"mubench_intelligence_index": index,
"mubench_intelligence_index_se": index_se,
}
with open(args.output, "w", encoding="utf-8") as f:
json.dump(out, f, indent=2, ensure_ascii=False)
print(f"Results written to {args.output}")
if args.dump:
with open(args.dump, "w", encoding="utf-8") as f:
for row in dump_rows:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
print(f"Per-item predictions written to {args.dump}")
if __name__ == "__main__":
main()