Skip to content

Distribute and run LLMs with a single file.

Add barebones /completion endpoint to new server

Justine Tunneyfb3421c776d2
diff --git a/llama.cpp/sampling.cpp b/llama.cpp/sampling.cpp
index 080ad591..99b8d42a 100644
--- a/llama.cpp/sampling.cpp
+++ b/llama.cpp/sampling.cpp
@@ -4,6 +4,8 @@
#define LLAMA_API_INTERNAL
#include "sampling.h"
#include <random>
+#include <cosmo.h>
+#include "common.h"
struct llama_sampling_context * llama_sampling_init(const struct llama_sampling_params & params) {
struct llama_sampling_context * result = new llama_sampling_context();
@@ -17,14 +19,14 @@ struct llama_sampling_context * llama_sampling_init(const struct llama_sampling_
// will be empty (default) if there are parse errors
if (result->parsed_grammar.rules.empty()) {
- fprintf(stderr, "%s: failed to parse grammar\n", __func__);
+ kprintf("%s: failed to parse grammar\n", __func__);
delete result;
return nullptr;
}
// Ensure that there is a "root" node.
if (result->parsed_grammar.symbol_ids.find("root") == result->parsed_grammar.symbol_ids.end()) {
- fprintf(stderr, "%s: grammar does not contain a 'root' symbol\n", __func__);
+ kprintf("%s: grammar does not contain a 'root' symbol\n", __func__);
delete result;
return nullptr;
}
diff --git a/llama.cpp/sampling.h b/llama.cpp/sampling.h
index 655732ad..0e5bf427 100644
--- a/llama.cpp/sampling.h
+++ b/llama.cpp/sampling.h
@@ -86,8 +86,6 @@ struct llama_sampling_context {
std::mt19937 rng;
};
-#include "common.h"
-
// Create a new sampling context instance.
struct llama_sampling_context * llama_sampling_init(const struct llama_sampling_params & params);
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 13145f8e..895d774f 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -20,7 +20,6 @@ LLAMAFILE_OBJS := \
# this executable defines its own malloc(), free(), etc.
# therefore we want to avoid it going inside the .a file
LLAMAFILE_OBJS := $(filter-out o/$(MODE)/llamafile/zipalign.o,$(LLAMAFILE_OBJS))
-LLAMAFILE_OBJS := $(filter-out o/$(MODE)/llamafile/thread_test.o,$(LLAMAFILE_OBJS))
include llamafile/server/BUILD.mk
@@ -51,7 +50,6 @@ o/$(MODE)/llamafile: \
o/$(MODE)/llamafile/zipcheck \
o/$(MODE)/llamafile/tokenize \
o/$(MODE)/llamafile/addnl \
- o/$(MODE)/llamafile/thread_test.runs \
################################################################################
# microarchitectures
diff --git a/llamafile/server/cleanup.cpp b/llamafile/server/cleanup.cpp
new file mode 100644
index 00000000..a318aed6
--- /dev/null
+++ b/llamafile/server/cleanup.cpp
@@ -0,0 +1,48 @@
+// -*- 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 "cleanup.h"
+
+#include <ctl/vector.h>
+
+#include "llama.cpp/llama.h"
+
+void
+cleanup_float_vector(void* arg)
+{
+ delete (ctl::vector<float>*)arg;
+}
+
+void
+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;
+}
+
+void
+cleanup_llama_context(void* arg)
+{
+ llama_free((llama_context*)arg);
+}
diff --git a/llamafile/server/cleanup.h b/llamafile/server/cleanup.h
new file mode 100644
index 00000000..7f9ecb7e
--- /dev/null
+++ b/llamafile/server/cleanup.h
@@ -0,0 +1,30 @@
+// -*- 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
+
+void
+cleanup_float_vector(void*);
+
+void
+cleanup_token_vector(void*);
+
+void
+cleanup_llama_batch(void*);
+
+void
+cleanup_llama_context(void*);
diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cpp
index 70ff4bdb..5b50936a 100644
--- a/llamafile/server/client.cpp
+++ b/llamafile/server/client.cpp
@@ -54,7 +54,7 @@ Client::close()
DestroyHttpMessage(&msg);
if (fd != -1) {
if (FLAG_verbose >= 2)
- LOG("close");
+ SLOG("close");
rc = ::close(fd);
fd = -1;
}
@@ -141,17 +141,17 @@ Client::read_request()
return true;
}
if (inmsglen == -1) {
- LOG("bad message %m");
+ SLOG("bad message %m");
return false;
}
if (ibuf.n)
- LOG("fragmented message with %zu bytes", ibuf.n);
+ SLOG("fragmented message with %zu bytes", ibuf.n);
ssize_t got;
got = read(fd, ibuf.p + ibuf.n, ibuf.c - ibuf.n);
if (!got && ibuf.n)
- LOG("unexpected eof after %zu bytes", ibuf.n);
+ SLOG("unexpected eof after %zu bytes", ibuf.n);
if (got == -1 && (ibuf.n || (errno != EAGAIN && errno != ECONNRESET)))
- LOG("read failed %m");
+ SLOG("read failed %m");
if (got <= 0)
return false;
ibuf.n += got;
@@ -201,7 +201,7 @@ Client::transport()
}
if (FLAG_verbose >= 1)
- LOG("get %#.*s", msg.uri.b - msg.uri.a, ibuf.p + msg.uri.a);
+ SLOG("get %#.*s", msg.uri.b - msg.uri.a, ibuf.p + msg.uri.a);
if (msg.version >= 11)
if (HeaderEqualCase(kHttpExpect, "100-continue"))
@@ -230,7 +230,7 @@ Client::send_error(int code, const char* reason)
begin_response();
if (!reason)
reason = GetHttpReason(code);
- LOG("error %d %s", code, reason);
+ SLOG("error %d %s", code, reason);
char* p = start_response(obuf.p, code, reason);
return send_response(obuf.p, p, string(reason) + "\r\n");
}
@@ -300,7 +300,7 @@ Client::send(const string_view s)
ssize_t sent;
if ((sent = write(fd, s.data(), s.size())) != s.size()) {
if (sent == -1 && errno != EAGAIN && errno != ECONNRESET)
- LOG("write failed %m");
+ SLOG("write failed %m");
return false;
}
return true;
@@ -317,7 +317,7 @@ Client::send2(const string_view s1, const string_view s2)
iov[1].iov_len = s2.size();
if ((sent = writev(fd, iov, 2)) != s1.size() + s2.size()) {
if (sent == -1 && errno != EAGAIN && errno != ECONNRESET)
- LOG("writev failed %m");
+ SLOG("writev failed %m");
return false;
}
return true;
@@ -349,9 +349,9 @@ Client::read_payload()
ssize_t got;
if ((got = read(fd, ibuf.p + ibuf.n, ibuf.c - ibuf.n)) <= 0) {
if (!got)
- LOG("unexpected eof");
+ SLOG("unexpected eof");
if (got == -1)
- LOG("read failed %m");
+ SLOG("read failed %m");
return false;
}
ibuf.n += got;
@@ -399,6 +399,8 @@ Client::dispatcher()
return tokenize();
if (path() == "/embedding")
return embedding();
+ if (path() == "/completion")
+ return completion();
return send_error(404);
}
diff --git a/llamafile/server/client.h b/llamafile/server/client.h
index add65d4b..3b8bc0a2 100644
--- a/llamafile/server/client.h
+++ b/llamafile/server/client.h
@@ -37,6 +37,7 @@
SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H))
struct EmbeddingParams;
+struct CompletionParams;
struct Cleanup
{
@@ -88,7 +89,11 @@ struct Client
bool dispatch() __wur;
bool tokenize() __wur;
- bool embedding() __wur;
bool dispatcher() __wur;
+
+ bool embedding() __wur;
bool get_embedding_params(EmbeddingParams*);
+
+ bool completion() __wur;
+ bool get_completion_params(CompletionParams*);
};
diff --git a/llamafile/server/completion.cpp b/llamafile/server/completion.cpp
new file mode 100644
index 00000000..03a124ec
--- /dev/null
+++ b/llamafile/server/completion.cpp
@@ -0,0 +1,320 @@
+// -*- 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 "client.h"
+
+#include <ctl/vector.h>
+#include <math.h>
+#include <string.h>
+#include <sys/resource.h>
+
+#include "llama.cpp/llama.h"
+#include "llama.cpp/sampling.h"
+
+#include "cleanup.h"
+#include "fastjson.h"
+#include "json.h"
+#include "log.h"
+#include "utils.h"
+
+struct CompletionParams
+{
+ bool add_special;
+ bool parse_special;
+ bool display_special;
+ ctl::string_view prompt;
+ ctl::string content;
+};
+
+struct CompletionResponse
+{
+ ctl::string prompt;
+ ctl::string content;
+ bool stop = false;
+};
+
+extern 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 void
+add_token_to_batch(llama_batch& batch,
+ llama_token id,
+ llama_pos pos,
+ const ctl::vector<llama_seq_id>& seq_ids,
+ bool logits)
+{
+ batch.token[batch.n_tokens] = id;
+ batch.pos[batch.n_tokens] = pos;
+ batch.n_seq_id[batch.n_tokens] = seq_ids.size();
+ for (size_t i = 0; i < seq_ids.size(); ++i)
+ batch.seq_id[batch.n_tokens][i] = seq_ids[i];
+ batch.logits[batch.n_tokens] = logits;
+ batch.n_tokens++;
+}
+
+static ctl::string
+token_to_piece(const struct llama_context* ctx, llama_token token, bool special)
+{
+ ctl::vector<char> result(8, 0);
+ const int n_tokens = llama_token_to_piece(
+ llama_get_model(ctx), token, result.data(), result.size(), special);
+ if (n_tokens < 0) {
+ result.resize(-n_tokens);
+ int check = llama_token_to_piece(
+ llama_get_model(ctx), token, result.data(), result.size(), special);
+ GGML_ASSERT(check == -n_tokens);
+ } else {
+ result.resize(n_tokens);
+ }
+ return ctl::string(result.data(), result.size());
+}
+
+void
+cleanup_completion_params(void* arg)
+{
+ delete (CompletionParams*)arg;
+}
+
+void
+cleanup_completion_response(void* arg)
+{
+ delete (CompletionResponse*)arg;
+}
+
+void
+cleanup_llama_sampling_context(void* arg)
+{
+ llama_sampling_free((llama_sampling_context*)arg);
+}
+
+bool
+Client::get_completion_params(CompletionParams* params)
+{
+ params->add_special = atob(or_empty(param("add_special")), true);
+ params->parse_special = atob(or_empty(param("parse_special")), false);
+ params->display_special = atob(or_empty(param("display_special")), true);
+ ctl::optional<ctl::string_view> prompt = param("prompt");
+ if (prompt.has_value()) {
+ params->prompt = prompt.value();
+ } else if (HasHeader(kHttpContentType)) {
+ if (IsMimeType(HeaderData(kHttpContentType),
+ HeaderLength(kHttpContentType),
+ "text/plain")) {
+ params->prompt = payload;
+ } else if (IsMimeType(HeaderData(kHttpContentType),
+ HeaderLength(kHttpContentType),
+ "application/json")) {
+ ctl::pair<Json::Status, Json> json = Json::parse(payload);
+ if (json.first != Json::success)
+ return send_error(400, Json::StatusToString(json.first));
+ if (!json.second["prompt"].isString())
+ return send_error(400, "JSON missing \"prompt\" key");
+ params->content = ctl::move(json.second["prompt"].getString());
+ params->prompt = params->content;
+ } else {
+ return send_error(501, "Content Type Not Implemented");
+ }
+ } else {
+ params->prompt = payload;
+ }
+ return true;
+}
+
+bool
+Client::completion()
+{
+ if (msg.method != kHttpGet && msg.method != kHttpPost)
+ return send_error(405);
+
+ if (!read_payload())
+ return false;
+
+ // get parameters
+ auto params = new CompletionParams;
+ defer_cleanup(cleanup_completion_params, params);
+ if (!get_completion_params(params))
+ return false;
+
+ // create response object
+ auto response = new CompletionResponse;
+ defer_cleanup(cleanup_completion_response, response);
+
+ // setup statistics
+ rusage rustart = {};
+ getrusage(RUSAGE_THREAD, &rustart);
+ timespec started = timespec_real();
+
+ // turn text into tokens
+ auto toks = new ctl::vector<llama_token>(params->prompt.size() + 16);
+ defer_cleanup(cleanup_token_vector, toks);
+ int count = llama_tokenize(g_model,
+ params->prompt.data(),
+ params->prompt.size(),
+ &(*toks)[0],
+ toks->size(),
+ params->add_special,
+ params->parse_special);
+ if (count < 0) {
+ SLOG("llama_tokenize failed");
+ return send_error(405);
+ }
+ toks->resize(count);
+
+ if (toks->empty())
+ return send_error(400, "completely empty prompt disallowed");
+
+ // fail if exceeds model context size
+ const int n_ctx_train = llama_n_ctx_train(g_model);
+ if (count + 1 > n_ctx_train)
+ return send_error(400, "prompt too big for model context size");
+
+ // initialize context
+ llama_context_params cparams = {};
+ cparams.embeddings = true;
+ cparams.embeddings_only = false;
+ cparams.logits_all = true;
+ cparams.seed = _rand64();
+ cparams.n_ctx = FLAG_ctx;
+ if (cparams.n_ctx < count + 512)
+ cparams.n_ctx = count + 512;
+ if (cparams.n_ctx > n_ctx_train)
+ cparams.n_ctx = n_ctx_train;
+ cparams.n_batch = count;
+ cparams.n_ubatch = count;
+ cparams.n_seq_max = 1;
+ cparams.n_threads = FLAG_threads;
+ cparams.n_threads_batch = FLAG_threads;
+ cparams.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE;
+ cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
+ cparams.rope_freq_base = 0;
+ cparams.yarn_ext_factor = -1;
+ cparams.yarn_attn_factor = 1;
+ cparams.yarn_beta_fast = 32;
+ cparams.yarn_beta_slow = 1;
+ cparams.yarn_orig_ctx = 0;
+ cparams.defrag_thold = -1;
+ 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);
+ if (!ctx) {
+ SLOG("llama_new_context_with_model failed");
+ return send_error(500);
+ }
+ defer_cleanup(cleanup_llama_context, ctx);
+
+ // turn prompt back into string
+ for (auto tok : *toks)
+ response->prompt += token_to_piece(ctx, tok, params->display_special);
+
+ // prefill time
+ if (llama_decode(ctx, llama_batch_get_one(&(*toks)[0], count, 0, 0))) {
+ SLOG("llama_decode prefill failed");
+ return send_error(500, "llama_decode prefill failed");
+ }
+
+ // init sampling
+ llama_sampling_params sparams;
+ sparams.temp = FLAG_temp;
+ sparams.seed = cparams.seed;
+ llama_sampling_context* ctx_sampling = llama_sampling_init(sparams);
+ if (!ctx_sampling) {
+ SLOG("llama_sampling_init() failed");
+ return send_error(500, "llama_sampling_init() failed");
+ }
+ defer_cleanup(cleanup_llama_sampling_context, ctx_sampling);
+
+ // prediction time
+ for (;;) {
+ llama_token id = llama_sampling_sample(ctx_sampling, ctx, NULL);
+ llama_sampling_accept(ctx_sampling, ctx, id, true);
+ if (llama_token_is_eog(g_model, id)) {
+ response->stop = true;
+ break;
+ }
+ response->content += token_to_piece(ctx, id, params->display_special);
+ if (llama_decode(ctx, llama_batch_get_one(&id, 1, count, 0)))
+ break;
+ ++count;
+ }
+
+ // serialize tokens to json
+ char* p = obuf.p;
+ p = stpcpy(p, "{\r\n");
+ p = stpcpy(p, " \"add_special\": ");
+ p = encode_bool(p, params->add_special);
+ p = stpcpy(p, ",\r\n");
+ p = stpcpy(p, " \"parse_special\": ");
+ p = encode_bool(p, params->parse_special);
+ p = stpcpy(p, ",\r\n");
+ p = stpcpy(p, " \"display_special\": ");
+ p = encode_bool(p, params->display_special);
+ p = stpcpy(p, ",\r\n");
+ p = stpcpy(p, " \"tokens_provided\": ");
+ p = encode_json(p, toks->size());
+ p = stpcpy(p, ",\r\n");
+ p = stpcpy(p, " \"tokens_used\": ");
+ p = encode_json(p, count);
+ p = stpcpy(p, ",\r\n");
+ p = stpcpy(p, " \"prompt\": ");
+ p = encode_json(p, response->prompt);
+ p = stpcpy(p, ",\r\n");
+ p = stpcpy(p, " \"content\": ");
+ p = encode_json(p, response->content);
+ p = stpcpy(p, ",\r\n");
+ p = stpcpy(p, " \"stop\": ");
+ p = encode_bool(p, response->stop);
+ p = stpcpy(p, "\r\n");
+ p = stpcpy(p, "}\r\n");
+ ctl::string_view content(obuf.p, p - obuf.p);
+
+ // collect statistics
+ rusage ruend = {};
+ getrusage(RUSAGE_THREAD, &ruend);
+ timeval user = timeval_sub(ruend.ru_utime, rustart.ru_utime);
+ timeval system = timeval_sub(ruend.ru_stime, rustart.ru_stime);
+ timespec ended = timespec_real();
+ timespec wall = timespec_sub(ended, started);
+ long wall_us = timespec_tomicros(wall);
+ long user_us = timeval_tomicros(user);
+ long system_us = timeval_tomicros(system);
+
+ // send response
+ char* headers = p;
+ p = start_response(p, 200);
+ p = stpcpy(p, "Content-Type: application/json\r\n");
+ p = stpcpy(p, "X-Wall-Micros: ");
+ p = FormatInt64(p, wall_us);
+ p = stpcpy(p, "\r\nX-User-Micros: ");
+ p = FormatInt64(p, user_us);
+ p = stpcpy(p, "\r\nX-System-Micros: ");
+ p = FormatInt64(p, system_us);
+ p = stpcpy(p, "\r\n");
+ return send_response(headers, p, content);
+}
diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cpp
index 9da30a83..037e308e 100644
--- a/llamafile/server/embedding.cpp
+++ b/llamafile/server/embedding.cpp
@@ -24,6 +24,7 @@
#include "llama.cpp/llama.h"
+#include "cleanup.h"
#include "fastjson.h"
#include "json.h"
#include "log.h"
@@ -51,7 +52,7 @@ normalize_embeddings(const float* inp, float* out, int n)
out[i] = inp[i] * norm;
}
-void
+static void
add_token_to_batch(struct llama_batch& batch,
llama_token id,
llama_pos pos,
@@ -67,32 +68,6 @@ add_token_to_batch(struct llama_batch& batch,
batch.n_tokens++;
}
-void
-cleanup_float_vector(void* arg)
-{
- delete (ctl::vector<float>*)arg;
-}
-
-void
-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;
-}
-
-void
-cleanup_llama_context(void* arg)
-{
- llama_free((llama_context*)arg);
-}
-
void
cleanup_embedding_params(void* arg)
{
@@ -170,11 +145,14 @@ Client::embedding()
params->add_special,
params->parse_special);
if (count < 0) {
- LOG("llama_tokenize failed");
+ SLOG("llama_tokenize failed");
return send_error(405);
}
toks->resize(count);
+ if (toks->empty())
+ 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);
if (count > n_ctx_train)
@@ -199,7 +177,7 @@ Client::embedding()
cparams.flash_attn = FLAG_flash_attn;
llama_context* ctx = llama_new_context_with_model(g_model, cparams);
if (!ctx) {
- LOG("llama_new_context_with_model failed");
+ SLOG("llama_new_context_with_model failed");
return send_error(500);
}
defer_cleanup(cleanup_llama_context, ctx);
@@ -214,7 +192,7 @@ Client::embedding()
// inference time
if (llama_decode(ctx, *batch) < 0) {
- LOG("llama_decode failed");
+ SLOG("llama_decode failed");
return send_error(500);
}
auto embeddings = new ctl::vector<float>(n_embd, 0);
@@ -224,7 +202,7 @@ Client::embedding()
continue;
const float* embd = llama_get_embeddings_ith(ctx, i);
if (!embd) {
- LOG("llama_get_embeddings_ith failed");
+ SLOG("llama_get_embeddings_ith failed");
return send_error(500);
}
normalize_embeddings(
diff --git a/llamafile/server/listen.cpp b/llamafile/server/listen.cpp
index 2f71ff46..4f22b1f4 100644
--- a/llamafile/server/listen.cpp
+++ b/llamafile/server/listen.cpp
@@ -30,12 +30,12 @@
void
print_listening_url(unsigned ip, int port)
{
- LOG("listen http://%hhu.%hhu.%hhu.%hhu:%hu",
- ip >> 24,
- ip >> 16,
- ip >> 8,
- ip,
- port);
+ SLOG("listen http://%hhu.%hhu.%hhu.%hhu:%hu",
+ ip >> 24,
+ ip >> 16,
+ ip >> 8,
+ ip,
+ port);
}
int
diff --git a/llamafile/server/log.h b/llamafile/server/log.h
index 1ddb2bda..16423414 100644
--- a/llamafile/server/log.h
+++ b/llamafile/server/log.h
@@ -18,7 +18,7 @@
#pragma once
#include <libc/intrin/kprintf.h>
-#define LOG(FMT, ...) \
+#define SLOG(FMT, ...) \
kprintf("%s %s:%d %s " FMT "\n", \
get_log_timestamp(), \
__FILE__, \
diff --git a/llamafile/server/main.cpp b/llamafile/server/main.cpp
index 5e842431..100c6c04 100644
--- a/llamafile/server/main.cpp
+++ b/llamafile/server/main.cpp
@@ -84,13 +84,13 @@ main(int argc, char* argv[])
signals_destroy();
// shutdown server
- LOG("shutdown");
+ SLOG("shutdown");
g_server->shutdown();
g_server->close();
delete g_server;
llama_free_model(g_model);
time_destroy();
- LOG("exit");
+ SLOG("exit");
// quality assurance
while (!pthread_orphan_np())
diff --git a/llamafile/server/server.cpp b/llamafile/server/server.cpp
index 527a8364..ef596ce7 100644
--- a/llamafile/server/server.cpp
+++ b/llamafile/server/server.cpp
@@ -146,7 +146,7 @@ Server::accept()
}
if (FLAG_verbose >= 2)
- LOG("accept");
+ SLOG("accept");
return clifd;
}
diff --git a/llamafile/server/signals.cpp b/llamafile/server/signals.cpp
index 558f5305..64837884 100644
--- a/llamafile/server/signals.cpp
+++ b/llamafile/server/signals.cpp
@@ -43,17 +43,17 @@ static struct
void
on_termination_signal(int sig)
{
- LOG("%G", sig);
+ SLOG("%G", sig);
g_server->terminate();
}
void
on_crash_signal(int sig, siginfo_t* si, void* arg)
{
- LOG("crashed %G", sig);
+ SLOG("crashed %G", sig);
char message[256];
describe_crash(message, sizeof(message), sig, si, arg);
- LOG("crashed %s", message);
+ SLOG("crashed %s", message);
pthread_exit(PTHREAD_CANCELED);
}
diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cpp
index e697ecac..84fb47a5 100644
--- a/llamafile/server/tokenize.cpp
+++ b/llamafile/server/tokenize.cpp
@@ -79,7 +79,7 @@ Client::tokenize()
add_special,
parse_special);
if (count < 0) {
- LOG("failed to tokenize");
+ SLOG("failed to tokenize");
return send_error(405);
}
toks.resize(count);
@@ -101,7 +101,7 @@ Client::tokenize()
char s[32];
int n = llama_token_to_piece(g_model, toks[i], s, sizeof(s), true);
if (n < 0) {
- LOG("failed to turn token into string");
+ SLOG("failed to turn token into string");
return send_error(405);
}
p = encode_json(p, ctl::string_view(s, n));
diff --git a/llamafile/server/worker.cpp b/llamafile/server/worker.cpp
index 1d3a0ecd..8396bde0 100644
--- a/llamafile/server/worker.cpp
+++ b/llamafile/server/worker.cpp
@@ -46,7 +46,7 @@ Worker::begin()
if (dll_is_empty(server->idle_workers)) {
Dll* slowbro;
if ((slowbro = dll_last(server->active_workers))) {
- LOG("all threads active! dropping oldest client");
+ SLOG("all threads active! dropping oldest client");
WORKER(slowbro)->kill();
}
}
@@ -84,7 +84,7 @@ void
Worker::handle(void)
{
if ((client.fd = server->accept()) == -1) {
- LOG("accept returned %m");
+ SLOG("accept returned %m");
return;
}
@@ -100,9 +100,9 @@ Worker::handle(void)
try {
client.run();
} catch (const std::exception& e) {
- LOG("caught %s", e.what());
+ SLOG("caught %s", e.what());
} catch (...) {
- LOG("caught unknown exception");
+ SLOG("caught unknown exception");
}
pthread_cleanup_pop(true);
diff --git a/llamafile/simple.cpp b/llamafile/simple.cpp
index a17e4b19..513cfb5c 100644
--- a/llamafile/simple.cpp
+++ b/llamafile/simple.cpp
@@ -32,6 +32,7 @@ static bool eval_tokens(struct llama_context *ctx_llama, std::vector<llama_token
int n_eval = (int)tokens.size() - i;
if (n_eval > n_batch)
n_eval = n_batch;
+ printf("llama_decode n_eval=%d n_past=%d\n", n_eval, *n_past);
if (llama_decode(ctx_llama, llama_batch_get_one(&tokens[i], n_eval, *n_past, 0)))
return false; // probably ran out of context
*n_past += n_eval;