tokenizer: remember the ids of repeated pre-tokenizer pieces (a resent 89K-token agent prompt encodes in 0.07 s instead of 0.32 s; same ids)

This commit is contained in:
Niko1221 committed 2026-10-07 21:05:33 +02:00
1 parent dfa26c19c9
commit f346dc6b0c
2 files changed
+69 -6

No files matched your search

+17 -6
View File
@@ -208,15 +208,26 @@ class Tokenizer:
heapq.heappush(heap, (r2, p, parts[p], parts[i]))
return [s for s in parts if s is not None]
PIECE_CACHE_MAX = 200_000 # pre-tokenizer pieces remembered (an agent resends its whole history every turn)
def _encode_plain(self, text: str) -> list[int]:
out: list[int] = []
# A piece's ids depend on the piece alone, so repeated pieces (most of a resent conversation) are looked up
# instead of merged again. The ids are the ones _bpe gives: this only skips the work.
cache = self.__dict__.setdefault("_piece_ids", {})
for piece in self._re.findall(text):
mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8"))
for tok in self._bpe(mapped):
i = self.ids.get(tok)
if i is None:
raise KeyError("BPE produced a token outside the vocabulary: %r" % tok)
out.append(i)
got = cache.get(piece)
if got is None:
mapped = "".join(BYTE_TO_UNICODE[b] for b in piece.encode("utf-8"))
got = []
for tok in self._bpe(mapped):
i = self.ids.get(tok)
if i is None:
raise KeyError("BPE produced a token outside the vocabulary: %r" % tok)
got.append(i)
if len(cache) < self.PIECE_CACHE_MAX:
cache[piece] = got
out.extend(got)
return out
def _encode_matching(self, text: str, pat, plain=()) -> list[int]:
+52
View File
@@ -0,0 +1,52 @@
"""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()