okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bd0e878f4
main
1"""Request accounting across thinking-budget continuations, through the HTTP APIs (no GPU or model pack). 2 3python -m unittest serve.test_request_accounting -v 4""" 5import json 6import unittest 7import urllib .error 8import urllib .request 9from pathlib import Path 10 11from serve .frontend import ChatTemplate 12from serve .server import ByteTokenizer ,EngineDied ,Service ,add_carry ,carry_leg ,request_stats ,request_timings ,serve 13from serve .test_server import ThinkingEngine 14 15 16class ClockedThinkingEngine (ThinkingEngine ): 17"""The native DONE contract: closing a generation drains its statistics before the next one starts.""" 18REUSED = 5 19 20def __init__ (self ,tok ): 21super ().__init__ (tok ) 22self .attempts = 0 23self .done = [] 24self .fail_continuation = False 25self .cancel_continuation = False 26 27def generate (self ,ids ,max_new ,sampling ,cancel ,embeddings = None ): 28self .attempts += 1 29if self .fail_continuation and self .attempts == 2 : 30raise EngineDied ("the continuation ended without a DONE line" ) 31first = self .attempts == 1 32generated = 0 33stopped = False 34try : 35for token in super ().generate (ids ,max_new ,sampling ,cancel ,embeddings ): 36generated += 1 37stopped = token in self .tok .encode ("<|im_end|>" ,parse_special = True ) 38yield token 39if self .cancel_continuation and not first and generated == 3 : 40cancel .set () 41finally : 42# The continuation reuses the original prompt plus the generated thinking. 43reused = self .REUSED if first else len (self .prompts [0 ])+ self .done [0 ]["generated" ] 44self .last = dict (prompt_tokens = len (ids ),generated = generated ,reused = reused , 45prompt_read = len (ids )- reused ,finish = "stop" if stopped else "cancel" , 46prompt_ms = 40.0 if first else 7.0 ,decode_ms = 200.0 if first else 80.0 , 47drafts_offered = 18 if first else 11 ,drafts_accepted = 8 if first else 7 , 48hits = 9 if first else 7 ,lookups = 10 if first else 8 , 49ram_blobs = 1 if first else 3 ,file_blobs = 2 if first else 4 , 50file_mb = 1.5 if first else 2.5 ) 51self .done .append (dict (self .last )) 52 53 54class RequestAccounting (unittest .TestCase ): 55def setUp (self ): 56tok = ByteTokenizer () 57self .engine = ClockedThinkingEngine (tok ) 58self .svc = Service (self .engine ,tok ,ChatTemplate (Path (__file__ ).with_name ("chat_template.jinja" ))) 59self .httpd = serve (self .svc ,port = 0 ) 60self .base = f"http://127.0.0.1: { self . httpd . server_address [ 1 ] } " 61 62def tearDown (self ): 63self .httpd .shutdown () 64self .httpd .server_close () 65 66def request (self ,path ,body = None ): 67req = urllib .request .Request (self .base + path ,data = json .dumps (body ).encode ()if body else None , 68headers = {"Content-Type" :"application/json" ,"anthropic-version" :"2023-06-01" }) 69try : 70response = urllib .request .urlopen (req ,timeout = 10 ) 71except urllib .error .HTTPError as error : 72response = error 73with response : 74raw = response .read ().decode () 75return response .status ,raw 76 77def chat (self ,path = "/v1/chat/completions" ,stream = False ,budget = 20 ): 78code ,raw = self .request (path , {"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"2+2?" }], 79"max_tokens" :400 ,"reasoning_budget_tokens" :budget ,"stream" :stream }) 80self .assertEqual (code ,200 ,raw ) 81if stream : 82return [json .loads (line [6 :])for line in raw .splitlines ()if line .startswith ("data: {" )] 83return json .loads (raw ) 84 85def assert_original_input (self ,usage ): 86original = len (self .engine .prompts [0 ]) 87self .assertEqual (self .engine .attempts ,2 ) 88self .assertGreater (self .engine .done [1 ]["reused" ],original ,"exercise reuse beyond the API input" ) 89self .assertEqual (usage ["prompt_tokens" ],original ) 90self .assertEqual (usage ["prompt_tokens_details" ]["cached_tokens" ],self .engine .REUSED ) 91self .assertEqual (usage ["total_tokens" ],original + usage ["completion_tokens" ]) 92 93def assert_request_work (self ,timings ,completion_tokens ,finish = "stop" ): 94original = len (self .engine .prompts [0 ]) 95self .assertEqual (len (self .engine .done ),2 ) 96native_generated = sum (done ["generated" ]for done in self .engine .done ) 97self .assertEqual ((timings ["cache_n" ],timings ["prompt_n" ]), (5 ,original - 5 )) 98self .assertEqual ((timings ["prompt_ms" ],timings ["predicted_ms" ]), (47.0 ,280.0 )) 99self .assertEqual (timings ["predicted_n" ],completion_tokens ) 100self .assertGreater (completion_tokens ,native_generated ,"wrap-up tokens count as output, not native decode" ) 101self .assertEqual (timings ["predicted_per_second" ],round (native_generated / 0.280 ,1 )) 102self .assertEqual (timings ["predicted_per_token_ms" ],round (280.0 / native_generated ,3 )) 103self .assertEqual ((timings ["draft_n" ],timings ["draft_n_accepted" ]), (29 ,15 )) 104code ,raw = self .request ("/metrics" ) 105self .assertEqual (code ,200 ) 106metrics = json .loads (raw ) 107row ,totals = metrics ["requests" ][0 ],metrics ["totals" ] 108self .assertEqual (row ["finish" ],finish ) 109self .assertEqual ((row ["prompt_tokens" ],row ["reused" ],row ["prompt_read" ]), (original ,5 ,original - 5 )) 110self .assertEqual (row ["engine_generated" ],native_generated ) 111self .assertEqual (row ["decode_tok_s" ],timings ["predicted_per_second" ]) 112self .assertEqual ((row ["prompt_ms" ],row ["decode_ms" ]), (47.0 ,280.0 )) 113self .assertEqual ((row ["ram_blobs" ],row ["file_blobs" ],row ["file_mb" ]), (4 ,6 ,4.0 )) 114self .assertAlmostEqual (row ["hit_rate" ],16 / 18 ,places = 3 ) 115self .assertEqual ((totals ["requests" ],totals ["prompt_tokens" ],totals ["reused" ]), (1 ,original ,5 )) 116self .assertEqual ((totals ["prompt_ms" ],totals ["decode_ms" ]), (47.0 ,280.0 )) 117self .assertEqual ((totals ["drafts_offered" ],totals ["drafts_accepted" ]), (29 ,15 )) 118code ,raw = self .request ("/v1/status" ) 119self .assertEqual (code ,200 ) 120self .assertEqual (json .loads (raw )["last_timings" ]["draft_n" ],29 ) 121 122def test_openai_nonstream_keeps_original_cache_and_all_segment_work (self ): 123response = self .chat () 124self .assertEqual (response ["choices" ][0 ]["message" ]["content" ],self .engine .ANSWER ) 125self .assertEqual (response ["choices" ][0 ]["finish_reason" ],"stop" ) 126self .assert_original_input (response ["usage" ]) 127self .assert_request_work (response ["timings" ],response ["usage" ]["completion_tokens" ]) 128 129def test_openai_stream_keeps_original_cache_and_all_segment_work (self ): 130events = self .chat (stream = True ) 131final = events [- 1 ] 132self .assertEqual (final ["choices" ][0 ]["finish_reason" ],"stop" ) 133self .assert_original_input (final ["usage" ]) 134self .assert_request_work (final ["timings" ],final ["usage" ]["completion_tokens" ]) 135 136def test_cancelled_continuation_keeps_original_input_and_counts_each_done_once (self ): 137self .engine .cancel_continuation = True 138events = self .chat (stream = True ) 139final = events [- 1 ] 140content = "" .join (event ["choices" ][0 ]["delta" ].get ("content" ,"" )for event in events ) 141self .assertEqual (content ,"The" ) 142self .assertEqual (final ["choices" ][0 ]["finish_reason" ],"stop" ) 143self .assertEqual ([done ["generated" ]for done in self .engine .done ], [20 ,3 ]) 144self .assert_original_input (final ["usage" ]) 145self .assert_request_work (final ["timings" ],final ["usage" ]["completion_tokens" ],finish = "cancel" ) 146 147def test_anthropic_nonstream_classifies_only_original_input_as_cached (self ): 148usage = self .chat ("/v1/messages" )["usage" ] 149self .assertEqual (self .engine .attempts ,2 ) 150self .assertEqual (usage ["cache_read_input_tokens" ],5 ) 151self .assertEqual (usage ["input_tokens" ]+ usage ["cache_creation_input_tokens" ],len (self .engine .prompts [0 ])- 5 ) 152 153def test_anthropic_stream_classifies_only_original_input_as_cached (self ): 154events = self .chat ("/v1/messages" ,stream = True ) 155usage = next (event ["usage" ]for event in events if event ["type" ]== "message_delta" ) 156self .assertEqual (self .engine .attempts ,2 ) 157self .assertEqual (usage ["cache_read_input_tokens" ],5 ) 158self .assertEqual (usage ["input_tokens" ]+ usage ["cache_creation_input_tokens" ],len (self .engine .prompts [0 ])- 5 ) 159 160def test_single_segment_keeps_its_own_usage_and_timings (self ): 161response = self .chat (budget = 10000 ) 162self .assertEqual (self .engine .attempts ,1 ) 163self .assertEqual (response ["usage" ]["prompt_tokens_details" ]["cached_tokens" ],5 ) 164timings = response ["timings" ] 165self .assertEqual ((timings ["prompt_ms" ],timings ["predicted_ms" ]), (40.0 ,200.0 )) 166self .assertEqual ((timings ["draft_n" ],timings ["draft_n_accepted" ]), (18 ,8 )) 167 168def test_failed_continuation_does_not_count_the_first_done_twice (self ): 169self .engine .fail_continuation = True 170events = self .chat (stream = True ) 171self .assertTrue (any ("error" in event for event in events )) 172self .assertEqual (self .engine .attempts ,2 ) 173self .assertEqual (len (self .engine .done ),1 ) 174_ ,raw = self .request ("/metrics" ) 175metrics = json .loads (raw ) 176row = metrics ["requests" ][0 ] 177self .assertEqual (row ["finish" ],"error" ) 178self .assertEqual (row ["engine_generated" ],20 ) 179self .assertEqual ((row ["prompt_ms" ],row ["decode_ms" ]), (40.0 ,200.0 )) 180self .assertEqual ((metrics ["totals" ]["drafts_offered" ],metrics ["totals" ]["drafts_accepted" ]), (18 ,8 )) 181 182 183class SlotLegAccounting (unittest .TestCase ): 184"""#1869: a request that decoded in a batch slot and finished on the solo path keeps the slot leg's decode time and 185tokens (the solo DONE alone said 1 token in 18 ms); #1870: prompt_n is what the engine read.""" 186 187def test_solo_leg_adds_to_the_slot_leg (self ): 188carry = {} 189slot_leg = {"generated" :134 ,"decode_ms" :2900.0 ,"prompt_ms" :3794.7 ,"prompt_read" :2052 ,"finish" :"cancel" } 190carry_leg (carry ,slot_leg ) 191solo_done = {"generated" :1 ,"decode_ms" :18.4 ,"prompt_ms" :2.0 ,"prompt_read" :1 ,"finish" :"stop" ,"reused" :0 } 192total = add_carry (carry ,solo_done ) 193self .assertEqual ((total ["generated" ],total ["decode_ms" ]), (135 ,2918.4 )) 194self .assertEqual ((total ["prompt_ms" ],total ["prompt_read" ],total ["finish" ]), (3794.7 ,2052 ,"stop" )) 195timings = request_timings (2052 ,135 ,total ) 196self .assertEqual (timings ["predicted_ms" ],2918.4 ) 197self .assertAlmostEqual (timings ["predicted_per_second" ],46.3 ,places = 1 ) 198 199def test_two_hand_backs_sum (self ): 200carry = {} 201carry_leg (carry , {"generated" :10 ,"decode_ms" :100.0 ,"prompt_ms" :50.0 }) 202carry_leg (carry , {"generated" :20 ,"decode_ms" :300.0 ,"prompt_ms" :1.0 }) 203total = add_carry (carry , {"generated" :5 ,"decode_ms" :50.0 ,"prompt_ms" :1.0 }) 204self .assertEqual ((total ["generated" ],total ["decode_ms" ],total ["prompt_ms" ]), (35 ,450.0 ,50.0 )) 205self .assertNotIn ("prompt_read" ,total ) 206 207def test_missing_slot_time_stays_unknown_after_solo_carry (self ): 208carry = {} 209carry_leg (carry , {"generated" :10 ,"decode_ms" :None ,"prompt_ms" :50.0 }) 210total = add_carry (carry , {"generated" :5 ,"decode_ms" :100.0 ,"prompt_ms" :1.0 }) 211self .assertEqual (total ["generated" ],15 ) 212self .assertIsNone (total ["decode_ms" ]) 213 214def test_missing_final_figures_stay_unknown_after_carry_and_segments (self ): 215carry = {} 216carry_leg (carry , {"generated" :10 ,"decode_ms" :20.0 ,"prompt_ms" :50.0 }) 217total = add_carry (carry , {"generated" :None ,"decode_ms" :None ,"prompt_ms" :1.0 }) 218combined = request_stats ([{"generated" :5 ,"decode_ms" :100.0 ,"prompt_ms" :10.0 },total ]) 219self .assertIsNone (combined ["generated" ]) 220self .assertIsNone (combined ["decode_ms" ]) 221 222def test_unknown_decode_time_is_not_reported_as_zero (self ): 223timings = request_timings (100 ,10 , {"generated" :10 ,"decode_ms" :None ,"prompt_ms" :50.0 }) 224self .assertIsNone (timings ["predicted_ms" ]) 225self .assertIsNone (timings ["predicted_per_token_ms" ]) 226self .assertIsNone (timings ["predicted_per_second" ]) 227 228def test_explicit_zero_native_count_is_not_replaced_by_api_output_count (self ): 229timings = request_timings (100 ,5 , {"generated" :0 ,"decode_ms" :0.0 ,"prompt_ms" :50.0 }) 230self .assertEqual ((timings ["predicted_n" ],timings ["predicted_ms" ]), (5 ,0.0 )) 231self .assertIsNone (timings ["predicted_per_token_ms" ]) 232self .assertIsNone (timings ["predicted_per_second" ]) 233 234def test_prompt_n_is_what_was_read (self ): 235# the slot already held the whole prompt: 1 token read, the conversation cache off (reused 0) 236last = {"prompt_ms" :563.5 ,"decode_ms" :700.0 ,"generated" :30 ,"reused" :0 ,"prompt_read" :1 ,"finish" :"stop" } 237t = request_timings (43086 ,30 ,last ) 238self .assertEqual ((t ["prompt_n" ],t ["cache_n" ]), (1 ,43085 )) 239self .assertEqual (t ["prompt_n" ]+ t ["cache_n" ],43086 ) 240self .assertLess (t ["prompt_per_second" ],10 ) 241# a cold read, and an older engine without the field: unchanged 242cold = request_timings (2052 ,10 , {** last ,"prompt_read" :2052 }) 243self .assertEqual ((cold ["prompt_n" ],cold ["cache_n" ]), (2052 ,0 )) 244old = request_timings (2052 ,10 , {k :v for k ,v in last .items ()if k != "prompt_read" }) 245self .assertEqual ((old ["prompt_n" ],old ["cache_n" ]), (2052 ,0 )) 246# the conversation cache's own count still counts when larger 247both = request_timings (1000 ,10 , {** last ,"reused" :900 ,"prompt_read" :100 }) 248self .assertEqual ((both ["prompt_n" ],both ["cache_n" ]), (100 ,900 )) 249 250 251if __name__ == "__main__" : 252unittest .main ()