Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

tokenizer: initialize caches once per instance

InB4DevOpsac1df2c41622
diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py
index 7ab273e04..c9e84ee71 100644
--- a/tools/strata_tokenizer.py
+++ b/tools/strata_tokenizer.py
@@ -111,6 +111,10 @@ class Tokenizer:
# token containing regex metacharacters (several do: `<|`, `[`, `(`) is matched literally.
self._always_re = self._alt(always)
self._special_re = self._alt(list(self.special_tokens))
+ # Initialize once, rather than allocating a default dict and looking it up
+ # through __dict__.setdefault on each encoded segment or decoded token.
+ self._piece_ids: dict[str, list[int]] = {}
+ self._bytes_cache: dict[int, bytes] = {}
@staticmethod
def _alt(literals: list[str]):
@@ -214,7 +218,7 @@ class Tokenizer:
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", {})
+ cache = self._piece_ids
for piece in self._re.findall(text):
got = cache.get(piece)
if got is None:
@@ -281,7 +285,7 @@ class Tokenizer:
def token_bytes(self, i: int) -> bytes:
"""The raw bytes of one token (a multi-byte character can be split across tokens)."""
- cache = self.__dict__.setdefault("_bytes_cache", {})
+ cache = self._bytes_cache
b = cache.get(i)
if b is None:
if i < 0 or i >= len(self.tokens):
diff --git a/tools/test_strata_tokenizer.py b/tools/test_strata_tokenizer.py
index 6b2f9009e..17c3f6986 100644
--- a/tools/test_strata_tokenizer.py
+++ b/tools/test_strata_tokenizer.py
@@ -48,5 +48,52 @@ class PieceCache(unittest.TestCase):
self.assertLessEqual(len(t._piece_ids), 5)
+class ByteCache(unittest.TestCase):
+ def test_decode_before_encode_cold_and_warm(self):
+ t = toy()
+ text = "café 日本語 🙂\r\n\x00"
+ ids = list(text.encode("utf-8")) # toy's first 256 token IDs are the raw bytes
+ self.assertEqual(t.decode(ids, errors="strict"), text)
+ self.assertEqual(t.decode(ids, errors="strict"), text)
+ self.assertEqual(t.decode([]), "")
+ for i in range(256):
+ self.assertEqual(t.token_bytes(i), bytes([i]))
+
+ def test_invalid_ids_before_and_after_cache_use(self):
+ t = toy()
+ for _ in range(2):
+ for i in (-1, len(t.tokens), len(t.tokens) + 100):
+ with self.assertRaises(IndexError):
+ t.token_bytes(i)
+ self.assertEqual(t.token_bytes(65), b"A")
+
+ def test_instances_with_different_vocabularies_stay_independent(self):
+ tokens = [ST.BYTE_TO_UNICODE[b] for b in range(256)]
+ a, b = ST.Tokenizer(tokens, []), ST.Tokenizer(tokens[::-1], [])
+ text = "the café 日本語 🙂\n"
+ for t in (a, b, a, b):
+ expected = [t.ids[ST.BYTE_TO_UNICODE[byte]] for byte in text.encode("utf-8")]
+ self.assertEqual(t.encode(text), expected)
+ self.assertEqual(t.decode(expected, errors="strict"), text)
+ self.assertEqual(a.token_bytes(0), b"\x00")
+ self.assertEqual(b.token_bytes(0), b"\xff")
+
+ def test_shared_tokenizer_concurrent_first_decode(self):
+ import threading
+ from concurrent.futures import ThreadPoolExecutor
+ t = toy()
+ texts = ["café", "日本語", "🙂\r\n", "\x00plain"]
+ barrier = threading.Barrier(len(texts))
+ def decode(text):
+ ids = list(text.encode("utf-8"))
+ barrier.wait(timeout=5)
+ for _ in range(100):
+ if t.decode(ids, errors="strict") != text:
+ raise AssertionError("concurrent decode changed the text")
+ return text
+ with ThreadPoolExecutor(len(texts)) as pool:
+ self.assertEqual(list(pool.map(decode, texts)), texts)
+
+
if __name__ == "__main__":
unittest.main()