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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Is the recurrence input sp^m related to its output sp^{m+1}? (= is sp^m -> sp^{m+1}
|
| 4 |
+
a learnable, amortizable map?) Each sp^j is optimized INDEPENDENTLY from the FIXED
|
| 5 |
+
init_sp anchor (deterministic; NO chaining -> no warm-start proximity artifact), so the
|
| 6 |
+
dCor reflects genuine shared-history structure, not closeness-by-construction.
|
| 7 |
+
|
| 8 |
+
Measured over consecutive pairs pooled across many samples (cross-sample = amortization angle):
|
| 9 |
+
dCor(sp^m , sp^{m+1}) -- does the prev SP predict the next SP at all?
|
| 10 |
+
dCor([sp^m;chunk_m], sp^{m+1}) -- does the actual recurrence INPUT predict the output?
|
| 11 |
+
vs shuffled null. PCA-reduced (N>>dim -> clean null).
|
| 12 |
+
"""
|
| 13 |
+
import sys
|
| 14 |
+
sys.path.insert(0, "/workspace")
|
| 15 |
+
import argparse, json
|
| 16 |
+
import torch
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 19 |
+
from transformers.cache_utils import DynamicCache
|
| 20 |
+
from train_qwen_distill import (HyperNetwork, Config, extract_qa, CJK_RE, TOOLCALL_RE,
|
| 21 |
+
soft_prompt_stability_loss)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def dcor(X, Y):
|
| 25 |
+
a = torch.cdist(X, X); b = torch.cdist(Y, Y)
|
| 26 |
+
A = a - a.mean(0, keepdim=True) - a.mean(1, keepdim=True) + a.mean()
|
| 27 |
+
B = b - b.mean(0, keepdim=True) - b.mean(1, keepdim=True) + b.mean()
|
| 28 |
+
dcov2 = (A * B).mean(); dvx = (A * A).mean(); dvy = (B * B).mean()
|
| 29 |
+
return float((dcov2.clamp(min=0) / (dvx.sqrt() * dvy.sqrt()).clamp(min=1e-12)).sqrt().item())
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def zscore(X): return (X - X.mean(0, keepdim=True)) / X.std(0, keepdim=True).clamp(min=1e-6)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def pca(X, k):
|
| 36 |
+
Xc = X - X.mean(0, keepdim=True)
|
| 37 |
+
U, S, Vh = torch.linalg.svd(Xc, full_matrices=False)
|
| 38 |
+
return Xc @ Vh[:min(k, Vh.size(0))].T
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@torch.no_grad()
|
| 42 |
+
def teacher_dist(llm, embed, q, valid_q, a, max_q, max_a, q_lens, device, dtype):
|
| 43 |
+
B = q.size(0); cache = DynamicCache()
|
| 44 |
+
qe = (embed(q[:, :max_q]) * valid_q.unsqueeze(-1)).to(dtype)
|
| 45 |
+
oq = llm(inputs_embeds=qe, attention_mask=valid_q, past_key_values=cache, use_cache=True,
|
| 46 |
+
cache_position=torch.arange(max_q, device=device))
|
| 47 |
+
t0 = oq.logits[torch.arange(B, device=device), (q_lens - 1).clamp(min=0), :]
|
| 48 |
+
ae = embed(a[:, :max_a]).to(dtype)
|
| 49 |
+
pos = torch.arange(max_q, max_q + max_a, device=device)
|
| 50 |
+
attn = torch.cat([valid_q, torch.ones(B, max_a, dtype=torch.long, device=device)], 1)
|
| 51 |
+
oa = llm(inputs_embeds=ae, attention_mask=attn, past_key_values=cache,
|
| 52 |
+
position_ids=pos.unsqueeze(0).expand(B, -1), use_cache=True, cache_position=pos)
|
| 53 |
+
V = oa.logits.size(-1); T = torch.empty(B, max_a, V, dtype=oa.logits.dtype, device=device)
|
| 54 |
+
T[:, 0] = t0; T[:, 1:] = oa.logits[:, :max_a - 1]; return T
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@torch.no_grad()
|
| 58 |
+
def prefill(llm, embed, q, valid_q, max_q, device, dtype):
|
| 59 |
+
cache = DynamicCache()
|
| 60 |
+
llm(inputs_embeds=(embed(q[:, :max_q]) * valid_q.unsqueeze(-1)).to(dtype),
|
| 61 |
+
attention_mask=valid_q, past_key_values=cache, use_cache=True,
|
| 62 |
+
cache_position=torch.arange(max_q, device=device))
|
| 63 |
+
return cache
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def opt_chunk_sp(llm, embed, q, valid_q, a, a_lens, teacher, init_sp, c0, c1, max_q, device,
|
| 67 |
+
dtype, cfg, max_norm, raw_window, steps, lr, S, T):
|
| 68 |
+
"""fixed-init independent optimization of the SP for predicting chunk [c0:c1]."""
|
| 69 |
+
B = q.size(0); cur_C = c1 - c0; R = min(c0, raw_window)
|
| 70 |
+
raw = embed(a[:, c0 - R:c0]).to(dtype) if R > 0 else None
|
| 71 |
+
chunk = embed(a[:, c0:c1]).to(dtype)
|
| 72 |
+
n_new = S + R + cur_C
|
| 73 |
+
cpos = torch.arange(max_q, max_q + n_new, device=device)
|
| 74 |
+
attn = torch.cat([valid_q, torch.ones(B, n_new, dtype=torch.long, device=device)], 1)
|
| 75 |
+
t_p = F.softmax(teacher[:, c0:c1].float() / T, dim=-1)
|
| 76 |
+
posv = torch.arange(cur_C, device=device)
|
| 77 |
+
vf = ((c0 + posv).unsqueeze(0) < a_lens.unsqueeze(1)).float()
|
| 78 |
+
valid = (c0 < a_lens)
|
| 79 |
+
sp = init_sp.expand(B, -1, -1).clone().requires_grad_(True)
|
| 80 |
+
opt = torch.optim.Adam([sp], lr=lr)
|
| 81 |
+
best_kl = torch.full((B,), float("inf"), device=device); best = sp.detach().clone()
|
| 82 |
+
for _ in range(steps):
|
| 83 |
+
opt.zero_grad(set_to_none=True)
|
| 84 |
+
n = sp.norm(dim=-1, keepdim=True).clamp(min=1e-6)
|
| 85 |
+
sc = torch.where(n > max_norm, max_norm / n, torch.ones_like(n))
|
| 86 |
+
spc = (sp * sc).to(dtype)
|
| 87 |
+
x = torch.cat([spc, raw, chunk], 1) if R > 0 else torch.cat([spc, chunk], 1)
|
| 88 |
+
cache = prefill(llm, embed, q, valid_q, max_q, device, dtype)
|
| 89 |
+
o = llm(inputs_embeds=x, attention_mask=attn, past_key_values=cache,
|
| 90 |
+
position_ids=cpos.unsqueeze(0).expand(B, -1), use_cache=True, cache_position=cpos)
|
| 91 |
+
lp = F.log_softmax(o.logits[:, S - 1 + R:S - 1 + R + cur_C].float() / T, dim=-1)
|
| 92 |
+
kl = ((t_p * (t_p.clamp_min(1e-9).log() - lp)).sum(-1) * vf).sum(1) / vf.sum(1).clamp(min=1) * (T * T)
|
| 93 |
+
loss = (kl * valid.float()).sum() / valid.float().sum().clamp(min=1)
|
| 94 |
+
(loss + soft_prompt_stability_loss(sp, cfg)).backward(); opt.step()
|
| 95 |
+
with torch.no_grad():
|
| 96 |
+
imp = (kl < best_kl) & valid
|
| 97 |
+
if imp.any():
|
| 98 |
+
n2 = sp.norm(dim=-1, keepdim=True).clamp(min=1e-6)
|
| 99 |
+
sc2 = torch.where(n2 > max_norm, max_norm / n2, torch.ones_like(n2))
|
| 100 |
+
best[imp] = (sp * sc2)[imp].detach(); best_kl[imp] = kl[imp]
|
| 101 |
+
return best.detach(), valid, best_kl
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def load_samples(path, tok, cfg, n, min_chars, mal, min_tok):
|
| 105 |
+
out = []
|
| 106 |
+
with open(path) as f:
|
| 107 |
+
for line in f:
|
| 108 |
+
if len(out) >= n: break
|
| 109 |
+
line = line.strip()
|
| 110 |
+
if not line: continue
|
| 111 |
+
try: row = json.loads(line)
|
| 112 |
+
except Exception: continue
|
| 113 |
+
q, a = extract_qa(row, cfg)
|
| 114 |
+
if not q or not a or len(a) < min_chars: continue
|
| 115 |
+
if CJK_RE.search(a) or CJK_RE.search(q) or TOOLCALL_RE.search(a) or TOOLCALL_RE.search(q): continue
|
| 116 |
+
qi = tok(q, max_length=cfg.max_query_len, truncation=True, add_special_tokens=True).input_ids
|
| 117 |
+
ai = tok(a, max_length=mal, truncation=True, add_special_tokens=False).input_ids
|
| 118 |
+
if len(ai) < min_tok: continue
|
| 119 |
+
out.append((qi, ai))
|
| 120 |
+
out.sort(key=lambda x: len(x[1])); return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def main():
|
| 124 |
+
p = argparse.ArgumentParser()
|
| 125 |
+
p.add_argument("--ckpt", default="/workspace/hypernet_qwen/hn_step7750.pt")
|
| 126 |
+
p.add_argument("--base_model", default="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B")
|
| 127 |
+
p.add_argument("--data", default="/workspace/dolphin_subset.jsonl")
|
| 128 |
+
p.add_argument("--n_samples", type=int, default=24)
|
| 129 |
+
p.add_argument("--skip", type=int, default=300)
|
| 130 |
+
p.add_argument("--max_ans_len", type=int, default=512)
|
| 131 |
+
p.add_argument("--batch", type=int, default=12)
|
| 132 |
+
p.add_argument("--chunk_size", type=int, default=64)
|
| 133 |
+
p.add_argument("--raw_window", type=int, default=32)
|
| 134 |
+
p.add_argument("--steps", type=int, default=100)
|
| 135 |
+
p.add_argument("--lr", type=float, default=0.03)
|
| 136 |
+
p.add_argument("--pca_k", type=int, default=24)
|
| 137 |
+
args = p.parse_args()
|
| 138 |
+
device = torch.device("cuda"); dtype = torch.bfloat16
|
| 139 |
+
cfg = Config(); cfg.base_model = args.base_model
|
| 140 |
+
C = args.chunk_size; S = cfg.num_soft_tokens; T = 1.0
|
| 141 |
+
print("Loading frozen base...", flush=True)
|
| 142 |
+
tok = AutoTokenizer.from_pretrained(cfg.base_model)
|
| 143 |
+
if tok.pad_token is None: tok.pad_token = tok.eos_token
|
| 144 |
+
llm = AutoModelForCausalLM.from_pretrained(cfg.base_model, dtype=dtype, device_map="cuda",
|
| 145 |
+
attn_implementation="sdpa")
|
| 146 |
+
llm.config.use_cache = True
|
| 147 |
+
for prm in llm.parameters(): prm.requires_grad_(False)
|
| 148 |
+
llm.eval(); embed = llm.get_input_embeddings(); cfg.hidden_dim = llm.config.hidden_size
|
| 149 |
+
with torch.no_grad():
|
| 150 |
+
ids = torch.randint(0, embed.weight.size(0), (512,), device=device)
|
| 151 |
+
cfg.target_norm = embed(ids).float().norm(dim=-1).mean().item()
|
| 152 |
+
max_norm = cfg.target_norm * 3.0
|
| 153 |
+
hn = HyperNetwork(cfg).to(dtype=torch.float32, device=device); hn.eval()
|
| 154 |
+
ckd = torch.load(args.ckpt, map_location="cpu", weights_only=False)
|
| 155 |
+
hn.load_state_dict(ckd["hypernet"], strict=False)
|
| 156 |
+
init_sp = hn.init_sp.detach().clone()
|
| 157 |
+
alls = load_samples(args.data, tok, cfg, args.skip + args.n_samples, 1500, args.max_ans_len, 400)
|
| 158 |
+
samples = alls[args.skip:args.skip + args.n_samples]
|
| 159 |
+
print(f" {len(samples)} samples, fixed-init independent SP per chunk, steps={args.steps}\n", flush=True)
|
| 160 |
+
|
| 161 |
+
spm, spm1, chunkm = [], [], [] # sp^m, sp^{m+1}, chunk_m (pooled)
|
| 162 |
+
B = args.batch; kl_all = []
|
| 163 |
+
for bi in range(0, len(samples), B):
|
| 164 |
+
chunk_samples = samples[bi:bi + B]; b = len(chunk_samples)
|
| 165 |
+
max_q = max(len(s[0]) for s in chunk_samples); max_a = max(len(s[1]) for s in chunk_samples)
|
| 166 |
+
q = torch.zeros(b, max_q, dtype=torch.long, device=device)
|
| 167 |
+
a = torch.zeros(b, max_a, dtype=torch.long, device=device)
|
| 168 |
+
ql = torch.zeros(b, dtype=torch.long, device=device); al = torch.zeros(b, dtype=torch.long, device=device)
|
| 169 |
+
for i, (qi, ai) in enumerate(chunk_samples):
|
| 170 |
+
q[i, :len(qi)] = torch.tensor(qi, device=device); ql[i] = len(qi)
|
| 171 |
+
a[i, :len(ai)] = torch.tensor(ai, device=device); al[i] = len(ai)
|
| 172 |
+
valid_q = (torch.arange(max_q, device=device).unsqueeze(0) < ql.unsqueeze(1)).long()
|
| 173 |
+
teacher = teacher_dist(llm, embed, q, valid_q, a, max_q, max_a, ql, device, dtype)
|
| 174 |
+
n_chunks = (max_a + C - 1) // C
|
| 175 |
+
sp_by_chunk = {}
|
| 176 |
+
for j in range(1, n_chunks):
|
| 177 |
+
c0 = j * C; c1 = min(c0 + C, max_a)
|
| 178 |
+
if c1 - c0 < 4: break
|
| 179 |
+
sp_j, valid, klj = opt_chunk_sp(llm, embed, q, valid_q, a, al, teacher, init_sp,
|
| 180 |
+
c0, c1, max_q, device, dtype, cfg, max_norm,
|
| 181 |
+
args.raw_window, args.steps, args.lr, S, T)
|
| 182 |
+
sp_by_chunk[j] = (sp_j, valid)
|
| 183 |
+
kl_all.append(klj[valid].mean().item() if valid.any() else float('nan'))
|
| 184 |
+
# consecutive pairs
|
| 185 |
+
for j in sorted(sp_by_chunk):
|
| 186 |
+
if j + 1 not in sp_by_chunk: continue
|
| 187 |
+
spj, vj = sp_by_chunk[j]; spj1, vj1 = sp_by_chunk[j + 1]
|
| 188 |
+
c0 = j * C; c1 = min(c0 + C, max_a)
|
| 189 |
+
ce = embed(a[:, c0:c1]).float().mean(1) # chunk_m pooled
|
| 190 |
+
both = vj & vj1
|
| 191 |
+
for i in range(b):
|
| 192 |
+
if bool(both[i]):
|
| 193 |
+
spm.append(spj[i].mean(0).float().cpu())
|
| 194 |
+
spm1.append(spj1[i].mean(0).float().cpu())
|
| 195 |
+
chunkm.append(ce[i].cpu())
|
| 196 |
+
del teacher; torch.cuda.empty_cache()
|
| 197 |
+
print(f" batch {bi//B+1} done, pairs so far={len(spm)}", flush=True)
|
| 198 |
+
|
| 199 |
+
Xm = zscore(torch.stack(spm).to(device)); Xm1 = zscore(torch.stack(spm1).to(device))
|
| 200 |
+
Xc = zscore(torch.stack(chunkm).to(device))
|
| 201 |
+
N = Xm.size(0); K = args.pca_k; perm = torch.randperm(N, device=device)
|
| 202 |
+
Xm_r, Xm1_r, Xc_r = pca(Xm, K), pca(Xm1, K), pca(Xc, K)
|
| 203 |
+
Xin_r = pca(torch.cat([Xm, Xc], 1), K)
|
| 204 |
+
print(f"\nN consecutive pairs = {N} | mean opt KL = {sum(x for x in kl_all if x==x)/max(len(kl_all),1):.4f}")
|
| 205 |
+
print("=" * 64)
|
| 206 |
+
print(f"dCor(sp^m, sp^m+1) = {dcor(Xm_r, Xm1_r):.4f} (null {dcor(Xm_r, Xm1_r[perm]):.4f})")
|
| 207 |
+
print(f"dCor([sp^m;chunk],sp^m+1) = {dcor(Xin_r, Xm1_r):.4f} (null {dcor(Xin_r, Xm1_r[perm]):.4f})")
|
| 208 |
+
print(f"dCor(chunk_m, sp^m+1) = {dcor(Xc_r, Xm1_r):.4f} (null {dcor(Xc_r, Xm1_r[perm]):.4f})")
|
| 209 |
+
print("=" * 64)
|
| 210 |
+
print(">>null => the recurrence INPUT predicts the next SP => recurrence is learnable/amortizable.")
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
main()
|