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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Target-consistency test (the RIGHT test, replacing the loose overfit argument).
|
| 4 |
+
|
| 5 |
+
For each (sample, depth c0) we optimize the target SP* TWICE from two DIFFERENT
|
| 6 |
+
random initializations (constrained: clamp to target_norm*3 + stability), to the
|
| 7 |
+
same KL objective. Then we measure:
|
| 8 |
+
- KL_a, KL_b : both should reach a good low KL (the SP* are both "correct")
|
| 9 |
+
- cross-seed per-token L2 ||SP*_a - SP*_b||^2 : if BOTH are low-KL yet this L2 is
|
| 10 |
+
LARGE, the optimum is NON-UNIQUE (soft-prompt symmetry) -> MSE-to-a-fixed-vector
|
| 11 |
+
has an irreducible floor ~ this L2, and we should distill in OUTPUT space (KL).
|
| 12 |
+
- also the L2 between each SP* and their midpoint, and norms, for context.
|
| 13 |
+
|
| 14 |
+
Compare cross-seed L2 to the ~1.1 regression floor we observed. If they match,
|
| 15 |
+
symmetry is the cause.
|
| 16 |
+
"""
|
| 17 |
+
import sys
|
| 18 |
+
sys.path.insert(0, "/workspace")
|
| 19 |
+
import argparse, json
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 23 |
+
from transformers.cache_utils import DynamicCache
|
| 24 |
+
from train_qwen_distill import (HyperNetwork, Config, extract_qa, CJK_RE, TOOLCALL_RE,
|
| 25 |
+
soft_prompt_stability_loss)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@torch.no_grad()
|
| 29 |
+
def teacher_dist(llm, embed, q_ids, a_ids, max_q, max_a, device, dtype):
|
| 30 |
+
cache = DynamicCache()
|
| 31 |
+
q_emb = embed(q_ids[:, :max_q]).to(dtype)
|
| 32 |
+
out_q = llm(inputs_embeds=q_emb, attention_mask=torch.ones(1, max_q, device=device),
|
| 33 |
+
past_key_values=cache, use_cache=True, cache_position=torch.arange(max_q, device=device))
|
| 34 |
+
t0 = out_q.logits[:, -1, :]
|
| 35 |
+
a_emb = embed(a_ids[:, :max_a]).to(dtype)
|
| 36 |
+
pos_a = torch.arange(max_q, max_q + max_a, device=device)
|
| 37 |
+
out_a = llm(inputs_embeds=a_emb, attention_mask=torch.ones(1, max_q + max_a, device=device),
|
| 38 |
+
past_key_values=cache, position_ids=pos_a.unsqueeze(0), use_cache=True, cache_position=pos_a)
|
| 39 |
+
V = out_a.logits.size(-1)
|
| 40 |
+
teacher = torch.empty(1, max_a, V, dtype=out_a.logits.dtype, device=device)
|
| 41 |
+
teacher[:, 0, :] = t0
|
| 42 |
+
teacher[:, 1:, :] = out_a.logits[:, :max_a - 1, :]
|
| 43 |
+
return teacher
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@torch.no_grad()
|
| 47 |
+
def prefill_query(llm, embed, q_ids, max_q, device, dtype):
|
| 48 |
+
cache = DynamicCache()
|
| 49 |
+
llm(inputs_embeds=embed(q_ids[:, :max_q]).to(dtype),
|
| 50 |
+
attention_mask=torch.ones(1, max_q, device=device), past_key_values=cache,
|
| 51 |
+
use_cache=True, cache_position=torch.arange(max_q, device=device))
|
| 52 |
+
return cache
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def optimize_sp(llm, embed, q_ids, a_ids, teacher, c0, c1, max_q, device, dtype, cfg,
|
| 56 |
+
max_norm, raw_window, steps, lr, seed, S, T):
|
| 57 |
+
g = torch.Generator(device=device).manual_seed(seed)
|
| 58 |
+
cur_C = c1 - c0
|
| 59 |
+
R = min(c0, raw_window)
|
| 60 |
+
raw_emb = embed(a_ids[:, c0 - R:c0]).to(dtype) if R > 0 else None
|
| 61 |
+
chunk_emb = embed(a_ids[:, c0:c1]).to(dtype)
|
| 62 |
+
n_new = S + R + cur_C
|
| 63 |
+
cache_pos = torch.arange(max_q, max_q + n_new, device=device)
|
| 64 |
+
t_p = F.softmax(teacher[:, c0:c1, :].float() / T, dim=-1)
|
| 65 |
+
# random init scaled to ~ target_norm
|
| 66 |
+
sp = torch.randn(1, S, cfg.hidden_dim, generator=g, device=device)
|
| 67 |
+
sp = sp / sp.norm(dim=-1, keepdim=True).clamp(min=1e-6) * cfg.target_norm
|
| 68 |
+
sp = sp.requires_grad_(True)
|
| 69 |
+
opt = torch.optim.Adam([sp], lr=lr)
|
| 70 |
+
best_kl = float("inf"); best_v = None
|
| 71 |
+
for _m in range(steps):
|
| 72 |
+
opt.zero_grad(set_to_none=True)
|
| 73 |
+
vn = sp.norm(dim=-1, keepdim=True).clamp(min=1e-6)
|
| 74 |
+
v_c = (sp * torch.where(vn > max_norm, max_norm / vn, torch.ones_like(vn))).to(dtype)
|
| 75 |
+
v_in = torch.cat([v_c, raw_emb, chunk_emb], dim=1) if R > 0 else torch.cat([v_c, chunk_emb], dim=1)
|
| 76 |
+
cache = prefill_query(llm, embed, q_ids, max_q, device, dtype)
|
| 77 |
+
out = llm(inputs_embeds=v_in, attention_mask=torch.ones(1, max_q + n_new, device=device),
|
| 78 |
+
past_key_values=cache, position_ids=cache_pos.unsqueeze(0), use_cache=True,
|
| 79 |
+
cache_position=cache_pos)
|
| 80 |
+
v_logp = F.log_softmax(out.logits[:, S - 1 + R: S - 1 + R + cur_C, :].float() / T, dim=-1)
|
| 81 |
+
kl = (t_p * (t_p.clamp_min(1e-9).log() - v_logp)).sum(-1).mean() * (T * T)
|
| 82 |
+
(kl + soft_prompt_stability_loss(sp, cfg)).backward()
|
| 83 |
+
opt.step()
|
| 84 |
+
if kl.item() < best_kl:
|
| 85 |
+
best_kl = kl.item()
|
| 86 |
+
best_v = (sp.detach() * torch.where(vn > max_norm, max_norm / vn, torch.ones_like(vn))).clone()
|
| 87 |
+
return best_kl, best_v # best_v = clamped effective SP* (1,S,H)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def load_samples(path, tok, cfg, n_want, min_chars, max_ans_len, min_tok):
|
| 91 |
+
out = []
|
| 92 |
+
with open(path) as f:
|
| 93 |
+
for line in f:
|
| 94 |
+
if len(out) >= n_want:
|
| 95 |
+
break
|
| 96 |
+
line = line.strip()
|
| 97 |
+
if not line:
|
| 98 |
+
continue
|
| 99 |
+
try:
|
| 100 |
+
row = json.loads(line)
|
| 101 |
+
except Exception:
|
| 102 |
+
continue
|
| 103 |
+
q, a = extract_qa(row, cfg)
|
| 104 |
+
if not q or not a or len(a) < min_chars:
|
| 105 |
+
continue
|
| 106 |
+
if CJK_RE.search(a) or CJK_RE.search(q) or TOOLCALL_RE.search(a) or TOOLCALL_RE.search(q):
|
| 107 |
+
continue
|
| 108 |
+
qi = tok(q, max_length=cfg.max_query_len, truncation=True, add_special_tokens=True).input_ids
|
| 109 |
+
ai = tok(a, max_length=max_ans_len, truncation=True, add_special_tokens=False).input_ids
|
| 110 |
+
if len(ai) < min_tok:
|
| 111 |
+
continue
|
| 112 |
+
out.append((qi, ai))
|
| 113 |
+
out.sort(key=lambda x: len(x[1]))
|
| 114 |
+
return out
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def main():
|
| 118 |
+
p = argparse.ArgumentParser()
|
| 119 |
+
p.add_argument("--ckpt", default="/workspace/hypernet_qwen/hn_step7750.pt")
|
| 120 |
+
p.add_argument("--base_model", default="deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B")
|
| 121 |
+
p.add_argument("--data", default="/workspace/dolphin_subset.jsonl")
|
| 122 |
+
p.add_argument("--n_samples", type=int, default=6)
|
| 123 |
+
p.add_argument("--skip_samples", type=int, default=500)
|
| 124 |
+
p.add_argument("--min_chars", type=int, default=1500)
|
| 125 |
+
p.add_argument("--min_tok", type=int, default=400)
|
| 126 |
+
p.add_argument("--max_ans_len", type=int, default=512)
|
| 127 |
+
p.add_argument("--depths", default="128,256,384")
|
| 128 |
+
p.add_argument("--chunk_size", type=int, default=64)
|
| 129 |
+
p.add_argument("--raw_window", type=int, default=32)
|
| 130 |
+
p.add_argument("--steps", type=int, default=150)
|
| 131 |
+
p.add_argument("--lr", type=float, default=0.03)
|
| 132 |
+
p.add_argument("--kl_temperature", type=float, default=1.0)
|
| 133 |
+
args = p.parse_args()
|
| 134 |
+
|
| 135 |
+
device = torch.device("cuda"); dtype = torch.bfloat16
|
| 136 |
+
cfg = Config(); cfg.base_model = args.base_model; cfg.kl_temperature = args.kl_temperature
|
| 137 |
+
T = args.kl_temperature; C = args.chunk_size; S = cfg.num_soft_tokens
|
| 138 |
+
print("Loading frozen base...", flush=True)
|
| 139 |
+
tok = AutoTokenizer.from_pretrained(cfg.base_model)
|
| 140 |
+
if tok.pad_token is None:
|
| 141 |
+
tok.pad_token = tok.eos_token
|
| 142 |
+
llm = AutoModelForCausalLM.from_pretrained(cfg.base_model, dtype=dtype, device_map="cuda",
|
| 143 |
+
attn_implementation="sdpa")
|
| 144 |
+
llm.config.use_cache = True
|
| 145 |
+
for prm in llm.parameters():
|
| 146 |
+
prm.requires_grad_(False)
|
| 147 |
+
llm.eval()
|
| 148 |
+
embed = llm.get_input_embeddings()
|
| 149 |
+
cfg.hidden_dim = llm.config.hidden_size
|
| 150 |
+
with torch.no_grad():
|
| 151 |
+
ids = torch.randint(0, embed.weight.size(0), (512,), device=device)
|
| 152 |
+
cfg.target_norm = embed(ids).float().norm(dim=-1).mean().item()
|
| 153 |
+
max_norm = cfg.target_norm * 3.0
|
| 154 |
+
print(f"target_norm={cfg.target_norm:.3f} max_norm={max_norm:.3f}", flush=True)
|
| 155 |
+
|
| 156 |
+
depths = [int(x) for x in args.depths.split(",")]
|
| 157 |
+
alls = load_samples(args.data, tok, cfg, args.skip_samples + args.n_samples, args.min_chars,
|
| 158 |
+
args.max_ans_len, args.min_tok)
|
| 159 |
+
samples = alls[args.skip_samples: args.skip_samples + args.n_samples]
|
| 160 |
+
print(f"samples={len(samples)} depths={depths} steps={args.steps} lr={args.lr}\n", flush=True)
|
| 161 |
+
|
| 162 |
+
sumL2 = 0.0; sumKL = 0.0; cnt = 0; sum_selfE = 0.0
|
| 163 |
+
for si, (qi, ai) in enumerate(samples):
|
| 164 |
+
q = torch.tensor([qi], device=device); a = torch.tensor([ai], device=device)
|
| 165 |
+
max_q = q.size(1); max_a = a.size(1)
|
| 166 |
+
teacher = teacher_dist(llm, embed, q, a, max_q, max_a, device, dtype)
|
| 167 |
+
for c0 in depths:
|
| 168 |
+
c1 = min(c0 + C, max_a)
|
| 169 |
+
if c1 - c0 < 4 or c0 + 1 >= max_a:
|
| 170 |
+
continue
|
| 171 |
+
kl_a, sp_a = optimize_sp(llm, embed, q, a, teacher, c0, c1, max_q, device, dtype, cfg,
|
| 172 |
+
max_norm, args.raw_window, args.steps, args.lr, 111, S, T)
|
| 173 |
+
kl_b, sp_b = optimize_sp(llm, embed, q, a, teacher, c0, c1, max_q, device, dtype, cfg,
|
| 174 |
+
max_norm, args.raw_window, args.steps, args.lr, 999, S, T)
|
| 175 |
+
l2 = ((sp_a - sp_b) ** 2).sum(-1).mean().item() # per-token cross-seed L2
|
| 176 |
+
selfE = (sp_a ** 2).sum(-1).mean().item() # per-token energy of a target
|
| 177 |
+
na = sp_a.norm(dim=-1).mean().item(); nb = sp_b.norm(dim=-1).mean().item()
|
| 178 |
+
cos = F.cosine_similarity(sp_a, sp_b, dim=-1).mean().item()
|
| 179 |
+
print(f" s{si+1} c0={c0}: KL_a={kl_a:.4f} KL_b={kl_b:.4f} | "
|
| 180 |
+
f"crossL2={l2:.4f} (||tgt||^2~{selfE:.2f}) cos={cos:.3f} norms=({na:.2f},{nb:.2f})",
|
| 181 |
+
flush=True)
|
| 182 |
+
sumL2 += l2; sumKL += 0.5 * (kl_a + kl_b); sum_selfE += selfE; cnt += 1
|
| 183 |
+
del teacher
|
| 184 |
+
torch.cuda.empty_cache()
|
| 185 |
+
|
| 186 |
+
if cnt:
|
| 187 |
+
print("\n" + "=" * 70)
|
| 188 |
+
print(f"mean KL (both seeds reach): {sumKL/cnt:.4f} <- should be LOW (both correct)")
|
| 189 |
+
print(f"mean cross-seed L2: {sumL2/cnt:.4f} <- the MSE floor from non-uniqueness")
|
| 190 |
+
print(f"mean ||target||^2/token: {sum_selfE/cnt:.4f}")
|
| 191 |
+
print("=" * 70)
|
| 192 |
+
print("If KL low AND crossL2 ~ the regression floor (~1.1): targets are NON-UNIQUE")
|
| 193 |
+
print(" (soft-prompt symmetry) -> MSE-to-vector is the wrong loss; use KL distillation.")
|
| 194 |
+
print("If crossL2 ~ 0: targets unique -> regression floor is capacity/optimization.")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
main()
|