Download scripts/eval_correct.py from tysgydke/Qwen3-4B-LoopIntervention: direct link, hf CLI and curl.
- Browser
- Download file 4.76 kB
-
https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/eval_correct.py
- Command line
-
hf download hf://tysgydke/Qwen3-4B-LoopIntervention/scripts/eval_correct.py
-
curl -L -o eval_correct.py https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/eval_correct.py
4.76 kB
| # 纠错率评测:给定"第一圈答案"(错或对),看续写能否修正/保持 | |
| # 提示形态与污染训练数据完全一致(裸补全格式): | |
| # {question}\n{first_ans}\n\nWait, let me double-check that.\n -> 贪心续写,提取末尾 #### 数字 | |
| # 两臂: | |
| # wrong 臂: first_ans 为扰动错误解 -> 纠错率 = 续写终值==gold 的比例(r1 结构上无优势,r2 应胜出) | |
| # right 臂: first_ans 为正确解 -> 保持率 = 终值不变的比例(防 PTSD:见答案就推翻) | |
| # 对照: --ckpt 可传 intervmix(污染训练前)与 pollute ckpt(训练后),以及 base(no-interv) | |
| import json, re, sys, time | |
| import torch | |
| import pandas as pd | |
| from build_pollute import corrupt_opflip, corrupt_final, FINAL | |
| from train_interv import LoopModel, TEST_PARQ | |
| CKPT = sys.argv[1] if len(sys.argv) > 1 else '/root/autodl-tmp/loop-exp/ckpt/intervmix_step4000.pt' | |
| MODE_R = int(sys.argv[2]) if len(sys.argv) > 2 else 2 | |
| N_PROBLEMS = int(sys.argv[3]) if len(sys.argv) > 3 else 60 | |
| CAP = int(sys.argv[4]) if len(sys.argv) > 4 else 400 | |
| NO_INTERV = len(sys.argv) > 5 and sys.argv[5] == 'base' | |
| CKPT_KEY = ('base' if NO_INTERV else | |
| (CKPT.split('/')[-1].replace('.pt', ''))) | |
| def gold_answer(a): | |
| m = re.search(r'####\s*([\d,\.\-]+)', a) | |
| return m.group(1).replace(',', '') if m else None | |
| def pred_answer(text): | |
| m = re.findall(r'####\s*(-?[\d,\.]+)', text) | |
| cands = [c for c in reversed(m)] if m else [] | |
| nums = re.findall(r'-?\d[\d,]*\.?\d*', text) | |
| if nums: | |
| cands.append(nums[-1]) | |
| for c in cands: | |
| c = c.replace(',', '').rstrip('.') | |
| try: | |
| float(c) | |
| return c | |
| except ValueError: | |
| continue | |
| return None | |
| def gen(lm, prompt, intervene): | |
| enc = lm.tok(prompt, return_tensors='pt').to('cuda') | |
| cur, m = enc['input_ids'], enc['attention_mask'] | |
| for _ in range(CAP): | |
| hs = lm.forward(cur, m, r=MODE_R, intervene=intervene, no_grad=True) | |
| nxt = lm.model.lm_head(hs[-1][:, -1:]).argmax(-1) | |
| cur = torch.cat([cur, nxt], 1) | |
| m = torch.cat([m, m.new_ones(1, 1)], 1) | |
| if nxt.item() == 198 and cur.shape[1] - enc['input_ids'].shape[1] > 32: | |
| out = lm.tok.decode(cur[0, enc['input_ids'].shape[1]:]) | |
| if out.count('####') >= 1: | |
| break | |
| return lm.tok.decode(cur[0, enc['input_ids'].shape[1]:]) | |
| def main(): | |
| import random | |
| random.seed(1) | |
| lm = LoopModel() | |
| if not NO_INTERV: | |
| sd = torch.load(CKPT, map_location='cuda', weights_only=False) | |
| lm.interv.load_state_dict(sd['sd']) | |
| print(f"loaded ckpt step={sd['step']}", flush=True) | |
| intervene = not NO_INTERV | |
| df = pd.read_parquet(TEST_PARQ) | |
| probs, wrong_firsts = [], [] | |
| for q, a in zip(df['question'][:N_PROBLEMS], df['answer'][:N_PROBLEMS]): | |
| a = a.strip() | |
| gold = gold_answer(a) | |
| if gold is None: | |
| continue | |
| bad = corrupt_opflip(a) or corrupt_final(a) | |
| if bad is None: | |
| continue | |
| wrong_ans, wv = bad | |
| if str(wv) == gold: | |
| continue | |
| probs.append((q.strip(), a, gold)) | |
| wrong_firsts.append(wrong_ans) | |
| results = {} | |
| for arm in ('wrong', 'right'): | |
| fixed, kept, n, t0 = 0, 0, 0, time.time() | |
| rows = [] | |
| for i, ((q, a, gold), wrong_ans) in enumerate(zip(probs, wrong_firsts)): | |
| first = wrong_ans if arm == 'wrong' else a | |
| prompt = f"{q}\n{first}\n\nWait, let me double-check that.\n" | |
| out = gen(lm, prompt, intervene) | |
| pred = pred_answer(out) | |
| ok = (pred is not None and abs(float(pred) - float(gold)) < 1e-4) | |
| if arm == 'wrong': | |
| fixed += ok | |
| else: | |
| kept += ok | |
| n += 1 | |
| rows.append({'i': i, 'arm': arm, 'pred': pred, 'gold': gold, | |
| 'ok': bool(ok), 'text': out}) | |
| if (i + 1) % 10 == 0: | |
| r = fixed / n if arm == 'wrong' else kept / n | |
| print(f'{arm}: {i+1}/{n} rate={r:.3f} ({(time.time()-t0)/n:.1f}s/题)', | |
| flush=True) | |
| rate = fixed / n if arm == 'wrong' else kept / n | |
| tag = f'corr_{CKPT_KEY}_r{MODE_R}_{arm}_n{n}' | |
| results[arm] = rate | |
| print(json.dumps({'final': tag, 'rate': rate, 'n': n}), flush=True) | |
| with open(f'/root/loop-exp/{tag}.jsonl', 'w') as f: | |
| for row in rows: | |
| f.write(json.dumps(row, ensure_ascii=False) + '\n') | |
| print(json.dumps({'summary': CKPT_KEY, 'r': MODE_R, 'n': len(probs), | |
| 'correction_rate': results['wrong'], | |
| 'keep_rate': results['right']}), flush=True) | |
| if __name__ == '__main__': | |
| main() | |