Trinity / tools /colab_bpb_compare.py
STAR-future's picture
H6 mode + parametric bpb dir
d719545 verified
Raw History Blame Contribute Delete
9.64 kB
"""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)