okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1"""serve/test_prompt_encoder.py - #567's incremental prompt encoding with #537's plain spans: every prompt's ids 2are those of a full encode, and a turn reuses the previous one's. 3 4python -m unittest serve.test_prompt_encoder -v 5""" 6from __future__import annotations 7 8import random 9import re 10import sys 11import unittest 12from pathlib import Path 13 14ROOT = Path (__file__ ).resolve ().parents [1 ] 15sys .path .insert (0 ,str (ROOT )) 16sys .path .insert (0 ,str (ROOT / "tools" )) 17from serve .frontend import ChatTemplate # noqa: E402 18from serve .server import ByteTokenizer ,MockEngine ,Service # noqa: E402 19from strata_tokenizer import PromptEncoder ,plain_agree_until # noqa: E402 20 21 22class ThinkTokenizer (ByteTokenizer ): 23"""ByteTokenizer whose <think> / </think> are specials matched even without parse_special (type 4), as in the 24Qwen vocabulary: the case #537's plain spans exist for.""" 25SPECIALS = ByteTokenizer .SPECIALS + ["<think>" ,"</think>" ] 26ALWAYS = ("<think>" ,"</think>" ) 27 28 29PIECES = ["<|im_start|>user\n" ,"<|im_end|>\n" ,"<think>" ,"</think>" ,"hello " ,"é你 " ,"<|im_sta" ,"x" * 7 , 30"<|im_start|>assistant\n" ,"</thi" ,"\n\n" ,"<|endoftext|>" ,"<|vision_start|>" ,"<|image_pad|>" ] 31 32 33def spans_of (text ,rng ): 34"""Random plain spans over the specials' texts (<think>, </think>, <|im_start|>, ...), as unmark_think_literals 35marks the ones quoted inside a message.""" 36matches = re .finditer ("|" .join (map (re .escape ,ThinkTokenizer .SPECIALS )),text ) 37return tuple ((m .start (),m .end ())for m in matches if rng .random ()< 0.5 )# finditer: left to right, no overlap 38 39 40class Units (unittest .TestCase ): 41def test_plain_agree_until (self ): 42self .assertEqual (plain_agree_until ((), (),50 ),50 ) 43self .assertEqual (plain_agree_until (((5 ,13 ),), ((5 ,13 ),),50 ),50 ) 44self .assertEqual (plain_agree_until (((5 ,13 ),), (),50 ),5 ) 45self .assertEqual (plain_agree_until (((5 ,13 ),), ((5 ,9 ),),50 ),9 ) 46self .assertEqual (plain_agree_until (((60 ,70 ),), (),50 ),50 )# beyond the shared text: no matter 47self .assertEqual (plain_agree_until (((5 ,13 ), (20 ,28 )), ((5 ,13 ),),50 ),20 ) 48 49def test_same_ids_as_a_full_encode (self ): 50tok = ThinkTokenizer () 51rng = random .Random (7 ) 52for conv in range (300 ): 53enc = PromptEncoder (tok ) 54text ,plain = "" , () 55for turn in range (8 ): 56text += "" .join (rng .choice (PIECES )for _ in range (rng .randint (1 ,12 ))) 57if rng .random ()< 0.6 : 58plain = spans_of (text ,rng )# the spans may change in the shared part too 59with self .subTest (conv = conv ,turn = turn ): 60self .assertEqual (enc .encode (text ,plain ),tok .encode (text ,True ,plain )) 61if rng .random ()< 0.2 and len (text )> 10 :# an edit: a client re-rendering its history 62cut = rng .randrange (len (text )) 63text = text [:cut ] 64plain = tuple ((a ,b )for a ,b in plain if b <= cut ) 65 66def test_a_turn_reuses_the_previous_one (self ): 67tok = ThinkTokenizer () 68enc = PromptEncoder (tok ) 69# as a chat turn: the earlier prompt goes on past its last special (the answer being written), and the 70# next one shares it up to there - the resume point needs max_special_len characters after it 71base = "<|im_start|>user\n" + "quoted </think> here " * 200 + "<|im_end|>\n<|im_start|>assistant\nan answer" 72plain = tuple ((i ,i + 8 )for i in range (len (base ))if base .startswith ("</think>" ,i )) 73enc .encode (base ,plain ) 74more = base + " that goes on<|im_end|>\n<|im_start|>user\nnext<|im_end|>\n" 75self .assertEqual (enc .encode (more ,plain ),tok .encode (more ,True ,plain )) 76self .assertGreater (enc .last_reused ,len (base )// 2 ) 77# the same text with the quoted </think> no longer plain: nothing before it may be reused past its start 78self .assertEqual (enc .encode (more , ()),tok .encode (more ,True , ())) 79self .assertLessEqual (enc .last_reused ,plain [0 ][0 ]) 80 81 82class Served (unittest .TestCase ): 83def test_quoted_think_across_turns (self ): 84tok = ThinkTokenizer () 85template = ChatTemplate (ROOT / "serve/chat_template.jinja" ) 86svc = Service (MockEngine (tok ,"</think>\n\nok" ,max_context = 1 << 20 ),tok ,template ) 87full = Service (MockEngine (tok ,"</think>\n\nok" ,max_context = 1 << 20 ),tok ,template ) 88full .prompts = None # the reference: a full encode every time 89self .assertIsNotNone (svc .prompts ) 90msgs = [{"role" :"system" ,"content" :"Explain tags." }] 91for turn in range (5 ): 92msgs .append ({"role" :"user" ,"content" :f"turn { turn } : what does </think> mean? <think> too " * 3 }) 93got ,want = svc .encode_prompt (msgs ,None , {}),full .encode_prompt (msgs ,None , {}) 94self .assertEqual (got ,want ) 95if turn : 96self .assertGreater (svc .prompts .last_reused ,0 ) 97msgs .append ({"role" :"assistant" ,"content" :"It closes the reasoning: </think> is a marker." }) 98 99def service (self ,max_context = 1 << 22 ): 100tok = ByteTokenizer () 101return Service (MockEngine (tok ,"ok" ,max_context = max_context ),tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 102 103def test_another_conversation_does_not_evict_the_first (self ): 104"""A subagent beside the main conversation: every rendered prompt starts with the template's header, which 105must not make the second client's prompt a continuation of the first's entry.""" 106svc = self .service () 107turn2 = [{"role" :"user" ,"content" :"a long question " * 500 }, {"role" :"assistant" ,"content" :"answer" }, 108 {"role" :"user" ,"content" :"next" }] 109svc .encode_prompt (turn2 ,None , {}) 110svc .encode_prompt ([{"role" :"user" ,"content" :"one unrelated prompt " * 300 }],None , {}) 111self .assertEqual (len (svc .prompts .entries ),2 ) 112turn3 = turn2 + [{"role" :"assistant" ,"content" :"x" }, {"role" :"user" ,"content" :"more" }] 113svc .encode_prompt (turn3 ,None , {}) 114self .assertGreater (svc .prompts .last_reused ,len (turn2 [0 ]["content" ])) 115self .assertEqual (len (svc .prompts .entries ),2 )# turn 3 replaced turn 2, the other one stayed 116 117def test_a_refused_prompt_is_not_kept (self ): 118svc = self .service (max_context = 4096 ) 119svc .fit_max_tokens = False # the strict mode refuses an over-long max_tokens (the default now shortens it) 120msgs = [{"role" :"user" ,"content" :"kept " * 20 }] 121svc .prepare (msgs ,None , {},16 ) 122refused = msgs + [{"role" :"assistant" ,"content" :"a" }, {"role" :"user" ,"content" :"more " * 20 }] 123full = self .service (max_context = 4096 ) 124full .prompts = None 125refused_ids = full .encode_prompt (refused ,None , {}) 126with self .assertRaisesRegex (ValueError ,"exceeds the context" ): 127svc .prepare (refused ,None , {},1 << 20 ) 128self .assertNotIn (refused_ids , [e [2 ]for e in svc .prompts .entries ]) 129self .assertNotIn (full .render_prompt (refused ,None , {}), [e [0 ]for e in svc .prompts .entries ]) 130 131def test_random_messages_equal_a_full_encode (self ): 132"""Messages quoting control-token texts and <think> tags at random, growing, edited and cut back between 133requests: the incremental encoder's ids are the full encode's, 2400 prompts.""" 134tok = ThinkTokenizer () 135template = ChatTemplate (ROOT / "serve/chat_template.jinja" ) 136svc = Service (MockEngine (tok ,"ok" ,max_context = 1 << 20 ),tok ,template ) 137full = Service (MockEngine (tok ,"ok" ,max_context = 1 << 20 ),tok ,template ) 138full .prompts = None 139rng = random .Random (567 ) 140quoted = ThinkTokenizer .SPECIALS + ["<|im_sta" ,"</thi" ] 141words = ["hello " ,"é你 " ,"x" * 9 ,"\n" ,"tool " ] 142 143def text (): 144return "" .join (rng .choice (quoted if rng .random ()< 0.4 else words )for _ in range (rng .randint (1 ,10 ))) 145 146reused = 0 147for conv in range (300 ): 148msgs = [{"role" :"system" ,"content" :text ()}] 149for turn in range (8 ): 150msgs .append ({"role" :"user" ,"content" :text ()}) 151if rng .random ()< 0.15 :# an earlier turn edited by the client 152msgs [rng .randrange (len (msgs ))]["content" ]= text () 153if rng .random ()< 0.1 and len (msgs )> 2 :# a shorter conversation 154msgs = msgs [:rng .randrange (1 ,len (msgs ))]+ msgs [- 1 :] 155with self .subTest (conv = conv ,turn = turn ): 156self .assertEqual (svc .encode_prompt (msgs ,None , {}),full .encode_prompt (msgs ,None , {})) 157reused += svc .prompts .last_reused > 0 158msgs .append ({"role" :"assistant" ,"content" :text ()}) 159self .assertGreater (reused ,1000 ) 160 161 162if __name__ == "__main__" : 163unittest .main ()