okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
36.2 KiB584 linesraw
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
7  name 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
10  without 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:
31    a: Any = None
32    adopted: Any = None
33    chosen: Any = None
34    cuda_tk: Any = None
35    draft_vocab: Any = None
36    eng: Any = None
37    engine_ver: Any = None
38    esp: Any = None
39    fam: Any = None
40    family: Any = None
41    gpu: Any = None
42    hip: Any = None
43    in_budget: Any = None
44    lib_dirs: Any = None
45    low_ram: Any = None
46    meta: Any = None
47    mmproj: Any = None
48    model: Any = None
49    model_args: Any = None
50    models_dir: Any = None
51    multi: Any = None
52    pack: Any = None
53    ple: Any = None
54    port: Any = None
55    q4_split: Any = None
56    ram: Any = None
57    reader: Any = None
58    ready: Any = None
59    rope_scale: Any = None
60    rt: Any = None
61    scaling: Any = None
62    shards: Any = None
63    tag: Any = None
64    vision: Any = None
65    ctx: Any = None
66    kv: Any = None
67    resident: Any = None
68    budget: Any = None
69    GGUFFile: Any = None
70
71
72@dataclass
73class SetupConfig:
74    cfg: dict
75    cfg_path: Path
76    cal: Any
77    args: list
78    ctx: int
79    kv: str
80    resident: bool
81
82
83def neutral_profile_if_other_shape(shipped, first_shard, pack, GGUFFile, say=print):
84    """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
85    shape ("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
86    once, interleaved across the layers, nothing learned. The first run's `--expert-profile-save` can replace it. Returns the profile to use."""
87    import struct
88    try:
89        meta = GGUFFile(first_shard).metadata
90        n_layer = next(int(v) for k, v in meta.items() if k.endswith(".block_count"))
91        n_expert = next(int(v) for k, v in meta.items() if k.endswith(".expert_count"))
92        blob = Path(shipped).read_bytes()[:24]
93        _ver, have_l, have_e, _slots, _n = struct.unpack_from("<5I", blob, 4)
94        if blob[:4] == b"STRP" and (have_l, have_e) == (n_layer, n_expert):
95            return Path(shipped)
96        out = Path(pack) / f"expert-profile-{n_layer}x{n_expert}.bin"
97        if not out.exists():
98            ranked = [(layer, e) for e in range(n_expert) for layer in range(n_layer)]
99            table = [[-1] * n_expert for _ in range(n_layer)]
100            for slot, (layer, e) in enumerate(ranked):
101                table[layer][e] = slot
102            with open(out, "wb") as f:
103                f.write(b"STRP" + struct.pack("<5I", 1, n_layer, n_expert, len(ranked), len(ranked)))
104                for layer, e in ranked:
105                    f.write(struct.pack("<HH", layer, e))
106                for layer in range(n_layer):
107                    f.write(struct.pack("<%di" % n_expert, *table[layer]))
108        say("  This model's shape differs from Flash-Next, so a neutral expert profile is used.")
109        return out
110    except (OSError, ValueError, StopIteration, struct.error):
111        return 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)
116    a = inp.a
117    adopted = inp.adopted
118    chosen = inp.chosen
119    cuda_tk = inp.cuda_tk
120    draft_vocab = inp.draft_vocab
121    eng = inp.eng
122    engine_ver = inp.engine_ver
123    esp = inp.esp
124    fam = inp.fam
125    family = inp.family
126    gpu = inp.gpu
127    hip = inp.hip
128    in_budget = inp.in_budget
129    lib_dirs = inp.lib_dirs
130    low_ram = inp.low_ram
131    meta = inp.meta
132    mmproj = inp.mmproj
133    model = inp.model
134    model_args = inp.model_args
135    models_dir = inp.models_dir
136    multi = inp.multi
137    pack = inp.pack
138    ple = inp.ple
139    port = inp.port
140    q4_split = inp.q4_split
141    ram = inp.ram
142    reader = inp.reader
143    ready = inp.ready
144    rope_scale = inp.rope_scale
145    rt = inp.rt
146    scaling = inp.scaling
147    shards = inp.shards
148    tag = inp.tag
149    vision = inp.vision
150    ctx = inp.ctx
151    kv = inp.kv
152    resident = inp.resident
153    budget = inp.budget
154    GGUFFile = inp.GGUFFile
155    CONTROL = lib.CONTROL
156    DISPLAY_RESERVE_MIB = lib.DISPLAY_RESERVE_MIB
157    GFX1103_OPT_IN = lib.GFX1103_OPT_IN
158    GFX1103_SWITCHES = lib.GFX1103_SWITCHES
159    GFX1150_OPT_IN = lib.GFX1150_OPT_IN
160    GFX1150_SWITCHES = lib.GFX1150_SWITCHES
161    MODELS = lib.MODELS
162    RESIDENT_ENGINE = lib.RESIDENT_ENGINE
163    ROOT = lib.ROOT
164    SMALL_CARD_GB = lib.SMALL_CARD_GB
165    UD_FIT_CARD_GB = lib.UD_FIT_CARD_GB
166    UD_FIT_ENGINE_RESERVE_MIB = lib.UD_FIT_ENGINE_RESERVE_MIB
167    UD_FIT_MIN_SLACK_MIB = lib.UD_FIT_MIN_SLACK_MIB
168    UNSLOTH_RAM_LEFT_GB = lib.UNSLOTH_RAM_LEFT_GB
169    VEXE = lib.VEXE
170    VISION = lib.VISION
171    VISION_GPU_SMALL_RESERVE_MIB = lib.VISION_GPU_SMALL_RESERVE_MIB
172    WIN = lib.WIN
173    apu_hides_chunk_tip = lib.apu_hides_chunk_tip
174    bench_tips = lib.bench_tips
175    compute_mode_warning = lib.compute_mode_warning
176    cpu_sockets = lib.cpu_sockets
177    desktop_reserve_note = lib.desktop_reserve_note
178    draft_layer = lib.draft_layer
179    engine_exe = lib.engine_exe
180    gfx_arch_is = lib.gfx_arch_is
181    gpu_compute_mode = lib.gpu_compute_mode
182    gpu_drives_display = lib.gpu_drives_display
183    hipblaslt_table = lib.hipblaslt_table
184    home = lib.home
185    is_gb10 = lib.is_gb10
186    is_wsl = lib.is_wsl
187    kv_streaming_need_gb = lib.kv_streaming_need_gb
188    kv_streaming_ram_gb = lib.kv_streaming_ram_gb
189    linux_desktop = lib.linux_desktop
190    ok = lib.ok
191    parallel_note = lib.parallel_note
192    ple_ram_platform_ok = lib.ple_ram_platform_ok
193    pool_workers_note = lib.pool_workers_note
194    ready_paths = lib.ready_paths
195    recommend_pool_workers = lib.recommend_pool_workers
196    recommend_remote_expert_opt = lib.recommend_remote_expert_opt
197    resident_budget_gib = lib.resident_budget_gib
198    rotational_disk = lib.rotational_disk
199    say = lib.say
200    setup_calibration = lib.setup_calibration
201    setup_images = lib.setup_images
202    small_card_note = lib.small_card_note
203    two_socket_note = lib.two_socket_note
204    uma_expert_cache = lib.uma_expert_cache
205    unsloth_default_env = lib.unsloth_default_env
206    unsloth_runtime_mib = lib.unsloth_runtime_mib
207    unsloth_small_card_lines = lib.unsloth_small_card_lines
208    unsloth_small_card_plan = lib.unsloth_small_card_plan
209    unsloth_vram_slack_mib = lib.unsloth_vram_slack_mib
210    vision_threads = lib.vision_threads
211    vision_tokens = lib.vision_tokens
212    warn = lib.warn
213    # ---- the moved lines (unchanged)
214    profile = ROOT / "data" / fam.get("profile", "expert-profile.bin")
215    if fam.get("feed") and shards:
216        profile = neutral_profile_if_other_shape(profile, shards[0], pack, GGUFFile, say)       # a feed model of another shape than the shipped profile's
217    args = [*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)]
221    if scaling is not None:     # the resolved config: explicit flags as given, or the automatic yarn+factor
222        args += ["--rope-scaling", scaling, "--rope-scale", f"{rope_scale:g}"]
223    if ctx > 8192:
224        args += ["--kv", kv]
225    if resident and a.low_ram != "resident" and engine_ver < RESIDENT_ENGINE:
226        resident = False                               # an engine from before --resident-experts would refuse it
227        ok(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)")
229    if 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
234        rb = resident_budget_gib(model, ram)
235        args += ["--resident-budget-gib", str(rb)]
236        ok(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")
238    elif low_ram:   # the experts from the pack's experts.bin: the ones the GPU does not hold copied into RAM, or mapped
239        args += ["--resident-experts" if resident else "--mmap-experts"]
240    elif 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)
243        args += ["--mmap-experts"]
244        ok("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)
250        if "--prefill" in args:
251            args[args.index("--prefill") + 1] = "auto:32768"
252        if "--mtp" in args:
253            args += ["--mtp-q4", "all", "--mtp-hnorm", "stream"]
254            ok("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])
258        say("  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).")
260    disk = None if is_wsl() else rotational_disk(ple)  # #605 (WSL's virtual disk says rotational)
261    if disk:
262        tensor = None if ready else next((t for t in GGUFFile(ple).tensors if t.name == "per_layer_token_embd.weight"), None)
263        size = ple.stat().st_size if ready else getattr(tensor, "expected_bytes", lambda: None)()
264        table_gb = size / 1e9 if size else 28.8
265        if ram >= MODELS[model]["ram_gb"] + table_gb + 4:
266            args += ["--ple-io", "ram"]
267            ok(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)")
269        else:
270            warn(f"the model is on a rotational disk ({disk}): its n-gram table is read from it at random, which can "
271                 f"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")
273    elif 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.
280        try:
281            tensor = None if ready else next((t for t in GGUFFile(ple).tensors if t.name == "per_layer_token_embd.weight"), None)
282            size = ple.stat().st_size if ready else getattr(tensor, "expected_bytes", lambda: None)()
283        except Exception:
284            size = None
285        table_gb = size / 1e9 if size else 28.8
286        if ram >= MODELS[model]["ram_gb"] + table_gb + 16:
287            args += ["--ple-io", "ram"]
288            ok(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.
295    kv_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.
297    stream_need = kv_streaming_need_gb(model, ctx, kv)
298    stream_fits = ram >= stream_need
299    if is_wsl() and ctx >= 65536:
300        ok("WSL: KV streaming off (the driver pins only about 1 GB of RAM); the KV cache stays in VRAM")
301        if a.kv_streaming == "on":
302            warn("--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")
304    elif ctx >= 65536 and a.kv_streaming == "off":
305        ok("KV streaming off, as you chose (--kv-streaming off): the KV cache stays in VRAM")
306    elif ctx >= 65536 and (stream_fits or a.kv_streaming == "on"):
307        args += ["--kv-resident", "32768"]
308        ok(f"KV streaming on: the context's KV cache lives in RAM ({kv_ram_gb:.1f} GB), more experts fit in VRAM")
309        if not stream_fits:
310            warn(f"KV streaming needs ~{stream_need:.0f} GB of RAM for {model} (its experts, the room beside them and "
311                 f"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")
313        if q4_split:                                   # #498: no budget to take it out of
314            pass
315        elif budget is not None and a.resident_budget_gib is None:   # its RAM comes out of the experts' budget
316            budget = resident_budget_gib(model, ram, kv_ram_gb)
317            ok(f"RAM budget: {budget} GiB (less the KV cache's RAM)")
318        elif budget is not None and budget > resident_budget_gib(model, ram, kv_ram_gb):
319            warn(f"the KV cache's {kv_ram_gb:.1f} GB of RAM come on top of your {budget:g} GiB RAM budget (setup "
320                 f"would take them out of it: {resident_budget_gib(model, ram, kv_ram_gb)} GiB); kept as you chose")
321    elif ctx >= 65536:   # #620: say why, so a regenerated config that lost --kv-resident is not a surprise
322        ok(f"KV streaming off: it needs ~{stream_need:.0f} GB of RAM for {model} (its experts, the room beside them "
323           f"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")
325    elif a.kv_streaming == "on":
326        warn("--kv-streaming on: a context under 64K is not streamed (the attention's window holds all of it): off")
327    if budget is not None and not q4_split:   # UD-Q4_K_XL: the experts read from the GGUF in place, the most-used N
328        args += ["--resident-budget-gib", f"{budget:g}"]   # GiB kept in RAM (#498: a layer split had no budget)
329        if 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`
331            slots = uma_expert_cache(model, ram, budget, kv_ram_gb if "--kv-resident" in args else 0.0)
332            if slots is not None:
333                args[args.index("--expert-cache") + 1] = str(slots)
334                ok(f"expert cache: {slots} slots (not auto): this GPU shares the RAM with the {budget:g} GiB budget, "
335                   f"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")
337            else:
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.
340                carve = float(gpu.get("dedicated_gb") or 0.0)
341                ok(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.")
342    if vision != "none":
343        args += ["--vision"]
344        if VISION[vision]["reserve_mib"]:
345            args += ["--vram-reserve-mib", str(VISION[vision]["reserve_mib"])]
346        if 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
348            print(f"  tip: images on a {gpu['vram_gb']:.0f} GB card can leave little VRAM free; if a request stalls, "
349                  f"run setup again with --vram-reserve-mib {VISION_GPU_SMALL_RESERVE_MIB}")
350    if a.vram_reserve_mib is not None:                 # #493: VRAM left free for other programs (only when given)
351        if "--vram-reserve-mib" in args:
352            i = args.index("--vram-reserve-mib") + 1
353            if vision == "gpu" and a.vram_reserve_mib < int(args[i]):
354                warn(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)")
356            args[i] = str(a.vram_reserve_mib)
357        else:
358            args += ["--vram-reserve-mib", str(a.vram_reserve_mib)]
359        ok(f"VRAM kept free for other programs: {a.vram_reserve_mib} MiB (--vram-reserve-mib; the expert cache takes "
360           "that much less)")
361    elif 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.
367        args += ["--vram-reserve-mib", str(UMA_WIN_RESERVE_MIB)]
368    if 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
371        res_arg = int(args[args.index("--vram-reserve-mib") + 1]) if "--vram-reserve-mib" in args[:-1] else None
372        vg = gpu["vram_gb"]
373        rt_mib = unsloth_runtime_mib(gpu)
374        fits = unsloth_vram_slack_mib(vg, ctx, kv, UD_FIT_ENGINE_RESERVE_MIB if res_arg is None else res_arg, True,
375                                      rt_mib) >= UD_FIT_MIN_SLACK_MIB
376        plan = None
377        if not fits:
378            plan = unsloth_small_card_plan(vg, ctx, kv, res_arg, ctx_fixed=bool(a.context), kv_fixed=bool(a.kv),
379                                           runtime_mib=rt_mib)
380            if plan is not None:
381                nctx, nkv, nmtp, slack = plan
382                changes = []
383                if nctx != ctx:
384                    args[args.index("--max-context") + 1] = str(nctx)
385                    changes.append(f"context {ctx} -> {nctx}")
386                    ctx = nctx
387                if nkv != kv:
388                    if "--kv" in args[:-1]:
389                        args[args.index("--kv") + 1] = nkv
390                    else:
391                        args += ["--kv", nkv]
392                    changes.append(f"KV cache {kv} -> {nkv}")
393                    kv = nkv
394                if not nmtp and "--mtp" in args[:-1]:
395                    i = args.index("--mtp")
396                    del args[i:i + 2]
397                    changes.append("no MTP draft layer on the GPU (about 0.8 GB more for the expert cache; decode is slower)")
398                warn(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).")
402        for line in unsloth_small_card_lines(model, vg, plan, fits):
403            warn(line)
404    if 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.
407        for line in small_card_note(ctx, draft_vocab):   # a recommendation: nothing changes
408            say("  " + line)
409    elif hip and a.vram_reserve_mib is None and linux_desktop():
410        for line in desktop_reserve_note():              # #560 #516: a recommendation: nothing changes
411            say("  " + line)
412    if not hip and not multi and a.vram_reserve_mib is None and gpu_drives_display(gpu):
413        say("  tip: this card drives a display. If the PC freezes or the screen goes black once the model is loaded "
414            f"(#779), keep more VRAM free: run setup again with --vram-reserve-mib {DISPLAY_RESERVE_MIB}")   # a tip only
415    if not hip:
416        for gi in ([g for g in multi] if multi else [gpu.get("index", 0)]):
417            gi = gi["index"] if isinstance(gi, dict) else gi
418            w = compute_mode_warning(gi, gpu_compute_mode(gi))
419            if w:
420                warn(w)                                   # #1445: a warning only, never a refusal
421    if esp is not None:
422        # the package's profile, with llama.cpp's flags (the engine takes the same ones)
423        args += ["--control-vector-scaled", f"{esp}:1.0", "--control-vector-layer-range", "4", "44",
424                 "--cvec-mode", "project", "--cvec-dir", "per-layer"]
425    cfg = {"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}
428    if cuda_tk == 12:                                  # the experimental CUDA 12 engine (engine-cuda12/)
429        cfg["cuda"] = 12
430    if (uenv := unsloth_default_env(family, model, hip, in_budget, str(gpu.get("arch") or ""))):
431        cfg["env"] = uenv
432    if hip:
433        cfg["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)
437        if CONTROL:
438            pass    # the app's engine is a package: the server picks its tuning/ table for the card when it starts (strata_control/hipblaslt_tuning.py)
439        else:
440            table = hipblaslt_table(gpu["arch"], lib_dirs, meta.get("hipblaslt_version"), [eng / "tuning"])
441            if table:
442                cfg["env"] = {"STRATA_HIPBLASLT_TUNING": str(table)}
443        if 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
445            cfg.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.
449            cfg.setdefault("env", {}).update(GFX1103_SWITCHES)
450        if 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.
454            cfg.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.
459        rocblas_tables = sorted(p.name for p in (ROOT / "tools" / "hip").glob(f"{gpu['arch']}-rocblas-*.txt"))
460        if rocblas_tables:
461            cfg.setdefault("env", {})["STRATA_ROCBLAS_TUNING"] = str(ROOT / "tools" / "hip")
462            ok(f"rocBLAS tuning tables for {gpu['arch']}: {', '.join(rocblas_tables)} (the engine takes the one of its rocBLAS build)")
463        if resident:   # ROCm: large page-locked host allocations can fail or be slow for the CPU; keep the copy pageable
464            cfg.setdefault("env", {})["STRATA_RESIDENT_PIN"] = "0"
465    if gpu["count"] > 1 or a.gpu is not None:
466        cfg["gpu"] = gpu["index"]                      # the engine is told this card (issue #51)
467        cfg["gpus_asked"] = True                       # chosen at setup: not asked again at start
468    if multi:                                          # a layer split across these cards (the server adds the flag)
469        cfg["gpu"] = multi
470        cfg["layer_split"] = a.layer_split or "auto"
471        if getattr(a, "_roles", None):                 # roles chosen: the card list is Main last, in this order, and the server keeps it
472            cfg["gpu_order"] = "as_given"
473        ok(f"layer split across GPUs {multi} ({cfg['layer_split']})")
474        recommend_remote_expert_opt(cfg, off=a.no_remote_expert_opt)
475        replica_done = False
476        if a.replicas is None and a.layer_split in (None, "auto") and (getattr(a, "replica_profile", False) or
477                                                                       os.environ.get("STRATA_REPLICA_PROFILE")):
478            try:                                       # the opt-in replica profile (strata_control/replica_profile.py)
479                from strata_control import replica_profile
480                if getattr(a, "replica_profile", False):
481                    cfg["replica_profile"] = True
482                lines = 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),
484                                              parallel_given=a.parallel is not None)
485                replica_done = bool(cfg.get("replicas"))
486                for line in lines:
487                    (ok if replica_done else say)(line)
488            except Exception as e:                     # noqa: BLE001 - a profile is never a reason to stop setup
489                say(f"  (the replica profile was not applied: {e})")
490        if 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
491            try:                                       # (strata_control/amd_four_card.py); what the person chose always wins
492                from strata_control import amd_four_card
493                for line in amd_four_card.apply([{"name": c.get("name"), "vram_gb": c.get("vram_gb"), "vendor": "amd"} for c in chosen],
494                                                cfg, parallel_given=a.parallel is not None):
495                    ok(line)
496            except Exception as e:                     # noqa: BLE001 - a profile is never a reason to stop setup
497                say(f"  (the four-card profile was not applied: {e})")
498    if getattr(a, "_roles", None):                     # the roles themselves (strata_control/gpu_roles.py); "gpu" above is their mirror
499        final = cfg["gpu"] if isinstance(cfg.get("gpu"), list) else [cfg["gpu"]]      # what the checks above left (a model that cannot share keeps one card)
500        main = final[-1]
501        cfg["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))}
502        cfg["gpus_asked"] = True
503        cfg.pop("gpu_none", None)
504        if isinstance(cfg.get("gpu"), list) and len(final) > 1:
505            cfg["gpu_order"] = "as_given"
506    if a.replicas is not None and a.replicas >= 2:      # data-parallel replicas (serve/replicas.py), opt-in
507        cards = multi if multi else []
508        if not cards or len(cards) % a.replicas:
509            warn(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]}])')
512        else:
513            cfg["replicas"] = a.replicas
514            per = len(cards) // a.replicas
515            ok(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))}")
516            if per > 1 and a.layer_split not in (None, "auto"):
517                warn("--layer-split is one engine's value; with replicas every group would get it: leave it at auto")
518            if (os.cpu_count() or 0) < 8 * a.replicas:
519                warn("each replica loads its own copy of the model into RAM and runs its own host threads: check the RAM")
520    if a.host:
521        cfg["host"] = a.host
522    if a.api_key:
523        cfg["api_key"] = a.api_key
524    if draft_vocab:
525        cfg["draft_vocab"] = draft_vocab
526    if a.browser is not None:                          # #609: only when given (else an earlier choice is carried over)
527        cfg["open_browser"] = a.browser
528    if a.mtp is not None:                              # written only when given (else an earlier choice is carried over)
529        if a.mtp == "off":
530            cfg["mtp"] = False
531            removed = draft_layer.apply(cfg)
532            if getattr(a, "feed_no_drafter", False):
533                cfg["drafting"] = "off"                # a feed model with no draft layer (its entry says drafter: none): no drafter at any start, Auto or not
534            ok("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")
536        else:
537            cfg["mtp"] = True                          # explicit, so carry_over does not bring an earlier false back
538            ok("the draft layer (MTP) is on")
539    # #465: requests at once - written only when given (else an earlier "parallel" is carried over); a recommendation
540    streaming = "--kv-resident" in args
541    if a.parallel is not None:
542        if a.parallel >= 2:
543            cfg["parallel"] = a.parallel
544            for i, line in enumerate(parallel_note(a.parallel, [g.get("vram_gb", 0.0) for g in chosen],
545                                                   MODELS[model]["arena_gb"], ctx, kv, streaming)):
546                (ok if i == 0 else warn)(line)
547        else:
548            cfg["parallel"] = 1
549            ok("parallel requests: one at a time (--parallel 1)")
550    if vision != "none":
551        old_cfg = home() / f"strata-{tag.lower()}.json"
552        vt = vision_tokens(a.vision_tokens, vision, old_cfg if old_cfg.is_file() else adopted)
553        cfg["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}
556        if reader is not None:                          # AMD: the HIP reader with the CPU reader behind it, or the CPU reader
557            from strata_control import vision_reader as VR
558            cfg["vision"] = VR.vision_section(reader, cfg["vision"])
559        if vision == "cpu":
560            cfg["vision"]["threads"] = vision_threads()
561    elif a.vision_tokens is not None:
562        warn("--vision-tokens: images are off for this model, so it is not used")
563    if a.images:                                       # only when given: else an earlier "images" is carried over
564        cfg["images"] = setup_images(a, gpu, hip, Path(a.models_dir))
565    cfg_path = home() / f"strata-{tag.lower()}.json"
566    cal = setup_calibration(cfg, hip)                  # #566: Linux HIP too; the tuning is offered on NVIDIA only
567    if cal is not None:
568        sys.path.insert(0, str(ROOT / "tools"))
569        import calibrate as CAL
570        cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {})
571        if "env" in cal:                               # a calibration from before the env step leaves "env" as it is
572            cfg["env"] = CAL.apply_env(cfg.get("env"), cal["env"])
573        ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else ""))
574    else:                                              # #642: measured counts (a calibration) win over the rule
575        cfg["args"] = recommend_pool_workers(cfg["args"])
576        for line in pool_workers_note(cfg["args"]):
577            warn(line)
578        for line in two_socket_note(cpu_sockets()):    # bench tips: text only, the config is not touched
579            say("  " + line)
580    for line in bench_tips(cfg["args"], cfg.get("env"), ram, MODELS[model]["ram_gb"], gpu.get("vram_gb", 0.0), vision, WIN, gpu):
581        if apu_hides_chunk_tip(gpu, line):
582            continue
583        say("  " + line)
584    return SetupConfig(cfg=cfg, cfg_path=cfg_path, cal=cal, args=args, ctx=ctx, kv=kv, resident=resident)