Trinity / tools /colab_k3scale.py
STAR-future's picture
Trinity: public release (history squashed)
f80e81a
Raw History Blame Contribute Delete
3.66 kB
"""Colab GPU cell: how does the k3 pass cost scale with the number of tokens? (timing only, no cache, no training)
Same texts (train_corpus_v1 packed as in colab_k3pass 'train') at x1 and x10 copies, first 4 layers only.
Reads the per-layer 'attn'/'mlp' seconds from k3pass and uploads eval/k3scale.json. Decides whether expanding the
domain cache 10-10000x costs ~linear GPU time or mostly a fixed per-layer weight cost.
import os; from google.colab import userdata; import huggingface_hub as h
os.environ['HF_TOKEN'] = userdata.get('STARHUGGIN')
exec(open(h.hf_hub_download('STAR-future/Trinity', 'tools/colab_k3scale.py', token=os.environ['HF_TOKEN'],
force_download=True)).read())
"""
import json
import os
import re
import subprocess
import sys
import time
from pathlib import Path
from huggingface_hub import HfApi, hf_hub_download
TOK = os.environ["HF_TOKEN"]
REPO = "STAR-future/Trinity"
W = Path("/content/k3s")
W.mkdir(parents=True, exist_ok=True)
api = HfApi(token=TOK)
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "tiktoken"], check=True)
for f in ("k3ref.py", "k3pass.py"):
(W / f).write_bytes(Path(hf_hub_download(REPO, f"tools/{f}", token=TOK, force_download=True)).read_bytes())
docs = [json.loads(x) for x in Path(hf_hub_download(REPO, "eval/data/train_corpus_v1.jsonl", token=TOK,
force_download=True)).read_text(encoding="utf-8").splitlines() if x.strip()]
rows = []
for dom in sorted({d["domain"] for d in docs}):
buf, k = [], 0
for d in sorted((d for d in docs if d["domain"] == dom), key=lambda d: d["id"]):
buf.append(d["text"].strip())
if sum(len(b) for b in buf) >= 12500:
rows.append({"id": f"s_{dom}_{k:03d}", "text": "\n\n".join(buf), "set": f"train_{dom}", "role": "train",
"base": False})
buf, k = [], k + 1
import torch # noqa: E402
gpu = torch.cuda.get_device_name(0)
gb = torch.cuda.get_device_properties(0).total_memory / 2 ** 30
batch = os.environ.get("K3_BATCH", "12" if gb > 60 else ("8" if gb > 20 else "4"))
res = {"gpu": gpu, "batch": batch, "layers": 4, "runs": []}
for mult in (1, 10):
texts = W / f"t{mult}.jsonl"
texts.write_text("".join(json.dumps(dict(r, id=f"{r['id']}_c{c}")) + "\n" for c in range(mult) for r in rows),
encoding="utf-8")
t0 = time.time()
p = subprocess.run([sys.executable, "-u", str(W / "k3pass.py"), "--texts", str(texts), "--work", str(W / f"w{mult}"),
"--out", str(W / f"o{mult}"), "--batch", batch, "--layers", "4", "--no-cache"], cwd=W,
env=dict(os.environ, PYTHONPATH=str(W), PYTORCH_CUDA_ALLOC_CONF="expandable_segments:True",
HF_HUB_DISABLE_PROGRESS_BARS="1"), capture_output=True, text=True)
log = p.stdout + p.stderr
print(log[-3000:], flush=True)
toks = re.findall(r"tokens (\d+)", log)
lay = [{"layer": int(a), "wait": int(b), "attn": int(c), "mlp": int(d)}
for a, b, c, d in re.findall(r"layer (\d+) wait (\d+)s attn (\d+)s mlp (\d+)s", log)]
res["runs"].append({"mult": mult, "rc": p.returncode, "tokens": int(toks[0]) if toks else None, "layers": lay,
"wall_s": round(time.time() - t0)})
print(json.dumps(res["runs"][-1]), flush=True)
(W / "k3scale.json").write_text(json.dumps(res, indent=1))
api.upload_file(path_or_fileobj=str(W / "k3scale.json"), path_in_repo="eval/k3scale.json", repo_id=REPO,
commit_message="k3 pass scaling measurement")
print("SCALE", json.dumps(res), flush=True)