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
feat(scripts): fetch only the shards a --layers N run needs
Fareed Khan0838cb4cc45f
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 851bfbd..f34a3eb 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -216,6 +216,18 @@ add_test(NAME ultra_cli_contractCOMMAND ${CMAKE_COMMAND} -DCLI=$<TARGET_FILE:k3_cli>-P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/test_ultra_cli.cmake)+# Contract for tools/layers_to_shards.py, the mapper behind download-model.sh+# --layers. Same expectations as the "partial download contract" block in `make+# test`. find_program rather than find_package: python3 drives only this test,+# and a missing interpreter must fail this test, never the configure step.+find_program(K3_PYTHON python3)+if(K3_PYTHON)+ add_test(NAME partial_shards+ COMMAND ${CMAKE_COMMAND} -DPYTHON=${K3_PYTHON}+ -DFIXTURES=${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/test_partial_shards.cmake)+endif()+# The tokenizer test needs the released vocabulary, which is not in this repository.# 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 sentencediff --git a/Makefile b/Makefileindex 49d4dc6..6a54970 100644--- a/Makefile+++ b/Makefile@@ -282,6 +282,31 @@ test: $(CLI_BIN) $(TEST_BINS)echo " asserting only the exit code would pass on the loader's error"; exit 1;; \esac; \done; echo " 6 malformed numerics refused, each for the right reason"+ @echo "== partial download contract =="; \+ if ! command -v $(PYTHON) >/dev/null 2>&1; then \+ echo " NOT RUN: no $(PYTHON) on PATH. tools/layers_to_shards.py backs"; \+ echo " download-model.sh --layers; the engine itself needs no Python."; \+ else \+ out=$$($(PYTHON) tools/layers_to_shards.py $(FIXTURES)/partial_index.json --layers 1); \+ exp=$$(printf 'model-00001-of-00005.safetensors\nmodel-00002-of-00005.safetensors\nmodel-00005-of-00005.safetensors'); \+ test "$$out" = "$$exp" || { echo " --layers 1 mapped to:"; echo " $$out"; exit 1; }; \+ out=$$($(PYTHON) tools/layers_to_shards.py $(FIXTURES)/partial_index.json --layers 2); \+ case "$$out" in *"model-00003-of-00005.safetensors"*) ;; \+ *) echo " --layers 2 missed the shard holding half of layer 1:"; \+ echo " $$out"; exit 1;; \+ esac; \+ case "$$out" in *"model-00004-of-00005.safetensors"*) \+ echo " --layers 2 pulled the shard holding only a far-future layer:"; \+ echo " $$out"; exit 1;; \+ esac; \+ for bad in "--layers 0" "--layers 9" "--layers abc" "--layers 1junk"; do \+ $(PYTHON) tools/layers_to_shards.py $(FIXTURES)/partial_index.json $$bad >/dev/null 2>&1; \+ rc=$$?; test $$rc -eq 2 || { echo " '$$bad' returned $$rc, expected 2"; exit 1; }; \+ done; \+ $(PYTHON) tools/layers_to_shards.py $(FIXTURES)/partial_index_nomap.json --layers 1 >/dev/null 2>&1; \+ rc=$$?; test $$rc -eq 2 || { echo " index without a weight_map returned $$rc, expected 2"; exit 1; }; \+ echo " 2 prefix maps exact, 5 malformed inputs refused with exit 2"; \+ fi@echo "== op kernels =="; ./$(BIN)/test_ops $(FIXTURES)/ops@echo "== streaming cache =="; ./$(BIN)/test_cache $(FIXTURES)/cache@echo "== streaming cache, split reads =="; K3_EXPERT_CHUNK=4096 ./$(BIN)/test_cache $(FIXTURES)/cachediff --git a/cmake/test_partial_shards.cmake b/cmake/test_partial_shards.cmakenew file mode 100644index 0000000..a00eaeb--- /dev/null+++ b/cmake/test_partial_shards.cmake@@ -0,0 +1,53 @@+# Contract for tools/layers_to_shards.py, mirroring the "partial download+# contract" block in `make test`. Same fixture, same expectations: an exact+# shard set for --layers 1, the split-layer shard present and the far-future+# shard absent for --layers 2, and exit 2 for every malformed input.+if(NOT DEFINED PYTHON OR NOT DEFINED FIXTURES)+ message(FATAL_ERROR "PYTHON and FIXTURES were not provided")+endif()++function(map_layers out_var rc_var)+ execute_process(+ COMMAND "${PYTHON}" "${CMAKE_CURRENT_LIST_DIR}/../tools/layers_to_shards.py" ${ARGN}+ OUTPUT_VARIABLE map_out+ ERROR_QUIET+ RESULT_VARIABLE map_rc)+ # execute_process keeps the trailing newline; command substitution in the+ # Makefile block strips it. Strip it here so both harnesses compare the same+ # string.+ string(REGEX REPLACE "\n$" "" map_out "${map_out}")+ set(${out_var} "${map_out}" PARENT_SCOPE)+ set(${rc_var} "${map_rc}" PARENT_SCOPE)+endfunction()++map_layers(out1 rc1 "${FIXTURES}/partial_index.json" --layers 1)+if(NOT rc1 EQUAL 0)+ message(FATAL_ERROR "--layers 1 returned ${rc1}, expected 0")+endif()+set(exp1 "model-00001-of-00005.safetensors\nmodel-00002-of-00005.safetensors\nmodel-00005-of-00005.safetensors")+if(NOT out1 STREQUAL exp1)+ message(FATAL_ERROR "--layers 1 mapped to [${out1}], expected [${exp1}]")+endif()++map_layers(out2 rc2 "${FIXTURES}/partial_index.json" --layers 2)+if(NOT rc2 EQUAL 0)+ message(FATAL_ERROR "--layers 2 returned ${rc2}, expected 0")+endif()+if(NOT out2 MATCHES "model-00003-of-00005\\.safetensors")+ message(FATAL_ERROR "--layers 2 missed the shard holding half of layer 1: [${out2}]")+endif()+if(out2 MATCHES "model-00004-of-00005\\.safetensors")+ message(FATAL_ERROR "--layers 2 pulled the far-future shard: [${out2}]")+endif()++foreach(bad 0 9 abc 1junk)+ map_layers(bad_out bad_rc "${FIXTURES}/partial_index.json" --layers "${bad}")+ if(NOT bad_rc EQUAL 2)+ message(FATAL_ERROR "--layers ${bad} returned ${bad_rc}, expected 2")+ endif()+endforeach()++map_layers(nomap_out nomap_rc "${FIXTURES}/partial_index_nomap.json" --layers 1)+if(NOT nomap_rc EQUAL 2)+ message(FATAL_ERROR "index without a weight_map returned ${nomap_rc}, expected 2")+endif()diff --git a/docs/TUNING.md b/docs/TUNING.mdindex b9b9671..31c6e4f 100644--- a/docs/TUNING.md+++ b/docs/TUNING.md@@ -123,6 +123,9 @@ trunk is fully resident and the floor is ~115 GB. Pack it once with**`--layers N`** binds only the first N layers. Useful for testing the machinery on apartial download; the output is not the full model and the engine says so.+`scripts/download-model.sh <dest> --layers N` fetches exactly that prefix (shards+resolved from the Hub's tensor index, sizes verified), so a 1 TB disk can still+exercise the pipeline.## Storage matters more than you expectdiff --git a/scripts/download-model.sh b/scripts/download-model.shindex b9f5172..1b3736f 100755--- a/scripts/download-model.sh+++ b/scripts/download-model.sh@@ -1,12 +1,19 @@#!/usr/bin/env bash# download-model.sh, fetch the Kimi K3 checkpoint and verify it byte-exactly.#-# scripts/download-model.sh <dest_dir>+# scripts/download-model.sh <dest_dir> [--layers N]## The checkpoint is 1.56 TB across 96 safetensors shards. A partial or corrupt download# 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.#+# With --layers N, only the shards holding layers 0..N-1 (plus the embedding table and+# the output head, which every run needs) are fetched, as resolved from the Hub's own+# tensor-to-shard index rather than guessed from filenames. The result runs ONLY with+# `k3 ... --layers M` for M <= N; it is a test instrument for exercising the pipeline,+# measuring per-layer cost and checking the I/O path, not the model. The engine prints+# that plainly on every such run, and so does this script.+## 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.@@ -21,7 +28,26 @@ case "$(uname -s)" inesacfilesize() { stat $STAT_FMT "$1"; }-DEST="${1:?usage: download-model.sh <dest_dir>}"+DEST="${1:?usage: download-model.sh <dest_dir> [--layers N]}"+LAYERS=""+if [ "${2:-}" != "" ]; then+ [ "${2:-}" = "--layers" ] || {+ echo "usage: download-model.sh <dest_dir> [--layers N]" >&2+ exit 1+ }+ LAYERS="${3:?usage: download-model.sh <dest_dir> [--layers N]}"+ [ "${4:-}" = "" ] || {+ echo "usage: download-model.sh <dest_dir> [--layers N]" >&2+ exit 1+ }+ # atoi-style parsing turned "1junk" into 1 in the CLI once; refuse that shape+ # here rather than downloading a prefix nobody asked for.+ case "$LAYERS" in+ ''|*[!0-9]*|0*)+ echo "download-model.sh: --layers must be a positive integer, got '$LAYERS'." >&2+ exit 1 ;;+ esac+fiREPO="moonshotai/Kimi-K3"# Published totals for the released checkpoint. Verified, not assumed.@@ -94,6 +120,98 @@ esacmkdir -p "$DEST"+# Partial mode: fetch only the shards a --layers N run binds. The shard set comes+# from tools/layers_to_shards.py over the Hub's own tensor index, never from a+# filename guess, and the per-shard sizes below are checked against the same+# published figures as the full download. The full byte total and the Hub checksum+# verification are defined over all 96 shards, so they cannot pass here and are+# skipped loudly rather than weakened into something that looks like proof.+if [ -n "$LAYERS" ]; then+ MAPPER="$(dirname "$0")/../tools/layers_to_shards.py"+ SIZES="$(dirname "$0")/shard_sizes.txt"+ [ -f "$SIZES" ] || {+ echo "FAIL: $SIZES is missing; the subset cannot be sized or verified." >&2+ exit 1+ }+ echo "resolving layer prefix --layers $LAYERS to shards…"+ echo " (fetching the 59 MB tensor index first; the shards follow)"+ HF_XET_HIGH_PERFORMANCE="${HF_XET_HIGH_PERFORMANCE:-1}" \+ hf download "$REPO" --revision "$REVISION" --local-dir "$DEST" --max-workers 16 \+ --include "model.safetensors.index.json" \+ --include "config.json" \+ --include "tokenizer_config.json" \+ --include "tiktoken.model"+ [ -f "$DEST/config.json" ] || {+ echo "FAIL: config.json did not download; without it the engine refuses to start." >&2+ exit 1+ }+ [ -f "$DEST/tiktoken.model" ] || {+ echo "WARNING: tiktoken.model did not download; --ids runs work without it," >&2+ echo " but --prompt/--prompt-file need --tok pointing at a tokenizer." >&2+ }+ SHARD_LIST="$DEST/.k3_partial_shards.txt"+ python3 "$MAPPER" "$DEST/model.safetensors.index.json" --layers "$LAYERS" >"$SHARD_LIST" || {+ echo "FAIL: could not resolve --layers $LAYERS to shards; nothing fetched." >&2+ exit 1+ }+ # Size the subset BEFORE moving gigabytes: a --layers prefix still pulls whole+ # expert pools per layer (each MoE layer holds 896 routed experts), so N=8 is+ # ~125 GB, not megabytes. Failing here reports a number instead of filling the disk.+ NEED=0+ while read -r name; do+ [ -n "$name" ] || continue+ want=$(awk -v n="$name" '$1 == n {print $2}' "$SIZES")+ [ -n "$want" ] || {+ echo "FAIL: $name is not in the published shard sizes; refusing to guess." >&2+ exit 1+ }+ NEED=$((NEED + want))+ done <"$SHARD_LIST"+ NSHARD=$(wc -l <"$SHARD_LIST" | tr -d ' ')+ AVAIL=$(df -P -k "$DEST" | awk 'NR==2 {print $4 * 1024}')+ if [ "$AVAIL" -lt "$NEED" ]; then+ printf 'FAIL: %s has %s bytes free, --layers %s needs %s across %s shard(s).\n' \+ "$DEST" "$AVAIL" "$LAYERS" "$NEED" "$NSHARD" >&2+ exit 1+ fi+ echo "downloading $NSHARD shard(s), $NEED bytes, for --layers $LAYERS"+ INC=()+ while read -r name; do+ [ -n "$name" ] || continue+ INC+=(--include "$name")+ done <"$SHARD_LIST"+ # Every element is an exact shard filename from the index (no spaces, no+ # globs), so the quoted expansion passes one --include per shard.+ HF_XET_HIGH_PERFORMANCE="${HF_XET_HIGH_PERFORMANCE:-1}" \+ hf download "$REPO" --revision "$REVISION" --local-dir "$DEST" --max-workers 16 \+ "${INC[@]}"+ echo+ echo "verifying…"+ bad=0+ while read -r name; do+ [ -n "$name" ] || continue+ want=$(awk -v n="$name" '$1 == n {print $2}' "$SIZES")+ got=$(filesize "$DEST/$name" 2>/dev/null || echo 0)+ if [ "$got" != "$want" ]; then+ printf ' BAD %s: %s bytes, expected %s\n' "$name" "$got" "$want"+ bad=$((bad + 1))+ fi+ done <"$SHARD_LIST"+ if [ "$bad" -ne 0 ]; then+ echo "FAIL: $bad shard(s) do not match their published sizes."+ echo " Delete just those files and re-run; the download resumes."+ exit 1+ fi+ printf ' shards : all %s match their published sizes individually\n' "$NSHARD"+ echo+ echo "PARTIAL CHECKPOINT: layers 0..$((LAYERS - 1)) plus embed/head, $NSHARD of $EXPECT_SHARDS shards."+ echo " This is NOT the full model. Run only as:"+ echo " ./bin/k3 $DEST --layers $LAYERS --ids ... (or any M <= $LAYERS)"+ echo " The engine prints the same warning on every such run. Full runs need the"+ echo " whole 1.56 TB: re-run without --layers."+ exit 0+fi+# 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.diff --git a/tests/fixtures/partial_index.json b/tests/fixtures/partial_index.jsonnew file mode 100644index 0000000..b0ad266--- /dev/null+++ b/tests/fixtures/partial_index.json@@ -0,0 +1,20 @@+{+ "metadata": {+ "total_size": 42,+ "note": "Miniature stand-in for the Hub's model.safetensors.index.json, shaped so a plausible wrong mapper fails. Layer 0 is split across shards 1 AND 2 (a first-shard-per-layer lookup misses half of it), layer 1 lives wholly in shard 3 (a first-K-shards guess is wrong in both directions), shard 4 holds only a far-future layer and a vision tensor (an implementation that returns every shard, or every non-layer tensor, passes nothing), and shard 5 holds the final norm and output AttnRes tensors apart from the embedding and head (a mapper that follows only embed and head misses it)."+ },+ "weight_map": {+ "language_model.model.embed_tokens.weight": "model-00001-of-00005.safetensors",+ "language_model.lm_head.weight": "model-00001-of-00005.safetensors",+ "language_model.model.layers.0.input_layernorm.weight": "model-00001-of-00005.safetensors",+ "language_model.model.layers.0.mlp.weight": "model-00002-of-00005.safetensors",+ "language_model.model.layers.1.input_layernorm.weight": "model-00003-of-00005.safetensors",+ "language_model.model.layers.1.mlp.weight": "model-00003-of-00005.safetensors",+ "language_model.model.layers.2.input_layernorm.weight": "model-00003-of-00005.safetensors",+ "language_model.model.layers.7.mlp.weight": "model-00004-of-00005.safetensors",+ "language_model.model.norm.weight": "model-00005-of-00005.safetensors",+ "language_model.model.output_attn_res_norm.weight": "model-00005-of-00005.safetensors",+ "language_model.model.output_attn_res_proj.weight": "model-00005-of-00005.safetensors",+ "vision_tower.patch_embed.proj.weight": "model-00004-of-00005.safetensors"+ }+}diff --git a/tests/fixtures/partial_index_nomap.json b/tests/fixtures/partial_index_nomap.jsonnew file mode 100644index 0000000..eca9029--- /dev/null+++ b/tests/fixtures/partial_index_nomap.json@@ -0,0 +1,6 @@+{+ "metadata": {+ "total_size": 0,+ "note": "An index with no weight_map at all. The mapper must refuse it, never guess."+ }+}diff --git a/tools/layers_to_shards.py b/tools/layers_to_shards.pynew file mode 100644index 0000000..10c7fdd--- /dev/null+++ b/tools/layers_to_shards.py@@ -0,0 +1,121 @@+#!/usr/bin/env python+"""+layers_to_shards.py - which shards does a `--layers N` run actually need?++WHY THIS EXISTS+ `--layers N` binds only the first N decoder layers, so it runs against a partial+ shard set. But which shards hold layers 0..N-1 is not something you can guess from+ the filenames: tensors are packed bin-first, so one layer spans several shards and+ one shard holds slices of several layers (layer 0 alone touches shards 1 AND 2,+ while the embedding table and the output head both live in shard 94). Guessing+ "the first K shards" downloads the wrong set and the engine refuses it with+ "missing tensors in this shard set" after the gigabytes have already moved.++ The Hub publishes the exact tensor-to-shard map as model.safetensors.index.json+ (59 MB, fetched by download-model.sh before this runs). This script reads that map+ and prints the minimal shard set for the requested prefix: every shard holding any+ tensor of layers 0..N-1, plus the shards holding the embedding table and the+ output head, which every run needs regardless of depth.++ usage: layers_to_shards.py <model.safetensors.index.json> --layers N++ Prints one shard filename per line, sorted, on stdout. Anything else is an error:+ exit 2, following the engine's own convention that a usage or config problem is+ exit 2, never a silent default.+"""+from __future__ import annotations++import argparse+import json+import re+import sys++LAYER_RE = re.compile(r"^language_model\.model\.layers\.(\d+)\.")+EMBED_KEY = "language_model.model.embed_tokens.weight"+HEAD_KEY = "language_model.lm_head.weight"+++def parse_args(argv: list[str]) -> argparse.Namespace:+ p = argparse.ArgumentParser(description="map a --layers N prefix to shard files")+ p.add_argument("index", help="model.safetensors.index.json from the Hub")+ p.add_argument("--layers", required=True, help="layer-prefix depth N (>= 1)")+ args = p.parse_args(argv)+ try:+ layers = int(args.layers)+ except ValueError:+ p.error("--layers must be a positive integer, got %r" % args.layers)+ if layers < 1:+ p.error("--layers must be a positive integer, got %r" % args.layers)+ args.layers = layers+ return args+++def main(argv: list[str]) -> int:+ args = parse_args(argv)+ try:+ with open(args.index, encoding="utf-8") as f:+ index = json.load(f)+ except (OSError, ValueError) as e:+ print("layers_to_shards: cannot read %s: %s" % (args.index, e), file=sys.stderr)+ return 2+ weight_map = index.get("weight_map") if isinstance(index, dict) else None+ if not isinstance(weight_map, dict) or not weight_map:+ print(+ "layers_to_shards: %s has no usable weight_map; refusing to guess." % args.index,+ file=sys.stderr,+ )+ return 2++ max_layer = -1+ for name in weight_map:+ m = LAYER_RE.match(name)+ if m:+ max_layer = max(max_layer, int(m.group(1)))+ if max_layer < 0:+ print(+ "layers_to_shards: no language_model.model.layers.* tensors in %s." % args.index,+ file=sys.stderr,+ )+ return 2+ if args.layers > max_layer + 1:+ print(+ "layers_to_shards: --layers %d exceeds the %d layers in %s."+ % (args.layers, max_layer + 1, args.index),+ file=sys.stderr,+ )+ return 2++ for key in (EMBED_KEY, HEAD_KEY):+ if key not in weight_map:+ print(+ "layers_to_shards: %s is absent from %s; refusing to guess where it lives."+ % (key, args.index),+ file=sys.stderr,+ )+ return 2++ # Every language_model tensor outside the decoder layers is bound on every run:+ # the embedding and head, but also the final norm and the output AttnRes pair. In+ # the released index they all happen to share shard 94; selecting them by name+ # rather than by that coincidence keeps a re-sharded revision from producing a+ # subset that downloads cleanly and then fails to load. Vision tensors are not+ # language_model tensors and stay out.+ need: set[str] = set()+ for name, shard in weight_map.items():+ m = LAYER_RE.match(name)+ if m:+ if int(m.group(1)) < args.layers:+ need.add(shard)+ elif name.startswith("language_model."):+ need.add(shard)+ # LF, not the platform's text-mode newline: download-model.sh reads these names with+ # `read -r`, and under Git Bash on Windows a CRLF leaves a carriage return on every+ # name, so no shard matches its published size and every one is refused.+ sys.stdout.reconfigure(newline="\n")+ for shard in sorted(need):+ print(shard)+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))