Download scripts/gen_cached.py from tysgydke/Qwen3-4B-LoopIntervention: direct link, hf CLI and curl.
- Browser
- Download file 5.29 kB
-
https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/gen_cached.py
- Command line
-
hf download hf://tysgydke/Qwen3-4B-LoopIntervention/scripts/gen_cached.py
-
curl -L -o gen_cached.py https://huggingface.co/tysgydke/Qwen3-4B-LoopIntervention/resolve/main/scripts/gen_cached.py
5.29 kB
| # KV cache 版循环生成器:O(len^2)->O(len) | |
| # 口径对齐 train_interv.LoopModel.forward: | |
| # h = emb(ids); for t: h_t = trunk(vtok_t + FiLM_t(h_{t-1})); 圈间逐位置传递 | |
| # 生成新 token 时:新 token emb 过圈1(带cache)得 h1_new,再过圈2(带cache)得 logits | |
| # 圈内增量:上一圈同位置输出即本圈该位置输入(逐位置对齐) | |
| # r=2 推理时等价于:每生成一步,新 token 依次过圈1 cache 和圈2 cache; | |
| # prompt 段两圈各 prefill 一次(圈2 的输入=圈1 的 prefill 输出)。 | |
| import torch | |
| from train_interv import LoopModel, NVT | |
| class CachedLoop(LoopModel): | |
| def _trunk(self, h, t, past, cache_len): | |
| """把隐状态 h(B,L,D) 送入圈 t(含 vtok 前缀仅 prefill 时)。 | |
| past=None 且带 vtok -> prefill;否则增量。返回(last_hidden, past)。""" | |
| B, L = h.shape[0], h.shape[1] | |
| g, b = self.interv.gamma[t], self.interv.beta[t] | |
| h = (h.float() * (1 + g) + b).to(h.dtype) | |
| if past is None: # prefill:拼 vtok | |
| vt = self.interv.vtok[t].to(h.dtype).unsqueeze(0).expand(B, -1, -1) | |
| ie = torch.cat([vt, h], dim=1) | |
| am = torch.ones(B, ie.shape[1], dtype=torch.long, device=h.device) | |
| pos = torch.arange(ie.shape[1], device=h.device).unsqueeze(0) | |
| else: # 增量:L 个新 token | |
| ie = h | |
| # past 含 prefill 的 vtok 前缀(NVT),增量 token 位置需从真实位置续起 | |
| real_len = cache_len - NVT if cache_len >= NVT else cache_len | |
| am = torch.ones(B, cache_len + L, dtype=torch.long, device=h.device) | |
| pos = torch.arange(real_len, real_len + L, | |
| device=h.device).unsqueeze(0) | |
| self.interv.enabled = True | |
| self.interv.cur_t = t | |
| out = self.model.model(inputs_embeds=ie, attention_mask=am, | |
| position_ids=pos, past_key_values=past, | |
| use_cache=True) | |
| return out.last_hidden_state[:, NVT:, :] if past is None \ | |
| else out.last_hidden_state, out.past_key_values | |
| def _prefill_all(self, ids, r): | |
| """两圈串行 prefill:圈1 吃 embedding,圈2 吃圈1 输出。 | |
| 返回两圈的 (last_hidden, past) 列表。""" | |
| states = [] | |
| h = self.model.get_input_embeddings()(ids) | |
| am = torch.ones_like(ids) | |
| for t in range(r): | |
| hid, past = self._trunk(h, t, None, 0) | |
| states.append((hid, past)) | |
| h = hid # 下一圈输入 = 本圈输出(逐位置) | |
| return states | |
| def _step_all(self, tok_ids, r, states): | |
| """新 token(B,1) 依次过 r 圈(各带各自 cache)。 | |
| 返回末圈 last_hidden;states 原地更新。""" | |
| h = self.model.get_input_embeddings()(tok_ids) | |
| new_states = [] | |
| for t in range(r): | |
| past = states[t][1] | |
| cache_len = past.get_seq_length() | |
| hid, past = self._trunk(h, t, past, cache_len) | |
| new_states.append((hid, past)) | |
| h = hid # 圈t 输出 -> 圈t+1 输入(该位置) | |
| states[:] = new_states | |
| return h | |
| def generate(self, ids, cap=512, r=2, eos=151645, | |
| temperature=None, top_p=None): | |
| """贪心生成(默认)。temperature/top_p 传入时暂不支持(见 gen_cached_v2 采样版)。""" | |
| states = self._prefill_all(ids, r) | |
| hid_last = states[-1][0][:, -1:, :] | |
| logits = self.model.lm_head(hid_last) | |
| gen = [] | |
| for i in range(cap): | |
| nxt = logits.argmax(-1) | |
| if nxt.item() == eos: | |
| break | |
| gen.append(nxt.item()) | |
| hid = self._step_all(nxt, r, states) | |
| logits = self.model.lm_head(hid[:, -1:, :]) | |
| return gen | |
| def load_cached(ckpt=None): | |
| from train_interv import MODEL | |
| r = 2 | |
| if ckpt: | |
| sd = torch.load(ckpt, map_location='cuda', weights_only=False) | |
| r = sd.get('r', 2) | |
| lm = CachedLoop(R=r) | |
| if ckpt: | |
| lm.interv.load_state_dict(sd['sd']) | |
| print(f'loaded {ckpt} step={sd["step"]} r={r}', flush=True) | |
| return lm | |
| if __name__ == '__main__': | |
| # 等价性自测:与原版 forward 的贪心生成逐 token 比对 | |
| import sys | |
| ckpt = sys.argv[1] if len(sys.argv) > 1 else \ | |
| '/root/autodl-tmp/loop-exp/ckpt/intervmix_step4000.pt' | |
| lm = load_cached(ckpt) | |
| prompt = lm.tok.apply_chat_template( | |
| [{"role": "user", "content": "2+3=?"}], | |
| tokenize=False, add_generation_prompt=True, enable_thinking=False) | |
| enc = lm.tok(prompt, return_tensors='pt').to('cuda') | |
| ids, m = enc['input_ids'], enc['attention_mask'] | |
| # 原版参考:逐步 forward 整序列 | |
| cur = ids.clone() | |
| ref = [] | |
| for _ in range(24): | |
| hs = lm.forward(cur, m, r=2, intervene=True, no_grad=True) | |
| nxt = lm.model.lm_head(hs[-1][:, -1:, :]).argmax(-1) | |
| if nxt.item() == 151645: | |
| break | |
| ref.append(nxt.item()) | |
| cur = torch.cat([cur, nxt], 1) | |
| m = torch.cat([m, m.new_ones(1, 1)], 1) | |
| # 新版 | |
| new = lm.generate(ids, cap=24, r=2) | |
| print('ref:', ref) | |
| print('new:', new) | |
| print('MATCH' if ref == new else 'MISMATCH') | |