okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f31abf7bd
main
1"""Which graphics cards a model should use: ONE place for the app, `strata launch` and setup. 2 3The rule (owner decision): 41. First try the model on ONE card (the largest) plus system RAM, the normal hybrid mode. 52. Only when that does not fit, or would be too tight, offer to add the second card as a layer split. 63. Let the person choose: every option comes with plain numbers and a recommended one is pre-selected (recommend, never force). 7 8The memory arithmetic is native-fit.ts `fitOn` (apps/host/src/lib/native-fit.ts) with the same constants (a test keeps them equal): 9the experts are held first in the graphics memory beyond about DENSE_GB (the dense weights, buffers and a 32K cache), then in RAM beyond 10about SYSTEM_ROOM_GB left for the system; whatever is left would be read from the SSD (`spill_gb`). A split adds the memory of the extra 11cards but every extra card holds its own dense layers and prompt buffers, so each one costs SPLIT_CARD_OVERHEAD_GB of that (an estimate: 12docs/MULTI_GPU.md says each card "holds the dense weights of its layers and its own prompt buffers"). 13 14Cards that count: not integrated (an iGPU shares the system RAM and is ignored), at least MIN_CARD_GB of graphics memory, flagged usable by 15the caller's own driver checks (NVIDIA RTX 20 or newer, a supported AMD card, ...). A card needs SPLIT_MIN_VRAM_GB to share a model. 16Pure functions, no I/O: setup.py, strata_cli/launch and tools/strata_mcp.py import it. 17""" 18 19from __future__import annotations 20 21from typing import Any 22 23DENSE_GB = 5.0 # = native-fit.ts DENSE_GB 24SYSTEM_ROOM_GB = 10.0 # = native-fit.ts SYSTEM_ROOM_GB 25DENSE_EXTRA_GB = 1.0 # = native-fit.ts DENSE_EXTRA_GB 26SPLIT_CARD_OVERHEAD_GB = 2.0 # each extra card of a split: its own dense layers and prompt buffers 27SPLIT_MIN_VRAM_GB = 8.0 # setup.py SPLIT_MIN_VRAM_GB: a card sharing a model needs this much 28SPLIT_PROMPT_VRAM_GB = 12.0 # setup.py SPLIT_PROMPT_VRAM_GB (#448): a smaller second card caps the prompt chunk 29MIN_CARD_GB = 4.0 # under this a card cannot hold the dense weights: ignored (an iGPU, a display card) 30FITS_SPARE_RAM_GB = 4.0 # RAM left beyond the experts below which "fits" becomes "tight" 31SPLIT_PROMPT_GAIN = "about 20% faster" # setup.py's own words for prompts read on two cards (docs/MULTI_GPU.md) 32 33 34def _round1 (x :float )-> float : 35return round (float (x )* 10 )/ 10 36 37 38# ---- one engine, one vendor ----------------------------------------------------------------------------------------------- 39# Every Strata engine package drives the cards of ONE vendor (CUDA: NVIDIA, HIP: AMD, SYCL: Intel, Metal: Apple). A model is never split 40# across vendors, and two models at once, one per vendor, is not supported yet. So the cards offered for running and splitting are the 41# ones the engine can drive; a better card of the other vendor is mentioned in one plain line (recommend, never force). 42BACKEND_VENDOR = {"cuda" :"nvidia" ,"hip" :"amd" ,"sycl" :"intel" ,"metal" :"apple" } 43VENDOR_NAME = {"nvidia" :"NVIDIA" ,"amd" :"AMD" ,"intel" :"Intel" ,"apple" :"Apple" } 44SECOND_MODEL_SENTENCE = ("Running two models at the same time, one on each make of graphics card, is not supported yet. " 45"Strata runs one model at a time on the cards of one make." ) 46 47 48def vendor_of_backend (backend :str | None )-> str | None : 49return BACKEND_VENDOR .get (str (backend or "" ).lower ()) 50 51 52def _vendor (card :dict )-> str | None : 53v = card .get ("vendor" ) 54return str (v ).lower ()if v else None 55 56 57def pick_vendor (cards :list [dict ],backend :str | None = None )-> str | None : 58"""The make of card the engine drives: the installed (or detected) engine's, else the only make among the cards that count; with more 59than one make, NVIDIA (the engine setup picks first), else the make of the card with the most memory. None: no card names a make.""" 60named = vendor_of_backend (backend ) 61if named : 62return named 63keep ,_ = usable_cards (cards ) 64makes = {_vendor (c )for c in keep if _vendor (c )} 65if len (makes )<= 1 : 66return next (iter (makes ),None ) 67if "nvidia" in makes : 68return "nvidia" 69return _vendor (keep [0 ]) 70 71 72def for_vendor (cards :list [dict ],vendor :str | None )-> tuple [list [dict ],list [dict ]]: 73"""(the cards the engine of that make can drive, the cards of other makes). A card that names no make goes with the engine's.""" 74if not vendor : 75return list (cards or []), [] 76mine = [c for c in cards or []if _vendor (c )in (None ,vendor )] 77return mine , [c for c in cards or []if _vendor (c )not in (None ,vendor )] 78 79 80def _short_name (c :dict ,vendor :str )-> str : 81n = str (c .get ("name" )or "graphics card" ) 82for junk in ("NVIDIA GeForce " ,"NVIDIA " ,"AMD Radeon " ,"AMD " ,"Intel " ): 83if n .startswith (junk ): 84n = n [len (junk ):] 85break 86return f" { VENDOR_NAME . get ( vendor , vendor . title ()) } { n } " .strip () 87 88 89# ---- UD-Q4_K_XL on a Strix Halo (0.2.10) ------------------------------------------------------------------------------------------------ 90# REMOVE this block, its three callers (setup.py "size:", strata_cli/launch/cmd.py apply_defaults, tests/terminal/test_strix_q4_note.py) when the 91# stall is fixed in the engine (STRIX-2Q). The numbers are the 0.2.9 release notes'. 92STRIX_Q4_MODEL = "UD-Q4_K_XL" 93STRIX_Q4_NOTE = ("UD-Q4_K_XL on a Ryzen AI Max (Strix Halo) can stop on the first request after a start, with no CPU or disk activity: 7 of 30 " 94"starts did on the 0.1.55 engine and 2 of 5 on 0.1.54. If it happens, stop the engine and start it again. UD-IQ4_XS ran 99 " 95"starts in the same setup without stopping; choose it if you want to be sure. Nothing is refused." ) 96 97 98def is_strix_halo_card (card :dict )-> bool : 99"""A Ryzen AI Max (Strix Halo, gfx1151, Radeon 8060S / 8050S / 8040S) from the fields the hardware readers give.""" 100if not isinstance (card ,dict ): 101return False 102text = " " .join (str (card .get (k )or "" )for k in ("name" ,"arch" ,"gfx" )).lower () 103return "gfx1151" in text or "strix halo" in text or any (x in text for x in ("8060s" ,"8050s" ,"8040s" )) 104 105 106def strix_q4_stall_note (model ,cards )-> str | None : 107"""The plain warning for UD-Q4_K_XL on a Strix Halo, else None. Warn only.""" 108if str (model or "" ).lower ()!= STRIX_Q4_MODEL .lower (): 109return None 110return STRIX_Q4_NOTE if any (is_strix_halo_card (c )for c in cards or [])else None 111 112 113def other_vendor_note (cards :list [dict ],vendor :str | None )-> str | None : 114"""One plain line when the other make's best card is bigger than the best card the engine can use, else None: 115"This computer also has an AMD R9700 (32 GB). The AMD build of Strata can use it - it fits bigger models." """ 116if not vendor : 117return None 118mine ,others = for_vendor (usable_cards (cards )[0 ],vendor ) 119others = [c for c in others if _vendor (c )and not _shares_memory (c )] 120if not others : 121return None 122intel = [c for c in others if _vendor (c )== "intel" ] 123if intel : 124# Intel Arc cards beside another make: always said (the engine for one make runs at a time; the person chooses which), never refused 125total = sum (float (c .get ("vram_gb" )or 0 )for c in intel ) 126cards = (f" { len ( intel ) } Intel Arc cards ( { total :.0f } GB together)" if len (intel )> 1 127else f"an { _short_name ( intel [ 0 ], 'intel' ) } ( { total :.0f } GB)" ) 128return (f"This computer also has { cards } . Strata uses the { VENDOR_NAME . get ( vendor , vendor ) } card; to use the Intel card" 129f" { 's' if len ( intel ) > 1 else '' } instead, add --backend intel (it is remembered; --backend auto goes back)." ) 130if vendor == "intel" : 131names = ", " .join (sorted ({_short_name (c ,_vendor (c ))for c in others })) 132return (f"This computer also has { names } . Strata uses the Intel cards; --backend auto goes back to the PC's own choice " 133"(NVIDIA first)." ) 134best = max (others ,key = lambda c :float (c .get ("vram_gb" )or 0 )) 135mine_best = max ((float (c .get ("vram_gb" )or 0 )for c in mine ),default = 0.0 ) 136if float (best .get ("vram_gb" )or 0 )<= mine_best : 137return None 138other = _vendor (best ) 139return (f"This computer also has an { _short_name ( best , other ) } ( { float ( best . get ( 'vram_gb' ) or 0 ):.0f } GB). " 140f"The { VENDOR_NAME . get ( other , other . title ()) } build of Strata can use it — it fits bigger models." ) 141 142 143def memory_needed (variant :dict )-> float : 144"""RAM + VRAM the model asks for (native-fit.ts memoryNeeded).""" 145if isinstance (variant .get ("memory_gb" ), (int ,float )): 146return float (variant ["memory_gb" ]) 147if variant .get ("mem_total" )and isinstance (variant .get ("ram_needed_gb" ), (int ,float )): 148return float (variant ["ram_needed_gb" ]) 149return _round1 (float (variant .get ("experts_gb" )or variant .get ("ram_needed_gb" )or 0 )+ DENSE_EXTRA_GB ) 150 151 152def fit (memory_gb :float ,ram_gb :float | None ,vram_gb :float )-> dict [str ,Any ]: 153"""native-fit.ts `fitOn` for a given memory need: where the weights go. Keys: vram_use_gb, ram_use_gb, spill_gb, spare_ram_gb, known.""" 154vram = float (vram_gb or 0 ) 155if not ram_gb or ram_gb <= 0 : 156return {"vram_use_gb" :0.0 ,"ram_use_gb" :0.0 ,"spill_gb" :0.0 ,"spare_ram_gb" :0.0 ,"known" :False } 157experts = max (0.0 ,memory_gb - DENSE_EXTRA_GB ) 158on_gpu = max (0.0 ,min (experts ,vram - DENSE_GB )) 159ram_room = max (0.0 ,float (ram_gb )- SYSTEM_ROOM_GB ) 160spill = max (0.0 ,experts - on_gpu - ram_room ) 161in_ram = max (0.0 ,experts - on_gpu - spill ) 162return {"vram_use_gb" :_round1 (min (vram ,DENSE_GB + on_gpu )if vram > 0 else 0.0 ), 163"ram_use_gb" :_round1 (in_ram + (DENSE_EXTRA_GB if vram <= 0 else 0 )),"spill_gb" :_round1 (spill ), 164"spare_ram_gb" :_round1 (max (0.0 ,ram_room - in_ram )),"known" :True } 165 166 167def verdict (f :dict )-> str : 168"""fits / tight / spills: all in memory with room to spare / all in memory but little RAM left / part of it is read from the SSD.""" 169if not f .get ("known" ): 170return "unknown" 171if f ["spill_gb" ]>= 1.0 : 172return "spills" 173return "fits" if f ["spare_ram_gb" ]>= FITS_SPARE_RAM_GB or f ["ram_use_gb" ]<= 0 else "tight" 174 175 176def _shares_memory (c :dict )-> bool : 177"""An integrated chip or a unified-memory chip (Apple, Strix Halo): its memory is the system RAM.""" 178return bool (c .get ("integrated" )or c .get ("uma" )or c .get ("unified_memory" )or c .get ("unified_gb" )or str (c .get ("vendor" ))== "apple" ) 179 180 181def usable_cards (cards :list [dict ])-> tuple [list [dict ],list [dict ]]: 182"""(cards that count, cards ignored with a plain reason in 'why_ignored'). Largest memory first, then the card number. 183 184A chip that shares the system memory is ignored when the computer has a card with memory of its own (it adds nothing to it); when it is 185the only device (a Mac, a Strix Halo PC) it is the one that counts. A card under MIN_CARD_GB cannot hold the dense weights.""" 186flagged = [c for c in (cards or [])if c .get ("usable" )is not False ] 187has_real = any (not _shares_memory (c )and float (c .get ("vram_gb" )or 0 )>= MIN_CARD_GB for c in flagged ) 188keep ,ignored = [], [] 189for c in cards or []: 190vram = float (c .get ("vram_gb" )or 0 ) 191why = None 192if c .get ("usable" )is False : 193why = c .get ("problem" )or "Strata cannot use this card" 194elif _shares_memory (c ): 195if has_real : 196why = "it shares the system memory (an integrated graphics chip), so it adds nothing" 197elif vram < MIN_CARD_GB : 198why = f"only { vram :.0f } GB of graphics memory" 199if why : 200ignored .append ({** c ,"why_ignored" :why }) 201else : 202keep .append (c ) 203keep .sort (key = lambda c : (- round (float (c .get ("vram_gb" )or c .get ("unified_gb" )or 0 )),c .get ("index" ,0 ))) 204return keep ,ignored 205 206 207def _name (c :dict )-> str : 208n = str (c .get ("name" )or f"card { c . get ( 'index' ) } " ) 209for junk in ("NVIDIA GeForce " ,"NVIDIA " ,"AMD Radeon " ,"AMD " ): 210n = n .replace (junk ,"" ) 211return n + (f" (card { c . get ( 'index' ) } )" if c .get ("_dup" )else "" ) 212 213 214def own_memory_gb (c :dict )-> float : 215"""The graphics memory a card adds BESIDE the RAM. A discrete card: its VRAM. A chip that shares the system memory (Strix Halo, an APU): only 216its BIOS carve-out (`dedicated_gb`; 0 when the report does not give it) - its "shared" pool is the RAM itself, and counting it as VRAM as well as 217as RAM made a model look like it fit twice (setup.py low_ram_vram does the same).""" 218if c .get ("uma" )or c .get ("integrated" ): 219return float (c .get ("dedicated_gb" )or 0 ) 220return float (c .get ("vram_gb" )or 0 ) 221 222 223def _option (key :str ,cards :list [dict ],memory_gb :float ,ram_gb :float | None )-> dict [str ,Any ]: 224n = len (cards ) 225total = sum (own_memory_gb (c )for c in cards ) 226eff = total - SPLIT_CARD_OVERHEAD_GB * (n - 1 ) 227f = fit (memory_gb ,ram_gb ,eff ) 228v = verdict (f ) 229names = " + " .join (_name (c )for c in cards ) 230label = f" { names } + RAM" if n == 1 else f" { names } + RAM (layer split)" 231have = (eff + max (0.0 ,float (ram_gb or 0 )- SYSTEM_ROOM_GB )) 232if v == "unknown" : 233words = "memory of this computer unknown" 234elif v == "spills" : 235words = f"does not fit in memory: about { f [ 'spill_gb' ]:.0f } GB is read from the SSD while answering (slower)" 236elif v == "tight" : 237words = f"fits, but tight: needs { memory_gb :.0f } GB of the { have :.0f } GB available" 238else : 239words = f"fits: needs { memory_gb :.0f } GB of the { have :.0f } GB available" 240notes = [] 241if n >= 2 : 242notes .append (f"prompts are read { SPLIT_PROMPT_GAIN } ; the cards share the layers (docs/MULTI_GPU.md)" ) 243small = [c for c in cards [1 :]if float (c .get ("vram_gb" )or 0 )< SPLIT_PROMPT_VRAM_GB - 0.5 ] 244if small and float (cards [0 ].get ("vram_gb" )or 0 )>= SPLIT_PROMPT_VRAM_GB - 0.5 : 245notes .append (f" { _name ( small [ 0 ]) } is small: it can make prompts slower than the first card alone" ) 246return {"key" :key ,"cards" : [c .get ("index" )for c in cards ],"label" :label ,"verdict" :v ,"summary" :f" { label } : { words } " , 247"words" :words ,"vram_gb" :_round1 (total ),"spill_gb" :f ["spill_gb" ],"ram_use_gb" :f ["ram_use_gb" ], 248"spare_ram_gb" :f ["spare_ram_gb" ],"notes" :notes ,"recommended" :False } 249 250 251_RANK = {"fits" :0 ,"tight" :1 ,"unknown" :2 ,"spills" :3 } 252 253 254def options (memory_gb :float ,ram_gb :float | None ,cards :list [dict ],vendor :str | None = None )-> dict [str ,Any ]: 255"""The choices for this model on this computer: {"options": [...], "recommended": key, "ignored": [...], "cards": n counted}. 256 257Options (best known first): the largest card alone; with two or more cards that can share a model, the two largest as a layer split 258(and all of them when there are more than two); then every other card alone. Exactly one option is recommended: 259the single largest card when the model fits it (with RAM); otherwise the split if it fits better (a smaller verdict or less SSD use); 260otherwise the single largest card again (nothing better to offer).""" 261vendor = vendor or pick_vendor (cards ) 262mine ,others = for_vendor (cards ,vendor ) 263keep ,ignored = usable_cards (mine ) 264ignored = ignored + [{** c ,"why_ignored" :f"it needs the { VENDOR_NAME . get ( _vendor ( c ), _vendor ( c )) } build of Strata, and this engine drives " 265f" { VENDOR_NAME . get ( vendor , vendor ) } cards" }for c in others ] 266out :dict [str ,Any ]= {"options" : [],"recommended" :None ,"ignored" :ignored ,"cards" :len (keep ),"vendor" :vendor , 267"other_vendor_note" :other_vendor_note (cards ,vendor )} 268if not keep : 269return out 270names = [str (c .get ("name" ))for c in keep ] 271keep = [{** c ,"_dup" :names .count (str (c .get ("name" )))> 1 }for c in keep ]# two cards of one model: told apart by their number 272opts = [_option ("single" , [keep [0 ]],memory_gb ,ram_gb )] 273share = [c for c in keep if float (c .get ("vram_gb" )or 0 )>= SPLIT_MIN_VRAM_GB - 0.5 ] 274if len (share )>= 2 : 275opts .append (_option ("split" ,share [:2 ],memory_gb ,ram_gb )) 276if len (share )> 2 : 277opts .append (_option ("split-all" ,share ,memory_gb ,ram_gb )) 278for c in keep [1 :]: 279opts .append (_option (f"single- { c . get ( 'index' ) } " , [c ],memory_gb ,ram_gb )) 280single = opts [0 ] 281best = single 282if single ["verdict" ]!= "fits" : 283for o in opts [1 :]: 284if len (o ["cards" ])> 1 and (_RANK [o ["verdict" ]],o ["spill_gb" ])< (_RANK [best ["verdict" ]],best ["spill_gb" ]): 285best = o 286best ["recommended" ]= True 287out ["options" ],out ["recommended" ]= opts ,best ["key" ] 288return out 289 290 291def recommended_cards (memory_gb :float ,ram_gb :float | None ,cards :list [dict ],vendor :str | None = None )-> list [int ]: 292"""The card numbers of the recommended option (empty: no usable card).""" 293res = options (memory_gb ,ram_gb ,cards ,vendor ) 294return next ((o ["cards" ]for o in res ["options" ]if o ["recommended" ]), [])