Skip to content

Distribute and run LLMs with a single file.

Reclaim llama_decode() memory on cancelation

Justine Tunney0d62d0576aba
diff --git a/llama.cpp/ggml.c b/llama.cpp/ggml.c
index 05d55d1e..5826a604 100644
--- a/llama.cpp/ggml.c
+++ b/llama.cpp/ggml.c
@@ -18511,7 +18511,7 @@ typedef int ggml_lock_t;
typedef pthread_t ggml_thread_t;
-#define ggml_thread_create llamafile_thread_create
+#define ggml_thread_create llamafile_thread_create // [jart]
#define ggml_thread_join pthread_join
#else
@@ -18934,7 +18934,7 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {
memory_order_relaxed);
#endif
- int ct;
+ int ct; // [jart] enable instant math cancelation
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &ct);
pthread_testcancel();
@@ -18942,7 +18942,7 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {
if (cplan->abort_callback && cplan->abort_callback(cplan->abort_callback_data)) {
state->shared->node_n += 1;
state->ec = GGML_STATUS_ABORTED;
- pthread_setcanceltype(ct, 0);
+ pthread_setcanceltype(ct, 0); // [jart]
return 0;
}
@@ -19079,7 +19079,7 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {
}
}
- pthread_setcanceltype(ct,0);
+ pthread_setcanceltype(ct, 0); // [jart]
#ifdef LLAMAFILE_SYNC_REPORT
g_sync.work_cycles += rdtsc() - g_sync.stamp;
@@ -19355,6 +19355,10 @@ enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cpl
}
}
+ // if we've been canceled then must
+ // die before launching the threads
+ pthread_testcancel(); // [jart]
+
#ifdef LLAMAFILE_SYNC_REPORT
fprintf(stderr, "\n");
#endif
diff --git a/llama.cpp/llama.cpp b/llama.cpp/llama.cpp
index 55316d3e..ffb08ff8 100644
--- a/llama.cpp/llama.cpp
+++ b/llama.cpp/llama.cpp
@@ -11134,6 +11134,15 @@ static void llama_graph_compute(
// fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
}
+struct llama_decoder {
+ std::vector<llama_pos> pos;
+ std::vector<int32_t> n_seq_id;
+ std::vector<llama_seq_id *> seq_id_arr;
+ std::vector<std::vector<llama_seq_id>> seq_id;
+ llama_decoder() = default;
+ ~llama_decoder() = default;
+};
+
// decode a batch of tokens by evaluating the transformer
//
// - lctx: llama context
@@ -11145,7 +11154,8 @@ static void llama_graph_compute(
//
static int llama_decode_internal(
llama_context & lctx,
- llama_batch batch_all) { // TODO: rename back to batch
+ llama_batch batch_all,
+ llama_decoder * decoder) { // TODO: rename back to batch
const uint32_t n_tokens_all = batch_all.n_tokens;
@@ -11179,10 +11189,7 @@ static int llama_decode_internal(
const auto n_ubatch = cparams.n_ubatch;
- std::vector<llama_pos> pos;
- std::vector<int32_t> n_seq_id;
- std::vector<llama_seq_id *> seq_id_arr;
- std::vector<std::vector<llama_seq_id>> seq_id;
+ // TODO(jart): these need to be cleanup up on thread cancelation
// count outputs
if (batch_all.logits) {
@@ -11258,27 +11265,27 @@ static int llama_decode_internal(
// helpers for smoother batch API transition
// after deprecating the llama_eval calls, these will be removed
if (u_batch.pos == nullptr) {
- pos.resize(n_tokens);
+ decoder->pos.resize(n_tokens);
for (uint32_t i = 0; i < n_tokens; i++) {
- pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
+ decoder->pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
}
- u_batch.pos = pos.data();
+ u_batch.pos = decoder->pos.data();
}
if (u_batch.seq_id == nullptr) {
- n_seq_id.resize(n_tokens);
- seq_id.resize(n_tokens);
- seq_id_arr.resize(n_tokens);
+ decoder->n_seq_id.resize(n_tokens);
+ decoder->seq_id.resize(n_tokens);
+ decoder->seq_id_arr.resize(n_tokens);
for (uint32_t i = 0; i < n_tokens; i++) {
- n_seq_id[i] = 1;
- seq_id[i].resize(1);
- seq_id[i][0] = u_batch.all_seq_id;
- seq_id_arr[i] = seq_id[i].data();
+ decoder->n_seq_id[i] = 1;
+ decoder->seq_id[i].resize(1);
+ decoder->seq_id[i][0] = u_batch.all_seq_id;
+ decoder->seq_id_arr[i] = decoder->seq_id[i].data();
}
- u_batch.n_seq_id = n_seq_id.data();
- u_batch.seq_id = seq_id_arr.data();
+ u_batch.n_seq_id = decoder->n_seq_id.data();
+ u_batch.seq_id = decoder->seq_id_arr.data();
}
// non-causal masks do not use the KV cache
@@ -17270,7 +17277,21 @@ void llama_batch_free(struct llama_batch batch) {
int32_t llama_decode(
struct llama_context * ctx,
struct llama_batch batch) {
- const int ret = llama_decode_internal(*ctx, batch);
+ int ret;
+
+ // [jart] pthread_cancel() safety
+ llama_decoder * decoder = new llama_decoder;
+ pthread_cleanup_push(
+ [](void* arg) {
+ llama_decoder * decoder = (llama_decoder*)arg;
+ delete decoder;
+ },
+ decoder);
+
+ ret = llama_decode_internal(*ctx, batch, decoder);
+
+ pthread_cleanup_pop(true);
+
if (ret < 0) {
LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
}
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 9245f03e..095acaf4 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -51,6 +51,7 @@ 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/dll3.h b/llamafile/dll3.h
index 29f59241..6c414760 100644
--- a/llamafile/dll3.h
+++ b/llamafile/dll3.h
@@ -21,6 +21,12 @@
extern "C" {
#endif
+/**
+ * Double linked list.
+ *
+ * This is the same thing as `Dll` except it does not need `offsetof()`,
+ * which can't be used for non-POD C++ object types.
+ */
struct Dll3 {
struct Dll3 *next;
struct Dll3 *prev;
diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cpp
index 74dd5a58..78ec9c69 100644
--- a/llamafile/server/client.cpp
+++ b/llamafile/server/client.cpp
@@ -38,7 +38,8 @@
using namespace ctl;
-Client::Client() : ibuf(FLAG_http_ibuf_size), obuf(FLAG_http_obuf_size)
+Client::Client()
+ : cleanups(nullptr), ibuf(FLAG_http_ibuf_size), obuf(FLAG_http_obuf_size)
{
InitHttpMessage(&msg, 0);
url.params.p = nullptr;
@@ -59,9 +60,21 @@ Client::close()
return rc;
}
+void
+Client::cleanup()
+{
+ Cleanup* clean;
+ while ((clean = cleanups)) {
+ cleanups = clean->next;
+ clean->func(clean->arg);
+ delete clean;
+ }
+}
+
void
Client::clear()
{
+ cleanup();
free(url_memory);
url_memory = nullptr;
free(params_memory);
@@ -73,6 +86,16 @@ Client::clear()
unread = 0;
}
+void
+Client::defer_cleanup(void (*func)(void*), void* arg)
+{
+ Cleanup* clean = new Cleanup;
+ clean->next = cleanups;
+ clean->func = func;
+ clean->arg = arg;
+ cleanups = clean;
+}
+
void
Client::run()
{
@@ -195,6 +218,7 @@ Client::transport()
bool
Client::send_error(int code, const char* reason)
{
+ cleanup();
if (!reason)
reason = GetHttpReason(code);
LOG("error %d %s", code, reason);
@@ -230,6 +254,8 @@ Client::start_response(char* p, int code, const char* reason)
bool
Client::send_response(char* p0, char* p, string_view content)
{
+ cleanup();
+
// append date header
tm tm;
p = stpcpy(p, "Date: ");
diff --git a/llamafile/server/client.h b/llamafile/server/client.h
index 8f2c3b40..5da84bb7 100644
--- a/llamafile/server/client.h
+++ b/llamafile/server/client.h
@@ -36,6 +36,13 @@
#define HeaderEqualCase(H, S) \
SlicesEqualCase(S, strlen(S), HeaderData(H), HeaderLength(H))
+struct Cleanup
+{
+ Cleanup* next;
+ void (*func)(void*);
+ void* arg;
+};
+
struct Client
{
int fd = -1;
@@ -47,6 +54,7 @@ struct Client
char* url_memory = nullptr;
char* params_memory = nullptr;
ctl::string_view payload;
+ Cleanup* cleanups;
Buffer ibuf;
Buffer obuf;
@@ -55,6 +63,7 @@ struct Client
void run();
int close();
void clear();
+ void cleanup();
bool transport() __wur;
bool synchronize() __wur;
bool read_payload() __wur;
@@ -62,6 +71,7 @@ struct Client
bool read_content() __wur;
bool send_continue() __wur;
bool send(const ctl::string_view) __wur;
+ void defer_cleanup(void (*)(void*), void*);
char* start_response(char*, int, const char* = nullptr);
bool send_error(int, const char* = nullptr) __wur;
bool send_response(char*, char*, const ctl::string_view) __wur;
diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cpp
index 456c2efc..685190d1 100644
--- a/llamafile/server/embedding.cpp
+++ b/llamafile/server/embedding.cpp
@@ -28,6 +28,8 @@
#include "log.h"
#include "utils.h"
+extern llama_model* g_model;
+
void
normalize_embeddings(const float* inp, float* out, int n)
{
@@ -50,14 +52,32 @@ add_token_to_batch(struct llama_batch& batch,
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) {
+ 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++;
}
+void
+cleanup_llama_batch(void* arg)
+{
+ llama_batch* batch = (llama_batch*)arg;
+ llama_batch_free(*batch);
+ delete batch;
+}
+
+void
+cleanup_token_vector(void* arg)
+{
+ delete (ctl::vector<llama_token>*)arg;
+}
+
+void
+cleanup_llama_context(void* arg)
+{
+ llama_free((llama_context*)arg);
+}
+
bool
Client::embedding()
{
@@ -99,28 +119,25 @@ Client::embedding()
timespec started = timespec_real();
// turn text into tokens
- extern llama_model* g_model;
- ctl::vector<llama_token> toks(input.size() + 16);
+ auto toks = new ctl::vector<llama_token>(input.size() + 16);
+ defer_cleanup(cleanup_token_vector, toks);
int count = llama_tokenize(g_model,
input.data(),
input.size(),
- &toks[0],
- toks.size(),
+ &(*toks)[0],
+ toks->size(),
add_special,
parse_special);
if (count < 0) {
LOG("llama_tokenize failed");
return send_error(405);
}
- toks.resize(count);
- LOG("toks.size() = %d", count);
+ toks->resize(count);
// truncate if exceeds model context size
const int n_ctx_train = llama_n_ctx_train(g_model);
- LOG("n_ctx_train = %d", n_ctx_train);
if (count > n_ctx_train)
count = n_ctx_train;
- LOG("count = %d", count);
// initialize context
llama_context_params cparams = {};
@@ -144,36 +161,33 @@ Client::embedding()
LOG("llama_new_context_with_model failed");
return send_error(500);
}
+ defer_cleanup(cleanup_llama_context, ctx);
// initialize batch
const int n_embd = llama_n_embd(g_model);
- struct llama_batch batch = llama_batch_init(count, 0, 1);
+ llama_batch* batch = new llama_batch;
+ *batch = llama_batch_init(count, 0, 1);
+ defer_cleanup(cleanup_llama_batch, batch);
for (size_t i = 0; i < count; ++i)
- add_token_to_batch(batch, toks[i], i, { 0 }, i == count - 1);
+ add_token_to_batch(*batch, (*toks)[i], i, { 0 }, i == count - 1);
// inference time
- if (llama_decode(ctx, batch) < 0) {
+ if (llama_decode(ctx, *batch) < 0) {
LOG("llama_decode failed");
- llama_free(ctx);
- llama_batch_free(batch);
return send_error(500);
}
ctl::vector<float> embeddings(n_embd, 0);
- for (int i = 0; i < batch.n_tokens; i++) {
- if (!batch.logits[i])
+ for (int i = 0; i < batch->n_tokens; i++) {
+ if (!batch->logits[i])
continue;
const float* embd = llama_get_embeddings_ith(ctx, i);
if (!embd) {
LOG("llama_get_embeddings_ith failed");
- llama_free(ctx);
- llama_batch_free(batch);
return send_error(500);
}
normalize_embeddings(
- embd, &embeddings[0] + batch.seq_id[i][0] * n_embd, n_embd);
+ embd, &embeddings[0] + batch->seq_id[i][0] * n_embd, n_embd);
}
- llama_free(ctx);
- llama_batch_free(batch);
// serialize tokens to json
char* p = obuf.p;
@@ -185,7 +199,7 @@ Client::embedding()
p = encode_bool(p, parse_special);
p = stpcpy(p, ",\n");
p = stpcpy(p, " \"tokens_provided\": ");
- p = encode_json(p, toks.size());
+ p = encode_json(p, toks->size());
p = stpcpy(p, ",\n");
p = stpcpy(p, " \"tokens_used\": ");
p = encode_json(p, count);
diff --git a/llamafile/thread.cpp b/llamafile/thread.cpp
index 2eed2383..07ff55b5 100644
--- a/llamafile/thread.cpp
+++ b/llamafile/thread.cpp
@@ -89,12 +89,10 @@ static void on_parent_exit(Parent *parent) {
dll3_remove(&parent->children, e);
parent->unlock();
parent->unref(); // remove child's reference to parent
- if (child->thread) {
- pthread_cancel(child->thread);
- if (child->detach_state == PTHREAD_CREATE_JOINABLE)
- if (pthread_join(child->thread, 0))
- __builtin_trap();
- }
+ pthread_cancel(child->thread);
+ if (child->detach_state == PTHREAD_CREATE_JOINABLE)
+ if (pthread_join(child->thread, 0))
+ __builtin_trap();
child->unref(); // remove parent's reference to child
parent->lock();
}