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.

build: add the Makefile, CMake build and lint configuration

FareedKhan-dev9efa1974a99b
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..052e65d
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,131 @@
+# Kimi K3 inference engine.
+#
+# The Makefile is the reference build and what CI uses. This exists for IDE integration
+# and for platforms where GNU make is awkward. Both produce the same binary.
+#
+# cmake -B build -DCMAKE_BUILD_TYPE=Release
+# cmake --build build -j
+# ctest --test-dir build --output-on-failure
+
+cmake_minimum_required(VERSION 3.16)
+
+project(kimi-k3-in-c
+ VERSION 0.1.0
+ DESCRIPTION "Kimi K3 inference engine in portable C"
+ LANGUAGES C)
+
+set(CMAKE_C_STANDARD 99)
+set(CMAKE_C_STANDARD_REQUIRED ON)
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+
+if(NOT CMAKE_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
+endif()
+
+# -march=native gives a real speedup on the expert matmuls but produces a binary tied to
+# the build machine. Off by default so a packaged build is portable.
+option(K3_NATIVE_ARCH "Optimise for the building CPU (-march=native)" OFF)
+option(K3_SANITIZE "Build with ASan + UBSan" OFF)
+
+find_package(OpenMP)
+
+add_library(k3_flags INTERFACE)
+target_compile_options(k3_flags INTERFACE
+ -Wall -Wextra
+ # Not cosmetic: weight pointers are `const void *`, and pointer arithmetic on void is a
+ # GNU extension that strides by one byte. Without this the mistake compiles silently.
+ -Wpointer-arith
+ -Wshadow -Wvla
+ -Wno-unused-parameter
+ # Keeps floating-point results reproducible across compilers by disabling automatic FMA
+ # contraction; the op tests compare against a reference at a fixed tolerance.
+ -ffp-contract=off)
+
+if(K3_NATIVE_ARCH)
+ target_compile_options(k3_flags INTERFACE -march=native)
+else()
+ # Documented baseline. The engine assumes AVX2 + FMA are available.
+ target_compile_options(k3_flags INTERFACE -mavx2 -mfma)
+endif()
+
+if(K3_SANITIZE)
+ target_compile_options(k3_flags INTERFACE -fsanitize=address,undefined -fno-omit-frame-pointer -g)
+ target_link_options(k3_flags INTERFACE -fsanitize=address,undefined)
+endif()
+
+# --------------------------------------------------------------------------- engine --
+add_library(k3 STATIC
+ src/core/k3_ops.c
+ src/io/k3_st.c
+ src/io/k3_load.c
+ src/io/k3_trunk.c
+ src/cache/k3_cache.c
+ src/model/k3_bind.c)
+
+target_include_directories(k3 PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/include
+ ${CMAKE_CURRENT_SOURCE_DIR}/include/k3
+ ${CMAKE_CURRENT_SOURCE_DIR}/third_party
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/core
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/io
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/cache
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/model
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/tokenizer)
+
+target_link_libraries(k3 PUBLIC k3_flags m)
+if(OpenMP_C_FOUND)
+ target_link_libraries(k3 PUBLIC OpenMP::OpenMP_C)
+endif()
+
+# ------------------------------------------------------------------------------ cli --
+add_executable(k3_cli src/cli/k3_run.c)
+set_target_properties(k3_cli PROPERTIES OUTPUT_NAME k3)
+target_link_libraries(k3_cli PRIVATE k3)
+
+# ---------------------------------------------------------------------------- tests --
+# Every test below runs WITHOUT model weights. The checkpoint is 1.56 TB; if correctness
+# needed it, correctness would go unchecked.
+enable_testing()
+
+function(k3_add_test name src)
+ add_executable(${name} ${src})
+ target_link_libraries(${name} PRIVATE k3)
+endfunction()
+
+k3_add_test(test_ops tests/unit/test_ops.c)
+k3_add_test(test_cache tests/unit/test_cache.c)
+k3_add_test(test_st tests/unit/test_st.c)
+k3_add_test(test_cfg tests/unit/test_cfg.c)
+k3_add_test(test_tok tests/unit/test_tok.c)
+k3_add_test(scale_test tests/unit/scale_test.c)
+k3_add_test(k3_model tests/unit/k3_model.c)
+
+set(FIX ${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures)
+
+# Every test the Makefile's `test` target runs is registered here too. The two build
+# systems are documented as interchangeable, so a test present in one and absent from
+# the other silently gives ctest less coverage than `make test`.
+add_test(NAME ops COMMAND test_ops ${FIX}/ops)
+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})
+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()
+
+add_executable(bench_kernels benchmarks/bench_kernels.c)
+target_link_libraries(bench_kernels PRIVATE k3)
+
+install(TARGETS k3_cli RUNTIME DESTINATION bin)
+install(DIRECTORY include/k3 DESTINATION include)
+# k3_cfg.h includes json.h and exposes jval in its signatures, so an installed header
+# set without it does not compile. Kept in step with the Makefile's install target.
+install(FILES third_party/json.h DESTINATION include/k3)
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..94ab35e
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,192 @@
+# Kimi K3 inference engine.
+#
+# make build the engine (bin/k3)
+# make test run every test that needs no model weights
+# make bench kernel microbenchmarks
+# make portable build without -march=native (for distribution)
+# make debug -O0 -g with assertions
+# make asan / ubsan sanitizer builds
+# make format clang-format the tree
+# make clean
+#
+# Nothing here requires a checkpoint. `make test` is the gate that must stay green.
+
+# ---------------------------------------------------------------------------- config --
+CC ?= cc
+PYTHON ?= python3
+BUILD ?= build
+BIN ?= bin
+PREFIX ?= /usr/local
+
+# -march=native is a real win on the expert matmuls but produces a binary that will not
+# run on an older CPU. `make portable` drops it.
+ARCH ?= -march=native
+
+# -Wpointer-arith is not cosmetic: weight pointers are `const void *`, and arithmetic on
+# a void pointer is a silent GNU extension that strides by ONE BYTE. Without this flag
+# that mistake compiles clean under -Wall -Wextra and returns the wrong tensor.
+#
+# -ffp-contract=off keeps floating-point results reproducible across compilers by
+# 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) -fopenmp -ffp-contract=off
+LDFLAGS ?= -lm -fopenmp
+
+# Flat include search across the module dirs: sources use "k3.h", "k3_cache.h" etc
+# rather than path-qualified includes, which keeps them relocatable.
+INCLUDES := -Iinclude -Iinclude/k3 -Ithird_party \
+ -Isrc/core -Isrc/io -Isrc/cache -Isrc/model -Isrc/tokenizer
+
+# ----------------------------------------------------------------------------- files --
+ENGINE_SRC := src/core/k3_ops.c \
+ src/io/k3_st.c src/io/k3_load.c src/io/k3_trunk.c \
+ src/cache/k3_cache.c \
+ src/model/k3_bind.c
+ENGINE_OBJ := $(patsubst %.c,$(BUILD)/%.o,$(ENGINE_SRC))
+
+CLI_SRC := src/cli/k3_run.c
+CLI_BIN := $(BIN)/k3
+
+# Tests that need no checkpoint. These run in CI on every push.
+UNIT_TESTS := test_ops test_cache test_st test_cfg test_tok scale_test k3_model
+# Tests that need real shards. Built and run by `make test-all` with SHARD_DIR set;
+# see the weights-test target below.
+WEIGHT_TESTS := test_expert test_real_layer
+
+TEST_BINS := $(addprefix $(BIN)/,$(UNIT_TESTS))
+WEIGHT_BINS := $(addprefix $(BIN)/,$(WEIGHT_TESTS))
+
+FIXTURES ?= tests/fixtures
+TOK_FILES ?= $(HOME)/k3model
+
+# The safetensors test rebuilds an index and writes it to $(BUILD) rather than /tmp, so
+# two concurrent `make test` runs cannot race on one filename and `make clean` removes it.
+
+# ---------------------------------------------------------------------------- targets --
+.PHONY: all test test-all bench portable debug asan ubsan format clean install help \
+ tok cfg ops cache st oracle weights-test
+
+all: $(CLI_BIN)
+
+$(BUILD)/%.o: %.c
+ @mkdir -p $(dir $@)
+ $(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@
+
+$(CLI_BIN): $(CLI_SRC) $(ENGINE_OBJ) | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $(CLI_SRC) $(ENGINE_OBJ) -o $@ $(LDFLAGS)
+
+$(BIN):
+ @mkdir -p $(BIN)
+
+# Each test links only what it needs, so a failure points at one subsystem.
+$(BIN)/test_ops: tests/unit/test_ops.c $(BUILD)/src/core/k3_ops.o | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+$(BIN)/test_cache: tests/unit/test_cache.c $(BUILD)/src/cache/k3_cache.o \
+ $(BUILD)/src/io/k3_load.o $(BUILD)/src/io/k3_st.o \
+ $(BUILD)/src/core/k3_ops.o | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+$(BIN)/test_st: tests/unit/test_st.c $(BUILD)/src/io/k3_st.o | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+# The tokenizer and config reader are portable C99 with no OpenMP and no platform calls,
+# so they build and are verifiable on any machine, including one with no checkpoint.
+$(BIN)/test_tok: tests/unit/test_tok.c | $(BIN)
+ $(CC) -O2 -std=c99 $(WARN) -Wno-unused-function $(INCLUDES) $< -o $@
+
+$(BIN)/test_cfg: tests/unit/test_cfg.c src/core/k3_ops.c | $(BIN)
+ $(CC) -O2 -std=c99 $(WARN) -Wno-unused-function $(INCLUDES) $^ -o $@ -lm
+
+# Allocates at REAL model widths (a ~1.8 GB KDA layer), so it needs the optimised build
+# rather than the portable C99 one the tokenizer and config tests use.
+$(BIN)/scale_test: tests/unit/scale_test.c $(BUILD)/src/core/k3_ops.o | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+$(BIN)/k3_model: tests/unit/k3_model.c $(BUILD)/src/core/k3_ops.o | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+$(BIN)/bench_kernels: benchmarks/bench_kernels.c $(BUILD)/src/core/k3_ops.o | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+## test: everything that needs no model weights
+test: $(TEST_BINS)
+ @echo "== op kernels =="; ./$(BIN)/test_ops $(FIXTURES)/ops
+ @echo "== streaming cache =="; ./$(BIN)/test_cache $(FIXTURES)/cache
+ @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 "== real dimensions =="; ./$(BIN)/scale_test
+ @echo "== full-model oracle =="; ./$(BIN)/k3_model $(FIXTURES)
+ @echo; echo "ALL WEIGHTLESS TESTS PASSED"
+
+## test-all: adds tests that need a real checkpoint (set SHARD_DIR)
+test-all: test
+ @test -n "$(SHARD_DIR)" || { echo "set SHARD_DIR=/path/to/shards"; exit 2; }
+ $(MAKE) weights-test SHARD_DIR=$(SHARD_DIR)
+
+weights-test: $(WEIGHT_BINS)
+ ./$(BIN)/test_expert $(SHARD_DIR) 1 64
+ ./$(BIN)/test_real_layer $(SHARD_DIR) 1 4 8
+
+$(BIN)/test_expert: tests/unit/test_expert.c $(BUILD)/src/io/k3_load.o \
+ $(BUILD)/src/io/k3_st.o $(BUILD)/src/core/k3_ops.o | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+$(BIN)/test_real_layer: tests/unit/test_real_layer.c $(ENGINE_OBJ) | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
+## tok: tokenizer parity against the reference implementation
+tok: $(BIN)/test_tok
+ @$(PYTHON) tools/tok_parity.py ./$(BIN)/test_tok
+
+## cfg: config reader against both supported config layouts
+cfg: $(BIN)/test_cfg
+ @./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json
+ @test -f "$(TOK_FILES)/config.json" && ./$(BIN)/test_cfg real $(TOK_FILES)/config.json \
+ || echo " (skipped real config: none at $(TOK_FILES))"
+
+## bench: kernel microbenchmarks, no weights required
+bench: $(BIN)/bench_kernels
+ ./$(BIN)/bench_kernels
+
+## portable: no -march=native, runs on any x86-64
+portable:
+ $(MAKE) ARCH="-mavx2 -mfma" all
+
+## debug: -O0 -g, assertions on
+debug:
+ $(MAKE) CFLAGS="-O0 -g3 -std=gnu99 $(WARN) -fopenmp -ffp-contract=off" all
+
+asan:
+ $(MAKE) CFLAGS="-O1 -g -std=gnu99 $(WARN) -fsanitize=address,undefined -fno-omit-frame-pointer" \
+ LDFLAGS="-lm -fsanitize=address,undefined" ARCH= all
+
+ubsan:
+ $(MAKE) CFLAGS="-O1 -g -std=gnu99 $(WARN) -fsanitize=undefined" \
+ LDFLAGS="-lm -fsanitize=undefined" ARCH= all
+
+format:
+ @command -v clang-format >/dev/null || { echo "clang-format not installed"; exit 1; }
+ clang-format -i $(shell find src include tests benchmarks -name '*.c' -o -name '*.h' 2>/dev/null)
+
+# Installs the binary AND the public headers, matching CMake's install rules exactly
+# the two build systems are documented as interchangeable, so they must stay so.
+# third_party/json.h goes with them: k3_cfg.h includes it and exposes jval in its
+# signatures, so an installed k3_cfg.h without it does not compile.
+install: $(CLI_BIN)
+ install -d $(DESTDIR)$(PREFIX)/bin
+ install -m 755 $(CLI_BIN) $(DESTDIR)$(PREFIX)/bin/k3
+ install -d $(DESTDIR)$(PREFIX)/include/k3
+ install -m 644 include/k3/*.h $(DESTDIR)$(PREFIX)/include/k3/
+ install -m 644 third_party/json.h $(DESTDIR)$(PREFIX)/include/k3/
+
+clean:
+ rm -rf $(BUILD) $(BIN)
+
+## help: list targets
+help:
+ @grep -E '^## ' $(MAKEFILE_LIST) | sed 's/## / /'
diff --git a/ruff.toml b/ruff.toml
new file mode 100644
index 0000000..559529e
--- /dev/null
+++ b/ruff.toml
@@ -0,0 +1,47 @@
+# Lint configuration for the Python tooling under tools/.
+#
+# These scripts generate the test fixtures and the reference implementation the C engine
+# is graded against, so a defect here is a defect in the pass criteria, silently, and in
+# the direction of passing. That is what this configuration is selected to catch.
+#
+# It deliberately does NOT enforce style modernization. The rule set below is chosen so
+# that every reported finding is a real problem, because a gate that reports 200 findings
+# nobody intends to fix is a gate people learn to ignore.
+
+line-length = 100
+target-version = "py39"
+
+[lint]
+select = [
+ "F", # pyflakes: undefined names, unused imports, unused variables, f-string bugs
+ "E4", # import placement
+ "E7", # comparison and statement errors (== None, bare semicolons, lambda assignment)
+ "E9", # syntax and IO errors
+ "B", # bugbear: mutable default args, loop-variable capture, assert-on-tuple
+ "A", # builtin shadowing, `id`, `type` and `list` are easy to shadow accidentally
+ "RUF", # ruff-specific correctness checks
+]
+
+ignore = [
+ # %-formatting is used throughout for printf-style diagnostic output, where the format
+ # string reads as one unit alongside the C code printing the same thing. Converting to
+ # f-strings would be churn with no defect fixed.
+ "UP031", "UP032",
+ # Assert is used in the fixture generators as a precondition on generated data. That is
+ # the intended meaning: if the assertion fails the fixture is wrong and must not ship.
+ "B011",
+ # Ambiguous unicode is intentional in the tokenizer parity cases, which exist precisely
+ # to exercise homoglyphs, ZWJ sequences and combining marks.
+ "RUF001", "RUF002", "RUF003",
+ # Compact `a = x; b = y` for parallel assignments of the same kind, used consistently
+ # where splitting the pair across lines obscures that they belong together.
+ "E702",
+ # `list + [x]` rather than `[*list, x]`. Both are correct; neither is a defect.
+ "RUF005",
+]
+
+[lint.per-file-ignores]
+# The reference implementation mirrors modeling_kimi_linear.py statement for statement,
+# including its single-letter tensor names. Renaming them for style would break the
+# line-by-line correspondence that makes the reference auditable against the released code.
+"k3_ref.py" = ["E741"]