okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
568127b7a
main
1"""The monitor's Overview (view 1): numbers from /metrics, the drawing, glyph fallbacks, and the monitor showing it.""" 2 3from __future__import annotations 4 5import asyncio 6import io 7import time 8import unittest 9 10from rich .console import Console 11 12from strata_cli import overview 13from strata_cli .monitor import MonitorApp 14 15GIB = 2 ** 30 16 17 18def metrics (state = "reading" ,** over ): 19now = time .time () 20hist = lambda base ,amp : [base + amp * ((i * 7 )% 5 )/ 4 for i in range (60 )]# noqa: E731 21m = {"time" :now , 22"engine" : {"model" :"IQ3_S" ,"max_context" :131072 ,"expert_slots" :1644 ,"experts" :5120 ,"expert_cache_mib" :3280 }, 23"live" : {"state" :state ,"queued" :0 ,"prompt_read" :35610 if state == "reading" else None ,"prompt_total" :36742 if state == "reading" else None , 24"prompt_tokens" :36742 ,"generated" :120 if state == "generating" else 0 ,"max_tokens" :4096 , 25"tok_s" :50.4 if state == "generating" else None ,"prefill_tok_s_mean" :820.0 }, 26"hardware" : {"gpu_util" :88 ,"gpu_mem_used" :11.2 * GIB ,"gpu_mem_total" :12 * GIB ,"gpu_temp" :54 ,"gpu_power" :114 ,"gpu_power_limit" :250 , 27"gpu_pcie_rx_mb" :18237 ,"gpu_pcie_gen" :4 ,"gpu_pcie_width" :16 ,"cpu" :14 ,"ram_used" :58.5 * GIB ,"ram_total" :63 * GIB , 28"disk_read_mb" :0.1 ,"disk_write_mb" :0.0 }, 29"hardware_static" : {"gpu_name" :"RTX 5070" ,"gpu_count" :1 ,"cores" :6 ,"threads" :12 }, 30"history" : {"tok_s" :hist (40 ,10 ),"gpu_util" :hist (80 ,10 ),"gpu_mem_used" : [11.2 * GIB ]* 60 ,"gpu_temp" : [54 ]* 60 , 31"gpu_power" :hist (110 ,10 ),"gpu_pcie_rx_mb" :hist (10000 ,9000 ),"cpu" :hist (10 ,8 ),"disk_read_mb" :hist (0 ,3 )}, 32"requests" : [{"id" :"a" ,"time" :now - 5 ,"duration_s" :429.8 ,"finish_reason" :"stop" ,"prompt_tokens" :17183 ,"reused" :0 , 33"output_tokens" :19511 ,"decode_ms" :386000 }, 34 {"id" :"b" ,"time" :now - 9 ,"duration_s" :4.0 ,"finish_reason" :"stop" ,"prompt_tokens" :626 ,"reused" :0 , 35"output_tokens" :11 ,"decode_ms" :410 }], 36"totals" : {"requests" :12 ,"prompt_tokens" :90000 ,"reused" :5000 ,"output_tokens" :40000 , 37"prompt_ms" :120000.0 ,"decode_ms" :1000000.0 }} 38m .update (over ) 39return m 40 41 42def draw (model ,width = 110 ,height = 30 ,** kw )-> str : 43c = Console (width = width + 2 ,record = True ,file = io .StringIO (),force_terminal = False ,legacy_windows = False ) 44c .overview .render (model ,width = width ,height = height ,connection = "http://127.0.0.1:8080" ,** kw )) 45return c .export_text () 46 47 48class AsciiLook (unittest .TestCase ): 49"""The ASCII look is pure ASCII: written to a stdout that cannot encode U+00B7 (cp852, cp874, cp932, ascii) it must not raise UnicodeEncodeError.""" 50 51def test_the_ascii_look_has_no_middle_dot (self ): 52for state in ("idle" ,"reading" ,"generating" ): 53text = draw (overview .build (metrics (state )),glyphs = "ascii" ) 54self .assertNotIn ("·" ,text ,state )# (the box lines are rich's: it swaps them for + - | on a stream that cannot encode them) 55self .assertIn ("·" ,draw (overview .build (metrics ("reading" )),glyphs = "unicode" ),"the Unicode look keeps it" ) 56 57def test_it_writes_to_strict_streams_of_the_legacy_code_pages (self ): 58from rich .console import Console as C 59for enc in ("cp437" ,"cp852" ,"cp874" ,"cp932" ,"ascii" ): 60raw = io .BytesIO () 61f = io .TextIOWrapper (raw ,encoding = enc ,errors = "strict" ) 62c = C (file = f ,width = 112 ,force_terminal = False ,legacy_windows = False ) 63for state in ("idle" ,"reading" ,"generating" ): 64c .overview .render (overview .build (metrics (state )),width = 110 ,height = 30 ,connection = "http://127.0.0.1:8080" ,glyphs = "ascii" )) 65f .flush () 66self .assertGreater (len (raw .getvalue ()),1000 ,enc ) 67 68 69class Build (unittest .TestCase ): 70def test_reading_state_and_progress (self ): 71m = overview .build (metrics ("reading" )) 72self .assertEqual (m ["state" ],"Reading" ) 73self .assertEqual (m ["progress" ], (35610.0 ,36742.0 )) 74self .assertEqual (m ["context" ], (36742.0 ,131072.0 )) 75self .assertEqual (m ["speed" ][:2 ], (820.0 ,"reading the prompt" )) 76 77def test_generating_uses_the_live_rate_and_prompt_plus_generated_for_context (self ): 78m = overview .build (metrics ("generating" )) 79self .assertEqual (m ["state" ],"Generating" ) 80self .assertEqual (m ["speed" ][:2 ], (50.4 ,"now" )) 81self .assertEqual (m ["context" ][0 ],36742 + 120 ) 82self .assertEqual (m ["progress" ], (120.0 ,4096.0 )) 83 84def test_idle_shows_the_run_average (self ): 85m = overview .build (metrics ("idle" )) 86self .assertEqual (m ["state" ],"Idle" ) 87self .assertEqual (m ["speed" ][1 ],"average of the run" ) 88self .assertAlmostEqual (m ["speed" ][0 ],40.0 ,places = 1 )# totals: 40000 tokens in 1000 s, not the last request's 50.5 89self .assertEqual (m ["context" ][0 ],17183 + 19511 ) 90self .assertEqual (m ["progress" ], (None ,None )) 91 92def test_the_run_average_is_token_weighted_and_never_invented (self ): 93"""Community patch (keinebenutzer/STRATA-average-patch, MIT): the idle tile is every token over the run's decode time, from the server's totals.""" 94self .assertEqual (overview .run_average_speed ({"totals" : {"output_tokens" :40000 ,"decode_ms" :1000000.0 }}),40.0 ) 95# a long request and a short one: the long one counts for what it is (a plain mean of the two would be 30.3) 96self .assertEqual (overview .run_average_speed ({"totals" : {"output_tokens" :19522 ,"decode_ms" :386410.0 }}),50.5 ) 97for totals in (None , {}, {"output_tokens" :0 ,"decode_ms" :100.0 }, {"output_tokens" :1 ,"decode_ms" :100.0 }, {"output_tokens" :500 ,"decode_ms" :0 }, 98 {"output_tokens" :500 }, {"decode_ms" :500.0 }, {"output_tokens" :True ,"decode_ms" :5.0 }, {"output_tokens" :"9" ,"decode_ms" :3.0 }, 99 {"output_tokens" :float ("nan" ),"decode_ms" :3.0 }): 100self .assertIsNone (overview .run_average_speed ({"totals" :totals }),totals ) 101self .assertIsNone (overview .run_average_speed ({})) 102 103def test_without_totals_idle_falls_back_to_the_last_request (self ): 104m = metrics ("idle" ) 105del m ["totals" ] 106built = overview .build (m ) 107self .assertEqual (built ["speed" ][1 ],"last request" ) 108self .assertAlmostEqual (built ["speed" ][0 ],50.5 ,places = 1 ) 109m = metrics ("idle" ,totals = {"requests" :0 ,"output_tokens" :0 ,"decode_ms" :0.0 }) 110self .assertEqual (overview .build (m )["speed" ][1 ],"last request" ,"an empty run is not an average of zero" ) 111 112def test_live_values_stay_live (self ): 113"""Only the idle value is an average: generating and reading are what they were.""" 114self .assertEqual (overview .build (metrics ("generating" ))["speed" ][:2 ], (50.4 ,"now" )) 115self .assertEqual (overview .build (metrics ("reading" ))["speed" ][:2 ], (820.0 ,"reading the prompt" )) 116self .assertIn ("average of the run" ,draw (overview .build (metrics ("idle" )))) 117 118def test_queued_and_error (self ): 119self .assertEqual (overview .build (metrics ("idle" ,live = {"state" :"idle" ,"queued" :3 }))["state" ],"Queued" ) 120self .assertEqual (overview .build (metrics ("idle" ,engine = {"model" :"x" ,"error" :"boom" }))["state" ],"Error" ) 121 122def test_hardware_in_gb (self ): 123m = overview .build (metrics ()) 124self .assertAlmostEqual (m ["gpu" ]["vram_used" ],11.2 ) 125self .assertEqual (m ["gpu" ]["vram_total" ],12.0 ) 126self .assertAlmostEqual (m ["ram" ][0 ],58.5 ) 127self .assertEqual (m ["experts" ], {"slots" :1644.0 ,"total" :5120.0 ,"gb" :3280 / 1024.0 }) 128 129def test_missing_numbers_stay_missing (self ): 130m = overview .build ({"live" : {"state" :"idle" },"engine" : {},"hardware" : {},"requests" : []}) 131self .assertIsNone (m ["gpu" ]["util" ]) 132self .assertIsNone (m ["speed" ][0 ]) 133text = draw (m ) 134self .assertIn ("-- tok/s" ,text ) 135self .assertIn ("No requests yet" ,text ) 136self .assertNotIn ("0 %" ,text .replace ("-- %" ,"" ))# no invented zero 137 138def test_a_server_without_metrics_gives_none (self ): 139self .assertIsNone (overview .build (None )) 140self .assertIsNone (overview .build ({"engine" : {}})) 141 142 143class Draw (unittest .TestCase ): 144def test_the_approved_layout (self ): 145text = draw (overview .build (metrics ("reading" )),connect = True ) 146for part in ("STRATA Overview" ,"IQ3_S 128K" ,"Reading prompt · 97%" ,"[LIVE]" ,"[1 Overview]" ,"7 Connect" , 147"Model state" ,"[Reading]" ,"35,610 / 36,742 tokens · 97%" , 148"Speed" ,"GPU load" ,"VRAM" ,"GPU temp" ,"Power" ,"PCIe" ,"CPU" ,"Disk read" , 149"88 %" ,"RTX 5070" ,"11.2 / 12 GB" ,"1,644 experts cached" ,"54 °C" ,"114 W" ,"of 250 W limit" ,"Gen4 x16" , 150"to GPU 18,237 MB/s" ,"6 cores · 12 threads" ,"0.1 MB/s" ,"write 0.0 MB/s" , 151"Context fill" ,"36K / 128K" ,"Experts in VRAM" ,"1,644 · 3.2 GB" ,"System RAM" ,"58.5 / 63 GB" , 152"Recent requests" ,"TIME" ,"STATUS" ,"PROMPT" ,"REUSED" ,"OUTPUT" ,"TOK/S" ,"DURATION" ,"17,183" ,"19,511" ,"429.8 s" , 153"1-7 views" ,"b open in browser" ,"q quit" ): 154self .assertIn (part ,text ,part ) 155 156def test_without_connect_the_hint_says_six_views (self ): 157text = draw (overview .build (metrics ()),connect = False ) 158self .assertIn ("1-6 views" ,text ) 159self .assertNotIn ("7 Connect" ,text ) 160 161def test_ascii_mode_has_no_glyphs_the_classic_windows_console_font_lacks (self ): 162text = draw (overview .build (metrics ()),glyphs = "ascii" ,color = False ) 163for bad in "▁▂▃▄▅▆▇█░╭╮╰╯✓●" : 164self .assertNotIn (bad ,text ,bad ) 165self .assertIn ("#" ,text ) 166self .assertIn ("54 C" ,text ) 167 168def test_fits_the_width_it_is_given (self ): 169for w in (80 ,100 ,120 ): 170text = draw (overview .build (metrics ()),width = w - 2 ) 171self .assertTrue (all (len (line )<= w for line in text .splitlines ()),w ) 172 173def test_spark (self ): 174self .assertEqual (len (overview .spark ([1 ,2 ,3 ],8 ,"unicode" )),8 ) 175self .assertEqual (overview .spark ([None ,None ],4 ,"unicode" )," " ) 176self .assertEqual (overview .spark ([0 ,100 ],2 ,"unicode" ,lo = 0 ,hi = 100 ),"▁█" ) 177self .assertEqual (overview .spark ([0 ,100 ],2 ,"ascii" ,lo = 0 ,hi = 100 ),".@" ) 178 179 180class Source : 181root = "http://127.0.0.1:8095" 182 183def __init__ (self ,raw ): 184self .raw = raw 185self .base_url = self .root 186 187def get (self ,path ): 188if path == "/metrics" : 189return self .raw 190raise AssertionError (path ) 191 192def snapshot (self ): 193return {"source" :"fixture" ,"sampled_at" :time .time (),"schema_version" :1 ,"instance" : {"id" :"x" }, 194"model" : {"id" :"IQ3_S" ,"loaded" :True },"work" : {},"rates" : {},"devices" : [],"recent" : [],"totals" : {}, 195"topology" : {},"quality" : {}} 196 197 198class InTheMonitor (unittest .TestCase ): 199def test_view_one_is_the_new_overview_and_the_others_stay (self ): 200async def go (): 201app = MonitorApp (Source (metrics ("generating" )),None ,interval = 30 ) 202async with app .run_test (size = (120 ,36 ))as pilot : 203await pilot .pause (0.5 ) 204shown = "\n" .join (s .text for s in app .screen ._compositor .render_strips ()) 205self .assertIn ("Model state" ,shown ) 206self .assertIn ("Generating" ,shown ) 207await pilot .press ("2" ) 208await pilot .pause (0.2 ) 209shown = "\n" .join (s .text for s in app .screen ._compositor .render_strips ()) 210self .assertNotIn ("Model state" ,shown ) 211self .assertIn ("Serving" ,shown ) 212asyncio .run (go ()) 213 214def test_an_older_server_without_metrics_keeps_the_earlier_overview (self ): 215class Old (Source ): 216def get (self ,path ): 217from strata_cli .client import ClientError 218raise ClientError ("not found" ,http_status = 404 ) 219 220async def go (): 221app = MonitorApp (Old (None ),None ,interval = 30 ) 222async with app .run_test (size = (120 ,36 ))as pilot : 223await pilot .pause (0.5 ) 224shown = "\n" .join (s .text for s in app .screen ._compositor .render_strips ()) 225self .assertNotIn ("Model state" ,shown ) 226self .assertIn ("MONITOR" ,shown ) 227asyncio .run (go ()) 228 229 230if __name__ == "__main__" : 231unittest .main ()