File size: 6,359 Bytes
47a719e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SET 4, REVERSE direction: the partner language is the anchor, English is transported into it.

Same four Goldfish pairs, same rungs, same metric — but the merged model now lives in the PARTNER
language's tokenizer and residual basis. If the composition failure were an artifact of anchoring on
English (English rows filling every unshared id, English tokenizer scoring the partner text), it
would not survive the swap."""
import os, sys, json, time, argparse, gc
sys.path.insert(0, "/root/compose-audit")
from common import *
import gpt2_align as G2
from set4_goldfish_lib import sent_acts
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_reverse.jsonl"
DEV = "cuda"
ENG_REPO = "goldfish-models/eng_latn_1000mb"


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


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


@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


eng_lines = flores_lines("eng_Latn")[: A.n_sent]
eng_text = "\n".join(eng_lines)
m_e, tok_e = load_hf(ENG_REPO, dtype=torch.float32, device=DEV); m_e.eval()
SD_E = sd_np(m_e)
cfg = m_e.config
D, NH, NL, V = cfg.n_embd, cfg.n_head, cfg.n_layer, cfg.vocab_size
acts_e = sent_acts(m_e, tok_e, eng_lines, DEV)
bl_e_e, by_e_e = build_blocks(tok_e, eng_text)
te0, _ = nll_total(m_e, bl_e_e, DEV, bs=A.bs)
ENG_ON_ENG = te0 / by_e_e
del m_e; torch.cuda.empty_cache()
log(f"eng parent on eng (own tok) = {ENG_ON_ENG:.4f} nats/byte")

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

for spec in A.pairs.split(","):
    fcode, gcode = spec.split(":")
    if fcode in done: continue
    t0 = time.time()
    repo = f"goldfish-models/{gcode}_1000mb"
    log(f"=== ANCHOR={fcode}  transporting {ENG_REPO} into it")
    m_x, tok_x = load_hf(repo, dtype=torch.float32, device=DEV); m_x.eval()
    SD_X = sd_np(m_x)                       # ANCHOR  (role "A")
    shell = m_x
    x_lines = flores_lines(fcode)[: A.n_sent]
    x_text = "\n".join(x_lines)
    acts_x = sent_acts(m_x, tok_x, x_lines, DEV)
    bl_x_x, by_x_x = build_blocks(tok_x, x_text)         # X text, X tok  (anchor space)
    bl_e_x, by_e_x = build_blocks(tok_x, eng_text)       # eng text, X tok (anchor space)
    tx, _ = nll_total(m_x, bl_x_x, DEV, bs=A.bs); X_ON_X = tx / by_x_x

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

    tex, _ = ev(SD_X, bl_e_x); X_ON_ENG = tex / by_e_x
    log(f"  parents: X/X={X_ON_X:.4f}  X-on-eng={X_ON_ENG:.4f}  eng/eng(own tok)={ENG_ON_ENG:.4f}")

    # transport ENGLISH into the anchor's id space
    vkeys = [k for k in SD_E if k.endswith("wte.weight") or k.endswith("lm_head.weight")]
    SD_E_V, cov = AL.remap_vocab_rows(SD_E, tok_x, tok_e, V, keys=vkeys)
    for k in vkeys:
        W = np.asarray(SD_E_V[k], float)
        if W.shape[0] == V:
            bad = ~np.isfinite(W).all(axis=1); W[bad] = np.asarray(SD_X[k], float)[bad]
        SD_E_V[k] = W
    anchors = AL.vocab_anchors(tok_x, tok_e)
    BODY = [k for k in SD_X if not (k.endswith("wte.weight") or k.endswith("lm_head.weight"))]
    R_emb, n_anch = G2.emb_procrustes(SD_X, SD_E, tok_x, tok_e)
    sd_emb = G2.apply_resid(SD_E_V, D, R=R_emb)
    sdp, ip = G2.align_full(SD_X, SD_E_V, D, NH, acts_x, acts_e, "permutation", body_keys=BODY)
    sdo, io = G2.align_full(SD_X, SD_E_V, D, NH, acts_x, acts_e, "orthogonal", body_keys=BODY)
    sdof, _ = G2.align_full(SD_X, SD_E_V, D, NH, acts_x, acts_e, "orthogonal", body_keys=BODY, accept_each=False)

    rungs = {"M0_naive_avg": MG.average([SD_X, SD_E]),
             "M1a_vocab_avg": MG.average([SD_X, SD_E_V]),
             "M1b_vocab_perm_avg": MG.average([SD_X, sdp]),
             "M1c_vocab_orth_avg": MG.average([SD_X, sdo]),
             "M1e_vocab_orth_forced": MG.average([SD_X, sdof]),
             "M1g_emb_procrustes": MG.average([SD_X, sd_emb])}
    res = {}
    for k, sd in rungs.items():
        t_x, n_x = ev(sd, bl_x_x); t_e, n_e = ev(sd, bl_e_x)
        res[k] = {"x": {"nats_per_byte": t_x / by_x_x, "nats_per_token": t_x / n_x},
                  "eng": {"nats_per_byte": t_e / by_e_x, "nats_per_token": t_e / n_e},
                  "delta_floor_x": t_x / by_x_x - X_ON_X,
                  "delta_floor_eng": t_e / by_e_x - min(X_ON_ENG, ENG_ON_ENG)}
        res[k]["delta_floor_mean"] = 0.5 * (res[k]["delta_floor_x"] + res[k]["delta_floor_eng"])
    for k in res:
        res[k]["delta_vs_naive_mean"] = res[k]["delta_floor_mean"] - res["M0_naive_avg"]["delta_floor_mean"]

    r = {"set": "set4_reverse", "lang": fcode, "anchor": fcode, "repo_a": repo, "repo_b": ENG_REPO,
         "corpus": "flores200_devtest", "n_sent": A.n_sent,
         "metric": "nats_per_utf8_byte (likelihood, NOT benchmark accuracy)",
         "parents": {"x_on_x": X_ON_X, "x_on_eng": X_ON_ENG, "eng_on_eng_own_tok": ENG_ON_ENG},
         "floor_x": X_ON_X, "floor_eng": min(X_ON_ENG, ENG_ON_ENG),
         "vocab_anchors": len(anchors), "align_info": {"perm": ip, "orth": io},
         "rungs": res, "secs": time.time() - t0}
    fh.write(json.dumps(r) + "\n"); fh.flush()
    log("  " + "  ".join(f"{k}: dfl_mean={v['delta_floor_mean']:+.4f}" for k, v in res.items()))
    del rungs, sdp, sdo, sdof, sd_emb, SD_E_V, m_x; gc.collect(); torch.cuda.empty_cache()
fh.close()
log("DONE set4_reverse")