Files
strata/tools/test_strata_tokenizer.py
T

53 lines
1.7 KiB
Python

"""The tokenizer's piece cache (0.1.41): the ids are the ones the merge loop gives, cache cold, warm or switched off.
python -m unittest tools.test_strata_tokenizer
"""
from __future__ import annotations
import random
import sys
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tools"))
import strata_tokenizer as ST # noqa: E402
def toy() -> ST.Tokenizer:
base = [ST.BYTE_TO_UNICODE[b] for b in range(256)]
merges = ["t h", "th e", "i n", "a n", "an d", "Ġ t", "Ġt h", "Ġth e", "e r", "o n"]
merges = [m.replace("Ġ", ST.BYTE_TO_UNICODE[32]) for m in merges]
tokens = list(base)
for m in merges:
a, b = m.split(" ")
tokens.append(a + b)
return ST.Tokenizer(tokens, merges)
class PieceCache(unittest.TestCase):
def test_same_ids_cold_warm_and_off(self):
rng = random.Random(7)
words = ["the", "and", "in", "on", "there", "other", "x" * 70, "你好", "def", "return", "\n\n", " "]
text = "".join(rng.choice(words) + rng.choice([" ", "", "\n", "\t"]) for _ in range(3000))
a = toy()
a.PIECE_CACHE_MAX = 0
want = a.encode(text)
b = toy()
cold = b.encode(text)
warm = b.encode(text)
self.assertEqual(cold, want)
self.assertEqual(warm, want)
self.assertGreater(len(b._piece_ids), 0)
self.assertEqual(b.decode(warm), text)
def test_the_cache_is_bounded(self):
t = toy()
t.PIECE_CACHE_MAX = 5
t.encode(" ".join("w%d" % i for i in range(100)))
self.assertLessEqual(len(t._piece_ids), 5)
if __name__ == "__main__":
unittest.main()