Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
setup: build CUDA only when the toolkit builds for the card (#1852)
JustVugg8dae08ae987d
diff --git a/c/coli b/c/coliindex 4b537a47..7ec5fe0f 100755--- a/c/coli+++ b/c/coli@@ -3619,7 +3619,8 @@ def main():pset.add_argument("--dir",default=None,metavar="DIR",help="folder for downloaded models (default ~/colibri-models)")pset.add_argument("--backend",choices=("auto","cpu","vulkan","cuda"),default=None,- help="engine build: auto (default) picks CUDA, then Vulkan, then the CPU")+ help="engine build: auto (default) picks CUDA when the toolkit builds for the "+ "card, then Vulkan, then the CPU, and a build that fails falls back to the next")pset.add_argument("--no-gpu",action="store_true",help="same as --backend cpu")pset.add_argument("--host",default=None,help="address to serve on (default 127.0.0.1)")pset.add_argument("--port",type=int,default=None,help="port to serve on (default 8000)")diff --git a/c/setup_flow.py b/c/setup_flow.pyindex fdb0cbee..08d4c3d9 100644--- a/c/setup_flow.py+++ b/c/setup_flow.py@@ -172,6 +172,107 @@ def _nvcc():return None+#: What each CUDA release compiles for, for an nvcc that cannot answer+#: --list-gpu-arch: (first release, oldest compute_XX, newest compute_XX).+#: From 11.4 on, the bounds are the measured `nvcc --list-gpu-arch` of NVIDIA's+#: own nvcc (the redistributable archives for 11.4.152 to 12.9.86, the+#: nvidia-cuda-nvcc wheels for 13.0.88 and 13.4.92; tests/test_setup_flow.py+#: keeps the outputs); the earlier rows are from the toolkit release notes+#: (9.0 added Volta and dropped Fermi, 10.0 Turing, 11.0 Ampere and dropped+#: sm_30/sm_32, 11.1 sm_86). The table is also what says when a card was+#: dropped and which toolkit still builds for it.+CUDA_RELEASES = (+ ((9, 0), 30, 70),+ ((10, 0), 30, 75),+ ((11, 0), 35, 80),+ ((11, 1), 35, 86),+ ((11, 4), 35, 87),+ ((11, 8), 35, 90),+ ((12, 0), 50, 90),+ ((12, 8), 50, 120),+ ((12, 9), 50, 121),+ ((13, 0), 75, 121),+)+#: nvcc takes -arch=native from 11.6 on (measured: 11.5.119 answers "Value+#: 'native' is not defined for option 'gpu-architecture'", 11.6.55 takes it).+#: Below that the build names the card's architecture itself.+CUDA_NATIVE_SINCE = (11, 6)+CUDA_ARCHIVE_URL = "https://developer.nvidia.com/cuda-toolkit-archive"+++def parse_nvcc_version(text):+ """(13, 0) from `nvcc --version` ("Cuda compilation tools, release 13.0,+ V13.0.88"); None when there is no release line."""+ match = re.search(r"\brelease (\d+)\.(\d+)", text or "")+ return (int(match.group(1)), int(match.group(2))) if match else None+++def parse_nvcc_arch_list(text):+ """The compute_XX numbers of `nvcc --list-gpu-arch`, sorted ([75, 80, ...]).+ None when it lists none: an nvcc without the option prints an error."""+ found = {int(n) for n in re.findall(r"^\s*compute_(\d+)[a-z]?\s*$", text or "", re.M)}+ return sorted(found) or None+++def cuda_toolkit(nvcc):+ """What this nvcc is and builds for: {"cuda_version": "13.0" or None,+ "cuda_archs": [75, 80, ...] or None (then the release table answers)}."""+ version = parse_nvcc_version(setup_hw._run([nvcc, "--version"], timeout=30))+ archs = parse_nvcc_arch_list(setup_hw._run([nvcc, "--list-gpu-arch"], timeout=30))+ return {"cuda_version": f"{version[0]}.{version[1]}" if version else None,+ "cuda_archs": archs}+++def _version_tuple(text):+ match = re.match(r"^\s*(\d+)\.(\d+)", str(text or ""))+ return (int(match.group(1)), int(match.group(2))) if match else None+++def _release_bounds(version):+ bounds = None+ for first, low, high in CUDA_RELEASES:+ if version >= first:+ bounds = (low, high)+ return bounds+++def toolkit_builds(tc, sm):+ """Whether this machine's CUDA toolkit compiles for compute_<sm>: True or+ False, or None when nothing says (the card or the toolkit is unknown)."""+ if sm is None:+ return None+ if tc.get("cuda_archs"):+ return sm in tc["cuda_archs"]+ version = _version_tuple(tc.get("cuda_version"))+ bounds = _release_bounds(version) if version else None+ if bounds is None:+ return None+ return bounds[0] <= sm <= bounds[1]+++def _release_name(version):+ return str(version[0]) if version[1] == 0 else f"{version[0]}.{version[1]}"+++def cuda_release_advice(sm, version=None):+ """For a card the toolkit here cannot build for: (what happened, what to+ install). ("dropped in CUDA 13", "install a CUDA 12.x toolkit") for a card+ older than the toolkit, ("needs CUDA 12.8 or newer", "install CUDA 12.8 or+ newer") for one newer than it; from CUDA_RELEASES."""+ rows = [index for index, (_first, low, high) in enumerate(CUDA_RELEASES) if low <= sm <= high]+ if not rows:+ return None, f"install a CUDA toolkit whose `nvcc --list-gpu-arch` lists compute_{sm}"+ first = CUDA_RELEASES[rows[0]][0]+ if version is not None and version < first:+ return (f"needs CUDA {first[0]}.{first[1]} or newer",+ f"install CUDA {first[0]}.{first[1]} or newer")+ if rows[-1] + 1 < len(CUDA_RELEASES):+ dropped = CUDA_RELEASES[rows[-1] + 1][0]+ return (f"dropped in CUDA {_release_name(dropped)}",+ f"install a CUDA {CUDA_RELEASES[rows[-1]][0][0]}.x toolkit")+ return None, f"install a CUDA toolkit whose `nvcc --list-gpu-arch` lists compute_{sm}"++def toolchain(here=None):"""What can be built here, and with what."""here = here or HERE@@ -205,6 +306,11 @@ def toolchain(here=None):tc["can_build"] = bool(tc["source_checkout"] and tc["make"] and tc["cc"])tc["can_build_vulkan"] = bool(tc["can_build"] and tc["glslc"] and tc["vulkan_headers"])tc["can_build_cuda"] = bool(tc["can_build"] and tc["nvcc"] and sys.platform.startswith("linux"))+ # A toolkit is not enough: CUDA 13 cannot build for a V100 (#1852).+ # choose_backend asks toolkit_builds() about each card.+ tc["cuda_version"], tc["cuda_archs"] = None, None+ if tc["nvcc"]:+ tc.update(cuda_toolkit(tc["nvcc"]))return tc@@ -291,46 +397,161 @@ def package_hint(kinds, os_info=None, platform_name=None):#: (--backend vulkan). A discrete GPU, with its own VRAM, runs Vulkan for every one.VULKAN_IGPU_MEASURED = frozenset({"qwen36", "qwen38"})+#: The engines with a CUDA path on Linux, and what their CUDA build needs, read+#: from the code (tests/test_setup_flow.py, CudaEngineTable, checks each entry+#: against the Makefiles and the sources):+#:+#: backend_cuda.o (qwen36, qwen38, colibri, kimi_k3): nvcc -std=c++17, no+#: compute floor in the code. The tensor-core kernels are guarded+#: (__CUDA_ARCH__ >= 700 on the device, compute_major >= 7 where they are+#: dispatched) and fall back below that; the engine ran on four sm_50 Tesla+#: M10 (#1652, docs/qwen36-cuda-tier.md).+#: backend_cuda_ink.o (inkling): plain bf16 GEMV kernels, no floor either.+#: backend_cuda_dsv4.o (deepseek_v4, Makefile.deepseek-v4): nvcc -std=c++20,+#: which nvcc takes from 12.0 on (measured: 11.8.89 answers "Value 'c++20'+#: is not defined for option 'std'"); NO_TC=1 below 12.8, whose cuBLASLt+#: block-scaling API the opt-in tensor-core path calls (docs/deepseek-v4.md,+#: "Linux CUDA tier"); and dsv4_cuda_backend_arch_ok turns the tier on from+#: compute 6.0, so an older card would sit idle while the CPU did the work.+#:+#: glm53 links no CUDA object (its accelerator is Metal) and the remaining+#: engines are CPU-only: none of them is here, so none of them is built with CUDA.+CUDA_ENGINES = {+ "qwen36": {"object": "backend_cuda.o"},+ "qwen38": {"object": "backend_cuda.o"},+ "glm": {"object": "backend_cuda.o"},+ "kimi": {"object": "backend_cuda.o"},+ "inkling": {"object": "backend_cuda_ink.o"},+ "deepseek_v4": {"object": "backend_cuda_dsv4.o", "min_compute": 60,+ "min_toolkit": (12, 0), "no_tc_below": (12, 8)},+}++#: How a backend is named in a sentence: "the CUDA build", "using the CPU".+BACKEND_NAME = {"cuda": "CUDA", "vulkan": "Vulkan", "cpu": "CPU"}+USING = {"cuda": "CUDA", "vulkan": "Vulkan", "cpu": "the CPU"}+++def cuda_problem(cards, family, tc):+ """Why this engine's CUDA build cannot serve these NVIDIA cards, as+ {"why": ..., "fix": ...}, or None when it can.++ Unknown is not a no: a card whose compute capability nothing reported, or+ a toolkit that did not say what it builds, passes, and a build that then+ fails falls back to the next backend (resolve_with_fallback). `fix` is+ what to install; None when no toolkit would help (the card is older than+ the engine's CUDA code runs on). With -arch=native nvcc builds for every+ card it sees and stops at the first it cannot, so every card is checked."""+ engine = CUDA_ENGINES.get(family.id, {})+ version = _version_tuple(tc.get("cuda_version"))+ floor = engine.get("min_compute")+ for card in cards:+ sm = setup_hw.compute_cap_sm(card.get("compute_cap"))+ if floor and sm is not None and sm < floor:+ return {"why": (f"{family.display_name}'s CUDA tier runs on compute "+ f"{floor // 10}.{floor % 10} and newer, and the {card['name']} "+ f"is compute {card['compute_cap']}"),+ "fix": None}+ need = engine.get("min_toolkit")+ if need and version and version < need:+ return {"why": (f"{family.display_name}'s CUDA code needs CUDA {need[0]}.{need[1]} "+ f"or newer (it is C++20), and the toolkit here is CUDA {tc['cuda_version']}"),+ "fix": f"install CUDA {need[0]}.{need[1]} or newer"}+ toolkit = f"CUDA {tc['cuda_version']}" if tc.get("cuda_version") else "CUDA"+ for card in cards:+ sm = setup_hw.compute_cap_sm(card.get("compute_cap"))+ if toolkit_builds(tc, sm) is False:+ note, fix = cuda_release_advice(sm, version)+ detail = f"compute {card['compute_cap']}" + (f", {note}" if note else "")+ return {"why": f"the {toolkit} toolkit cannot build for the {card['name']} ({detail})",+ "fix": fix}+ return None+-def choose_backend(hw, family, tc, requested="auto"):+def cuda_make_args(family, tc, cards):+ """The make variables the CUDA build of this engine needs on this toolkit:+ the card's own architecture when nvcc is too old for -arch=native (and+ CUDA_ARCH is not set by hand), NO_TC=1 where the engine needs it."""+ args = []+ version = _version_tuple(tc.get("cuda_version"))+ if version and version < CUDA_NATIVE_SINCE and not os.environ.get("CUDA_ARCH") and cards:+ sm = setup_hw.compute_cap_sm(cards[0].get("compute_cap"))+ if sm:+ args.append(f"CUDA_ARCH=sm_{sm}")+ below = CUDA_ENGINES.get(family.id, {}).get("no_tc_below")+ if below and version and version < below:+ args.append("NO_TC=1")+ return args+++def choose_backend(hw, family, tc, requested="auto", exclude=()):"""Which build to run the model with, and why.- CUDA first for an NVIDIA card when this engine has a CUDA path and the- toolkit is here (its VRAM expert tier is the measured fast path); else- Vulkan when a Vulkan GPU answered and the build has its headers and glslc;- else the CPU. On an integrated GPU, Vulkan only for the engines measured- faster there (VULKAN_IGPU_MEASURED) unless Vulkan was asked for by name.- Every GPU path the machine has but cannot build yet comes back in `missing`- with the command that would enable it."""+ CUDA first for an NVIDIA card when this engine has a CUDA path (CUDA_ENGINES)+ and the toolkit here builds for every card (cuda_problem); its VRAM expert+ tier is the measured fast path. Else Vulkan when a Vulkan GPU answered and+ the build has its headers and glslc; else the CPU. On an integrated GPU,+ Vulkan only for the engines measured faster there (VULKAN_IGPU_MEASURED)+ unless Vulkan was asked for by name. Every GPU path the machine has but+ cannot build yet comes back in `missing` with what would enable it.++ A toolkit that cannot build for the card is not a build to try: auto says+ why and takes the next backend, and an explicit --backend cuda stops here+ with the same reason instead of failing inside make. `exclude` names the+ backends whose build already failed (resolve_with_fallback)."""gpu = hw.get("gpu") or {}vk, nvidia = gpu.get("vulkan"), gpu.get("nvidia") or []decision = {"backend": "cpu", "reason": "", "missing": [], "gpu": None}if requested == "cpu":decision["reason"] = "CPU only, as requested"return decision- cuda_engine = family.supports_accelerator and host_os().startswith("linux")- if nvidia and requested in ("auto", "cuda"):+ cuda_engine = family.id in CUDA_ENGINES and host_os().startswith("linux")+ blocked = None+ if nvidia and requested in ("auto", "cuda") and "cuda" not in exclude:if cuda_engine and tc.get("can_build_cuda"):- decision.update(backend="cuda", gpu=nvidia[0]["name"],- reason=f"NVIDIA {nvidia[0]['name']} with the CUDA toolkit")- return decision- if cuda_engine:+ blocked = cuda_problem(nvidia, family, tc)+ if blocked is None:+ card = nvidia[0]+ detail = f" (compute {card['compute_cap']})" if card.get("compute_cap") else ""+ toolkit = f"CUDA {tc['cuda_version']}" if tc.get("cuda_version") else "CUDA"+ decision.update(backend="cuda", gpu=card["name"],+ reason=f"NVIDIA {card['name']}{detail} with the {toolkit} toolkit",+ make_args=cuda_make_args(family, tc, nvidia))+ return decision+ if requested == "cuda":+ instead = choose_backend(hw, family, tc, "auto", exclude=tuple(exclude) + ("cuda",))+ raise SetupError(f"{blocked['why']}: "+ + (f"{blocked['fix']} for the CUDA path, or " if blocked["fix"] else "")+ + f"run with --backend auto to use {USING[instead['backend']]}")+ if blocked["fix"]:+ decision["missing"].append(("cuda", f"{blocked['fix']} ({CUDA_ARCHIVE_URL})"))+ elif cuda_engine:needs = ["cuda"] if tc.get("can_build") else ["build", "cuda"]decision["missing"].append(("cuda", _gpu_hint(needs, hw, tc)))elif requested == "cuda" and not cuda_engine:decision["missing"].append(("cuda", f"{family.display_name} has no CUDA path here; ""Vulkan or the CPU run it"))++ def because(using, otherwise):+ """The reason, led by why CUDA was passed over when it was."""+ if blocked is None:+ return otherwise+ text = f"{blocked['why']}: using {using}"+ if blocked["fix"]:+ text += f"; {blocked['fix']} for the CUDA path"+ return text+if (vk and vk.get("type") == "integrated" and requested in ("auto", "cuda")and family.id not in VULKAN_IGPU_MEASURED):- decision["reason"] = (f"{vk['name']} is an integrated GPU, which shares the CPU's RAM, "- f"and {family.display_name} was not measured faster on one: "- "the engine runs on the CPU (--backend vulkan uses the GPU anyway)")+ igpu = (f"{vk['name']} is an integrated GPU, which shares the CPU's RAM, "+ f"and {family.display_name} was not measured faster on one: "+ "the engine runs on the CPU (--backend vulkan uses the GPU anyway)")+ decision["reason"] = igpu if blocked is None else f"{because('the CPU', '')}. {igpu}"return decision- if vk and requested in ("auto", "vulkan", "cuda"):+ if vk and requested in ("auto", "vulkan", "cuda") and "vulkan" not in exclude:if tc.get("can_build_vulkan"):kind = vk.get("type")decision.update(backend="vulkan", gpu=vk["name"],- reason=f"{vk['name']}, {kind} GPU")+ reason=because("Vulkan", f"{vk['name']}, {kind} GPU"))return decisionneeds = ["vulkan"] if tc.get("can_build") else ["build", "vulkan"]decision["missing"].append(("vulkan", _gpu_hint(needs, hw, tc)))@@ -339,7 +560,8 @@ def choose_backend(hw, family, tc, requested="auto"):elif requested == "vulkan" and not vk:decision["reason"] = "no Vulkan GPU answered: the engine runs on the CPU"else:- decision["reason"] = "the GPU build is not possible yet: the engine runs on the CPU"+ decision["reason"] = because("the CPU",+ "the GPU build is not possible yet: the engine runs on the CPU")return decision@@ -380,14 +602,20 @@ def engine_path(directory, family):# ---------------------------------------------------------------- building-def make_command(family, backend, tc):- """The make invocation for this engine and backend (argv, cwd, env)."""+def make_command(family, backend, tc, make_args=()):+ """The make invocation for this engine and backend (argv, cwd, env).+ `make_args` are the extra variables the decision asked for+ (cuda_make_args): they come last, and a CUDA_ARCH among them replaces+ the default one."""target = family.build_targetargs = [target, f"ARCH={os.environ.get('ARCH') or 'native'}"]if backend == "vulkan":args.append("VK=1")elif backend == "cuda":- args += ["CUDA=1", f"CUDA_ARCH={os.environ.get('CUDA_ARCH') or 'native'}"]+ args.append("CUDA=1")+ if not any(arg.startswith("CUDA_ARCH=") for arg in make_args):+ args.append(f"CUDA_ARCH={os.environ.get('CUDA_ARCH') or 'native'}")+ args += list(make_args)if host_os() == "win32" and tc.get("msys2"):bash = os.path.join(tc["msys2"], "usr", "bin", "bash.exe")script = 'cd "$(cygpath -u "$1")" && shift && exec make "$@"'@@ -396,12 +624,28 @@ def make_command(family, backend, tc):return [tc.get("make") or "make", "-C", HERE] + args, HERE, dict(os.environ)-def build_engine(family, backend, tc, out=print):- cmd, cwd, env = make_command(family, backend, tc)+class BuildError(SetupError):+ """A build that failed: which backend, and where its log is."""++ def __init__(self, message, backend, log):+ super().__init__(message)+ self.backend = backend+ self.log = log+++def build_log_name(backend):+ """One log per backend (logs/build-cuda.log, ...): when a failed CUDA build+ falls back to Vulkan, the CUDA log is still there to read."""+ return f"build-{backend}"+++def build_engine(family, backend, tc, out=print, make_args=()):+ cmd, cwd, env = make_command(family, backend, tc, make_args)shown = [a for a in cmd if a == family.build_target or re.match(r"^[A-Z_]+=", a)]- out(f" building: make {' '.join(shown)} (a few minutes; log: {log_path('build')})")+ log_file = log_path(build_log_name(backend))+ out(f" building: make {' '.join(shown)} (a few minutes; log: {log_file})")write_state("build", engine=family.engine_artifact, backend=backend)- with open(_ensure_log("build"), "w", encoding="utf-8", errors="replace") as log:+ with open(_ensure_log(build_log_name(backend)), "w", encoding="utf-8", errors="replace") as log:process = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, encoding="utf-8", errors="replace")tail = []@@ -412,7 +656,8 @@ def build_engine(family, backend, tc, out=print):path = engine_path(HERE, family)if process.returncode != 0 or not os.path.exists(path):detail = "\n".join(" " + line for line in tail[-12:])- raise SetupError(f"the {family.build_target} build failed (full log: {log_path('build')}):\n{detail}")+ raise BuildError(f"the {family.build_target} {BACKEND_NAME[backend]} build "+ f"failed (full log: {log_file}):\n{detail}", backend, log_file)return path@@ -611,7 +856,8 @@ def resolve_engine(family, entry, decision, tc, out=print, allow_prebuilt=True):return {"launcher_dir": HERE, "engine": local, "backend": have if have != "cuda" else "cpu","source": "present"}if tc.get("can_build"):- path = build_engine(family, decision["backend"], tc, out=out)+ path = build_engine(family, decision["backend"], tc, out=out,+ make_args=decision.get("make_args", ()))return {"launcher_dir": HERE, "engine": path, "backend": decision["backend"], "source": "built"}if not allow_prebuilt:raise SetupError(f"no compiler here to build {family.engine_artifact}: "@@ -634,6 +880,38 @@ def resolve_engine(family, entry, decision, tc, out=print, allow_prebuilt=True):return {"launcher_dir": runtime, "engine": engine, "backend": "cpu", "source": f"release {tag}"}+def resolve_with_fallback(ui, family, entry, decision, tc, hw, requested, failed=()):+ """resolve_engine, and when a build fails the next backend that can work+ instead of a stop: CUDA, then Vulkan, then the CPU (choose_backend again,+ without the backends that failed). With someone at the terminal it asks+ first; with --yes it goes ahead. Either way it says which build failed and+ where its log is. A CPU build that fails still stops the setup.++ Returns (engine_info, decision, failed): the decision the engine was built+ for, and the backends whose build failed, which the run configuration+ keeps so that a resumed setup does not build them again."""+ failed = list(failed)+ while True:+ try:+ return resolve_engine(family, entry, decision, tc, out=ui.say), decision, failed+ except BuildError as error:+ if error.backend == "cpu":+ raise+ failed.append(error.backend)+ following = choose_backend(hw, family, tc, requested, exclude=tuple(failed))+ ui.say(f" {error}")+ if ui.interactive and not ui.confirm(+ f" Build for {USING[following['backend']]} instead?", True):+ raise+ following["reason"] = (f"the {BACKEND_NAME[error.backend]} build failed "+ f"(full log: {error.log}): using {USING[following['backend']]}")+ decision = following+ ui.say(f"\nEngine: {family.engine_artifact} with {decision['backend'].upper()} "+ f"({decision['reason']})")+ for kind, hint in decision["missing"]:+ ui.say(f" to use the GPU through {kind.upper()}, first run: {hint}")++# ---------------------------------------------------------------- the run configuration@@ -1225,7 +1503,20 @@ def gpu_now_buildable(cfg, tc=None):if not pending or cfg.get("backend") != "cpu":return Falsetc = tc or toolchain()- return any(tc.get(f"can_build_{kind}") for kind in pending)+ for kind in pending:+ if not tc.get(f"can_build_{kind}"):+ continue+ if kind == "cuda":+ # A toolkit is here, but it has to build for the cards the last+ # setup found (kept in the configuration: no hardware probe here).+ try:+ family = family_by_id(cfg.get("family"))+ except Exception:+ continue+ if cuda_problem(cfg.get("nvidia") or [], family, tc) is not None:+ continue+ return True+ return Falsedef config_ready(cfg):@@ -1321,7 +1612,15 @@ def cmd_setup(a, ui=None):save_config(pending)tc = toolchain()- decision = choose_backend(hw, family, tc, requested)+ # A build that failed in the run this one resumes is not tried again; a new+ # choice (another model, --reconfigure, --backend) starts clean.+ failed = [] if (a.backend or a.no_gpu or picking or not resume) else \+ [b for b in (resume.get("failed_builds") or []) if b in ("cuda", "vulkan")]+ decision = choose_backend(hw, family, tc, requested, exclude=tuple(failed))+ if failed:+ decision["reason"] = (f"the {BACKEND_NAME[failed[-1]]} build failed in the last run "+ f"(log: {log_path(build_log_name(failed[-1]))}): "+ f"using {USING[decision['backend']]}")ui.say(f"\nEngine: {family.engine_artifact} with {decision['backend'].upper()} "f"({decision['reason']})")for kind, hint in decision["missing"]:@@ -1329,7 +1628,12 @@ def cmd_setup(a, ui=None):if decision["missing"] and ui.interactive and decision["backend"] == "cpu":if not ui.confirm(" Continue on the CPU for now (rerun after installing to switch)?", True):raise SetupError("stopped so you can install the GPU packages; rerun afterwards")- engine_info = resolve_engine(family, entry, decision, tc, out=ui.say)+ engine_info, decision, failed = resolve_with_fallback(ui, family, entry, decision, tc, hw,+ requested, failed)+ if failed:+ current = load_config()+ if current:+ save_config(dict(current, failed_builds=failed))engine_info["gpu"] = decision.get("gpu") if engine_info["backend"] != "cpu" else Noneui.say(f" engine ready: {engine_info['engine']} ({engine_info['backend']}, {engine_info['source']})")@@ -1357,6 +1661,11 @@ def cmd_setup(a, ui=None):# the packages arrived and rebuilds (gpu_now_buildable).cfg["gpu_pending"] = ([kind for kind, _hint in decision["missing"]]if engine_info["backend"] == "cpu" and requested == "auto" else [])+ # The cards a pending CUDA build has to serve: a rerun checks the toolkit+ # against them without probing the hardware again.+ cfg["nvidia"] = [{"name": card.get("name"), "compute_cap": card.get("compute_cap")}+ for card in (hw.get("gpu") or {}).get("nvidia") or []]+ cfg["failed_builds"] = failedcfg = save_config(cfg)write_state("ready", model=cfg["model"].get("id"), model_dir=model_dir)ui.say(f"\nSaved the run configuration: {config_path()}")diff --git a/c/setup_hw.py b/c/setup_hw.pyindex 2d4fcf79..50f66d35 100644--- a/c/setup_hw.py+++ b/c/setup_hw.py@@ -4,7 +4,8 @@What it answers, and nothing more: how much RAM there is, how much disk is freewhere the model would go, which CPU features the engine can use, and which GPUsare there (Vulkan devices with their type and memory, NVIDIA cards through-nvidia-smi). It never changes anything on the machine.+nvidia-smi with their compute capability). It never changes anything on the+machine.Every probe is split in two: a function that runs a command or a system call,and a pure parser that turns its output into data. The parsers are what the@@ -320,34 +321,94 @@ def windows_fixed_drives():# ---------------------------------------------------------------- NVIDIA-NVIDIA_SMI_QUERY = ["--query-gpu=index,name,memory.total,memory.free,driver_version",- "--format=csv,noheader,nounits"]+#: What the setup asks nvidia-smi, in this order. compute_cap is the card's CUDA+#: compute capability ("7.0" for a V100): which nvcc can build for the card+#: depends on it (setup_flow.choose_backend). pci.bus_id ties a row to the CUDA+#: driver's own device when compute_cap has to come from there.+NVIDIA_FIELDS = ("index", "name", "memory.total", "memory.free", "driver_version",+ "compute_cap", "pci.bus_id")+#: The same without compute_cap: a driver that predates the field refuses the+#: whole query and prints no rows, so the setup asks again without it.+NVIDIA_FIELDS_NO_CC = tuple(f for f in NVIDIA_FIELDS if f != "compute_cap")-def parse_nvidia_smi(text):- """Rows of `nvidia-smi --query-gpu=index,name,memory.total,memory.free,- driver_version --format=csv,noheader,nounits` (MiB). A unified-memory part- prints [N/A] for memory: that is None, not zero."""+def nvidia_smi_query(fields=NVIDIA_FIELDS):+ return [f"--query-gpu={','.join(fields)}", "--format=csv,noheader,nounits"]+++NVIDIA_SMI_QUERY = nvidia_smi_query()+++def parse_nvidia_smi(text, fields=NVIDIA_FIELDS):+ """Rows of `nvidia-smi --query-gpu=<fields> --format=csv,noheader,nounits`+ (memory in MiB). A unified-memory part prints [N/A] for memory: that is+ None, not zero; so is a compute capability the driver does not report.+ Rows with fewer columns than `fields` (an older query) leave the missing+ ones None."""import csvgpus = []- for fields in csv.reader((text or "").splitlines()):- fields = [f.strip() for f in fields]- if len(fields) < 4:+ for row in csv.reader((text or "").splitlines()):+ row = [f.strip() for f in row]+ if len(row) < 4:continue+ values = dict(zip(fields, row))try:- index = int(fields[0])- except ValueError:+ index = int(values["index"])+ except (KeyError, ValueError):continuedef mib(value):try:return int(float(value)) * 1024 * 1024- except ValueError:+ except (TypeError, ValueError):return None- gpus.append({"index": index, "name": fields[1], "total_bytes": mib(fields[2]),- "free_bytes": mib(fields[3]),- "driver": fields[4] if len(fields) > 4 and fields[4] else None})+ def known(value):+ return value if value and not value.startswith("[") else None++ gpus.append({"index": index, "name": values.get("name"),+ "total_bytes": mib(values.get("memory.total")),+ "free_bytes": mib(values.get("memory.free")),+ "driver": known(values.get("driver_version")),+ "compute_cap": compute_cap_text(values.get("compute_cap")),+ "pci_bus_id": known(values.get("pci.bus_id"))})+ return gpus+++def compute_cap_text(value):+ """A compute capability as "7.0", from nvidia-smi or the CUDA driver; None+ for [N/A], an empty field or anything that is not major.minor."""+ match = re.match(r"^\s*(\d+)\.(\d+)\s*$", value or "")+ return f"{int(match.group(1))}.{int(match.group(2))}" if match else None+++def compute_cap_sm(value):+ """The number nvcc names an architecture by: "7.0" -> 70 (compute_70,+ sm_70), "12.0" -> 120, "10.3" -> 103. None when the capability is unknown."""+ text = compute_cap_text(value)+ if text is None:+ return None+ major, minor = text.split(".")+ return int(major) * 10 + int(minor)+++def pci_bus_key(value):+ """nvidia-smi writes 00000000:01:00.0, the CUDA driver 0000:01:00.0: the+ same slot. (domain, bus, device, function) as integers, or None."""+ match = re.match(r"^\s*([0-9a-fA-F]+):([0-9a-fA-F]+):([0-9a-fA-F]+)\.([0-7])\s*$", value or "")+ return tuple(int(part, 16) for part in match.groups()) if match else None+++def fill_compute_caps(gpus, cuda_devices):+ """Give each nvidia-smi row without a compute capability the one the CUDA+ driver reports for the same PCI slot. Rows that cannot be matched stay None:+ an unknown capability is not a guess."""+ by_slot = {pci_bus_key(d.get("pci_bus_id")): compute_cap_text(d.get("compute_cap"))+ for d in cuda_devices or []}+ by_slot.pop(None, None)+ for gpu in gpus:+ if gpu.get("compute_cap") is None:+ gpu["compute_cap"] = by_slot.get(pci_bus_key(gpu.get("pci_bus_id")))return gpus@@ -363,10 +424,81 @@ def nvidia_smi_path():def detect_nvidia():+ """The NVIDIA cards, each with its compute capability when anything can tell.++ First nvidia-smi with compute_cap. A driver that does not know that field+ refuses the whole query, so no rows means asking again without it; then+ (and for any card printed as [N/A]) the CUDA driver itself is asked, in a+ child process like the Vulkan probe, and its answer matched by PCI slot."""exe = nvidia_smi_path()if not exe:return []- return parse_nvidia_smi(_run([exe] + NVIDIA_SMI_QUERY, timeout=10))+ gpus = parse_nvidia_smi(_run([exe] + nvidia_smi_query(NVIDIA_FIELDS), timeout=10), NVIDIA_FIELDS)+ if not gpus:+ gpus = parse_nvidia_smi(_run([exe] + nvidia_smi_query(NVIDIA_FIELDS_NO_CC), timeout=10),+ NVIDIA_FIELDS_NO_CC)+ if any(gpu.get("compute_cap") is None for gpu in gpus):+ probe = _probe_cuda_child()+ if probe:+ fill_compute_caps(gpus, probe.get("devices"))+ return gpus+++def _cuda_driver_library():+ names = {"win32": ["nvcuda.dll"]}.get(sys.platform, ["libcuda.so.1", "libcuda.so"])+ for name in names:+ try:+ return ctypes.CDLL(name)+ except OSError:+ continue+ return None+++def _cuda_probe_inprocess():+ """Compute capability and PCI slot of every device, from the CUDA driver+ API (the same driver the engine's CUDA runtime talks to)."""+ lib = _cuda_driver_library()+ if lib is None:+ return {"driver": False, "devices": []}+ c_int = ctypes.c_int+ if lib.cuInit(0) != 0:+ return {"driver": True, "devices": []}+ count = c_int(0)+ if lib.cuDeviceGetCount(ctypes.byref(count)) != 0:+ return {"driver": True, "devices": []}+ devices = []+ for ordinal in range(count.value):+ device = c_int(0)+ if lib.cuDeviceGet(ctypes.byref(device), ordinal) != 0:+ continue+ major, minor = c_int(0), c_int(0)+ # CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75, _MINOR = 76 (cuda.h)+ lib.cuDeviceGetAttribute(ctypes.byref(major), 75, device)+ lib.cuDeviceGetAttribute(ctypes.byref(minor), 76, device)+ bus = ctypes.create_string_buffer(64)+ name = ctypes.create_string_buffer(256)+ lib.cuDeviceGetPCIBusId(bus, 64, device)+ lib.cuDeviceGetName(name, 256, device)+ devices.append({"name": name.value.decode("utf-8", "replace"),+ "pci_bus_id": bus.value.decode("ascii", "replace"),+ "compute_cap": f"{major.value}.{minor.value}" if major.value else None})+ return {"driver": True, "devices": devices}+++def _probe_cuda_child(timeout=25):+ try:+ result = subprocess.run([sys.executable, os.path.join(HERE, "setup_hw.py"), "--cuda-probe"],+ capture_output=True, text=True, timeout=timeout)+ except (OSError, subprocess.SubprocessError):+ return None+ for line in reversed(result.stdout.splitlines()):+ line = line.strip()+ if line.startswith("{"):+ try:+ return json.loads(line)+ except ValueError:+ return None+ return None# ---------------------------------------------------------------- Vulkan@@ -770,6 +902,7 @@ def format_report(report):shown = Truefor card in gpu.get("nvidia", []):lines.append(f" GPU {card['name']} (NVIDIA, {fmt_gb(card.get('total_bytes'))} VRAM"+ + (f", compute {card['compute_cap']}" if card.get("compute_cap") else "")+ (f", driver {card['driver']}" if card.get("driver") else "") + ")")shown = Trueif not shown:@@ -797,6 +930,12 @@ def main(argv=None):except Exception as error: # report, never crash the parent's parseprint(json.dumps({"loader": False, "error": str(error), "devices": []}))return 0+ if argv[:1] == ["--cuda-probe"]:+ try:+ print(json.dumps(_cuda_probe_inprocess()))+ except Exception as error: # same rule as the Vulkan probe+ print(json.dumps({"driver": False, "error": str(error), "devices": []}))+ return 0sys.path.insert(0, HERE)targets = [arg for arg in argv if not arg.startswith("--")]report = detect(targets[0] if targets else os.path.expanduser("~"))diff --git a/c/tests/test_setup_flow.py b/c/tests/test_setup_flow.pyindex cee8555b..5baa29b6 100644--- a/c/tests/test_setup_flow.py+++ b/c/tests/test_setup_flow.py@@ -17,6 +17,7 @@ import hashlibimport ioimport jsonimport os+import reimport socketimport subprocessimport sys@@ -39,6 +40,7 @@ import setup_catalog # noqa: E402import setup_download # noqa: E402import setup_flow # noqa: E402import setup_hw # noqa: E402+import family_registry # noqa: E402from fake_hub import FakeHub # noqa: E402from family_registry import family_by_id # noqa: E402@@ -213,6 +215,294 @@ class BackendChoice(unittest.TestCase):self.assertIn("source checkout", hint) # a release archive cannot rebuild itself+#: What NVIDIA's own nvcc prints, measured: 11.x and 12.x from the+#: redistributable archives (developer.download.nvidia.com/compute/cuda/redist/+#: cuda_nvcc/linux-x86_64/cuda_nvcc-linux-x86_64-<version>-archive.tar.xz), 13.x+#: from NVIDIA's nvidia-cuda-nvcc wheels. The release line of `nvcc --version`, and+#: `nvcc --list-gpu-arch` with its one-per-line output joined by spaces. The+#: order is nvcc's own (13.x does not sort).+NVCC_SAMPLES = {+ "11.4.152": ("Cuda compilation tools, release 11.4, V11.4.152",+ "compute_35 compute_37 compute_50 compute_52 compute_53 compute_60 compute_61 compute_62 "+ "compute_70 compute_72 compute_75 compute_80 compute_86 compute_87"),+ "11.8.89": ("Cuda compilation tools, release 11.8, V11.8.89",+ "compute_35 compute_37 compute_50 compute_52 compute_53 compute_60 compute_61 compute_62 "+ "compute_70 compute_72 compute_75 compute_80 compute_86 compute_87 compute_89 compute_90"),+ "12.0.140": ("Cuda compilation tools, release 12.0, V12.0.140",+ "compute_50 compute_52 compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 "+ "compute_75 compute_80 compute_86 compute_87 compute_89 compute_90"),+ "12.6.85": ("Cuda compilation tools, release 12.6, V12.6.85",+ "compute_50 compute_52 compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 "+ "compute_75 compute_80 compute_86 compute_87 compute_89 compute_90"),+ "12.8.93": ("Cuda compilation tools, release 12.8, V12.8.93",+ "compute_50 compute_52 compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 "+ "compute_75 compute_80 compute_86 compute_87 compute_89 compute_90 compute_100 compute_101 "+ "compute_120"),+ "12.9.86": ("Cuda compilation tools, release 12.9, V12.9.86",+ "compute_50 compute_52 compute_53 compute_60 compute_61 compute_62 compute_70 compute_72 "+ "compute_75 compute_80 compute_86 compute_87 compute_89 compute_90 compute_100 compute_101 "+ "compute_103 compute_120 compute_121"),+ "13.0.88": ("Cuda compilation tools, release 13.0, V13.0.88",+ "compute_75 compute_80 compute_86 compute_87 compute_88 compute_89 compute_90 compute_100 "+ "compute_110 compute_103 compute_120 compute_121"),+ "13.4.92": ("Cuda compilation tools, release 13.4, V13.4.92",+ "compute_75 compute_80 compute_86 compute_87 compute_88 compute_89 compute_90 compute_100 "+ "compute_110 compute_103 compute_120 compute_121 compute_107"),+}+#: `nvcc --version` in full (13.0.88), and an option nvcc does not know (11.4.152).+NVCC_VERSION_13 = """nvcc: NVIDIA (R) Cuda compiler driver+Copyright (c) 2005-2025 NVIDIA Corporation+Built on Wed_Aug_20_01:58:59_PM_PDT_2025+Cuda compilation tools, release 13.0, V13.0.88+Build cuda_13.0.r13.0/compiler.36424714_0+"""+NVCC_UNKNOWN_OPTION = "nvcc fatal : Unknown option '--list-gpu-foo'\n"+++def nvcc_toolkit(version):+ """The toolchain fields toolchain() fills from that nvcc's real output."""+ release, archs = NVCC_SAMPLES[version]+ return {"cuda_version": "%d.%d" % setup_flow.parse_nvcc_version(release),+ "cuda_archs": setup_flow.parse_nvcc_arch_list(archs.replace(" ", "\n") + "\n")}+++V100 = {"index": 0, "name": "Tesla V100-SXM2-16GB", "total_bytes": 16384 * 2**20,+ "free_bytes": 16144 * 2**20, "driver": "580.178.04", "compute_cap": "7.0"}+V100_VK = {"name": "Tesla V100-SXM2-16GB", "type": "discrete", "api_version": "1.4.312",+ "api_version_raw": (1 << 22) | (4 << 12) | 312}+RTX3090 = {"index": 0, "name": "NVIDIA GeForce RTX 3090", "total_bytes": 24576 * 2**20,+ "free_bytes": 23000 * 2**20, "driver": "580.65", "compute_cap": "8.6"}+RTX5080 = {"index": 0, "name": "NVIDIA GeForce RTX 5080", "total_bytes": 16303 * 2**20,+ "free_bytes": 15000 * 2**20, "driver": "580.65", "compute_cap": "12.0"}+GTX970 = {"index": 0, "name": "NVIDIA GeForce GTX 970", "total_bytes": 4096 * 2**20,+ "free_bytes": 3900 * 2**20, "driver": "535.183", "compute_cap": "5.2"}+++class CudaToolkit(unittest.TestCase):+ """What nvcc says it builds for, from its real output."""++ def test_list_gpu_arch(self):+ for version, (release, archs) in NVCC_SAMPLES.items():+ with self.subTest(nvcc=version):+ parsed = setup_flow.parse_nvcc_arch_list(archs.replace(" ", "\n") + "\n")+ self.assertEqual(parsed, sorted(int(a.split("_")[1]) for a in archs.split()))+ self.assertEqual(setup_flow.parse_nvcc_version(release),+ tuple(int(p) for p in version.split(".")[:2]))+ self.assertNotIn(70, nvcc_toolkit("13.0.88")["cuda_archs"]) # Volta is gone in 13+ self.assertIn(70, nvcc_toolkit("12.9.86")["cuda_archs"])+ self.assertNotIn(120, nvcc_toolkit("12.6.85")["cuda_archs"]) # Blackwell needs 12.8+ self.assertEqual(setup_flow.parse_nvcc_version(NVCC_VERSION_13), (13, 0))++ def test_an_nvcc_without_the_option_lists_nothing(self):+ self.assertIsNone(setup_flow.parse_nvcc_arch_list(NVCC_UNKNOWN_OPTION))+ self.assertIsNone(setup_flow.parse_nvcc_arch_list(""))+ self.assertIsNone(setup_flow.parse_nvcc_version(""))++ def test_the_release_table_matches_what_nvcc_lists(self):+ """Each measured nvcc's oldest and newest architecture is its row of+ CUDA_RELEASES, which answers for an nvcc that cannot list them."""+ for version in NVCC_SAMPLES:+ with self.subTest(nvcc=version):+ archs = nvcc_toolkit(version)["cuda_archs"]+ bounds = setup_flow._release_bounds(tuple(int(p) for p in version.split(".")[:2]))+ self.assertEqual(bounds, (min(archs), max(archs)))++ def test_the_version_answers_when_the_list_does_not(self):+ old = {"cuda_version": "10.2", "cuda_archs": None}+ self.assertTrue(setup_flow.toolkit_builds(old, 70))+ self.assertFalse(setup_flow.toolkit_builds(old, 80))+ self.assertFalse(setup_flow.toolkit_builds({"cuda_version": "13.1", "cuda_archs": None}, 70))+ self.assertIsNone(setup_flow.toolkit_builds({"cuda_version": None, "cuda_archs": None}, 70))+ self.assertIsNone(setup_flow.toolkit_builds({"cuda_version": "8.0", "cuda_archs": None}, 60))+ self.assertIsNone(setup_flow.toolkit_builds(nvcc_toolkit("13.0.88"), None)) # card unknown++ def test_what_to_install(self):+ advice = setup_flow.cuda_release_advice+ self.assertEqual(advice(70, (13, 0)), ("dropped in CUDA 13", "install a CUDA 12.x toolkit"))+ self.assertEqual(advice(61, (13, 2)), ("dropped in CUDA 13", "install a CUDA 12.x toolkit"))+ self.assertEqual(advice(37, (12, 6)), ("dropped in CUDA 12", "install a CUDA 11.x toolkit"))+ self.assertEqual(advice(120, (12, 6)), ("needs CUDA 12.8 or newer", "install CUDA 12.8 or newer"))+ self.assertEqual(advice(121, (12, 8)), ("needs CUDA 12.9 or newer", "install CUDA 12.9 or newer"))+ self.assertIn("compute_200", advice(200, (13, 0))[1])++ def test_cuda_toolkit_runs_nvcc(self):+ release, archs = NVCC_SAMPLES["13.0.88"]+ answers = {"--version": NVCC_VERSION_13, "--list-gpu-arch": archs.replace(" ", "\n") + "\n"}+ with mock.patch.object(setup_hw, "_run", side_effect=lambda cmd, timeout=10: answers[cmd[1]]):+ info = setup_flow.cuda_toolkit("/usr/local/cuda/bin/nvcc")+ self.assertEqual(info, {"cuda_version": "13.0", "cuda_archs": nvcc_toolkit("13.0.88")["cuda_archs"]})+ answers["--list-gpu-arch"] = NVCC_UNKNOWN_OPTION # an nvcc without the option+ with mock.patch.object(setup_hw, "_run", side_effect=lambda cmd, timeout=10: answers[cmd[1]]):+ self.assertIsNone(setup_flow.cuda_toolkit("nvcc")["cuda_archs"])+++class CudaBackendChoice(unittest.TestCase):+ """#1852: a CUDA toolkit is there, but it has to build for the card."""++ def choose(self, nvidia, toolkit, family="qwen36", vulkan=None, requested="auto", tc=None):+ tc = dict(tc or TC_ALL, **(nvcc_toolkit(toolkit) if toolkit else {}))+ with modeled("linux"):+ return setup_flow.choose_backend(hw_report(vulkan=vulkan, nvidia=nvidia),+ family_by_id(family), tc, requested)++ def test_v100_with_cuda_13_takes_vulkan_and_says_why(self):+ decision = self.choose([V100], "13.0.88", vulkan=V100_VK)+ self.assertEqual(decision["backend"], "vulkan")+ self.assertEqual(decision["reason"],+ "the CUDA 13.0 toolkit cannot build for the Tesla V100-SXM2-16GB (compute 7.0, "+ "dropped in CUDA 13): using Vulkan; install a CUDA 12.x toolkit for the CUDA path")+ self.assertEqual(decision["missing"][0][0], "cuda")+ self.assertIn("CUDA 12.x", decision["missing"][0][1])+ self.assertIn(setup_flow.CUDA_ARCHIVE_URL, decision["missing"][0][1])++ def test_v100_with_cuda_12_takes_cuda(self):+ for toolkit in ("12.0.140", "12.6.85", "12.9.86", "11.8.89"):+ with self.subTest(nvcc=toolkit):+ decision = self.choose([V100], toolkit, vulkan=V100_VK)+ self.assertEqual(decision["backend"], "cuda")+ self.assertEqual(decision["make_args"], [])+ self.assertIn("compute 7.0", decision["reason"])++ def test_rtx_30_with_cuda_13_takes_cuda(self):+ for toolkit in ("13.0.88", "13.4.92"):+ with self.subTest(nvcc=toolkit):+ decision = self.choose([RTX3090], toolkit)+ self.assertEqual(decision["backend"], "cuda")+ self.assertEqual(decision["gpu"], "NVIDIA GeForce RTX 3090")++ def test_a_card_newer_than_the_toolkit(self):+ decision = self.choose([RTX5080], "12.6.85")+ self.assertEqual(decision["backend"], "cpu") # no Vulkan GPU here+ self.assertIn("needs CUDA 12.8 or newer", decision["reason"])+ self.assertIn("using the CPU", decision["reason"])+ self.assertEqual(decision["missing"][0][0], "cuda")+ self.assertEqual(self.choose([RTX5080], "12.8.93")["backend"], "cuda")++ def test_explicit_cuda_stops_before_building(self):+ with self.assertRaises(setup_flow.SetupError) as caught:+ self.choose([V100], "13.0.88", vulkan=V100_VK, requested="cuda")+ self.assertEqual(str(caught.exception),+ "the CUDA 13.0 toolkit cannot build for the Tesla V100-SXM2-16GB (compute 7.0, "+ "dropped in CUDA 13): install a CUDA 12.x toolkit for the CUDA path, or run "+ "with --backend auto to use Vulkan")+ with self.assertRaises(setup_flow.SetupError) as caught:+ self.choose([V100], "13.0.88", requested="cuda") # no Vulkan GPU: the CPU+ self.assertIn("--backend auto to use the CPU", str(caught.exception))+ # A toolkit that does build for the card is taken as asked.+ self.assertEqual(self.choose([V100], "12.6.85", requested="cuda")["backend"], "cuda")++ def test_every_card_has_to_be_buildable(self):+ """-arch=native builds for every card nvcc sees and stops at the first+ it cannot: a V100 next to an RTX 3090 stops CUDA 13 too."""+ second = dict(V100, index=1)+ decision = self.choose([RTX3090, second], "13.0.88")+ self.assertNotEqual(decision["backend"], "cuda")+ self.assertIn("Tesla V100", decision["reason"])++ def test_unknown_is_not_a_no(self):+ """No compute capability (an old driver, no CUDA probe) or a toolkit+ that said nothing: CUDA as before; a failed build falls back later."""+ unknown_card = dict(V100, compute_cap=None)+ self.assertEqual(self.choose([unknown_card], "13.0.88")["backend"], "cuda")+ self.assertEqual(self.choose([V100], None)["backend"], "cuda")++ def test_deepseek_v4_needs_compute_6_and_cuda_12(self):+ decision = self.choose([GTX970], "12.6.85", family="deepseek_v4")+ self.assertEqual(decision["backend"], "cpu")+ self.assertIn("DeepSeek V4 Flash's CUDA tier runs on compute 6.0 and newer", decision["reason"])+ self.assertEqual(decision["missing"], []) # no toolkit would change that+ self.assertEqual(self.choose([GTX970], "12.6.85")["backend"], "cuda") # backend_cuda.o: no floor+ decision = self.choose([V100], "11.8.89", family="deepseek_v4")+ self.assertNotEqual(decision["backend"], "cuda")+ self.assertIn("needs CUDA 12.0 or newer", decision["reason"])++ def test_deepseek_v4_below_cuda_12_8_builds_without_the_tensor_core_path(self):+ self.assertEqual(self.choose([V100], "12.6.85", family="deepseek_v4")["make_args"], ["NO_TC=1"])+ self.assertEqual(self.choose([RTX5080], "12.8.93", family="deepseek_v4")["make_args"], [])+ self.assertEqual(self.choose([V100], "12.6.85")["make_args"], []) # qwen36 has no NO_TC++ def test_an_nvcc_without_native_gets_the_card_architecture(self):+ tc = {"cuda_version": "11.5", "cuda_archs": [35, 37, 50, 52, 53, 60, 61, 62, 70, 72, 75, 80, 86, 87]}+ with mock.patch.dict(os.environ, {"CUDA_ARCH": ""}):+ decision = self.choose([V100], None, tc=dict(TC_ALL, **tc))+ self.assertEqual(decision["make_args"], ["CUDA_ARCH=sm_70"])+ self.assertEqual(self.choose([V100], "11.8.89")["make_args"], [])+ with mock.patch.dict(os.environ, {"CUDA_ARCH": "sm_70"}): # set by hand: kept+ self.assertEqual(self.choose([V100], None, tc=dict(TC_ALL, **tc))["make_args"], [])++ def test_glm53_has_no_cuda_path(self):+ decision = self.choose([RTX3090], "13.0.88", family="glm53", vulkan=DGPU)+ self.assertEqual(decision["backend"], "vulkan")++ def test_make_command_takes_the_decision_arguments(self):+ with modeled("linux"), mock.patch.dict(os.environ, {"ARCH": "", "CUDA_ARCH": ""}):+ cmd, _cwd, _env = setup_flow.make_command(family_by_id("deepseek_v4"), "cuda", TC_ALL,+ ["NO_TC=1"])+ self.assertEqual(cmd[cmd.index("deepseek-v4"):],+ ["deepseek-v4", "ARCH=native", "CUDA=1", "CUDA_ARCH=native", "NO_TC=1"])+ cmd, _cwd, _env = setup_flow.make_command(family_by_id("qwen36"), "cuda", TC_ALL,+ ["CUDA_ARCH=sm_70"])+ self.assertEqual(cmd[cmd.index("qwen36"):], ["qwen36", "ARCH=native", "CUDA=1", "CUDA_ARCH=sm_70"])++ def test_a_pending_cuda_rebuild_checks_the_cards_it_was_for(self):+ cfg = {"backend": "cpu", "gpu_pending": ["cuda"], "family": "qwen36",+ "nvidia": [{"name": V100["name"], "compute_cap": "7.0"}]}+ self.assertFalse(setup_flow.gpu_now_buildable(cfg, dict(TC_ALL, **nvcc_toolkit("13.0.88"))))+ self.assertTrue(setup_flow.gpu_now_buildable(cfg, dict(TC_ALL, **nvcc_toolkit("12.6.85"))))+ self.assertFalse(setup_flow.gpu_now_buildable(+ cfg, dict(TC_ALL, nvcc=None, can_build_cuda=False, **nvcc_toolkit("12.6.85"))))+++class CudaEngineTable(unittest.TestCase):+ """CUDA_ENGINES says what each engine's CUDA build is and needs; this reads+ the same facts from the Makefiles and the sources."""++ OBJECTS = {"CUDA_OBJ": "backend_cuda.o", "INK_CUDA_OBJ": "backend_cuda_ink.o"}++ def rule(self, artifact):+ makefile = (C_DIR / "Makefile").read_text(encoding="utf-8")+ match = re.search(rf"^{re.escape(artifact)}\$\(EXE\):.*?(?=\n\S|\Z)", makefile, re.M | re.S)+ return match.group(0) if match else ""++ def test_the_cuda_object_each_engine_links(self):+ for family in family_registry.FAMILIES:+ with self.subTest(family=family.id):+ if family.engine_artifact == "deepseek_v4":+ v4 = (C_DIR / "Makefile.deepseek-v4").read_text(encoding="utf-8")+ linked = "backend_cuda_dsv4.o" if "V4_WIN_EXTRA_OBJS += backend_cuda_dsv4.o" in v4 else None+ else:+ rule = self.rule(family.engine_artifact)+ self.assertTrue(rule, f"no Makefile rule for {family.engine_artifact}")+ first_line = rule.splitlines()[0]+ linked = next((obj for var, obj in self.OBJECTS.items()+ if f"$({var})" in first_line), None)+ self.assertEqual((setup_flow.CUDA_ENGINES.get(family.id) or {}).get("object"), linked)++ def test_deepseek_v4_needs_what_the_table_says(self):+ v4 = (C_DIR / "Makefile.deepseek-v4").read_text(encoding="utf-8")+ flags = v4[v4.index("V4_NVCCFLAGS ="):].split("\n\n")[0]+ self.assertIn("-std=c++20", flags) # nvcc takes it from 12.0+ self.assertEqual(setup_flow.CUDA_ENGINES["deepseek_v4"]["min_toolkit"], (12, 0))+ self.assertIn("NO_TC ?= 0", v4)+ source = (C_DIR / "backend_cuda_dsv4.cu").read_text(encoding="utf-8")+ gate = source[source.index("int dsv4_cuda_backend_arch_ok"):]+ self.assertIn("return prop.major>=6;", gate[:400])+ self.assertEqual(setup_flow.CUDA_ENGINES["deepseek_v4"]["min_compute"], 60)++ def test_backend_cuda_has_no_compute_floor(self):+ """The tensor-core kernels are guarded and fall back; nothing refuses an+ older card, so the table puts no floor on the engines that link it."""+ makefile = (C_DIR / "Makefile").read_text(encoding="utf-8")+ self.assertIn("NVCC_STD ?= c++17", makefile)+ source = (C_DIR / "backend_cuda.cu").read_text(encoding="utf-8")+ self.assertIn("#if __CUDA_ARCH__ >= 700", source)+ self.assertIn("ctx->compute_major<7)return 0", source)+ for family_id, entry in setup_flow.CUDA_ENGINES.items():+ if entry["object"] in ("backend_cuda.o", "backend_cuda_ink.o"):+ self.assertNotIn("min_compute", entry, family_id)+ self.assertNotIn("min_toolkit", entry, family_id)++class PackageHints(unittest.TestCase):def test_one_command_per_system(self):hint = setup_flow.package_hint@@ -593,7 +883,7 @@ class WholeSetup(HomeTestCase):os.remove(os.path.join(self.engines, "qwen36"))shard_fetches = sum("/cdn/" in r["path"] for r in self.hub.requests)- def rebuild(family, backend, tc, out=print):+ def rebuild(family, backend, tc, out=print, make_args=()):Path(self.engines, "qwen36").write_bytes(b"libvulkan.so.1")return os.path.join(self.engines, "qwen36")@@ -619,7 +909,7 @@ class WholeSetup(HomeTestCase):code, text = self.run_setup()self.assertIn("Already set up", text)- def rebuild(family, backend, tc, out=print):+ def rebuild(family, backend, tc, out=print, make_args=()):self.assertEqual(backend, "vulkan")Path(self.engines, "qwen36").write_bytes(b"libvulkan.so.1")return os.path.join(self.engines, "qwen36")@@ -632,6 +922,117 @@ class WholeSetup(HomeTestCase):self.assertEqual((cfg["backend"], cfg["gpu_pending"]), ("vulkan", []))self.assertEqual(cfg["env"]["COLI_VULKAN"], "1")+ def failing_build(self, *broken):+ """build_engine as a mock: the backends in `broken` fail the way make+ does (BuildError with their log), the others write a matching engine."""+ loaders = {"cuda": b"libcudart.so.12", "vulkan": b"libvulkan.so.1", "cpu": b"plain"}+ calls = []++ def build(family, backend, tc, out=print, make_args=()):+ calls.append(backend)+ log = setup_flow.log_path(setup_flow.build_log_name(backend))+ if backend in broken:+ raise setup_flow.BuildError(+ f"the qwen36 {setup_flow.BACKEND_NAME[backend]} build failed (full log: {log}):\n"+ " make: *** [Makefile:949: backend_cuda.o] Error 1", backend, log)+ Path(self.engines, "qwen36").write_bytes(b"\x7fELF " + loaders[backend])+ return os.path.join(self.engines, "qwen36")++ return build, calls++ def v100_machine(self):+ """The #1852 machine, with a toolkit that did not say what it builds:+ CUDA is chosen, so the build is what fails."""+ Path(self.engines, "qwen36").write_bytes(b"\x7fELF plain")+ return mock.patch.object(setup_hw, "detect", return_value=hw_report(vulkan=V100_VK, nvidia=[V100]))++ def test_a_failed_cuda_build_falls_back_to_vulkan(self):+ build, calls = self.failing_build("cuda")+ with self.v100_machine(), mock.patch.object(setup_flow, "build_engine", side_effect=build):+ code, text = self.run_setup(pick="tiny")+ self.assertEqual(code, 0, text)+ self.assertEqual(calls, ["cuda", "vulkan"])+ cuda_log = setup_flow.log_path("build-cuda")+ self.assertIn(f"the qwen36 CUDA build failed (full log: {cuda_log})", text)+ self.assertIn(f"Engine: qwen36 with VULKAN (the CUDA build failed (full log: {cuda_log}): "+ "using Vulkan)", text)+ cfg = setup_flow.load_config()+ self.assertEqual((cfg["backend"], cfg["failed_builds"]), ("vulkan", ["cuda"]))+ self.assertEqual(cfg["env"]["COLI_VULKAN"], "1")++ def test_a_failed_vulkan_build_falls_back_to_the_cpu(self):+ build, calls = self.failing_build("cuda", "vulkan")+ with self.v100_machine(), mock.patch.object(setup_flow, "build_engine", side_effect=build):+ code, text = self.run_setup(pick="tiny")+ self.assertEqual(code, 0, text)+ self.assertEqual(calls, ["cuda", "vulkan"]) # a plain engine is already here for the CPU+ self.assertIn("the qwen36 Vulkan build failed (full log: ", text)+ self.assertIn("using the CPU", text)+ cfg = setup_flow.load_config()+ self.assertEqual((cfg["backend"], cfg["failed_builds"], cfg["gpu_pending"]),+ ("cpu", ["cuda", "vulkan"], [])) # nothing to install: no rebuild on rerun++ def test_a_failed_cpu_build_stops(self):+ os.remove(os.path.join(self.engines, "qwen36"))+ build, calls = self.failing_build("cpu")+ with mock.patch.object(setup_flow, "build_engine", side_effect=build):+ code, text = self.run_setup(pick="tiny", backend="cpu")+ self.assertEqual(code, 1)+ self.assertEqual(calls, ["cpu"])+ self.assertEqual(setup_flow.read_state()["phase"], "error")+ self.assertIn("build-cpu.log", setup_flow.read_state()["message"])++ def test_the_fallback_is_offered_when_someone_can_answer(self):+ build, calls = self.failing_build("cuda")+ out = io.StringIO()+ ui = setup_flow.UI(True, stream=out)+ with self.v100_machine(), mock.patch.object(setup_flow, "build_engine", side_effect=build), \+ mock.patch("builtins.input", side_effect=["n"]) as asked:+ code = setup_flow.run(lambda a: setup_flow.cmd_setup(a, ui=ui),+ setup_args(dir=self.models, pick="tiny", yes=False))+ self.assertEqual(code, 1, out.getvalue())+ self.assertEqual(calls, ["cuda"])+ self.assertIn("Build for Vulkan instead?", asked.call_args[0][0])+ self.assertIn("build-cuda.log", setup_flow.read_state()["message"])++ def test_a_resumed_setup_does_not_build_the_failed_backend_again(self):+ build, calls = self.failing_build("cuda")+ real = setup_download.download_repo+ self.hub.cut_after["model-00000.safetensors"] = 150_000+ with self.v100_machine(), mock.patch.object(setup_flow, "build_engine", side_effect=build), \+ mock.patch.object(setup_download, "download_repo",+ side_effect=lambda *a, **k: real(*a, **dict(k, retries=0))):+ code, text = self.run_setup(pick="tiny")+ self.assertEqual(code, 1) # the download was cut+ self.assertEqual(setup_flow.load_config()["failed_builds"], ["cuda"])+ with self.v100_machine(), mock.patch.object(setup_flow, "build_engine", side_effect=build):+ Path(self.engines, "qwen36").write_bytes(b"\x7fELF libvulkan.so.1") # what the fallback built+ code, text = self.run_setup()+ self.assertEqual(code, 0, text)+ self.assertEqual(calls, ["cuda", "vulkan"]) # nothing built the second time+ self.assertIn("the CUDA build failed in the last run", text)+ self.assertEqual(setup_flow.load_config()["backend"], "vulkan")++ def test_explicit_cuda_with_a_toolkit_that_cannot_build_stops_before_make(self):+ tc = dict(TC_ALL, **nvcc_toolkit("13.0.88"))+ with self.v100_machine(), mock.patch.object(setup_flow, "toolchain", return_value=tc), \+ mock.patch.object(setup_flow, "build_engine") as build:+ code, text = self.run_setup(pick="tiny", backend="cuda")+ self.assertEqual(code, 1)+ build.assert_not_called()+ self.assertIn("cannot build for the Tesla V100-SXM2-16GB (compute 7.0, dropped in CUDA 13)",+ setup_flow.read_state()["message"])+ # auto takes Vulkan on the same machine, and says why.+ with self.v100_machine(), mock.patch.object(setup_flow, "toolchain", return_value=tc), \+ mock.patch.object(setup_flow, "build_engine", side_effect=self.failing_build()[0]):+ code, text = self.run_setup(pick="tiny", backend="auto")+ self.assertEqual(code, 0, text)+ self.assertIn("Engine: qwen36 with VULKAN (the CUDA 13.0 toolkit cannot build for the "+ "Tesla V100-SXM2-16GB (compute 7.0, dropped in CUDA 13): using Vulkan; "+ "install a CUDA 12.x toolkit for the CUDA path)", text)+ self.assertIn("GPU Tesla V100-SXM2-16GB (NVIDIA, 17.2 GB VRAM, compute 7.0, "+ "driver 580.178.04)", text)+def test_wsl_download_through_windows_when_faster(self):entry = setup_catalog.by_id("tiny")files = [{"path": "model-00000.safetensors", "size": 400_000}]diff --git a/c/tests/test_setup_hw.py b/c/tests/test_setup_hw.pyindex 3aef649b..8c2bbe03 100644--- a/c/tests/test_setup_hw.py+++ b/c/tests/test_setup_hw.py@@ -42,6 +42,15 @@ NVIDIA_SMI = """0, NVIDIA GeForce RTX 4070, 12282, 11520, 560.94garbage line"""+# The query with compute_cap and pci.bus_id (setup_hw.NVIDIA_FIELDS): a V100 as+# in #1852, an RTX 3090, a GB10 whose memory is unified, and a card the driver+# gives no compute capability for.+NVIDIA_SMI_CC = """0, Tesla V100-SXM2-16GB, 16384, 16144, 580.178.04, 7.0, 00000000:1A:00.0+1, NVIDIA GeForce RTX 3090, 24576, 24253, 580.65, 8.6, 00000000:68:00.0+2, NVIDIA GB10, [N/A], [N/A], 580.65, 12.1, 0000000F:01:00.0+3, Some Card, 8192, 8000, 580.65, [N/A], 00000000:B1:00.0+"""+VULKANINFO_SUMMARY = """==========VULKANINFO==========@@ -219,6 +228,130 @@ class NvidiaParsing(unittest.TestCase):def test_empty(self):self.assertEqual(setup_hw.parse_nvidia_smi(""), [])+ def test_compute_capability_and_slot(self):+ gpus = setup_hw.parse_nvidia_smi(NVIDIA_SMI_CC)+ self.assertEqual([g["compute_cap"] for g in gpus], ["7.0", "8.6", "12.1", None])+ self.assertEqual(gpus[0]["name"], "Tesla V100-SXM2-16GB")+ self.assertEqual(gpus[0]["total_bytes"], 16384 * 2**20)+ self.assertEqual(gpus[0]["driver"], "580.178.04")+ self.assertEqual(gpus[0]["pci_bus_id"], "00000000:1A:00.0")+ self.assertIsNone(gpus[2]["total_bytes"]) # GB10: unified memory+ self.assertEqual(setup_hw.compute_cap_sm(gpus[0]["compute_cap"]), 70)+ self.assertEqual(setup_hw.compute_cap_sm("12.0"), 120)+ self.assertEqual(setup_hw.compute_cap_sm("10.3"), 103)+ self.assertIsNone(setup_hw.compute_cap_sm("[N/A]"))+ self.assertIsNone(setup_hw.compute_cap_sm(None))++ def test_the_old_query_has_no_compute_capability(self):+ gpus = setup_hw.parse_nvidia_smi("0, Tesla V100-SXM2-16GB, 16384, 16144, 470.256.02, "+ "00000000:1A:00.0\n", setup_hw.NVIDIA_FIELDS_NO_CC)+ self.assertIsNone(gpus[0]["compute_cap"])+ self.assertEqual(gpus[0]["pci_bus_id"], "00000000:1A:00.0")++ def test_the_query_asks_for_the_compute_capability(self):+ self.assertEqual(setup_hw.NVIDIA_SMI_QUERY,+ ["--query-gpu=index,name,memory.total,memory.free,driver_version,"+ "compute_cap,pci.bus_id", "--format=csv,noheader,nounits"])+ self.assertNotIn("compute_cap", setup_hw.nvidia_smi_query(setup_hw.NVIDIA_FIELDS_NO_CC)[0])++ def run_detect(self, answers, exe, probe=None):+ """detect_nvidia with nvidia-smi answering `answers` by query, and the+ CUDA driver probe answering `probe`."""+ seen = []++ def run(cmd, timeout=10):+ seen.append(cmd)+ return answers.get(cmd[1], "")++ with mock.patch.object(setup_hw, "nvidia_smi_path", return_value=exe), \+ mock.patch.object(setup_hw, "_run", side_effect=run), \+ mock.patch.object(setup_hw, "_probe_cuda_child", return_value=probe) as child:+ gpus = setup_hw.detect_nvidia()+ return gpus, seen, child++ def test_detect_on_linux_windows_and_wsl(self):+ """The same query through every nvidia-smi the setup finds: the Linux+ one, Windows' nvidia-smi.exe and the one WSL maps in."""+ query = setup_hw.nvidia_smi_query()[0]+ for exe in ("/usr/bin/nvidia-smi", r"C:\Windows\System32\nvidia-smi.exe",+ "/usr/lib/wsl/lib/nvidia-smi"):+ with self.subTest(exe=exe):+ gpus, seen, child = self.run_detect({query: NVIDIA_SMI_CC.splitlines()[0] + "\n"}, exe)+ self.assertEqual(seen[0][:2], [exe, query])+ self.assertEqual(len(seen), 1)+ self.assertEqual(gpus[0]["compute_cap"], "7.0")+ child.assert_not_called() # nvidia-smi answered++ def test_an_old_driver_is_asked_again_and_the_cuda_driver_fills_in(self):+ query = setup_hw.nvidia_smi_query()[0]+ old_query = setup_hw.nvidia_smi_query(setup_hw.NVIDIA_FIELDS_NO_CC)[0]+ # A driver that does not know the field: an error instead of rows (the+ # wording does not matter, no row parses).+ answers = {query: 'Field "compute_cap" is not a valid field to query.\n\n',+ old_query: ("0, Tesla V100-SXM2-16GB, 16384, 16144, 470.256.02, 00000000:1A:00.0\n"+ "1, Tesla P40, 22919, 22800, 470.256.02, 00000000:3B:00.0\n")}+ probe = {"driver": True, "devices": [+ {"name": "Tesla P40", "pci_bus_id": "0000:3B:00.0", "compute_cap": "6.1"},+ {"name": "Tesla V100-SXM2-16GB", "pci_bus_id": "0000:1a:00.0", "compute_cap": "7.0"}]}+ gpus, seen, child = self.run_detect(answers, "/usr/bin/nvidia-smi", probe)+ self.assertEqual([cmd[1] for cmd in seen], [query, old_query])+ child.assert_called_once()+ self.assertEqual([(g["name"], g["compute_cap"]) for g in gpus],+ [("Tesla V100-SXM2-16GB", "7.0"), ("Tesla P40", "6.1")]) # matched by slot+ # No driver to ask: unknown, not a guess.+ gpus, _seen, _child = self.run_detect(answers, "/usr/bin/nvidia-smi", None)+ self.assertEqual([g["compute_cap"] for g in gpus], [None, None])++ def test_pci_slots_in_both_spellings(self):+ self.assertEqual(setup_hw.pci_bus_key("00000000:1A:00.0"), setup_hw.pci_bus_key("0000:1a:00.0"))+ self.assertNotEqual(setup_hw.pci_bus_key("00000000:1A:00.0"), setup_hw.pci_bus_key("0000:1b:00.0"))+ self.assertIsNone(setup_hw.pci_bus_key("[N/A]"))++ def test_the_cuda_driver_probe(self):+ """_cuda_probe_inprocess against a stand-in for libcuda/nvcuda.dll: the+ attribute numbers are the compute capability's (75, 76 in cuda.h)."""+ cards = [("Tesla V100-SXM2-16GB", "0000:1A:00.0", 7, 0), ("NVIDIA GeForce RTX 3090", "0000:68:00.0", 8, 6)]++ class Driver:+ def cuInit(self, flags):+ return 0++ def cuDeviceGetCount(self, count):+ count._obj.value = len(cards)+ return 0++ def cuDeviceGet(self, device, ordinal):+ device._obj.value = ordinal+ return 0++ def cuDeviceGetAttribute(self, value, attribute, device):+ value._obj.value = {75: cards[device.value][2], 76: cards[device.value][3]}[attribute]+ return 0++ def cuDeviceGetPCIBusId(self, buffer, size, device):+ buffer.value = cards[device.value][1].encode()+ return 0++ def cuDeviceGetName(self, buffer, size, device):+ buffer.value = cards[device.value][0].encode()+ return 0++ with mock.patch.object(setup_hw, "_cuda_driver_library", return_value=Driver()):+ probe = setup_hw._cuda_probe_inprocess()+ self.assertEqual(probe["devices"], [+ {"name": "Tesla V100-SXM2-16GB", "pci_bus_id": "0000:1A:00.0", "compute_cap": "7.0"},+ {"name": "NVIDIA GeForce RTX 3090", "pci_bus_id": "0000:68:00.0", "compute_cap": "8.6"}])+ with mock.patch.object(setup_hw, "_cuda_driver_library", return_value=None):+ self.assertEqual(setup_hw._cuda_probe_inprocess(), {"driver": False, "devices": []})++ def test_the_child_probe_reads_the_last_json_line(self):+ done = mock.Mock(stdout='driver noise\n{"driver": true, "devices": [{"compute_cap": "7.0"}]}\n')+ with mock.patch.object(setup_hw.subprocess, "run", return_value=done) as run:+ self.assertEqual(setup_hw._probe_cuda_child()["devices"], [{"compute_cap": "7.0"}])+ self.assertEqual(run.call_args[0][0][-1], "--cuda-probe")+ with mock.patch.object(setup_hw.subprocess, "run", side_effect=OSError("no python")):+ self.assertIsNone(setup_hw._probe_cuda_child())+class VulkanParsing(unittest.TestCase):def test_vulkaninfo_summary(self):@@ -340,6 +473,18 @@ class Report(unittest.TestCase):"/home/u/dzn.json"):self.assertIn(piece, text)+ def test_the_report_names_the_compute_capability(self):+ card = setup_hw.parse_nvidia_smi(NVIDIA_SMI_CC)[0]+ report = {"os": {"platform": "linux", "pretty_name": "Ubuntu 26.04.1 LTS"},+ "cpu": {"name": "Test CPU", "features": [], "logical_cores": 16},+ "memory": {"total": 31.6e9, "available": 24.1e9}, "disk": None,+ "vulkan": {"devices": []}, "nvidia": [card], "windows_video": [],+ "gpu": setup_hw.gpu_summary({"devices": []}, [card, dict(card, compute_cap=None)])}+ lines = setup_hw.format_report(report).splitlines()+ self.assertIn(" GPU Tesla V100-SXM2-16GB (NVIDIA, 17.2 GB VRAM, compute 7.0, "+ "driver 580.178.04)", lines)+ self.assertIn(" GPU Tesla V100-SXM2-16GB (NVIDIA, 17.2 GB VRAM, driver 580.178.04)", lines)+def test_detect_without_gpu_probe_is_plain_data(self):import jsonwith tempfile.TemporaryDirectory() as tmp:diff --git a/docs/AI_SETUP.md b/docs/AI_SETUP.mdindex 83aa5533..25e0ccb6 100644--- a/docs/AI_SETUP.md+++ b/docs/AI_SETUP.md@@ -54,7 +54,8 @@ python3 c/coli setup --list --json # every model against this machine`cpu.features`, `gpu.vulkan` (the Vulkan device the engine would use, with its`type`, `integrated` or `discrete`, and `budget_bytes` or `device_local_bytes`),`gpu.vulkan_icd` (a driver manifest found under the home folder, typical on-WSL) and `gpu.nvidia` (from nvidia-smi).+WSL) and `gpu.nvidia` (from nvidia-smi, each card with its `compute_cap`,+for example `7.0`, or null when nothing reported it).`setup --list --json` returns one object per model:@@ -84,15 +85,10 @@ Non-interactive, with the model the user chose:python3 c/coli setup --yes --model qwen36-35b --no-start```-What it does, in order: detects the hardware, picks the engine build (CUDA-for an NVIDIA card when the CUDA toolkit is installed and the engine has a-CUDA path, else Vulkan when a Vulkan GPU answered and the Vulkan headers and-`glslc` are installed, else the CPU; on an integrated GPU, which shares the-CPU's RAM, Vulkan only for the engines measured faster there, today Qwen3.6,-Qwen3-Coder and Qwen3.8, unless `--backend vulkan` asks for it), builds or-fetches the engine, downloads-the model with resume, runs the planner on the files, and writes the run-configuration. It prints each step.+What it does, in order: detects the hardware, picks the engine build (see+[How the engine build is chosen](#how-the-engine-build-is-chosen)), builds or+fetches the engine, downloads the model with resume, runs the planner on the+files, and writes the run configuration. It prints each step.The download can take hours. If your command runner has a time limit, startit detached and poll the status instead of waiting:@@ -129,7 +125,7 @@ rerun the same setup command.| `--model ID` | the model to install (ids from `--list`) || `--model-dir DIR` | use a model already on disk instead of downloading || `--dir DIR` | where models are downloaded (default `~/colibri-models`) |-| `--backend auto\|cpu\|vulkan\|cuda` | force the engine build; `--no-gpu` is `--backend cpu` |+| `--backend auto\|cpu\|vulkan\|cuda` | force the engine build (`auto`: see below); `--no-gpu` is `--backend cpu` || `--host H`, `--port N` | where the server listens (default `127.0.0.1:8000`) || `--no-start` | stop after writing the configuration || `--background` | start the server detached at the end |@@ -140,6 +136,48 @@ rerun the same setup command.| `--no-verify` | skip the checksums of downloaded files || `--json` | machine-readable result (implies `--yes` and a background start) |+### How the engine build is chosen++With `--backend auto` (the default):++1. **CUDA**, for an NVIDIA card, when all of these hold:+ - the engine has a CUDA path on Linux: Qwen3.6 (with Qwen3-Coder and+ Qwen3.8-27B), Qwen3.8 Flash Next, GLM-5.2/5.3 (the `colibri` engine; not+ GLM-5.3-Flash), Kimi K3, Inkling and DeepSeek V4 Flash;+ - a CUDA toolkit (`nvcc`) is installed;+ - the toolkit builds for every NVIDIA card here. The card's compute+ capability comes from `nvidia-smi` (`gpu.nvidia[].compute_cap` in+ `setup_hw.py --json`, for example `7.0` for a V100). The toolkit's list+ comes from `nvcc --list-gpu-arch`, or from its version for an nvcc too+ old to answer. CUDA 13 dropped Maxwell, Pascal and Volta (compute 5.x to+ 7.2), and Blackwell (compute 12.0) needs CUDA 12.8 or newer;+ - the engine's own CUDA code supports the card and the toolkit.+ DeepSeek V4 Flash needs compute 6.0 or newer and CUDA 12.0 or newer, and+ below CUDA 12.8 the setup builds it with `NO_TC=1`.+2. **Vulkan**, when a Vulkan GPU answered and the Vulkan headers and `glslc`+ are installed. On an integrated GPU, which shares the CPU's RAM, only the+ engines measured faster there (today Qwen3.6, Qwen3-Coder and Qwen3.8)+ use it, unless `--backend vulkan` asks for it.+3. **The CPU** otherwise.++When the toolkit cannot build for the card, the setup does not try. It says+why and what to install, and takes the next backend:++```+Engine: qwen36 with VULKAN (the CUDA 13.0 toolkit cannot build for the Tesla V100-SXM2-16GB (compute 7.0, dropped in CUDA 13): using Vulkan; install a CUDA 12.x toolkit for the CUDA path)+```++With `--backend cuda` the same check stops the setup before any build, with+the same reason. `--backend auto` then takes the next backend.++If a build still fails, the setup prints the end of the log and the log's+path, then moves to the next backend: CUDA, then Vulkan, then the CPU. With+someone at the terminal it asks first; with `--yes` it goes ahead. A setup+resumed later does not retry a backend whose build failed. A failed CPU build+stops the setup. Each backend has its own log, `logs/build-cuda.log`,+`logs/build-vulkan.log` or `logs/build-cpu.log`, so the log of the failed+build is still there after the fallback.+### When a GPU package is missingIf the machine has a GPU that the build cannot use yet, the setup continues@@ -225,7 +263,7 @@ Linux, `~/Library/Application Support/colibri` on macOS,|---|---|| `setup.json` | the run configuration: model, engine, backend, environment, launcher arguments, URLs || `install-state.json` | phase and progress of the current or last install |-| `logs/serve.log`, `logs/install.log`, `logs/build.log` | logs |+| `logs/serve.log`, `logs/install.log`, `logs/build-<backend>.log` | logs (one build log per backend: `cuda`, `vulkan`, `cpu`) || `runtime/` | a prebuilt release, when there is no compiler |The model folder holds `.colibri-download.json`, which lists the files and@@ -242,6 +280,8 @@ says when the download is complete. Partial files end in `.part`.| `checksum mismatch` | the partial file was removed; rerun || `needs N GB free for the download` | pass `--dir` with a folder on a bigger disk || `the published release ... predates <model>` | there is no compiler and the last release cannot run that model: install the compiler (the message names the command) or pick another model |+| `... toolkit cannot build for the <card> (compute X.Y, ...)` | the setup took Vulkan or the CPU; for CUDA, install the toolkit the line names and rerun with `--reconfigure` |+| `the <engine> CUDA build failed (full log: ...)` | the setup moved to the next backend; the log says why the CUDA build failed || `Already set up: ...` but the user wants another model | `--reconfigure`, or `--model ID` || `server.state` stays `loading` | `coli logs -n 50`; large models take minutes to load || `plan warning: RAM budget cannot hold one expert slot` | the model does not fit in the free RAM: close programs or choose a smaller model |diff --git a/docs/quickstart.md b/docs/quickstart.mdindex 3b532047..4776dda8 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -40,7 +40,12 @@ Both run `coli setup`, which does the rest:prebuilt one (CPU) when there is no compiler. If a package is missing foryour GPU it prints the exact command to install it and carries on with theCPU; nothing is installed system-wide without you. Run the setup again once- you have installed it, and it rebuilds the engine for the GPU.+ you have installed it, and it rebuilds the engine for the GPU. CUDA is used+ only when the installed CUDA toolkit can build for your card: CUDA 13, for+ example, no longer builds for Maxwell, Pascal or Volta cards (a V100), so+ there the setup says so and uses Vulkan. If a GPU build fails anyway, it+ moves to the next one (CUDA, then Vulkan, then the CPU) and tells you where+ the build log is.4. **Downloads the model** with progress and resume. Interrupt it whenever youlike: running it again continues where it stopped.5. **Starts colibri** and opens the dashboard in your browser, and prints the@@ -98,7 +103,8 @@ download through Windows' `curl.exe` into the same folder.Useful options (`c/coli setup --help` lists them all): `--yes` takes everydefault without asking, `--model ID` picks a model (`--list` shows the idsagainst your machine), `--dir DIR` puts the models elsewhere, `--no-gpu` keeps-everything on the CPU, `--model-dir DIR` uses a model you already have.+everything on the CPU, `--backend vulkan` (or `cuda`) picks the GPU path+yourself, `--model-dir DIR` uses a model you already have.The rest of this page is the same thing done by hand, step by step.diff --git a/start-here.sh b/start-here.shindex a721e114..c11def43 100755--- a/start-here.sh+++ b/start-here.sh@@ -13,6 +13,7 @@# ./start-here.sh --model qwen3-coder-30b a specific model# ./start-here.sh --reconfigure choose another model# ./start-here.sh --no-gpu CPU only+# ./start-here.sh --backend vulkan the GPU through Vulkan rather than CUDA# Stop: Ctrl+C in this terminal, or `c/coli stop` from another one.# The engine build itself is c/setup.sh, unchanged.here=$(cd "$(dirname "$0")" && pwd)