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
merge: overlap trunk reads with layer compute
FareedKhan-devca52ac581950
diff --cc Makefileindex 6c155fa,36347de..0a61a13--- a/Makefile+++ b/Makefile@@@ -80,8 -30,8 +80,11 @@@ endi# disabling automatic FMA contraction. The test-suite compares against a reference to a# fixed tolerance; letting the compiler fuse changes results by more than that.WARN := -Wall -Wextra -Wpointer-arith -Wshadow -Wvla -Wno-unused-parameter- CFLAGS ?= -O3 -std=gnu99 $(WARN) $(ARCH) $(OMP_CFLAGS) -ffp-contract=off- LDFLAGS ?= -lm $(OMP_LDFLAGS)-CFLAGS ?= -O3 -std=gnu99 $(WARN) $(ARCH) -fopenmp -pthread -ffp-contract=off-LDFLAGS ?= -lm -fopenmp -pthread++# -pthread is for the trunk's asynchronous reader, which is a plain pthread rather than++# an OpenMP construct. It composes with the platform OpenMP flags above rather than++# replacing them: Apple Clang needs -Xpreprocessor -fopenmp AND -pthread.++CFLAGS ?= -O3 -std=gnu99 $(WARN) $(ARCH) $(OMP_CFLAGS) -pthread -ffp-contract=off++LDFLAGS ?= -lm $(OMP_LDFLAGS) -pthread# Flat include search across the module dirs: sources use "k3.h", "k3_cache.h" etc# rather than path-qualified includes, which keeps them relocatable.diff --cc src/cli/k3_run.cindex 65cae2e,4e3afb7..a27838b--- a/src/cli/k3_run.c+++ b/src/cli/k3_run.c@@@ -865,10 -851,10 +865,17 @@@ int main(int argc, char **argv* trunk time with a last-step expert time and dividing by the whole run* understates the expert share by roughly the token count. */const double io_s = trunk_s + expert_s_total;++ const double share = t_total > 0 ? 100.0 * io_s / t_total : 0.0;printf("I/O share of wall clock: %.1f%% (trunk %.1f s + experts %.1f s of %.1f s)\n",-- t_total > 0 ? 100.0 * io_s / t_total : 0.0, trunk_s,-- expert_s_total, t_total);++ share, trunk_s, expert_s_total, t_total);printf(" both figures are WHOLE-RUN totals over %d steps\n", nout);++ /* Above 100% is not a bug in the arithmetic: with more than one trunk ring slot++ * the reader thread does device work while the main thread computes, so the two++ * terms genuinely overlap and their sum can exceed wall clock. Say so, rather++ * than printing an impossible percentage with no explanation. */++ if (share > 100.0)++ printf(" over 100%% because trunk reads overlap compute on the reader thread;\n"++ " %.1f s of device time was hidden behind arithmetic\n", io_s - t_total);/* Report the DERIVED retention, not the raw hit count. `hits` counts an expert* the batch prefetch pulled off disk microseconds earlier, so it equals the* request count at every cache size and means nothing on its own. An expert thatdiff --cc src/io/k3_trunk.cindex d4f37f5,cb0b3e1..b2c7f21--- a/src/io/k3_trunk.c+++ b/src/io/k3_trunk.c@@@ -173,18 -185,9 +189,18 @@@ int k3_trunk_open(K3Trunk *tr, const chif (!tr->slot_of) return -1;for (int i = 0; i < tr->n_layers; i++) tr->slot_of[i] = -1;- /* ONE ring slot, not two.- *- * The second slot was sized for a prefetch that does not exist: k3_trunk_prefetch is- * inert on the O_DIRECT path, because POSIX_FADV_WILLNEED warms the page cache and- * O_DIRECT bypasses it. The engine's own logs prove the slot never paid for itself:- * the 12 GB run reports "binds 558, hits 0 (0.0%)". A cyclic 0..92 scan cannot hit in- * a 2-slot ring anyway, so the slot held 2.34 GB and returned nothing, which is 20%- * of a 12 GB budget.- /* Two ring slots: current layer plus one asynchronous read in flight. The old- * implementation allocated a spare slot without a reader, wasting memory. */- const int RING = 2;++ /* Two ring slots: the layer being computed on, plus one asynchronous read in flight.+ *- * Restore RING = 2 only alongside a real asynchronous reader (a thread or io_uring)- * filling the spare slot, at which point it starts earning its keep. */- const int RING = 1;++ * This is a REQUEST, not a guarantee. The second slot costs a full slot's worth of++ * memory, which at the floor is 2.37 GB, and the budget the caller asked for has to++ * come first: measured on the released checkpoint, taking the second slot++ * unconditionally moved the laptop preset from 8.78 GB to 11.12 GB peak RSS, a 27%++ * overshoot of a 3.0 GB trunk budget, and left the printed memory plan understating++ * the real figure. So it is granted only when it fits, and reported when it does not.++ * A single slot is exactly what this file did before the asynchronous reader existed,++ * so falling back is always safe; it costs speed, not correctness. */++ const int RING_WANT = 2;++ int RING = RING_WANT;/* Size the ring from the layers that will actually STREAM through it.*@@@ -211,6 -214,6 +227,12 @@@rs += (int64_t)widen;rs = (rs + 4095) & ~(int64_t)4095;++ /* The ring itself must fit the budget before any layer is pinned. The loop below++ * only ever tested ADDITIONAL pinned layers against it, so RING * rs was spent++ * whether or not it fitted. Drop to one slot rather than overshoot. */++ RING = RING_WANT;++ while (RING > 1 && (int64_t)RING * rs > budget_bytes) RING--;++int64_t sp = (int64_t)RING * rs;int np = 0;while (np < tr->n_layers) {@@@ -255,6 -273,6 +292,14 @@@RING, (double)ring_slot / 1e9);printf(" reads use %s\n",tr->direct ? "O_DIRECT (page cache bypassed)" : "buffered I/O");++ if (RING < RING_WANT)++ printf(" ring held at %d slot: a second slot needs %.2f GB and the "++ "trunk budget is %.2f GB,\n"++ " so reads are NOT overlapped with compute. Raise --trunk-gb "++ "above %.2f GB to enable it.\n",++ RING, (double)RING_WANT * ring_slot / 1e9,++ (double)budget_bytes / 1e9,++ (double)RING_WANT * ring_slot / 1e9);printf(" deterministic hit rate %.1f%% (a cyclic scan defeats LRU, so ""a pinned prefix is used instead)\n", 100.0 * npin / tr->n_layers);return 0;@@@ -419,14 -499,14 +526,32 @@@ void k3_trunk_report(const K3Trunk *tr* Reporting the widen step separately is what distinguishes a slow device from* excessive work per bind, two causes with the same symptom and different fixes. */{-- const double other = k3_trunk_bind_wall - tr->load_seconds - k3_trunk_widen_wall;-- printf(" bind wall %.2f s over %ld binds = read %.2f + widen %.2f + other %.2f\n",-- k3_trunk_bind_wall, k3_trunk_binds, tr->load_seconds,-- k3_trunk_widen_wall, other);-- if (k3_trunk_bind_wall > 0.0)-- printf(" shares: read %.0f%% widen %.0f%% other %.0f%%\n",-- 100.0 * tr->load_seconds / k3_trunk_bind_wall,-- 100.0 * k3_trunk_widen_wall / k3_trunk_bind_wall,-- 100.0 * other / k3_trunk_bind_wall);++ /* load_seconds is DEVICE time and, with more than one ring slot, some of it++ * happens on the reader thread while the main thread is computing. Subtracting it++ * from bind wall clock then goes negative by exactly the amount of overlap++ * achieved, which is how the previous form of this line reported the feature++ * working as "other -157.06" and a read share of 207%. Overlapped time is a++ * result, not unattributed overhead, so it is named rather than subtracted. */++ const double serial = tr->load_seconds + k3_trunk_widen_wall;++ const double overlapped = serial - k3_trunk_bind_wall;++ if (overlapped > 0.0) {++ printf(" bind wall %.2f s over %ld binds; read %.2f + widen %.2f = %.2f s of "++ "device work,\n"++ " of which %.2f s (%.0f%%) overlapped compute on the "++ "reader thread\n",++ k3_trunk_bind_wall, k3_trunk_binds, tr->load_seconds,++ k3_trunk_widen_wall, serial, overlapped,++ serial > 0.0 ? 100.0 * overlapped / serial : 0.0);++ } else {++ const double other = k3_trunk_bind_wall - serial;++ printf(" bind wall %.2f s over %ld binds = read %.2f + widen %.2f + other %.2f\n",++ k3_trunk_bind_wall, k3_trunk_binds, tr->load_seconds,++ k3_trunk_widen_wall, other);++ if (k3_trunk_bind_wall > 0.0)++ printf(" shares: read %.0f%% widen %.0f%% other %.0f%%\n",++ 100.0 * tr->load_seconds / k3_trunk_bind_wall,++ 100.0 * k3_trunk_widen_wall / k3_trunk_bind_wall,++ 100.0 * other / k3_trunk_bind_wall);++ }}}diff --cc src/io/k3_trunk.hindex fa6e7b2,363d849..f8bdfc5--- a/src/io/k3_trunk.h+++ b/src/io/k3_trunk.h@@@ -23,10 -23,10 +23,17 @@@* the trunk access order is FIXED: layer 0, 1, ... 92, every single token, so the next* read is always known in advance.*-- * NOTE it is not currently hidden. k3_trunk_prefetch is a no-op on the O_DIRECT path-- * (POSIX_FADV_WILLNEED warms the page cache, which O_DIRECT exists to bypass), so the-- * read does not overlap the previous layer's arithmetic today. Doing so needs real-- * async I/O; the fixed order is what would make it straightforward.++ * It IS hidden now. k3_trunk_prefetch hands layer L+1 to a reader thread while the++ * main thread computes on layer L, which is what the fixed walk order makes safe: the++ * next layer is always known, so there is nothing to predict. Measured on the released++ * checkpoint at the laptop preset, this took 71.75 s/token to 42.27 s/token, a 1.70x++ * improvement, and it beat running the same model with four times the memory and no++ * overlap.++ *++ * The second ring slot it needs costs a full slot, 2.37 GB at the floor, so it is only++ * taken when the trunk budget can pay for it. Below that the ring stays at one slot and++ * reads are serial again; k3_trunk_open says so on stdout when that happens. Correctness++ * does not depend on which path runs, and the emitted tokens are identical either way.** WHY LRU WOULD BE THE WORST POSSIBLE POLICY HERE* A cyclic sequential scan is the classic LRU pathology. With N < 93 slots, by the