Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Make GGML asynchronously cancelable
Justine Tunneyb3930aa6472f
diff --git a/llama.cpp/ggml.c b/llama.cpp/ggml.cindex 946f18cc..d420b0c2 100644--- a/llama.cpp/ggml.c+++ b/llama.cpp/ggml.c@@ -1636,7 +1636,7 @@ struct ggml_compute_state_shared {typedef pthread_t ggml_thread_t;struct ggml_compute_state {- ggml_thread_t thrd;+ _Atomic(ggml_thread_t) thrd;int ith;struct ggml_compute_state_shared* shared;enum ggml_status ec;@@ -19127,6 +19127,26 @@ static void print_graph(FILE *f, const struct ggml_cgraph *g, int n_threads) {}}++struct ggml_compute_cleanup {+ int n_threads;+ struct ggml_compute_state * workers;+};++static void ggml_compute_canceled(void *arg) {+ struct ggml_compute_cleanup *cleanup = arg;+ clear_numa_thread_affinity();+ for (int j = 1; j < cleanup->n_threads; j++) {+ pthread_t t;+ if ((t = atomic_exchange_explicit(&cleanup->workers[j].thrd, 0,+ memory_order_relaxed))) {+ pthread_cancel(t);+ const int rc = ggml_thread_join(t, NULL);+ GGML_ASSERT(rc == 0);+ }+ }+}+enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplan * cplan) {{GGML_ASSERT(cplan);@@ -19170,43 +19190,61 @@ enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplif (n_threads > 1) {for (int j = 1; j < n_threads; ++j) {workers[j] = (struct ggml_compute_state) {- .thrd = 0,+ .thrd = ATOMIC_VAR_INIT(0),.ith = j,.shared = &state_shared,.ec = GGML_STATUS_SUCCESS,.is_main_thread = false, // [jart]};- const int rc = ggml_thread_create(&workers[j].thrd, NULL, ggml_graph_compute_thread, &workers[j]);+ const int rc = ggml_thread_create((pthread_t *)&workers[j].thrd, NULL,+ ggml_graph_compute_thread, &workers[j]);GGML_ASSERT(rc == 0);UNUSED(rc);}}+ int64_t perf_start_cycles;+ int64_t perf_start_time_us;+ enum ggml_status compute_status;+ struct ggml_compute_cleanup cleanup = {n_threads, workers};+ pthread_cleanup_push(ggml_compute_canceled, &cleanup);+workers[0].ith = 0;workers[0].shared = &state_shared;workers[0].ec = GGML_STATUS_SUCCESS;workers[0].is_main_thread = true; // [jart]- const int64_t perf_start_cycles = ggml_perf_cycles();- const int64_t perf_start_time_us = ggml_perf_time_us();+ perf_start_cycles = ggml_perf_cycles();+ perf_start_time_us = ggml_perf_time_us();// this is a work thread tooggml_graph_compute_thread(&workers[0]);- enum ggml_status compute_status = workers[0].ec;-- // don't leave affinity set on the main thread- clear_numa_thread_affinity();+ compute_status = workers[0].ec;// join or kill thread pool- if (n_threads > 1) {- for (int j = 1; j < n_threads; j++) {- const int rc = ggml_thread_join(workers[j].thrd, NULL);+ int cs;+ pthread_setcancelstate(PTHREAD_CANCEL_MASKED, &cs);+ for (int j = 1; j < n_threads; j++) {+ pthread_t t;+ if ((t = atomic_exchange_explicit(&workers[j].thrd, 0,+ memory_order_relaxed))) {+ const int rc = ggml_thread_join(t, NULL);+ if (rc == ECANCELED) {+ workers[j].thrd = t;+ pthread_exit(PTHREAD_CANCELED);+ }GGML_ASSERT(rc == 0);if (workers[j].ec != GGML_STATUS_SUCCESS)compute_status = workers[j].ec;}}+ pthread_setcancelstate(cs, 0);++ // don't leave affinity set on the main thread+ clear_numa_thread_affinity();++ pthread_cleanup_pop(false);#ifdef LLAMAFILE_SYNC_REPORTopstart[cgraph->n_nodes] = rdtsc();diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mkindex 095acaf4..13145f8e 100644--- a/llamafile/BUILD.mk+++ b/llamafile/BUILD.mk@@ -120,7 +120,6 @@ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_arm82.o: private TARGET_ARCH += -Xaarch6o/$(MODE)/llamafile/thread_test: \o/$(MODE)/llamafile/thread_test.o \- o/$(MODE)/llamafile/thread.o \o/$(MODE)/llamafile/crash.o \o/$(MODE)/llamafile/dll3.o \diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cppindex 78ec9c69..70ff4bdb 100644--- a/llamafile/server/client.cpp+++ b/llamafile/server/client.cpp@@ -18,6 +18,7 @@#include "client.h"#include <errno.h>+#include <fcntl.h>#include <limits.h>#include <string.h>#include <sys/uio.h>@@ -215,10 +216,18 @@ Client::transport()return dispatch();}+void+Client::begin_response()+{+ cleanup();+ pthread_testcancel();+ should_send_error_if_canceled = false;+}+boolClient::send_error(int code, const char* reason){- cleanup();+ begin_response();if (!reason)reason = GetHttpReason(code);LOG("error %d %s", code, reason);@@ -254,7 +263,7 @@ Client::start_response(char* p, int code, const char* reason)boolClient::send_response(char* p0, char* p, string_view content){- cleanup();+ begin_response();// append date headertm tm;@@ -362,8 +371,29 @@ Client::read_payload()return true;}+static void+cancel_http_request(void* arg)+{+ Client* client = (Client*)arg;+ if (client->should_send_error_if_canceled) {+ fcntl(client->fd, F_SETFL, fcntl(client->fd, F_GETFL) | O_NONBLOCK);+ client->send_error(503);+ }+}+boolClient::dispatch()+{+ bool res;+ should_send_error_if_canceled = true;+ pthread_cleanup_push(cancel_http_request, this);+ res = dispatcher();+ pthread_cleanup_pop(false);+ return res;+}++bool+Client::dispatcher(){if (path() == "/tokenize")return tokenize();diff --git a/llamafile/server/client.h b/llamafile/server/client.hindex 612e6aa5..add65d4b 100644--- a/llamafile/server/client.h+++ b/llamafile/server/client.h@@ -49,6 +49,7 @@ struct Client{int fd = -1;bool close_connection = false;+ bool should_send_error_if_canceled;size_t unread = 0;timespec message_started;HttpMessage msg;@@ -72,10 +73,11 @@ struct Clientbool read_request() __wur;bool read_content() __wur;bool send_continue() __wur;+ void begin_response();bool send(const ctl::string_view) __wur;void defer_cleanup(void (*)(void*), void*);+ bool send_error(int, const char* = nullptr);char* start_response(char*, int, const char* = nullptr);- bool send_error(int, const char* = nullptr) __wur;bool send_response(char*, char*, const ctl::string_view) __wur;bool send2(const ctl::string_view, const ctl::string_view) __wur;char* append_header(const ctl::string_view, const ctl::string_view);@@ -87,5 +89,6 @@ struct Clientbool dispatch() __wur;bool tokenize() __wur;bool embedding() __wur;+ bool dispatcher() __wur;bool get_embedding_params(EmbeddingParams*);};diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cppindex 22181627..9da30a83 100644--- a/llamafile/server/embedding.cpp+++ b/llamafile/server/embedding.cpp@@ -68,11 +68,9 @@ add_token_to_batch(struct llama_batch& batch,}void-cleanup_llama_batch(void* arg)+cleanup_float_vector(void* arg){- llama_batch* batch = (llama_batch*)arg;- llama_batch_free(*batch);- delete batch;+ delete (ctl::vector<float>*)arg;}void@@ -81,6 +79,14 @@ cleanup_token_vector(void* arg)delete (ctl::vector<llama_token>*)arg;}+void+cleanup_llama_batch(void* arg)+{+ llama_batch* batch = (llama_batch*)arg;+ llama_batch_free(*batch);+ delete batch;+}+voidcleanup_llama_context(void* arg){@@ -211,7 +217,8 @@ Client::embedding()LOG("llama_decode failed");return send_error(500);}- ctl::vector<float> embeddings(n_embd, 0);+ auto embeddings = new ctl::vector<float>(n_embd, 0);+ defer_cleanup(cleanup_float_vector, embeddings);for (int i = 0; i < batch->n_tokens; i++) {if (!batch->logits[i])continue;@@ -221,7 +228,7 @@ Client::embedding()return send_error(500);}normalize_embeddings(- embd, &embeddings[0] + batch->seq_id[i][0] * n_embd, n_embd);+ embd, embeddings->data() + batch->seq_id[i][0] * n_embd, n_embd);}// serialize tokens to json@@ -240,12 +247,12 @@ Client::embedding()p = encode_json(p, count);p = stpcpy(p, ",\n");p = stpcpy(p, " \"embedding\": [");- for (size_t i = 0; i < embeddings.size(); ++i) {+ for (size_t i = 0; i < embeddings->size(); ++i) {if (i) {*p++ = ',';*p++ = ' ';}- p = encode_json(p, embeddings[i]);+ p = encode_json(p, (*embeddings)[i]);}p = stpcpy(p, "]\r\n");p = stpcpy(p, "}\r\n");diff --git a/llamafile/server/main.cpp b/llamafile/server/main.cppindex 119921d2..5e842431 100644--- a/llamafile/server/main.cpp+++ b/llamafile/server/main.cpp@@ -27,15 +27,13 @@#include "signals.h"#include "time.h"-extern "C" void-_pthread_decimate(void);-Server* g_server;llama_model* g_model;intmain(int argc, char* argv[]){+ ShowCrashReports();llamafile_check_cpu();if (llamafile_has(argv, "--version")) {puts("llamafile-server v" LLAMAFILE_VERSION_STRING);@@ -47,6 +45,10 @@ main(int argc, char* argv[])llamafile_get_flags(argc, argv);time_init();+ // we must disable the llama.cpp logger+ // otherwise pthread_cancel() will cause deadlocks+ FLAG_log_disable = true;+// load modelllama_model_params mparams = {.n_gpu_layers = FLAG_n_gpu_layers,@@ -92,6 +94,6 @@ main(int argc, char* argv[])// quality assurancewhile (!pthread_orphan_np())- _pthread_decimate();+ pthread_decimate_np();CheckForMemoryLeaks();}diff --git a/llamafile/thread.cpp b/llamafile/thread.cppdeleted file mode 100644index 07ff55b5..00000000--- a/llamafile/thread.cpp+++ /dev/null@@ -1,146 +0,0 @@-// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*--// vi: set et ft=cpp 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.--#include "thread.h"--#include <stdatomic.h>-#include <stdlib.h>--#include "dll3.h"-#include "lockable.h"-#include "refcounted.h"-#include "threadlocal.h"--struct Parent : public Lockable, public RefCounted<Parent> {- Dll3 *children;-- Parent() : children(nullptr) {- }-- ~Parent() {- if (children)- __builtin_trap();- }-};--struct Child : public RefCounted<Child> {- pthread_t thread;- int detach_state;- _Atomic(Parent *) parent;- void *(*start_routine)(void *);- void *arg;- Dll3 elem; // owned by parent lock-- Child(Parent *p, int detach_state, void *(*start_routine)(void *), void *arg)- : thread(0),- detach_state(detach_state),- parent(ATOMIC_VAR_INIT(p->ref())),- start_routine(start_routine),- arg(arg) {- dll3_init(&elem, this);- p->lock();- dll3_make_last(&p->children, &elem);- p->unlock();- }-- ~Child() {- unregister();- }-- void unregister() {- Parent *p;- if ((p = atomic_exchange(&parent, nullptr))) {- p->lock();- dll3_remove(&p->children, &elem);- p->unlock();- p->unref(); // remove child's reference to parent- unref(); // remove parent's reference to child- }- }-};--static void on_child_exit(Child *child) {- child->unregister();- child->unref(); // child frees self-}--static ThreadLocal<Child> g_child(on_child_exit);--static void on_parent_exit(Parent *parent) {- Dll3 *e;- parent->lock();- while ((e = dll3_first(parent->children))) {- Child *child = (Child *)e->container;- if ((parent = atomic_exchange(&child->parent, nullptr))) {- dll3_remove(&parent->children, e);- parent->unlock();- parent->unref(); // remove child's reference to parent- pthread_cancel(child->thread);- if (child->detach_state == PTHREAD_CREATE_JOINABLE)- if (pthread_join(child->thread, 0))- __builtin_trap();- child->unref(); // remove parent's reference to child- parent->lock();- }- }- parent->unlock();- parent->unref(); // parent frees self-}--static ThreadLocal<Parent> g_parent(on_parent_exit);--static void *llamafile_thread(void *arg) {- Child *child;- g_child.set((child = (Child *)arg));- return child->start_routine(child->arg);-}--/**- * Creates managed thread.- *- * Threads created by this function will be canceled automatically, when- * the current thread exits or is itself canceled by another thread. The- * killing hierarchy works for both detached and joinable threads. It is- * a good idea for threads to put themselves in asynchronous cancelation- * mode whilst performing mathematical operations. Threads that block on- * i/o or semaphores should use the default deferred cancelation instead- * since it helps avoid memory leaks and other badness.- *- * @return 0 on success, or errno on error- */-errno_t llamafile_thread_create(pthread_t *thread, const pthread_attr_t *attr,- void *(*start_routine)(void *), void *arg) {- errno_t err;- Parent *parent;- int detach_state = PTHREAD_CREATE_JOINABLE;- if (attr)- pthread_attr_getdetachstate(attr, &detach_state);- if (!(parent = g_parent.get()))- g_parent.set((parent = new Parent));- Child *child = new Child(parent, detach_state, start_routine, arg);- child->ref(); // acquire ownership for parent destructor- child->ref(); // ensure ownership for rest of this function- err = pthread_create(&child->thread, attr, llamafile_thread, child);- if (!err) {- *thread = child->thread;- } else {- child->unref(); // release reference for parent destructor- child->unref(); // release reference for child thread- }- child->unref(); // release reference for this function- return err;-}diff --git a/llamafile/thread_test.cpp b/llamafile/thread_test.cppindex 7fee7243..4d41443f 100644--- a/llamafile/thread_test.cpp+++ b/llamafile/thread_test.cpp@@ -15,19 +15,21 @@// See the License for the specific language governing permissions and// limitations under the License.-#include "thread.h"-#include <cosmo.h>+#include <pthread.h>#include <stdatomic.h>#include <stdlib.h>-#define WORKERS 10-#define MATHS 10+#define WORKERS 20+#define MATHS 20atomic_int barrier;void *start_math(void *arg) {+ long id = (long)arg;++barrier;+ if ((long)arg % 2 == 0)+ return 0;pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);pthread_testcancel();for (;;) {@@ -35,21 +37,45 @@ void *start_math(void *arg) {}void *start_worker(void *arg) {- ++barrier;- pthread_t th[MATHS];- for (int i = 0; i < MATHS; ++i)- if (llamafile_thread_create(&th[i], 0, start_math, 0))+ _Atomic(pthread_t) th[MATHS];+ for (long i = 0; i < MATHS; ++i)+ if (pthread_create((pthread_t *)&th[i], 0, start_math, (void *)i))_Exit(3);- for (int i = 0; i < MATHS; ++i)- if (pthread_join(th[i], 0))- _Exit(4);+ pthread_cleanup_push(+ [](void *arg) {+ _Atomic(pthread_t) *th = (_Atomic(pthread_t) *)arg;+ for (long i = 0; i < MATHS; ++i) {+ pthread_t t;+ if ((t = atomic_exchange(&th[i], 0))) {+ pthread_cancel(t);+ if (pthread_join(t, 0))+ _Exit(4);+ }+ }+ },+ th);+ start_math(arg);+ pthread_setcancelstate(PTHREAD_CANCEL_MASKED, 0);+ for (long i = 0; i < MATHS; ++i) {+ pthread_t t;+ if ((t = atomic_exchange(&th[i], 0))) {+ int err = pthread_join(t, 0);+ if (err == ECANCELED) {+ th[i] = t;+ pthread_exit(PTHREAD_CANCELED);+ }+ if (err)+ _Exit(4);+ }+ }+ pthread_cleanup_pop(false);return 0;}int main() {pthread_t th[WORKERS];- for (int i = 0; i < WORKERS; ++i)- if (llamafile_thread_create(&th[i], 0, start_worker, 0))+ for (long i = 0; i < WORKERS; ++i)+ if (pthread_create(&th[i], 0, start_worker, (void *)i))_Exit(1);while (barrier < WORKERS * MATHS) {}