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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
END-TO-END OVERFIT: can a SINGLE learnable recurrent step() keep KL low across a whole
|
| 4 |
+
sequence? Train the hypernet end-to-end (KL through the recurrence, FULL BPTT over all
|
| 5 |
+
chunks) on a few FIXED sequences; log per-chunk KL (esp. deep chunks) over training.
|
| 6 |
+
|
| 7 |
+
This is a SYMMETRY-INVARIANT existence test (output/KL space, never touches a specific
|
| 8 |
+
SP* vector):
|
| 9 |
+
deep-chunk KL -> low => a recurrent SP trajectory EXISTS and is findable by gradient
|
| 10 |
+
descent (the floor was amortization/generalization -> fixable).
|
| 11 |
+
deep-chunk KL stuck => the recurrent structure genuinely cannot carry the history.
|
| 12 |
+
"""
|
| 13 |
+
import sys
|
| 14 |
+
sys.path.insert(0, "/workspace")
|
| 15 |
+
import argparse, json, time
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn as nn
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 20 |
+
from transformers.cache_utils import DynamicCache
|
| 21 |
+
from train_qwen_distill import (HyperNetwork, Config, extract_qa, CJK_RE, TOOLCALL_RE,
|
| 22 |
+
soft_prompt_stability_loss)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_samples(path, tok, cfg, n_want, skip, min_chars, ans_len):
|
| 26 |
+
out = []
|
| 27 |
+
with open(path) as f:
|
| 28 |
+
for line in f:
|
| 29 |
+
if len(out) >= skip + n_want:
|
| 30 |
+
break
|
| 31 |
+
line = line.strip()
|
| 32 |
+
if not line:
|
| 33 |
+
continue
|
| 34 |
+
try:
|
| 35 |
+
row = json.loads(line)
|
| 36 |
+
except Exception:
|
| 37 |
+
continue
|
| 38 |
+
q, a = extract_qa(row, cfg)
|
| 39 |
+
if not q or not a or len(a) < min_chars:
|
| 40 |
+
continue
|
| 41 |
+
if CJK_RE.search(a) or CJK_RE.search(q) or TOOLCALL_RE.search(a) or TOOLCALL_RE.search(q):
|
| 42 |
+
continue
|
| 43 |
+
qi = tok(q, max_length=cfg.max_query_len, truncation=True, add_special_tokens=True).input_ids
|
| 44 |
+
ai = tok(a, max_length=ans_len, truncation=True, add_special_tokens=False).input_ids
|
| 45 |
+
if len(ai) < ans_len: # need full-length sequences (no padding/masking)
|
| 46 |
+
continue
|
| 47 |
+
out.append((qi, ai))
|
| 48 |
+
return out[skip:skip + n_want]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def main():
|
| 52 |
+
p = argparse.ArgumentParser()
|
| 53 |
+
p.add_argument("--init_ckpt", default="/workspace/hypernet_qwen/hn_step7750.pt")
|
| 54 |
+
p.add_argument("--base_model", default="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B")
|
| 55 |
+
p.add_argument("--data", default="/workspace/dolphin_subset.jsonl")
|
| 56 |
+
p.add_argument("--n_seq", type=int, default=2)
|
| 57 |
+
p.add_argument("--skip", type=int, default=400)
|
| 58 |
+
p.add_argument("--min_chars", type=int, default=2500)
|
| 59 |
+
p.add_argument("--ans_len", type=int, default=512)
|
| 60 |
+
p.add_argument("--chunk_size", type=int, default=64)
|
| 61 |
+
p.add_argument("--raw_window", type=int, default=32)
|
| 62 |
+
p.add_argument("--steps", type=int, default=400)
|
| 63 |
+
p.add_argument("--lr", type=float, default=1e-3)
|
| 64 |
+
p.add_argument("--kl_temperature", type=float, default=1.0)
|
| 65 |
+
p.add_argument("--from_scratch", action="store_true")
|
| 66 |
+
args = p.parse_args()
|
| 67 |
+
|
| 68 |
+
device = torch.device("cuda"); dtype = torch.bfloat16
|
| 69 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 70 |
+
cfg = Config(); cfg.base_model = args.base_model; cfg.kl_temperature = args.kl_temperature
|
| 71 |
+
T = args.kl_temperature; C = args.chunk_size; S = cfg.num_soft_tokens
|
| 72 |
+
print("Loading frozen base...", flush=True)
|
| 73 |
+
tok = AutoTokenizer.from_pretrained(cfg.base_model)
|
| 74 |
+
if tok.pad_token is None:
|
| 75 |
+
tok.pad_token = tok.eos_token
|
| 76 |
+
llm = AutoModelForCausalLM.from_pretrained(cfg.base_model, dtype=dtype, device_map="cuda",
|
| 77 |
+
attn_implementation="sdpa")
|
| 78 |
+
llm.config.use_cache = False
|
| 79 |
+
for prm in llm.parameters():
|
| 80 |
+
prm.requires_grad_(False)
|
| 81 |
+
llm.eval()
|
| 82 |
+
embed = llm.get_input_embeddings()
|
| 83 |
+
cfg.hidden_dim = llm.config.hidden_size
|
| 84 |
+
with torch.no_grad():
|
| 85 |
+
ids = torch.randint(0, embed.weight.size(0), (512,), device=device)
|
| 86 |
+
cfg.target_norm = embed(ids).float().norm(dim=-1).mean().item()
|
| 87 |
+
max_norm = cfg.target_norm * 3.0
|
| 88 |
+
hn = HyperNetwork(cfg).to(dtype=torch.float32, device=device)
|
| 89 |
+
if not args.from_scratch:
|
| 90 |
+
ckd = torch.load(args.init_ckpt, map_location="cpu", weights_only=False)
|
| 91 |
+
hn.load_state_dict(ckd["hypernet"], strict=False)
|
| 92 |
+
print(f"init from {args.init_ckpt}", flush=True)
|
| 93 |
+
else:
|
| 94 |
+
print("init from scratch", flush=True)
|
| 95 |
+
hn.train()
|
| 96 |
+
opt = torch.optim.AdamW([pp for pp in hn.parameters() if pp.requires_grad], lr=args.lr, weight_decay=0.0)
|
| 97 |
+
|
| 98 |
+
samples = load_samples(args.data, tok, cfg, args.n_seq, args.skip, args.min_chars, args.ans_len)
|
| 99 |
+
B = len(samples)
|
| 100 |
+
max_q = max(len(s[0]) for s in samples)
|
| 101 |
+
max_a = args.ans_len
|
| 102 |
+
q_ids = torch.zeros(B, max_q, dtype=torch.long, device=device)
|
| 103 |
+
a_ids = torch.zeros(B, max_a, dtype=torch.long, device=device)
|
| 104 |
+
q_lens = torch.zeros(B, dtype=torch.long, device=device)
|
| 105 |
+
for i, (qi, ai) in enumerate(samples):
|
| 106 |
+
q_ids[i, :len(qi)] = torch.tensor(qi, device=device); q_lens[i] = len(qi)
|
| 107 |
+
a_ids[i, :max_a] = torch.tensor(ai[:max_a], device=device)
|
| 108 |
+
pos_q = torch.arange(max_q, device=device).unsqueeze(0).expand(B, -1)
|
| 109 |
+
valid_q = (pos_q < q_lens.unsqueeze(1)).long()
|
| 110 |
+
n_chunks = (max_a + C - 1) // C
|
| 111 |
+
print(f"overfit B={B} seqs | max_q={max_q} max_a={max_a} n_chunks={n_chunks} | lr={args.lr} steps={args.steps}\n", flush=True)
|
| 112 |
+
|
| 113 |
+
# ---- teacher (frozen, full real context), precompute once ----
|
| 114 |
+
with torch.no_grad():
|
| 115 |
+
cache_t = DynamicCache()
|
| 116 |
+
q_emb = (embed(q_ids) * valid_q.unsqueeze(-1)).to(dtype)
|
| 117 |
+
out_q = llm(inputs_embeds=q_emb, attention_mask=valid_q, past_key_values=cache_t,
|
| 118 |
+
use_cache=True, cache_position=torch.arange(max_q, device=device))
|
| 119 |
+
last_q = (q_lens - 1).clamp(min=0)
|
| 120 |
+
t0 = out_q.logits[torch.arange(B, device=device), last_q, :]
|
| 121 |
+
a_emb_t = embed(a_ids).to(dtype)
|
| 122 |
+
attn_qa = torch.cat([valid_q, torch.ones(B, max_a, dtype=torch.long, device=device)], dim=1)
|
| 123 |
+
pos_a = torch.arange(max_q, max_q + max_a, device=device)
|
| 124 |
+
out_a = llm(inputs_embeds=a_emb_t, attention_mask=attn_qa, past_key_values=cache_t,
|
| 125 |
+
position_ids=pos_a.unsqueeze(0).expand(B, -1), use_cache=True, cache_position=pos_a)
|
| 126 |
+
V = out_a.logits.size(-1)
|
| 127 |
+
teacher = torch.empty(B, max_a, V, dtype=out_a.logits.dtype, device=device)
|
| 128 |
+
teacher[:, 0, :] = t0; teacher[:, 1:, :] = out_a.logits[:, :max_a - 1, :]
|
| 129 |
+
t_p_all = F.softmax(teacher.float() / T, dim=-1) # (B,max_a,V)
|
| 130 |
+
del cache_t, out_q, out_a, teacher
|
| 131 |
+
torch.cuda.empty_cache()
|
| 132 |
+
|
| 133 |
+
def student_step(record_kl=False):
|
| 134 |
+
cache_s = DynamicCache()
|
| 135 |
+
with torch.no_grad():
|
| 136 |
+
llm(inputs_embeds=(embed(q_ids) * valid_q.unsqueeze(-1)).to(dtype), attention_mask=valid_q,
|
| 137 |
+
past_key_values=cache_s, use_cache=True, cache_position=torch.arange(max_q, device=device))
|
| 138 |
+
sp = hn.init_sp.expand(B, -1, -1).contiguous()
|
| 139 |
+
total = 0.0; per_chunk = []
|
| 140 |
+
for j in range(n_chunks):
|
| 141 |
+
c0 = j * C; c1 = min(c0 + C, max_a); cur_C = c1 - c0
|
| 142 |
+
with torch.no_grad():
|
| 143 |
+
nrm = sp.norm(dim=-1, keepdim=True).clamp(min=1e-6)
|
| 144 |
+
sc = torch.where(nrm > max_norm, max_norm / nrm, torch.ones_like(nrm))
|
| 145 |
+
sp_c = (sp * sc).to(dtype)
|
| 146 |
+
R = min(c0, args.raw_window)
|
| 147 |
+
chunk_emb = embed(a_ids[:, c0:c1]).to(dtype)
|
| 148 |
+
parts = [sp_c] + ([embed(a_ids[:, c0 - R:c0]).to(dtype)] if R > 0 else []) + [chunk_emb]
|
| 149 |
+
llm_in = torch.cat(parts, dim=1); n_new = S + R + cur_C
|
| 150 |
+
cpos = torch.arange(max_q, max_q + n_new, device=device)
|
| 151 |
+
attn = torch.cat([valid_q, torch.ones(B, n_new, dtype=torch.long, device=device)], dim=1)
|
| 152 |
+
out = llm(inputs_embeds=llm_in, attention_mask=attn, past_key_values=cache_s,
|
| 153 |
+
position_ids=cpos.unsqueeze(0).expand(B, -1), use_cache=True, cache_position=cpos)
|
| 154 |
+
cache_s.crop(max_q)
|
| 155 |
+
for layer in cache_s.layers:
|
| 156 |
+
layer.keys = layer.keys.detach().contiguous(); layer.values = layer.values.detach().contiguous()
|
| 157 |
+
s_logp = F.log_softmax(out.logits[:, S - 1 + R: S - 1 + R + cur_C, :].float() / T, dim=-1)
|
| 158 |
+
t_p = t_p_all[:, c0:c1, :]
|
| 159 |
+
kl = (t_p * (t_p.clamp_min(1e-9).log() - s_logp)).sum(-1).mean() * (T * T)
|
| 160 |
+
total = total + kl + soft_prompt_stability_loss(sp, cfg)
|
| 161 |
+
if record_kl:
|
| 162 |
+
per_chunk.append(kl.item())
|
| 163 |
+
if j < n_chunks - 1:
|
| 164 |
+
sp = hn.step(sp, chunk_emb.float(), None) # FULL BPTT (no detach)
|
| 165 |
+
return total, per_chunk
|
| 166 |
+
|
| 167 |
+
t0t = time.time()
|
| 168 |
+
for st in range(1, args.steps + 1):
|
| 169 |
+
opt.zero_grad(set_to_none=True)
|
| 170 |
+
rec = (st % 25 == 0 or st == 1)
|
| 171 |
+
total, per_chunk = student_step(record_kl=rec)
|
| 172 |
+
total.backward()
|
| 173 |
+
nn.utils.clip_grad_norm_([pp for pp in hn.parameters() if pp.requires_grad], 1.0)
|
| 174 |
+
opt.step()
|
| 175 |
+
torch.cuda.empty_cache()
|
| 176 |
+
if rec:
|
| 177 |
+
pcs = " ".join(f"{k:.3f}" for k in per_chunk)
|
| 178 |
+
deep = sum(per_chunk[3:]) / max(len(per_chunk[3:]), 1)
|
| 179 |
+
print(f"step {st:4d} | meanKL={sum(per_chunk)/len(per_chunk):.4f} deepKL(c0>=192)={deep:.4f} "
|
| 180 |
+
f"| per-chunk[{pcs}] | {time.time()-t0t:.0f}s", flush=True)
|
| 181 |
+
print("\nDONE. If deepKL dropped low, a recurrent SP trajectory EXISTS & is learnable.")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
main()
|