STAR-future commited on
Commit
5abef56
·
verified ·
1 Parent(s): d0821e7

bpb comparison on the sealed holdout

Browse files
Files changed (1) hide show
  1. tools/colab_bpb_compare.py +103 -0
tools/colab_bpb_compare.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bits per byte on the SEALED holdout (61 sequences, published after 2026-11-01): Trinity, Trinity + adapter, the base
2
+ model, and open models that fit one A100 (Qwen3.8-27B, Gemma-4-31B). Bits per byte do not depend on the tokenizer, so
3
+ models with different vocabularies are compared on exactly the same bytes.
4
+
5
+ Byte span of a sequence: the text of Trinity's tokens 2..2047 (the first 2,048 tokens of the text, as k3pass scored them;
6
+ token 1 is excluded for every model because the domain texts all start with the same marker). Trinity's numbers come
7
+ from the per-token losses of the sealed pass (eval/h5_sealed/*.raw.npz); each open model scores the text of tokens
8
+ 1..2047 and only its tokens that start inside the span are counted.
9
+
10
+ Run on Colab right after `K3P=sealed` (same VM: /content/k3p/out_sealed and /content/k3p/h5_sealed exist).
11
+ Result: eval/h5_sealed/bpb_compare.json (aggregates and per-sequence values, no text).
12
+ """
13
+ import gc
14
+ import json
15
+ import math
16
+ import os
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import torch
21
+ from huggingface_hub import HfApi, hf_hub_download
22
+ from transformers import AutoModelForCausalLM, AutoTokenizer
23
+
24
+ TOK = os.environ["HF_TOKEN"]
25
+ REPO = "STAR-future/Trinity"
26
+ BASE = "moonshotai/Kimi-K3.1-Pro"
27
+ W = Path("/content/k3p")
28
+ OPEN = [m for m in os.environ.get("BPB_MODELS", "Qwen/Qwen3.8-27B,google/gemma-4-31B").split(",") if m]
29
+ api = HfApi(token=TOK)
30
+ LN2 = math.log(2)
31
+
32
+ texts = W / "streams_sealed.jsonl"
33
+ rows = [json.loads(x) for x in texts.read_text(encoding="utf-8").splitlines() if x.strip()]
34
+ ktok = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True)
35
+ spans = []
36
+ for r in rows:
37
+ ids = ktok.encode(r["text"])[:2048]
38
+ ctx = ktok.decode(ids[1:2048]) # context the open models score (token 0 is the start marker/BOS)
39
+ head = ktok.decode(ids[1:2]) # token 1: excluded for everybody
40
+ spans.append({"set": r["set"], "ctx": ctx, "start": len(head), "bytes": len(ctx[len(head):].encode("utf-8"))})
41
+
42
+ raw = next((W / "h5_sealed").glob("*.raw.npz"))
43
+ z = np.load(raw)
44
+ per = {}
45
+ for k in z.files:
46
+ st, i, arm = k.split("/")
47
+ per.setdefault(int(i), {})[arm] = z[k].astype(np.float64)
48
+ res = {"span": "Trinity tokens 2..2047 of each sealed sequence", "n_seqs": len(rows), "models": {}}
49
+ for arm, name in (("base", "base model"), ("lb", "Trinity"), ("lb_fulltail", "Trinity + adapter F1")):
50
+ vals = [per[i][arm][1:].sum() / LN2 / spans[i]["bytes"] for i in range(len(rows))]
51
+ res["models"][name] = vals
52
+
53
+
54
+ def score(model_id):
55
+ tok = AutoTokenizer.from_pretrained(model_id)
56
+ kw = dict(dtype=torch.bfloat16, device_map={"": 0})
57
+ try:
58
+ model = AutoModelForCausalLM.from_pretrained(model_id, **kw)
59
+ except (ValueError, KeyError):
60
+ from transformers import AutoModelForImageTextToText
61
+ model = AutoModelForImageTextToText.from_pretrained(model_id, **kw)
62
+ model.eval()
63
+ out = []
64
+ for s in spans:
65
+ enc = tok(s["ctx"], return_offsets_mapping=True, add_special_tokens=True)
66
+ ids = torch.tensor([enc["input_ids"]], device="cuda")
67
+ offs = enc["offset_mapping"]
68
+ with torch.no_grad():
69
+ logits = model(input_ids=ids).logits[0, :-1].float()
70
+ lp = torch.log_softmax(logits, -1)
71
+ nll = -lp.gather(1, ids[0, 1:, None])[:, 0].cpu().numpy()
72
+ keep = np.array([offs[j][0] >= s["start"] and offs[j][1] > offs[j][0] for j in range(1, len(offs))])
73
+ out.append(float(nll[keep].sum() / LN2 / s["bytes"]))
74
+ del logits, lp
75
+ del model
76
+ gc.collect()
77
+ torch.cuda.empty_cache()
78
+ return out
79
+
80
+
81
+ for m in OPEN:
82
+ print("scoring", m, flush=True)
83
+ res["models"][m] = score(m)
84
+
85
+ rng = np.random.default_rng(20261124)
86
+ sets = sorted({s["set"] for s in spans})
87
+ summary = {}
88
+ ref = np.array(res["models"]["Trinity + adapter F1"])
89
+ for name, vals in res["models"].items():
90
+ v = np.array(vals)
91
+ summary[name] = {}
92
+ for st in sets + ["all_domain"]:
93
+ ix = np.array([i for i, s in enumerate(spans) if (s["set"] == st if st != "all_domain" else s["set"] != "wikipedia")])
94
+ diff = v[ix] - ref[ix] # > 0: this model needs more bits than Trinity + F1
95
+ boots = [diff[rng.integers(0, len(ix), len(ix))].mean() for _ in range(4000)]
96
+ summary[name][st] = {"bpb": float(v[ix].mean()), "minus_trinity_f1": float(diff.mean()),
97
+ "ci95": [float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5))], "n": int(len(ix))}
98
+ res["summary"] = summary
99
+ out = W / "h5_sealed" / "bpb_compare.json"
100
+ out.write_text(json.dumps(res, indent=1))
101
+ api.upload_file(path_or_fileobj=str(out), path_in_repo="eval/h5_sealed/bpb_compare.json", repo_id=REPO,
102
+ commit_message="Sealed holdout: bits per byte, Trinity vs open models")
103
+ print(json.dumps(summary, indent=1), flush=True)