Download src/eval_prob.py from Ziruibest/jspace-unlearning: direct link, hf CLI and curl.
- Browser
- Download file 4.87 kB
-
https://huggingface.co/datasets/Ziruibest/jspace-unlearning/resolve/main/src/eval_prob.py
- Command line
-
hf download hf://datasets/Ziruibest/jspace-unlearning/src/eval_prob.py
-
curl -L -o eval_prob.py https://huggingface.co/datasets/Ziruibest/jspace-unlearning/resolve/main/src/eval_prob.py
4.87 kB
| """Fast per-question evaluator for H2 revival curves. | |
| For every forget10 question: teacher-forced answer probability | |
| (exp(-avg_token_loss), same construction as OpenUnlearning's | |
| forget_Q_A_Prob — parity-checked against their TOFU_EVAL.json), plus the | |
| free-energy signal logsumexp(logits) at the last prompt position. | |
| Optional --rouge: greedy generation (max_new_tokens=200) + ROUGE-L recall. | |
| Output json: {"prob": {idx: p}, "energy": {idx: e}, "rouge": {idx: r}?} | |
| Usage: python eval_prob.py --model_dir M --out out.json [--rouge] [--indices 0,1,...] | |
| """ | |
| import argparse | |
| import json | |
| import torch | |
| import transformers | |
| SYSTEM_PROMPT = "You are a helpful assistant." | |
| DATE_STRING = "10 Apr 2025" | |
| def build_rows(): | |
| from datasets import load_dataset | |
| ds = load_dataset("locuslab/TOFU", "forget10")["train"] | |
| return [(i, ds[i]["question"], ds[i]["answer"]) for i in range(len(ds))] | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--model_dir", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--rouge", action="store_true") | |
| ap.add_argument("--indices", default=None, help="comma list; default all 400") | |
| ap.add_argument("--batch", type=int, default=16) | |
| args = ap.parse_args() | |
| tok = transformers.AutoTokenizer.from_pretrained(args.model_dir) | |
| tok.padding_side = "right" | |
| if tok.pad_token is None: | |
| tok.pad_token = tok.eos_token | |
| hf = transformers.AutoModelForCausalLM.from_pretrained( | |
| args.model_dir, dtype=torch.bfloat16 | |
| ).cuda() | |
| hf.eval() | |
| rows = build_rows() | |
| if args.indices: | |
| keep = {int(x) for x in args.indices.split(",")} | |
| rows = [r for r in rows if r[0] in keep] | |
| def encode(question, answer): | |
| chat_sys = [{"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": question}] | |
| prompt_ids = tok.apply_chat_template( | |
| chat_sys, tokenize=True, add_generation_prompt=True, | |
| date_string=DATE_STRING)["input_ids"] | |
| full_ids = tok.apply_chat_template( | |
| chat_sys + [{"role": "assistant", "content": answer}], | |
| tokenize=True, add_generation_prompt=False, | |
| date_string=DATE_STRING)["input_ids"] | |
| return prompt_ids, full_ids | |
| prob, energy = {}, {} | |
| with torch.no_grad(): | |
| for b0 in range(0, len(rows), args.batch): | |
| chunk = rows[b0 : b0 + args.batch] | |
| enc = [encode(q, a) for _, q, a in chunk] | |
| maxlen = max(len(f) for _, f in enc) | |
| ids = torch.full((len(chunk), maxlen), tok.pad_token_id, dtype=torch.long) | |
| for j, (_, f) in enumerate(enc): | |
| ids[j, : len(f)] = torch.tensor(f) | |
| ids = ids.cuda() | |
| attn = (ids != tok.pad_token_id).long() | |
| logits = hf(ids, attention_mask=attn).logits.float() | |
| logprobs = torch.log_softmax(logits, dim=-1) | |
| for j, ((idx, _, _), (p_ids, f_ids)) in enumerate(zip(chunk, enc)): | |
| n_p, n_f = len(p_ids), len(f_ids) | |
| # answer tokens are positions n_p..n_f-1, predicted from n_p-1..n_f-2 | |
| tgt = torch.tensor(f_ids[n_p:], device="cuda") | |
| lp = logprobs[j, n_p - 1 : n_f - 1].gather(1, tgt[:, None]).squeeze(1) | |
| prob[idx] = float(torch.exp(lp.mean())) | |
| energy[idx] = float(torch.logsumexp(logits[j, n_p - 1], dim=-1)) | |
| out = {"prob": prob, "energy": energy} | |
| if args.rouge: | |
| from rouge_score import rouge_scorer | |
| scorer = rouge_scorer.RougeScorer(["rougeL"], use_stemmer=True) | |
| tok.padding_side = "left" | |
| rouge = {} | |
| with torch.no_grad(): | |
| for b0 in range(0, len(rows), args.batch): | |
| chunk = rows[b0 : b0 + args.batch] | |
| prompts = [ | |
| tok.apply_chat_template( | |
| [{"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": q}], | |
| tokenize=False, add_generation_prompt=True, | |
| date_string=DATE_STRING) | |
| for _, q, _ in chunk | |
| ] | |
| enc = tok(prompts, return_tensors="pt", padding=True, | |
| add_special_tokens=False).to("cuda") | |
| gen = hf.generate(**enc, max_new_tokens=200, do_sample=False, | |
| pad_token_id=tok.pad_token_id) | |
| for j, (idx, _, a) in enumerate(chunk): | |
| text = tok.decode(gen[j, enc["input_ids"].shape[1]:], | |
| skip_special_tokens=True) | |
| rouge[idx] = scorer.score(a, text)["rougeL"].recall | |
| out["rouge"] = rouge | |
| json.dump(out, open(args.out, "w")) | |
| print("saved", args.out, f"n={len(prob)}") | |
| if __name__ == "__main__": | |
| main() | |