okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8aeefca2d
main
1"""The streaming detokenizer (perf-review F-1): the incremental one emits exactly what the old re-decode did, token 2by token, and its cost per token does not grow with the reply. 3 4python -m unittest serve.test_detok (needs a pack's tokenizer; skipped without one) 5""" 6import os 7import random 8import sys 9import time 10import unittest 11from pathlib import Path 12 13ROOT = Path (__file__ ).resolve ().parent .parent 14sys .path .insert (0 ,str (ROOT / "tools" )) 15sys .path .insert (0 ,str (ROOT )) 16 17from serve .server import Detokenizer # noqa: E402 18 19 20def find_tokenizer (): 21cands = [os .environ .get ("STRATA_TOKENIZER" ,"" )] 22cands += [str (p )for p in ROOT .glob ("packs/*/tokenizer" )]+ [str (p )for p in ROOT .glob ("pack/*/tokenizer" )] 23cands += [r"C:\Users\AI-Server\Desktop\Strata\Public\Engine\pack\full\tokenizer" ] 24for c in cands : 25if c and (Path (c )/ "vocab.json" ).exists (): 26return Path (c ) 27return None 28 29 30class OldDetokenizer : 31"""The pre-0.1.22 algorithm: re-decode every generated id, hold a trailing U+FFFD.""" 32 33def __init__ (self ,tok ): 34self .tok ,self .ids ,self .sent = tok , [],0 35 36def push (self ,t ): 37self .ids .append (t ) 38text = self .tok .decode (self .ids ) 39if text .endswith ("\ufffd" ): 40return "" 41delta ,self .sent = text [self .sent :],len (text ) 42return delta 43 44 45@ unittest . skipIf (find_tokenizer() is None , "no pack tokenizer here" ) 46class Detok (unittest .TestCase ): 47@classmethod 48def setUpClass (cls ): 49import json 50import strata_tokenizer as ST 51t = find_tokenizer () 52vocab = json .loads ((t / "vocab.json" ).read_text (encoding = "utf-8" )) 53toks = [None ]* len (vocab ) 54for s ,i in vocab .items (): 55toks [i ]= s 56cls .tok = ST .Tokenizer (toks , (t / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 57json .loads ((t / "token_type.json" ).read_text ())) 58 59def same_stream (self ,ids ): 60"""The same text as the old re-decode, never behind it (the old one held complete characters too while 61the tail was an incomplete one; the new one holds only the incomplete bytes), and never ahead of what the 62ids so far decode to.""" 63a ,b = OldDetokenizer (self .tok ),Detokenizer (self .tok ) 64self .assertIsNotNone (b .inc ) 65old = new = "" 66for i ,t in enumerate (ids ): 67old += a .push (t ) 68new += b .push (t ) 69self .assertTrue (new .startswith (old ),f"token { i } ( { t } ): behind the old stream" ) 70self .assertTrue (self .tok .decode (ids [:i + 1 ]).startswith (new ),f"token { i } ( { t } ): ahead of the ids" ) 71if not self .tok .decode (ids ).endswith ("�" ): 72self .assertEqual (old ,new ) 73 74def test_text_with_split_characters (self ): 75text = ("Grüße aus Zürich! 你好,世界。日本語のテキスト 🌊🦊👩💻 and ASCII code: def f(x): return x**2\n" * 40 ) 76self .same_stream (self .tok .encode (text )) 77 78def test_random_ids_and_broken_bytes (self ): 79rng = random .Random (5 ) 80n = len (self .tok .tokens ) 81for _ in range (20 ):# random ids: split and invalid UTF-8 sequences everywhere (no U+FFFD token itself) 82ids = [rng .randrange (n )for _ in range (300 )] 83ids = [t for t in ids if "\ufffd" not in self .tok .decode ([t ],errors = "strict" if False else "replace" ) 84or len (self .tok .token_bytes (t ))< 3 ] 85self .same_stream (ids ) 86 87def test_constant_cost (self ): 88ids = self .tok .encode ("The quick brown fox jumps over the lazy dog. " * 2000 )[:16384 ] 89d = Detokenizer (self .tok ) 90for t in ids [:1024 ]: 91d .push (t ) 92t0 = time .perf_counter () 93for t in ids [1024 :1124 ]: 94d .push (t ) 95early = time .perf_counter ()- t0 96for t in ids [1124 :16000 ]: 97d .push (t ) 98t0 = time .perf_counter () 99for t in ids [16000 :16100 ]: 100d .push (t ) 101late = time .perf_counter ()- t0 102self .assertLess (late / 100 ,0.0002 ,"a token after 16K tokens costs more than 0.2 ms" ) 103self .assertLess (late ,early * 5 + 0.002 ) 104 105 106# ------------------------------------------------------------------ #268: the heap BPE for long words 107_REAL = [] 108 109 110def real_tokenizer (): 111"""The pack's tokenizer, loaded once for every class that needs it (None when there is no pack here).""" 112if not _REAL : 113t = find_tokenizer () 114if t is None : 115_REAL .append (None ) 116else : 117import json 118import strata_tokenizer as ST 119vocab = json .loads ((t / "vocab.json" ).read_text (encoding = "utf-8" )) 120toks = [None ]* len (vocab ) 121for s ,i in vocab .items (): 122toks [i ]= s 123_REAL .append (ST .Tokenizer (toks , (t / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 124json .loads ((t / "token_type.json" ).read_text ()))) 125return _REAL [0 ] 126 127 128def random_text (rng ,n_pieces = 40 ): 129"""Strings shaped to make one pre-token piece long or awkward: CJK and Hangul runs (syllables and conjoining 130jamo), letters under stacks of combining marks, URLs, minified code, digits, emoji, whitespace, specials.""" 131def run (lo ,hi ,k ): 132return "" .join (chr (rng .randint (lo ,hi ))for _ in range (k )) 133 134kinds = [ 135lambda :run (0x4E00 ,0x9FFF ,rng .randint (1 ,400 )),# CJK 136lambda :run (0xAC00 ,0xD7A3 ,rng .randint (1 ,200 )),# Hangul syllables 137lambda :"" .join (chr (0x1100 + rng .randrange (19 ))+ chr (0x1161 + rng .randrange (21 )) 138for _ in range (rng .randint (1 ,60 ))),# conjoining jamo 139lambda :"" .join (rng .choice ("aeiouxyz" )+ run (0x0300 ,0x036F ,rng .randint (0 ,4 )) 140for _ in range (rng .randint (1 ,80 ))),# combining marks 141lambda :"https://example.com/" + "/" .join (run (0x61 ,0x7A ,rng .randint (1 ,12 )) 142for _ in range (rng .randint (1 ,20 )))+ "?q=" + run (0x30 ,0x39 ,8 ), 143lambda :"" .join (rng .choice (["var " ,"a=" ,"b" ,"(" ,")" ,"{" ,"}" ,";" ,"function" ,"return" ,"x" ,"+" , 144"!0" ,"void 0" ,"," ,"." ,"[" ,"]" ,"=>" ,"&&" ])for _ in range (rng .randint (1 ,300 ))), 145lambda :run (0x30 ,0x39 ,rng .randint (1 ,50 )), 146lambda :rng .choice ([" " ," " ,"\n" ,"\n\n" ,"\t" ,"\r\n" ," \n " ])* rng .randint (1 ,30 ), 147lambda :rng .choice (["\U0001f600" ,"\U0001f30a" ,"\U0001f469\U0001f4bb" ,"é" ,"ß" ])* rng .randint (1 ,30 ), 148lambda :rng .choice (["<|im_end|>" ,"<|im_start|>" ,"<think>" ,"</think>" ,"<tool_call>" ,"<|im_sta" ]), 149lambda :"a" * rng .randint (60 ,300 ), 150lambda :run (0x20 ,0x7E ,rng .randint (1 ,200 )), 151 ] 152return "" .join (rng .choice (kinds )()for _ in range (rng .randint (1 ,n_pieces ))) 153 154 155def encode_with (tok ,text ,parse_special ,heap_min ): 156tok .HEAP_MIN = heap_min 157try : 158return tok .encode (text ,parse_special = parse_special ) 159finally : 160del tok .HEAP_MIN 161 162 163def synthetic_tokenizer (seed = 268 ,n_merges = 1500 ): 164"""A small byte-level BPE vocabulary with merges learned (randomly) from random_text, and a few specials of 165both kinds - so the parity test runs without a pack.""" 166import strata_tokenizer as ST 167rng = random .Random (seed ) 168tokens = sorted (set (ST .BYTE_TO_UNICODE .values ())) 169have ,merges = set (tokens ), [] 170words = [] 171for _ in range (60 ): 172for piece in ST .regex .compile (ST .QWEN35_PATTERN ).findall (random_text (rng ,10 )): 173words .append ([ST .BYTE_TO_UNICODE [b ]for b in piece .encode ("utf-8" )]) 174words = [w for w in words if len (w )> 1 ] 175while len (merges )< n_merges : 176w = rng .choice (words ) 177if len (w )< 2 : 178continue 179i = rng .randrange (len (w )- 1 ) 180a ,b = w [i ],w [i + 1 ] 181w [i :i + 2 ]= [a + b ]# learn in place, so later merges build on earlier ones 182if a + b in have or f" { a } { b } " in merges : 183continue 184merges .append (f" { a } { b } " ) 185tokens .append (a + b ) 186have .add (a + b ) 187types = [1 ]* len (tokens ) 188for lit ,ty in [("<|im_end|>" ,3 ), ("<|im_start|>" ,3 ), ("<think>" ,4 ), ("</think>" ,4 ), ("<tool_call>" ,4 )]: 189tokens .append (lit ) 190types .append (ty ) 191return ST .Tokenizer (tokens ,merges ,types ) 192 193 194class ThreadedEncode (unittest .TestCase ): 195"""#1385: 'int' object has no attribute 'ranks' in _bpe, seen once under load. Could not be reproduced here (it 196looks like an interpreter fault); this pins that many threads sharing one Tokenizer, as the server does, get 197exactly the single-threaded ids, and that _bpe works with a tokenizer whose own state is only read.""" 198 199def test_threads_match_serial (self ): 200import threading 201tok = synthetic_tokenizer () 202rng = random .Random (1385 ) 203texts = [random_text (rng ,6 )for _ in range (40 )] 204want = [tok .encode (t )for t in texts ] 205errors = [] 206 207def work (): 208try : 209for _ in range (15 ): 210for t ,w in zip (texts ,want ): 211if tok .encode (t )!= w : 212errors .append ("mismatch" ) 213except Exception as e :# noqa: BLE001 214errors .append (repr (e )) 215 216ts = [threading .Thread (target = work )for _ in range (8 )] 217for t in ts : 218t .start () 219for t in ts : 220t .join () 221self .assertEqual (errors , []) 222 223 224class HeapBpe (unittest .TestCase ): 225"""#268: words longer than HEAP_MIN symbols merge with a heap; the ids must be exactly the scan's.""" 226 227def parity (self ,tok ,texts ): 228for k ,text in enumerate (texts ): 229for ps in (False ,True ): 230old = encode_with (tok ,text ,ps ,10 ** 9 )# the scan for every word 231self .assertEqual (encode_with (tok ,text ,ps ,0 ),old ,f"text { k } parse_special= { ps } " )# the heap 232self .assertEqual (tok .encode (text ,parse_special = ps ),old ,f"text { k } parse_special= { ps } " ) 233 234def test_words_directly (self ): 235tok = synthetic_tokenizer () 236rng = random .Random (1 ) 237import strata_tokenizer as ST 238for _ in range (300 ): 239for piece in ST .regex .compile (ST .QWEN35_PATTERN ).findall (random_text (rng ,8 )): 240word = "" .join (ST .BYTE_TO_UNICODE [b ]for b in piece .encode ("utf-8" )) 241tok .HEAP_MIN = 10 ** 9 242try : 243old = tok ._bpe (word ) 244finally : 245del tok .HEAP_MIN 246self .assertEqual (tok ._bpe_heap (word ),old ,repr (piece [:40 ])) 247 248def test_synthetic_vocab (self ): 249tok = synthetic_tokenizer () 250rng = random .Random (2 ) 251self .parity (tok , [random_text (rng )for _ in range (60 )]+ ["a" * 5000 ,"ab" * 3000 ,"" ]) 252 253@ unittest . skipIf (find_tokenizer() is None , "no pack tokenizer here" ) 254def test_pack_vocab (self ): 255tok = real_tokenizer () 256rng = random .Random (3 ) 257fixed = ["你好,世界" * 150 ,"한국어 텍스트" * 100 , 258"é́̂" * 200 ,"x" * 5000 , 259"https://example.com/" + "a/b-c_d.e?f=g&h=i#j" * 60 , 260"!function(e){var t={};function n(r){if(t[r])return t[r].exports}}" * 30 , 261"<|im_start|>user\n日本語" * 40 + "<|im_end|><think>" + "漢" * 300 ] 262self .parity (tok ,fixed + [random_text (rng )for _ in range (40 )]) 263 264def check_speed (self ,tok ): 265rng = random .Random (4 ) 266text = "" .join (chr (rng .randint (0x4E00 ,0x9FFF ))for _ in range (8192 ))# one 24K-byte piece 267t0 = time .perf_counter () 268ids = tok .encode (text ) 269took = time .perf_counter ()- t0 270self .assertEqual (tok .decode (ids ),text ) 271self .assertLess (took ,1.0 ,f"an 8K-character CJK run took { took :.2f } s" ) 272 273def test_speed_synthetic (self ): 274self .check_speed (synthetic_tokenizer ()) 275 276@ unittest . skipIf (find_tokenizer() is None , "no pack tokenizer here" ) 277def test_speed_pack (self ): 278self .check_speed (real_tokenizer ()) 279 280 281if __name__ == "__main__" : 282unittest .main ()