Image-Text-to-Text
Transformers
Safetensors
kimi_k31
text-generation
mixture-of-experts
expert-upcycling
scientific-ai
chip-design
space
physics
s-t-a-r
custom_code
8-bit precision
Instructions to use STAR-future/Trinity with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use STAR-future/Trinity with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="STAR-future/Trinity", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForSeq2SeqLM model = AutoModelForSeq2SeqLM.from_pretrained("STAR-future/Trinity", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use STAR-future/Trinity with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "STAR-future/Trinity" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "STAR-future/Trinity", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/STAR-future/Trinity
- SGLang
How to use STAR-future/Trinity with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "STAR-future/Trinity" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "STAR-future/Trinity", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "STAR-future/Trinity" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "STAR-future/Trinity", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use STAR-future/Trinity with Docker Model Runner:
docker model run hf.co/STAR-future/Trinity
bpb compare: patch 32 (exact alignment, OOM-safe)
Browse files- 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:
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 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 |
-
|
| 22 |
-
from
|
| 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 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|