okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a89b97898
main
1import json 2from pathlib import Path 3from types import SimpleNamespace 4import unittest 5import urllib .error 6import urllib .request 7 8from serve .logit_bias import engine_key ,normalize ,validate_request 9from serve .server import ByteTokenizer ,MockEngine ,Service ,StrataEngine ,serve 10from serve .frontend import ChatTemplate 11 12 13class LogitBias (unittest .TestCase ): 14def test_forms_and_transport (self ): 15self .assertEqual (normalize ({"7" :- 100 ,"9" :2.5 },10 ),normalize ([[7 ,False ], [9 ,2.5 ]],10 )) 16self .assertEqual (engine_key ([[9 ,2.5 ], [7 ,False ]])," logit_bias=7:-100,9:2.5" ) 17self .assertEqual (StrataEngine .sampling_keys ({"logit_bias" : {"7" :- 100 }})," logit_bias=7:-100" ) 18for value in [None , {}, []]: 19self .assertEqual (engine_key (value ),"" ) 20 21def test_invalid (self ): 22bad = [True ,1 ,"x" , [1 ], [[1 ]], [[1 ,0 ,2 ]], {"-1" :0 }, {"1.0" :0 }, {"10" :0 }, 23 {"1" :False }, [[1 ,True ]], [[1.0 ,0 ]], [[True ,0 ]], [[1 ,0 ], ["1" ,2 ]], 24 {"1" :101 }, {"1" :- 101 }, {"1" :float ('nan' )}, {"1" :float ('inf' )}, {"1" :10 ** 1000 }] 25for value in bad : 26with self .subTest (value = str (value )[:50 ]),self .assertRaises (ValueError ): 27normalize (value ,10 ) 28with self .assertRaises (ValueError ): 29normalize ({str (i ):- 100 for i in range (10 )},10 ) 30 31def test_large_list (self ): 32entries = [[i ,False ]for i in range (103215 )] 33self .assertEqual (len (normalize (entries ,248320 )),103215 ) 34self .assertEqual (engine_key (entries ).count (':-100' ),103215 ) 35 36def test_capability_and_batch (self ): 37for engine in [SimpleNamespace (info = {})]: 38with self .assertRaises (ValueError ): 39validate_request ({'logit_bias' : {'1' :- 100 }},engine ,10 ) 40self .assertEqual (validate_request ({},engine ,10 ), {}) 41# --batch: a slot keeps its request's own bias (Verifier::set_slot_logit_bias) 42self .assertEqual (validate_request ({'logit_bias' : {'1' :- 100 }},SimpleNamespace (info = {'logit_bias' :1 },batch = 2 ),10 ), {1 :- 100 }) 43self .assertEqual (validate_request ({'logit_bias' : {'1' :- 100 }},SimpleNamespace (info = {'logit_bias' :1 }),10 ), {1 :- 100 }) 44 45def test_http_rejects_before_stream (self ): 46tok = ByteTokenizer () 47engine = MockEngine (tok ,'ok' ,max_context = 4096 ) 48service = Service (engine ,tok ,ChatTemplate (Path (__file__ ).parent / 'chat_template.jinja' )) 49httpd = serve (service ,port = 0 ) 50try : 51for bias in [True , {'1' :- 100 }, [[1 ,True ]]]: 52data = json .dumps ({'messages' : [{'role' :'user' ,'content' :'hi' }],'max_tokens' :2 , 53'stream' :True ,'logit_bias' :bias }).encode () 54req = urllib .request .Request (f'http://127.0.0.1: { httpd . server_address [ 1 ] } /v1/chat/completions' , 55data = data ,headers = {'Content-Type' :'application/json' }) 56with self .assertRaises (urllib .error .HTTPError )as caught : 57urllib .request .urlopen (req ,timeout = 10 ) 58with caught .exception as response : 59self .assertEqual (response .code ,400 ) 60self .assertIn ('logit_bias' ,json .loads (response .read ())['error' ]['message' ]) 61finally : 62httpd .shutdown () 63httpd .server_close () 64 65 66class LogitBiasCache (unittest .TestCase ): 67"""A long list is normalized once; the cache must not change what a call returns or raises.""" 68 69def setUp (self ): 70from serve import logit_bias 71logit_bias ._cache .clear () 72logit_bias ._last = None 73 74def test_same_answers_as_the_plain_function (self ): 75from serve .logit_bias import _normalize 76forms = [{str (i ):- 100 for i in range (200 )}, 77 [[i ,False ]for i in range (200 )], 78 {str (i ): (i % 7 )- 3.5 for i in range (200 )}, 79 [[str (i ),2 ]for i in range (200 )]] 80for vocab in (None ,1000 ): 81for form in forms : 82want = _normalize (form ,vocab ) 83for _ in range (3 ):# the first call fills the cache, the others read it 84self .assertEqual (normalize (form ,vocab ),want ) 85self .assertEqual (normalize (json .loads (json .dumps (form )),vocab ),want )# an equal list, another object 86for form in forms : 87ref = " logit_bias=" + "," .join (f" { i } : { b :g } " for i ,b in sorted (_normalize (form ).items ())) 88self .assertEqual (engine_key (form ),ref ) 89self .assertEqual (engine_key (form ),ref ) 90 91def test_false_is_not_zero (self ): 92ban = [[i ,False ]for i in range (100 )] 93zero = [[i ,0 ]for i in range (100 )] 94self .assertTrue (ban == zero )# Python calls them equal, so an == key would mix them up 95for first ,second in [(ban ,zero ), (zero ,ban )]: 96self .setUp () 97self .assertEqual (set (normalize (first ).values ()), {- 100.0 if first is ban else 0.0 }) 98self .assertEqual (set (normalize (second ).values ()), {- 100.0 if second is ban else 0.0 }) 99 100def test_a_bad_list_is_never_stored (self ): 101good = {str (i ):- 1 for i in range (100 )} 102normalize (good ,1000 ) 103for bad in [{** good ,"5" :True }, {** good ,"5" :101 }, {** good ,"5" :float ("nan" )}, {** good ,"5" :"x" }]: 104for _ in range (2 ): 105with self .assertRaises (ValueError ): 106normalize (bad ,1000 ) 107pairs = [[i ,1 ]for i in range (100 )] 108normalize (pairs ) 109with self .assertRaises (ValueError ):# True == 1, but a bool is not a bias 110normalize ([[i ,1 ]for i in range (99 )]+ [[99 ,True ]]) 111with self .assertRaises (ValueError ):# a duplicate ID 112normalize ([[i ,1 ]for i in range (100 )]+ [[0 ,1 ]]) 113 114def test_vocabulary_size_is_part_of_the_key (self ): 115ids = {str (i ):- 1 for i in range (100 )} 116self .assertEqual (len (normalize (ids ,1000 )),100 ) 117with self .assertRaises (ValueError ): 118normalize (ids ,50 ) 119self .assertEqual (len (normalize (ids )),100 ) 120with self .assertRaises (ValueError ): 121normalize (ids ,50 ) 122 123def test_the_result_is_a_copy (self ): 124ids = {str (i ):- 1 for i in range (100 )} 125first = normalize (ids ) 126first [0 ]= 99.0 127self .assertEqual (normalize (ids )[0 ],- 1.0 ) 128self .assertEqual (validate_request ({"logit_bias" :ids },SimpleNamespace (info = {"logit_bias" :1 }),1000 )[0 ],- 1.0 ) 129 130def test_an_equal_list_in_a_later_request_is_a_hit (self ): 131from serve import logit_bias 132a = {str (i ):- 100 for i in range (100 )} 133b = json .loads (json .dumps (a )) 134self .assertIsNot (a ,b ) 135key_a = engine_key (a ) 136logit_bias ._last = None # a later request: the previous object is gone 137key_b = engine_key (b ) 138self .assertIs (key_a ,key_b )# one entry, one key string 139self .assertEqual (len (logit_bias ._cache ),1 ) 140 141def test_the_cache_is_bounded (self ): 142from serve import logit_bias 143for n in range (logit_bias ._CACHE_MAX + 3 ): 144normalize ({str (i ):- (n + 1 )for i in range (100 )}) 145self .assertEqual (len (logit_bias ._cache ),logit_bias ._CACHE_MAX ) 146 147class ConfigLogitBias (unittest .TestCase ): 148def test_config_default_bias_is_normalized (self ): 149from serve .server import sampling_defaults_from_config 150self .assertEqual (sampling_defaults_from_config ({"sampling" : {"logit_bias" : {"9008" :- 100 ,25414 :2 }}})["logit_bias" ], {9008 :- 100.0 ,25414 :2.0 }) 151 152def test_bad_config_bias_refuses_to_start (self ): 153from serve .server import sampling_defaults_from_config 154with self .assertRaises (SystemExit ): 155sampling_defaults_from_config ({"sampling" : {"logit_bias" : {"x" :- 100 }}})