Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Probe GPU device count out-of-process on Windows (#988 follow-up) (#994)
Davide Eynardb1b78146286a
diff --git a/llamafile/cuda.c b/llamafile/cuda.cindex 6c4779fc..c412961b 100644--- a/llamafile/cuda.c+++ b/llamafile/cuda.c@@ -76,7 +76,9 @@ static bool LinkCudaAmd(const char *dso) {static bool TryGpuBackend(const char *dso, llamafile_link_dso_fn link_fn) {if (!llamafile_try_load_prebuilt_dso(dso, "cuda", link_fn))return false;- return gpu_backend_probe(&g_cuda);+ // On Windows a faulting driver-init behind get_device_count() can corrupt+ // the process if caught in-process; probe out-of-process there (#988).+ return IsWindows() ? gpu_backend_probe_oop(&g_cuda) : gpu_backend_probe(&g_cuda);}static bool ImportCudaImpl(void) {diff --git a/llamafile/gpu_backend.c b/llamafile/gpu_backend.cindex 68c76240..36f77ced 100644--- a/llamafile/gpu_backend.c+++ b/llamafile/gpu_backend.c@@ -19,9 +19,18 @@#include "llamafile.h"#include <cosmo.h>#include <dlfcn.h>+#include <errno.h>+#include <fcntl.h>#include <setjmp.h>#include <signal.h>+#include <spawn.h>+#include <stdio.h>+#include <stdlib.h>#include <string.h>+#include <sys/wait.h>+#include <unistd.h>++extern char **environ;// Register a backend with ggml (from ggml-backend.h).extern void ggml_backend_register(ggml_backend_reg_t reg);@@ -82,6 +91,7 @@ void gpu_backend_unlink(GpuBackend *b) {b->get_device_count = NULL;b->get_device_description = NULL;b->log_set = NULL;+ b->lib_path[0] = '\0';}bool gpu_backend_link(GpuBackend *b, const char *dso, const GpuBackendDesc *desc) {@@ -126,6 +136,7 @@ bool gpu_backend_link(GpuBackend *b, const char *dso, const GpuBackendDesc *desc}b->lib_handle = lib;+ snprintf(b->lib_path, sizeof(b->lib_path), "%s", dso);return true;}@@ -248,3 +259,164 @@ void gpu_backend_register(GpuBackend *b) {llamafile_info(b->desc->tag, "%s backend registered with GGML", b->desc->name);}}++// =============================================================================+// Out-of-process probe (Windows)+//+// On Windows the get_device_count() call can trigger GPU driver init that+// throws a C++/SEH exception across the cosmo_dlopen/ms_abi boundary. Catching+// that in-process and siglongjmp-ing out (gpu_run_guarded) is unsafe: it leaves+// the process corrupted and it dies silently later, during model load (#988+// follow-up). Instead we re-exec this binary as a tiny child that just dlopens+// the DSO and calls get_device_count(); a crash dies in the child and the+// parent reads the device count from the child's exit status. The parent never+// runs the faulting driver-init code for a device-less backend, so CPU fallback+// stays clean no matter how deep the fault is.+//+// Transport is the child's exit code:+// 0..253 -> device count (clamped)+// 254 -> child could not load/resolve the DSO+// 255 -> child caught a crash during the probe call+// A child killed by an uncaught signal is treated like 255.+// =============================================================================++#define GPU_PROBE_ENV_DSO "LLAMAFILE_GPU_PROBE_DSO"+#define GPU_PROBE_ENV_SYM "LLAMAFILE_GPU_PROBE_SYM"+#define GPU_PROBE_MAX_COUNT 253+#define GPU_PROBE_EXIT_LOAD_FAILED 254+#define GPU_PROBE_EXIT_CRASHED 255++static void gpu_probe_child_crash(int sig) {+ (void)sig;+ _Exit(GPU_PROBE_EXIT_CRASHED);+}++// Runs in the re-exec'd child before main(). When the probe env vars are set it+// dlopens the DSO, calls its device-count symbol, and _Exit()s with the count+// (or an error/crash code). In every normal invocation the env is unset and it+// returns immediately, so the parent and all non-probe binaries are unaffected.+__attribute__((constructor)) static void gpu_probe_child(void) {+ const char *dso = getenv(GPU_PROBE_ENV_DSO);+ const char *sym = getenv(GPU_PROBE_ENV_SYM);+ if (!dso || !sym || !*dso || !*sym)+ return;++ // Convert any crash during driver init into a clean exit code. We never+ // resume after the fault (unlike gpu_run_guarded), so there is no unwind and+ // nothing to corrupt -- this just replaces a backtrace / error dialog with a+ // quiet _Exit().+ static const int kSignals[] = {SIGSEGV, SIGABRT, SIGILL, SIGBUS, SIGFPE};+ struct sigaction sa;+ memset(&sa, 0, sizeof(sa));+ sa.sa_handler = gpu_probe_child_crash;+ sigemptyset(&sa.sa_mask);+ for (int i = 0; i < (int)(sizeof(kSignals) / sizeof(kSignals[0])); ++i)+ sigaction(kSignals[i], &sa, NULL);++ void *lib = cosmo_dlopen(dso, RTLD_LAZY);+ if (!lib)+ _Exit(GPU_PROBE_EXIT_LOAD_FAILED);+ void *fp = cosmo_dlsym(lib, sym);+ if (!fp)+ _Exit(GPU_PROBE_EXIT_LOAD_FAILED);++ int n = gpu_call_device_count(fp);+ if (n < 0)+ n = 0;+ if (n > GPU_PROBE_MAX_COUNT)+ n = GPU_PROBE_MAX_COUNT;+ _Exit(n);+}++bool gpu_backend_probe_oop(GpuBackend *b) {+ // Keep the DSO's own ggml logging suppressed for the later in-parent reg()+ // call, matching gpu_backend_probe()'s behaviour.+ if (!FLAG_verbose)+ gpu_call_log_set(b->log_set, llamafile_log_callback_null, NULL);++ const char *exe = GetProgramExecutableName();++ // Build a private envp (environ + the two probe vars) rather than mutating+ // the global environment, so concurrent cuda/vulkan probes can't race.+ size_t nenv = 0;+ while (environ[nenv])+ ++nenv;+ char **envp = (char **)malloc((nenv + 3) * sizeof(char *));+ char *dso_var = (char *)malloc(sizeof(GPU_PROBE_ENV_DSO) + 1 + strlen(b->lib_path) + 1);+ char *sym_var =+ (char *)malloc(sizeof(GPU_PROBE_ENV_SYM) + 1 + strlen(b->desc->get_device_count) + 1);+ if (!envp || !dso_var || !sym_var) {+ free(envp);+ free(dso_var);+ free(sym_var);+ llamafile_info(b->desc->tag, "%s probe: out of memory; trying next backend",+ b->desc->name);+ gpu_backend_unlink(b);+ return false;+ }+ sprintf(dso_var, "%s=%s", GPU_PROBE_ENV_DSO, b->lib_path);+ sprintf(sym_var, "%s=%s", GPU_PROBE_ENV_SYM, b->desc->get_device_count);+ for (size_t i = 0; i < nenv; ++i)+ envp[i] = environ[i];+ envp[nenv + 0] = dso_var;+ envp[nenv + 1] = sym_var;+ envp[nenv + 2] = NULL;++ // Hide the child's stdout/stderr unless --verbose so a probe's own driver+ // chatter stays quiet (a crash is already silent thanks to the child's+ // _Exit()).+ posix_spawn_file_actions_t fa;+ posix_spawn_file_actions_t *fap = NULL;+ if (!FLAG_verbose && posix_spawn_file_actions_init(&fa) == 0) {+ posix_spawn_file_actions_addopen(&fa, 1, "/dev/null", O_WRONLY, 0);+ posix_spawn_file_actions_addopen(&fa, 2, "/dev/null", O_WRONLY, 0);+ fap = &fa;+ }++ char *const argv[] = {(char *)exe, NULL};+ pid_t pid;+ int rc = posix_spawn(&pid, exe, fap, NULL, argv, envp);+ if (fap)+ posix_spawn_file_actions_destroy(fap);++ bool available = false;+ if (rc != 0) {+ llamafile_info(b->desc->tag, "%s probe: failed to spawn helper (%s); trying next backend",+ b->desc->name, strerror(rc));+ gpu_backend_unlink(b);+ } else {+ int ws;+ while (waitpid(pid, &ws, 0) == -1 && errno == EINTR) {+ }+ int code = WIFEXITED(ws) ? WEXITSTATUS(ws) : -1;+ if (code >= 1 && code <= GPU_PROBE_MAX_COUNT) {+ // At least one usable device. The parent keeps its linked handle and+ // the caller will register the backend; re-running driver init in the+ // parent is safe because the child already proved it initialises.+ available = true;+ } else if (code == 0) {+ llamafile_info(b->desc->tag,+ "%s library loaded but no devices detected; trying next backend",+ b->desc->name);+ gpu_backend_unlink(b);+ } else if (code == GPU_PROBE_EXIT_LOAD_FAILED) {+ // The child couldn't dlopen the DSO or resolve get_device_count.+ // Unexpected (the parent already linked it), but report it for what+ // it is rather than as a crash.+ llamafile_info(b->desc->tag,+ "%s probe: failed to load/resolve library; trying next backend",+ b->desc->name);+ gpu_backend_unlink(b);+ } else {+ // 255 or killed by an uncaught signal: the probe call faulted.+ llamafile_info(b->desc->tag, "%s crashed during device probe; trying next backend",+ b->desc->name);+ gpu_backend_unlink(b);+ }+ }++ free(envp);+ free(dso_var);+ free(sym_var);+ return available;+}diff --git a/llamafile/gpu_backend.h b/llamafile/gpu_backend.hindex 3624e286..9f6305cc 100644--- a/llamafile/gpu_backend.h+++ b/llamafile/gpu_backend.h@@ -17,6 +17,7 @@#ifndef LLAMAFILE_GPU_BACKEND_H_#define LLAMAFILE_GPU_BACKEND_H_+#include <limits.h>#include <stdatomic.h>#include <stdbool.h>#include <stddef.h>@@ -80,6 +81,9 @@ typedef struct GpuBackend {void *get_device_count;void *get_device_description;void *log_set;+ // Resolved on-disk path of the loaded DSO, recorded by gpu_backend_link().+ // The out-of-process probe needs it to tell the child what to dlopen.+ char lib_path[PATH_MAX];} GpuBackend;// dlopen `dso` and resolve `desc`'s symbols into `b`, recording `desc` as the@@ -101,6 +105,18 @@ void gpu_backend_unlink(GpuBackend *b);// backend has at least one device and should be registered.bool gpu_backend_probe(GpuBackend *b);+// Same contract as gpu_backend_probe(), but runs the device-count call in a+// short-lived child process (a re-exec of this binary) instead of under an+// in-process signal guard. Used on Windows, where the foreign driver-init code+// behind get_device_count() can throw a C++/SEH exception across the+// cosmo_dlopen/ms_abi boundary; catching it in-process and siglongjmp-ing out+// leaves the process corrupted (silent exit later, issue #988 follow-up). A+// crash here dies in the child, and the parent never executes the faulting+// driver-init code for a device-less backend, so CPU fallback stays clean+// regardless of how deep the fault is. Requires gpu_backend_link() to have run+// (it needs b->lib_path).+bool gpu_backend_probe_oop(GpuBackend *b);+// Call backend_reg() and, if it returns a registry, hand it to// ggml_backend_register(), logging "<name> backend registered with GGML". Safe// to call only after gpu_backend_probe() returned true.diff --git a/llamafile/vulkan.c b/llamafile/vulkan.cindex 5ac19111..55cd27bb 100644--- a/llamafile/vulkan.c+++ b/llamafile/vulkan.c@@ -83,8 +83,10 @@ static bool ImportVulkanImpl(void) {// Gate on device count before registering (issue #988). The DSO loads even// when Vulkan has no usable device; without this check we'd register a// 0-device backend and block fallback to CPU. gpu_backend_probe() unlinks- // and returns false in that case so AUTO mode moves on.- if (!gpu_backend_probe(&g_vulkan))+ // and returns false in that case so AUTO mode moves on. On Windows a+ // faulting Vulkan driver init behind get_device_count() can corrupt the+ // process if caught in-process, so probe out-of-process there (#988).+ if (!(IsWindows() ? gpu_backend_probe_oop(&g_vulkan) : gpu_backend_probe(&g_vulkan)))return false;gpu_backend_register(&g_vulkan);