"""Second-generation streaming pass over the LittleBoy checkpoint with disk-backed state, for many sequences. Differences from k3stream.py: * the per-token state (prefix, delta, attention-residual blocks) lives in numpy memmaps on local disk, so hundreds of thousands of tokens fit (the blocks alone are 8 x 7168 bf16 = 115 KB per token); * the MoE runs over ALL tokens of all sequences and both models at once, in chunks, so each expert is dequantised once per chunk instead of once per batch (rows whose new experts are masked = the base model); * at the last layer it writes, for every LittleBoy-mode token, the per-token cache that makes everything after the last layer's attention a per-token function: MoE input x, routed latent sum acc (before routed_expert_norm), the prefix at MoE time, the block terms (A, Z, m) of the output attention-residual mix, and the next-token target. Training and evaluating the last layer's BF16 parts then needs no further pass over the 2 TB. python k3pass.py --texts streams.jsonl --work /content/k3p --out /content/k3p/out [--batch 4] [--chunk 65536] [--ckpt-repo STAR-future/Trinity-k3ckpt-holdout --ckpt-every 6] streams.jsonl rows: {"id", "text", "set", "role": "train"|"holdout", "base": true|false}. Every row runs in LittleBoy mode; rows with base=true also run in base mode (experts >= 896 masked = Kimi K3.1-Pro). Checkpoints (2026-11-19, after two Colab runtimes were lost mid-pass with nothing saved): every --ckpt-every layers the state that the next layer needs (prefix, delta, the attention-residual blocks written so far) goes to a private Hugging Face dataset with a progress.json; a rerun with the same streams resumes after the last checkpointed layer. The fingerprint (streams + sequence length + code version) must match, or the checkpoint is ignored. Each layer also logs free host RAM and disk, so a lost runtime leaves a trace of why. """ from __future__ import annotations import argparse import hashlib import json import math import os import shutil import time from pathlib import Path import numpy as np 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" CODE_VERSION = "k3pass v3 (per-block files, checkpoints)" def host_status(path: Path) -> str: """Free host RAM and disk, for the per-layer log line.""" avail = "?" try: for ln in Path("/proc/meminfo").read_text().splitlines(): if ln.startswith("MemAvailable:"): avail = f"{int(ln.split()[1]) / 2 ** 20:.1f}" except OSError: pass du = shutil.disk_usage(str(path)) return f"ram_free {avail} GiB disk_free {du.free / 2 ** 30:.0f} GiB" class Mem: """bf16 / fp32 arrays on disk, moved to and from torch by row ranges. reuse=True opens an existing file of the same shape (resume) instead of creating it.""" def __init__(self, path: Path, shape, dtype, reuse: bool = False): self.dtype, self.path = dtype, Path(path) np_dtype = np.uint16 if dtype == torch.bfloat16 else np.float32 if reuse and self.path.exists(): self.a = np.load(str(self.path), mmap_mode="r+") if tuple(self.a.shape) != tuple(shape) or self.a.dtype != np_dtype: raise ValueError(f"checkpoint {self.path.name} has shape {self.a.shape}, expected {tuple(shape)}") else: self.a = np.lib.format.open_memmap(str(self.path), mode="w+", dtype=np_dtype, shape=tuple(shape)) def flush(self): self.a.flush() def get(self, sl, dev): x = torch.from_numpy(np.ascontiguousarray(self.a[sl])) return (x.view(torch.bfloat16) if self.dtype == torch.bfloat16 else x).to(dev) def put(self, sl, t): t = t.detach().to("cpu").contiguous() self.a[sl] = (t.view(torch.uint16) if self.dtype == torch.bfloat16 else t).numpy() class Ckpt: """Layer checkpoints on a private Hugging Face dataset: prefix.npy, delta.npy, blocks_J.npy and progress.json, always in ONE commit (a runtime lost during an upload leaves the previous checkpoint intact), history squashed after each one so the repository holds only the latest state.""" def __init__(self, repo: str, tok: str | None, work: Path, fingerprint: str): from huggingface_hub import HfApi self.repo, self.tok, self.work, self.fp = repo, tok, work, fingerprint self.api = HfApi(token=tok) if repo else None self.sent = set() # blocks already in the repository (a block never changes once written) def resume(self) -> dict | None: """Download the last checkpoint into work/ if its fingerprint matches; its progress, or None.""" if self.api is None: return None try: p = json.loads(Path(hf_hub_download(self.repo, "progress.json", repo_type="dataset", token=self.tok, force_download=True)).read_text()) except Exception as e: # noqa: BLE001 - no checkpoint yet say("no checkpoint in", self.repo, type(e).__name__) return None if p.get("fingerprint") != self.fp: say("checkpoint fingerprint differs, starting from layer 0:", p.get("fingerprint"), "vs", self.fp) return None for n in ["prefix.npy", "delta.npy"] + [f"blocks_{j}.npy" for j in p["blocks"]]: src = hf_hub_download(self.repo, n, repo_type="dataset", token=self.tok, local_dir=str(self.work / "ckdl")) shutil.move(src, self.work / n) self.sent = set(p["blocks"]) say("resumed from the checkpoint after layer", p["layer_done"], host_status(self.work)) return p def save(self, layer_done: int, blocks_written: list, share: dict, mems: list) -> None: if self.api is None: return from huggingface_hub import CommitOperationAdd t0 = time.time() for m in mems: m.flush() try: self.api.create_repo(self.repo, repo_type="dataset", private=True, exist_ok=True) prog = {"fingerprint": self.fp, "layer_done": layer_done, "blocks": sorted(blocks_written), "share": {str(k): v for k, v in share.items()}, "time": time.strftime("%Y-%m-%d %H:%M:%S")} new_blocks = [j for j in sorted(blocks_written) if j not in self.sent] ops = [CommitOperationAdd(path_in_repo=n, path_or_fileobj=str(self.work / n)) for n in ["prefix.npy", "delta.npy"] + [f"blocks_{j}.npy" for j in new_blocks]] ops.append(CommitOperationAdd(path_in_repo="progress.json", path_or_fileobj=json.dumps(prog).encode())) self.api.create_commit(self.repo, operations=ops, repo_type="dataset", commit_message=f"checkpoint after layer {layer_done}") self.sent |= set(new_blocks) try: self.api.super_squash_history(repo_id=self.repo, repo_type="dataset") except Exception as e: # noqa: BLE001 say("history squash failed (storage grows, the pass continues):", type(e).__name__) say(f"checkpoint after layer {layer_done} in {time.time() - t0:.0f}s") except Exception as e: # noqa: BLE001 - a failed checkpoint must not stop the pass say("checkpoint FAILED (the pass continues):", type(e).__name__, str(e)[:300]) def layer_weights(f, L: int, dev) -> dict: """Dense weights to the GPU; experts read lazily from the memory-mapped shard (no 20 GB stack in RAM).""" pre = f"language_model.model.layers.{L}." W, ex_keys = {}, {} 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(".") ex_keys[(int(e), w, kind)] = 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_keys: def experts(e): return tuple(K.dequant(f.get_tensor(ex_keys[(e, w, "weight_packed")]).to(dev, non_blocking=True), f.get_tensor(ex_keys[(e, w, "weight_scale")]).to(dev, non_blocking=True)) for w in ("w1", "w2", "w3")) W["experts"] = experts return W def moe_group(W, c, hbuf, delta, mask_rows, g0, g1, dev, sub, cache): """MoE over token rows [g0, g1): routing and latent projection for all rows, then every expert dequantised ONCE and applied to all its rows, then the BF16 tail per sub-chunk. Same arithmetic as k3ref.moe (sums in another order). Returns (new-expert share over LittleBoy rows, number of LittleBoy rows).""" n, k = g1 - g0, c.topk lat = W["routed_expert_down_proj"].shape[0] n_exp = W["gate"].shape[0] xl = torch.empty(n, lat, dtype=torch.bfloat16, device=dev) idx = torch.empty(n, k, dtype=torch.long, device=dev) wts = torch.empty(n, k, dtype=torch.float32, device=dev) mask = mask_rows[g0:g1].to(dev) for s0 in range(0, n, sub): s1 = min(s0 + sub, n) x = hbuf.get(slice(g0 + s0, g0 + s1), dev) scores = torch.sigmoid(x.float() @ W["gate"].float().t()) sel = scores + W["e_score_correction_bias"].float() if n_exp > K.E0: sel[mask[s0:s1], K.E0:] = -float("inf") ii = sel.topk(k, dim=-1).indices ww = scores.gather(1, ii) idx[s0:s1], wts[s0:s1] = ii, ww / ww.sum(-1, keepdim=True) xl[s0:s1] = K.lin(x, W["routed_expert_down_proj"]) del x, scores, sel acc = torch.zeros(n, lat, dtype=torch.float32, device=dev) flat = idx.reshape(-1) order = torch.argsort(flat) tok = torch.arange(n, device=dev).repeat_interleave(k)[order] wv = wts.reshape(-1)[order] counts = torch.bincount(flat, minlength=n_exp).tolist() start = 0 for e, cnt in enumerate(counts): if cnt == 0: continue w1, w2, w3 = W["experts"](e) for q0 in range(0, cnt, 32768): q1 = min(cnt, q0 + 32768) t, w = tok[start + q0:start + q1], wv[start + q0:start + q1] h = K.situ_mul(K.lin(xl[t], w1), K.lin(xl[t], w3), c.situ_beta, c.situ_lin) acc.index_add_(0, t, K.lin(h, w2).float() * w[:, None]) start += cnt lbm = ~mask share = (float((idx[lbm] >= K.E0).float().mean()) if lbm.any() else 0.0, int(lbm.sum())) del xl, idx, wts, tok, wv for s0 in range(0, n, sub): s1 = min(s0 + sub, n) rs = slice(g0 + s0, g0 + s1) x = hbuf.get(rs, dev) delta.put(rs, K.moe_tail(acc[s0:s1], x, W, c)) if cache is not None and rs.start < cache[2]: e = min(rs.stop, cache[2]) cache[0].put(slice(rs.start, e), x[: e - rs.start]) cache[1].put(slice(rs.start, e), acc[s0:s0 + (e - rs.start)]) del x del acc return share def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--texts", required=True) ap.add_argument("--work", required=True) ap.add_argument("--out", required=True) ap.add_argument("--seq", type=int, default=2048) ap.add_argument("--batch", type=int, default=4) ap.add_argument("--chunk", type=int, default=65536) ap.add_argument("--layers", type=int, default=-1) ap.add_argument("--no-cache", action="store_true") ap.add_argument("--ckpt-repo", default="", help="private HF dataset for layer checkpoints (empty = none)") ap.add_argument("--ckpt-every", type=int, default=6) a = ap.parse_args() work, out = Path(a.work), Path(a.out) work.mkdir(parents=True, exist_ok=True) out.mkdir(parents=True, exist_ok=True) tok_hf = os.environ.get("HF_TOKEN") dev = torch.device("cuda") c = K.Cfg(json.loads(Path(hf_hub_download(BASE, "config.json")).read_text())["text_config"]) 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"), "role": r.get("role", "holdout"), "base": bool(r.get("base", False))}) ids = torch.tensor(seqs, dtype=torch.long) # streams: (sequence index, mode); LittleBoy streams first so the cache rows are contiguous streams = [(i, "littleboy") for i in range(len(seqs))] + [(i, "base") for i, m in enumerate(meta) if m["base"]] S, T, D = len(streams), a.seq, c.hidden N = S * T n_lb = len(seqs) * T say("sequences", len(seqs), "streams", S, "tokens", N, "sets", sorted({m["set"] for m in meta})) (out / "streams.json").write_text(json.dumps({"meta": meta, "streams": streams, "seq": T})) mask_rows = torch.zeros(N, dtype=torch.bool) for s, (_, mode) in enumerate(streams): if mode == "base": mask_rows[s * T:(s + 1) * T] = True n_layers = c.n_layers if a.layers < 0 else a.layers fingerprint = hashlib.sha256(json.dumps({"v": CODE_VERSION, "streams": streams, "meta": meta, "seq": T, "n_layers": n_layers}).encode() + ids.numpy().tobytes()).hexdigest()[:16] ck = Ckpt(a.ckpt_repo, tok_hf, work, fingerprint) prog = ck.resume() start = prog["layer_done"] + 1 if prog else 0 prefix = Mem(work / "prefix.npy", (N, D), torch.bfloat16, reuse=prog is not None) delta = Mem(work / "delta.npy", (N, D), torch.bfloat16, reuse=prog is not None) hbuf = Mem(work / "h.npy", (N, D), torch.bfloat16) blocks = [Mem(work / f"blocks_{j}.npy", (N, D), torch.bfloat16, reuse=prog is not None and j in prog["blocks"]) for j in range(c.n_blocks)] say("fingerprint", fingerprint, "start at layer", start, host_status(work)) def dl(name): for k in range(5): try: return hf_hub_download(REPO, name, token=tok_hf, local_dir=str(work / "shards")) except Exception as e: # noqa: BLE001 say("download retry", name, k, e) time.sleep(30 * (k + 1)) raise RuntimeError(name) from concurrent.futures import ThreadPoolExecutor pool = ThreadPoolExecutor(2) fut = {94: pool.submit(dl, shard_name(94)), start + 1: pool.submit(dl, shard_name(start + 1))} with safe_open(fut[94].result(), 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)} if prog is None: emb_w = f.get_tensor("language_model.model.embed_tokens.weight") for s, (i, _) in enumerate(streams): prefix.put(slice(s * T, (s + 1) * T), emb_w[ids[i]]) del emb_w batches = [list(range(b, min(b + a.batch, S))) for b in range(0, S, a.batch)] gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30 chunk = a.chunk if gpu_gb > 60 else (32768 if gpu_gb > 30 else (16384 if gpu_gb > 20 else 8192)) group = 524288 if gpu_gb > 60 else (262144 if gpu_gb > 20 else 131072) say("GPU", torch.cuda.get_device_name(0), round(gpu_gb, 1), "GiB, sub-chunk", chunk, "expert group", group) share = {int(k): v for k, v in prog["share"].items()} if prog else {} for L in range(start, n_layers): if L + 2 <= 93: fut[L + 2] = pool.submit(dl, shard_name(L + 2)) t0 = time.time() path = fut.pop(L + 1).result() t1 = time.time() nb_valid = math.ceil(L / c.block) + int(L % c.block == 0) with safe_open(path, framework="pt", device="cpu") as f, torch.no_grad(): W = layer_weights(f, L, dev) for bt in batches: # attention phase, per batch of whole sequences rs = slice(bt[0] * T, (bt[-1] + 1) * T) st = {"shape": (len(bt), T), "prefix": prefix.get(rs, dev), "delta": None if L == 0 else delta.get(rs, dev), "blocks": torch.zeros(len(bt) * T, c.n_blocks, D, dtype=torch.bfloat16, device=dev)} for j in range(min(nb_valid, c.n_blocks)): st["blocks"][:, j] = blocks[j].get(rs, dev) h = K.attn_phase(L, W, c, st) prefix.put(rs, st["prefix"]) if L % c.block == 0: j = L // c.block blocks[j].put(rs, st["blocks"][:, j]) hbuf.put(rs, h) del st, h t2 = time.time() last = (L == c.n_layers - 1) and not a.no_cache if last: xc = Mem(out / "x92.npy", (n_lb, D), torch.bfloat16) accc = Mem(out / "acc92.npy", (n_lb, W["routed_expert_up_proj"].shape[1]), torch.float32) new_share = [] if L < c.first_dense: # the dense layer-0 MLP is 33792 wide for c0 in range(0, N, 4096): rs = slice(c0, min(c0 + 4096, N)) delta.put(rs, K.dense_mlp(hbuf.get(rs, dev), W, c)) else: for g0 in range(0, N, group): # each expert dequantised once per token group g1 = min(g0 + group, N) new_share.append(moe_group(W, c, hbuf, delta, mask_rows, g0, g1, dev, chunk, (xc, accc, n_lb) if last else None)) del W tot = sum(n for _, n in new_share) share[L] = sum(v * n for v, n in new_share) / tot if tot else 0.0 say(f"layer {L} wait {t1 - t0:.0f}s attn {t2 - t1:.0f}s mlp {time.time() - t2:.0f}s new-share(LB) {share[L]:.4f}", host_status(work)) if L > 0: Path(path).unlink(missing_ok=True) if a.ckpt_repo and (L + 1) % a.ckpt_every == 0 and L < n_layers - 1: ck.save(L, [j for j in range(c.n_blocks) if j * c.block <= L], share, [prefix, delta] + blocks) # final mix, NLL, and the last-layer cache terms (lm_head only now: 2.35 GB not held during the layers) with safe_open(hf_hub_download(REPO, shard_name(94), token=tok_hf, local_dir=str(work / "shards")), framework="pt", device="cpu") as f: lm_head = f.get_tensor("language_model.lm_head.weight").to(dev) nll = np.zeros((S, T - 1), dtype=np.float32) if not a.no_cache: pc = Mem(out / "prefix92.npy", (n_lb, D), torch.bfloat16) Ac = Mem(out / "A92.npy", (n_lb, D), torch.float32) Zm = Mem(out / "Zm92.npy", (n_lb, 2), torch.float32) tgt = np.full((n_lb,), -1, dtype=np.int64) with torch.no_grad(): for bt in batches: rs = slice(bt[0] * T, (bt[-1] + 1) * T) p = prefix.get(rs, dev) d = delta.get(rs, dev) bl = torch.stack([blocks[j].get(rs, dev) for j in range(c.n_blocks)], dim=1) A, Z, m = K.final_mix_terms(bl, Wf, c) hid = K.final_from_terms(p, d, A, Z, m, Wf, c).view(len(bt), T, D) for k, s in enumerate(bt): i = streams[s][0] nll[s] = K.token_nll(hid[k, :-1].contiguous(), lm_head, ids[i, 1:].to(dev)).cpu().numpy() if not a.no_cache and rs.start < n_lb: e = min(rs.stop, n_lb) n = e - rs.start pc.put(slice(rs.start, e), p[:n]) Ac.put(slice(rs.start, e), A[:n]) Zm.put(slice(rs.start, e), torch.stack([Z[:n], m[:n]], dim=1)) del p, d, bl, A, Z, m, hid if not a.no_cache: for s in range(len(seqs)): tgt[s * T:(s + 1) * T - 1] = ids[s, 1:].numpy() # target of the last position stays -1 np.save(out / "target92.npy", tgt) np.save(out / "nll.npy", nll) res = {"seq": T, "n_seqs": len(seqs), "streams": S, "layers_run": n_layers, "new_share_lb_by_layer": share, "per_set": {}} for mode in ("littleboy", "base"): for sname in sorted({m["set"] for m in meta}): rows_s = [s for s, (i, md) in enumerate(streams) if md == mode and meta[i]["set"] == sname] if rows_s: v = float(nll[rows_s].mean()) res["per_set"].setdefault(mode, {})[sname] = {"mean_nll": v, "ppl": math.exp(v), "n_seqs": len(rows_s)} (out / "summary.json").write_text(json.dumps(res, indent=1)) say("DONE", json.dumps(res["per_set"])) return 0 if __name__ == "__main__": raise SystemExit(main())