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: make the first run work on a stock machine
FareedKhan-dev9cac1ae73f99
diff --git a/Makefile b/Makefileindex 94ab35e..e2a81c1 100644--- a/Makefile+++ b/Makefile@@ -117,11 +117,21 @@ test: $(TEST_BINS)@echo "== safetensors =="; ./$(BIN)/test_st $(FIXTURES)/st $(BUILD)/st_index.json \plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32@echo "== config reader =="; ./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json- @echo "== tokenizer =="; ./$(BIN)/test_tok $(TOK_FILES) roundtrip src/core/k3_ops.c \- || echo " (skipped: no tokenizer files at $(TOK_FILES))"+ @echo "== tokenizer =="; \+ if [ -f "$(TOK_FILES)/tiktoken.model" ]; then \+ ./$(BIN)/test_tok $(TOK_FILES) roundtrip src/core/k3_ops.c; \+ else \+ echo " NOT RUN: no tiktoken.model at $(TOK_FILES)"; \+ echo " the vocabulary ships with the checkpoint, not with this"; \+ echo " repository. Run: make tok TOK_FILES=/path/to/k3model"; \+ fi@echo "== real dimensions =="; ./$(BIN)/scale_test@echo "== full-model oracle =="; ./$(BIN)/k3_model $(FIXTURES)- @echo; echo "ALL WEIGHTLESS TESTS PASSED"+ @echo+ @if [ ! -f "$(TOK_FILES)/tiktoken.model" ]; then \+ echo "NOTE: tokenizer parity did NOT run; see above. Everything else did."; \+ fi+ @echo "ALL WEIGHTLESS TESTS PASSED"## test-all: adds tests that need a real checkpoint (set SHARD_DIR)test-all: testdiff --git a/README.md b/README.mdindex 35ebe87..051c698 100644--- a/README.md+++ b/README.md@@ -2302,7 +2302,7 @@ The first time the engine touched all 2.78 trillion parameters:```textKimi K3, pure C, released checkpoint- shards : 96+ model : /home/k3/k3modelprompt : 5 tokens, generating 2indexed 497220 tensors from 96 shards in 0.70 sdiff --git a/scripts/download-model.sh b/scripts/download-model.shindex f2cebfe..9eda4fc 100755--- a/scripts/download-model.sh+++ b/scripts/download-model.sh@@ -7,7 +7,9 @@# does not fail loudly, it produces wrong tokens, so the byte total is checked against# the published figure before anything else is allowed to use it.#-# Requires a HuggingFace token in $HF_TOKEN or ~/.cache/huggingface/token.+# The repository is public, so no token is needed. If you have one, the hf CLI picks it+# up from $HF_TOKEN or ~/.cache/huggingface/token on its own; this script never reads,+# echoes or forwards it.set -euo pipefail@@ -18,23 +20,56 @@ REPO="moonshotai/Kimi-K3"EXPECT_SHARDS=96EXPECT_BYTES=1560936091448-command -v python3 >/dev/null || { echo "python3 required"; exit 1; }+# The downloader is the `hf` CLI from huggingface_hub 1.x. The older entry points are+# gone: `python3 -m huggingface_hub.commands.huggingface_cli` was removed when the CLI+# was renamed, and the `[cli]` extra no longer exists.+#+# We deliberately do NOT attempt a pip install here. On the platform this project+# targets, a system pip install cannot succeed: Ubuntu 24.04 ships no pip module at+# all, and once pip is present PEP 668 marks the interpreter externally-managed and+# refuses. Guessing wrong in an unattended script that is about to move 1.56 TB is+# worse than stopping with an instruction.+if ! command -v hf >/dev/null 2>&1; then+ cat >&2 <<'EOF'+the `hf` CLI is required and was not found on PATH.++Install it one of these ways, then re-run:-if ! python3 -c "import huggingface_hub" 2>/dev/null; then- echo "installing huggingface_hub…"- python3 -m pip install --quiet --upgrade "huggingface_hub[cli]"+ pipx install huggingface_hub # recommended; what PEP 668 points you to+ uv tool install huggingface_hub+ python3 -m venv ~/.venvs/hf && ~/.venvs/hf/bin/pip install huggingface_hub+ then add ~/.venvs/hf/bin to PATH++On Debian/Ubuntu, `pipx` is `sudo apt install pipx`.+EOF+ exit 1fimkdir -p "$DEST"+# Free-space preflight. Without this the transfer runs until the filesystem fills, which+# takes the machine's logging and package manager with it, and the byte-total check below+# then reports a mismatch -- a true statement that misdiagnoses the actual failure.+AVAIL=$(df -P -k "$DEST" | awk 'NR==2 {print $4 * 1024}')+if [ "$AVAIL" -lt "$EXPECT_BYTES" ]; then+ printf 'FAIL: %s has %s bytes free, the checkpoint needs %s.\n' \+ "$DEST" "$AVAIL" "$EXPECT_BYTES" >&2+ printf ' Short by %s bytes (%.2f TB). Point <dest_dir> at a larger filesystem.\n' \+ "$((EXPECT_BYTES - AVAIL))" \+ "$(awk -v d="$((EXPECT_BYTES - AVAIL))" 'BEGIN{print d/1e12}')" >&2+ printf ' Packing the trunk afterwards needs a further ~109 GB.\n' >&2+ exit 1+fi+echo "downloading $REPO -> $DEST"echo " 1.56 TB across $EXPECT_SHARDS shards; expect ~30 min at 1 GB/s"echo-# The token is read from the environment and never echoed.-HF_HUB_ENABLE_HF_TRANSFER=1 \-python3 -m huggingface_hub.commands.huggingface_cli download "$REPO" \- --local-dir "$DEST" --max-workers 16+# Xet is the transfer backend in huggingface_hub 1.x. HF_HUB_ENABLE_HF_TRANSFER, which+# this script used to set, is ignored there and was a hard error on 0.x whenever the+# hf_transfer package was absent -- which it always was, since nothing installed it.+HF_XET_HIGH_PERFORMANCE="${HF_XET_HIGH_PERFORMANCE:-1}" \+hf download "$REPO" --local-dir "$DEST" --max-workers 16echoecho "verifying…"diff --git a/scripts/k3-doctor.sh b/scripts/k3-doctor.shindex 02f3a4f..b3d9603 100755--- a/scripts/k3-doctor.sh+++ b/scripts/k3-doctor.sh@@ -80,7 +80,15 @@ else PRESET=""; fiif [ -n "$PRESET" ]; thenok "recommended preset: --preset $PRESET (expect $EXPECT)"else- bad "under 10 GB available, below the engine's floor (~8.2 GB measured peak RSS)"+ # A warning, not a failure. This threshold is about RUNNING the checkpoint; it says+ # nothing about building the engine or running the test suite, both of which need no+ # weights and pass comfortably here. `make test`'s own ceiling is the ~1.7 GB single+ # allocation in tests/unit/scale_test.c. Failing the whole check on this number told+ # people their machine was broken when the only thing they could not do was the one+ # thing that needs 1.56 TB of disk they also did not have.+ warn "under 10 GB available, below the floor for running the checkpoint (~8.2 GB peak RSS)"+ printf ' %s the build and \`make test\` need no weights and work fine here%s\n' \+ "$DIM" "$RST"fi# -------------------------------------------------------------------- storage --@@ -129,7 +137,12 @@ fihdr "result"if [ "$FAILED" -eq 0 ]; then- printf ' %sthis machine can run Kimi K3%s\n' "$GRN" "$RST"+ if [ -n "$PRESET" ]; then+ printf ' %sthis machine can run Kimi K3%s\n' "$GRN" "$RST"+ else+ printf ' %sthis machine can build and test the engine, but not run the checkpoint%s\n' \+ "$YLW" "$RST"+ fi# The command printed here is the one a user is most likely to copy, so every part# of it has to work as written:@@ -146,6 +159,17 @@ if [ "$FAILED" -eq 0 ]; thenprintf ' %s./scripts/pack-trunk.sh %s ~/k3trunk%s\n' "$DIM" "$M" "$RST"printf ' %s./bin/k3 %s --trunk ~/k3trunk --preset %s \\%s\n' "$DIM" "$M" "$PRESET" "$RST"printf ' %s --tok %s --prompt "Hello" --gen 8 --incremental%s\n' "$DIM" "$M" "$RST"+ else+ # No preset fits, but the weightless path always does, and it is the whole of+ # the README's Quick start. Printing nothing here was what made the old FAIL+ # read as "give up".+ printf '\n next:\n'+ printf ' %smake -j%s\n' "$DIM" "$RST"+ printf ' %smake test%s\n' "$DIM" "$RST"+ printf ' %sboth need no checkpoint. Running the model needs ~10 GB of RAM and%s\n' \+ "$DIM" "$RST"+ printf ' %s~1.7 TB of disk; come back with those and re-run this check.%s\n' \+ "$DIM" "$RST"fiexit 0elsediff --git a/src/cli/k3_run.c b/src/cli/k3_run.cindex 4e3afb7..c49877c 100644--- a/src/cli/k3_run.c+++ b/src/cli/k3_run.c@@ -510,7 +510,10 @@ int main(int argc, char **argv)char b1[32];printf("Kimi K3, pure C, released checkpoint\n");- printf(" shards : %s\n", dir);+ /* The directory, not a shard count: the index has not been built yet at this point.+ * The count is printed by the "indexed N tensors from M shards" line below, once+ * k3_st_open has actually counted them. */+ printf(" model : %s\n", dir);printf(" prompt : %d tokens, generating %d\n", np, gen);/* Echo the preset so a captured log is self-describing: a timing figure is* meaningless without the budget that produced it. */diff --git a/src/core/k3_ops.c b/src/core/k3_ops.cindex 4217347..417c3b8 100644--- a/src/core/k3_ops.c+++ b/src/core/k3_ops.c@@ -57,6 +57,23 @@ static void k3_fatal_oom(const char *what, size_t bytes)abort();}+/* The same rule, for a bound that is exceeded rather than an allocation that fails.+ * k3_mla_cached writes its output only after the capacity check, so returning early+ * would hand the caller back whatever the scratch buffer held from the previous layer,+ * and k3_decoder_layer_inc folds that straight into the residual. The run finishes and+ * prints a token derived from the wrong layer's activations. Abort instead. */+static void k3_fatal_bound(const char *what, long value, long limit)+{+ fprintf(stderr,+ "k3: FATAL, %s is %ld, which exceeds the limit of %ld.\n"+ " Aborting rather than returning without writing the output buffer,\n"+ " which would fold the previous layer's values into the residual and\n"+ " produce plausible-looking but meaningless output.\n"+ " Shorten the prompt, lower --gen, or drop --incremental.\n",+ what, value, limit);+ abort();+}+/* ------------------------------------------------------------- layer map ---- *//* The released config lists full_attn_layers ONE-BASED, and* configuration_kimi_k3.py:152-156 tests (layer_idx + 1) in kda_layers. Getting this@@ -284,10 +301,8 @@ void k3_mla_cached(float *out, const float *x, const K3MlaW *w, const K3Cfg *c,const float scale = 1.0f / sqrtf((float)qh); /* :359, over qh not qn */if (!kvc) cached = 0;const int last = cached + T - 1; /* highest absolute position */- if (kvc && last >= cap) {- fprintf(stderr, "k3_mla: position %d exceeds KV cache capacity %d\n", last, cap);- return;- }+ if (kvc && last >= cap)+ k3_fatal_bound("MLA KV cache position", (long)last, (long)cap - 1);/* Scratch layout. Every region below is DISJOINT and must stay so. Overlapping* any two of them can appear to work, aliasing the gate buffer onto q, say, is