From 82c6464c9206ebc613bfb948626eb86b0535103e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Tue, 29 Sep 2026 06:56:26 +0200 Subject: [PATCH] F-1: the streaming detokenizer decodes each token's bytes incrementally (constant time per token) It re-decoded every generated id per token: 2 ms per token after 8K tokens, 4 ms after 16K. Now 0.0005 ms at any length; the text is the same (serve/test_detok.py checks it against the old algorithm on real and random token streams), and a complete character is no longer held back behind an incomplete one. --- serve/server.py | 11 +++- serve/test_detok.py | 107 ++++++++++++++++++++++++++++++++++++++ tools/strata_tokenizer.py | 21 +++++--- 3 files changed, 130 insertions(+), 9 deletions(-) create mode 100644 serve/test_detok.py diff --git a/serve/server.py b/serve/server.py index 2cdd84f7..defdbc79 100644 --- a/serve/server.py +++ b/serve/server.py @@ -24,6 +24,7 @@ import argparse import collections import base64 import hashlib +import codecs import json import os import queue @@ -515,13 +516,19 @@ class ByteTokenizer: # ------------------------------------------------------------------------------------------------ core class Detokenizer: - """Incremental decode: re-decode the generated ids and emit only the new, complete suffix (a multi-byte - character split across tokens is held until complete).""" + """Incremental decode: each token's bytes go through an incremental UTF-8 decoder, which emits the complete + characters and holds a multi-byte character split across tokens until it is complete (invalid bytes become + U+FFFD, as a whole decode with errors="replace" makes them). Constant time per token - the old re-decode of + every generated id cost 2 ms per token after 8K tokens and 4 ms after 16K (perf-review F-1). A tokenizer + without `token_bytes` (the tests' byte tokenizer) keeps the re-decode.""" def __init__(self, tok): self.tok, self.ids, self.sent = tok, [], 0 + self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") if hasattr(tok, "token_bytes") else None def push(self, t: int) -> str: + if self.inc is not None: + return self.inc.decode(self.tok.token_bytes(t)) self.ids.append(t) text = self.tok.decode(self.ids) if text.endswith("�"): diff --git a/serve/test_detok.py b/serve/test_detok.py new file mode 100644 index 00000000..1a1f1ec6 --- /dev/null +++ b/serve/test_detok.py @@ -0,0 +1,107 @@ +"""The streaming detokenizer (perf-review F-1): the incremental one emits exactly what the old re-decode did, token +by token, and its cost per token does not grow with the reply. + + python -m unittest serve.test_detok (needs a pack's tokenizer; skipped without one) +""" +import os +import random +import sys +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "tools")) +sys.path.insert(0, str(ROOT)) + +from serve.server import Detokenizer # noqa: E402 + + +def find_tokenizer(): + cands = [os.environ.get("STRATA_TOKENIZER", "")] + cands += [str(p) for p in ROOT.glob("packs/*/tokenizer")] + [str(p) for p in ROOT.glob("pack/*/tokenizer")] + cands += [r"C:\Users\AI-Server\Desktop\Strata\Public\Engine\pack\full\tokenizer"] + for c in cands: + if c and (Path(c) / "vocab.json").exists(): + return Path(c) + return None + + +class OldDetokenizer: + """The pre-0.1.22 algorithm: re-decode every generated id, hold a trailing U+FFFD.""" + + def __init__(self, tok): + self.tok, self.ids, self.sent = tok, [], 0 + + def push(self, t): + self.ids.append(t) + text = self.tok.decode(self.ids) + if text.endswith("\ufffd"): + return "" + delta, self.sent = text[self.sent:], len(text) + return delta + + +@unittest.skipIf(find_tokenizer() is None, "no pack tokenizer here") +class Detok(unittest.TestCase): + @classmethod + def setUpClass(cls): + import json + import strata_tokenizer as ST + t = find_tokenizer() + vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8")) + toks = [None] * len(vocab) + for s, i in vocab.items(): + toks[i] = s + cls.tok = ST.Tokenizer(toks, (t / "merges.txt").read_text(encoding="utf-8").split("\n"), + json.loads((t / "token_type.json").read_text())) + + def same_stream(self, ids): + """The same text as the old re-decode, never behind it (the old one held complete characters too while + the tail was an incomplete one; the new one holds only the incomplete bytes), and never ahead of what the + ids so far decode to.""" + a, b = OldDetokenizer(self.tok), Detokenizer(self.tok) + self.assertIsNotNone(b.inc) + old = new = "" + for i, t in enumerate(ids): + old += a.push(t) + new += b.push(t) + self.assertTrue(new.startswith(old), f"token {i} ({t}): behind the old stream") + self.assertTrue(self.tok.decode(ids[:i + 1]).startswith(new), f"token {i} ({t}): ahead of the ids") + if not self.tok.decode(ids).endswith("�"): + self.assertEqual(old, new) + + def test_text_with_split_characters(self): + text = ("Grüße aus Zürich! 你好,世界。日本語のテキスト 🌊🦊👩‍💻 and ASCII code: def f(x): return x**2\n" * 40) + self.same_stream(self.tok.encode(text)) + + def test_random_ids_and_broken_bytes(self): + rng = random.Random(5) + n = len(self.tok.tokens) + for _ in range(20): # random ids: split and invalid UTF-8 sequences everywhere (no U+FFFD token itself) + ids = [rng.randrange(n) for _ in range(300)] + ids = [t for t in ids if "\ufffd" not in self.tok.decode([t], errors="strict" if False else "replace") + or len(self.tok.token_bytes(t)) < 3] + self.same_stream(ids) + + def test_constant_cost(self): + ids = self.tok.encode("The quick brown fox jumps over the lazy dog. " * 2000)[:16384] + d = Detokenizer(self.tok) + for t in ids[:1024]: + d.push(t) + t0 = time.perf_counter() + for t in ids[1024:1124]: + d.push(t) + early = time.perf_counter() - t0 + for t in ids[1124:16000]: + d.push(t) + t0 = time.perf_counter() + for t in ids[16000:16100]: + d.push(t) + late = time.perf_counter() - t0 + self.assertLess(late / 100, 0.0002, "a token after 16K tokens costs more than 0.2 ms") + self.assertLess(late, early * 5 + 0.002) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.py index 59dfb876..92a71f87 100644 --- a/tools/strata_tokenizer.py +++ b/tools/strata_tokenizer.py @@ -194,17 +194,24 @@ class Tokenizer: """ return self._encode_matching(text, self._special_re if parse_special else self._always_re) - def decode(self, ids: list[int], errors: str = "replace") -> str: - raw = bytearray() - for i in ids: + 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", {}) + b = cache.get(i) + if b is None: if i < 0 or i >= len(self.tokens): raise IndexError("token id %d is outside the vocabulary (%d)" % (i, len(self.tokens))) + raw = bytearray() for ch in self.tokens[i]: - b = UNICODE_TO_BYTE.get(ch) - if b is None: + v = UNICODE_TO_BYTE.get(ch) + if v is None: raise KeyError("token %d contains a character outside the byte alphabet: %r" % (i, ch)) - raw.append(b) - return raw.decode("utf-8", errors=errors) + raw.append(v) + b = cache[i] = bytes(raw) + return b + + def decode(self, ids: list[int], errors: str = "replace") -> str: + return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors=errors) # ------------------------------------------------------------------ the pack's tokenizer/ directory