Distribute and run LLMs with a single file.
C++ cross-platformggufllama-cpplocal-ailocal-inferencelocal-llmopen-source-aisingle-file-executablespeech-to-text
Add chrome://tracing/ feature
Justine Tunneyd451e0edd24e
diff --git a/.gitignore b/.gitignoreindex fcbdcd99..d928dde4 100644--- a/.gitignore+++ b/.gitignore@@ -7,5 +7,6 @@/cosmocc/perf.data/perf.data.old+/trace.json/*.logdiff --git a/llama.cpp/common.cpp b/llama.cpp/common.cppindex d5024783..9fb83724 100644--- a/llama.cpp/common.cpp+++ b/llama.cpp/common.cpp@@ -183,6 +183,10 @@ bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_paif (arg == "--cli") {return true;}+ if (arg == "--trace") {+ FLAG_trace = true;+ return true;+ }if (arg == "--fast") {FLAG_precise = false;return true;diff --git a/llama.cpp/ggml.c b/llama.cpp/ggml.cindex 74dcf6a5..b20137da 100644--- a/llama.cpp/ggml.c+++ b/llama.cpp/ggml.c@@ -2,7 +2,6 @@// vi: set et ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi#define GGML_USE_LLAMAFILE 1-// #define LLAMAFILE_SYNC_REPORT__notice(ggml_notice, "\llama.cpp (MIT License)\n\@@ -44,6 +43,7 @@ SOFTWARE.");#include "llamafile/sgemm.h"#include "llamafile/thread.h"#include "llamafile/crash.h"+#include "llamafile/trace.h"#include <alloca.h>#include <assert.h>@@ -1564,35 +1564,6 @@ static inline void __lsx_f16x4_store(ggml_fp16_t *x, __m128 y) {#define GGML_F16_ARR (GGML_F16_STEP/GGML_F16_EPR)#endif-////////////////////////////////////////////////////////////////////////////////-// SYNCHRONIZATION MEASUREMENTS--int cycles[5000][100];-_Atomic(unsigned long) opstart[5000];-_Atomic(unsigned long) absolute_start;--static thread_local struct {- unsigned long work_cycles;- unsigned long wait_cycles;- unsigned long stamp;-} g_sync;--static void sync_wait_start(void) {-#ifdef LLAMAFILE_SYNC_REPORT- unsigned long now = rdtsc();- g_sync.work_cycles += now - g_sync.stamp;- g_sync.stamp = now;-#endif-}--static void sync_wait_end(void) {-#ifdef LLAMAFILE_SYNC_REPORT- unsigned long now = rdtsc();- g_sync.wait_cycles += now - g_sync.stamp;- g_sync.stamp = now;-#endif-}-////////////////////////////////////////////////////////////////////////////////// SYNCHRONIZATION PRIMITIVES@@ -1616,7 +1587,6 @@ void ggml_once(atomic_uint * once, void init(void)) {}int ggml_delay(int backoff) {-#if 1if (backoff < 7) {volatile int i;for (i = 0; i != 1 << backoff; i++) {@@ -1625,13 +1595,12 @@ int ggml_delay(int backoff) {} else {pthread_yield_np();}-#endifreturn backoff;}// creates barrier and blocks until all threads call thisvoid ggml_syncthreads(struct ggml_barrier * b, int nth) {- sync_wait_start();+ llamafile_trace_begin("syncthreads");unsigned phase = atomic_load_explicit(&b->phase, memory_order_relaxed);if (atomic_fetch_add_explicit(&b->count, 1, memory_order_acq_rel) + 1 == nth) {atomic_store_explicit(&b->count, 0, memory_order_relaxed);@@ -1642,7 +1611,7 @@ void ggml_syncthreads(struct ggml_barrier * b, int nth) {while (atomic_load_explicit(&b->phase, memory_order_relaxed) == phase)backoff = ggml_delay(backoff);}- sync_wait_end();+ llamafile_trace_end("syncthreads");}//@@ -11499,6 +11468,7 @@ UseGgmlGemm1:;assert(params->wsize >= ne11*ne12*ne13*row_size);GGML_ASSERT(src1->type == GGML_TYPE_F32);+ llamafile_trace_begin(ggml_type_name(vec_dot_type));unsigned chore = 0; // [jart] need for speedfor (int64_t i13 = 0; i13 < ne13; ++i13) {for (int64_t i12 = 0; i12 < ne12; ++i12) {@@ -11510,6 +11480,7 @@ UseGgmlGemm1:;}}}+ llamafile_trace_end(ggml_type_name(vec_dot_type));ggml_syncthreads(params->barrier, params->nth);}@@ -16682,14 +16653,7 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggmreturn;}-#ifdef LLAMAFILE_SYNC_REPORT- long start = rdtsc();- unsigned long old = 0;- atomic_compare_exchange_strong_explicit(&opstart[llamafile_debug_op_index],- &old, start,- memory_order_relaxed,- memory_order_relaxed);-#endif+ llamafile_trace_begin(ggml_op_desc(tensor));switch (tensor->op) {case GGML_OP_DUP:@@ -17024,10 +16988,7 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm} break;}-#ifdef LLAMAFILE_SYNC_REPORT- long end = rdtsc();- cycles[llamafile_debug_op_index][params->ith] += end - start;-#endif+ llamafile_trace_end(ggml_op_desc(tensor));#ifdef LLAMAFILE_DEBUGllamafile_trapping_restore();@@ -18768,7 +18729,6 @@ static void ggml_graph_compute_thread_sync_node(int * node_n, struct ggml_computconst int last_node_n = * node_n;int backoff = 0;- sync_wait_start();while (true) {* node_n = atomic_load_explicit(&state->shared->node_n, memory_order_acquire);if (* node_n != last_node_n) break;@@ -18778,7 +18738,6 @@ static void ggml_graph_compute_thread_sync_node(int * node_n, struct ggml_computbackoff = ggml_delay(backoff);}}- sync_wait_end();}static void ggml_graph_compute_thread_sync_task(int * task_phase, struct ggml_compute_state * state, const bool do_yield) {@@ -18786,7 +18745,6 @@ static void ggml_graph_compute_thread_sync_task(int * task_phase, struct ggml_coconst int last_task_phase = * task_phase;int backoff = 0;- sync_wait_start();while (true) {* task_phase = atomic_load_explicit(&state->shared->node_task, memory_order_acquire);if (* task_phase != last_task_phase) break;@@ -18796,7 +18754,6 @@ static void ggml_graph_compute_thread_sync_task(int * task_phase, struct ggml_cobackoff = ggml_delay(backoff);}}- sync_wait_end();}static thread_ret_t ggml_graph_compute_thread(void * data) {@@ -18818,14 +18775,7 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {}#endif-#ifdef LLAMAFILE_SYNC_REPORT- g_sync.stamp = rdtsc();- unsigned long old = 0;- atomic_compare_exchange_strong_explicit(&absolute_start,- &old, g_sync.stamp,- memory_order_relaxed,- memory_order_relaxed);-#endif+ llamafile_trace_set_tid(state->ith);int ct; // [jart] enable instant math cancelationpthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &ct);@@ -18839,7 +18789,7 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {return 0;}- if (atomic_fetch_sub(&state->shared->n_active, 1) == 1) {+ if (atomic_fetch_sub(&state->shared->n_active, 1) == n_threads) {// all other threads are finished and spinning// do finalize and init here so we don't have synchronize againstruct ggml_compute_params params = {@@ -18852,7 +18802,7 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {};#ifdef LLAMAFILE_DEBUG- llamafile_debug_op_index = node_n;+ llamafile_debug_op_index = node_n;#endifif (node_n != -1) {@@ -18909,12 +18859,19 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {task_phase = GGML_TASK_TYPE_INIT;+ int backoff = 0;+ while (atomic_load(&state->shared->n_active)) {+ backoff = ggml_delay(backoff);+ }+atomic_store_explicit(&state->shared->n_active, n_threads, memory_order_release);atomic_store_explicit(&state->shared->node_n, node_n, memory_order_release);atomic_store_explicit(&state->shared->node_task, task_phase, memory_order_release);} else {+ llamafile_trace_begin("sync #1");ggml_graph_compute_thread_sync_node(&node_n, state, false);ggml_graph_compute_thread_sync_task(&task_phase, state, false);+ llamafile_trace_end("sync #1");}// check if we should stop@@ -18952,8 +18909,10 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {// since it is not clear what is the best approach, it should potentially become user-configurable// ref: https://github.com/ggerganov/ggml/issues/291// UPD: adding the do_yield flag seems to resolve the issue universally+ llamafile_trace_begin("sync #2");const bool do_yield = node_n < 0 || cgraph->nodes[node_n]->op == GGML_OP_MUL_MAT;ggml_graph_compute_thread_sync_task(&task_phase, state, do_yield);+ llamafile_trace_end("sync #2");}}@@ -18968,19 +18927,14 @@ static thread_ret_t ggml_graph_compute_thread(void * data) {atomic_store_explicit(&state->shared->node_task, task_phase, memory_order_release);}else {+ llamafile_trace_begin("sync #3");ggml_graph_compute_thread_sync_task(&task_phase, state, false);+ llamafile_trace_end("sync #3");}}pthread_setcanceltype(ct, 0); // [jart]-#ifdef LLAMAFILE_SYNC_REPORT- g_sync.work_cycles += rdtsc() - g_sync.stamp;- double total = g_sync.work_cycles + g_sync.wait_cycles;- int workpercent = g_sync.work_cycles / total * 100.5;- fprintf(stderr, "SYNC %03d %3d%% working\n", state->ith, workpercent);-#endif-return 0;}@@ -19259,10 +19213,6 @@ enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cpl// die before launching the threadspthread_testcancel(); // [jart]-#ifdef LLAMAFILE_SYNC_REPORT- fprintf(stderr, "\n");-#endif-const int n_threads = cplan->n_threads;struct ggml_compute_state_shared state_shared = {@@ -19350,37 +19300,6 @@ enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplpthread_cleanup_pop(false);-#ifdef LLAMAFILE_SYNC_REPORT- opstart[cgraph->n_nodes] = rdtsc();- static int lol;- if (++lol == 2) {- const char *path = "/tmp/cgraph.txt";- FILE *f = fopen(path, "w");- if (!f) {- const char *help;- if (errno == EPERM) {- help = " (you need to pass the --unsecure flag)";- } else {- help = "";- }- fprintf(stderr, "%s: %s%s\n", path, strerror(errno), help);- exit(1);- }- print_graph(f, cgraph, cplan->n_threads);- fclose(f);- fprintf(stderr, "\n");- }- for (int i = 0; i < cgraph->n_nodes; ++i) {- fprintf(stderr, "OP %-11s %12ld %4d", describe_vertex(cgraph->nodes[i]), opstart[i + 1] - opstart[i], i);- for (int j = 0; j < n_threads; ++j) {- fprintf(stderr, " %10d", cycles[i][j]);- }- fprintf(stderr, "\n");- }- memset(opstart, 0, sizeof(opstart));- memset(cycles, 0, sizeof(cycles));-#endif-// performance stats (graph){int64_t perf_cycles_cur = ggml_perf_cycles() - perf_start_cycles;diff --git a/llamafile/flags.cpp b/llamafile/flags.cppindex ef1ca97c..7dc5dc39 100644--- a/llamafile/flags.cpp+++ b/llamafile/flags.cpp@@ -33,6 +33,7 @@ bool FLAG_nocompile = false;bool FLAG_precise = false;bool FLAG_recompile = false;bool FLAG_tinyblas = false;+bool FLAG_trace = false;bool FLAG_unsecure = false;const char *FLAG_file = nullptr;const char *FLAG_listen = "0.0.0.0:8080";@@ -222,6 +223,11 @@ void llamafile_get_flags(int argc, char **argv) {continue;}+ if (!strcmp(flag, "--trace")) {+ FLAG_trace = true;+ continue;+ }+if (!strcmp(flag, "--precise")) {FLAG_precise = true;continue;diff --git a/llamafile/llamafile.h b/llamafile/llamafile.hindex 85ebf52d..b01726ee 100644--- a/llamafile/llamafile.h+++ b/llamafile/llamafile.h@@ -13,6 +13,7 @@ extern bool FLAG_nocompile;extern bool FLAG_precise;extern bool FLAG_recompile;extern bool FLAG_tinyblas;+extern bool FLAG_trace;extern bool FLAG_trap;extern bool FLAG_unsecure;extern const char *FLAG_file;diff --git a/llamafile/trace.c b/llamafile/trace.cnew file mode 100644index 00000000..804836d5--- /dev/null+++ b/llamafile/trace.c@@ -0,0 +1,137 @@+// -*- 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 "trace.h"++#include <cosmo.h>+#include <pthread.h>+#include <stdatomic.h>+#include <threads.h>++#include "llamafile.h"+#include "log.h"++struct TraceEvent {+ unsigned long long ts;+ int pid;+ int tid;+ const char *name;+ const char *cat;+ char ph;+};++static int g_pid;+static atomic_bool g_oom;+static atomic_int g_count;+static thread_local int g_id;+static thread_local int g_ids;+static thread_local int g_tid;+static struct TraceEvent g_events[1000000];++static int llamafile_trace_oom(void) {+ if (atomic_load_explicit(&g_oom, memory_order_relaxed))+ return -1;+ if (atomic_exchange_explicit(&g_oom, true, memory_order_acq_rel))+ return -1;+ tinylog("warning: ran out of trace event memory\n", NULL);+ return -1;+}++static int llamafile_trace_reserve(int count) {+ int id = atomic_load_explicit(&g_count, memory_order_relaxed);+ if (id + count > sizeof(g_events) / sizeof(*g_events))+ return llamafile_trace_oom();+ id = atomic_fetch_add_explicit(&g_count, count, memory_order_acq_rel);+ if (id + count > sizeof(g_events) / sizeof(*g_events))+ return llamafile_trace_oom();+ return id;+}++static void llamafile_trace_event(int id, const char *name, const char *cat, char ph) {+ g_events[id].ts = rdtsc();+ g_events[id].pid = g_pid ? g_pid - 1 : getpid();+ g_events[id].tid = g_tid ? g_tid - 1 : gettid();+ g_events[id].name = name;+ g_events[id].cat = cat;+ g_events[id].ph = ph;+}++void llamafile_trace_set_pid(int pid) {+ g_pid = pid + 1;+}++void llamafile_trace_set_tid(int tid) {+ g_tid = tid + 1;+}++void llamafile_trace_begin(const char *name) {+ if (!FLAG_trace)+ return;+ if (g_ids < 2) {+ g_ids = 20;+ g_id = llamafile_trace_reserve(g_ids);+ if (g_id == -1) {+ g_ids = 0;+ return;+ }+ }+ llamafile_trace_event(g_id++, name, "category", 'B');+ --g_ids;+}++void llamafile_trace_end(const char *name) {+ if (!FLAG_trace)+ return;+ if (g_ids < 1)+ return;+ llamafile_trace_event(g_id++, name, "category", 'E');+ --g_ids;+}++static void llamafile_trace_save(const char *filename) {+ int count = atomic_load_explicit(&g_count, memory_order_relaxed);+ if (!count)+ return;+ tinylog("saving trace to ", filename, "...\n", NULL);+ FILE *file = fopen(filename, "w");+ if (!file) {+ perror(filename);+ return;+ }+ fprintf(file, "[\n");+ bool once = false;+ for (int i = 0; i < count; i++) {+ if (!g_events[i].name)+ continue;+ if (!once) {+ once = true;+ } else {+ fputs(",\n", file);+ }+ fprintf(file,+ "{\"name\": \"%s\", \"cat\": \"%s\", \"ph\": \"%c\", "+ "\"ts\": %.3f, \"pid\": %d, \"tid\": %d}",+ g_events[i].name, g_events[i].cat, g_events[i].ph,+ (g_events[i].ts - kStartTsc) / 3000., g_events[i].pid, g_events[i].tid);+ }+ fprintf(file, "\n]\n");+ fclose(file);+}++__attribute__((__destructor__)) static void trace_shutdown(void) {+ llamafile_trace_save("trace.json"); // see chrome://tracing/+}diff --git a/llamafile/trace.h b/llamafile/trace.hnew file mode 100644index 00000000..46a549e2--- /dev/null+++ b/llamafile/trace.h@@ -0,0 +1,13 @@+#pragma once+#ifdef __cplusplus+extern "C" {+#endif++void llamafile_trace_set_pid(int);+void llamafile_trace_set_tid(int);+void llamafile_trace_begin(const char *);+void llamafile_trace_end(const char *);++#ifdef __cplusplus+}+#endifdiff --git a/stable-diffusion.cpp/main.cpp b/stable-diffusion.cpp/main.cppindex 523ae213..ef0d0ca5 100644--- a/stable-diffusion.cpp/main.cpp+++ b/stable-diffusion.cpp/main.cpp@@ -219,6 +219,8 @@ void parse_args(int argc, const char** argv, SDParams& params) {FLAG_precise = false;} else if (arg == "--precise") {FLAG_precise = true;+ } else if (arg == "--trace") {+ FLAG_trace = true;} else if (arg == "--trap") {FLAG_trap = true;FLAG_unsecure = true; // for better backtracesdiff --git a/whisper.cpp/main.cpp b/whisper.cpp/main.cppindex 4cfd75bb..84752203 100644--- a/whisper.cpp/main.cpp+++ b/whisper.cpp/main.cpp@@ -126,6 +126,8 @@ static bool whisper_params_parse(int argc, char ** argv, whisper_params & paramsif (arg == "--log-disable") {FLAG_log_disable = true;+ } else if (arg == "--trace") {+ FLAG_trace = true;} else if (arg == "--trap") {FLAG_trap = true;FLAG_unsecure = true; // for better backtraces@@ -939,6 +941,8 @@ static void cb_log_disable(enum ggml_log_level , const char * , void * ) { }int main(int argc, char ** argv) {whisper_params params;+ ShowCrashReports();+// [jart] disable GPU by default (pass `--gpu auto` to enable it)FLAG_gpu = LLAMAFILE_GPU_DISABLE;