From 5322f1c2bd8e8de4279038c2366ad1e2aec3dd06 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 01:21:21 +0100 Subject: [PATCH 1/8] NOTICE for libstrix (asf0, MIT): the gfx1151 fused-expert barrier follows its barrier() --- third_party/libstrix/NOTICE.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 third_party/libstrix/NOTICE.md diff --git a/third_party/libstrix/NOTICE.md b/third_party/libstrix/NOTICE.md new file mode 100644 index 0000000000..c72538daf5 --- /dev/null +++ b/third_party/libstrix/NOTICE.md @@ -0,0 +1,7 @@ +# libstrix (asf0), MIT + +The workgroup barrier with the explicit LDS wait in `src/prefill/moe_fused_iq.cu` (the gfx1151 fused prompt experts) takes the idea +and the wording of `barrier()` from libstrix by asf0 (https://github.com/asf0/libstrix), MIT License. + +Copyright (c) asf0 and the libstrix contributors. The MIT licence text is in the upstream repository; this notice stays with the code +that uses it. From f93ec8a9241fc12c3b088c4c9a1281d0d44cd014 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 02:56:19 +0100 Subject: [PATCH 2/8] DeepSeek card rule shared by the plan, the options and setup: every card that counts, one AMD card on Windows, only cards the engine package has code for, an APU beside a discrete card left out --- strata_control/dsv41_fit.py | 65 +++++++++++++++++++++++++++++-------- tools/strata_mcp.py | 2 +- tools/test_setup_dsv41.py | 10 ++++++ 3 files changed, 62 insertions(+), 15 deletions(-) diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index 4b7c429771..7f78b20bb9 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -23,6 +23,8 @@ import platform import sys from typing import Any +import os + from strata_control import gpu_fit GB = 1e9 @@ -107,6 +109,46 @@ def variant(model: str | None) -> dict | None: return next((v for k, v in ISTA_SETS.items() if k.lower() == str(model).lower()), None) +#: The AMD cards the DeepSeek engine package holds code for (packaging/build_hip_linux.sh: strata-dsv41 ships in the rx9070 build, gfx1200 and +#: gfx1201). setup passes the installed package's own list when it has one. +DSV41_HIP_ARCHS = ("gfx1200", "gfx1201") + + +def _on_windows() -> bool: + return os.name == "nt" + + +def run_cards(cards: list[dict] | None, vendor: str | None = None, *, windows: bool | None = None, + covered=None, named: bool = False) -> tuple[list[dict], list[dict]]: + """The cards one DeepSeek run uses when the person named none: (cards, left out with 'why_ignored'), in card order. The ONE rule that + `strata launch --plan`, setup and the app share, so the plan says what the run does. + Every card that counts (gpu_fit.usable_cards: no integrated chip beside a card with memory of its own, no card under 8 GB). AMD: + on Windows one card only (several AMD cards sharing a model is Linux-only, setup.py), and only cards the engine package holds code for + (`covered`, default DSV41_HIP_ARCHS): a PC with an RX 9070 and an RX 7900 uses the RX 9070 and says why the other is left out. + `named`: the person named these cards: they are used as named (setup warns about one the package has no code for).""" + mine = gpu_fit.for_vendor(list(cards or []), vendor)[0] if vendor else list(cards or []) + keep, ignored = gpu_fit.usable_cards(mine) + small = [c for c in keep if float(c.get("vram_gb") or 0) < SMALLEST_CARD_GB] + keep = [c for c in keep if float(c.get("vram_gb") or 0) >= SMALLEST_CARD_GB] + ignored = list(ignored) + [{**c, "why_ignored": f"only {float(c.get('vram_gb') or 0):.0f} GB of graphics memory"} for c in small] + amd = not named and bool(keep) and all(str(c.get("vendor") or vendor or "").lower() == "amd" for c in keep) + if amd: + archs = tuple(covered if covered is not None else DSV41_HIP_ARCHS) + known = [c for c in keep if c.get("arch")] + ok = [c for c in keep if not c.get("arch") or c["arch"] in archs] + if known and ok and len(ok) < len(keep): + ignored += [{**c, "why_ignored": f"the DeepSeek engine has no code for {c['arch']} (it runs on {', '.join(archs)})"} + for c in keep if c not in ok] + keep = ok + if (_on_windows() if windows is None else windows) and len(keep) > 1: + first = min(keep, key=lambda c: (-round(float(c.get("vram_gb") or 0)), c.get("index", 0))) + ignored += [{**c, "why_ignored": "on Windows a model runs on one AMD card"} for c in keep if c is not first] + keep = [first] + keep = sorted(keep, key=lambda c: c.get("index", 0)) + return keep, ignored + + + def uma_card(cards: list[dict] | None) -> dict | None: """The integrated Radeon a run uses, when the graphics memory is the PC's RAM (Ryzen AI Max, gfx1151): setup marks it `uma` (and `integrated`); a discrete card never is. None on every other computer.""" @@ -201,14 +243,12 @@ def _tp_args(n_cards: int, tp: int) -> list[str]: def _plan_ista(model: str, cards: list[dict] | None, ram_gb: float | None, disk_free_gb: float | None, context: int, - vendor: str | None) -> dict[str, Any]: + vendor: str | None, named: bool = False) -> dict[str, Any]: """plan() for an official IST-DAS set (ISTA_SETS): the same keys, the measured speeds in plain words. RAM classes: with RAM for every expert the CPU lane keeps ("fits"), with 40 GB or more the engine's RAM store keeps the hot experts and reads the rest from the SSD ("tight": measured 4.7 tokens a second on 64 GB, 7.2 on 46 GB), under 40 GB it is untested and slower ("spills"). Never a refusal.""" v = variant(model) - keep, ignored = gpu_fit.usable_cards(gpu_fit.for_vendor(list(cards or []), vendor)[0]) if vendor else gpu_fit.usable_cards(list(cards or [])) - keep = [c for c in keep if float(c.get("vram_gb") or 0) >= SMALLEST_CARD_GB] - keep.sort(key=lambda c: c.get("index", 0)) + keep, ignored = run_cards(cards, vendor, named=named) n = len(keep) expert_gb = v["experts_gb"] / EXPERTS set_gb = v["set_bytes"] / GB @@ -353,7 +393,7 @@ def _plan_uma(key: str, model: str, card: dict, ram_gb: float | None, disk_free_ def plan(cards: list[dict] | None, ram_gb: float | None, disk_free_gb: float | None = None, context: int = 8192, - vendor: str | None = None, model: str | None = None) -> dict[str, Any]: + vendor: str | None = None, model: str | None = None, named: bool = False) -> dict[str, Any]: """Where the model goes on this computer. `cards`: the graphics cards ({"index", "name", "vram_gb", ...}, as gpu_fit takes them), `ram_gb` the RAM, `disk_free_gb` the free space where the files go (None: not checked). `model`: an official IST-DAS set (ISTA_SETS: "IST-DAS-2.00bpw" / "IST-DAS-2.25bpw" / "IST-DAS-1.75bpw") gets its own numbers; None or "UD-Q8_K_XL" is Unsloth's 508 GB set. @@ -368,13 +408,11 @@ def plan(cards: list[dict] | None, ram_gb: float | None, disk_free_gb: float | N if mac is not None and variant_key(model) in MAC_SET_PACK: return _plan_mac(variant_key(model), model, mac, ram_gb, disk_free_gb, context) mine = gpu_fit.for_vendor(list(cards or []), vendor)[0] if vendor else list(cards or []) - card = uma_card(mine) + card = uma_card(gpu_fit.usable_cards(mine)[0]) # an APU beside a card with memory of its own does not count (setup leaves it out too) if card is not None: return _plan_uma(variant_key(model), model, card, ram_gb, disk_free_gb, context) - return _plan_ista(variant_key(model), cards, ram_gb, disk_free_gb, context, vendor) - keep, ignored = gpu_fit.usable_cards(gpu_fit.for_vendor(list(cards or []), vendor)[0]) if vendor else gpu_fit.usable_cards(list(cards or [])) - keep = [c for c in keep if float(c.get("vram_gb") or 0) >= SMALLEST_CARD_GB] - keep.sort(key=lambda c: c.get("index", 0)) # the engine takes the layers in card order + return _plan_ista(variant_key(model), cards, ram_gb, disk_free_gb, context, vendor, named) + keep, ignored = run_cards(cards, vendor, named=named) # the engine takes the layers in card order n = len(keep) out: dict[str, Any] = {"cards": [], "experts_total": EXPERTS, "experts_in_vram": 0, "vram_experts_gb": 0.0, "cpu_experts_gb": EXPERTS_GB, "weights_gb": _round1(WEIGHTS_GB), "experts_gb": _round1(EXPERTS_GB), @@ -490,16 +528,15 @@ def _option(key: str, cards: list[dict], ram_gb: float | None, ctx: int, vendor: def options(cards: list[dict], ram_gb: float | None, vendor: str | None = None, context: int = 8192, model: str | None = None) -> dict[str, Any]: """gpu_fit.options for this model: every card that counts (recommended: the model is bigger than any one card, so each card adds experts that stay off the CPU), and the largest card alone. Same keys as gpu_fit.options.""" - mine, others = gpu_fit.for_vendor(list(cards or []), vendor) if vendor else (list(cards or []), []) - keep, ignored = gpu_fit.usable_cards(mine) - keep = [c for c in keep if float(c.get("vram_gb") or 0) >= SMALLEST_CARD_GB] + keep, ignored = run_cards(cards, vendor) # the same cards `strata launch --plan` and setup use (Windows: one AMD card; the package's own archs) out: dict[str, Any] = {"options": [], "recommended": None, "ignored": ignored, "cards": len(keep), "vendor": vendor, "other_vendor_note": gpu_fit.other_vendor_note(list(cards or []), vendor)} if not keep: return out opts = [_option("all", sorted(keep, key=lambda c: c.get("index", 0)), ram_gb, context, vendor, model)] if len(keep) > 1: - opts.append(_option("single", [keep[0]], ram_gb, context, vendor, model)) + largest = min(keep, key=lambda c: (-round(float(c.get("vram_gb") or c.get("unified_gb") or 0)), c.get("index", 0))) + opts.append(_option("single", [largest], ram_gb, context, vendor, model)) opts[0]["recommended"] = True out["options"], out["recommended"] = opts, "all" return out diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index eaf927aa06..bdea17bcb3 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -1371,7 +1371,7 @@ class Strata: cards = list((hw or {}).get("gpus", [])) if only: cards = [c for c in cards if int(c.get("index", -1)) in {int(i) for i in only}] - return dsv41_fit.plan(cards, (hw or {}).get("ram_gb"), disk_free, vendor=(hw or {}).get("engine_vendor"), model=model) + return dsv41_fit.plan(cards, (hw or {}).get("ram_gb"), disk_free, vendor=(hw or {}).get("engine_vendor"), model=model, named=bool(only)) def dsv41_words(self, hw, model=None, installed: bool = False) -> str: """The catalog's `on_this_pc` text for DeepSeek-V4.1-Flash, with the disk it needs (download and preparation) beside the memory: a set that diff --git a/tools/test_setup_dsv41.py b/tools/test_setup_dsv41.py index 13d8ddf091..ed2d9d6e03 100644 --- a/tools/test_setup_dsv41.py +++ b/tools/test_setup_dsv41.py @@ -77,6 +77,11 @@ class Entries(unittest.TestCase): class Fit(unittest.TestCase): + def setUp(self): # the AMD rules below are the Linux ones, whatever box the test runs on + p = mock.patch.object(dsv41_fit, "_on_windows", lambda: False) + p.start() + self.addCleanup(p.stop) + def test_the_numbers_of_the_model(self): self.assertAlmostEqual(dsv41_fit.WEIGHTS_GB, 305.6, delta=0.1) self.assertAlmostEqual(dsv41_fit.EXPERTS_GB, 288.8, delta=0.1) @@ -301,6 +306,11 @@ class Install(unittest.TestCase): class Catalog(unittest.TestCase): + def setUp(self): # the AMD rules below are the Linux ones, whatever box the test runs on + p = mock.patch.object(dsv41_fit, "_on_windows", lambda: False) + p.start() + self.addCleanup(p.stop) + def test_the_mcp_catalog_lists_the_size(self): import strata_mcp as M s = M.Strata(ROOT) From 6f7f763ce580a798e24094ee0fe9c8b6afa76a05 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 02:56:19 +0100 Subject: [PATCH 3/8] DeepSeek on several AMD cards uses every card when none was named: setup's own pick is no longer 'asked'; old configs of that pick move to every card at the start; the launcher and the app stop keeping it --- apps/host/server/native-control.mjs | 12 ++- setup.py | 117 +++++++++++++++++++++++++--- strata_cli/launch/runner.py | 20 ++++- strata_cli/launch/screens.py | 2 +- strata_control/gpu_pick.py | 78 +++++++++++++++++++ 5 files changed, 212 insertions(+), 17 deletions(-) create mode 100644 strata_control/gpu_pick.py diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 769150d804..01bb36377f 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -278,7 +278,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} const resources=args.resourceProfile&&!ownEngine(config)?resourceSettings({...base0,[USER_KEY]:mine,vision},snapshot.hardware,args.resourceProfile,modelArena(args.model),values0):null; const cfg={...config,...visionPreferences,...(resources?{...resources,ui_resource_profile:args.resourceProfile}:{}),host:'127.0.0.1',open_browser:false,...validateNativeSettings(args.values??{}),vision}; /* The app's suggested cards only fill a gap: a model whose settings file already names its GPUs ("gpu": [1, 0], with "gpu_order": "as_given") keeps them (#3256). A card the person picked in the screen always wins. */ - const namedInFile=(Array.isArray(config.gpu)?config.gpu.length>0:config.gpu!==undefined&&config.gpu!==null&&config.gpu!=='')||!!config.gpu_roles; + const namedInFile=((Array.isArray(config.gpu)?config.gpu.length>0:config.gpu!==undefined&&config.gpu!==null&&config.gpu!=='')||!!config.gpu_roles)&&!setupPickedOneCard(config,snapshot.hardware); /* Roles chosen in the screen (Main / Helper / Off per card, gpu-roles.mjs): the card list is the roles' mirror - Helpers first, the Main card LAST, Off cards left out - with "gpu_roles" beside it. Every card Off is allowed: the server says plainly what the engine can do. */ if(args.gpuRoles!==undefined){const make=snapshot.hardware?.engine_vendor,cards=(snapshot.hardware?.gpus??[]).filter(g=>!make||!g.vendor||g.vendor===make),named=parseRoles(args.gpuRoles);if(!named)throw new Error('Choose Main, Helper or Off for each graphics card, with one Main.');const known=new Set(cards.map(g=>g.index));if(Object.keys(named).some(k=>!known.has(Number(k))))throw new Error('Choose detected graphics cards.');const roles=Object.fromEntries(cards.map(g=>[g.index,named[g.index]??'off'])),m=mirrorRoles(roles,cards);for(const k of ['gpu','gpu_order','gpu_none','gpu_roles','gpu_cards','hip_ordinal'])delete cfg[k];Object.assign(cfg,m);const count=Array.isArray(m.gpu)?m.gpu.length:m.gpu_none?0:1;cfg.layer_split=count>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==count-1)throw new Error('Choose one layer split point between each pair of GPUs.');} else if(args.gpus!==undefined&&!(args.gpusFromRecommendation&&namedInFile)){const detected=new Set((snapshot.hardware?.gpus??[]).map(g=>g.index));if(!Array.isArray(args.gpus)||!args.gpus.length||new Set(args.gpus).size!==args.gpus.length||args.gpus.some(g=>!Number.isInteger(g)||!detected.has(g)))throw new Error('Choose distinct detected GPUs. CPU-only text inference is not supported by this native adapter.');cfg.gpu=args.gpus.length===1?args.gpus[0]:args.gpus;for(const k of ['gpu_roles','gpu_cards','gpu_none'])delete cfg[k];delete cfg.hip_ordinal;cfg.layer_split=args.gpus.length>1?validateNativeSettings({layer_split:args.layerSplit??'auto'}).layer_split:'auto';if(cfg.layer_split!=='auto'&&cfg.layer_split.split(',').length!==args.gpus.length-1)throw new Error('Choose one layer split point between each pair of GPUs.');} @@ -593,3 +593,13 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} async function localPreview(path){if(!packaged)throw new Error('Checking local model files is part of the Strata app.');if(typeof path!=='string'||!path.trim()||[...path].some(c=>c.charCodeAt(0)<32))throw new Error('Choose a folder.');return control.importPlan(path.trim());} return {state:publicState,tuneStatus,tuneEffective,tuneOff,tunePresets:{list:()=>autotuner.list(),action:(kind,id,extra)=>autotuner.action(kind,id,extra),undoFor:async args=>autotuner.undoFor(tuneConfig(args).path)},refresh,localPreview,configure,setDownloadDirectory,planModelsFolder,startModelsFolder,interruptedMove,finishInterruptedMove,leaveInterruptedMove,plan,settings,save,settingsFile,openSettingsFile,operation,cancel,unload,resolveInstance,poll,logs:()=>logs.slice(),benchmarkReport:()=>readJson(join(directory,'native-benchmark.json'),null),setDefault(id){defaultId=resolveInstance(id).id;emit();return publicState();},hasLive:()=>[...instances.values()].some(i=>i.status==='ready'),readyInstances:()=>[...instances.values()].filter(i=>i.status==='ready'),defaultInstanceId:()=>defaultId,close}; } +/* A DeepSeek config on AMD written by setup 0.2.8 or earlier names ONE card and marks it "asked", though setup picked it itself (strata_control/gpu_pick.py): it must not stop the app's recommended cards from applying. A card setup named for itself is the first of the usable cards, largest memory first; another card number was the person's. Roles and a "gpus_by" marker are always honoured. */ +export function setupPickedOneCard(config,hardware){ + if(!config||config.arch!=='deepseek41'||config.backend!=='hip'||config.gpus_by||config.gpu_roles||!config.gpus_asked)return false; + const one=Array.isArray(config.gpu)?(config.gpu.length===1?config.gpu[0]:null):config.gpu;if(!Number.isInteger(Number(one))||one===null||one==='')return false; + const cards=(hardware?.gpus??[]).filter(g=>(g.vendor==='amd')&&g.usable!==false),shares=g=>!!(g.uma||g.integrated||g.unified_gb),vram=g=>Number(g.vram_gb)||0; + const real=cards.some(g=>!shares(g)&&vram(g)>=4),keep=cards.filter(g=>!(shares(g)&&real)&&vram(g)>=8); + if(process.platform==='win32'||keep.length<2)return false; + const first=[...keep].sort((a,b)=>Math.round(vram(b))-Math.round(vram(a))||a.index-b.index)[0]; + return Number(one)===first.index; +} diff --git a/setup.py b/setup.py index 03861fa317..fd839d116b 100644 --- a/setup.py +++ b/setup.py @@ -6496,7 +6496,7 @@ def write_config(path: Path, cfg: dict): # "args_written" (strata_control/user_args.py) is setup's own; "user_args" is not in SETUP_KEYS on purpose: carry_over keeps it, # then applies the person's options over the generated ones SETUP_KEYS = frozenset({"exe", "args", "cwd", "tokenizer", "model_name", "log", "lib_dirs", "port", "backend", "env", - "gpu", "gpus_asked", "layer_split", "host", "api_key", "draft_vocab", "vision", "args_written"}) + "gpu", "gpus_asked", "gpus_by", "layer_split", "host", "api_key", "draft_vocab", "vision", "args_written"}) SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_ROCBLAS_TUNING", "STRATA_RESIDENT_PIN", "STRATA_NO_ARENA_THP", "STRATA_MMQ_KQ", "STRATA_HC_Q8", "STRATA_ROUTE_TAIL_SKIP"}) | frozenset(GFX1103_SWITCHES) | frozenset(GFX1150_SWITCHES) # the "env" entries setup writes (the gfx1103 switches are setup's too: a re-run refreshes them, they do not linger) # 0.1.44 added these three, written for Unsloth's files only (unsloth_default_env). In any other model's config they are the @@ -7078,6 +7078,31 @@ def settings_summary(cfg: dict, port=None) -> str: return " ".join(out) + ("; " if out else "") + "server " + ", ".join(srv) +def widen_setups_one_card(cfg_path: Path, cfg: dict, amd: list) -> dict: + """A DeepSeek run config on AMD that names one card and was written by setup 0.2.8 or earlier (the card was setup's own pick, marked "asked" + by mistake) moves to every card that counts, here at the start, with its pack and files untouched. A card the person named + (strata_control/gpu_pick.py) stays. Linux only: several AMD cards sharing a model is not supported on Windows.""" + if WIN or not isinstance(cfg, dict) or cfg.get("gpus_by") or not cfg.get("gpus_asked"): + return cfg + try: + from strata_control import gpu_pick + usable = amd_usable_cards(amd) + if not gpu_pick.looks_like_setups_pick(cfg, usable): + return cfg + cards = [c["index"] for c in dsv41_auto_cards(amd, ROOT / "engine")] + if len(cards) < 2: + return cfg + was = gpu_pick.single_card(cfg) + new = gpu_pick.widened(cfg, cards) + write_config(cfg_path, new) + ok(f"DeepSeek now uses all {len(cards)} of your AMD cards (it was set up on GPU {was} alone by an earlier Strata). Nothing is rebuilt. " + f"To keep it on one card: ./setup.sh --gpu {was}") + return new + except Exception as e: # noqa: BLE001 - never stop a start over this + warn(f"could not check which cards this model should use ({e})") + return cfg + + def start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open_browser=True, yes=False, layer_split=None, keep=None) -> int: """Start the model. Nothing is installed, downloaded or compiled while it starts (strata_control/acquisition.py): @@ -7132,13 +7157,15 @@ def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open if miss: fail("the installed engine has no code for " + ", ".join(f"{x['name']} ({x['arch']})" for x in miss), "set it up for these cards: ./setup.sh --setup --backend hip --gpus " + ",".join(map(str, gpu))) - cfg["gpu"], cfg["gpus_asked"] = gpu, True + cfg["gpu"], cfg["gpus_asked"], cfg["gpus_by"] = gpu, True, "person" cfg["layer_split"] = layer_split or cfg.get("layer_split") or "auto" split_budget(cfg, yes, True) # #498: before it is saved (asks when the RAM is short, #737) write_config(cfg_path, cfg) gpu = None elif gpu is not None: cmd += ["--gpu", str(gpu)] + else: + cfg = widen_setups_one_card(cfg_path, cfg, amd) # a DeepSeek config from setup 0.2.8 and earlier: setup's own one-card pick found = [] use = gpu if gpu is not None else cfg.get("gpu") if isinstance(use, list): @@ -8133,7 +8160,7 @@ def dsv41_manual_steps(eng: Path) -> str: "and run it again. Strata checks it before it is used.") -def get_dsv41_engine(eng: Path, hip: bool, package: str | None = None, feed: str | None = None) -> Path | None: +def get_dsv41_engine(eng: Path, hip: bool, package: str | None = None, feed: str | None = None, archs=None) -> Path | None: """The DeepSeek engine package next to the engine `eng`: one the person gave (--dsv41-package) or put in engine-dsv41/ by hand, else downloaded from the signed feed `feed` (--feed; else STRATA_UPDATE_FEED, a remembered https feed, or the release's). Checked first either way; its strata-dsv41, or None when it cannot be had.""" @@ -8157,6 +8184,8 @@ def get_dsv41_engine(eng: Path, hip: bool, package: str | None = None, feed: str if hip: from strata_control import updater hw = {**updater.detect_hardware(), "backend": "hip", "backend_source": "requested"} + if archs: # the package is chosen for the cards this model runs on, not for every card in the PC + hw["gfx"] = sorted({str(x) for x in archs}) exe = dsv41_engine.install(root, source, hardware=hw, emit=lambda m: say(" " + m)) if exe is None: warn("no DeepSeek engine package could be fetched (see above)") @@ -8384,6 +8413,50 @@ def dsv41_smoke(exe: Path, pack: Path, lib_dirs, gpus=None, timeout: int = 5400) return r.returncode == 0, text[-1500:].encode(enc, "replace").decode(enc, "replace") +def cards_named(a, hip: bool = False) -> bool: + """Did the person name the cards (--gpu / --gpus)? On AMD setup's own pick is written into a.gpu further on (other steps rely on it), so + the AMD branch records the answer first (a._cards_named); NVIDIA keeps its way (choose_gpus sets a.gpu to the cards in use).""" + named = getattr(a, "_cards_named", None) + return bool(named) if (hip and named is not None) else bool(a.gpu is not None or a.gpus) + + +def amd_usable_cards(amd) -> list: + """The AMD cards that count for a model (gpu_fit.usable_cards: no integrated chip beside a card with memory of its own, none under 8 GB).""" + from strata_control import gpu_fit + return gpu_fit.usable_cards([{**g, "vendor": "amd", "usable": amd_problem(g) is None} for g in amd])[0] + + +def dsv41_covered_archs(eng) -> tuple: + """The AMD architectures the installed DeepSeek engine package holds code for (its manifest), else what the release's package is built for.""" + from strata_control import dsv41_fit + try: + from strata_control import engine_component as ec + exe = dsv41_exe(Path(eng)) + if exe is not None and (exe.parent / ec.MANIFEST).is_file(): + archs = ec.read_manifest(exe.parent).hip_archs + if archs: + return tuple(archs) + except Exception: # noqa: BLE001 - the release's list is the fallback + pass + return tuple(dsv41_fit.DSV41_HIP_ARCHS) + + +def dsv41_auto_cards(amd, eng) -> list: + """DeepSeek on AMD with no card named: every card that counts and the engine package can run (one card on Windows: several AMD cards sharing + a model is Linux-only). The same rule as `strata launch --plan` (strata_control/dsv41_fit.run_cards). What is left out is said.""" + from strata_control import dsv41_fit + # only real AMD cards (gfx...): sycl/setup_intel.py runs this same branch with its Intel cards in `amd` (arch "xe" / "i915"), and the DeepSeek + # engine has no Intel package: those keep the one card setup picked + pool = [{**g, "vendor": "amd", "usable": amd_problem(g) is None} for g in amd + if amd_problem(g) is None and str(g.get("arch") or "").startswith("gfx")] + keep, left = dsv41_fit.run_cards(pool, "amd", windows=WIN, covered=dsv41_covered_archs(eng)) + byid = {g["index"]: g for g in amd} + for c in left: + if c.get("why_ignored") and not str(c["why_ignored"]).startswith("it shares the system memory"): + say(f" Not used for DeepSeek: GPU {c.get('index')} ({c.get('name')}): {c['why_ignored']}.") + return [byid[c["index"]] for c in keep] + + def dsv41_cards(gpu: dict, all_cards: list | None, asked: bool) -> list: """The cards the model runs on: the ones asked for (--gpu / --gpus), else every card setup can use (recommend: the model is larger than any one card, so the more graphics memory the more of its experts stay off the CPU).""" @@ -8431,7 +8504,8 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, udlow = md.get("recipe") == "udlow" # Unsloth's UD-IQ1_S / UD-IQ1_M: packed and checked like the IST-DAS sets; shard 5 is the Engram ista = md.get("recipe") in ("ista", "udlow") tag = fam["tag"] + model - cards = dsv41_cards(gpu, all_cards, bool(a.gpu is not None or a.gpus)) + named = cards_named(a, hip) + cards = dsv41_cards(gpu, all_cards, named) ctx = a.context or DSV41_CONTEXT if dsv41_context.problem(ctx): # 8K to 1M: the model reads 1,048,576 positions (Project Maya #442); a size it cannot address stops here, before any download fail(dsv41_context.problem(ctx), "--context takes 8192 up to 1048576 (8K, 32K, 64K, 128K, 256K, 512K, 1M); the default is 8192") @@ -8461,7 +8535,8 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, for f in [*shards, *shared]) / 1e9 probe = folder if folder.exists() else (folder.parent if folder.parent.exists() else Path(a.models_dir)) free = free_gb(probe) - plan = dsv41_fit.plan([{**c, "vram_gb": float(c.get("vram_gb") or 0)} for c in cards], ram, free if left else None, ctx, model=model) + plan = dsv41_fit.plan([{**c, "vram_gb": float(c.get("vram_gb") or 0)} for c in cards], ram, free if left else None, ctx, model=model, + named=True) # `cards` are decided above (dsv41_auto_cards / the person's): the plan describes them say() for line in plan["lines"]: say(" " + line) @@ -8523,7 +8598,8 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, fail("Strata can't reach GitHub to download the DeepSeek engine.", "Check the internet connection and run the same command again. " + dsv41_manual_steps(eng)) if exe is None and not getattr(a, "build", False): - get_dsv41_engine(eng, hip, getattr(a, "dsv41_package", None), getattr(a, "feed", None)) + get_dsv41_engine(eng, hip, getattr(a, "dsv41_package", None), getattr(a, "feed", None), + archs=[c.get("arch") for c in cards if c.get("arch")] if hip else None) exe = dsv41_exe(eng) if (exe is not None and not getattr(a, "dsv41_package", None) and not getattr(a, "build", False) and not (os.environ.get("STRATA_DSV41_EXE") or "").strip() and exe.parent.parent == dsv41_engine_dir(eng)): @@ -8531,6 +8607,12 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, if exe is not None and exe.parent != Path(eng): from strata_control import dsv41_engine lib_dirs = [*lib_dirs, *dsv41_engine.lib_dirs(exe)] # its own package, and the rocm/bin an AMD package keeps the ROCm DLLs in + if hip and exe is not None and named: # cards the person named that this package holds no code for: said, never refused + covered = dsv41_covered_archs(eng) + for c in cards: + if c.get("arch") and c["arch"] not in covered: + warn(f"GPU {c['index']} ({c['name']}, {c['arch']}): this DeepSeek engine package holds code for {', '.join(covered)} only, so it may " + "not start on that card. Leave it out (--gpus ...) to be sure.") if exe is None: if os.environ.get("STRATA_VERBOSE") == "1" or "--verbose" in sys.argv: say(" Details for developers: build it with cmake -DSTRATA_BUILD_DSV41=ON -DCMAKE_CUDA_ARCHITECTURES= " @@ -8612,7 +8694,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, warn("the 16-word test run was skipped (STRATA_DSV41_NO_SMOKE=1)") else: say(" Testing the model with a short question (a few minutes: the engine reads the first experts from the disk) ...") - good, why = dsv41_smoke(exe, pack, lib_dirs, [c["index"] for c in cards] if (a.gpu is not None or a.gpus) else None) + good, why = dsv41_smoke(exe, pack, lib_dirs, [c["index"] for c in cards] if (named or (hip and len(cards) > 1)) else None) if not good: fail("the model does not answer sensibly after the preparation: " + (why.splitlines()[-1] if why else "no answer"), f"delete {pack} and run setup again so the pack is built fresh; if the test fails again, " @@ -8649,9 +8731,14 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, if mac: cfg["backend"] = "metal" idx = [c["index"] for c in cards] - if len(idx) > 1 or a.gpu is not None or a.gpus: + if len(idx) > 1 or named: cfg["gpu"] = idx if len(idx) > 1 else idx[0] - cfg["gpus_asked"] = True + if hip: # who chose them (strata_control/gpu_pick.py): setup's own pick is not "asked" + cfg["gpus_by"] = "person" if named else "setup" + if named: + cfg["gpus_asked"] = True + else: + cfg["gpus_asked"] = True if a.host: cfg["host"] = a.host if a.api_key: @@ -9194,7 +9281,14 @@ def main() -> int: a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"]) a.layer_split = a.layer_split or ch.get("layer_split") else: - a.gpu = a.gpu if a.gpu is not None else ch.get("gpu") + try: # a card setup picked itself is not a choice to carry over (strata_control/gpu_pick.py) + from strata_control import gpu_pick + earlier = json.loads(prev.read_text(encoding="utf-8-sig")) + keep_card = gpu_pick.chosen_by_person(earlier, amd_usable_cards(amd_gpus())) + except (OSError, ValueError): + keep_card = True + if keep_card: + a.gpu = a.gpu if a.gpu is not None else ch.get("gpu") a.yes = True global GPU_PICK, OLD_GPUS # starting an installed model: --gpus 0,2 (or all) saves those cards for it and starts on them (it used to start @@ -9308,6 +9402,7 @@ def main() -> int: "your user in the render and video groups)") if not usable: fail("no AMD GPU Strata can use", f"the AMD backend runs on {AMD_CARDS}") + a._cards_named = bool(a.gpu is not None or a.gpus) # before setup's own pick is written into a.gpu below if a.gpus: # a layer split across these cards, the first one the main chosen = amd_parse_gpus(a.gpus, amd) gpu = chosen[0] @@ -9503,7 +9598,7 @@ def main() -> int: if family in OWN_PATH_FAMILIES: # Qwen3.6: its own engine path, its own steps 2-7 return install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted) if family in MULTI_FILE_FAMILIES: # DeepSeek-V4.1-Flash: nine shards, its own engine, several cards - all_cards = amd_ok if hip else [g for g in found if gpu_problem(g) is None] + all_cards = (None if (WIN or getattr(a, "_cards_named", False)) else dsv41_auto_cards(amd, ROOT / "engine")) if hip else [g for g in found if gpu_problem(g) is None] gpu = {**gpu, "cards": chosen} return install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, all_cards) fam = FAMILIES[family] diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 4a01dc9ee8..0209c69085 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -356,11 +356,15 @@ def apply_cards(cfg: dict, gpus: "list[int] | dict | None") -> None: cfg.pop("layer_split", None) -def installed_cards(base: dict | None) -> list[int] | None: +def installed_cards(base: dict | None, usable: list[dict] | None = None) -> list[int] | None: """The cards the installed model's own config names after a choice (setup --gpu / --gpus, the app's card pick: "gpus_asked"), in its order; - None when it names none or was never asked.""" + None when it names none or was never asked, or when setup picked them itself (strata_control/gpu_pick.py: a DeepSeek config of setup 0.2.8 + and earlier marks setup's one-card pick as asked; `usable`: the cards that count on this PC, needed to tell the two apart).""" if not isinstance(base, dict) or not (base.get("gpus_asked") or base.get("gpu_roles")): return None + from strata_control import gpu_pick + if not gpu_pick.chosen_by_person(base, usable): + return None g = base.get("gpu") if g is None or g == "": return None @@ -387,7 +391,11 @@ def cards_for_launch(s: S.LaunchSettings, catalog, ram_gb: float | None = None, return None if s.gpus: return [int(g) for g in s.gpus] - if installed_cards(base) or (isinstance(base, dict) and base.get("gpu_roles")): + try: + usable_now = catalog.computer().usable_gpus + except Exception: # noqa: BLE001 - without the card list a saved card is kept, as before + usable_now = None + if installed_cards(base, usable_now) or (isinstance(base, dict) and base.get("gpu_roles")): return None try: from strata_control import gpu_roles @@ -948,7 +956,11 @@ class Runner: roles = base.get("gpu_roles") if isinstance(roles, dict) and roles: return ["--gpu-roles", ",".join(f"{k}={v}" for k, v in sorted(roles.items(), key=lambda kv: int(kv[0])))] - cards = installed_cards(base) + try: + usable_now = self.catalog.computer().usable_gpus + except Exception: # noqa: BLE001 + usable_now = None + cards = installed_cards(base, usable_now) if cards: return ["--gpus", ",".join(str(g) for g in cards)] if len(cards) > 1 else ["--gpu", str(cards[0])] except Exception: # noqa: BLE001 - never block a launch over remembering the cards diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index a7e8bc6ae3..266a4ac2e7 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -620,7 +620,7 @@ class CardsScreen(Base): """The cards the installed model was set to by a person's choice (kept unless this launch names others).""" from strata_cli.launch.runner import installed_cards try: - return installed_cards(self.ctx.base_config()) + return installed_cards(self.ctx.base_config(), self.ctx.computer.usable_gpus) except Exception: # noqa: BLE001 return None diff --git a/strata_control/gpu_pick.py b/strata_control/gpu_pick.py new file mode 100644 index 0000000000..3681a907ad --- /dev/null +++ b/strata_control/gpu_pick.py @@ -0,0 +1,78 @@ +"""Who chose the graphics cards of an installed model: the person, or setup's own pick. + +Setup used to write "gpus_asked": true for every single-card run config, also when setup had picked the card itself (a DeepSeek run on a PC +with several AMD cards: setup took the first card, called it asked, and every later launch handed that "choice" back, so four cards ran +on one). New configs say who chose in "gpus_by" ("person" or "setup"). A config without it is judged here: + +* roles ("gpu_roles") and card lists of two or more are the person's (setup never wrote a list unless the cards were named or all used); +* a single card is setup's pick when the model is DeepSeek on AMD, the PC has more than one card that counts, and the card is the one setup + would have taken (the first of the usable cards, largest memory first). A person who named another card (``--gpu 2``) keeps it; + one who named exactly the card setup would have taken cannot be told from setup's own pick and is moved to all cards once, with a plain + line saying how to keep one card (``--gpu N``, remembered from then on). +""" +from __future__ import annotations + +from typing import Any + +ASKED_BY_PERSON = "person" +PICKED_BY_SETUP = "setup" + + +def _is_deepseek_amd(cfg: dict) -> bool: + return str(cfg.get("arch") or "") == "deepseek41" and str(cfg.get("backend") or "") == "hip" + + +def single_card(cfg: dict) -> int | None: + g = cfg.get("gpu") + if isinstance(g, bool) or g is None or g == "": + return None + if isinstance(g, (list, tuple)): + return int(g[0]) if len(g) == 1 and str(g[0]).strip().lstrip("-").isdigit() else None + return int(str(g).strip()) if str(g).strip().lstrip("-").isdigit() else None + + +def setup_pick_index(usable: list[dict]) -> int | None: + """The card setup takes when nothing is named: the usable cards, largest memory first, then the lower number.""" + if not usable: + return None + first = min(usable, key=lambda c: (-round(float(c.get("vram_gb") or 0)), int(c.get("index", 0)))) + return int(first.get("index", 0)) + + +def chosen_by_person(cfg: dict | None, usable: list[dict] | None = None) -> bool: + """True when the cards in `cfg` are the person's choice (keep them); False when setup picked them (they may be widened). + `usable`: the cards that count on this PC (strata_control.gpu_fit.usable_cards), needed only to judge a legacy single AMD card.""" + if not isinstance(cfg, dict): + return False + if cfg.get("gpu_roles"): + return True + by = cfg.get("gpus_by") + if by in (ASKED_BY_PERSON, PICKED_BY_SETUP): + return by == ASKED_BY_PERSON + if not cfg.get("gpus_asked"): + return False + return not looks_like_setups_pick(cfg, usable) + + +def looks_like_setups_pick(cfg: dict, usable: list[dict] | None) -> bool: + """A config from setup 0.2.8 and earlier: DeepSeek on AMD, one card, on a PC where more than one card counts, and the card setup would have taken.""" + if not _is_deepseek_amd(cfg) or cfg.get("gpus_by") or cfg.get("gpu_roles"): + return False + one = single_card(cfg) + if one is None or not usable or len(usable) < 2: + return False + return one == setup_pick_index(usable) + + +def widened(cfg: dict, cards: list[int]) -> dict: + """`cfg` with setup's own pick of `cards` (two or more): card list, no 'asked' mark, and the marker that setup chose them.""" + out = dict(cfg) + out["gpu"] = list(cards) if len(cards) > 1 else cards[0] + out.pop("gpus_asked", None) + out["gpus_by"] = PICKED_BY_SETUP + out.pop("hip_ordinal", None) + return out + + +def describe(cfg: dict, usable: list[dict] | None) -> dict[str, Any]: + return {"by_person": chosen_by_person(cfg, usable), "legacy": not cfg.get("gpus_by") and bool(cfg.get("gpus_asked"))} From dec8f1366c89ab4385b22a7b5688d24dd8dcb88d Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 02:56:19 +0100 Subject: [PATCH 4/8] Tests for the AMD card rules (4 cards, APU, mixed architectures, Windows, --gpu, --gpus, old configs, Intel, NVIDIA unchanged); stale-stamp test stubs setup.gpus --- apps/host/tests/native-ds-cards.test.mjs | 25 +++ tools/test_setup_amd_cards.py | 266 +++++++++++++++++++++++ tools/test_setup_stale_stamp.py | 1 + 3 files changed, 292 insertions(+) create mode 100644 apps/host/tests/native-ds-cards.test.mjs create mode 100644 tools/test_setup_amd_cards.py diff --git a/apps/host/tests/native-ds-cards.test.mjs b/apps/host/tests/native-ds-cards.test.mjs new file mode 100644 index 0000000000..36d6b69053 --- /dev/null +++ b/apps/host/tests/native-ds-cards.test.mjs @@ -0,0 +1,25 @@ +/** The app must not keep the one card a DeepSeek config of setup 0.2.8 and earlier names after setup's own pick (strata_control/gpu_pick.py). */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { setupPickedOneCard } from '../server/native-control.mjs'; + +const amd = (index, extra = {}) => ({ index, vendor: 'amd', vram_gb: 32, usable: true, ...extra }); +const four = { gpus: [0, 1, 2, 3].map(i => amd(i)) }; +const old = { arch: 'deepseek41', backend: 'hip', gpu: 0, gpus_asked: true }; +const linux = process.platform !== 'win32'; + +test('setup\'s own one-card pick is not a choice (Linux, several cards)', { skip: !linux }, () => { + assert.equal(setupPickedOneCard(old, four), true); +}); +test('another card, a marker, roles, a list or another model are the person\'s', () => { + assert.equal(setupPickedOneCard({ ...old, gpu: 2 }, four), false); + assert.equal(setupPickedOneCard({ ...old, gpus_by: 'person' }, four), false); + assert.equal(setupPickedOneCard({ ...old, gpu_roles: { 0: 'main' } }, four), false); + assert.equal(setupPickedOneCard({ ...old, gpu: [0, 1] }, four), false); + assert.equal(setupPickedOneCard({ ...old, arch: 'qwen4exp' }, four), false); + assert.equal(setupPickedOneCard({ ...old, backend: 'cuda' }, four), false); +}); +test('one usable card, or an APU beside one discrete card, leaves nothing to widen', () => { + assert.equal(setupPickedOneCard(old, { gpus: [amd(0)] }), false); + assert.equal(setupPickedOneCard({ ...old, gpu: 1 }, { gpus: [amd(0, { uma: true, vram_gb: 96 }), amd(1)] }), false); +}); diff --git a/tools/test_setup_amd_cards.py b/tools/test_setup_amd_cards.py new file mode 100644 index 0000000000..57cd309fac --- /dev/null +++ b/tools/test_setup_amd_cards.py @@ -0,0 +1,266 @@ +"""DeepSeek on several AMD cards: which cards a run uses when the person named none, and who chose the cards in a saved config. + +A PC with four AMD cards used one: setup picked the first card itself, counted that as "asked", wrote "gpus_asked", and every later launch handed +the "choice" back. The cases below are the rules the fix keeps, with fake cards (nothing is read from the box the test runs on). + + python -m unittest tools.test_setup_amd_cards +""" +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import setup # noqa: E402 +import test_setup_dsv41 as D # noqa: E402 +from strata_control import dsv41_fit, gpu_pick # noqa: E402 + + +def amd(i, arch="gfx1201", vram=32.0, **kw): + return {"index": i, "name": f"AMD card {i} ({arch})", "vram_gb": vram, "arch": arch, "driver": "amdgpu", "vendor": "amd", **kw} + + +def apu(i, vram=96.0): + return amd(i, "gfx1151", vram, uma=True) + + +FOUR = [amd(i) for i in range(4)] +INTEL2 = [{"index": i, "name": "Intel Arc B580", "vram_gb": 12.0, "arch": "xe", "driver": "xe", "devid": "e20b"} for i in range(2)] + + +def ids(cards): + return [c["index"] for c in cards] + + +class Rule(unittest.TestCase): + """dsv41_fit.run_cards: the one rule `strata launch --plan`, setup and the app share.""" + + def test_four_same_cards_all_run(self): + keep, left = dsv41_fit.run_cards(FOUR, "amd", windows=False) + self.assertEqual(ids(keep), [0, 1, 2, 3]) + self.assertEqual(left, []) + + def test_an_apu_beside_a_discrete_card_is_left_out(self): + keep, left = dsv41_fit.run_cards([apu(0), amd(1)], "amd", windows=False) + self.assertEqual(ids(keep), [1]) + self.assertIn("shares the system memory", left[0]["why_ignored"]) + + def test_an_apu_alone_is_the_one_that_counts(self): + self.assertEqual(ids(dsv41_fit.run_cards([apu(0)], "amd", windows=False)[0]), [0]) + + def test_a_card_the_engine_package_has_no_code_for_is_left_out_and_said(self): + keep, left = dsv41_fit.run_cards([amd(0, "gfx1201"), amd(1, "gfx1100", 24.0)], "amd", windows=False) + self.assertEqual(ids(keep), [0]) + self.assertIn("gfx1100", left[0]["why_ignored"]) + self.assertIn("gfx1200, gfx1201", left[0]["why_ignored"]) + + def test_the_installed_package_decides_what_it_covers(self): + keep, _ = dsv41_fit.run_cards([amd(0, "gfx1201"), amd(1, "gfx1100", 24.0)], "amd", windows=False, covered=("gfx1100", "gfx1201")) + self.assertEqual(ids(keep), [0, 1]) + + def test_windows_runs_on_one_card(self): + keep, left = dsv41_fit.run_cards([amd(0), amd(1)], "amd", windows=True) + self.assertEqual(ids(keep), [0]) + self.assertIn("Windows", left[0]["why_ignored"]) + + def test_named_cards_are_used_as_named(self): + keep, left = dsv41_fit.run_cards([amd(0, "gfx1201"), amd(1, "gfx1100", 24.0)], "amd", windows=True, named=True) + self.assertEqual(ids(keep), [0, 1]) + self.assertEqual(left, []) + + def test_nvidia_cards_are_not_touched(self): + nv = [{"index": i, "name": "RTX 3090", "vram_gb": 24.0, "vendor": "nvidia", "arch": 86} for i in range(2)] + self.assertEqual(ids(dsv41_fit.run_cards(nv, "nvidia", windows=True)[0]), [0, 1]) + + def test_the_plan_and_the_options_say_what_the_run_does(self): + cases = {"four": (FOUR, False, [0, 1, 2, 3]), "apu": ([apu(0), amd(1)], False, [1]), + "mixed": ([amd(0), amd(1, "gfx1100", 24.0)], False, [0]), "windows": ([amd(0), amd(1)], True, [0])} + for name, (cards, windows, want) in cases.items(): + with mock.patch.object(dsv41_fit, "_on_windows", lambda w=windows: w): + plan = dsv41_fit.plan(cards, 251.0, None, vendor="amd", model="IST-DAS-2.25bpw") + opts = dsv41_fit.options(cards, 251.0, vendor="amd", model="IST-DAS-2.25bpw") + self.assertEqual([c["index"] for c in plan["cards"]], want, name) + self.assertEqual(opts["cards"], len(want), name) + + +class Pick(unittest.TestCase): + """strata_control/gpu_pick.py: who chose the cards in a saved config.""" + + def cfg(self, **kw): + return {"arch": "deepseek41", "backend": "hip", "gpu": 0, "gpus_asked": True, **kw} + + def test_a_config_of_setup_0_2_8_that_holds_setups_own_pick_is_not_a_choice(self): + self.assertFalse(gpu_pick.chosen_by_person(self.cfg(), FOUR)) + + def test_another_card_than_the_one_setup_would_take_was_the_persons(self): + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(gpu=2), FOUR)) + + def test_a_new_config_says_who_chose(self): + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(gpus_by="person"), FOUR)) + self.assertFalse(gpu_pick.chosen_by_person(self.cfg(gpus_by="setup"), FOUR)) + + def test_a_person_who_chose_card_0_after_the_fix_keeps_it(self): + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(gpus_by="person", gpu=0), FOUR)) + + def test_one_usable_card_is_the_only_choice(self): + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(), [amd(0)])) + + def test_card_lists_and_roles_are_the_persons(self): + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(gpu=[0, 1]), FOUR)) + self.assertTrue(gpu_pick.chosen_by_person({"gpu_roles": {"0": "main"}, "gpu": 0}, FOUR)) + + def test_other_models_and_makes_keep_what_they_had(self): + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(arch="qwen4exp"), FOUR)) + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(backend="cuda"), FOUR)) + + def test_no_choice_was_made_when_none_is_marked(self): + self.assertFalse(gpu_pick.chosen_by_person({"arch": "deepseek41", "backend": "hip", "gpu": 0}, FOUR)) + + def test_the_apu_is_not_a_card_for_the_pick(self): + usable = [c for c in FOUR[:1]] # an APU beside one discrete card: one card counts + self.assertTrue(gpu_pick.chosen_by_person(self.cfg(), usable)) + + +class Intel(unittest.TestCase): + """sycl/setup_intel.py runs setup's AMD branch with its Intel cards in the AMD list (arch "xe").""" + + def test_two_intel_cards_keep_the_one_card_setup_picked_for_deepseek(self): + with mock.patch.object(setup, "amd_problem", lambda g: None), mock.patch.object(setup, "WIN", False): + self.assertEqual(setup.dsv41_auto_cards(INTEL2, Path("nowhere")), []) # [] -> dsv41_cards falls back to the one card + + def test_a_qwen_config_of_the_intel_path_is_not_widened(self): + cfg = {"arch": "qwen4exp", "backend": "sycl", "gpu": 0, "gpus_asked": True} + self.assertTrue(gpu_pick.chosen_by_person(cfg, INTEL2)) + + +class Install(unittest.TestCase): + """setup.install_dsv41 with the Install test harness: what the config says.""" + setUp = D.Install.setUp + install = D.Install.install + + def go(self, all_cards, cards, hip=True, **kw): + named = kw.pop("named", False) + gpu = {"index": cards[0]["index"], "count": len(all_cards or cards), "vram_gb": 32.0, "name": "R9700", "cards": cards, "arch": "gfx1201"} + self.exe.parent.mkdir(parents=True, exist_ok=True) + self.exe.write_text("x") + a = D.args(models_dir=str(self.root / "models"), model="UD-Q8_K_XL", vision="no", **kw) + a._cards_named = named + rc, out = D.run(setup.install_dsv41, a, "deepseek41", gpu, hip, [], 13, [], 8080, 251.0, None, all_cards) + self.assertEqual(rc, 0, out) + return out + + def test_nothing_asked_uses_every_card_and_is_not_marked_asked(self): + out = self.go(FOUR, [FOUR[0]]) + self.assertEqual(self.cfg["gpu"], [0, 1, 2, 3]) + self.assertNotIn("gpus_asked", self.cfg) + self.assertEqual(self.cfg["gpus_by"], "setup") + self.assertIn("4 cards", out) + + def test_gpu_0_is_one_card_and_remembered_as_the_persons(self): + self.go(None, [FOUR[0]], gpu=0, named=True) + self.assertEqual(self.cfg["gpu"], 0) + self.assertTrue(self.cfg["gpus_asked"]) + self.assertEqual(self.cfg["gpus_by"], "person") + + def test_gpus_0_1_are_those_two_cards(self): + self.go(None, FOUR[:2], gpus="0,1", named=True) + self.assertEqual(self.cfg["gpu"], [0, 1]) + self.assertTrue(self.cfg["gpus_asked"]) + self.assertEqual(self.cfg["gpus_by"], "person") + + def test_a_windows_pc_runs_on_one_card_and_writes_no_card_choice(self): + self.go(None, [FOUR[0]]) + self.assertNotIn("gpu", self.cfg) + self.assertNotIn("gpus_asked", self.cfg) + + def test_nvidia_is_written_as_before(self): + nv = [{"index": i, "name": "RTX 3090", "vram_gb": 24.0, "vendor": "nvidia", "arch": 86} for i in range(2)] + with mock.patch.object(setup, "dsv41_engine_pending", lambda *a, **k: False): + self.go(nv, nv[:1], hip=False) + self.assertEqual(self.cfg["gpu"], [0, 1]) + self.assertTrue(self.cfg["gpus_asked"]) + self.assertNotIn("gpus_by", self.cfg) + + +class Widen(unittest.TestCase): + """An installed config of setup 0.2.8 and earlier, at the start.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.path = Path(self.tmp.name) / "strata-deepseek-v4.1-flash-ist-das-2.25bpw.json" + self.args = ["--pack", "/p/pack", "--eos", "1"] + for p in (mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "amd_problem", lambda g: None), + mock.patch.object(setup, "ok", lambda *a, **k: None), mock.patch.object(setup, "warn", lambda *a, **k: None), + mock.patch.object(setup, "say", lambda *a, **k: None), mock.patch.object(setup, "ROOT", Path(self.tmp.name))): + p.start() + self.addCleanup(p.stop) + + def widen(self, cfg, cards=FOUR): + full = {"exe": "/e/strata-dsv41", "args": self.args, "arch": "deepseek41", "backend": "hip", **cfg} + self.path.write_text(json.dumps(full)) + return setup.widen_setups_one_card(self.path, full, cards), json.loads(self.path.read_text()) + + def test_an_old_config_by_accident_moves_to_every_card_and_keeps_its_pack(self): + new, saved = self.widen({"gpu": 0, "gpus_asked": True}) + self.assertEqual(saved["gpu"], [0, 1, 2, 3]) + self.assertEqual(new["gpu"], [0, 1, 2, 3]) + self.assertNotIn("gpus_asked", saved) + self.assertEqual(saved["gpus_by"], "setup") + self.assertEqual(saved["args"], self.args) # the pack and the files are not touched + + def test_a_second_start_stays_on_every_card(self): + _, saved = self.widen({"gpu": 0, "gpus_asked": True}) + again, saved2 = self.widen(saved) + self.assertEqual(saved2["gpu"], [0, 1, 2, 3]) + + def test_an_old_config_by_choice_of_another_card_stays(self): + new, saved = self.widen({"gpu": 2, "gpus_asked": True}) + self.assertEqual(saved["gpu"], 2) + + def test_a_choice_made_after_the_fix_stays_even_on_card_0(self): + _, saved = self.widen({"gpu": 0, "gpus_asked": True, "gpus_by": "person"}) + self.assertEqual(saved["gpu"], 0) + + def test_windows_stays_on_one_card(self): + with mock.patch.object(setup, "WIN", True): + _, saved = self.widen({"gpu": 0, "gpus_asked": True}) + self.assertEqual(saved["gpu"], 0) + + def test_one_usable_card_has_nothing_to_widen(self): + _, saved = self.widen({"gpu": 0, "gpus_asked": True}, [amd(0)]) + self.assertEqual(saved["gpu"], 0) + + def test_an_apu_beside_a_discrete_card_is_not_added(self): + _, saved = self.widen({"gpu": 1, "gpus_asked": True}, [apu(0), amd(1)]) + self.assertEqual(saved["gpu"], 1) + + def test_a_qwen_config_is_not_widened(self): + _, saved = self.widen({"gpu": 0, "gpus_asked": True, "arch": "qwen4exp"}) + self.assertEqual(saved["gpu"], 0) + + def test_mixed_architectures_widen_only_to_the_cards_the_package_runs(self): + _, saved = self.widen({"gpu": 0, "gpus_asked": True}, [amd(0), amd(1, "gfx1100", 24.0), amd(2)]) + self.assertEqual(saved["gpu"], [0, 2]) + + +class Launcher(unittest.TestCase): + def test_installed_cards_skips_setups_own_pick_and_keeps_a_choice(self): + from strata_cli.launch.runner import installed_cards + base = {"arch": "deepseek41", "backend": "hip", "gpu": 0, "gpus_asked": True} + usable = FOUR + self.assertIsNone(installed_cards(base, usable)) + self.assertEqual(installed_cards({**base, "gpu": 2}, usable), [2]) + self.assertEqual(installed_cards({**base, "gpus_by": "person"}, usable), [0]) + self.assertEqual(installed_cards({**base, "gpu": [0, 1]}, usable), [0, 1]) + self.assertEqual(installed_cards(base, None), [0]) # no card list: as before + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/test_setup_stale_stamp.py b/tools/test_setup_stale_stamp.py index a7c98d797b..0b8cb116b2 100644 --- a/tools/test_setup_stale_stamp.py +++ b/tools/test_setup_stale_stamp.py @@ -73,6 +73,7 @@ class BuildEngineStamp(unittest.TestCase): mock.patch.object(setup, "cpu_floor", lambda avx2: ""), mock.patch.object(setup, "cpu_info", lambda: ("cpu", True)), mock.patch.object(setup, "cmake_build", self.fake_build), + mock.patch.object(setup, "gpus", lambda: []), # no real card of the box the test runs on (#4662: the build also covers every other card) mock.patch.object(setup, "say", lambda *a, **k: None), mock.patch.object(setup, "ok", lambda *a, **k: None)] for p in patches: From e4031fc4d01f232568023fbc250d9bfc8c3f8265 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 03:05:41 +0100 Subject: [PATCH 5/8] AMD cards fix, review round: setup's pinned one-card pick is still written (with gpus_by), only DeepSeek on AMD is judged when a copy adopts an earlier card, the launcher uses the plan's card rule and remembers a named card, Windows uses setup's amd_rank and no Linux arch list, message names strata launch --gpu --- setup.py | 53 ++++++---- strata_cli/launch/runner.py | 12 +++ strata_control/dsv41_fit.py | 26 ++--- strata_control/gpu_pick.py | 33 +++++-- tools/test_setup_amd_cards.py | 175 ++++++++++++++++++++++++++++++++-- 5 files changed, 255 insertions(+), 44 deletions(-) diff --git a/setup.py b/setup.py index fd839d116b..6b60dd1e3d 100644 --- a/setup.py +++ b/setup.py @@ -7096,7 +7096,7 @@ def widen_setups_one_card(cfg_path: Path, cfg: dict, amd: list) -> dict: new = gpu_pick.widened(cfg, cards) write_config(cfg_path, new) ok(f"DeepSeek now uses all {len(cards)} of your AMD cards (it was set up on GPU {was} alone by an earlier Strata). Nothing is rebuilt. " - f"To keep it on one card: ./setup.sh --gpu {was}") + f"To keep it on one card: strata launch --gpu {was} (it is remembered from then on)") return new except Exception as e: # noqa: BLE001 - never stop a start over this warn(f"could not check which cards this model should use ({e})") @@ -7164,6 +7164,12 @@ def _start(cfg_path: Path, port: int | None, gpu: int | list | None = None, open gpu = None elif gpu is not None: cmd += ["--gpu", str(gpu)] + if not isinstance(gpu, list): # a DeepSeek model on AMD keeps a card the person names (the others: this start only) + from strata_control import gpu_pick + saved = gpu_pick.remember(cfg_path, [gpu]) + if saved is not None: + cfg = saved + ok(f"saved for this model: it runs on GPU {gpu} from now on") else: cfg = widen_setups_one_card(cfg_path, cfg, amd) # a DeepSeek config from setup 0.2.8 and earlier: setup's own one-card pick found = [] @@ -8413,6 +8419,20 @@ def dsv41_smoke(exe: Path, pack: Path, lib_dirs, gpus=None, timeout: int = 5400) return r.returncode == 0, text[-1500:].encode(enc, "replace").decode(enc, "replace") +def earlier_card_kept(prev: Path) -> bool: + """A new copy of Strata set up like an earlier install carries over the card that install was set to. A card setup picked itself on a + DeepSeek model on AMD (strata_control/gpu_pick.py) is not a choice to carry over; every other config keeps its card exactly as before + (no AMD listing is read for them, and nothing here can stop a setup).""" + try: + earlier = json.loads(Path(prev).read_text(encoding="utf-8-sig")) + from strata_control import gpu_pick + if WIN or not gpu_pick.is_deepseek_amd(earlier): + return True + return gpu_pick.chosen_by_person(earlier, amd_usable_cards(amd_gpus())) + except Exception: # noqa: BLE001 - an unreadable file or listing: keep the card, as before + return True + + def cards_named(a, hip: bool = False) -> bool: """Did the person name the cards (--gpu / --gpus)? On AMD setup's own pick is written into a.gpu further on (other steps rely on it), so the AMD branch records the answer first (a._cards_named); NVIDIA keeps its way (choose_gpus sets a.gpu to the cards in use).""" @@ -8426,9 +8446,9 @@ def amd_usable_cards(amd) -> list: return gpu_fit.usable_cards([{**g, "vendor": "amd", "usable": amd_problem(g) is None} for g in amd])[0] -def dsv41_covered_archs(eng) -> tuple: - """The AMD architectures the installed DeepSeek engine package holds code for (its manifest), else what the release's package is built for.""" - from strata_control import dsv41_fit +def dsv41_covered_archs(eng): + """The AMD architectures the installed DeepSeek engine package holds code for (its manifest); None when it names none (no package yet, or one + without a list): the caller then uses the release's own rule (dsv41_fit.run_cards) and says nothing about a card it cannot know.""" try: from strata_control import engine_component as ec exe = dsv41_exe(Path(eng)) @@ -8436,9 +8456,9 @@ def dsv41_covered_archs(eng) -> tuple: archs = ec.read_manifest(exe.parent).hip_archs if archs: return tuple(archs) - except Exception: # noqa: BLE001 - the release's list is the fallback + except Exception: # noqa: BLE001 - no list: None pass - return tuple(dsv41_fit.DSV41_HIP_ARCHS) + return None def dsv41_auto_cards(amd, eng) -> list: @@ -8609,7 +8629,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, lib_dirs = [*lib_dirs, *dsv41_engine.lib_dirs(exe)] # its own package, and the rocm/bin an AMD package keeps the ROCm DLLs in if hip and exe is not None and named: # cards the person named that this package holds no code for: said, never refused covered = dsv41_covered_archs(eng) - for c in cards: + for c in cards if covered else []: if c.get("arch") and c["arch"] not in covered: warn(f"GPU {c['index']} ({c['name']}, {c['arch']}): this DeepSeek engine package holds code for {', '.join(covered)} only, so it may " "not start on that card. Leave it out (--gpus ...) to be sure.") @@ -8694,7 +8714,7 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, warn("the 16-word test run was skipped (STRATA_DSV41_NO_SMOKE=1)") else: say(" Testing the model with a short question (a few minutes: the engine reads the first experts from the disk) ...") - good, why = dsv41_smoke(exe, pack, lib_dirs, [c["index"] for c in cards] if (named or (hip and len(cards) > 1)) else None) + good, why = dsv41_smoke(exe, pack, lib_dirs, [c["index"] for c in cards] if (a.gpu is not None or a.gpus or (hip and len(cards) > 1)) else None) if not good: fail("the model does not answer sensibly after the preparation: " + (why.splitlines()[-1] if why else "no answer"), f"delete {pack} and run setup again so the pack is built fresh; if the test fails again, " @@ -8731,14 +8751,11 @@ def install_dsv41(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopted, if mac: cfg["backend"] = "metal" idx = [c["index"] for c in cards] - if len(idx) > 1 or named: + if len(idx) > 1 or a.gpu is not None or a.gpus: # (a.gpu is also setup's own pick: one card pinned when several devices are in the PC) cfg["gpu"] = idx if len(idx) > 1 else idx[0] - if hip: # who chose them (strata_control/gpu_pick.py): setup's own pick is not "asked" + cfg["gpus_asked"] = True + if hip: # who chose them (strata_control/gpu_pick.py): the person, or setup itself cfg["gpus_by"] = "person" if named else "setup" - if named: - cfg["gpus_asked"] = True - else: - cfg["gpus_asked"] = True if a.host: cfg["host"] = a.host if a.api_key: @@ -9281,13 +9298,7 @@ def main() -> int: a.gpus = a.gpus or ",".join(str(g) for g in ch["gpu"]) a.layer_split = a.layer_split or ch.get("layer_split") else: - try: # a card setup picked itself is not a choice to carry over (strata_control/gpu_pick.py) - from strata_control import gpu_pick - earlier = json.loads(prev.read_text(encoding="utf-8-sig")) - keep_card = gpu_pick.chosen_by_person(earlier, amd_usable_cards(amd_gpus())) - except (OSError, ValueError): - keep_card = True - if keep_card: + if earlier_card_kept(prev): a.gpu = a.gpu if a.gpu is not None else ch.get("gpu") a.yes = True global GPU_PICK, OLD_GPUS diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 0209c69085..bd6d29e550 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -403,6 +403,15 @@ def cards_for_launch(s: S.LaunchSettings, catalog, ram_gb: float | None = None, if len(comp.usable_gpus) < 2: return None cards = gpu_roles.rows(comp.gpus, comp.engine_vendor) + if comp.engine_vendor == "amd" and ((isinstance(base, dict) and base.get("arch") == "deepseek41") + or getattr(s, "family", None) == "deepseek41"): + # DeepSeek on AMD: the cards setup and `--plan` use (strata_control/dsv41_fit.run_cards): one card on Windows, only cards the engine + # package runs, no integrated chip beside a card with memory of its own + from strata_control import dsv41_fit + ids = [int(c["index"]) for c in dsv41_fit.run_cards(comp.usable_gpus, comp.engine_vendor)[0]] + if len(ids) < 2: + return ids or None # pinned to that card, exactly as setup pins it + cards = [c for c in cards if int(c.get("index", 0)) in ids] rec = gpu_roles.recommend(cards, comp.engine_vendor)["roles"] return gpu_roles.order(rec, cards) or None except Exception: # noqa: BLE001 - never block a launch over the choice of cards @@ -1431,6 +1440,9 @@ class Runner: base = read_config(base_path) cfg = derive_config(base, self.s, bool_flags=tune_knobs.BOOL_FLAGS, log=str(launch_dir() / f"{self.name}.engine.log"), gpus=cards_for_launch(self.s, self.catalog, base=base)) + if self.s.gpus and not self.s.gpu_roles: # a DeepSeek model on AMD keeps the card the person names from now on (strata_control/gpu_pick.py) + from strata_control import gpu_pick + gpu_pick.remember(base_path, [int(g) for g in self.s.gpus]) self.apply_four_card(cfg) self.use_own_dsv41_engine(cfg) apply_experts(cfg, self.experts_flag(cfg.get("exe"))) # after the engine is settled: only a 0.1.50+ engine is given --experts diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index 7f78b20bb9..3486cef232 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -19,12 +19,11 @@ setup.py, tools/strata_mcp.py and strata_cli/launch import it. Recommend, never from __future__ import annotations +import os import platform import sys from typing import Any -import os - from strata_control import gpu_fit GB = 1e9 @@ -133,15 +132,20 @@ def run_cards(cards: list[dict] | None, vendor: str | None = None, *, windows: b ignored = list(ignored) + [{**c, "why_ignored": f"only {float(c.get('vram_gb') or 0):.0f} GB of graphics memory"} for c in small] amd = not named and bool(keep) and all(str(c.get("vendor") or vendor or "").lower() == "amd" for c in keep) if amd: - archs = tuple(covered if covered is not None else DSV41_HIP_ARCHS) - known = [c for c in keep if c.get("arch")] - ok = [c for c in keep if not c.get("arch") or c["arch"] in archs] - if known and ok and len(ok) < len(keep): - ignored += [{**c, "why_ignored": f"the DeepSeek engine has no code for {c['arch']} (it runs on {', '.join(archs)})"} - for c in keep if c not in ok] - keep = ok - if (_on_windows() if windows is None else windows) and len(keep) > 1: - first = min(keep, key=lambda c: (-round(float(c.get("vram_gb") or 0)), c.get("index", 0))) + win = _on_windows() if windows is None else windows + # the list of architectures: the package's own (`covered`), else the Linux package's (gfx1200, gfx1201). Windows ships a different + # DeepSeek package (hip-rdna3), so without a list of its own nothing is filtered there. + archs = tuple(covered) if covered else (() if win else DSV41_HIP_ARCHS) + if archs: + known = [c for c in keep if c.get("arch")] + ok = [c for c in keep if not c.get("arch") or c["arch"] in archs] + if known and ok and len(ok) < len(keep): + ignored += [{**c, "why_ignored": f"the DeepSeek engine has no code for {c['arch']} (it runs on {', '.join(archs)})"} + for c in keep if c not in ok] + keep = ok + if win and len(keep) > 1: + # the card setup takes (setup.py amd_rank): a card with memory of its own before an APU, then the most memory, then the lower number + first = min(keep, key=lambda c: (bool(c.get("uma") or c.get("integrated")), -round(float(c.get("vram_gb") or 0)), c.get("index", 0))) ignored += [{**c, "why_ignored": "on Windows a model runs on one AMD card"} for c in keep if c is not first] keep = [first] keep = sorted(keep, key=lambda c: c.get("index", 0)) diff --git a/strata_control/gpu_pick.py b/strata_control/gpu_pick.py index 3681a907ad..0aa36d6490 100644 --- a/strata_control/gpu_pick.py +++ b/strata_control/gpu_pick.py @@ -12,8 +12,6 @@ on one). New configs say who chose in "gpus_by" ("person" or "setup"). A confi """ from __future__ import annotations -from typing import Any - ASKED_BY_PERSON = "person" PICKED_BY_SETUP = "setup" @@ -65,14 +63,37 @@ def looks_like_setups_pick(cfg: dict, usable: list[dict] | None) -> bool: def widened(cfg: dict, cards: list[int]) -> dict: - """`cfg` with setup's own pick of `cards` (two or more): card list, no 'asked' mark, and the marker that setup chose them.""" + """`cfg` with setup's own pick of `cards` (two or more): the card list and the marker that setup chose them; nothing else changes.""" out = dict(cfg) out["gpu"] = list(cards) if len(cards) > 1 else cards[0] - out.pop("gpus_asked", None) + out["gpus_asked"] = True # as setup writes it for every card list; "gpus_by" says who chose out["gpus_by"] = PICKED_BY_SETUP out.pop("hip_ordinal", None) return out -def describe(cfg: dict, usable: list[dict] | None) -> dict[str, Any]: - return {"by_person": chosen_by_person(cfg, usable), "legacy": not cfg.get("gpus_by") and bool(cfg.get("gpus_asked"))} +def is_deepseek_amd(cfg: dict | None) -> bool: + return isinstance(cfg, dict) and _is_deepseek_amd(cfg) + + +def remember(path, cards: list[int]) -> dict | None: + """The person named `cards` for a DeepSeek model on AMD (`strata launch --gpu N`, `--gpus ...`, `setup --gpu N`): saved in the installed + config as theirs, so no later start widens or moves it. Returns the new config, or None when the file is not a DeepSeek AMD config + (everything else keeps its own rules) or cannot be written. Nothing else in the file changes.""" + import json + import os + from pathlib import Path + p = Path(path) + try: + cfg = json.loads(p.read_text(encoding="utf-8-sig")) + if not _is_deepseek_amd(cfg) or not cards: + return None + cfg["gpu"] = list(cards) if len(cards) > 1 else int(cards[0]) + cfg["gpus_asked"] = True + cfg["gpus_by"] = ASKED_BY_PERSON + tmp = p.with_name(p.name + ".tmp") + tmp.write_text(json.dumps(cfg, indent=1), encoding="utf-8") + os.replace(tmp, p) + return cfg + except (OSError, ValueError, TypeError): + return None diff --git a/tools/test_setup_amd_cards.py b/tools/test_setup_amd_cards.py index 57cd309fac..c78f724d37 100644 --- a/tools/test_setup_amd_cards.py +++ b/tools/test_setup_amd_cards.py @@ -19,6 +19,7 @@ sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "tools")) import setup # noqa: E402 import test_setup_dsv41 as D # noqa: E402 +import serve.server as server # noqa: E402 from strata_control import dsv41_fit, gpu_pick # noqa: E402 @@ -74,6 +75,35 @@ class Rule(unittest.TestCase): self.assertEqual(ids(keep), [0, 1]) self.assertEqual(left, []) + def test_windows_rx_7900_and_rx_9070_run_on_the_card_setup_takes_and_nothing_is_dropped_by_arch(self): + cards = [amd(0, "gfx1201", 16.0), amd(1, "gfx1100", 24.0)] + keep, left = dsv41_fit.run_cards(cards, "amd", windows=True) + self.assertEqual(ids(keep), [1]) # discrete, then the most memory: setup's amd_rank + self.assertEqual([c["index"] for c in left], [0]) + self.assertIn("Windows", left[0]["why_ignored"]) + self.assertNotIn("no code", left[0]["why_ignored"]) # Windows ships another package: the Linux list is not applied + with mock.patch.object(setup, "amd_problem", lambda g: None), mock.patch.object(setup, "WIN", True): + self.assertEqual(ids(setup.dsv41_auto_cards(cards, Path("nowhere"))), [1]) + self.assertEqual(min(cards, key=setup.amd_rank)["index"], 1) # what setup pins as a.gpu + + def test_windows_prefers_a_discrete_card_to_an_apu(self): + keep, _ = dsv41_fit.run_cards([apu(0), amd(1, "gfx1100", 24.0), amd(2, "gfx1100", 24.0)], "amd", windows=True) + self.assertEqual(ids(keep), [1]) + + def test_no_manifest_list_means_no_code_warning_for_a_named_card(self): + self.assertIsNone(setup.dsv41_covered_archs(Path("nowhere"))) + + def test_nvidia_small_cards_are_said_as_before_and_options_single_is_the_largest(self): + nv = [{"index": 0, "name": "RTX 3060", "vram_gb": 12.0, "vendor": "nvidia", "arch": 86}, + {"index": 1, "name": "RTX 3090", "vram_gb": 24.0, "vendor": "nvidia", "arch": 86}, + {"index": 2, "name": "GT 1030", "vram_gb": 2.0, "vendor": "nvidia", "arch": 61}] + keep, left = dsv41_fit.run_cards(nv, "nvidia", windows=True) + self.assertEqual(ids(keep), [0, 1]) + self.assertEqual([c["index"] for c in left], [2]) # only the truth: 2 GB (usable_cards says it already) + opts = dsv41_fit.options(nv, 128.0, vendor="nvidia", model="IST-DAS-2.25bpw") + single = next(o for o in opts["options"] if o["key"] == "single") + self.assertEqual(single["cards"], [1]) + def test_nvidia_cards_are_not_touched(self): nv = [{"index": i, "name": "RTX 3090", "vram_gb": 24.0, "vendor": "nvidia", "arch": 86} for i in range(2)] self.assertEqual(ids(dsv41_fit.run_cards(nv, "nvidia", windows=True)[0]), [0, 1]) @@ -144,8 +174,10 @@ class Install(unittest.TestCase): setUp = D.Install.setUp install = D.Install.install - def go(self, all_cards, cards, hip=True, **kw): + def go(self, all_cards, cards, hip=True, pick=None, **kw): named = kw.pop("named", False) + if pick is not None: # setup's own pick, written into a.gpu by the AMD branch (more than one device) + kw["gpu"] = pick gpu = {"index": cards[0]["index"], "count": len(all_cards or cards), "vram_gb": 32.0, "name": "R9700", "cards": cards, "arch": "gfx1201"} self.exe.parent.mkdir(parents=True, exist_ok=True) self.exe.write_text("x") @@ -155,12 +187,13 @@ class Install(unittest.TestCase): self.assertEqual(rc, 0, out) return out - def test_nothing_asked_uses_every_card_and_is_not_marked_asked(self): + def test_nothing_asked_uses_every_card_and_says_setup_chose_them(self): out = self.go(FOUR, [FOUR[0]]) self.assertEqual(self.cfg["gpu"], [0, 1, 2, 3]) - self.assertNotIn("gpus_asked", self.cfg) + self.assertTrue(self.cfg["gpus_asked"]) # as setup always wrote it for a card list; gpus_by says who chose self.assertEqual(self.cfg["gpus_by"], "setup") self.assertIn("4 cards", out) + self.assertEqual(server.child_env({**self.cfg})["HIP_VISIBLE_DEVICES"], "0,1,2,3") def test_gpu_0_is_one_card_and_remembered_as_the_persons(self): self.go(None, [FOUR[0]], gpu=0, named=True) @@ -174,10 +207,31 @@ class Install(unittest.TestCase): self.assertTrue(self.cfg["gpus_asked"]) self.assertEqual(self.cfg["gpus_by"], "person") - def test_a_windows_pc_runs_on_one_card_and_writes_no_card_choice(self): + def test_windows_with_two_cards_pins_the_one_card_and_the_engine_sees_only_it(self): + self.go(None, [FOUR[0]], pick=0) + self.assertEqual(self.cfg["gpu"], 0) + self.assertTrue(self.cfg["gpus_asked"]) + self.assertEqual(self.cfg["gpus_by"], "setup") + self.assertEqual(server.child_env({**self.cfg})["HIP_VISIBLE_DEVICES"], "0") + + def test_an_apu_beside_a_discrete_card_not_at_index_0_pins_the_discrete_card(self): + discrete = amd(1) + self.go([discrete], [discrete], pick=1) + self.assertEqual(self.cfg["gpu"], 1) + self.assertTrue(self.cfg["gpus_asked"]) + self.assertEqual(self.cfg["gpus_by"], "setup") + self.assertEqual(server.child_env({**self.cfg})["HIP_VISIBLE_DEVICES"], "1") + + def test_two_mixed_cards_pin_the_one_the_package_runs_even_when_setup_picked_the_other(self): + covered = amd(0, "gfx1201", 16.0) + self.go([covered], [covered], pick=1) # setup's own pick (more memory) was the gfx1100 card + self.assertEqual(self.cfg["gpu"], 0) + self.assertEqual(self.cfg["gpus_by"], "setup") + self.assertEqual(server.child_env({**self.cfg})["HIP_VISIBLE_DEVICES"], "0") + + def test_one_card_in_the_pc_writes_no_card_choice(self): self.go(None, [FOUR[0]]) self.assertNotIn("gpu", self.cfg) - self.assertNotIn("gpus_asked", self.cfg) def test_nvidia_is_written_as_before(self): nv = [{"index": i, "name": "RTX 3090", "vram_gb": 24.0, "vendor": "nvidia", "arch": 86} for i in range(2)] @@ -211,7 +265,7 @@ class Widen(unittest.TestCase): new, saved = self.widen({"gpu": 0, "gpus_asked": True}) self.assertEqual(saved["gpu"], [0, 1, 2, 3]) self.assertEqual(new["gpu"], [0, 1, 2, 3]) - self.assertNotIn("gpus_asked", saved) + self.assertTrue(saved["gpus_asked"]) # as for every card list; "gpus_by" says setup chose them self.assertEqual(saved["gpus_by"], "setup") self.assertEqual(saved["args"], self.args) # the pack and the files are not touched @@ -250,6 +304,115 @@ class Widen(unittest.TestCase): self.assertEqual(saved["gpu"], [0, 2]) +class Adoption(unittest.TestCase): + """A new copy set up like an earlier install: only a DeepSeek-on-AMD config of setup's own pick loses its card.""" + + def kept(self, cfg, listing=None, win=False): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "strata-x.json" + path.write_text(json.dumps(cfg)) + with mock.patch.object(setup, "WIN", win), mock.patch.object(setup, "amd_problem", lambda g: None), \ + mock.patch.object(setup, "amd_gpus", listing or (lambda: FOUR)): + return setup.earlier_card_kept(path) + + def test_nvidia_and_qwen_configs_keep_their_card_whatever_marks_they_have(self): + def boom(): + raise AssertionError("the AMD listing must not be read for another model or make") + self.assertTrue(self.kept({"arch": "qwen4exp", "backend": "cuda", "gpu": 1}, boom)) + self.assertTrue(self.kept({"arch": "qwen4exp", "backend": "hip", "gpu": 1, "gpus_asked": True}, boom)) + self.assertTrue(self.kept({"arch": "deepseek41", "backend": "cuda", "gpu": 1}, boom)) + + def test_deepseek_on_amd_by_setups_own_pick_is_not_carried_over(self): + self.assertFalse(self.kept({"arch": "deepseek41", "backend": "hip", "gpu": 0, "gpus_asked": True})) + + def test_deepseek_on_amd_by_the_person_is_carried_over(self): + self.assertTrue(self.kept({"arch": "deepseek41", "backend": "hip", "gpu": 2, "gpus_asked": True})) + self.assertTrue(self.kept({"arch": "deepseek41", "backend": "hip", "gpu": 0, "gpus_asked": True, "gpus_by": "person"})) + + def test_a_listing_that_fails_or_windows_cannot_stop_a_setup(self): + def boom(): + raise OSError("no kfd") + self.assertTrue(self.kept({"arch": "deepseek41", "backend": "hip", "gpu": 0, "gpus_asked": True}, boom)) + self.assertTrue(self.kept({"arch": "deepseek41", "backend": "hip", "gpu": 0, "gpus_asked": True}, win=True)) + self.assertTrue(setup.earlier_card_kept(Path("does-not-exist.json"))) + + +class Remember(unittest.TestCase): + """`strata launch --gpu N` / `setup --gpu N` on a DeepSeek AMD model is the person's choice from then on.""" + + def test_the_choice_is_saved_and_then_kept_by_every_later_launch(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "strata-ds.json" + old = {"arch": "deepseek41", "backend": "hip", "gpu": 0, "gpus_asked": True, "args": ["--pack", "/p"]} + path.write_text(json.dumps(old)) + self.assertIsNotNone(gpu_pick.remember(path, [0])) + saved = json.loads(path.read_text()) + self.assertEqual((saved["gpu"], saved["gpus_by"], saved["args"]), (0, "person", ["--pack", "/p"])) + from strata_cli.launch.runner import installed_cards + self.assertEqual(installed_cards(saved, FOUR), [0]) # a person's card 0 is not widened again + self.assertFalse(Path(str(path) + ".tmp").exists()) + + def test_other_configs_are_left_alone(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "strata-q.json" + path.write_text(json.dumps({"arch": "qwen4exp", "backend": "hip", "gpu": 0})) + self.assertIsNone(gpu_pick.remember(path, [1])) + self.assertEqual(json.loads(path.read_text())["gpu"], 0) + self.assertIsNone(gpu_pick.remember(Path(d) / "missing.json", [1])) + + +class LauncherCards(unittest.TestCase): + """cards_for_launch: what the launcher puts on the engine matches what setup and the plan say.""" + + class Comp: + def __init__(self, gpus): + self.gpus, self.engine_vendor = gpus, "amd" + + @property + def usable_gpus(self): + from strata_control import gpu_fit + return gpu_fit.usable_cards([{**g, "usable": True} for g in self.gpus])[0] + + class Cat: + def __init__(self, gpus): + self.comp = LauncherCards.Comp(gpus) + + def computer(self): + return self.comp + + def cards(self, gpus, base, windows=False, gpus_named=None): + from strata_cli.launch import runner + from strata_cli.launch import settings as S + s = S.LaunchSettings(family="deepseek41", gpus=gpus_named) + with mock.patch.object(dsv41_fit, "_on_windows", lambda: windows): + return runner.cards_for_launch(s, self.Cat(gpus), base=base) + + def base(self, **kw): + return {"arch": "deepseek41", "backend": "hip", **kw} + + def test_nothing_named_on_linux_uses_every_card_in_roles_order(self): + self.assertEqual(sorted(self.cards(FOUR, self.base())), [0, 1, 2, 3]) + + def test_an_old_config_of_setups_own_pick_is_widened_for_this_launch(self): + self.assertEqual(sorted(self.cards(FOUR, self.base(gpu=0, gpus_asked=True))), [0, 1, 2, 3]) + + def test_a_card_the_person_named_is_kept(self): + self.assertIsNone(self.cards(FOUR, self.base(gpu=2, gpus_asked=True))) + self.assertIsNone(self.cards(FOUR, self.base(gpu=0, gpus_asked=True, gpus_by="person"))) + + def test_gpu_0_named_on_this_launch_is_one_card(self): + self.assertEqual(self.cards(FOUR, self.base(), gpus_named=[0]), [0]) + + def test_windows_pins_the_one_card_setup_takes(self): + self.assertEqual(self.cards([amd(0), amd(1)], self.base(gpus_by="setup", gpu=0, gpus_asked=True), windows=True), [0]) + + def test_an_apu_beside_a_discrete_card_leaves_nothing_to_split(self): + self.assertIsNone(self.cards([apu(0), amd(1)], self.base(gpus_by="setup", gpu=1, gpus_asked=True))) + + def test_mixed_cards_run_on_the_ones_the_package_has_code_for(self): + self.assertEqual(self.cards([amd(0), amd(1, "gfx1100", 24.0)], self.base(gpus_by="setup", gpu=0, gpus_asked=True)), [0]) + + class Launcher(unittest.TestCase): def test_installed_cards_skips_setups_own_pick_and_keeps_a_choice(self): from strata_cli.launch.runner import installed_cards From 987ebd442fe2e02fc5ccd01a573a5723f3fde3fd Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 02:57:34 +0100 Subject: [PATCH 6/8] Launch: list the Arc Pro B65 (0xe222) and the other discrete Battlemage/Alchemist ids, so two cards are both named for a launch that names none --- strata_cli/launch/catalog.py | 11 ++-- sycl/setup_intel.py | 2 +- tests/terminal/test_intel_cards_029.py | 80 ++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 tests/terminal/test_intel_cards_029.py diff --git a/strata_cli/launch/catalog.py b/strata_cli/launch/catalog.py index cc0977e6be..e9a36e82f8 100644 --- a/strata_cli/launch/catalog.py +++ b/strata_cli/launch/catalog.py @@ -193,11 +193,14 @@ def install_root(explicit: str | os.PathLike | None = None, src: str | os.PathLi return discovery.find_install(here=installer_folder(src))[0] -# Intel Arc cards by PCI id: (name, memory in GB). The kernel does not tell an ordinary user how much memory the card has, so the common -# cards are listed; an id that is not here is shown as "Intel Arc" with no size and is treated as a small card. (A770: the 8 GB model shares -# the id of the 16 GB one, so the smaller figure is used.) +# Intel Arc cards by PCI id: (name, memory in GB). The kernel does not tell an ordinary user how much memory the card has, so the discrete +# cards are listed (the same ids as sycl/setup_intel.py; tests/terminal/test_intel_cards_029.py keeps the two in step). An id that is not +# here is NOT counted: it is skipped, because an Intel chip built into the processor shares this vendor id and must never be named as a card. +# (A770: the 8 GB model shares the id of the 16 GB one, so the smaller figure is used.) INTEL_ARC = {"0x56a1": ("Arc A750", 8.0), "0x56a2": ("Arc A580", 8.0), "0x56a0": ("Arc A770", 8.0), "0x56a5": ("Arc A380", 6.0), - "0x56a6": ("Arc A310", 4.0), "0xe20b": ("Arc B580", 12.0), "0xe20c": ("Arc B570", 10.0), "0xe223": ("Arc Pro B70", 32.0)} + "0x56a6": ("Arc A310", 4.0), "0x5690": ("Arc A770M", 16.0), "0xe20b": ("Arc B580", 12.0), "0xe20c": ("Arc B570", 10.0), + "0xe223": ("Arc Pro B70", 32.0), "0xe222": ("Arc Pro B65", 32.0), "0xe221": ("Arc Pro B60", 24.0), "0xe211": ("Arc Pro B60", 24.0), + "0xe212": ("Arc B50", 16.0)} def intel_arc_cards(root: str = "/sys/class/drm") -> list[dict]: diff --git a/sycl/setup_intel.py b/sycl/setup_intel.py index 2a0bf012d8..e89f0a2064 100644 --- a/sycl/setup_intel.py +++ b/sycl/setup_intel.py @@ -44,7 +44,7 @@ MOUNT = Path(os.environ.get("STRATA_SYCL_ROOT") or ROOT.parent) # what strata- # Battlemage / Alchemist PCI device ids -> (name, VRAM GB). lspci's database lags new cards (an Arc Pro B70 reads # "Intel Corporation Device [8086:e223]"), so the sysfs id is the reliable signal and the name table is ours. -INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e221": ("Arc Pro B60", 24.0), "e211": ("Arc Pro B60", 24.0), +INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e222": ("Arc Pro B65", 32.0), "e221": ("Arc Pro B60", 24.0), "e211": ("Arc Pro B60", 24.0), "e20b": ("Arc B580", 12.0), "e20c": ("Arc B570", 10.0), "e212": ("Arc B50", 16.0), "56a0": ("Arc A770", 16.0), "56a1": ("Arc A750", 8.0), "56a2": ("Arc A580", 8.0), diff --git a/tests/terminal/test_intel_cards_029.py b/tests/terminal/test_intel_cards_029.py new file mode 100644 index 0000000000..ad0e548e31 --- /dev/null +++ b/tests/terminal/test_intel_cards_029.py @@ -0,0 +1,80 @@ +"""Two Intel Arc Pro B65 cards (device id 0xe222): the Terminal must see both and name both for a launch that names none (fake sysfs, no hardware).""" +from __future__ import annotations + +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + +from strata_cli.launch import catalog as C, runner as R, settings as S # noqa: E402 + + +def fake_drm(root: Path, ids: list[str]) -> None: + for i, did in enumerate(ids): + dev = root / f"card{i}" / "device" + dev.mkdir(parents=True) + (dev / "vendor").write_text("0x8086\n") + (dev / "device").write_text(did + "\n") + + +class IntelCards(unittest.TestCase): + def cards(self, ids): + with tempfile.TemporaryDirectory() as d: + fake_drm(Path(d), ids) + return C.intel_arc_cards(d) + + def test_two_b65_are_two_cards_of_32_gb(self): + cards = self.cards(["0xe222", "0xe222"]) + self.assertEqual([(c["index"], c["vram_gb"]) for c in cards], [(0, 32.0), (1, 32.0)]) + self.assertTrue(all("B65" in c["name"] for c in cards)) + + def test_the_other_battlemage_ids_are_listed(self): + for did in ("0xe221", "0xe211", "0xe212", "0xe20b", "0xe223"): + self.assertEqual(len(self.cards([did])), 1, did) + + def test_an_integrated_intel_gpu_is_never_a_card(self): + for did in ("0x46a6", "0x7d55", "0xa7a0", "0x9a49", "0x4680", "0x64a0"): + self.assertEqual(self.cards([did]), [], did) + self.assertEqual(len(self.cards(["0x7d55", "0xe222"])), 1) # an iGPU beside a B65: one card + + def test_both_tables_list_the_same_discrete_ids(self): + import ast + src = (ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8") + node = next(n for n in ast.parse(src).body if isinstance(n, ast.Assign) and getattr(n.targets[0], "id", "") == "INTEL_ARC") + theirs = {"0x" + k: v[0].replace("Arc ", "") for k, v in ast.literal_eval(node.value).items()} + ours = {k: v[0].replace("Arc ", "") for k, v in C.INTEL_ARC.items()} + self.assertEqual(set(theirs), set(ours)) + self.assertEqual({k: v.replace(" ", "") for k, v in theirs.items()}, {k: v.replace(" ", "") for k, v in ours.items()}) + + def test_mixed_sizes_get_roles_like_any_other_pair(self): + cards = self.cards(["0xe222", "0xe20b"]) # 32 GB + 12 GB + hw = {"ram_gb": 128.0, "os": "Linux", "cpu": {"avx2": True}, "gpus": cards} + cat = C.Catalog(root=Path(tempfile.mkdtemp()), hardware=hw) + cat.installed_backend = lambda: "sycl" + got = R.cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_S"), cat, base={}) + self.assertEqual(sorted(got), [0, 1]) + + def test_one_card_names_nothing(self): + hw = {"ram_gb": 128.0, "os": "Linux", "cpu": {"avx2": True}, "gpus": self.cards(["0xe222"])} + cat = C.Catalog(root=Path(tempfile.mkdtemp()), hardware=hw) + cat.installed_backend = lambda: "sycl" + self.assertIsNone(R.cards_for_launch(S.LaunchSettings(family="qwen", model="IQ3_S"), cat, base={})) + + def test_a_launch_that_names_no_card_gets_both_b65(self): + hw = {"ram_gb": 128.0, "os": "Linux", "cpu": {"avx2": True}, "gpus": self.cards(["0xe222", "0xe222"])} + cat = C.Catalog(root=Path(tempfile.mkdtemp()), hardware=hw) + cat.installed_backend = lambda: "sycl" + s = S.LaunchSettings(family="qwen", model="IQ3_S") + got = R.cards_for_launch(s, cat, base={}) + self.assertEqual(sorted(got), [0, 1]) + cfg = {} + R.apply_cards(cfg, got) + self.assertEqual(sorted(cfg["gpu"]), [0, 1]) + self.assertEqual(cfg["layer_split"], "auto") + + +if __name__ == "__main__": + unittest.main() From 7aa9a584aac0f30d443cb60a8596f25b4953a6a3 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 03:10:00 +0100 Subject: [PATCH 7/8] Setup: say which card is not used when a card under 8 GB sits beside a bigger NVIDIA card (a line only, no change to the cards used) --- setup.py | 4 +++ tools/test_setup_cards_029.py | 53 +++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 tools/test_setup_cards_029.py diff --git a/setup.py b/setup.py index 6b60dd1e3d..bd59a30617 100644 --- a/setup.py +++ b/setup.py @@ -1963,6 +1963,10 @@ def choose_gpus(a, found) -> list: fail("none of your GPUs can run Strata", "it needs an NVIDIA RTX 20 series or newer (compute capability 7.5+)") can = together_ok(found) if not can: + for g in found: # said, not asked: a card that works alone but cannot share a model beside a bigger one + if g["index"] != single[0]["index"] and gpu_problem(g) is None: + say(f" GPU {g['index']} ({g['name']}, {g['vram_gb']:.0f} GB) is not used: a card that shares a model needs {SPLIT_MIN_VRAM_GB} GB or more, " + f"so the model runs on GPU {single[0]['index']} alone.") return [single[0]["index"]] return choose_roles(a, found) diff --git a/tools/test_setup_cards_029.py b/tools/test_setup_cards_029.py new file mode 100644 index 0000000000..95c8c61f0c --- /dev/null +++ b/tools/test_setup_cards_029.py @@ -0,0 +1,53 @@ +"""A card that works alone but cannot share a model (under 7.5 GB) beside a bigger NVIDIA card: setup says it is not used (a line, no question, no +change to which cards run). Fake cards through setup.main (tools/test_setup_golden.py's harness).""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from test_setup_golden import install, argv_for # noqa: E402 + + +def card(i, name, gb, arch="86"): + return {"index": i, "name": name, "vram_gb": gb, "arch": arch, "driver": "580.97"} + + +BIG = card(0, "NVIDIA GeForce RTX 4090", 24.0, "89") +SMALL = card(1, "NVIDIA GeForce RTX 2060", 5.9, "75") + + +class SmallCardSaid(unittest.TestCase): + def run_it(self, found, extra=()): + code, out, cfg, asked = install(256.0, found, argv_for("qwen", "IQ3_S") + ["--yes", *extra]) + self.assertEqual(code, 0, out) + return out, cfg, asked + + def test_the_small_card_is_named_with_the_reason(self): + out, cfg, asked = self.run_it([BIG, SMALL]) + self.assertIn("GPU 1 (NVIDIA GeForce RTX 2060, 6 GB) is not used", out) + self.assertIn("needs 8 GB or more", out) + self.assertIn("runs on GPU 0 alone", out) + self.assertEqual(asked, []) # printed only + self.assertEqual((cfg["gpu"], cfg["gpus_asked"]), (0, True)) # the cards used are what they were + + def test_the_small_card_listed_first(self): + out, cfg, _ = self.run_it([card(0, "NVIDIA GeForce RTX 2060", 5.9, "75"), card(1, "NVIDIA GeForce RTX 4090", 24.0, "89")]) + self.assertIn("GPU 0 (NVIDIA GeForce RTX 2060, 6 GB) is not used", out) + self.assertEqual(cfg["gpu"], 1) + + def test_nothing_is_said_where_nothing_is_left_out(self): + for found in ([BIG], [BIG, card(1, "NVIDIA GeForce RTX 3060", 12.0)], [BIG, card(1, "NVIDIA GeForce RTX 3070", 8.0)]): + out, _cfg, _ = self.run_it(found) + self.assertNotIn("is not used", out, found) + + def test_naming_a_card_says_nothing_extra(self): + out, cfg, _ = self.run_it([BIG, SMALL], ["--gpu", "0"]) + self.assertNotIn("is not used", out) + self.assertEqual(cfg["gpu"], 0) + + +if __name__ == "__main__": + unittest.main() From c62d5e3a15b40ea51c96aae9e8d36928965f53ab Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 31 Oct 2026 03:23:01 +0100 Subject: [PATCH 8/8] DeepSeek plan: the NVIDIA cards it counts are the ones setup runs (a card of 8 GB or less starts Off beside a bigger one), and the plan says which card is not used --- strata_control/dsv41_fit.py | 9 ++++ tests/terminal/test_dsv41_cards_nvidia_029.py | 52 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 tests/terminal/test_dsv41_cards_nvidia_029.py diff --git a/strata_control/dsv41_fit.py b/strata_control/dsv41_fit.py index 3486cef232..9e19c482e4 100644 --- a/strata_control/dsv41_fit.py +++ b/strata_control/dsv41_fit.py @@ -130,6 +130,15 @@ def run_cards(cards: list[dict] | None, vendor: str | None = None, *, windows: b small = [c for c in keep if float(c.get("vram_gb") or 0) < SMALLEST_CARD_GB] keep = [c for c in keep if float(c.get("vram_gb") or 0) >= SMALLEST_CARD_GB] ignored = list(ignored) + [{**c, "why_ignored": f"only {float(c.get('vram_gb') or 0):.0f} GB of graphics memory"} for c in small] + if not named and len(keep) > 1 and all(str(c.get("vendor") or "").lower() == "nvidia" for c in keep): + # NVIDIA: setup's role rule (gpu_roles.recommend): a card of 8 GB or less starts Off beside a bigger one, so the plan counts what the run uses + # (an AMD card of 8 GB counts in both the plan and the run) + from strata_control import gpu_roles + if any(round(float(c.get("vram_gb") or 0)) > gpu_roles.OFF_AT_OR_BELOW_GB for c in keep): + off = [c for c in keep if round(float(c.get("vram_gb") or 0)) <= gpu_roles.OFF_AT_OR_BELOW_GB] + ignored += [{**c, "why_ignored": f"a card with {gpu_roles.OFF_AT_OR_BELOW_GB:.0f} GB or less starts Off beside a bigger card (setup does the same)"} + for c in off] + keep = [c for c in keep if c not in off] amd = not named and bool(keep) and all(str(c.get("vendor") or vendor or "").lower() == "amd" for c in keep) if amd: win = _on_windows() if windows is None else windows diff --git a/tests/terminal/test_dsv41_cards_nvidia_029.py b/tests/terminal/test_dsv41_cards_nvidia_029.py new file mode 100644 index 0000000000..5b27df38ec --- /dev/null +++ b/tests/terminal/test_dsv41_cards_nvidia_029.py @@ -0,0 +1,52 @@ +"""DeepSeek's plan counts the NVIDIA cards setup runs: a card of 8 GB or less starts Off beside a bigger card (gpu_roles), and the plan says so. +Fake cards only.""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from strata_control import dsv41_fit # noqa: E402 + + +def card(i, name, gb, vendor="nvidia"): + return {"index": i, "name": name, "vram_gb": gb, "vendor": vendor, "usable": True} + + +class NvidiaPlan(unittest.TestCase): + def plan(self, cards, **kw): + return dsv41_fit.plan(cards, 128.0, None, vendor=cards[0].get("vendor"), model="IST-DAS-2.25bpw", **kw) + + def test_an_8_gb_card_beside_a_bigger_one_is_off_in_the_plan_and_said(self): + p = self.plan([card(0, "NVIDIA GeForce RTX 4090", 24.0), card(1, "NVIDIA GeForce RTX 3070", 8.0)]) + self.assertEqual([c["index"] for c in p["cards"]], [0]) + text = " ".join(p["lines"]) + self.assertIn("Not used: NVIDIA GeForce RTX 3070 (a card with 8 GB or less starts Off beside a bigger card", text) + + def test_the_card_may_be_listed_first(self): + p = self.plan([card(0, "NVIDIA GeForce RTX 3070", 8.0), card(1, "NVIDIA GeForce RTX 4090", 24.0)]) + self.assertEqual([c["index"] for c in p["cards"]], [1]) + + def test_two_8_gb_cards_and_two_bigger_cards_are_unchanged(self): + self.assertEqual([c["index"] for c in self.plan([card(0, "A", 8.0), card(1, "A", 8.0)])["cards"]], [0, 1]) + self.assertEqual([c["index"] for c in self.plan([card(0, "A", 24.0), card(1, "B", 12.0)])["cards"]], [0, 1]) + self.assertEqual([c["index"] for c in self.plan([card(i, "A", 24.0) for i in range(3)])["cards"]], [0, 1, 2]) + + def test_a_named_card_is_used_as_named(self): + p = self.plan([card(0, "A", 24.0), card(1, "B", 8.0)], named=True) + self.assertEqual([c["index"] for c in p["cards"]], [0, 1]) + + def test_an_amd_card_of_8_gb_still_counts(self): + from unittest import mock + with mock.patch.object(dsv41_fit, "_on_windows", lambda: False): # (on Windows a model runs on one AMD card) + p = self.plan([card(0, "AMD Radeon AI PRO R9700", 32.0, "amd"), card(1, "AMD Radeon RX 9060", 8.0, "amd")]) + self.assertEqual([c["index"] for c in p["cards"]], [0, 1]) + + def test_cards_with_no_make_are_left_alone(self): + cs = [{"index": 0, "name": "A", "vram_gb": 24.0}, {"index": 1, "name": "B", "vram_gb": 8.0}] + self.assertEqual([c["index"] for c in dsv41_fit.plan(cs, 128.0, None, model="IST-DAS-2.25bpw")["cards"]], [0, 1]) + + +if __name__ == "__main__": + unittest.main()