interplane.Get Omega
Read in your language

gpu-head-to-head

aien-dev/gpu-head-to-head

Brought by drakestapleton

branch main Branches Tags History

gpu-head-to-head / q35-9b / tools / tie_check.py

49 lines · 3074 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Throwaway analysis (host tool): explain every greedy divergence against the HF transformers oracle.
3
4For each arm's agree output and each prompt: retokenize the arm's text, find the first token index k where it
5differs from the oracle's greedy ids, then run the oracle model on prompt + oracle_ids[:k] and read the logits
6at that position. Report the oracle's logit gap between its own token and the arm's token. A small gap means the
7two tokens were a near tie for the reference model too (a precision-level divergence); a large gap means the
8arm picked a token the reference model considers clearly worse (a bug signal).
9usage: tie_check.py MODEL ORACLE.jsonl OUT.jsonl ARM=raw.jsonl [ARM=raw.jsonl ...]
10"""
11import json, sys
12import torch
13from transformers import AutoTokenizer, Qwen3_5ForConditionalGeneration
14
15MODEL, ORACLE, OUT = sys.argv[1:4]
16arms = dict(a.split("=", 1) for a in sys.argv[4:])
17tok = AutoTokenizer.from_pretrained(MODEL)
18model = Qwen3_5ForConditionalGeneration.from_pretrained(MODEL, dtype=torch.bfloat16).to("cuda").eval()
19prompts = {json.loads(l)["id"]: json.loads(l)["text"]
20 for l in open("/home/drakestapleton/handoffs/HeadToHead/repo/prompts/decode.jsonl")}
21oracle = {r["prompt_id"]: r for r in map(json.loads, open(ORACLE))}
22
23with open(OUT, "w") as f:
24 for arm, path in arms.items():
25 rows = {}
26 for r in map(json.loads, open(path)):
27 if r.get("metric", "agree") == "agree" and not r.get("warmup") and not r.get("error"):
28 rows.setdefault(r["prompt_id"], r["text"])
29 for pid, text in sorted(rows.items()):
30 o = oracle[pid]["ids"]
31 a = tok(text, add_special_tokens=False)["input_ids"]
32 k = next((i for i in range(min(len(a), len(o))) if a[i] != o[i]), None)
33 rec = {"arm": arm, "prompt_id": pid, "oracle_len": len(o), "arm_len": len(a), "first_div": k}
34 if k is not None:
35 p = tok.apply_chat_template([{"role": "user", "content": prompts[pid]}], add_generation_prompt=True,
36 enable_thinking=False, return_tensors="pt", return_dict=True)
37 ids = torch.cat([p["input_ids"][0], torch.tensor(o[:k], dtype=torch.long)]).unsqueeze(0).to("cuda")
38 with torch.no_grad():
39 lg = model(input_ids=ids).logits[0, -1].float()
40 lp = torch.log_softmax(lg, -1)
41 top2 = torch.topk(lg, 2)
42 rec.update({"oracle_tok": o[k], "arm_tok": a[k],
43 "logit_gap": float(lg[o[k]] - lg[a[k]]),
44 "oracle_top1_top2_gap": float(top2.values[0] - top2.values[1]),
45 "arm_tok_rank": int((lg > lg[a[k]]).sum()),
46 "logprob_oracle_tok": float(lp[o[k]]), "logprob_arm_tok": float(lp[a[k]]),
47 "oracle_piece": tok.decode([o[k]]), "arm_piece": tok.decode([a[k]])})
48 f.write(json.dumps(rec) + "\n"); f.flush()
49 print(json.dumps(rec), flush=True)