Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Allow new completions endpoint to reuse slots
Justine Tunney24a4b87ff642
diff --git a/llamafile/chatbot.cpp b/llamafile/chatbot.cppindex f18be7f6..ae6f123a 100644--- a/llamafile/chatbot.cpp+++ b/llamafile/chatbot.cpp@@ -205,7 +205,7 @@ static void on_context(const std::vector<std::string> &args) {}static void on_clear(const std::vector<std::string> &args) {- llama_kv_cache_seq_rm(g_ctx, 0, g_system_prompt_tokens, tokens_used() - g_system_prompt_tokens);+ llama_kv_cache_seq_rm(g_ctx, 0, g_system_prompt_tokens, -1);g_history.resize(g_system_prompt_tokens);g_stack.clear();fix_stacks();@@ -228,7 +228,7 @@ static void on_pop(const std::vector<std::string> &args) {}printf(BOLD "%12d" RESET " restored " FAINT "(%s)" RESET "\n", g_stack.back(),describe_position(g_stack.back()).c_str());- llama_kv_cache_seq_rm(g_ctx, 0, g_stack.back(), tokens_used() - g_stack.back());+ llama_kv_cache_seq_rm(g_ctx, 0, g_stack.back(), -1);g_history.resize(g_stack.back());g_stack.pop_back();fix_stacks();@@ -244,7 +244,7 @@ static void on_undo(const std::vector<std::string> &args) {}printf(FAINT "restoring conversation to: %s" RESET "\n",describe_position(g_undo.back()).c_str());- llama_kv_cache_seq_rm(g_ctx, 0, g_undo.back(), tokens_used() - g_undo.back());+ llama_kv_cache_seq_rm(g_ctx, 0, g_undo.back(), -1);g_history.resize(g_undo.back());g_undo.pop_back();fix_stacks();diff --git a/llamafile/flags.cpp b/llamafile/flags.cppindex fa4e9804..d8ef693a 100644--- a/llamafile/flags.cpp+++ b/llamafile/flags.cpp@@ -237,9 +237,19 @@ void llamafile_get_flags(int argc, char **argv) {// model flagsif (!strcmp(flag, "-c") || !strcmp(flag, "--ctx-size")) {+ char *ep;if (i == argc)missing("--ctx-size");- FLAG_ctx_size = atoi(argv[i++]);+ FLAG_ctx_size = strtol(argv[i++], &ep, 10);+ if (*ep == 'k')+ FLAG_ctx_size *= 1024;+ continue;+ }++ if (!strcmp(flag, "-s") || !strcmp(flag, "--slots")) {+ if (i == argc)+ missing("--slots");+ FLAG_slots = atoi(argv[i++]);continue;}diff --git a/llamafile/server/cleanup.cpp b/llamafile/server/cleanup.cppindex 5cbed976..1e25418c 100644--- a/llamafile/server/cleanup.cpp+++ b/llamafile/server/cleanup.cpp@@ -30,7 +30,7 @@ cleanup_float_vector(void* arg)voidcleanup_token_vector(void* arg){- delete (std::vector<llama_token>*)arg;+ delete (std::vector<int>*)arg;}voiddiff --git a/llamafile/server/client.cpp b/llamafile/server/client.cppindex de2685be..3d250174 100644--- a/llamafile/server/client.cpp+++ b/llamafile/server/client.cpp@@ -32,6 +32,7 @@#include "llamafile/version.h"#include "log.h"+#include "server.h"#include "time.h"#include "tokenbucket.h"#include "worker.h"@@ -54,8 +55,11 @@ on_http_cancel(Client* client)static ThreadLocal<Client> g_http_cancel(on_http_cancel);-Client::Client()- : cleanups(nullptr), ibuf(FLAG_http_ibuf_size), obuf(FLAG_http_obuf_size)+Client::Client(llama_model* model)+ : model_(model)+ , cleanups(nullptr)+ , ibuf(FLAG_http_ibuf_size)+ , obuf(FLAG_http_obuf_size){InitHttpMessage(&msg, 0);url.params.p = nullptr;@@ -213,11 +217,11 @@ Client::transport()}if (get_header("X-Priority") == "batch") {- worker->deprioritize();+ worker_->deprioritize();} else if (!effective_ip_trusted) {if (tokenbucket_acquire(client_ip) > FLAG_token_burst) {SLOG("deprioritizing");- worker->deprioritize();+ worker_->deprioritize();}}diff --git a/llamafile/server/client.h b/llamafile/server/client.hindex cf9615ac..c7d97495 100644--- a/llamafile/server/client.h+++ b/llamafile/server/client.h@@ -36,7 +36,9 @@#define HeaderEqualCase(H, S) \SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H))+struct Slot;struct Worker;+struct llama_model;struct TokenizeParams;struct EmbeddingParams;struct V1ChatCompletionParams;@@ -58,7 +60,9 @@ struct Clientbool close_connection = false;bool should_send_error_if_canceled;size_t unread = 0;- Worker* worker;+ Worker* worker_; // borrowed+ Slot* slot_ = nullptr; // owned or null+ llama_model* model_; // borrowedtimespec message_started;HttpMessage msg;Url url = {};@@ -69,7 +73,7 @@ struct ClientBuffer ibuf;Buffer obuf;- Client();+ explicit Client(llama_model*);void run();int close();diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cppindex bc000cdf..53008303 100644--- a/llamafile/server/embedding.cpp+++ b/llamafile/server/embedding.cpp@@ -28,7 +28,6 @@#include "fastjson.h"#include "json.h"#include "log.h"-#include "model.h"#include "utils.h"struct EmbeddingParams@@ -161,7 +160,7 @@ Client::embedding()// turn text into tokensauto toks = new std::vector<llama_token>(params->prompt.size() + 16);defer_cleanup(cleanup_token_vector, toks);- int count = llama_tokenize(g_model,+ int count = llama_tokenize(model_,params->prompt.data(),params->prompt.size(),&(*toks)[0],@@ -178,7 +177,7 @@ Client::embedding()return send_error(400, "completely empty prompt disallowed");// truncate if exceeds model context size- const int n_ctx_train = llama_n_ctx_train(g_model);+ const int n_ctx_train = llama_n_ctx_train(model_);if (count > n_ctx_train)count = n_ctx_train;@@ -200,7 +199,7 @@ Client::embedding()cparams.type_k = GGML_TYPE_F16;cparams.type_v = GGML_TYPE_F16;cparams.flash_attn = FLAG_flash_attn;- llama_context* ctx = llama_new_context_with_model(g_model, cparams);+ llama_context* ctx = llama_new_context_with_model(model_, cparams);if (!ctx) {SLOG("llama_new_context_with_model failed");return send_error(500);@@ -208,7 +207,7 @@ Client::embedding()defer_cleanup(cleanup_llama_context, ctx);// initialize batch- const int n_embd = llama_n_embd(g_model);+ const int n_embd = llama_n_embd(model_);llama_batch* batch = new llama_batch;*batch = llama_batch_init(count, 0, 1);defer_cleanup(cleanup_llama_batch, batch);diff --git a/llamafile/server/main.1 b/llamafile/server/main.1index 072a118e..702c73e5 100644--- a/llamafile/server/main.1+++ b/llamafile/server/main.1@@ -33,6 +33,24 @@ Specifies the local [HOST:]PORT on which the HTTP server should listen.By default this is 0.0.0.0:8080 which means llamafiler will bind to port8080 on every locally available IPv4 network interface. This option maycurrently only be specified once.+.It Fl c Ar TOKENS , Fl Fl ctx-size Ar TOKENS+Specifies context size. This specifies how long a completion can get+before it runs out of space. It defaults to 8k which means 8192 tokens.+Many models support a larger context size, like 128k, but that'll need+much more RAM or VRAM per slot. If this value is larger than the trained+context size of the model, it'll be tuned down to the maximum. If this+value is 0 or negative, the maximum number of tokens will be used.+.It Fl s Ar COUNT , Fl Fl slots Ar COUNT+Specifies how many slots to maintain. This defaults to 1. Slots are used+by chat completions requests. When such a request comes in, the client+needs to take control of a slot. When the completion is finished, the+slot is relinquished back to the server. HTTP clients will wait for a+slot to be relinquished if none are available. Tuning this parameter to+nicely fit available RAM or VRAM can help you manage your server+resources, and control how much completion parallelism can happen.+Please note that+.Fl Fl ctx-size+has a strong influence on how many slots can be created..It Fl Fl url-prefix Ar URLPREFIXSpecifies a URL prefix (subdirectory) under which the HTTP server willmake the API accessible, e.g. /lamafiler. Useful when running llamafilerdiff --git a/llamafile/server/main.1.asc b/llamafile/server/main.1.ascindex 1916f3d7..91e23ab6 100644--- a/llamafile/server/main.1.asc+++ b/llamafile/server/main.1.asc@@ -35,6 +35,27 @@will bind to port 8080 on every locally available IPv4 networkinterface. This option may currently only be specified once.+ [1m-c [4m[22mTOKENS[24m, [1m--ctx-size [4m[22mTOKENS[0m+ Specifies context size. This specifies how long a completion+ can get before it runs out of space. It defaults to 8k which+ means 8192 tokens. Many models support a larger context size,+ like 128k, but that'll need much more RAM or VRAM per slot. If+ this value is larger than the trained context size of the+ model, it'll be tuned down to the maximum. If this value is 0+ or negative, the maximum number of tokens will be used.++ [1m-s [4m[22mCOUNT[24m, [1m--slots [4m[22mCOUNT[0m+ Specifies how many slots to maintain. This defaults to 1. Slots+ are used by chat completions requests. When such a request+ comes in, the client needs to take control of a slot. When the+ completion is finished, the slot is relinquished back to the+ server. HTTP clients will wait for a slot to be relinquished if+ none are available. Tuning this parameter to nicely fit avail‐+ able RAM or VRAM can help you manage your server resources, and+ control how much completion parallelism can happen. Please+ note that [1m--ctx-size [22mhas a strong influence on how many slots+ can be created.+[1m--url-prefix [4m[22mURLPREFIX[0mSpecifies a URL prefix (subdirectory) under which the HTTPserver will make the API accessible, e.g. /lamafiler. Usefuldiff --git a/llamafile/server/main.cpp b/llamafile/server/main.cppindex 8bdcdcf5..df0d102b 100644--- a/llamafile/server/main.cpp+++ b/llamafile/server/main.cpp@@ -24,15 +24,14 @@#include "llamafile/version.h"#include "log.h"-#include "model.h"#include "server.h"#include "signals.h"+#include "slots.h"#include "time.h"#include "tokenbucket.h"#include "utils.h"Server* g_server;-llama_model* g_model;std::string g_url_prefix;int@@ -42,7 +41,6 @@ main(int argc, char* argv[])mallopt(M_GRANULARITY, 2 * 1024 * 1024);mallopt(M_MMAP_THRESHOLD, 16 * 1024 * 1024);mallopt(M_TRIM_THRESHOLD, 128 * 1024 * 1024);- FLAG_gpu = LLAMAFILE_GPU_DISABLE;llamafile_check_cpu();ShowCrashReports();@@ -88,7 +86,18 @@ main(int argc, char* argv[]).use_mlock = false,.check_tensors = false,};- g_model = llama_load_model_from_file(FLAG_model, mparams);+ llama_model* model = llama_load_model_from_file(FLAG_model, mparams);+ if (!model) {+ fprintf(stderr, "%s: failed to load model\n", FLAG_model);+ exit(1);+ }++ // create slots+ Slots* slots = new Slots(model);+ if (!slots->start(FLAG_slots)) {+ SLOG("no slots could be created");+ exit(1);+ }// create serverif (FLAG_workers <= 0)@@ -96,7 +105,7 @@ main(int argc, char* argv[])if (FLAG_workers <= 0)FLAG_workers = 16;set_thread_name("server");- g_server = new Server(create_listening_socket(FLAG_listen));+ g_server = new Server(create_listening_socket(FLAG_listen), slots, model);for (int i = 0; i < FLAG_workers; ++i)npassert(!g_server->spawn());@@ -122,7 +131,8 @@ main(int argc, char* argv[])g_server->shutdown();g_server->close();delete g_server;- llama_free_model(g_model);+ delete slots;+ llama_free_model(model);tokenbucket_destroy();time_destroy();SLOG("exit");diff --git a/llamafile/server/server.cpp b/llamafile/server/server.cppindex b4d0fa57..108a9d7e 100644--- a/llamafile/server/server.cpp+++ b/llamafile/server/server.cpp@@ -16,6 +16,7 @@// limitations under the License.#include "server.h"+#include "slots.h"#include <assert.h>#include <netinet/in.h>@@ -32,7 +33,8 @@#include "server.h"#include "worker.h"-Server::Server(int fd) : fd(fd)+Server::Server(int fd, Slots* slots, llama_model* model)+ : fd(fd), slots_(slots), model_(model){}@@ -102,12 +104,12 @@ Server::spawn()errno_t err;Worker* worker;pthread_attr_t attr;- worker = new Worker(this);+ worker = new Worker(this, model_);pthread_attr_init(&attr);pthread_attr_setguardsize(&attr, sysconf(_SC_PAGESIZE));pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);pthread_attr_setsigaltstacksize_np(&attr, sysconf(_SC_MINSIGSTKSZ) + 16384);- if ((err = pthread_create(&worker->th, &attr, worker_thread, worker)))+ if ((err = pthread_create(&worker->th_, &attr, worker_thread, worker)))delete worker;pthread_attr_destroy(&attr);return err;diff --git a/llamafile/server/server.h b/llamafile/server/server.hindex 2ef83455..b877f710 100644--- a/llamafile/server/server.h+++ b/llamafile/server/server.h@@ -21,9 +21,12 @@#include <pthread.h>#include <string>+struct Slots;+struct llama_model;+struct Server{- Server(int);+ Server(int, Slots*, llama_model*);~Server();int accept(unsigned*);@@ -38,6 +41,8 @@ struct Servervoid wait();int fd;+ Slots* slots_;+ llama_model* model_;Dll* idle_workers = nullptr;Dll* active_workers = nullptr;pthread_cond_t cond_ = PTHREAD_COND_INITIALIZER;diff --git a/llamafile/server/slot.cpp b/llamafile/server/slot.cppindex 3d8b8746..ffbdb903 100644--- a/llamafile/server/slot.cpp+++ b/llamafile/server/slot.cpp@@ -16,20 +16,19 @@// limitations under the License.#include "slot.h"-#include "llama.cpp/common.h"+#include "llamafile/llama.h"#include "llamafile/llamafile.h"#include "llamafile/macros.h"-#include "llamafile/server/log.h"-#include "llamafile/server/model.h"#include "llamafile/vector.h"#include "llamafile/version.h"+#include "log.h"#include <cassert>#include <cosmo.h>static int-ctx_size(void)+ctx_size(llama_model* model){- int n_ctx_train = llama_n_ctx_train(g_model);+ int n_ctx_train = llama_n_ctx_train(model);if (FLAG_ctx_size <= 0 || FLAG_ctx_size > n_ctx_train)return n_ctx_train;return FLAG_ctx_size;@@ -49,9 +48,8 @@ generate_system_fingerprint(const llama_context_params* cparams)return b;}-Slot::Slot()+Slot::Slot(llama_model* model) : model_(model){- dll_init(&elem_);}Slot::~Slot()@@ -69,7 +67,7 @@ Slot::start()cparams.embeddings_only = false;cparams.logits_all = false;cparams.seed = 12345;- cparams.n_ctx = ctx_size();+ cparams.n_ctx = ctx_size(model_);cparams.n_batch = FLAG_batch;cparams.n_ubatch = FLAG_ubatch;cparams.n_seq_max = 1;@@ -88,7 +86,7 @@ Slot::start()cparams.type_v = GGML_TYPE_F16;cparams.flash_attn = FLAG_flash_attn;system_fingerprint_ = generate_system_fingerprint(&cparams);- if (!(ctx_ = llama_new_context_with_model(g_model, cparams)))+ if (!(ctx_ = llama_new_context_with_model(model_, cparams)))return false;return true;}@@ -100,15 +98,15 @@ Slot::n_ctx()}bool-Slot::eval_token(llama_token id)+Slot::eval_token(int id){- std::vector<llama_token> tokens;+ std::vector<int> tokens;tokens.push_back(id);return eval_tokens(tokens);}bool-Slot::eval_tokens(std::vector<llama_token> tokens)+Slot::eval_tokens(std::vector<int> tokens){unassert(ctx_);if (history_.size() + tokens.size() > n_ctx())@@ -129,17 +127,27 @@ Slot::eval_tokens(std::vector<llama_token> tokens)}bool-Slot::can_use_slot(const std::vector<llama_token>& prompt)+Slot::prefill(const std::vector<int>& tokens){- return ctx_ && vector_starts_with(prompt, history_);-}--bool-Slot::prefill(const std::vector<llama_token>& tokens)-{- unassert(can_use_slot(tokens));- if (history_.empty())- return eval_tokens(tokens);- return eval_tokens(- std::vector<llama_token>(tokens.begin() + history_.size(), tokens.end()));+ unassert(ctx_);+ size_t erase_count = 0;+ size_t reuse_count = lf::vector_common_prefix_length(tokens, history_);+ if (history_.size() > reuse_count) {+ erase_count = history_.size() - reuse_count;+ if (llama_kv_cache_seq_rm(ctx_, 0, reuse_count, -1)) {+ history_.resize(reuse_count);+ } else {+ SLOG("failed to remove tokens from KV cache");+ llama_kv_cache_clear(ctx_);+ reuse_count = 0;+ erase_count = history_.size();+ history_.clear();+ }+ }+ std::vector<int> new_tokens(tokens.begin() + history_.size(), tokens.end());+ SLOG("prefilling %zu tokens (after removing %zu and reusing %zu)",+ new_tokens.size(),+ erase_count,+ reuse_count);+ return eval_tokens(new_tokens);}diff --git a/llamafile/server/slot.h b/llamafile/server/slot.hindex e07d6f1d..4fe7a6ba 100644--- a/llamafile/server/slot.h+++ b/llamafile/server/slot.h@@ -16,29 +16,26 @@// limitations under the License.#pragma once-#include "llama.cpp/llama.h"-#include <cosmo.h>-#include <stdatomic.h>#include <time.h>+#include <utility>#include <vector>-#define SLOT(e) DLL_CONTAINER(Slot, elem, e)+struct llama_model;+struct llama_context;struct Slot{- Dll elem_;- atomic_int refs_ = 0;+ llama_model* model_;llama_context* ctx_ = nullptr;timespec last_used_ = timespec_zero;- std::vector<llama_token> history_;+ std::vector<int> history_;std::string system_fingerprint_;- Slot();+ Slot(llama_model*);~Slot();int n_ctx();bool start();- bool eval_token(llama_token);- bool eval_tokens(std::vector<llama_token>);- bool can_use_slot(const std::vector<llama_token>&);- bool prefill(const std::vector<llama_token>&);+ bool eval_token(int);+ bool eval_tokens(std::vector<int>);+ bool prefill(const std::vector<int>&);};diff --git a/llamafile/server/slot_entry.cpp b/llamafile/server/slot_entry.cppnew file mode 100644index 00000000..de8aab9b--- /dev/null+++ b/llamafile/server/slot_entry.cpp@@ -0,0 +1,52 @@+// -*- 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 "slot_entry.h"+#include "slot.h"+#include <assert.h>++SlotEntry::SlotEntry(Slot* slot) : slot_(slot), key_(nullptr)+{+ unassert(slot);+}++SlotEntry::SlotEntry(const std::vector<int>* key) : slot_(nullptr), key_(key)+{+ unassert(key);+}++SlotEntry::~SlotEntry()+{+}++Slot*+SlotEntry::slot() const+{+ return slot_;+}++const std::vector<int>*+SlotEntry::key() const+{+ return key_ ? key_ : &slot_->history_;+}++bool+operator<(const SlotEntry& lhs, const SlotEntry& rhs)+{+ return *lhs.key() < *rhs.key();+}diff --git a/llamafile/server/model.h b/llamafile/server/slot_entry.hsimilarity index 68%rename from llamafile/server/model.hrename to llamafile/server/slot_entry.hindex ee57c88d..b6d884ba 100644--- a/llamafile/server/model.h+++ b/llamafile/server/slot_entry.h@@ -16,6 +16,23 @@// limitations under the License.#pragma once-#include "llama.cpp/llama.h"+#include <vector>-extern llama_model* g_model;+struct Slot;++class SlotEntry+{+ public:+ explicit SlotEntry(Slot*);+ explicit SlotEntry(const std::vector<int>*);+ ~SlotEntry();+ Slot* slot() const;+ const std::vector<int>* key() const;++ private:+ Slot* slot_;+ const std::vector<int>* key_;+};++bool+operator<(const SlotEntry&, const SlotEntry&);diff --git a/llamafile/server/slots.cpp b/llamafile/server/slots.cppindex 5966454a..c102c629 100644--- a/llamafile/server/slots.cpp+++ b/llamafile/server/slots.cpp@@ -16,11 +16,107 @@// limitations under the License.#include "slots.h"+#include "llamafile/server/log.h"+#include "llamafile/vector.h"+#include "log.h"+#include "slot.h"+#include "slot_entry.h"+#include <assert.h>-Slots::Slots()+Slots::Slots(llama_model* model) : model_(model){+ pthread_mutex_init(&lock_, 0);+ pthread_cond_init(&cond_, 0);}Slots::~Slots(){+ for (const auto& e : slots_)+ if (e.slot())+ delete e.slot();+ pthread_cond_destroy(&cond_);+ pthread_mutex_destroy(&lock_);+}++int+Slots::start(int count)+{+ int made = 0;+ pthread_mutex_lock(&lock_);+ for (int i = 0; i < count; ++i) {+ Slot* slot = new Slot(model_);+ if (slot->start()) {+ ++made;+ slots_.emplace(slot);+ } else {+ delete slot;+ }+ }+ if (made)+ pthread_cond_broadcast(&cond_);+ pthread_mutex_unlock(&lock_);+ if (made < count)+ SLOG("could only make %d out of %d slots", made);+ return made;+}++Slot*+Slots::take(const std::vector<int>& prefix)+{+ pthread_mutex_lock(&lock_);+ for (;;) {++ // find slot with longest matching prefix+ SlotEntry search_key{ &prefix };+ auto i = slots_.upper_bound(search_key);++ // handle special case+ if (i == slots_.end() && i != slots_.begin()) {+ --i;+ Slot* slot = i->slot();+ unassert(slot);+ slots_.erase(i);+ pthread_mutex_unlock(&lock_);+ return slot;+ }++ // avoid slots with non-matching suffix+ // they probably belong to another client+ if (i != slots_.begin()) {+ --i;+ Slot* slot = i->slot();+ unassert(slot);+ int cpl = lf::vector_common_prefix_length(slot->history_, prefix);+ if (cpl == slot->history_.size()) {+ slots_.erase(i);+ pthread_mutex_unlock(&lock_);+ return slot;+ }+ ++i;+ }++ // otherwise return result of search+ if (i != slots_.end()) {+ Slot* slot = i->slot();+ unassert(slot);+ slots_.erase(i);+ pthread_mutex_unlock(&lock_);+ return slot;+ }++ // all slots are being used+ SLOG("waiting for slot to be relinquished...");+ pthread_cond_wait(&cond_, &lock_);+ }+}++void+Slots::give(Slot* slot)+{+ SLOG("relinquishing slot");+ unassert(slot);+ pthread_mutex_lock(&lock_);+ slots_.emplace(slot);+ pthread_cond_signal(&cond_);+ pthread_mutex_unlock(&lock_);}diff --git a/llamafile/server/slots.h b/llamafile/server/slots.hindex 933dae7a..64c4b24a 100644--- a/llamafile/server/slots.h+++ b/llamafile/server/slots.h@@ -16,14 +16,24 @@// limitations under the License.#pragma once-#include <cosmo.h>#include <pthread.h>+#include <set>+#include <vector>++struct Slot;+class SlotEntry;+struct llama_model;struct Slots{- Dll* slots_ = nullptr;- pthread_mutex_t lock_ = PTHREAD_MUTEX_INITIALIZER;+ llama_model* model_;+ std::multiset<SlotEntry> slots_;+ pthread_mutex_t lock_;+ pthread_cond_t cond_;- Slots();+ Slots(llama_model*);~Slots();+ int start(int);+ Slot* take(const std::vector<int>&);+ void give(Slot*);};diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cppindex 2742975b..8f9f71c2 100644--- a/llamafile/server/tokenize.cpp+++ b/llamafile/server/tokenize.cpp@@ -28,7 +28,6 @@#include "fastjson.h"#include "json.h"#include "log.h"-#include "model.h"#include "signals.h"#include "utils.h"@@ -111,7 +110,7 @@ Client::tokenize()// turn text into tokensauto toks = new std::vector<llama_token>(params->prompt.size() + 16);defer_cleanup(cleanup_token_vector, toks);- int count = llama_tokenize(g_model,+ int count = llama_tokenize(model_,params->prompt.data(),params->prompt.size(),&(*toks)[0],@@ -140,7 +139,7 @@ Client::tokenize()p = stpcpy(p, "\n ");char s[32];int n =- llama_token_to_piece(g_model, (*toks)[i], s, sizeof(s), false, true);+ llama_token_to_piece(model_, (*toks)[i], s, sizeof(s), false, true);if (n < 0) {SLOG("failed to turn token into string");return send_error(405);diff --git a/llamafile/server/v1_chat_completions.cpp b/llamafile/server/v1_chat_completions.cppindex f806d62d..7ab7b33b 100644--- a/llamafile/server/v1_chat_completions.cpp+++ b/llamafile/server/v1_chat_completions.cpp@@ -33,9 +33,11 @@#include "fastjson.h"#include "json.h"#include "log.h"-#include "model.h"+#include "server.h"#include "slot.h"+#include "slots.h"#include "utils.h"+#include "worker.h"struct V1ChatCompletionParams{@@ -49,19 +51,19 @@ struct V1ChatCompletionParamsstd::string user;std::string model;std::vector<llama_chat_msg> messages;- std::vector<std::vector<llama_token>> stop;+ std::vector<std::vector<int>> stop;std::string grammar;- void add_stop(const std::string& text)+ void add_stop(llama_model* model, const std::string& text){stop.emplace_back(- llama_tokenize(g_model, text, DONT_ADD_SPECIAL, DONT_PARSE_SPECIAL));+ llama_tokenize(model, text, DONT_ADD_SPECIAL, DONT_PARSE_SPECIAL));}- bool should_stop(const std::vector<llama_token>& history)+ bool should_stop(const std::vector<int>& history){for (const auto& suffix : stop)- if (vector_ends_with(history, suffix))+ if (lf::vector_ends_with(history, suffix))return true;return false;}@@ -70,7 +72,7 @@ struct V1ChatCompletionParamsstruct V1ChatCompletionState{std::string prompt;- std::vector<llama_token> tokens;+ std::vector<int> tokens;std::string piece;};@@ -107,7 +109,11 @@ cleanup_sampler(void* arg)static voidcleanup_slot(void* arg){- delete (Slot*)arg;+ Client* client = (Client*)arg;+ if (client->slot_) {+ client->worker_->server_->slots_->give(client->slot_);+ client->slot_ = nullptr;+ }}static bool@@ -357,7 +363,7 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)Json& stop = json.second["stop"];if (!stop.isNull()) {if (stop.isString()) {- params->add_stop(stop.getString());+ params->add_stop(model_, stop.getString());} else if (stop.isArray()) {std::vector<Json>& stops = stop.getArray();if (stops.size() > 4)@@ -367,7 +373,7 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)return send_error(400, "stop array item must be string");if (stop2.getString().size() > 50)return send_error(400, "stop array string too long");- params->add_stop(stop2.getString());+ params->add_stop(model_, stop2.getString());}} else {return send_error(400, "stop field must be string or string array");@@ -448,29 +454,23 @@ Client::v1_chat_completions()// turn text into tokensstate->prompt =- llama_chat_apply_template(g_model, "", params->messages, ADD_ASSISTANT);+ llama_chat_apply_template(model_, "", params->messages, ADD_ASSISTANT);state->tokens =- llama_tokenize(g_model, state->prompt, DONT_ADD_SPECIAL, PARSE_SPECIAL);+ llama_tokenize(model_, state->prompt, DONT_ADD_SPECIAL, PARSE_SPECIAL);// add bos token if it's needed- if (llama_should_add_bos_token(g_model)) {- llama_token bos = llama_token_bos(g_model);+ if (llama_should_add_bos_token(model_)) {+ llama_token bos = llama_token_bos(model_);if (state->tokens.empty() || state->tokens[0] != bos)state->tokens.insert(state->tokens.begin(), bos);}// find appropriate slot- Slot* slot;- slot = new Slot;- if (!slot->start()) {- delete slot;- SLOG("failed to create slot");- return send_error(500);- }- defer_cleanup(cleanup_slot, slot);+ slot_ = worker_->server_->slots_->take(state->tokens);+ defer_cleanup(cleanup_slot, this);// sanity check- if (state->tokens.size() + 1 > slot->n_ctx())+ if (state->tokens.size() + 1 > slot_->n_ctx())return send_error(400, "prompt too big for model context size");// init sampling@@ -480,7 +480,7 @@ Client::v1_chat_completions()defer_cleanup(cleanup_sampler, sampler);// prefill time- if (!slot->prefill(state->tokens)) {+ if (!slot_->prefill(state->tokens)) {SLOG("slot prefill failed");return send_error(500, "llama_decode prefill failed");}@@ -489,7 +489,7 @@ Client::v1_chat_completions()response->json["id"].setString(generate_id());response->json["object"].setString("chat.completion");response->json["model"].setString(params->model);- response->json["system_fingerprint"].setString(slot->system_fingerprint_);+ response->json["system_fingerprint"].setString(slot_->system_fingerprint_);response->json["choices"].setArray();Json& choice = response->json["choices"][0];choice.setObject();@@ -519,27 +519,27 @@ Client::v1_chat_completions()for (;;) {if (params->max_tokens >= 0 &&completion_tokens >= params->max_tokens) {- slot->eval_token(llamafile_token_eot(g_model));+ slot_->eval_token(llamafile_token_eot(model_));break;}- llama_token id = llama_sampling_sample(sampler, slot->ctx_, NULL);- llama_sampling_accept(sampler, slot->ctx_, id, APPLY_GRAMMAR);+ llama_token id = llama_sampling_sample(sampler, slot_->ctx_, NULL);+ llama_sampling_accept(sampler, slot_->ctx_, id, APPLY_GRAMMAR);++completion_tokens;- if (!slot->eval_token(id)) {+ if (!slot_->eval_token(id)) {SLOG("ran out of context window");break;}- if (llama_token_is_eog(g_model, id)) {+ if (llama_token_is_eog(model_, id)) {finish_reason = "stop";break;}- if (params->should_stop(slot->history_)) {- slot->eval_token(llamafile_token_eot(g_model));+ if (params->should_stop(slot_->history_)) {+ slot_->eval_token(llamafile_token_eot(model_));finish_reason = "stop";break;}state->piece =- llama_token_to_piece(slot->ctx_, id, DONT_RENDER_SPECIAL_TOKENS);+ llama_token_to_piece(slot_->ctx_, id, DONT_RENDER_SPECIAL_TOKENS);if (!state->piece.empty()) {if (params->stream) {char* p = append_http_response_message(obuf.p, 200);@@ -558,6 +558,7 @@ Client::v1_chat_completions()choice["finish_reason"].setString(finish_reason);// finalize response+ cleanup_slot(this);if (params->stream) {choice["delta"].setObject();choice["delta"]["content"].setString("");diff --git a/llamafile/server/worker.cpp b/llamafile/server/worker.cppindex 9152bb5e..ce327969 100644--- a/llamafile/server/worker.cpp+++ b/llamafile/server/worker.cpp@@ -27,86 +27,88 @@#include "client.h"#include "log.h"+#include "server.h"#include "signals.h"#include "tokenbucket.h"-Worker::Worker(Server* server) : server(server)+Worker::Worker(Server* server, llama_model* model)+ : server_(server), client_(model){- dll_init(&elem);+ dll_init(&elem_);}voidWorker::kill(){- pthread_cancel(th);+ pthread_cancel(th_);}voidWorker::begin(){- npassert(!working);- client.worker = this;- client.client_ip_trusted = is_trusted_ip(client.client_ip);+ npassert(!working_);+ client_.worker_ = this;+ client_.client_ip_trusted = is_trusted_ip(client_.client_ip);int tokens = 0;- if (!client.client_ip_trusted)- tokens = tokenbucket_acquire(client.client_ip);- server->lock();- dll_remove(&server->idle_workers, &elem);- if (dll_is_empty(server->idle_workers)) {+ if (!client_.client_ip_trusted)+ tokens = tokenbucket_acquire(client_.client_ip);+ server_->lock();+ dll_remove(&server_->idle_workers, &elem_);+ if (dll_is_empty(server_->idle_workers)) {Dll* slowbro;- if ((slowbro = dll_last(server->active_workers))) {+ if ((slowbro = dll_last(server_->active_workers))) {SLOG("all threads active! dropping oldest client");WORKER(slowbro)->kill();}}- working = true;+ working_ = true;if (tokens > FLAG_token_burst) {- dll_make_last(&server->active_workers, &elem);+ dll_make_last(&server_->active_workers, &elem_);} else {- dll_make_first(&server->active_workers, &elem);+ dll_make_first(&server_->active_workers, &elem_);}- server->unlock();+ server_->unlock();}voidWorker::end(){- npassert(working);- server->lock();- dll_remove(&server->active_workers, &elem);- working = false;- dll_make_first(&server->idle_workers, &elem);- server->unlock();+ npassert(working_);+ server_->lock();+ dll_remove(&server_->active_workers, &elem_);+ working_ = false;+ dll_make_first(&server_->idle_workers, &elem_);+ server_->unlock();}voidWorker::deprioritize(){- npassert(working);- server->lock();- dll_remove(&server->active_workers, &elem);- dll_make_last(&server->active_workers, &elem);- server->unlock();+ npassert(working_);+ server_->lock();+ dll_remove(&server_->active_workers, &elem_);+ dll_make_last(&server_->active_workers, &elem_);+ server_->unlock();}voidWorker::retire(){- server->lock();- if (working)- dll_remove(&server->active_workers, &elem);+ server_->lock();+ if (working_)+ dll_remove(&server_->active_workers, &elem_);else- dll_remove(&server->idle_workers, &elem);- server->worker_count.fetch_sub(1, std::memory_order_acq_rel);- server->signal();- server->unlock();+ dll_remove(&server_->idle_workers, &elem_);+ server_->worker_count.fetch_sub(1, std::memory_order_acq_rel);+ server_->signal();+ server_->unlock();delete this;}voidWorker::handle(){- if ((client.fd = server->accept(&client.client_ip)) == -1) {+ if ((client_.fd = server_->accept(&client_.client_ip)) == -1) {SLOG("accept returned %m");return;}@@ -114,35 +116,35 @@ Worker::handle()begin();try {- client.run();+ client_.run();} catch (const std::exception& e) {SLOG("caught %s", e.what());} catch (...) {SLOG("caught unknown exception");}- client.close();+ client_.close();end();}voidWorker::run(){- server->lock();- dll_make_first(&server->idle_workers, &elem);- server->worker_count.fetch_add(1, std::memory_order_acq_rel);- server->unlock();+ server_->lock();+ dll_make_first(&server_->idle_workers, &elem_);+ server_->worker_count.fetch_add(1, std::memory_order_acq_rel);+ server_->unlock();static ThreadLocal<Worker> cleanup([](Worker* worker) {- if (worker->working) {- worker->client.close();+ if (worker->working_) {+ worker->client_.close();worker->end();}worker->retire();});cleanup.set(this);- while (!server->terminated.load(std::memory_order_acquire)) {+ while (!server_->terminated.load(std::memory_order_acquire)) {sigset_t mask;sigemptyset(&mask);sigaddset(&mask, SIGHUP);diff --git a/llamafile/server/worker.h b/llamafile/server/worker.hindex a76ccb61..a40b240b 100644--- a/llamafile/server/worker.h+++ b/llamafile/server/worker.h@@ -17,21 +17,23 @@#pragma once#include "client.h"-#include "server.h"#include <cosmo.h>#include <pthread.h>-#define WORKER(e) DLL_CONTAINER(Worker, elem, e)+#define WORKER(e) DLL_CONTAINER(Worker, elem_, e)++struct Server;+struct llama_model;struct Worker{- Server* server;- Dll elem;- pthread_t th = 0;- bool working = false;- Client client;+ Server* server_;+ Dll elem_;+ pthread_t th_ = 0;+ bool working_ = false;+ Client client_;- Worker(Server*);+ explicit Worker(Server*, llama_model*);void run();void begin();void handle();diff --git a/llamafile/vector.h b/llamafile/vector.hindex a167bb4d..7cdaafaf 100644--- a/llamafile/vector.h+++ b/llamafile/vector.h@@ -19,6 +19,8 @@#include <algorithm>#include <vector>+namespace lf {+template <typename T>bool vector_starts_with(const std::vector<T> &sequence, const std::vector<T> &prefix) {if (prefix.size() > sequence.size())@@ -32,3 +34,16 @@ bool vector_ends_with(const std::vector<T> &sequence, const std::vector<T> &suffreturn false;return std::equal(sequence.rbegin(), sequence.rend(), suffix.rbegin());}++template <typename T>+size_t vector_common_prefix_length(const std::vector<T> &a, const std::vector<T> &b) {+ size_t i = 0;+ size_t n = std::min(a.size(), b.size());+ const T *ai = a.data();+ const T *bi = b.data();+ while (i < n && ai[i] == bi[i])+ ++i;+ return i;+}++} // namespace lf