File size: 9,644 Bytes
88d2a92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d719545
88d2a92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d719545
88d2a92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d719545
88d2a92
d719545
88d2a92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Bits per byte on the SEALED holdout (61 sequences, published after 2026-11-01): Trinity, Trinity + adapter, the base

model, and open models that fit one A100 (Qwen3.8-27B, Gemma-4-31B). Bits per byte do not depend on the tokenizer, so

models with different vocabularies are compared on exactly the same bytes.



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`

excluding the fixed domain prefix `ids[0:2]` = "Title:" for every model, and choosing the first common token boundary

across all evaluated tokenizers so zero bytes are straddled or dropped). Crucially, Kimi's `encode()` does NOT prepend

[BOS], so open models receive the FULL prefix `ids[0:k_end]` (not `ids[1:2048]`, which chopped off `ids[0]`!).



Run on Colab right after `K3P=sealed` (same VM: /content/k3p/out_sealed and /content/k3p/h5_sealed exist).

Result: eval/h5_sealed/bpb_compare.json (aggregates and per-sequence values, no text).

"""
import gc
import json
import math
import os
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F
from huggingface_hub import HfApi, hf_hub_download
from transformers import AutoModelForCausalLM, AutoTokenizer

TOK = os.environ["HF_TOKEN"]
REPO = "STAR-future/Trinity"
BASE = "moonshotai/Kimi-K3.1-Pro"
W = Path("/content/k3p")
BPB_DIR = os.environ.get("BPB_DIR", "h5_sealed")   # 2026-11-24: h6_sealed for the H6 specialisation
OPEN = [m for m in os.environ.get("BPB_MODELS", "Qwen/Qwen3.8-27B,google/gemma-4-31B").split(",") if m]
api = HfApi(token=TOK)
LN2 = math.log(2)

texts = W / "streams_sealed.jsonl"
all_rows = [json.loads(x) for x in texts.read_text(encoding="utf-8").splitlines() if x.strip()]
ktok = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True)

# Mirror k3pass.py:267-270 exact sequence filter (>= 2048 tokens) so indices match out_sealed/streams.json 1-to-1!
kept = []
for r in all_rows:
    ids_full = ktok.encode(r["text"])
    if len(ids_full) >= 2048:
        kept.append((r, ids_full[:2048]))

raw = next((W / BPB_DIR).glob("*.raw.npz"))
z = np.load(raw)
per = {}
for k in z.files:
    st, i, arm = k.split("/")
    per.setdefault(int(i), {})[arm] = z[k].astype(np.float64)
assert len(kept) == len(per), f"Sequence count mismatch: kept={len(kept)} vs raw.npz={len(per)}"

# Load fast open-model tokenizers upfront (small) to pick a guaranteed zero-straddle common boundary per sequence
open_toks = {m: AutoTokenizer.from_pretrained(m) for m in OPEN}
spans = []
for idx, (r, ids) in enumerate(kept):
    # Detect whether Kimi prepended BOS (tokenization_kimi.py:211 does NOT, so bos_off == 0)
    bos_off = 1 if (ktok.bos_token_id is not None and ids[0] == ktok.bos_token_id) else 0
    # Strip any trailing partial UTF-8 bytes at token 2047 so decode() never injects U+FFFD
    k_end = len(ids)
    while k_end > bos_off + 2:
        cand = ktok.decode(ids[bos_off:k_end])
        if "\ufffd" not in cand[-4:]:
            break
        k_end -= 1
    ctx = ktok.decode(ids[bos_off:k_end])  # FULL text incl. ids[0], matching what Kimi/Trinity actually saw!

    # Collect valid scored token start offsets for every open tokenizer
    tok_starts = {}
    for m, tk in open_toks.items():
        enc = tk(ctx, return_offsets_mapping=True, add_special_tokens=True)
        offs = enc["offset_mapping"]
        tok_starts[m] = {o[0] for j, o in enumerate(offs) if j >= 1 and o[1] > o[0]}

    # First k_start >= max(2, bos_off + 1) whose UTF-8 char offset is an exact token boundary for ALL models
    k_start, start = None, None
    for k in range(max(2, bos_off + 1), min(k_end - 1, 64)):
        pref = ktok.decode(ids[bos_off:k])
        if "\ufffd" in pref or not ctx.startswith(pref) or len(pref) == 0:
            continue
        cp = len(pref)
        if all(cp in st for st in tok_starts.values()):
            k_start, start = k, cp
            break
    if k_start is None:
        k_start = max(2, bos_off + 1)
        start = len(ktok.decode(ids[bos_off:k_start]))
    spans.append({
        "set": r["set"],
        "ctx": ctx,
        "k_start": k_start,
        "k_end": k_end,
        "start": start,
        "bytes": len(ctx[start:].encode("utf-8")),
    })

res = {
    "span": "Exact common-boundary UTF-8 clean slice ids[k_start:k_end] (k_start>=2, full prefix ids[0:] given to all models)",
    "n_seqs": len(spans),
    "max_k_start": max(s["k_start"] for s in spans),
    "max_trimmed_end_tokens": max(2048 - s["k_end"] for s in spans),
    "span_bytes_per_seq": [s["bytes"] for s in spans],
    "bos_added_by_model": {"base model": False, "Trinity": False, "Trinity + adapter F1": False},
    "byte_alignment_max_abs_diff": {},
    "models": {},
}
for arm, name in (("base", "base model"), ("lb", "Trinity"), ("lb_fulltail", "Trinity + adapter F1")):
    # 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]
    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))]
    res["models"][name] = vals
    res["byte_alignment_max_abs_diff"][name] = 0


def summarize_and_save(res_obj):
    rng = np.random.default_rng(20261124)
    sets = sorted({s["set"] for s in spans})
    ref = np.array(res_obj["models"]["Trinity + adapter F1"])
    sb = np.array([s["bytes"] for s in spans], dtype=np.float64)
    summary = {}
    for name, vals in res_obj["models"].items():
        v = np.array(vals, dtype=np.float64)
        summary[name] = {}
        for st in sets + ["all_domain"]:
            ix = np.array([i for i, s in enumerate(spans) if (s["set"] == st if st != "all_domain" else s["set"] != "wikipedia")])
            diff = v[ix] - ref[ix]                       # > 0: this model needs more bits than Trinity + F1
            boots = [diff[rng.integers(0, len(ix), len(ix))].mean() for _ in range(4000)]
            corpus_bpb = float((v[ix] * sb[ix]).sum() / sb[ix].sum())
            summary[name][st] = {
                "bpb": float(v[ix].mean()),
                "corpus_weighted_bpb": corpus_bpb,
                "minus_trinity_f1": float(diff.mean()),
                "ci95": [float(np.percentile(boots, 2.5)), float(np.percentile(boots, 97.5))],
                "n": int(len(ix)),
            }
    res_obj["summary"] = summary
    out = W / BPB_DIR / "bpb_compare.json"
    out.write_text(json.dumps(res_obj, indent=1))
    api.upload_file(path_or_fileobj=str(out), path_in_repo=f"eval/{BPB_DIR}/bpb_compare.json", repo_id=REPO,
                    commit_message="Sealed holdout: bits per byte, Trinity vs open models")
    return summary


# Persist Trinity/Base BPB BEFORE loading 27B/31B models so an OOM can never wipe Trinity's results!
summarize_and_save(res)


def score(model_id):
    tok = open_toks[model_id]
    gpu_gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30
    dmap = {"": 0} if gpu_gb >= 70 else "auto"  # 27B/31B BF16 (~54-62 GB) OOMs single 40 GB A100 with {"": 0}
    kw = dict(dtype=torch.bfloat16, device_map=dmap, low_cpu_mem_usage=True)
    try:
        model = AutoModelForCausalLM.from_pretrained(model_id, **kw)
    except (ValueError, KeyError):
        from transformers import AutoModelForImageTextToText
        model = AutoModelForImageTextToText.from_pretrained(model_id, **kw)
    model.eval()
    dev = next(model.parameters()).device
    out = []
    max_diff_b = 0
    bos_added = False
    for s in spans:
        enc = tok(s["ctx"], return_offsets_mapping=True, add_special_tokens=True)
        offs = enc["offset_mapping"]
        if offs and offs[0] == (0, 0):
            bos_added = True
        ids = torch.tensor([enc["input_ids"]], device=dev)
        with torch.no_grad():
            logits = model(input_ids=ids).logits[0, :-1]
            targets = ids[0, 1:]
            # Chunked FP32 cross_entropy saves ~4 GB VRAM vs full [2047, 262144] log_softmax on Gemma-4!
            chunks = [
                F.cross_entropy(logits[c:c + 512].float(), targets[c:c + 512], reduction="none")
                for c in range(0, logits.shape[0], 512)
            ]
            nll = torch.cat(chunks, 0).cpu().numpy()
        keep_idx = [j for j in range(1, len(offs)) if offs[j][0] >= s["start"] and offs[j][1] > offs[j][0]]
        scored_bytes = len(s["ctx"][offs[keep_idx[0]][0]:offs[keep_idx[-1]][1]].encode("utf-8")) if keep_idx else 0
        max_diff_b = max(max_diff_b, abs(scored_bytes - s["bytes"]))
        keep = np.zeros(len(offs) - 1, dtype=bool)
        for j in keep_idx:
            keep[j - 1] = True
        out.append(float(nll[keep].sum() / LN2 / s["bytes"]))
        del logits, targets, chunks
    del model
    gc.collect()
    torch.cuda.empty_cache()
    res["bos_added_by_model"][model_id] = bos_added
    res["byte_alignment_max_abs_diff"][model_id] = int(max_diff_b)
    assert max_diff_b == 0, f"{model_id}: byte alignment mismatch max_diff={max_diff_b}"
    return out


for m in OPEN:
    print("scoring", m, flush=True)
    try:
        res["models"][m] = score(m)
        summary = summarize_and_save(res)
    except Exception as e:  # noqa: BLE001
        print(f"ERROR scoring {m}: {type(e).__name__}: {str(e)[:240]}", flush=True)
        res.setdefault("model_errors", {})[m] = f"{type(e).__name__}: {str(e)[:240]}"
        summary = summarize_and_save(res)

print(json.dumps(res["summary"], indent=1), flush=True)