okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The setup seam: the run config `setup.py` writes, built from what setup has decided and found. 2 3This is a MOVE of the lines that stood in `setup.py`'s main() between the model arguments and `write_setup_config()` (the engine arguments, the 4speed switches, the cards, the vision section, the calibration). Nothing in the body changed; the names it used are now an explicit list: 5 6* `SetupInputs` - what setup decided or found before this point (the cards, the RAM, the context, the model files, the engine's build file). Each field has the 7name the body uses. 8* `lib` - the module that still holds the helper functions and constants (`setup.py` today; the helpers move here in step 5.1). Probes of the machine 9(nvidia-smi, the disk kind, the compute mode, the saved calibration) are reached through `lib`, so a caller that passes another object answers them 10without a machine. 11 12`config_for` prints its notes through `lib.say/ok/warn` exactly as before, and returns the run config; setup writes it with `write_setup_config()`. 13""" 14 15from __future__import annotations 16 17import os 18import sys 19from dataclasses import dataclass 20from pathlib import Path 21from typing import Any 22 23#: The reserve a Windows Strix Halo config gets when nothing else gives one: the engine's own default (--vram-reserve-mib 700), written down so the engine's 24#: Windows floor of 2560 MiB does not replace it (G16). The app's own reserve and the one pictures on write are 700 or more already, so this is one rule for 25#: every size on a single-card Windows Strix Halo (no size threshold: a new model of unknown size could hang the same way). 26UMA_WIN_RESERVE_MIB = 700 27 28 29@dataclass 30class SetupInputs : 31a :Any = None 32adopted :Any = None 33chosen :Any = None 34cuda_tk :Any = None 35draft_vocab :Any = None 36eng :Any = None 37engine_ver :Any = None 38esp :Any = None 39fam :Any = None 40family :Any = None 41gpu :Any = None 42hip :Any = None 43in_budget :Any = None 44lib_dirs :Any = None 45low_ram :Any = None 46meta :Any = None 47mmproj :Any = None 48model :Any = None 49model_args :Any = None 50models_dir :Any = None 51multi :Any = None 52pack :Any = None 53ple :Any = None 54port :Any = None 55q4_split :Any = None 56ram :Any = None 57reader :Any = None 58ready :Any = None 59rope_scale :Any = None 60rt :Any = None 61scaling :Any = None 62shards :Any = None 63tag :Any = None 64vision :Any = None 65ctx :Any = None 66kv :Any = None 67resident :Any = None 68budget :Any = None 69GGUFFile :Any = None 70 71 72@dataclass 73class SetupConfig : 74cfg :dict 75cfg_path :Path 76cal :Any 77args :list 78ctx :int 79kv :str 80resident :bool 81 82 83def neutral_profile_if_other_shape (shipped ,first_shard ,pack ,GGUFFile ,say = """The shipped expert profile ranks the (layer, expert) pairs of Flash-Next (48 layers x 512 experts; the Coder 48 x 256). The engine refuses a profile of another 85shape ("it is a profile for a different artifact"), so a model of another shape (a new Qwen4 size from the feed) gets a NEUTRAL one in its pack folder: every pair 86once, interleaved across the layers, nothing learned. The first run's `--expert-profile-save` can replace it. Returns the profile to use.""" 87import struct 88try : 89meta = GGUFFile (first_shard ).metadata 90n_layer = next (int (v )for k ,v in meta .items ()if k .endswith (".block_count" )) 91n_expert = next (int (v )for k ,v in meta .items ()if k .endswith (".expert_count" )) 92blob = Path (shipped ).read_bytes ()[:24 ] 93_ver ,have_l ,have_e ,_slots ,_n = struct .unpack_from ("<5I" ,blob ,4 ) 94if blob [:4 ]== b"STRP" and (have_l ,have_e )== (n_layer ,n_expert ): 95return Path (shipped ) 96out = Path (pack )/ f"expert-profile- { n_layer } x { n_expert } .bin" 97if not out .exists (): 98ranked = [(layer ,e )for e in range (n_expert )for layer in range (n_layer )] 99table = [[- 1 ]* n_expert for _ in range (n_layer )] 100for slot , (layer ,e )in enumerate (ranked ): 101table [layer ][e ]= slot 102with open (out ,"wb" )as f : 103f .write (b"STRP" + struct .pack ("<5I" ,1 ,n_layer ,n_expert ,len (ranked ),len (ranked ))) 104for layer ,e in ranked : 105f .write (struct .pack ("<HH" ,layer ,e )) 106for layer in range (n_layer ): 107f .write (struct .pack ("<%di" % n_expert ,* table [layer ])) 108say (" This model's shape differs from Flash-Next, so a neutral expert profile is used." ) 109return out 110except (OSError ,ValueError ,StopIteration ,struct .error ): 111return Path (shipped ) 112 113 114def config_for (inp :SetupInputs ,lib )-> SetupConfig : 115# ---- the names the body uses: what setup decided (inp) and the helpers (lib) 116a = inp .a 117adopted = inp .adopted 118chosen = inp .chosen 119cuda_tk = inp .cuda_tk 120draft_vocab = inp .draft_vocab 121eng = inp .eng 122engine_ver = inp .engine_ver 123esp = inp .esp 124fam = inp .fam 125family = inp .family 126gpu = inp .gpu 127hip = inp .hip 128in_budget = inp .in_budget 129lib_dirs = inp .lib_dirs 130low_ram = inp .low_ram 131meta = inp .meta 132mmproj = inp .mmproj 133model = inp .model 134model_args = inp .model_args 135models_dir = inp .models_dir 136multi = inp .multi 137pack = inp .pack 138ple = inp .ple 139port = inp .port 140q4_split = inp .q4_split 141ram = inp .ram 142reader = inp .reader 143ready = inp .ready 144rope_scale = inp .rope_scale 145rt = inp .rt 146scaling = inp .scaling 147shards = inp .shards 148tag = inp .tag 149vision = inp .vision 150ctx = inp .ctx 151kv = inp .kv 152resident = inp .resident 153budget = inp .budget 154GGUFFile = inp .GGUFFile 155CONTROL = lib .CONTROL 156DISPLAY_RESERVE_MIB = lib .DISPLAY_RESERVE_MIB 157GFX1103_OPT_IN = lib .GFX1103_OPT_IN 158GFX1103_SWITCHES = lib .GFX1103_SWITCHES 159GFX1150_OPT_IN = lib .GFX1150_OPT_IN 160GFX1150_SWITCHES = lib .GFX1150_SWITCHES 161MODELS = lib .MODELS 162RESIDENT_ENGINE = lib .RESIDENT_ENGINE 163ROOT = lib .ROOT 164SMALL_CARD_GB = lib .SMALL_CARD_GB 165UD_FIT_CARD_GB = lib .UD_FIT_CARD_GB 166UD_FIT_ENGINE_RESERVE_MIB = lib .UD_FIT_ENGINE_RESERVE_MIB 167UD_FIT_MIN_SLACK_MIB = lib .UD_FIT_MIN_SLACK_MIB 168UNSLOTH_RAM_LEFT_GB = lib .UNSLOTH_RAM_LEFT_GB 169VEXE = lib .VEXE 170VISION = lib .VISION 171VISION_GPU_SMALL_RESERVE_MIB = lib .VISION_GPU_SMALL_RESERVE_MIB 172WIN = lib .WIN 173apu_hides_chunk_tip = lib .apu_hides_chunk_tip 174bench_tips = lib .bench_tips 175compute_mode_warning = lib .compute_mode_warning 176cpu_sockets = lib .cpu_sockets 177desktop_reserve_note = lib .desktop_reserve_note 178draft_layer = lib .draft_layer 179engine_exe = lib .engine_exe 180gfx_arch_is = lib .gfx_arch_is 181gpu_compute_mode = lib .gpu_compute_mode 182gpu_drives_display = lib .gpu_drives_display 183hipblaslt_table = lib .hipblaslt_table 184home = lib .home 185is_gb10 = lib .is_gb10 186is_wsl = lib .is_wsl 187kv_streaming_need_gb = lib .kv_streaming_need_gb 188kv_streaming_ram_gb = lib .kv_streaming_ram_gb 189linux_desktop = lib .linux_desktop 190ok = lib .ok 191parallel_note = lib .parallel_note 192ple_ram_platform_ok = lib .ple_ram_platform_ok 193pool_workers_note = lib .pool_workers_note 194ready_paths = lib .ready_paths 195recommend_pool_workers = lib .recommend_pool_workers 196recommend_remote_expert_opt = lib .recommend_remote_expert_opt 197resident_budget_gib = lib .resident_budget_gib 198rotational_disk = lib .rotational_disk 199say = lib .say 200setup_calibration = lib .setup_calibration 201setup_images = lib .setup_images 202small_card_note = lib .small_card_note 203two_socket_note = lib .two_socket_note 204uma_expert_cache = lib .uma_expert_cache 205unsloth_default_env = lib .unsloth_default_env 206unsloth_runtime_mib = lib .unsloth_runtime_mib 207unsloth_small_card_lines = lib .unsloth_small_card_lines 208unsloth_small_card_plan = lib .unsloth_small_card_plan 209unsloth_vram_slack_mib = lib .unsloth_vram_slack_mib 210vision_threads = lib .vision_threads 211vision_tokens = lib .vision_tokens 212warn = lib .warn 213# ---- the moved lines (unchanged) 214profile = ROOT / "data" / fam .get ("profile" ,"expert-profile.bin" ) 215if fam .get ("feed" )and shards : 216profile = neutral_profile_if_other_shape (profile ,shards [0 ],pack ,GGUFFile ,say )# a feed model of another shape than the shipped profile's 217args = [* model_args , 218"--expert-profile" ,str (profile ),"--expert-cache" ,"auto" , 219"--prefill" ,"auto" ,"--spec" ,"4" ,"--spec-min-p" ,"0.5" ,"--mtp" ,str (rt ), 220"--max-context" ,str (ctx )] 221if scaling is not None :# the resolved config: explicit flags as given, or the automatic yarn+factor 222args += ["--rope-scaling" ,scaling ,"--rope-scale" ,f" { rope_scale :g } " ] 223if ctx > 8192 : 224args += ["--kv" ,kv ] 225if resident and a .low_ram != "resident" and engine_ver < RESIDENT_ENGINE : 226resident = False # an engine from before --resident-experts would refuse it 227ok (f"low-RAM mode: engine { meta . get ( 'version' ) } has no resident variant yet; the experts are read through " 228"the OS file cache (run setup again after the next engine update)" ) 229if low_ram and ready : 230# NVFP4 (68 GB of experts) on a PC whose RAM does not hold them: the RAM-budget mode, as Unsloth's files - the 231# most-used experts outside VRAM pinned within RAM less 24 GB, the rest read from experts.bin. Mapped 232# (--mmap-experts) on a 64 GB Windows PC, the experts it read stayed in the engine's working set: free RAM 233# fell to 0.6 GB on the RTX 5070 PC (2026-10-13), where the budget mode kept 22 GB free 234rb = resident_budget_gib (model ,ram ) 235args += ["--resident-budget-gib" ,str (rb )] 236ok (f"low-RAM mode: { rb } GiB of { model } 's experts kept in RAM (the most used), the rest read from the pack's " 237"experts.bin on the SSD as needed" ) 238elif low_ram :# the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped 239args += ["--resident-experts" if resident else "--mmap-experts" ] 240elif is_gb10 (gpu ): 241# a DGX Spark: the RAM copy of the experts and the GPU's cache are the same memory. Mapped, every expert fits in the cache (NVFP4 242# on a 128 GB GB10: 24576 of 24576 slots, not 13702; chat decode 44.4 against 40.6 tok/s, 16K prompt 1471 against 1397) 243args += ["--mmap-experts" ] 244ok ("unified memory: the experts are read from the model files in place (--mmap-experts), so the GPU's cache holds them " 245"instead of a second copy in RAM" ) 246# the measured settings of this part (docs/DGX_SPARK_LINUX.md): the 32,768-token prompt chunk (auto's 8,192 measured 2-6% slower 247# here); the draft layer as 4-bit copies (+3.5% decode, 3 paired rounds, answers identical: the drafter's proposals are verified 248# by the target); one norm per hyper-connection stream in the draft layer (llama.cpp's graph: acceptance 0.60 -> 0.63, decode +4.3% 249# [1.009, 1.078], 5 of 5 greedy answers identical) 250if "--prefill" in args : 251args [args .index ("--prefill" )+ 1 ]= "auto:32768" 252if "--mtp" in args : 253args += ["--mtp-q4" ,"all" ,"--mtp-hnorm" ,"stream" ] 254ok ("prompt chunk 32,768 (--prefill auto:32768), the draft layer as 4-bit copies (--mtp-q4 all) and one norm per " 255"hyper-connection stream in it (--mtp-hnorm stream): measured faster on this part, the answers are unchanged" ) 256# the language is the user's choice: the default subset keeps Chinese, Japanese and Korean drafts, the English one measured +3.1% 257# decode on English prompts here (16 samples a cell, 90% interval [1.018, 1.049]) 258say (" Tip: for English or code only, --draft-vocab en measured +3.1% decode on this part (the default keeps Chinese, Japanese " 259"and Korean drafts)." ) 260disk = None if is_wsl ()else rotational_disk (ple )# #605 (WSL's virtual disk says rotational) 261if disk : 262tensor = None if ready else next ((t for t in GGUFFile (ple ).tensors if t .name == "per_layer_token_embd.weight" ),None ) 263size = ple .stat ().st_size if ready else getattr (tensor ,"expected_bytes" ,lambda :None )() 264table_gb = size / 1e9 if size else 28.8 265if ram >= MODELS [model ]["ram_gb" ]+ table_gb + 4 : 266args += ["--ple-io" ,"ram" ] 267ok (f"the model is on a rotational disk ( { disk } ): its { table_gb :.0f } GB n-gram table is kept in RAM " 268"(--ple-io ram) - read from the disk at random, it can stall prompts for minutes (#605)" ) 269else : 270warn (f"the model is on a rotational disk ( { disk } ): its n-gram table is read from it at random, which can " 271f"stall prompts for minutes (#605). An SSD is recommended; with ~ { table_gb :.0f } GB more RAM, " 272"--ple-io ram in the config's args keeps the table in RAM instead" ) 273elif not low_ram and ple_ram_platform_ok (): 274# 147-verify: on an SSD too, a PC with RAM to spare keeps the n-gram table in RAM: a new prompt's first chunk then 275# does not wait for its table rows (65,536 random SSD reads at 4K tokens). RTX PRO 5000 (Linux, NVMe, fresh engine 276# per prompt, 3 rounds, the same bits): prompt 4K 1298 -> 1059 ms (-18%), 20K 4644 -> 4223 ms (-9%), 98K 20447 -> 277# 20027 ms (-2%), decode +0.8%. On a card whose prompt is slow (R9700) the read hides behind layer 0 and nothing 278# changes. It costs the table's size in RAM, so only with 16 GB to spare beyond the model's own need; a smaller PC 279# keeps reading from the SSD as before. 280try : 281tensor = None if ready else next ((t for t in GGUFFile (ple ).tensors if t .name == "per_layer_token_embd.weight" ),None ) 282size = ple .stat ().st_size if ready else getattr (tensor ,"expected_bytes" ,lambda :None )() 283except Exception : 284size = None 285table_gb = size / 1e9 if size else 28.8 286if ram >= MODELS [model ]["ram_gb" ]+ table_gb + 16 : 287args += ["--ple-io" ,"ram" ] 288ok (f" { ram :.0f } GB of RAM: the { table_gb :.0f } GB n-gram table is kept in RAM (--ple-io ram), so a new prompt does " 289"not wait for its rows from the SSD (a 4K prompt about 18% sooner on a fast card); remove --ple-io ram from " 290"the config's args to read it from the SSD instead" ) 291# KV streaming: from 64K up the whole KV cache lives in RAM and only the part the attention reads (32K positions 292# per layer) stays in VRAM; the VRAM it frees holds more experts (+6% at 128K, +23% at 262K with Q2_0). It 293# costs ~13.7 KB of RAM per context token with 8-bit KV (1.7 GB at 128K), 10.6 KB with K8V4, 7.5 KB with 4-bit, so only 294# when it fits. 295kv_ram_gb = kv_streaming_ram_gb (ctx ,kv )# the branches below are kv_streaming_wanted, with its messages 296# --kv-streaming on|off overrides the RAM test (the owner's rule); WSL stays off - it cannot stream. 297stream_need = kv_streaming_need_gb (model ,ctx ,kv ) 298stream_fits = ram >= stream_need 299if is_wsl ()and ctx >= 65536 : 300ok ("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM" ) 301if a .kv_streaming == "on" : 302warn ("--kv-streaming on: WSL cannot stream the KV cache (its RAM copy must be pinned, and the driver pins " 303"only about 1 GB there): off" ) 304elif ctx >= 65536 and a .kv_streaming == "off" : 305ok ("KV streaming off, as you chose (--kv-streaming off): the KV cache stays in VRAM" ) 306elif ctx >= 65536 and (stream_fits or a .kv_streaming == "on" ): 307args += ["--kv-resident" ,"32768" ] 308ok (f"KV streaming on: the context's KV cache lives in RAM ( { kv_ram_gb :.1f } GB), more experts fit in VRAM" ) 309if not stream_fits : 310warn (f"KV streaming needs ~ { stream_need :.0f } GB of RAM for { model } (its experts, the room beside them and " 311f"the { kv_ram_gb :.1f } GB cache); this PC has { ram :.0f } . Kept as you chose (--kv-streaming on): it may page or run out of RAM " 312"under load" ) 313if q4_split :# #498: no budget to take it out of 314pass 315elif budget is not None and a .resident_budget_gib is None :# its RAM comes out of the experts' budget 316budget = resident_budget_gib (model ,ram ,kv_ram_gb ) 317ok (f"RAM budget: { budget } GiB (less the KV cache's RAM)" ) 318elif budget is not None and budget > resident_budget_gib (model ,ram ,kv_ram_gb ): 319warn (f"the KV cache's { kv_ram_gb :.1f } GB of RAM come on top of your { budget :g } GiB RAM budget (setup " 320f"would take them out of it: { resident_budget_gib ( model , ram , kv_ram_gb ) } GiB); kept as you chose" ) 321elif ctx >= 65536 :# #620: say why, so a regenerated config that lost --kv-resident is not a surprise 322ok (f"KV streaming off: it needs ~ { stream_need :.0f } GB of RAM for { model } (its experts, the room beside them " 323f"and the { kv_ram_gb :.1f } GB cache), and this PC has { ram :.0f } ; the KV cache stays in VRAM (fewer cached experts). --kv-streaming on " 324"turns it on anyway" ) 325elif a .kv_streaming == "on" : 326warn ("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off" ) 327if budget is not None and not q4_split :# UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N 328args += ["--resident-budget-gib" ,f" { budget :g } " ]# GiB kept in RAM (#498: a layer split had no budget) 329if gpu .get ("uma" )and "--expert-cache" in args : 330# #1715: the cache and the budget draw on the same RAM: a number that leaves the OS its room, not `auto` 331slots = uma_expert_cache (model ,ram ,budget ,kv_ram_gb if "--kv-resident" in args else 0.0 ) 332if slots is not None : 333args [args .index ("--expert-cache" )+ 1 ]= str (slots ) 334ok (f"expert cache: { slots } slots (not auto): this GPU shares the RAM with the { budget :g } GiB budget, " 335f"so setup leaves { UNSLOTH_RAM_LEFT_GB } GB of the RAM for the OS and the desktop (#1715). " 336"--expert-cache N in the config's args sets it" ) 337else : 338# Round 0215 (owner 11-05): on a Windows Strix Halo the cache lives in the GPU's own pool (the BIOS carve-out + the shared memory), not in the RAM the OS 339# needs, so the earlier "may take the room the OS needs" warning was misleading there; the cache stays on auto and this says where it is sized from. 340carve = float (gpu .get ("dedicated_gb" )or 0.0 ) 341ok (f"The expert cache is sized from the graphics memory ( { f' { carve :g } GB ' if carve > 0 else '' } carve-out + shared), not from the RAM." ) 342if vision != "none" : 343args += ["--vision" ] 344if VISION [vision ]["reserve_mib" ]: 345args += ["--vram-reserve-mib" ,str (VISION [vision ]["reserve_mib" ])] 346if vision == "gpu" and a .vram_reserve_mib is None and 0 < gpu .get ("vram_gb" ,0.0 )<= 12.5 : 347# a tip only (recommend, never force): on a 12 GB card the encoder's 700 MiB can leave ~200 MiB free 348f" tip: images on a { gpu [ 'vram_gb' ]:.0f } GB card can leave little VRAM free; if a request stalls, " 349f"run setup again with --vram-reserve-mib { VISION_GPU_SMALL_RESERVE_MIB } " ) 350if a .vram_reserve_mib is not None :# #493: VRAM left free for other programs (only when given) 351if "--vram-reserve-mib" in args : 352i = args .index ("--vram-reserve-mib" )+ 1 353if vision == "gpu" and a .vram_reserve_mib < int (args [i ]): 354warn (f"--vram-reserve-mib { a . vram_reserve_mib } : the image encoder on the GPU needs ~ { args [ i ] } MiB of " 355"it; kept as you chose (it may run out of VRAM when it reads a picture)" ) 356args [i ]= str (a .vram_reserve_mib ) 357else : 358args += ["--vram-reserve-mib" ,str (a .vram_reserve_mib )] 359ok (f"VRAM kept free for other programs: { a . vram_reserve_mib } MiB (--vram-reserve-mib; the expert cache takes " 360"that much less)" ) 361elif hip and WIN and gpu .get ("uma" )and gfx_arch_is (gpu .get ("arch" ),"gfx1151" )and not multi and "--vram-reserve-mib" not in args : 362# G16 (Q4-P8, 2026-11-08): a Windows Strix Halo config with no reserve at all (pictures off, or a model with no picture reader) never started 363# UD-Q4_K_XL: with no --vram-reserve-mib the engine puts its Windows floor of 2560 MiB on any card of 15 GiB or more (made for a 20 GB discrete 364# card that paged, #1376), and on this shared pool that room is taken straight back by the RAM budget's page-locked complement, so the prompt 365# path's own buffers found 0 MiB and the engine stepped its chunk down for ever. Pictures on already write 700 (VISION above), the app writes its 366# own, and every measured Strix run carried it: the engine's own default, said out loud, so the floor does not apply. 367args += ["--vram-reserve-mib" ,str (UMA_WIN_RESERVE_MIB )] 368if not multi and family == "unsloth" and 0 < gpu .get ("vram_gb" ,0.0 )<= UD_FIT_CARD_GB : 369# a card of about 8 GB: the config setup would write may not start (measured on an A750). Pick the least 370# harmful one that fits and say so; what the user chose with --context / --kv / --vram-reserve-mib is kept 371res_arg = int (args [args .index ("--vram-reserve-mib" )+ 1 ])if "--vram-reserve-mib" in args [:- 1 ]else None 372vg = gpu ["vram_gb" ] 373rt_mib = unsloth_runtime_mib (gpu ) 374fits = unsloth_vram_slack_mib (vg ,ctx ,kv ,UD_FIT_ENGINE_RESERVE_MIB if res_arg is None else res_arg ,True , 375rt_mib )>= UD_FIT_MIN_SLACK_MIB 376plan = None 377if not fits : 378plan = unsloth_small_card_plan (vg ,ctx ,kv ,res_arg ,ctx_fixed = bool (a .context ),kv_fixed = bool (a .kv ), 379runtime_mib = rt_mib ) 380if plan is not None : 381nctx ,nkv ,nmtp ,slack = plan 382changes = [] 383if nctx != ctx : 384args [args .index ("--max-context" )+ 1 ]= str (nctx ) 385changes .append (f"context { ctx } -> { nctx } " ) 386ctx = nctx 387if nkv != kv : 388if "--kv" in args [:- 1 ]: 389args [args .index ("--kv" )+ 1 ]= nkv 390else : 391args += ["--kv" ,nkv ] 392changes .append (f"KV cache { kv } -> { nkv } " ) 393kv = nkv 394if not nmtp and "--mtp" in args [:- 1 ]: 395i = args .index ("--mtp" ) 396del args [i :i + 2 ] 397changes .append ("no MTP draft layer on the GPU (about 0.8 GB more for the expert cache; decode is slower)" ) 398warn (f"with the usual settings { model } would not start on this { vg :.0f } GB card (setup's estimate: no VRAM " 399"left for the expert cache). Setup chose the least harmful start that fits: " + ", " .join (changes ) 400+ ". A bigger context, 8-bit KV or the draft layer need a card with more VRAM (or " 401"--vram-reserve-mib 0, which leaves nothing for other programs)." ) 402for line in unsloth_small_card_lines (model ,vg ,plan ,fits ): 403warn (line ) 404if not multi and 0 < gpu .get ("vram_gb" ,0.0 )< SMALL_CARD_GB : 405# #496: on a 6 GB card the expert cache can get no room at all; the engine lowers its own reserve when that 406# is what it takes, and says what is short when even that is not enough. Setup only says what helps. 407for line in small_card_note (ctx ,draft_vocab ):# a recommendation: nothing changes 408say (" " + line ) 409elif hip and a .vram_reserve_mib is None and linux_desktop (): 410for line in desktop_reserve_note ():# #560 #516: a recommendation: nothing changes 411say (" " + line ) 412if not hip and not multi and a .vram_reserve_mib is None and gpu_drives_display (gpu ): 413say (" tip: this card drives a display. If the PC freezes or the screen goes black once the model is loaded " 414f"(#779), keep more VRAM free: run setup again with --vram-reserve-mib { DISPLAY_RESERVE_MIB } " )# a tip only 415if not hip : 416for gi in ([g for g in multi ]if multi else [gpu .get ("index" ,0 )]): 417gi = gi ["index" ]if isinstance (gi ,dict )else gi 418w = compute_mode_warning (gi ,gpu_compute_mode (gi )) 419if w : 420warn (w )# #1445: a warning only, never a refusal 421if esp is not None : 422# the package's profile, with llama.cpp's flags (the engine takes the same ones) 423args += ["--control-vector-scaled" ,f" { esp } :1.0" ,"--control-vector-layer-range" ,"4" ,"44" , 424"--cvec-mode" ,"project" ,"--cvec-dir" ,"per-layer" ] 425cfg = {"exe" :engine_exe (eng ),"args" :args ,"cwd" :str (ROOT ),"tokenizer" :str (pack / "tokenizer" ), 426"model_name" :f" { fam [ 'name' ] } - { model . lower () } " ,"log" :str (home ()/ f"strata- { tag . lower () } .log" ), 427"lib_dirs" :lib_dirs ,"port" :port } 428if cuda_tk == 12 :# the experimental CUDA 12 engine (engine-cuda12/) 429cfg ["cuda" ]= 12 430if (uenv := unsloth_default_env (family ,model ,hip ,in_budget ,str (gpu .get ("arch" )or "" ))): 431cfg ["env" ]= uenv 432if hip : 433cfg ["backend" ]= "hip" 434# the dense prompt GEMMs through hipBLASLt with kernels measured on this GPU generation (tools/hip; +40-60% 435# prompt speed on the 7900 XTX): only a table for this card's arch AND the installed hipBLASLt version (the 436# engine refuses any other one and falls back to plain hipBLAS) 437if CONTROL : 438pass # the app's engine is a package: the server picks its tuning/ table for the card when it starts (strata_control/hipblaslt_tuning.py) 439else : 440table = hipblaslt_table (gpu ["arch" ],lib_dirs ,meta .get ("hipblaslt_version" ), [eng / "tuning" ]) 441if table : 442cfg ["env" ]= {"STRATA_HIPBLASLT_TUNING" :str (table )} 443if GFX1103_OPT_IN and gfx_arch_is (gpu ["arch" ],"gfx1103" )and not WIN : 444# the 780M's KFD queues are evicted (a GPU reset) while transparent huge pages move the pinned expert arena 445cfg .setdefault ("env" , {})["STRATA_NO_ARENA_THP" ]= "1" 446# the exact gfx1151 speed switches measured on this chip (GFX1103_SWITCHES): the engine has no arch defaults 447# for gfx1103, so setup writes them into the config. They are setup's own (SETUP_ENV), so a re-run refreshes 448# them and turning the opt-in off takes them out again. 449cfg .setdefault ("env" , {}).update (GFX1103_SWITCHES ) 450if GFX1150_OPT_IN and gfx_arch_is (gpu ["arch" ],"gfx1150" ): 451# the exact gfx1151 speed switches measured on this chip (GFX1150_SWITCHES): the engine has no arch defaults 452# for gfx1150, so setup writes them into the config. They are setup's own (SETUP_ENV), so a re-run refreshes 453# them and turning the opt-in off takes them out again. 454cfg .setdefault ("env" , {}).update (GFX1150_SWITCHES ) 455# RDNA2 (gfx103x): the prompt's FP16 GEMMs through rocBLAS's best kernel per shape (tools/hip/tune_rocblas; 456# the GDN input projection 6x faster below 1,152 tokens on a 6900 XT). The ids are valid for one rocBLAS 457# build, which only the engine can read, so setup points it at the directory and the engine picks the file 458# <arch>-rocblas-<version>.txt for its own library, or runs the default kernels and says so in its log. 459rocblas_tables = sorted (p .name for p in (ROOT / "tools" / "hip" ).glob (f" { gpu [ 'arch' ] } -rocblas-*.txt" )) 460if rocblas_tables : 461cfg .setdefault ("env" , {})["STRATA_ROCBLAS_TUNING" ]= str (ROOT / "tools" / "hip" ) 462ok (f"rocBLAS tuning tables for { gpu [ 'arch' ] } : { ', ' . join ( rocblas_tables ) } (the engine takes the one of its rocBLAS build)" ) 463if resident :# ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable 464cfg .setdefault ("env" , {})["STRATA_RESIDENT_PIN" ]= "0" 465if gpu ["count" ]> 1 or a .gpu is not None : 466cfg ["gpu" ]= gpu ["index" ]# the engine is told this card (issue #51) 467cfg ["gpus_asked" ]= True # chosen at setup: not asked again at start 468if multi :# a layer split across these cards (the server adds the flag) 469cfg ["gpu" ]= multi 470cfg ["layer_split" ]= a .layer_split or "auto" 471if getattr (a ,"_roles" ,None ):# roles chosen: the card list is Main last, in this order, and the server keeps it 472cfg ["gpu_order" ]= "as_given" 473ok (f"layer split across GPUs { multi } ( { cfg [ 'layer_split' ] } )" ) 474recommend_remote_expert_opt (cfg ,off = a .no_remote_expert_opt ) 475replica_done = False 476if a .replicas is None and a .layer_split in (None ,"auto" )and (getattr (a ,"replica_profile" ,False )or 477os .environ .get ("STRATA_REPLICA_PROFILE" )): 478try :# the opt-in replica profile (strata_control/replica_profile.py) 479from strata_control import replica_profile 480if getattr (a ,"replica_profile" ,False ): 481cfg ["replica_profile" ]= True 482lines = replica_profile .apply ([{"name" :c .get ("name" ),"vram_gb" :c .get ("vram_gb" ),"vendor" :c .get ("vendor" ), 483"index" :c .get ("index" )}for c in chosen ],cfg ,float (ram ), 484parallel_given = a .parallel is not None ) 485replica_done = bool (cfg .get ("replicas" )) 486for line in lines : 487 (ok if replica_done else say )(line ) 488except Exception as e :# noqa: BLE001 - a profile is never a reason to stop setup 489say (f" (the replica profile was not applied: { e } )" ) 490if hip and a .layer_split in (None ,"auto" )and not replica_done :# four Radeon AI PRO R9700 cards and Qwen3.8 IQ3_S: the measured serving profile 491try :# (strata_control/amd_four_card.py); what the person chose always wins 492from strata_control import amd_four_card 493for line in amd_four_card .apply ([{"name" :c .get ("name" ),"vram_gb" :c .get ("vram_gb" ),"vendor" :"amd" }for c in chosen ], 494cfg ,parallel_given = a .parallel is not None ): 495ok (line ) 496except Exception as e :# noqa: BLE001 - a profile is never a reason to stop setup 497say (f" (the four-card profile was not applied: { e } )" ) 498if getattr (a ,"_roles" ,None ):# the roles themselves (strata_control/gpu_roles.py); "gpu" above is their mirror 499final = cfg ["gpu" ]if isinstance (cfg .get ("gpu" ),list )else [cfg ["gpu" ]]# what the checks above left (a model that cannot share keeps one card) 500main = final [- 1 ] 501cfg ["gpu_roles" ]= {str (i ): ("main" if i == main else "helper" if i in final else "off" )for i in sorted (set (a ._roles )| set (final ))} 502cfg ["gpus_asked" ]= True 503cfg .pop ("gpu_none" ,None ) 504if isinstance (cfg .get ("gpu" ),list )and len (final )> 1 : 505cfg ["gpu_order" ]= "as_given" 506if a .replicas is not None and a .replicas >= 2 :# data-parallel replicas (serve/replicas.py), opt-in 507cards = multi if multi else [] 508if not cards or len (cards )% a .replicas : 509warn (f"--replicas { a . replicas } : needs the chosen GPUs ( { cards or 'one' } ) to divide into { a . replicas } equal " 510"groups; not set (choose the cards with --gpu 0,1,2,3, or write the groups into the config: " 511'"replicas": [{"gpus": [0, 1]}, {"gpus": [2, 3]}])' ) 512else : 513cfg ["replicas" ]= a .replicas 514per = len (cards )// a .replicas 515ok (f" { a . replicas } replicas of { per } GPU(s) each: { ' | ' . join ( ',' . join ( map ( str , cards [ i * per :( i + 1 ) * per ])) for i in range ( a . replicas )) } " ) 516if per > 1 and a .layer_split not in (None ,"auto" ): 517warn ("--layer-split is one engine's value; with replicas every group would get it: leave it at auto" ) 518if (os .cpu_count ()or 0 )< 8 * a .replicas : 519warn ("each replica loads its own copy of the model into RAM and runs its own host threads: check the RAM" ) 520if a .host : 521cfg ["host" ]= a .host 522if a .api_key : 523cfg ["api_key" ]= a .api_key 524if draft_vocab : 525cfg ["draft_vocab" ]= draft_vocab 526if a .browser is not None :# #609: only when given (else an earlier choice is carried over) 527cfg ["open_browser" ]= a .browser 528if a .mtp is not None :# written only when given (else an earlier choice is carried over) 529if a .mtp == "off" : 530cfg ["mtp" ]= False 531removed = draft_layer .apply (cfg ) 532if getattr (a ,"feed_no_drafter" ,False ): 533cfg ["drafting" ]= "off" # a feed model with no draft layer (its entry says drafter: none): no drafter at any start, Auto or not 534ok ("the draft layer (MTP) is off for this model" + (f" ( { ' ' . join ( removed ) } left out)" if removed else "" )+ 535": less graphics memory and RAM, slower words per second. `--mtp on` turns it back on" ) 536else : 537cfg ["mtp" ]= True # explicit, so carry_over does not bring an earlier false back 538ok ("the draft layer (MTP) is on" ) 539# #465: requests at once - written only when given (else an earlier "parallel" is carried over); a recommendation 540streaming = "--kv-resident" in args 541if a .parallel is not None : 542if a .parallel >= 2 : 543cfg ["parallel" ]= a .parallel 544for i ,line in enumerate (parallel_note (a .parallel , [g .get ("vram_gb" ,0.0 )for g in chosen ], 545MODELS [model ]["arena_gb" ],ctx ,kv ,streaming )): 546 (ok if i == 0 else warn )(line ) 547else : 548cfg ["parallel" ]= 1 549ok ("parallel requests: one at a time (--parallel 1)" ) 550if vision != "none" : 551old_cfg = home ()/ f"strata- { tag . lower () } .json" 552vt = vision_tokens (a .vision_tokens ,vision ,old_cfg if old_cfg .is_file ()else adopted ) 553cfg ["vision" ]= {"exe" :str (eng / VEXE ),"mmproj" :str (mmproj ),# the text model, opened vocab-only: 554"model" :str (ready_paths (model ,models_dir )["dense" ]if ready else shards [0 ]), 555"gpu" :vision == "gpu" ,"max_tokens" :vt } 556if reader is not None :# AMD: the HIP reader with the CPU reader behind it, or the CPU reader 557from strata_control import vision_reader as VR 558cfg ["vision" ]= VR .vision_section (reader ,cfg ["vision" ]) 559if vision == "cpu" : 560cfg ["vision" ]["threads" ]= vision_threads () 561elif a .vision_tokens is not None : 562warn ("--vision-tokens: images are off for this model, so it is not used" ) 563if a .images :# only when given: else an earlier "images" is carried over 564cfg ["images" ]= setup_images (a ,gpu ,hip ,Path (a .models_dir )) 565cfg_path = home ()/ f"strata- { tag . lower () } .json" 566cal = setup_calibration (cfg ,hip )# #566: Linux HIP too; the tuning is offered on NVIDIA only 567if cal is not None : 568sys .path .insert (0 ,str (ROOT / "tools" )) 569import calibrate as CAL 570cfg ["args" ]= CAL .apply (cfg ["args" ],cal .get ("settings" )or {}) 571if "env" in cal :# a calibration from before the env step leaves "env" as it is 572cfg ["env" ]= CAL .apply_env (cfg .get ("env" ),cal ["env" ]) 573ok ("the settings tuned for this PC earlier are used" + (f" ( { cal [ 'date' ] } )" if cal .get ("date" )else "" )) 574else :# #642: measured counts (a calibration) win over the rule 575cfg ["args" ]= recommend_pool_workers (cfg ["args" ]) 576for line in pool_workers_note (cfg ["args" ]): 577warn (line ) 578for line in two_socket_note (cpu_sockets ()):# bench tips: text only, the config is not touched 579say (" " + line ) 580for line in bench_tips (cfg ["args" ],cfg .get ("env" ),ram ,MODELS [model ]["ram_gb" ],gpu .get ("vram_gb" ,0.0 ),vision ,WIN ,gpu ): 581if apu_hides_chunk_tip (gpu ,line ): 582continue 583say (" " + line ) 584return SetupConfig (cfg = cfg ,cfg_path = cfg_path ,cal = cal ,args = args ,ctx = ctx ,kv = kv ,resident = resident )