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
docs: catch the README up with the CLI, and record this round
Fareed Khan1ae4d62c2181
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b44a7fa..b3211bc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,22 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).it were mid document rather than answering it.- **`--trunk-ring N`**: the streaming trunk's prefetch queue depth is now a flag(default 2) instead of fixed at two slots.+- **Ctrl-C stops at a safe point.** The first Ctrl-C lets the step in flight finish,+ then writes the state file, the `--out` JSON and the reports exactly as a finished run+ would, and exits 5. A second Ctrl-C kills. Before, SIGINT discarded everything.+- **Chat reuses the previous turn's state.** When the next turn's rendered prompt begins+ with exactly the ids the carried state was built from, only the new tail is prefilled.+ GATE 3b in the oracle requires that to be bit identical to a full prefill: logits, every+ KV row, and the KDA state.+- **`--top-k K`** for chat sampling, on the existing sampler. Off by default.+- **`--threads N`**, and a default of the physical core count on Linux instead of one+ thread per logical CPU, which measured about 23% slower per token on a 16 core SMT part.+- **`download-model.sh <dest> --layers N`** fetches only the shards a `--layers N` run+ needs, resolved from the Hub's own index, with a banner saying the result is not the+ model.+- **A missing tensor names the missing file.** The shard filenames declare the shard+ count, so a partial download now says which file is absent instead of only which+ tensor.- **`--stop-id N`** (repeatable, up to 8): generation halts as soon as the model emitsa listed token id. Off by default, so `--gen N` still means exactly N tokens forevery benchmark and oracle gate. The stop id stays in the sequence, so `--save-state`@@ -46,6 +62,8 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).### Changed+- **Expert reads are split into 1 MiB chunks**, so a batch of reads no longer waits on its+ slowest expert. Output is unchanged.- **Trunk layers are read in parallel chunks.** `load_run()` streamed each layer withone sequential `pread` loop, so the device saw queue depth 1. It now splits the layerinto 64 MiB chunks (a multiple of `K3_TRUNK_ALIGN`, so every chunk stays aligned for@@ -60,6 +78,25 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).### Fixed+- **`--preset auto` refused itself on large machines.** It planned to 98% of available+ memory while admission allowed 95%, so from about 100 GB of RAM upward the recommended+ preset could never start, and the refusal printed a negative shortfall. One constant+ now drives both.+- **On macOS the available memory read as 0**, which silently switched off both memory+ refusals. Darwin and Windows now have their own probes, and Windows also caps by the+ remaining commit limit.+- **A state file could be wrong without the loader noticing.** One flipped byte restored+ cleanly, and a save that failed partway destroyed the previous good file. The payload+ is now checksummed and the file published by an atomic rename. State files move to+ version 2; a version 1 file is refused rather than guessed at.+- **Safetensors headers whose tensor spans overlap or leave a gap** were read without+ complaint, shifting every tensor after them. They are refused now, the same rule the+ reference loader applies; all 96 shards of the released checkpoint pass it.+- **The JSON parser read past the end of a truncated string** and accepted incomplete+ documents. Both are refusals now. Every JSON file the engine reads from the released+ checkpoint parses to the same tree as before.+- **A refused trunk.json leaked its whole parse tree**, and `--ids` values past the int+ range wrapped to a real token id.- **Hostile or corrupt safetensors, trunk, and config input could reach undefinedbehavior instead of a refusal.** Integer overflow in shape and offset arithmetic(a hostile shape or `data_offsets` pair near `INT64_MAX` could wrap and defeat thediff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.mdindex 71937f2..7e3c81e 100644--- a/CONTRIBUTORS.md+++ b/CONTRIBUTORS.md@@ -57,7 +57,11 @@ record.and a `rename` that actually replaces an existing file); found and fixed the missingOpenMP link on the CMake Apple/libomp path; largest-first trunk pinning, the`--trunk-ring` flag, and two prefetcher re-read bugs found by instrumentation rather- than by inspection.+ than by inspection; Ctrl-C that stops at a safe point and still writes everything; a+ checksummed state file published by atomic rename; chat turns that reuse the previous+ turn's state behind a bit-exact gate; available memory that is real on macOS and+ capped by commit headroom on Windows; missing-shard diagnostics that name the file; and+ safetensors span checks validated against every shard of the released checkpoint.- **[Blake Evans](https://github.com/BlakeEvans22)** -- the original K3 XTML chat coreand REPL, reproducing the checkpoint's own chat format so the engine answers achat-shaped prompt instead of completing it.@@ -68,6 +72,14 @@ record.allocation failure, and a new weightless fault-injection test; a batched MoE prefillpath that read uninitialized memory on an expert load failure instead of contributingzero, exactly as the per-token path already does; and CLI refusals for a malformed- `--ids` list, an out-of-range `--layers`, and a lost `--out` file.+ `--ids` list, an out-of-range `--layers`, and a lost `--out` file; a strict JSON parser+ that refuses truncated input instead of reading past it; a trunk.json leak on the+ refusal path; sampler tests that run without the tokenizer; and `--top-k` for chat.+- **[santhoshsathish94](https://github.com/santhoshsathish94)** -- found that+ `--preset auto` could never start on the machines it was written for and fixed it,+ with the measurements that made the thread-count default change a clear call; split+ expert reads so a batch no longer waits on its slowest read.+- **[Irfanwani](https://github.com/Irfanwani)** -- the `--layers N` download mode, so the+ pipeline can be exercised on a disk too small for the checkpoint.Thank you, all of you.diff --git a/README.md b/README.mdindex 346beae..b682b36 100644--- a/README.md+++ b/README.md@@ -405,6 +405,8 @@ printf 'La capitale de la France est' > /tmp/p.txt| `--trunk` | `DIR` | off | the packed trunk directory from step 5. **This is what enables streaming.** Without it the trunk loads fully resident, around 113.5 GB || `--trunk-gb` | `X` | 16 | budget for pinned layers plus the streaming ring || `--cache-gb` | `X` | 64 | budget for the routed-expert LRU cache |+| `--trunk-ring` | `N` | 2 | streaming ring slots: one layer being computed on, the rest reads in flight. Each extra slot costs one slot of RAM, and the budget still wins if it does not fit |+| `--threads` | `N` | physical cores | OpenMP threads. On Linux the default is the physical core count rather than OpenMP's one thread per logical CPU, which is slower here on SMT parts. `OMP_NUM_THREADS`, if set, is respected || `--ultra-low-memory` | none | off | stream exact embedding rows and lm_head chunks; full recompute also reuses one recurrent-state slot. Requires `--trunk` |The `ultra` preset selects `--ultra-low-memory` with a 2.5 GB trunk ring and a@@ -423,7 +425,8 @@ shorthand. Order matters if you mix them: a later flag wins, so| flag | argument | default | ||---|---|---|---|-| `--gen` | `N` | 8 | tokens to generate. Ceiling 4096; prompts may be up to 32768 tokens |+| `--gen` | `N` | 8 | tokens to generate. Ceiling 4096; prompts may be up to 32768 tokens. `--gen 0 --incremental --save-state PATH` runs only the prefill and saves its exact state, to warm a prefix once and resume it many times |+| `--stop-id` | `N` | off | stop as soon as the model emits id `N`; repeatable, up to 8. The released checkpoint declares two end ids that disagree (163586 in `config.json`, 163585 in `tokenizer_config.json`) and emits both, so pass both || `--incremental` | none | off | carry the KV cache and the recurrent state between tokens instead of re-running the whole prefix || `--tok` | `DIR` | none | directory holding `tiktoken.model` and `tokenizer_config.json` |@@ -506,14 +509,16 @@ Scripts can rely on these.| `0` | success || `1` | a tensor failed to bind, or a forward pass failed || `2` | usage error, or a config that could not be read with confidence; the engine declines to guess |+| `3` | the run finished but the `--out` file could not be written, so the results a harness reads are missing || `4` | the run finished, but at least one routed expert failed to load, so the emitted ids are unsound. Distinct from `1` because the process otherwise succeeded, and it is the code that catches silent numerical corruption |+| `5` | stopped early by Ctrl-C. The step in flight finished, and the state file, `--out` and the reports were all written, but the token list is shorter than asked for. A second Ctrl-C kills the process instead |### Environment variables| variable | used by | ||---|---|---|| `HF_TOKEN` | `download-model.sh` | HuggingFace token, read from the environment and never echoed |-| `OMP_NUM_THREADS` | the engine | thread count, defaulting to all cores |+| `OMP_NUM_THREADS` | the engine | thread count. When neither this nor `--threads` is given, Linux defaults to the physical core count || `K3_TOK_FILES` | tokenizer tools and CI | directory holding `tiktoken.model`, when it is not in a default location || `K3_MODEL_DIR` | `tools/budget.py` | checkpoint directory, when not given as an argument |@@ -647,6 +652,21 @@ hour in. Shorten the request, or drop `--incremental`, which carries no KV cache**Is the whole 1.56 TB needed?** For generation, yes. For development, no: `make test`needs nothing at all, and `--layers N` runs against partial shard sets.+`scripts/download-model.sh <dest> --layers N` fetches only the shards those layers need,+about 7 GB for `N=1` and 125 GB for `N=8`. That is for exercising the pipeline on a small+disk; a layer prefix is not the model and does not produce its output.++**Why no BLAS?** Because every matmul here has to give the same bits on every machine.+The test suite checks the engine against a PyTorch reference exactly, not to a tolerance,+and that only works if the order in which each dot product is summed is fixed and known.+A BLAS library chooses its own blocking and reduction order, which can differ between+versions, between vendors (OpenBLAS, MKL, Accelerate), and between thread counts on the+same machine. Each of those answers is numerically correct and none of them matches the+others bit for bit. The kernels in `src/core/k3_ops.c` exist to pin that order: the AVX2+and NEON paths reproduce the scalar reduction exactly, and `test_ops` checks they do.+It also keeps the build free of a dependency that installs differently on each+platform, for kernels that are not the bottleneck anyway. A run is limited by how fast+the trunk and the experts come off disk, not by arithmetic.**macOS, Windows, WSL?** Linux is the reference platform. macOS/arm64 builds with plain`make` (see the Makefile's platform block). Windows builds natively too, via MSYS2's