Skip to content

Distribute and run LLMs with a single file.

Make improvements to chatbot and completions api

Justine Tunney880894d5c2d6
diff --git a/llamafile/chatbot.cpp b/llamafile/chatbot.cpp
index 855d45f7..7d11ff86 100644
--- a/llamafile/chatbot.cpp
+++ b/llamafile/chatbot.cpp
@@ -32,6 +32,7 @@
#include "llamafile/bestline.h"
#include "llamafile/compute.h"
#include "llamafile/highlight.h"
+#include "llamafile/llama.h"
#include "llamafile/llamafile.h"
#include "llamafile/string.h"
@@ -61,13 +62,13 @@ struct ServerArgs {
char **argv;
};
-static int g_past;
-static int g_clear;
-static bool g_once;
-static bool g_manual;
+static bool g_manual_mode;
+static bool g_said_something;
+static int g_system_prompt_tokens;
static llama_model *g_model;
static llama_context *g_ctx;
-static std::vector<int> g_stack;
+static std::vector<llama_pos> g_undo;
+static std::vector<llama_pos> g_stack;
static std::vector<llama_token> g_history;
static enum Role g_role = ROLE_USER;
static pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
@@ -79,6 +80,10 @@ static void on_sigint(int sig) {
g_got_sigint = 1;
}
+static int tokens_used(void) {
+ return g_history.size();
+}
+
static bool is_empty(const char *s) {
int c;
while ((c = *s++))
@@ -87,6 +92,21 @@ static bool is_empty(const char *s) {
return true;
}
+static void fix_stack(std::vector<llama_pos> *stack) {
+ while (!stack->empty() && stack->back() > tokens_used())
+ stack->pop_back();
+}
+
+static void fix_stacks(void) {
+ fix_stack(&g_undo);
+ fix_stack(&g_stack);
+}
+
+static void record_undo(void) {
+ if (g_undo.empty() || g_undo.back() != tokens_used())
+ g_undo.push_back(tokens_used());
+}
+
static const char *get_role_name(enum Role role) {
switch (role) {
case ROLE_USER:
@@ -139,30 +159,6 @@ static enum Role cycle_role(enum Role role) {
}
}
-static std::string basename(const std::string_view path) {
- size_t i, e;
- if ((e = path.size())) {
- while (e > 1 && path[e - 1] == '/')
- --e;
- i = e - 1;
- while (i && path[i - 1] != '/')
- --i;
- return std::string(path.substr(i, e - i));
- } else {
- return ".";
- }
-}
-
-static std::string join(const std::vector<std::string> &vec, const std::string_view &delim) {
- std::string result;
- for (size_t i = 0; i < vec.size(); i++) {
- result += vec[i];
- if (i < vec.size() - 1)
- result += delim;
- }
- return result;
-}
-
static std::string describe_compute(void) {
if (llama_n_gpu_layers(g_model) > 0 && llamafile_has_gpu()) {
if (llamafile_has_metal()) {
@@ -175,23 +171,41 @@ static std::string describe_compute(void) {
ggml_backend_cuda_get_device_description(i, buf, sizeof(buf));
vec.emplace_back(buf);
}
- return join(vec, ", ");
+ return lf::join(vec, ", ");
}
} else {
return llamafile_describe_cpu();
}
}
+static std::string describe_position(llama_pos pos) {
+ unassert(pos <= tokens_used());
+ std::string description;
+ while (pos > 0 && description.size() < 63) {
+ std::string piece =
+ llama_token_to_piece(g_ctx, g_history[--pos], DONT_RENDER_SPECIAL_TOKENS);
+ description = piece + description;
+ }
+ if (pos > 0)
+ description = std::string("... ") + description;
+ return lf::collapse(description);
+}
+
static void on_help(const std::vector<std::string> &args) {
if (args.size() == 1) {
fprintf(stderr, "\
" BOLD "available commands" RESET "\n\
+ /clear restart conversation\n\
/context print context window usage\n\
/dump [FILE] print or save context window to file\n\
/exit end program\n\
/help [COMMAND] show help\n\
/manual [on|off] toggle manual role mode\n\
+ /pop restore context window size\n\
+ /push push context window size to stack\n\
+ /stack prints context window stack\n\
/stats print performance metrics\n\
+ /undo erases last message in conversation\n\
");
} else if (args[1] == "context") {
fprintf(stderr, "\
@@ -262,6 +276,19 @@ with /pop to backtrack a conversation.\n\
usage: /pop" RESET "\n\
restores size of context window from stack. this command may be used\n\
with /push to backtrack a conversation.\n\
+");
+ } else if (args[1] == "stack") {
+ fprintf(stderr, "\
+usage: /stack" RESET "\n\
+prints the current conversation stack, created by /push commands.\n\
+the stack consists of token offsets within the context window.\n\
+");
+ } else if (args[1] == "undo") {
+ fprintf(stderr, "\
+usage: /undo" RESET "\n\
+erases last exchange in conversation. in the normal mode, this includes\n\
+what the assistant last said, as well as the question that was asked. in\n\
+manual mode, this will erase only the last chat message.\n\
");
} else {
fprintf(stderr, BRIGHT_RED "%s: unknown command" RESET "\n", args[1].c_str());
@@ -270,53 +297,78 @@ with /push to backtrack a conversation.\n\
static void on_manual(const std::vector<std::string> &args) {
if (args.size() == 1) {
- g_manual = !g_manual;
+ g_manual_mode = !g_manual_mode;
} else if (args.size() == 2 && (args[1] == "on" || args[1] == "off")) {
- g_manual = args[1] == "on";
+ g_manual_mode = args[1] == "on";
} else {
fprintf(stderr, BRIGHT_RED "error: bad /manual command" RESET "\n"
"usage: /manual [on|off]\n");
return;
}
- fprintf(stderr, FAINT "manual mode %s" RESET "\n", g_manual ? "enabled" : "disabled");
- if (!g_manual)
+ fprintf(stderr, FAINT "manual mode %s" RESET "\n", g_manual_mode ? "enabled" : "disabled");
+ if (!g_manual_mode)
g_role = ROLE_USER;
}
static void on_context(const std::vector<std::string> &args) {
int configured_context = llama_n_ctx(g_ctx);
int max_context = llama_n_ctx_train(g_model);
- printf("%d out of %d context tokens used (%d tokens remaining)\n", g_past, configured_context,
- configured_context - g_past);
+ printf("%d out of %d context tokens used (%d tokens remaining)\n", tokens_used(),
+ configured_context, configured_context - tokens_used());
if (configured_context < max_context)
printf("use the `-c %d` flag at startup for maximum context\n", max_context);
}
-static void print_stack(void) {
- for (size_t i = g_stack.size(); i--;)
- printf("%8d\n", g_stack[i]);
+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);
+ g_history.resize(g_system_prompt_tokens);
+ g_stack.clear();
}
-static void on_clear(const std::vector<std::string> &args) { // [experimental]
- g_past = g_clear;
- g_stack.clear();
- g_history.resize(g_past);
+static void print_stack(void) {
+ for (size_t i = g_stack.size(); i--;)
+ printf("%12d " FAINT "(%s)" RESET "\n", g_stack[i], describe_position(g_stack[i]).c_str());
}
-static void on_push(const std::vector<std::string> &args) { // [experimental]
- g_stack.push_back(g_past);
+static void on_push(const std::vector<std::string> &args) {
+ g_stack.push_back(tokens_used());
print_stack();
}
-static void on_pop(const std::vector<std::string> &args) { // [experimental]
+static void on_pop(const std::vector<std::string> &args) {
if (g_stack.empty()) {
fprintf(stderr, BRIGHT_RED "error: context length stack is empty" RESET "\n");
return;
}
- printf(BOLD "%12d" RESET " restored\n", g_stack[g_stack.size() - 1]);
- g_past = g_stack.back();
+ 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());
+ g_history.resize(g_stack.back());
g_stack.pop_back();
- g_history.resize(g_past);
+ fix_stacks();
+ print_stack();
+}
+
+static void on_undo(const std::vector<std::string> &args) {
+ while (!g_undo.empty() && g_undo.back() == tokens_used())
+ g_undo.pop_back();
+ if (g_undo.empty()) {
+ fprintf(stderr, BRIGHT_RED "error: no further undo actions possible" RESET "\n");
+ return;
+ }
+ 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());
+ g_history.resize(g_undo.back());
+ g_undo.pop_back();
+ fix_stacks();
+}
+
+static void on_stack(const std::vector<std::string> &args) {
+ if (g_stack.empty()) {
+ printf(FAINT "stack is currently empty (try using /push)" RESET "\n");
+ return;
+ }
print_stack();
}
@@ -336,7 +388,7 @@ static void on_dump(const std::vector<std::string> &args) {
}
std::string s;
for (auto id : g_history)
- s += llama_token_to_piece(g_ctx, id, true);
+ s += llama_token_to_piece(g_ctx, id, RENDER_SPECIAL_TOKENS);
if (!s.empty() && s[s.size() - 1] != '\n')
s += '\n';
write(fd, s.data(), s.size());
@@ -347,20 +399,24 @@ static void on_dump(const std::vector<std::string> &args) {
static char *on_hint(const char *line, const char **ansi1, const char **ansi2) {
*ansi1 = FAINT;
*ansi2 = UNBOLD;
- if (!*line && g_manual)
+ if (!*line && g_manual_mode)
return strdup(get_role_name(g_role));
- else if (!*line && !g_manual && !g_once)
+ else if (!*line && !g_manual_mode && !g_said_something)
return strdup("say something (or type /help for help)");
return strdup("");
}
static void on_completion(const char *line, int pos, bestlineCompletions *comp) {
static const char *const kCompletions[] = {
+ "/clear", // usage: /clear
"/context", // usage: /context
"/dump", // usage: /dump [FILE]
"/exit", // usage: /exit
"/help", // usage: /help [COMMAND]
"/manual", // usage: /manual [on|off]
+ "/pop", // usage: /pop
+ "/push", // usage: /push
+ "/stack", // usage: /stack
"/stats", // usage: /stats
};
for (int i = 0; i < sizeof(kCompletions) / sizeof(*kCompletions); ++i)
@@ -395,6 +451,10 @@ static bool handle_command(const char *command) {
on_push(args);
} else if (args[0] == "pop") {
on_pop(args);
+ } else if (args[0] == "undo") {
+ on_undo(args);
+ } else if (args[0] == "stack") {
+ on_stack(args);
} else {
fprintf(stderr, BRIGHT_RED "%s: unrecognized command" RESET "\n", args[0].c_str());
}
@@ -431,31 +491,28 @@ static void clear_ephemeral(void) {
fprintf(stderr, CLEAR_FORWARD);
}
-static void die_out_of_context(void) {
+static void die_out_of_context(int extra) {
fprintf(stderr,
"\n" BRIGHT_RED
"error: ran out of context window at %d tokens; you can use the maximum "
"context window size by passing the flag `-c %d` to llamafile." UNFOREGROUND "\n",
- g_past, llama_n_ctx_train(g_model));
+ tokens_used() + extra, llama_n_ctx_train(g_model));
exit(1);
}
static void eval_tokens(std::vector<llama_token> tokens, int n_batch) {
int N = (int)tokens.size();
- if (g_past + N > llama_n_ctx(g_ctx)) {
- g_past += N;
- die_out_of_context();
- }
+ if (tokens_used() + N > llama_n_ctx(g_ctx))
+ die_out_of_context(N);
for (int i = 0; i < N; i += n_batch) {
if (N > n_batch)
print_ephemeral(lf::format("loading prompt %d%%...", (int)((double)i / N * 100)));
int n_eval = (int)tokens.size() - i;
if (n_eval > n_batch)
n_eval = n_batch;
- if (llama_decode(g_ctx, llama_batch_get_one(&tokens[i], n_eval, g_past, 0)))
- die_out_of_context();
+ if (llama_decode(g_ctx, llama_batch_get_one(&tokens[i], n_eval, tokens_used(), 0)))
+ die_out_of_context(n_eval);
g_history.insert(g_history.end(), tokens.begin() + i, tokens.begin() + i + n_eval);
- g_past += n_eval;
}
}
@@ -510,6 +567,9 @@ int chatbot_main(int argc, char **argv) {
gpt_params params;
params.n_batch = 512; // for better progress indication
params.sparams.temp = 0; // don't believe in randomness by default
+ params.prompt = "A chat between a curious human and an artificial intelligence assistant. "
+ "The assistant gives helpful, detailed, and polite answers to the "
+ "human's questions.";
if (!gpt_params_parse(argc, argv, params)) { // also loads gpu module
fprintf(stderr, "error: failed to parse flags\n");
exit(1);
@@ -549,7 +609,7 @@ int chatbot_main(int argc, char **argv) {
printf(BOLD "software" UNBOLD ": llamafile " LLAMAFILE_VERSION_STRING "\n" //
BOLD "model" UNBOLD ": %s\n",
- basename(params.model).c_str());
+ lf::basename(params.model).c_str());
printf(BOLD "compute" UNBOLD ": %s\n", describe_compute().c_str());
if (want_server)
printf(BOLD "server" UNBOLD ": %s\n", g_listen_url.c_str());
@@ -565,16 +625,20 @@ int chatbot_main(int argc, char **argv) {
}
clear_ephemeral();
- if (params.prompt.empty())
- params.prompt = "A chat between a curious human and an artificial intelligence assistant. "
- "The assistant gives helpful, detailed, and polite answers to the "
- "human's questions.";
+ if (llama_model_has_encoder(g_model))
+ fprintf(stderr, "warning: this model has an encoder\n");
- bool add_bos = llama_should_add_bos_token(llama_get_model(g_ctx));
+ // setup conversation
+ if (llama_should_add_bos_token(g_model))
+ eval_id(llama_token_bos(g_model));
+ record_undo();
+
+ // setup system prompt
std::vector<llama_chat_msg> chat = {{"system", params.prompt}};
- std::string msg = llama_chat_apply_template(g_model, params.chat_template, chat, false);
- eval_string(msg, params.n_batch, add_bos, true);
- g_clear = g_past;
+ std::string msg =
+ llama_chat_apply_template(g_model, params.chat_template, chat, DONT_ADD_ASSISTANT);
+ eval_string(msg, params.n_batch, DONT_ADD_SPECIAL, PARSE_SPECIAL);
+ g_system_prompt_tokens = tokens_used();
clear_ephemeral();
printf("%s\n", params.special ? msg.c_str() : params.prompt.c_str());
@@ -586,6 +650,7 @@ int chatbot_main(int argc, char **argv) {
// run chatbot
for (;;) {
+ record_undo();
bestlineLlamaMode(true);
bestlineSetHintsCallback(on_hint);
bestlineSetFreeHintsCallback(free);
@@ -599,7 +664,7 @@ int chatbot_main(int argc, char **argv) {
break;
}
if (is_empty(line)) {
- if (g_manual) {
+ if (g_manual_mode) {
g_role = cycle_role(g_role);
write(1, "\033[F", 3);
}
@@ -610,26 +675,30 @@ int chatbot_main(int argc, char **argv) {
free(line);
continue;
}
- g_once = true;
- bool add_assi = !g_manual;
+ g_said_something = true;
+ bool add_assi = !g_manual_mode;
std::vector<llama_chat_msg> chat = {{get_role_name(g_role), line}};
std::string msg = llama_chat_apply_template(g_model, params.chat_template, chat, add_assi);
- eval_string(msg, params.n_batch, false, true);
- if (g_manual) {
+ eval_string(msg, params.n_batch, DONT_ADD_SPECIAL, PARSE_SPECIAL);
+ if (g_manual_mode) {
g_role = get_next_role(g_role);
free(line);
continue;
}
- while (!g_got_sigint) {
+ for (;;) {
+ if (g_got_sigint) {
+ eval_id(llamafile_token_eot(g_model));
+ break;
+ }
llama_token id = llama_sampling_sample(sampler, g_ctx, NULL);
- llama_sampling_accept(sampler, g_ctx, id, true);
+ llama_sampling_accept(sampler, g_ctx, id, APPLY_GRAMMAR);
+ eval_id(id);
if (llama_token_is_eog(g_model, id))
break;
std::string s;
bleeder.feed(&s, llama_token_to_piece(g_ctx, id, params.special));
printf("%s", s.c_str());
fflush(stdout);
- eval_id(id);
}
g_got_sigint = 0;
free(line);
diff --git a/llamafile/flags.cpp b/llamafile/flags.cpp
index 5efdb83f..fa4e9804 100644
--- a/llamafile/flags.cpp
+++ b/llamafile/flags.cpp
@@ -62,6 +62,7 @@ int FLAG_keepalive = 5;
int FLAG_main_gpu = 0;
int FLAG_n_gpu_layers = -1;
int FLAG_seed = LLAMA_DEFAULT_SEED;
+int FLAG_slots = 1;
int FLAG_split_mode = LLAMA_SPLIT_MODE_LAYER;
int FLAG_threads;
int FLAG_token_burst = 100;
diff --git a/llamafile/llama.cpp b/llamafile/llama.cpp
new file mode 100644
index 00000000..24628403
--- /dev/null
+++ b/llamafile/llama.cpp
@@ -0,0 +1,25 @@
+// -*- 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.h"
+
+int llamafile_token_eot(llama_model *model) {
+ llama_token eot = llama_token_eot(model);
+ if (eot != -1)
+ return eot;
+ return llama_token_eos(model);
+}
diff --git a/llamafile/llama.h b/llamafile/llama.h
new file mode 100644
index 00000000..429ac0ce
--- /dev/null
+++ b/llamafile/llama.h
@@ -0,0 +1,39 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// Copyright 2024 Mozilla Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+#include "llama.cpp/llama.h"
+
+// Many llama.cpp APIs take boolean parameters at the end. Please favor
+// passing these constants as arguments instead, for better readability
+
+#define ADD_SPECIAL true
+#define DONT_ADD_SPECIAL false
+
+#define PARSE_SPECIAL true
+#define DONT_PARSE_SPECIAL false
+
+#define ADD_ASSISTANT true
+#define DONT_ADD_ASSISTANT false
+
+#define APPLY_GRAMMAR true
+#define DONT_APPLY_GRAMMAR false
+
+#define RENDER_SPECIAL_TOKENS true
+#define DONT_RENDER_SPECIAL_TOKENS false
+
+int llamafile_token_eot(llama_model *);
diff --git a/llamafile/llamafile.h b/llamafile/llamafile.h
index e74a210d..2f853670 100644
--- a/llamafile/llamafile.h
+++ b/llamafile/llamafile.h
@@ -23,9 +23,9 @@ extern bool FLAG_unsecure;
extern const char *FLAG_file;
extern const char *FLAG_ip_header;
extern const char *FLAG_listen;
-extern const char *FLAG_url_prefix;
extern const char *FLAG_model;
extern const char *FLAG_prompt;
+extern const char *FLAG_url_prefix;
extern double FLAG_token_rate;
extern float FLAG_temp;
extern int FLAG_batch;
@@ -39,6 +39,7 @@ extern int FLAG_keepalive;
extern int FLAG_main_gpu;
extern int FLAG_n_gpu_layers;
extern int FLAG_seed;
+extern int FLAG_slots;
extern int FLAG_split_mode;
extern int FLAG_threads;
extern int FLAG_token_burst;
diff --git a/llamafile/server/json.cpp b/llamafile/server/json.cpp
index 715ad70d..930f1e82 100644
--- a/llamafile/server/json.cpp
+++ b/llamafile/server/json.cpp
@@ -477,10 +477,18 @@ Json::operator[](const std::string& key) noexcept
}
std::string
-Json::toString(bool pretty) const noexcept
+Json::toString() const noexcept
{
std::string b;
- marshal(b, pretty, 0);
+ marshal(b, false, 0);
+ return b;
+}
+
+std::string
+Json::toStringPretty() const noexcept
+{
+ std::string b;
+ marshal(b, true, 0);
return b;
}
diff --git a/llamafile/server/json.h b/llamafile/server/json.h
index 4a0bbd0c..1b60c2e3 100644
--- a/llamafile/server/json.h
+++ b/llamafile/server/json.h
@@ -220,7 +220,8 @@ class Json
void setArray();
void setObject();
- std::string toString(bool pretty = false) const noexcept;
+ std::string toString() const noexcept;
+ std::string toStringPretty() const noexcept;
Json& operator=(const Json&);
Json& operator=(Json&&) noexcept;
diff --git a/llamafile/server/json_test.cpp b/llamafile/server/json_test.cpp
index de3ebbde..deb197b3 100644
--- a/llamafile/server/json_test.cpp
+++ b/llamafile/server/json_test.cpp
@@ -136,13 +136,13 @@ parse_test()
exit(3);
if (res.second.toString() != "{\"content\":[[[0,10,20,3.14,40]]]}")
exit(4);
- if (res.second.toString(true) !=
+ if (res.second.toStringPretty() !=
R"({"content": [[[0, 10, 20, 3.14, 40]]]})")
exit(5);
res = Json::parse("{ \"a\": 1, \"b\": [2, 3]}");
- if (res.second.toString(false) != R"({"a":1,"b":[2,3]})")
+ if (res.second.toString() != R"({"a":1,"b":[2,3]})")
exit(6);
- if (res.second.toString(true) !=
+ if (res.second.toStringPretty() !=
R"({
"a": 1,
"b": [2, 3]
diff --git a/llamafile/server/slot.cpp b/llamafile/server/slot.cpp
index 55d5040b..3d8b8746 100644
--- a/llamafile/server/slot.cpp
+++ b/llamafile/server/slot.cpp
@@ -16,21 +16,15 @@
// limitations under the License.
#include "slot.h"
+#include "llama.cpp/common.h"
#include "llamafile/llamafile.h"
#include "llamafile/macros.h"
#include "llamafile/server/log.h"
#include "llamafile/server/model.h"
-#include <algorithm>
+#include "llamafile/vector.h"
+#include "llamafile/version.h"
#include <cassert>
-
-static bool
-vector_starts_with(const std::vector<llama_token>& sequence,
- const std::vector<llama_token>& prefix)
-{
- if (prefix.size() > sequence.size())
- return false;
- return std::equal(prefix.begin(), prefix.end(), sequence.begin());
-}
+#include <cosmo.h>
static int
ctx_size(void)
@@ -41,6 +35,20 @@ ctx_size(void)
return FLAG_ctx_size;
}
+static std::string
+generate_system_fingerprint(const llama_context_params* cparams)
+{
+ uint64_t h = 0;
+ h ^= __fnv(LLAMAFILE_VERSION_STRING, sizeof(LLAMAFILE_VERSION_STRING));
+ h ^= __fnv(cparams, sizeof(*cparams));
+ std::string b = "fp_";
+ for (int j = 0; j < 64 / 5; ++j) {
+ b += "abcdefghijklmnopqrstuvwxyz012345"[h & 31];
+ h >>= 5;
+ }
+ return b;
+}
+
Slot::Slot()
{
dll_init(&elem_);
@@ -60,7 +68,7 @@ Slot::start()
cparams.embeddings = false;
cparams.embeddings_only = false;
cparams.logits_all = false;
- cparams.seed = _rand64();
+ cparams.seed = 12345;
cparams.n_ctx = ctx_size();
cparams.n_batch = FLAG_batch;
cparams.n_ubatch = FLAG_ubatch;
@@ -79,8 +87,10 @@ Slot::start()
cparams.type_k = GGML_TYPE_F16;
cparams.type_v = GGML_TYPE_F16;
cparams.flash_attn = FLAG_flash_attn;
- ctx_ = llama_new_context_with_model(g_model, cparams);
- return ctx_ != nullptr;
+ system_fingerprint_ = generate_system_fingerprint(&cparams);
+ if (!(ctx_ = llama_new_context_with_model(g_model, cparams)))
+ return false;
+ return true;
}
int
diff --git a/llamafile/server/slot.h b/llamafile/server/slot.h
index a95546dd..e07d6f1d 100644
--- a/llamafile/server/slot.h
+++ b/llamafile/server/slot.h
@@ -31,6 +31,7 @@ struct Slot
llama_context* ctx_ = nullptr;
timespec last_used_ = timespec_zero;
std::vector<llama_token> history_;
+ std::string system_fingerprint_;
Slot();
~Slot();
diff --git a/llamafile/server/v1_chat_completions.cpp b/llamafile/server/v1_chat_completions.cpp
index 70bf83fc..f806d62d 100644
--- a/llamafile/server/v1_chat_completions.cpp
+++ b/llamafile/server/v1_chat_completions.cpp
@@ -24,8 +24,10 @@
#include "llama.cpp/llama.h"
#include "llama.cpp/sampling.h"
+#include "llamafile/llama.h"
#include "llamafile/macros.h"
#include "llamafile/string.h"
+#include "llamafile/vector.h"
#include "cleanup.h"
#include "fastjson.h"
@@ -52,30 +54,42 @@ struct V1ChatCompletionParams
void add_stop(const std::string& text)
{
- stop.emplace_back(llama_tokenize(g_model, text, false, false));
+ stop.emplace_back(
+ llama_tokenize(g_model, text, DONT_ADD_SPECIAL, DONT_PARSE_SPECIAL));
+ }
+
+ bool should_stop(const std::vector<llama_token>& history)
+ {
+ for (const auto& suffix : stop)
+ if (vector_ends_with(history, suffix))
+ return true;
+ return false;
}
};
-struct V1ChatCompletionResponse
+struct V1ChatCompletionState
{
std::string prompt;
std::vector<llama_token> tokens;
+ std::string piece;
+};
+
+struct V1ChatCompletionResponse
+{
std::string content;
Json json;
};
-static bool
-is_legal_role(const std::string_view& role)
+static void
+cleanup_params(void* arg)
{
- return role == "system" || //
- role == "user" || //
- role == "assistant";
+ delete (V1ChatCompletionParams*)arg;
}
static void
-cleanup_params(void* arg)
+cleanup_state(void* arg)
{
- delete (V1ChatCompletionParams*)arg;
+ delete (V1ChatCompletionState*)arg;
}
static void
@@ -96,6 +110,14 @@ cleanup_slot(void* arg)
delete (Slot*)arg;
}
+static bool
+is_legal_role(const std::string_view& role)
+{
+ return role == "system" || //
+ role == "user" || //
+ role == "assistant";
+}
+
static std::string
generate_id()
{
@@ -155,26 +177,24 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)
return send_error(400, "JSON body must be an object");
// fields openai documents that we don't support yet
- if (!json.second["n"].isNull())
- return send_error(400, "OpenAI n field not supported");
if (!json.second["tools"].isNull())
- return send_error(400, "OpenAI tools field not supported");
+ return send_error(400, "OpenAI tools field not supported yet");
if (!json.second["audio"].isNull())
- return send_error(400, "OpenAI audio field not supported");
+ return send_error(400, "OpenAI audio field not supported yet");
if (!json.second["logprobs"].isNull())
- return send_error(400, "OpenAI logprobs field not supported");
+ return send_error(400, "OpenAI logprobs field not supported yet");
if (!json.second["functions"].isNull())
- return send_error(400, "OpenAI functions field not supported");
+ return send_error(400, "OpenAI functions field not supported yet");
if (!json.second["modalities"].isNull())
- return send_error(400, "OpenAI modalities field not supported");
+ return send_error(400, "OpenAI modalities field not supported yet");
if (!json.second["tool_choice"].isNull())
- return send_error(400, "OpenAI tool_choice field not supported");
+ return send_error(400, "OpenAI tool_choice field not supported yet");
if (!json.second["top_logprobs"].isNull())
- return send_error(400, "OpenAI top_logprobs field not supported");
+ return send_error(400, "OpenAI top_logprobs field not supported yet");
if (!json.second["function_call"].isNull())
- return send_error(400, "OpenAI function_call field not supported");
+ return send_error(400, "OpenAI function_call field not supported yet");
if (!json.second["parallel_tool_calls"].isNull())
- return send_error(400, "parallel_tool_calls field not supported");
+ return send_error(400, "parallel_tool_calls field not supported yet");
// model: string
Json& model = json.second["model"];
@@ -186,6 +206,8 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)
if (!json.second["messages"].isArray())
return send_error(400, "JSON missing messages array");
std::vector<Json>& messages = json.second["messages"].getArray();
+ if (messages.empty())
+ return send_error(400, "JSON messages array is empty");
for (Json& message : messages) {
if (!message.isObject())
return send_error(400, "messages array must hold objects");
@@ -200,6 +222,20 @@ Client::get_v1_chat_completions_params(V1ChatCompletionParams* params)
std::move(message["content"].getString()));
}
+ // n: integer|null
+ //
+ // How many chat completion choices to generate for each input
+ // message. Note that you will be charged based on the number of
+ // generated tokens across all of the choices. Keep n as 1 to
+ // minimize costs.
+ Json& n = json.second["n"];
+ if (!n.isNull()) {
+ if (!n.isLong())
+ return send_error(400, "n field must be integer");
+ if (n.getLong() != 1)
+ return send_error(400, "n field must be 1 if specified");
+ }
+
// stream: bool|null
//
// If set, partial message deltas will be sent, like in ChatGPT.
@@ -404,14 +440,24 @@ Client::v1_chat_completions()
if (!get_v1_chat_completions_params(params))
return false;
- // create response object
+ // create state and response objects
+ V1ChatCompletionState* state = new V1ChatCompletionState;
+ defer_cleanup(cleanup_state, state);
V1ChatCompletionResponse* response = new V1ChatCompletionResponse;
defer_cleanup(cleanup_response, response);
// turn text into tokens
- response->prompt =
- llama_chat_apply_template(g_model, "", params->messages, true);
- response->tokens = llama_tokenize(g_model, response->prompt, true, false);
+ state->prompt =
+ llama_chat_apply_template(g_model, "", params->messages, ADD_ASSISTANT);
+ state->tokens =
+ llama_tokenize(g_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 (state->tokens.empty() || state->tokens[0] != bos)
+ state->tokens.insert(state->tokens.begin(), bos);
+ }
// find appropriate slot
Slot* slot;
@@ -424,7 +470,7 @@ Client::v1_chat_completions()
defer_cleanup(cleanup_slot, slot);
// sanity check
- if (response->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
@@ -434,7 +480,7 @@ Client::v1_chat_completions()
defer_cleanup(cleanup_sampler, sampler);
// prefill time
- if (!slot->prefill(response->tokens)) {
+ if (!slot->prefill(state->tokens)) {
SLOG("slot prefill failed");
return send_error(500, "llama_decode prefill failed");
}
@@ -443,6 +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["choices"].setArray();
Json& choice = response->json["choices"][0];
choice.setObject();
@@ -469,31 +516,44 @@ Client::v1_chat_completions()
// prediction time
int completion_tokens = 0;
const char* finish_reason = "length";
- while (params->max_tokens < 0 || completion_tokens < params->max_tokens) {
- llama_token id = llama_sampling_sample(sampler, slot->ctx_, NULL);
- llama_sampling_accept(sampler, slot->ctx_, id, true);
- if (llama_token_is_eog(g_model, id)) {
- finish_reason = "stop";
+ for (;;) {
+ if (params->max_tokens >= 0 &&
+ completion_tokens >= params->max_tokens) {
+ slot->eval_token(llamafile_token_eot(g_model));
break;
}
+ llama_token id = llama_sampling_sample(sampler, slot->ctx_, NULL);
+ llama_sampling_accept(sampler, slot->ctx_, id, APPLY_GRAMMAR);
++completion_tokens;
- std::string piece = llama_token_to_piece(slot->ctx_, id, false);
- if (params->stream) {
- char* p = append_http_response_message(obuf.p, 200);
- choice["delta"].setObject();
- choice["delta"]["content"].setString(piece);
- response->json["created"].setLong(timespec_real().tv_sec);
- response->content = make_event(response->json);
- choice.getObject().erase("delta");
- if (!send_response_chunk(response->content))
- return false;
- } else {
- response->content += piece;
- }
if (!slot->eval_token(id)) {
SLOG("ran out of context window");
break;
}
+ if (llama_token_is_eog(g_model, id)) {
+ finish_reason = "stop";
+ break;
+ }
+ if (params->should_stop(slot->history_)) {
+ slot->eval_token(llamafile_token_eot(g_model));
+ finish_reason = "stop";
+ break;
+ }
+ state->piece =
+ 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);
+ choice["delta"].setObject();
+ choice["delta"]["content"].setString(state->piece);
+ response->json["created"].setLong(timespec_real().tv_sec);
+ response->content = make_event(response->json);
+ choice.getObject().erase("delta");
+ if (!send_response_chunk(response->content))
+ return false;
+ } else {
+ response->content += state->piece;
+ }
+ }
}
choice["finish_reason"].setString(finish_reason);
@@ -510,17 +570,17 @@ Client::v1_chat_completions()
} else {
Json& usage = response->json["usage"];
usage.setObject();
- usage["prompt_tokens"].setLong(response->tokens.size());
+ usage["prompt_tokens"].setLong(state->tokens.size());
usage["completion_tokens"].setLong(completion_tokens);
- usage["total_tokens"].setLong(completion_tokens +
- response->tokens.size());
+ usage["total_tokens"].setLong(completion_tokens + state->tokens.size());
choice["message"].setObject();
choice["message"]["role"].setString("assistant");
choice["message"]["content"].setString(std::move(response->content));
response->json["created"].setLong(timespec_real().tv_sec);
char* p = append_http_response_message(obuf.p, 200);
p = stpcpy(p, "Content-Type: application/json\r\n");
- response->content = response->json.toString();
+ response->content = response->json.toStringPretty();
+ response->content += '\n';
return send_response(obuf.p, p, response->content);
}
}
diff --git a/llamafile/string.cpp b/llamafile/string.cpp
index ee0da99a..04cacb57 100644
--- a/llamafile/string.cpp
+++ b/llamafile/string.cpp
@@ -17,12 +17,13 @@
#include "string.h"
+#include <cctype>
#include <cosmo.h>
-#include <ctype.h>
+#include <cstdio>
namespace lf {
-std::string tolower(const std::string_view &s) {
+std::string tolower(const std::string_view s) {
std::string b;
for (char c : s)
b += std::tolower(c);
@@ -55,6 +56,16 @@ std::string format(const char *fmt, ...) {
return res;
}
+std::string join(const std::vector<std::string> &vec, const std::string_view &delim) {
+ std::string result;
+ for (size_t i = 0; i < vec.size(); i++) {
+ result += vec[i];
+ if (i < vec.size() - 1)
+ result += delim;
+ }
+ return result;
+}
+
std::string basename(const std::string_view path) {
size_t i, e;
if ((e = path.size())) {
@@ -112,4 +123,31 @@ std::string resolve(const std::string_view lhs, const std::string_view rhs) {
return res;
}
+// replaces multiple isspace() with one space and trims result
+std::string collapse(const std::string_view input) {
+ size_t start = 0;
+ while (start < input.length() && std::isspace(input[start]))
+ ++start;
+ if (start == input.length())
+ return "";
+ size_t end = input.length() - 1;
+ while (end > start && std::isspace(input[end]))
+ --end;
+ std::string result;
+ result.reserve(end - start + 1);
+ bool lastWasSpace = false;
+ for (size_t i = start; i <= end; ++i) {
+ if (std::isspace(input[i])) {
+ if (!lastWasSpace) {
+ result += ' ';
+ lastWasSpace = true;
+ }
+ } else {
+ result += input[i];
+ lastWasSpace = false;
+ }
+ }
+ return result;
+}
+
} // namespace lf
diff --git a/llamafile/string.h b/llamafile/string.h
index cc99d4a4..0aaf9a65 100644
--- a/llamafile/string.h
+++ b/llamafile/string.h
@@ -17,15 +17,18 @@
#pragma once
#include <string>
+#include <vector>
namespace lf {
std::string basename(const std::string_view);
+std::string collapse(const std::string_view);
std::string dirname(const std::string_view);
std::string extname(const std::string_view);
std::string format(const char *, ...) __attribute__((format(printf, 1, 2)));
+std::string join(const std::vector<std::string> &, const std::string_view &);
std::string resolve(const std::string_view, const std::string_view);
-std::string tolower(const std::string_view &);
+std::string tolower(const std::string_view);
void append_wchar(std::string *, wchar_t);
} // namespace lf
diff --git a/llamafile/vector.h b/llamafile/vector.h
new file mode 100644
index 00000000..a167bb4d
--- /dev/null
+++ b/llamafile/vector.h
@@ -0,0 +1,34 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// Copyright 2024 Mozilla Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#pragma once
+#include <algorithm>
+#include <vector>
+
+template <typename T>
+bool vector_starts_with(const std::vector<T> &sequence, const std::vector<T> &prefix) {
+ if (prefix.size() > sequence.size())
+ return false;
+ return std::equal(prefix.begin(), prefix.end(), sequence.begin());
+}
+
+template <typename T>
+bool vector_ends_with(const std::vector<T> &sequence, const std::vector<T> &suffix) {
+ if (suffix.size() > sequence.size())
+ return false;
+ return std::equal(sequence.rbegin(), sequence.rend(), suffix.rbegin());
+}