File size: 11,233 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""LittleBoy gate LB-B: specialise the last layer's BF16 parts on domain text, from the per-token cache of k3pass.py.



After the last layer's attention every token is independent, so with the cache (MoE input x, routed latent sum acc,

prefix at MoE time, output-mix block terms A/Z/m, target) the model output is a per-token function of the trainable

BF16 weights. Trained here, with LoRA merged back into BF16 (so the checkpoint keeps its exact stock format):

  shared_experts.{gate,up,down}_proj and routed_expert_up_proj of layer 92 (+ routed_expert_norm, full vector).

The routed experts, their router rows and everything before layer 92's MoE are unchanged.



Loss: cross-entropy on domain training tokens + kl_weight * KL(original || trained) on general replay tokens.

Selection: hyper-parameters chosen on a validation split of the TRAINING sequences only; the holdout is read once,

at the end, by evaluate(). Acceptance (preregistered in PREREG_LB_B.md) is computed by lb_tail_eval.py.



    python lb_tail_train.py --cache DIR --out DIR [--rank 64 --lr 2e-4 --epochs 2 --kl 1.0]

"""
from __future__ import annotations

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

import numpy as np
import torch
import torch.nn.functional as F
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"
L_LAST = 92
TRAINABLE = ["shared_experts.gate_proj", "shared_experts.up_proj", "shared_experts.down_proj", "routed_expert_up_proj"]


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


class LoRA(torch.nn.Module):
    def __init__(self, w: torch.Tensor, rank: int, alpha: float):
        super().__init__()
        self.w = w                                                   # frozen BF16 [out, in]
        self.a = torch.nn.Parameter(torch.randn(rank, w.shape[1], device=w.device) / math.sqrt(w.shape[1]))
        self.b = torch.nn.Parameter(torch.zeros(w.shape[0], rank, device=w.device))
        self.scale = alpha / rank

    def weight(self) -> torch.Tensor:
        return (self.w.float() + self.scale * (self.b @ self.a)).to(self.w.dtype)

    def merged(self) -> torch.Tensor:
        with torch.no_grad():
            return self.weight()


def load_tail(dev, tok):
    p93 = hf_hub_download(REPO, "model-00093-of-000096.safetensors", token=tok)
    p94 = hf_hub_download(REPO, "model-00094-of-000096.safetensors", token=tok)
    W = {}
    pre = f"language_model.model.layers.{L_LAST}.block_sparse_moe."
    with safe_open(p93, framework="pt", device="cpu") as f:
        for n in TRAINABLE + ["routed_expert_norm"]:
            W[n] = f.get_tensor(pre + n + ".weight").to(dev)
    with safe_open(p94, framework="pt", device="cpu") as f:
        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)
    return W, Wf, lm_head


class Cache:
    def __init__(self, d: Path):
        self.x = np.load(d / "x92.npy", mmap_mode="r")
        self.acc = np.load(d / "acc92.npy", mmap_mode="r")
        self.p = np.load(d / "prefix92.npy", mmap_mode="r")
        self.A = np.load(d / "A92.npy", mmap_mode="r")
        self.Zm = np.load(d / "Zm92.npy", mmap_mode="r")
        self.t = np.load(d / "target92.npy")
        s = json.loads((d / "streams.json").read_text())
        self.meta, self.T = s["meta"], s["seq"]

    def rows(self, pred) -> np.ndarray:
        """Token rows of the sequences for which pred(index, meta) holds; the last position has no target."""
        idx = [np.arange(i * self.T, (i + 1) * self.T - 1) for i, m in enumerate(self.meta) if pred(i, m)]
        return np.concatenate(idx) if idx else np.zeros(0, dtype=np.int64)

    def batch(self, r: np.ndarray, dev):
        r = np.sort(r)
        bf = lambda a: torch.from_numpy(np.ascontiguousarray(a[r])).view(torch.bfloat16).to(dev)  # noqa: E731
        f32 = lambda a: torch.from_numpy(np.ascontiguousarray(a[r])).to(dev)                     # noqa: E731
        zm = f32(self.Zm)
        return bf(self.x), f32(self.acc), bf(self.p), f32(self.A), zm[:, 0], zm[:, 1], torch.from_numpy(self.t[r]).to(dev)


def logits_of(x, acc, p, A, Z, m, W, Wf, lm_head, c):
    delta = K.moe_tail(acc, x, W, c)
    h = K.final_from_terms(p, delta, A, Z, m, Wf, c)
    return h @ lm_head.t()


def nll_rows(cache, rows, W, Wf, lm_head, c, dev, bs=2048):
    out = []
    with torch.no_grad():
        for i in range(0, len(rows), bs):
            x, acc, p, A, Z, m, t = cache.batch(rows[i:i + bs], dev)
            out.append(F.cross_entropy(logits_of(x, acc, p, A, Z, m, W, Wf, lm_head, c).float(), t, reduction="none").cpu())
    return torch.cat(out) if out else torch.zeros(0)


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--cache", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--rank", type=int, default=0, help="0 = full rank (amendment 1)")
    ap.add_argument("--alpha", type=float, default=64.0)
    ap.add_argument("--lr", type=float, default=2e-5)
    ap.add_argument("--epochs", type=float, default=2.0)
    ap.add_argument("--bs", type=int, default=2048)
    ap.add_argument("--kl", type=float, default=1.0)
    ap.add_argument("--val-frac", type=float, default=0.1)
    ap.add_argument("--seed", type=int, default=20261119)
    a = ap.parse_args()
    dev = torch.device("cuda")
    torch.manual_seed(a.seed)
    out = Path(a.out)
    out.mkdir(parents=True, exist_ok=True)
    c = K.Cfg(json.loads(Path(hf_hub_download(BASE, "config.json")).read_text())["text_config"])
    cache = Cache(Path(a.cache))
    W0, Wf, lm_head = load_tail(dev, os.environ.get("HF_TOKEN"))
    rng = np.random.default_rng(a.seed)
    train_seq = [i for i, m in enumerate(cache.meta) if m["role"] == "train"]
    rng.shuffle(train_seq)
    n_val = max(1, int(len(train_seq) * a.val_frac))
    val_seq = set(train_seq[:n_val])
    dom = lambda m: m["set"] != "wikipedia" and not m["set"].startswith("general")  # noqa: E731
    tr_dom = cache.rows(lambda i, m: m["role"] == "train" and dom(m) and i not in val_seq)
    tr_gen = cache.rows(lambda i, m: m["role"] == "train" and not dom(m) and i not in val_seq)
    va_dom = cache.rows(lambda i, m: m["role"] == "train" and dom(m) and i in val_seq)
    va_gen = cache.rows(lambda i, m: m["role"] == "train" and not dom(m) and i in val_seq)
    say("train domain tokens", len(tr_dom), "general replay tokens", len(tr_gen),
        "val domain tokens", len(va_dom), "val general tokens", len(va_gen))

    norm = torch.nn.Parameter(W0["routed_expert_norm"].float().clone())
    if a.rank > 0:                                       # low-rank variant (kept for comparison)
        lora = {n: LoRA(W0[n], a.rank, a.alpha) for n in TRAINABLE}
        params = [p for m in lora.values() for p in m.parameters() if p.requires_grad] + [norm]

        def Wcur():
            W = {n: lora[n].weight() for n in TRAINABLE}
            W["routed_expert_norm"] = norm.to(W0["routed_expert_norm"].dtype)
            return W

        def Wfinal():
            W = {n: lora[n].merged() for n in TRAINABLE}
            W["routed_expert_norm"] = norm.detach().to(W0["routed_expert_norm"].dtype)
            return W
    else:                                                # full rank (amendment 1): fp32 masters, BF16 in the forward
        master = {n: torch.nn.Parameter(W0[n].float().clone()) for n in TRAINABLE}
        params = list(master.values()) + [norm]

        def Wcur():
            W = {n: master[n].to(W0[n].dtype) for n in TRAINABLE}
            W["routed_expert_norm"] = norm.to(W0["routed_expert_norm"].dtype)
            return W

        def Wfinal():
            with torch.no_grad():
                return {k: v.detach().clone() for k, v in Wcur().items()}
    opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
    say("trainable parameters", sum(p.numel() for p in params))

    val0 = float(nll_rows(cache, va_dom, W0, Wf, lm_head, c, dev).mean())
    val_gen0 = float(nll_rows(cache, va_gen, W0, Wf, lm_head, c, dev).mean()) if len(va_gen) else None
    say("validation NLL before", round(val0, 5), "val_gen0", None if val_gen0 is None else round(val_gen0, 5))
    bs_d = min(a.bs, len(tr_dom))
    bs_g = min(a.bs // 2, len(tr_gen))
    steps = max(1, int(a.epochs * len(tr_dom) / max(1, bs_d)))
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=a.lr, total_steps=steps, pct_start=0.1)
    log = []
    for step in range(steps):
        opt.zero_grad(set_to_none=True)
        rd = rng.choice(tr_dom, bs_d, replace=False)
        x, acc, p, A, Z, m, t = cache.batch(rd, dev)
        loss_d = F.cross_entropy(logits_of(x, acc, p, A, Z, m, Wcur(), Wf, lm_head, c).float(), t)
        loss_d_val = float(loss_d.detach())
        loss_d.backward()                                # split-backward: frees domain logit graph before KL
        del loss_d, x, acc, p, A, Z, m, t
        kl_val = 0.0
        if a.kl > 0 and bs_g > 0:
            rg = rng.choice(tr_gen, bs_g, replace=False)
            xg, accg, pg, Ag, Zg, mg, _ = cache.batch(rg, dev)
            with torch.no_grad():
                ref = F.log_softmax(logits_of(xg, accg, pg, Ag, Zg, mg, W0, Wf, lm_head, c).float(), -1)
            cur = F.log_softmax(logits_of(xg, accg, pg, Ag, Zg, mg, Wcur(), Wf, lm_head, c).float(), -1)
            kl = F.kl_div(cur, ref, log_target=True, reduction="batchmean")
            kl_val = float(kl.detach())
            (a.kl * kl).backward()
            del kl, cur, ref, xg, accg, pg, Ag, Zg, mg
        torch.nn.utils.clip_grad_norm_(params, 1.0)
        opt.step()
        sched.step()
        if step % 20 == 0 or step == steps - 1:
            rec = {"step": step, "loss_domain": loss_d_val, "loss_kl": kl_val, "loss": loss_d_val + a.kl * kl_val}
            log.append(rec)
            say(json.dumps(rec))
    Wt = Wfinal()
    val1 = float(nll_rows(cache, va_dom, Wt, Wf, lm_head, c, dev).mean())
    val_gen1 = float(nll_rows(cache, va_gen, Wt, Wf, lm_head, c, dev).mean()) if len(va_gen) else None
    val_improved = val1 < val0
    say("validation NLL after", round(val1, 5), "relative", round((val1 - val0) / val0, 5),
        "val_gen1", None if val_gen1 is None else round(val_gen1, 5), "val_improved", val_improved)
    torch.save({n: v.cpu() for n, v in Wt.items()}, out / "layer92_trained.pt")
    (out / "train_record.json").write_text(json.dumps({
        "args": vars(a), "val_before": val0, "val_after": val1, "val_improved": val_improved,
        "val_gen_before": val_gen0, "val_gen_after": val_gen1, "steps": steps, "log": log}, indent=1))
    return 0


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