okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1"""Logprobs with "parallel" (batch slots): python -m unittest serve.test_logprobs_parallel. 2 3The fake engine of serve/test_parallel.py behind the real StrataEngine and Service, writing an LP line after each 4T line when the GEN / BGEN line asks for logprobs. A typed decision (max_tokens 1) is read on the control lines 5(an admission: BGEN, one T, DONE, BADM 0) and gets its logprobs; longer replies are refused with a 400, since the 6slot's BT lines carry none. 7""" 8import json 9import threading 10import unittest 11import urllib .error 12import urllib .request 13from unittest import mock 14 15import serve .test_parallel as tp 16 17# LP after each T when asked: the token's log-probability is -(prompt length) / 1000 (so two requests can be told 18# apart) and "A" (65) is its one alternative at -1.5 -- or the named ids themselves, at -1, when the line carries 19# `allowed=` (the engine's own branch: it prints those and no top-K) 20_T_LINE = ' print(f"T {t}", flush=True)\n' 21assert tp .FAKE_BATCH .count (_T_LINE )== 1 22FAKE_LP = tp .FAKE_BATCH .replace (_T_LINE ,_T_LINE + ( 23' if " logprobs=" in line:\n' 24' al = [x[8:] for x in line.split() if x.startswith("allowed=")]\n' 25' cs = (" " + " ".join(i + ":-1.000000" for i in al[0].split(","))) if al else " 65:-1.500000"\n' 26' print(f"LP {-len(ids) / 1000:.6f}" + cs, flush=True)\n' )) 27 28 29class LogprobsWithBatchSlots (unittest .TestCase ): 30start ,tearDown ,get = tp .ParallelService .start ,tp .ParallelService .tearDown ,tp .ParallelService .get 31 32def start_lp (self ,fake = FAKE_LP ,slots = 2 ): 33with mock .patch .object (tp ,"FAKE_BATCH" ,fake ): 34self .start (slots ) 35 36def chat (self ,text ,max_tokens = 1 ,logprobs = True ,allowed = None ): 37body = {"messages" : [{"role" :"user" ,"content" :text }],"max_tokens" :max_tokens , 38"reasoning_effort" :"none" } 39if logprobs : 40body |= {"logprobs" :True ,"top_logprobs" :1 } 41if allowed : 42body ["allowed_token_ids" ]= allowed 43req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = json .dumps (body ).encode (), 44headers = {"Content-Type" :"application/json" }) 45with urllib .request .urlopen (req ,timeout = 60 )as r : 46return json .loads (r .read ().decode ()) 47 48@staticmethod 49def entries (reply ): 50return ((reply ["choices" ][0 ].get ("logprobs" )or {}).get ("content" ))or [] 51 52def test_a_decision_gets_its_logprobs (self ): 53self .start_lp () 54r = self .chat ("Is it A or B?" ) 55self .assertEqual (r ["choices" ][0 ]["message" ]["content" ],"o" ) 56e = self .entries (r ) 57self .assertEqual (len (e ),1 ) 58self .assertEqual (e [0 ]["token" ],"o" ) 59self .assertLess (e [0 ]["logprob" ],0 ) 60self .assertEqual (e [0 ]["top_logprobs" ], [{"token" :"A" ,"logprob" :- 1.5 ,"bytes" : [65 ]}]) 61self .assertTrue (any (x .startswith ("BGEN" )for x in self .log .read_text ().splitlines ()))# an admission 62 63def test_the_named_ids_reach_the_slot_and_are_what_is_reported (self ): 64# allowed_token_ids travels in the same BGEN keys as logprobs, so the engine's own branch answers with 65# exactly those ids: the admission path carries the whole feature, not just the top-K one 66self .start_lp () 67e = self .entries (self .chat ("Is it A or B?" ,allowed = [65 ])) 68self .assertEqual (len (e ),1 ) 69self .assertEqual ([x ["token" ]for x in e [0 ]["top_logprobs" ]], ["A" ]) 70self .assertEqual (e [0 ]["top_logprobs" ][0 ]["logprob" ],0 )# the whole distribution: just that id 71 72def test_two_at_once_each_get_their_own (self ): 73self .start_lp () 74short ,long_ = "A or B?" ,"A or B? " + "x" * 300 75alone = {t :self .entries (self .chat (t ))[0 ]["logprob" ]for t in (short ,long_ )} 76self .assertNotEqual (alone [short ],alone [long_ ]) 77for _ in range (5 ): 78got ,errs = {}, [] 79 80def run (t ): 81try : 82got [t ]= self .entries (self .chat (t ))[0 ]["logprob" ] 83except Exception as exc :# noqa: BLE001 - reported below 84errs .append (repr (exc )) 85th = [threading .Thread (target = run ,args = (t ,))for t in (short ,long_ ,short ,long_ )] 86for x in th : 87x .start () 88for x in th : 89x .join (60 ) 90self .assertEqual (errs , []) 91self .assertEqual (got ,alone ) 92 93def test_not_asked_nothing_changes (self ): 94self .start_lp () 95r = self .chat ("Is it A or B?" ,logprobs = False ) 96self .assertEqual (r ["choices" ][0 ]["message" ]["content" ],"o" ) 97self .assertIsNone (r ["choices" ][0 ].get ("logprobs" )) 98 99def test_longer_replies_are_refused_with_batch_slots (self ): 100self .start_lp () 101with self .assertRaises (urllib .error .HTTPError )as cm : 102self .chat ("Is it A or B?" ,max_tokens = 8 ) 103self .assertEqual (cm .exception .code ,400 ) 104self .assertIn ("max_tokens 1" ,cm .exception .read ().decode ()) 105# the server is still serving, and a reply that does not ask is untouched 106self .assertEqual (self .chat ("still serving?" ,max_tokens = 16 ,logprobs = False )["choices" ][0 ]["message" ]["content" ], 107"ok, done." ) 108 109def test_an_engine_without_lp_lines (self ): 110self .start_lp (fake = tp .FAKE_BATCH )# an older engine: the key is ignored, no LP line at all 111r = self .chat ("Is it A or B?" ) 112self .assertEqual (r ["choices" ][0 ]["message" ]["content" ],"o" ) 113self .assertEqual (self .entries (r ), []) 114 115 116if __name__ == "__main__" : 117unittest .main ()