okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd0e3766a
main
1"""Rich, read-only overview for the interactive monitor. 2 3The layout follows YASD's one-screen dashboard idea while using Strata's 4bounded telemetry contract and theme. No server text is treated as markup. 5""" 6 7from __future__import annotations 8 9import math 10import time 11from collections import deque 12from typing import Any 13 14from rich import box 15from rich .align import Align 16from rich .console import Group 17from rich .panel import Panel 18from rich .table import Table 19from rich .text import Text 20 21from strata_cli import nav 22from strata_cli .client import complete_slots 23from strata_cli .render import (_queue_wait ,activity_continuity_notice ,activity_label ,display_width , 24field ,group_occupancy ,number ,safe ) 25 26 27WORK_SAMPLE_MAX_AGE_S = 5.0 28 29 30_ASCII_BOXES = False 31 32 33def _rounded (): 34"""Panel corners: rounded where the font has them, square (Consolas has these) in the classic Windows console.""" 35return box .SQUARE if _ASCII_BOXES else box .ROUNDED 36 37 38def set_ascii_boxes (on :bool )-> None : 39global _ASCII_BOXES 40_ASCII_BOXES = bool (on ) 41 42 43def _current_sample (row :dict ,age_key :str )-> bool : 44"""A retained engine sample stops representing current work after five seconds.""" 45age = row .get (age_key ) 46return (isinstance (age , (int ,float ))and not isinstance (age ,bool )and 47math .isfinite (age )and 0 <= age <= WORK_SAMPLE_MAX_AGE_S ) 48 49 50def _current_batch_value (row :dict ,key :str )-> Any : 51return row .get (key )if _current_sample (row ,"batch_sample_age_s" )else None 52 53 54class MonitorHistory : 55"""Small display-only device history, reset when the server changes.""" 56 57def __init__ (self ,limit :int = 32 ): 58self .limit = limit 59self .instance :tuple [str ,str ]| None = None 60self .device_util :dict [int ,deque [float | None ]]= {} 61self .device_vram :dict [int ,deque [float | None ]]= {} 62self .output_rate :deque [float | None ]= deque (maxlen = limit ) 63self .prefill_rate :deque [float | None ]= deque (maxlen = limit ) 64self .answer_rate :deque [float | None ]= deque (maxlen = limit ) 65self .batch_rows :deque [float | None ]= deque (maxlen = limit ) 66self .pre_admit :deque [float | None ]= deque (maxlen = limit ) 67self .replica_batch_rows :dict [int ,deque [float | None ]]= {} 68 69@staticmethod 70def _sample (value :Any )-> float | None : 71return (float (value )if isinstance (value , (int ,float ))and not isinstance (value ,bool ) 72and math .isfinite (value )and 0 <= value <= 1_000_000_000 else None ) 73 74def gap (self )-> None : 75"""Keep an outage visible between samples from the same instance.""" 76self .output_rate .append (None ) 77self .prefill_rate .append (None ) 78self .answer_rate .append (None ) 79self .batch_rows .append (None ) 80self .pre_admit .append (None ) 81for series in (* self .device_util .values (),* self .device_vram .values (), 82* self .replica_batch_rows .values ()): 83series .append (None ) 84 85def add (self ,snapshot :dict ,instance :tuple [str ,str ]| None )-> None : 86if instance != self .instance : 87self .device_util .clear () 88self .device_vram .clear () 89self .output_rate .clear () 90self .prefill_rate .clear () 91self .answer_rate .clear () 92self .batch_rows .clear () 93self .pre_admit .clear () 94self .replica_batch_rows .clear () 95self .instance = instance 96value = (snapshot .get ("rates" )or {}).get ("aggregate_output_tok_s" ) 97self .output_rate .append (self ._sample (value )) 98self .prefill_rate .append (self ._sample ((snapshot .get ("rates" )or {}).get ("prefill_tok_s" ))) 99self .answer_rate .append (self ._sample ((snapshot .get ("rates" )or {}).get ("answer_tok_s" ))) 100work = snapshot .get ("work" )or {} 101self .batch_rows .append (self ._sample (_current_batch_value (work ,"effective_rows_window" ))) 102self .pre_admit .append (self ._sample (work .get ("queued" ))) 103replica_rows = work .get ("replica_batches" )or [] 104reported :dict [int ,dict ]= {} 105ambiguous :set [int ]= set () 106for row in (replica_rows if isinstance (replica_rows ,list )else [])[:16 ]: 107if not isinstance (row ,dict ): 108continue 109replica = row .get ("replica" ) 110if type (replica )is not int or not 0 <= replica < 16 : 111continue 112if replica in reported : 113ambiguous .add (replica ) 114reported [replica ]= row 115topology = snapshot .get ("topology" )or {} 116configured = {row .get ("replica" )for row in (topology .get ("replica_devices" )or [])[:16 ] 117if isinstance (row ,dict )and type (row .get ("replica" ))is int and 1180 <= row ["replica" ]< 16 } 119current_replicas = configured or set (reported ) 120self .replica_batch_rows = { 121replica :self .replica_batch_rows .get (replica ,deque (maxlen = self .limit )) 122for replica in current_replicas 123 } 124for replica ,series in self .replica_batch_rows .items (): 125row = reported .get (replica , {})if replica not in ambiguous else {} 126series .append (self ._sample (_current_batch_value (row ,"effective_rows_window" ))) 127reported :dict [int ,dict ]= {} 128ambiguous :set [int ]= set () 129devices = snapshot .get ("devices" ) 130for row in (devices if isinstance (devices ,list )else [])[:16 ]: 131if not isinstance (row ,dict ): 132continue 133index = row .get ("index" ) 134if type (index )is not int or not 0 <= index <= 65535 : 135continue 136if index in reported : 137ambiguous .add (index ) 138reported [index ]= row 139topology = snapshot .get ("topology" )or {} 140selected = topology .get ("selected_devices" ) 141selected = selected if isinstance (selected ,list )else [] 142indices = list (dict .fromkeys (index for index in selected [:16 ] 143if type (index )is int and 0 <= index <= 65535 )) 144if not indices : 145indices = list (reported ) 146self .device_util = {index :self .device_util .get (index ,deque (maxlen = self .limit )) 147for index in indices } 148self .device_vram = {index :self .device_vram .get (index ,deque (maxlen = self .limit )) 149for index in indices } 150for index in indices : 151row = reported .get (index )if index not in ambiguous else None 152value = row .get ("util" )if row else None 153if not isinstance (value , (int ,float ))or isinstance (value ,bool )or not math .isfinite (value ): 154value = None 155self .device_util [index ].append (value ) 156used ,total = (row .get ("mem_used" ),row .get ("mem_total" ))if row else (None ,None ) 157if (not all (isinstance (item , (int ,float ))and not isinstance (item ,bool )and 158math .isfinite (item )for item in (used ,total ))or 159total <= 0 or used < 0 or used > total ): 160vram = None 161else : 162vram = 100.0 * (used / total ) 163self .device_vram [index ].append (vram ) 164 165 166def _spark (values :Any ,glyphs :str ,width :int = 8 )-> str : 167samples = list (values or [])[- (width * 2 if glyphs == "braille" else width ):] 168if not samples or all (value is None for value in samples ): 169return "--" 170if glyphs != "braille" : 171ramp = ".:-=+*#@" if glyphs == "ascii" else "▁▂▃▄▅▆▇█" 172return "" .join (" " if value is None else ramp [min (7 ,max (0 ,int (value / 100 * 7 )))] 173for value in samples ) 174# Braille has two columns and four rows per cell. A cell represents two 175# consecutive utilization samples, with the newest sample at the right. 176left ,right = (0x40 ,0x04 ,0x02 ,0x01 ), (0x80 ,0x20 ,0x10 ,0x08 ) 177if len (samples )% 2 : 178samples .insert (0 ,None ) 179graph = [] 180for first ,second in zip (samples [::2 ],samples [1 ::2 ]): 181bits = 0 182for value ,dots in ((first ,left ), (second ,right )): 183if value is not None : 184level = max (1 ,min (4 ,round (value / 100 * 4 ))) 185bits |= sum (dots [:level ]) 186graph .append (chr (0x2800 + bits )if bits else " " ) 187return "" .join (graph ) 188 189 190def _output_trend (values :Any ,glyphs :str ,compact :bool )-> str : 191width = 6 if compact else 8 192samples = list (values or [])[- width * (2 if glyphs == "braille" else 1 ):] 193valid = [value for value in samples if value is not None ] 194label = "Output" if compact else "Output trend" 195if len (valid )< 2 or samples [- 1 ]is None : 196return f" { label } --" 197low ,high = min (valid ),max (valid ) 198scaled = [None if value is None else 1990 if high == 0 else 50 if high == low else 100 * (value - low )/ (high - low ) 200for value in samples ] 201graph = _spark (scaled ,glyphs ,width ) 202span = f" { low :.3g } " if high == low else f" { low :.3g } - { high :.3g } " 203return f" { label } { graph } { span } tok/s" 204 205 206def _work_trend (values :Any ,glyphs :str ,label :str ,unit :str ,digits :int = 0 )-> str | None : 207"""Show the range of displayed samples; never turn missing work into zero.""" 208width = 8 209samples = list (values or [])[- width * (2 if glyphs == "braille" else 1 ):] 210valid = [value for value in samples if value is not None ] 211if len (valid )< 2 or samples [- 1 ]is None : 212return None 213low ,high = min (valid ),max (valid ) 214scaled = [None if value is None else 2150 if high == 0 else 50 if high == low else 100 * (value - low )/ (high - low ) 216for value in samples ] 217span = number (low ,"" ,digits ) 218if high != low : 219span += "-" + number (high ,"" ,digits ) 220return f" { label } { _spark ( scaled , glyphs , width ) } { span } { unit } " 221 222 223def _panel (lines :list [str ],title :str ,accent :str ,* ,color :bool )-> Panel : 224body = Text ("\n" .join (lines ),no_wrap = True ,overflow = "crop" ) 225if color : 226body .highlight_regex (r"\b(?:READY|LIVE|GENERATING|READING)\b" ,accent ) 227body .highlight_regex (r"\b(?:STALE|FROZEN|QUEUED|DRAINING)\b" ,"yellow" ) 228body .highlight_regex (r"\b(?:DISCONNECTED|INCOMPATIBLE|REJECTED|AUTH REQUIRED)\b" ,"red" ) 229body .highlight_regex (r"[\u2800-\u28ff▁▂▃▄▅▆▇█]+" ,accent ) 230return Panel (body ,title = Text (title ,style = f"bold { accent } " if color else "bold" ), 231border_style = "dim" if color else "" ,box = _rounded (),padding = (0 ,1 )) 232 233 234def _columns (left :list [Panel ],right :list [Panel ])-> Table : 235"""Keep the YASD-style metric stack beside hardware and request activity.""" 236grid = Table .grid (expand = True ,padding = (0 ,1 )) 237grid .add_column (ratio = 3 ) 238grid .add_column (ratio = 4 ) 239grid .add_row (Group (* left ),Group (* right )) 240return grid 241 242 243def _state (snapshot :dict ,connection_state :str ,frozen :bool )-> tuple [str ,bool ]: 244age = _age (snapshot ) 245telemetry = (snapshot .get ("quality" )or {}).get ("telemetry" ) 246state = ("NO TELEMETRY" if telemetry == "unavailable" and connection_state == "connected" else 247 {"connected" :"LIVE" ,"connecting" :"CONNECTING" ,"stale" :"STALE" , 248"disconnected" :"DISCONNECTED" ,"auth_required" :"AUTH REQUIRED" , 249"incompatible" :"INCOMPATIBLE" ,"telemetry_unavailable" :"NO TELEMETRY" } 250 .get (connection_state ,"STALE" )) 251if state == "LIVE" and (age is None or age > 5 or age < - 5 ): 252state = "STALE" 253if state == "LIVE" and (snapshot .get ("model" )or {}).get ("loaded" )is False : 254state = "SLEEPING" 255return (f"FROZEN / { state } " if frozen else state ),state == "LIVE" 256 257 258def _prompt_progress (work :dict ,compact :bool ,glyphs :str )-> str | None : 259for row in work .get ("requests" )or []: 260if row .get ("state" )!= "reading" : 261continue 262done ,total = row .get ("prompt_read" ),row .get ("prompt_tokens" ) 263if any (not isinstance (value , (int ,float ))or isinstance (value ,bool )or 264not math .isfinite (value )for value in (done ,total ))or total <= 0 or done < 0 : 265continue 266size = 6 if compact else 8 267filled = min (size ,max (0 ,round (done / total * size ))) 268full ,empty = ("#" ,"." )if glyphs == "ascii" else ("█" ,"░" ) 269prefix = "Read" if compact else f"Reading { safe ( row . get ( 'id' ), 11 ) } " 270return f" { prefix } { number ( done ) } / { number ( total ) } [ { full * filled } { empty * ( size - filled ) } ]" 271return None 272 273 274def _age (snapshot :dict )-> float | None : 275sampled = snapshot .get ("sampled_at" ) 276if not isinstance (sampled , (int ,float ))or isinstance (sampled ,bool )or not math .isfinite (sampled ): 277return None 278return time .time ()- sampled 279 280 281def _gib (value :Any )-> str : 282if not isinstance (value , (int ,float ))or isinstance (value ,bool ): 283return "--" 284return number (value / 2 ** 30 ,"" ,1 ) 285 286 287def _groups (work :dict ,compact :bool ,glyphs :str )-> list [str ]: 288occupancy = group_occupancy (work ) 289if occupancy is None : 290return ["Group occupancy --" ] 291owner_sets :dict [int ,set [int | None ]]= {} 292for row in complete_slots (work )or []: 293group = row .get ("group" ) 294if type (group )is int : 295replica = row .get ("replica" ) 296owner_sets .setdefault (group ,set ()).add (replica if type (replica )is int else None ) 297owners = {group :next (iter (values ))for group ,values in owner_sets .items ()if len (values )== 1 } 298def label (group :int )-> str : 299replica = owners .get (group ) 300return f"R { replica } G { group } " if replica is not None else f"G { group } " 301labels = [f" { label ( group ) } { busy } / { total } " 302for group , (busy ,total )in sorted (occupancy .items ())] 303if compact : 304lines = [" " .join (labels [:2 ])," " .join (labels [2 :4 ])]if len (labels )> 2 else [" " .join (labels )] 305if len (labels )> 4 : 306lines .append (f"+ { len ( labels ) - 4 } groups; press 2" ) 307return lines 308full ,empty = ("#" ,"." )if glyphs == "ascii" else ("█" ,"░" ) 309lines = ["Pipeline groups · occupied slots" if glyphs != "ascii" else "Pipeline groups / occupied slots" ] 310for group , (busy ,total )in sorted (occupancy .items ())[:5 ]: 311bar = full * min (busy ,8 )+ empty * min (max (0 ,total - busy ),8 ) 312lines .append (f" { label ( group ):<6 } { bar } { busy } / { total } slots" ) 313if len (occupancy )> 5 : 314lines .append (f"+ { len ( occupancy ) - 5 } groups; press 2" ) 315return lines 316 317 318def _replica_batch_line (work :dict ,compact :bool )-> str : 319"""Each replica reports its own batch window; there is no cross-replica average.""" 320rows = sorted (work .get ("replica_batches" )or [],key = lambda row :row ["replica" ]) 321if not rows : 322return "Batch rows -- across replicas" if compact else "Rows/window -- across replicas" 323shown = rows [:2 ] 324if compact : 325text = "Proc/win " + " " .join ( 326f"R { row [ 'replica' ] } { number ( _current_batch_value ( row , 'effective_rows_window' ), '' , 1 ) } " for row in shown ) 327else : 328text = "Rows/win p/a " + " " .join ( 329f"R { row [ 'replica' ] } { number ( _current_batch_value ( row , 'effective_rows_window' ), '' , 1 ) } /" 330f" { number ( _current_batch_value ( row , 'batch_active_rows_window' ), '' , 1 ) } " for row in shown ) 331return text + (f" + { len ( rows ) - 2 } " if len (rows )> 2 else "" ) 332 333 334def _slot_phases (work :dict ,compact :bool )-> str | None : 335"""Summarize slot states only when the complete effective slot set is present.""" 336slots = complete_slots (work ) 337if slots is None : 338return None 339counts = {"reading" :0 ,"decoding" :0 ,"idle" :0 } 340for row in slots : 341counts [row ["state" ]]+= 1 342prefix = "Slot phases" if not compact else "Phases" 343return (f" { prefix } read { counts [ 'reading' ] } decode { counts [ 'decoding' ] } " 344f"idle { counts [ 'idle' ] } " ) 345 346 347def _hardware (snapshot :dict ,history :MonitorHistory ,glyphs :str ,compact :bool )-> list [str ]: 348devices = snapshot .get ("devices" )or [] 349topology = snapshot .get ("topology" )or {} 350selected = [index for index in topology .get ("selected_devices" )or [] 351if type (index )is int and index >= 0 ] 352selected = list (dict .fromkeys (selected )) 353if selected : 354reported = {} 355ambiguous = set () 356for row in devices : 357index = row .get ("index" ) 358if type (index )is not int or index < 0 : 359continue 360if index in reported : 361ambiguous .add (index ) 362reported [index ]= row 363rows = [(reported [index ],True )if index in reported and index not in ambiguous 364else ({"index" :index },False )for index in selected ] 365else : 366rows = [(row ,True )for row in devices ] 367if not rows : 368return ["Per-device readings unavailable" ] 369stages = (topology .get ("stages" )or [])if topology .get ("resolved" )is True else [] 370mapped = {row .get ("device_index" ):row .get ("stage" )for row in stages } 371replica_map = {device :row .get ("replica" )for row in topology .get ("replica_devices" )or [] 372for device in row .get ("devices" )or []} 373replica_stages :dict [int ,list [tuple [int ,int ]]]= {} 374for entry in topology .get ("replica_stages" )or []: 375replica = entry .get ("replica" ) 376for stage in entry .get ("stages" )or []: 377device = stage .get ("device_index" ) 378stage_id = stage .get ("stage" ) 379if (type (device )is int and type (replica )is int and type (stage_id )is int and 3800 <= replica < 16 and 0 <= stage_id < 16 and replica_map .get (device )== replica ): 381replica_stages .setdefault (device , []).append ((replica ,stage_id )) 382lines = [] 383for row ,sensor_present in rows [:4 ]: 384index = row .get ("index" ) 385label = f"GPU { number ( index ) } " 386local_stages = replica_stages .get (index )or [] 387stage = (f"R { local_stages [ 0 ][ 0 ] } /S { local_stages [ 0 ][ 1 ] } " if len (local_stages )== 1 else 388f"R { number ( replica_map [ index ]) } " if index in replica_map else 389f"S { number ( mapped [ index ]) } " if index in mapped else "S--" ) 390memory = field (f" { _gib ( row . get ( 'mem_used' )) } / { _gib ( row . get ( 'mem_total' )) } G" ,13 ) 391graph = (_spark (history .device_util .get (index ),glyphs ,6 if compact else 8 ) 392if sensor_present else "--" ) 393vram_graph = (_spark (history .device_vram .get (index ),glyphs ,6 ) 394if sensor_present else "--" ) 395if compact : 396lines .append (f" { label :<5 } { stage :<5 } { memory :<11 } { number ( row . get ( 'util' ), '%' ):>4 } { graph } " ) 397else : 398lines .append (f" { label :<5 } { stage :<5 } { field ( row . get ( 'name' ), 18 ) } { memory } vram { vram_graph } " ) 399lines .append (f" load { number ( row . get ( 'util' ), '%' ):>4 } temp { number ( row . get ( 'temp' ), 'C' ):>4 } " 400f"power { number ( row . get ( 'power' ), 'W' ):>5 } { graph } " ) 401if len (rows )> 4 : 402lines .append (f"+ { len ( rows ) - 4 } { 'selected ' if selected else '' } devices; press 5 for all" ) 403return lines 404 405 406def _request_lines (snapshot :dict ,compact :bool ,filter_text :str ,* ,tall :bool = False )-> list [str ]: 407work = snapshot .get ("work" )or {} 408needle = filter_text .lower () 409live = [row for row in (work .get ("requests" )or [])if not needle or 410needle in (safe (row .get ("id" ))+ safe (row .get ("state" ))).lower ()] 411lines = [] 412limit = 2 if compact else 12 if tall else 4 413queued = [row for row in live if row .get ("state" )== "queued" ] 414admitted = [row for row in live if row .get ("slot" )is None and row .get ("state" )!= "queued" ] 415running = [row for row in live if row .get ("slot" )is not None ] 416preferred = ((queued [:1 ]+ running [:1 ])if compact else 417 (queued [:2 ]+ admitted [:1 ]+ running [:1 ])) 418chosen = [] 419seen = set () 420for row in preferred + live : 421if id (row )not in seen : 422chosen .append (row ) 423seen .add (id (row )) 424if len (chosen )== limit : 425break 426for row in chosen : 427wait = _queue_wait (row ,snapshot .get ("sampled_at" )) 428state = safe (row .get ("state" ),9 ) 429state_column = field (row .get ("state" ),7 if compact else 9 ) 430work_label = (f"wait { number ( wait , 's' , 1 ) } " if state == "queued" else 431"awaiting slot" if row .get ("slot" )is None else 432f"read { number ( row . get ( 'prompt_read' )) } " if state == "reading" else 433f"out { number ( row . get ( 'generated' )) } " ) 434replica = f"r { row [ 'replica' ] } " if type (row .get ("replica" ))is int else "" 435if compact : 436if state == "queued" : 437lines .append (f" { field ( row . get ( 'id' ), 9 ) } { state_column } { work_label } " ) 438else : 439lines .append (f" { field ( row . get ( 'id' ), 9 ) } { state_column } " 440f" { replica } s { number ( row . get ( 'slot' )) } g { number ( row . get ( 'group' )) } { work_label } " ) 441else : 442lines .append (f" { field ( row . get ( 'id' ), 12 ) } { state_column } " 443f" { replica } s { number ( row . get ( 'slot' )) } g { number ( row . get ( 'group' )) } { work_label } " ) 444if len (live )> limit : 445lines .append (f"+ { len ( live ) - limit } more; press 3 for all" ) 446if not lines : 447slots = [row for row in work .get ("slots" )or []if row .get ("state" )!= "idle" ] 448if slots : 449lines = [f" { ( 'R' + str ( row [ 'replica' ]) + ' ' ) if type ( row . get ( 'replica' )) is int else '' } " 450f"Slot { number ( row . get ( 'slot' )) } G { number ( row . get ( 'group' )) } " 451f" { safe ( row . get ( 'state' ), 12 ) } { number ( row . get ( 'generated' )) } out" 452for row in slots [:limit ]] 453lines .insert (0 ,"Request identities unavailable" ) 454else : 455lines = ["No active requests" ] 456return lines 457 458 459def _activity (snapshot :dict ,compact :bool ,filter_text :str )-> list [str ]: 460activity = snapshot .get ("activity" )or {} 461if not activity .get ("available" ): 462return ["Request activity unavailable" ] 463notice = activity_continuity_notice (snapshot ) 464needle = filter_text .lower () 465rows = [row for row in activity .get ("events" )or []if isinstance (row ,dict )and 466 (not needle or needle in (safe (row .get ("event" ))+ safe (row .get ("request_id" ))).lower ())] 467if not rows : 468return ([notice ]if notice else [])+ ["No matching transitions" if needle else "No recent transitions" ] 469if compact : 470return ([notice ]if notice else [])+ [f" { field ( row . get ( 'request_id' ), 10 ) } " 471f" { safe ( row . get ( 'event' ), 18 ) } " for row in rows [- (1 if notice else 2 ):]] 472return ([notice ]if notice else [])+ [activity_label (row ,48 )for row in rows [- (3 if notice else 4 ):]] 473 474 475_DIGITS = { 476"0" : (" ███ " ,"█ █" ,"█ █" ,"█ █" ," ███ " ), 477"1" : (" █ " ," ██ " ," █ " ," █ " ," ███ " ), 478"2" : (" ███ " ,"█ █" ," █ " ," █ " ,"█████" ), 479"3" : ("████ " ," █" ," ███ " ," █" ,"████ " ), 480"4" : ("█ █" ,"█ █" ,"█████" ," █" ," █" ), 481"5" : ("█████" ,"█ " ,"████ " ," █" ,"████ " ), 482"6" : (" ███ " ,"█ " ,"████ " ,"█ █" ," ███ " ), 483"7" : ("█████" ," █" ," █ " ," █ " ," █ " ), 484"8" : (" ███ " ,"█ █" ," ███ " ,"█ █" ," ███ " ), 485"9" : (" ███ " ,"█ █" ," ████" ," █" ," ███ " ), 486"." : (" " ," " ," " ,"██" ,"██" ), 487"," : (" " ," " ," " ," ██" ," █ " ), 488"-" : (" " ," " ,"█████" ," " ," " ), 489} 490 491 492def _big_rate (value :Any ,color :str ,glyphs :str )-> list [Text ]: 493"""Legible five-row numerals; the exact value is repeated in plain text.""" 494label = number (value ,"" ,1 )if value is not None else "--" 495if glyphs == "ascii" : 496return [Text (label + " tok/s" ,style = f"bold { color } " )] 497if len (label )> 9 : 498return [Text (label + " tok/s" ,style = f"bold { color } " )] 499return [Text (" " .join (_DIGITS .get (char , (" " ,)* 5 )[row ] 500for char in label ),style = f"bold { color } " ,no_wrap = True ) 501for row in range (5 )] 502 503 504def _meter (value :Any ,total :Any ,size :int ,glyphs :str )-> str : 505valid = (all (isinstance (item , (int ,float ))and not isinstance (item ,bool )and 506math .isfinite (item )for item in (value ,total ))and total > 0 and 0 <= value <= total ) 507if not valid : 508return "[" + ("?" * size )+ "]" 509filled = max (0 ,min (size ,round (value / total * size ))) 510on ,off = ("#" ,"." )if glyphs == "ascii" else ("█" ,"░" ) 511return "[" + on * filled + off * (size - filled )+ "]" 512 513 514def _visual_panel (lines :list [Text ],title :str ,accent :str ,color :bool , 515height :int | None = None )-> Panel : 516return Panel (Group (* lines ),title = Text (title ,style = f"bold { accent } " if color else "bold" ), 517border_style = "dim" if color else "" ,box = box .SQUARE ,padding = (0 ,1 ), 518height = height ) 519 520 521def _visual_pair (left :Panel ,right :Panel ,left_ratio :int = 3 ,right_ratio :int = 4 )-> Table : 522grid = Table .grid (expand = True ,padding = (0 ,1 )) 523grid .add_column (ratio = left_ratio ) 524grid .add_column (ratio = right_ratio ) 525grid .add_row (left ,right ) 526return grid 527 528 529def _visual_overview (snapshot :dict ,history :MonitorHistory ,* ,width :int ,height :int , 530header :Panel ,footer :Text ,live :bool ,glyphs :str ,color :bool , 531theme :str ,filter_text :str )-> Group : 532"""Wide monitor: rate, cards, context, slot concurrency and live requests.""" 533cyan = ("#087b9a" if theme == "light" else "#22d3ee" )if color else "default" 534green = ("#0c8a60" if theme == "light" else "#34d399" )if color else "default" 535amber = ("#946000" if theme == "light" else "#fbbf24" )if color else "default" 536violet = ("#7842af" if theme == "light" else "#a78bfa" )if color else "default" 537dim = "dim" if color else "" 538model ,work ,rates = (snapshot .get ("model" )or {},snapshot .get ("work" )or {}, 539snapshot .get ("rates" )or {}) 540topology = snapshot .get ("topology" )or {} 541slots = complete_slots (work ) 542output = rates .get ("aggregate_output_tok_s" )if live else None 543prefill = rates .get ("prefill_tok_s" )if live else None 544answer = rates .get ("answer_tok_s" )if live else None 545hero = [Text (f" { safe ( model . get ( 'id' ), 35 ) } " 546f" { number ( work . get ( 'active' )) } active · { number ( work . get ( 'queued' )) } pre-admit" , 547style = dim ,no_wrap = True )] 548hero .extend (_big_rate (output ,cyan ,glyphs )) 549hero .append (Text (f" { number ( output , '' , 1 ) } tok/s · ALL REQUESTS" , 550style = f"bold { cyan } " if color else "bold" )) 551hero .append (Text (f"PROMPT { number ( prefill , '' , 1 ) } tok/s " 552f"ANSWER { number ( answer , '' , 1 ) } tok/s" ,no_wrap = True )) 553hero .append (Text (_output_trend (history .output_rate if live else (),glyphs ,False ),style = dim )) 554hero .append (Text (f"Prefill { _rate_spark ( history . prefill_rate if live else (), glyphs ) } " 555f"Answer { _rate_spark ( history . answer_rate if live else (), glyphs ) } " ,style = dim )) 556while len (hero )< 9 : 557hero .append (Text ("" )) 558 559devices = snapshot .get ("devices" )or [] 560selected = [index for index in topology .get ("selected_devices" )or []if type (index )is int and index >= 0 ] 561selected = list (dict .fromkeys (selected )) 562reported :dict [int ,dict ]= {} 563ambiguous :set [int ]= set () 564for row in devices : 565index = row .get ("index" ) 566if type (index )is int and index >= 0 : 567if index in reported : 568ambiguous .add (index ) 569reported [index ]= row 570indices = selected or list (reported ) 571gpu_lines :list [Text ]= [] 572for index in indices [:4 ]: 573row = reported .get (index , {})if index not in ambiguous else {} 574stage = _device_role (index ,topology ) 575util = row .get ("util" )if live else None 576used = row .get ("mem_used" )if live else None 577total = row .get ("mem_total" )if live else None 578gpu_lines .append (Text (f"GPU { index } { stage :<5 } { field ( row . get ( 'name' ), 19 ) } " 579f"load { number ( util , '%' ):>4 } " 580f" { number ( row . get ( 'power' ) if live else None , 'W' ):>5 } " 581f" { number ( row . get ( 'temp' ) if live else None , 'C' ):>4 } " ,no_wrap = True )) 582gpu_lines .append (Text (f" { _meter ( util , 100 , 16 , glyphs ) } " 583f"VRAM { _meter ( used , total , 12 , glyphs ) } " 584f" { _gib ( used ) } / { _gib ( total ) } G " 585f" { _spark ( history . device_util . get ( index ) if live else (), glyphs , 6 ) } " , 586style = green if color else "" ,no_wrap = True )) 587if not gpu_lines : 588gpu_lines .append (Text ("Per-device sensors unavailable" ,style = dim )) 589if len (indices )> 4 : 590gpu_lines .append (Text (f"+ { len ( indices ) - 4 } selected cards · press 5" ,style = dim )) 591while len (gpu_lines )< 9 : 592gpu_lines .append (Text ("" )) 593 594context = model .get ("context" ) 595held = [row .get ("held_tokens" )for row in (slots or [])if live 596if row .get ("state" )!= "idle" and 597isinstance (row .get ("held_tokens" ), (int ,float ))and 598not isinstance (row .get ("held_tokens" ),bool )and 599math .isfinite (row ["held_tokens" ])and row ["held_tokens" ]>= 0 ] 600# A complete all-idle slot map establishes zero active context. An active 601# slot with a missing held-token reading still remains unavailable. 602max_held = (max (held )if held else 6030 if live and slots is not None and all (row .get ("state" )== "idle" for row in slots ) 604else None ) 605context_lines = [Text (f"CAPACITY { number ( context ) } tokens / slot " 606f"MAX ACTIVE HELD { number ( max_held ) } " ,no_wrap = True ), 607Text (_meter (max_held ,context ,max (12 ,min (80 ,width - 8 )),glyphs ), 608style = violet if color else "" ,no_wrap = True ), 609Text (f"Slots { number ( work . get ( 'occupied_slots' )) } / { number ( work . get ( 'slots_effective' )) } " 610f"occupied · wait { number ( work . get ( 'waiting' )) } · " 611f"queue { number ( work . get ( 'queued' )) } · " 612f"rows/window { number ( _current_batch_value ( work , 'effective_rows_window' ), '' , 1 ) } " 613f"processed / { number ( _current_batch_value ( work , 'batch_active_rows_window' ), '' , 1 ) } active" , 614no_wrap = True )] 615if work .get ("replica_batches" ): 616context_lines .append (Text (_replica_batch_line (work ,False ),style = dim )) 617else : 618context_lines .append (Text ("Held is the largest active slot cache; groups are not GPU lanes." ,style = dim )) 619 620slot_lines :list [Text ]= [] 621if slots is None : 622slot_lines .append (Text ("Complete slot map unavailable" ,style = dim )) 623else : 624grouped :dict [tuple [int | None ,int | None ],list [dict ]]= {} 625for row in slots : 626key = (row .get ("replica" )if type (row .get ("replica" ))is int else None , 627row .get ("group" )if type (row .get ("group" ))is int else None ) 628grouped .setdefault (key , []).append (row ) 629for (replica ,group ),rows in sorted (grouped .items (),key = lambda item : ( 630- 1 if item [0 ][0 ]is None else item [0 ][0 ], 631- 1 if item [0 ][1 ]is None else item [0 ][1 ]))[:10 ]: 632label = f"R { replica } " if replica is not None else "" 633label += f"G { group } " if group is not None else "G--" 634line = Text (f" { label :<7 } " ,no_wrap = True ) 635for row in rows [:8 ]: 636state = {"reading" :"P" ,"decoding" :"D" ,"idle" :"·" }.get (row .get ("state" ),"?" ) 637tint = (amber if state == "P" else green if state == "D" else dim ) 638line .append (f"[ { number ( row . get ( 'slot' )):>2 } { state } ] " ,style = tint if color else "" ) 639if len (rows )> 8 : 640line .append (f"+ { len ( rows ) - 8 } " ,style = dim ) 641slot_lines .append (line ) 642if len (grouped )> 10 : 643slot_lines .append (Text (f"+ { len ( grouped ) - 10 } groups · press 2" ,style = dim )) 644slot_lines .insert (0 ,Text ("P prefill D decode · idle | engine slots" ,style = dim )) 645slot_lines .append (Text (f" { _slot_phases ( work , False ) or 'Slot phases unavailable' } " ,style = dim )) 646slot_lines .append (Text (_replica_batch_line (work ,False )if work .get ("replica_batches" )else 647f"Oldest queue { number ( work . get ( 'oldest_queue_s' ), 's' , 1 ) } · " 648f"admission { number ( work . get ( 'admission_reserved' )) } /" 649f" { number ( work . get ( 'admission_limit' )) } " ,style = dim )) 650active_slots = [row for row in slots or []if row .get ("state" )!= "idle" ] 651if active_slots : 652slot_lines .append (Text ("ACTIVE CONTEXTS · held / capacity" ,style = dim )) 653for row in active_slots [:max (1 ,min (8 ,height - 32 ))]: 654held_tokens = row .get ("held_tokens" )if live else None 655slot_lines .append (Text (f"S { number ( row . get ( 'slot' )):<3 } " 656f" { _meter ( held_tokens , context , 10 , glyphs ) } " 657f" { number ( held_tokens ) } / { number ( context ) } tokens " 658f" { number ( row . get ( 'tok_s' ) if live else None , '' , 1 ) } t/s" , 659style = green if color else "" ,no_wrap = True )) 660if len (active_slots )> max (1 ,min (8 ,height - 32 )): 661slot_lines .append (Text (f"+ { len ( active_slots ) - max ( 1 , min ( 8 , height - 32 )) } slots · press 2" , 662style = dim )) 663 664needle = filter_text .lower () 665requests = [row for row in work .get ("requests" )or []if not needle or 666needle in (safe (row .get ("id" ))+ safe (row .get ("state" ))).lower ()] 667requests .sort (key = lambda row : (row .get ("state" )!= "queued" ,row .get ("slot" )is None , 668row .get ("slot" )if type (row .get ("slot" ))is int else 999 )) 669slot_rates = {(row .get ("slot" ),row .get ("request_id" )):row .get ("tok_s" ) 670for row in slots or []if row .get ("request_id" )is not None } 671narrow_requests = width < 138 672req_lines = [Text ("ID STATE SLOT PROMPT OUT t/s 1ST ENGINE" if narrow_requests else 673"ID STATE ROUTE PROMPT OUT SLOT t/s 1ST ENGINE" , 674style = dim )] 675limit = max (5 ,min (15 ,height - 28 )) 676for row in requests [:limit ]: 677route = (f"R { row [ 'replica' ] } /" if type (row .get ("replica" ))is int else "" ) 678route += (f"S { row [ 'slot' ] } " if type (row .get ("slot" ))is int else "--" ) 679prompt_read = row .get ("prompt_read" ) 680prompt_total = row .get ("prompt_tokens" ) 681prompt_label = (f" { number ( prompt_read ) } / { number ( prompt_total ) } " if row .get ("state" )== "reading" else 682number (prompt_total )) 683first = number (row .get ("first_engine_token_s" ),"s" ,2 ) 684if row .get ("state" )== "queued" : 685first = f"wait { number ( _queue_wait ( row , snapshot . get ( 'sampled_at' )), 's' , 1 ) } " 686slot_rate = slot_rates .get ((row .get ("slot" ),row .get ("id" )))if live else None 687state = safe (row .get ("state" ),10 ) 688tint = amber if state == "reading" else green if state == "decoding" else violet 689if narrow_requests : 690request_text = (f" { field ( row . get ( 'id' ), 10 ) } { state :<8 } { route :<6 } " 691f" { prompt_label :<9 } { number ( row . get ( 'generated' )):>4 } " 692f" { number ( slot_rate , '' , 1 ):>5 } { first } " ) 693else : 694request_text = (f" { field ( row . get ( 'id' ), 12 ) } { state :<10 } { route :<9 } " 695f" { prompt_label :<11 } { number ( row . get ( 'generated' )):>4 } " 696f" { number ( slot_rate , '' , 1 ):>7 } { first } " ) 697req_lines .append (Text (request_text ,style = tint if color else "" ,no_wrap = True )) 698if len (requests )> limit : 699req_lines .append (Text (f"+ { len ( requests ) - limit } more · press 3" ,style = dim )) 700if not requests : 701req_lines .append (Text ("No active requests" if work .get ("requests" )is not None else 702"Request identities unavailable" ,style = dim )) 703if work .get ("requests_omitted" ): 704req_lines .append (Text (f" { number ( work . get ( 'requests_omitted' )) } additional rows omitted by server" ,style = dim )) 705lower_rows = max (len (slot_lines ),len (req_lines )) 706slot_lines .extend (Text ("" )for _ in range (lower_rows - len (slot_lines ))) 707req_lines .extend (Text ("" )for _ in range (lower_rows - len (req_lines ))) 708 709top = _visual_pair (_visual_panel (hero ,"THROUGHPUT" ,cyan ,color ), 710_visual_panel (gpu_lines ,f"GPUS · { len ( indices ) } " 711f" { 'selected' if selected else 'reported' } " ,green ,color )) 712middle = _visual_panel (context_lines ,"CONTEXT / BATCHING" ,violet ,color ) 713lower_height = max (lower_rows + 2 ,height - 23 ) 714lower = _visual_pair (_visual_panel (slot_lines ,"PARALLEL SLOTS" ,amber ,color , 715height = lower_height ), 716_visual_panel (req_lines ,f"REQUESTS · { len ( requests ) } visible" ,green ,color , 717height = lower_height ),3 ,4 ) 718return Group (header ,top ,middle ,lower ,footer ) 719 720 721def _rate_spark (values :Any ,glyphs :str )-> str : 722samples = list (values or [])[- (16 if glyphs == "braille" else 8 ):] 723valid = [value for value in samples if value is not None ] 724if len (valid )< 2 or samples [- 1 ]is None : 725return "--" 726low ,high = min (valid ),max (valid ) 727scaled = [None if value is None else (50 if high == low else 100 * (value - low )/ (high - low )) 728for value in samples ] 729return _spark (scaled ,glyphs ,8 ) 730 731 732def _device_role (index :int ,topology :dict )-> str : 733for replica in topology .get ("replica_devices" )or []: 734if index in replica .get ("devices" , []): 735return f"R { number ( replica . get ( 'replica' )) } " 736if topology .get ("resolved" ): 737for stage in topology .get ("stages" )or []: 738if stage .get ("device_index" )== index : 739return f"S { number ( stage . get ( 'stage' )) } " 740return "" 741 742 743def render_dashboard (snapshot :dict ,* ,width :int ,height :int ,history :MonitorHistory , 744connection :str = "" ,connection_state :str = "connected" ,frozen :bool = False , 745filter_text :str = "" ,glyphs :str = "ascii" ,color :bool = True , 746theme :str = "dark" ,connect :bool = False )-> Group : 747"""Compose the primary one-screen monitor at standard terminal sizes. 748 749Smaller terminals retain the existing compact text renderer in MonitorApp. 750""" 751set_ascii_boxes (glyphs == "ascii" ) 752compact = width < 100 or height < 27 753accent = ("#0c8a60" if theme == "light" else "#34d399" )if color else "default" 754danger = ("#b01a2e" if theme == "light" else "#ff8a98" )if color else "default" 755danger_border = ("#e0283f" if theme == "light" else "#ff5a6e" )if color else "default" 756model ,instance = snapshot .get ("model" )or {},snapshot .get ("instance" )or {} 757work ,rates = snapshot .get ("work" )or {},snapshot .get ("rates" )or {} 758topology = snapshot .get ("topology" )or {} 759recent = snapshot .get ("recent" )or [] 760state ,live = _state (snapshot ,connection_state ,frozen ) 761model_state = ("DRAINING" if instance .get ("state" )== "draining" else 762"READY" if model .get ("loaded" )is True else 763"NO MODEL LOADED" if model .get ("loaded" )is False else "UNKNOWN" ) 764heading = Text () 765heading .append ("STRATA / MONITOR" ,style = f"bold { accent } " ) 766heading .append (" " ) 767heading .append (state ,style = (f"bold { accent } " if state == "LIVE" else 768"bold yellow" if state in ("SLEEPING" ,"STALE" ,"CONNECTING" )else 769f"bold { danger } " if state in ("DISCONNECTED" ,"AUTH REQUIRED" ,"INCOMPATIBLE" )else 770"bold" )) 771heading .append (f" { safe ( connection , max ( 0 , width - 45 )) } " ) 772blocked = connection_state in ("disconnected" ,"auth_required" ,"incompatible" ) 773header = Panel (heading ,box = _rounded (), 774border_style = danger_border if blocked else accent ,padding = (0 ,1 )) 775 776if connection_state in ("connecting" ,"disconnected" ,"auth_required" ,"incompatible" ): 777title ,message ,action = { 778"connecting" : ("CONNECTING" ,"Waiting for the first Strata telemetry snapshot." , 779"The monitor will update automatically." ), 780"disconnected" : ("CONNECTION LOST" ,"The Strata server is not responding." , 781"Retrying automatically; press r to retry now." ), 782"auth_required" : ("AUTHORIZATION REQUIRED" ,"The telemetry credential was rejected." , 783"Update the saved monitor connection, then press r." ), 784"incompatible" : ("INCOMPATIBLE SERVER" ,"This telemetry schema is unsupported." , 785"Connect to a compatible Strata server, then press r." ), 786 }[connection_state ] 787age = _age (snapshot ) 788last_seen = (f"Last snapshot { number ( age , 's' , 1 ) } ago" if age is not None and age >= 0 else 789"No telemetry snapshot available" ) 790lines = Group (Text (title ,style = f"bold { danger } " if blocked else f"bold { accent } " ), 791Text (message ),Text (action ,style = "dim" ),Text (last_seen ,style = "dim" )) 792panel = Panel (Align .center (lines ,vertical = "middle" ), 793title = Text ("CONNECTION" ,style = f"bold { danger } " if blocked else f"bold { accent } " ), 794border_style = danger_border if blocked else "dim" ,box = _rounded (), 795height = max (8 ,height - 4 )) 796return Group (header ,panel ,Text (f"r Retry q Detach { nav . keys ( connect ) } Views" ,style = "dim" )) 797 798model_name = safe (model .get ("id" ),80 ) 799if compact and display_width (model_name )> 19 : 800model_name = safe (model_name ,18 )+ "…" 801else : 802model_name = safe (model_name ,19 if compact else 35 ) 803serving = [f"Model { model_name } " , 804 (f"State { model_state } { number ( work . get ( 'active' )) } active" if compact else 805f"State { model_state } | { number ( work . get ( 'active' )) } in flight" ), 806 (f"Queue { number ( work . get ( 'waiting' )) } engine { number ( work . get ( 'queued' )) } pre-admit" if compact else 807f"Queue { number ( work . get ( 'waiting' )) } engine / { number ( work . get ( 'queued' )) } pre-admit" )] 808progress = _prompt_progress (work ,compact ,glyphs )if live else None 809if progress : 810serving .append (progress ) 811telemetry_unavailable = (snapshot .get ("quality" )or {}).get ("telemetry" )== "unavailable" 812answer = number (rates .get ('answer_tok_s' )if live else None ,'' ,1 ) 813prompt = number (rates .get ('prefill_tok_s' )if live else None ,'' ,1 ) 814aggregate = number (rates .get ('aggregate_output_tok_s' )if live else None ,' tok/s' ,1 ) 815performance = ([f"P { prompt } A { answer } tok/s" ,f"All { aggregate } server" ]if compact else 816 [f"Prompt { prompt } Answer { answer } tok/s" ,f"Aggregate { aggregate } server" ]) 817performance .append (_output_trend (history .output_rate if live else (),glyphs ,compact )) 818 819batch = [f"Slots { number ( work . get ( 'occupied_slots' )) } / { number ( work . get ( 'slots_effective' )) } " 820f"req { number ( work . get ( 'slots_requested' )) } groups { number ( work . get ( 'groups' )) } " , 821f"Rows/win { number ( _current_batch_value ( work , 'effective_rows_window' ), '' , 1 ) } processed " 822f" { number ( _current_batch_value ( work , 'batch_active_rows_window' ), '' , 1 ) } active" , 823f"Admit { number ( work . get ( 'admission_reserved' )) } / { number ( work . get ( 'admission_limit' )) } " 824f"oldest { number ( work . get ( 'oldest_queue_s' ), 's' , 1 ) } " 825f"reject { number ( work . get ( 'admission_rejected' )) } " ] 826replica_ids = {row .get ("replica" )for row in complete_slots (work )or [] 827if type (row .get ("replica" ))is int } 828replica_count = max (len (replica_ids ),len (topology .get ("replica_devices" )or []), 829len (work .get ("replica_batches" )or [])) 830if replica_count : 831batch [0 ]= (f"Slots { number ( work . get ( 'occupied_slots' )) } / { number ( work . get ( 'slots_effective' )) } " 832f"| requested { number ( work . get ( 'slots_requested' )) } | replicas { replica_count } " ) 833batch [1 ]= _replica_batch_line (work ,compact = False ) 834if compact : 835batch [0 ]= (f"Slots { number ( work . get ( 'occupied_slots' )) } / { number ( work . get ( 'slots_effective' )) } " 836f" { 'replicas ' + str ( replica_count ) if replica_count else 'groups ' + number ( work . get ( 'groups' )) } " ) 837batch [1 ]= (_replica_batch_line (work ,compact = True )if replica_count else 838f"Batch rows { number ( _current_batch_value ( work , 'effective_rows_window' ), '' , 1 ) } " 839f"active { number ( _current_batch_value ( work , 'batch_active_rows_window' ), '' , 1 ) } " ) 840batch [2 ]= (f"Admit { number ( work . get ( 'admission_reserved' )) } / { number ( work . get ( 'admission_limit' )) } " 841f"oldest { number ( work . get ( 'oldest_queue_s' ), 's' , 1 ) } " ) 842phases = _slot_phases (work ,compact ) 843if phases : 844batch .append (phases .replace ("Phases " ,"" )if compact else phases ) 845batch += _groups (work ,compact ,glyphs ) 846if not compact : 847stages = (work .get ("stage_in_flight" )or [])if _current_sample (work ,"stage_sample_age_s" )else [] 848replica_samples = work .get ("replica_stage_samples" )or [] 849if replica_samples : 850for row in replica_samples [:2 ]: 851samples = (row .get ("stage_in_flight" )or [])if _current_sample (row ,"stage_sample_age_s" )else [] 852batch .append (f"Host span R { row [ 'replica' ] } " + (" " .join ( 853f"S { number ( stage . get ( 'stage' )) } { number ( stage . get ( 'percent' ), '%' ) } " 854for stage in samples )+ f" age { number ( row . get ( 'stage_sample_age_s' ), 's' , 1 ) } " 855if samples else "--" )) 856if len (replica_samples )> 2 : 857batch .append (f"+ { len ( replica_samples ) - 2 } replicas; see Engine" ) 858else : 859batch .append (("Host span " + " " .join (f"S { number ( row . get ( 'stage' )) } /" 860f" { number ( row . get ( 'percent' ), '%' ) } " for row in stages ))if stages else 861"Stage host span --" ) 862if live : 863if replica_count : 864trends = [_work_trend (history .replica_batch_rows .get (replica ),glyphs , 865f"R { replica } rows" ,"/win" ,1 ) 866for replica in sorted (history .replica_batch_rows )[:2 ]] 867else : 868trends = [_work_trend (history .batch_rows ,glyphs ,"Rows trend" ,"/win" ,1 ), 869_work_trend (history .pre_admit ,glyphs ,"Pre-admit" ," req" )] 870detail_rows = 10 if width >= 100 and height >= 40 else 0 871used_rows = (3 + 1 + len (serving )+ 2 + len (performance )+ 2 + 872len (batch )+ 2 + detail_rows ) 873batch .extend ([trend for trend in trends if trend ][:max (0 ,height + 1 - used_rows )]) 874 875hardware = _hardware (snapshot ,history ,glyphs ,compact ) 876ram = snapshot .get ("ram" )or {} 877if isinstance (ram .get ("used" ), (int ,float ))and isinstance (ram .get ("total" ), (int ,float )): 878hardware .append (f"RAM { _gib ( ram [ 'used' ]) } / { _gib ( ram [ 'total' ]) } GiB" ) 879hardware .append (("Each request stays in one replica" if replica_count else "Groups are not GPU lanes" )if compact else 880 ("Per-card sensors; replicas serve independently" if replica_count else 881"Per-card sensors; requests cross all stages" )) 882requests = _request_lines (snapshot ,compact ,filter_text ,tall = height >= 40 ) 883activity = _activity (snapshot ,compact ,filter_text ) 884age = _age (snapshot ) 885age_text = f"age { number ( age , 's' , 1 ) } " 886footer = Text (nav .plain (0 ,max (20 ,width - len (age_text )- 4 ),connect )+ " " + age_text ,style = "dim" ) 887if width >= 126 and height >= 34 : 888return _visual_overview (snapshot ,history ,width = width ,height = height , 889header = header ,footer = footer ,live = live ,glyphs = glyphs , 890color = color ,theme = theme ,filter_text = filter_text ) 891left_sections = [(serving ,"SERVING" ), (performance ,"PERFORMANCE" ), 892 (batch ,"BATCHING / PARALLEL" )] 893if width >= 100 and height >= 40 : 894totals = snapshot .get ("totals" )or {} 895left_sections .extend ([ 896 ([f"Completed { number ( totals . get ( 'requests' )) } [server lifetime]" , 897f"Prompt { number ( totals . get ( 'prompt_tokens' )) } tokens" , 898f"Output { number ( totals . get ( 'output_tokens' )) } tokens" ],"SESSION" ), 899 ([f"Context { number ( model . get ( 'context' )) } tokens" , 900f"Topology { safe ( topology . get ( 'mode' ), 26 ) } " , 901f"Last engine token { number ( recent [ 0 ]. get ( 'first_engine_token_s' ) if recent else None , 's' , 3 ) } " ], 902"ENGINE" ), 903 ]) 904right_sections = [(hardware ,"HARDWARE" ), (requests ,"REQUESTS" ), 905 (activity ,"ACTIVITY" )] 906panel_rows = max (sum (len (lines )+ 2 for lines ,_ in left_sections ), 907sum (len (lines )+ 2 for lines ,_ in right_sections )) 908# Textual reserves its final row for the read-only message. Keep this 909# navigation row next to it when a tall terminal has spare space. 910filler = max (0 ,min (200 ,height + 1 - (3 + int (telemetry_unavailable )+ panel_rows + 1 ))) 911return Group (header ,* ([Text ("Telemetry unavailable; status only" ,style = "yellow" if color else "" )] 912if telemetry_unavailable else []), 913_columns ([_panel (lines ,title ,accent ,color = color )for lines ,title in left_sections ], 914 [_panel (lines ,title ,accent ,color = color )for lines ,title in right_sections ]), 915* [Text (" " )for _ in range (filler )],footer )