Skip to content

Distribute and run LLMs with a single file.

Get Nvidia GPU support working with APE

Justine Tunney22b782f3d1cd
diff --git a/build/deps.mk b/build/deps.mk
index 8e53dd80..29cb9d05 100644
--- a/build/deps.mk
+++ b/build/deps.mk
@@ -3,13 +3,15 @@
SRCS = $(foreach x,$(PKGS),$($(x)_SRCS))
HDRS = $(foreach x,$(PKGS),$($(x)_HDRS))
+INCS = $(foreach x,$(PKGS),$($(x)_INCS))
-o/$(MODE)/depend: $(SRCS) $(HDRS)
+o/$(MODE)/depend: $(SRCS) $(HDRS) $(INCS)
@mkdir -p $(@D)
- mkdeps -o $@ -r o/$(MODE)/ $(SRCS) $(HDRS)
+ mkdeps -o $@ -r o/$(MODE)/ $(SRCS) $(HDRS) $(INCS)
$(SRCS):
$(HDRS):
+$(INCS):
.DEFAULT:
@echo
@echo NOTE: deleting o/$(MODE)/depend because of an unspecified prerequisite: $@
diff --git a/build/tags.mk b/build/tags.mk
index 5e2a0c73..dba1f380 100644
--- a/build/tags.mk
+++ b/build/tags.mk
@@ -14,7 +14,7 @@ TAGS: o/$(MODE)/tags-srcs.txt $(SRCS)
@rm -f $@
ctags $(TAGSFLAGS) -L $< -o $@
-HTAGS: o/$(MODE)/tags-hdrs.txt $(HDRS)
+HTAGS: o/$(MODE)/tags-hdrs.txt $(HDRS) $(INCS)
@rm -f $@
build/htags ctags -L $< -o $@
diff --git a/llama.cpp/BUILD.mk b/llama.cpp/BUILD.mk
index 2cb23eee..7db74d34 100644
--- a/llama.cpp/BUILD.mk
+++ b/llama.cpp/BUILD.mk
@@ -5,6 +5,7 @@ PKGS += LLAMA_CPP
LLAMA_CPP_FILES := $(wildcard llama.cpp/*.*)
LLAMA_CPP_HDRS = $(filter %.h,$(LLAMA_CPP_FILES))
+LLAMA_CPP_INCS = $(filter %.inc,$(LLAMA_CPP_FILES))
LLAMA_CPP_SRCS_C = $(filter %.c,$(LLAMA_CPP_FILES))
LLAMA_CPP_SRCS_CC = $(filter %.cc,$(LLAMA_CPP_FILES))
LLAMA_CPP_SRCS = $(LLAMA_CPP_SRCS_C) $(LLAMA_CPP_SRCS_CC)
diff --git a/llama.cpp/common.cc b/llama.cpp/common.cc
index 713f027c..673a3721 100644
--- a/llama.cpp/common.cc
+++ b/llama.cpp/common.cc
@@ -2,6 +2,7 @@
// vi: set net ft=c++ ts=4 sts=4 sw=4 fenc=utf-8 :vi
#include "common.h"
#include "llama.h"
+#include "ggml-cuda.h"
#include "ggml-metal.h"
#include "runtime.h"
@@ -517,7 +518,7 @@ bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
invalid_param = true;
break;
}
- if (ggml_metal_supported()) {
+ if (ggml_metal_supported() || ggml_cuda_supported()) {
params.n_gpu_layers = std::stoi(argv[i]);
} else {
fprintf(stderr, "warning: GPU offload not supported on this platform, --n-gpu-layers option will be ignored\n");
@@ -528,7 +529,7 @@ bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
invalid_param = true;
break;
}
- if (ggml_metal_supported()) {
+ if (ggml_metal_supported() || ggml_cuda_supported()) {
params.n_gpu_layers_draft = std::stoi(argv[i]);
} else {
fprintf(stderr, "warning: GPU offload not supported on this platform, --n-gpu-layers-draft option will be ignored\n");
@@ -539,17 +540,17 @@ bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
invalid_param = true;
break;
}
-#ifdef GGML_USE_CUBLAS
- params.main_gpu = std::stoi(argv[i]);
-#else
- fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
-#endif
+ if (ggml_cuda_supported()) {
+ params.main_gpu = std::stoi(argv[i]);
+ } else {
+ fprintf(stderr, "warning: cuBLAS GPU couldn't be supported on this system. It is not possible to set a main GPU.\n");
+ }
} else if (arg == "--tensor-split" || arg == "-ts") {
if (++i >= argc) {
invalid_param = true;
break;
}
-#ifdef GGML_USE_CUBLAS
+ if (ggml_cuda_supported()) {
std::string arg_next = argv[i];
// split string by , and /
@@ -565,15 +566,15 @@ bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
params.tensor_split[i] = 0.0f;
}
}
-#else
- fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
-#endif // GGML_USE_CUBLAS
+ } else {
+ fprintf(stderr, "warning: cuBLAS GPU couldn't be supported on this system. It is not possible to set a tensor split.\n");
+ }
} else if (arg == "--no-mul-mat-q" || arg == "-nommq") {
-#ifdef GGML_USE_CUBLAS
- params.mul_mat_q = false;
-#else
- fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n");
-#endif // GGML_USE_CUBLAS
+ if (ggml_cuda_supported()) {
+ params.mul_mat_q = false;
+ } else {
+ fprintf(stderr, "warning: cuBLAS GPU couldn't be supported on this system. Disabling mul_mat_q kernels has no effect.\n");
+ }
} else if (arg == "--no-mmap") {
params.use_mmap = false;
} else if (arg == "--numa") {
@@ -840,7 +841,7 @@ void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
printf(" --numa attempt optimizations that help on some NUMA systems\n");
printf(" if run without this previously, it is recommended to drop the system page cache before using this\n");
printf(" see https://github.com/ggerganov/llama.cpp/issues/1437\n");
- if (ggml_metal_supported()) {
+ if (ggml_metal_supported() || ggml_cuda_supported()) {
printf(" -ngl N, --n-gpu-layers N\n");
printf(" number of layers to store in VRAM\n");
printf(" -ngld N, --n-gpu-layers-draft N\n");
@@ -848,11 +849,11 @@ void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
printf(" -ts SPLIT --tensor-split SPLIT\n");
printf(" how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
printf(" -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
-#ifdef GGML_USE_CUBLAS
+ if (ggml_cuda_supported()) {
printf(" -nommq, --no-mul-mat-q\n");
printf(" use " GGML_CUBLAS_NAME " instead of custom mul_mat_q " GGML_CUDA_NAME " kernels.\n");
printf(" Not recommended since this is both slower and uses more VRAM.\n");
-#endif // GGML_USE_CUBLAS
+ }
}
printf(" --verbose-prompt print prompt before generation\n");
printf(" --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
diff --git a/llama.cpp/cpucheck.c b/llama.cpp/cpucheck.c
index 0a7b1eb2..2812a191 100644
--- a/llama.cpp/cpucheck.c
+++ b/llama.cpp/cpucheck.c
@@ -4,7 +4,6 @@
#include <cosmo.h>
#include <stdlib.h>
#include <errno.h>
-#include "cpucheck.h"
static int on_missing_feature(const char *name) {
tinyprint(2, program_invocation_name, ": fatal error: the cpu feature ", name,
@@ -25,7 +24,7 @@ static int on_missing_feature(const char *name) {
* written to use runtime dispatching should be configured so that
* microarchitecture flags only get passed to that specific object
*/
-void llama_cpucheck(void) {
+void ggml_check_cpu(void) {
if (X86_NEED(SSE3) && !X86_CHECK(SSE3)) {
on_missing_feature("SSE3");
}
diff --git a/llama.cpp/cpucheck.h b/llama.cpp/cpucheck.h
deleted file mode 100644
index b8f2b24d..00000000
--- a/llama.cpp/cpucheck.h
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef LLAMA_CPP_LLAMA_CHECK_CPU_H_
-#define LLAMA_CPP_LLAMA_CHECK_CPU_H_
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-void llama_has_gpu(void);
-void llama_cpucheck(void);
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* LLAMA_CPP_LLAMA_CHECK_CPU_H_ */
diff --git a/llama.cpp/cuda.c b/llama.cpp/cuda.c
new file mode 100644
index 00000000..b27ae6e9
--- /dev/null
+++ b/llama.cpp/cuda.c
@@ -0,0 +1,325 @@
+// -*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi
+#define _COSMO_SOURCE
+#include <cosmo.h>
+#include <time.h>
+#include <dlfcn.h>
+#include <errno.h>
+#include <spawn.h>
+#include <assert.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <limits.h>
+#include <pthread.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <stdatomic.h>
+#include "ggml-cuda.h"
+
+__static_yoink("llama.cpp/ggml.h");
+__static_yoink("llama.cpp/ggml-cuda.h");
+__static_yoink("llama.cpp/ggml-cuda.cu");
+
+static const struct Source {
+ const char *zip;
+ const char *name;
+} srcs[] = {
+ {"/zip/llama.cpp/ggml.h", "ggml.h"},
+ {"/zip/llama.cpp/ggml-impl.h", "ggml-cuda.h"},
+ {"/zip/llama.cpp/ggml-cuda.cu", "ggml-cuda.cu"}, // must come last
+};
+
+static struct Cuda {
+ bool supported;
+ atomic_uint once;
+ typeof(ggml_init_cublas) *init;
+ typeof(ggml_cublas_loaded) *loaded;
+ typeof(ggml_cuda_host_free) *host_free;
+ typeof(ggml_cuda_host_malloc) *host_malloc;
+ typeof(ggml_cuda_can_mul_mat) *can_mul_mat;
+ typeof(ggml_cuda_set_tensor_split) *set_tensor_split;
+ typeof(ggml_cuda_transform_tensor) *transform_tensor;
+ typeof(ggml_cuda_free_data) *free_data;
+ typeof(ggml_cuda_assign_buffers) *assign_buffers;
+ typeof(ggml_cuda_assign_buffers_no_scratch) *assign_buffers_no_scratch;
+ typeof(ggml_cuda_assign_buffers_force_inplace) *assign_buffers_force_inplace;
+ typeof(ggml_cuda_assign_buffers_no_alloc) *assign_buffers_no_alloc;
+ typeof(ggml_cuda_assign_scratch_offset) *assign_scratch_offset;
+ typeof(ggml_cuda_copy_to_device) *copy_to_device;
+ typeof(ggml_cuda_set_main_device) *set_main_device;
+ typeof(ggml_cuda_set_scratch_size) *set_scratch_size;
+ typeof(ggml_cuda_free_scratch) *free_scratch;
+ typeof(ggml_cuda_compute_forward) *compute_forward;
+ typeof(ggml_cuda_get_device_count) *get_device_count;
+ typeof(ggml_cuda_get_device_description) *get_device_description;
+} ggml_cuda;
+
+static const char *Dlerror(void) {
+ const char *msg;
+ msg = cosmo_dlerror();
+ if (!msg) msg = "null dlopen error";
+ return msg;
+}
+
+static const char *GetDsoExtension(void) {
+ if (IsWindows()) {
+ return "dll";
+ } else if (IsXnu()) {
+ return "dylib";
+ } else {
+ return "so";
+ }
+}
+
+static bool CompileNativeCuda(char dso[static PATH_MAX]) {
+
+ // find path of nvidia compiler
+ char nvcc[PATH_MAX];
+ const char *cuda_path;
+ nvcc[0] = 0;
+ if ((cuda_path = getenv("CUDA_PATH"))) {
+ strlcat(nvcc, cuda_path, sizeof(nvcc));
+ strlcat(nvcc, "/bin/", sizeof(nvcc));
+ }
+ strlcat(nvcc, "nvcc", sizeof(nvcc));
+ if (IsWindows()) {
+ strlcat(nvcc, ".exe", sizeof(nvcc));
+ }
+
+ // extract source code
+ char src[PATH_MAX];
+ bool needs_rebuild = false;
+ for (int i = 0; i < sizeof(srcs) / sizeof(*srcs); ++i) {
+ ggml_get_app_dir(src, sizeof(src));
+ if (!i && mkdir(src, 0755) && errno != EEXIST) {
+ perror(src);
+ return false;
+ }
+ strlcat(src, srcs[i].name, sizeof(src));
+ if (ggml_is_newer_than(srcs[i].zip, src)) {
+ needs_rebuild = true;
+ if (!ggml_extract(srcs[i].zip, src)) {
+ return false;
+ }
+ }
+ }
+
+ // compile dynamic shared object
+ ggml_get_app_dir(dso, PATH_MAX);
+ strlcat(dso, "ggml-cuda.", PATH_MAX);
+ strlcat(dso, GetDsoExtension(), PATH_MAX);
+ if (needs_rebuild || ggml_is_newer_than(src, dso)) {
+ tinyprint(2, "building ggml-cuda with nvcc...\n", NULL);
+ int fd;
+ char tmpdso[PATH_MAX];
+ strlcpy(tmpdso, dso, sizeof(tmpdso));
+ strlcat(tmpdso, ".XXXXXX", sizeof(tmpdso));
+ if ((fd = mkstemp(tmpdso)) != -1) {
+ close(fd);
+ } else {
+ perror(tmpdso);
+ return false;
+ }
+ char *args[] = {
+ nvcc,
+ "--shared",
+ "-arch=native",
+ "-DGGML_BUILD=1",
+ "-DGGML_SHARED=1",
+ "-o", tmpdso,
+ src,
+ "-lcublas",
+ NULL,
+ };
+ int pid, ws;
+ errno_t err = posix_spawnp(&pid, nvcc, NULL, NULL, args, environ);
+ if (err) {
+ perror(nvcc);
+ return false;
+ }
+ while (waitpid(pid, &ws, 0) == -1) {
+ if (errno != EINTR) {
+ perror(nvcc);
+ return false;
+ }
+ }
+ if (ws) {
+ tinyprint(2, nvcc, ": returned nonzero exit status\n", NULL);
+ return false;
+ }
+ if (rename(tmpdso, dso)) {
+ perror(dso);
+ return false;
+ }
+ }
+
+ return true;
+}
+
+static bool ImportCudaImpl(void) {
+
+ // get native cuda dll if possible
+ char dso[PATH_MAX];
+ if (!CompileNativeCuda(dso)) {
+ return false;
+ }
+
+ // runtime link dynamic shared object
+ void *lib;
+ tinyprint(2, "OPENING: ", dso, "\n", NULL);
+ lib = cosmo_dlopen(dso, RTLD_LAZY);
+ if (!lib) {
+ tinyprint(2, Dlerror(), ": failed to load library\n", NULL);
+ return false;
+ }
+
+ // import functions
+ bool ok = true;
+ ok &= !!(ggml_cuda.init = cosmo_dlsym(lib, "ggml_init_cublas"));
+ ok &= !!(ggml_cuda.loaded = cosmo_dlsym(lib, "ggml_cublas_loaded"));
+ ok &= !!(ggml_cuda.host_free = cosmo_dlsym(lib, "ggml_cuda_host_free"));
+ ok &= !!(ggml_cuda.host_malloc = cosmo_dlsym(lib, "ggml_cuda_host_malloc"));
+ ok &= !!(ggml_cuda.can_mul_mat = cosmo_dlsym(lib, "ggml_cuda_can_mul_mat"));
+ ok &= !!(ggml_cuda.set_tensor_split = cosmo_dlsym(lib, "ggml_cuda_set_tensor_split"));
+ ok &= !!(ggml_cuda.transform_tensor = cosmo_dlsym(lib, "ggml_cuda_transform_tensor"));
+ ok &= !!(ggml_cuda.free_data = cosmo_dlsym(lib, "ggml_cuda_free_data"));
+ ok &= !!(ggml_cuda.assign_buffers = cosmo_dlsym(lib, "ggml_cuda_assign_buffers"));
+ ok &= !!(ggml_cuda.assign_buffers_no_scratch = cosmo_dlsym(lib, "ggml_cuda_assign_buffers_no_scratch"));
+ ok &= !!(ggml_cuda.assign_buffers_force_inplace = cosmo_dlsym(lib, "ggml_cuda_assign_buffers_force_inplace"));
+ ok &= !!(ggml_cuda.assign_buffers_no_alloc = cosmo_dlsym(lib, "ggml_cuda_assign_buffers_no_alloc"));
+ ok &= !!(ggml_cuda.assign_scratch_offset = cosmo_dlsym(lib, "ggml_cuda_assign_scratch_offset"));
+ ok &= !!(ggml_cuda.copy_to_device = cosmo_dlsym(lib, "ggml_cuda_copy_to_device"));
+ ok &= !!(ggml_cuda.set_main_device = cosmo_dlsym(lib, "ggml_cuda_set_main_device"));
+ ok &= !!(ggml_cuda.set_scratch_size = cosmo_dlsym(lib, "ggml_cuda_set_scratch_size"));
+ ok &= !!(ggml_cuda.free_scratch = cosmo_dlsym(lib, "ggml_cuda_free_scratch"));
+ ok &= !!(ggml_cuda.compute_forward = cosmo_dlsym(lib, "ggml_cuda_compute_forward"));
+ ok &= !!(ggml_cuda.get_device_count = cosmo_dlsym(lib, "ggml_cuda_get_device_count"));
+ ok &= !!(ggml_cuda.get_device_description = cosmo_dlsym(lib, "ggml_cuda_get_device_description"));
+ if (!ok) {
+ tinyprint(2, Dlerror(), ": not all symbols could be imported\n", NULL);
+ return false;
+ }
+
+ // we're good
+ return true;
+}
+
+static void ImportCuda(void) {
+ if (ImportCudaImpl()) {
+ ggml_cuda.supported = true;
+ tinyprint(2, "NVIDIA cuBLAS GPU supported locked and loaded\n", NULL);
+ } else {
+ tinyprint(2, "warning: couldn't load Nvidia CUDA GPU support\n", NULL);
+ }
+}
+
+bool ggml_cuda_supported(void) {
+ cosmo_once(&ggml_cuda.once, ImportCuda);
+ return ggml_cuda.supported;
+}
+
+void ggml_init_cublas(void) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.init();
+}
+
+bool ggml_cublas_loaded(void) {
+ if (!ggml_cuda_supported()) return false;
+ return ggml_cuda.loaded();
+}
+
+void *ggml_cuda_host_malloc(size_t n) {
+ if (!ggml_cuda_supported()) return NULL;
+ return ggml_cuda.host_malloc(n);
+}
+
+void ggml_cuda_host_free(void *data) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.host_free(data);
+}
+
+bool ggml_cuda_can_mul_mat(const struct ggml_tensor *src0,
+ const struct ggml_tensor *src1,
+ struct ggml_tensor *dst) {
+ if (!ggml_cuda_supported()) return false;
+ return ggml_cuda.can_mul_mat(src0, src1, dst);
+}
+
+void ggml_cuda_set_tensor_split(const float *tensor_split) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.set_tensor_split(tensor_split);
+}
+
+void ggml_cuda_transform_tensor(void *data, struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.transform_tensor(data, tensor);
+}
+
+void ggml_cuda_free_data(struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.free_data(tensor);
+}
+
+void ggml_cuda_assign_buffers(struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.assign_buffers(tensor);
+}
+
+void ggml_cuda_assign_buffers_no_scratch(struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.assign_buffers_no_scratch(tensor);
+}
+
+void ggml_cuda_assign_buffers_force_inplace(struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.assign_buffers_force_inplace(tensor);
+}
+
+void ggml_cuda_assign_buffers_no_alloc(struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.assign_buffers_no_alloc(tensor);
+}
+
+void ggml_cuda_assign_scratch_offset(struct ggml_tensor *tensor, size_t offset) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.assign_scratch_offset(tensor, offset);
+}
+
+void ggml_cuda_copy_to_device(struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.copy_to_device(tensor);
+}
+
+void ggml_cuda_set_main_device(int main_device) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.set_main_device(main_device);
+}
+
+void ggml_cuda_set_scratch_size(size_t scratch_size) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.set_scratch_size(scratch_size);
+}
+
+void ggml_cuda_free_scratch(void) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.free_scratch();
+}
+
+bool ggml_cuda_compute_forward(struct ggml_compute_params *params,
+ struct ggml_tensor *tensor) {
+ if (!ggml_cuda_supported()) return false;
+ return ggml_cuda.compute_forward(params, tensor);
+}
+
+int ggml_cuda_get_device_count(void) {
+ if (!ggml_cuda_supported()) return 0;
+ return ggml_cuda.get_device_count();
+}
+
+void ggml_cuda_get_device_description(int device,
+ char *description,
+ size_t description_size) {
+ if (!ggml_cuda_supported()) return;
+ return ggml_cuda.get_device_description(device, description,
+ description_size);
+}
diff --git a/llama.cpp/extract.c b/llama.cpp/extract.c
index 875b62d4..731520a5 100644
--- a/llama.cpp/extract.c
+++ b/llama.cpp/extract.c
@@ -5,9 +5,66 @@
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
#include <unistd.h>
+#include <sys/stat.h>
#include "ggml.h"
+static const char *GetTmpDir(void) {
+ const char *tmpdir;
+ if (!(tmpdir = getenv("TMPDIR")) || !*tmpdir) {
+ if (!(tmpdir = getenv("HOME")) || !*tmpdir) {
+ tmpdir = ".";
+ }
+ }
+ return tmpdir;
+}
+
+/**
+ * Returns path of directory for app-specific files.
+ */
+void ggml_get_app_dir(char *path, size_t size) {
+ strlcpy(path, GetTmpDir(), size);
+ strlcat(path, "/.llamafile/", size);
+}
+
+/**
+ * Returns true if `path` should replace `other`.
+ *
+ * The use case for this function is determining if a source code file
+ * needs to be rebuilt. In that case, `path` can be thought of as the
+ * source code file (which may reside under `/zip/...`, and `other`
+ * would be the generated artifact that's dependent on `path`.
+ */
+bool ggml_is_newer_than(const char *path, const char *other) {
+ struct stat st1, st2;
+ if (stat(path, &st1) == -1) {
+ // PATH should always exist when calling this function
+ perror(path);
+ return false;
+ }
+ if (stat(other, &st2) == -1) {
+ if (errno == ENOENT) {
+ // PATH should replace OTHER because OTHER doesn't exist yet
+ return true;
+ } else {
+ // some other error happened, so we can't do anything
+ perror(path);
+ return false;
+ }
+ }
+ // PATH should replace OTHER if PATH was modified more recently
+ return timespec_cmp(st1.st_mtim, st2.st_mtim) > 0;
+}
+
+/**
+ * Returns true if `zip` was successfully copied to `to`.
+ *
+ * Copying happens atomically. The `zip` argument is a file system path,
+ * which may reside under `/zip/...` to relocate a compressed executable
+ * asset to the local filesystem.
+ */
bool ggml_extract(const char *zip, const char *to) {
int fdin, fdout;
char stage[PATH_MAX];
diff --git a/llama.cpp/ggml-cuda.cu b/llama.cpp/ggml-cuda.cu
index f87f1880..4d6a9691 100644
--- a/llama.cpp/ggml-cuda.cu
+++ b/llama.cpp/ggml-cuda.cu
@@ -1,3 +1,5 @@
+// -*- mode:cuda;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi
#include <algorithm>
#include <cstddef>
#include <cstdint>
@@ -82,6 +84,231 @@
#include "ggml-cuda.h"
#include "ggml.h"
+////////////////////////////////////////////////////////////////////////////////
+// BEGIN: COPIED FROM GGML.C
+
+#define QK4_0 32
+#define QK4_1 32
+#define QK5_0 32
+#define QK5_1 32
+#define QK8_0 32
+#define QK8_1 32
+#define QK_K 256
+
+#undef MIN
+#undef MAX
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+#define MAX(a, b) ((a) > (b) ? (a) : (b))
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846
+#endif
+
+#define ggml_blck_size ggml_blck_size_
+static int ggml_blck_size(enum ggml_type type) {
+ switch (type) {
+ case GGML_TYPE_I8:
+ return 1;
+ case GGML_TYPE_I16:
+ return 1;
+ case GGML_TYPE_I32:
+ return 1;
+ case GGML_TYPE_F32:
+ return 1;
+ case GGML_TYPE_F16:
+ return 1;
+ case GGML_TYPE_Q4_0:
+ return QK4_0;
+ case GGML_TYPE_Q4_1:
+ return QK4_1;
+ case GGML_TYPE_Q5_0:
+ return QK5_0;
+ case GGML_TYPE_Q5_1:
+ return QK5_1;
+ case GGML_TYPE_Q8_0:
+ return QK8_0;
+ case GGML_TYPE_Q8_1:
+ return QK8_1;
+ case GGML_TYPE_Q2_K:
+ return QK_K;
+ case GGML_TYPE_Q3_K:
+ return QK_K;
+ case GGML_TYPE_Q4_K:
+ return QK_K;
+ case GGML_TYPE_Q5_K:
+ return QK_K;
+ case GGML_TYPE_Q6_K:
+ return QK_K;
+ case GGML_TYPE_Q8_K:
+ return QK_K;
+ default:
+ return 0;
+ }
+}
+
+#define ggml_is_quantized ggml_is_quantized_
+static bool ggml_is_quantized(enum ggml_type type) {
+ switch (type) {
+ case GGML_TYPE_I8:
+ return false;
+ case GGML_TYPE_I16:
+ return false;
+ case GGML_TYPE_I32:
+ return false;
+ case GGML_TYPE_F32:
+ return false;
+ case GGML_TYPE_F16:
+ return false;
+ case GGML_TYPE_Q4_0:
+ return true;
+ case GGML_TYPE_Q4_1:
+ return true;
+ case GGML_TYPE_Q5_0:
+ return true;
+ case GGML_TYPE_Q5_1:
+ return true;
+ case GGML_TYPE_Q8_0:
+ return true;
+ case GGML_TYPE_Q8_1:
+ return true;
+ case GGML_TYPE_Q2_K:
+ return true;
+ case GGML_TYPE_Q3_K:
+ return true;
+ case GGML_TYPE_Q4_K:
+ return true;
+ case GGML_TYPE_Q5_K:
+ return true;
+ case GGML_TYPE_Q6_K:
+ return true;
+ case GGML_TYPE_Q8_K:
+ return true;
+ default:
+ return false;
+ }
+}
+
+#define ggml_type_size ggml_type_size_
+static size_t ggml_type_size(enum ggml_type type) {
+ switch (type) {
+ case GGML_TYPE_I8:
+ return sizeof(int8_t);
+ case GGML_TYPE_I16:
+ return sizeof(int16_t);
+ case GGML_TYPE_I32:
+ return sizeof(int32_t);
+ case GGML_TYPE_F32:
+ return sizeof(float);
+ case GGML_TYPE_F16:
+ return 2;
+ case GGML_TYPE_Q4_0:
+ return 18;
+ case GGML_TYPE_Q4_1:
+ return 20;
+ case GGML_TYPE_Q5_0:
+ return 22;
+ case GGML_TYPE_Q5_1:
+ return 24;
+ case GGML_TYPE_Q8_0:
+ return 34;
+ case GGML_TYPE_Q8_1:
+ return 40;
+ case GGML_TYPE_Q2_K:
+ return 84;
+ case GGML_TYPE_Q3_K:
+ return 110;
+ case GGML_TYPE_Q4_K:
+ return 144;
+ case GGML_TYPE_Q5_K:
+ return 176;
+ case GGML_TYPE_Q6_K:
+ return 210;
+ case GGML_TYPE_Q8_K:
+ return 292;
+ default:
+ return 0;
+ }
+}
+
+#define ggml_nbytes ggml_nbytes_
+static size_t ggml_nbytes(const struct ggml_tensor * tensor) {
+ size_t nbytes;
+ size_t blck_size = ggml_blck_size(tensor->type);
+ if (blck_size == 1) {
+ nbytes = ggml_type_size(tensor->type);
+ for (int i = 0; i < GGML_MAX_DIMS; ++i) {
+ nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
+ }
+ }
+ else {
+ nbytes = tensor->ne[0]*tensor->nb[0]/blck_size;
+ for (int i = 1; i < GGML_MAX_DIMS; ++i) {
+ nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
+ }
+ }
+ return nbytes;
+}
+
+#define ggml_is_transposed ggml_is_transposed_
+static bool ggml_is_transposed(const struct ggml_tensor * tensor) {
+ return tensor->nb[0] > tensor->nb[1];
+}
+
+#define ggml_is_permuted ggml_is_permuted_
+static bool ggml_is_permuted(const struct ggml_tensor * tensor) {
+ return tensor->nb[0] > tensor->nb[1] || tensor->nb[1] > tensor->nb[2] || tensor->nb[2] > tensor->nb[3];
+}
+
+#define ggml_is_contiguous ggml_is_contiguous_
+static bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
+ static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
+ return
+ tensor->nb[0] == ggml_type_size(tensor->type) &&
+ tensor->nb[1] == (tensor->nb[0]*tensor->ne[0])/ggml_blck_size(tensor->type) &&
+ tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
+ tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
+}
+
+#define ggml_nrows ggml_nrows_
+static int64_t ggml_nrows(const struct ggml_tensor * tensor) {
+ return tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
+}
+
+#define ggml_nelements ggml_nelements_
+static int64_t ggml_nelements(const struct ggml_tensor * tensor) {
+ return tensor->ne[0]*tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
+}
+
+static int32_t ggml_get_op_params_i32(const struct ggml_tensor * tensor, uint32_t i) {
+ return ((const int32_t *)(tensor->op_params))[i];
+}
+
+#define ggml_get_unary_op ggml_get_unary_op_
+static enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor) {
+ return (enum ggml_unary_op) ggml_get_op_params_i32(tensor, 0);
+}
+
+#define ggml_nbytes_split ggml_nbytes_split_
+static size_t ggml_nbytes_split(const struct ggml_tensor * tensor, int nrows_split) {
+ return (nrows_split*tensor->ne[0]*ggml_type_size(tensor->type))/ggml_blck_size(tensor->type);
+}
+
+static float ggml_rope_yarn_corr_dim(int n_dims, int n_orig_ctx, float n_rot, float base) {
+ return n_dims * logf(n_orig_ctx / (n_rot * 2 * (float)M_PI)) / (2 * logf(base));
+}
+
+#define ggml_rope_yarn_corr_dims ggml_rope_yarn_corr_dims_
+static void ggml_rope_yarn_corr_dims(
+ int n_dims, int n_orig_ctx, float freq_base, float beta_fast, float beta_slow, float dims[2]
+) {
+ // start and end correction dims
+ dims[0] = MAX(0, floorf(ggml_rope_yarn_corr_dim(n_dims, n_orig_ctx, beta_fast, freq_base)));
+ dims[1] = MIN(n_dims - 1, ceilf(ggml_rope_yarn_corr_dim(n_dims, n_orig_ctx, beta_slow, freq_base)));
+}
+
+// END: COPIED FROM GGML.C
+////////////////////////////////////////////////////////////////////////////////
+
#define MIN_CC_DP4A 610 // minimum compute capability for __dp4a, an intrinsic for byte-wise dot products
#define CC_VOLTA 700
#define CC_OFFSET_AMD 1000000
@@ -7544,8 +7771,8 @@ static void ggml_cuda_cpy(const ggml_tensor * src0, const ggml_tensor * src1, gg
ggml_cpy_f32_f16_cuda(src0_ddc, src1_ddc, ne, ne00, ne01, nb00, nb01, nb02,
ne10, ne11, nb10, nb11, nb12, main_stream);
} else {
- fprintf(stderr, "%s: unsupported type combination (%s to %s)\n", __func__,
- ggml_type_name(src0->type), ggml_type_name(src1->type));
+ fprintf(stderr, "%s: unsupported type combination (%d to %d)\n", __func__,
+ src0->type, src1->type);
GGML_ASSERT(false);
}
@@ -7964,263 +8191,3 @@ void ggml_cuda_get_device_description(int device, char * description, size_t des
CUDA_CHECK(cudaGetDeviceProperties(&prop, device));
snprintf(description, description_size, "%s", prop.name);
}
-
-////////////////////////////////////////////////////////////////////////////////
-
-// backend interface
-
-#define UNUSED GGML_UNUSED
-
-struct ggml_backend_context_cuda {
-};
-
-static const char * ggml_backend_cuda_name(ggml_backend_t backend) {
- return GGML_CUDA_NAME;
-
- UNUSED(backend);
-}
-
-static void ggml_backend_cuda_free(ggml_backend_t backend) {
- ggml_backend_context_cuda * cuda_ctx = (ggml_backend_context_cuda *)backend->context;
- delete cuda_ctx;
- delete backend;
-}
-
-struct ggml_backend_buffer_context_cuda {
- void * device;
-
- ggml_tensor_extra_gpu * temp_tensor_extras = nullptr;
- size_t temp_tensor_extra_index = 0;
-
- ~ggml_backend_buffer_context_cuda() {
- delete[] temp_tensor_extras;
- }
-
- ggml_tensor_extra_gpu * ggml_cuda_alloc_temp_tensor_extra() {
- if (temp_tensor_extras == nullptr) {
- temp_tensor_extras = new ggml_tensor_extra_gpu[GGML_MAX_NODES];
- }
-
- size_t alloc_index = temp_tensor_extra_index;
- temp_tensor_extra_index = (temp_tensor_extra_index + 1) % GGML_MAX_NODES;
- ggml_tensor_extra_gpu * extra = &temp_tensor_extras[alloc_index];
- memset(extra, 0, sizeof(*extra));
-
- return extra;
- }
-};
-
-static void ggml_backend_cuda_buffer_free_buffer(ggml_backend_buffer_t buffer) {
- ggml_backend_buffer_context_cuda * ctx = (ggml_backend_buffer_context_cuda *)buffer->context;
- CUDA_CHECK(cudaFree(ctx->device));
- delete ctx;
-}
-
-static void * ggml_backend_cuda_buffer_get_base(ggml_backend_buffer_t buffer) {
- ggml_backend_buffer_context_cuda * ctx = (ggml_backend_buffer_context_cuda *)buffer->context;
- return ctx->device;
-}
-
-static size_t ggml_backend_cuda_buffer_get_alloc_size(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
- int64_t row_low = 0;
- int64_t row_high = ggml_nrows(tensor);
- int64_t nrows_split = row_high - row_low;
-
- size_t size = ggml_nbytes_split(tensor, nrows_split);
-
- int64_t ne0 = tensor->ne[0];
-
- if (ggml_is_quantized(tensor->type)) {
- if (ne0 % MATRIX_ROW_PADDING != 0) {
- size += (MATRIX_ROW_PADDING - ne0 % MATRIX_ROW_PADDING)
- * ggml_type_size(tensor->type)/ggml_blck_size(tensor->type);
- }
- }
-
- return size;
-
- UNUSED(buffer);
-}
-
-static void ggml_backend_cuda_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
- ggml_backend_buffer_context_cuda * ctx = (ggml_backend_buffer_context_cuda *)buffer->context;
-
- if (tensor->view_src != NULL && tensor->view_offs == 0) {
- assert(tensor->view_src->buffer->backend == buffer->backend);
- tensor->backend = tensor->view_src->backend;
- tensor->extra = tensor->view_src->extra;
- return;
- }
-
- ggml_tensor_extra_gpu * extra = ctx->ggml_cuda_alloc_temp_tensor_extra();
-
- extra->data_device[g_main_device] = tensor->data;
-
- tensor->backend = GGML_BACKEND_GPU;
- tensor->extra = extra;
-
- if (ggml_is_quantized(tensor->type)) {
- // initialize padding to 0 to avoid possible NaN values
- int64_t row_low = 0;
- int64_t row_high = ggml_nrows(tensor);
- int64_t nrows_split = row_high - row_low;
-
- size_t original_size = ggml_nbytes_split(tensor, nrows_split);
- size_t padded_size = ggml_backend_cuda_buffer_get_alloc_size(tensor->buffer, tensor);
-
- if (padded_size > original_size && tensor->view_src == nullptr) {
- CUDA_CHECK(cudaMemsetAsync((char *)tensor->data + original_size, 0, padded_size - original_size, g_cudaStreams[g_main_device][0]));
- }
- }
-
- UNUSED(buffer);
-}
-
-static struct ggml_backend_buffer_i cuda_backend_buffer_interface = {
- /* .free_buffer = */ ggml_backend_cuda_buffer_free_buffer,
- /* .get_base = */ ggml_backend_cuda_buffer_get_base,
- /* .get_alloc_size = */ ggml_backend_cuda_buffer_get_alloc_size,
- /* .init_tensor = */ ggml_backend_cuda_buffer_init_tensor,
- /* .free_tensor = */ NULL,
-};
-
-static ggml_backend_buffer_t ggml_backend_cuda_alloc_buffer(ggml_backend_t backend, size_t size) {
- ggml_cuda_set_device(g_main_device);
-
- ggml_backend_buffer_context_cuda * ctx = new ggml_backend_buffer_context_cuda;
- CUDA_CHECK(cudaMalloc(&ctx->device, size));
- return ggml_backend_buffer_init(backend, cuda_backend_buffer_interface, ctx, size);
-}
-
-static size_t ggml_backend_cuda_get_alignment(ggml_backend_t backend) {
- return 128;
- UNUSED(backend);
-}
-
-static void ggml_backend_cuda_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
- GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
- GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
- GGML_ASSERT(tensor->backend == GGML_BACKEND_GPU);
-
- CUDA_CHECK(cudaMemcpyAsync((char *)tensor->data + offset, data, size, cudaMemcpyHostToDevice, g_cudaStreams[g_main_device][0]));
-
- UNUSED(backend);
-}
-
-static void ggml_backend_cuda_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) {
- GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
- GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
- GGML_ASSERT(tensor->backend == GGML_BACKEND_GPU);
-
- CUDA_CHECK(cudaMemcpyAsync(data, (const char *)tensor->data + offset, size, cudaMemcpyDeviceToHost, g_cudaStreams[g_main_device][0]));
-
- UNUSED(backend);
-}
-
-static void ggml_backend_cuda_synchronize(ggml_backend_t backend) {
- CUDA_CHECK(cudaStreamSynchronize(g_cudaStreams[g_main_device][0]));
-
- UNUSED(backend);
-}
-
-static ggml_backend_graph_plan_t ggml_backend_cuda_graph_plan_create(ggml_backend_t backend, ggml_cgraph * cgraph) {
- GGML_ASSERT(!"not implemented");
-
- return nullptr;
-
- UNUSED(backend);
- UNUSED(cgraph);
-}
-
-static void ggml_backend_cuda_graph_plan_free(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
- GGML_ASSERT(!"not implemented");
-
- UNUSED(backend);
- UNUSED(plan);
-}
-
-static void ggml_backend_cuda_graph_plan_compute(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
- GGML_ASSERT(!"not implemented");
-
- UNUSED(backend);
- UNUSED(plan);
-}
-
-static void ggml_backend_cuda_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
- ggml_cuda_set_device(g_main_device);
-
- ggml_compute_params params = {};
- params.type = GGML_TASK_COMPUTE;
- params.ith = 0;
- for (int i = 0; i < cgraph->n_nodes; i++) {
- ggml_tensor * node = cgraph->nodes[i];
-
- assert(node->backend == GGML_BACKEND_GPU);
- for (int j = 0; j < GGML_MAX_SRC; j++) {
- if (node->src[j] != nullptr) {
- assert(node->src[j]->backend == GGML_BACKEND_GPU);
- }
- }
-
- bool ok = ggml_cuda_compute_forward(&params, node);
- if (!ok) {
- fprintf(stderr, "%s: error: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op));
- }
- GGML_ASSERT(ok);
-
-#if 0
- if (node->type == GGML_TYPE_F32) {
- cudaDeviceSynchronize();
- std::vector<float> tmp(ggml_nelements(node), 0.0f);
- cudaMemcpy(tmp.data(), node->data, ggml_nelements(node)*sizeof(float), cudaMemcpyDeviceToHost);
- printf("\n%s (%s) (%s %s) (%s %s): ", node->name, ggml_op_name(node->op),
- ggml_type_name(node->src[0]->type),
- node->src[1] ? ggml_type_name(node->src[1]->type) : "none",
- node->src[0]->name,
- node->src[1] ? node->src[1]->name : "none");
- double sum = 0.0;
- double sq_sum = 0.0;
- for (int i = 0; i < ggml_nelements(node); i++) {
- printf("%f ", tmp[i]);
- sum += tmp[i];
- sq_sum += tmp[i]*tmp[i];
- }
- printf("\n");
- printf("sum: %f, ", sum);
- printf("sq_sum: %f\n", sq_sum);
- }
-#endif
- }
-
- UNUSED(backend);
-}
-
-static ggml_backend_i cuda_backend_i = {
- /* .get_name = */ ggml_backend_cuda_name,
- /* .free = */ ggml_backend_cuda_free,
- /* .alloc_buffer = */ ggml_backend_cuda_alloc_buffer,
- /* .get_alignment = */ ggml_backend_cuda_get_alignment,
- /* .set_tensor_async = */ ggml_backend_cuda_set_tensor_async,
- /* .get_tensor_async = */ ggml_backend_cuda_get_tensor_async,
- /* .synchronize = */ ggml_backend_cuda_synchronize,
- /* .cpy_tensor_from = */ nullptr,
- /* .cpy_tensor_to = */ nullptr,
- /* .graph_plan_create = */ ggml_backend_cuda_graph_plan_create,
- /* .graph_plan_free = */ ggml_backend_cuda_graph_plan_free,
- /* .graph_plan_compute = */ ggml_backend_cuda_graph_plan_compute,
- /* .graph_compute = */ ggml_backend_cuda_graph_compute,
- /* .supports_op = */ nullptr,
-};
-
-ggml_backend_t ggml_backend_cuda_init() {
- ggml_init_cublas(); // TODO: remove from ggml.c
-
- ggml_backend_context_cuda * ctx = new ggml_backend_context_cuda;
-
- ggml_backend_t cuda_backend = new ggml_backend {
- /* .interface = */ cuda_backend_i,
- /* .context = */ ctx
- };
-
- return cuda_backend;
-}
diff --git a/llama.cpp/ggml-cuda.h b/llama.cpp/ggml-cuda.h
index 528e66c3..0d9e7641 100644
--- a/llama.cpp/ggml-cuda.h
+++ b/llama.cpp/ggml-cuda.h
@@ -1,7 +1,6 @@
#pragma once
#include "ggml.h"
-#include "ggml-backend.h"
#ifdef GGML_USE_HIPBLAS
#define GGML_CUDA_NAME "ROCm"
@@ -19,6 +18,7 @@ extern "C" {
// Always success. To check if CUDA is actually loaded, use `ggml_cublas_loaded`.
GGML_API void ggml_init_cublas(void);
+GGML_API bool ggml_cuda_supported(void);
// Returns `true` if there are available CUDA devices and cublas loads successfully; otherwise, it returns `false`.
GGML_API bool ggml_cublas_loaded(void);
@@ -40,7 +40,6 @@ GGML_API void ggml_cuda_assign_scratch_offset(struct ggml_tensor * tensor, siz
GGML_API void ggml_cuda_copy_to_device(struct ggml_tensor * tensor);
GGML_API void ggml_cuda_set_main_device(int main_device);
-GGML_API void ggml_cuda_set_mul_mat_q(bool mul_mat_q);
GGML_API void ggml_cuda_set_scratch_size(size_t scratch_size);
GGML_API void ggml_cuda_free_scratch(void);
GGML_API bool ggml_cuda_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor);
@@ -48,9 +47,6 @@ GGML_API bool ggml_cuda_compute_forward(struct ggml_compute_params * params, s
GGML_API int ggml_cuda_get_device_count(void);
GGML_API void ggml_cuda_get_device_description(int device, char * description, size_t description_size);
-// backend API
-GGML_API ggml_backend_t ggml_backend_cuda_init(void); // TODO: take a list of devices to use
-
#ifdef __cplusplus
}
#endif
diff --git a/llama.cpp/ggml.c b/llama.cpp/ggml.c
index 992b386d..00a855ff 100644
--- a/llama.cpp/ggml.c
+++ b/llama.cpp/ggml.c
@@ -230,6 +230,9 @@ inline static void * ggml_aligned_malloc(size_t size) {
#include "ggml-opencl.h"
#endif
+#include "ggml-cuda.h"
+#include "ggml-metal.h"
+
// floating point type used to accumulate sums
typedef double ggml_float;
@@ -2185,9 +2188,9 @@ struct ggml_context * ggml_init(struct ggml_init_params params) {
GGML_PRINT_DEBUG("%s: g_state initialized in %f ms\n", __func__, (t_end - t_start)/1000.0f);
}
-#if defined(GGML_USE_CUBLAS)
ggml_init_cublas();
-#elif defined(GGML_USE_CLBLAST)
+
+#if defined(GGML_USE_CLBLAST)
ggml_cl_init();
#endif
@@ -19655,11 +19658,7 @@ int ggml_cpu_has_arm_fma(void) {
}
int ggml_cpu_has_metal(void) {
-#if defined(GGML_USE_METAL)
- return 1;
-#else
- return 0;
-#endif
+ return ggml_metal_supported();
}
int ggml_cpu_has_f16c(void) {
@@ -19695,11 +19694,7 @@ int ggml_cpu_has_blas(void) {
}
int ggml_cpu_has_cublas(void) {
-#if defined(GGML_USE_CUBLAS)
- return 1;
-#else
- return 0;
-#endif
+ return ggml_cuda_supported();
}
int ggml_cpu_has_clblast(void) {
diff --git a/llama.cpp/ggml.h b/llama.cpp/ggml.h
index 2e712057..d47e68fc 100644
--- a/llama.cpp/ggml.h
+++ b/llama.cpp/ggml.h
@@ -2156,7 +2156,10 @@ extern "C" {
GGML_API ggml_type_traits_t ggml_internal_get_type_traits(enum ggml_type type);
+ GGML_API void ggml_check_cpu(void);
+ GGML_API void ggml_get_app_dir(char *path, size_t size);
GGML_API bool ggml_extract(const char *zip, const char *to);
+ GGML_API bool ggml_is_newer_than(const char *path, const char *other);
#ifdef __cplusplus
}
diff --git a/llama.cpp/llama.cc b/llama.cpp/llama.cc
index 095016b9..76a13276 100644
--- a/llama.cpp/llama.cc
+++ b/llama.cpp/llama.cc
@@ -11,13 +11,11 @@
#include "runtime.h"
#include "ggml.h"
-
#include "ggml-alloc.h"
#include "ggml-metal.h"
+#include "ggml-cuda.h"
-#ifdef GGML_USE_CUBLAS
-# include "ggml-cuda.h"
-#elif defined(GGML_USE_CLBLAST)
+#if defined(GGML_USE_CLBLAST)
# include "ggml-opencl.h"
#endif
@@ -618,6 +616,8 @@ static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph *
inline void * llama_host_malloc(size_t n) {
if (ggml_metal_supported()) {
return ggml_metal_host_malloc(n);
+ } else if (ggml_cublas_loaded()) {
+ return ggml_cuda_host_malloc(n);
} else {
return malloc(n);
}
@@ -626,6 +626,8 @@ inline void * llama_host_malloc(size_t n) {
inline void llama_host_free(void * ptr) {
if (ggml_metal_supported()) {
return ggml_metal_host_free(ptr);
+ } else if (ggml_cublas_loaded()) {
+ return ggml_cuda_host_free(ptr);
} else {
return free(ptr);
}
@@ -1210,12 +1212,10 @@ struct llama_kv_cache {
ggml_free(ctx);
}
-#ifdef GGML_USE_CUBLAS
- if (ggml_cublas_loaded()) {
+ if (!ggml_metal_supported() && ggml_cublas_loaded()) {
ggml_cuda_free_data(k);
ggml_cuda_free_data(v);
}
-#endif
}
};
@@ -1314,14 +1314,12 @@ struct llama_model {
ggml_free(ctx);
}
-#ifdef GGML_USE_CUBLAS
- if (ggml_cublas_loaded()) {
+ if (!ggml_metal_supported() && ggml_cublas_loaded()) {
for (size_t i = 0; i < tensors_by_name.size(); ++i) {
ggml_cuda_free_data(tensors_by_name[i].second);
}
ggml_cuda_free_scratch();
}
-#endif
#if defined(GGML_USE_CLBLAST)
for (size_t i = 0; i < tensors_by_name.size(); ++i) {
@@ -1432,8 +1430,7 @@ static bool llama_kv_cache_init(
(void) n_gpu_layers;
-#ifdef GGML_USE_CUBLAS
- if (ggml_cublas_loaded()) {
+ if (!ggml_metal_supported() && ggml_cublas_loaded()) {
size_t vram_kv_cache = 0;
if (n_gpu_layers > (int)n_layer + 1) {
@@ -1450,7 +1447,6 @@ static bool llama_kv_cache_init(
LLAMA_LOG_INFO("%s: VRAM kv self = %.2f MB\n", __func__, vram_kv_cache / 1024.0 / 1024.0);
}
}
-#endif
return true;
}
@@ -1955,26 +1951,16 @@ struct llama_model_loader {
lmlock->grow_to(size_lock);
}
break;
-#ifdef GGML_USE_CUBLAS
case GGML_BACKEND_GPU:
case GGML_BACKEND_GPU_SPLIT:
// old code:
//ggml_cuda_transform_tensor(lt.data, lt.ggml_tensor);
-
// TODO: test if this works !!
ggml_cuda_transform_tensor(cur->data, cur);
if (!use_mmap) {
free(cur->data);
}
break;
-#elif defined(GGML_USE_CLBLAST)
- case GGML_BACKEND_GPU:
- ggml_cl_transform_tensor(cur->data, cur);
- if (!use_mmap) {
- free(cur->data);
- }
- break;
-#endif
default:
continue;
}
@@ -2542,15 +2528,14 @@ static void llm_load_tensors(
enum ggml_backend_type llama_backend_offload = GGML_BACKEND_CPU;
enum ggml_backend_type llama_backend_offload_split = GGML_BACKEND_CPU;
-#ifdef GGML_USE_CUBLAS
- if (ggml_cublas_loaded()) {
+ if (!ggml_metal_supported() && ggml_cublas_loaded()) {
LLAMA_LOG_INFO("%s: using " GGML_CUDA_NAME " for GPU acceleration\n", __func__);
ggml_cuda_set_main_device(main_gpu);
llama_backend_offload = GGML_BACKEND_GPU;
llama_backend_offload_split = GGML_BACKEND_GPU_SPLIT;
}
-#elif defined(GGML_USE_CLBLAST)
+#if defined(GGML_USE_CLBLAST)
LLAMA_LOG_INFO("%s: using OpenCL for GPU acceleration\n", __func__);
llama_backend_offload = GGML_BACKEND_GPU;
llama_backend_offload_split = GGML_BACKEND_GPU;
@@ -3084,7 +3069,6 @@ static void llm_load_tensors(
LLAMA_LOG_INFO("%s: mem required = %7.2f MB\n", __func__, mem_required / 1024.0 / 1024.0);
-#if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
@@ -3092,19 +3076,11 @@ static void llm_load_tensors(
LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
}
-#ifdef GGML_USE_CUBLAS
const int max_backend_supported_layers = hparams.n_layer + 3;
const int max_offloadable_layers = hparams.n_layer + 3;
-#elif GGML_USE_CLBLAST
- const int max_backend_supported_layers = hparams.n_layer + 1;
- const int max_offloadable_layers = hparams.n_layer + 1;
-#endif // GGML_USE_CUBLAS
LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
LLAMA_LOG_INFO("%s: VRAM used: %.2f MB\n", __func__, vram_weights / 1024.0 / 1024.0);
-#else
- (void) n_gpu_layers;
-#endif // defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST)
}
// populate `tensors_by_name`
@@ -3114,11 +3090,9 @@ static void llm_load_tensors(
}
(void) tensor_split;
-#ifdef GGML_USE_CUBLAS
{
ggml_cuda_set_tensor_split(tensor_split);
}
-#endif
ml.load_all_data(ctx, progress_callback, progress_callback_user_data, use_mlock ? &model.mlock_mmap : NULL);
@@ -4737,11 +4711,7 @@ static struct ggml_cgraph * llama_build_graph(
bool alloc_inp_KQ_mask = false;
bool alloc_inp_K_shift = false;
-#ifdef GGML_USE_CUBLAS
const bool do_offload = true;
-#else
- const bool do_offload = true; // TODO: set to false after finishing refactoring
-#endif
int n_non_view = 0; // number of non-view tensors that have been processed by the callback
@@ -4885,19 +4855,11 @@ static struct ggml_cgraph * llama_build_graph(
static const std::unordered_map<llm_offload_func_e, std::string, std::hash<int>> k_offload_func_name = {
{ OFFLOAD_FUNC_NOP, "CPU" },
{ OFFLOAD_FUNC_OUT, "CPU" },
-#ifdef GGML_USE_CUBLAS
{ OFFLOAD_FUNC, "GPU (CUDA)" },
{ OFFLOAD_FUNC_KQ, "GPU (CUDA) KQ" },
{ OFFLOAD_FUNC_V, "GPU (CUDA) V" },
{ OFFLOAD_FUNC_NR, "GPU (CUDA) NR" },
{ OFFLOAD_FUNC_EMB, "GPU (CUDA) EMB" },
-#else
- { OFFLOAD_FUNC, "CPU" },
- { OFFLOAD_FUNC_KQ, "CPU" },
- { OFFLOAD_FUNC_V, "CPU" },
- { OFFLOAD_FUNC_NR, "CPU" },
- { OFFLOAD_FUNC_EMB, "CPU" },
-#endif // GGML_USE_CUBLAS
};
// check the global map for what offload function to use for this tensor
@@ -4953,11 +4915,7 @@ static struct ggml_cgraph * llama_build_graph(
offload_func_t func = ggml_offload_nop;
// this is needed for compatibility with Metal for example
-#ifdef GGML_USE_CUBLAS
static offload_func_t ggml_offload_gpu = ggml_cuda_assign_buffers_no_alloc;
-#else
- static offload_func_t ggml_offload_gpu = ggml_offload_nop;
-#endif
switch (func_e) {
case OFFLOAD_FUNC_NOP:
@@ -5153,7 +5111,7 @@ static int llama_decode_internal(
GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
-#ifdef GGML_USE_CUBLAS
+ if (!ggml_metal_supported() && ggml_cuda_supported()) {
for (int i = 0; i < gf->n_leafs; i++) {
ggml_tensor * node = gf->leafs[i];
if (node->backend == GGML_BACKEND_GPU && node->extra == NULL) {
@@ -5174,7 +5132,7 @@ static int llama_decode_internal(
embeddings->backend = GGML_BACKEND_CPU;
}
res->backend = GGML_BACKEND_CPU;
-#endif
+ }
// LLAMA_LOG_INFO("graph build time: %.3f ms (%d nodes, %d leafs)\n", (ggml_time_us() - t_start_us)/1000.0, gf->n_nodes, gf->n_leafs);
@@ -7862,7 +7820,7 @@ static int llama_apply_lora_from_file_internal(
offload_func_t offload_func = ggml_offload_nop;
offload_func_t offload_func_force_inplace = ggml_offload_nop;
-#ifdef GGML_USE_CUBLAS
+ if (!ggml_metal_supported() && ggml_cuda_supported()) {
if (dest_t->backend == GGML_BACKEND_GPU || dest_t->backend == GGML_BACKEND_GPU_SPLIT) {
if (dest_t->type != GGML_TYPE_F16) {
ThrowRuntimeError(format(
@@ -7871,7 +7829,7 @@ static int llama_apply_lora_from_file_internal(
offload_func = ggml_cuda_assign_buffers;
offload_func_force_inplace = ggml_cuda_assign_buffers_force_inplace;
}
-#endif // GGML_USE_CUBLAS
+ }
ggml_tensor * base_t;
if (ml) {
@@ -8225,7 +8183,7 @@ struct llama_context * llama_new_context_with_model(
if (ctx->ctx_metal) {
//ggml_allocr_set_parse_seq(ctx->alloc, ggml_metal_get_concur_list(ctx->ctx_metal), ggml_metal_if_optimized(ctx->ctx_metal));
}
-#ifdef GGML_USE_CUBLAS
+ if (!ggml_metal_supported() && ggml_cuda_supported()) {
ggml_cuda_set_scratch_size(alloc_size);
LLAMA_LOG_INFO("%s: VRAM scratch buffer: %.2f MB\n", __func__, alloc_size / 1024.0 / 1024.0);
@@ -8251,7 +8209,7 @@ struct llama_context * llama_new_context_with_model(
total_vram_size / 1024.0 / 1024.0,
model_vram_size / 1024.0 / 1024.0,
ctx_vram_size / 1024.0 / 1024.0);
-#endif
+ }
}
if (ggml_metal_supported() && model->n_gpu_layers > 0) {
diff --git a/llama.cpp/llava/llava-cli.cc b/llama.cpp/llava/llava-cli.cc
index 7028a40c..1e9944a0 100644
--- a/llama.cpp/llava/llava-cli.cc
+++ b/llama.cpp/llava/llava-cli.cc
@@ -280,6 +280,7 @@ static void llava_free(struct llava_context * ctx_llava) {
}
int main(int argc, char ** argv) {
+ ggml_check_cpu();
ggml_time_init();
gpt_params params;
diff --git a/llama.cpp/llava/llava-quantize.cc b/llama.cpp/llava/llava-quantize.cc
index daec48f0..766692e5 100644
--- a/llama.cpp/llava/llava-quantize.cc
+++ b/llama.cpp/llava/llava-quantize.cc
@@ -1,10 +1,12 @@
// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-
-// vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi
+// vi: set net ft=c++ ts=4 sts=4 sw=4 fenc=utf-8 :vi
#include <stdio.h>
#include <stdlib.h>
+#include "llama.cpp/ggml.h"
#include "clip.h"
int main(int argc, char *argv[]) {
+ ggml_check_cpu();
if (argc != 4) {
fprintf(stderr, "Usage: %s INPUT OUTPUT FORMAT\n");
exit(1);
diff --git a/llama.cpp/main/main.cc b/llama.cpp/main/main.cc
index 80b3fe45..3bcd40b2 100644
--- a/llama.cpp/main/main.cc
+++ b/llama.cpp/main/main.cc
@@ -3,7 +3,6 @@
#define _COSMO_SOURCE
#include <cosmo.h>
-#include "llama.cpp/cpucheck.h"
#include "tool/args/args.h"
#include "llama.cpp/common.h"
@@ -108,7 +107,7 @@ static void sigint_handler(int signo) {
#endif
int main(int argc, char ** argv) {
- llama_cpucheck();
+ ggml_check_cpu();
LoadZipArgs(&argc, &argv);
ShowCrashReports();
diff --git a/llama.cpp/metal.c b/llama.cpp/metal.c
index 0ed9cd83..bc08bab9 100644
--- a/llama.cpp/metal.c
+++ b/llama.cpp/metal.c
@@ -23,6 +23,18 @@ __static_yoink("llama.cpp/ggml-metal.h");
__static_yoink("llama.cpp/ggml-quants.h");
__static_yoink("llama.cpp/ggml-metal.metal");
+static const struct Source {
+ const char *zip;
+ const char *name;
+} srcs[] = {
+ {"/zip/llama.cpp/ggml.h", "ggml.h"},
+ {"/zip/llama.cpp/ggml-impl.h", "ggml-impl.h"},
+ {"/zip/llama.cpp/ggml-metal.h", "ggml-metal.h"},
+ {"/zip/llama.cpp/ggml-quants.h", "ggml-quants.h"},
+ {"/zip/llama.cpp/ggml-metal.metal", "ggml-metal.metal"},
+ {"/zip/llama.cpp/ggml-metal.m", "ggml-metal.m"}, // must come last
+};
+
static struct Metal {
bool supported;
atomic_uint once;
@@ -45,67 +57,19 @@ static const char *Dlerror(void) {
return msg;
}
-static const char *GetTmpDir(void) {
- const char *tmpdir;
- if (!(tmpdir = getenv("TMPDIR")) || !*tmpdir) {
- if (!(tmpdir = getenv("HOME")) || !*tmpdir) {
- tmpdir = ".";
- }
- }
- return tmpdir;
-}
-
-static void GetAppDir(char path[PATH_MAX]) {
- strlcpy(path, GetTmpDir(), PATH_MAX);
- strlcat(path, "/.llamafile/", PATH_MAX);
-}
-
-static bool IsNewerThan(const char *path, const char *other) {
- struct stat st1, st2;
- if (stat(path, &st1) == -1) {
- // PATH should always exist when calling this function
- perror(path);
- return false;
- }
- if (stat(other, &st2) == -1) {
- if (errno == ENOENT) {
- // PATH should replace OTHER because OTHER doesn't exist yet
- return true;
- } else {
- // some other error happened, so we can't do anything
- perror(path);
- return false;
- }
- }
- // PATH should replace OTHER if PATH was modified more recently
- return timespec_cmp(st1.st_mtim, st2.st_mtim) > 0;
-}
-
-static const struct Source {
- const char *zip;
- const char *name;
-} srcs[] = {
- {"/zip/llama.cpp/ggml.h", "ggml.h"},
- {"/zip/llama.cpp/ggml-impl.h", "ggml-impl.h"},
- {"/zip/llama.cpp/ggml-metal.h", "ggml-metal.h"},
- {"/zip/llama.cpp/ggml-quants.h", "ggml-quants.h"},
- {"/zip/llama.cpp/ggml-metal.metal", "ggml-metal.metal"},
- {"/zip/llama.cpp/ggml-metal.m", "ggml-metal.m"}, // must come last
-};
-
static bool ImportMetalImpl(void) {
// extract source code
char src[PATH_MAX];
bool needs_rebuild = false;
for (int i = 0; i < sizeof(srcs) / sizeof(*srcs); ++i) {
- GetAppDir(src);
+ ggml_get_app_dir(src, PATH_MAX);
if (!i && mkdir(src, 0755) && errno != EEXIST) {
perror(src);
return false;
}
strlcat(src, srcs[i].name, sizeof(src));
- if (IsNewerThan(srcs[i].zip, src)) {
+ if (ggml_is_newer_than(srcs[i].zip, src)) {
needs_rebuild = true;
if (!ggml_extract(srcs[i].zip, src)) {
return false;
@@ -115,9 +79,9 @@ static bool ImportMetalImpl(void) {
// compile dynamic shared object
char dso[PATH_MAX];
- GetAppDir(dso);
+ ggml_get_app_dir(dso, PATH_MAX);
strlcat(dso, "ggml-metal.dylib", sizeof(dso));
- if (needs_rebuild || IsNewerThan(src, dso)) {
+ if (needs_rebuild || ggml_is_newer_than(src, dso)) {
tinyprint(2, "building ggml-metal.dylib with xcode...\n", NULL);
int fd;
char tmpdso[PATH_MAX];
@@ -200,15 +164,16 @@ static bool ImportMetalImpl(void) {
}
static void ImportMetal(void) {
- if (ImportMetalImpl()) {
- ggml_metal.supported = true;
- } else {
- tinyprint(2, "couldn't import metal gpu support\n", NULL);
+ if (IsXnuSilicon()) {
+ if (ImportMetalImpl()) {
+ ggml_metal.supported = true;
+ } else {
+ tinyprint(2, "couldn't import metal gpu support\n", NULL);
+ }
}
}
bool ggml_metal_supported(void) {
- if (!IsXnuSilicon()) return false;
cosmo_once(&ggml_metal.once, ImportMetal);
return ggml_metal.supported;
}
@@ -227,7 +192,7 @@ struct ggml_metal_context *ggml_metal_init(int n_cb, const char *metalPath) {
char path[PATH_MAX];
if (!ggml_metal_supported()) return NULL;
if (!metalPath) {
- GetAppDir(path);
+ ggml_get_app_dir(path, PATH_MAX);
strlcat(path, "ggml-metal.metal", sizeof(path));
metalPath = path;
}
diff --git a/llama.cpp/perplexity/perplexity.cc b/llama.cpp/perplexity/perplexity.cc
index 1acc56f6..4e519bb3 100644
--- a/llama.cpp/perplexity/perplexity.cc
+++ b/llama.cpp/perplexity/perplexity.cc
@@ -1,7 +1,6 @@
// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-
// vi: set net ft=c++ ts=4 sts=4 sw=4 fenc=utf-8 :vi
#include "llama.cpp/common.h"
-#include "llama.cpp/cpucheck.h"
#include "llama.cpp/llama.h"
#include <cmath>
@@ -683,7 +682,7 @@ static void hellaswag_score(llama_context * ctx, const gpt_params & params) {
int main(int argc, char ** argv) {
gpt_params params;
- llama_cpucheck();
+ ggml_check_cpu();
params.n_batch = 512;
if (!gpt_params_parse(argc, argv, params)) {
diff --git a/llama.cpp/quantize/quantize.cc b/llama.cpp/quantize/quantize.cc
index 08f0ddc8..9e174d5e 100644
--- a/llama.cpp/quantize/quantize.cc
+++ b/llama.cpp/quantize/quantize.cc
@@ -94,6 +94,8 @@ static void usage(const char * executable) {
}
int main(int argc, char ** argv) {
+ ggml_check_cpu();
+
if (argc < 3) {
usage(argv[0]);
}
diff --git a/llama.cpp/server/BUILD.mk b/llama.cpp/server/BUILD.mk
index 5732cbb2..033edc63 100644
--- a/llama.cpp/server/BUILD.mk
+++ b/llama.cpp/server/BUILD.mk
@@ -11,18 +11,15 @@ LLAMA_CPP_SERVER_ASSETS := \
$(wildcard llama.cpp/server/public/*) \
llama.cpp/server/.args
-LLAMA_CPP_SERVER_LINKARGS = \
- o/$(MODE)/llama.cpp/server/server.o \
- o/$(MODE)/llama.cpp/server/lib/lib.a \
- o/$(MODE)/llama.cpp/llava/llava.a \
- o/$(MODE)/llama.cpp/llama.cpp.a
-
o/$(MODE)/llama.cpp/server/server: \
- $(LLAMA_CPP_SERVER_LINKARGS) \
- $(LLAMA_CPP_SERVER_ASSETS)
- $(LINK.o) $(LLAMA_CPP_SERVER_LINKARGS) $(LOADLIBES) $(LDLIBS) -o [email protected]
- cd llama.cpp/server && zip -q ../../[email protected] $(LLAMA_CPP_SERVER_ASSETS:llama.cpp/server/%=%)
+ o/$(MODE)/llama.cpp/server/server.o \
+ o/$(MODE)/llama.cpp/server/lib/lib.a \
+ o/$(MODE)/llama.cpp/llava/llava.a \
+ o/$(MODE)/llama.cpp/llama.cpp.a \
+ $(LLAMA_CPP_SERVER_ASSETS:%=o/$(MODE)/%.zip.o)
+
+# strip llama.cpp/server/ directory prefix off name in zip archive
+o/$(MODE)/llama.cpp/server/.args.zip.o: private ZIPOBJ_FLAGS += -B
include llama.cpp/server/lib/BUILD.mk
diff --git a/llama.cpp/server/server.cc b/llama.cpp/server/server.cc
index 91d4a88d..ed167da0 100644
--- a/llama.cpp/server/server.cc
+++ b/llama.cpp/server/server.cc
@@ -6,7 +6,6 @@
#include "llama.cpp/llama.h"
#include "llama.cpp/grammar-parser.h"
#include "llama.cpp/llava/clip.h"
-#include "llama.cpp/cpucheck.h"
#include "llama.cpp/server/lib/lib.h"
#include "llama.cpp/stb_image.h"
@@ -34,7 +33,7 @@ using json = nlohmann::json;
struct server_params
{
std::string hostname = "127.0.0.1";
- std::string public_path = "/zip/public";
+ std::string public_path = "/zip/llama.cpp/server/public";
int32_t port = 8080;
int32_t read_timeout = 600;
int32_t write_timeout = 600;
@@ -2257,7 +2256,7 @@ static void append_to_generated_text_from_generated_token_probs(llama_server_con
int main(int argc, char **argv)
{
- llama_cpucheck();
+ ggml_check_cpu();
#ifdef __COSMOPOLITAN__
LoadZipArgs(&argc, &argv);