Skip to content

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.

test: gate the config refusals, and stop the suite overstating itself

FareedKhan-devd625067c5414
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 886c7ef..7b641f1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -34,32 +34,29 @@ jobs:
sudo apt-get install -y --no-install-recommends libomp-dev
${{ matrix.cc }} --version
- # -march=native is wrong for CI: the runner's CPU is not the user's. `portable`
- # targets a documented baseline (AVX2 + FMA) instead.
+ # -march=native is wrong for CI: the runner's CPU is not the user's. ARCH pins the
+ # documented baseline (AVX2 + FMA) instead. It is passed to `test`, not only to
+ # `all`, because the test binaries are built from the same objects and a mixed
+ # -march=native/-mavx2 tree is neither of the two configurations we ship.
- name: Build (portable baseline)
- run: make portable CC=${{ matrix.cc }} -j"$(nproc)"
-
- - name: Build tests
- run: make CC=${{ matrix.cc }} bin/test_ops bin/test_cache bin/test_st bin/test_cfg bin/test_tok bin/k3_model -j"$(nproc)"
-
- - name: Op kernels
- run: ./bin/test_ops tests/fixtures/ops
-
- - name: Streaming expert cache
- run: ./bin/test_cache tests/fixtures/cache
-
- - name: Safetensors reader
+ run: make CC=${{ matrix.cc }} ARCH="-mavx2 -mfma" -j"$(nproc)"
+
+ # `make test` and not the individual binaries. This is the command the README's
+ # Quick start tells every user to run, so it is the one that has to be green. The
+ # per-binary list this replaced omitted scale_test entirely -- the only gate with a
+ # real memory cost, and the only one that exercises the real 7168-wide dimensions.
+ - name: make test
+ run: make CC=${{ matrix.cc }} ARCH="-mavx2 -mfma" test -j"$(nproc)"
+
+ # The tokenizer leg above reports NOT RUN without a vocabulary, which is correct but
+ # must not be mistaken for coverage. Assert the rest of the suite really ran.
+ - name: Assert the suite was not silently empty
run: |
- ./bin/test_st tests/fixtures/st /tmp/idx.json \
- plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32
-
- - name: Config reader (both layouts + refusal cases)
- run: ./bin/test_cfg fixture tests/fixtures/ref_k3.json
-
- # The end-to-end gate: teacher forcing, greedy decode, and incremental decode must
- # all match a reference implementation exactly on the tiny oracle model.
- - name: Full-model oracle gates
- run: ./bin/k3_model tests/fixtures
+ make CC=${{ matrix.cc }} ARCH="-mavx2 -mfma" test 2>&1 | tee /tmp/t.log
+ grep -q "22 passed, 0 failed, 0 skipped" /tmp/t.log
+ grep -q "SCALE TEST PASSED" /tmp/t.log
+ grep -q "VERDICT: ENGINE MATCHES THE REFERENCE EXACTLY" /tmp/t.log
+ grep -q "ALL WEIGHTLESS TESTS PASSED" /tmp/t.log
# Warnings are defects here. The engine does arithmetic on `const void *` weight
# pointers, where a missing -Wpointer-arith silently strides by one byte.
@@ -95,6 +92,9 @@ jobs:
run: |
./bin/test_ops tests/fixtures/ops
./bin/test_cfg fixture tests/fixtures/ref_k3.json
+ for f in no_layermap bad_layer_index bad_topk; do
+ ./bin/test_cfg reject "tests/fixtures/cfg/$f.json"
+ done
./bin/test_cache tests/fixtures/cache
./bin/test_st tests/fixtures/st "$RUNNER_TEMP/idx.json" \
plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 052e65d..0199fe5 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -110,16 +110,32 @@ add_test(NAME cache COMMAND test_cache ${FIX}/cache)
add_test(NAME config COMMAND test_cfg fixture ${FIX}/ref_k3.json)
add_test(NAME scale COMMAND scale_test)
add_test(NAME oracle COMMAND k3_model ${FIX})
+
+# The negative half of the config contract. Each fixture is the working flat config with
+# exactly one field mutated, so a rejection can only come from that field. Without these
+# the refuse-rather-than-guess policy -- the reason this reader exists -- has no executed
+# test at all, in either build system.
+add_test(NAME config_reject_no_layermap
+ COMMAND test_cfg reject ${FIX}/cfg/no_layermap.json)
+add_test(NAME config_reject_bad_layer_index
+ COMMAND test_cfg reject ${FIX}/cfg/bad_layer_index.json)
+add_test(NAME config_reject_bad_topk
+ COMMAND test_cfg reject ${FIX}/cfg/bad_topk.json)
add_test(NAME safetensors COMMAND test_st ${FIX}/st ${CMAKE_CURRENT_BINARY_DIR}/idx.json
plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32)
# The tokenizer test needs the released vocabulary, which is not in this repository.
-# Registered so `ctest` reports it as skipped rather than omitting it silently; point
-# K3_TOK_FILES at a checkpoint directory to make it run.
-if(DEFINED ENV{K3_TOK_FILES})
- add_test(NAME tokenizer COMMAND test_tok $ENV{K3_TOK_FILES} roundtrip
- ${CMAKE_CURRENT_SOURCE_DIR}/README.md)
-endif()
+# Registered UNCONDITIONALLY so ctest reports it as Skipped rather than omitting it:
+# wrapping this in if(DEFINED ENV{K3_TOK_FILES}) did the opposite of what that sentence
+# claims, and made `ctest` quietly report one fewer test than `make test` runs. The
+# wrapper resolves K3_TOK_FILES at TEST time, not configure time, so exporting it before
+# ctest now works as the docs say.
+add_test(NAME tokenizer
+ COMMAND ${CMAKE_COMMAND}
+ -DTEST_TOK=$<TARGET_FILE:test_tok>
+ -DINPUT=${CMAKE_CURRENT_SOURCE_DIR}/README.md
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/run_tok_test.cmake)
+set_tests_properties(tokenizer PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:")
add_executable(bench_kernels benchmarks/bench_kernels.c)
target_link_libraries(bench_kernels PRIVATE k3)
diff --git a/Makefile b/Makefile
index e2a81c1..8b11382 100644
--- a/Makefile
+++ b/Makefile
@@ -117,6 +117,10 @@ 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 "== config refusals =="; \
+ for f in no_layermap bad_layer_index bad_topk; do \
+ ./$(BIN)/test_cfg reject $(FIXTURES)/cfg/$$f.json || exit 1; \
+ done
@echo "== tokenizer =="; \
if [ -f "$(TOK_FILES)/tiktoken.model" ]; then \
./$(BIN)/test_tok $(TOK_FILES) roundtrip src/core/k3_ops.c; \
diff --git a/README.md b/README.md
index 051c698..2ce6061 100644
--- a/README.md
+++ b/README.md
@@ -104,7 +104,7 @@ component at a time.
- [The four reductions](#the-four-reductions)
- [The machine, and what it assumes](#the-machine-and-what-it-assumes)
- [The codebase](#the-codebase)
-- [Five invariants](#five-invariants)
+- [Three invariants](#three-invariants)
- [1. Reading a 1.56 TB checkpoint from its headers](#1-reading-a-156-tb-checkpoint-from-its-headers)
- [2. The config reader that refuses to guess](#2-the-config-reader-that-refuses-to-guess)
- [3. The tokenizer, byte for byte](#3-the-tokenizer-byte-for-byte)
@@ -757,22 +757,33 @@ Two compilers on two operating systems produce the same 6,862 token ids from the
24,499 bytes. The md5 sums differ by exactly one byte, and the reason is the line ending
the shell added, not anything the tokenizer did.
-## Five invariants
+## Three invariants
-The public header opens with five invariants that must hold. Each one is a place where a
+The public header opens with three invariants that must hold. Each one is a place where a
plausible-looking implementation produces a model that runs, emits fluent text, and is
wrong, with no crash and no NaN to warn you.
1. **`A_log` is indexed per head, not per channel.** The checkpoint ships `head_dim`
floats but only the first `num_heads` are meaningful; the rest are padding.
-2. **The UT-transform inverse is `(I + Akk)^-1`.** The sign is not a convention.
-3. **`Aqk` retains its diagonal and `Akk` does not.**
-4. **MLA uses NoPE, yet the 64 rope dimensions still exist and are still cached.** Only
+2. **MLA uses NoPE, yet the 64 rope dimensions still exist and are still cached.** Only
the rotation is absent; dropping the slots changes the head width.
-5. **The MoE routing bias steers selection only.** The combining weights come from the
+3. **The MoE routing bias steers selection only.** The combining weights come from the
unbiased sigmoid scores.
-Each is ticked off below as its component arrives.
+Each is ticked off below as its component arrives, and each is gated by a fixture chosen
+so that getting it wrong changes the output: `A_log` by a linspace that a per-channel
+misindex scrambles, NoPE by asserting the softmax scale is over the full head width, and
+the routing bias by a fixture whose bias reorders the top-k on five of its six rows.
+
+This list used to have five entries. The other two — that the UT-transform inverse is
+`(I + Akk)^-1`, and that `Aqk` keeps its diagonal while `Akk` does not — describe the
+chunked parallel form of the delta rule. This engine does not use it. `k3_kda_step` runs
+the naive sequential recurrence one position at a time, and so does the PyTorch reference
+it is checked against, so neither matrix is ever formed. They were claims about an
+algorithm rather than about this code, nothing implemented them, and no test could have
+caught getting them wrong. They now live in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)
+with the rest of the algorithm description. Restoring a chunked KDA path means restoring
+them, with the fixtures that gate them.
## 1. Reading a 1.56 TB checkpoint from its headers
@@ -1608,7 +1619,7 @@ of the head dimension **before** the recurrence rather than after it.
![Norm first, then gate, then project, and that order is not interchangeable](docs/images/eq_kda_gate.png)
-Steps 7, 8 and 9 are where **invariants two and three** live. The released model ends the
+Steps 7, 8 and 9 carry an ordering constraint of their own. The released model ends the
layer with a fused kernel from the `fla` library called `FusedRMSNormGated`, which takes
the raw gate and applies the sigmoid internally. The reference implementation instead does
an explicit RMSNorm followed by a multiply by the sigmoid of the gate. Those are the same
diff --git a/cmake/run_tok_test.cmake b/cmake/run_tok_test.cmake
new file mode 100644
index 0000000..9c4af31
--- /dev/null
+++ b/cmake/run_tok_test.cmake
@@ -0,0 +1,29 @@
+# Runs the tokenizer roundtrip when the released vocabulary is available, and prints a
+# line ctest recognises as a skip when it is not.
+#
+# tiktoken.model has 163,584 entries and ships with the checkpoint, not with this
+# repository, so this gate cannot run on a clean checkout. It is registered anyway: a
+# check that vanishes from the list when it cannot run reads as "one fewer test to care
+# about", and ctest's count silently stops matching what `make test` runs.
+#
+# K3_TOK_FILES is read here, at TEST time rather than configure time, so
+# `K3_TOK_FILES=/path/to/k3model ctest` works without reconfiguring the build.
+
+set(TOK_FILES "$ENV{K3_TOK_FILES}")
+
+if(TOK_FILES STREQUAL "")
+ message("SKIPPED: K3_TOK_FILES is not set. The vocabulary ships with the checkpoint;"
+ " set K3_TOK_FILES to a model directory to run this gate.")
+ return()
+endif()
+
+if(NOT EXISTS "${TOK_FILES}/tiktoken.model")
+ message("SKIPPED: no tiktoken.model in ${TOK_FILES}")
+ return()
+endif()
+
+execute_process(COMMAND "${TEST_TOK}" "${TOK_FILES}" roundtrip "${INPUT}"
+ RESULT_VARIABLE rc)
+if(NOT rc EQUAL 0)
+ message(FATAL_ERROR "tokenizer roundtrip failed with status ${rc}")
+endif()
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 9cf8ecc..f7c4316 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -44,7 +44,7 @@ dial; the 5.3 GB is the floor.
```
include/k3/
- k3.h public types, config, and the five invariants that must hold
+ k3.h public types, config, and the three invariants that must hold
k3_cfg.h config reader, never defaults a missing field
src/core/
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 217a46f..f18e96a 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -4,7 +4,7 @@ Every test in `make test` runs **without model weights**. The checkpoint is 1.56
correctness depended on having it, correctness would not get checked.
```bash
-make test # everything below, seconds
+make test # everything below; about 15 s, peak RSS ~1.7 GB
make test-all SHARD_DIR=~/k3model # adds the checkpoint-dependent tests
```
@@ -22,14 +22,29 @@ access. Uses a synthetic shard of structurally faithful experts, a few KB.
**`test_st`**, the safetensors reader: dtype widening, offsets, tail bytes, escaped
tensor names, and a tensor deliberately containing non-finite values.
-**`test_cfg`**, the config reader against both supported layouts, plus three malformed
-configs it must **refuse**. This matters more than it looks: a config reader that
-substitutes defaults for missing fields produces a model that loads, runs, and is
-architecturally wrong, with nothing to indicate it.
+**`test_cfg`**, the config reader against the fixture layout, plus three malformed configs
+in `tests/fixtures/cfg/` it must **refuse**: `no_layermap.json` (no `full_attn_layers` at
+all), `bad_layer_index.json` (a one-based index outside `1..n_layers`), and
+`bad_topk.json` (a top-k above `K3_MAX_TOPK`). Each is the working config with exactly one
+field mutated, so a rejection can only come from that field. This matters more than it
+looks: a config reader that substitutes defaults for missing fields produces a model that
+loads, runs, and is architecturally wrong, with nothing to indicate it.
+
+**`scale_test`**, the same kernels at the real released dimensions: 7168 wide, 93 layers,
+96 heads, 896 experts. It checks the layer map really is 69 KDA + 24 MLA, that every
+scratch-sizing helper returns a sane value at full width rather than only at fixture
+width, and it allocates and runs one complete 7168-wide KDA layer. That last step is a
+single **1.77 GB** allocation, which is the only real resource requirement anywhere in
+`make test`; on a machine too small for it the test says so and fails rather than
+skipping.
**`test_tok`**, byte-exact roundtrip (encode then decode recovers the input exactly).
With `tools/tok_parity.py` it also compares token-for-token against the reference
tokenizer across CJK, emoji, ZWJ sequences, accents, contractions and whitespace runs.
+This is the one gate that cannot run on a clean checkout: `tiktoken.model` has 163,584
+entries and ships with the checkpoint, not with this repository. `make test` reports it as
+**NOT RUN** rather than passing it quietly. Point `TOK_FILES` at a downloaded checkpoint
+to run it: `make tok TOK_FILES=~/k3model`.
**`k3_model`**, the end-to-end gate, on a tiny model whose tensor graph matches the released
architecture exactly:
diff --git a/include/k3/k3.h b/include/k3/k3.h
index cf644ad..26d73c9 100644
--- a/include/k3/k3.h
+++ b/include/k3/k3.h
@@ -30,19 +30,34 @@
* latent width 3584, SiTU-GLU activation, MXFP4 expert weights.
* docs/ARCHITECTURE.md maps each of these onto the technical report.
*
- * FIVE INVARIANTS THAT MUST HOLD
+ * THREE INVARIANTS THAT MUST HOLD
* Each of these is a place where a plausible-looking implementation produces a model
- * that runs, emits fluent text, and is wrong. They are asserted by the test-suite and
- * restated at their point of use.
+ * that runs, emits fluent text, and is wrong. Each is gated by a fixture in
+ * tests/fixtures/ops chosen so that getting it wrong changes the output, and each is
+ * restated at its point of use.
*
* 1. A_log is indexed PER HEAD, not per channel. The checkpoint ships head_dim floats
* but only the first num_heads are meaningful; the remainder are padding.
- * 2. The UT-transform inverse is (I + Akk)^-1. The sign is not a convention.
- * 3. Aqk retains its diagonal; Akk does not.
- * 4. MLA uses NoPE, yet the 64 rope dimensions still exist and are still cached.
+ * Gated by the kda_decay fixture, whose A_log is a linspace, so a per-channel
+ * misindex moves every element.
+ * 2. MLA uses NoPE, yet the 64 rope dimensions still exist and are still cached.
* Only the rotation is absent. Dropping the slots changes the head width.
- * 5. The MoE routing bias steers SELECTION only. Combining weights come from the
+ * Gated by the mla fixture, which asserts the softmax scale is over the FULL head
+ * width qk_nope + qk_rope, not over qk_nope alone.
+ * 3. The MoE routing bias steers SELECTION only. Combining weights come from the
* UNBIASED sigmoid scores.
+ * Gated by the router fixture, whose bias reorders the top-k on 5 of its 6 rows.
+ *
+ * NOT INVARIANTS OF THIS IMPLEMENTATION
+ * Earlier revisions of this header also listed the UT-transform inverse (I + Akk)^-1
+ * and the retention of Aqk's diagonal but not Akk's. Those describe the chunked
+ * parallel form of the delta rule. This engine does not use it: k3_kda_step runs the
+ * naive sequential O(T) recurrence, one position at a time, and so does the reference
+ * in tools/k3_ref.py. Neither matrix is ever formed, so there was nothing to get right
+ * and no test could have caught getting it wrong. They are recorded in
+ * docs/ARCHITECTURE.md as properties of the algorithm, which is where a claim the code
+ * does not make belongs. Anyone adding a chunked KDA path must reinstate them here
+ * together with the fixtures that gate them.
*/
#ifndef K3_H
#define K3_H
diff --git a/tests/fixtures/cfg/bad_layer_index.json b/tests/fixtures/cfg/bad_layer_index.json
new file mode 100644
index 0000000..7a12383
--- /dev/null
+++ b/tests/fixtures/cfg/bad_layer_index.json
@@ -0,0 +1,37 @@
+{
+ "hidden_size": 128,
+ "num_hidden_layers": 13,
+ "vocab_size": 256,
+ "rms_norm_eps": 1e-05,
+ "tie_word_embeddings": false,
+ "kda_num_heads": 4,
+ "kda_head_dim": 16,
+ "short_conv_kernel_size": 4,
+ "gate_lower_bound": -5.0,
+ "num_attention_heads": 4,
+ "q_lora_rank": 64,
+ "kv_lora_rank": 32,
+ "qk_nope_head_dim": 24,
+ "qk_rope_head_dim": 8,
+ "v_head_dim": 16,
+ "mla_use_output_gate": true,
+ "num_experts": 8,
+ "num_experts_per_token": 2,
+ "num_shared_experts": 2,
+ "routed_expert_hidden_size": 64,
+ "moe_intermediate_size": 48,
+ "routed_scaling_factor": 1.0,
+ "moe_renormalize": true,
+ "latent_moe_use_norm": true,
+ "first_k_dense_replace": 1,
+ "intermediate_size": 96,
+ "attn_res_block_size": 3,
+ "situ_beta": 4.0,
+ "situ_linear_beta": 25.0,
+ "full_attn_layers": [
+ 4,
+ 8,
+ 999,
+ 13
+ ]
+}
diff --git a/tests/fixtures/cfg/bad_topk.json b/tests/fixtures/cfg/bad_topk.json
new file mode 100644
index 0000000..4ab383d
--- /dev/null
+++ b/tests/fixtures/cfg/bad_topk.json
@@ -0,0 +1,37 @@
+{
+ "hidden_size": 128,
+ "num_hidden_layers": 13,
+ "vocab_size": 256,
+ "rms_norm_eps": 1e-05,
+ "tie_word_embeddings": false,
+ "kda_num_heads": 4,
+ "kda_head_dim": 16,
+ "short_conv_kernel_size": 4,
+ "gate_lower_bound": -5.0,
+ "num_attention_heads": 4,
+ "q_lora_rank": 64,
+ "kv_lora_rank": 32,
+ "qk_nope_head_dim": 24,
+ "qk_rope_head_dim": 8,
+ "v_head_dim": 16,
+ "mla_use_output_gate": true,
+ "num_experts": 8,
+ "num_experts_per_token": 128,
+ "num_shared_experts": 2,
+ "routed_expert_hidden_size": 64,
+ "moe_intermediate_size": 48,
+ "routed_scaling_factor": 1.0,
+ "moe_renormalize": true,
+ "latent_moe_use_norm": true,
+ "first_k_dense_replace": 1,
+ "intermediate_size": 96,
+ "attn_res_block_size": 3,
+ "situ_beta": 4.0,
+ "situ_linear_beta": 25.0,
+ "full_attn_layers": [
+ 4,
+ 8,
+ 12,
+ 13
+ ]
+}
diff --git a/tests/fixtures/cfg/no_layermap.json b/tests/fixtures/cfg/no_layermap.json
new file mode 100644
index 0000000..8b37eda
--- /dev/null
+++ b/tests/fixtures/cfg/no_layermap.json
@@ -0,0 +1,31 @@
+{
+ "hidden_size": 128,
+ "num_hidden_layers": 13,
+ "vocab_size": 256,
+ "rms_norm_eps": 1e-05,
+ "tie_word_embeddings": false,
+ "kda_num_heads": 4,
+ "kda_head_dim": 16,
+ "short_conv_kernel_size": 4,
+ "gate_lower_bound": -5.0,
+ "num_attention_heads": 4,
+ "q_lora_rank": 64,
+ "kv_lora_rank": 32,
+ "qk_nope_head_dim": 24,
+ "qk_rope_head_dim": 8,
+ "v_head_dim": 16,
+ "mla_use_output_gate": true,
+ "num_experts": 8,
+ "num_experts_per_token": 2,
+ "num_shared_experts": 2,
+ "routed_expert_hidden_size": 64,
+ "moe_intermediate_size": 48,
+ "routed_scaling_factor": 1.0,
+ "moe_renormalize": true,
+ "latent_moe_use_norm": true,
+ "first_k_dense_replace": 1,
+ "intermediate_size": 96,
+ "attn_res_block_size": 3,
+ "situ_beta": 4.0,
+ "situ_linear_beta": 25.0
+}