Download scripts/probe_baseline.py from tysgydke/Qwen3-4B-LoopIntervention: direct link, hf CLI and curl.
- Browser
- Download file 3.85 kB
-
https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/probe_baseline.py
- Command line
-
hf download hf://tysgydke/Qwen3-4B-LoopIntervention/scripts/probe_baseline.py
-
curl -L -o probe_baseline.py https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/probe_baseline.py
3.85 kB
| # R 轮零干预循环坍缩基线探针 | |
| # 做法:把 Qwen3-4B 的 36 层堆叠当作一个映射 M,h^(t) = M(h^(t-1)),h^(0)=embed(x) | |
| # 每轮输出过 lm_head 测交叉熵,并记录轮间动力学指标。 | |
| import json, math, os, sys | |
| import torch | |
| import torch.nn.functional as F | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| MODEL = '/root/autodl-tmp/models/Qwen/Qwen3-4B' | |
| N_DOCS = 200 # GSM8K test 前 200 题 | |
| MAX_LEN = 512 | |
| MAX_T = 4 | |
| BATCH = 8 | |
| ATTN_DOCS = 16 # 只对前 16 篇算注意力熵(eager 慢) | |
| LOG = '/root/loop-exp/probe_baseline.log.jsonl' | |
| torch.manual_seed(0) | |
| def load_docs(): | |
| import pandas as pd | |
| df = pd.read_parquet('/root/autodl-tmp/data/gsm8k2/main/test-00000-of-00001.parquet') | |
| return [q + '\n' + a for q, a in zip(df['question'][:N_DOCS], df['answer'][:N_DOCS])] | |
| def main(): | |
| tok = AutoTokenizer.from_pretrained(MODEL) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL, dtype=torch.bfloat16, attn_implementation='eager').cuda().eval() | |
| docs = load_docs() | |
| print(f'docs={len(docs)}', flush=True) | |
| recs = [] | |
| for b0 in range(0, len(docs), BATCH): | |
| chunk = docs[b0:b0+BATCH] | |
| want_attn = (b0 < ATTN_DOCS) | |
| enc = tok(chunk, return_tensors='pt', padding=True, truncation=True, | |
| max_length=MAX_LEN).to('cuda') | |
| ids, mask = enc['input_ids'], enc['attention_mask'] | |
| h = model.get_input_embeddings()(ids) | |
| prev_h, prev_logits = None, None | |
| for t in range(1, MAX_T+1): | |
| out = model.model(inputs_embeds=h, attention_mask=mask, | |
| output_attentions=want_attn) | |
| h = out.last_hidden_state | |
| logits = model.lm_head(h) | |
| # 移位交叉熵(带 mask) | |
| lp = F.log_softmax(logits[:, :-1].float(), dim=-1) | |
| tgt = ids[:, 1:] | |
| m = mask[:, 1:].bool() | |
| nll = -lp.gather(-1, tgt.unsqueeze(-1)).squeeze(-1) | |
| ce = (nll * m).sum() / m.sum() | |
| rec = {'batch': b0//BATCH, 't': t, 'ce': ce.item()} | |
| if prev_h is not None: | |
| dh = (h - prev_h).norm(dim=-1) / prev_h.norm(dim=-1).clamp_min(1e-6) | |
| cos = F.cosine_similarity(h, prev_h, dim=-1) | |
| agree = (logits.argmax(-1)[:, 1:] == prev_logits.argmax(-1)[:, 1:]) | |
| rec['dh_ratio'] = (dh * mask).sum().item() / mask.sum().item() | |
| rec['cos'] = (cos * mask).sum().item() / mask.sum().item() | |
| rec['top1_agree'] = (agree & m).sum().item() / m.sum().item() | |
| rec['h_norm'] = (h.norm(dim=-1) * mask).sum().item() / mask.sum().item() | |
| if want_attn: | |
| ent = [] | |
| for att in out.attentions: # (B, heads, M, M) | |
| p = att.float().clamp_min(1e-12) | |
| e = -(p * p.log()).sum(-1) # (B, heads, M) | |
| ent.append((e * mask.unsqueeze(1)).sum().item() | |
| / (mask.sum().item() * att.shape[1])) | |
| rec['attn_entropy'] = sum(ent) / len(ent) | |
| recs.append(rec) | |
| prev_h, prev_logits = h, logits | |
| if (b0//BATCH) % 5 == 0: | |
| print(f'batch {b0//BATCH} done', flush=True) | |
| # 聚合 | |
| agg = {} | |
| for t in range(1, MAX_T+1): | |
| rows = [r for r in recs if r['t'] == t] | |
| a = {'t': t} | |
| for k in ('ce', 'dh_ratio', 'cos', 'top1_agree', 'h_norm', 'attn_entropy'): | |
| vals = [r[k] for r in rows if k in r] | |
| if vals: | |
| a[k] = sum(vals) / len(vals) | |
| a['ppl'] = math.exp(a['ce']) | |
| agg[t] = a | |
| print(json.dumps(a), flush=True) | |
| with open(LOG, 'w') as f: | |
| for r in recs: | |
| f.write(json.dumps(r) + '\n') | |
| print('saved to', LOG, flush=True) | |
| if __name__ == '__main__': | |
| main() | |