"""HumanEval + MBPP pass@k (user 11-28: "can you do humaneval and mbpp at pass@10 or 20"). n samples per problem (default 20) at temperature 0.8 / top-p 0.95 (the Codex paper's setting for pass@k with k > 1), then pass@1, pass@10 and pass@20 with the unbiased estimator 1 - C(n-c, k) / C(n, k) (Chen et al. 2021). Everything else is code_eval.py's: the same prompts (BOS + prompt), stop strings, trimming of cut-off answers, sandboxed test runs (guard + job object, 10 s, 1 GB) and "clean" subsets (decontaminated problems). Identical programs run once. GPU by default (continuous batching over the KV cache, like code_eval.generate but sampled): pause training first. Usage: python passk_eval.py [path=runs/ctx32k_1b/model.pt] [n=20] [temp=0.8] [top_p=0.95] [sets=humaneval,mbpp] [batch=96] [max_new=384] [limit=0] [device=cuda] [threads=6] [seed=1] [out_dir=] Output: /passk_eval/.jsonl (every sample), /passk_eval.jsonl (one summary line per run). """ import json, math, os, shutil, sys, tempfile, time from concurrent.futures import ThreadPoolExecutor _cvd = os.environ.get("CUDA_VISIBLE_DEVICES") import code_eval as ce # (hides the GPU at import: restored below, before CUDA is first touched) if _cvd is None: os.environ.pop("CUDA_VISIBLE_DEVICES", None) else: os.environ["CUDA_VISIBLE_DEVICES"] = _cvd import torch import kvdecode as kv from model import BOS_ID def pass_at_k(n, c, k): if n - c < k: return 1.0 return 1.0 - math.comb(n - c, k) / math.comb(n, k) @torch.no_grad() def sample_all(model, tok, probs, n, max_new, batch, temp, top_p, device, seed): """n sampled continuations per prompt, cut at the set's first stop string. Returns {(i, j): (text, n_tokens)}.""" prompts = [[BOS_ID] + tok.encode(p).ids for _, _, p, _ in probs] jobs = [(i, j) for i in range(len(probs)) for j in range(n)][::-1] B = min(batch, len(jobs)) cache = kv.Cache(model, B, max(map(len, prompts)) + max_new + 1, device) g = torch.Generator(device=device).manual_seed(seed) out, slot = {}, [None] * B feed = torch.zeros(B, dtype=torch.long, device=device) ac = lambda: torch.autocast(device.type, dtype=torch.bfloat16) def pick(logits): # [R, V] -> [R] sampled ids p = torch.softmax(logits.float() / temp, -1) sp, si = p.sort(-1, descending=True) sp[(sp.cumsum(-1) - sp) > top_p] = 0 # keep the smallest set whose mass reaches top_p return si.gather(-1, torch.multinomial(sp, 1, generator=g)).squeeze(-1) def start(r): while jobs: i, j = jobs.pop() slot[r] = (i, j, []) cache.reset(r) with ac(): t = int(pick(kv.extend(model, cache, r, prompts[i])[None])[0]) if take(r, t): return slot[r] = None def take(r, t): """Row r produced t. True: the row goes on; False: its answer is recorded (the row is free).""" i, j, ids = slot[r] if t != BOS_ID: ids.append(t) if t != BOS_ID and len(ids) < max_new and not ce.stop_in_tail(tok, ids, ce.STOPS[probs[i][0]]): feed[r] = t return True text = tok.decode(ids) cut = ce.first_stop(text, ce.STOPS[probs[i][0]]) out[(i, j)] = (text if cut is None else text[:cut], len(ids)) return False for r in range(B): start(r) t0, shown = time.time(), 0 while any(s is not None for s in slot): active = torch.tensor([s is not None for s in slot], device=device) span = int(cache.len.max()) + 1 with ac(): nxt = pick(kv.step(model, cache, feed, active, span=span)).tolist() for r in range(B): if slot[r] is not None and not take(r, nxt[r]): start(r) if len(out) >= shown + 500: shown = len(out) el = time.time() - t0 print(f" {len(out)}/{len(probs) * n} samples ({el:.0f}s, ~{el / len(out) * (len(probs) * n - len(out)):.0f}s" f" to go)", flush=True) return out def main(): args = dict(a.split("=", 1) for a in sys.argv[1:]) path = args.get("path", "runs/ctx32k_1b/model.pt") n, temp, top_p = int(args.get("n", 20)), float(args.get("temp", 0.8)), float(args.get("top_p", 0.95)) max_new, limit = int(args.get("max_new", 384)), int(args.get("limit", 0)) device = torch.device(args.get("device", "cuda")) torch.set_num_threads(int(args.get("threads", 6))) t0 = time.time() model, tok, step, tokens = ce.load_model(path) model.to(device) probs = ce.load_problems(args.get("sets", "humaneval,mbpp").split(","), limit) print(f"{len(probs)} problems x {n} samples (temp {temp}, top-p {top_p}) on {device}", flush=True) t1 = time.time() samples = sample_all(model, tok, probs, n, max_new, int(args.get("batch", 96)), temp, top_p, device, int(args.get("seed", 1))) gen_s = time.time() - t1 del model if device.type == "cuda": torch.cuda.empty_cache() # run every distinct program once (code_eval's sandbox) keys = sorted(samples) code = {k: ce.trim_to_valid(probs[k[0]][2], samples[k][0]) if samples[k][1] >= max_new else samples[k][0] for k in keys} programs = {} for k in keys: src = ce.GUARD + probs[k[0]][2] + code[k] + probs[k[0]][3] + f"print({ce.OK!r})\n" programs.setdefault(src, []).append(k) srcs = list(programs) print(f"{len(keys)} samples = {len(srcs)} distinct programs; running the tests", flush=True) t1 = time.time() workdir = tempfile.mkdtemp(prefix="passk_eval_") add_to_job = ce.job_object(1 << 30) try: with ThreadPoolExecutor(int(args.get("exec_threads", 6))) as pool: res = list(pool.map(lambda a: ce.run_program(a[1], workdir, f"p{a[0]}", add_to_job), enumerate(srcs))) finally: shutil.rmtree(workdir, ignore_errors=True) exec_s = time.time() - t1 result = {} for src, r in zip(srcs, res): for k in programs[src]: result[k] = r with open(ce.CONTAMINATED, encoding="utf-8") as f: cont = json.load(f) dirty, dirty2 = set(cont["tasks"]), set(cont["tasks"]) | set(cont.get("tasks_v2", [])) run_dir = args.get("out_dir") or os.path.dirname(path) tag = f"{os.path.splitext(os.path.basename(path))[0]}_n{n}_t{temp}" os.makedirs(os.path.join(run_dir, "passk_eval"), exist_ok=True) per = {} with open(os.path.join(run_dir, "passk_eval", tag + ".jsonl"), "w", encoding="utf-8") as f: for k in keys: kind, task = probs[k[0]][0], probs[k[0]][1] passed, status, err = result[k] per.setdefault((kind, task), []).append(passed) f.write(json.dumps(dict(set=kind, task=task, sample=k[1], passed=passed, status=status, error=err, tokens=samples[k][1], completion=samples[k][0])) + "\n") summary = {} for kind in dict.fromkeys(p[0] for p in probs): s = summary[kind] = {} for sub, excl in (("", set()), ("clean_", dirty), ("clean2_", dirty2)): cs = [sum(v) for (kd, t), v in per.items() if kd == kind and t not in excl] s[sub + "n"] = len(cs) for k in (1, 10, 20): if k <= n: s[f"{sub}pass@{k}"] = round(sum(pass_at_k(n, c, k) for c in cs) / max(len(cs), 1), 4) s["solved_by_any"] = sum(1 for (kd, _), v in per.items() if kd == kind and any(v)) line = dict(time=time.strftime("%Y-%m-%d %H:%M:%S"), path=path, tokens=tokens, n=n, temp=temp, top_p=top_p, max_new=max_new, limit=limit, gen_s=round(gen_s), exec_s=round(exec_s), programs=len(srcs), **summary) with open(os.path.join(run_dir, "passk_eval.jsonl"), "a", encoding="utf-8") as f: f.write(json.dumps(line) + "\n") for kind, s in summary.items(): ks = [k for k in (1, 10, 20) if k <= n] print(f"{kind:9s} " + " ".join(f"pass@{k} {100 * s[f'pass@{k}']:5.1f}%" for k in ks) + " clean2 " + " ".join(f"pass@{k} {100 * s[f'clean2_pass@{k}']:5.1f}%" for k in ks) + f" solved by any sample {s['solved_by_any']}/{s['n']}", flush=True) print(f"Done in {time.time() - t0:.0f}s (generation {gen_s:.0f}s, tests {exec_s:.0f}s): " f"{os.path.join(run_dir, 'passk_eval', tag + '.jsonl')}") if __name__ == "__main__": main()