solstice-80m-webgpu / tools /build_embeddings.py
thalismind
Claude Opus 5.5
feat: Solstice 80M and Nyx 36M in the browser with prompt sweeps, embedding arithmetic and runtime LoRAs
48441eb
Raw History Blame Contribute Delete
5.97 kB
"""Precompute the text embeddings of the prompt library (tools/prompts.py) for both models.
python tools/build_embeddings.py [--models solstice nyx] [--device cpu] [--batch 16]
-> data/library.json, data/<model>.json (index) and data/<model>.bin (tensors)
Needs torch, transformers (with T5Gemma) and sentencepiece. Encoders, as each model was trained:
solstice google/t5gemma-2b-2b-ul2 encoder, "pixel art, 32px, <caption>" padded right to 64 tokens,
states zeroed past the attention mask, pool = masked mean; "" unprefixed is the unconditional
prompt (generate.py). fp32 on CPU, bf16 on CUDA.
nyx google/siglip-base-patch16-224 text tower, "pixel art icon of a <phrase>" padded to 64,
tokens = positions 0-31 (all attended), pool = pooler_output; "" is unconditional (nyx_v2).
Storage, per entry, little endian: int8 tokens [len, D], float16 scale [len], float16 pool [D].
Tokens are quantised per token (scale = max|h| / 127), as Solstice's training text cache was; only the
`len` valid positions are kept (Nyx: all 32). The index JSON holds each entry's key, encoded text, len and
byte offset; entry 0 is the unconditional prompt.
"""
import argparse
import json
import sys
import time
from pathlib import Path
import numpy as np
import torch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(Path(__file__).resolve().parent))
from prompts import build, nyx_caption, solstice_caption # noqa: E402
class Solstice:
name, repo, tokens = "solstice", "google/t5gemma-2b-2b-ul2", 64
def __init__(self, device):
from transformers import AutoTokenizer, T5GemmaEncoderModel
self.device = device
self.tok = AutoTokenizer.from_pretrained(self.repo)
self.tok.padding_side = "right"
dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
self.model = T5GemmaEncoderModel.from_pretrained(self.repo, dtype=dtype, is_encoder_decoder=False)
self.model = self.model.to(device).eval().requires_grad_(False)
caption = staticmethod(solstice_caption)
@torch.inference_mode()
def __call__(self, strings):
enc = self.tok(strings, padding="max_length", max_length=self.tokens, truncation=True,
return_tensors="pt").to(self.device)
mask = enc.attention_mask.bool()
h = torch.where(mask[..., None], self.model(**enc).last_hidden_state.float(), 0.0)
length = mask.sum(1)
pool = h.sum(1) / length.clamp(min=1)[:, None]
return h.cpu(), length.cpu(), pool.cpu()
class Nyx:
name, repo, tokens = "nyx", "google/siglip-base-patch16-224", 32
def __init__(self, device):
from transformers import AutoTokenizer, SiglipTextModel
self.device = device
self.tok = AutoTokenizer.from_pretrained(self.repo)
self.model = SiglipTextModel.from_pretrained(self.repo, dtype=torch.float32).to(device).eval()
caption = staticmethod(nyx_caption)
@torch.inference_mode()
def __call__(self, strings):
enc = self.tok(strings, padding="max_length", max_length=64, truncation=True, return_tensors="pt")
out = self.model(input_ids=enc.input_ids.to(self.device))
h = out.last_hidden_state[:, :32].float()
return h.cpu(), torch.full((len(strings),), 32), out.pooler_output.float().cpu()
def quantise(h):
"""[L, D] float -> (int8 [L, D], float16 scale [L])."""
scale = np.maximum(np.abs(h).max(-1) / 127.0, 1e-8).astype(np.float16)
q = np.clip(np.round(h / scale.astype(np.float32)[:, None]), -127, 127).astype(np.int8)
return q, scale
def run(enc_cls, lib, device, batch, out_dir):
t0 = time.time()
enc = enc_cls(device)
print(f"{enc.name}: loaded {enc.repo} in {time.time() - t0:.0f}s", flush=True)
entries = [{"key": "", "text": ""}] + [{"key": e["key"], "text": enc.caption(e)} for e in lib["entries"]]
blobs, index, offset, dim = [], [], 0, None
t0 = time.time()
for i in range(0, len(entries), batch):
chunk = entries[i:i + batch]
h, length, pool = enc([e["text"] for e in chunk])
dim = h.shape[-1]
for j, e in enumerate(chunk):
n = int(length[j])
n_keep = max(1, n)
q, scale = quantise(h[j, :n_keep].numpy())
p = pool[j].numpy().astype(np.float16)
blob = q.tobytes() + scale.tobytes() + p.tobytes()
index.append({"key": e["key"], "text": e["text"], "len": n, "offset": offset})
blobs.append(blob)
offset += len(blob)
done = min(i + batch, len(entries))
print(f" {done}/{len(entries)} {time.time() - t0:.0f}s", flush=True)
(out_dir / f"{enc.name}.bin").write_bytes(b"".join(blobs))
meta = {"model": enc.name, "encoder": enc.repo, "tokens": enc.tokens, "dim": dim,
"mask": "all" if enc.name == "nyx" else "length", "bytes": offset, "entries": index}
(out_dir / f"{enc.name}.json").write_text(json.dumps(meta))
print(f"{enc.name}: {len(index)} entries, {offset / 1e6:.1f} MB", flush=True)
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--models", nargs="+", default=["solstice", "nyx"], choices=["solstice", "nyx"])
p.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
p.add_argument("--batch", type=int, default=16)
p.add_argument("--threads", type=int, default=0)
a = p.parse_args()
if a.threads:
torch.set_num_threads(a.threads)
out_dir = ROOT / "data"
out_dir.mkdir(exist_ok=True)
lib = build()
(out_dir / "library.json").write_text(json.dumps(lib, indent=1))
print(f"library: {len(lib['entries'])} prompts", flush=True)
for m in a.models:
run({"solstice": Solstice, "nyx": Nyx}[m], lib, torch.device(a.device), a.batch, out_dir)
if __name__ == "__main__":
main()