Skip to content

Fast local LLM inference on plain CPUs. No GPU, 8 GB of RAM. OpenAI-compatible server.

fix(attention): keep split partials in each graph workspace (#103)

Afloatf9953d91d22e
diff --git a/kernels/attn-fast.inc b/kernels/attn-fast.inc
index 63fbf13..e656a14 100644
--- a/kernels/attn-fast.inc
+++ b/kernels/attn-fast.inc
@@ -555,9 +555,6 @@ static int attnf_mode(void) {
return mode;
}
-static float * attnf_part = NULL; // split-mode partials, grown by thread 0 between barriers
-static size_t attnf_part_cap = 0;
-
// first / last+1 key a mask row leaves visible, within [0, nkv)
static void attnf_visible(const ggml_fp16_t * mr, int64_t nkv, int64_t * lo, int64_t * hi) {
if (!mr) { *lo = 0; *hi = nkv; return; }
@@ -611,12 +608,9 @@ static bool attnf_forward(const struct ggml_compute_params * params, struct ggml
const int64_t nch = c1 - c0, units = HKV * nch;
const size_t ps = (size_t) DV + 2; // [m, l, O[DV]] per row
const size_t need = (size_t) units * R * ps;
- if (ith == 0 && need > attnf_part_cap) {
- free(attnf_part);
- attnf_part_cap = need + need / 4;
- attnf_part = (float *) aligned_alloc(64, (attnf_part_cap * sizeof(float) + 63) / 64 * 64);
- GGML_ASSERT(attnf_part && "attn-fast: out of memory");
- }
+ // The graph owns this scratch buffer; another context may run attention concurrently.
+ GGML_ASSERT(params->wsize >= need * sizeof(float) + 63);
+ float * attnf_part = (float *) (((uintptr_t) params->wdata + 63) & ~(uintptr_t) 63);
ggml_barrier(params->threadpool);
float ml[2 * ATTNF_RMAX];
// each thread takes a contiguous run of (chunk, head) units, chunk-major: it streams one token range of the
diff --git a/patches/0008-attention-kernel.patch b/patches/0008-attention-kernel.patch
index 6e3a5d5..37607ea 100644
--- a/patches/0008-attention-kernel.patch
+++ b/patches/0008-attention-kernel.patch
@@ -10,6 +10,29 @@ index 94dead3..eef8b99 100644
};
static ggml_type kv_cache_type_from_str(const std::string & s) {
+diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c
+--- a/ggml/src/ggml-cpu/ggml-cpu.c
++++ b/ggml/src/ggml-cpu/ggml-cpu.c
+@@ -3021,7 +3021,17 @@ struct ggml_cplan ggml_graph_plan(
+ size_t n_chunks = n_tasks;
+ size_t decode = sizeof(float)*(neq2*n_chunks*(2+DV) + n_tasks*(DK + 2*DV));
+-
++
+- cur += MAX(prefill, decode);
++ // attn-fast.inc splits small query groups over canonical 1024-key chunks.
++ // Reserve their partials in this graph's workspace, not a process-global buffer.
++ const int64_t neq1 = node->src[0]->ne[1];
++ const int64_t nek1 = node->src[1]->ne[1];
++ const int64_t nek2 = node->src[1]->ne[2];
++ size_t grouped = 0;
++ if (nek2 > 0 && neq2 % nek2 == 0 && neq1 * (neq2 / nek2) <= 48) {
++ grouped = sizeof(float)*neq1*neq2*((nek1 + 1023)/1024)*(2+DV) + 63;
++ }
++
++ cur += MAX(MAX(prefill, decode), grouped);
+ } break;
+ case GGML_OP_FLASH_ATTN_BACK:
+ {
diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp
index 6884720..12f84df 100644
--- a/ggml/src/ggml-cpu/ops.cpp
diff --git a/tests/test_attention_concurrent_graphs.py b/tests/test_attention_concurrent_graphs.py
new file mode 100644
index 0000000..72c325e
--- /dev/null
+++ b/tests/test_attention_concurrent_graphs.py
@@ -0,0 +1,109 @@
+from pathlib import Path
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class AttentionConcurrentGraphs(unittest.TestCase):
+ def test_independent_graphs_keep_their_attention_partials(self):
+ compiler = shutil.which('c++') or shutil.which('g++') or shutil.which('clang++')
+ if compiler is None:
+ self.skipTest('needs a C++ compiler')
+ harness = r'''
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <mutex>
+#include <thread>
+#include <vector>
+#define GGML_ABORT(...) std::abort()
+#define GGML_ASSERT(condition) do { if (!(condition)) std::abort(); } while (0)
+using ggml_fp16_t = uint16_t;
+#define GGML_CPU_FP16_TO_FP32(value) ((float) (value))
+enum ggml_type { GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_Q8_K, GGML_TYPE_KV4, GGML_TYPE_KV5, GGML_TYPE_KV6 };
+struct ggml_tensor {
+ ggml_type type;
+ int64_t ne[4];
+ size_t nb[4];
+ void * data;
+ ggml_tensor * src[5] = {};
+ float op_params[3] = {1, 0, 0};
+};
+struct ggml_threadpool { bool first; int barriers = 0; int chunk = 0; };
+struct ggml_compute_params { int ith, nth; void * wdata; size_t wsize; ggml_threadpool * threadpool; };
+static std::mutex lock;
+static std::condition_variable changed;
+static bool first_ready = false, second_finished = false;
+static void ggml_barrier(ggml_threadpool * pool) {
+ if (pool->first && ++pool->barriers == 2) {
+ std::unique_lock<std::mutex> guard(lock);
+ first_ready = true;
+ changed.notify_all();
+ changed.wait(guard, [] { return second_finished; });
+ }
+}
+static void ggml_threadpool_chunk_set(ggml_threadpool * pool, int value) { pool->chunk = value; }
+static int ggml_threadpool_chunk_add(ggml_threadpool * pool, int value) { int old = pool->chunk; pool->chunk += value; return old; }
+static size_t ggml_type_size(ggml_type type) {
+ return type == GGML_TYPE_Q8_K ? 292 : type == GGML_TYPE_KV4 ? 132 : type == GGML_TYPE_KV5 ? 164 : 196;
+}
+#include "attn-fast.inc"
+static bool run_graph(bool first, int8_t value) {
+ attnf_q8k keys{}, values{};
+ keys.d = values.d = 1.0f;
+ for (int i = 0; i < 256; ++i) values.qs[i] = value;
+ float query[256] = {}, output[256] = {};
+ ggml_tensor q{GGML_TYPE_F32, {256,1,1,1}, {4,1024,1024,1024}, query};
+ ggml_tensor k{GGML_TYPE_Q8_K, {256,1,1,1}, {292,292,292,292}, &keys};
+ ggml_tensor v{GGML_TYPE_Q8_K, {256,1,1,1}, {292,292,292,292}, &values};
+ ggml_tensor dst{GGML_TYPE_F32, {256,1,1,1}, {4,1024,1024,1024}, output};
+ dst.src[0] = &q; dst.src[1] = &k; dst.src[2] = &v;
+ std::vector<uint8_t> scratch(4096);
+ ggml_threadpool pool{first};
+ ggml_compute_params params{0,1,scratch.data(),scratch.size(),&pool};
+ if (!attnf_forward(&params, &dst)) return false;
+ for (float actual : output) {
+ if (actual != value) {
+ std::fprintf(stderr, "graph with V=%d produced %g\n", value, actual);
+ return false;
+ }
+ }
+ return true;
+}
+int main() {
+ bool a = false, b = false;
+ std::thread first([&] { a = run_graph(true, 1); });
+ std::thread second([&] {
+ {
+ std::unique_lock<std::mutex> guard(lock);
+ changed.wait(guard, [] { return first_ready; });
+ }
+ b = run_graph(false, 9);
+ {
+ std::lock_guard<std::mutex> guard(lock);
+ second_finished = true;
+ }
+ changed.notify_all();
+ });
+ first.join(); second.join();
+ return a && b ? 0 : 1;
+}
+'''
+ with tempfile.TemporaryDirectory() as tmp:
+ code, executable = Path(tmp) / 'concurrent.cpp', Path(tmp) / 'concurrent'
+ code.write_text(harness)
+ build = subprocess.run([compiler, '-std=c++17', '-O2', '-pthread', '-I', str(ROOT / 'kernels'),
+ str(code), '-o', str(executable)], capture_output=True, text=True)
+ self.assertEqual(build.returncode, 0, build.stderr)
+ run = subprocess.run([str(executable)], capture_output=True, text=True, timeout=20)
+ self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
+
+
+if __name__ == '__main__':
+ unittest.main()