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

fix(windows): select the HIP backend DLL in HIP mode

Kenneth-Javier Ortigoza841ee23f6655
diff --git a/c/backend_loader.c b/c/backend_loader.c
index 434a4a8c..583666d8 100644
--- a/c/backend_loader.c
+++ b/c/backend_loader.c
@@ -1,4 +1,4 @@
-/* backend_loader.c β€” Windows runtime loader for coli_cuda.dll.
+/* backend_loader.c β€” Windows runtime loader for the GPU backend DLL.
*
* Why this exists: the engine is built with MinGW-w64 (gcc), but CUDA kernels
* must be compiled with MSVC + nvcc. We cannot link a CUDA .o into a gcc binary
@@ -27,6 +27,24 @@
#include "backend_cuda.h"
+/* Which backend DLL this host looks for, and how it labels its own messages.
+ * The Makefile defines COLI_HIP_DLL for a HIP_DLL=1 host and leaves it undefined
+ * for CUDA_DLL=1; the two builds are mutually exclusive there, so exactly one
+ * arm is live. Every filename-coupled site below uses COLI_BACKEND_DLL β€”
+ * including the path bounds check, which must derive from the same constant so
+ * it can never drift from the name it is guarding.
+ *
+ * The EXPORTED symbol prefix stays coli_cuda_ for both vendors: one shared ABI,
+ * one shared backend_cuda.cu (see GPU_BACKENDS.md). Only the container filename
+ * and the diagnostic label differ. */
+#ifdef COLI_HIP_DLL
+#define COLI_BACKEND_DLL "coli_hip.dll"
+#define COLI_VENDOR_TAG "[HIP]"
+#else
+#define COLI_BACKEND_DLL "coli_cuda.dll"
+#define COLI_VENDOR_TAG "[CUDA]"
+#endif
+
/* Function-pointer typedefs matching each exported symbol. */
typedef int (*fn_init)(const int *devices, int count);
typedef void (*fn_shutdown)(void);
@@ -161,10 +179,10 @@ static int coli_cuda_load(void){
if(g_cuda.loaded) return g_cuda.available;
g_cuda.loaded = 1;
- /* Load coli_cuda.dll from the engine's OWN directory, by absolute path β€”
- * never a bare name. LoadLibraryA("coli_cuda.dll") searches the current
+ /* Load the backend DLL from the engine's OWN directory, by absolute path β€”
+ * never a bare name. LoadLibraryA(COLI_BACKEND_DLL) searches the current
* working directory (and, without SafeDllSearchMode, other writable dirs):
- * an attacker who drops a coli_cuda.dll where the user launches glm.exe (or
+ * an attacker who drops a same-named DLL where the user launches glm.exe (or
* inside a downloaded model directory the user cd's into) would get their
* DllMain run at load β€” classic DLL hijacking -> arbitrary code execution.
* Resolving the path next to glm.exe and loading THAT specific file with
@@ -174,19 +192,19 @@ static int coli_cuda_load(void){
DWORD mn = GetModuleFileNameA(NULL, dllpath, (DWORD)sizeof(dllpath));
if(mn > 0 && mn < sizeof(dllpath)){
char *slash = strrchr(dllpath, '\\');
- if(slash && (size_t)(slash + 1 - dllpath) + sizeof("coli_cuda.dll") <= sizeof(dllpath)){
- strcpy(slash + 1, "coli_cuda.dll");
+ if(slash && (size_t)(slash + 1 - dllpath) + sizeof(COLI_BACKEND_DLL) <= sizeof(dllpath)){
+ strcpy(slash + 1, COLI_BACKEND_DLL);
g_cuda.dll = LoadLibraryExA(dllpath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
}
}
if(!g_cuda.dll){
/* fallback (GetModuleFileNameA praticamente non fallisce): cerca solo
* nella dir dell'applicazione e in System32, MAI la CWD. */
- g_cuda.dll = LoadLibraryExA("coli_cuda.dll", NULL,
+ g_cuda.dll = LoadLibraryExA(COLI_BACKEND_DLL, NULL,
LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
}
if(!g_cuda.dll){
- fprintf(stderr, "[CUDA] coli_cuda.dll not found; GPU tier disabled "
+ fprintf(stderr, COLI_VENDOR_TAG " " COLI_BACKEND_DLL " not found; GPU tier disabled "
"(CPU path remains active).\n");
return 0;
}
@@ -201,7 +219,8 @@ static int coli_cuda_load(void){
g_cuda.name = (type)GetProcAddress(g_cuda.dll, "coli_cuda_" #name); \
_Pragma("GCC diagnostic pop") \
if(!g_cuda.name){ \
- fprintf(stderr, "[CUDA] coli_cuda.dll missing symbol coli_cuda_" #name "\n"); \
+ fprintf(stderr, COLI_VENDOR_TAG " " COLI_BACKEND_DLL \
+ " missing symbol coli_cuda_" #name "\n"); \
FreeLibrary(g_cuda.dll); g_cuda.dll=NULL; return 0; }
/* Optional symbol: a DLL predating it leaves the pointer NULL and only that
diff --git a/c/tests/test_cuda_env.py b/c/tests/test_cuda_env.py
index 6c0b91b2..24c31f33 100644
--- a/c/tests/test_cuda_env.py
+++ b/c/tests/test_cuda_env.py
@@ -11,6 +11,7 @@ Prerequisites (tests skip gracefully when unmet):
import json
import os
+import shutil
import struct
import subprocess
import sys
@@ -245,5 +246,112 @@ class CudaExpertBudgetTest(unittest.TestCase):
self.assertNotIn("auto-sized", combined)
+class LoaderBackendSelectionTest(unittest.TestCase):
+ """Which backend DLL does a Windows host look for, and how does it label its
+ own loader messages?
+
+ Deliberately a *miss*-path contract, so it needs no GPU, no vendor SDK and
+ no backend DLL: each host is copied into an empty temp directory, and
+ ``backend_loader.c`` resolves the DLL next to the executable β€” so the load
+ is guaranteed to fail there and print exactly which file it wanted. That
+ makes the assertion behavioural (run the artifact, read its stderr) rather
+ than a source-text grep, and keeps it green on a machine with no NVIDIA
+ driver, no ROCm and no ``nvidia-smi``.
+
+ The two hosts are built under distinct EXE names so the shared
+ ``c/colibri.exe`` this module's other tests probe is never disturbed.
+ """
+
+ _hosts = {}
+
+ @classmethod
+ def setUpClass(cls):
+ if sys.platform != "win32":
+ raise unittest.SkipTest("backend_loader.c is compiled only on Windows")
+ if shutil.which("make") is None or shutil.which("gcc") is None:
+ raise unittest.SkipTest("MinGW make/gcc needed to build the host matrix")
+ # HIP_DLL=1 is a host-only build: it links backend_loader.o and no HIP
+ # library, so it must succeed with no HIP SDK, HIP_PATH or HIP_ARCH.
+ for key, exe_suffix, flag in (("cuda", "_cudadll.exe", "CUDA_DLL=1"),
+ ("hip", "_hipdll.exe", "HIP_DLL=1")):
+ target = "colibri" + exe_suffix
+ # errors="replace": the toolchain speaks the console codepage, which
+ # is not always decodable as the Python default on localized hosts.
+ proc = subprocess.run(
+ ["make", "-C", str(HERE), target, "EXE=" + exe_suffix, flag],
+ cwd=str(HERE.parent), text=True, errors="replace",
+ capture_output=True, timeout=600,
+ )
+ built = HERE / target
+ if proc.returncode != 0 or not built.exists():
+ raise unittest.SkipTest(
+ "could not build the %s host matrix: %s" % (key, proc.stderr[-400:])
+ )
+ cls._hosts[key] = built
+
+ @classmethod
+ def tearDownClass(cls):
+ for path in cls._hosts.values():
+ try:
+ path.unlink()
+ except OSError:
+ pass
+ cls._hosts.clear()
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def _run_isolated(self, key, timeout=60):
+ """Copy one host into an empty dir and run it with the GPU requested.
+
+ The directory holds the executable and the throwaway model only β€” no
+ backend DLL β€” so the loader's not-found path is the one exercised.
+ """
+ # One sandbox per host, so a test may exercise both in a single method.
+ sandbox = Path(self.tmp.name) / ("bin_" + key)
+ sandbox.mkdir(exist_ok=True)
+ exe = sandbox / self._hosts[key].name
+ shutil.copy2(self._hosts[key], exe)
+ model = _minimal_model(str(sandbox))
+ merged = {**os.environ, "SNAP": str(model), "COLI_CUDA": "1"}
+ return subprocess.run(
+ [str(exe), "1"],
+ env=merged, cwd=str(sandbox), text=True, errors="replace",
+ capture_output=True, timeout=timeout,
+ )
+
+ def test_cuda_dll_host_reports_cuda_backend(self):
+ """CUDA_DLL host: '[CUDA] coli_cuda.dll not found', never the HIP name."""
+ err = self._run_isolated("cuda").stderr or ""
+ self.assertIn("[CUDA] coli_cuda.dll not found", err)
+ self.assertNotIn("coli_hip.dll", err)
+ self.assertNotIn("[HIP]", err)
+
+ def test_hip_dll_host_reports_hip_backend(self):
+ """HIP_DLL host: '[HIP] coli_hip.dll not found', never the CUDA name.
+
+ Runs with no AMD GPU, no HIP SDK and no nvidia-smi β€” the loader has not
+ reached any vendor runtime at the point this message is printed.
+ """
+ err = self._run_isolated("hip").stderr or ""
+ self.assertIn("[HIP] coli_hip.dll not found", err)
+ self.assertNotIn("coli_cuda.dll", err)
+
+ def test_backend_miss_is_not_silent_and_does_no_gpu_work(self):
+ """Both hosts fail closed the same way: exit 2, no GPU touched."""
+ for key in ("cuda", "hip"):
+ with self.subTest(host=key):
+ result = self._run_isolated(key)
+ err = result.stderr or ""
+ self.assertIn("not found; GPU tier disabled", err)
+ # colibri.c owns this second line and stays vendor-neutral in
+ # W1-B1: only the loader's own prefix is discriminated here.
+ self.assertIn("[CUDA] requested backend is unavailable", err)
+ self.assertEqual(result.returncode, 2)
+
+
if __name__ == "__main__":
unittest.main()