Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Include llamafiler in llamafile binary
Justine Tunneye64c7e2c62bf
diff --git a/README.md b/README.mdindex 0fdcc842..ae28b2e4 100644--- a/README.md+++ b/README.md@@ -164,6 +164,17 @@ ChatCompletionMessage(content='There once was a programmer named Mike\nWho wrote</details>+## New v2 Server++We have a new server that has a better web gui. It also implements+OpenAI API compatible endpoints, including embeddings. It's designed to+be more reliable. It's better able to recycle context windows across+multiple slots. To try it, run:++```+llamafile --server --v2 --help+llamafile --server --v2+```## Other example llamafilesdiff --git a/build/config.mk b/build/config.mkindex 552e6225..3f95c9ca 100644--- a/build/config.mk+++ b/build/config.mk@@ -2,7 +2,7 @@#── vi: set noet ft=make ts=8 sw=8 fenc=utf-8 :vi ────────────────────┘PREFIX = /usr/local-COSMOCC = .cosmocc/4.0.0+COSMOCC = .cosmocc/4.0.2TOOLCHAIN = $(COSMOCC)/bin/cosmoCC = $(TOOLCHAIN)cc@@ -52,5 +52,5 @@ clean:; rm -rf o.PHONY: distcleandistclean:; rm -rf o .cosmocc-.cosmocc/4.0.0:- build/download-cosmocc.sh $@ 4.0.0 15d8ab4442c94ce925f1d59884c772ab817af5e2889549c21ce5fa11c5d773bc+.cosmocc/4.0.2:+ build/download-cosmocc.sh $@ 4.0.2 85b8c37a406d862e656ad4ec14be9f6ce474c1b436b9615e91a55208aced3f44diff --git a/llama.cpp/common.cpp b/llama.cpp/common.cppindex 1c215ff3..dba1b3e9 100644--- a/llama.cpp/common.cpp+++ b/llama.cpp/common.cpp@@ -217,6 +217,10 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_paFLAG_fast = true;return true;}+ if (arg == "--v2") {+ FLAG_v2 = true;+ return true;+ }if (arg == "--iq") {FLAG_iq = true;return true;@@ -633,6 +637,7 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_paif (arg == "-m" || arg == "--model") {CHECK_ARGparams.model = argv[i];+ FLAG_model = params.model.c_str(); // [jart]return true;}if (arg == "-md" || arg == "--model-draft") {diff --git a/llama.cpp/main/BUILD.mk b/llama.cpp/main/BUILD.mkindex fb432e16..f47b3236 100644--- a/llama.cpp/main/BUILD.mk+++ b/llama.cpp/main/BUILD.mk@@ -11,13 +11,16 @@ LLAMA_CPP_MAIN_OBJS = $(LLAMA_CPP_MAIN_SRCS:%.cpp=o/$(MODE)/%.o)o/$(MODE)/llama.cpp/main/main: \o/$(MODE)/llama.cpp/main/main.o \o/$(MODE)/llama.cpp/main/embedding.o \+ o/$(MODE)/llamafile/server/server.a \o/$(MODE)/llama.cpp/server/server.a \o/$(MODE)/llama.cpp/llava/llava.a \o/$(MODE)/llama.cpp/llama.cpp.a \o/$(MODE)/llamafile/highlight/highlight.a \o/$(MODE)/third_party/stb/stb.a \o/$(MODE)/llama.cpp/main/main.1.asc.zip.o \- $(LLAMA_CPP_SERVER_ASSETS:%=o/$(MODE)/%.zip.o)+ o/$(MODE)/llamafile/server/main.1.asc.zip.o \+ $(LLAMA_CPP_SERVER_ASSETS:%=o/$(MODE)/%.zip.o) \+ $(LLAMAFILE_SERVER_ASSETS:%=o/$(MODE)/%.zip.o) \$(LLAMA_CPP_MAIN_OBJS): llama.cpp/main/BUILD.mkdiff --git a/llama.cpp/main/main.cpp b/llama.cpp/main/main.cppindex cbf4eede..b6099dc1 100644--- a/llama.cpp/main/main.cpp+++ b/llama.cpp/main/main.cpp@@ -27,6 +27,7 @@#include "llama.cpp/ggml-metal.h"#include "llama.cpp/llava/llava.h"#include "llama.cpp/server/server.h"+#include "llamafile/server/prog.h"static llama_context ** g_ctx;static llama_model ** g_model;@@ -150,9 +151,11 @@ enum Program {SERVER,CHATBOT,EMBEDDING,+ LLAMAFILER,};enum Program determine_program(char *argv[]) {+ bool v2 = false;enum Program prog = UNKNOWN;for (int i = 0; argv[i]; ++i) {if (!strcmp(argv[i], "--cli")) {@@ -163,16 +166,18 @@ enum Program determine_program(char *argv[]) {prog = SERVER;} else if (!strcmp(argv[i], "--embedding")) {prog = EMBEDDING;+ } else if (!strcmp(argv[i], "--v2")) {+ v2 = true;}}+ if (prog == SERVER && v2) {+ prog = LLAMAFILER;+ }return prog;}int 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);+ llamafile_check_cpu();if (llamafile_has(argv, "--version")) {puts("llamafile v" LLAMAFILE_VERSION_STRING);@@ -182,16 +187,24 @@ int main(int argc, char ** argv) {if (llamafile_has(argv, "-h") ||llamafile_has(argv, "-help") ||llamafile_has(argv, "--help")) {- llamafile_help("/zip/llama.cpp/main/main.1.asc");+ if (llamafile_has(argv, "--v2")) {+ llamafile_help("/zip/llamafile/server/main.1.asc");+ } else {+ llamafile_help("/zip/llama.cpp/main/main.1.asc");+ }__builtin_unreachable();}- llamafile_check_cpu();+ enum Program prog = determine_program(argv);+ if (prog == LLAMAFILER)+ return lf::server::main(argc, argv);++ mallopt(M_GRANULARITY, 2 * 1024 * 1024);+ mallopt(M_MMAP_THRESHOLD, 16 * 1024 * 1024);+ mallopt(M_TRIM_THRESHOLD, 128 * 1024 * 1024);ShowCrashReports();argc = cosmo_args("/zip/.args", &argv);- enum Program prog = determine_program(argv);-if (prog == SERVER)return server_cli(argc, argv);diff --git a/llamafile/chatbot_main.cpp b/llamafile/chatbot_main.cppindex dfa31854..0ce2af41 100644--- a/llamafile/chatbot_main.cpp+++ b/llamafile/chatbot_main.cpp@@ -107,6 +107,7 @@ bool is_base_model() {}int main(int argc, char **argv) {+ signal(SIGPIPE, SIG_IGN);// print logologo(argv);@@ -147,7 +148,7 @@ int main(int argc, char **argv) {if (g_params.n_ctx < g_params.n_batch)g_params.n_batch = g_params.n_ctx;- bool want_server = !llamafile_has(argv, "--chat");+ bool want_server = !llamafile_has(argv, "--chat") && !llamafile_has(argv, "--v2");if (want_server) {print_ephemeral("launching server...");pthread_t thread;diff --git a/llamafile/flags.cpp b/llamafile/flags.cppindex 8d076263..c0e3bb3b 100644--- a/llamafile/flags.cpp+++ b/llamafile/flags.cpp@@ -52,6 +52,7 @@ bool FLAG_recompile = false;bool FLAG_tinyblas = false;bool FLAG_trace = false;bool FLAG_unsecure = false;+bool FLAG_v2 = false;const char *FLAG_chat_template = "";const char *FLAG_db = nullptr;const char *FLAG_db_startup_sql = "PRAGMA journal_mode=WAL;"@@ -160,6 +161,11 @@ void llamafile_get_flags(int argc, char **argv) {//////////////////////////////////////////////////////////////////////// chatbot flags+ if (!strcmp(flag, "--v2")) {+ FLAG_v2 = true;+ continue;+ }+if (!strcmp(flag, "--ascii")) {FLAG_ascii = true;continue;@@ -215,6 +221,9 @@ void llamafile_get_flags(int argc, char **argv) {//////////////////////////////////////////////////////////////////////// server flags+ if (!strcmp(flag, "--server"))+ continue;+if (!strcmp(flag, "-l") || !strcmp(flag, "--listen")) {if (i == argc)missing("--listen");diff --git a/llamafile/llamafile.h b/llamafile/llamafile.hindex fcc770bc..b74dda60 100644--- a/llamafile/llamafile.h+++ b/llamafile/llamafile.h@@ -23,6 +23,7 @@ extern bool FLAG_tinyblas;extern bool FLAG_trace;extern bool FLAG_trap;extern bool FLAG_unsecure;+extern bool FLAG_v2;extern const char *FLAG_chat_template;extern const char *FLAG_db;extern const char *FLAG_db_startup_sql;diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cppindex 52d576b6..2335997e 100644--- a/llamafile/server/client.cpp+++ b/llamafile/server/client.cpp@@ -704,6 +704,8 @@ Client::dispatcher()if (p1 == "flagz")return flagz();+#if 0+ // TODO: implement frontend for databaseif (p1 == "db/chats" || p1 == "db/chats/")return db_chats();if (p1.starts_with("db/chat/")) {@@ -721,6 +723,7 @@ Client::dispatcher()if (id != -1)return db_messages(id);}+#endif// serve static endpointsint infd;diff --git a/llamafile/server/listen.cpp b/llamafile/server/listen.cppindex d39d4986..0ebd2e76 100644--- a/llamafile/server/listen.cpp+++ b/llamafile/server/listen.cpp@@ -42,21 +42,21 @@ print_listening_url(unsigned ip, int port)}int-create_listening_socket(const char* hostport)+create_listening_socket(const char* hostport, unsigned* out_ip, int* out_port){// parse hostname:portchar* p;- char* host;- char* port;char addr[128];+ const char* host;+ const char* port;strlcpy(addr, hostport, sizeof(addr));if ((p = strrchr(addr, ':'))) {*p = '\0';host = addr;port = p + 1;} else {- host = NULL;- port = addr;+ host = addr;+ port = "8080";}// turn listen address names into numbers@@ -103,14 +103,21 @@ create_listening_socket(const char* hostport)exit(1);}struct sockaddr_in* in = (struct sockaddr_in*)ai->ai_addr;+ if (out_port)+ *out_port = ntohs(in->sin_port);if (ntohl(in->sin_addr.s_addr) == INADDR_ANY) {int i;uint32_t* hostips;- for (hostips = GetHostIps(), i = 0; hostips[i]; ++i)+ for (hostips = GetHostIps(), i = 0; hostips[i]; ++i) {print_listening_url(hostips[i], ntohs(in->sin_port));+ if (out_ip)+ *out_ip = hostips[i];+ }free(hostips);} else {print_listening_url(ntohl(in->sin_addr.s_addr), ntohs(in->sin_port));+ if (out_ip)+ *out_ip = ntohl(in->sin_addr.s_addr);}freeaddrinfo(ai);diff --git a/llamafile/server/log.cpp b/llamafile/server/log.cppindex f39ff3d6..04c36758 100644--- a/llamafile/server/log.cpp+++ b/llamafile/server/log.cpp@@ -23,6 +23,8 @@namespace lf {namespace server {+bool g_log_disable;+static thread_local char g_thread_name[128];const char*diff --git a/llamafile/server/log.h b/llamafile/server/log.hindex 775c334c..e91b7078 100644--- a/llamafile/server/log.h+++ b/llamafile/server/log.h@@ -19,16 +19,19 @@#include <libc/intrin/kprintf.h>#define SLOG(FMT, ...) \- kprintf("%s %s:%d %s " FMT "\n", \- get_log_timestamp(), \- __FILE__, \- __LINE__, \- get_thread_name(), \- ##__VA_ARGS__)+ (!lf::server::g_log_disable && (kprintf("%s %s:%d %s " FMT "\n", \+ get_log_timestamp(), \+ __FILE__, \+ __LINE__, \+ get_thread_name(), \+ ##__VA_ARGS__), \+ 0))namespace lf {namespace server {+extern bool g_log_disable;+const char*get_thread_name(void);diff --git a/llamafile/server/main.1 b/llamafile/server/main.1index 4dcd8d89..e5d01adc 100644--- a/llamafile/server/main.1+++ b/llamafile/server/main.1@@ -3,19 +3,18 @@.Os Mozilla Ocho.Sh NAME.Nm llamafiler-.Nd fast reliable embedding server+.Nd fast reliable large language model server.Sh SYNOPSIS.Nm.Fl m Ar model.gguf.Op flags....Sh DESCRIPTION.Nm-is a brand new HTTP server for Large Language Models (LLMs). To date,-its development has been focused on doing fewer things really well, and-right now that's serving embeddings. It offers you 3.4x the performance,-stronger security, client request prioritization, request preemption, as-well as request isolation that helps ensure software bugs won't cause-the whole server to crash.+llamafiler is an HTTP server for Large Language Models (LLMs). It+includes a web GUI for both chatbot and text completion. It can be your+OpenAI API compatible embeddings / completions / chat completions+server. It's able to more intelligently recycle context windows across+multiple slots serving multiple clients..Sh OPTIONSThe following options are available:.Bl -tag -width indentdiff --git a/llamafile/server/main.1.asc b/llamafile/server/main.1.ascindex ae91c8bb..ab99e219 100644--- a/llamafile/server/main.1.asc+++ b/llamafile/server/main.1.asc@@ -1,265 +1,269 @@-LLAMAFILER(1) General Commands Manual LLAMAFILER(1)--NNAAMMEE- llllaammaaffiilleerr - fast reliable embedding server--SSYYNNOOPPSSIISS- llllaammaaffiilleerr --mm _m_o_d_e_l_._g_g_u_f [flags...]--DDEESSCCRRIIPPTTIIOONN- llllaammaaffiilleerr is a brand new HTTP server for Large Language Models (LLMs). To- date, its development has been focused on doing fewer things really well,- and right now that's serving embeddings. It offers you 3.4x the- performance, stronger security, client request prioritization, request- preemption, as well as request isolation that helps ensure software bugs- won't cause the whole server to crash.--OOPPTTIIOONNSS- The following options are available:-- ----vveerrssiioonn- Print version and exit.-- --hh, ----hheellpp- Show help message and exit.-- --mm _F_N_A_M_E, ----mmooddeell _F_N_A_M_E- Path of GGUF model weights. Each server process is currently- limited to serving only one model. If you need to host multiple- models, then it's recommended that you run multiple instances of- llamafiler behind a reverse proxy such as NGINX or Redbean.-- --mmmm _F_N_A_M_E, ----mmmmpprroojj _F_N_A_M_E- Path of vision model weights.-- ----ddbb _F_I_L_E- Specifies path of sqlite3 database.-- The default is _~_/_._l_l_a_m_a_f_i_l_e_/_l_l_a_m_a_f_i_l_e_._s_q_l_i_t_e_3-- --nnggll _N, ----ggppuu--llaayyeerrss _N, ----nn--ggppuu--llaayyeerrss _N- Specifies number of layers to offload to GPU.-- This flag must be passed in order to use GPU on systems with NVIDIA- or AMD GPUs. If you're confident that you have enough VRAM, then- you can pass --nnggll _9_9_9 to enable full offloading, since this number- is automatically downtuned to however many number of layers the- model has. If VRAM is limited, then the ----vveerrbboossee flag may be- passed to learn how many layers the model has, e.g. 35, which can- then be down-tuned until the out of memory error goes away.-- On Apple Silicon systems with Metal, GPU offloading is enabled by- default. Since these GPUs use unified memory, they're treated as- having a single layer; therefore, using values higher than 1 will- be treated as 1. You can pass --nnggll _0 to disable GPU offloading and- run in CPU mode on Apple Metal systems.-- --ll _H_O_S_T_P_O_R_T, ----lliisstteenn _H_O_S_T_P_O_R_T- 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 port 8080 on every locally available IPv4 network- interface. This option may currently only be specified once.-- --cc _T_O_K_E_N_S, ----ccttxx--ssiizzee _T_O_K_E_N_S- 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.-- --ss _C_O_U_N_T, ----sslloottss _C_O_U_N_T- 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 ----ccttxx--ssiizzee has a strong- influence on how many slots can be created.-- ----ddeeccaayy--ddeellaayy _I_N_T- Number of seconds a context window slot needs to be inactive before- the system starts to strongly consider giving it to other clients.- The default is 300 which is five minutes.-- ----ddeeccaayy--ggrroowwtthh _F_L_O_A_T- Sets slot decay growth factor. Context window slots are assigned in- a least recently used fashion, based on the formula _a_g_e + _e^(_g_r_o_w_t_h- * (_a_g_e - _d_e_l_a_y))-- --pp _T_E_X_T, ----pprroommpptt _T_E_X_T, ----ssyysstteemm--pprroommpptt _T_E_X_T- Specifies system prompt. This value is passed along to the web- frontend.-- ----nnoo--ddiissppllaayy--pprroommpptt- Hide system prompt from web user interface.-- ----nnoollooggoo- Hide llamafile logo icon from web ui.-- ----uurrll--pprreeffiixx _U_R_L_P_R_E_F_I_X- Specifies a URL prefix (subdirectory) under which the HTTP server- will make the API accessible, e.g. /lamafiler. Useful when running- llamafiler behind a reverse proxy such as NGINX or Redbean. By- default, this is set to / (root).-- ----vveerrbboossee- Enable logging of diagnostic information. This flag is useful for- learning more about the model and hardware. It can also be helpful- for troubleshooting errors. We currently recommend that this flag- be avoided in production since the llama.cpp logger may disrupt- thread cancelation.-- --ww _N, ----wwoorrkkeerrss _N- Number of HTTP client handling threads.-- ----ttrruusstt _C_I_D_R- Adds a network to the trusted network list. This argument is- specified in the form IPV4/MASKBITS, e.g. 192.168.0.0/24. By- default, all clients are untrusted, which means they're subject to- token bucket throttling, and additional security precautions that- may cause request handling to go slightly slower. Therefore this- flag is important to use if you want to accurately benchmark- llamafiler, since the server will otherwise see the benchmark as a- DDOS and deprioritize its traffic accordingly.-- ----iipp--hheeaaddeerr _S_T_R- If this flag is passed a value, e.g. X-Forwarded-For, then any- trusted may send this header to your llamafile server to let it- know what the true effective client IPv4 address actually is. After- this happens the default security restrictions, e.g. token bucket,- will be measured and applied against that IPv4 address and its- adjacent networks.-- ----ttookkeenn--rraattee _N- Specifies how many times per second a token is dropped in each- bucket. This setting is used to define a limitation on how many- TCP connects and HTTP messages each chunk of the IPv4 address space- is permitted to send to llamafiler over a sustained period of time.- The default token rate is 1, which means that, on a long enough- timeline, a class-C network will be deprioritized if it sends more- than one request per second. No real penalty actually applies- though until the server runs out of resources, e.g. HTTP request- workers.-- ----ttookkeenn--bbuurrsstt _N- Specifies how many HTTP requests and TCP connects a given slice of- the IPv4 address space is permitted to send within a short period- of time, before token bucket restrictions kick in, and cause the- client to be deprioritized. By default, this value is set to 100.- It may be tuned to any value between 1 and 127 inclusive.-- ----ttookkeenn--cciiddrr _N- Specifies IPv4 address space granularity of token bucket algorithm,- in network bits. By default, this value is set to 24 which means- individual IPv4 addresses are viewed as being representative- members of a class-C network, or in other words, each group of 256- IPv4 addresses is lumped together. If one IP in the group does- something bad, then bad things happen to all the other IPv4- addresses in that granule. This number may be set to any integer- between 3 and 32 inclusive. Specifying a higher number will trade- away system memory to increase network specificity. For example,- using 32 means that 4 billion individual token buckets will be- created. By default, a background thread drops one token in each- bucket every second, so that could potentially be a lot of busy- work. A value of three means that everyone on the Internet who- talks to your server will have to fight over only eight token- buckets in total.-- ----uunnsseeccuurree- Disables sandboxing. By default, llamafiler puts itself in a- SECCOMP BPF sandbox, so that even if your server gets hacked in the- worst possible way (some kind of C++ memory bug) then there's very- little damage an attacker will be able to do. This works by- restricting system calls using Cosmopolitan Libc's implementation- of pledge() which is currently only supported on Linux (other OSes- will simply be unsecured by default). The pledge security policy- that's used by default is "stdio anet" which means that only- relatively harmless system calls like read(), write(), and accept()- are allowed once the server has finished initializing. It's not- possible for remotely executed code to do things like launch- subprocesses, read or write to the filesystem, or initiate a new- connection to a server.-- --kk _N, ----kkeeeeppaalliivvee _N- Specifies the TCP keepalive interval in seconds. This value is- passed along to both TCP_KEEPIDLE and TCP_KEEPINTVL if they're- supported by the host operating system. If this value is greater- than 0, then the the SO_KEEPALIVE and TCP_NODELAY options are- enabled on network sockets, if supported by the host operating- system. The default keepalive is 5.-- ----hhttttpp--oobbuuff--ssiizzee _N- Size of HTTP output buffer size, in bytes. Default is 1048576.-- ----hhttttpp--iibbuuff--ssiizzee _N- Size of HTTP input buffer size, in bytes. Default is 1048576.-- ----cchhaatt--tteemmppllaattee _N_A_M_E- Specifies or overrides chat template for model.-- Normally the GGUF metadata tokenizer.chat_template will specify- this value for instruct models. This flag may be used to either- override the chat template, or specify one when the GGUF metadata- field is absent, which effectively forces the web ui to enable- chatbot mode.-- Supported chat template names are: chatml, llama2, llama3, mistral- (alias for llama2), phi3, zephyr, monarch, gemma, gemma2 (alias for- gemma), orion, openchat, vicuna, vicuna-orca, deepseek, command-r,- chatglm3, chatglm4, minicpm, deepseek2, or exaone3.-- It is also possible to pass the jinja2 template itself to this- argument. Since llamafiler doesn't currently support jinja2, a- heuristic will be used to guess which of the above templates the- template represents.-- ----ccoommpplleettiioonn--mmooddee- Forces web ui to operate in completion mode, rather than chat mode.- Normally the web ui chooses its mode based on the GGUF metadata.- Base models normally don't define tokenizer.chat_template whereas- instruct models do. If it's a base model, then the web ui will- automatically use completion mode only, without needing to specify- this flag. This flag is useful in cases where a prompt template is- defined by the gguf, but it is desirable for the chat interface to- be disabled.-- ----ddbb--ssttaarrttuupp--ssqqll _C_O_D_E- Specifies SQL code that should be executed whenever connecting to- the SQLite database. The default is the following code, which- enables the write-ahead log.-- PRAGMA journal_mode=WAL;- PRAGMA synchronous=NORMAL;-- ----rreesseerrvvee--ttookkeennss _N- Percent of context window to reserve for predicted tokens. When the- server runs out of context window, old chat messages will be- forgotten until this percent of the context is empty. The default- is 15%. If this is specified as a floating point number, e.g. 0.15,- then it'll be multiplied by 100 to get the percent.--EEXXAAMMPPLLEESS- Here's an example of how you might start this server:-- llamafiler -m all-MiniLM-L6-v2.F32.gguf-- Here's how to send a tokenization request:-- curl -v http://127.0.0.1:8080/tokenize?prompt=hello+world-- Here's how to send a embedding request:-- curl -v http://127.0.0.1:8080/embedding?content=hello+world--DDOOCCUUMMEENNTTAATTIIOONN- Read our Markdown documentation for additional help and tutorials. See- llamafile/server/doc/index.md in the source repository on GitHub.--SSEEEE AALLSSOO- llamafile(1), whisperfile(1)--Mozilla Ocho November 30, 2024 Mozilla Ocho+[4mLLAMAFILER[24m(1) General Commands Manual [4mLLAMAFILER[24m(1)++[1mNAME[0m+ llamafiler — fast reliable large language model server++[1mSYNOPSIS[0m+ [1mllamafiler -m [4m[22mmodel.gguf[24m [flags...]++[1mDESCRIPTION[0m+ [1mllamafiler [22mllamafiler is an HTTP server for Large Language Models+ (LLMs). It includes a web GUI for both chatbot and text completion. It+ can be your OpenAI API compatible embeddings / completions / chat com‐+ pletions server. It's able to more intelligently recycle context win‐+ dows across multiple slots serving multiple clients.++[1mOPTIONS[0m+ The following options are available:++ [1m--version[0m+ Print version and exit.++ [1m-h[22m, [1m--help[0m+ Show help message and exit.++ [1m-m [4m[22mFNAME[24m, [1m--model [4m[22mFNAME[0m+ Path of GGUF model weights. Each server process is currently+ limited to serving only one model. If you need to host multiple+ models, then it's recommended that you run multiple instances+ of llamafiler behind a reverse proxy such as NGINX or Redbean.++ [1m-mm [4m[22mFNAME[24m, [1m--mmproj [4m[22mFNAME[0m+ Path of vision model weights.++ [1m--db [4m[22mFILE[0m+ Specifies path of sqlite3 database.++ The default is [4m~/.llamafile/llamafile.sqlite3[0m++ [1m-ngl [4m[22mN[24m, [1m--gpu-layers [4m[22mN[24m, [1m--n-gpu-layers [4m[22mN[0m+ Specifies number of layers to offload to GPU.++ This flag must be passed in order to use GPU on systems with+ NVIDIA or AMD GPUs. If you're confident that you have enough+ VRAM, then you can pass [1m-ngl [4m[22m999[24m to enable full offloading,+ since this number is automatically downtuned to however many+ number of layers the model has. If VRAM is limited, then the+ [1m--verbose [22mflag may be passed to learn how many layers the model+ has, e.g. 35, which can then be down-tuned until the out of+ memory error goes away.++ On Apple Silicon systems with Metal, GPU offloading is enabled+ by default. Since these GPUs use unified memory, they're+ treated as having a single layer; therefore, using values+ higher than 1 will be treated as 1. You can pass [1m-ngl [4m[22m0[24m to dis‐+ able GPU offloading and run in CPU mode on Apple Metal systems.++ [1m-l [4m[22mHOSTPORT[24m, [1m--listen [4m[22mHOSTPORT[0m+ 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 port 8080 on every locally available IPv4 network+ interface. 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--decay-delay [4m[22mINT[0m+ Number of seconds a context window slot needs to be inactive+ before the system starts to strongly consider giving it to+ other clients. The default is 300 which is five minutes.++ [1m--decay-growth [4m[22mFLOAT[0m+ Sets slot decay growth factor. Context window slots are as‐+ signed in a least recently used fashion, based on the formula+ age + e sup {growth * (age - delay)}++ [1m-p [4m[22mTEXT[24m, [1m--prompt [4m[22mTEXT[24m, [1m--system-prompt [4m[22mTEXT[0m+ Specifies system prompt. This value is passed along to the web+ frontend.++ [1m--no-display-prompt[0m+ Hide system prompt from web user interface.++ [1m--nologo[0m+ Hide llamafile logo icon from web ui.++ [1m--url-prefix [4m[22mURLPREFIX[0m+ Specifies a URL prefix (subdirectory) under which the HTTP+ server will make the API accessible, e.g. /lamafiler. Useful+ when running llamafiler behind a reverse proxy such as NGINX or+ Redbean. By default, this is set to / (root).++ [1m--verbose[0m+ Enable logging of diagnostic information. This flag is useful+ for learning more about the model and hardware. It can also be+ helpful for troubleshooting errors. We currently recommend that+ this flag be avoided in production since the llama.cpp logger+ may disrupt thread cancelation.++ [1m-w [4m[22mN[24m, [1m--workers [4m[22mN[0m+ Number of HTTP client handling threads.++ [1m--trust [4m[22mCIDR[0m+ Adds a network to the trusted network list. This argument is+ specified in the form IPV4/MASKBITS, e.g. 192.168.0.0/24. By+ default, all clients are untrusted, which means they're subject+ to token bucket throttling, and additional security precautions+ that may cause request handling to go slightly slower. There‐+ fore this flag is important to use if you want to accurately+ benchmark llamafiler, since the server will otherwise see the+ benchmark as a DDOS and deprioritize its traffic accordingly.++ [1m--ip-header [4m[22mSTR[0m+ If this flag is passed a value, e.g. X-Forwarded-For, then any+ trusted may send this header to your llamafile server to let it+ know what the true effective client IPv4 address actually is.+ After this happens the default security restrictions, e.g. to‐+ ken bucket, will be measured and applied against that IPv4 ad‐+ dress and its adjacent networks.++ [1m--token-rate [4m[22mN[0m+ Specifies how many times per second a token is dropped in each+ bucket. This setting is used to define a limitation on how+ many TCP connects and HTTP messages each chunk of the IPv4 ad‐+ dress space is permitted to send to llamafiler over a sustained+ period of time. The default token rate is 1, which means that,+ on a long enough timeline, a class-C network will be depriori‐+ tized if it sends more than one request per second. No real+ penalty actually applies though until the server runs out of+ resources, e.g. HTTP request workers.++ [1m--token-burst [4m[22mN[0m+ Specifies how many HTTP requests and TCP connects a given slice+ of the IPv4 address space is permitted to send within a short+ period of time, before token bucket restrictions kick in, and+ cause the client to be deprioritized. By default, this value is+ set to 100. It may be tuned to any value between 1 and 127 in‐+ clusive.++ [1m--token-cidr [4m[22mN[0m+ Specifies IPv4 address space granularity of token bucket algo‐+ rithm, in network bits. By default, this value is set to 24+ which means individual IPv4 addresses are viewed as being rep‐+ resentative members of a class-C network, or in other words,+ each group of 256 IPv4 addresses is lumped together. If one IP+ in the group does something bad, then bad things happen to all+ the other IPv4 addresses in that granule. This number may be+ set to any integer between 3 and 32 inclusive. Specifying a+ higher number will trade away system memory to increase network+ specificity. For example, using 32 means that 4 billion indi‐+ vidual token buckets will be created. By default, a background+ thread drops one token in each bucket every second, so that+ could potentially be a lot of busy work. A value of three means+ that everyone on the Internet who talks to your server will+ have to fight over only eight token buckets in total.++ [1m--unsecure[0m+ Disables sandboxing. By default, llamafiler puts itself in a+ SECCOMP BPF sandbox, so that even if your server gets hacked in+ the worst possible way (some kind of C++ memory bug) then+ there's very little damage an attacker will be able to do. This+ works by restricting system calls using Cosmopolitan Libc's im‐+ plementation of pledge() which is currently only supported on+ Linux (other OSes will simply be unsecured by default). The+ pledge security policy that's used by default is "stdio anet"+ which means that only relatively harmless system calls like+ read(), write(), and accept() are allowed once the server has+ finished initializing. It's not possible for remotely executed+ code to do things like launch subprocesses, read or write to+ the filesystem, or initiate a new connection to a server.++ [1m-k [4m[22mN[24m, [1m--keepalive [4m[22mN[0m+ Specifies the TCP keepalive interval in seconds. This value is+ passed along to both TCP_KEEPIDLE and TCP_KEEPINTVL if they're+ supported by the host operating system. If this value is+ greater than 0, then the the SO_KEEPALIVE and TCP_NODELAY op‐+ tions are enabled on network sockets, if supported by the host+ operating system. The default keepalive is 5.++ [1m--http-obuf-size [4m[22mN[0m+ Size of HTTP output buffer size, in bytes. Default is 1048576.++ [1m--http-ibuf-size [4m[22mN[0m+ Size of HTTP input buffer size, in bytes. Default is 1048576.++ [1m--chat-template [4m[22mNAME[0m+ Specifies or overrides chat template for model.++ Normally the GGUF metadata tokenizer.chat_template will specify+ this value for instruct models. This flag may be used to either+ override the chat template, or specify one when the GGUF meta‐+ data field is absent, which effectively forces the web ui to+ enable chatbot mode.++ Supported chat template names are: chatml, llama2, llama3, mis‐+ tral (alias for llama2), phi3, zephyr, monarch, gemma, gemma2+ (alias for gemma), orion, openchat, vicuna, vicuna-orca,+ deepseek, command-r, chatglm3, chatglm4, minicpm, deepseek2, or+ exaone3.++ It is also possible to pass the jinja2 template itself to this+ argument. Since llamafiler doesn't currently support jinja2, a+ heuristic will be used to guess which of the above templates+ the template represents.++ [1m--completion-mode[0m+ Forces web ui to operate in completion mode, rather than chat+ mode. Normally the web ui chooses its mode based on the GGUF+ metadata. Base models normally don't define tokenizer.chat_tem‐+ plate whereas instruct models do. If it's a base model, then+ the web ui will automatically use completion mode only, without+ needing to specify this flag. This flag is useful in cases+ where a prompt template is defined by the gguf, but it is de‐+ sirable for the chat interface to be disabled.++ [1m--db-startup-sql [4m[22mCODE[0m+ Specifies SQL code that should be executed whenever connecting+ to the SQLite database. The default is the following code,+ which enables the write-ahead log.++ PRAGMA journal_mode=WAL;+ PRAGMA synchronous=NORMAL;++ [1m--reserve-tokens [4m[22mN[0m+ Percent of context window to reserve for predicted tokens. When+ the server runs out of context window, old chat messages will+ be forgotten until this percent of the context is empty. The+ default is 15%. If this is specified as a floating point num‐+ ber, e.g. 0.15, then it'll be multiplied by 100 to get the per‐+ cent.++[1mEXAMPLES[0m+ Here's an example of how you might start this server:++ [1mllamafiler -m all-MiniLM-L6-v2.F32.gguf[0m++ Here's how to send a tokenization request:++ [1mcurl -v http://127.0.0.1:8080/tokenize?prompt=hello+world[0m++ Here's how to send a embedding request:++ [1mcurl -v http://127.0.0.1:8080/embedding?content=hello+world[0m++[1mDOCUMENTATION[0m+ Read our Markdown documentation for additional help and tutorials. See+ llamafile/server/doc/index.md in the source repository on GitHub.++[1mSEE ALSO[0m+ [4mllamafile[24m(1), [4mwhisperfile[24m(1)++Mozilla Ocho November 30, 2024 [4mLLAMAFILER[24m(1)diff --git a/llamafile/server/main.cpp b/llamafile/server/main.cppindex 5b0a5b40..312b7fcb 100644--- a/llamafile/server/main.cpp+++ b/llamafile/server/main.cpp@@ -15,125 +15,7 @@// See the License for the specific language governing permissions and// limitations under the License.-#include "llama.cpp/llama.h"-#include "llamafile/llamafile.h"-#include "llamafile/pool.h"-#include "llamafile/server/log.h"-#include "llamafile/server/server.h"-#include "llamafile/server/signals.h"-#include "llamafile/server/slots.h"-#include "llamafile/server/time.h"-#include "llamafile/server/tokenbucket.h"-#include "llamafile/server/utils.h"-#include "llamafile/version.h"-#include <cassert>-#include <cosmo.h>--namespace lf {-namespace server {--Server* g_server;--int-main(int argc, char* argv[])-{- signal(SIGPIPE, SIG_IGN);- mallopt(M_GRANULARITY, 2 * 1024 * 1024);- mallopt(M_MMAP_THRESHOLD, 16 * 1024 * 1024);- mallopt(M_TRIM_THRESHOLD, 128 * 1024 * 1024);- llamafile_check_cpu();- ShowCrashReports();-- if (llamafile_has(argv, "--version")) {- puts("llamafiler v" LLAMAFILE_VERSION_STRING);- exit(0);- }-- if (llamafile_has(argv, "-h") || llamafile_has(argv, "-help") ||- llamafile_has(argv, "--help")) {- llamafile_help("/zip/llamafile/server/main.1.asc");- __builtin_unreachable();- }-- // get config- argc = cosmo_args("/zip/.args", &argv);- llamafile_get_flags(argc, argv);-- // initialize subsystems- time_init();- tokenbucket_init();-- // we must disable the llama.cpp logger- // otherwise pthread_cancel() will cause deadlocks- if (!llamafile_has(argv, "--verbose"))- FLAG_log_disable = true;-- // load model- llama_model_params mparams = {- .n_gpu_layers = FLAG_n_gpu_layers,- .split_mode = (enum llama_split_mode)FLAG_split_mode,- .main_gpu = FLAG_main_gpu,- .tensor_split = nullptr,- .rpc_servers = nullptr,- .progress_callback = nullptr,- .progress_callback_user_data = nullptr,- .kv_overrides = nullptr,- .vocab_only = false,- .use_mmap = true,- .use_mlock = false,- .check_tensors = false,- };- 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 server- if (FLAG_workers <= 0)- FLAG_workers = __get_cpu_count() + 4;- if (FLAG_workers <= 0)- FLAG_workers = 16;- set_thread_name("server");- g_server = new Server(create_listening_socket(FLAG_listen), slots, model);- for (int i = 0; i < FLAG_workers; ++i)- npassert(!g_server->spawn());-- // run server- signals_init();- llama_backend_init();- g_server->run();- llama_backend_free();- signals_destroy();-- // shutdown server- SLOG("shutdown");- g_server->shutdown();- g_server->close();- delete g_server;- delete slots;- llama_free_model(model);- tokenbucket_destroy();- time_destroy();- SLOG("exit");-- // quality assurance- llamafile_task_shutdown();- while (!pthread_orphan_np())- pthread_decimate_np();- CheckForMemoryLeaks();- return 0;-}--} // namespace server-} // namespace lf+#include "llamafile/server/prog.h"intmain(int argc, char* argv[])diff --git a/llamafile/server/prog.cpp b/llamafile/server/prog.cppnew file mode 100644index 00000000..bd6e6b6a--- /dev/null+++ b/llamafile/server/prog.cpp@@ -0,0 +1,137 @@+// -*- 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 "llama.cpp/llama.h"+#include "llamafile/llamafile.h"+#include "llamafile/pool.h"+#include "llamafile/server/log.h"+#include "llamafile/server/server.h"+#include "llamafile/server/signals.h"+#include "llamafile/server/slots.h"+#include "llamafile/server/time.h"+#include "llamafile/server/tokenbucket.h"+#include "llamafile/server/utils.h"+#include "llamafile/version.h"+#include <cassert>+#include <cosmo.h>++namespace lf {+namespace server {++Server* g_server;++int+main(int argc, char* argv[])+{+ llamafile_check_cpu();+ signal(SIGPIPE, SIG_IGN);+ mallopt(M_GRANULARITY, 2 * 1024 * 1024);+ mallopt(M_MMAP_THRESHOLD, 16 * 1024 * 1024);+ mallopt(M_TRIM_THRESHOLD, 128 * 1024 * 1024);+ ShowCrashReports();++ if (llamafile_has(argv, "--version")) {+ puts("llamafiler v" LLAMAFILE_VERSION_STRING);+ exit(0);+ }++ if (llamafile_has(argv, "-h") || llamafile_has(argv, "-help") ||+ llamafile_has(argv, "--help")) {+ llamafile_help("/zip/llamafile/server/main.1.asc");+ __builtin_unreachable();+ }++ // get config+ argc = cosmo_args("/zip/.args", &argv);+ llamafile_get_flags(argc, argv);++ // initialize subsystems+ time_init();+ tokenbucket_init();++ // we must disable the llama.cpp logger+ // otherwise pthread_cancel() will cause deadlocks+ if (!llamafile_has(argv, "--verbose"))+ FLAG_log_disable = true;++ // load model+ llama_model_params mparams = {+ .n_gpu_layers = FLAG_n_gpu_layers,+ .split_mode = (enum llama_split_mode)FLAG_split_mode,+ .main_gpu = FLAG_main_gpu,+ .tensor_split = nullptr,+ .rpc_servers = nullptr,+ .progress_callback = nullptr,+ .progress_callback_user_data = nullptr,+ .kv_overrides = nullptr,+ .vocab_only = false,+ .use_mmap = true,+ .use_mlock = false,+ .check_tensors = false,+ };+ 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 server+ if (FLAG_workers <= 0)+ FLAG_workers = __get_cpu_count() + 4;+ if (FLAG_workers <= 0)+ FLAG_workers = 16;+ set_thread_name("server");+ g_server =+ new Server(create_listening_socket(FLAG_listen, 0, 0), slots, model);+ for (int i = 0; i < FLAG_workers; ++i)+ npassert(!g_server->spawn());++ // run server+ signals_init();+ llama_backend_init();+ g_server->run();+ llama_backend_free();+ signals_destroy();++ // shutdown server+ SLOG("shutdown");+ g_server->shutdown();+ g_server->close();+ delete g_server;+ delete slots;+ llama_free_model(model);+ tokenbucket_destroy();+ time_destroy();+ SLOG("exit");++ // quality assurance+ llamafile_task_shutdown();+ while (!pthread_orphan_np())+ pthread_decimate_np();+ CheckForMemoryLeaks();+ return 0;+}++} // namespace server+} // namespace lfdiff --git a/llamafile/server/prog.h b/llamafile/server/prog.hnew file mode 100644index 00000000..af6c5557--- /dev/null+++ b/llamafile/server/prog.h@@ -0,0 +1,10 @@+#pragma once++namespace lf {+namespace server {++int+main(int, char**);++} // namespace server+} // namespace lfdiff --git a/llamafile/server/server.h b/llamafile/server/server.hindex 05a515c5..de7e222e 100644--- a/llamafile/server/server.h+++ b/llamafile/server/server.h@@ -57,7 +57,7 @@ struct Serverextern Server* g_server;int-create_listening_socket(const char*);+create_listening_socket(const char*, unsigned*, int*);} // namespace server} // namespace lf