File size: 11,518 Bytes
e87a0a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5ef3bb
 
 
e87a0a7
 
 
 
 
 
 
 
 
e5ef3bb
e87a0a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5ef3bb
 
e87a0a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5ef3bb
e87a0a7
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""SET 4: Goldfish monolingual -> bilingual merge on the REAL composition models.
goldfish-models/eng_latn_1000mb x goldfish-models/{nld,spa,ell,pol}_*_1000mb (GPT-2, 125M each,
SEPARATE monolingual tokenizers). Rungs: M0 naive average (the merge the manuscript reports as
failing) vs M1 vocab-remapped + unit-aligned (permutation / Procrustes on the residual basis,
free MLP axis, attention heads).

METRIC: Delta-floor in NATS PER UTF-8 BYTE on FLORES-200 devtest. Bytes, not tokens: the two
parents use different tokenizers, so nats/token is not comparable across them. This is a
LIKELIHOOD metric, not benchmark accuracy."""
import os, sys, json, time, argparse, gc
sys.path.insert(0, "/root/compose-audit")
from common import *
import gpt2_align as G2
from mergeschool.core.models import load_hf

ap = argparse.ArgumentParser()
ap.add_argument("--pairs", default="nld_Latn:nld_latn,spa_Latn:spa_latn,ell_Grek:ell_grek,pol_Latn:pol_latn")
ap.add_argument("--n_sent", type=int, default=500)
ap.add_argument("--bs", type=int, default=8)
ap.add_argument("--barrier_n", type=int, default=7)
A = ap.parse_args()
OUT = "/root/compose-audit/results/set4_goldfish.jsonl"
DEV = "cuda"
ENG_REPO = "goldfish-models/eng_latn_1000mb"


def log(*a):
    print(f"[{time.strftime('%H:%M:%S')}]", *a, flush=True)


# ------------------------------------------------------------------ tokenizer-invariant eval
def build_blocks(tok, text, block=512, max_blocks=64):
    ids = tok(text)["input_ids"]
    n = max(1, min(max_blocks, len(ids) // block))
    ids = ids[: n * block]
    arr = torch.from_numpy(np.asarray(ids, dtype=np.int64).reshape(n, block))
    nbytes = sum(len(tok.decode(list(arr[i, 1:].numpy())).encode("utf-8")) for i in range(n))
    return arr, nbytes


@torch.no_grad()
def nll_total(model, blocks, dev, bs=8):
    tot, ntok = 0.0, 0
    for i in range(0, blocks.shape[0], bs):
        x = blocks[i:i + bs].to(dev)
        lp = torch.log_softmax(model(x).logits.float()[:, :-1], -1)
        tgt = x[:, 1:]
        tot += (-lp.gather(-1, tgt.unsqueeze(-1)).squeeze(-1)).sum().item()
        ntok += tgt.numel()
    return tot, ntok


@torch.no_grad()
def sent_acts(model, tok, lines, dev, bs=16, maxlen=128):
    """Mean-pooled per-sentence residual activations, {layer: (n_sent, d)} -- rows are matched
    ACROSS LANGUAGES by FLORES sentence id, which is what makes a cross-lingual basis map fittable."""
    outs = None
    for i in range(0, len(lines), bs):
        enc = tok(lines[i:i + bs], return_tensors="pt", padding=True, truncation=True, max_length=maxlen)
        ids = enc["input_ids"].to(dev); am = enc["attention_mask"].to(dev).float()
        hs = model(ids, attention_mask=enc["attention_mask"].to(dev), output_hidden_states=True).hidden_states
        if outs is None:
            outs = [[] for _ in hs]
        w = am / am.sum(1, keepdim=True).clamp(min=1)
        for j, h in enumerate(hs):
            outs[j].append((h.float() * w.unsqueeze(-1)).sum(1).cpu())
    return {j: torch.cat(o).numpy().astype(np.float64) for j, o in enumerate(outs)}


# ------------------------------------------------------------------ load English parent
log("loading eng parent")
m_e, tok_e = load_hf(ENG_REPO, dtype=torch.float32, device=DEV)
m_e.eval()
cfg = m_e.config
D, NH, NL, V = cfg.n_embd, cfg.n_head, cfg.n_layer, cfg.vocab_size
SD_E = sd_np(m_e)
log(f"gpt2 d={D} heads={NH} layers={NL} vocab={V}")

eng_lines = flores_lines("eng_Latn")[: A.n_sent]
eng_text = "\n".join(eng_lines)
bl_e_e, by_e_e = build_blocks(tok_e, eng_text)           # eng text, eng tokenizer
acts_e = sent_acts(m_e, tok_e, eng_lines, DEV)
shell = m_e                                              # reuse as the eval shell (eng tokenizer space)


def ev_np(sd, blocks):
    sd_load(shell, sd, DEV)
    t, n = nll_total(shell, blocks, DEV, bs=A.bs)
    return t, n


nll_e_eng_t, nll_e_eng_n = nll_total(m_e, bl_e_e, DEV, bs=A.bs)
PARENT_ENG = {"nats_per_byte": nll_e_eng_t / by_e_e, "nats_per_token": nll_e_eng_t / nll_e_eng_n}
log(f"eng parent on eng: {PARENT_ENG}")

done = set()
if os.path.exists(OUT):
    for line in open(OUT):
        try: done.add(json.loads(line)["lang"])
        except Exception: pass
fh = open(OUT, "a")

for spec in A.pairs.split(","):
    fcode, gcode = spec.split(":")
    if fcode in done:
        log("skip", fcode); continue
    t0 = time.time()
    repo = f"goldfish-models/{gcode}_1000mb"
    log(f"=== {fcode} <- {repo}")
    m_x, tok_x = load_hf(repo, dtype=torch.float32, device=DEV); m_x.eval()
    SD_X = sd_np(m_x)
    x_lines = flores_lines(fcode)[: A.n_sent]
    x_text = "\n".join(x_lines)
    bl_x_x, by_x_x = build_blocks(tok_x, x_text)         # X text, X tokenizer  (X parent's own floor)
    bl_x_e, by_x_e = build_blocks(tok_e, x_text)         # X text, ENG tokenizer (merged model's space)
    acts_x = sent_acts(m_x, tok_x, x_lines, DEV)
    tx, nx = nll_total(m_x, bl_x_x, DEV, bs=A.bs)
    parent_x = {"nats_per_byte": tx / by_x_x, "nats_per_token": tx / nx}
    del m_x; torch.cuda.empty_cache()
    te, ne = ev_np(SD_E, bl_x_e)                          # eng parent on X text
    eng_on_x = {"nats_per_byte": te / by_x_e, "nats_per_token": te / ne}
    log(f"  parents: eng/eng={PARENT_ENG['nats_per_byte']:.4f}  x/x={parent_x['nats_per_byte']:.4f}  "
        f"eng-on-x={eng_on_x['nats_per_byte']:.4f} nats/byte")

    # ------------- vocabulary transport (the OTHER axis: token ids, not the residual basis)
    vkeys = [k for k in SD_X if k.endswith("wte.weight") or k.endswith("lm_head.weight")]
    SD_X_V, cov = AL.remap_vocab_rows(SD_X, tok_e, tok_x, V, keys=vkeys)
    for k in vkeys:
        W = np.asarray(SD_X_V[k], float)
        bad = ~np.isfinite(W).all(axis=1) if W.shape[0] == V else ~np.isfinite(W).all(axis=0)
        if W.shape[0] == V:
            W[bad] = np.asarray(SD_E[k], float)[bad]     # unshared ids: keep English's row (no-op merge)
        SD_X_V[k] = W
    anchors = AL.vocab_anchors(tok_e, tok_x)
    log(f"  vocab anchors={len(anchors)} ({len(anchors)/V:.1%} of English ids)")

    BODY = [k for k in SD_E if not (k.endswith("wte.weight") or k.endswith("lm_head.weight"))]

    # ------------- alignments (fitted BEFORE merging)
    R_emb, n_anch = G2.emb_procrustes(SD_E, SD_X, tok_e, tok_x)
    sd_emb = G2.apply_resid(SD_X_V, D, R=R_emb)
    sd_emb2, _ = G2.align_full(SD_E, sd_emb, D, NH, None, None, "permutation", body_keys=BODY)
    sdp, ip = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "permutation", body_keys=BODY)
    sdo, io = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "orthogonal", body_keys=BODY)
    sdpf, ipf = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "permutation", body_keys=BODY, accept_each=False)
    sdof, iof = G2.align_full(SD_E, SD_X_V, D, NH, acts_e, acts_x, "orthogonal", body_keys=BODY, accept_each=False)
    log(f"  align perm={ip} orth={io}")

    # ------------- predictors (pre-merge)
    KEYS = shared_keys(SD_E, SD_X)
    fa, fb = flat(SD_E, KEYS), flat(SD_X, KEYS)
    p = {"n_emb_anchors": n_anch, "weight_cosine": float(fa @ fb / (np.linalg.norm(fa) * np.linalg.norm(fb))),
         "vocab_overlap": len(anchors) / V}
    p["weight_cosine_body"] = float(np.mean([
        float(np.asarray(SD_E[k], float).ravel() @ np.asarray(SD_X[k], float).ravel() /
              (np.linalg.norm(SD_E[k]) * np.linalg.norm(SD_X[k]) + 1e-12)) for k in BODY]))
    q_p = MT.quotient_weight_distance(SD_E, SD_X_V, sdp, BODY)
    q_o = MT.quotient_weight_distance(SD_E, SD_X_V, sdo, BODY)
    p.update({"d_raw": q_p["d_raw"], "qmd_perm": q_p["qmd"], "coord_share_perm": q_p["coord_fraction"],
              "qmd_orth": q_o["qmd"], "coord_share_orth": q_o["coord_fraction"]})
    b_raw = AL.block_normalised_distance(SD_E, SD_X_V, BODY)
    b_p = AL.block_normalised_distance(SD_E, sdp, BODY)
    b_o = AL.block_normalised_distance(SD_E, sdo, BODY)
    p.update({"bnd_raw": b_raw, "bnd_perm": b_p, "bnd_orth": b_o,
              "coord_share_bnd_perm": float((b_raw - b_p) / b_raw),
              "coord_share_bnd_orth": float((b_raw - b_o) / b_raw)})
    ck, ckby = mean_cka(acts_e, acts_x)
    p["cka_mean"] = ck; p["cka_last"] = ckby[max(ckby)]
    for g in ("perm", "procrustes", "ot"):
        try:
            qr = MT.quotient_residual(acts_e[NL // 2], acts_x[NL // 2], group=g)
            p[f"qmd_act_{g}"] = qr["distance"]; p[f"aligned_cka_{g}"] = qr["aligned_cka"]
        except Exception:
            p[f"qmd_act_{g}"] = float("nan")

    # ------------- merge rungs
    rungs = {"M0_naive_avg": MG.average([SD_E, SD_X]),
             "M1a_vocab_avg": MG.average([SD_E, SD_X_V]),
             "M1b_vocab_perm_avg": MG.average([SD_E, sdp]),
             "M1c_vocab_orth_avg": MG.average([SD_E, sdo]),
             "M1d_vocab_perm_forced": MG.average([SD_E, sdpf]),
             "M1e_vocab_orth_forced": MG.average([SD_E, sdof]),
             "M1g_emb_procrustes": MG.average([SD_E, sd_emb]),
             "M1h_emb_proc_units": MG.average([SD_E, sd_emb2]),
             "M1f_perm_novocab": MG.average([SD_E, G2.align_full(SD_E, SD_X, D, NH, acts_e, acts_x, "permutation", body_keys=BODY)[0]])}
    res = {}
    for name, sd in rungs.items():
        t_e, n_e = ev_np(sd, bl_e_e)
        t_x, n_x = ev_np(sd, bl_x_e)
        res[name] = {
            "eng": {"nats_per_byte": t_e / by_e_e, "nats_per_token": t_e / n_e},
            "x":   {"nats_per_byte": t_x / by_x_e, "nats_per_token": t_x / n_x},
            "delta_floor_eng": t_e / by_e_e - PARENT_ENG["nats_per_byte"],
            "delta_floor_x": t_x / by_x_e - min(parent_x["nats_per_byte"], eng_on_x["nats_per_byte"]),
        }
        res[name]["delta_floor_mean"] = 0.5 * (res[name]["delta_floor_eng"] + res[name]["delta_floor_x"])
    for name in res:
        res[name]["delta_vs_naive_mean"] = res[name]["delta_floor_mean"] - res["M0_naive_avg"]["delta_floor_mean"]

    r = {"set": "set4_goldfish", "lang": fcode, "repo_a": ENG_REPO, "repo_b": repo,
         "corpus": "flores200_devtest", "n_sent": A.n_sent,
         "metric": "nats_per_utf8_byte (likelihood, NOT benchmark accuracy)",
         "parents": {"eng_on_eng": PARENT_ENG, "x_on_x": parent_x, "eng_on_x": eng_on_x},
         "floor_eng": PARENT_ENG["nats_per_byte"],
         "floor_x": min(parent_x["nats_per_byte"], eng_on_x["nats_per_byte"]),
         "align_info": {"perm": ip, "orth": io, "perm_forced": ipf, "orth_forced": iof}, "predictors": p, "rungs": res}

    # ------------- barriers on the mean nats/byte
    def ev_mean(sd):
        t_e, _ = ev_np(sd, bl_e_e); t_x, _ = ev_np(sd, bl_x_e)
        return 0.5 * (t_e / by_e_e + t_x / by_x_e)
    try:
        bn = EV.merge_barrier(SD_E, SD_X, ev_mean, n=A.barrier_n)
        r["barrier_naive"] = {"barrier": bn["barrier"], "losses": list(map(float, bn["losses"]))}
        bp = EV.merge_barrier(SD_E, sdp, ev_mean, n=A.barrier_n)
        r["barrier_perm"] = {"barrier": bp["barrier"], "losses": list(map(float, bp["losses"]))}
    except Exception as e:
        log("barrier failed", e)

    r["secs"] = time.time() - t0
    fh.write(json.dumps(r) + "\n"); fh.flush()
    log(f"  {fcode}: M0 dfloor_mean={res['M0_naive_avg']['delta_floor_mean']:+.4f}  "
        f"M1a={res['M1a_vocab_avg']['delta_floor_mean']:+.4f}  "
        f"M1b_perm={res['M1b_vocab_perm_avg']['delta_floor_mean']:+.4f}  "
        f"M1c_orth={res['M1c_vocab_orth_avg']['delta_floor_mean']:+.4f}  ({r['secs']:.0f}s)")
    del rungs, sdp, sdo, sdpf, sdof, sd_emb, sd_emb2, SD_X, SD_X_V; gc.collect()
fh.close()
log("DONE set4")