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
perf: add the memory-ladder and split-sweep harnesses
FareedKhan-dev64155c831a79
diff --git a/benchmarks/bench_kernels.c b/benchmarks/bench_kernels.cnew file mode 100644index 0000000..5810538--- /dev/null+++ b/benchmarks/bench_kernels.c@@ -0,0 +1,134 @@+/* bench_kernels.c - where does the arithmetic actually go?+ *+ * The engine's decode time at the memory floor splits roughly 36 s trunk read, 11 s+ * expert read, 10 s compute. The read paths are now within 10-20% of what the device can+ * deliver, so the only lossless win left is the compute. Before optimising it, measure+ * which kernel owns it -- guessing which loop is hot is how people spend a week making+ * something 2% faster.+ *+ * Dimensions here are the REAL ones, per token:+ * bf16 trunk matmuls the attention projections, latent down/up, shared experts and+ * the dense MLP. Sized from the actual layer shapes.+ * MXFP4 expert matmuls 16 experts x 3 matrices x 92 layers, in latent space.+ *+ * Reports GFLOP/s and the projected per-token seconds for each, so the two can be+ * compared directly against the measured 10 s compute budget.+ */+#define _POSIX_C_SOURCE 199309L++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#include "k3.h"++static double now_s(void)+{+ struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec + t.tv_nsec * 1e-9;+}++/* Exact bits of a whole output vector.+ *+ * Building this file with and without AVX2 and comparing these hashes is the ONLY real+ * proof that a vector path is bit-identical rather than merely close. A tolerance check+ * would happily pass a kernel that quietly reassociated the reduction, which is exactly+ * the mistake worth catching: this engine's claim is that its output equals the+ * reference, and "equals" has to mean equals. */+static void fnv(const char *label, const float *v, int n)+{+ unsigned long long h = 1469598103934665603ull;+ for (int k = 0; k < n; k++) {+ union { float f; unsigned u; } b; b.f = v[k];+ for (int t = 0; t < 4; t++) { h ^= (b.u >> (8 * t)) & 0xFFu; h *= 1099511628211ull; }+ }+ printf(" %s OUTPUT FNV1a = %016llx\n", label, h);+}++static void fillf(float *p, size_t n, unsigned s)+{+ for (size_t i = 0; i < n; i++) {+ s ^= s << 13; s ^= s >> 17; s ^= s << 5;+ p[i] = ((float)(s >> 8) / 8388608.0f - 1.0f) * 0.05f;+ }+}+static void fillb(unsigned char *p, size_t n, unsigned s)+{+ for (size_t i = 0; i < n; i++) {+ s ^= s << 13; s ^= s >> 17; s ^= s << 5;+ p[i] = (unsigned char)(s >> 13);+ }+}++int main(void)+{+ printf("kernel benchmark at REAL Kimi K3 dimensions\n");+#ifdef __AVX2__+ printf("built WITH AVX2\n\n");+#else+ printf("built WITHOUT AVX2 (scalar)\n\n");+#endif++ /* ---------- bf16 trunk matmul: KDA q_proj, 7168 -> 12288 ---------- */+ {+ const int in = 7168, out = 12288;+ uint16_t *W = (uint16_t *)malloc((size_t)in * out * sizeof(uint16_t));+ float *x = (float *)malloc((size_t)in * sizeof(float));+ float *y = (float *)malloc((size_t)out * sizeof(float));+ if (!W || !x || !y) { printf("alloc failed\n"); return 1; }+ fillb((unsigned char *)W, (size_t)in * out * 2, 12345u);+ fillf(x, in, 999u);++ k3_matmul_bf16(y, x, W, in, out); /* warm */+ const int reps = 5;+ const double t0 = now_s();+ for (int r = 0; r < reps; r++) k3_matmul_bf16(y, x, W, in, out);+ const double dt = (now_s() - t0) / reps;+ const double gflop = 2.0 * in * out / 1e9;+ printf("bf16 matmul %5d x %-5d %7.2f ms %8.1f GFLOP/s\n",+ out, in, dt * 1e3, gflop / dt);++ /* Per token the trunk is 56.74 G always-active params = 113.49 GFLOP of+ * multiply-add. Project from the rate just measured. */+ fnv("bf16 ", y, out);+ printf(" trunk is 56.74 G params/token -> %.2f s/token at this rate\n",+ 2.0 * 56.74e9 / 1e9 / (gflop / dt));+ free(W); free(x); free(y);+ }++ /* ---------- MXFP4 expert matmul: w1, latent 3584 -> inter 3072 ---------- */+ {+ const int in = 3584, rows = 3072, group = K3_MXFP4_GROUP;+ const int pcols = in / 2, ngrp = in / group;+ unsigned char *pk = (unsigned char *)malloc((size_t)rows * pcols);+ unsigned char *sc = (unsigned char *)malloc((size_t)rows * ngrp);+ float *x = (float *)malloc((size_t)in * sizeof(float));+ float *y = (float *)malloc((size_t)rows * sizeof(float));+ if (!pk || !sc || !x || !y) { printf("alloc failed\n"); return 1; }+ fillb(pk, (size_t)rows * pcols, 777u);+ memset(sc, 127, (size_t)rows * ngrp); /* scale 2^0, none skipped */+ fillf(x, in, 4242u);++ k3_matmul_mxfp4(y, x, pk, sc, in, rows, group);+ const int reps = 5;+ const double t0 = now_s();+ for (int r = 0; r < reps; r++) k3_matmul_mxfp4(y, x, pk, sc, in, rows, group);+ const double dt = (now_s() - t0) / reps;+ const double gflop = 2.0 * in * rows / 1e9;+ printf("\nMXFP4 matmul %5d x %-5d %7.2f ms %8.1f GFLOP/s\n",+ rows, in, dt * 1e3, gflop / dt);++ /* One expert is w1 + w3 (both 3072x3584) + w2 (3584x3072) = 3 of these.+ * 16 experts x 92 MoE layers per token. */+ fnv("mxfp4", y, rows);+ const double per_tok = dt * 3.0 * 16 * 92;+ printf(" 16 experts x 3 mats x 92 layers -> %.2f s/token\n", per_tok);+ free(pk); free(sc); free(x); free(y);+ }++ printf("\nmeasured compute budget at the floor is about 10 s/token; whichever line\n"+ "above dominates it is the one worth vectorising.\n");+ return 0;+}diff --git a/benchmarks/memory-ladder.sh b/benchmarks/memory-ladder.shnew file mode 100644index 0000000..1702c65--- /dev/null+++ b/benchmarks/memory-ladder.sh@@ -0,0 +1,157 @@+#!/usr/bin/env bash+# Sweep the memory budget and check that output is identical at every rung.+#+# benchmarks/memory-ladder.sh <model_dir> <trunk_dir> <out_dir> [reps]+#+# Defaults to 3 repetitions per rung, because the measured run-to-run spread on an+# identical configuration is 33%, a single sample per rung cannot distinguish an effect+# from noise. See docs/BENCHMARKING.md.+#+# LINUX ONLY. Imposing a memory ceiling needs cgroups via systemd-run. There is no+# portable equivalent, and without a real ceiling every rung simply uses as much memory+# as it likes, so the ladder measures nothing while still producing a full table.+set -u+MODEL="${1:?usage: memory-ladder.sh <model_dir> <trunk_dir> <out_dir> [reps]}"+TRUNK="${2:?}"+OUT="${3:?}"+REPS="${4:-3}"+IDS=1008,10484,318,15383,387+GEN=8++# Preflight. Each of these, left unchecked, yields a COMPLETE and plausible-looking+# ladder composed entirely of failures, because the runner below cannot otherwise tell+# "killed for exceeding its memory ceiling" apart from "the command does not exist".+command -v systemd-run >/dev/null 2>&1 || {+ echo "systemd-run not found. This harness needs it to impose a genuine memory ceiling;"+ echo "without one every rung would run unconstrained and the ladder would be"+ echo "meaningless rather than merely wrong. Linux with systemd is required."+ exit 1+}+systemd-run --scope --user -q true 2>/dev/null || {+ echo "systemd-run --user does not work here (no user session bus?)."+ echo "Try: loginctl enable-linger \$USER, or run under a full login session."+ exit 1+}+[ -x ./bin/k3 ] || { echo "./bin/k3 not built, run 'make -j' first"; exit 1; }+[ -d "$MODEL" ] || { echo "no such model dir: $MODEL"; exit 1; }+[ -d "$TRUNK" ] || { echo "no such trunk dir: $TRUNK, run scripts/pack-trunk.sh"; exit 1; }+command -v python3 >/dev/null || { echo "python3 required for the summary"; exit 1; }++mkdir -p "$OUT"+TSV="$OUT/ladder.tsv"+printf 'total_gb\ttrunk_gb\tcache_gb\trep\ts_per_tok\tpeak_rss_gb\tgb_read\tids\n' > "$TSV"++# Machine provenance. A ladder without it cannot be compared against another machine's,+# and these are the first numbers anyone asks for when two ladders disagree.+{+ echo "date : $(date -u +%Y-%m-%dT%H:%M:%SZ)"+ echo "host : $(uname -srm)"+ echo "cpu : $(grep -m1 'model name' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')"+ echo "cores : $(nproc 2>/dev/null || echo '?')"+ echo "memtotal : $(awk '/MemTotal/{printf "%.1f GB", $2/1048576}' /proc/meminfo 2>/dev/null)"+ echo "swaptotal : $(awk '/SwapTotal/{printf "%.1f GB", $2/1048576}' /proc/meminfo 2>/dev/null)"+ echo "trunk_fs : $(df -PT "$TRUNK" 2>/dev/null | awk 'NR==2{print $2, $1}')"+ echo "model_fs : $(df -PT "$MODEL" 2>/dev/null | awk 'NR==2{print $2, $1}')"+ echo "k3 : $(./bin/k3 --version 2>&1 | head -1)"+ echo "reps/rung : $REPS"+ echo "ids : $IDS"+ echo "gen : $GEN"+} > "$OUT/machine.txt"+cat "$OUT/machine.txt"+echo++# Budget -> split. The trunk is filled first: it is re-read in full every token, while+# only ~25.8 GB of experts are touched. docs/TUNING.md has the measurements.+rungs="8:3:1 16:7:4 32:16:10 64:35:24 96:60:30 128:110:13"++REF=""+REF_RUNG=""+DIVERGED=0+for rung in $rungs; do+ TOT=${rung%%:*}; rest=${rung#*:}; TR=${rest%%:*}; CA=${rest#*:}+ for r in $(seq 1 "$REPS"); do+ tag="${TOT}gb_r${r}"+ echo "== ${TOT} GB (trunk ${TR} / cache ${CA}) rep ${r}/${REPS} =="++ # MemorySwapMax=0 alongside MemoryMax. Without it, a rung that exceeds its+ # ceiling swaps instead of dying: the run "passes" and its s/token measures swap+ # bandwidth rather than the configuration under test. That is a wrong number+ # wearing the shape of a right one, which is worse than a missing row.+ systemd-run --scope --user -q \+ -p MemoryMax=${TOT}G -p MemorySwapMax=0 \+ ./bin/k3 "$MODEL" --ids "$IDS" --gen "$GEN" \+ --trunk "$TRUNK" --trunk-gb "$TR" --cache-gb "$CA" --incremental \+ --out "$OUT/$tag.json" > "$OUT/$tag.log" 2>&1+ rc=$?++ if [ $rc -ne 0 ]; then+ # Distinguish "did not fit" from "broke". Only SIGKILL (137), which is how+ # the kernel terminates a cgroup over MemoryMax, is a legitimate rung result.+ # Recording any other failure as OOM fabricates a data point.+ if [ $rc -eq 137 ] || grep -qi 'out of memory\|oom-kill' "$OUT/$tag.log"; then+ printf '%s\t%s\t%s\t%s\tOOM\t-\t-\t-\n' "$TOT" "$TR" "$CA" "$r" >> "$TSV"+ echo " did not fit, that is a result, not an error"+ continue+ fi+ echo " *** FAILED with exit $rc, not an OOM, and not a data point ***"+ tail -5 "$OUT/$tag.log" | sed 's/^/ | /'+ exit 1+ fi++ SPT=$(grep -oE '[0-9.]+ s/token average' "$OUT/$tag.log" | tail -1 | awk '{print $1}')+ RSS=$(grep -oE 'PEAK RSS for the whole run: [0-9.]+' "$OUT/$tag.log" | tail -1 | awk '{print $7}')+ GBR=$(grep -oE 'read from disk: [0-9.]+ GB' "$OUT/$tag.log" | tail -1 | awk '{print $4}')+ IDSO=$(python3 -c "import json,sys;print(','.join(map(str,json.load(open(sys.argv[1]))['generated_ids'])))" "$OUT/$tag.json" 2>/dev/null)++ # The determinism assertion is the entire point of this harness, so it must not+ # pass vacuously. An unreadable result file leaves IDSO empty, and comparing+ # empty against empty would "confirm" identical output at every rung.+ if [ -z "$IDSO" ]; then+ echo " *** could not read generated_ids from $OUT/$tag.json ***"+ exit 1+ fi+ if [ -z "$REF" ]; then+ REF="$IDSO"; REF_RUNG="${TOT} GB rep $r"+ elif [ "$IDSO" != "$REF" ]; then+ echo " *** OUTPUT DIFFERS from $REF_RUNG, this is a bug ***"+ echo " expected: $REF"+ echo " got : $IDSO"+ DIVERGED=1+ fi++ printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \+ "$TOT" "$TR" "$CA" "$r" "${SPT:--}" "${RSS:--}" "${GBR:--}" "$IDSO" >> "$TSV"+ echo " ${SPT} s/token, peak RSS ${RSS} GB"+ done+done++echo+column -t "$TSV"+echo+python3 - "$TSV" <<'PY'+import sys, csv, statistics, collections+rows = list(csv.DictReader(open(sys.argv[1]), delimiter='\t'))+by = collections.defaultdict(list)+for r in rows:+ try: by[r['total_gb']].append(float(r['s_per_tok']))+ except (ValueError, KeyError): pass+print(f"{'budget':>8} {'mean':>7} {'sd':>6} {'spread':>7} n")+for k, v in sorted(by.items(), key=lambda kv: int(kv[0])):+ if not v: continue+ m = statistics.mean(v)+ sd = statistics.stdev(v) if len(v) > 1 else 0.0+ sp = (max(v) - min(v)) / m * 100 if len(v) > 1 else 0.0+ print(f"{k+' GB':>8} {m:7.2f} {sd:6.2f} {sp:6.1f}% {len(v)}")+ if len(v) == 1:+ print(f"{'':>8} ^ one sample: no spread, so no conclusion from this rung")+print("\nA difference between budgets that is smaller than the spread within a budget"+ "\nis not an effect.")+PY++if [ "$DIVERGED" -ne 0 ]; then+ echo+ echo "FAIL: output was not identical across memory budgets."+ exit 1+fi+echo+echo "Output identical at every rung. Machine details: $OUT/machine.txt"diff --git a/benchmarks/split-sweep.sh b/benchmarks/split-sweep.shnew file mode 100644index 0000000..717380f--- /dev/null+++ b/benchmarks/split-sweep.sh@@ -0,0 +1,149 @@+#!/usr/bin/env bash+# Hold total memory FIXED and sweep the trunk/cache split.+#+# benchmarks/split-sweep.sh <model_dir> <trunk_dir> <out_dir> [total_gb] [reps]+#+# This is the experiment behind the single most useful tuning result in the project:+# at a fixed budget, memory given to the trunk is worth more than memory given to the+# expert cache. memory-ladder.sh varies the total and cannot separate "more memory" from+# "better-allocated memory"; this script varies only the allocation, so any difference it+# finds is attributable to the split alone.+#+# Defaults to 3 repetitions per split. docs/PERFORMANCE.md records a 33% run-to-run+# spread on identical configurations, which is large enough that a one-sample-per-split+# sweep cannot distinguish an allocation effect from dispersion.+#+# LINUX ONLY see the note in memory-ladder.sh.+set -u+MODEL="${1:?usage: split-sweep.sh <model_dir> <trunk_dir> <out_dir> [total_gb] [reps]}"+TRUNK="${2:?}"+OUT="${3:?}"+TOTAL="${4:-128}"+REPS="${5:-3}"+IDS=1008,10484,318,15383,387+GEN=8++command -v systemd-run >/dev/null 2>&1 || {+ echo "systemd-run not found; a genuine memory ceiling is required. See memory-ladder.sh."+ exit 1+}+systemd-run --scope --user -q true 2>/dev/null || {+ echo "systemd-run --user does not work here (no user session bus?)."+ exit 1+}+[ -x ./bin/k3 ] || { echo "./bin/k3 not built, run 'make -j' first"; exit 1; }+[ -d "$MODEL" ] || { echo "no such model dir: $MODEL"; exit 1; }+[ -d "$TRUNK" ] || { echo "no such trunk dir: $TRUNK, run scripts/pack-trunk.sh"; exit 1; }+command -v python3 >/dev/null || { echo "python3 required for the summary"; exit 1; }++mkdir -p "$OUT"+TSV="$OUT/split.tsv"+printf 'total_gb\ttrunk_gb\tcache_gb\trep\ts_per_tok\tpeak_rss_gb\tgb_read\tids\n' > "$TSV"++{+ echo "date : $(date -u +%Y-%m-%dT%H:%M:%SZ)"+ echo "host : $(uname -srm)"+ echo "cpu : $(grep -m1 'model name' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')"+ echo "cores : $(nproc 2>/dev/null || echo '?')"+ echo "memtotal : $(awk '/MemTotal/{printf "%.1f GB", $2/1048576}' /proc/meminfo 2>/dev/null)"+ echo "trunk_fs : $(df -PT "$TRUNK" 2>/dev/null | awk 'NR==2{print $2, $1}')"+ echo "k3 : $(./bin/k3 --version 2>&1 | head -1)"+ echo "total_gb : $TOTAL"+ echo "reps/split : $REPS"+} > "$OUT/machine.txt"+cat "$OUT/machine.txt"+echo++# Fractions of the budget given to the trunk, cache-heavy first so the sweep runs against+# the hypothesis rather than with it. The engine needs a few GB outside both budgets, so+# the two never sum to the full total.+FRACS="0.10 0.25 0.60 0.86"++REF=""+DIVERGED=0+for f in $FRACS; do+ TR=$(python3 -c "print(round($TOTAL * $f, 1))")+ CA=$(python3 -c "print(round($TOTAL * (1 - $f) - 4, 1))")+ for r in $(seq 1 "$REPS"); do+ tag="tr${TR}_r${r}"+ echo "== ${TOTAL} GB total: trunk ${TR} / cache ${CA}, rep ${r}/${REPS} =="+ systemd-run --scope --user -q \+ -p MemoryMax=${TOTAL}G -p MemorySwapMax=0 \+ ./bin/k3 "$MODEL" --ids "$IDS" --gen "$GEN" \+ --trunk "$TRUNK" --trunk-gb "$TR" --cache-gb "$CA" --incremental \+ --out "$OUT/$tag.json" > "$OUT/$tag.log" 2>&1+ rc=$?+ if [ $rc -ne 0 ]; then+ # Unlike the ladder, an OOM here is a HARNESS defect, not a result: every+ # split in this sweep is sized to fit the same fixed total. Recording it as+ # a data point would hide a mis-sized split.+ echo " *** FAILED with exit $rc at a split that should fit ***"+ tail -5 "$OUT/$tag.log" | sed 's/^/ | /'+ exit 1+ fi+ SPT=$(grep -oE '[0-9.]+ s/token average' "$OUT/$tag.log" | tail -1 | awk '{print $1}')+ RSS=$(grep -oE 'PEAK RSS for the whole run: [0-9.]+' "$OUT/$tag.log" | tail -1 | awk '{print $7}')+ GBR=$(grep -oE 'read from disk: [0-9.]+ GB' "$OUT/$tag.log" | tail -1 | awk '{print $4}')+ IDSO=$(python3 -c "import json,sys;print(','.join(map(str,json.load(open(sys.argv[1]))['generated_ids'])))" "$OUT/$tag.json" 2>/dev/null)+ if [ -z "$IDSO" ]; then+ echo " *** could not read generated_ids from $OUT/$tag.json ***"+ exit 1+ fi+ if [ -z "$REF" ]; then REF="$IDSO"+ elif [ "$IDSO" != "$REF" ]; then+ echo " *** OUTPUT DIFFERS across splits, this is a bug ***"+ DIVERGED=1+ fi+ printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \+ "$TOTAL" "$TR" "$CA" "$r" "${SPT:--}" "${RSS:--}" "${GBR:--}" "$IDSO" >> "$TSV"+ echo " ${SPT} s/token, peak RSS ${RSS} GB, ${GBR} GB read"+ done+done++echo+column -t "$TSV"+echo+python3 - "$TSV" <<'PY'+import sys, csv, statistics, collections+rows = list(csv.DictReader(open(sys.argv[1]), delimiter='\t'))+by = collections.defaultdict(list)+for r in rows:+ try: by[float(r['trunk_gb'])].append(float(r['s_per_tok']))+ except (ValueError, KeyError): pass+if not by:+ print("no usable rows"); raise SystemExit(1)++print(f"{'trunk GB':>9} {'mean':>7} {'sd':>6} {'spread':>7} n")+means = {}+for k in sorted(by):+ v = by[k]+ m = statistics.mean(v)+ sd = statistics.stdev(v) if len(v) > 1 else 0.0+ sp = (max(v) - min(v)) / m * 100 if len(v) > 1 else 0.0+ means[k] = m+ print(f"{k:9.1f} {m:7.2f} {sd:6.2f} {sp:6.1f}% {len(v)}")++lo, hi = min(means), max(means)+factor = means[lo] / means[hi]+worst_spread = max(+ ((max(v) - min(v)) / statistics.mean(v) * 100) for v in by.values() if len(v) > 1+) if any(len(v) > 1 for v in by.values()) else None++print(f"\ntrunk {hi:.1f} GB is {factor:.2f}x faster than trunk {lo:.1f} GB "+ f"at the same total budget.")+ordered = [means[k] for k in sorted(means)]+print("monotonic in trunk size:", "yes" if ordered == sorted(ordered, reverse=True) else "NO")+if worst_spread is not None:+ print(f"worst within-split spread: {worst_spread:.1f}%")+ print("The effect is credible only if the factor above clearly exceeds this spread.")+else:+ print("Only one sample per split, no spread, so no conclusion. Re-run with reps > 1.")+PY++if [ "$DIVERGED" -ne 0 ]; then+ echo+ echo "FAIL: output was not identical across splits."+ exit 1+fi+echo+echo "Output identical at every split. Machine details: $OUT/machine.txt"