shadow-assistant-data / rebuild /text_shards.py
QLNI's picture
SHADOW Assistant data
362b32d
Raw History Blame Contribute Delete
1.85 kB
"""Write documents as SHADOW text shards: Gemma tokens (EmbeddingGemma 2 tokenizer), <bos> text <eos>, 3 bytes per token."""
import json, pathlib
import numpy as np
from transformers import AutoTokenizer
BOS, EOS, VOCAB = 2, 1, 262144
class Shards:
def __init__(self, out, name, shard_tokens=100_000_000):
self.dir = pathlib.Path(out) / name
self.dir.mkdir(parents=True, exist_ok=True)
self.name, self.shard_tokens = name, shard_tokens
self.tok = AutoTokenizer.from_pretrained("google/embeddinggemma-2")
self.buf, self.n, self.k, self.pending = [], 0, 0, []
def add(self, text):
self.pending.append(text)
if len(self.pending) >= 512:
self._tokenize()
def _tokenize(self):
for ids in self.tok(self.pending, add_special_tokens=False)["input_ids"]:
self.buf.append(np.asarray([BOS] + ids + [EOS], np.uint32))
self.n += len(ids) + 2
self.pending = []
if self.n >= self.shard_tokens:
self._write()
def _write(self):
if not self.n:
return
a = np.concatenate(self.buf)
b = np.empty((len(a), 3), np.uint8)
b[:, 0], b[:, 1], b[:, 2] = a & 255, (a >> 8) & 255, (a >> 16) & 255
stem = self.dir / f"{self.name}_{self.k:05d}"
stem.with_suffix(".bin").write_bytes(b.tobytes())
np.savez_compressed(f"{stem}.counts.npz", counts=np.bincount(a, minlength=VOCAB).astype(np.uint32))
stem.with_suffix(".json").write_text(json.dumps({"tokens": int(len(a)), "documents": len(self.buf), "bytes_per_token": 3, "bos": BOS, "eos": EOS}))
print(f"{stem.name}: {len(a):,} tokens", flush=True)
self.buf, self.n, self.k = [], 0, self.k + 1
def close(self):
if self.pending:
self._tokenize()
self._write()