okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1"""OpenAI logprobs on /v1/chat/completions, from the engine's LP lines: python -m unittest serve.test_logprobs. 2 3The engine (src/program/generate.cpp) writes an `LP <logprob> [id:logprob ...]` line right after 4each `T <id>` when the request carries `logprobs=K`; this is the server half that turns those 5lines into OpenAI's logprobs, and the parts that are easy to get wrong: 6 7- `allowed_token_ids`: only the named ids, renormalised over them (vLLM's semantics). 8- `response_format: json_schema` rewrites the content, so the tokens no longer spell what is 9returned; the entries are re-aligned or dropped, never returned wrong. 10""" 11from __future__import annotations 12 13import json 14import math 15import queue 16import threading 17import unittest 18import urllib .request 19from pathlib import Path 20from types import SimpleNamespace 21 22from serve .frontend import ChatTemplate 23from serve .server import (ByteTokenizer ,LogprobEntries ,LPLines ,MockEngine ,Service ,StrataEngine ,batch_slots_on , 24logprob_span ,serve ,top_logprobs ,allowed_ids ) 25 26ROOT = Path (__file__ ).resolve ().parent .parent 27TEMPLATE = ChatTemplate (ROOT / "serve" / "chat_template.jinja" ) 28 29 30class Tokenizer (ByteTokenizer ): 31def token_bytes (self ,token ): 32return self .SPECIALS [token - 256 ].encode ()if token >= 256 else bytes ([token ]) 33 34 35class ThinkTokenizer (Tokenizer ): 36# two extra special tokens that decode as the thinking marks; ALWAYS so the byte-level 37# encode() maps them wherever they appear ("" would loop forever in startswith, so they 38# are real strings, like the engine's own think tokens are) 39SPECIALS = ByteTokenizer .SPECIALS + ["<think>" ,"</think>" ] 40ALWAYS = ("<think>" ,"</think>" ) 41 42 43class LpEngine (MockEngine ): 44"""MockEngine with the LP line of each token on lp_lines before the token is yielded, as the 45engine leaves it; token i has the log-probability -(i + 1) / 100 and four named alternatives.""" 46 47def __init__ (self ,tok ,script ,lines = True ): 48super ().__init__ (tok ,script ,max_context = 16384 ) 49self .with_lines ,self .sampling = lines ,None 50 51def line (self ,i ,t ): 52"""The LP line of token t, the i-th of the reply: the same four ids whatever was asked.""" 53return (f"LP { - ( i + 1 ) / 100 :.6f } 65:-0.500000 72:-1.250000 " 54f"88:-3.000000 91:-4.200000\n" ) 55 56def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 57self .sampling ,self .lp_lines = dict (sampling or {}),LPLines (cancel ) 58for i ,t in enumerate (super ().generate (ids ,max_new ,sampling ,cancel ,embeddings )): 59if self .with_lines : 60self .lp_lines .append ((t ,self .line (i ,t ))) 61yield t 62 63 64class NamedEngine (LpEngine ): 65"""LpEngine that prints the request's own `allowed_token_ids`, as the engine's emit_lp_line does: 66`LP <logprob> <named id>:<logprob> ...`, the chosen id left out (it is on the head).""" 67 68def line (self ,i ,t ): 69named = [int (x )for x in (self .sampling or {}).get ("allowed_token_ids" )or []if int (x )!= t ] 70alts = "" .join (f" { x } : { - 0.700000 - 0.010000 * j :.6f } " for j ,x in enumerate (named )) 71return f"LP { - ( i + 1 ) / 100 :.6f } { alts } \n" 72 73 74class NextEngine (LpEngine ): 75"""LpEngine for two requests: the second one stops after its first token (its LP line is in lp_lines) 76until the first request's reply has been read.""" 77 78def __init__ (self ,tok ,scripts ,first_out ): 79super ().__init__ (tok ,scripts ) 80self .first_out ,self .calls = first_out ,0 81self .first_in ,self .first_generated ,self .second_started = (threading .Event (),threading .Event (), 82threading .Event ()) 83 84def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 85self .calls += 1 86mine = self .calls 87if mine == 1 : 88self .first_in .set () 89try : 90for i ,t in enumerate (super ().generate (ids ,max_new ,sampling ,cancel ,embeddings )): 91if mine == 2 and i == 0 : 92self .second_started .set () 93self .first_out .wait (10 ) 94yield t 95finally : 96if mine == 1 : 97self .first_generated .set () 98 99 100class HandOver : 101"""Service.fifo that, once the first request has generated, lets its turn go and then waits until the 102next request is generating before the first one goes on.""" 103 104def __init__ (self ,engine ): 105self .lock ,self .engine ,self .waited = threading .Lock (),engine ,False 106 107def acquire (self ,* a ,** k ): 108return self .lock .acquire (* a ,** k ) 109 110def release (self ): 111self .lock .release () 112if self .engine .first_generated .is_set ()and not self .waited : 113self .waited = True 114self .engine .second_started .wait (10 ) 115 116def locked (self ): 117return self .lock .locked () 118 119def __enter__ (self ): 120self .acquire () 121return self 122 123def __exit__ (self ,* exc ): 124self .release () 125 126 127SCHEMA = {"type" :"json_schema" ,"json_schema" : {"name" :"a" ,"strict" :True ,"schema" : { 128"type" :"object" ,"properties" : {"rent" : {"type" :"string" },"quote" : {"type" :"string" }}, 129"required" : ["rent" ,"quote" ],"additionalProperties" :False }}} 130 131 132class Keys (unittest .TestCase ): 133"""What the request asks for, and what reaches the engine line.""" 134 135def test_what_the_request_asks (self ): 136self .assertEqual (top_logprobs ({"logprobs" :True }),0 ) 137self .assertEqual (top_logprobs ({"logprobs" :True ,"top_logprobs" :3 }),3 ) 138self .assertEqual (top_logprobs ({"logprobs" :True ,"top_logprobs" :50 }),20 ) 139self .assertEqual (top_logprobs ({"logprobs" :2 }),2 )# the legacy completions form 140for req in ({}, {"logprobs" :False }, {"logprobs" :None }, {"top_logprobs" :3 }): 141self .assertIsNone (top_logprobs (req )) 142 143def test_allowed_ids (self ): 144self .assertEqual (allowed_ids ({"allowed_token_ids" : [1 ,2 ,3 ]}), [1 ,2 ,3 ]) 145for req in ({}, {"allowed_token_ids" :"1,2" }, {"allowed_token_ids" : [True ]}, {"allowed_token_ids" : [- 1 ]}): 146self .assertEqual (allowed_ids (req ), []) 147 148def test_the_engine_key_only_when_asked (self ): 149self .assertIn (" logprobs=0" ,StrataEngine .sampling_keys ({"logprobs" :True })) 150self .assertIn (" logprobs=5" ,StrataEngine .sampling_keys ({"logprobs" :True ,"top_logprobs" :5 })) 151self .assertNotIn ("logprobs" ,StrataEngine .sampling_keys ({})) 152self .assertNotIn ("logprobs" ,StrataEngine .sampling_keys ({"logprobs" :False ,"temperature" :0 })) 153 154def test_allowed_reaches_the_engine_line (self ): 155keys = StrataEngine .sampling_keys ({"logprobs" :True ,"top_logprobs" :2 , 156"allowed_token_ids" : [7 ,8 ,9 ]}) 157self .assertIn (" logprobs=2 " ,keys ) 158self .assertIn (" allowed=7,8,9" ,keys ) 159 160def test_unreadable_lines_give_no_entry (self ): 161a = threading .Event () 162eng = SimpleNamespace (lp_lines = LPLines (a )) 163for line in ("LP nan" ,"LP -nan(ind)" ,"LP inf" ,"LP -0.1 65:x" ,"LP -0.1 65:-inf" ,"LP -0.1 65" , 164"LP -0.200000 65:-1.0" ): 165eng .lp_lines .append ((72 ,line )) 166got = LogprobEntries (SimpleNamespace (tok = Tokenizer (),stop_ids = set ()),owner = a ).take (eng ) 167self .assertEqual ([e ["logprob" ]for e in got ], [- 0.2 ]) 168 169def test_a_filtered_line_with_nothing_left_keeps_its_token (self ): 170# none of the named ids on the line: the entry keeps the chosen token and its own logprob, and no 171# alternatives. It used to be None, appended all the same, and the reply failed on e["token"]. 172a = threading .Event () 173eng = SimpleNamespace (lp_lines = LPLines (a )) 174eng .lp_lines .append ((72 ,"LP -0.300000 65:-0.500000" )) 175got = LogprobEntries (SimpleNamespace (tok = Tokenizer (),stop_ids = set ()), [70 ],a ).take (eng ) 176self .assertEqual ([(e ["token" ],e ["logprob" ],e ["top_logprobs" ])for e in got ], [("H" ,- 0.3 , [])]) 177 178def test_a_named_token_the_line_does_not_repeat_is_its_own_distribution (self ): 179# the engine prints the chosen token's logprob on the head and the named ids after it, never repeating 180# the chosen one: naming only that id leaves it alone in the distribution, at 1 (logprob 0) 181a = threading .Event () 182eng = SimpleNamespace (lp_lines = LPLines (a )) 183eng .lp_lines .append ((72 ,"LP -0.300000 65:-0.500000" )) 184got = LogprobEntries (SimpleNamespace (tok = Tokenizer (),stop_ids = set ()), [72 ],a ).take (eng ) 185self .assertEqual (got [0 ]["top_logprobs" ], [{"token" :"H" ,"logprob" :0.0 ,"bytes" : [72 ]}]) 186self .assertEqual (got [0 ]["logprob" ],0.0 ) 187 188 189class Generate (unittest .TestCase ): 190"""The token's LP line is read next to it, and only when it was asked for.""" 191 192def engine (self ,* lines ): 193e = StrataEngine .__new__ (StrataEngine ) 194e .proc = __import__ ("types" ).SimpleNamespace ( 195stdin = __import__ ("io" ).StringIO (),poll = lambda :None ) 196e .lines ,e .can_stop ,e .max_context ,e .silence_s = queue .Queue (),False ,262144 ,0 197for line in lines : 198e .lines .put (line ) 199return e 200 201def test_a_token_is_yielded_with_its_lp_line_read (self ): 202e = self .engine ("PP 3 3" ,"T 72" ,"LP -0.100000 72:-0.1 65:-2.5" ,"T 105" , 203"LP -0.200000 105:-0.2 65:-3" ,"T 257" ,"LP -0.010000" , 204"DONE 3 3 0 3 stop 0 0 0" ) 205seen = [] 206for t in e .generate ([1 ,2 ,3 ],8 , {"logprobs" :True ,"top_logprobs" :2 },threading .Event ()): 207if t is not None : 208seen .append ((t , [x [0 ]for x in e .lp_lines ])) 209self .assertEqual (seen , [(72 , [72 ]), (105 , [72 ,105 ]), (257 , [72 ,105 ,257 ])]) 210self .assertIn (" logprobs=2 " ,e .proc .stdin .getvalue ()) 211self .assertEqual (e .lp_lines [1 ][1 ],"LP -0.200000 105:-0.2 65:-3" ) 212 213def test_an_engine_without_lp_lines (self ): 214e = self .engine ("T 72" ,"T 105" ,"DONE 3 3 0 2 stop 0 0 0" ) 215toks = [t for t in e .generate ([1 ],8 , {"logprobs" :True },threading .Event ())if t is not None ] 216self .assertEqual (toks , [72 ,105 ]) 217self .assertEqual (list (e .lp_lines ), []) 218self .assertEqual (e .last ["finish" ],"stop" ) 219 220def test_not_asked_reads_as_before (self ): 221e = self .engine ("T 72" ,"LP -0.1" ,"T 105" ,"DONE 3 3 0 2 stop 0 0 0" ) 222toks = [t for t in e .generate ([1 ],8 , {},threading .Event ())if t is not None ] 223self .assertEqual (toks , [72 ,105 ]) 224self .assertEqual (list (e .lp_lines ), []) 225 226def test_a_consumer_that_stops_early_does_not_lose_the_done_read_after_the_token (self ): 227# the DONE line was read while looking for the token's LP line: the drain must take it, 228# not wait for another 229e = self .engine ("T 72" ,"DONE 3 3 0 1 length 0 0 0" ,None ) 230gen = e .generate ([1 ],1 , {"logprobs" :True },threading .Event ()) 231self .assertEqual (next (gen ),72 ) 232gen .close () 233self .assertEqual (e .last ["finish" ],"length" ) 234 235 236class Api (unittest .TestCase ): 237def setUp (self ): 238self .tok = Tokenizer () 239self .engine = LpEngine (self .tok ,"Café costs €5." ) 240self .svc = Service (self .engine ,self .tok ,TEMPLATE ) 241self .httpd = serve (self .svc ,port = 0 ) 242self .base = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 243 244def tearDown (self ): 245self .httpd .shutdown () 246self .httpd .server_close () 247 248def post (self ,body ,stream = False ): 249body = {"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"hi" }],"max_tokens" :200 , 250"chat_template_kwargs" : {"enable_thinking" :False },** body } 251if stream : 252body ["stream" ]= True 253req = urllib .request .Request (self .base + "/v1/chat/completions" ,json .dumps (body ).encode (), 254 {"Content-Type" :"application/json" }) 255with urllib .request .urlopen (req ,timeout = 30 )as r : 256raw = r .read ().decode () 257if not stream : 258return json .loads (raw ) 259return [json .loads (x [6 :])for x in raw .splitlines ()if x .startswith ("data: {" )] 260 261def test_the_tokens_spell_the_content (self ): 262out = self .post ({"logprobs" :True ,"top_logprobs" :1 }) 263choice = out ["choices" ][0 ] 264content = choice ["message" ]["content" ] 265lps = choice ["logprobs" ]["content" ] 266self .assertEqual (content ,"Café costs €5." ) 267self .assertEqual ("" .join (e ["token" ]for e in lps ),content ) 268self .assertEqual (len (lps ),len (content .encode ()))# one per byte token; no stop token 269self .assertEqual (b"" .join (bytes (e ["bytes" ])for e in lps ),content .encode ()) 270e_acute = [e for e in lps if len (e ["bytes" ])== 1 and e ["bytes" ][0 ]>= 0x80 ] 271self .assertEqual ([e ["token" ]for e in e_acute [:2 ]], ["" ,"é" ])# split across two tokens 272self .assertEqual (lps [0 ]["logprob" ],- 0.01 ) 273self .assertEqual (lps [0 ]["top_logprobs" ][0 ]["token" ],"A" ) 274self .assertEqual (self .engine .sampling .get ("logprobs" ),True ) 275 276def test_a_request_reads_only_its_own_lines (self ): 277# A's last "." is held by its stop string and sent after A has left the queue, when B is 278# already generating on the same engine: each reply's tokens must spell that reply 279first_out = threading .Event () 280engine = NextEngine (self .tok , ["Café costs €5." ,"Bonjour!" ],first_out ) 281svc = Service (engine ,self .tok ,TEMPLATE ) 282svc .fifo = HandOver (engine ) 283httpd = serve (svc ,port = 0 ) 284got = {} 285try : 286self .base = f"http://127.0.0.1: { httpd . server_address [ 1 ] } " 287a = threading .Thread (target = lambda :got .update (a = self .post ({"logprobs" :True ,"stop" : [".!" ]}))) 288b = threading .Thread (target = lambda :got .update (b = self .post ({"logprobs" :True }))) 289a .start () 290self .assertTrue (engine .first_in .wait (10 )) 291b .start () 292a .join (30 ) 293first_out .set () 294b .join (30 ) 295finally : 296first_out .set () 297httpd .shutdown () 298httpd .server_close () 299for key ,text in (("a" ,"Café costs €5." ), ("b" ,"Bonjour!" )): 300choice = got [key ]["choices" ][0 ] 301self .assertEqual (choice ["message" ]["content" ],text ) 302self .assertEqual ("" .join (e ["token" ]for e in choice ["logprobs" ]["content" ]),text ,key ) 303 304def test_logprobs_take_any_max_tokens (self ): 305# No cap of our own: the reply is already bounded by max_tokens (the rest of the context when it is not 306# sent), which is the only bound OpenAI and vLLM put on it too -- openai-node's max_tokens is optional 307# and vLLM's defaults to 16 or None, neither tying it to logprobs. 308for max_tokens in (200 ,5000 ,0 ,- 1 ,None ):# 0 / -1: "the rest of the context"; None: not sent 309choice = self .post ({"logprobs" :True ,"top_logprobs" :1 ,"max_tokens" :max_tokens })["choices" ][0 ] 310self .assertEqual ("" .join (e ["token" ]for e in choice ["logprobs" ]["content" ]), 311"Café costs €5." ,max_tokens ) 312self .assertNotIn ("logprobs" ,self .post ({"max_tokens" :0 })["choices" ][0 ])# not asked: as before 313 314def test_a_streamed_reply_needs_no_bound (self ): 315# A streamed reply hands each entry out with its chunk and keeps none, so it is bounded by the reply's own 316# length. OpenAI itself bounds a reply only by the model's context, and its SDKs send no max_tokens by 317# default. 5000 and "the rest of the context" must both be answered, as they are without logprobs. 318for max_tokens in (5000 ,0 ,None ):# None: the field is not sent at all 319chunks = self .post ({"logprobs" :True ,"max_tokens" :max_tokens },stream = True ) 320text = "" .join (c ["choices" ][0 ]["delta" ].get ("content" )or "" for c in chunks if c .get ("choices" )) 321toks = [e ["token" ]for c in chunks if c .get ("choices" ) 322for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get ("content" , [])] 323self .assertEqual (text ,"Café costs €5." ,max_tokens ) 324self .assertEqual ("" .join (toks ),text ,max_tokens )# an entry for every token, streamed or not 325 326def test_a_json_schema_reply_takes_any_max_tokens (self ): 327# structured_chunks buffers the reply to validate it, logprobs included: it holds the entries until the 328# end, as a reply that is not streamed does. That memory is bounded by max_tokens, not by a cap of ours. 329written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' 330self .engine = self .svc .engine = LpEngine (self .tok ,written ) 331content = '{"rent": "$1,250", "quote": "x"}' 332for max_tokens in (200 ,0 ,5000 ): 333choice = self .post ({"logprobs" :True ,"max_tokens" :max_tokens ,"response_format" :SCHEMA })["choices" ][0 ] 334self .assertEqual (choice ["message" ]["content" ],content ,max_tokens ) 335self .assertEqual ("" .join (e ["token" ]for e in choice ["logprobs" ]["content" ]),content ,max_tokens ) 336chunks = self .post ({"logprobs" :True ,"max_tokens" :max_tokens ,"response_format" :SCHEMA },stream = True ) 337toks = [e ["token" ]for c in chunks if c .get ("choices" ) 338for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get ("content" , [])] 339self .assertEqual ("" .join (toks ),content , (max_tokens ,"streamed" )) 340 341def test_logprobs_are_refused_on_the_batch_path (self ): 342# --parallel/--batch: the engine's batched loop prints "BT <slot> <id>" and never calls emit_lp_line 343# (src/program/generate.cpp), so no LP line reaches the server and the field would simply be absent. 344# Refused up front instead, before anything is generated; a request that does not ask is untouched. 345self .engine .batch = 2 346with self .assertRaises (urllib .error .HTTPError )as cm : 347self .post ({"logprobs" :True }) 348self .assertEqual (cm .exception .code ,400 ) 349self .assertIn ("--parallel" ,cm .exception .read ().decode ()) 350self .engine .batch = 0 351self .assertIn ("logprobs" ,self .post ({"logprobs" :True })["choices" ][0 ]) 352 353def test_allowed_token_ids_outside_the_vocabulary_is_a_400 (self ): 354# emit_lp_line indexes its logits row with each named id, so an id past the vocabulary would read out of 355# bounds; the request is refused before anything is generated 356self .tok .tokens = [str (i )for i in range (300 )]# a tokenizer that knows its vocabulary 357with self .assertRaises (urllib .error .HTTPError )as cm : 358self .post ({"logprobs" :True ,"top_logprobs" :1 ,"allowed_token_ids" : [300 ]}) 359self .assertEqual (cm .exception .code ,400 ) 360self .assertIn ("allowed_token_ids" ,cm .exception .read ().decode ()) 361self .assertIn ("logprobs" ,self .post ({"logprobs" :True ,"top_logprobs" :1 , 362"allowed_token_ids" : [299 ]})["choices" ][0 ]) 363 364def test_streamed (self ): 365chunks = self .post ({"logprobs" :True },stream = True ) 366content = "" .join (c ["choices" ][0 ]["delta" ].get ("content" )or "" for c in chunks if c .get ("choices" )) 367toks = [e ["token" ]for c in chunks if c .get ("choices" ) 368for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get ("content" , [])] 369self .assertEqual (content ,"Café costs €5." ) 370self .assertEqual ("" .join (toks ),content ) 371 372def test_with_thinking_each_part_is_spelled_by_its_tokens (self ): 373tok = ThinkTokenizer () 374svc = Service (LpEngine (tok ,"Two times three.</think>\n\nSix." ),tok , 375TEMPLATE ) 376httpd = serve (svc ,port = 0 ) 377try : 378self .base = f"http://127.0.0.1: { httpd . server_address [ 1 ] } " 379for stream in (False ,True ): 380out = self .post ({"logprobs" :True ,"chat_template_kwargs" : {"enable_thinking" :True }}, 381stream ) 382chunks = out if stream else [{"choices" : [{"delta" :out ["choices" ][0 ]["message" ], 383"logprobs" :out ["choices" ][0 ]["logprobs" ]}]}] 384for key in ("content" ,"reasoning_content" ): 385text = "" .join (c ["choices" ][0 ]["delta" ].get (key )or "" for c in chunks if c .get ("choices" )) 386toks = "" .join (e ["token" ]for c in chunks if c .get ("choices" ) 387for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get (key , [])) 388self .assertTrue (text ) 389self .assertEqual (toks ,text , (key ,stream )) 390self .assertNotIn ("think>" ,toks ) 391finally : 392httpd .shutdown () 393httpd .server_close () 394 395def test_not_asked_no_logprobs (self ): 396out = self .post ({}) 397self .assertNotIn ("logprobs" ,out ["choices" ][0 ]) 398 399def test_an_engine_without_lp_lines_gives_none (self ): 400self .engine .with_lines = False 401out = self .post ({"logprobs" :True }) 402self .assertEqual (out ["choices" ][0 ]["message" ]["content" ],"Café costs €5." ) 403self .assertNotIn ("logprobs" ,out ["choices" ][0 ]) 404 405def test_allowed_token_ids_are_renormalised_over_the_named_ids (self ): 406out = self .post ({"logprobs" :True ,"allowed_token_ids" : [65 ,72 ]}) 407lps = out ["choices" ][0 ]["logprobs" ]["content" ] 408self .assertTrue (lps ) 409for e in lps : 410ids = [t ["token" ]for t in e ["top_logprobs" ]] 411self .assertEqual (ids , ["A" ,"H" ])# only the named ones 412import math 413total = sum (math .exp (t ["logprob" ])for t in lps [0 ]["top_logprobs" ]) 414self .assertAlmostEqual (total ,1.0 ,places = 6 )# renormalised: they sum to 1 415 416def test_allowed_token_ids_with_nothing_to_renormalise (self ): 417# the mock's alternatives are 65/72/88/91: naming another id leaves every line with no survivor. Each 418# token keeps its own logprob and an empty candidate list, and the reply still comes back whole (this 419# used to be a 400 on the unstreamed path and a reply cut after the role chunk when streamed). 420for body in ({"logprobs" :True ,"allowed_token_ids" : [66 ]}, 421 {"logprobs" :True ,"allowed_token_ids" : [66 ,70 ,71 ]}): 422choice = self .post (body )["choices" ][0 ] 423lps = choice ["logprobs" ]["content" ] 424self .assertEqual (choice ["message" ]["content" ],"Café costs €5." ) 425self .assertEqual ("" .join (e ["token" ]for e in lps ),"Café costs €5." ) 426self .assertEqual ([e ["top_logprobs" ]for e in lps ], [[]]* len (lps )) 427self .assertEqual (lps [0 ]["logprob" ],- 0.01 )# the token's own, as the engine reported it 428streamed = self .post (body ,stream = True ) 429toks = [e ["token" ]for c in streamed if c .get ("choices" ) 430for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get ("content" , [])] 431self .assertEqual ("" .join (toks ),"Café costs €5." ) 432 433def test_a_named_token_the_model_chose_is_in_its_distribution (self ): 434# 46 is the reply's final ".": the engine does not repeat the chosen token among the named ids, so 435# naming only it used to leave nothing to normalise over. It is the whole distribution now, at 0. 436lps = self .post ({"logprobs" :True ,"allowed_token_ids" : [46 ]})["choices" ][0 ]["logprobs" ]["content" ] 437dot = [e for e in lps if e ["token" ]== "." ] 438self .assertEqual (len (dot ),1 ) 439self .assertEqual (dot [0 ]["top_logprobs" ], [{"token" :"." ,"logprob" :0.0 ,"bytes" : [46 ]}]) 440self .assertEqual (dot [0 ]["logprob" ],0.0 ) 441self .assertEqual ([e ["top_logprobs" ]for e in lps if e ["token" ]!= "." ], [[]]* (len (lps )- 1 )) 442 443def test_a_choice_of_ten_that_only_the_ended_reply_settles (self ): 444# ten named ids, and a reply that is two of them: "1" alone is already one of the choices, so which 445# one was picked is only known when the reply ends. Here "11": each token's entries cover the ten 446# named ids (the chosen one included, because the engine never repeats it), and they sum to 1. 447self .engine = self .svc .engine = NamedEngine (self .tok ,"11" ) 448digits = [ord (c )for c in "0123456789" ] 449for stream in (False ,True ): 450out = self .post ({"logprobs" :True ,"top_logprobs" :10 ,"allowed_token_ids" :digits },stream ) 451chunks = out if stream else [{"choices" : [{"delta" :out ["choices" ][0 ]["message" ], 452"logprobs" :out ["choices" ][0 ]["logprobs" ]}]}] 453content = "" .join (c ["choices" ][0 ]["delta" ].get ("content" )or "" for c in chunks if c .get ("choices" )) 454lps = [e for c in chunks if c .get ("choices" ) 455for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get ("content" , [])] 456self .assertEqual (content ,"11" ) 457self .assertEqual ([e ["token" ]for e in lps ], ["1" ,"1" ])# the first token alone is a choice too 458self .assertEqual ("" .join (e ["token" ]for e in lps ),content ) 459for e in lps : 460ids = [t ["token" ]for t in e ["top_logprobs" ]] 461self .assertEqual (sorted (ids ),sorted ("0123456789" ))# the ten named ids, and only them 462self .assertIn (e ["token" ],ids )# the chosen one is one of them 463self .assertEqual (ids [0 ],e ["token" ])# ... and the most likely, here 464self .assertEqual ([t ["logprob" ]for t in e ["top_logprobs" ]], 465sorted ((t ["logprob" ]for t in e ["top_logprobs" ]),reverse = True )) 466self .assertAlmostEqual (sum (math .exp (t ["logprob" ])for t in e ["top_logprobs" ]),1.0 ,places = 6 ) 467 468def test_a_held_tail_of_more_than_one_token (self ): 469# "5." is the start of the stop string, so the parser holds two tokens and sends them as one piece 470# after the request has left the queue: both entries come from this request's own lines all the same 471chunks = self .post ({"logprobs" :True ,"stop" : ["5.!" ]},stream = True ) 472content = [c for c in chunks if c .get ("choices" )and c ["choices" ][0 ]["delta" ].get ("content" )] 473self .assertEqual (content [- 1 ]["choices" ][0 ]["delta" ]["content" ],"5." )# held, then flushed whole 474self .assertEqual ([e ["token" ]for e in content [- 1 ]["choices" ][0 ]["logprobs" ]["content" ]], ["5" ,"." ]) 475text = "" .join (c ["choices" ][0 ]["delta" ].get ("content" )or "" for c in chunks if c .get ("choices" )) 476self .assertEqual (text ,"Café costs €5." ) 477self .assertEqual ("" .join (e ["token" ]for c in chunks if c .get ("choices" ) 478for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get ("content" , [])),text ) 479choice = self .post ({"logprobs" :True ,"stop" : ["5.!" ]})["choices" ][0 ]# and not streamed 480self .assertEqual (choice ["message" ]["content" ],"Café costs €5." ) 481self .assertEqual ("" .join (e ["token" ]for e in choice ["logprobs" ]["content" ]),"Café costs €5." ) 482self .assertEqual ("" .join (e ["token" ]for e in choice ["logprobs" ]["content" ][- 2 :]),"5." ) 483 484def test_json_schema_answer_as_written_with_its_logprobs (self ): 485# MockEngine appends the stop token to the script it is built with, and reports 486# finish_reason=length when it runs out -- so the engine is rebuilt with this answer 487# rather than re-pointed at a raw token list (which would drop the stop token). 488written = '```json\n{"rent": "$1,250", "quote": "x"}\n```' 489self .engine = self .svc .engine = LpEngine (self .tok ,written ) 490out = self .post ({"logprobs" :True ,"temperature" :0 ,"response_format" :SCHEMA }) 491choice = out ["choices" ][0 ] 492content = choice ["message" ]["content" ] 493self .assertEqual (content ,'{"rent": "$1,250", "quote": "x"}' )# the JSON as written 494self .assertEqual ("" .join (e ["token" ]for e in choice ["logprobs" ]["content" ]),content ) 495streamed = self .post ({"logprobs" :True ,"response_format" :SCHEMA },stream = True ) 496toks = [e ["token" ]for c in streamed if c .get ("choices" ) 497for e in (c ["choices" ][0 ].get ("logprobs" )or {}).get ("content" , [])] 498self .assertEqual ("" .join (toks ),content ) 499plain = self .post ({"temperature" :0 ,"response_format" :SCHEMA })# not asked: as before 500self .assertEqual (plain ["choices" ][0 ]["message" ]["content" ], 501'{"rent":"$1,250","quote":"x"}' ) 502self .assertNotIn ("logprobs" ,plain ["choices" ][0 ]) 503 504 505class Replicas (unittest .TestCase ): 506"""`--replicas`: a ReplicaEngine's own `batch` is how many requests its engines run at once and counts a replica 507without slots as one, so asking it "does this engine use batch slots" refused logprobs on a server that has 508none -- one that reads every reply by the GEN path, which does write LP lines.""" 509 510@staticmethod 511def replica (* batches ): 512from serve .replicas import ReplicaEngine 513return ReplicaEngine ([SimpleNamespace (gen = 1 ,batch = b )for b in batches ]) 514 515def test_no_slots_behind_replicas (self ): 516self .assertFalse (batch_slots_on (self .replica (0 ,0 ))) 517self .assertFalse (batch_slots_on (SimpleNamespace (batch = 0 )))# no replicas: the engine's own figure 518 519def test_slots_behind_replicas (self ): 520self .assertTrue (batch_slots_on (self .replica (2 ,3 )))# every one of them 521self .assertTrue (batch_slots_on (self .replica (0 ,2 )))# one is enough 522self .assertTrue (batch_slots_on (SimpleNamespace (batch = 4 ))) 523 524 525class Span (unittest .TestCase ): 526def entries (self ,* toks ): 527return [{"token" :t }for t in toks ] 528 529def test_span (self ): 530es = self .entries ("```" ,"json" ,"\n" ,"{" ,"}" ,"\n" ,"```" ) 531self .assertEqual ([e ["token" ]for e in logprob_span ("```json\n{}\n```" ,"{}" ,es )], ["{" ,"}" ]) 532self .assertEqual (len (logprob_span ("{}" ,"{}" ,self .entries ("{" ,"}" ))),2 ) 533 534def test_no_span (self ): 535self .assertIsNone (logprob_span ("x{}" ,"{}" ,self .entries ("x{" ,"}" )))# no boundary at the start 536self .assertIsNone (logprob_span ("{}x" ,"{}" ,self .entries ("{" ,"}x" )))# none at the end 537self .assertIsNone (logprob_span ("{}" ,"{}" ,self .entries ("{" )))# do not spell it 538 539 540if __name__ == "__main__" : 541unittest .main ()