okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
568127b7a
main
1"""The run average of the speed cards (community patch: keinebenutzer/STRATA-average-patch, MIT, made against v0.1.55 c62d5e3a; ported by hand onto rc1). 2 3serve/web/app.js (the Monitor tab's Decode and Prefill cards), serve/web/monitor.js and monitor.html (the API monitor page) and strata_cli/overview.py (the Terminal 4Overview) show, when the server is idle, the token-weighted average of the run instead of the last request's speed. Live values stay live. This file runs the 5browser code the way a page would (a few lines of node, no browser, no network) and checks that what was added is display only.""" 6import json 7import re 8import shutil 9import subprocess 10import unittest 11from pathlib import Path 12 13WEB = Path (__file__ ).resolve ().parent / "web" 14NODE = shutil .which ("node" ) 15 16 17def run_node (source :str )-> object : 18done = subprocess .run ([NODE ,"-e" ,source ],capture_output = True ,text = True ,encoding = "utf-8" ,timeout = 60 ,check = True )# node writes UTF-8; the locale code page (cp1252, cp932 ...) is not what it speaks 19return json .loads (done .stdout ) 20 21 22def function_source (text :str ,name :str )-> str : 23"""One top-level function of a browser script, by its opening line to its closing brace in column 0.""" 24start = text .index (f"function { name } (" ) 25end = text .index ("\n}\n" ,start )+ 3 26return text [start :end ] 27 28 29def cards_block (text :str )-> str : 30"""The lines of renderMonitor that make the Decode and Prefill cards.""" 31start = text .index (" // the eight cards" ) 32return text [start :text .index (' spark("sp-speed"' ,start )] 33 34 35@ unittest . skipUnless ( NODE , "node is needed to run the page's own code" ) 36class MonitorTab (unittest .TestCase ): 37"""serve/web/app.js: the two cards, run with stand-ins for the page's helpers.""" 38 39def cards (self ,live ,last ,totals ): 40block = cards_block ((WEB / "app.js" ).read_text (encoding = "utf-8" )) 41script = ("const calls = []; const setMetric = (...a) => calls.push(a); const fmt = (n, d = 0) => Number(n).toFixed(d);\n" 42f"function run(live, last, totals) {{\n { block } \n}}\nrun( { json . dumps ( live ) } , { json . dumps ( last ) } , { json . dumps ( totals ) } );\nconsole.log(JSON.stringify(calls));" ) 43script = script .replace ("spark(" ,"(() => {})(" ) 44calls = run_node (script ) 45return {c [0 ]: (c [1 ],c [3 ])for c in calls } 46 47TOTALS = {"requests" :12 ,"prompt_tokens" :90000 ,"reused" :5000 ,"output_tokens" :40000 ,"prompt_ms" :120000.0 ,"decode_ms" :1000000.0 } 48LAST = {"decode_tok_s" :50.5 ,"prompt_ms" :2000.0 ,"prompt_tokens" :1000 ,"reused" :0 } 49 50def test_idle_shows_the_run_average_for_both_cards (self ): 51cards = self .cards ({"state" :"idle" },self .LAST ,self .TOTALS ) 52self .assertEqual (cards ["speed" ], ("40.0" ,"Decode · run average" )) 53self .assertEqual (cards ["prefill" ], ("708" ,"Prefill · run average" ),"(90000 - 5000 reused) tokens in 120 s" ) 54 55def test_live_values_stay_live (self ): 56self .assertEqual (self .cards ({"state" :"generating" ,"tok_s" :31.5 ,"prefill_tok_s_mean" :600 },self .LAST ,self .TOTALS )["speed" ], ("31.5" ,"Decode now" )) 57self .assertEqual (self .cards ({"state" :"generating" ,"tok_s" :31.5 ,"prefill_tok_s_mean" :600 },self .LAST ,self .TOTALS )["prefill" ], ("600" ,"Prefill this request" )) 58self .assertEqual (self .cards ({"state" :"reading" ,"prefill_tok_s_mean" :820 },self .LAST ,self .TOTALS )["prefill" ], ("820" ,"Prefill now" )) 59 60def test_without_totals_it_is_the_last_request_and_never_an_invented_zero (self ): 61for totals in (None , {}, {"output_tokens" :0 ,"decode_ms" :0 ,"prompt_tokens" :0 ,"prompt_ms" :0 }): 62cards = self .cards ({"state" :"idle" },self .LAST ,totals ) 63self .assertEqual (cards ["speed" ], ("50.5" ,"Decode last request" ),totals ) 64self .assertEqual (cards ["prefill" ], ("500" ,"Prefill last request" ),totals ) 65cards = self .cards ({"state" :"idle" },None ,None ) 66self .assertEqual (cards ["speed" ], (None ,"Decode" )) 67self .assertEqual (cards ["prefill" ], (None ,"Prefill" )) 68 69 70@ unittest . skipUnless ( NODE , "node is needed to run the page's own code" ) 71class MonitorPage (unittest .TestCase ): 72def average (self ,rows ): 73source = function_source ((WEB / "monitor.js" ).read_text (encoding = "utf-8" ),"averageDecodeSpeed" ) 74return run_node (f" { source } \nconsole.log(JSON.stringify(averageDecodeSpeed( { json . dumps ( rows ) } )));" ) 75 76def test_it_is_token_weighted_over_the_finished_requests (self ): 77long_one = {"timings" : {"predicted_n" :19511 ,"predicted_ms" :386000 }} 78short_one = {"timings" : {"predicted_n" :11 ,"predicted_ms" :410 }} 79self .assertAlmostEqual (self .average ([long_one ,short_one ]), (19511 + 11 )/ (386410 / 1000 ),places = 6 ) 80self .assertGreater (self .average ([long_one ,short_one ]),50 ,"a plain mean of the two (about 38) would let the short one count as much as the long one" ) 81 82def test_requests_without_timings_or_with_one_token_are_left_out (self ): 83self .assertIsNone (self .average ([])) 84self .assertIsNone (self .average ([{}, {"timings" :None }, {"timings" : {"predicted_n" :1 ,"predicted_ms" :10 }}, {"timings" : {"predicted_n" :5 ,"predicted_ms" :0 }}, 85 {"timings" : {"predicted_n" :"9" ,"predicted_ms" :5 }}])) 86self .assertEqual (self .average ([{"timings" : {"predicted_n" :100 ,"predicted_ms" :2000 }}, {}]),50 ) 87 88def test_the_card_says_what_it_shows (self ): 89html = (WEB / "monitor.html" ).read_text (encoding = "utf-8" ) 90self .assertIn ("Average decode speed" ,html ) 91self .assertIn ("Run average" ,html ) 92self .assertNotIn ("Last decode speed" ,html ) 93js = (WEB / "monitor.js" ).read_text (encoding = "utf-8" ) 94self .assertIn ('text("speed", speed(averageDecodeSpeed(records.filter(r => !active(r)))))' ,js ) 95 96 97class AddedCodeIsDisplayOnly (unittest .TestCase ): 98"""What the patch added reads numbers the page already has and writes text with textContent: no request, no eval, no markup, no address.""" 99 100def test_nothing_but_arithmetic_and_text (self ): 101pieces = [cards_block ((WEB / "app.js" ).read_text (encoding = "utf-8" )),function_source ((WEB / "monitor.js" ).read_text (encoding = "utf-8" ),"averageDecodeSpeed" ), 102 (Path (__file__ ).resolve ().parents [1 ]/ "strata_cli" / "overview.py" ).read_text (encoding = "utf-8" )] 103pieces [2 ]= pieces [2 ][pieces [2 ].index ("def run_average_speed" ):pieces [2 ].index ("def _cards" )] 104forbidden = re .compile (r"\b(fetch|XMLHttpRequest|WebSocket|sendBeacon|eval|Function|import|require|innerHTML|insertAdjacentHTML|document\.write|" 105r"subprocess|socket|urllib|requests|os\.system|open)\s*\(|https?://|\.src\s*=|new Image" ) 106for piece in pieces : 107self .assertIsNone (forbidden .search (piece ),forbidden .search (piece )and forbidden .search (piece ).group (0 )) 108self .assertIn ("textContent" , (WEB / "monitor.js" ).read_text (encoding = "utf-8" )) 109 110 111if __name__ == "__main__" : 112unittest .main ()