Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Fix POSIX undefined cancelation behavior
Justine Tunney8604e9a5b49a
diff --git a/Makefile b/Makefileindex 1b579122..4beee474 100644--- a/Makefile+++ b/Makefile@@ -40,7 +40,8 @@ install: llamafile/zipalign.1 \o/$(MODE)/llama.cpp/quantize/quantize \o/$(MODE)/llama.cpp/llama-bench/llama-bench \o/$(MODE)/llama.cpp/perplexity/perplexity \- o/$(MODE)/llama.cpp/llava/llava-quantize+ o/$(MODE)/llama.cpp/llava/llava-quantize \+ o/$(MODE)/llamafile/server/mainmkdir -p $(PREFIX)/bin$(INSTALL) o/$(MODE)/llamafile/zipalign $(PREFIX)/bin/zipalign$(INSTALL) o/$(MODE)/llamafile/tokenize $(PREFIX)/bin/llamafile-tokenize@@ -52,6 +53,7 @@ install: llamafile/zipalign.1 \$(INSTALL) build/llamafile-upgrade-engine $(PREFIX)/bin/llamafile-upgrade-engine$(INSTALL) o/$(MODE)/llama.cpp/perplexity/perplexity $(PREFIX)/bin/llamafile-perplexity$(INSTALL) o/$(MODE)/llama.cpp/llava/llava-quantize $(PREFIX)/bin/llava-quantize+ $(INSTALL) o/$(MODE)/llamafile/server/main $(PREFIX)/bin/llamafilermkdir -p $(PREFIX)/share/man/man1$(INSTALL) -m 0644 llamafile/zipalign.1 $(PREFIX)/share/man/man1/zipalign.1$(INSTALL) -m 0644 llama.cpp/main/main.1 $(PREFIX)/share/man/man1/llamafile.1diff --git a/llama.cpp/llama.cpp b/llama.cpp/llama.cppindex 6db75b3b..44673872 100644--- a/llama.cpp/llama.cpp+++ b/llama.cpp/llama.cpp@@ -58,6 +58,8 @@#include <sys/resource.h>#include <ctl/vector.h>+#include "llamafile/server/threadlocal.h"+#define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((__format__(__gnu_printf__, __VA_ARGS__)))#define LLAMA_MAX_NODES 8192@@ -17328,16 +17330,17 @@ int32_t llama_decode(// [jart] pthread_cancel() safetyllama_decoder * decoder = new llama_decoder;- pthread_cleanup_push(- [](void* arg) {- llama_decoder * decoder = (llama_decoder*)arg;+ static ThreadLocal<llama_decoder> cleanup(+ [](llama_decoder* decoder) {delete decoder;- },- decoder);+ });+ cleanup.set(decoder);ret = llama_decode_internal(*ctx, batch, decoder);- pthread_cleanup_pop(true);+ // [jart] pthread_cancel() safety+ cleanup.set(nullptr);+ delete decoder;if (ret < 0) {LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);diff --git a/llamafile/refcounted.h b/llamafile/refcounted.hdeleted file mode 100644index ca93d980..00000000--- a/llamafile/refcounted.h+++ /dev/null@@ -1,46 +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.--#pragma once-#include <stdatomic.h>--template <typename T>-class RefCounted {- public:- RefCounted() : refs_(ATOMIC_VAR_INIT(0)) {- }-- virtual ~RefCounted() {- if (atomic_load_explicit(&refs_, memory_order_relaxed) != -1)- __builtin_trap();- }-- T *ref() {- atomic_fetch_add_explicit(&refs_, 1, memory_order_relaxed);- return (T *)this;- }-- void unref() {- if (atomic_fetch_sub_explicit(&refs_, 1, memory_order_release))- return;- atomic_thread_fence(memory_order_acquire);- delete this;- }-- private:- atomic_int refs_;-};diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cppindex 5b50936a..cd67ea3d 100644--- a/llamafile/server/client.cpp+++ b/llamafile/server/client.cpp@@ -30,6 +30,7 @@#include "llamafile/version.h"#include "log.h"+#include "threadlocal.h"#include "time.h"#define STANDARD_RESPONSE_HEADERS \@@ -39,6 +40,17 @@using namespace ctl;+static void+on_http_cancel(Client* client)+{+ if (client->should_send_error_if_canceled) {+ fcntl(client->fd, F_SETFL, fcntl(client->fd, F_GETFL) | O_NONBLOCK);+ client->send_error(503);+ }+}++static ThreadLocal<Client> g_http_cancel(on_http_cancel);+Client::Client(): cleanups(nullptr), ibuf(FLAG_http_ibuf_size), obuf(FLAG_http_obuf_size){@@ -375,10 +387,6 @@ static voidcancel_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);- }}bool@@ -386,9 +394,9 @@ Client::dispatch(){bool res;should_send_error_if_canceled = true;- pthread_cleanup_push(cancel_http_request, this);+ g_http_cancel.set(this);res = dispatcher();- pthread_cleanup_pop(false);+ g_http_cancel.set(nullptr);return res;}diff --git a/llamafile/server/completion.cpp b/llamafile/server/completion.cppindex 03a124ec..2086bf41 100644--- a/llamafile/server/completion.cpp+++ b/llamafile/server/completion.cpp@@ -49,18 +49,6 @@ struct CompletionResponseextern llama_model* g_model;-void-normalize_completions(const float* inp, float* out, int n)-{- double sum = 0;- for (int i = 0; i < n; i++)- sum += inp[i] * inp[i];- sum = sqrt(sum);- const float norm = sum > 0 ? 1.f / sum : 0.f;- for (int i = 0; i < n; i++)- out[i] = inp[i] * norm;-}-static voidadd_token_to_batch(llama_batch& batch,llama_token id,@@ -266,32 +254,32 @@ Client::completion()// serialize tokens to jsonchar* p = obuf.p;- p = stpcpy(p, "{\r\n");+ p = stpcpy(p, "{\n");p = stpcpy(p, " \"add_special\": ");p = encode_bool(p, params->add_special);- p = stpcpy(p, ",\r\n");+ p = stpcpy(p, ",\n");p = stpcpy(p, " \"parse_special\": ");p = encode_bool(p, params->parse_special);- p = stpcpy(p, ",\r\n");+ p = stpcpy(p, ",\n");p = stpcpy(p, " \"display_special\": ");p = encode_bool(p, params->display_special);- p = stpcpy(p, ",\r\n");+ p = stpcpy(p, ",\n");p = stpcpy(p, " \"tokens_provided\": ");p = encode_json(p, toks->size());- p = stpcpy(p, ",\r\n");+ p = stpcpy(p, ",\n");p = stpcpy(p, " \"tokens_used\": ");p = encode_json(p, count);- p = stpcpy(p, ",\r\n");+ p = stpcpy(p, ",\n");p = stpcpy(p, " \"prompt\": ");p = encode_json(p, response->prompt);- p = stpcpy(p, ",\r\n");+ p = stpcpy(p, ",\n");p = stpcpy(p, " \"content\": ");p = encode_json(p, response->content);- p = stpcpy(p, ",\r\n");+ p = stpcpy(p, ",\n");p = stpcpy(p, " \"stop\": ");p = encode_bool(p, response->stop);- p = stpcpy(p, "\r\n");- p = stpcpy(p, "}\r\n");+ p = stpcpy(p, "\n");+ p = stpcpy(p, "}\n");ctl::string_view content(obuf.p, p - obuf.p);// collect statisticsdiff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cppindex 037e308e..311439c6 100644--- a/llamafile/server/embedding.cpp+++ b/llamafile/server/embedding.cpp@@ -211,7 +211,7 @@ Client::embedding()// serialize tokens to jsonchar* p = obuf.p;- p = stpcpy(p, "{\r\n");+ p = stpcpy(p, "{\n");p = stpcpy(p, " \"add_special\": ");p = encode_bool(p, params->add_special);p = stpcpy(p, ",\n");@@ -232,8 +232,8 @@ Client::embedding()}p = encode_json(p, (*embeddings)[i]);}- p = stpcpy(p, "]\r\n");- p = stpcpy(p, "}\r\n");+ p = stpcpy(p, "]\n");+ p = stpcpy(p, "}\n");ctl::string_view content(obuf.p, p - obuf.p);// collect statisticsdiff --git a/llamafile/server/main.cpp b/llamafile/server/main.cppindex 100c6c04..7164ea0b 100644--- a/llamafile/server/main.cpp+++ b/llamafile/server/main.cpp@@ -36,7 +36,7 @@ main(int argc, char* argv[])ShowCrashReports();llamafile_check_cpu();if (llamafile_has(argv, "--version")) {- puts("llamafile-server v" LLAMAFILE_VERSION_STRING);+ puts("llamafiler v" LLAMAFILE_VERSION_STRING);exit(0);}diff --git a/llamafile/threadlocal.h b/llamafile/server/threadlocal.hsimilarity index 78%rename from llamafile/threadlocal.hrename to llamafile/server/threadlocal.hindex b275dd18..816163aa 100644--- a/llamafile/threadlocal.h+++ b/llamafile/server/threadlocal.h@@ -18,26 +18,30 @@#pragma once#include <pthread.h>-template <typename T>-struct ThreadLocal {-- explicit ThreadLocal(void (*dtor)(T *value)) {- if (pthread_key_create(&key_, (void (*)(void *))dtor))+template<typename T>+struct ThreadLocal+{+ explicit ThreadLocal(void (*dtor)(T* value))+ {+ if (pthread_key_create(&key_, (void (*)(void*))dtor))__builtin_trap();}- ~ThreadLocal() {+ ~ThreadLocal()+ {if (pthread_key_delete(key_))__builtin_trap();}- void set(T *value) {+ void set(T* value)+ {if (pthread_setspecific(key_, value))__builtin_trap();}- T *get() {- return (T *)pthread_getspecific(key_);+ T* get()+ {+ return (T*)pthread_getspecific(key_);}private:diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cppindex 84fb47a5..f953048f 100644--- a/llamafile/server/tokenize.cpp+++ b/llamafile/server/tokenize.cpp@@ -23,6 +23,7 @@#include "llama.cpp/llama.h"+#include "cleanup.h"#include "fastjson.h"#include "log.h"#include "utils.h"@@ -70,11 +71,12 @@ Client::tokenize()// turn text into tokensextern llama_model* g_model;int maxcount = input.size() + 16;- ctl::vector<llama_token> toks(maxcount);+ auto toks = new ctl::vector<llama_token>(maxcount);+ defer_cleanup(cleanup_token_vector, toks);int count = llama_tokenize(g_model,input.data(),input.size(),- &toks[0],+ &(*toks)[0],maxcount,add_special,parse_special);@@ -82,11 +84,11 @@ Client::tokenize()SLOG("failed to tokenize");return send_error(405);}- toks.resize(count);+ toks->resize(count);// serialize tokens to jsonchar* p = obuf.p;- p = stpcpy(p, "{\r\n");+ p = stpcpy(p, "{\n");p = stpcpy(p, " \"add_special\": ");p = encode_bool(p, add_special);p = stpcpy(p, ",\n");@@ -97,17 +99,17 @@ Client::tokenize()for (int i = 0; i < count; ++i) {if (i)*p++ = ',';- p = stpcpy(p, "\r\n ");+ p = stpcpy(p, "\n ");char s[32];- int n = llama_token_to_piece(g_model, toks[i], s, sizeof(s), true);+ int n = llama_token_to_piece(g_model, (*toks)[i], s, sizeof(s), true);if (n < 0) {SLOG("failed to turn token into string");return send_error(405);}p = encode_json(p, ctl::string_view(s, n));}- p = stpcpy(p, "\r\n ]\r\n");- p = stpcpy(p, "}\r\n");+ p = stpcpy(p, "\n ]\n");+ p = stpcpy(p, "}\n");ctl::string_view content(obuf.p, p - obuf.p);// collect statisticsdiff --git a/llamafile/server/worker.cpp b/llamafile/server/worker.cppindex 8396bde0..18090b87 100644--- a/llamafile/server/worker.cpp+++ b/llamafile/server/worker.cpp@@ -21,10 +21,12 @@#include <exception>#include <pthread.h>-#include "client.h"#include "llamafile/llamafile.h"++#include "client.h"#include "log.h"#include "signals.h"+#include "threadlocal.h"Worker::Worker(Server* server) : server(server){@@ -89,13 +91,6 @@ Worker::handle(void)}begin();- pthread_cleanup_push(- [](void* arg) {- Worker* worker = (Worker*)arg;- worker->client.close();- worker->end();- },- this);try {client.run();@@ -105,7 +100,8 @@ Worker::handle(void)SLOG("caught unknown exception");}- pthread_cleanup_pop(true);+ client.close();+ end();}void@@ -116,12 +112,14 @@ Worker::run()server->worker_count.fetch_add(1, std::memory_order_acq_rel);server->unlock();- pthread_cleanup_push(- [](void* arg) {- Worker* worker = (Worker*)arg;- worker->retire();- },- this);+ static ThreadLocal<Worker> cleanup([](Worker* worker) {+ if (worker->working) {+ worker->client.close();+ worker->end();+ }+ worker->retire();+ });+ cleanup.set(this);while (!server->terminated.load(std::memory_order_acquire)) {sigset_t mask;@@ -136,5 +134,6 @@ Worker::run()handle();}- pthread_cleanup_pop(true);+ cleanup.set(nullptr);+ retire();}