STAR-future commited on
Commit
88d2a92
·
verified ·
1 Parent(s): 1df9490

bpb compare: patch 32 (exact alignment, OOM-safe)

Browse files
Files changed (1) hide show
  1. tools/colab_bpb_compare.py +203 -103
tools/colab_bpb_compare.py CHANGED
@@ -1,103 +1,203 @@
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: exact UTF-8 clean slice `ids[k_start:k_end]` of Kimi/Trinity's 2,048-token stream (`k_start >= 2`
6
+ excluding the fixed domain prefix `ids[0:2]` = "Title:" for every model, and choosing the first common token boundary
7
+ across all evaluated tokenizers so zero bytes are straddled or dropped). Crucially, Kimi's `encode()` does NOT prepend
8
+ [BOS], so open models receive the FULL prefix `ids[0:k_end]` (not `ids[1:2048]`, which chopped off `ids[0]`!).
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
+ import torch.nn.functional as F
22
+ from huggingface_hub import HfApi, hf_hub_download
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer
24
+
25
+ TOK = os.environ["HF_TOKEN"]
26
+ REPO = "STAR-future/Trinity"
27
+ BASE = "moonshotai/Kimi-K3.1-Pro"
28
+ W = Path("/content/k3p")
29
+ OPEN = [m for m in os.environ.get("BPB_MODELS", "Qwen/Qwen3.8-27B,google/gemma-4-31B").split(",") if m]
30
+ api = HfApi(token=TOK)
31
+ LN2 = math.log(2)
32
+
33
+ texts = W / "streams_sealed.jsonl"
34
+ all_rows = [json.loads(x) for x in texts.read_text(encoding="utf-8").splitlines() if x.strip()]
35
+ ktok = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True)
36
+
37
+ # Mirror k3pass.py:267-270 exact sequence filter (>= 2048 tokens) so indices match out_sealed/streams.json 1-to-1!
38
+ kept = []
39
+ for r in all_rows:
40
+ ids_full = ktok.encode(r["text"])
41
+ if len(ids_full) >= 2048:
42
+ kept.append((r, ids_full[:2048]))
43
+
44
+ raw = next((W / "h5_sealed").glob("*.raw.npz"))
45
+ z = np.load(raw)
46
+ per = {}
47
+ for k in z.files:
48
+ st, i, arm = k.split("/")
49
+ per.setdefault(int(i), {})[arm] = z[k].astype(np.float64)
50
+ assert len(kept) == len(per), f"Sequence count mismatch: kept={len(kept)} vs raw.npz={len(per)}"
51
+
52
+ # Load fast open-model tokenizers upfront (small) to pick a guaranteed zero-straddle common boundary per sequence
53
+ open_toks = {m: AutoTokenizer.from_pretrained(m) for m in OPEN}
54
+ spans = []
55
+ for idx, (r, ids) in enumerate(kept):
56
+ # Detect whether Kimi prepended BOS (tokenization_kimi.py:211 does NOT, so bos_off == 0)
57
+ bos_off = 1 if (ktok.bos_token_id is not None and ids[0] == ktok.bos_token_id) else 0
58
+ # Strip any trailing partial UTF-8 bytes at token 2047 so decode() never injects U+FFFD
59
+ k_end = len(ids)
60
+ while k_end > bos_off + 2:
61
+ cand = ktok.decode(ids[bos_off:k_end])
62
+ if "\ufffd" not in cand[-4:]:
63
+ break
64
+ k_end -= 1
65
+ ctx = ktok.decode(ids[bos_off:k_end]) # FULL text incl. ids[0], matching what Kimi/Trinity actually saw!
66
+
67
+ # Collect valid scored token start offsets for every open tokenizer
68
+ tok_starts = {}
69
+ for m, tk in open_toks.items():
70
+ enc = tk(ctx, return_offsets_mapping=True, add_special_tokens=True)
71
+ offs = enc["offset_mapping"]
72
+ tok_starts[m] = {o[0] for j, o in enumerate(offs) if j >= 1 and o[1] > o[0]}
73
+
74
+ # First k_start >= max(2, bos_off + 1) whose UTF-8 char offset is an exact token boundary for ALL models
75
+ k_start, start = None, None
76
+ for k in range(max(2, bos_off + 1), min(k_end - 1, 64)):
77
+ pref = ktok.decode(ids[bos_off:k])
78
+ if "\ufffd" in pref or not ctx.startswith(pref) or len(pref) == 0:
79
+ continue
80
+ cp = len(pref)
81
+ if all(cp in st for st in tok_starts.values()):
82
+ k_start, start = k, cp
83
+ break
84
+ if k_start is None:
85
+ k_start = max(2, bos_off + 1)
86
+ start = len(ktok.decode(ids[bos_off:k_start]))
87
+ spans.append({
88
+ "set": r["set"],
89
+ "ctx": ctx,
90
+ "k_start": k_start,
91
+ "k_end": k_end,
92
+ "start": start,
93
+ "bytes": len(ctx[start:].encode("utf-8")),
94
+ })
95
+
96
+ res = {
97
+ "span": "Exact common-boundary UTF-8 clean slice ids[k_start:k_end] (k_start>=2, full prefix ids[0:] given to all models)",
98
+ "n_seqs": len(spans),
99
+ "max_k_start": max(s["k_start"] for s in spans),
100
+ "max_trimmed_end_tokens": max(2048 - s["k_end"] for s in spans),
101
+ "span_bytes_per_seq": [s["bytes"] for s in spans],
102
+ "bos_added_by_model": {"base model": False, "Trinity": False, "Trinity + adapter F1": False},
103
+ "byte_alignment_max_abs_diff": {},
104
+ "models": {},
105
+ }
106
+ for arm, name in (("base", "base model"), ("lb", "Trinity"), ("lb_fulltail", "Trinity + adapter F1")):
107
+ # per[i][arm][t] is NLL of token t+1 given tokens 0..t -> tokens k_start..k_end-1 are slice [k_start-1 : k_end-1]
108
+ vals = [float(per[i][arm][spans[i]["k_start"] - 1:spans[i]["k_end"] - 1].sum() / LN2 / spans[i]["bytes"]) for i in range(len(spans))]
109
+ res["models"][name] = vals
110
+ res["byte_alignment_max_abs_diff"][name] = 0
111
+
112
+
113
+ def summarize_and_save(res_obj):
114
+ rng = np.random.default_rng(20261124)
115
+ sets = sorted({s["set"] for s in spans})
116
+ ref = np.array(res_obj["models"]["Trinity + adapter F1"])
117
+ sb = np.array([s["bytes"] for s in spans], dtype=np.float64)
118
+ summary = {}
119
+ for name, vals in res_obj["models"].items():
120
+ v = np.array(vals, dtype=np.float64)
121
+ summary[name] = {}
122
+ for st in sets + ["all_domain"]:
123
+ ix = np.array([i for i, s in enumerate(spans) if (s["set"] == st if st != "all_domain" else s["set"] != "wikipedia")])
124
+ diff = v[ix] - ref[ix] # > 0: this model needs more bits than Trinity + F1
125
+ boots = [diff[rng.integers(0, len(ix), len(ix))].mean() for _ in range(4000)]
126
+ corpus_bpb = float((v[ix] * sb[ix]).sum() / sb[ix].sum())
127
+ summary[name][st] = {
128
+ "bpb": float(v[ix].mean()),
129
+ "corpus_weighted_bpb": corpus_bpb,
130
+ "minus_trinity_f1": float(diff.mean()),
131
+ "ci95": [float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5))],
132
+ "n": int(len(ix)),
133
+ }
134
+ res_obj["summary"] = summary
135
+ out = W / "h5_sealed" / "bpb_compare.json"
136
+ out.write_text(json.dumps(res_obj, indent=1))
137
+ api.upload_file(path_or_fileobj=str(out), path_in_repo="eval/h5_sealed/bpb_compare.json", repo_id=REPO,
138
+ commit_message="Sealed holdout: bits per byte, Trinity vs open models")
139
+ return summary
140
+
141
+
142
+ # Persist Trinity/Base BPB BEFORE loading 27B/31B models so an OOM can never wipe Trinity's results!
143
+ summarize_and_save(res)
144
+
145
+
146
+ def score(model_id):
147
+ tok = open_toks[model_id]
148
+ gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30
149
+ dmap = {"": 0} if gpu_gb >= 70 else "auto" # 27B/31B BF16 (~54-62 GB) OOMs single 40 GB A100 with {"": 0}
150
+ kw = dict(dtype=torch.bfloat16, device_map=dmap, low_cpu_mem_usage=True)
151
+ try:
152
+ model = AutoModelForCausalLM.from_pretrained(model_id, **kw)
153
+ except (ValueError, KeyError):
154
+ from transformers import AutoModelForImageTextToText
155
+ model = AutoModelForImageTextToText.from_pretrained(model_id, **kw)
156
+ model.eval()
157
+ dev = next(model.parameters()).device
158
+ out = []
159
+ max_diff_b = 0
160
+ bos_added = False
161
+ for s in spans:
162
+ enc = tok(s["ctx"], return_offsets_mapping=True, add_special_tokens=True)
163
+ offs = enc["offset_mapping"]
164
+ if offs and offs[0] == (0, 0):
165
+ bos_added = True
166
+ ids = torch.tensor([enc["input_ids"]], device=dev)
167
+ with torch.no_grad():
168
+ logits = model(input_ids=ids).logits[0, :-1]
169
+ targets = ids[0, 1:]
170
+ # Chunked FP32 cross_entropy saves ~4 GB VRAM vs full [2047, 262144] log_softmax on Gemma-4!
171
+ chunks = [
172
+ F.cross_entropy(logits[c:c + 512].float(), targets[c:c + 512], reduction="none")
173
+ for c in range(0, logits.shape[0], 512)
174
+ ]
175
+ nll = torch.cat(chunks, 0).cpu().numpy()
176
+ keep_idx = [j for j in range(1, len(offs)) if offs[j][0] >= s["start"] and offs[j][1] > offs[j][0]]
177
+ scored_bytes = len(s["ctx"][offs[keep_idx[0]][0]:offs[keep_idx[-1]][1]].encode("utf-8")) if keep_idx else 0
178
+ max_diff_b = max(max_diff_b, abs(scored_bytes - s["bytes"]))
179
+ keep = np.zeros(len(offs) - 1, dtype=bool)
180
+ for j in keep_idx:
181
+ keep[j - 1] = True
182
+ out.append(float(nll[keep].sum() / LN2 / s["bytes"]))
183
+ del logits, targets, chunks
184
+ del model
185
+ gc.collect()
186
+ torch.cuda.empty_cache()
187
+ res["bos_added_by_model"][model_id] = bos_added
188
+ res["byte_alignment_max_abs_diff"][model_id] = int(max_diff_b)
189
+ assert max_diff_b == 0, f"{model_id}: byte alignment mismatch max_diff={max_diff_b}"
190
+ return out
191
+
192
+
193
+ for m in OPEN:
194
+ print("scoring", m, flush=True)
195
+ try:
196
+ res["models"][m] = score(m)
197
+ summary = summarize_and_save(res)
198
+ except Exception as e: # noqa: BLE001
199
+ print(f"ERROR scoring {m}: {type(e).__name__}: {str(e)[:240]}", flush=True)
200
+ res.setdefault("model_errors", {})[m] = f"{type(e).__name__}: {str(e)[:240]}"
201
+ summary = summarize_and_save(res)
202
+
203
+ print(json.dumps(res["summary"], indent=1), flush=True)