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
Download tools/k3stream.py from STAR-future/Trinity: direct link, hf CLI and curl.
- Browser
- Download file 8.91 kB
-
https://huggingface.co/STAR-future/Trinity/resolve/3743fa688df9117e6bdfd19f72cd91f4ccf6e20c/tools/k3stream.py
- Command line
-
hf download hf://STAR-future/Trinity@3743fa688df9117e6bdfd19f72cd91f4ccf6e20c/tools/k3stream.py
-
curl -L -o k3stream.py https://huggingface.co/STAR-future/Trinity/resolve/3743fa688df9117e6bdfd19f72cd91f4ccf6e20c/tools/k3stream.py
8.91 kB
| """Stream the LittleBoy checkpoint shard by shard through the k3ref reference and measure per-token loss of | |
| BOTH the base model (experts >= 896 masked out, which is exactly Kimi K3.1-Pro) and LittleBoy, in one pass. | |
| Runs on a single GPU (Colab A100/H100). Each shard is downloaded, used for one layer, then deleted, so the disk peak | |
| is ~2 shards. Texts: a JSONL file with {"id", "text", "set"}; each text is tokenised and cut to --seq tokens. | |
| python k3stream.py --texts eval.jsonl --seq 2048 --batch 8 --out out/ [--cache-layer K] | |
| Output: out/nll_{base,littleboy}.pt (per-token NLL, [n_seq, seq-1]) and out/summary.json (mean NLL and perplexity | |
| per set, routing share of the new experts per layer). With --cache-layer K the state entering layer K is saved for | |
| both models (frozen-prefix training of the top block). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import os | |
| import threading | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from huggingface_hub import hf_hub_download | |
| from safetensors import safe_open | |
| import k3ref as K | |
| REPO = "STAR-future/Trinity" | |
| BASE = "moonshotai/Kimi-K3.1-Pro" | |
| def say(*a): | |
| print(time.strftime("%H:%M:%S"), *a, flush=True) | |
| def shard_name(i: int) -> str: | |
| return f"model-{i:05d}-of-000096.safetensors" | |
| class Prefetch: | |
| """Download shard files one ahead of use.""" | |
| def __init__(self, repo, tok, work): | |
| self.repo, self.tok, self.work = repo, tok, work | |
| self.paths, self.threads = {}, {} | |
| def _get(self, s): | |
| for k in range(5): | |
| try: | |
| self.paths[s] = hf_hub_download(self.repo, s, token=self.tok, local_dir=self.work) | |
| return | |
| except Exception as e: # noqa: BLE001 | |
| say("download retry", s, k, e) | |
| time.sleep(30 * (k + 1)) | |
| raise RuntimeError("download failed: " + s) | |
| def start(self, s): | |
| if s not in self.threads: | |
| self.threads[s] = threading.Thread(target=self._get, args=(s,), daemon=True) | |
| self.threads[s].start() | |
| def get(self, s): | |
| self.start(s) | |
| self.threads[s].join() | |
| return self.paths[s] | |
| def layer_weights(path: str, L: int, dev, experts_on_gpu: bool) -> dict: | |
| pre = f"language_model.model.layers.{L}." | |
| W, ex = {}, {} | |
| with safe_open(path, framework="pt", device="cpu") as f: | |
| for key in f.keys(): | |
| if not key.startswith(pre): | |
| continue | |
| rest = key[len(pre):] | |
| if ".indexer." in rest: | |
| continue | |
| if ".experts." in rest: | |
| _, _, e, w, kind = rest.split(".") # block_sparse_moe.experts.E.wN.weight_packed|scale | |
| ex.setdefault(int(e), {})[(w, kind)] = f.get_tensor(key) | |
| continue | |
| for p in ("self_attn.", "block_sparse_moe."): | |
| if rest.startswith(p): | |
| rest = rest[len(p):] | |
| if rest == "gate.e_score_correction_bias": | |
| rest = "e_score_correction_bias" | |
| if rest.endswith(".weight"): | |
| rest = rest[: -len(".weight")] | |
| W[rest] = f.get_tensor(key).to(dev) | |
| if ex: | |
| n = max(ex) + 1 | |
| pk = {w: torch.stack([ex[e][(w, "weight_packed")] for e in range(n)]) for w in ("w1", "w2", "w3")} | |
| sc = {w: torch.stack([ex[e][(w, "weight_scale")] for e in range(n)]) for w in ("w1", "w2", "w3")} | |
| if experts_on_gpu: | |
| pk = {w: t.to(dev) for w, t in pk.items()} | |
| sc = {w: t.to(dev) for w, t in sc.items()} | |
| def experts(e, pk=pk, sc=sc): | |
| return tuple(K.dequant(pk[w][e].to(dev, non_blocking=True), sc[w][e].to(dev, non_blocking=True)) | |
| for w in ("w1", "w2", "w3")) | |
| W["experts"] = experts | |
| W["_n_experts"] = n | |
| return W | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--texts", required=True) | |
| ap.add_argument("--seq", type=int, default=2048) | |
| ap.add_argument("--batch", type=int, default=8) | |
| ap.add_argument("--max-seqs", type=int, default=16) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--work", default="/content/lbshards") | |
| ap.add_argument("--cache-layer", type=int, default=-1) | |
| ap.add_argument("--layers", type=int, default=-1, help="debug: stop after this many layers") | |
| ap.add_argument("--modes", default="base,littleboy") | |
| a = ap.parse_args() | |
| out = Path(a.out) | |
| out.mkdir(parents=True, exist_ok=True) | |
| tok_hf = os.environ.get("HF_TOKEN") | |
| dev = torch.device("cuda") | |
| torch.backends.cuda.matmul.allow_tf32 = True | |
| cfg_path = hf_hub_download(BASE, "config.json") # LittleBoy's own config.json is added at finalisation | |
| tc = json.loads(Path(cfg_path).read_text())["text_config"] | |
| c = K.Cfg(tc) | |
| from transformers import AutoTokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(BASE, trust_remote_code=True) | |
| rows = [json.loads(ln) for ln in Path(a.texts).read_text(encoding="utf-8").splitlines() if ln.strip()] | |
| seqs, meta = [], [] | |
| for r in rows: | |
| ids = tokenizer.encode(r["text"]) | |
| if len(ids) >= a.seq: | |
| seqs.append(ids[: a.seq]) | |
| meta.append({"id": r["id"], "set": r.get("set", "default")}) | |
| if len(seqs) >= a.max_seqs: | |
| break | |
| if not seqs: | |
| raise SystemExit("no text long enough for --seq") | |
| ids = torch.tensor(seqs, dtype=torch.long) | |
| say("sequences", ids.shape, "sets", sorted({m["set"] for m in meta})) | |
| modes = a.modes.split(",") | |
| free = torch.cuda.mem_get_info()[0] / 2 ** 30 | |
| experts_on_gpu = free > 60 | |
| say("GPU free GiB", round(free, 1), "experts on GPU:", experts_on_gpu) | |
| pf = Prefetch(REPO, tok_hf, a.work) | |
| last = shard_name(94) | |
| pf.start(last) | |
| pf.start(shard_name(1)) | |
| with safe_open(pf.get(last), framework="pt", device="cpu") as f: | |
| emb_w = f.get_tensor("language_model.model.embed_tokens.weight") | |
| Wf = {"output_attn_res_norm": f.get_tensor("language_model.model.output_attn_res_norm.weight").to(dev), | |
| "output_attn_res_proj": f.get_tensor("language_model.model.output_attn_res_proj.weight").to(dev), | |
| "norm": f.get_tensor("language_model.model.norm.weight").to(dev)} | |
| lm_head = f.get_tensor("language_model.lm_head.weight").to(dev) | |
| batches = [ids[i:i + a.batch] for i in range(0, len(ids), a.batch)] | |
| states = {m: [K.init_state(emb_w[b].to(dev), c) for b in batches] for m in modes} | |
| del emb_w | |
| stats = {m: {} for m in modes} | |
| n_layers = c.n_layers if a.layers < 0 else a.layers | |
| for L in range(n_layers): | |
| s = shard_name(L + 1) | |
| if L + 2 <= 93: | |
| pf.start(shard_name(L + 2)) | |
| t0 = time.time() | |
| path = pf.get(s) | |
| W = layer_weights(path, L, dev, experts_on_gpu) | |
| t1 = time.time() | |
| if L == a.cache_layer: | |
| torch.save({m: [{k: (v.cpu() if torch.is_tensor(v) else v) for k, v in st.items()} for st in states[m]] | |
| for m in modes}, out / f"state_in_layer{L}.pt") | |
| with torch.no_grad(): | |
| for m in modes: | |
| for st in states[m]: | |
| K.forward_layer(L, W, c, st, mask_new=(m == "base"), stats=stats[m].setdefault(L, {})) | |
| torch.cuda.synchronize() | |
| share = {m: round(sum(stats[m][L].get("new_share", [0])) / max(1, len(stats[m][L].get("new_share", [0]))), 4) | |
| for m in modes} | |
| say(f"layer {L} load {t1 - t0:.0f}s compute {time.time() - t1:.0f}s new-share {share}") | |
| del W | |
| if L > 0: | |
| Path(path).unlink(missing_ok=True) | |
| res = {"seq": a.seq, "n_seqs": len(seqs), "layers_run": n_layers, "modes": {}} | |
| with torch.no_grad(): | |
| for m in modes: | |
| # tgt_nll[i, t] is the loss of predicting token t+1 from tokens <= t | |
| tgt_nll = torch.cat([K.token_nll(K.final_hidden(st, Wf, c)[:, :-1].contiguous(), lm_head, b[:, 1:].to(dev)) | |
| for st, b in zip(states[m], batches)]) | |
| torch.save(tgt_nll.cpu(), out / f"nll_{m}.pt") | |
| per_set = {} | |
| for sname in sorted({x["set"] for x in meta}): | |
| rows_i = [i for i, x in enumerate(meta) if x["set"] == sname] | |
| v = float(tgt_nll[rows_i].mean()) | |
| per_set[sname] = {"mean_nll": v, "ppl": math.exp(v), "n_seqs": len(rows_i)} | |
| res["modes"][m] = {"per_set": per_set, | |
| "new_share_by_layer": {L: sum(d.get("new_share", [0])) / max(1, len(d.get("new_share", [0]))) | |
| for L, d in stats[m].items()}} | |
| res["meta"] = meta | |
| (out / "summary.json").write_text(json.dumps(res, indent=1)) | |
| say("DONE", json.dumps({m: res["modes"][m]["per_set"] for m in modes})) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |