Skip to content

Distribute and run LLMs with a single file.

Create /embedding endpoint in new server

Justine Tunney1346ef4010f2
diff --git a/llama.cpp/ggml.c b/llama.cpp/ggml.c
index 49362443..ac003c45 100644
--- a/llama.cpp/ggml.c
+++ b/llama.cpp/ggml.c
@@ -41,6 +41,7 @@ SOFTWARE.");
#include "llamafile/log.h"
#include "llamafile/debug.h"
#include "llamafile/sgemm.h"
+#include "llamafile/thread.h"
#include <alloca.h>
#include <assert.h>
@@ -1574,7 +1575,7 @@ int ggml_delay(int backoff) {
}
backoff++;
} else {
- sched_yield();
+ pthread_yield_np();
}
return backoff;
}
@@ -18561,7 +18562,7 @@ typedef int ggml_lock_t;
typedef pthread_t ggml_thread_t;
-#define ggml_thread_create pthread_create
+#define ggml_thread_create llamafile_thread_create
#define ggml_thread_join pthread_join
#else
@@ -18975,8 +18976,6 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {
}
#endif
- pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
-
#ifdef LLAMAFILE_SYNC_REPORT
g_sync.stamp = rdtsc();
unsigned long old = 0;
@@ -18986,10 +18985,15 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {
memory_order_relaxed);
#endif
+ int ct;
+ pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &ct);
+ pthread_testcancel();
+
while (true) {
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);
return 0;
}
@@ -19126,6 +19130,8 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {
}
}
+ pthread_setcanceltype(ct,0);
+
#ifdef LLAMAFILE_SYNC_REPORT
g_sync.work_cycles += rdtsc() - g_sync.stamp;
double total = g_sync.work_cycles + g_sync.wait_cycles;
diff --git a/llama.cpp/ggml.h b/llama.cpp/ggml.h
index cdd663b3..f15f6867 100644
--- a/llama.cpp/ggml.h
+++ b/llama.cpp/ggml.h
@@ -262,7 +262,7 @@
if (!(x)) { \
fflush(stdout); \
fprintf(stderr, "GGML_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
- exit(1); \
+ __builtin_trap(); \
} \
} while (0)
diff --git a/llama.cpp/llama.cpp b/llama.cpp/llama.cpp
index 9bc527d0..dc467c5c 100644
--- a/llama.cpp/llama.cpp
+++ b/llama.cpp/llama.cpp
@@ -56,6 +56,7 @@
#include <unistd.h>
#include <sys/mman.h>
#include <sys/resource.h>
+#include <ctl/vector.h>
#define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((__format__(__gnu_printf__, __VA_ARGS__)))
@@ -1629,6 +1630,7 @@ struct llama_cparams {
float defrag_thold;
bool embeddings;
+ bool embeddings_only;
bool causal_attn;
bool offload_kqv;
bool flash_attn;
@@ -1908,7 +1910,7 @@ struct llama_model {
layer_buft buft_input;
layer_buft buft_output;
- std::vector<layer_buft> buft_layer;
+ ctl::vector<layer_buft> buft_layer;
// contexts where the model tensors metadata is stored
std::vector<struct ggml_context *> ctxs;
@@ -2240,6 +2242,7 @@ static bool llama_kv_cache_init(
}
// allocate tensors and initialize the buffers to avoid NaNs in the padding
+ // BOOP 2709 us
for (auto it : ctx_map) {
ggml_backend_buffer_type_t buft = it.first;
ggml_context * ctx = it.second;
@@ -2248,7 +2251,8 @@ static bool llama_kv_cache_init(
LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
return false;
}
- ggml_backend_buffer_clear(buf, 0);
+ if (!cparams.embeddings_only)
+ ggml_backend_buffer_clear(buf, 0);
LLAMA_LOG_INFO("%s: %10s KV buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
cache.bufs.push_back(buf);
}
@@ -4611,13 +4615,15 @@ static bool llm_load_tensors(
}
#endif
+ n_gpu_layers = std::min(n_gpu_layers, (int)hparams.n_layer); // [jart]
+ n_gpu_layers = std::max(n_gpu_layers, 0); // [jart]
+
model.split_mode = split_mode;
model.main_gpu = main_gpu;
model.n_gpu_layers = n_gpu_layers;
const int64_t n_layer = hparams.n_layer;
- const int n_gpu = std::min(n_gpu_layers, int(n_layer)); // [jart] prevent vector overflow
- const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu, (int64_t) 0);
+ const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
bool use_mmap_buffer = true;
// there is very little benefit to offloading the input layer, so always keep it on the CPU
@@ -11122,7 +11128,7 @@ static int llama_decode_internal(
const uint32_t n_tokens_all = batch_all.n_tokens;
if (n_tokens_all == 0) {
- LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
+ LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
return -1;
}
@@ -15231,6 +15237,7 @@ struct llama_context_params llama_context_default_params() {
/*.type_v =*/ GGML_TYPE_F16,
/*.logits_all =*/ false,
/*.embeddings =*/ false,
+ /*.embeddings_only =*/ false, // [jart]
/*.offload_kqv =*/ true,
/*.flash_attn =*/ false,
/*.abort_callback =*/ nullptr,
@@ -15408,6 +15415,8 @@ struct llama_context * llama_new_context_with_model(
cparams.offload_kqv = params.offload_kqv;
cparams.flash_attn = params.flash_attn;
cparams.pooling_type = params.pooling_type;
+ cparams.embeddings = params.embeddings;
+ cparams.embeddings_only = params.embeddings_only; // [jart]
cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
@@ -15675,6 +15684,7 @@ if (llamafile_has_metal()) {
pipeline_parallel = false;
}
// #endif
+ // BOOP 1611 us ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel)
ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
if (pipeline_parallel) {
@@ -15688,6 +15698,7 @@ if (llamafile_has_metal()) {
ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
// initialize scheduler with the worst-case graph
+ // BOOP 298 us ggml_backend_sched_reserve(ctx->sched, gf)
if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
llama_free(ctx);
@@ -16112,6 +16123,8 @@ int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
}
void llama_kv_cache_clear(struct llama_context * ctx) {
+ if (ctx->cparams.embeddings_only) // [jart]
+ return;
llama_kv_cache_clear(ctx->kv_self);
}
@@ -17316,7 +17329,7 @@ float * llama_get_embeddings(struct llama_context * ctx) {
// [jart] DO NOT SYNC this function
static float * llama_get_embeddings_ith_fail(int i, std::string reason) {
- LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, reason);
+ LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, reason.c_str());
return nullptr;
}
diff --git a/llama.cpp/llama.h b/llama.cpp/llama.h
index e4b51582..5927f06c 100644
--- a/llama.cpp/llama.h
+++ b/llama.cpp/llama.h
@@ -298,6 +298,7 @@ extern "C" {
// Keep the booleans together to avoid misalignment during copy-by-value.
bool logits_all; // the llama_decode() call computes all logits, not just the last one (DEPRECATED - set llama_batch.logits instead)
bool embeddings; // if true, extract embeddings (together with logits)
+ bool embeddings_only; // if true, extract embeddings (together with logits)
bool offload_kqv; // whether to offload the KQV ops (including the KV cache) to GPU
bool flash_attn; // whether to use flash attention
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 2be033db..9245f03e 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -20,6 +20,7 @@ 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
@@ -49,7 +50,7 @@ o/$(MODE)/llamafile: \
o/$(MODE)/llamafile/zipalign \
o/$(MODE)/llamafile/zipcheck \
o/$(MODE)/llamafile/tokenize \
- o/$(MODE)/llamafile/addnl
+ o/$(MODE)/llamafile/addnl \
################################################################################
# microarchitectures
@@ -116,6 +117,12 @@ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_arm82.o: private TARGET_ARCH += -Xaarch6
################################################################################
# testing
+o/$(MODE)/llamafile/thread_test: \
+ o/$(MODE)/llamafile/thread_test.o \
+ o/$(MODE)/llamafile/thread.o \
+ o/$(MODE)/llamafile/crash.o \
+ o/$(MODE)/llamafile/dll3.o \
+
o/$(MODE)/llamafile/sgemm_sss_test: private LDFLAGS += -fopenmp
o/$(MODE)/llamafile/sgemm_sss_test.o: private CCFLAGS += -fopenmp
o/$(MODE)/llamafile/sgemm_matmul_test: private LDFLAGS += -fopenmp
diff --git a/llamafile/server/crash.cpp b/llamafile/crash.c
similarity index 75%
rename from llamafile/server/crash.cpp
rename to llamafile/crash.c
index afd8305f..5745b051 100644
--- a/llamafile/server/crash.cpp
+++ b/llamafile/crash.c
@@ -1,5 +1,5 @@
-// -*- 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
+// -*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi
//
// Copyright 2024 Mozilla Foundation
//
@@ -15,8 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#include "signals.h"
-#include "utils.h"
+#include "crash.h"
#include <cosmo.h>
#include <ucontext.h>
@@ -29,11 +28,18 @@
#define BP gregs[REG_RBP]
#endif
+char *hexcpy(char *p, unsigned long x) {
+ int k = x ? (__builtin_clzl(x) ^ 63) + 1 : 1;
+ k = (k + 3) & -4;
+ while (k > 0)
+ *p++ = "0123456789abcdef"[(x >> (k -= 4)) & 15];
+ *p = '\0';
+ return p;
+}
+
// returns true if `p` is preceded by x86 call instruction
// this is actually impossible to do but we'll do our best
-int
-is_call(const unsigned char* p)
-{
+int is_call(const unsigned char *p) {
if (p[-5] == 0xe8)
return 5; // call Jvds
if (p[-2] == 0xff && (p[-1] & 070) == 020)
@@ -49,10 +55,10 @@ is_call(const unsigned char* p)
return 0;
}
-char*
-describe_crash(char* buf, size_t len, int sig, siginfo_t* si, void* arg)
-{
- char* p = buf;
+// abashed the devil stood
+// and felt how awful goodness is
+char *describe_crash(char *buf, size_t len, int sig, siginfo_t *si, void *arg) {
+ char *p = buf;
// check minimum length
if (len < 64)
@@ -72,15 +78,15 @@ describe_crash(char* buf, size_t len, int sig, siginfo_t* si, void* arg)
}
// get stack frame daisy chain
- StackFrame pc;
- StackFrame* sf;
- ucontext_t* ctx;
- if ((ctx = (ucontext_t*)arg)) {
+ struct StackFrame pc;
+ struct StackFrame *sf;
+ ucontext_t *ctx;
+ if ((ctx = (ucontext_t *)arg)) {
pc.addr = ctx->uc_mcontext.PC;
- pc.next = (struct StackFrame*)ctx->uc_mcontext.BP;
+ pc.next = (struct StackFrame *)ctx->uc_mcontext.BP;
sf = &pc;
} else {
- sf = (struct StackFrame*)__builtin_frame_address(0);
+ sf = (struct StackFrame *)__builtin_frame_address(0);
}
// describe backtrace
@@ -90,10 +96,8 @@ describe_crash(char* buf, size_t len, int sig, siginfo_t* si, void* arg)
return p;
}
-char*
-describe_backtrace(char* p, size_t len, const StackFrame* sf)
-{
- char* pe = p + len;
+char *describe_backtrace(char *p, size_t len, const struct StackFrame *sf) {
+ char *pe = p + len;
bool gotsome = false;
// show address of each function
@@ -111,7 +115,7 @@ describe_backtrace(char* p, size_t len, const StackFrame* sf)
break;
}
if (p + 16 + 1 < pe) {
- unsigned char* ip = (unsigned char*)sf->addr;
+ unsigned char *ip = (unsigned char *)sf->addr;
#ifdef __x86_64__
// x86 advances the progrem counter before an instruction
// begins executing. return addresses in backtraces shall
diff --git a/llamafile/crash.h b/llamafile/crash.h
new file mode 100644
index 00000000..99922760
--- /dev/null
+++ b/llamafile/crash.h
@@ -0,0 +1,16 @@
+#ifndef LLAMAFILE_CRASH_H_
+#define LLAMAFILE_CRASH_H_
+#include <signal.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct StackFrame;
+
+char *describe_crash(char *, size_t, int, siginfo_t *, void *);
+char *describe_backtrace(char *, size_t, const struct StackFrame *);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* LLAMAFILE_CRASH_H_ */
diff --git a/llamafile/dll3.c b/llamafile/dll3.c
new file mode 100644
index 00000000..f6a185c6
--- /dev/null
+++ b/llamafile/dll3.c
@@ -0,0 +1,87 @@
+// -*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=c 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 "dll3.h"
+
+/**
+ * Makes `succ` and its successors come after `elem`.
+ *
+ * It's required that `elem` and `succ` aren't part of the same list.
+ */
+void dll3_splice_after(struct Dll3 *elem, struct Dll3 *succ) {
+ struct Dll3 *tmp1, *tmp2;
+ tmp1 = elem->next;
+ tmp2 = succ->prev;
+ elem->next = succ;
+ succ->prev = elem;
+ tmp2->next = tmp1;
+ tmp1->prev = tmp2;
+}
+
+/**
+ * Removes item from doubly-linked list.
+ *
+ * @param list is a doubly-linked list, where `!*list` means empty
+ */
+void dll3_remove(struct Dll3 **list, struct Dll3 *elem) {
+ if (*list == elem) {
+ if ((*list)->prev == *list) {
+ *list = 0;
+ } else {
+ *list = (*list)->prev;
+ }
+ }
+ elem->next->prev = elem->prev;
+ elem->prev->next = elem->next;
+ elem->next = elem;
+ elem->prev = elem;
+}
+
+/**
+ * Inserts items into list, at the beginning.
+ *
+ * The resulting list will start with `elem`, followed by other items in
+ * `elem`, followed by the items previously in `*list`.
+ *
+ * @param list is a doubly-linked list, where `!*list` means empty
+ * @param elem must not be a member of `list`, or null for no-op
+ */
+void dll3_make_first(struct Dll3 **list, struct Dll3 *elem) {
+ if (elem) {
+ if (!*list) {
+ *list = elem->prev;
+ } else {
+ dll3_splice_after(*list, elem);
+ }
+ }
+}
+
+/**
+ * Inserts items into list, at the end.
+ *
+ * The resulting `*list` will end with `elem`, preceded by the other
+ * items in `elem`, preceded by the items previously in `*list`.
+ *
+ * @param list is a doubly-linked list, where `!*list` means empty
+ * @param elem must not be a member of `list`, or null for no-op
+ */
+void dll3_make_last(struct Dll3 **list, struct Dll3 *elem) {
+ if (elem) {
+ dll3_make_first(list, elem->next);
+ *list = elem;
+ }
+}
diff --git a/llamafile/dll3.h b/llamafile/dll3.h
new file mode 100644
index 00000000..29f59241
--- /dev/null
+++ b/llamafile/dll3.h
@@ -0,0 +1,76 @@
+// -*- 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
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct Dll3 {
+ struct Dll3 *next;
+ struct Dll3 *prev;
+ void *container;
+};
+
+static inline void dll3_init(struct Dll3 *e, void *container) {
+ e->next = e;
+ e->prev = e;
+ e->container = container;
+}
+
+static inline int dll3_is_alone(struct Dll3 *e) {
+ return e->next == e && e->prev == e;
+}
+
+static inline int dll3_is_empty(struct Dll3 *list) {
+ return !list;
+}
+
+static inline struct Dll3 *dll3_last(struct Dll3 *list) {
+ return list;
+}
+
+static inline struct Dll3 *dll3_first(struct Dll3 *list) {
+ struct Dll3 *first = 0;
+ if (list)
+ first = list->next;
+ return first;
+}
+
+static inline struct Dll3 *dll3_next(struct Dll3 *list, struct Dll3 *e) {
+ struct Dll3 *next = 0;
+ if (e != list)
+ next = e->next;
+ return next;
+}
+
+static inline struct Dll3 *dll3_prev(struct Dll3 *list, struct Dll3 *e) {
+ struct Dll3 *prev = 0;
+ if (e != list->next)
+ prev = e->prev;
+ return prev;
+}
+
+void dll3_remove(struct Dll3 **, struct Dll3 *);
+void dll3_make_last(struct Dll3 **, struct Dll3 *);
+void dll3_make_first(struct Dll3 **, struct Dll3 *);
+void dll3_splice_after(struct Dll3 *, struct Dll3 *);
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/llamafile/flags.cpp b/llamafile/flags.cpp
index 07a6ffdf..0569902f 100644
--- a/llamafile/flags.cpp
+++ b/llamafile/flags.cpp
@@ -43,6 +43,8 @@ int FLAG_batch = 2048;
int FLAG_ctx = 512;
int FLAG_flash_attn = false;
int FLAG_gpu = 0;
+int FLAG_http_ibuf_size = 1024 * 1024;
+int FLAG_http_obuf_size = 1024 * 1024;
int FLAG_keepalive = 5;
int FLAG_main_gpu = 0;
int FLAG_n_gpu_layers = -1;
@@ -130,6 +132,23 @@ void llamafile_get_flags(int argc, char **argv) {
continue;
}
+ //////////////////////////////////////////////////////////////////////
+ // http server flags
+
+ if (!strcmp(flag, "--http-ibuf-size")) {
+ if (i == argc)
+ missing("--http-ibuf-size");
+ FLAG_http_ibuf_size = atoi(argv[i++]);
+ continue;
+ }
+
+ if (!strcmp(flag, "--http-obuf-size")) {
+ if (i == argc)
+ missing("--http-obuf-size");
+ FLAG_http_obuf_size = atoi(argv[i++]);
+ continue;
+ }
+
//////////////////////////////////////////////////////////////////////
// model flags
diff --git a/llamafile/latency.h b/llamafile/latency.h
new file mode 100644
index 00000000..7a02268a
--- /dev/null
+++ b/llamafile/latency.h
@@ -0,0 +1,31 @@
+// -*- 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
+#pragma once
+#include <cosmo.h>
+#include <time.h>
+
+#define LATENCY1() \
+ do { \
+ struct timespec started = timespec_real()
+
+#define LATENCY2(NAME) \
+ struct timespec ended = timespec_real(); \
+ struct timespec elapsed = timespec_sub(ended, started); \
+ long micros = timespec_tomicros(elapsed); \
+ kprintf("%10ld us %s\n", micros, NAME); \
+ } \
+ while (0)
+
+#define LATENCV(x) \
+ LATENCY1(); \
+ (x); \
+ LATENCY2(#x)
+
+#define LATENCY(x) \
+ ({ \
+ typeof(x) res; \
+ LATENCY1(); \
+ res = (x); \
+ LATENCY2(#x); \
+ res; \
+ })
diff --git a/llamafile/llamafile.h b/llamafile/llamafile.h
index 5b261b20..df18bbab 100644
--- a/llamafile/llamafile.h
+++ b/llamafile/llamafile.h
@@ -25,6 +25,8 @@ extern int FLAG_ctx;
extern int FLAG_flash_attn;
extern int FLAG_gpu;
extern int FLAG_gpu;
+extern int FLAG_http_ibuf_size;
+extern int FLAG_http_obuf_size;
extern int FLAG_keepalive;
extern int FLAG_main_gpu;
extern int FLAG_n_gpu_layers;
diff --git a/llamafile/server/hexcpy.cpp b/llamafile/lockable.h
similarity index 58%
rename from llamafile/server/hexcpy.cpp
rename to llamafile/lockable.h
index bc53d507..21838207 100644
--- a/llamafile/server/hexcpy.cpp
+++ b/llamafile/lockable.h
@@ -15,15 +15,31 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#include "utils.h"
+#pragma once
+#include <pthread.h>
-char*
-hexcpy(char* p, unsigned long x)
-{
- int k = x ? (__builtin_clzl(x) ^ 63) + 1 : 1;
- k = (k + 3) & -4;
- while (k > 0)
- *p++ = "0123456789abcdef"[(x >> (k -= 4)) & 15];
- *p = '\0';
- return p;
-}
+class Lockable {
+ public:
+ Lockable() {
+ if (pthread_mutex_init(&lock_, nullptr))
+ __builtin_trap();
+ }
+
+ virtual ~Lockable() {
+ if (pthread_mutex_destroy(&lock_))
+ __builtin_trap();
+ }
+
+ void lock() {
+ if (pthread_mutex_lock(&lock_))
+ __builtin_trap();
+ }
+
+ void unlock() {
+ if (pthread_mutex_unlock(&lock_))
+ __builtin_trap();
+ }
+
+ private:
+ pthread_mutex_t lock_;
+};
diff --git a/llamafile/server/memlog.inc b/llamafile/memlog.inc
similarity index 80%
rename from llamafile/server/memlog.inc
rename to llamafile/memlog.inc
index 57907a69..7edff1c6 100644
--- a/llamafile/server/memlog.inc
+++ b/llamafile/memlog.inc
@@ -15,42 +15,32 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#include "signals.h"
+#include "crash.h"
#include <cosmo.h>
#include <stdlib.h>
#include <third_party/dlmalloc/dlmalloc.h>
-void*
-memlog(void* p)
-{
+void *memlog(void *p) {
char bt[160];
- StackFrame* sf;
- sf = (StackFrame*)__builtin_frame_address(0);
+ struct StackFrame *sf;
+ sf = (struct StackFrame *)__builtin_frame_address(0);
describe_backtrace(bt, sizeof(bt), sf);
kprintf("alloc %p bt %s\n", p, bt);
return p;
}
-void*
-malloc(size_t n)
-{
+void *malloc(size_t n) {
return memlog(dlmalloc(n));
}
-void*
-calloc(size_t n, size_t z)
-{
+void *calloc(size_t n, size_t z) {
return memlog(dlcalloc(n, z));
}
-void*
-realloc(void* p, size_t n)
-{
+void *realloc(void *p, size_t n) {
return memlog(dlrealloc(p, n));
}
-void*
-memalign(size_t a, size_t n)
-{
+void *memalign(size_t a, size_t n) {
return memlog(dlmemalign(a, n));
}
diff --git a/llamafile/refcounted.h b/llamafile/refcounted.h
new file mode 100644
index 00000000..ca93d980
--- /dev/null
+++ b/llamafile/refcounted.h
@@ -0,0 +1,46 @@
+// -*- 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 <stdatomic.h>
+
+template <typename T>
+class RefCounted {
+ public:
+ RefCounted() : refs_(ATOMIC_VAR_INIT(0)) {
+ }
+
+ virtual ~RefCounted() {
+ if (atomic_load_explicit(&refs_, memory_order_relaxed) != -1)
+ __builtin_trap();
+ }
+
+ T *ref() {
+ atomic_fetch_add_explicit(&refs_, 1, memory_order_relaxed);
+ return (T *)this;
+ }
+
+ void unref() {
+ if (atomic_fetch_sub_explicit(&refs_, 1, memory_order_release))
+ return;
+ atomic_thread_fence(memory_order_acquire);
+ delete this;
+ }
+
+ private:
+ atomic_int refs_;
+};
diff --git a/llamafile/server/BUILD.mk b/llamafile/server/BUILD.mk
index f3bfdc73..576bc0bd 100644
--- a/llamafile/server/BUILD.mk
+++ b/llamafile/server/BUILD.mk
@@ -5,6 +5,7 @@ PKGS += LLAMAFILE_SERVER
LLAMAFILE_SERVER_FILES := $(wildcard llamafile/server/*)
LLAMAFILE_SERVER_HDRS = $(filter %.h,$(LLAMAFILE_SERVER_FILES))
+LLAMAFILE_SERVER_INCS = $(filter %.inc,$(LLAMAFILE_SERVER_FILES))
LLAMAFILE_SERVER_SRCS = $(filter %.cpp,$(LLAMAFILE_SERVER_FILES))
LLAMAFILE_SERVER_OBJS = $(LLAMAFILE_SERVER_SRCS:%.cpp=o/$(MODE)/%.o)
diff --git a/llamafile/server/client.cpp b/llamafile/server/client.cpp
index 8aa34f3c..74dd5a58 100644
--- a/llamafile/server/client.cpp
+++ b/llamafile/server/client.cpp
@@ -38,7 +38,7 @@
using namespace ctl;
-Client::Client() : ibuf(8 * 1024 * 1024), obuf(64 * 1024 * 1024)
+Client::Client() : ibuf(FLAG_http_ibuf_size), obuf(FLAG_http_obuf_size)
{
InitHttpMessage(&msg, 0);
url.params.p = nullptr;
@@ -341,6 +341,8 @@ Client::dispatch()
{
if (path() == "/tokenize")
return tokenize();
+ if (path() == "/embedding")
+ return embedding();
return send_error(404);
}
diff --git a/llamafile/server/client.h b/llamafile/server/client.h
index 140d4b4a..8f2c3b40 100644
--- a/llamafile/server/client.h
+++ b/llamafile/server/client.h
@@ -74,4 +74,5 @@ struct Client
bool dispatch() __wur;
bool tokenize() __wur;
+ bool embedding() __wur;
};
diff --git a/llamafile/server/embedding.cpp b/llamafile/server/embedding.cpp
new file mode 100644
index 00000000..456c2efc
--- /dev/null
+++ b/llamafile/server/embedding.cpp
@@ -0,0 +1,228 @@
+// -*- 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 "json.h"
+#include "log.h"
+#include "utils.h"
+
+void
+normalize_embeddings(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;
+}
+
+void
+add_token_to_batch(struct 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++;
+}
+
+bool
+Client::embedding()
+{
+ if (msg.method != kHttpGet && msg.method != kHttpPost)
+ return send_error(405);
+
+ if (!read_payload())
+ return false;
+
+ // get prompt
+ //
+ // 1. Allow GET "/tokenize?prompt=foo"
+ // 2. Allow POST "prompt=foo" (application/x-www-form-urlencoded)
+ // 3. Allow POST "foo" (text/plain)
+ //
+ ctl::string_view input;
+ ctl::optional<ctl::string_view> prompt = param("prompt");
+ if (prompt.has_value()) {
+ input = prompt.value();
+ } else if (HasHeader(kHttpContentType)) {
+ if (IsMimeType(HeaderData(kHttpContentType),
+ HeaderLength(kHttpContentType),
+ "text/plain")) {
+ input = payload;
+ } else {
+ return send_error(501, "Content Type Not Implemented");
+ }
+ } else {
+ input = payload;
+ }
+
+ // get optional parameters
+ bool add_special = atob(or_empty(param("add_special")), true);
+ bool parse_special = atob(or_empty(param("parse_special")), false);
+
+ // setup statistics
+ rusage rustart = {};
+ getrusage(RUSAGE_THREAD, &rustart);
+ timespec started = timespec_real();
+
+ // turn text into tokens
+ extern llama_model* g_model;
+ ctl::vector<llama_token> toks(input.size() + 16);
+ int count = llama_tokenize(g_model,
+ input.data(),
+ input.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);
+
+ // 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 = {};
+ cparams.embeddings = true;
+ cparams.embeddings_only = true;
+ cparams.logits_all = true;
+ cparams.seed = _rand64();
+ cparams.n_ctx = count;
+ cparams.n_batch = count;
+ cparams.n_ubatch = count;
+ cparams.n_seq_max = 1;
+ cparams.n_threads = 8;
+ cparams.n_threads_batch = 8;
+ cparams.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE;
+ cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
+ 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) {
+ LOG("llama_new_context_with_model failed");
+ return send_error(500);
+ }
+
+ // initialize batch
+ const int n_embd = llama_n_embd(g_model);
+ struct llama_batch batch = llama_batch_init(count, 0, 1);
+ for (size_t i = 0; i < count; ++i)
+ add_token_to_batch(batch, toks[i], i, { 0 }, i == count - 1);
+
+ // inference time
+ 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])
+ 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);
+ }
+ llama_free(ctx);
+ llama_batch_free(batch);
+
+ // serialize tokens to json
+ char* p = obuf.p;
+ p = stpcpy(p, "{\r\n");
+ p = stpcpy(p, " \"add_special\": ");
+ p = encode_bool(p, add_special);
+ p = stpcpy(p, ",\n");
+ p = stpcpy(p, " \"parse_special\": ");
+ p = encode_bool(p, parse_special);
+ p = stpcpy(p, ",\n");
+ p = stpcpy(p, " \"tokens_provided\": ");
+ p = encode_json(p, toks.size());
+ p = stpcpy(p, ",\n");
+ p = stpcpy(p, " \"tokens_used\": ");
+ p = encode_json(p, count);
+ p = stpcpy(p, ",\n");
+ p = stpcpy(p, " \"embedding\": [");
+ for (size_t i = 0; i < embeddings.size(); ++i) {
+ if (i) {
+ *p++ = ',';
+ *p++ = ' ';
+ }
+ p = encode_json(p, embeddings[i]);
+ }
+ 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/main.cpp b/llamafile/server/main.cpp
index 2979c568..40f2c1ae 100644
--- a/llamafile/server/main.cpp
+++ b/llamafile/server/main.cpp
@@ -58,7 +58,7 @@ main(int argc, char* argv[])
.progress_callback = nullptr,
.progress_callback_user_data = nullptr,
.kv_overrides = nullptr,
- .vocab_only = true,
+ .vocab_only = false,
.use_mmap = true,
.use_mlock = false,
.check_tensors = false,
@@ -77,7 +77,9 @@ main(int argc, char* argv[])
// run server
signals_init();
+ llama_backend_init();
g_server->run();
+ llama_backend_free();
signals_destroy();
// shutdown server
diff --git a/llamafile/server/server.cpp b/llamafile/server/server.cpp
index 83960637..527a8364 100644
--- a/llamafile/server/server.cpp
+++ b/llamafile/server/server.cpp
@@ -26,6 +26,7 @@
#include <time.h>
#include "llamafile/llamafile.h"
+
#include "log.h"
#include "server.h"
#include "worker.h"
@@ -59,9 +60,7 @@ Server::signal()
void
Server::wait()
{
- struct timespec waitfor =
- timespec_add(timespec_real(), timespec_fromseconds(1));
- pthread_cond_timedwait(&cond_, &lock_, &waitfor);
+ pthread_cond_wait(&cond_, &lock_);
}
void
diff --git a/llamafile/server/signals.cpp b/llamafile/server/signals.cpp
index 23932a6b..558f5305 100644
--- a/llamafile/server/signals.cpp
+++ b/llamafile/server/signals.cpp
@@ -20,6 +20,8 @@
#include <signal.h>
#include <ucontext.h>
+#include "llamafile/crash.h"
+
#include "log.h"
#include "server.h"
diff --git a/llamafile/server/signals.h b/llamafile/server/signals.h
index 6a196b34..1cc1d288 100644
--- a/llamafile/server/signals.h
+++ b/llamafile/server/signals.h
@@ -25,9 +25,3 @@ signals_init(void);
void
signals_destroy(void);
-
-char*
-describe_crash(char*, size_t, int, siginfo_t*, void*);
-
-char*
-describe_backtrace(char*, size_t, const StackFrame*);
diff --git a/llamafile/server/tokenize.cpp b/llamafile/server/tokenize.cpp
index 83a2aff8..fe3d8c46 100644
--- a/llamafile/server/tokenize.cpp
+++ b/llamafile/server/tokenize.cpp
@@ -17,24 +17,16 @@
#include "client.h"
+#include <ctl/vector.h>
#include <string.h>
#include <sys/resource.h>
#include "llama.cpp/llama.h"
#include "json.h"
+#include "log.h"
#include "utils.h"
-using namespace ctl;
-
-static string_view
-or_empty(optional<string_view> x)
-{
- if (x.has_value())
- return x.value();
- return {};
-}
-
bool
Client::tokenize()
{
@@ -50,8 +42,8 @@ Client::tokenize()
// 2. Allow POST "prompt=foo" (application/x-www-form-urlencoded)
// 3. Allow POST "foo" (text/plain)
//
- string_view input;
- optional<string_view> prompt = param("prompt");
+ ctl::string_view input;
+ ctl::optional<ctl::string_view> prompt = param("prompt");
if (prompt.has_value()) {
input = prompt.value();
} else if (HasHeader(kHttpContentType)) {
@@ -78,18 +70,19 @@ Client::tokenize()
// turn text into tokens
extern llama_model* g_model;
int maxcount = input.size() + 16;
- llama_token* toks = new llama_token[maxcount];
+ ctl::vector<llama_token> toks(maxcount);
int count = llama_tokenize(g_model,
input.data(),
input.size(),
- toks,
+ &toks[0],
maxcount,
add_special,
parse_special);
if (count < 0) {
- delete[] toks;
- __builtin_trap();
+ LOG("failed to tokenize");
+ return send_error(405);
}
+ toks.resize(count);
// serialize tokens to json
char* p = obuf.p;
@@ -108,15 +101,14 @@ Client::tokenize()
char s[32];
int n = llama_token_to_piece(g_model, toks[i], s, sizeof(s), true);
if (n < 0) {
- delete[] toks;
- __builtin_trap();
+ LOG("failed to turn token into string");
+ return send_error(405);
}
- p = encode_json(p, string_view(s, n));
+ p = encode_json(p, ctl::string_view(s, n));
}
p = stpcpy(p, "\r\n ]\r\n");
p = stpcpy(p, "}\r\n");
- string_view content(obuf.p, p - obuf.p);
- delete[] toks;
+ ctl::string_view content(obuf.p, p - obuf.p);
// collect statistics
rusage ruend = {};
diff --git a/llamafile/server/utils.h b/llamafile/server/utils.h
index 0a5c3940..6daeb713 100644
--- a/llamafile/server/utils.h
+++ b/llamafile/server/utils.h
@@ -16,6 +16,7 @@
// limitations under the License.
#pragma once
+#include <ctl/optional.h>
#include <ctl/string_view.h>
extern const signed char kHexToInt[256];
@@ -23,5 +24,10 @@ extern const signed char kHexToInt[256];
bool
atob(ctl::string_view, bool);
-char*
-hexcpy(char*, unsigned long);
+static inline ctl::string_view
+or_empty(ctl::optional<ctl::string_view> x)
+{
+ if (x.has_value())
+ return x.value();
+ return {};
+}
diff --git a/llamafile/thread.cpp b/llamafile/thread.cpp
new file mode 100644
index 00000000..2eed2383
--- /dev/null
+++ b/llamafile/thread.cpp
@@ -0,0 +1,148 @@
+// -*- 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 "thread.h"
+
+#include <stdatomic.h>
+#include <stdlib.h>
+
+#include "dll3.h"
+#include "lockable.h"
+#include "refcounted.h"
+#include "threadlocal.h"
+
+struct Parent : public Lockable, public RefCounted<Parent> {
+ Dll3 *children;
+
+ Parent() : children(nullptr) {
+ }
+
+ ~Parent() {
+ if (children)
+ __builtin_trap();
+ }
+};
+
+struct Child : public RefCounted<Child> {
+ pthread_t thread;
+ int detach_state;
+ _Atomic(Parent *) parent;
+ void *(*start_routine)(void *);
+ void *arg;
+ Dll3 elem; // owned by parent lock
+
+ Child(Parent *p, int detach_state, void *(*start_routine)(void *), void *arg)
+ : thread(0),
+ detach_state(detach_state),
+ parent(ATOMIC_VAR_INIT(p->ref())),
+ start_routine(start_routine),
+ arg(arg) {
+ dll3_init(&elem, this);
+ p->lock();
+ dll3_make_last(&p->children, &elem);
+ p->unlock();
+ }
+
+ ~Child() {
+ unregister();
+ }
+
+ void unregister() {
+ Parent *p;
+ if ((p = atomic_exchange(&parent, nullptr))) {
+ p->lock();
+ dll3_remove(&p->children, &elem);
+ p->unlock();
+ p->unref(); // remove child's reference to parent
+ unref(); // remove parent's reference to child
+ }
+ }
+};
+
+static void on_child_exit(Child *child) {
+ child->unregister();
+ child->unref(); // child frees self
+}
+
+static ThreadLocal<Child> g_child(on_child_exit);
+
+static void on_parent_exit(Parent *parent) {
+ Dll3 *e;
+ parent->lock();
+ while ((e = dll3_first(parent->children))) {
+ Child *child = (Child *)e->container;
+ if ((parent = atomic_exchange(&child->parent, nullptr))) {
+ 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();
+ }
+ child->unref(); // remove parent's reference to child
+ parent->lock();
+ }
+ }
+ parent->unlock();
+ parent->unref(); // parent frees self
+}
+
+static ThreadLocal<Parent> g_parent(on_parent_exit);
+
+static void *llamafile_thread(void *arg) {
+ Child *child;
+ g_child.set((child = (Child *)arg));
+ return child->start_routine(child->arg);
+}
+
+/**
+ * Creates managed thread.
+ *
+ * Threads created by this function will be canceled automatically, when
+ * the current thread exits or is itself canceled by another thread. The
+ * killing hierarchy works for both detached and joinable threads. It is
+ * a good idea for threads to put themselves in asynchronous cancelation
+ * mode whilst performing mathematical operations. Threads that block on
+ * i/o or semaphores should use the default deferred cancelation instead
+ * since it helps avoid memory leaks and other badness.
+ *
+ * @return 0 on success, or errno on error
+ */
+errno_t llamafile_thread_create(pthread_t *thread, const pthread_attr_t *attr,
+ void *(*start_routine)(void *), void *arg) {
+ errno_t err;
+ Parent *parent;
+ int detach_state = PTHREAD_CREATE_JOINABLE;
+ if (attr)
+ pthread_attr_getdetachstate(attr, &detach_state);
+ if (!(parent = g_parent.get()))
+ g_parent.set((parent = new Parent));
+ Child *child = new Child(parent, detach_state, start_routine, arg);
+ child->ref(); // acquire ownership for parent destructor
+ child->ref(); // ensure ownership for rest of this function
+ err = pthread_create(&child->thread, attr, llamafile_thread, child);
+ if (!err) {
+ *thread = child->thread;
+ } else {
+ child->unref(); // release reference for parent destructor
+ child->unref(); // release reference for child thread
+ }
+ child->unref(); // release reference for this function
+ return err;
+}
diff --git a/llamafile/thread.h b/llamafile/thread.h
new file mode 100644
index 00000000..4a7d0e83
--- /dev/null
+++ b/llamafile/thread.h
@@ -0,0 +1,14 @@
+#ifndef LLAMAFILE_THREAD_H_
+#define LLAMAFILE_THREAD_H_
+#include <pthread.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+errno_t llamafile_thread_create(pthread_t *thread, const pthread_attr_t *attr,
+ void *(*start_routine)(void *), void *arg);
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* LLAMAFILE_THREAD_H_ */
diff --git a/llamafile/thread_test.cpp b/llamafile/thread_test.cpp
new file mode 100644
index 00000000..7fee7243
--- /dev/null
+++ b/llamafile/thread_test.cpp
@@ -0,0 +1,62 @@
+// -*- 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 "thread.h"
+
+#include <cosmo.h>
+#include <stdatomic.h>
+#include <stdlib.h>
+
+#define WORKERS 10
+#define MATHS 10
+
+atomic_int barrier;
+
+void *start_math(void *arg) {
+ ++barrier;
+ pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
+ pthread_testcancel();
+ for (;;) {
+ }
+}
+
+void *start_worker(void *arg) {
+ ++barrier;
+ pthread_t th[MATHS];
+ for (int i = 0; i < MATHS; ++i)
+ if (llamafile_thread_create(&th[i], 0, start_math, 0))
+ _Exit(3);
+ for (int i = 0; i < MATHS; ++i)
+ if (pthread_join(th[i], 0))
+ _Exit(4);
+ return 0;
+}
+
+int main() {
+ pthread_t th[WORKERS];
+ for (int i = 0; i < WORKERS; ++i)
+ if (llamafile_thread_create(&th[i], 0, start_worker, 0))
+ _Exit(1);
+ while (barrier < WORKERS * MATHS) {
+ }
+ for (int i = 0; i < WORKERS; ++i)
+ pthread_cancel(th[i]);
+ for (int i = 0; i < WORKERS; ++i)
+ if (pthread_join(th[i], 0))
+ _Exit(2);
+ CheckForMemoryLeaks();
+}
diff --git a/llamafile/threadlocal.h b/llamafile/threadlocal.h
new file mode 100644
index 00000000..b275dd18
--- /dev/null
+++ b/llamafile/threadlocal.h
@@ -0,0 +1,45 @@
+// -*- 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 <pthread.h>
+
+template <typename T>
+struct ThreadLocal {
+
+ explicit ThreadLocal(void (*dtor)(T *value)) {
+ if (pthread_key_create(&key_, (void (*)(void *))dtor))
+ __builtin_trap();
+ }
+
+ ~ThreadLocal() {
+ if (pthread_key_delete(key_))
+ __builtin_trap();
+ }
+
+ void set(T *value) {
+ if (pthread_setspecific(key_, value))
+ __builtin_trap();
+ }
+
+ T *get() {
+ return (T *)pthread_getspecific(key_);
+ }
+
+ private:
+ pthread_key_t key_;
+};