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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
New mapping methods on top of the existing 25-anchor experiment data:
|
| 3 |
+
|
| 4 |
+
(f) procrustes Per-tensor orthogonal Procrustes alignment between
|
| 5 |
+
X-anchor and Y-anchor matrices in tensor-flat space.
|
| 6 |
+
Respects the LoRA gauge ambiguity better than ridge.
|
| 7 |
+
(g) topk_global_ridge Pick top-K anchors by X-side cosine similarity to X_target,
|
| 8 |
+
then run global anchor-basis ridge on that subset.
|
| 9 |
+
(h) topk_pertensor_ridge Same, but per-tensor ridge.
|
| 10 |
+
(i) topk_pertensor_mlp Top-K + per-tensor PCA-MLP hypernet (re-trained per task).
|
| 11 |
+
|
| 12 |
+
Reuses all training artifacts from /app/scaled/X and /app/scaled/Y.
|
| 13 |
+
"""
|
| 14 |
+
import os, json, gc, shutil, re, collections, math
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
from datasets import load_dataset
|
| 20 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, set_seed
|
| 21 |
+
from peft import PeftModel
|
| 22 |
+
from safetensors.torch import load_file, save_file
|
| 23 |
+
|
| 24 |
+
# Reuse main pipeline's task definitions
|
| 25 |
+
import sys; sys.path.insert(0, "/app")
|
| 26 |
+
import scaled_pipeline as sp
|
| 27 |
+
|
| 28 |
+
set_seed(42)
|
| 29 |
+
|
| 30 |
+
OUT = sp.OUT # /app/scaled
|
| 31 |
+
ANCHOR_NAMES = sp.ANCHOR_NAMES
|
| 32 |
+
HELDOUT_NAMES = sp.HELDOUT_NAMES
|
| 33 |
+
MODEL_Y = sp.MODEL_Y
|
| 34 |
+
EVAL_PER_TASK = sp.EVAL_PER_TASK
|
| 35 |
+
|
| 36 |
+
def load_sd(p): return {k: v.float().cpu() for k,v in load_file(str(p/"adapter_model.safetensors")).items()}
|
| 37 |
+
|
| 38 |
+
def parse_key(k):
|
| 39 |
+
m = re.search(r'layers\.(\d+)\.self_attn\.(\w+)_proj\.lora_(A|B)', k)
|
| 40 |
+
return int(m.group(1)), m.group(2), m.group(3)
|
| 41 |
+
|
| 42 |
+
def group_by_layer(sd):
|
| 43 |
+
g = collections.defaultdict(dict)
|
| 44 |
+
for k, v in sd.items():
|
| 45 |
+
L, mod, AB = parse_key(k)
|
| 46 |
+
g[(mod, AB)][L] = (k, v)
|
| 47 |
+
return g
|
| 48 |
+
|
| 49 |
+
def align_X_to_Y(X_anchors_list, X_target, Y_template_sd):
|
| 50 |
+
Y_g = group_by_layer(Y_template_sd)
|
| 51 |
+
X_gs = [group_by_layer(s) for s in X_anchors_list]
|
| 52 |
+
X_t = group_by_layer(X_target)
|
| 53 |
+
nLY = max(Y_g[("q","A")].keys()) + 1
|
| 54 |
+
nLX = max(X_gs[0][("q","A")].keys()) + 1
|
| 55 |
+
out = {}
|
| 56 |
+
for (mod, AB), layers in Y_g.items():
|
| 57 |
+
for L_y, (yk, _) in layers.items():
|
| 58 |
+
L_x = round(L_y * (nLX-1) / max(1, nLY-1))
|
| 59 |
+
x_anchors = [X_gs[i][(mod,AB)][L_x][1] for i in range(len(X_gs))]
|
| 60 |
+
x_target = X_t[(mod,AB)][L_x][1]
|
| 61 |
+
out[yk] = (x_anchors, x_target)
|
| 62 |
+
return out
|
| 63 |
+
|
| 64 |
+
# ----------------- (f) Procrustes -----------------
|
| 65 |
+
def procrustes_pred(X_anchors, Y_anchors, X_target):
|
| 66 |
+
"""Per-tensor orthogonal Procrustes (rectangular), avoiding dx*dy materialization.
|
| 67 |
+
Cross-covariance M = Xc^T Yc has rank ≤ N. Compute its SVD efficiently:
|
| 68 |
+
Xc = U_x S_x V_x^T (compact, V_x^T is (N, dx), V_x is (dx, N))
|
| 69 |
+
Yc = U_y S_y V_y^T
|
| 70 |
+
Then SVD(M) <- via N-by-N inner SVD; never materialize dx-by-dy.
|
| 71 |
+
"""
|
| 72 |
+
align = align_X_to_Y(X_anchors, X_target, Y_anchors[0])
|
| 73 |
+
out = {}
|
| 74 |
+
for yk, (x_anchors, x_target) in align.items():
|
| 75 |
+
Y_mat = torch.stack([s[yk].reshape(-1) for s in Y_anchors]) # (N, dy)
|
| 76 |
+
X_mat = torch.stack([t.reshape(-1) for t in x_anchors]) # (N, dx)
|
| 77 |
+
Ym, Xm = Y_mat.mean(0), X_mat.mean(0)
|
| 78 |
+
Yc, Xc = Y_mat - Ym, X_mat - Xm
|
| 79 |
+
Ux_, Sx_, Vxh = torch.linalg.svd(Xc, full_matrices=False)
|
| 80 |
+
Uy_, Sy_, Vyh = torch.linalg.svd(Yc, full_matrices=False)
|
| 81 |
+
C = (Sx_.unsqueeze(1) * Ux_.T) @ (Uy_ * Sy_.unsqueeze(0)) # (N, N)
|
| 82 |
+
Uz, Sz, Vzh = torch.linalg.svd(C, full_matrices=False)
|
| 83 |
+
scale = (Sz.sum() / (Sx_.pow(2).sum() + 1e-8)).item()
|
| 84 |
+
xt_c = x_target.reshape(-1) - Xm
|
| 85 |
+
a = Vxh @ xt_c # (N,)
|
| 86 |
+
b = (Uz @ Vzh) @ a # (N,)
|
| 87 |
+
delta = b @ Vyh # (dy,)
|
| 88 |
+
out[yk] = (Ym + scale * delta).reshape(Y_anchors[0][yk].shape)
|
| 89 |
+
return out
|
| 90 |
+
|
| 91 |
+
# ----------------- (g/h/i) top-K nearest anchor selection -----------------
|
| 92 |
+
def topk_anchor_idx(X_anchors, X_target, k=8):
|
| 93 |
+
"""Return indices of top-K anchors by cosine similarity to X_target."""
|
| 94 |
+
keys = sorted(X_anchors[0].keys())
|
| 95 |
+
Xa = torch.stack([torch.cat([s[kk].flatten() for kk in keys]) for s in X_anchors]) # (N, dx)
|
| 96 |
+
xt = torch.cat([X_target[kk].flatten() for kk in keys])
|
| 97 |
+
sims = F.cosine_similarity(Xa, xt.unsqueeze(0), dim=1)
|
| 98 |
+
idx = torch.topk(sims, k=min(k, len(X_anchors))).indices.tolist()
|
| 99 |
+
return idx, sims.tolist()
|
| 100 |
+
|
| 101 |
+
def topk_global_ridge(X_anchors, Y_anchors, X_target, k=8, ridge=1e-3):
|
| 102 |
+
idx, sims = topk_anchor_idx(X_anchors, X_target, k=k)
|
| 103 |
+
Xa = [X_anchors[i] for i in idx]
|
| 104 |
+
Ya = [Y_anchors[i] for i in idx]
|
| 105 |
+
pred, alpha = sp.global_ridge_pred(Xa, Ya, X_target, ridge=ridge)
|
| 106 |
+
return pred, idx, sims
|
| 107 |
+
|
| 108 |
+
def topk_pertensor_ridge(X_anchors, Y_anchors, X_target, k=8, ridge=1e-3):
|
| 109 |
+
idx, sims = topk_anchor_idx(X_anchors, X_target, k=k)
|
| 110 |
+
Xa = [X_anchors[i] for i in idx]
|
| 111 |
+
Ya = [Y_anchors[i] for i in idx]
|
| 112 |
+
pred = sp.pertensor_ridge_pred(Xa, Ya, X_target, ridge=ridge)
|
| 113 |
+
return pred, idx, sims
|
| 114 |
+
|
| 115 |
+
def topk_pertensor_mlp(X_anchors, Y_anchors, X_target, k=12, k_lat=6, epochs=300, lr=1e-3):
|
| 116 |
+
idx, sims = topk_anchor_idx(X_anchors, X_target, k=k)
|
| 117 |
+
Xa = [X_anchors[i] for i in idx]
|
| 118 |
+
Ya = [Y_anchors[i] for i in idx]
|
| 119 |
+
pred, _ = sp.pertensor_pca_mlp_pred(Xa, Ya, X_target, k_lat=k_lat, epochs=epochs, lr=lr)
|
| 120 |
+
return pred, idx, sims
|
| 121 |
+
|
| 122 |
+
# ----------------- save / eval -----------------
|
| 123 |
+
def save_adapter(sd, dirname, src_template):
|
| 124 |
+
d = OUT/"Y_pred"/dirname
|
| 125 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
shutil.copy(src_template/"adapter_config.json", d/"adapter_config.json")
|
| 127 |
+
save_file({k: v.to(torch.bfloat16) for k,v in sd.items()}, str(d/"adapter_model.safetensors"))
|
| 128 |
+
return d
|
| 129 |
+
|
| 130 |
+
@torch.no_grad()
|
| 131 |
+
def eval_adapter(adapter_dir, eval_ds, labels, tok, max_n=300):
|
| 132 |
+
base = AutoModelForCausalLM.from_pretrained(MODEL_Y, torch_dtype=torch.bfloat16, attn_implementation="eager").cuda()
|
| 133 |
+
if adapter_dir is None:
|
| 134 |
+
m = base
|
| 135 |
+
else:
|
| 136 |
+
m = PeftModel.from_pretrained(base, str(adapter_dir))
|
| 137 |
+
acc = sp.eval_classification(m, tok, eval_ds, labels, max_n=max_n)
|
| 138 |
+
del m, base
|
| 139 |
+
if adapter_dir is None: pass
|
| 140 |
+
gc.collect(); torch.cuda.empty_cache()
|
| 141 |
+
return acc
|
| 142 |
+
|
| 143 |
+
def cos_sd(sd1, sd2):
|
| 144 |
+
keys = sorted(sd1.keys())
|
| 145 |
+
a = torch.cat([sd1[k].float().flatten() for k in keys])
|
| 146 |
+
b = torch.cat([sd2[k].float().flatten() for k in keys])
|
| 147 |
+
return F.cosine_similarity(a.unsqueeze(0), b.unsqueeze(0)).item()
|
| 148 |
+
|
| 149 |
+
# ----------------- main -----------------
|
| 150 |
+
def main():
|
| 151 |
+
print("Loading anchors...")
|
| 152 |
+
X_anchors = [load_sd(OUT/"X"/n) for n in ANCHOR_NAMES]
|
| 153 |
+
Y_anchors = [load_sd(OUT/"Y"/n) for n in ANCHOR_NAMES]
|
| 154 |
+
print(f" N={len(X_anchors)} anchors")
|
| 155 |
+
|
| 156 |
+
tokY = AutoTokenizer.from_pretrained(MODEL_Y)
|
| 157 |
+
if tokY.pad_token is None: tokY.pad_token = tokY.eos_token
|
| 158 |
+
tokY.padding_side = "left"
|
| 159 |
+
|
| 160 |
+
out_results = {}
|
| 161 |
+
template = OUT/"Y"/ANCHOR_NAMES[0]
|
| 162 |
+
|
| 163 |
+
for t_name in HELDOUT_NAMES:
|
| 164 |
+
print(f"\n=== Held-out task: {t_name} ===")
|
| 165 |
+
X_target = load_sd(OUT/"X"/t_name)
|
| 166 |
+
Y_oracle = load_sd(OUT/"Y"/t_name)
|
| 167 |
+
|
| 168 |
+
results = {"cosines": {}, "acc": {}, "selected_anchors": {}}
|
| 169 |
+
|
| 170 |
+
# build predictions
|
| 171 |
+
preds = {}
|
| 172 |
+
print(" procrustes ...")
|
| 173 |
+
preds["procrustes"] = procrustes_pred(X_anchors, Y_anchors, X_target)
|
| 174 |
+
|
| 175 |
+
for k_top in [5, 8, 12]:
|
| 176 |
+
print(f" topk_global_ridge k={k_top} ...")
|
| 177 |
+
p, idx, sims = topk_global_ridge(X_anchors, Y_anchors, X_target, k=k_top)
|
| 178 |
+
preds[f"topk{k_top}_global_ridge"] = p
|
| 179 |
+
results["selected_anchors"][f"topk{k_top}"] = [ANCHOR_NAMES[i] for i in idx]
|
| 180 |
+
print(f" selected: {[ANCHOR_NAMES[i] for i in idx]}")
|
| 181 |
+
|
| 182 |
+
print(f" topk_pertensor_ridge k={k_top} ...")
|
| 183 |
+
p, _, _ = topk_pertensor_ridge(X_anchors, Y_anchors, X_target, k=k_top)
|
| 184 |
+
preds[f"topk{k_top}_pertensor_ridge"] = p
|
| 185 |
+
|
| 186 |
+
print(" topk12_pertensor_mlp ...")
|
| 187 |
+
p, _, _ = topk_pertensor_mlp(X_anchors, Y_anchors, X_target, k=12, k_lat=6, epochs=300)
|
| 188 |
+
preds["topk12_pertensor_mlp"] = p
|
| 189 |
+
|
| 190 |
+
# save and eval
|
| 191 |
+
_, eval_ds, labels = sp.build_task(t_name, n_train=10, n_eval=EVAL_PER_TASK)
|
| 192 |
+
|
| 193 |
+
# cosines
|
| 194 |
+
for n, sd in preds.items():
|
| 195 |
+
results["cosines"][n] = cos_sd(sd, Y_oracle)
|
| 196 |
+
|
| 197 |
+
# accuracies
|
| 198 |
+
results["acc"]["base_Y"] = eval_adapter(None, eval_ds, labels, tokY)
|
| 199 |
+
print(f" base_Y={results['acc']['base_Y']:.4f}")
|
| 200 |
+
for n, sd in preds.items():
|
| 201 |
+
d = save_adapter(sd, f"{t_name}_{n}", template)
|
| 202 |
+
acc = eval_adapter(d, eval_ds, labels, tokY)
|
| 203 |
+
results["acc"][n] = acc
|
| 204 |
+
print(f" {n:32s} cos={results['cosines'][n]:.4f} acc={acc:.4f}")
|
| 205 |
+
|
| 206 |
+
results["acc"]["oracle_Y"] = eval_adapter(OUT/"Y"/t_name, eval_ds, labels, tokY)
|
| 207 |
+
print(f" oracle_Y={results['acc']['oracle_Y']:.4f}")
|
| 208 |
+
|
| 209 |
+
out_results[t_name] = results
|
| 210 |
+
|
| 211 |
+
# aggregate
|
| 212 |
+
methods = ["base_Y","procrustes","topk5_global_ridge","topk5_pertensor_ridge",
|
| 213 |
+
"topk8_global_ridge","topk8_pertensor_ridge",
|
| 214 |
+
"topk12_global_ridge","topk12_pertensor_ridge","topk12_pertensor_mlp","oracle_Y"]
|
| 215 |
+
avg = {m: float(np.mean([out_results[t]["acc"][m] for t in HELDOUT_NAMES])) for m in methods}
|
| 216 |
+
print("\n=== AVG (new methods) ===")
|
| 217 |
+
for m in methods: print(f" {m:32s} {avg[m]:.4f}")
|
| 218 |
+
out_results["avg"] = avg
|
| 219 |
+
(OUT/"results_phaseA.json").write_text(json.dumps(out_results, indent=2, default=float))
|
| 220 |
+
|
| 221 |
+
if __name__ == "__main__":
|
| 222 |
+
main()
|