Skip to content

Distribute and run LLMs with a single file.

Add support for vulkan dylibs (#892)

Davide Eynardc7d7e3e575d1
diff --git a/Makefile b/Makefile
index e1b216ee..1631934f 100644
--- a/Makefile
+++ b/Makefile
@@ -58,6 +58,10 @@ cublas: # Build CUDA backend with cuBLAS (NVIDIA GPUs, requires cuBLAS at runtim
rocm: # Build ROCm backend with TinyBLAS (AMD GPUs)
GGML_VERSION=$(GGML_VERSION) GGML_COMMIT=$(GGML_COMMIT) llamafile/rocm.sh
+.PHONY: vulkan
+vulkan: # Build Vulkan backend (cross-platform GPUs)
+ GGML_VERSION=$(GGML_VERSION) GGML_COMMIT=$(GGML_COMMIT) llamafile/vulkan.sh
+
.PHONY: cosmocc
cosmocc: $(COSMOCC) # cosmocc toolchain setup
diff --git a/llama.cpp.patches/llamafile-files/BUILD.mk b/llama.cpp.patches/llamafile-files/BUILD.mk
index 857ab993..216e745e 100644
--- a/llama.cpp.patches/llamafile-files/BUILD.mk
+++ b/llama.cpp.patches/llamafile-files/BUILD.mk
@@ -344,11 +344,12 @@ TOOL_IMATRIX_OBJS := $(TOOL_IMATRIX_SRCS:%.cpp=o/$(MODE)/%.cpp.o)
TOOL_PERPLEXITY_OBJS := $(TOOL_PERPLEXITY_SRCS:%.cpp=o/$(MODE)/%.cpp.o)
TOOL_BENCH_OBJS := $(TOOL_BENCH_SRCS:%.cpp=o/$(MODE)/%.cpp.o)
TOOL_SERVER_OBJS := $(TOOL_SERVER_SRCS:%.cpp=o/$(MODE)/%.cpp.o)
-# llamafile objects are used to add dynamic GPU support (Metal, CUDA, ROCm)
+# llamafile objects are used to add dynamic GPU support (Metal, CUDA, ROCm, Vulkan)
TOOL_LLAMAFILE_OBJS := \
o/$(MODE)/llamafile/llamafile.o \
o/$(MODE)/llamafile/metal.o \
o/$(MODE)/llamafile/cuda.o \
+ o/$(MODE)/llamafile/vulkan.o \
o/$(MODE)/llamafile/zip.o
# Server objects depend on generated assets
diff --git a/llama.cpp.patches/patches/common_common.cpp.patch b/llama.cpp.patches/patches/common_common.cpp.patch
index a45bb7ac..a413ac99 100644
--- a/llama.cpp.patches/patches/common_common.cpp.patch
+++ b/llama.cpp.patches/patches/common_common.cpp.patch
@@ -18,3 +18,36 @@ diff --git a/common/common.cpp b/common/common.cpp
#elif defined(__EMSCRIPTEN__)
GGML_ABORT("not implemented on this platform");
#else
+@@ -1050,10 +1060,31 @@ common_init_result::common_init_result(common_params & params) :
+
+ if (params.fit_params) {
+ LOG_INF("%s: fitting params to device memory, for bugs during this step try to reproduce them with -fit off, or provide --verbose logs if the bug only occurs with -fit on\n", __func__);
++
++ // if a multimodal projection model is specified and will be loaded on GPU,
++ // add its estimated size to the fit margins so the fit leaves enough room for it
++ std::vector<size_t> fit_params_target = params.fit_params_target;
++ if (!params.mmproj.path.empty() && params.mmproj_use_gpu) {
++ struct gguf_init_params gparams = { /*.no_alloc =*/ true, /*.ctx =*/ nullptr };
++ struct gguf_context * gctx = gguf_init_from_file(params.mmproj.path.c_str(), gparams);
++ if (gctx != nullptr) {
++ size_t mmproj_size = 0;
++ for (int64_t i = 0; i < gguf_get_n_tensors(gctx); i++) {
++ mmproj_size += gguf_get_tensor_size(gctx, i);
++ }
++ gguf_free(gctx);
++ LOG_INF("%s: reserving %.2f MiB extra for mmproj model '%s'\n", __func__,
++ mmproj_size / (1024.0 * 1024.0), params.mmproj.path.c_str());
++ for (size_t & target : fit_params_target) {
++ target += mmproj_size;
++ }
++ }
++ }
++
+ llama_params_fit(params.model.path.c_str(), &mparams, &cparams,
+ params.tensor_split,
+ params.tensor_buft_overrides.data(),
+- params.fit_params_target.data(),
++ fit_params_target.data(),
+ params.fit_params_min_ctx,
+ params.verbosity >= 4 ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_ERROR);
+ }
diff --git a/llama.cpp.patches/patches/ggml_src_ggml-vulkan_ggml-vulkan.cpp.patch b/llama.cpp.patches/patches/ggml_src_ggml-vulkan_ggml-vulkan.cpp.patch
new file mode 100644
index 00000000..cf89aace
--- /dev/null
+++ b/llama.cpp.patches/patches/ggml_src_ggml-vulkan_ggml-vulkan.cpp.patch
@@ -0,0 +1,46 @@
+diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp
+--- a/llama.cpp/ggml/src/ggml-vulkan/ggml-vulkan.cpp
++++ b/llama.cpp/ggml/src/ggml-vulkan/ggml-vulkan.cpp
+@@ -13229,6 +13229,14 @@ static void ggml_backend_vk_buffer_free_buffer(ggml_backend_buffer_t buffer) {
+ delete ctx;
+ }
+
++// free_struct callback for cross-module memory management
++// When the Vulkan backend is loaded as a dynamic library, the buffer struct
++// is allocated by the dylib's 'new' operator and must be freed by the dylib's
++// 'delete' operator (not the main executable's)
++static void ggml_backend_vk_buffer_free_struct(ggml_backend_buffer_t buffer) {
++ delete buffer;
++}
++
+ static void * ggml_backend_vk_buffer_get_base(ggml_backend_buffer_t buffer) {
+ return vk_ptr_base;
+
+@@ -13302,6 +13310,7 @@ static ggml_backend_buffer_i ggml_backend_vk_buffer_interface = {
+ /* .cpy_tensor = */ ggml_backend_vk_buffer_cpy_tensor,
+ /* .clear = */ ggml_backend_vk_buffer_clear,
+ /* .reset = */ NULL,
++ /* .free_struct = */ ggml_backend_vk_buffer_free_struct,
+ };
+
+ // vk buffer type
+@@ -13388,6 +13397,7 @@ static ggml_backend_buffer_t ggml_backend_vk_host_buffer_type_alloc_buffer(ggml_
+ ggml_backend_buffer_t buffer = ggml_backend_cpu_buffer_from_ptr(ptr, size);
+ buffer->buft = buft;
+ buffer->iface.free_buffer = ggml_backend_vk_host_buffer_free_buffer;
++ buffer->iface.free_struct = ggml_backend_vk_buffer_free_struct;
+
+ return buffer;
+
+@@ -14796,7 +14806,10 @@ void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total
+ *total += heap.size;
+
+ if (membudget_supported && i < budgetprops.heapUsage.size()) {
+- *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
++ // heapUsage can exceed heapBudget (permitted by spec); clamp to 0 to avoid underflow
++ if (budgetprops.heapBudget[i] > budgetprops.heapUsage[i]) {
++ *free += budgetprops.heapBudget[i] - budgetprops.heapUsage[i];
++ }
+ } else {
+ *free += heap.size;
+ }
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 7b36535a..05a6d51e 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -123,6 +123,7 @@ LLAMAFILE_SRCS_C := \
llamafile/cuda.c \
llamafile/llamafile.c \
llamafile/metal.c \
+ llamafile/vulkan.c \
llamafile/zip.c
LLAMAFILE_SRCS_CPP := \
diff --git a/llamafile/cuda.c b/llamafile/cuda.c
index ff2cbbc2..c20b0380 100644
--- a/llamafile/cuda.c
+++ b/llamafile/cuda.c
@@ -69,54 +69,6 @@ static struct CudaBackend {
void (*log_set)(llamafile_log_callback log_callback, void *user_data);
} g_cuda;
-static const char *GetDsoExtension(void) {
- if (IsWindows())
- return "dll";
- else
- return "so";
-}
-
-static bool FileExists(const char *path) {
- struct stat st;
- return !stat(path, &st);
-}
-
-static int makedirs(const char *path, mode_t mode) {
- char tmp[PATH_MAX];
- char *p = NULL;
- size_t len;
-
- snprintf(tmp, sizeof(tmp), "%s", path);
- len = strlen(tmp);
-
- if (tmp[len - 1] == '/')
- tmp[len - 1] = '\0';
-
- if (mkdir(tmp, mode) == 0)
- return 0;
-
- if (errno == EEXIST) {
- struct stat st;
- if (stat(tmp, &st) == 0 && S_ISDIR(st.st_mode))
- return 0;
- return -1;
- }
-
- if (errno != ENOENT)
- return -1;
-
- for (p = tmp + 1; *p; p++) {
- if (*p == '/') {
- *p = '\0';
- if (mkdir(tmp, mode) != 0 && errno != EEXIST)
- return -1;
- *p = '/';
- }
- }
-
- return mkdir(tmp, mode);
-}
-
static bool LinkCuda(const char *dso) {
// Load dynamic shared object using Cosmopolitan's dlopen
void *lib = cosmo_dlopen(dso, RTLD_LAZY);
@@ -160,72 +112,6 @@ static bool LinkCuda(const char *dso) {
return true;
}
-static bool TryLoadPrebuiltDso(const char *name) {
- char dso[PATH_MAX];
- char app_dir[PATH_MAX];
-
- // Try loading from /zip/ (bundled in executable)
- snprintf(dso, PATH_MAX, "/zip/%s", name);
- if (FileExists(dso)) {
- // Extract to app dir first (cosmo_dlopen can't load from /zip/)
- llamafile_get_app_dir(app_dir, PATH_MAX);
- if (makedirs(app_dir, 0755) != 0) {
- perror(app_dir);
- return false;
- }
- char extracted[PATH_MAX];
- if (snprintf(extracted, PATH_MAX, "%s%s", app_dir, name) >= PATH_MAX) {
- fprintf(stderr, "cuda: path too long: %s%s\n", app_dir, name);
- return false;
- }
- // Check if extraction needed
- switch (llamafile_is_file_newer_than(dso, extracted)) {
- case -1:
- return false;
- case 0:
- // Already extracted and up to date
- break;
- case 1:
- if (!llamafile_extract(dso, extracted)) {
- return false;
- }
- break;
- }
-
- if (LinkCuda(extracted)) {
- if (FLAG_verbose)
- fprintf(stderr, "cuda: loaded bundled %s\n", name);
- return true;
- }
- }
-
- // Try loading from app directory
- llamafile_get_app_dir(app_dir, PATH_MAX);
- snprintf(dso, PATH_MAX, "%s%s", app_dir, name);
- if (FileExists(dso)) {
- if (LinkCuda(dso)) {
- if (FLAG_verbose)
- fprintf(stderr, "cuda: loaded %s from app directory\n", name);
- return true;
- }
- }
-
- // Try loading from home directory (common build location)
- const char *home = getenv("HOME");
- if (home && *home) {
- snprintf(dso, PATH_MAX, "%s/%s", home, name);
- if (FileExists(dso)) {
- if (LinkCuda(dso)) {
- if (FLAG_verbose)
- fprintf(stderr, "cuda: loaded %s from home directory\n", name);
- return true;
- }
- }
- }
-
- return false;
-}
-
static bool ImportCudaImpl(void) {
// Skip on Apple Silicon (use Metal instead)
if (IsXnuSilicon()) {
@@ -245,7 +131,7 @@ static bool ImportCudaImpl(void) {
}
// Determine DSO name based on GPU type
- const char *ext = GetDsoExtension();
+ const char *ext = llamafile_get_dso_extension();
char cuda_dso[64];
char rocm_dso[64];
snprintf(cuda_dso, sizeof(cuda_dso), "ggml-cuda.%s", ext);
@@ -253,14 +139,14 @@ static bool ImportCudaImpl(void) {
// Try to load pre-built DSO
if (FLAG_gpu == LLAMAFILE_GPU_AMD || FLAG_gpu == LLAMAFILE_GPU_AUTO) {
- if (TryLoadPrebuiltDso(rocm_dso)) {
+ if (llamafile_try_load_prebuilt_dso(rocm_dso, "cuda", LinkCuda)) {
g_cuda.is_amd = true;
goto RegisterBackend;
}
}
if (FLAG_gpu == LLAMAFILE_GPU_NVIDIA || FLAG_gpu == LLAMAFILE_GPU_AUTO) {
- if (TryLoadPrebuiltDso(cuda_dso)) {
+ if (llamafile_try_load_prebuilt_dso(cuda_dso, "cuda", LinkCuda)) {
g_cuda.is_amd = false;
goto RegisterBackend;
}
diff --git a/llamafile/llamafile.c b/llamafile/llamafile.c
index bf52c940..348045e2 100644
--- a/llamafile/llamafile.c
+++ b/llamafile/llamafile.c
@@ -627,6 +627,143 @@ int llamafile_is_file_newer_than(const char *path, const char *other) {
return is_file_newer_than_time(path, other);
}
+/**
+ * Returns the platform-specific dynamic library extension.
+ */
+const char *llamafile_get_dso_extension(void) {
+ if (IsWindows())
+ return "dll";
+ else if (IsXnu())
+ return "dylib";
+ else
+ return "so";
+}
+
+/**
+ * Returns true if the file at path exists.
+ */
+bool llamafile_file_exists(const char *path) {
+ struct stat st;
+ return !stat(path, &st);
+}
+
+/**
+ * Creates directories recursively, like `mkdir -p`.
+ * Returns 0 on success, -1 on error.
+ */
+int llamafile_makedirs(const char *path, int mode) {
+ char tmp[PATH_MAX];
+ char *p = NULL;
+ size_t len;
+
+ snprintf(tmp, sizeof(tmp), "%s", path);
+ len = strlen(tmp);
+
+ if (tmp[len - 1] == '/')
+ tmp[len - 1] = '\0';
+
+ if (mkdir(tmp, mode) == 0)
+ return 0;
+
+ if (errno == EEXIST) {
+ struct stat st;
+ if (stat(tmp, &st) == 0 && S_ISDIR(st.st_mode))
+ return 0;
+ return -1;
+ }
+
+ if (errno != ENOENT)
+ return -1;
+
+ for (p = tmp + 1; *p; p++) {
+ if (*p == '/') {
+ *p = '\0';
+ if (mkdir(tmp, mode) != 0 && errno != EEXIST)
+ return -1;
+ *p = '/';
+ }
+ }
+
+ return mkdir(tmp, mode);
+}
+
+/**
+ * Try to load a prebuilt DSO from standard locations.
+ *
+ * Search order:
+ * 1. /zip/<name> (bundled in executable, extracted to app dir)
+ * 2. ~/.llamafile/v/<version>/<name> (app directory)
+ * 3. ~/<name> (home directory)
+ *
+ * Returns true if link_fn successfully loaded the DSO.
+ */
+bool llamafile_try_load_prebuilt_dso(const char *name, const char *backend_name,
+ llamafile_link_dso_fn link_fn) {
+ char dso[PATH_MAX];
+ char app_dir[PATH_MAX];
+
+ // Try loading from /zip/ (bundled in executable)
+ snprintf(dso, PATH_MAX, "/zip/%s", name);
+ if (llamafile_file_exists(dso)) {
+ // Extract to app dir first (cosmo_dlopen can't load from /zip/)
+ llamafile_get_app_dir(app_dir, PATH_MAX);
+ if (llamafile_makedirs(app_dir, 0755) != 0) {
+ perror(app_dir);
+ return false;
+ }
+ char extracted[PATH_MAX];
+ if (snprintf(extracted, PATH_MAX, "%s%s", app_dir, name) >= PATH_MAX) {
+ fprintf(stderr, "%s: path too long: %s%s\n", backend_name, app_dir, name);
+ return false;
+ }
+ // Check if extraction needed
+ switch (llamafile_is_file_newer_than(dso, extracted)) {
+ case -1:
+ return false;
+ case 0:
+ // Already extracted and up to date
+ break;
+ case 1:
+ if (!llamafile_extract(dso, extracted)) {
+ return false;
+ }
+ break;
+ }
+
+ if (link_fn(extracted)) {
+ if (FLAG_verbose)
+ fprintf(stderr, "%s: loaded bundled %s\n", backend_name, name);
+ return true;
+ }
+ }
+
+ // Try loading from app directory
+ llamafile_get_app_dir(app_dir, PATH_MAX);
+ snprintf(dso, PATH_MAX, "%s%s", app_dir, name);
+ if (llamafile_file_exists(dso)) {
+ if (link_fn(dso)) {
+ if (FLAG_verbose)
+ fprintf(stderr, "%s: loaded %s from app directory\n", backend_name, name);
+ return true;
+ }
+ }
+
+ // Try loading from home directory (common build location)
+ const char *home = getenv("HOME");
+ if (home && *home) {
+ snprintf(dso, PATH_MAX, "%s/%s", home, name);
+ if (llamafile_file_exists(dso)) {
+ if (link_fn(dso)) {
+ if (FLAG_verbose)
+ fprintf(stderr, "%s: loaded %s from home directory\n", backend_name, name);
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
// ==============================================================================
// Logging
// ==============================================================================
@@ -644,7 +781,7 @@ void llamafile_log_callback_null(int level, const char *text, void *user_data) {
// llamafile_has_cuda() and llamafile_has_amd_gpu() are defined in cuda.c
bool llamafile_has_gpu(void) {
- return llamafile_has_metal() || llamafile_has_cuda() || llamafile_has_amd_gpu();
+ return llamafile_has_metal() || llamafile_has_cuda() || llamafile_has_amd_gpu() || llamafile_has_vulkan();
}
const char *llamafile_describe_gpu(void) {
@@ -657,6 +794,8 @@ const char *llamafile_describe_gpu(void) {
return "apple";
case LLAMAFILE_GPU_NVIDIA:
return "nvidia";
+ case LLAMAFILE_GPU_VULKAN:
+ return "vulkan";
case LLAMAFILE_GPU_DISABLE:
return "disabled";
default:
@@ -675,6 +814,8 @@ int llamafile_gpu_parse(const char *s) {
return LLAMAFILE_GPU_APPLE;
if (!strcasecmp(s, "nvidia") || !strcasecmp(s, "cublas"))
return LLAMAFILE_GPU_NVIDIA;
+ if (!strcasecmp(s, "vulkan") || !strcasecmp(s, "vk"))
+ return LLAMAFILE_GPU_VULKAN;
return LLAMAFILE_GPU_ERROR;
}
diff --git a/llamafile/llamafile.h b/llamafile/llamafile.h
index a8d6c05e..534c0f1a 100644
--- a/llamafile/llamafile.h
+++ b/llamafile/llamafile.h
@@ -80,6 +80,19 @@ void llamafile_get_app_dir(char *, size_t);
bool llamafile_extract(const char *, const char *);
int llamafile_is_file_newer_than(const char *, const char *);
+// Common utilities for GPU backend loaders (defined in llamafile.c)
+const char *llamafile_get_dso_extension(void);
+bool llamafile_file_exists(const char *);
+int llamafile_makedirs(const char *, int);
+
+// Link function type for TryLoadPrebuiltDso
+typedef bool (*llamafile_link_dso_fn)(const char *dso_path);
+
+// Try to load a prebuilt DSO from /zip/, app dir, or home dir
+// Returns true if successfully loaded via link_fn
+bool llamafile_try_load_prebuilt_dso(const char *name, const char *backend_name,
+ llamafile_link_dso_fn link_fn);
+
// =============================================================================
// GPU detection and configuration
// =============================================================================
@@ -90,11 +103,13 @@ int llamafile_is_file_newer_than(const char *, const char *);
#define LLAMAFILE_GPU_AMD 1
#define LLAMAFILE_GPU_APPLE 2
#define LLAMAFILE_GPU_NVIDIA 4
+#define LLAMAFILE_GPU_VULKAN 8
bool llamafile_has_gpu(void); // Defined in llamafile.c
bool llamafile_has_metal(void); // Defined in metal.c (dynamic loader)
bool llamafile_has_cuda(void); // Defined in cuda.c (dynamic loader)
bool llamafile_has_amd_gpu(void); // Defined in cuda.c (dynamic loader)
+bool llamafile_has_vulkan(void); // Defined in vulkan.c (dynamic loader)
int llamafile_gpu_parse(const char *); // Defined in llamafile.c
const char *llamafile_describe_gpu(void); // Defined in llamafile.c
void llamafile_early_gpu_init(char **); // Defined in llamafile.c
@@ -113,6 +128,10 @@ void llamafile_metal_log_set(llamafile_log_callback log_callback, void *user_dat
// Pass a no-op callback to disable logging
void llamafile_cuda_log_set(llamafile_log_callback log_callback, void *user_data);
+// Set logging callback for Vulkan dylib (defined in vulkan.c)
+// Pass a no-op callback to disable logging
+void llamafile_vulkan_log_set(llamafile_log_callback log_callback, void *user_data);
+
#ifdef __cplusplus
}
#endif
diff --git a/llamafile/metal.c b/llamafile/metal.c
index 267b6184..68ae1fa3 100644
--- a/llamafile/metal.c
+++ b/llamafile/metal.c
@@ -158,42 +158,6 @@ static struct MetalBackend {
void (*log_set)(llamafile_log_callback log_callback, void *user_data);
} g_metal;
-static int makedirs(const char *path, mode_t mode) {
- char tmp[PATH_MAX];
- char *p = NULL;
- size_t len;
-
- snprintf(tmp, sizeof(tmp), "%s", path);
- len = strlen(tmp);
-
- if (tmp[len - 1] == '/')
- tmp[len - 1] = '\0';
-
- if (mkdir(tmp, mode) == 0)
- return 0;
-
- if (errno == EEXIST) {
- struct stat st;
- if (stat(tmp, &st) == 0 && S_ISDIR(st.st_mode))
- return 0;
- return -1;
- }
-
- if (errno != ENOENT)
- return -1;
-
- for (p = tmp + 1; *p; p++) {
- if (*p == '/') {
- *p = '\0';
- if (mkdir(tmp, mode) != 0 && errno != EEXIST)
- return -1;
- *p = '/';
- }
- }
-
- return mkdir(tmp, mode);
-}
-
static char *read_file(const char *path, size_t *size_out) {
FILE *f = fopen(path, "r");
if (!f) return NULL;
@@ -335,7 +299,7 @@ static bool BuildMetal(const char *dso) {
}
// Create app directory
- if (makedirs(app_dir, 0755) != 0) {
+ if (llamafile_makedirs(app_dir, 0755) != 0) {
perror(app_dir);
return false;
}
@@ -351,7 +315,7 @@ static bool BuildMetal(const char *dso) {
size_t parent_len = last_slash - src;
memcpy(parent_dir, src, parent_len);
parent_dir[parent_len] = '\0';
- makedirs(parent_dir, 0755);
+ llamafile_makedirs(parent_dir, 0755);
}
switch (llamafile_is_file_newer_than(metal_srcs[i].zip, src)) {
diff --git a/llamafile/vulkan.c b/llamafile/vulkan.c
new file mode 100644
index 00000000..2890009b
--- /dev/null
+++ b/llamafile/vulkan.c
@@ -0,0 +1,212 @@
+// -*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// Copyright 2024 Mozilla Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//
+// Runtime Vulkan GPU support for llamafile
+//
+// This file implements dynamic loading of Vulkan GPU support.
+// At runtime on Linux/Windows/macOS with Vulkan-compatible GPU:
+// 1. Try to load pre-built DSO from /zip/ggml-vulkan.so (bundled)
+// 2. Or try to load from ~/.llamafile/ (pre-compiled)
+// 3. Load the DSO with cosmo_dlopen() and register the Vulkan backend
+//
+
+#include "llamafile.h"
+#include <cosmo.h>
+#include <dlfcn.h>
+#include <errno.h>
+#include <limits.h>
+#include <pthread.h>
+#include <stdatomic.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+// Forward declarations for ggml backend types
+typedef struct ggml_backend * ggml_backend_t;
+typedef struct ggml_backend_reg * ggml_backend_reg_t;
+
+// Function to register a backend with ggml (from ggml-backend.h)
+extern void ggml_backend_register(ggml_backend_reg_t reg);
+
+// Log callback type (must match ggml_log_callback from ggml.h)
+typedef void (*llamafile_log_callback)(int level, const char *text, void *user_data);
+
+// Vulkan backend state
+static struct VulkanBackend {
+ bool supported;
+ atomic_uint once;
+ void *lib_handle;
+
+ // Function pointers for Vulkan backend
+ ggml_backend_t (*backend_init)(size_t device);
+ ggml_backend_reg_t (*backend_reg)(void);
+ int (*get_device_count)(void);
+ void (*get_device_description)(int device, char *description, size_t description_size);
+
+ // Logging control
+ void (*log_set)(llamafile_log_callback log_callback, void *user_data);
+} g_vulkan;
+
+static bool LinkVulkan(const char *dso) {
+ // Load dynamic shared object using Cosmopolitan's dlopen
+ void *lib = cosmo_dlopen(dso, RTLD_LAZY);
+ if (!lib) {
+ char *err = cosmo_dlerror();
+ fprintf(stderr, "vulkan: %s: failed to load library\n", err ? err : "unknown error");
+ return false;
+ }
+
+ // Import functions
+ bool ok = true;
+
+ *(void **)(&g_vulkan.backend_init) = cosmo_dlsym(lib, "ggml_backend_vk_init");
+ ok &= (g_vulkan.backend_init != NULL);
+
+ *(void **)(&g_vulkan.backend_reg) = cosmo_dlsym(lib, "ggml_backend_vk_reg");
+ ok &= (g_vulkan.backend_reg != NULL);
+
+ *(void **)(&g_vulkan.get_device_count) = cosmo_dlsym(lib, "ggml_backend_vk_get_device_count");
+ // Optional - don't fail if not found
+
+ *(void **)(&g_vulkan.get_device_description) = cosmo_dlsym(lib, "ggml_backend_vk_get_device_description");
+ // Optional - don't fail if not found
+
+ // Import logging control (optional)
+ *(void **)(&g_vulkan.log_set) = cosmo_dlsym(lib, "ggml_log_set");
+
+ if (!ok) {
+ char *err = cosmo_dlerror();
+ fprintf(stderr, "vulkan: %s: not all symbols could be imported\n", err ? err : "unknown error");
+ g_vulkan.backend_init = NULL;
+ g_vulkan.backend_reg = NULL;
+ g_vulkan.get_device_count = NULL;
+ g_vulkan.get_device_description = NULL;
+ g_vulkan.log_set = NULL;
+ cosmo_dlclose(lib);
+ return false;
+ }
+
+ g_vulkan.lib_handle = lib;
+ return true;
+}
+
+static bool ImportVulkanImpl(void) {
+ // Note: Unlike CUDA, we don't skip Apple Silicon here because
+ // Vulkan works on macOS via MoltenVK (Vulkan-to-Metal translation)
+
+ // Check if we're allowed to even try
+ switch (FLAG_gpu) {
+ case LLAMAFILE_GPU_AUTO:
+ case LLAMAFILE_GPU_VULKAN:
+ break;
+ default:
+ return false;
+ }
+
+ // Determine DSO name
+ const char *ext = llamafile_get_dso_extension();
+ char vulkan_dso[64];
+ snprintf(vulkan_dso, sizeof(vulkan_dso), "ggml-vulkan.%s", ext);
+
+ // Try to load pre-built DSO
+ if (!llamafile_try_load_prebuilt_dso(vulkan_dso, "vulkan", LinkVulkan)) {
+ // No pre-built DSO found
+ if (FLAG_verbose) {
+ fprintf(stderr, "vulkan: no pre-built GPU library found\n");
+ fprintf(stderr, "vulkan: to enable Vulkan support, build with:\n");
+ fprintf(stderr, "vulkan: llamafile/vulkan.sh\n");
+ }
+ return false;
+ }
+
+ // Register the Vulkan backend with GGML
+ if (g_vulkan.backend_reg) {
+ ggml_backend_reg_t reg = g_vulkan.backend_reg();
+ if (reg) {
+ ggml_backend_register(reg);
+ if (FLAG_verbose)
+ fprintf(stderr, "vulkan: Vulkan backend registered with GGML\n");
+ }
+ }
+
+ return true;
+}
+
+static void ImportVulkan(void) {
+ if (ImportVulkanImpl()) {
+ g_vulkan.supported = true;
+ if (FLAG_verbose) {
+ fprintf(stderr, "vulkan: Vulkan GPU support successfully loaded\n");
+ if (g_vulkan.get_device_count) {
+ int count = g_vulkan.get_device_count();
+ fprintf(stderr, "vulkan: found %d GPU device(s)\n", count);
+ }
+ }
+ } else if (FLAG_gpu == LLAMAFILE_GPU_VULKAN) {
+ fprintf(stderr, "fatal error: support for --gpu vulkan was explicitly requested, "
+ "but it wasn't available\n");
+ exit(1);
+ }
+}
+
+bool llamafile_has_vulkan(void) {
+ cosmo_once(&g_vulkan.once, ImportVulkan);
+ return g_vulkan.supported;
+}
+
+// Wrapper functions for dynamically loaded Vulkan backend
+
+ggml_backend_t ggml_backend_vk_init(size_t device) {
+ if (!llamafile_has_vulkan())
+ return NULL;
+ if (!g_vulkan.backend_init)
+ return NULL;
+ return g_vulkan.backend_init(device);
+}
+
+int ggml_backend_vk_get_device_count(void) {
+ if (!llamafile_has_vulkan())
+ return 0;
+ if (!g_vulkan.get_device_count)
+ return 0;
+ return g_vulkan.get_device_count();
+}
+
+void ggml_backend_vk_get_device_description(int device, char *description, size_t description_size) {
+ if (!llamafile_has_vulkan()) {
+ if (description_size > 0)
+ description[0] = '\0';
+ return;
+ }
+ if (!g_vulkan.get_device_description) {
+ if (description_size > 0)
+ snprintf(description, description_size, "Vulkan GPU %d", device);
+ return;
+ }
+ g_vulkan.get_device_description(device, description, description_size);
+}
+
+void llamafile_vulkan_log_set(llamafile_log_callback log_callback, void *user_data) {
+ if (!llamafile_has_vulkan())
+ return;
+ if (g_vulkan.log_set)
+ g_vulkan.log_set(log_callback, user_data);
+}
diff --git a/llamafile/vulkan.sh b/llamafile/vulkan.sh
new file mode 100755
index 00000000..ea505a8c
--- /dev/null
+++ b/llamafile/vulkan.sh
@@ -0,0 +1,300 @@
+#!/bin/bash
+#
+# Vulkan build script for llamafile (parallel compilation)
+#
+# This script compiles the GGML Vulkan backend into a shared library.
+# Unlike CUDA/ROCm, Vulkan uses standard C++ compilers (g++/clang++),
+# not vendor-specific compilers.
+#
+# Build process:
+# 1. Build vulkan-shaders-gen tool (C++17)
+# 2. Generate shader C++ files from GLSL compute shaders using glslc
+# 3. Compile ggml-vulkan.cpp with generated shaders
+# 4. Compile core GGML sources
+# 5. Link into ggml-vulkan.so
+#
+# Requirements:
+# - Vulkan SDK with glslc compiler
+# - C++17 compatible compiler (g++ or clang++)
+# - libvulkan development files
+#
+# Usage:
+# ./vulkan.sh # Build with auto-detected parallelism
+# ./vulkan.sh -j16 # Build with 16 parallel jobs
+# ./vulkan.sh --clean # Clean and rebuild
+# ./vulkan.sh --output /path/to/output.so
+#
+# Output: ~/ggml-vulkan.so (default)
+#
+
+set -e
+
+# Source shared build functions
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+source "$SCRIPT_DIR/build-functions.sh"
+
+# Parse arguments (sets JOBS, CLEAN)
+parse_build_args "$@"
+
+#
+# Vulkan-specific configuration
+#
+
+# Determine library extension based on platform
+# Cosmopolitan's cosmo_dlopen expects .dylib on macOS, .so on Linux
+if [ "$(uname -s)" = "Darwin" ]; then
+ DSO_EXT="dylib"
+else
+ DSO_EXT="so"
+fi
+
+OUTPUT="${OUTPUT:-${HOME}/ggml-vulkan.${DSO_EXT}}"
+
+# Find compilers
+CXX="${CXX:-$(command -v g++ 2>/dev/null || command -v clang++ 2>/dev/null)}"
+CC="${CC:-$(command -v gcc 2>/dev/null || command -v clang 2>/dev/null)}"
+
+if [ -z "$CXX" ]; then
+ echo "Error: No C++ compiler found (g++ or clang++)"
+ exit 1
+fi
+
+# Find glslc (Vulkan shader compiler)
+GLSLC="${GLSLC:-$(command -v glslc 2>/dev/null)}"
+if [ -z "$GLSLC" ]; then
+ # Try common Vulkan SDK locations
+ if [ -n "$VULKAN_SDK" ] && [ -x "$VULKAN_SDK/bin/glslc" ]; then
+ GLSLC="$VULKAN_SDK/bin/glslc"
+ elif [ -x "/usr/bin/glslc" ]; then
+ GLSLC="/usr/bin/glslc"
+ else
+ echo "Error: glslc not found. Please install the Vulkan SDK."
+ echo " Linux (Ubuntu/Debian): sudo apt install vulkan-sdk"
+ echo " Linux (Fedora): sudo dnf install vulkan-tools shaderc"
+ echo " Linux (Arch): sudo pacman -S vulkan-devel shaderc"
+ echo " macOS: brew install vulkan-sdk"
+ echo " Or set VULKAN_SDK environment variable"
+ exit 1
+ fi
+fi
+
+# Directory setup
+LLAMAFILE_DIR="$SCRIPT_DIR"
+LLAMA_CPP_DIR="$SCRIPT_DIR/../llama.cpp"
+GGML_VULKAN_DIR="$LLAMA_CPP_DIR/ggml/src/ggml-vulkan"
+SHADERS_DIR="$GGML_VULKAN_DIR/vulkan-shaders"
+
+if [ ! -d "$GGML_VULKAN_DIR" ]; then
+ echo "Error: Vulkan source directory not found: $GGML_VULKAN_DIR"
+ exit 1
+fi
+
+# Get version info (sets GGML_VERSION, GGML_COMMIT)
+get_ggml_version "$LLAMA_CPP_DIR"
+
+# Build directory
+BUILD_DIR="${HOME}/.cache/llamafile-vulkan-build"
+setup_build_dir "$BUILD_DIR" "$CLEAN"
+
+# Subdirectories
+SHADERS_BUILD_DIR="$BUILD_DIR/shaders"
+SPVDIR="$BUILD_DIR/spv"
+mkdir -p "$SHADERS_BUILD_DIR" "$SPVDIR"
+
+echo "Building ggml-vulkan.so (parallel)..."
+echo " Version: $GGML_VERSION (commit: $GGML_COMMIT)"
+echo " Source: $GGML_VULKAN_DIR"
+echo " Output: $OUTPUT"
+echo " Build: $BUILD_DIR"
+echo " Jobs: $JOBS"
+echo " CXX: $CXX"
+echo " glslc: $GLSLC"
+echo ""
+
+START_TIME=$(date +%s)
+
+#
+# Phase 1: Build vulkan-shaders-gen tool
+#
+echo "Phase 1: Building vulkan-shaders-gen..."
+
+SHADERS_GEN_SRC="$SHADERS_DIR/vulkan-shaders-gen.cpp"
+SHADERS_GEN_BIN="$BUILD_DIR/vulkan-shaders-gen"
+
+if [ ! -f "$SHADERS_GEN_BIN" ] || [ "$SHADERS_GEN_SRC" -nt "$SHADERS_GEN_BIN" ]; then
+ echo " Compiling vulkan-shaders-gen.cpp..."
+ $CXX -std=c++17 -O2 -o "$SHADERS_GEN_BIN" "$SHADERS_GEN_SRC" -lpthread
+else
+ echo " vulkan-shaders-gen is up to date"
+fi
+
+#
+# Phase 2: Generate shader header (contains declarations)
+#
+echo ""
+echo "Phase 2: Generating shader header..."
+
+SHADERS_HPP="$BUILD_DIR/ggml-vulkan-shaders.hpp"
+if [ ! -f "$SHADERS_HPP" ]; then
+ echo " Generating ggml-vulkan-shaders.hpp..."
+ "$SHADERS_GEN_BIN" \
+ --output-dir "$SPVDIR" \
+ --target-hpp "$SHADERS_HPP"
+else
+ echo " Shader header already exists"
+fi
+
+#
+# Phase 3: Compile shaders and generate C++ source files
+#
+echo ""
+echo "Phase 3: Compiling shaders..."
+
+# Collect shader files
+SHADER_FILES=$(find "$SHADERS_DIR" -maxdepth 1 -name "*.comp" -type f | sort)
+NUM_SHADERS=$(echo "$SHADER_FILES" | wc -l)
+echo " Found $NUM_SHADERS shader files"
+
+count=0
+for shader in $SHADER_FILES; do
+ count=$((count + 1))
+ shader_name=$(basename "$shader")
+ shader_cpp="$SHADERS_BUILD_DIR/${shader_name}.cpp"
+
+ # Skip if cpp file is newer than shader
+ if [ -f "$shader_cpp" ] && [ "$shader_cpp" -nt "$shader" ]; then
+ echo " [$count/$NUM_SHADERS] Skipping: $shader_name (up to date)"
+ continue
+ fi
+
+ echo " [$count/$NUM_SHADERS] Compiling: $shader_name"
+ "$SHADERS_GEN_BIN" \
+ --glslc "$GLSLC" \
+ --source "$shader" \
+ --output-dir "$SPVDIR" \
+ --target-hpp "$SHADERS_HPP" \
+ --target-cpp "$shader_cpp" &
+
+ # Limit parallel jobs
+ running=$(jobs -r | wc -l)
+ while [ "$running" -ge "$JOBS" ]; do
+ sleep 0.1
+ running=$(jobs -r | wc -l)
+ done
+done
+
+echo ""
+echo "Waiting for shader compilation to finish..."
+wait
+
+SHADER_TIME=$(date +%s)
+echo "Shader compilation took $((SHADER_TIME - START_TIME)) seconds"
+
+#
+# Phase 4: Compile shader C++ files
+#
+echo ""
+echo "Phase 4: Compiling shader C++ files..."
+
+SHADER_CPP_FILES=$(find "$SHADERS_BUILD_DIR" -name "*.cpp" -type f)
+NUM_SHADER_CPPS=$(echo "$SHADER_CPP_FILES" | wc -l)
+echo " Found $NUM_SHADER_CPPS shader C++ files"
+
+CXX_FLAGS="-O2 -fPIC -std=c++17 \
+ -I$LLAMA_CPP_DIR/ggml/include \
+ -I$LLAMA_CPP_DIR/ggml/src \
+ -I$BUILD_DIR \
+ -DNDEBUG \
+ -DGGML_BUILD=1 \
+ -DGGML_SHARED=1 \
+ -DGGML_MULTIPLATFORM"
+
+count=0
+for src in $SHADER_CPP_FILES; do
+ count=$((count + 1))
+ base=$(basename "$src" .cpp)
+ obj="$BUILD_DIR/shader-${base}.o"
+
+ # Skip if object file is newer than source
+ if [ -f "$obj" ] && [ "$obj" -nt "$src" ]; then
+ echo " [$count/$NUM_SHADER_CPPS] Skipping: $base (up to date)"
+ continue
+ fi
+
+ echo " [$count/$NUM_SHADER_CPPS] Compiling: $base"
+ $CXX -c $CXX_FLAGS -o "$obj" "$src" &
+
+ # Limit parallel jobs
+ running=$(jobs -r | wc -l)
+ while [ "$running" -ge "$JOBS" ]; do
+ sleep 0.1
+ running=$(jobs -r | wc -l)
+ done
+done
+
+echo ""
+echo "Waiting for shader C++ compilation to finish..."
+wait
+
+#
+# Phase 5: Compile ggml-vulkan.cpp
+#
+echo ""
+echo "Phase 5: Compiling ggml-vulkan.cpp..."
+
+VULKAN_OBJ="$BUILD_DIR/ggml-vulkan.o"
+VULKAN_SRC="$GGML_VULKAN_DIR/ggml-vulkan.cpp"
+
+if [ ! -f "$VULKAN_OBJ" ] || [ "$VULKAN_SRC" -nt "$VULKAN_OBJ" ] || [ "$SHADERS_HPP" -nt "$VULKAN_OBJ" ]; then
+ echo " Compiling ggml-vulkan.cpp..."
+ $CXX -c $CXX_FLAGS \
+ -I$GGML_VULKAN_DIR \
+ -o "$VULKAN_OBJ" "$VULKAN_SRC"
+else
+ echo " ggml-vulkan.o is up to date"
+fi
+
+#
+# Phase 6: Compile core GGML sources
+#
+echo ""
+echo "Phase 6: Compiling core GGML sources..."
+compile_ggml_core "$LLAMA_CPP_DIR" "$BUILD_DIR"
+
+#
+# Phase 7: Link
+#
+echo ""
+echo "Phase 7: Linking..."
+
+OBJ_FILES=$(find "$BUILD_DIR" -name "*.o" -type f | tr '\n' ' ')
+NUM_OBJS=$(find "$BUILD_DIR" -name "*.o" -type f | wc -l)
+echo " Linking $NUM_OBJS object files..."
+
+# Platform-specific link flags
+LINK_FLAGS="-shared -fPIC"
+if [ "$(uname -s)" = "Darwin" ]; then
+ # On macOS, set rpath so libvulkan can be found at runtime
+ # Check common locations for Vulkan SDK
+ if [ -n "$VULKAN_SDK" ] && [ -d "$VULKAN_SDK/lib" ]; then
+ VULKAN_LIB_PATH="$VULKAN_SDK/lib"
+ elif [ -d "/usr/local/lib" ] && [ -f "/usr/local/lib/libvulkan.dylib" ]; then
+ VULKAN_LIB_PATH="/usr/local/lib"
+ elif [ -d "/opt/homebrew/lib" ] && [ -f "/opt/homebrew/lib/libvulkan.dylib" ]; then
+ VULKAN_LIB_PATH="/opt/homebrew/lib"
+ else
+ echo "Warning: Could not find libvulkan location for rpath"
+ VULKAN_LIB_PATH="/usr/local/lib"
+ fi
+ LINK_FLAGS="$LINK_FLAGS -Wl,-rpath,$VULKAN_LIB_PATH -L$VULKAN_LIB_PATH"
+fi
+
+$CXX $LINK_FLAGS -o "$OUTPUT" $OBJ_FILES -lvulkan -lpthread
+
+# Done
+END_TIME=$(date +%s)
+echo ""
+echo "Total time: $((END_TIME - START_TIME)) seconds"
+echo ""
+echo "Successfully built: $OUTPUT"
+ls -lh "$OUTPUT"
diff --git a/whisperfile/BUILD.mk b/whisperfile/BUILD.mk
index 2a2568f1..d6a39747 100644
--- a/whisperfile/BUILD.mk
+++ b/whisperfile/BUILD.mk
@@ -102,6 +102,7 @@ WHISPERFILE_LLAMAFILE_OBJS := \
o/$(MODE)/llamafile/llamafile.o \
o/$(MODE)/llamafile/metal.o \
o/$(MODE)/llamafile/cuda.o \
+ o/$(MODE)/llamafile/vulkan.o \
o/$(MODE)/llamafile/zip.o \
o/$(MODE)/llamafile/check_cpu.o