"""Our exact base-model tests on a Hugging Face model, for a fair peer column on the model card. CORE (core_eval.py), HumanEval + MBPP (code_eval.py: same prompts, stop strings, answer trimming, sandboxed test runs, "clean" subsets) and GSM8K (gsm8k_eval.py: same 8-shot prompt and answer extraction). Only the model and tokenizer differ, and each gets its own natural input format: CORE prefixes BOS for every model (its protocol); generation prompts are tokenized the way the model's own tokenizer does it (Granite adds no BOS); and code prompts lose their trailing whitespace (strip=1, as bigcode-evaluation-harness does), because StarCoder-style tokenizers merge " " with the next line's indentation: a prompt ending in a bare " " leaves such a model mid-token, and Granite then just emits EOS. Greedy decoding. Uses the GPU by default: pause training first (never two GPU jobs at once). Usage: python peer_eval.py model=ibm-granite/granite-3.0-1b-a400m-base [device=cuda] [sets=core,humaneval,mbpp,gsm8k] [limit=0] [core_max=-1] [core_tasks=a,b] [batch=32] [core_batch_tokens=8192] [dtype=bf16] Results: runs/peers//summary.json; every answer in runs/peers//{code_eval,gsm8k}.jsonl. """ import json, os, shutil, sys, tempfile, time from concurrent.futures import ThreadPoolExecutor _cvd = os.environ.get("CUDA_VISIBLE_DEVICES") import code_eval as ce # (a CPU tool: it hides the GPU at import; restored below, before CUDA is first touched) import gsm8k_eval as gs from core_eval import evaluate_core if _cvd is None: os.environ.pop("CUDA_VISIBLE_DEVICES", None) else: os.environ["CUDA_VISIBLE_DEVICES"] = _cvd import torch from transformers import AutoModelForCausalLM, AutoTokenizer @torch.no_grad() def generate(model, tok, probs, max_new, batch, device): """Greedy continuation of every prompt (one set per call), cut at the set's first stop string, like code_eval.generate. Batches of similar length, left-padded. Returns [(completion, n_tokens)].""" stops = ce.STOPS[probs[0][0]] assert all(p[0] == probs[0][0] for p in probs) eos = tok.eos_token_id pad = tok.pad_token_id if tok.pad_token_id is not None else eos # (SmolLM2, Qwen2.5 define no pad token) enc = [tok.encode(p) for _, _, p, _ in probs] # the tokenizer's own special tokens (none for Granite) order = sorted(range(len(probs)), key=lambda i: -len(enc[i])) # longest first: an out-of-memory shows up at once out, t0 = [None] * len(probs), time.time() for b0 in range(0, len(order), batch): idx = order[b0:b0 + batch] T = max(len(enc[i]) for i in idx) ids = torch.full((len(idx), T), pad, dtype=torch.long) mask = torch.zeros_like(ids) for r, i in enumerate(idx): ids[r, T - len(enc[i]):] = torch.tensor(enc[i]) mask[r, T - len(enc[i]):] = 1 g = model.generate(input_ids=ids.to(device), attention_mask=mask.to(device), max_new_tokens=max_new, do_sample=False, stop_strings=stops, tokenizer=tok, pad_token_id=pad, eos_token_id=eos) for r, i in enumerate(idx): new = g[r, T:].tolist() if eos in new: # stopped by itself (or padding after a stop string) new = new[:new.index(eos)] text = tok.decode(new, skip_special_tokens=True) cut = ce.first_stop(text, stops) n = len(new) if cut is not None: # tokens up to the one that completed the stop string (as code_eval counts them) lo, hi = 1, n while lo < hi: m = (lo + hi) // 2 if ce.first_stop(tok.decode(new[:m], skip_special_tokens=True), stops) is None: lo = m + 1 else: hi = m n = lo out[i] = (text if cut is None else text[:cut], n) print(f" {min(b0 + batch, len(order))}/{len(order)} answers ({time.time() - t0:.0f}s)", flush=True) return out def code_tests(probs, answers, max_new): """code_eval.py's scoring: trim cut-off answers, run each program against its tests, clean subsets.""" tested = [ce.trim_to_valid(p[2], c) if n >= max_new else c for p, (c, n) in zip(probs, answers)] workdir = tempfile.mkdtemp(prefix="peer_eval_") add_to_job = ce.job_object(1 << 30) try: def check(k): return ce.run_program(ce.GUARD + probs[k][2] + tested[k] + probs[k][3] + f"print({ce.OK!r})\n", workdir, f"p{k}", add_to_job) with ThreadPoolExecutor(4) as pool: results = list(pool.map(check, range(len(probs)))) finally: shutil.rmtree(workdir, ignore_errors=True) with open(ce.CONTAMINATED, encoding="utf-8") as f: cont = json.load(f) dirty = set(cont["tasks"]) dirty2 = dirty | set(cont.get("tasks_v2", [])) rows, summary = [], {} for (kind, task, prompt, _), (completion, n), code, (passed, status, err) in zip(probs, answers, tested, results): try: compile(prompt + code, task, "exec") valid = True except Exception: valid = False rows.append(dict(set=kind, task=task, passed=passed, valid=valid, status=status, error=err, tokens=n, trimmed=code != completion, completion=completion)) s = summary.setdefault(kind, dict(n=0, passed=0, valid=0, clean_n=0, clean_passed=0, clean2_n=0, clean2_passed=0)) s["n"] += 1 s["passed"] += passed s["valid"] += valid s["clean_n"] += task not in dirty s["clean_passed"] += passed and task not in dirty s["clean2_n"] += task not in dirty2 s["clean2_passed"] += passed and task not in dirty2 for s in summary.values(): s["pass@1"] = round(s["passed"] / s["n"], 4) s["clean_pass@1"] = round(s["clean_passed"] / max(s["clean_n"], 1), 4) s["clean2_pass@1"] = round(s["clean2_passed"] / max(s["clean2_n"], 1), 4) return rows, summary def main(): args = dict(a.split("=", 1) if "=" in a else (a, "1") for a in sys.argv[1:]) name = args.get("model", "ibm-granite/granite-3.0-1b-a400m-base") device = torch.device(args.get("device", "cuda")) sets = args.get("sets", "core,humaneval,mbpp,gsm8k").split(",") limit, batch = int(args.get("limit", 0)), int(args.get("batch", 32)) dtype = {"bf16": torch.bfloat16, "fp32": torch.float32}[args.get("dtype", "bf16")] if device.type == "cpu": torch.set_num_threads(int(args.get("threads", 4))) out_dir = os.path.join("runs", "peers", args.get("tag", name.split("/")[-1])) os.makedirs(out_dir, exist_ok=True) t0 = time.time() tok = AutoTokenizer.from_pretrained(name) model = AutoModelForCausalLM.from_pretrained(name, dtype=dtype).to(device).eval() n_params = sum(p.numel() for p in model.parameters()) print(f"Loaded {name} ({n_params / 1e9:.3f}B params, {dtype}) on {device} in {time.time() - t0:.0f}s", flush=True) summary = dict(time=time.strftime("%Y-%m-%d %H:%M:%S"), model=name, params=n_params, dtype=str(dtype), device=str(device), limit=limit, code_prompt_rstrip=bool(int(args.get("strip", 1)))) if "core" in sets: t1 = time.time() tasks = args["core_tasks"].split(",") if "core_tasks" in args else None res = evaluate_core(lambda ids: model(input_ids=ids).logits, lambda s: tok.encode(s, add_special_tokens=False), tok.bos_token_id if tok.bos_token_id is not None else tok.eos_token_id, device, max_per_task=int(args.get("core_max", -1)), max_len=2048, max_batch_tokens=int(args.get("core_batch_tokens", 8192)), tasks=tasks) summary.update(core=res["core"], core_results=res["results"], core_centered=res["centered"], core_max=int(args.get("core_max", -1)), core_s=round(time.time() - t1)) code_sets = [s for s in ("humaneval", "mbpp") if s in sets] if code_sets: max_new = int(args.get("max_new", 384)) probs, answers = [], [] t1 = time.time() for s in code_sets: p = ce.load_problems([s], limit) if int(args.get("strip", 1)): # the program tested is then prompt.rstrip() + completion + tests p = [(k, t, pr.rstrip(), tests) for k, t, pr, tests in p] print(f"{s}: {len(p)} problems", flush=True) answers += generate(model, tok, p, max_new, batch, device) probs += p gen_s = time.time() - t1 rows, code_summary = code_tests(probs, answers, max_new) with open(os.path.join(out_dir, "code_eval.jsonl"), "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r) + "\n") summary.update(code_summary) summary["code_gen_s"] = round(gen_s) for kind, s in code_summary.items(): print(f"{kind:9s} pass@1 {100 * s['pass@1']:5.1f}% ({s['passed']}/{s['n']}) clean " f"{100 * s['clean_pass@1']:5.1f}% clean2 {100 * s['clean2_pass@1']:5.1f}% valid Python " f"{100 * s['valid'] / s['n']:5.1f}%", flush=True) if "gsm8k" in sets: with open(gs.DATA, encoding="utf-8") as f: items = [json.loads(l) for l in f] items = items[:limit or None] probs = [("gsm8k", f"gsm8k/{i}", it["context"] + "\n\nA:", None) for i, it in enumerate(items)] t1 = time.time() answers = generate(model, tok, probs, int(args.get("gsm_max_new", 256)), batch, device) rows, correct = [], 0 for it, (_, task, _, _), (completion, n) in zip(items, probs, answers): pred, gold = gs.extract(completion), float(it["answer"].replace(",", "")) ok = pred is not None and abs(pred - gold) < 1e-6 correct += ok rows.append(dict(task=task, gold=gold, pred=pred, correct=ok, tokens=n, completion=completion)) with open(os.path.join(out_dir, "gsm8k.jsonl"), "w", encoding="utf-8") as f: for r in rows: f.write(json.dumps(r) + "\n") summary.update(gsm8k=dict(n=len(rows), correct=correct, accuracy=round(correct / len(rows), 4), answer_found=round(sum(r["pred"] is not None for r in rows) / len(rows), 4), gen_s=round(time.time() - t1))) print(f"gsm8k 8-shot CoT, greedy accuracy {100 * correct / len(rows):.1f}% ({correct}/{len(rows)})", flush=True) summary["total_s"] = round(time.time() - t0) with open(os.path.join(out_dir, "summary.json" if not limit else "summary_test.json"), "w", encoding="utf-8") as f: json.dump(summary, f, indent=1) print(f"Done in {summary['total_s']}s: {out_dir}", flush=True) if __name__ == "__main__": main()