File size: 8,912 Bytes
f80e81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Stream the LittleBoy checkpoint shard by shard through the k3ref reference and measure per-token loss of
BOTH the base model (experts >= 896 masked out, which is exactly Kimi K3.1-Pro) and LittleBoy, in one pass.

Runs on a single GPU (Colab A100/H100). Each shard is downloaded, used for one layer, then deleted, so the disk peak
is ~2 shards. Texts: a JSONL file with {"id", "text", "set"}; each text is tokenised and cut to --seq tokens.

    python k3stream.py --texts eval.jsonl --seq 2048 --batch 8 --out out/ [--cache-layer K]

Output: out/nll_{base,littleboy}.pt (per-token NLL, [n_seq, seq-1]) and out/summary.json (mean NLL and perplexity
per set, routing share of the new experts per layer). With --cache-layer K the state entering layer K is saved for
both models (frozen-prefix training of the top block).
"""
from __future__ import annotations

import argparse
import json
import math
import os
import threading
import time
from pathlib import Path

import torch
from huggingface_hub import hf_hub_download
from safetensors import safe_open

import k3ref as K

REPO = "STAR-future/Trinity"
BASE = "moonshotai/Kimi-K3.1-Pro"


def say(*a):
    print(time.strftime("%H:%M:%S"), *a, flush=True)


def shard_name(i: int) -> str:
    return f"model-{i:05d}-of-000096.safetensors"


class Prefetch:
    """Download shard files one ahead of use."""

    def __init__(self, repo, tok, work):
        self.repo, self.tok, self.work = repo, tok, work
        self.paths, self.threads = {}, {}

    def _get(self, s):
        for k in range(5):
            try:
                self.paths[s] = hf_hub_download(self.repo, s, token=self.tok, local_dir=self.work)
                return
            except Exception as e:  # noqa: BLE001
                say("download retry", s, k, e)
                time.sleep(30 * (k + 1))
        raise RuntimeError("download failed: " + s)

    def start(self, s):
        if s not in self.threads:
            self.threads[s] = threading.Thread(target=self._get, args=(s,), daemon=True)
            self.threads[s].start()

    def get(self, s):
        self.start(s)
        self.threads[s].join()
        return self.paths[s]


def layer_weights(path: str, L: int, dev, experts_on_gpu: bool) -> dict:
    pre = f"language_model.model.layers.{L}."
    W, ex = {}, {}
    with safe_open(path, framework="pt", device="cpu") as f:
        for key in f.keys():
            if not key.startswith(pre):
                continue
            rest = key[len(pre):]
            if ".indexer." in rest:
                continue
            if ".experts." in rest:
                _, _, e, w, kind = rest.split(".")          # block_sparse_moe.experts.E.wN.weight_packed|scale
                ex.setdefault(int(e), {})[(w, kind)] = f.get_tensor(key)
                continue
            for p in ("self_attn.", "block_sparse_moe."):
                if rest.startswith(p):
                    rest = rest[len(p):]
            if rest == "gate.e_score_correction_bias":
                rest = "e_score_correction_bias"
            if rest.endswith(".weight"):
                rest = rest[: -len(".weight")]
            W[rest] = f.get_tensor(key).to(dev)
    if ex:
        n = max(ex) + 1
        pk = {w: torch.stack([ex[e][(w, "weight_packed")] for e in range(n)]) for w in ("w1", "w2", "w3")}
        sc = {w: torch.stack([ex[e][(w, "weight_scale")] for e in range(n)]) for w in ("w1", "w2", "w3")}
        if experts_on_gpu:
            pk = {w: t.to(dev) for w, t in pk.items()}
            sc = {w: t.to(dev) for w, t in sc.items()}

        def experts(e, pk=pk, sc=sc):
            return tuple(K.dequant(pk[w][e].to(dev, non_blocking=True), sc[w][e].to(dev, non_blocking=True))
                         for w in ("w1", "w2", "w3"))

        W["experts"] = experts
        W["_n_experts"] = n
    return W


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--texts", required=True)
    ap.add_argument("--seq", type=int, default=2048)
    ap.add_argument("--batch", type=int, default=8)
    ap.add_argument("--max-seqs", type=int, default=16)
    ap.add_argument("--out", required=True)
    ap.add_argument("--work", default="/content/lbshards")
    ap.add_argument("--cache-layer", type=int, default=-1)
    ap.add_argument("--layers", type=int, default=-1, help="debug: stop after this many layers")
    ap.add_argument("--modes", default="base,littleboy")
    a = ap.parse_args()
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    tok_hf = os.environ.get("HF_TOKEN")
    dev = torch.device("cuda")
    torch.backends.cuda.matmul.allow_tf32 = True

    cfg_path = hf_hub_download(BASE, "config.json")       # LittleBoy's own config.json is added at finalisation
    tc = json.loads(Path(cfg_path).read_text())["text_config"]
    c = K.Cfg(tc)
    from transformers import AutoTokenizer
    tokenizer = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True)

    rows = [json.loads(ln) for ln in Path(a.texts).read_text(encoding="utf-8").splitlines() if ln.strip()]
    seqs, meta = [], []
    for r in rows:
        ids = tokenizer.encode(r["text"])
        if len(ids) >= a.seq:
            seqs.append(ids[: a.seq])
            meta.append({"id": r["id"], "set": r.get("set", "default")})
        if len(seqs) >= a.max_seqs:
            break
    if not seqs:
        raise SystemExit("no text long enough for --seq")
    ids = torch.tensor(seqs, dtype=torch.long)
    say("sequences", ids.shape, "sets", sorted({m["set"] for m in meta}))
    modes = a.modes.split(",")
    free = torch.cuda.mem_get_info()[0] / 2 ** 30
    experts_on_gpu = free > 60
    say("GPU free GiB", round(free, 1), "experts on GPU:", experts_on_gpu)

    pf = Prefetch(REPO, tok_hf, a.work)
    last = shard_name(94)
    pf.start(last)
    pf.start(shard_name(1))
    with safe_open(pf.get(last), framework="pt", device="cpu") as f:
        emb_w = f.get_tensor("language_model.model.embed_tokens.weight")
        Wf = {"output_attn_res_norm": f.get_tensor("language_model.model.output_attn_res_norm.weight").to(dev),
              "output_attn_res_proj": f.get_tensor("language_model.model.output_attn_res_proj.weight").to(dev),
              "norm": f.get_tensor("language_model.model.norm.weight").to(dev)}
        lm_head = f.get_tensor("language_model.lm_head.weight").to(dev)
    batches = [ids[i:i + a.batch] for i in range(0, len(ids), a.batch)]
    states = {m: [K.init_state(emb_w[b].to(dev), c) for b in batches] for m in modes}
    del emb_w
    stats = {m: {} for m in modes}
    n_layers = c.n_layers if a.layers < 0 else a.layers
    for L in range(n_layers):
        s = shard_name(L + 1)
        if L + 2 <= 93:
            pf.start(shard_name(L + 2))
        t0 = time.time()
        path = pf.get(s)
        W = layer_weights(path, L, dev, experts_on_gpu)
        t1 = time.time()
        if L == a.cache_layer:
            torch.save({m: [{k: (v.cpu() if torch.is_tensor(v) else v) for k, v in st.items()} for st in states[m]]
                        for m in modes}, out / f"state_in_layer{L}.pt")
        with torch.no_grad():
            for m in modes:
                for st in states[m]:
                    K.forward_layer(L, W, c, st, mask_new=(m == "base"), stats=stats[m].setdefault(L, {}))
        torch.cuda.synchronize()
        share = {m: round(sum(stats[m][L].get("new_share", [0])) / max(1, len(stats[m][L].get("new_share", [0]))), 4)
                 for m in modes}
        say(f"layer {L} load {t1 - t0:.0f}s compute {time.time() - t1:.0f}s new-share {share}")
        del W
        if L > 0:
            Path(path).unlink(missing_ok=True)
    res = {"seq": a.seq, "n_seqs": len(seqs), "layers_run": n_layers, "modes": {}}
    with torch.no_grad():
        for m in modes:
            # tgt_nll[i, t] is the loss of predicting token t+1 from tokens <= t
            tgt_nll = torch.cat([K.token_nll(K.final_hidden(st, Wf, c)[:, :-1].contiguous(), lm_head, b[:, 1:].to(dev))
                                 for st, b in zip(states[m], batches)])
            torch.save(tgt_nll.cpu(), out / f"nll_{m}.pt")
            per_set = {}
            for sname in sorted({x["set"] for x in meta}):
                rows_i = [i for i, x in enumerate(meta) if x["set"] == sname]
                v = float(tgt_nll[rows_i].mean())
                per_set[sname] = {"mean_nll": v, "ppl": math.exp(v), "n_seqs": len(rows_i)}
            res["modes"][m] = {"per_set": per_set,
                               "new_share_by_layer": {L: sum(d.get("new_share", [0])) / max(1, len(d.get("new_share", [0])))
                                                      for L, d in stats[m].items()}}
    res["meta"] = meta
    (out / "summary.json").write_text(json.dumps(res, indent=1))
    say("DONE", json.dumps({m: res["modes"][m]["per_set"] for m in modes}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())