File size: 5,001 Bytes
fb9e149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Broad ecosystem screen: how many RELEASED Llama-3.1-8B derivatives have actually left the base
model's coordinate frame? Streams one model at a time (download -> screen -> delete) so the disk
footprint stays at one checkpoint."""
import os, sys, json, time, gc, shutil, traceback
sys.path.insert(0, "/root/merge-accuracy")
import numpy as np, torch
from huggingface_hub import snapshot_download, hf_hub_download
import ma_common as C, gmap
from cheap_screen import screen
from mergeschool.core import alignment as AL

OUT = "/root/merge-accuracy/results/ecosystem_screen.json"
CACHE = "/root/hf_cache_mergeacc"
BASE = "meta-llama/Llama-3.1-8B"
CAND = [
    ("NousResearch/Hermes-3-Llama-3.1-8B", "instruct post-training", "Nous Research"),
    ("allenai/Llama-3.1-Tulu-3-8B-SFT", "instruct SFT", "AI2"),
    ("dphn/Dolphin3.0-Llama3.1-8B", "instruct post-training", "Dolphin"),
    ("meta-llama/Llama-Guard-3-8B", "safety classifier", "Meta"),
    ("fdtn-ai/Foundation-Sec-8B", "domain CPT (security)", "Foundation AI"),
    ("OpenSciLM/Llama-3.1_OpenScholar-8B", "domain CPT (science)", "OpenSciLM"),
    ("nvidia/OpenMath2-Llama3.1-8B", "domain SFT (maths)", "NVIDIA"),
    ("NCSOFT/Llama-VARCO-8B-Instruct", "language CPT (Korean)", "NCSOFT"),
    ("McGill-NLP/AfriqueLlama-8B", "language CPT (African)", "McGill NLP"),
    ("Yiddish-NLP/MameLoshnLM", "language CPT (Yiddish)", "Yiddish-NLP"),
    ("deepcogito/cogito-v1-preview-llama-8B", "instruct post-training", "Deep Cogito"),
    ("tokyotech-llm/Llama-3.1-Swallow-8B-v0.2", "language CPT (Japanese)", "TokyoTech"),
    ("aisingapore/Llama-SEA-LION-v3-8B", "language CPT (SEA)", "AI Singapore"),
    ("microsoft/UserLM-8b", "role post-training", "Microsoft"),
]
res = json.load(open(OUT)) if os.path.exists(OUT) else {}

mb = C.load_model(BASE, dev="cpu", dtype=torch.float32)
sd_base = C.sd_np(mb); cfg = mb.config
HID, NH, NKV, VOC = cfg.hidden_size, cfg.num_attention_heads, cfg.num_key_value_heads, cfg.vocab_size
del mb; gc.collect()
print(f"base ready HID={HID} NH={NH} NKV={NKV}", flush=True)

for repo, kind, group in CAND:
    if repo in res: continue
    d = None
    try:
        cfp = hf_hub_download(repo, "config.json", cache_dir=CACHE)
        c = json.load(open(cfp))
        if (c.get("hidden_size") != HID or c.get("num_attention_heads") != NH
                or c.get("num_key_value_heads") != NKV or c.get("vocab_size") != VOC
                or c.get("num_hidden_layers") != cfg.num_hidden_layers):
            res[repo] = {"kind": kind, "group": group, "status": "shape mismatch",
                         "config": {k: c.get(k) for k in ("hidden_size", "num_attention_heads",
                                                          "num_key_value_heads", "vocab_size",
                                                          "num_hidden_layers")}}
            print(f"SKIP {repo}: shape mismatch", flush=True)
            json.dump(res, open(OUT, "w"), indent=1); continue
        t0 = time.time()
        d = snapshot_download(repo, allow_patterns=["*.safetensors", "*.json", "tokenizer*"],
                              cache_dir=CACHE, max_workers=8)
        dl = time.time() - t0
        m = C.load_model(repo, dev="cpu", dtype=torch.float32)
        sd = C.sd_np(m); del m; gc.collect()
        t = time.time(); f_id, pres = screen(sd, sd_base, HID); dt = time.time() - t
        keys = C.shared_keys(sd_base, sd)
        a = np.concatenate([sd_base[k].ravel() for k in keys])
        b = np.concatenate([sd[k].ravel() for k in keys])
        wc = float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
        rd = float(np.linalg.norm(a - b) / np.linalg.norm(a))
        del a, b, sd; gc.collect()
        res[repo] = {"kind": kind, "group": group, "status": "screened",
                     "identity_fraction_worst_layer": f_id, "screen_seconds": dt,
                     "download_seconds": dl, "layers_screened": len(pres),
                     "weight_cosine_vs_base": wc, "rel_drift": rd,
                     "frame_has_drifted": bool(f_id < 0.95)}
        print(f"{repo:48s} id_frac={f_id:.4f} wcos={wc:.4f} drift={rd:.4f} "
              f"-> {'DRIFTED' if f_id < 0.95 else 'same frame'}  ({dt:.0f}s)", flush=True)
        json.dump(res, open(OUT, "w"), indent=1)
    except Exception:
        res[repo] = {"kind": kind, "group": group, "status": "error",
                     "error": traceback.format_exc()[-400:]}
        print(f"ERR {repo}: {traceback.format_exc()[-250:]}", flush=True)
        json.dump(res, open(OUT, "w"), indent=1)
    finally:
        # stream and delete: keep at most one candidate checkpoint on disk
        keep = ("Llama-3.1-8B", "Llama-3.1-8B-Instruct", "Swallow-8B-v0.1",
                "typhoon2", "sea-lionv3-base")
        if not any(k in repo for k in keep):
            p = f"{CACHE}/models--" + repo.replace("/", "--")
            if os.path.isdir(p):
                shutil.rmtree(p, ignore_errors=True)
        gc.collect()
print("SWEEP_DONE", flush=True)