okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cded60248
main
1"""The end of a reply and the text held back in front of a stop string (#4576: "Nerazim" came out as "Neraz"). 2 3DeepSeek-V4.1's tokenizer has no single token for Qwen's <|im_end|> / <|endoftext|>: it splits them into '<', '|', 'im', '_end', 4'|', '>' and 'end', 'of', 'text'. A server that took the ids of those pieces as its stop ids (a config without "arch") ended the 5reply in front of the first "im" it wrote: Nerazim = N, er, az, im. These tests keep three things true, for the OpenAI and the 6Anthropic route, streamed and not, with and without the family named: 7 8* the reply that has no stop string comes out whole (every word that ends in a piece of a stop string or of an end marker); 9* a stop string cuts the reply exactly there, whatever the chunking; 10* the text held back for a stop string that does not come is given back at the end. 11 12python -m unittest serve.test_stop_holdback -v 13""" 14from __future__import annotations 15 16import json 17import sys 18import unittest 19import urllib .request 20from pathlib import Path 21 22ROOT = Path (__file__ ).resolve ().parents [1 ] 23sys .path .insert (0 ,str (ROOT )) 24sys .path .insert (0 ,str (ROOT / "tools" )) 25import strata_tokenizer as ST # noqa: E402 26from serve import frontend ,server # noqa: E402 27from serve .frontend import ChatTemplate # noqa: E402 28from serve .server import ByteTokenizer ,Detokenizer ,Service ,StopMatcher ,end_token_ids ,serve # noqa: E402 29from serve .test_dsv41 import EOS ,SPECIALS ,TEMPLATE ,DsEngine # noqa: E402 30 31QWEN_STOPS = ["<|im_end|>" ,"<|im_start|>" ,"<|endoftext|>" ,"\nUser:" ] 32DEEPSEEK_STOPS = ["<|end▁of▁sentence|>" ,"<|User|>" ,"</s>" ,"\n\nHuman:" ] 33# words and endings that look like the start of a stop string or a piece of an end marker 34WORDS = ["Nerazim" ,"Zim" ,"swim" ,"Neraz" ,"im" ,"im_end" ,"Nerazimville" ,"a|b|c|" ,"x > y and a < b" ,"the end of the text" , 35"<" ,"<|" ,"<|im" ,"<|im_end" ,"|>" ,"friend" ,"legend" ,"\nUser" ,"\n\nHuman" ,"</" ,"</s" ,"<|User" ,"<|" ,"Nerazim<" , 36"Nerazim|" ,"Nerazim <|im_start|" ] 37 38 39def nerazim_tokenizer ()-> ST .Tokenizer : 40"""DeepSeek's specials, the 256 byte tokens and the pieces of the real vocabulary that matter here: N er az im ('im' is id 41328 in the real one), and the pieces its tokenizer cuts Qwen's end markers into.""" 42b2u = ST .bytes_to_unicode () 43extra = ["er" ,"az" ,"im" ,"_e" ,"_en" ,"_end" ,"en" ,"end" ,"of" ,"te" ,"tex" ,"text" ] 44merges = ["e r" ,"a z" ,"i m" ,"_ e" ,"_e n" ,"_en d" ,"e n" ,"en d" ,"o f" ,"t e" ,"te x" ,"tex t" ] 45tokens = [s for s ,_ in SPECIALS ]+ [b2u [b ]for b in range (256 )]+ extra 46types = [t for _ ,t in SPECIALS ]+ [1 ]* (256 + len (extra )) 47return ST .Tokenizer (tokens ,merges ,types ,"deepseek3" , {"bos" :0 ,"eos" :EOS }) 48 49 50class Fixture (unittest .TestCase ): 51@classmethod 52def setUpClass (cls ): 53cls .tok = nerazim_tokenizer () 54 55def test_the_fixture_has_the_real_tokenizer_shape (self ): 56self .assertEqual ([self .tok .tokens [i ]for i in self .tok .encode ("Nerazim" )], ["N" ,"er" ,"az" ,"im" ]) 57pieces = [self .tok .tokens [i ]for i in self .tok .encode ("<|im_end|>" ,parse_special = True )] 58self .assertEqual (pieces , ["<" ,"|" ,"im" ,"_end" ,"|" ,">" ]) 59pieces = [self .tok .tokens [i ]for i in self .tok .encode ("<|endoftext|>" ,parse_special = True )] 60self .assertEqual (pieces , ["<" ,"|" ,"end" ,"of" ,"text" ,"|" ,">" ]) 61 62 63class EndTokenIds (Fixture ): 64def test_pieces_of_the_qwen_markers_are_not_stop_ids (self ): 65ids = end_token_ids (self .tok ) 66self .assertEqual (ids , {EOS }) 67pieces = set (self .tok .encode ("<|im_end|>" ,parse_special = True ))| set (self .tok .encode ("<|endoftext|>" ,parse_special = True )) 68self .assertFalse (ids & pieces ) 69 70def test_qwen_markers_that_are_one_token_each_are_the_stop_ids (self ): 71tok = ByteTokenizer () 72self .assertEqual (end_token_ids (tok ),set (tok .encode ("<|im_end|>" ,parse_special = True )) 73| set (tok .encode ("<|endoftext|>" ,parse_special = True ))) 74self .assertEqual (len (end_token_ids (tok )),2 ) 75 76def test_no_marker_and_no_eos_means_no_stop_id (self ): 77class Bare : 78def encode (self ,text ,parse_special = False ): 79return list (text .encode ()) 80self .assertEqual (end_token_ids (Bare ()),set ()) 81 82def test_a_service_without_a_family_does_not_stop_on_im (self ): 83svc = Service (DsEngine (self .tok ,"x" ),self .tok ,ChatTemplate (TEMPLATE )) 84im = self .tok .encode ("im" )[0 ] 85for piece in ("im" ,"<" ,"|" ,">" ,"end" ,"of" ,"text" ,"_end" ): 86self .assertNotIn (self .tok .encode (piece )[0 ],svc .stop_ids ,piece ) 87self .assertIn (im ,set (self .tok .encode ("<|im_end|>" ,parse_special = True ))) 88self .assertEqual (svc .stop_ids , {EOS }) 89 90 91class StopMatcherSplits (unittest .TestCase ): 92"""StopMatcher alone: every way to cut the text in two, and one character at a time.""" 93 94@staticmethod 95def run_matcher (stops ,chunks ): 96m = StopMatcher (stops ) 97out = "" .join (m .push (c )for c in chunks ) 98if m .hit is None : 99out += m .flush () 100return out ,m .hit 101 102def chunkings (self ,text ): 103yield [text ] 104for i in range (1 ,len (text )): 105yield [text [:i ],text [i :]] 106yield list (text ) 107 108def test_text_without_a_stop_string_comes_out_whole_at_every_split (self ): 109for stops in (QWEN_STOPS ,DEEPSEEK_STOPS , ["im_end" ], ["im" ], ["zim" ], ["|" ,">" ], ["end" ]): 110for word in WORDS : 111text = "My friend " + word 112if any (s in text for s in stops ): 113continue 114for chunks in self .chunkings (text ): 115with self .subTest (stops = stops ,text = text ,chunks = chunks ): 116self .assertEqual (self .run_matcher (stops ,chunks ), (text ,None )) 117 118def test_a_stop_string_cuts_exactly_there_at_every_split (self ): 119for stops in (QWEN_STOPS ,DEEPSEEK_STOPS ): 120for stop in stops : 121for word in ("Nerazim" ,"swim" ): 122text = f"My friend { word } { stop } never seen" 123for chunks in self .chunkings (text ): 124with self .subTest (stops = stops ,text = text ,chunks = chunks ): 125first = min ((text .find (s ),s )for s in stops if s in text ) 126self .assertEqual (self .run_matcher (stops ,chunks ), (text [:first [0 ]],first [1 ])) 127 128def test_the_held_back_tail_is_given_back_at_the_end (self ): 129for stops in (QWEN_STOPS ,DEEPSEEK_STOPS ): 130for text in ("Nerazim <|im" ,"Nerazim <|User" ,"Nerazim\nUser" ,"Nerazim <" ,"ends with a pipe |" ): 131with self .subTest (stops = stops ,text = text ): 132self .assertEqual (self .run_matcher (stops ,list (text )), (text ,None )) 133 134def test_a_stop_string_that_starts_like_the_word_costs_nothing_but_the_wait (self ): 135# "im_end" as a stop: "Nerazim" holds "im" until the next character says it is not the stop string 136m = StopMatcher (["im_end" ]) 137self .assertEqual (m .push ("Neraz" ),"Neraz" ) 138self .assertEqual (m .push ("im" ),"" ) 139self .assertEqual (m .held ,"im" ) 140self .assertEqual (m .flush (),"im" ) 141 142 143class ByteWise (Fixture ): 144"""The text path as the server runs it: one token per byte through the Detokenizer (a UTF-8 character split across tokens is held 145until it is whole), then the StopMatcher.""" 146 147def run_bytes (self ,stops ,text ): 148tok = ByteTokenizer () 149detok ,m ,out = Detokenizer (tok ),StopMatcher (stops ),"" 150for b in text .encode ("utf-8" ): 151out += m .push (detok .push (b )) 152if m .hit is not None : 153break 154if m .hit is None : 155out += m .flush () 156return out ,m .hit 157 158def test_every_word_comes_out_whole_byte_by_byte (self ): 159for stops in (QWEN_STOPS ,DEEPSEEK_STOPS ): 160for word in WORDS + ["Zażółć" ,"日本語の名前" ]: 161text = "Hello " + word 162if any (s in text for s in stops ): 163continue 164with self .subTest (stops = stops ,text = text ): 165self .assertEqual (self .run_bytes (stops ,text ), (text ,None )) 166 167def test_a_multibyte_stop_string_is_cut_byte_by_byte (self ): 168text = "Nerazim<|end▁of▁sentence|>not shown" 169self .assertEqual (self .run_bytes (DEEPSEEK_STOPS ,text ), ("Nerazim" ,"<|end▁of▁sentence|>" )) 170 171 172class Routes (Fixture ): 173"""The four ways out of the server (OpenAI and Anthropic, streamed and whole), with the family named and without it.""" 174 175def start (self ,script ,named ): 176"""A server for `named` (one per test and setting, reused); the engine replays `script` for the next request.""" 177if named in self .servers : 178engine = self .servers [named ] 179engine .script = self .tok .encode (script )+ [EOS ]# (a marker in the script is text the model wrote) 180self .base = self .bases [named ] 181return engine 182engine = self .servers [named ]= DsEngine (self .tok ,script ) 183engine .script = self .tok .encode (script )+ [EOS ] 184svc = Service (engine ,self .tok ,ChatTemplate (TEMPLATE ),model_name = "deepseek-v4.1-flash" ) 185if named : 186svc .model_arch = "deepseek41" 187svc .set_family ("deepseek41" ) 188httpd = serve (svc ,port = 0 ) 189self .addCleanup (httpd .server_close ) 190self .addCleanup (httpd .shutdown ) 191self .addCleanup (frontend .use_family ,None ) 192self .base = self .bases [named ]= f"http://127.0.0.1: { httpd . server_address [ 1 ] } " 193return engine 194 195def send (self ,route ,stream ,stops ): 196if route == "openai" : 197path = "/v1/chat/completions" 198body = {"model" :"m" ,"max_tokens" :200 ,"stream" :stream ,"chat_template_kwargs" : {"enable_thinking" :False }, 199"messages" : [{"role" :"user" ,"content" :"Use the name Nerazim in a sentence." }]} 200if stops : 201body ["stop" ]= stops [:4 ] 202else : 203path = "/v1/messages" 204body = {"model" :"m" ,"max_tokens" :200 ,"stream" :stream ,"thinking" : {"type" :"disabled" }, 205"messages" : [{"role" :"user" ,"content" :"Use the name Nerazim in a sentence." }]} 206if stops : 207body ["stop_sequences" ]= stops 208req = urllib .request .Request (self .base + path ,data = json .dumps (body ).encode (),headers = {"Content-Type" :"application/json" }) 209with urllib .request .urlopen (req ,timeout = 30 )as r : 210raw = r .read ().decode ("utf-8" ) 211text ,finish ,stop_seq = "" ,None ,None 212if not stream : 213d = json .loads (raw ) 214if route == "openai" : 215text ,finish = d ["choices" ][0 ]["message" ].get ("content" )or "" ,d ["choices" ][0 ]["finish_reason" ] 216else : 217text = "" .join (b .get ("text" ,"" )for b in d ["content" ]if b ["type" ]== "text" ) 218finish ,stop_seq = d ["stop_reason" ],d .get ("stop_sequence" ) 219return text ,finish ,stop_seq 220for line in raw .splitlines (): 221if not line .startswith ("data:" )or line .strip ()== "data: [DONE]" : 222continue 223d = json .loads (line [5 :]) 224if route == "openai" : 225for ch in d .get ("choices" , []): 226text += (ch .get ("delta" )or {}).get ("content" )or "" 227finish = ch .get ("finish_reason" )or finish 228elif d .get ("type" )== "content_block_delta" : 229text += d ["delta" ].get ("text" ,"" ) 230elif d .get ("type" )== "message_delta" : 231finish ,stop_seq = d ["delta" ].get ("stop_reason" ),d ["delta" ].get ("stop_sequence" ) 232return text ,finish ,stop_seq 233 234def setUp (self ): 235self .servers = {} 236self .bases = {} 237 238def every_route (self ): 239for named in (False ,True ): 240for route in ("openai" ,"anthropic" ): 241for stream in (False ,True ): 242yield named ,route ,stream 243 244def test_nerazim_and_its_kin_come_out_whole_with_no_stop_string (self ): 245for word in ("Nerazim" ,"Nerazimville and Nerazim" ,"swim" ,"Zim" ,"a|b|c|" ,"x > y" ,"the end of the text" ,"im_end" ,"<" ,"Nerazim<|im" ): 246for named ,route ,stream in self .every_route (): 247with self .subTest (word = word ,named = named ,route = route ,stream = stream ): 248self .start (word ,named ) 249text ,finish ,_ = self .send (route ,stream ,None ) 250self .assertEqual (text .strip (),word ) 251self .assertIn (finish , ("stop" ,"end_turn" )) 252 253def test_the_held_tail_is_given_back_when_the_stop_string_never_comes (self ): 254for stops in (QWEN_STOPS ,DEEPSEEK_STOPS , ["im_end" ,"|>" ]): 255for named ,route ,stream in self .every_route (): 256for word in ("My friend Nerazim" ,"Nerazim <|im" ,"Nerazim <|User" ,"ends with a pipe |" ): 257with self .subTest (stops = stops ,word = word ,named = named ,route = route ,stream = stream ): 258self .start (word ,named ) 259text ,finish ,stop_seq = self .send (route ,stream ,stops ) 260self .assertEqual (text .strip (),word ) 261self .assertIn (finish , ("stop" ,"end_turn" )) 262self .assertIsNone (stop_seq ) 263 264def test_a_stop_string_cuts_the_reply_there (self ): 265for stops in (QWEN_STOPS ,DEEPSEEK_STOPS ): 266for named ,route ,stream in self .every_route (): 267for stop in stops : 268with self .subTest (stops = stops ,stop = stop ,named = named ,route = route ,stream = stream ): 269self .start ("My friend Nerazim" + stop + "and more" ,named ) 270text ,finish ,stop_seq = self .send (route ,stream ,stops ) 271self .assertEqual (text .strip (),"My friend Nerazim" ) 272self .assertIn (finish , ("stop" ,"end_turn" ,"stop_sequence" )) 273if route == "anthropic" : 274self .assertEqual (stop_seq ,stop ) 275 276 277if __name__ == "__main__" : 278unittest .main ()