Download scripts/think_test.py from tysgydke/Qwen3-4B-LoopIntervention: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/think_test.py
- Command line
-
hf download hf://tysgydke/Qwen3-4B-LoopIntervention/scripts/think_test.py
-
curl -L -o think_test.py https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/think_test.py
2.13 kB
| # thinking 模式试水:现有干预 ckpt 在思维链生成下的表现(CPU 跑) | |
| # chat template 默认开 thinking;greedy 解码,对比 base / r1 / r2 | |
| import sys | |
| import time | |
| import torch | |
| import train_interv | |
| from train_interv import LoopModel | |
| CKPT = '/root/autodl-tmp/loop-exp/ckpt/intervmix_step4000.pt' | |
| MAX_NEW = 250 | |
| QUESTIONS = [ | |
| "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?", | |
| ] | |
| def main(): | |
| lm = LoopModel() | |
| sd = torch.load(CKPT, map_location='cpu', weights_only=False) | |
| lm.interv.load_state_dict(sd['sd']) | |
| print(f"loaded ckpt step={sd['step']}", flush=True) | |
| # 挪到 CPU(生成式评测守则:优先 CPU) | |
| lm.model.cpu() | |
| lm.interv.cpu() | |
| for q in QUESTIONS: | |
| msgs = [{"role": "user", "content": q}] | |
| text = lm.tok.apply_chat_template(msgs, tokenize=False, | |
| add_generation_prompt=True) | |
| print(f'===== PROMPT(thinking): {q[:60]}... =====', flush=True) | |
| enc = lm.tok(text, return_tensors='pt') | |
| for mode, r in (('base', 1), ('r1', 1), ('r2', 2)): | |
| intervene = mode != 'base' | |
| cur = enc['input_ids'].clone() | |
| m = enc['attention_mask'].clone() | |
| t0 = time.time() | |
| ngen = 0 | |
| for _ in range(MAX_NEW): | |
| 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: # <|im_end|> | |
| break | |
| cur = torch.cat([cur, nxt], 1) | |
| m = torch.cat([m, m.new_ones(1, 1)], 1) | |
| ngen += 1 | |
| if ngen % 25 == 0: | |
| print(f'[{mode}] {ngen} tok, {ngen/(time.time()-t0):.2f} tok/s', | |
| flush=True) | |
| dt = time.time() - t0 | |
| print(f'\n[{mode}] ({ngen} tok, {dt:.0f}s)') | |
| print(lm.tok.decode(cur[0, enc["input_ids"].shape[1]:]), flush=True) | |
| if __name__ == '__main__': | |
| main() | |