okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""STRATA_DS4_RESTORE_POINTS: where the server asks the DeepSeek engine to keep restore points (its GEN line's marks=, 2tail= and shared=), computed from the chat as the template renders it - no GPU, no engine (a fake one). From Project 3Maya's restore points (#639, mw00 / needmorevram), on Strata's shared-start pin. 4 5python -m unittest serve.test_ds4_restore_points -v 6""" 7from __future__import annotations 8 9import os 10import sys 11import unittest 12import unittest .mock 13from pathlib import Path 14 15ROOT = Path (__file__ ).resolve ().parents [1 ] 16sys .path .insert (0 ,str (ROOT )) 17sys .path .insert (0 ,str (ROOT / "tools" )) 18from serve .server import StrataEngine ,deepseek_restore_points ,restore_point_settings # noqa: E402 19from serve import frontend # noqa: E402 20from serve .frontend import ChatTemplate # noqa: E402 21from serve .server import Service ,default_model_name ,serve # noqa: E402 22from serve .test_dsv41 import TEMPLATE ,ApiBase ,DsEngine # noqa: E402 23 24ON ,TAIL = "STRATA_DS4_RESTORE_POINTS" ,"STRATA_DS4_RESTORE_TAIL" 25# one id a byte (the stand-in tokenizer): a system prompt of ~2,700 tokens 26SYSTEM = "You are a careful assistant; answer from the documents you are given. " * 40 27DOC = "" .join (f"Line { i } : the quarterly figures for region { i % 7 } rose by { i % 13 } percent.\n" for i in range (400 )) 28 29 30def lcp (a ,b )-> int : 31n = 0 32for x ,y in zip (a ,b ): 33if x != y : 34break 35n += 1 36return n 37 38 39class Pure (unittest .TestCase ): 40"""deepseek_restore_points() and the settings on ids built by hand.""" 41 42USER ,SYS = 900 ,901 43 44def ids (self ,* parts ): 45out = [] 46for p in parts : 47out += [p ]if p in (self .USER ,self .SYS )else [7 ]* p 48return out 49 50def test_last_user_turn_the_shared_start_and_the_tail (self ): 51ids = self .ids (2000 ,self .USER ,1500 ,5 ,self .USER ,3000 ) 52pts = deepseek_restore_points (ids ,self .USER ,self .SYS ,512 ) 53self .assertEqual (pts ["shared" ],2000 ) 54self .assertEqual (pts ["marks" ], [2000 + 1 + 1500 + 5 ]) 55self .assertEqual (pts ["tail" ],len (ids )- 512 ) 56 57def test_short_starts_are_left_out (self ): 58ids = self .ids (300 ,self .USER ,100 ,self .USER ,100 ) 59self .assertEqual (deepseek_restore_points (ids ,self .USER ,self .SYS ,512 ), {}) 60self .assertEqual (deepseek_restore_points (self .ids (5000 ),None ), {})# (no user token: no DeepSeek prompt) 61 62def test_a_system_message_after_the_first_user_turn_is_a_boundary_too (self ): 63ids = self .ids (1500 ,self .USER ,1500 ,self .SYS ,40 ) 64pts = deepseek_restore_points (ids ,self .USER ,self .SYS ,0 ) 65self .assertEqual (pts , {"shared" :1500 ,"marks" : [1500 + 1 + 1500 ]}) 66self .assertEqual (ids [pts ["marks" ][0 ]],self .SYS ) 67 68def test_tail_zero_and_a_tail_inside_the_last_turn_only (self ): 69ids = self .ids (1200 ,self .USER ,4000 ) 70self .assertNotIn ("tail" ,deepseek_restore_points (ids ,self .USER ,self .SYS ,0 )) 71self .assertEqual (deepseek_restore_points (ids ,self .USER ,self .SYS ,300 )["tail" ],len (ids )- 300 ) 72short = self .ids (1200 ,self .USER ,100 )# (the last turn shorter than the tail: the boundary alone) 73self .assertNotIn ("tail" ,deepseek_restore_points (short ,self .USER ,self .SYS ,512 )) 74 75def test_settings (self ): 76self .assertEqual (restore_point_settings ({}), (True ,512 ))# (on by default: 4) 77self .assertEqual (restore_point_settings ({ON :"0" }), (False ,512 )) 78self .assertEqual (restore_point_settings ({ON :"4" }), (True ,512 )) 79self .assertEqual (restore_point_settings ({ON :"yes" ,TAIL :"x" }), (True ,512 ))# (not a number: the default) 80self .assertEqual (restore_point_settings ({ON :"8" ,TAIL :"0" }), (True ,0 )) 81self .assertEqual (restore_point_settings ({ON :"8" ,TAIL :"2000" }), (True ,2000 )) 82 83def test_the_engine_line (self ): 84s = {"_restore" : {"marks" : [3000 ,4000 ],"tail" :5000 ,"shared" :2000 }} 85self .assertEqual (StrataEngine .restore_keys (s )," marks=3000,4000 tail=5000 shared=2000" ) 86self .assertEqual (StrataEngine .restore_keys ({}),"" ) 87self .assertEqual (StrataEngine .restore_keys ({"_restore" : {"marks" : [0 ,- 1 ,True ],"shared" :0 }}),"" ) 88self .assertIn ("marks=3000,4000" ,StrataEngine .sampling_keys ({** s ,"temperature" :0.7 }).split ()) 89self .assertEqual (StrataEngine .sampling_keys ({"temperature" :0.7 }), 90StrataEngine .sampling_keys ({"temperature" :0.7 ,"_restore" : {}})) 91 92 93class Api (ApiBase ): 94"""The same through the server, with the template's own tokens.""" 95 96def start (self ,script ): 97engine = DsEngine (self .tok ,script ,max_context = 1 << 20 )# (the documents here are tens of thousands of tokens) 98svc = Service (engine ,self .tok ,ChatTemplate (TEMPLATE ),model_name = default_model_name ({"arch" :"deepseek41" })) 99svc .model_arch = "deepseek41" 100svc .set_family ("deepseek41" ) 101httpd = serve (svc ,port = 0 ) 102self .addCleanup (httpd .server_close ) 103self .addCleanup (httpd .shutdown ) 104self .addCleanup (frontend .use_family ,None ) 105self .engine ,self .svc = engine ,svc 106self .base = f"http://127.0.0.1: { httpd . server_address [ 1 ] } " 107return engine 108 109def chat_body (self ,last = "And how did region 3 do in the last quarter?" ,system = SYSTEM ): 110return {"messages" : [{"role" :"system" ,"content" :system }, 111 {"role" :"user" ,"content" :"Here are the figures.\n" + DOC }, 112 {"role" :"assistant" ,"content" :"I have read them." }, 113 {"role" :"user" ,"content" :last }],"max_tokens" :40 } 114 115def run_request (self ,body ,env = None ): 116env = env or {} 117with unittest .mock .patch .dict (os .environ ,env ): 118for k in (ON ,TAIL ): 119if k not in env : 120os .environ .pop (k ,None ) 121self .assertEqual (self .post ("/v1/chat/completions" ,body )[0 ],200 ) 122return self .engine .last_prompt ,self .engine .last_sampling 123 124def user_id (self ): 125return self .svc .deepseek_turn_ids ()[0 ] 126 127def test_marks_at_the_last_user_turn_and_the_pin_is_the_shared_start (self ): 128self .start ("ok" ) 129ids ,s = self .run_request (self .chat_body ()) 130user = self .user_id () 131boundary = len (ids )- 1 - ids [::- 1 ].index (user ) 132self .assertEqual (s ["_restore" ]["marks" ], [boundary ]) 133# the system prompt is already the request's shared start (pin=N): shared= is not asked twice 134self .assertNotIn ("shared" ,s ["_restore" ]) 135self .assertEqual (s ["strata_prefix" ]["tokens" ],ids .index (user )) 136keys = StrataEngine .sampling_keys (s ).split () 137self .assertIn (f"marks= { boundary } " ,keys ) 138self .assertIn (f"pin= { ids . index ( user ) } " ,keys ) 139self .assertFalse ([k for k in keys if k .startswith ("shared=" )]) 140# the last message edited: the prompt agrees with this one up to the boundary, and leaves it before the end 141ids2 ,_ = self .run_request (self .chat_body ("And region 5, over the whole year?" )) 142self .assertGreaterEqual (lcp (ids ,ids2 ),boundary ) 143self .assertLess (lcp (ids ,ids2 ),len (ids )- 1 ) 144 145def test_shared_is_asked_when_the_pin_is_switched_off (self ): 146self .start ("ok" ) 147with unittest .mock .patch .dict (os .environ , {"STRATA_DS4_AUTO_PIN" :"0" }): 148ids ,s = self .run_request (self .chat_body ()) 149self .assertNotIn ("strata_prefix" ,s ) 150self .assertEqual (s ["_restore" ]["shared" ],ids .index (self .user_id ())) 151self .assertIn (f"shared= { ids . index ( self . user_id ()) } " ,StrataEngine .sampling_keys (s ).split ()) 152 153def test_tail_point_for_a_long_last_message (self ): 154self .start ("ok" ) 155ids ,s = self .run_request ({"messages" : [{"role" :"user" ,"content" :DOC + "\nWhich region rose most?" }], 156"max_tokens" :40 }) 157self .assertEqual (s ["_restore" ], {"tail" :len (ids )- 512 }) 158_ ,s = self .run_request ({"messages" : [{"role" :"user" ,"content" :DOC }],"max_tokens" :40 }, {TAIL :"100" }) 159self .assertEqual (s ["_restore" ], {"tail" :len (self .engine .last_prompt )- 100 }) 160self .assertIn (f"tail= { len ( self . engine . last_prompt ) - 100 } " ,StrataEngine .sampling_keys (s ).split ()) 161 162def test_off_with_0_and_never_the_clients_own (self ): 163self .start ("ok" ) 164_ ,on = self .run_request (self .chat_body ())# (on by default) 165self .assertIn ("_restore" ,on ) 166_ ,off = self .run_request (self .chat_body (), {ON :"0" }) 167self .assertNotIn ("_restore" ,off ) 168for k in ("marks=" ,"shared=" ,"tail=" ): 169self .assertNotIn (k ,StrataEngine .sampling_keys (off )) 170# a client's own `_restore` never reaches the engine 171_ ,forged = self .run_request ({** self .chat_body (),"_restore" : {"marks" : [5 ],"shared" :7 }}, {ON :"0" }) 172self .assertNotIn ("_restore" ,forged ) 173_ ,forged = self .run_request ({** self .chat_body (),"_restore" : {"marks" : [5 ],"shared" :7 }}, {ON :"4" }) 174self .assertNotEqual (forged ["_restore" ].get ("marks" ), [5 ]) 175 176def test_short_prompts_get_none (self ): 177self .start ("ok" ) 178_ ,s = self .run_request ({"messages" : [{"role" :"user" ,"content" :"hi" }],"max_tokens" :40 }) 179self .assertNotIn ("_restore" ,s ) 180 181 182if __name__ == "__main__" : 183unittest .main ()