okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""Main / Helper / Off for every graphics card: ONE place for the app, `strata launch`, setup and the server. 2 3A card has one of three roles: 4* Main - the card that runs the LAST stage of the layer split: the output head, the draft layer and the check of its guesses. Exactly one. 5* Helper - holds a share of the model, so more of it fits on graphics cards instead of being read from the drive. 6* Off - Strata does not touch it. 7 8The engine takes the cards in stage order (`"gpu": [helper, ..., main]` with `"gpu_order": "as_given"`), so the Main card is the LAST one. This 9module turns roles into that list (and back), recommends roles, and words the few warnings a person could not work out alone. 10The app has the same rules in apps/host/src/lib/gpu-roles.ts; both run tests/data/gpu_roles_vectors.json. 11 12Pure functions, no I/O. 13""" 14 15from __future__import annotations 16 17from typing import Any ,Callable 18 19from strata_control import gpu_fit 20 21ROLES = ("main" ,"helper" ,"off" ) 22OFF_AT_OR_BELOW_GB = 8.0 # owner rule: a card with 8 GB or less starts Off (it is not a helper unless the person turns it on) 23SAME_SPEED = 1.05 # serve/server.py ordered_gpus: cards within 5% of each other are the same card 24MEMORY_GUARD_SPEED = 0.5 # a card with more memory takes Main from a faster one only when it is at least half as fast (#1576) 25 26CPU_ONLY_LINE = "Performance is degraded on CPU only." 27NO_CARD_LINE = "This engine needs a graphics card to start. Turn one on." 28 29 30def _idx (c :dict )-> int : 31return int (c .get ("index" ,0 )) 32 33 34def _mem (c :dict )-> float : 35return float (c .get ("vram_gb" )or 0 ) 36 37 38def _speed (c :dict )-> float : 39v = c .get ("speed" ) 40return float (v )if isinstance (v , (int ,float ))and not isinstance (v ,bool )and v > 0 else 0.0 41 42 43def rnd_ (x :float )-> int : 44return round (x ) 45 46 47def _shares (c :dict )-> bool : 48return gpu_fit ._shares_memory (c ) 49 50 51def _can_run (c :dict )-> bool : 52return c .get ("usable" )is not False 53 54 55def short_name (c :dict )-> str : 56n = str (c .get ("name" )or f"GPU { _idx ( c ) + 1 } " ) 57for junk in ("NVIDIA GeForce " ,"NVIDIA " ,"GeForce " ,"AMD Radeon " ,"AMD " ,"Intel(R) " ,"Intel " ): 58if n .startswith (junk ): 59n = n [len (junk ):] 60break 61return n .strip () 62 63 64def gpu_label (c :dict )-> str : 65"""The number the screens show: GPU 1 is card 0 (Monitor, the model picker, the loaded list).""" 66return f"GPU { _idx ( c ) + 1 } " 67 68 69def rows (cards :list [dict ],vendor :str | None = None )-> list [dict ]: 70"""The cards shown as rows: every card the engine's make can name, in card order. The other make is `gpu_fit.for_vendor(...)[1]` (a muted line).""" 71vendor = vendor or gpu_fit .pick_vendor (cards ) 72mine = gpu_fit .for_vendor (cards ,vendor )[0 ] 73return sorted (mine ,key = _idx ) 74 75 76def _eligible (cs :list [dict ])-> list [dict ]: 77"""The cards that can be Main: run Strata, have memory of their own and at least MIN_CARD_GB of it; an integrated chip only when it is the 78only device (a Strix Halo PC, a mini PC).""" 79real = [c for c in cs if _can_run (c )and not _shares (c )and _mem (c )>= gpu_fit .MIN_CARD_GB ] 80if real : 81return real 82return [c for c in cs if _can_run (c )] 83 84 85def pick_main (cs :list [dict ])-> tuple [dict | None ,str ]: 86"""(the Main card, why) why: only | faster | same | memory. The faster card, cards within 5% being the same card (the one with more memory, 87then, for identical cards, the HIGHEST number - so the engine order stays [0, 1] - else the lower number); a card with clearly more memory wins when it is at least half as fast (#1576).""" 88pool = _eligible (cs ) 89if not pool : 90return None ,"none" 91if len (pool )== 1 : 92return pool [0 ],"only" 93top = max (_speed (c )for c in pool ) 94group = [c for c in pool if _speed (c )* SAME_SPEED >= top ]if top > 0 else list (pool ) 95main = sorted (group ,key = lambda c : (- round (_mem (c )),_idx (c )))[0 ] 96why = "faster" if len (group )== 1 else "same" 97if len (group )> 1 and len ({(str (c .get ("name" )),rnd_ (_mem (c )))for c in group })== 1 : 98main = max (group ,key = _idx )# identical cards: the HIGHEST number is Main, so the engine order stays [0, 1] as it always was 99if top <= 0 and len ({round (_mem (c ))for c in pool })> 1 : 100why = "memory" # speeds unknown: the card with the most memory 101bigger = [c for c in pool if round (_mem (c ))> round (_mem (main ))and (top <= 0 or _speed (c )>= MEMORY_GUARD_SPEED * top )] 102if bigger : 103main = sorted (bigger ,key = lambda c : (- round (_mem (c )),_idx (c )))[0 ] 104why = "memory" 105return main ,why 106 107 108def recommend (cards :list [dict ],vendor :str | None = None )-> dict [str ,Any ]: 109"""The recommended roles: {"roles": {index: role}, "main": index|None, "why": code, "reasons": {index: code}}. 110The best card is Main, every other card starts as Helper, EXCEPT a card with 8 GB or less when a bigger card is there (or it has under 4 GB), an integrated chip beside a card with memory of 111its own, and a card the engine cannot run: those start Off.""" 112cs = rows (cards ,vendor ) 113main ,why = pick_main (cs ) 114roles :dict [int ,str ]= {} 115reasons :dict [int ,str ]= {} 116# An 8 GB card is a poor Helper beside a bigger card, but a perfectly good one when 8 GB is all there is: two GTX 1080s are a working 117# 16 GB pool (#3655). A card with 8 GB or less starts Off only when a bigger usable card is there, or when it is too small to help. 118has_bigger = any (_can_run (c )and not _shares (c )and round (_mem (c ))> OFF_AT_OR_BELOW_GB for c in cs ) 119for c in cs : 120i = _idx (c ) 121if main is not None and c is main : 122roles [i ],reasons [i ]= "main" ,why 123elif not _can_run (c ): 124roles [i ],reasons [i ]= "off" ,"cannot_run" 125elif _shares (c )and main is not None : 126roles [i ],reasons [i ]= "off" ,"igpu" 127elif round (_mem (c ))<= OFF_AT_OR_BELOW_GB and (has_bigger or _mem (c )< gpu_fit .MIN_CARD_GB ): 128roles [i ],reasons [i ]= "off" ,"small" 129else : 130roles [i ],reasons [i ]= "helper" ,"helper" 131return {"roles" :roles ,"main" :_idx (main )if main is not None else None ,"why" :why ,"reasons" :reasons } 132 133 134def _on (roles :dict [int ,str ])-> list [int ]: 135return [i for i ,r in roles .items ()if r != "off" ] 136 137 138def normalize (roles :dict [int ,str ],cards :list [dict ])-> dict [int ,str ]: 139"""Exactly one Main among the cards that are on: none -> the fastest card that is on; more than one -> the first keeps it. A lone card that 140is on is Main.""" 141cs = {_idx (c ):c for c in cards } 142out = {i : (r if r in ROLES else "off" )for i ,r in roles .items ()if i in cs } 143on = _on (out ) 144mains = [i for i in on if out [i ]== "main" ] 145if on and not mains : 146best = sorted (on ,key = lambda i : (- _speed (cs [i ]),- round (_mem (cs [i ])),i ))[0 ] 147out [best ]= "main" 148for extra in mains [1 :]: 149out [extra ]= "helper" 150if len (on )== 1 : 151out [on [0 ]]= "main" 152return out 153 154 155def set_role (roles :dict [int ,str ],cards :list [dict ],idx :int ,role :str )-> tuple [dict [int ,str ],str | None ]: 156"""One click: the new roles and a code for the quiet line the app/Terminal may show (None: nothing to say). 157Codes: old_main_helper:<i> (the old Main became a Helper), promoted:<i> (this card became Main because the Main left), only_main (refused).""" 158cs = {_idx (c ):c for c in cards } 159out = dict (roles ) 160note :str | None = None 161if idx not in cs or role not in ROLES : 162return out ,None 163if role == "main" : 164old = next ((i for i in out if i != idx and out [i ]== "main" ),None ) 165out [idx ]= "main" 166if old is not None : 167out [old ]= "helper" 168note = f"old_main_helper: { old } " 169elif role == "helper" : 170if out .get (idx )== "main" : 171others = sorted ([i for i in out if i != idx and out [i ]== "helper" ],key = lambda i : (- _speed (cs [i ]),i )) 172if not others : 173return out ,"only_main" 174out [idx ]= "helper" 175out [others [0 ]]= "main" 176note = f"promoted: { others [ 0 ] } " 177else : 178out [idx ]= "helper" 179else : 180was_main = out .get (idx )== "main" 181out [idx ]= "off" 182if was_main : 183nxt = sorted ([i for i in out if out [i ]== "helper" ],key = lambda i : (- _speed (cs [i ]),i )) 184if nxt : 185out [nxt [0 ]]= "main" 186note = f"promoted: { nxt [ 0 ] } " 187on = _on (out ) 188if len (on )== 1 : 189out [on [0 ]]= "main" 190elif on and not any (out [i ]== "main" for i in on ): 191out [on [0 ]]= "main" 192return out ,note 193 194 195def order (roles :dict [int ,str ],cards :list [dict ])-> list [int ]: 196"""The engine's card list: Helpers (slowest first, ties by number), then the Main card LAST; Off cards left out.""" 197cs = {_idx (c ):c for c in cards } 198roles = normalize (roles ,cards ) 199helpers = sorted ([i for i ,r in roles .items ()if r == "helper" ],key = lambda i : (_speed (cs [i ]),i )) 200return helpers + [i for i ,r in roles .items ()if r == "main" ] 201 202 203def mirror (roles :dict [int ,str ],cards :list [dict ])-> dict [str ,Any ]: 204"""What a writer stores: "gpu_roles" plus the legacy mirror older engines and the Monitor read. Nothing on: "gpu": [] and "gpu_none": true.""" 205roles = normalize (roles ,cards ) 206lst = order (roles ,cards ) 207out :dict [str ,Any ]= {"gpu_roles" : {str (i ):roles [i ]for i in sorted (roles )}} 208if lst : 209out ["gpu" ]= lst [0 ]if len (lst )== 1 else lst 210out ["gpu_order" ]= "as_given" 211else : 212out ["gpu" ]= [] 213out ["gpu_none" ]= True 214out ["gpu_cards" ]= {str (_idx (c )):"|" .join (x for x in (short_name (c ),str (c .get ("bus" )or "" ))if x )for c in cards if _idx (c )in roles } 215return out 216 217 218def parse_roles (text :str ,cards :list [dict ]| None = None )-> dict [int ,str ]: 219"""`1=main,0=helper,2=off` (also `1:main`) -> {1: "main", 0: "helper", 2: "off"}. ValueError with a plain message otherwise.""" 220out :dict [int ,str ]= {} 221for part in str (text or "" ).replace (";" ,"," ).split ("," ): 222part = part .strip () 223if not part : 224continue 225sep = "=" if "=" in part else ":" if ":" in part else None 226if sep is None : 227raise ValueError (f" { part !r } : write each card as number=role, e.g. 1=main,0=helper,2=off" ) 228k ,v = (x .strip ().lower ()for x in part .split (sep ,1 )) 229if not k .isdigit ()or v not in ROLES : 230raise ValueError (f" { part !r } : a card number and one of main, helper, off, e.g. 1=main" ) 231if int (k )in out : 232raise ValueError (f"card { k } is named twice" ) 233out [int (k )]= v 234if not out : 235raise ValueError ("no cards named; write e.g. 1=main,0=helper" ) 236mains = [i for i ,r in out .items ()if r == "main" ] 237if len (mains )> 1 : 238raise ValueError ("only one card can be Main" ) 239if cards is not None : 240known = {_idx (c )for c in cards } 241missing = [i for i in out if i not in known ] 242if missing : 243raise ValueError ("no card " + ", " .join (str (i )for i in missing )+ " on this computer (cards: " + ", " .join (str (i )for i in sorted (known ))+ ")" ) 244return out 245 246 247def roles_from_text (text :str ,cards :list [dict ])-> dict [int ,str ]: 248"""A command line's roles: the cards named get their role; every card NOT named is Off (an explicit command means only what was named); 249no Main named -> the fastest named card that is on becomes Main.""" 250named = parse_roles (text ,cards ) 251full = {_idx (c ):named .get (_idx (c ),"off" )for c in cards } 252return normalize (full ,cards ) 253 254 255def speed_stage_order (order :list [int ],speeds :dict [int ,float ],vram_mib :"dict[int, int] | Callable[[], dict[int, int] | None] | None" = None )-> tuple [list [int ],str ,tuple [int ,int ]| None ]: 256"""THE decision of the card order of an automatic layer split (#1352, #1576, #1760), shared by the start (serve/server.py ordered_gpus) and the plan 257(`from_legacy`, strata launch --plan): the same function, so the plan can never name a different Main card than the run. 258`order`: the cards as the config lists them. `speeds`: {index: multiprocessors x max clock}, every card of `order`. `vram_mib`: {index: MiB}, or a function 259that returns it (asked only when a reorder is on the table; None / missing cards: no VRAM check). 260Returns (order, why, vram) with why: 261"same" the speeds are within 5% of each other (#1760): the config's order is kept; 262"kept" the order is already speed order: nothing to change; 263"kept-vram" the faster card has less total VRAM than the card the config ends on (#1576): the config's order is kept; vram = (that card's MiB, the config's last card's MiB); 264"faster-last" the cards are put in speed order, the faster card LAST (it runs the head, the draft layer and the verify; a prompt chunk waits on it).""" 265gl = list (order ) 266if len (gl )< 2 : 267return gl ,"same" ,None 268if max (speeds [i ]for i in gl )< SAME_SPEED * min (speeds [i ]for i in gl ): 269return gl ,"same" ,None # #1760: cards within 5% of each other are the same card (two 5070 Ti read 1.2% apart on the clock): keep the order 270out = sorted (gl ,key = lambda i :speeds [i ]) 271if out == gl : 272return gl ,"kept" ,None 273vram = vram_mib ()if callable (vram_mib )else vram_mib 274if vram is not None and all (i in vram for i in gl )and vram [out [- 1 ]]< vram [gl [- 1 ]]: 275return gl ,"kept-vram" , (vram [out [- 1 ]],vram [gl [- 1 ]]) 276return out ,"faster-last" ,None 277 278 279def from_legacy (gpu :Any ,cards :list [dict ],gpu_order :str | None = None ,speed_order :bool = True )-> dict [int ,str ]: 280"""Roles of an old "gpu" setting, for display: the LAST card of the engine's order is Main, earlier ones are Helpers, unlisted cards are Off. 281`gpu` None / "" / []: the recommendation (nothing was chosen).""" 282items :list [int ]= [] 283if isinstance (gpu , (list ,tuple )): 284items = [int (x )for x in gpu ] 285elif gpu is not None and str (gpu ).strip ()!= "" : 286items = [int (x )for x in str (gpu ).split ("," )if x .strip ()!= "" ] 287cs = {_idx (c ):c for c in cards } 288items = [i for i in items if i in cs ] 289if not items : 290return dict (recommend (cards )["roles" ]) 291if len (items )> 1 and gpu_order != "as_given" and speed_order and all (_speed (cs [i ])for i in items ): 292# the engine's own decision (serve/server.py ordered_gpus calls the same function): the faster card last (#1352), unless the speeds are within 5% (#1760) 293# or the faster card has less VRAM than the one the list ends on (#1576) 294vram = {i :int (_mem (cs [i ])* 1024 )for i in items }if all (_mem (cs [i ])for i in items )else None 295items = speed_stage_order (items , {i :_speed (cs [i ])for i in items },vram )[0 ] 296roles = {i :"off" for i in cs } 297for i in items [:- 1 ]: 298roles [i ]= "helper" 299roles [items [- 1 ]]= "main" 300return roles 301 302 303def is_recommended (roles :dict [int ,str ],cards :list [dict ],vendor :str | None = None )-> bool : 304rec = recommend (cards ,vendor )["roles" ] 305return {i :r for i ,r in roles .items ()if i in rec }== rec 306 307 308# ---- warnings: only what a person could not know ------------------------------------------------------------------------------------------- 309 310def warnings (roles :dict [int ,str ],cards :list [dict ],* ,spill_gb :float = 0.0 ,engine_runs_cpu_only :bool = False )-> list [dict ]: 311"""[{"code", "card"|None, "text", "fix": {"card": i, "role": r}|None}] - one short line each, never blocking. 312* igpu_main built-in graphics as Main (fix: the real card becomes Main) 313* cannot_run a card the engine cannot run is on (fix: turn it off) 314* low_memory too little memory for the chosen setup (part of the model would be read from the drive) 315* cpu_only every card is Off""" 316cs = {_idx (c ):c for c in cards } 317out :list [dict ]= [] 318for i in sorted (roles ): 319c ,role = cs .get (i ),roles [i ] 320if c is None or role == "off" : 321continue 322if not _can_run (c ): 323out .append ({"code" :"cannot_run" ,"card" :i ,"text" :f" { short_name ( c ) } cannot run Strata." ,"fix" : {"card" :i ,"role" :"off" }}) 324elif role == "main" and _shares (c )and any (not _shares (x )and _can_run (x )for x in cs .values ()): 325real = sorted ([x for x in cs .values ()if not _shares (x )and _can_run (x )],key = lambda x : (- _speed (x ),- _mem (x ),_idx (x )))[0 ] 326out .append ({"code" :"igpu_main" ,"card" :i ,"text" :f" { short_name ( c ) } is built-in graphics; it is slow as Main." , 327"fix" : {"card" :_idx (real ),"role" :"main" }}) 328if not _on (roles ): 329out .append ({"code" :"cpu_only" ,"card" :None ,"text" :CPU_ONLY_LINE if engine_runs_cpu_only else NO_CARD_LINE ,"fix" :None }) 330elif spill_gb >= 1.0 : 331out .append ({"code" :"low_memory" ,"card" :None ,"text" :f"Not enough memory for this setup: about { spill_gb :.0f } GB is read from the drive." ,"fix" :None }) 332return out 333 334 335def spill_for (roles :dict [int ,str ],cards :list [dict ],memory_gb :float | None ,ram_gb :float | None )-> float : 336"""About how many GB of the model would be read from the drive with the cards that are on (0 when unknown): gpu_fit's arithmetic, every 337extra card costing its own dense layers.""" 338if not memory_gb or not ram_gb : 339return 0.0 340cs = {_idx (c ):c for c in cards } 341on = [cs [i ]for i in _on (roles )if i in cs and not _shares (cs [i ])] 342vram = sum (_mem (c )for c in on )- gpu_fit .SPLIT_CARD_OVERHEAD_GB * max (0 ,len (on )- 1 ) 343return float (gpu_fit .fit (float (memory_gb ),float (ram_gb ),max (0.0 ,vram ))["spill_gb" ]) 344 345 346def note_text (code :str | None ,cards :list [dict ])-> str : 347"""The quiet line for a `set_role` code.""" 348if not code : 349return "" 350cs = {_idx (c ):c for c in cards } 351kind ,_ ,arg = code .partition (":" ) 352c = cs .get (int (arg ))if arg .isdigit ()else None 353name = short_name (c )if c else "That card" 354if kind == "old_main_helper" : 355return f" { name } is now a Helper." 356if kind == "promoted" : 357return f" { name } is now Main." 358if kind == "only_main" : 359return "The only card that is on has to be Main." 360return "" 361 362 363# ---- the sentence above the cards ---------------------------------------------------------------------------------------------------------- 364 365def sentence (cards :list [dict ],vendor :str | None = None )-> str : 366"""One plain line for the recommendation: who is Main and why, who helps, who starts Off.""" 367cs = rows (cards ,vendor ) 368rec = recommend (cards ,vendor ) 369byi = {_idx (c ):c for c in cs } 370if rec ["main" ]is None : 371return "No graphics card that Strata can use was found." 372m = byi [rec ["main" ]] 373if len (cs )== 1 : 374return f"Strata will use your { short_name ( m ) } ." 375helpers = [byi [i ]for i ,r in rec ["roles" ].items ()if r == "helper" ] 376why = {"same" :"the cards are alike" ,"memory" :"it has more memory" ,"faster" :"it is faster" ,"only" :"it is the only card" }[rec ["why" ]] 377s = f" { short_name ( m ) } is Main: { why } ." 378if helpers : 379s += " " + " and " .join (short_name (h )for h in helpers )+ (" help." if len (helpers )> 1 else " helps." ) 380for i ,r in rec ["roles" ].items (): 381if r == "off" : 382code = rec ["reasons" ][i ] 383c = byi [i ] 384s += f" { short_name ( c ) } starts Off: " + ("Strata cannot run it." if code == "cannot_run" else "built-in graphics." if code == "igpu" else f" { OFF_AT_OR_BELOW_GB :.0f } GB or less." ) 385return s 386 387 388# ---- reading saved settings (server, launch, app) --------------------------------------------------------------------------------------- 389 390def _int_list (g :Any )-> list [int ]: 391if g is None or g == "" : 392return [] 393items = g if isinstance (g , (list ,tuple ))else str (g ).split ("," ) 394return [int (str (x ).strip ())for x in items if str (x ).strip ()!= "" ] 395 396 397def parse_saved (value :Any )-> dict [int ,str ]| None : 398"""A saved "gpu_roles" object -> {index: role}; None when it is not one (the setting is then ignored).""" 399if not isinstance (value ,dict )or not value : 400return None 401out :dict [int ,str ]= {} 402for k ,v in value .items (): 403try : 404i = int (str (k ).strip ()) 405except ValueError : 406return None 407if str (v ).lower ()not in ROLES : 408return None 409out [i ]= str (v ).lower () 410if sum (1 for r in out .values ()if r == "main" )> 1 : 411return None 412return out 413 414 415def saved_roles (cfg :dict )-> tuple [dict [int ,str ]| None ,str | None ]: 416"""(the roles a run settings dict carries, a problem line or None). Roles win when the legacy "gpu" is the mirror of them, or when "gpu" is 417missing; a "gpu" that was edited by hand (it names other cards, or another Main) wins and the roles are ignored (#3256: a file that names 418its GPUs keeps them).""" 419roles = parse_saved (cfg .get ("gpu_roles" )) 420if roles is None : 421return None , ("run settings: gpu_roles is not {card: main|helper|off} with one main; ignored" if cfg .get ("gpu_roles" )is not None else None ) 422try : 423gl = _int_list (cfg .get ("gpu" )) 424except ValueError : 425return None ,"run settings: gpu is not a card number or a list; gpu_roles ignored" 426on = [i for i ,r in roles .items ()if r != "off" ] 427main = next ((i for i ,r in roles .items ()if r == "main" ),None ) 428if cfg .get ("gpu_none" )and not on : 429return roles ,None 430if not gl : 431return (roles ,None )if on else (None ,None ) 432if sorted (gl )!= sorted (on )or (main is not None and gl [- 1 ]!= main ): 433return None ,"run settings: gpu was edited by hand, gpu_roles ignored" 434return roles ,None 435 436 437def engine_order (roles :dict [int ,str ],speeds :dict [int ,float ]| None = None )-> list [int ]: 438"""The card list of saved roles for the server: Helpers slowest first (ties by number), then Main. Used where only numbers and 439(maybe) measured speeds are known.""" 440sp = speeds or {} 441helpers = sorted ([i for i ,r in roles .items ()if r == "helper" ],key = lambda i : (sp .get (i ,0.0 ),i )) 442return helpers + sorted (i for i ,r in roles .items ()if r == "main" ) 443 444 445def describe (roles :dict [int ,str ],cards :list [dict ],* ,card_numbers :bool = False )-> str : 446"""`Main: GPU 2 RTX 4070 Ti. Helper: GPU 1 RTX 3060.` (the line setup prints; the screens count from 1: GPU 1 is card 0). 447`card_numbers`: each card also names the number `--gpu` takes, as `strata launch --plan` prints them: `GPU 2 (--gpu 1) RTX 4070 Ti`.""" 448cs = {_idx (c ):c for c in cards } 449parts = [] 450for role ,word in (("main" ,"Main" ), ("helper" ,"Helper" ), ("off" ,"Off" )): 451label = (lambda i :f"GPU { i + 1 } (--gpu { i } )" )if card_numbers else (lambda i :f"GPU { i + 1 } " ) 452names = [f" { label ( i ) } { short_name ( cs [ i ]) } " if i in cs else label (i )for i in sorted (roles )if roles [i ]== role ] 453if names : 454parts .append (f" { word } : { ', ' . join ( names ) } ." ) 455return " " .join (parts ) 456 457 458# ---- the cards the environment leaves visible ------------------------------------------------------------------------------------------------ 459 460def _ordinals (value :str | None ,indexes :list [int ])-> list [int ]| None : 461"""The card numbers a visibility list (``1,0``) names, in its order, over `indexes` (the cards in ordinal order). An entry that is not a card ends the list, as 462the CUDA and HIP runtimes read it. None: not set, or it names cards by something other than a number (a UUID), which this cannot map.""" 463if value is None : 464return None 465if not value .strip (): 466return [] 467out :list [int ]= [] 468for tok in value .split ("," ): 469tok = tok .strip () 470if not tok .lstrip ("-" ).isdigit (): 471return None 472n = int (tok ) 473if n < 0 or n >= len (indexes ): 474break 475out .append (indexes [n ]) 476return out 477 478 479def env_visible (indexes :list [int ],vendor :str | None ,environ :dict | None = None ,* ,alike :bool = False )-> list [int ]| None : 480"""The card numbers (the numbers `--gpu` takes) that CUDA_VISIBLE_DEVICES leaves visible (NVIDIA), or ROCR_VISIBLE_DEVICES and then HIP_VISIBLE_DEVICES (AMD); None when 481nothing restricts them or the list cannot be read (a UUID, or CUDA's own card order when the cards differ and CUDA_DEVICE_ORDER is not PCI_BUS_ID). 482`alike`: the cards are all one model, so their order does not matter.""" 483import os 484env = os .environ if environ is None else environ 485cards = sorted (indexes ) 486if vendor == "amd" : 487seen :list [int ]| None = None 488for name in ("ROCR_VISIBLE_DEVICES" ,"HIP_VISIBLE_DEVICES" ): 489raw = env .get (name ) 490if raw is None : 491continue 492got = _ordinals (raw ,seen if seen is not None else cards ) 493if got is None : 494return None 495seen = got 496return seen 497if vendor != "nvidia" : 498return None 499raw = env .get ("CUDA_VISIBLE_DEVICES" ) 500if raw is not None and raw .strip ()and len (cards )> 1 and not alike and str (env .get ("CUDA_DEVICE_ORDER" )or "" ).strip ().upper ()!= "PCI_BUS_ID" : 501return None # numbers in CUDA's own card order (fastest first) cannot be told from nvidia-smi's here 502return _ordinals (raw ,cards ) 503 504 505def visible_cards (cards :list [dict ],vendor :str | None ,environ :dict | None = None ,keep :set [int ]| frozenset [int ]= frozenset ())-> list [dict ]: 506"""`cards` without the ones the environment hides (env_visible); a card in `keep` (named with --gpu, which the server sets the visibility from) stays.""" 507vis = env_visible ([_idx (c )for c in cards ],vendor ,environ ,alike = len ({(str (c .get ("name" )),rnd_ (_mem (c )))for c in cards })<= 1 ) 508if vis is None : 509return list (cards ) 510return [c for c in cards if _idx (c )in vis or _idx (c )in keep ] 511 512 513# ---- speed of each card (the same measure the engine orders a split by: multiprocessors x max clock) ------------------------------------ 514 515def nvidia_speeds (timeout :float = 20.0 )-> dict [int ,float ]: 516"""{nvidia-smi number: SMs x max clock} from the CUDA driver API in a child process (no toolkit needed); {} when it cannot say.""" 517import os 518import subprocess 519import sys 520code = ("import ctypes,sys,os\n" 521"os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID'\n" 522"lib=ctypes.CDLL('nvcuda.dll' if os.name=='nt' else 'libcuda.so.1')\n" 523"assert lib.cuInit(0)==0\n" 524"n=ctypes.c_int()\n" 525"assert lib.cuDeviceGetCount(ctypes.byref(n))==0\n" 526"for i in range(n.value):\n" 527" d=ctypes.c_int()\n" 528" assert lib.cuDeviceGet(ctypes.byref(d),i)==0\n" 529" sm=ctypes.c_int(); mhz=ctypes.c_int()\n" 530" lib.cuDeviceGetAttribute(ctypes.byref(sm),16,d)\n" 531" lib.cuDeviceGetAttribute(ctypes.byref(mhz),13,d)\n" 532" print(i,sm.value,mhz.value)\n" ) 533try : 534env = dict (os .environ ) 535env ["CUDA_DEVICE_ORDER" ]= "PCI_BUS_ID" 536env .pop ("CUDA_VISIBLE_DEVICES" ,None ) 537r = subprocess .run ([sys .executable ,"-c" ,code ],capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ,env = env ) 538out = {} 539for line in r .stdout .splitlines (): 540i ,sm ,khz = (int (x )for x in line .split ()) 541if sm > 0 and khz > 0 : 542out [i ]= float (sm )* float (khz ) 543return out 544except (OSError ,ValueError ,subprocess .SubprocessError ): 545return {} 546 547 548def add_speeds (gpus :list [dict ])-> None : 549"""Puts "speed" on the NVIDIA cards of a hardware report (in place); a card it cannot measure keeps none.""" 550nv = [g for g in gpus if str (g .get ("vendor" ))== "nvidia" ] 551if not nv : 552return 553sp = nvidia_speeds () 554for g in nv : 555if g .get ("index" )in sp : 556g ["speed" ]= sp [g ["index" ]]