A 2.78-trillion-parameter Kimi K3 running inference on a single CPU in 8.24 GB of RAM. Portable C99: no BLAS, no framework, no GPU.
C avx2c99cpu-inferencedeep-learningfrom-scratchinference-enginekimi-k3linear-attentionllmllm-inferencemachine-learningmemory-efficientmixture-of-expertsmoemxfp4quantizationsimdsystems-programmingtransformerzero-dependencies
fix(cli): read available memory on macOS, cap it by commit headroom on Windows
Fareed Khan998b489ffe3e
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 2b95083..ebe36f9 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -157,6 +157,8 @@ target_include_directories(test_cancel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/ck3_add_test(test_state tests/unit/test_state.c)target_sources(test_state PRIVATE src/cli/k3_state.c)target_include_directories(test_state PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/cli)+k3_add_test(test_sysmem tests/unit/test_sysmem.c)+target_include_directories(test_sysmem PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/cli)target_link_libraries(test_chat PRIVATE k3_chat)k3_add_test(test_sampler tests/unit/test_sampler.c)target_link_libraries(test_sampler PRIVATE k3_chat)@@ -176,6 +178,7 @@ add_test(NAME ops COMMAND test_ops ${FIX}/ops)add_test(NAME cache COMMAND test_cache ${FIX}/cache)add_test(NAME config COMMAND test_cfg fixture ${FIX}/ref_k3.json)add_test(NAME interrupt COMMAND test_cancel)+add_test(NAME memory_probe COMMAND test_sysmem)add_test(NAME scale COMMAND scale_test)add_test(NAME trunk COMMAND test_trunk)add_test(NAME oracle COMMAND k3_model ${FIX})diff --git a/Makefile b/Makefileindex 2543081..fca77d7 100644--- a/Makefile+++ b/Makefile@@ -156,7 +156,7 @@ CHAT_SRC := src/chat/k3_chat.c src/chat/k3_sampler.cCLI_BIN := $(BIN)/k3# Tests that need no checkpoint. These run in CI on every push.-UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat test_sampler scale_test k3_model test_trunk test_st_faults test_prefix test_state test_cancel test_json+UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat test_sampler scale_test k3_model test_trunk test_st_faults test_sysmem test_prefix test_state test_cancel test_json# Tests that need real shards. Built and run by `make test-all` with SHARD_DIR set;# see the weights-test target below.WEIGHT_TESTS := test_expert test_real_layer@@ -231,6 +231,9 @@ $(BIN)/test_state: tests/unit/test_state.c src/cli/k3_state.c | $(BIN)# equivalence it relies on is GATE 3b of k3_model.$(BIN)/test_prefix: tests/unit/test_prefix.c src/chat/k3_prefix.h | $(BIN)$(CC) -O2 -std=c99 $(WARN) -Wno-unused-function $(INCLUDES) $< -o $@+# The memory probe is one platform call per OS and nothing else; built the same way.+$(BIN)/test_sysmem: tests/unit/test_sysmem.c src/cli/k3_sysmem.h | $(BIN)+ $(CC) -O2 -std=gnu99 $(WARN) $(INCLUDES) -Isrc/cli $< -o $@# Allocates at REAL model widths (a ~1.8 GB KDA layer), so it needs the optimised build# rather than the portable C99 one the tokenizer and config tests use.@@ -289,6 +292,7 @@ test: $(CLI_BIN) $(TEST_BINS)@echo "== state file =="; ./$(BIN)/test_state $(BUILD)/state@echo "== config reader =="; ./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json@echo "== interrupt contract =="; ./$(BIN)/test_cancel+ @echo "== memory probe =="; ./$(BIN)/test_sysmem@echo "== config refusals =="; \for f in no_layermap bad_layer_index bad_topk; do \./$(BIN)/test_cfg reject $(FIXTURES)/cfg/$$f.json || exit 1; \diff --git a/src/cli/k3_run.c b/src/cli/k3_run.cindex c326ace..d681a51 100644--- a/src/cli/k3_run.c+++ b/src/cli/k3_run.c@@ -72,6 +72,7 @@#include "k3_cfg.h" /* read the checkpoint's own config rather than assuming it */#include "k3_cancel.h" /* first Ctrl-C stops at a safe point; see the header */#include "k3_state.h" /* --save-state / --load-state file format */+#include "k3_sysmem.h" /* available/total memory on Linux, Darwin and Windows */static double now_s(void){@@ -377,31 +378,6 @@ static double peak_rss_bytes(void)#endif}-/* MemAvailable, which is what the kernel thinks can actually be handed out, not- * MemFree. Returns 0 if it cannot be read. */-static double mem_available_bytes(void)-{-#ifdef _WIN32- /* ullAvailPhys is Windows' MemAvailable equivalent: physical memory that can- * actually be handed out (already accounts for the standby/modified page- * lists the way MemAvailable accounts for reclaimable cache), not the raw- * free count. */- MEMORYSTATUSEX ms;- ms.dwLength = sizeof ms;- if (!GlobalMemoryStatusEx(&ms)) return 0.0;- return (double)ms.ullAvailPhys;-#else- FILE *f = fopen("/proc/meminfo", "r");- if (!f) return 0.0;- char line[256];- double kb = 0.0;- while (fgets(line, sizeof line, f))- if (!strncmp(line, "MemAvailable:", 13)) { kb = atof(line + 13); break; }- fclose(f);- return kb * 1024.0;-#endif-}-typedef struct {K3LayerBind *lay;K3ModelBind mb;@@ -654,7 +630,7 @@ static int chat_run(Tok *tok, const K3ChatTemplate *tmpl, K3ChatHistory *history}if (incremental) {const double kv_need = (double)need * K3_KV_BYTES_PER_POS;- const double avail = mem_available_bytes();+ const double avail = k3_mem_available_bytes();if (avail > 0.0 && kv_need > avail * 0.9) {char kb[32], ab[32];human(kv_need, kb, sizeof kb); human(avail, ab, sizeof ab);@@ -1052,10 +1028,10 @@ int main(int argc, char **argv)* this machine has, minus a safety margin, and the cache gets real memory only* after the whole 110 GB trunk would be resident. */if (budget_auto) {- const double avail = mem_available_bytes();+ const double avail = k3_mem_available_bytes();if (avail <= 0.0) {- fprintf(stderr, "--preset auto needs /proc/meminfo; pass explicit "- "--trunk-gb/--cache-gb on this platform\n");+ fprintf(stderr, "--preset auto could not read this machine's available memory; "+ "pass explicit --trunk-gb/--cache-gb\n");return 2;}/* Fixed costs outside both budgets: embeddings + lm_head 4.70 GB, safetensors@@ -1086,24 +1062,9 @@ int main(int argc, char **argv)* mildly positive (40.1 s/token at 25 GB, device throughput unharmed).* So below full residency, auto pins only while the whole process stays* comfortably clear of the RAM ceiling. */- double memtotal = 0.0;-#ifdef _WIN32- {- MEMORYSTATUSEX ms;- ms.dwLength = sizeof ms;- if (GlobalMemoryStatusEx(&ms)) memtotal = (double)ms.ullTotalPhys;- }-#else- FILE *mf = fopen("/proc/meminfo", "r");- if (mf) {- char ln[256];- while (fgets(ln, sizeof ln, mf))- if (!strncmp(ln, "MemTotal:", 9)) { memtotal = atof(ln + 9) * 1024.0; break; }- fclose(mf);- }-#endif+ const double memtotal = k3_mem_total_bytes();const double rss_ceiling = memtotal > 0.0 ? 0.55 * memtotal / 1e9- : usable; /* no /proc: keep old cap */+ : usable; /* total unknown: keep old cap */double cap = rss_ceiling - reserve - cache_min;if (cap < slot_min) cap = slot_min;trunk_gb = usable - cache_min;@@ -1309,7 +1270,7 @@ int main(int argc, char **argv)* incremental decode allocates the KV cache; full recompute carries no cache. */if (incremental) {const double kv_need = (double)(np + gen + 1) * K3_KV_BYTES_PER_POS;- const double avail = mem_available_bytes();+ const double avail = k3_mem_available_bytes();char kb[32], ab[32];human(kv_need, kb, sizeof kb);human(avail, ab, sizeof ab);@@ -1401,7 +1362,7 @@ int main(int argc, char **argv)* ((double)c.n_heads * (c.qk_nope + c.v_head) + c.qk_rope) * 4: 0.0;const double need_b = w_trunk + w_model + w_cache + w_state + w_buf + w_kv;- const double have = mem_available_bytes();+ const double have = k3_mem_available_bytes();char b2[32], b3[32], b4[32], b5[32], b6[32], b7[32];human(w_kv, b7, sizeof b7);diff --git a/src/cli/k3_sysmem.h b/src/cli/k3_sysmem.hnew file mode 100644index 0000000..9207fa1--- /dev/null+++ b/src/cli/k3_sysmem.h@@ -0,0 +1,95 @@+/* k3_sysmem.h - how much memory this machine can actually hand out, on every platform+ * the engine builds on.+ *+ * Two refusals in k3_run.c compare the plan against this number: the KV cache check+ * and the whole-plan check before allocation. Both are guarded by "available > 0", so+ * a probe that returns 0 does not fail loudly, it silently turns both guards off, and+ * --preset auto refuses outright. Until this header the probe was /proc/meminfo behind+ * #ifdef _WIN32, which is exactly 0 on macOS.+ *+ * Linux MemAvailable, the kernel's own estimate of what can be handed out without+ * swapping, which counts reclaimable page cache; MemFree does not.+ * Darwin free + inactive + purgeable pages from host_statistics64. Darwin has no+ * MemAvailable; this is the same set of pages, the ones the kernel will give+ * up without paging anything out. free_count already includes speculative.+ * Windows ullAvailPhys, the MemAvailable equivalent (it accounts for the standby+ * list the way MemAvailable accounts for cache), capped by ullAvailPageFile,+ * the remaining commit limit: a machine with a small pagefile can refuse to+ * commit an allocation while plenty of physical memory sits free, and the+ * engine's arenas are committed up front.+ *+ * Both functions return 0 when the platform cannot say, which every caller already+ * treats as "unknown", not as "none". */+#ifndef K3_SYSMEM_H+#define K3_SYSMEM_H++#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#if defined(_WIN32)+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#elif defined(__APPLE__)+#include <mach/mach.h>+#include <sys/sysctl.h>+#endif++#if !defined(_WIN32) && !defined(__APPLE__)+/* One "Field:" line of /proc/meminfo, in bytes; 0 if absent. */+static double k3_meminfo_field(const char *field)+{+ FILE *f = fopen("/proc/meminfo", "r");+ if (!f) return 0.0;+ const size_t n = strlen(field);+ char line[256];+ double kb = 0.0;+ while (fgets(line, sizeof line, f))+ if (!strncmp(line, field, n)) { kb = atof(line + n); break; }+ fclose(f);+ return kb * 1024.0;+}+#endif++static double k3_mem_available_bytes(void)+{+#if defined(_WIN32)+ MEMORYSTATUSEX ms;+ ms.dwLength = sizeof ms;+ if (!GlobalMemoryStatusEx(&ms)) return 0.0;+ return (double)(ms.ullAvailPhys < ms.ullAvailPageFile ? ms.ullAvailPhys+ : ms.ullAvailPageFile);+#elif defined(__APPLE__)+ vm_statistics64_data_t vm;+ mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;+ vm_size_t page = 0;+ const mach_port_t host = mach_host_self();+ if (host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&vm, &count) != KERN_SUCCESS)+ return 0.0;+ if (host_page_size(host, &page) != KERN_SUCCESS || page == 0) return 0.0;+ return ((double)vm.free_count + (double)vm.inactive_count + (double)vm.purgeable_count)+ * (double)page;+#else+ return k3_meminfo_field("MemAvailable:");+#endif+}++static double k3_mem_total_bytes(void)+{+#if defined(_WIN32)+ MEMORYSTATUSEX ms;+ ms.dwLength = sizeof ms;+ if (!GlobalMemoryStatusEx(&ms)) return 0.0;+ return (double)ms.ullTotalPhys;+#elif defined(__APPLE__)+ uint64_t bytes = 0;+ size_t len = sizeof bytes;+ if (sysctlbyname("hw.memsize", &bytes, &len, NULL, 0) != 0) return 0.0;+ return (double)bytes;+#else+ return k3_meminfo_field("MemTotal:");+#endif+}++#endif /* K3_SYSMEM_H */diff --git a/tests/unit/test_sysmem.c b/tests/unit/test_sysmem.cnew file mode 100644index 0000000..8b15af2--- /dev/null+++ b/tests/unit/test_sysmem.c@@ -0,0 +1,74 @@+/* test_sysmem.c - the available-memory probe must return a real number on every+ * platform the engine builds on.+ *+ * WHY THIS FILE EXISTS+ * Two refusals in k3_run.c compare the memory plan against what the machine can+ * actually hand out: the KV cache check and the whole-plan check before+ * allocation. Both are written as "if (available > 0 && need > available)", so a+ * probe that returns 0 does not fail loudly, it silently disables both guards, and+ * --preset auto refuses outright. Before src/cli/k3_sysmem.h the probe was+ * /proc/meminfo behind #ifdef _WIN32, which is exactly 0 on macOS. This test fails+ * on any platform where the number is 0 or impossible.+ *+ * usage: test_sysmem+ */+#define _POSIX_C_SOURCE 200809L+#if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE)+#define _DARWIN_C_SOURCE+#endif++#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "k3_sysmem.h"++static int g_fail = 0;++static void ck(int ok, const char *what, const char *detail)+{+ printf(" %s %-40s %s\n", ok ? "PASS" : "FAIL", what, detail ? detail : "");+ if (!ok) g_fail++;+}++int main(void)+{+ const double avail = k3_mem_available_bytes();+ const double total = k3_mem_total_bytes();+ char d[96];++ printf("system memory probe\n");+ snprintf(d, sizeof d, "%.2f GB", total / 1e9);+ ck(total > 0.0, "total is known", d);+ snprintf(d, sizeof d, "%.2f GB", avail / 1e9);+ ck(avail > 0.0, "available is known (0 disables two refusals)", d);+ ck(avail <= total, "available does not exceed total", NULL);+ /* Any real machine that can run this test has more than this to spare; a probe+ * that returns a page count where bytes were wanted lands far below it. */+ ck(avail >= 64.0 * 1024 * 1024, "available is at least 64 MB", d);++#if !defined(_WIN32) && !defined(__APPLE__)+ {+ /* Linux: the probe must agree with an independent read of the same source.+ * Memory moves between two reads, so the bound is loose, but a wrong field or+ * a wrong unit is off by far more than this. */+ FILE *f = fopen("/proc/meminfo", "r");+ double kb_avail = 0.0, kb_total = 0.0;+ char line[256];+ while (f && fgets(line, sizeof line, f)) {+ unsigned long long v;+ if (sscanf(line, "MemAvailable: %llu kB", &v) == 1) kb_avail = (double)v;+ if (sscanf(line, "MemTotal: %llu kB", &v) == 1) kb_total = (double)v;+ }+ if (f) fclose(f);+ const double ref_avail = kb_avail * 1024.0, ref_total = kb_total * 1024.0;+ snprintf(d, sizeof d, "probe %.3f GB, sscanf %.3f GB", avail / 1e9, ref_avail / 1e9);+ ck(ref_avail > 0.0 && avail > 0.8 * ref_avail && avail < 1.25 * ref_avail,+ "available agrees with /proc/meminfo", d);+ ck(ref_total > 0.0 && total == ref_total, "total equals MemTotal", NULL);+ }+#endif++ printf("\n%s\n", g_fail ? "SYSMEM TESTS FAILED" : "SYSMEM TESTS PASSED");+ return g_fail ? 1 : 0;+}