Download scripts/eval_cont.py from tysgydke/Qwen3-4B-LoopIntervention: direct link, hf CLI and curl.
- Browser
- Download file 2.43 kB
-
https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/eval_cont.py
- Command line
-
hf download hf://tysgydke/Qwen3-4B-LoopIntervention/scripts/eval_cont.py
-
curl -L -o eval_cont.py https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/eval_cont.py
2.43 kB
| # 续写/通用文本测试:干预网络是否伤害通用生成质量 | |
| # (a) wikitext-2 test 前 100 篇有效文本的 CE:base / r1 / r2 | |
| # (b) 5 条中英提示各 greedy 续写 80 token,打印原文对比 | |
| import sys | |
| import torch | |
| import pandas as pd | |
| import train_interv | |
| from train_interv import LoopModel, batchify | |
| CKPT = sys.argv[1] if len(sys.argv) > 1 else '/root/autodl-tmp/loop-exp/ckpt/interv_step7500.pt' | |
| if len(sys.argv) > 2: | |
| train_interv.NVT = int(sys.argv[2]) | |
| if len(sys.argv) > 3: | |
| train_interv.RANK = int(sys.argv[3]) | |
| PROMPTS = [ | |
| 'The city of Paris is', | |
| 'Artificial intelligence will', | |
| 'In a small village by the sea,', | |
| '人工智能的发展', | |
| '春天的早晨,', | |
| ] | |
| def main(): | |
| lm = LoopModel() | |
| 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) | |
| df = pd.read_parquet('/root/autodl-tmp/data/wikitext/wt2-test.parquet') | |
| docs = [t.strip() for t in df['text']] | |
| docs = [t for t in docs if len(t) > 200 and not t.startswith('=')][:100] | |
| enc = [lm.tok(d, truncation=True, max_length=512)['input_ids'] for d in docs] | |
| for mode, r in (('base', 1), ('r1', 1), ('r2', 2)): | |
| intervene = mode != 'base' | |
| tot, n = 0.0, 0 | |
| for b0 in range(0, len(enc), 8): | |
| ids, mask = batchify(enc, b0, 8) | |
| hs = lm.forward(ids, mask, r=r, intervene=intervene, no_grad=True) | |
| tot += lm.ce(hs[-1], ids, mask).item(); n += 1 | |
| import math | |
| print(f'[CE] {mode}: ce={tot/n:.4f} ppl={math.exp(tot/n):.2f}', flush=True) | |
| for p in PROMPTS: | |
| print(f'\n===== PROMPT: {p} =====', flush=True) | |
| encp = lm.tok(p, return_tensors='pt').to('cuda') | |
| for mode, r in (('base', 1), ('r1', 1), ('r2', 2)): | |
| intervene = mode != 'base' | |
| cur, m = encp['input_ids'], encp['attention_mask'] | |
| for _ in range(80): | |
| hs = lm.forward(cur, m, r=r, intervene=intervene, no_grad=True) | |
| nxt = lm.model.lm_head(hs[-1][:, -1:]).argmax(-1) | |
| if nxt.item() == 151645: | |
| break | |
| cur = torch.cat([cur, nxt], 1) | |
| m = torch.cat([m, m.new_ones(1, 1)], 1) | |
| print(f'[{mode}] {lm.tok.decode(cur[0, encp["input_ids"].shape[1]:])}', flush=True) | |
| if __name__ == '__main__': | |
| main() | |