# pip install torch==2.15.0 transformers==5.22.1 einops==0.8.2 ; git clone https://github.com/fstandhartinger/jevbenchimport inspect, itertools, json, string, sysimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizer M = sys.argv[1] if len(sys.argv) > 1 else "deshwalmahesh/d-edge-decision"JB = sys.argv[2] if len(sys.argv) > 2 else "jevbench/datasets/public"tok = AutoTokenizer.from_pretrained(M, trust_remote_code=True)tok.padding_side = "left"model = AutoModelForCausalLM.from_pretrained(M, trust_remote_code=True, dtype=torch.bfloat16).cuda().eval() def fp32(f): # run f with autocast off def g(*a, **k): with torch.autocast("cuda", enabled=False): return f(*a, **k) return g head = model.get_output_embeddings() # fp32 LM head + fp32 RoPE angleshead.register_forward_hook(fp32(lambda m, i, o: torch.nn.functional.linear(i[0].float(), m.weight.float())))for m in model.modules(): if "inv_freq" in m._buffers: m.forward = fp32(m.forward) PROMPT = ("Answer the question about the state with exactly one option code.\n\nState:\n{state}\n\nQuestion: {question}" "\n\nOptions:\n{options}\n\nReply with only the option code.")chat = lambda u: tok.apply_chat_template([{"role": "user", "content": u}], tokenize=False, add_generation_prompt=True, enable_thinking=False)tail, pre, codes = chat("x"), tok.encode(chat("x"), add_special_tokens=False), []for c in list(string.ascii_uppercase) + ["".join(p) for p in itertools.product(string.ascii_uppercase, repeat=2)]: ids = tok.encode(tail + c, add_special_tokens=False) # codes that are ONE token at the decision position if ids[:-1] == pre and ids[-1] not in [i for _, i in codes]: codes.append((c, ids[-1])) def item(r): # JevBench item -> (option texts, gold index) q, crit = r["question"], r["question"].get("criteria") if q["type"] == "noul": return ["yes", "no"], 0 if r["expected"] == "yes" else 1 if q["type"] == "score": return [str(c) for c in (crit or r["labels"])], int(r["expected"]) if isinstance(crit, dict): return [f"{k} — {v}" if v else str(k) for k, v in crit.items()], list(crit).index(r["expected"]) keys = [str(k) for k in (crit or r["labels"])] return keys, keys.index(r["expected"]) rows = []for tier in ("easy", "original", "hard"): for line in open(f"{JB}/{tier}.jsonl"): r = json.loads(line) if r.get("expected") is None or (r.get("provenance") or {}).get("exclude_reason"): continue opts, gold = item(r) st = r["state"] if isinstance(r["state"], str) else json.dumps(r["state"], ensure_ascii=False, sort_keys=True) lines = "\n".join(f"{codes[i][0]}: {t}" for i, t in enumerate(opts)) rows.append((tier, chat(PROMPT.format(state=st, question=r["question"]["instructions"], options=lines)), [codes[i][1] for i in range(len(opts))], gold)) pos = "position_ids" in inspect.signature(model.forward).parametershit = {t: [0, 0] for t in ("easy", "original", "hard")}with torch.no_grad(), torch.autocast("cuda", dtype=torch.bfloat16): for b in range(0, len(rows), 8): # batches of 8, left-padded batch = rows[b:b + 8] enc = tok([r[1] for r in batch], padding=True, return_tensors="pt").to("cuda") if pos: enc["position_ids"] = (enc["attention_mask"].cumsum(-1) - 1).clamp(min=0) logits = model(**enc, logits_to_keep=1, use_cache=False).logits[:, -1, :].float() for (tier, _, ids, gold), lg in zip(batch, logits): hit[tier][0] += int(lg[ids].argmax()) == gold hit[tier][1] += 1 n_ok, n = sum(h[0] for h in hit.values()), sum(h[1] for h in hit.values())chance = sum(1 / len(r[2]) for r in rows) / nI = 100 * (n_ok / n - chance) / (1 - chance)print({t: f"{a}/{b}" for t, (a, b) in hit.items()}, f"all {n_ok}/{n} = {n_ok / n:.3f}")print(f"Intelligence {I:.2f} Composite {3 / (1 / I + 1 / 92.61 + 1 / 60.30):.2f} (Speed 92.61, Cost 60.30: board 4B row)")