Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

setup: hardware detection, model catalog, resumable downloads

JustVugg018831673f31
diff --git a/c/setup_catalog.py b/c/setup_catalog.py
new file mode 100644
index 00000000..240a367b
--- /dev/null
+++ b/c/setup_catalog.py
@@ -0,0 +1,277 @@
+#!/usr/bin/env python3
+"""Ready-to-run downloads for the one-step setup, and which of them fit a machine.
+
+family_registry.py knows every engine and how to plan a model it can see on
+disk. It has no notion of a model that is not downloaded yet: where to fetch it,
+how big it is, how much RAM it needs before its shards exist to be measured.
+That is this table. Each entry names a registry family, so the engine, build
+target and accelerator support come from the registry, never from here
+(tests/test_setup_catalog.py holds the two together).
+
+Only checkpoints that run straight after a plain download are listed: a
+pre-converted colibri container, or an official checkpoint the engine reads
+natively. Models that need a conversion (GLM-5.3-Flash, OLMoE, Qwen3.8-27B) or a
+post-download step with third-party packages (DeepSeek V4.1 Flash) stay in the
+README's manual path.
+
+Sizes are the repository listings (with the excludes applied), in GB of 10^9
+bytes, checked against the Hugging Face API on 2026-10-02. The RAM figures come
+from the measurements quoted in README.md and the per-model docs:
+
+- ram_min_gb: the always-resident weights (the dense part) plus the smallest
+ expert cache the engine runs with, plus a little for the operating system.
+ Below it the model does not start or swaps.
+- ram_good_gb: where it runs as the docs measured it: the whole expert set in
+ RAM for the small models, a comfortable cache for the large ones.
+
+After the download, `coli setup` runs the real planner (resource_plan.py) on the
+files, which is the authority; these numbers only decide what to offer.
+"""
+import json
+import os
+from dataclasses import dataclass, field, fields
+
+GB = 1_000_000_000
+
+
+@dataclass(frozen=True)
+class CatalogModel:
+ id: str
+ family: str # family_registry id
+ name: str
+ repo: str
+ disk_gb: float
+ ram_min_gb: float
+ ram_good_gb: float
+ dense_gb: float # always-resident part, for the "what fits" line
+ rank: int # higher = more capable
+ size_class: str # "small": fits in RAM on a normal PC; "large": streams from the SSD
+ summary: str
+ revision: str = "main"
+ include: tuple = ()
+ exclude: tuple = ()
+ modality: str = "text"
+ license_note: str = ""
+ # (tool under tools/ run with the model folder, the file it creates)
+ post_install: tuple = ()
+ # The first published release whose prebuilt engines run this checkpoint.
+ # Older release archives predate the engine support; build from source then.
+ prebuilt_since: str = "1.12.1"
+ doc: str = ""
+ notes: tuple = field(default_factory=tuple)
+
+
+CATALOG = (
+ CatalogModel(
+ id="qwen36-35b", family="qwen36", name="Qwen3.6-35B-A3B",
+ repo="Kreuzzelg/qwen36-35b-a3b-colibri-i4-gs64", disk_gb=23.1,
+ # docs/qwen36.md: peak RSS 17 GB with every expert cached (cap 256);
+ # the minimum follows the same engine's measured 6.5 GB at 32 experts/layer.
+ ram_min_gb=10, ram_good_gb=20, dense_gb=3.5, rank=3, size_class="small",
+ summary="general chat with thinking, tools and images; int4-gs64 container",
+ doc="docs/qwen36.md"),
+ CatalogModel(
+ id="qwen3-coder-30b", family="qwen36", name="Qwen3-Coder-30B-A3B",
+ repo="Justvugg/Qwen3-Coder-30B-A3B-colibri-int4", disk_gb=19.4,
+ # docs/qwen36.md: 6.5 GB resident at 32 experts/layer, 15.2 GB with all 128.
+ ram_min_gb=8, ram_good_gb=18, dense_gb=3.6, rank=2, size_class="small",
+ summary="coding model with tool calls, no thinking; int4-gs64 container",
+ prebuilt_since="1.12.2", doc="docs/qwen36.md#qwen3-coder-30b-a3b"),
+ CatalogModel(
+ id="deepseek-v4-flash-reap", family="deepseek_v4", name="DeepSeek V4 Flash REAP 150B",
+ repo="puwaer/DeepSeek-V4-Flash-0731-reap-150b", disk_gb=84.7,
+ ram_min_gb=16, ram_good_gb=32, dense_gb=7.9, rank=4, size_class="large",
+ summary="pruned DeepSeek V4 Flash (132 of 256 experts), official fp4/fp8 weights",
+ doc="docs/deepseek-v4.md"),
+ CatalogModel(
+ id="deepseek-v4-flash", family="deepseek_v4", name="DeepSeek V4 Flash",
+ repo="deepseek-ai/DeepSeek-V4-Flash-0731", disk_gb=166.9,
+ ram_min_gb=16, ram_good_gb=32, dense_gb=7.9, rank=5, size_class="large",
+ summary="284B, official checkpoint, no conversion",
+ doc="docs/deepseek-v4.md"),
+ CatalogModel(
+ id="qwen38-flash-next", family="qwen38", name="Qwen3.8-Flash-Next",
+ repo="Qwen/Qwen3.8-Flash-Next-FP8", revision="bcd9f01ddc9cff2316eb84281bebcd5b058bddce",
+ disk_gb=185.6, ram_min_gb=24, ram_good_gb=32, dense_gb=8.0, rank=5, size_class="large",
+ summary="125B + 51B n-gram, official FP8 checkpoint (pinned revision)",
+ doc="docs/qwen38.md"),
+ CatalogModel(
+ id="mimo-v2.6-flash", family="mimo", name="MiMo-V2.6 Flash",
+ repo="XiaomiMiMo/MiMo-V2.6-Flash-MOPD", disk_gb=171.8,
+ # docs/mimo.md: 30.1 GB resident with 32 experts cached per layer, 49.8 GB with 64.
+ ram_min_gb=32, ram_good_gb=52, dense_gb=24.0, rank=6, size_class="large",
+ summary="309B with vision and tools, official checkpoint",
+ # The engine never loads these three (docs/mimo.md, measured on Pro,
+ # the same engine and layout).
+ exclude=("dflash/*", "audio_tokenizer/*", "model_mtp.safetensors"),
+ prebuilt_since="1.12.2", doc="docs/mimo.md"),
+ CatalogModel(
+ id="glm-5.2", family="glm", name="GLM-5.2",
+ repo="mastouri/GLM-5.2-colibri-int4-g64-with-int8-mtp", disk_gb=429.3,
+ ram_min_gb=16, ram_good_gb=24, dense_gb=9.9, rank=8, size_class="large",
+ summary="744B, the reference model; int4-gs64 with the int8 MTP head",
+ doc="README.md#2-get-the-model"),
+ CatalogModel(
+ id="glm-5.3", family="glm", name="GLM-5.3",
+ repo="Justvugg/GLM-5.3-colibri-int4-g64", disk_gb=419.3,
+ ram_min_gb=16, ram_good_gb=24, dense_gb=9.9, rank=8, size_class="large",
+ summary="744B, int4-gs64, no MTP head (no speculative decoding)",
+ doc="README.md#2-get-the-model"),
+ CatalogModel(
+ id="mimo-v2.6-pro", family="mimo", name="MiMo-V2.6 Pro",
+ repo="XiaomiMiMo/MiMo-V2.6-Pro-MOPD", disk_gb=563.6,
+ ram_min_gb=54, ram_good_gb=64, dense_gb=32.4, rank=9, size_class="large",
+ summary="1.02T with vision and tools, official checkpoint",
+ exclude=("dflash/*", "audio_tokenizer/*", "model_mtp.safetensors"),
+ prebuilt_since="1.12.2", doc="docs/mimo.md#pro"),
+ CatalogModel(
+ id="inkling", family="inkling", name="Inkling",
+ repo="nbeerbower/Inkling-colibri-int4", disk_gb=514.1,
+ # README: ~120 GB of RAM as downloaded (bf16 dense, 49.4 GB resident);
+ # the 25 GB path needs docs/inkling.md's dense conversion first.
+ ram_min_gb=120, ram_good_gb=128, dense_gb=49.4, rank=9, size_class="large",
+ summary="975B, int4 experts with bf16 dense weights",
+ doc="docs/inkling.md"),
+ CatalogModel(
+ id="kimi-k3", family="kimi", name="Kimi K3",
+ repo="moonshotai/Kimi-K3", disk_gb=1561.0,
+ ram_min_gb=32, ram_good_gb=64, dense_gb=20.0, rank=10, size_class="large",
+ summary="2.8T, original checkpoint with native MXFP4 experts",
+ # The repo ships tiktoken.model only; the engines read tokenizer.json.
+ post_install=(("k3_tokenizer", "tokenizer.json"),),
+ doc="docs/kimi_k3.md"),
+ CatalogModel(
+ id="qwen-image-2.1", family="qwen_image", name="Qwen-Image-2.1",
+ repo="Qwen/Qwen-Image-2.1", disk_gb=33.1,
+ # docs/qwen-image.md: 9.0 GB peak for one 768x512 image with the text
+ # encoder loaded per prompt, 16.0 GB with everything resident.
+ ram_min_gb=12, ram_good_gb=18, dense_gb=8.5, rank=1, size_class="small",
+ modality="image", summary="text to image (pictures, not chat)",
+ license_note="Qwen Research License: non-commercial use only",
+ prebuilt_since="1.12.2", doc="docs/qwen-image.md"),
+)
+
+
+def catalog():
+ """The built-in entries, plus any from the JSON list COLI_SETUP_CATALOG names:
+ a mirror, a private repository, or a test fixture served by a fake hub. An
+ extra entry with a built-in id replaces it."""
+ entries = {entry.id: entry for entry in CATALOG}
+ path = os.environ.get("COLI_SETUP_CATALOG")
+ if path:
+ with open(path, encoding="utf-8") as handle:
+ extra = json.load(handle)
+ known = {f.name for f in fields(CatalogModel)}
+ for item in extra if isinstance(extra, list) else []:
+ values = {k: tuple(v) if isinstance(v, list) else v
+ for k, v in item.items() if k in known}
+ entry = CatalogModel(**values)
+ entries[entry.id] = entry
+ return tuple(entries.values())
+
+
+def by_id(model_id):
+ for entry in catalog():
+ if entry.id == model_id:
+ return entry
+ raise KeyError(model_id)
+
+
+def version_tuple(text):
+ parts = []
+ for piece in str(text or "").lstrip("v").split("."):
+ digits = "".join(ch for ch in piece if ch.isdigit())
+ parts.append(int(digits) if digits else 0)
+ return tuple((parts + [0, 0, 0])[:3])
+
+
+def platform_supported(entry, os_name, machine):
+ """Engine builds the Makefile itself refuses (COLI_V4_SUPPORTED)."""
+ machine = (machine or "").lower()
+ if entry.family == "deepseek_v4":
+ x86 = machine in ("x86_64", "amd64")
+ arm = machine in ("aarch64", "arm64")
+ return (x86 and os_name in ("linux", "win32")) or (arm and os_name in ("linux", "darwin"))
+ return True
+
+
+def assess(entry, ram_total, disk_free, *, os_name="linux", machine="x86_64",
+ already_downloaded=0):
+ """One entry against one machine. Returns (status, reason).
+
+ status is one of: good, tight, needs-ram, needs-disk, unsupported."""
+ if not platform_supported(entry, os_name, machine):
+ return "unsupported", f"no {entry.family} engine for {os_name}/{machine}"
+ need_disk = max(0.0, entry.disk_gb * GB * 1.02 + 2 * GB - (already_downloaded or 0))
+ if ram_total is not None and ram_total < entry.ram_min_gb * GB:
+ return "needs-ram", (f"needs {entry.ram_min_gb:g} GB of RAM "
+ f"(dense part {entry.dense_gb:g} GB plus the expert cache); "
+ f"this machine has {ram_total / GB:.1f} GB")
+ if disk_free is not None and disk_free < need_disk:
+ return "needs-disk", (f"needs {need_disk / GB:.0f} GB free for the download; "
+ f"{disk_free / GB:.0f} GB free there")
+ if ram_total is not None and ram_total < entry.ram_good_gb * GB:
+ return "tight", (f"runs with a small expert cache (needs {entry.ram_min_gb:g} GB, "
+ f"runs best with {entry.ram_good_gb:g} GB)")
+ if entry.size_class == "small":
+ return "good", f"the whole model fits in RAM ({entry.ram_good_gb:g} GB)"
+ return "good", (f"dense part {entry.dense_gb:g} GB stays in RAM, the experts "
+ "stream from the SSD (a fast NVMe drive makes it faster)")
+
+
+def recommend(ram_total, disk_free, *, os_name="linux", machine="x86_64",
+ downloaded=None, include_images=True):
+ """Every catalog entry assessed, the default marked.
+
+ The default is the most capable model that runs from RAM on this machine;
+ if no small model fits, the smallest download among the large ones that do.
+ A 20 GB download that answers at several tokens per second is the better
+ first experience than a 400 GB one at a fraction of a token; the larger
+ ones are listed right below it."""
+ downloaded = downloaded or {}
+ rows = []
+ for entry in catalog():
+ if entry.modality != "text" and not include_images:
+ continue
+ status, reason = assess(entry, ram_total, disk_free, os_name=os_name, machine=machine,
+ already_downloaded=downloaded.get(entry.id, 0))
+ rows.append({"entry": entry, "status": status, "reason": reason,
+ "fits": status in ("good", "tight"), "recommended": False})
+ text = [r for r in rows if r["fits"] and r["entry"].modality == "text"]
+ pick = None
+ for wanted in ("good", "tight"):
+ small = [r for r in text if r["entry"].size_class == "small" and r["status"] == wanted]
+ if small:
+ pick = max(small, key=lambda r: r["entry"].rank)
+ break
+ if pick is None:
+ large = [r for r in text if r["entry"].size_class == "large"]
+ if large:
+ pick = min(large, key=lambda r: r["entry"].disk_gb)
+ if pick is not None:
+ pick["recommended"] = True
+ fitting = [r for r in rows if r["fits"]]
+ fitting.sort(key=lambda r: (not r["recommended"], r["entry"].modality != "text",
+ r["entry"].disk_gb))
+ others = [r for r in rows if not r["fits"]]
+ others.sort(key=lambda r: r["entry"].disk_gb)
+ return fitting + others
+
+
+def as_dict(row):
+ """A recommendation row as plain data (the MCP server and --json)."""
+ entry = row["entry"]
+ return {
+ "id": entry.id, "name": entry.name, "family": entry.family, "repo": entry.repo,
+ "revision": entry.revision, "download_gb": entry.disk_gb,
+ "ram_min_gb": entry.ram_min_gb, "ram_good_gb": entry.ram_good_gb,
+ "dense_gb": entry.dense_gb, "kind": entry.modality,
+ "runs": "from RAM" if entry.size_class == "small" else "streams experts from the SSD",
+ "summary": entry.summary, "status": row["status"], "fits": row["fits"],
+ "reason": row["reason"], "recommended": row["recommended"],
+ "license_note": entry.license_note, "doc": entry.doc,
+ }
+
+
+FITS_EXPLAINED = ("fits = the always-resident weights (the dense part) plus a minimum "
+ "expert cache fit in RAM, and the download fits on the disk")
diff --git a/c/setup_download.py b/c/setup_download.py
new file mode 100644
index 00000000..118c4db9
--- /dev/null
+++ b/c/setup_download.py
@@ -0,0 +1,447 @@
+#!/usr/bin/env python3
+"""Resumable Hugging Face downloads for the one-step setup, standard library only.
+
+A model is hundreds of files and up to a few hundred GB, and the connection will
+drop. The rules that make a rerun continue instead of starting over:
+
+- every file is written to `<name>.part` and renamed only once its size and
+ hash check out, so a name without `.part` is always a whole file;
+- a rerun asks for `Range: bytes=<what is there>-` and appends; a server that
+ answers 200 instead of 206 restarts that file from zero, never appends a
+ second copy;
+- the hash is computed while the bytes arrive (the prefix already on disk is
+ read once when resuming), so the check costs no second pass over the model;
+- `.colibri-download.json` in the model folder records the repository, the
+ revision and the file list, and says when the folder is complete.
+
+The token, when there is one (HF_TOKEN or the file `hf auth login` writes), is
+sent as an unredirected header: the resolve URL redirects to a CDN host, and the
+token must not follow it there.
+
+On WSL the Linux side's network can be far slower than Windows' on the same
+machine (63 KB/s against 3.3 MB/s, measured). `probe_*` time a short ranged
+request on both sides, and `download_file` can hand the transfer to Windows'
+own curl.exe, writing into the same folder through its \\\\wsl.localhost path.
+"""
+import fnmatch
+import hashlib
+import http.client
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+MANIFEST = ".colibri-download.json"
+CHUNK = 1 << 20
+USER_AGENT = "colibri-setup"
+
+
+class DownloadError(RuntimeError):
+ pass
+
+
+def endpoint():
+ return (os.environ.get("HF_ENDPOINT") or "https://huggingface.co").rstrip("/")
+
+
+def hf_token():
+ for name in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
+ if os.environ.get(name):
+ return os.environ[name].strip()
+ home = os.environ.get("HF_HOME") or os.path.join(os.path.expanduser("~"), ".cache", "huggingface")
+ try:
+ with open(os.path.join(home, "token"), encoding="utf-8") as handle:
+ token = handle.read().strip()
+ return token or None
+ except OSError:
+ return None
+
+
+def _request(url, token=None, headers=None):
+ request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, **(headers or {})})
+ if token:
+ # Unredirected: the token reaches huggingface.co, never the CDN it redirects to.
+ request.add_unredirected_header("Authorization", f"Bearer {token}")
+ return request
+
+
+def file_url(repo, revision, path, base=None):
+ return (f"{base or endpoint()}/{repo}/resolve/{urllib.parse.quote(revision, safe='')}/"
+ f"{urllib.parse.quote(path)}")
+
+
+def _matches(path, patterns):
+ return any(fnmatch.fnmatch(path, pattern) for pattern in patterns)
+
+
+def list_repo_files(repo, revision="main", *, include=(), exclude=(), token=None,
+ base=None, opener=None, timeout=60):
+ """Files of a model repository: [{path, size, sha256, git_oid}].
+
+ sha256 is the LFS object id (the content hash) when the file is in LFS;
+ git_oid is git's blob id otherwise. Follows the Link pagination the API
+ uses for long listings."""
+ opener = opener or urllib.request.urlopen
+ url = (f"{base or endpoint()}/api/models/{repo}/tree/{urllib.parse.quote(revision, safe='')}"
+ "?recursive=true")
+ files = []
+ seen = 0
+ while url:
+ try:
+ with opener(_request(url, token), timeout=timeout) as response:
+ entries = json.loads(response.read().decode("utf-8"))
+ link = response.headers.get("Link") or ""
+ except urllib.error.HTTPError as error:
+ error.close()
+ if error.code in (401, 403):
+ raise DownloadError(f"{repo}: access denied (HTTP {error.code}). If the model is "
+ "gated, accept its terms on huggingface.co and set HF_TOKEN.")
+ if error.code == 404:
+ raise DownloadError(f"{repo}@{revision}: not found on {base or endpoint()}")
+ raise DownloadError(f"{repo}: listing failed (HTTP {error.code})")
+ except (urllib.error.URLError, OSError, ValueError) as error:
+ raise DownloadError(f"{repo}: cannot list files ({error})")
+ for entry in entries:
+ if entry.get("type") != "file":
+ continue
+ path = entry.get("path", "")
+ if include and not _matches(path, include):
+ continue
+ if exclude and _matches(path, exclude):
+ continue
+ lfs = entry.get("lfs") or {}
+ files.append({"path": path, "size": int(entry.get("size") or 0),
+ "sha256": lfs.get("oid"),
+ "git_oid": None if lfs else entry.get("oid")})
+ seen += 1
+ match = re.search(r'<([^>]+)>;\s*rel="next"', link)
+ url = match.group(1) if match else None
+ if seen > 1000:
+ raise DownloadError(f"{repo}: listing does not end")
+ return files
+
+
+def safe_join(root, relative):
+ """root/relative, refusing anything that would land outside root."""
+ parts = [p for p in relative.replace("\\", "/").split("/") if p not in ("", ".")]
+ if not parts or any(p == ".." for p in parts) or re.match(r"^[A-Za-z]:", parts[0]):
+ raise DownloadError(f"unsafe path in the repository listing: {relative!r}")
+ return os.path.join(root, *parts)
+
+
+def _hasher(spec):
+ """A running hash for the expected digest: sha256 for LFS files, git's blob
+ sha1 for the small files git stores itself."""
+ if spec.get("sha256"):
+ return hashlib.sha256(), spec["sha256"].lower()
+ if spec.get("git_oid"):
+ sha1 = hashlib.sha1()
+ sha1.update(b"blob %d\0" % spec["size"])
+ return sha1, spec["git_oid"].lower()
+ return None, None
+
+
+def _feed_prefix(hasher, path, length):
+ with open(path, "rb") as handle:
+ remaining = length
+ while remaining > 0:
+ block = handle.read(min(CHUNK * 8, remaining))
+ if not block:
+ break
+ hasher.update(block)
+ remaining -= len(block)
+
+
+def _content_range_start(value):
+ match = re.match(r"bytes\s+(\d+)-", value or "")
+ return int(match.group(1)) if match else None
+
+
+def download_file(url, dest, spec, *, token=None, progress=None, opener=None,
+ retries=5, timeout=60, verify=True, backoff=(1, 2, 4, 8, 15)):
+ """Fetch one file to `dest`, resuming `dest.part`. Returns "present" when it
+ was already complete, "downloaded" otherwise. `progress(done, total)` is
+ called as bytes land."""
+ opener = opener or urllib.request.urlopen
+ size = int(spec["size"])
+ if os.path.exists(dest) and os.path.getsize(dest) == size:
+ return "present"
+ os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
+ part = dest + ".part"
+ have = os.path.getsize(part) if os.path.exists(part) else 0
+ if have > size:
+ os.remove(part)
+ have = 0
+ hasher, expected = _hasher(spec) if verify else (None, None)
+ if hasher is not None and have:
+ _feed_prefix(hasher, part, have)
+ attempt = 0
+ while have < size:
+ headers = {"Range": f"bytes={have}-"} if have else {}
+ try:
+ with opener(_request(url, token, headers), timeout=timeout) as response:
+ status = getattr(response, "status", None) or response.getcode()
+ if have and status == 206:
+ start = _content_range_start(response.headers.get("Content-Range"))
+ if start is not None and start != have:
+ raise DownloadError(f"server resumed at byte {start}, expected {have}")
+ elif have:
+ # 200 to a ranged request: the server sent the whole file.
+ have = 0
+ hasher, expected = _hasher(spec) if verify else (None, None)
+ with open(part, "ab" if have else "wb") as out:
+ while True:
+ block = response.read(CHUNK)
+ if not block:
+ break
+ out.write(block)
+ if hasher is not None:
+ hasher.update(block)
+ have += len(block)
+ if progress:
+ progress(have, size)
+ if have > size:
+ break
+ if have < size:
+ raise ConnectionError(f"connection closed at {have} of {size} bytes")
+ except urllib.error.HTTPError as error:
+ error.close()
+ if error.code == 416 and have >= size:
+ break
+ if error.code in (401, 403, 404):
+ raise DownloadError(f"{url}: HTTP {error.code}")
+ if attempt >= retries:
+ raise DownloadError(f"{url}: HTTP {error.code} after {attempt + 1} attempts")
+ except DownloadError:
+ raise
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as error:
+ if attempt >= retries:
+ raise DownloadError(f"{os.path.basename(dest)}: {error} (rerun to continue "
+ f"from {have} of {size} bytes)")
+ else:
+ continue
+ attempt += 1
+ time.sleep(backoff[min(attempt - 1, len(backoff) - 1)])
+ have = os.path.getsize(part) if os.path.exists(part) else 0
+ if hasher is not None:
+ hasher, expected = _hasher(spec)
+ if have:
+ _feed_prefix(hasher, part, have)
+ if have != size:
+ os.remove(part)
+ raise DownloadError(f"{os.path.basename(dest)}: got {have} bytes, expected {size}; "
+ "the partial file was removed, rerun to fetch it again")
+ if hasher is not None and hasher.hexdigest() != expected:
+ os.remove(part)
+ raise DownloadError(f"{os.path.basename(dest)}: checksum mismatch; the partial file "
+ "was removed, rerun to fetch it again")
+ os.replace(part, dest)
+ return "downloaded"
+
+
+def verify_file(path, spec):
+ """Size and hash of a file someone else wrote (curl.exe)."""
+ if not os.path.exists(path) or os.path.getsize(path) != int(spec["size"]):
+ return False
+ hasher, expected = _hasher(spec)
+ if hasher is None:
+ return True
+ _feed_prefix(hasher, path, int(spec["size"]))
+ return hasher.hexdigest() == expected
+
+
+# ---------------------------------------------------------------- WSL: Windows' curl.exe
+
+
+def windows_curl():
+ """curl.exe on the Windows side, reachable from WSL through interop."""
+ for candidate in (shutil.which("curl.exe"), "/mnt/c/Windows/System32/curl.exe",
+ "/mnt/c/WINDOWS/system32/curl.exe"):
+ if candidate and os.path.isfile(candidate):
+ return candidate
+ return None
+
+
+def wsl_windows_path(path):
+ try:
+ out = subprocess.run(["wslpath", "-w", os.path.abspath(path)], capture_output=True,
+ text=True, timeout=10).stdout.strip()
+ return out or None
+ except (OSError, subprocess.SubprocessError):
+ return None
+
+
+def probe_throughput(url, *, token=None, max_bytes=4 << 20, max_seconds=8.0, opener=None):
+ """Bytes per second for a short ranged GET, or None when it failed."""
+ opener = opener or urllib.request.urlopen
+ start = time.monotonic()
+ got = 0
+ try:
+ request = _request(url, token, {"Range": f"bytes=0-{max_bytes - 1}"})
+ with opener(request, timeout=max_seconds + 5) as response:
+ first = time.monotonic()
+ while got < max_bytes and time.monotonic() - start < max_seconds:
+ block = response.read(64 * 1024)
+ if not block:
+ break
+ got += len(block)
+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError):
+ return None
+ elapsed = max(time.monotonic() - (first if got else start), 1e-3)
+ return got / elapsed if got else None
+
+
+def parse_curl_speed(text):
+ try:
+ return float((text or "").strip().split()[-1].replace(",", "."))
+ except (ValueError, IndexError):
+ return None
+
+
+def probe_throughput_windows(url, curl, *, token=None, max_bytes=4 << 20, max_seconds=8):
+ cmd = [curl, "-s", "-L", "-r", f"0-{max_bytes - 1}", "--max-time", str(int(max_seconds)),
+ "-o", "NUL", "-w", "%{speed_download}", url]
+ if token:
+ cmd[1:1] = ["-H", f"Authorization: Bearer {token}"]
+ try:
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=max_seconds + 20).stdout
+ except (OSError, subprocess.SubprocessError):
+ return None
+ speed = parse_curl_speed(out)
+ return speed if speed and speed > 0 else None
+
+
+def download_file_windows(url, dest, spec, curl, *, token=None, progress=None, verify=True):
+ """The same contract as download_file, with Windows' curl.exe doing the transfer
+ into the same `.part` file (curl's own `-C -` resumes it)."""
+ size = int(spec["size"])
+ if os.path.exists(dest) and os.path.getsize(dest) == size:
+ return "present"
+ os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
+ part = dest + ".part"
+ if os.path.exists(part) and os.path.getsize(part) > size:
+ os.remove(part)
+ if not (os.path.exists(part) and os.path.getsize(part) == size):
+ target = wsl_windows_path(part)
+ if not target:
+ raise DownloadError("wslpath could not translate the target folder for curl.exe")
+ cmd = [curl, "-L", "--fail", "--retry", "5", "--retry-delay", "3", "-s", "-S",
+ "-C", "-", "-o", target, url]
+ if token:
+ cmd[1:1] = ["-H", f"Authorization: Bearer {token}"]
+ with tempfile.TemporaryFile("w+", encoding="utf-8", errors="replace") as errors, \
+ subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=errors) as process:
+ while process.poll() is None:
+ time.sleep(1.0)
+ if progress and os.path.exists(part):
+ progress(os.path.getsize(part), size)
+ errors.seek(0)
+ err = errors.read()
+ if process.returncode != 0 and not (os.path.exists(part) and os.path.getsize(part) == size):
+ raise DownloadError(f"curl.exe failed ({process.returncode}): {err.strip()[:200]} "
+ "(rerun to continue)")
+ if progress:
+ progress(os.path.getsize(part), size)
+ if os.path.getsize(part) != size or (verify and not verify_file(part, spec)):
+ os.remove(part)
+ raise DownloadError(f"{os.path.basename(dest)}: size or checksum mismatch after curl.exe; "
+ "removed, rerun to fetch it again")
+ os.replace(part, dest)
+ return "downloaded"
+
+
+# ---------------------------------------------------------------- the repository
+
+
+def read_manifest(model_dir):
+ try:
+ with open(os.path.join(model_dir, MANIFEST), encoding="utf-8") as handle:
+ data = json.load(handle)
+ return data if isinstance(data, dict) else None
+ except (OSError, ValueError):
+ return None
+
+
+def _write_manifest(model_dir, data):
+ path = os.path.join(model_dir, MANIFEST)
+ tmp = path + ".tmp"
+ with open(tmp, "w", encoding="utf-8") as handle:
+ json.dump(data, handle, indent=1)
+ os.replace(tmp, path)
+
+
+def is_complete(model_dir):
+ """The folder holds every file the manifest lists, at its size."""
+ manifest = read_manifest(model_dir)
+ if not manifest or not manifest.get("complete"):
+ return False
+ for spec in manifest.get("files", []):
+ path = safe_join(model_dir, spec["path"])
+ if not os.path.exists(path) or os.path.getsize(path) != int(spec["size"]):
+ return False
+ return True
+
+
+def bytes_present(model_dir, files):
+ """What is already on disk for these files, whole or partial."""
+ total = 0
+ for spec in files:
+ path = safe_join(model_dir, spec["path"])
+ if os.path.exists(path) and os.path.getsize(path) == int(spec["size"]):
+ total += int(spec["size"])
+ elif os.path.exists(path + ".part"):
+ total += min(os.path.getsize(path + ".part"), int(spec["size"]))
+ return total
+
+
+def download_repo(repo, revision, model_dir, files, *, token=None, progress=None,
+ base=None, opener=None, curl=None, retries=5, verify=True):
+ """Every listed file into model_dir, small files first (so config.json and the
+ tokenizer are there early), then the shards by size. `progress(event)` gets
+ dicts with file, file_done, file_total, done, total."""
+ os.makedirs(model_dir, exist_ok=True)
+ files = sorted(files, key=lambda spec: (spec["size"] > (64 << 20), spec["size"], spec["path"]))
+ manifest = {"repo": repo, "revision": revision, "complete": False,
+ "files": [{"path": s["path"], "size": s["size"]} for s in files]}
+ _write_manifest(model_dir, manifest)
+ total = sum(int(s["size"]) for s in files)
+ done_before = 0
+ for spec in files:
+ dest = safe_join(model_dir, spec["path"])
+
+ def on_bytes(have, size, _spec=spec, _base=done_before):
+ if progress:
+ progress({"file": _spec["path"], "file_done": have, "file_total": size,
+ "done": _base + have, "total": total})
+
+ url = file_url(repo, revision, spec["path"], base)
+ if curl:
+ download_file_windows(url, dest, spec, curl, token=token, progress=on_bytes, verify=verify)
+ else:
+ download_file(url, dest, spec, token=token, progress=on_bytes, opener=opener,
+ retries=retries, verify=verify)
+ done_before += int(spec["size"])
+ on_bytes(int(spec["size"]), int(spec["size"]))
+ manifest["complete"] = True
+ manifest["completed"] = time.strftime("%Y-%m-%dT%H:%M:%S")
+ _write_manifest(model_dir, manifest)
+ return {"files": len(files), "bytes": total}
+
+
+def human_rate(bytes_per_second):
+ if not bytes_per_second:
+ return "?"
+ if bytes_per_second >= 1e6:
+ return f"{bytes_per_second / 1e6:.1f} MB/s"
+ return f"{bytes_per_second / 1e3:.0f} KB/s"
+
+
+if __name__ == "__main__":
+ sys.exit("setup_download.py is a module; run `coli setup`")
diff --git a/c/setup_hw.py b/c/setup_hw.py
new file mode 100644
index 00000000..394a1957
--- /dev/null
+++ b/c/setup_hw.py
@@ -0,0 +1,792 @@
+#!/usr/bin/env python3
+"""Hardware detection for the one-step setup (`coli setup`, the MCP server).
+
+What it answers, and nothing more: how much RAM there is, how much disk is free
+where the model would go, which CPU features the engine can use, and which GPUs
+are there (Vulkan devices with their type and memory, NVIDIA cards through
+nvidia-smi). 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
+tests exercise with mocked hardware (tests/test_setup_hw.py); the probes are
+thin and fail closed (a probe that cannot run reports nothing, never a guess).
+
+Vulkan is probed through the loader itself with ctypes, in a child process: the
+same vkEnumeratePhysicalDevices the engine calls, the same device ranking
+(discrete > integrated > virtual > other > CPU), and the device-local heap
+budget from VK_EXT_memory_budget when the driver has it. A child process,
+because a broken driver can crash the process that loads it. When the loader
+cannot be loaded, `vulkaninfo --summary` is parsed instead (names and types,
+no memory figures).
+"""
+import ctypes
+import glob
+import json
+import os
+import platform
+import re
+import shutil
+import struct
+import subprocess
+import sys
+
+HERE = os.path.dirname(os.path.realpath(__file__))
+GB = 1_000_000_000
+
+# ---------------------------------------------------------------- memory
+
+
+def memory_from_meminfo(text):
+ """{"total": bytes, "available": bytes} from /proc/meminfo text.
+
+ Missing lines come back as None rather than 0: zero would read as a
+ measurement ("no RAM free") when it is only an absence."""
+ out = {"total": None, "available": None}
+ for key, field in (("MemTotal", "total"), ("MemAvailable", "available")):
+ match = re.search(rf"^{key}:\s+(\d+)\s+kB\s*$", text or "", re.M)
+ if match:
+ out[field] = int(match.group(1)) * 1024
+ return out
+
+
+def memory_from_windows_status(total_phys, avail_phys, avail_pagefile=None):
+ """GlobalMemoryStatusEx figures. Available is the smaller of free physical
+ memory and the commit Windows can still grant (resource_plan's rule, #1375)."""
+ available = avail_phys
+ if avail_pagefile and 0 < avail_pagefile < avail_phys:
+ available = avail_pagefile
+ return {"total": int(total_phys) if total_phys else None,
+ "available": int(available) if available else None}
+
+
+def memory_from_darwin(memsize_text, vm_stat_text=""):
+ """hw.memsize plus the reclaimable pages of vm_stat (free, inactive,
+ speculative, purgeable), the engine's own definition of available."""
+ try:
+ total = int((memsize_text or "").strip())
+ except ValueError:
+ total = None
+ page_match = re.search(r"page size of (\d+) bytes", vm_stat_text or "")
+ page = int(page_match.group(1)) if page_match else 16384
+ pages = 0
+ for key in ("Pages free", "Pages inactive", "Pages speculative", "Pages purgeable"):
+ match = re.search(rf"{key}:\s+(\d+)\.", vm_stat_text or "")
+ if match:
+ pages += int(match.group(1))
+ return {"total": total, "available": pages * page if pages else None}
+
+
+def _windows_memory():
+ try:
+ from resource_plan import WINDOWS_MEMORYSTATUSEX_FIELDS
+
+ class MEMORYSTATUSEX(ctypes.Structure):
+ _fields_ = [(name, getattr(ctypes, kind))
+ for name, kind in WINDOWS_MEMORYSTATUSEX_FIELDS]
+
+ stat = MEMORYSTATUSEX(dwLength=ctypes.sizeof(MEMORYSTATUSEX))
+ kernel32 = ctypes.windll.kernel32
+ kernel32.GlobalMemoryStatusEx.argtypes = [ctypes.c_void_p]
+ kernel32.GlobalMemoryStatusEx.restype = ctypes.c_int
+ if kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)):
+ return memory_from_windows_status(stat.ullTotalPhys, stat.ullAvailPhys,
+ stat.ullAvailPageFile)
+ except (OSError, AttributeError, ImportError, ValueError):
+ pass
+ return {"total": None, "available": None}
+
+
+def detect_memory():
+ if sys.platform == "win32":
+ return _windows_memory()
+ if sys.platform == "darwin":
+ return memory_from_darwin(_run(["sysctl", "-n", "hw.memsize"]), _run(["vm_stat"]))
+ try:
+ with open("/proc/meminfo", encoding="ascii", errors="replace") as handle:
+ mem = memory_from_meminfo(handle.read(256 * 1024))
+ except OSError:
+ mem = {"total": None, "available": None}
+ # A container limit is what kills the process, whatever the host has free:
+ # resource_plan already knows how to read it.
+ try:
+ from resource_plan import memory_available
+ budget = memory_available()
+ if budget is not None:
+ mem["available"] = budget if mem["available"] is None else min(mem["available"], budget)
+ except Exception: # a malformed cgroup is reported by `coli plan`, not here
+ pass
+ return mem
+
+
+# ---------------------------------------------------------------- CPU
+
+#: The flags that change which kernels the engine compiles in (ARCH=native).
+CPU_FEATURES_OF_INTEREST = (
+ "avx2", "fma", "f16c", "avx_vnni", "avx512f", "avx512bw", "avx512_vnni",
+ "avx512_bf16", "amx_tile", "asimd", "asimddp", "i8mm", "sve",
+)
+
+
+def cpu_from_cpuinfo(text):
+ """Model name and feature flags from /proc/cpuinfo (x86 `flags`, Arm `Features`)."""
+ name = None
+ flags = set()
+ for line in (text or "").splitlines():
+ key, sep, value = line.partition(":")
+ if not sep:
+ continue
+ key = key.strip().lower()
+ if key in ("model name", "hardware", "cpu model") and not name:
+ name = value.strip() or None
+ elif key in ("flags", "features") and not flags:
+ flags = set(value.split())
+ # Linux spells the VNNI flags avx512_vnni / avx_vnni; some kernels avx512vnni.
+ if "avx512vnni" in flags:
+ flags.add("avx512_vnni")
+ features = [f for f in CPU_FEATURES_OF_INTEREST if f in flags]
+ return {"name": name, "features": features}
+
+
+#: IsProcessorFeaturePresent codes (winnt.h).
+WINDOWS_PF = {"avx2": 40, "avx512f": 41, "asimd": 43}
+
+
+def cpu_features_from_windows(is_present):
+ """`is_present(code) -> bool` is kernel32.IsProcessorFeaturePresent."""
+ return [name for name, code in WINDOWS_PF.items() if is_present(code)]
+
+
+def _windows_cpu():
+ name, features = None, []
+ try:
+ import winreg
+ key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
+ r"HARDWARE\DESCRIPTION\System\CentralProcessor\0")
+ name = winreg.QueryValueEx(key, "ProcessorNameString")[0].strip()
+ except (OSError, ImportError):
+ pass
+ try:
+ k32 = ctypes.windll.kernel32
+ k32.IsProcessorFeaturePresent.argtypes = [ctypes.c_uint]
+ k32.IsProcessorFeaturePresent.restype = ctypes.c_int
+ features = cpu_features_from_windows(lambda code: bool(k32.IsProcessorFeaturePresent(code)))
+ except (OSError, AttributeError):
+ pass
+ return {"name": name, "features": features}
+
+
+def detect_cpu():
+ if sys.platform == "win32":
+ cpu = _windows_cpu()
+ elif sys.platform == "darwin":
+ name = _run(["sysctl", "-n", "machdep.cpu.brand_string"]).strip() or None
+ feats = _run(["sysctl", "-n", "machdep.cpu.features", "machdep.cpu.leaf7_features"]).lower().split()
+ flags = set(feats)
+ if platform.machine().lower() in ("arm64", "aarch64"):
+ flags.update({"asimd", "asimddp"})
+ cpu = {"name": name, "features": [f for f in CPU_FEATURES_OF_INTEREST if f in flags]}
+ else:
+ try:
+ with open("/proc/cpuinfo", encoding="utf-8", errors="replace") as handle:
+ cpu = cpu_from_cpuinfo(handle.read(1 << 20))
+ except OSError:
+ cpu = {"name": None, "features": []}
+ cpu["arch"] = platform.machine().lower() or None
+ cpu["logical_cores"] = os.cpu_count()
+ try:
+ from resource_plan import physical_cpu_count
+ cpu["physical_cores"] = physical_cpu_count()
+ except Exception:
+ cpu["physical_cores"] = None
+ return cpu
+
+
+# ---------------------------------------------------------------- OS / WSL
+
+
+def is_wsl(osrelease_text=None, environ=None):
+ environ = os.environ if environ is None else environ
+ if environ.get("WSL_DISTRO_NAME") or environ.get("WSL_INTEROP"):
+ return True
+ if osrelease_text is None:
+ try:
+ with open("/proc/sys/kernel/osrelease", encoding="ascii", errors="replace") as handle:
+ osrelease_text = handle.read(4096)
+ except OSError:
+ return False
+ lowered = osrelease_text.lower()
+ return "microsoft" in lowered or "wsl" in lowered
+
+
+def os_release(text=None):
+ """ID and ID_LIKE from /etc/os-release, for the package hints."""
+ if text is None:
+ try:
+ with open("/etc/os-release", encoding="utf-8", errors="replace") as handle:
+ text = handle.read(65536)
+ except OSError:
+ return {}
+ out = {}
+ for line in text.splitlines():
+ key, sep, value = line.partition("=")
+ if sep and key in ("ID", "ID_LIKE", "PRETTY_NAME", "VERSION_ID"):
+ out[key] = value.strip().strip('"')
+ return out
+
+
+def detect_os():
+ info = {"platform": sys.platform, "machine": platform.machine().lower(),
+ "wsl": sys.platform.startswith("linux") and is_wsl()}
+ if sys.platform.startswith("linux"):
+ info.update({k.lower(): v for k, v in os_release().items()})
+ elif sys.platform == "win32":
+ info["pretty_name"] = f"Windows {platform.release()}"
+ elif sys.platform == "darwin":
+ info["pretty_name"] = f"macOS {platform.mac_ver()[0]}"
+ return info
+
+
+# ---------------------------------------------------------------- disk
+
+
+def existing_ancestor(path):
+ path = os.path.abspath(os.path.expanduser(path))
+ while not os.path.exists(path):
+ parent = os.path.dirname(path)
+ if parent == path:
+ break
+ path = parent
+ return path
+
+
+def disk_free(path):
+ try:
+ return shutil.disk_usage(existing_ancestor(path)).free
+ except OSError:
+ return None
+
+
+def path_warnings(path, wsl):
+ """Advice about where a model lives; the engine streams it, so it matters."""
+ warnings = []
+ absolute = os.path.abspath(os.path.expanduser(path))
+ if wsl and re.match(r"^/mnt/[a-zA-Z](/|$)", absolute):
+ warnings.append(
+ f"{absolute} is a Windows drive seen from WSL: reading it is many times "
+ "slower than the Linux disk, and the engine streams the model from it. "
+ "Keep the model in the Linux home (for example ~/colibri-models).")
+ return warnings
+
+
+def fixed_drives_from_mask(mask, drive_type):
+ """Drive roots from GetLogicalDrives' bitmask, kept when GetDriveTypeW says
+ DRIVE_FIXED (3): no network shares, no removable sticks."""
+ roots = []
+ for index in range(26):
+ if mask & (1 << index):
+ root = f"{chr(ord('A') + index)}:\\"
+ if drive_type(root) == 3:
+ roots.append(root)
+ return roots
+
+
+def windows_fixed_drives():
+ if sys.platform != "win32":
+ return []
+ try:
+ k32 = ctypes.windll.kernel32
+ k32.GetDriveTypeW.argtypes = [ctypes.c_wchar_p]
+ k32.GetDriveTypeW.restype = ctypes.c_uint
+ return fixed_drives_from_mask(k32.GetLogicalDrives(), k32.GetDriveTypeW)
+ except (OSError, AttributeError):
+ return []
+
+
+# ---------------------------------------------------------------- NVIDIA
+
+NVIDIA_SMI_QUERY = ["--query-gpu=index,name,memory.total,memory.free,driver_version",
+ "--format=csv,noheader,nounits"]
+
+
+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."""
+ import csv
+ gpus = []
+ for fields in csv.reader((text or "").splitlines()):
+ fields = [f.strip() for f in fields]
+ if len(fields) < 4:
+ continue
+ try:
+ index = int(fields[0])
+ except ValueError:
+ continue
+
+ def mib(value):
+ try:
+ return int(float(value)) * 1024 * 1024
+ except 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})
+ return gpus
+
+
+def nvidia_smi_path():
+ found = shutil.which("nvidia-smi")
+ if found:
+ return found
+ for candidate in ("/usr/lib/wsl/lib/nvidia-smi",
+ r"C:\Windows\System32\nvidia-smi.exe"):
+ if os.path.isfile(candidate):
+ return candidate
+ return None
+
+
+def detect_nvidia():
+ exe = nvidia_smi_path()
+ if not exe:
+ return []
+ return parse_nvidia_smi(_run([exe] + NVIDIA_SMI_QUERY, timeout=10))
+
+
+# ---------------------------------------------------------------- Vulkan
+
+VK_DEVICE_TYPES = {0: "other", 1: "integrated", 2: "discrete", 3: "virtual", 4: "cpu"}
+#: The engine's own ranking (backend_vulkan.c, coli_vk_init).
+VK_TYPE_RANK = {"discrete": 4, "integrated": 3, "virtual": 2, "other": 1, "cpu": 0}
+VK_VENDORS = {0x10DE: "NVIDIA", 0x1002: "AMD", 0x1022: "AMD", 0x8086: "Intel",
+ 0x13B5: "Arm", 0x5143: "Qualcomm", 0x106B: "Apple", 0x1414: "Microsoft",
+ 0x10005: "Mesa"}
+
+
+def vk_version(value):
+ return f"{value >> 22 & 0x7F}.{value >> 12 & 0x3FF}.{value & 0xFFF}"
+
+
+def _vulkan_library():
+ names = {"win32": ["vulkan-1.dll"],
+ "darwin": ["libvulkan.1.dylib", "libMoltenVK.dylib"]}.get(
+ sys.platform, ["libvulkan.so.1", "libvulkan.so"])
+ for name in names:
+ try:
+ return ctypes.CDLL(name)
+ except OSError:
+ continue
+ return None
+
+
+def _vk_probe_inprocess():
+ """Enumerate Vulkan physical devices with the loader, as the engine does.
+
+ Raw buffers and explicit offsets rather than full ctypes mirrors of the
+ Vulkan structs: only the leading fields are read, and a buffer larger than
+ the struct cannot be overrun by a newer driver. Offsets are the C layout on
+ every 64-bit ABI colibri builds for."""
+ lib = _vulkan_library()
+ if lib is None:
+ return {"loader": False, "devices": []}
+ u32, vp = ctypes.c_uint32, ctypes.c_void_p
+
+ lib.vkCreateInstance.argtypes = [vp, vp, ctypes.POINTER(vp)]
+ lib.vkCreateInstance.restype = ctypes.c_int32
+ lib.vkEnumeratePhysicalDevices.argtypes = [vp, ctypes.POINTER(u32), vp]
+ lib.vkEnumeratePhysicalDevices.restype = ctypes.c_int32
+ lib.vkGetPhysicalDeviceProperties.argtypes = [vp, vp]
+ lib.vkGetPhysicalDeviceProperties.restype = None
+ lib.vkGetPhysicalDeviceMemoryProperties.argtypes = [vp, vp]
+ lib.vkGetPhysicalDeviceMemoryProperties.restype = None
+ lib.vkEnumerateDeviceExtensionProperties.argtypes = [vp, ctypes.c_char_p, ctypes.POINTER(u32), vp]
+ lib.vkEnumerateDeviceExtensionProperties.restype = ctypes.c_int32
+ lib.vkDestroyInstance.argtypes = [vp, vp]
+ lib.vkDestroyInstance.restype = None
+
+ instance_version = 1 << 22 # 1.0
+ if hasattr(lib, "vkEnumerateInstanceVersion"):
+ lib.vkEnumerateInstanceVersion.argtypes = [ctypes.POINTER(u32)]
+ lib.vkEnumerateInstanceVersion.restype = ctypes.c_int32
+ value = u32(0)
+ if lib.vkEnumerateInstanceVersion(ctypes.byref(value)) == 0:
+ instance_version = value.value
+ api = min(instance_version, (1 << 22) | (3 << 12))
+
+ class AppInfo(ctypes.Structure):
+ _fields_ = [("sType", u32), ("pNext", vp), ("pApplicationName", ctypes.c_char_p),
+ ("applicationVersion", u32), ("pEngineName", ctypes.c_char_p),
+ ("engineVersion", u32), ("apiVersion", u32)]
+
+ class CreateInfo(ctypes.Structure):
+ _fields_ = [("sType", u32), ("pNext", vp), ("flags", u32), ("pApplicationInfo", vp),
+ ("enabledLayerCount", u32), ("ppEnabledLayerNames", vp),
+ ("enabledExtensionCount", u32), ("ppEnabledExtensionNames", vp)]
+
+ app = AppInfo(0, None, b"colibri-setup", 1, b"colibri", 1, api)
+ info = CreateInfo(1, None, 0, ctypes.cast(ctypes.byref(app), vp), 0, None, 0, None)
+ instance = vp()
+ result = lib.vkCreateInstance(ctypes.byref(info), None, ctypes.byref(instance))
+ if result != 0 or not instance:
+ return {"loader": True, "instance_error": result, "devices": []}
+ devices = []
+ try:
+ count = u32(0)
+ lib.vkEnumeratePhysicalDevices(instance, ctypes.byref(count), None)
+ handles = (vp * max(count.value, 1))()
+ lib.vkEnumeratePhysicalDevices(instance, ctypes.byref(count), handles)
+ props2 = None
+ if api >= (1 << 22) | (1 << 12):
+ props2 = getattr(lib, "vkGetPhysicalDeviceMemoryProperties2", None)
+ if props2 is not None:
+ props2.argtypes = [vp, vp]
+ props2.restype = None
+ for handle in handles[:count.value]:
+ raw = (ctypes.c_ubyte * 2048)()
+ lib.vkGetPhysicalDeviceProperties(handle, raw)
+ props = bytes(raw)
+ api_v, driver_v, vendor, device_id, dtype = struct.unpack_from("<5I", props, 0)
+ name = props[20:276].split(b"\0", 1)[0].decode("utf-8", "replace")
+
+ ext_count = u32(0)
+ lib.vkEnumerateDeviceExtensionProperties(handle, None, ctypes.byref(ext_count), None)
+ ext_raw = (ctypes.c_ubyte * (260 * max(ext_count.value, 1)))()
+ lib.vkEnumerateDeviceExtensionProperties(handle, None, ctypes.byref(ext_count), ext_raw)
+ ext_bytes = bytes(ext_raw)
+ extensions = {ext_bytes[i * 260:i * 260 + 256].split(b"\0", 1)[0].decode("ascii", "replace")
+ for i in range(ext_count.value)}
+ has_budget = "VK_EXT_memory_budget" in extensions and props2 is not None
+
+ budget_raw = (ctypes.c_ubyte * 512)()
+ if has_budget:
+ mem2 = (ctypes.c_ubyte * 1024)()
+ struct.pack_into("<I", budget_raw, 0, 1000237000)
+ struct.pack_into("<I", mem2, 0, 1000059006)
+ struct.pack_into("<Q", mem2, 8, ctypes.addressof(budget_raw))
+ props2(handle, mem2)
+ memory = bytes(mem2)[16:16 + 520]
+ else:
+ mem = (ctypes.c_ubyte * 1024)()
+ lib.vkGetPhysicalDeviceMemoryProperties(handle, mem)
+ memory = bytes(mem)[:520]
+ devices.append(_vk_device_record(name, dtype, vendor, device_id, api_v, driver_v,
+ memory, bytes(budget_raw) if has_budget else None,
+ "VK_KHR_cooperative_matrix" in extensions))
+ finally:
+ lib.vkDestroyInstance(instance, None)
+ return {"loader": True, "instance_version": vk_version(instance_version), "devices": devices}
+
+
+def _vk_device_record(name, dtype, vendor, device_id, api_v, driver_v, memory, budget, coop):
+ """Turn VkPhysicalDeviceMemoryProperties (and the budget struct) into figures."""
+ heap_count = struct.unpack_from("<I", memory, 260)[0]
+ heaps = []
+ for index in range(min(heap_count, 16)):
+ size, flags = struct.unpack_from("<QI", memory, 264 + index * 16)
+ heap = {"size": size, "device_local": bool(flags & 1)}
+ if budget is not None:
+ heap["budget"] = struct.unpack_from("<Q", budget, 16 + index * 8)[0]
+ heap["usage"] = struct.unpack_from("<Q", budget, 144 + index * 8)[0]
+ heaps.append(heap)
+ local = [h for h in heaps if h["device_local"]]
+ return {
+ "name": name,
+ "type": VK_DEVICE_TYPES.get(dtype, "other"),
+ "vendor": VK_VENDORS.get(vendor, f"0x{vendor:04x}"),
+ "vendor_id": vendor,
+ "device_id": device_id,
+ "api_version": vk_version(api_v),
+ "api_version_raw": api_v,
+ "device_local_bytes": sum(h["size"] for h in local) or None,
+ "budget_bytes": (sum(h.get("budget", 0) for h in local) or None) if budget is not None else None,
+ "memory_budget_ext": budget is not None,
+ "cooperative_matrix": coop,
+ "heaps": heaps,
+ }
+
+
+def parse_vulkaninfo_summary(text):
+ """Devices from `vulkaninfo --summary`: names, types and API versions. The
+ summary carries no memory figures, so those stay None."""
+ devices = []
+ current = None
+ for line in (text or "").splitlines():
+ stripped = line.strip()
+ if re.match(r"^GPU\d+:$", stripped):
+ current = {"name": None, "type": "other", "vendor": None, "vendor_id": None,
+ "device_id": None, "api_version": None, "api_version_raw": None,
+ "device_local_bytes": None, "budget_bytes": None,
+ "memory_budget_ext": False, "cooperative_matrix": False, "heaps": []}
+ devices.append(current)
+ continue
+ if current is None:
+ continue
+ key, sep, value = stripped.partition("=")
+ if not sep:
+ continue
+ key, value = key.strip(), value.strip()
+ if key == "deviceName":
+ current["name"] = value
+ elif key == "deviceType":
+ kind = value.replace("PHYSICAL_DEVICE_TYPE_", "").lower()
+ current["type"] = {"integrated_gpu": "integrated", "discrete_gpu": "discrete",
+ "virtual_gpu": "virtual"}.get(kind, kind if kind in VK_TYPE_RANK else "other")
+ elif key == "apiVersion":
+ version = value.split()[0]
+ current["api_version"] = version
+ parts = [int(p) for p in re.findall(r"\d+", version)[:3]] + [0, 0, 0]
+ current["api_version_raw"] = (parts[0] << 22) | (parts[1] << 12) | parts[2]
+ elif key == "vendorID":
+ try:
+ vendor = int(value.split()[0], 0)
+ current["vendor_id"] = vendor
+ current["vendor"] = VK_VENDORS.get(vendor, f"0x{vendor:04x}")
+ except ValueError:
+ pass
+ elif key == "deviceID":
+ try:
+ current["device_id"] = int(value.split()[0], 0)
+ except ValueError:
+ pass
+ return [d for d in devices if d["name"]]
+
+
+def vulkan_usable(device):
+ """A device the GPU path can use: a real GPU (not a CPU rasterizer such as
+ llvmpipe/Lavapipe) with Vulkan 1.2, the engine's floor."""
+ if device.get("type") not in ("discrete", "integrated", "virtual"):
+ return False
+ raw = device.get("api_version_raw")
+ return raw is None or raw >= (1 << 22) | (2 << 12)
+
+
+def best_vulkan_device(devices):
+ """The device the engine will pick: the highest-ranked type, first wins."""
+ best, rank = None, -1
+ for device in devices:
+ value = VK_TYPE_RANK.get(device.get("type"), 0)
+ if value > rank:
+ best, rank = device, value
+ return best
+
+
+def find_user_icds(home=None):
+ """Vulkan driver manifests installed under the home directory.
+
+ A driver built by hand (Mesa's Dozen for WSL2 is the usual case) installs
+ its manifest under a prefix in $HOME, which the loader does not search. Only
+ manifests are returned; whether one gives a usable device is the probe's
+ question."""
+ home = home or os.path.expanduser("~")
+ patterns = (".local/share/vulkan/icd.d/*.json",
+ "*/share/vulkan/icd.d/*.json",
+ "*/install/share/vulkan/icd.d/*.json",
+ "*/*/share/vulkan/icd.d/*.json")
+ found = []
+ for pattern in patterns:
+ for path in sorted(glob.glob(os.path.join(home, pattern))):
+ if path not in found and os.path.isfile(path):
+ found.append(path)
+ return found
+
+
+def _probe_vulkan_child(extra_env=None, timeout=25):
+ env = dict(os.environ)
+ if extra_env:
+ env.update(extra_env)
+ try:
+ result = subprocess.run([sys.executable, os.path.join(HERE, "setup_hw.py"), "--vulkan-probe"],
+ capture_output=True, text=True, timeout=timeout, env=env)
+ 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
+
+
+def detect_vulkan(wsl=None, home=None):
+ """{"devices": [...], "icd": manifest-or-None, "source": "loader"|"vulkaninfo"|None}.
+
+ On WSL the system drivers usually see no GPU (only the CPU rasterizer); a
+ Dozen driver installed under $HOME does. When the default search finds no
+ usable GPU there, each user manifest is tried in turn and the first one that
+ yields a usable device is reported with its path, so the run configuration
+ can point the engine at the same driver."""
+ if sys.platform == "darwin":
+ return {"devices": [], "icd": None, "source": None}
+ wsl = is_wsl() if wsl is None else wsl
+ probe = _probe_vulkan_child()
+ if probe is not None and probe.get("loader"):
+ result = {"devices": probe.get("devices", []), "icd": None, "source": "loader"}
+ else:
+ summary = _run(["vulkaninfo", "--summary"], timeout=20) if shutil.which("vulkaninfo") else ""
+ result = {"devices": parse_vulkaninfo_summary(summary), "icd": None,
+ "source": "vulkaninfo" if summary else None}
+ if not any(vulkan_usable(d) for d in result["devices"]) and sys.platform.startswith("linux") \
+ and not os.environ.get("VK_ICD_FILENAMES") and not os.environ.get("VK_DRIVER_FILES"):
+ for manifest in find_user_icds(home):
+ extra = _probe_vulkan_child({"VK_ICD_FILENAMES": manifest, "VK_DRIVER_FILES": manifest})
+ if extra and any(vulkan_usable(d) for d in extra.get("devices", [])):
+ result = {"devices": extra["devices"], "icd": manifest, "source": "loader"}
+ break
+ if os.environ.get("VK_ICD_FILENAMES") or os.environ.get("VK_DRIVER_FILES"):
+ result["icd"] = os.environ.get("VK_ICD_FILENAMES") or os.environ.get("VK_DRIVER_FILES")
+ return result
+
+
+# ---------------------------------------------------------------- Windows video (informational)
+
+
+def parse_win_video_controllers(text):
+ """`Name|AdapterRAM` lines from Win32_VideoController. AdapterRAM is a uint32
+ and saturates at 4 GiB, so it is shown, never planned with."""
+ out = []
+ for line in (text or "").splitlines():
+ name, sep, ram = line.strip().partition("|")
+ if not name:
+ continue
+ try:
+ ram_bytes = int(ram) if sep and ram.strip() else None
+ except ValueError:
+ ram_bytes = None
+ out.append({"name": name.strip(), "adapter_ram_bytes": ram_bytes})
+ return out
+
+
+def detect_windows_video():
+ if sys.platform != "win32":
+ return []
+ text = _run(["powershell", "-NoProfile", "-Command",
+ "Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name + '|' + $_.AdapterRAM }"],
+ timeout=20)
+ return parse_win_video_controllers(text)
+
+
+# ---------------------------------------------------------------- the report
+
+
+def _run(cmd, timeout=10):
+ try:
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=timeout).stdout
+ except (OSError, subprocess.SubprocessError, ValueError):
+ return ""
+
+
+def gpu_summary(vulkan, nvidia):
+ """What the setup acts on: the Vulkan device the engine would pick (when it
+ is a usable GPU) and the NVIDIA cards."""
+ devices = vulkan.get("devices", []) if vulkan else []
+ best = best_vulkan_device(devices)
+ usable = best if best is not None and vulkan_usable(best) else None
+ return {"vulkan": usable, "vulkan_icd": vulkan.get("icd") if vulkan else None,
+ "nvidia": nvidia, "has_gpu": bool(usable or nvidia)}
+
+
+def detect(target_dir=None, probe_gpu=True):
+ """The whole report, as plain data (JSON-serialisable)."""
+ os_info = detect_os()
+ target = os.path.abspath(os.path.expanduser(target_dir)) if target_dir else None
+ report = {
+ "os": os_info,
+ "cpu": detect_cpu(),
+ "memory": detect_memory(),
+ "disk": None,
+ "vulkan": {"devices": [], "icd": None, "source": None},
+ "nvidia": [],
+ "windows_video": [],
+ }
+ if target:
+ report["disk"] = {"path": target, "free_bytes": disk_free(target),
+ "warnings": path_warnings(target, os_info.get("wsl"))}
+ if probe_gpu:
+ report["vulkan"] = detect_vulkan(wsl=os_info.get("wsl"))
+ report["nvidia"] = detect_nvidia()
+ if not report["vulkan"]["devices"]:
+ report["windows_video"] = detect_windows_video()
+ report["gpu"] = gpu_summary(report["vulkan"], report["nvidia"])
+ return report
+
+
+def fmt_gb(value):
+ if value is None:
+ return "?"
+ return f"{value / GB:.1f} GB" if value < 100 * GB else f"{value / GB:.0f} GB"
+
+
+def format_report(report):
+ cpu, mem, osi = report["cpu"], report["memory"], report["os"]
+ lines = []
+ cores = cpu.get("physical_cores")
+ threads = cpu.get("logical_cores")
+ core_text = f"{cores} cores ({threads} threads)" if cores and threads and cores != threads \
+ else f"{threads or cores or '?'} cores"
+ features = ", ".join(f.upper() for f in cpu.get("features", []) if f in
+ ("avx2", "avx_vnni", "avx512f", "avx512_vnni", "avx512_bf16", "asimddp", "sve"))
+ lines.append(f" CPU {cpu.get('name') or cpu.get('arch') or '?'}, {core_text}"
+ + (f", {features}" if features else ""))
+ lines.append(f" RAM {fmt_gb(mem.get('total'))}"
+ + (f" ({fmt_gb(mem.get('available'))} free now)" if mem.get("available") else ""))
+ disk = report.get("disk")
+ if disk:
+ lines.append(f" Disk {fmt_gb(disk.get('free_bytes'))} free in {disk['path']}")
+ for warning in disk.get("warnings", []):
+ lines.append(f" warning: {warning}")
+ gpu = report.get("gpu", {})
+ shown = False
+ if gpu.get("vulkan"):
+ device = gpu["vulkan"]
+ memory = device.get("budget_bytes") or device.get("device_local_bytes")
+ share = ", shares RAM" if device["type"] == "integrated" else ""
+ lines.append(f" GPU {device['name']} via Vulkan {device.get('api_version') or ''}"
+ f" ({device['type']}{share}"
+ + (f", {fmt_gb(memory)} {'budget' if device.get('budget_bytes') else 'device memory'}" if memory else "")
+ + ")")
+ if gpu.get("vulkan_icd"):
+ lines.append(f" driver manifest: {gpu['vulkan_icd']}")
+ shown = True
+ for card in gpu.get("nvidia", []):
+ lines.append(f" GPU {card['name']} (NVIDIA, {fmt_gb(card.get('total_bytes'))} VRAM"
+ + (f", driver {card['driver']}" if card.get("driver") else "") + ")")
+ shown = True
+ if not shown:
+ cpu_only = [d for d in report.get("vulkan", {}).get("devices", []) if d.get("type") == "cpu"]
+ others = report.get("windows_video") or []
+ if others:
+ names = ", ".join(v["name"] for v in others)
+ lines.append(f" GPU {names} (no Vulkan driver answered; the engine will use the CPU)")
+ elif cpu_only:
+ lines.append(f" GPU none usable (Vulkan sees only {cpu_only[0]['name']}, a CPU rasterizer)")
+ else:
+ lines.append(" GPU none found (the engine runs on the CPU)")
+ system = osi.get("pretty_name") or osi.get("platform")
+ if osi.get("wsl"):
+ system = f"{system} under WSL2"
+ lines.append(f" System {system}")
+ return "\n".join(lines)
+
+
+def main(argv=None):
+ argv = sys.argv[1:] if argv is None else argv
+ if argv[:1] == ["--vulkan-probe"]:
+ try:
+ print(json.dumps(_vk_probe_inprocess()))
+ except Exception as error: # report, never crash the parent's parse
+ print(json.dumps({"loader": False, "error": str(error), "devices": []}))
+ return 0
+ sys.path.insert(0, HERE)
+ targets = [arg for arg in argv if not arg.startswith("--")]
+ report = detect(targets[0] if targets else os.path.expanduser("~"))
+ if "--json" in argv:
+ print(json.dumps(report, indent=2))
+ else:
+ print(format_report(report))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/c/tests/fake_hub.py b/c/tests/fake_hub.py
new file mode 100644
index 00000000..c3d3e9b4
--- /dev/null
+++ b/c/tests/fake_hub.py
@@ -0,0 +1,189 @@
+"""A local stand-in for the Hugging Face hub, for the setup tests.
+
+Serves one or more model repositories from folders on disk, the way the real
+hub does for a downloader: the tree listing API (with LFS sha256 for large
+files, git blob ids for small ones, and Link pagination), and `resolve/` URLs
+that redirect to a separate "CDN" path serving the bytes with Range support.
+
+Faults can be injected per file: `cut_after[path] = n` makes the next request
+for that file send its full Content-Length and then drop the connection after n
+bytes, the way a flaky network does; `ignore_range` answers 200 with the whole
+body to a ranged request. Every request's headers are recorded, so a test can
+check that the token reached the hub and not the CDN.
+
+Not a test module (no test_ prefix): imported by tests/test_setup_download.py
+and tests/test_setup_flow.py, and usable by hand:
+
+ python3 tests/fake_hub.py <repo-id> <folder> [port]
+"""
+import hashlib
+import http.server
+import json
+import os
+import re
+import sys
+import threading
+import urllib.parse
+
+LFS_THRESHOLD = 1024
+
+
+def git_blob_oid(data):
+ return hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest()
+
+
+class FakeHub:
+ def __init__(self, repos, page_size=0):
+ self.repos = dict(repos) # repo id -> folder
+ self.page_size = page_size
+ self.cut_after = {}
+ self.ignore_range = False
+ self.requests = []
+ self.lock = threading.Lock()
+ hub = self
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ with hub.lock:
+ hub.requests.append({"path": self.path, "headers": dict(self.headers)})
+ hub.route(self)
+
+ self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.server.daemon_threads = True
+ self.port = self.server.server_address[1]
+ self.base = f"http://127.0.0.1:{self.port}"
+ self.thread = threading.Thread(target=self.server.serve_forever,
+ kwargs={"poll_interval": 0.05}, daemon=True)
+
+ def __enter__(self):
+ self.thread.start()
+ return self
+
+ def __exit__(self, *exc):
+ self.server.shutdown()
+ self.server.server_close()
+
+ def files(self, repo):
+ root = self.repos[repo]
+ out = []
+ for folder, _dirs, names in os.walk(root):
+ for name in sorted(names):
+ full = os.path.join(folder, name)
+ rel = os.path.relpath(full, root).replace(os.sep, "/")
+ out.append((rel, full))
+ return sorted(out)
+
+ def listing(self, repo):
+ entries = []
+ for rel, full in self.files(repo):
+ with open(full, "rb") as handle:
+ data = handle.read()
+ entry = {"type": "file", "path": rel, "size": len(data), "oid": git_blob_oid(data)}
+ if len(data) >= LFS_THRESHOLD:
+ entry["lfs"] = {"oid": hashlib.sha256(data).hexdigest(), "size": len(data),
+ "pointerSize": 130}
+ entries.append(entry)
+ return entries
+
+ def route(self, handler):
+ parsed = urllib.parse.urlsplit(handler.path)
+ path = urllib.parse.unquote(parsed.path)
+ match = re.match(r"^/api/models/(.+?)/tree/([^/]+)$", path)
+ if match and match.group(1) in self.repos:
+ entries = self.listing(match.group(1))
+ query = urllib.parse.parse_qs(parsed.query)
+ start = int(query.get("cursor", ["0"])[0])
+ link = None
+ if self.page_size:
+ page = entries[start:start + self.page_size]
+ if start + self.page_size < len(entries):
+ link = (f'<{self.base}{parsed.path}?recursive=true&cursor='
+ f'{start + self.page_size}>; rel="next"')
+ entries = page
+ body = json.dumps(entries).encode()
+ handler.send_response(200)
+ handler.send_header("Content-Type", "application/json")
+ handler.send_header("Content-Length", str(len(body)))
+ if link:
+ handler.send_header("Link", link)
+ handler.end_headers()
+ handler.wfile.write(body)
+ return
+ for repo in self.repos:
+ prefix = f"/{repo}/resolve/"
+ if path.startswith(prefix):
+ rel = path[len(prefix):].split("/", 1)[1]
+ handler.send_response(302)
+ handler.send_header("Location", f"{self.base}/cdn/{urllib.parse.quote(repo)}/"
+ f"{urllib.parse.quote(rel)}")
+ handler.send_header("Content-Length", "0")
+ handler.end_headers()
+ return
+ cdn = f"/cdn/{repo}/"
+ if path.startswith(cdn):
+ self.serve_bytes(handler, repo, path[len(cdn):])
+ return
+ handler.send_response(404)
+ handler.send_header("Content-Length", "0")
+ handler.end_headers()
+
+ def serve_bytes(self, handler, repo, rel):
+ full = os.path.join(self.repos[repo], *rel.split("/"))
+ if not os.path.isfile(full):
+ handler.send_response(404)
+ handler.send_header("Content-Length", "0")
+ handler.end_headers()
+ return
+ with open(full, "rb") as stream:
+ data = stream.read()
+ start = 0
+ ranged = handler.headers.get("Range")
+ match = re.match(r"bytes=(\d+)-(\d*)$", ranged or "")
+ if match and not self.ignore_range:
+ start = int(match.group(1))
+ end = int(match.group(2)) if match.group(2) else len(data) - 1
+ if start >= len(data):
+ handler.send_response(416)
+ handler.send_header("Content-Range", f"bytes */{len(data)}")
+ handler.send_header("Content-Length", "0")
+ handler.end_headers()
+ return
+ end = min(end, len(data) - 1)
+ body = data[start:end + 1]
+ handler.send_response(206)
+ handler.send_header("Content-Range", f"bytes {start}-{end}/{len(data)}")
+ else:
+ body = data
+ handler.send_response(200)
+ handler.send_header("Content-Length", str(len(body)))
+ handler.send_header("Accept-Ranges", "bytes")
+ handler.end_headers()
+ cut = self.cut_after.pop(rel, None)
+ if cut is not None:
+ handler.wfile.write(body[:cut])
+ handler.wfile.flush()
+ handler.close_connection = True
+ try:
+ handler.connection.shutdown(2)
+ except OSError:
+ pass
+ return
+ handler.wfile.write(body)
+
+
+if __name__ == "__main__":
+ repo, folder = sys.argv[1], sys.argv[2]
+ hub = FakeHub({repo: folder})
+ if len(sys.argv) > 3:
+ hub.server.server_close()
+ hub.server = http.server.ThreadingHTTPServer(("127.0.0.1", int(sys.argv[3])),
+ hub.server.RequestHandlerClass)
+ hub.port = int(sys.argv[3])
+ hub.base = f"http://127.0.0.1:{hub.port}"
+ print(f"HF_ENDPOINT={hub.base}", flush=True)
+ hub.server.serve_forever()
diff --git a/c/tests/test_setup_catalog.py b/c/tests/test_setup_catalog.py
new file mode 100644
index 00000000..8853e24c
--- /dev/null
+++ b/c/tests/test_setup_catalog.py
@@ -0,0 +1,154 @@
+"""The setup's model catalog and its recommendation, on mocked machines.
+
+The catalog names registry families; the registry owns engines, build targets
+and accelerator support. The first class holds the two together, so a family
+renamed in the registry cannot leave the setup offering an engine that does not
+exist. The second runs the recommendation on machines described by numbers.
+"""
+import json
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+import setup_catalog # noqa: E402
+from family_registry import family_by_id # noqa: E402
+
+GB = 10**9
+
+
+def recommended(rows):
+ picks = [r["entry"].id for r in rows if r["recommended"]]
+ return picks[0] if picks else None
+
+
+class CatalogAgreesWithTheRegistry(unittest.TestCase):
+ def test_every_entry_names_a_registry_family(self):
+ for entry in setup_catalog.CATALOG:
+ with self.subTest(entry=entry.id):
+ family = family_by_id(entry.family)
+ self.assertTrue(family.build_target)
+ if entry.modality != "text":
+ self.assertEqual(family.modality, entry.modality)
+
+ def test_ids_are_unique_and_numbers_sane(self):
+ ids = [entry.id for entry in setup_catalog.CATALOG]
+ self.assertEqual(len(ids), len(set(ids)))
+ for entry in setup_catalog.CATALOG:
+ with self.subTest(entry=entry.id):
+ self.assertGreater(entry.disk_gb, 0)
+ self.assertLessEqual(entry.ram_min_gb, entry.ram_good_gb)
+ self.assertLess(entry.dense_gb, entry.ram_min_gb)
+ self.assertIn(entry.size_class, ("small", "large"))
+ self.assertRegex(entry.repo, r"^[\w.-]+/[\w.-]+$")
+ for step in entry.post_install:
+ self.assertTrue((Path(__file__).resolve().parent.parent / "tools"
+ / f"{step[0]}.py").is_file(), step)
+
+ def test_lookup(self):
+ self.assertEqual(setup_catalog.by_id("qwen36-35b").family, "qwen36")
+ with self.assertRaises(KeyError):
+ setup_catalog.by_id("no-such-model")
+
+
+class Recommendation(unittest.TestCase):
+ def test_laptop_with_27_gb_gets_the_model_that_runs_from_ram(self):
+ rows = setup_catalog.recommend(27 * GB, 800 * GB)
+ self.assertEqual(recommended(rows), "qwen36-35b")
+ status = {r["entry"].id: r["status"] for r in rows}
+ self.assertEqual(status["mimo-v2.6-flash"], "needs-ram")
+ self.assertEqual(status["glm-5.2"], "good")
+ # fitting rows first, the recommendation at the top
+ self.assertTrue(rows[0]["recommended"])
+ fits = [r["fits"] for r in rows]
+ self.assertEqual(fits, sorted(fits, reverse=True))
+
+ def test_small_ram_takes_the_smaller_model(self):
+ rows = setup_catalog.recommend(9 * GB, 200 * GB)
+ self.assertEqual(recommended(rows), "qwen3-coder-30b")
+
+ def test_tight_ram_prefers_the_most_capable_small_model_that_runs(self):
+ rows = setup_catalog.recommend(16 * GB, 200 * GB)
+ self.assertEqual(recommended(rows), "qwen36-35b")
+ self.assertEqual({r["entry"].id: r["status"] for r in rows}["qwen36-35b"], "tight")
+
+ def test_nothing_fits(self):
+ rows = setup_catalog.recommend(4 * GB, 1000 * GB)
+ self.assertIsNone(recommended(rows))
+ self.assertFalse(any(r["fits"] for r in rows))
+
+ def test_disk_decides_too(self):
+ # 22 GB free: room for the 19.4 GB coder (plus 2% and 2 GB of slack),
+ # not for the 23.1 GB Qwen3.6, whatever the RAM.
+ rows = setup_catalog.recommend(64 * GB, 22 * GB)
+ status = {r["entry"].id: r["status"] for r in rows}
+ self.assertEqual(status["qwen36-35b"], "needs-disk")
+ self.assertEqual(status["glm-5.2"], "needs-disk")
+ self.assertEqual(recommended(rows), "qwen3-coder-30b")
+
+ def test_a_partial_download_counts_toward_the_disk(self):
+ rows = setup_catalog.recommend(64 * GB, 10 * GB, downloaded={"qwen36-35b": 20 * GB})
+ self.assertEqual({r["entry"].id: r["status"] for r in rows}["qwen36-35b"], "good")
+
+ def test_large_models_are_the_default_only_when_no_small_one_fits(self):
+ with mock.patch.object(setup_catalog, "CATALOG",
+ tuple(e for e in setup_catalog.CATALOG if e.size_class == "large")):
+ rows = setup_catalog.recommend(27 * GB, 800 * GB)
+ self.assertEqual(recommended(rows), "deepseek-v4-flash-reap") # smallest download
+
+ def test_the_image_model_is_offered_never_the_default(self):
+ with mock.patch.object(setup_catalog, "CATALOG",
+ tuple(e for e in setup_catalog.CATALOG if e.modality == "image")):
+ rows = setup_catalog.recommend(64 * GB, 800 * GB)
+ self.assertTrue(rows[0]["fits"])
+ self.assertIsNone(recommended(rows))
+
+ def test_platform_limits(self):
+ rows = setup_catalog.recommend(64 * GB, 800 * GB, os_name="darwin", machine="x86_64")
+ self.assertEqual({r["entry"].id: r["status"] for r in rows}["deepseek-v4-flash"], "unsupported")
+ rows = setup_catalog.recommend(64 * GB, 800 * GB, os_name="win32", machine="amd64")
+ self.assertEqual({r["entry"].id: r["status"] for r in rows}["deepseek-v4-flash"], "good")
+
+ def test_reasons_explain_ram_as_dense_plus_cache(self):
+ rows = setup_catalog.recommend(8 * GB, 800 * GB)
+ reason = {r["entry"].id: r["reason"] for r in rows}["mimo-v2.6-flash"]
+ self.assertIn("dense part", reason)
+ self.assertIn("expert cache", reason)
+
+ def test_as_dict_is_json(self):
+ rows = setup_catalog.recommend(27 * GB, 800 * GB)
+ data = [setup_catalog.as_dict(r) for r in rows]
+ json.dumps(data)
+ self.assertEqual(sum(1 for d in data if d["recommended"]), 1)
+ self.assertEqual(data[0]["runs"], "from RAM")
+
+
+class ExtraCatalog(unittest.TestCase):
+ def test_entries_from_the_environment(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = os.path.join(tmp, "extra.json")
+ with open(path, "w") as handle:
+ json.dump([{"id": "mirror-qwen", "family": "qwen36", "name": "Mirror",
+ "repo": "me/mirror", "disk_gb": 1, "ram_min_gb": 1, "ram_good_gb": 2,
+ "dense_gb": 0.5, "rank": 50, "size_class": "small",
+ "summary": "test", "exclude": ["*.md"], "unknown_key": 1}], handle)
+ with mock.patch.dict(os.environ, {"COLI_SETUP_CATALOG": path}):
+ entry = setup_catalog.by_id("mirror-qwen")
+ rows = setup_catalog.recommend(27 * GB, 800 * GB)
+ self.assertEqual(entry.exclude, ("*.md",))
+ self.assertEqual(recommended(rows), "mirror-qwen")
+
+
+class Versions(unittest.TestCase):
+ def test_version_order(self):
+ v = setup_catalog.version_tuple
+ self.assertLess(v("v1.12.1"), v("1.12.2"))
+ self.assertLess(v("1.12.9"), v("v1.13.0"))
+ self.assertEqual(v("1.12"), (1, 12, 0))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_setup_download.py b/c/tests/test_setup_download.py
new file mode 100644
index 00000000..171ce156
--- /dev/null
+++ b/c/tests/test_setup_download.py
@@ -0,0 +1,251 @@
+"""Resumable downloads, against a local fake of the Hugging Face hub.
+
+Nothing here touches the network: tests/fake_hub.py serves a repository from a
+temporary folder with the hub's listing API, a redirect to a "CDN" path, Range
+support and injected faults. The contract under test: a dropped connection
+resumes from the bytes on disk (Range, then append), a server that ignores
+Range restarts the file instead of appending a second copy, corrupt bytes never
+become a file without `.part`, and the token never follows the redirect.
+"""
+import hashlib
+import os
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent))
+sys.path.insert(0, str(HERE))
+import setup_download # noqa: E402
+from fake_hub import FakeHub # noqa: E402
+
+REPO = "tester/tiny-model"
+
+
+def make_repo(root):
+ files = {
+ "config.json": b'{"model_type": "qwen3_5_moe_text"}',
+ "tokenizer.json": b'{"model": {}}' * 10,
+ "model-00000.safetensors": os.urandom(300_000),
+ "model-00001.safetensors": os.urandom(200_000),
+ "sub/extra.bin": os.urandom(5_000),
+ "README.md": b"# readme\n",
+ }
+ for name, data in files.items():
+ path = Path(root, *name.split("/"))
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(data)
+ return files
+
+
+class DownloadTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.src = os.path.join(self.tmp.name, "src")
+ self.dst = os.path.join(self.tmp.name, "dst")
+ self.files = make_repo(self.src)
+ self.hub = FakeHub({REPO: self.src})
+ self.hub.__enter__()
+ self.addCleanup(self.hub.__exit__)
+ # Retries without the real backoff sleeps.
+ patcher = mock.patch.object(setup_download.time, "sleep")
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def listing(self, **kw):
+ return setup_download.list_repo_files(REPO, "main", base=self.hub.base, **kw)
+
+ def spec(self, name):
+ return next(f for f in self.listing() if f["path"] == name)
+
+ def url(self, name):
+ return setup_download.file_url(REPO, "main", name, self.hub.base)
+
+ def ranges(self, name):
+ return [r["headers"].get("Range") for r in self.hub.requests
+ if r["path"].endswith("/" + name) and "/cdn/" in r["path"]]
+
+ def test_listing_sizes_hashes_and_filters(self):
+ files = {f["path"]: f for f in self.listing()}
+ self.assertEqual(set(files), set(self.files))
+ shard = files["model-00000.safetensors"]
+ self.assertEqual(shard["size"], 300_000)
+ self.assertEqual(shard["sha256"], hashlib.sha256(self.files["model-00000.safetensors"]).hexdigest())
+ self.assertIsNone(files["config.json"]["sha256"])
+ self.assertIsNotNone(files["config.json"]["git_oid"])
+ kept = {f["path"] for f in self.listing(exclude=("sub/*", "*.md"))}
+ self.assertEqual(kept, {"config.json", "tokenizer.json", "model-00000.safetensors",
+ "model-00001.safetensors"})
+ only = {f["path"] for f in self.listing(include=("*.safetensors",))}
+ self.assertEqual(only, {"model-00000.safetensors", "model-00001.safetensors"})
+
+ def test_listing_follows_pagination(self):
+ self.hub.page_size = 2
+ self.assertEqual({f["path"] for f in self.listing()}, set(self.files))
+
+ def test_missing_repo_is_a_clear_error(self):
+ with self.assertRaises(setup_download.DownloadError) as caught:
+ setup_download.list_repo_files("nobody/nothing", base=self.hub.base)
+ self.assertIn("not found", str(caught.exception))
+
+ def test_whole_repo_and_manifest(self):
+ files = self.listing()
+ events = []
+ setup_download.download_repo(REPO, "main", self.dst, files, base=self.hub.base,
+ progress=events.append)
+ for name, data in self.files.items():
+ self.assertEqual(Path(self.dst, *name.split("/")).read_bytes(), data)
+ self.assertTrue(setup_download.is_complete(self.dst))
+ self.assertEqual(events[-1]["done"], events[-1]["total"])
+ self.assertEqual(events[0]["file"], "README.md") # small files first
+ # A rerun fetches nothing.
+ before = len(self.hub.requests)
+ setup_download.download_repo(REPO, "main", self.dst, files, base=self.hub.base)
+ self.assertEqual(len(self.hub.requests), before)
+
+ def test_interrupted_download_resumes_with_range(self):
+ name = "model-00000.safetensors"
+ spec = self.spec(name)
+ dest = os.path.join(self.dst, name)
+ self.hub.cut_after[name] = 120_000
+ with self.assertRaises(setup_download.DownloadError) as caught:
+ setup_download.download_file(self.url(name), dest, spec, retries=0)
+ self.assertIn("rerun to continue", str(caught.exception))
+ self.assertFalse(os.path.exists(dest))
+ self.assertEqual(os.path.getsize(dest + ".part"), 120_000)
+ # The rerun: asks for the rest only, and the file checks out.
+ result = setup_download.download_file(self.url(name), dest, spec, retries=0)
+ self.assertEqual(result, "downloaded")
+ self.assertEqual(Path(dest).read_bytes(), self.files[name])
+ self.assertEqual(self.ranges(name)[-1], "bytes=120000-")
+ self.assertFalse(os.path.exists(dest + ".part"))
+
+ def test_dropped_connection_retries_inside_one_call(self):
+ name = "model-00001.safetensors"
+ self.hub.cut_after[name] = 50_000
+ dest = os.path.join(self.dst, name)
+ setup_download.download_file(self.url(name), dest, self.spec(name), retries=2)
+ self.assertEqual(Path(dest).read_bytes(), self.files[name])
+ self.assertEqual(self.ranges(name), [None, "bytes=50000-"])
+
+ def test_server_ignoring_range_restarts_instead_of_appending(self):
+ name = "model-00001.safetensors"
+ dest = os.path.join(self.dst, name)
+ os.makedirs(self.dst, exist_ok=True)
+ Path(dest + ".part").write_bytes(self.files[name][:70_000])
+ self.hub.ignore_range = True
+ setup_download.download_file(self.url(name), dest, self.spec(name), retries=0)
+ self.assertEqual(Path(dest).read_bytes(), self.files[name])
+
+ def test_corrupt_partial_is_removed_not_kept(self):
+ name = "model-00000.safetensors"
+ dest = os.path.join(self.dst, name)
+ os.makedirs(self.dst, exist_ok=True)
+ Path(dest + ".part").write_bytes(b"\0" * 100_000) # wrong bytes, right offset
+ with self.assertRaises(setup_download.DownloadError) as caught:
+ setup_download.download_file(self.url(name), dest, self.spec(name), retries=0)
+ self.assertIn("checksum", str(caught.exception))
+ self.assertFalse(os.path.exists(dest))
+ self.assertFalse(os.path.exists(dest + ".part"))
+ # and the rerun after that starts clean and succeeds
+ setup_download.download_file(self.url(name), dest, self.spec(name), retries=0)
+ self.assertEqual(Path(dest).read_bytes(), self.files[name])
+
+ def test_oversized_partial_starts_over(self):
+ name = "config.json"
+ dest = os.path.join(self.dst, name)
+ os.makedirs(self.dst, exist_ok=True)
+ Path(dest + ".part").write_bytes(b"x" * 10_000)
+ setup_download.download_file(self.url(name), dest, self.spec(name), retries=0)
+ self.assertEqual(Path(dest).read_bytes(), self.files[name])
+
+ def test_token_reaches_the_hub_and_not_the_cdn(self):
+ name = "config.json"
+ setup_download.download_file(self.url(name), os.path.join(self.dst, name),
+ self.spec(name), token="hf_secret", retries=0)
+ hub_side = [r for r in self.hub.requests if "/resolve/" in r["path"]]
+ cdn_side = [r for r in self.hub.requests if "/cdn/" in r["path"]]
+ self.assertEqual(hub_side[-1]["headers"].get("Authorization"), "Bearer hf_secret")
+ self.assertIsNone(cdn_side[-1]["headers"].get("Authorization"))
+
+ def test_bytes_present_counts_partials(self):
+ files = self.listing()
+ os.makedirs(self.dst, exist_ok=True)
+ Path(self.dst, "config.json").write_bytes(self.files["config.json"])
+ Path(self.dst, "model-00000.safetensors.part").write_bytes(b"x" * 1000)
+ self.assertEqual(setup_download.bytes_present(self.dst, files),
+ len(self.files["config.json"]) + 1000)
+ self.assertFalse(setup_download.is_complete(self.dst))
+
+ def test_unsafe_paths_are_refused(self):
+ for bad in ("../escape.bin", "a/../../b", "C:/x", ""):
+ with self.subTest(path=bad), self.assertRaises(setup_download.DownloadError):
+ setup_download.safe_join(self.dst, bad)
+
+ def test_throughput_probe(self):
+ rate = setup_download.probe_throughput(self.url("model-00000.safetensors"),
+ max_bytes=100_000, max_seconds=5)
+ self.assertGreater(rate, 0)
+ self.assertEqual(self.ranges("model-00000.safetensors")[-1], "bytes=0-99999")
+
+ def test_curl_speed_parsing(self):
+ self.assertEqual(setup_download.parse_curl_speed("3456789.000"), 3456789.0)
+ self.assertEqual(setup_download.parse_curl_speed("3456789,500"), 3456789.5)
+ self.assertIsNone(setup_download.parse_curl_speed(""))
+
+ def test_verify_file(self):
+ name = "model-00001.safetensors"
+ path = Path(self.dst, name)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(self.files[name])
+ self.assertTrue(setup_download.verify_file(str(path), self.spec(name)))
+ path.write_bytes(b"\1" * len(self.files[name]))
+ self.assertFalse(setup_download.verify_file(str(path), self.spec(name)))
+
+ @unittest.skipUnless(os.name == "posix", "the stand-in curl.exe is a script")
+ def test_windows_curl_transport(self):
+ """WSL's slow-network path: Windows' curl.exe writes the .part file, then
+ the same size and hash checks decide whether it becomes the file."""
+ fake_curl = Path(self.tmp.name, "curl.exe")
+ fake_curl.write_text(
+ "#!" + sys.executable + "\n"
+ "import sys, urllib.request\n"
+ "args = sys.argv[1:]\n"
+ "out = args[args.index('-o') + 1]\n"
+ "data = urllib.request.urlopen(args[-1]).read()\n"
+ "open(out, 'wb').write(data)\n")
+ fake_curl.chmod(0o755)
+ name = "model-00000.safetensors"
+ dest = os.path.join(self.dst, name)
+ seen = []
+ with mock.patch.object(setup_download, "wsl_windows_path", side_effect=lambda p: p):
+ result = setup_download.download_file_windows(
+ self.url(name), dest, self.spec(name), str(fake_curl),
+ progress=lambda done, total: seen.append((done, total)))
+ self.assertEqual(result, "downloaded")
+ self.assertEqual(Path(dest).read_bytes(), self.files[name])
+ self.assertEqual(seen[-1], (300_000, 300_000))
+ # A transfer that ends with the wrong bytes is not kept.
+ other = "model-00001.safetensors"
+ bad = dict(self.spec(other), sha256="0" * 64)
+ with mock.patch.object(setup_download, "wsl_windows_path", side_effect=lambda p: p), \
+ self.assertRaises(setup_download.DownloadError):
+ setup_download.download_file_windows(self.url(other), os.path.join(self.dst, other),
+ bad, str(fake_curl))
+ self.assertFalse(os.path.exists(os.path.join(self.dst, other)))
+
+ def test_token_from_file(self):
+ with tempfile.TemporaryDirectory() as hf_home:
+ Path(hf_home, "token").write_text("hf_from_file\n")
+ env = {k: v for k, v in os.environ.items()
+ if k not in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN")}
+ env["HF_HOME"] = hf_home
+ with mock.patch.dict(os.environ, env, clear=True):
+ self.assertEqual(setup_download.hf_token(), "hf_from_file")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_setup_hw.py b/c/tests/test_setup_hw.py
new file mode 100644
index 00000000..9639a250
--- /dev/null
+++ b/c/tests/test_setup_hw.py
@@ -0,0 +1,318 @@
+"""Hardware detection for the one-step setup, against mocked hardware.
+
+Every probe in setup_hw.py has a pure parser behind it; these tests feed the
+parsers the text and the raw structs real machines produce (Linux /proc files,
+nvidia-smi, vulkaninfo, the Vulkan memory-properties layout, the Windows
+system calls' results) so the detection is checked without the hardware.
+"""
+import os
+import struct
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+import setup_hw # noqa: E402
+
+MEMINFO = """MemTotal: 26673356 kB
+MemFree: 1203980 kB
+MemAvailable: 23465316 kB
+Buffers: 123456 kB
+"""
+
+CPUINFO_X86 = """processor\t: 0
+vendor_id\t: GenuineIntel
+model name\t: 13th Gen Intel(R) Core(TM) i7-1355U
+flags\t\t: fpu vme sse sse2 avx f16c fma avx2 avx_vnni sha_ni
+processor\t: 1
+model name\t: 13th Gen Intel(R) Core(TM) i7-1355U
+flags\t\t: fpu vme sse sse2 avx f16c fma avx2 avx_vnni sha_ni
+"""
+
+CPUINFO_ARM = """processor\t: 0
+BogoMIPS\t: 2000.00
+Features\t: fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics asimddp sve i8mm
+CPU implementer\t: 0x41
+"""
+
+NVIDIA_SMI = """0, NVIDIA GeForce RTX 4070, 12282, 11520, 560.94
+1, NVIDIA GB10, [N/A], [N/A], 580.65
+garbage line
+"""
+
+VULKANINFO_SUMMARY = """==========
+VULKANINFO
+==========
+
+Vulkan Instance Version: 1.3.275
+
+Devices:
+========
+GPU0:
+\tapiVersion = 1.3.289
+\tdriverVersion = 24.2.8
+\tvendorID = 0x1002
+\tdeviceID = 0x15bf
+\tdeviceType = PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU
+\tdeviceName = AMD Radeon 780M (RADV PHOENIX)
+\tdriverID = DRIVER_ID_MESA_RADV
+GPU1:
+\tapiVersion = 1.4.318
+\tdriverVersion = 25.2.8
+\tvendorID = 0x10005
+\tdeviceID = 0x0000
+\tdeviceType = PHYSICAL_DEVICE_TYPE_CPU
+\tdeviceName = llvmpipe (LLVM 20.1.2, 256 bits)
+"""
+
+
+def memory_properties(heaps):
+ """VkPhysicalDeviceMemoryProperties bytes: heaps = [(size, device_local)]."""
+ raw = bytearray(520)
+ struct.pack_into("<I", raw, 0, 1) # one memory type
+ struct.pack_into("<II", raw, 4, 1, 0) # DEVICE_LOCAL, heap 0
+ struct.pack_into("<I", raw, 260, len(heaps))
+ for index, (size, local) in enumerate(heaps):
+ struct.pack_into("<QI", raw, 264 + index * 16, size, 1 if local else 0)
+ return bytes(raw)
+
+
+def budget_struct(budgets, usages):
+ raw = bytearray(512)
+ for index, (budget, usage) in enumerate(zip(budgets, usages)):
+ struct.pack_into("<Q", raw, 16 + index * 8, budget)
+ struct.pack_into("<Q", raw, 144 + index * 8, usage)
+ return bytes(raw)
+
+
+def device(name, kind, api="1.3.0"):
+ major, minor, patch = (int(p) for p in api.split("."))
+ return {"name": name, "type": kind, "api_version": api,
+ "api_version_raw": (major << 22) | (minor << 12) | patch,
+ "budget_bytes": None, "device_local_bytes": 8 * 2**30}
+
+
+class MemoryParsing(unittest.TestCase):
+ def test_meminfo(self):
+ mem = setup_hw.memory_from_meminfo(MEMINFO)
+ self.assertEqual(mem["total"], 26673356 * 1024)
+ self.assertEqual(mem["available"], 23465316 * 1024)
+
+ def test_meminfo_without_available_is_unknown_not_zero(self):
+ mem = setup_hw.memory_from_meminfo("MemTotal: 1000 kB\n")
+ self.assertEqual(mem["total"], 1000 * 1024)
+ self.assertIsNone(mem["available"])
+
+ def test_windows_status_uses_the_commit_limit_when_smaller(self):
+ mem = setup_hw.memory_from_windows_status(32 * 2**30, 20 * 2**30, 12 * 2**30)
+ self.assertEqual(mem, {"total": 32 * 2**30, "available": 12 * 2**30})
+ mem = setup_hw.memory_from_windows_status(32 * 2**30, 20 * 2**30, 40 * 2**30)
+ self.assertEqual(mem["available"], 20 * 2**30)
+
+ def test_darwin(self):
+ vm_stat = ("Mach Virtual Memory Statistics: (page size of 16384 bytes)\n"
+ "Pages free: 10000.\n"
+ "Pages inactive: 5000.\n"
+ "Pages speculative: 1000.\n")
+ mem = setup_hw.memory_from_darwin("17179869184\n", vm_stat)
+ self.assertEqual(mem["total"], 17179869184)
+ self.assertEqual(mem["available"], 16000 * 16384)
+
+
+class CpuParsing(unittest.TestCase):
+ def test_x86(self):
+ cpu = setup_hw.cpu_from_cpuinfo(CPUINFO_X86)
+ self.assertEqual(cpu["name"], "13th Gen Intel(R) Core(TM) i7-1355U")
+ self.assertIn("avx2", cpu["features"])
+ self.assertIn("avx_vnni", cpu["features"])
+ self.assertNotIn("avx512f", cpu["features"])
+
+ def test_arm(self):
+ cpu = setup_hw.cpu_from_cpuinfo(CPUINFO_ARM)
+ for flag in ("asimd", "asimddp", "i8mm", "sve"):
+ self.assertIn(flag, cpu["features"])
+
+ def test_windows_feature_codes(self):
+ present = {40} # AVX2 only
+ self.assertEqual(setup_hw.cpu_features_from_windows(lambda code: code in present), ["avx2"])
+
+
+class SystemParsing(unittest.TestCase):
+ def test_wsl_from_kernel_release(self):
+ self.assertTrue(setup_hw.is_wsl("6.18.33.2-microsoft-standard-WSL2", environ={}))
+ self.assertFalse(setup_hw.is_wsl("6.8.0-45-generic", environ={}))
+ self.assertTrue(setup_hw.is_wsl("6.8.0", environ={"WSL_DISTRO_NAME": "Ubuntu"}))
+
+ def test_os_release(self):
+ info = setup_hw.os_release('ID=ubuntu\nID_LIKE=debian\nPRETTY_NAME="Ubuntu 24.04 LTS"\n')
+ self.assertEqual(info["ID"], "ubuntu")
+ self.assertEqual(info["PRETTY_NAME"], "Ubuntu 24.04 LTS")
+
+ def test_windows_drive_from_wsl_is_flagged(self):
+ self.assertTrue(setup_hw.path_warnings("/mnt/c/Users/me/models", wsl=True))
+ self.assertFalse(setup_hw.path_warnings("/home/me/colibri-models", wsl=True))
+ self.assertFalse(setup_hw.path_warnings("/mnt/c/Users/me/models", wsl=False))
+
+ def test_fixed_drives(self):
+ kinds = {"C:\\": 3, "D:\\": 3, "E:\\": 2, "Z:\\": 4} # fixed, fixed, removable, network
+ mask = (1 << 2) | (1 << 3) | (1 << 4) | (1 << 25)
+ self.assertEqual(setup_hw.fixed_drives_from_mask(mask, lambda root: kinds.get(root, 0)),
+ ["C:\\", "D:\\"])
+
+ def test_disk_free_walks_up_to_an_existing_folder(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ free = setup_hw.disk_free(os.path.join(tmp, "not", "yet", "there"))
+ self.assertIsInstance(free, int)
+ self.assertGreater(free, 0)
+
+ def test_windows_video_controllers(self):
+ rows = setup_hw.parse_win_video_controllers(
+ "Intel(R) Iris(R) Xe Graphics|1073741824\nNVIDIA GeForce RTX 3060|\n\n")
+ self.assertEqual(rows[0], {"name": "Intel(R) Iris(R) Xe Graphics",
+ "adapter_ram_bytes": 1073741824})
+ self.assertIsNone(rows[1]["adapter_ram_bytes"])
+
+
+class NvidiaParsing(unittest.TestCase):
+ def test_rows(self):
+ gpus = setup_hw.parse_nvidia_smi(NVIDIA_SMI)
+ self.assertEqual(len(gpus), 2)
+ self.assertEqual(gpus[0]["name"], "NVIDIA GeForce RTX 4070")
+ self.assertEqual(gpus[0]["total_bytes"], 12282 * 2**20)
+ self.assertEqual(gpus[0]["driver"], "560.94")
+
+ def test_unified_memory_is_unknown_not_zero(self):
+ gpus = setup_hw.parse_nvidia_smi(NVIDIA_SMI)
+ self.assertIsNone(gpus[1]["total_bytes"])
+ self.assertIsNone(gpus[1]["free_bytes"])
+
+ def test_empty(self):
+ self.assertEqual(setup_hw.parse_nvidia_smi(""), [])
+
+
+class VulkanParsing(unittest.TestCase):
+ def test_vulkaninfo_summary(self):
+ devices = setup_hw.parse_vulkaninfo_summary(VULKANINFO_SUMMARY)
+ self.assertEqual([d["name"] for d in devices],
+ ["AMD Radeon 780M (RADV PHOENIX)", "llvmpipe (LLVM 20.1.2, 256 bits)"])
+ self.assertEqual(devices[0]["type"], "integrated")
+ self.assertEqual(devices[0]["vendor"], "AMD")
+ self.assertEqual(devices[1]["type"], "cpu")
+ self.assertEqual(devices[0]["api_version"], "1.3.289")
+ self.assertIsNone(devices[0]["device_local_bytes"]) # the summary has no memory figures
+
+ def test_memory_record_with_budget(self):
+ memory = memory_properties([(16 * 2**30, True), (32 * 2**30, False)])
+ budget = budget_struct([12 * 2**30, 30 * 2**30], [1 * 2**30, 2 * 2**30])
+ record = setup_hw._vk_device_record("Radeon RX 7800 XT", 2, 0x1002, 0x747e,
+ (1 << 22) | (3 << 12), 1, memory, budget, True)
+ self.assertEqual(record["type"], "discrete")
+ self.assertEqual(record["vendor"], "AMD")
+ self.assertEqual(record["device_local_bytes"], 16 * 2**30)
+ self.assertEqual(record["budget_bytes"], 12 * 2**30) # device-local heaps only
+ self.assertTrue(record["memory_budget_ext"])
+ self.assertEqual(record["api_version"], "1.3.0")
+
+ def test_memory_record_without_budget(self):
+ memory = memory_properties([(17 * 10**9, True)])
+ record = setup_hw._vk_device_record("Microsoft Direct3D12 (Intel(R) Iris(R) Xe Graphics)",
+ 1, 0x8086, 0xa7a1, (1 << 22) | (2 << 12), 1,
+ memory, None, False)
+ self.assertEqual(record["type"], "integrated")
+ self.assertEqual(record["vendor"], "Intel")
+ self.assertIsNone(record["budget_bytes"])
+ self.assertEqual(record["device_local_bytes"], 17 * 10**9)
+
+ def test_usable_and_best(self):
+ cpu = device("llvmpipe", "cpu")
+ igpu = device("Iris Xe", "integrated", "1.2.318")
+ dgpu = device("RTX 4070", "discrete")
+ old = device("Old card", "discrete", "1.1.0")
+ self.assertFalse(setup_hw.vulkan_usable(cpu))
+ self.assertTrue(setup_hw.vulkan_usable(igpu))
+ self.assertFalse(setup_hw.vulkan_usable(old)) # below the engine's Vulkan 1.2
+ self.assertIs(setup_hw.best_vulkan_device([cpu, igpu, dgpu]), dgpu)
+ self.assertIs(setup_hw.best_vulkan_device([cpu, igpu]), igpu)
+ summary = setup_hw.gpu_summary({"devices": [cpu], "icd": None}, [])
+ self.assertIsNone(summary["vulkan"])
+ self.assertFalse(summary["has_gpu"])
+
+ def test_user_driver_manifests(self):
+ with tempfile.TemporaryDirectory() as home:
+ manifest = Path(home, "mesa-dzn", "install", "share", "vulkan", "icd.d",
+ "dzn_icd.x86_64.json")
+ manifest.parent.mkdir(parents=True)
+ manifest.write_text("{}")
+ local = Path(home, ".local", "share", "vulkan", "icd.d", "x.json")
+ local.parent.mkdir(parents=True)
+ local.write_text("{}")
+ found = setup_hw.find_user_icds(home)
+ self.assertIn(str(manifest), found)
+ self.assertIn(str(local), found)
+
+ def test_wsl_falls_back_to_a_user_driver(self):
+ """The system drivers see only the CPU rasterizer; the Dozen manifest
+ under $HOME sees the GPU, and its path is kept for the run config."""
+ cpu_only = {"loader": True, "devices": [device("llvmpipe", "cpu")]}
+ dozen = {"loader": True, "devices": [device("Microsoft Direct3D12 (Iris Xe)",
+ "integrated", "1.2.318")]}
+
+ def probe(extra_env=None, timeout=25):
+ return dozen if extra_env else cpu_only
+
+ env = {k: v for k, v in os.environ.items()
+ if k not in ("VK_ICD_FILENAMES", "VK_DRIVER_FILES")}
+ with mock.patch.object(setup_hw, "_probe_vulkan_child", side_effect=probe), \
+ mock.patch.object(setup_hw, "find_user_icds", return_value=["/home/u/dzn.json"]), \
+ mock.patch.object(setup_hw.sys, "platform", "linux"), \
+ mock.patch.dict(os.environ, env, clear=True):
+ result = setup_hw.detect_vulkan(wsl=True)
+ self.assertEqual(result["icd"], "/home/u/dzn.json")
+ self.assertEqual(result["devices"][0]["type"], "integrated")
+
+ def test_no_loader_uses_vulkaninfo(self):
+ with mock.patch.object(setup_hw, "_probe_vulkan_child", return_value={"loader": False}), \
+ mock.patch.object(setup_hw.shutil, "which", return_value="/usr/bin/vulkaninfo"), \
+ mock.patch.object(setup_hw, "_run", return_value=VULKANINFO_SUMMARY), \
+ mock.patch.object(setup_hw, "find_user_icds", return_value=[]), \
+ mock.patch.object(setup_hw.sys, "platform", "linux"):
+ result = setup_hw.detect_vulkan(wsl=False)
+ self.assertEqual(result["source"], "vulkaninfo")
+ self.assertEqual(len(result["devices"]), 2)
+
+
+class Report(unittest.TestCase):
+ def test_format_report_names_the_pieces(self):
+ report = {
+ "os": {"platform": "linux", "pretty_name": "Ubuntu 24.04", "wsl": True},
+ "cpu": {"name": "Test CPU", "features": ["avx2"], "physical_cores": 6,
+ "logical_cores": 12},
+ "memory": {"total": 27 * 10**9, "available": 24 * 10**9},
+ "disk": {"path": "/home/u/colibri-models", "free_bytes": 800 * 10**9, "warnings": []},
+ "vulkan": {"devices": [], "icd": None},
+ "nvidia": [{"name": "NVIDIA RTX 4070", "total_bytes": 12 * 2**30, "driver": "560"}],
+ "windows_video": [],
+ "gpu": {"vulkan": device("Iris Xe", "integrated", "1.2.318"),
+ "vulkan_icd": "/home/u/dzn.json",
+ "nvidia": [{"name": "NVIDIA RTX 4070", "total_bytes": 12 * 2**30,
+ "driver": "560"}], "has_gpu": True},
+ }
+ text = setup_hw.format_report(report)
+ for piece in ("Test CPU", "6 cores (12 threads)", "AVX2", "27.0 GB", "800 GB free",
+ "Iris Xe via Vulkan", "integrated, shares RAM", "NVIDIA RTX 4070", "WSL2",
+ "/home/u/dzn.json"):
+ self.assertIn(piece, text)
+
+ def test_detect_without_gpu_probe_is_plain_data(self):
+ import json
+ with tempfile.TemporaryDirectory() as tmp:
+ report = setup_hw.detect(tmp, probe_gpu=False)
+ json.dumps(report) # serialisable for the MCP server
+ self.assertIn("memory", report)
+ self.assertEqual(report["disk"]["path"], os.path.abspath(tmp))
+
+
+if __name__ == "__main__":
+ unittest.main()