Download rebuild/text_shards.py from QLNI/shadow-assistant-data: direct link, hf CLI and curl.
- Browser
- Download file 1.85 kB
-
https://huggingface.co/datasets/QLNI/shadow-assistant-data/resolve/main/rebuild/text_shards.py
- Command line
-
hf download hf://datasets/QLNI/shadow-assistant-data/rebuild/text_shards.py
-
curl -L -o text_shards.py https://huggingface.co/datasets/QLNI/shadow-assistant-data/resolve/main/rebuild/text_shards.py
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() | |