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.

feat: add exact ultra-low-memory full-model inference

Fareed Khanb2f5b5bc6f1f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index fefd90b..40f0005 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -135,7 +135,8 @@ jobs:
run: |
make CFLAGS="-O1 -g -std=gnu99 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer" \
LDFLAGS="-lm -fsanitize=address,undefined" ARCH= \
- bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/k3_model \
+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st \
+ bin/test_model_stream bin/k3_model \
bin/bench_kernels \
-j"$(nproc)"
- name: Run under sanitizers
@@ -151,6 +152,7 @@ jobs:
./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
+ ./bin/test_model_stream tests/fixtures/st
./bin/k3_model tests/fixtures
# The ms and GFLOP/s it prints are meaningless under -O1 with ASan interceptors
# on every load. It is run for what ASan sees, not for what it reports.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4ac3657..54053fc 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -96,6 +96,7 @@ 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_model_stream tests/unit/test_model_stream.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)
@@ -126,6 +127,10 @@ 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)
+add_test(NAME model_stream COMMAND test_model_stream ${FIX}/st)
+add_test(NAME ultra_cli_contract
+ COMMAND ${CMAKE_COMMAND} -DCLI=$<TARGET_FILE:k3_cli>
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/test_ultra_cli.cmake)
# 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:
diff --git a/Makefile b/Makefile
index baa7849..c1c8ff3 100644
--- a/Makefile
+++ b/Makefile
@@ -65,9 +65,13 @@ ifeq ($(UNAME_S),Darwin)
$(warning or point the build at another copy with `make OMP_PREFIX=/path/to/libomp`.)
endif
else
- # -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
+ # GCC uses -mcpu=native for AArch64 tuning. Keep -march=native on the x86 reference;
+ # `make portable` drops both so the produced binary is not tied to the build host.
+ ifeq ($(UNAME_M),aarch64)
+ ARCH ?= -mcpu=native
+ else
+ ARCH ?= -march=native
+ endif
OMP_CFLAGS ?= -fopenmp
OMP_LDFLAGS ?= -fopenmp
endif
@@ -102,7 +106,7 @@ 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 test_trunk
+UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok scale_test k3_model test_trunk
# 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
@@ -144,6 +148,10 @@ $(BIN)/test_cache: tests/unit/test_cache.c $(BUILD)/src/cache/k3_cache.o \
$(BIN)/test_st: tests/unit/test_st.c $(BUILD)/src/io/k3_st.o | $(BIN)
$(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
+$(BIN)/test_model_stream: tests/unit/test_model_stream.c $(BUILD)/src/model/k3_bind.o \
+ $(BUILD)/src/io/k3_st.o $(BUILD)/src/core/k3_ops.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)
@@ -170,11 +178,19 @@ $(BIN)/bench_kernels: benchmarks/bench_kernels.c $(BUILD)/src/core/k3_ops.o | $(
$(CC) $(CFLAGS) $(INCLUDES) $^ -o $@ $(LDFLAGS)
## test: everything that needs no model weights
-test: $(TEST_BINS)
+test: $(CLI_BIN) $(TEST_BINS)
+ @echo "== ultra CLI contract =="; \
+ if ./$(CLI_BIN) fake --ids 1 --preset ultra >/dev/null 2>&1; then \
+ echo "ultra mode accepted a missing --trunk"; exit 1; \
+ else rc=$$?; test $$rc -eq 2 || exit 1; fi; \
+ if ./$(CLI_BIN) fake --ids 1 --preset ultra --trunk fake --spec 2 >/dev/null 2>&1; then \
+ echo "ultra mode accepted --spec"; exit 1; \
+ else rc=$$?; test $$rc -eq 2 || exit 1; fi
@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 "== model streaming =="; ./$(BIN)/test_model_stream $(FIXTURES)/st
@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 \
@@ -231,7 +247,7 @@ bench: $(BIN)/bench_kernels
# On x86-64 that means a generic AVX2 + FMA baseline. On arm64 there is no equivalent
# sub-baseline worth naming -- the ISA is the baseline -- so tuning is simply omitted.
portable:
-ifeq ($(UNAME_S)/$(UNAME_M),Darwin/arm64)
+ifneq ($(filter arm64 aarch64,$(UNAME_M)),)
$(MAKE) ARCH= all
else
$(MAKE) ARCH="-mavx2 -mfma" all
diff --git a/README.md b/README.md
index 902d603..cf9dc9d 100644
--- a/README.md
+++ b/README.md
@@ -404,6 +404,11 @@ 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 |
+| `--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
+0.31 GB expert cache. It is a proof-of-life path for 8 GB-class machines, not an
+interactive-speed preset; model precision, Top-K routing and all 93 layers are unchanged.
`--preset` and the two `-gb` flags set the same two numbers, so a preset is just a
shorthand. Order matters if you mix them: a later flag wins, so
@@ -459,6 +464,10 @@ Scripts can rely on these.
### Worked examples
```bash
+# Full-model, one-token proof of life on an 8 GB-class ARM64 machine.
+./bin/k3 ~/k3model --trunk ~/k3trunk --preset ultra \
+ --tok ~/k3model --prompt "The capital of France is" --gen 1
+
# Smallest possible run, the 8 GB floor.
./bin/k3 ~/k3model --trunk ~/k3trunk --preset laptop \
--tok ~/k3model --prompt "Hello! My name is" --gen 16 --incremental
@@ -501,11 +510,12 @@ systemd-run --scope --user -q -p MemoryMax=8G -p MemorySwapMax=0 \
```console
$ ./bin/k3 --list-presets
presets (trunk / expert-cache, in GB):
- laptop 3.0 / 1.0 8.2 GB peak RSS. The floor. Runs, slowly.
- desktop 16.0 / 10.0 31.9 GB peak RSS.
- workstation 60.0 / 30.0 95.5 GB peak RSS; the expert cache starts to matter here.
- server 110.0 / 13.0 ~128 GB peak RSS; 90 of 93 trunk layers pinned. Fastest.
- max 110.0 / 109.0 ~224 GB peak RSS; trunk pinned and a large expert cache.
+ ultra 2.50 / 0.31 ~3 GB planned: streamed model tables, one state slot. Slow.
+ laptop 3.00 / 1.00 8.2 GB peak RSS. The ordinary-path floor.
+ desktop 16.00 / 10.00 31.9 GB peak RSS.
+ workstation 60.00 / 30.00 95.5 GB peak RSS; the expert cache starts to matter here.
+ server 110.00 / 13.00 ~128 GB peak RSS; 90 of 93 trunk layers pinned. Fastest.
+ max 110.00 / 109.00 ~224 GB peak RSS; trunk pinned and a large expert cache.
All presets stream the trunk, so they need --trunk <packed_dir>.
Run scripts/k3-doctor.sh to see which one this machine fits.
diff --git a/cmake/test_ultra_cli.cmake b/cmake/test_ultra_cli.cmake
new file mode 100644
index 0000000..388181e
--- /dev/null
+++ b/cmake/test_ultra_cli.cmake
@@ -0,0 +1,19 @@
+if(NOT DEFINED CLI)
+ message(FATAL_ERROR "CLI was not provided")
+endif()
+
+execute_process(
+ COMMAND "${CLI}" fake --ids 1 --preset ultra
+ RESULT_VARIABLE no_trunk_rc
+ OUTPUT_QUIET ERROR_QUIET)
+if(NOT no_trunk_rc EQUAL 2)
+ message(FATAL_ERROR "ultra mode without --trunk returned ${no_trunk_rc}, expected 2")
+endif()
+
+execute_process(
+ COMMAND "${CLI}" fake --ids 1 --preset ultra --trunk fake --spec 2
+ RESULT_VARIABLE spec_rc
+ OUTPUT_QUIET ERROR_QUIET)
+if(NOT spec_rc EQUAL 2)
+ message(FATAL_ERROR "ultra mode with --spec returned ${spec_rc}, expected 2")
+endif()
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 2479f6f..9f59891 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -31,6 +31,11 @@ on it, producing fluent but wrong tokens with no diagnostic.
**`test_st`**, the safetensors reader: dtype widening, offsets, tail bytes, escaped
tensor names, and a tensor deliberately containing non-finite values.
+**`test_model_stream`**, the ultra-low-memory model-table reader. It gathers one BF16
+embedding row and projects through the lm_head in bounded aligned chunks, then requires
+both results to be bit-identical to the resident kernels. It also injects a corrupt file
+offset and requires the resulting short read to fail without being counted as valid I/O.
+
**`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
@@ -76,6 +81,7 @@ first case. The roundtrip leg in `make test` needs only `tiktoken.model` and
architecture exactly:
- teacher forcing: every position matches the reference
+- full-recompute state reuse: every logit is bit-identical with one recurrent-state slot
- greedy decode: every generated token matches
- incremental decode: same tokens as full recompute, with KV cache and carried
recurrent state
diff --git a/docs/TUNING.md b/docs/TUNING.md
index 0949a1c..a5a145d 100644
--- a/docs/TUNING.md
+++ b/docs/TUNING.md
@@ -88,6 +88,7 @@ $ ./bin/k3 --list-presets
| preset | trunk | cache | total | expect |
|---|---:|---:|---:|---|
+| `ultra` | 2.5 | 0.31 | ~3 GB | proof-of-life only; streams embed/lm_head and reuses one state slot |
| `laptop` | 3 | 1 | ~10 GB | ~32 s/token |
| `desktop` | 16 | 10 | ~32 GB | ~31 s/token |
| `workstation` | 60 | 30 | ~96 GB | ~24 s/token |
@@ -100,6 +101,12 @@ in these measurements, the extra 96 GB buys nothing outside the noise floor.
Flags after `--preset` override it, so `--preset server --cache-gb 40` works.
+`ultra` is deliberately a separate execution path, not a smaller ordinary preset. It
+requires a packed trunk, streams exact BF16 embedding/lm_head bytes, and with full
+recompute clears and reuses one layer-state slot. It trades I/O for RAM and is intended
+for short, deterministic proof runs; speculative/draft decoding is rejected in this
+mode. The arithmetic, Top-K routing and weight precision are unchanged.
+
## Other options
**`--incremental`** carries a KV cache and the recurrent state between tokens instead of
diff --git a/docs/results/jetson-orin-nano-super/README.md b/docs/results/jetson-orin-nano-super/README.md
new file mode 100644
index 0000000..c37ddfc
--- /dev/null
+++ b/docs/results/jetson-orin-nano-super/README.md
@@ -0,0 +1,99 @@
+# Jetson Orin Nano Super proof of life
+
+This is a four-run reproduction of one-token inference with the complete official
+Kimi K3 text checkpoint on an 8 GB-class Jetson. It demonstrates completion under a
+tight RAM budget; it is not an interactive-performance claim.
+
+## Result
+
+Input: `The capital of France is`
+
+| run | token ID | decoded token | layers | expert drops | peak RSS | inference time |
+|---:|---:|---|---:|---:|---:|---:|
+| 1 | `17374` | ` Paris` | 93/93 | 0 | 2,760,306,688 bytes | 948.5179 s |
+| 2 | `17374` | ` Paris` | 93/93 | 0 | 2,759,565,312 bytes | 949.8126 s |
+| 3 | `17374` | ` Paris` | 93/93 | 0 | 2,762,563,584 bytes | 950.6945 s |
+| 4 | `17374` | ` Paris` | 93/93 | 0 | 2,761,093,120 bytes | 948.7180 s |
+
+All four runs passed every structural gate and matched the recorded greedy reference.
+Their complete float32 logit dumps also had the same SHA-256, so the agreement was not
+limited to argmax. Mean inference time was 949.4358 seconds (15m 49.4s); maximum peak RSS
+was 2.573 GiB.
+
+The proof runner treats token ID `17374`, decoded token ` Paris`, 93/93 completed layers
+and zero expert drops as hard acceptance gates. Its case-insensitive `Paris` check is
+reported only as an additional semantic diagnostic and cannot turn a mismatch into PASS.
+
+Each run read exactly:
+
+- 108,811,952,128 bytes of packed dense trunk from the internal NVMe;
+- 99,703,554,048 bytes of routed experts from the external rotating HDD;
+- 71,680 bytes of selected embedding rows;
+- 2,348,810,240 bytes of chunked lm_head data.
+
+The checkpoint kept its official BF16 and MXFP4 representations. The path uses the
+original Top-16 routing and all official weights; it does not drop experts, layers, or
+precision. Embedding rows and lm_head chunks use the same resident kernels after an
+aligned read, and the full-recompute recurrent state reuses one slot only after the
+previous layer has finished consuming it.
+
+## Machine and storage
+
+- NVIDIA Jetson Orin Nano Super, six visible CPU cores;
+- Ubuntu 22.04.5 LTS, Jetson Linux R36.4.4, Linux 5.15.148-tegra, `aarch64`;
+- scalar/ARM C path with OpenMP; no CUDA inference implementation;
+- official checkpoint and routed experts on `/dev/sda2`, a rotating external HDD;
+- packed 93-layer dense trunk on `/dev/nvme0n1p1`, the internal NVMe.
+
+The expert loader used serial reads (`K3_NOPREFETCH=1`) to avoid multi-stream seeks on
+the HDD. That changes I/O scheduling only; routing, weights, accumulation and output are
+unchanged.
+
+## Checkpoint identity
+
+- repository: `moonshotai/Kimi-K3`;
+- immutable revision: `9f62e4e9fffbd0a83ddd60e1c209d828994b3569`;
+- official safetensors shards: 96;
+- exact safetensors bytes: 1,560,936,091,448;
+- checksum verification completed: `2026-08-08T21:02:46+08:00`.
+
+The verification marker is created only after `hf cache verify --fail-on-missing-files`
+succeeds. The proof script also rejects a missing marker, a changed/newer shard, a wrong
+repository or revision, the wrong shard count/byte total, or a trunk other than the exact
+93-layer 108,811,952,128-byte manifest.
+
+## Source provenance
+
+This worktree starts from upstream v1.0.0 commit
+`ff11dce858a2eb8a781224facdffd33a1fa48d25`. The Jetson executed a source bundle without
+Git metadata. A sanitizer pass after the first three runs found a strict-alignment edge
+case in synthetic BF16 data; the safeguard was added and a fourth complete run was
+performed. The official embedding and lm_head offsets were already 4-byte aligned, and
+all four logit hashes remained identical. The final runtime source manifest has SHA-256
+`fb416123155a9d76a7559050a4b42ed2174f7e910b27b6911d17a76a6c978ea6`.
+Before publication cleanup, all 293 captured files matched it byte-for-byte. That
+manifest incidentally included one generated `tools/__pycache__` file. In the proposed
+tree, 288 entries still match exactly; the four intentional differences are CI coverage,
+README text, the proof runner's stricter exact-output gate, and line wrapping only in
+`src/cli/k3_run.c`. The generated cache is omitted and the seven result files below are
+new. All other runtime, build, fixture, download and packer files remain byte-identical
+to the fourth run.
+
+## Artifact hashes
+
+The small result and acceptance JSON files are included here. Large logs and float32
+logit dumps are retained on the experiment host rather than committed to Git.
+
+```text
+4197fa5554f2c97c82f24bb76481941d1d8252a1001388d8e458aded9c3145f8 result-run-1.json
+ea5d5dd9bb5130a3b864aba8b6360359636b551ebab9ec5eedba33f13cadc22c result-run-2.json
+7a832b6ff39e43e88be2274231c3cbd1ce008883fa8c3cd2fc2e303e762dca62 result-run-3.json
+f8106d0c6b1e1f586737f42727d586d8f5755056ea3a0c75e68d5390c164d6f6 result-run-4.json
+d41c716a64a85ac6ecbad2ffb31f45e5fb0f998c4d003852345af49510acec16 acceptance.json
+d5f6e2ef3d533cf1b80ba2cff4ee74cf4fc6d3011f80d7b64cf9703f38d5fe20 checkpoint-verification.txt
+4518032e5cac0763caae4c6f23a026f4644bb3c1209779e53d21136354880d28 logits.f32 (all four runs)
+8ef4776ab9e412821d00867b1de76c754b06d45c3ee70471cf73cadd2ae0c8dd trunk.json
+```
+
+The official checkpoint, packed trunk, routed weights and logit dumps are not
+redistributed by this repository.
diff --git a/docs/results/jetson-orin-nano-super/acceptance.json b/docs/results/jetson-orin-nano-super/acceptance.json
new file mode 100644
index 0000000..9df0d67
--- /dev/null
+++ b/docs/results/jetson-orin-nano-super/acceptance.json
@@ -0,0 +1,26 @@
+{
+ "hard_checks": {
+ "prompt tokenization": true,
+ "official 93-layer walk": true,
+ "no expert drops": true,
+ "exactly one generated token": true,
+ "exact token ID 17374": true,
+ "exact decoded token ' Paris'": true,
+ "ultra path active": true,
+ "peak RSS <= 6 GiB": true,
+ "trunk was read": true,
+ "experts were read": true,
+ "embedding was streamed": true,
+ "lm_head was streamed": true
+ },
+ "hard_pass": true,
+ "reference_token_id": 17374,
+ "reference_decoded": " Paris",
+ "reference_match": true,
+ "generated_ids": [
+ 17374
+ ],
+ "generated_text": " Paris",
+ "semantic_reasonable": true,
+ "semantic_rule": "the single decoded token contains Paris, case-insensitive"
+}
diff --git a/docs/results/jetson-orin-nano-super/checkpoint-verification.txt b/docs/results/jetson-orin-nano-super/checkpoint-verification.txt
new file mode 100644
index 0000000..f718525
--- /dev/null
+++ b/docs/results/jetson-orin-nano-super/checkpoint-verification.txt
@@ -0,0 +1,3 @@
+repo=moonshotai/Kimi-K3
+revision=9f62e4e9fffbd0a83ddd60e1c209d828994b3569
+verified_at=2026-08-08T21:02:46+08:00
diff --git a/docs/results/jetson-orin-nano-super/result-run-1.json b/docs/results/jetson-orin-nano-super/result-run-1.json
new file mode 100644
index 0000000..e94b93d
--- /dev/null
+++ b/docs/results/jetson-orin-nano-super/result-run-1.json
@@ -0,0 +1 @@
+{"prompt_ids":[1008,10484,318,15383,387],"generated_ids":[17374],"full_ids":[1008,10484,318,15383,387,17374],"layers":93,"layers_requested":93,"layers_completed":93,"expert_drops":0,"peak_rss_bytes":2760306688,"wall_seconds":948.5179,"seconds_per_token":948.5179,"expert_bytes_read":99703554048,"trunk_bytes_read":108811952128,"embedding_bytes_read":71680,"lm_head_bytes_read":2348810240,"ultra_low_memory":true,"generated_text":" Paris"}
diff --git a/docs/results/jetson-orin-nano-super/result-run-2.json b/docs/results/jetson-orin-nano-super/result-run-2.json
new file mode 100644
index 0000000..7474dd4
--- /dev/null
+++ b/docs/results/jetson-orin-nano-super/result-run-2.json
@@ -0,0 +1 @@
+{"prompt_ids":[1008,10484,318,15383,387],"generated_ids":[17374],"full_ids":[1008,10484,318,15383,387,17374],"layers":93,"layers_requested":93,"layers_completed":93,"expert_drops":0,"peak_rss_bytes":2759565312,"wall_seconds":949.8126,"seconds_per_token":949.8126,"expert_bytes_read":99703554048,"trunk_bytes_read":108811952128,"embedding_bytes_read":71680,"lm_head_bytes_read":2348810240,"ultra_low_memory":true,"generated_text":" Paris"}
diff --git a/docs/results/jetson-orin-nano-super/result-run-3.json b/docs/results/jetson-orin-nano-super/result-run-3.json
new file mode 100644
index 0000000..36e2703
--- /dev/null
+++ b/docs/results/jetson-orin-nano-super/result-run-3.json
@@ -0,0 +1 @@
+{"prompt_ids":[1008,10484,318,15383,387],"generated_ids":[17374],"full_ids":[1008,10484,318,15383,387,17374],"layers":93,"layers_requested":93,"layers_completed":93,"expert_drops":0,"peak_rss_bytes":2762563584,"wall_seconds":950.6945,"seconds_per_token":950.6945,"expert_bytes_read":99703554048,"trunk_bytes_read":108811952128,"embedding_bytes_read":71680,"lm_head_bytes_read":2348810240,"ultra_low_memory":true,"generated_text":" Paris"}
diff --git a/docs/results/jetson-orin-nano-super/result-run-4.json b/docs/results/jetson-orin-nano-super/result-run-4.json
new file mode 100644
index 0000000..dfa3c8e
--- /dev/null
+++ b/docs/results/jetson-orin-nano-super/result-run-4.json
@@ -0,0 +1 @@
+{"prompt_ids":[1008,10484,318,15383,387],"generated_ids":[17374],"full_ids":[1008,10484,318,15383,387,17374],"layers":93,"layers_requested":93,"layers_completed":93,"expert_drops":0,"peak_rss_bytes":2761093120,"wall_seconds":948.7180,"seconds_per_token":948.7180,"expert_bytes_read":99703554048,"trunk_bytes_read":108811952128,"embedding_bytes_read":71680,"lm_head_bytes_read":2348810240,"ultra_low_memory":true,"generated_text":" Paris"}
diff --git a/scripts/download-model.sh b/scripts/download-model.sh
index ab42324..b9f5172 100755
--- a/scripts/download-model.sh
+++ b/scripts/download-model.sh
@@ -185,6 +185,13 @@ else
hf cache verify "$REPO" --revision "$REVISION" --local-dir "$DEST" \
--fail-on-missing-files
echo " RESULT : checksum-verified snapshot at $REVISION"
+ # The proof runner must be able to prove which immutable Hub snapshot these bytes
+ # came from without re-hashing 1.56 TB immediately before every experiment. Write a
+ # marker only after the Hub checksum verification succeeds; size-only or explicitly
+ # skipped verification never creates it.
+ printf 'repo=%s\nrevision=%s\nverified_at=%s\n' \
+ "$REPO" "$REVISION" "$(date --iso-8601=seconds)" \
+ >"$DEST/.k3_hf_verified"
fi
echo
echo "next: scripts/pack-trunk.sh $DEST <trunk_dir>"
diff --git a/scripts/jetson-proof-of-life.sh b/scripts/jetson-proof-of-life.sh
new file mode 100755
index 0000000..0dff235
--- /dev/null
+++ b/scripts/jetson-proof-of-life.sh
@@ -0,0 +1,202 @@
+#!/usr/bin/env bash
+# One-token, full-checkpoint acceptance run for an 8 GB-class Jetson.
+set -euo pipefail
+
+MODEL="${1:?usage: jetson-proof-of-life.sh <model_dir> <trunk_dir> [output_dir]}"
+TRUNK="${2:?usage: jetson-proof-of-life.sh <model_dir> <trunk_dir> [output_dir]}"
+OUT="${3:-$PWD/k3-proof-$(date +%Y%m%d-%H%M%S)}"
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+EXPECT_SHARDS=96
+EXPECT_BYTES=1560936091448
+EXPECT_TRUNK_BYTES=108811952128
+EXPECT_TOKEN=17374
+MAX_RSS_BYTES=$((6 * 1024 * 1024 * 1024))
+VERIFY_MARKER="$MODEL/.k3_hf_verified"
+
+case "$(uname -m)" in
+ aarch64|arm64) ;;
+ *) echo "FAIL: this runner is for ARM64/Jetson, got $(uname -m)" >&2; exit 2 ;;
+esac
+[ -d "$MODEL" ] || { echo "FAIL: no model directory $MODEL" >&2; exit 2; }
+[ -f "$TRUNK/trunk.bin" ] && [ -f "$TRUNK/trunk.json" ] || {
+ echo "FAIL: $TRUNK is not a packed trunk directory" >&2; exit 2;
+}
+[ -x "$ROOT/bin/k3" ] || {
+ echo "FAIL: $ROOT/bin/k3 is not built; run make first" >&2; exit 2;
+}
+
+# Count and byte total catch partial transfers. The marker below is stronger: it is
+# created only after `hf cache verify` checks the official immutable Hub snapshot.
+N=$(find "$MODEL" -maxdepth 1 -name '*.safetensors' | wc -l)
+B=$(find "$MODEL" -maxdepth 1 -name '*.safetensors' -printf '%s\n' \
+ | awk '{s+=$1} END{printf "%.0f\n", s}')
+[ "$N" -eq "$EXPECT_SHARDS" ] || {
+ echo "FAIL: checkpoint has $N shards, expected $EXPECT_SHARDS" >&2; exit 2;
+}
+[ "$B" -eq "$EXPECT_BYTES" ] || {
+ echo "FAIL: checkpoint has $B safetensors bytes, expected $EXPECT_BYTES" >&2; exit 2;
+}
+[ -f "$VERIFY_MARKER" ] || {
+ echo "FAIL: no checksum-verification marker $VERIFY_MARKER" >&2
+ echo " run scripts/download-model.sh $MODEL first" >&2
+ exit 2
+}
+if find "$MODEL" -maxdepth 1 -name '*.safetensors' -newer "$VERIFY_MARKER" -print -quit \
+ | grep -q .; then
+ echo "FAIL: checkpoint shard changed after checksum verification" >&2
+ exit 2
+fi
+grep -qx 'repo=moonshotai/Kimi-K3' "$VERIFY_MARKER" || {
+ echo "FAIL: verification marker names a different repository" >&2; exit 2;
+}
+REVISION=$(sed -n 's/^revision=//p' "$VERIFY_MARKER")
+if ! printf '%s' "$REVISION" | grep -Eq '^[0-9a-fA-F]{40}$'; then
+ echo "FAIL: verification marker has no immutable 40-hex revision" >&2
+ exit 2
+fi
+
+read -r NL TB < <(python3 - "$TRUNK/trunk.json" <<'PY'
+import json, sys
+with open(sys.argv[1], encoding="utf-8") as f:
+ j = json.load(f)
+layers = j.get("layers") or []
+ids = [x.get("layer", i) for i, x in enumerate(layers)]
+if ids != list(range(93)):
+ raise SystemExit("trunk layer ids are not exactly 0..92")
+print(len(layers), sum(int(x["nbytes"]) for x in layers))
+PY
+)
+[ "$NL" -eq 93 ] || { echo "FAIL: packed trunk has $NL layers, expected 93" >&2; exit 2; }
+[ "$TB" -eq "$EXPECT_TRUNK_BYTES" ] || {
+ echo "FAIL: packed trunk metadata has $TB bytes, expected $EXPECT_TRUNK_BYTES" >&2
+ exit 2
+}
+[ "$(stat -c%s "$TRUNK/trunk.bin")" -eq "$EXPECT_TRUNK_BYTES" ] || {
+ echo "FAIL: trunk.bin size does not match its complete metadata" >&2; exit 2;
+}
+
+mkdir -p "$OUT"
+cp "$VERIFY_MARKER" "$OUT/checkpoint-verification.txt"
+if git -C "$ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
+ GIT_COMMIT=$(git -C "$ROOT" rev-parse HEAD)
+ git -C "$ROOT" status --porcelain=v1 >"$OUT/source-status.txt"
+ git -C "$ROOT" diff --binary >"$OUT/source.patch"
+ (cd "$ROOT" && git ls-files --cached --others --exclude-standard -z \
+ | sort -z | xargs -0 sha256sum) >"$OUT/source-files.sha256"
+else
+ GIT_COMMIT=unavailable-source-bundle
+ echo "source was deployed as a bundle without .git metadata" >"$OUT/source-status.txt"
+ : >"$OUT/source.patch"
+ (cd "$ROOT" && find . -type f \
+ -not -path './.git/*' -not -path './build*/*' -not -path './bin*/*' \
+ -not -path './cmake-build*/*' -print0 | sort -z | xargs -0 sha256sum) \
+ >"$OUT/source-files.sha256"
+fi
+{
+ echo "timestamp=$(date --iso-8601=seconds)"
+ echo "git_commit=$GIT_COMMIT"
+ echo "uname=$(uname -a)"
+ echo "machine=$(uname -m)"
+ echo "nproc=$(nproc)"
+ echo "model_dir=$MODEL"
+ echo "model_revision=$REVISION"
+ echo "trunk_dir=$TRUNK"
+ echo "model_mount=$(findmnt -T "$MODEL" -no SOURCE,FSTYPE,TARGET,OPTIONS)"
+ echo "trunk_mount=$(findmnt -T "$TRUNK" -no SOURCE,FSTYPE,TARGET,OPTIONS)"
+ echo "--- os-release ---"
+ cat /etc/os-release
+ if [ -r /etc/nv_tegra_release ]; then
+ echo "--- Jetson Linux ---"
+ cat /etc/nv_tegra_release
+ fi
+ echo "--- CPU ---"
+ lscpu
+ echo "--- memory ---"
+ cat /proc/meminfo
+ swapon --show --bytes 2>/dev/null || true
+ zramctl 2>/dev/null || true
+ echo "--- storage ---"
+ df -hT "$MODEL" "$TRUNK" /
+ lsblk -o NAME,TYPE,SIZE,FSTYPE,MOUNTPOINTS,MODEL,ROTA
+ echo "--- compiler ---"
+ cc --version
+ echo "--- binary ---"
+ file "$ROOT/bin/k3"
+ ldd "$ROOT/bin/k3" || true
+} >"$OUT/environment.txt"
+
+# Serial expert reads avoid seeking sixteen ways across a mechanical HDD. This changes
+# only I/O scheduling; Top-K routing, official weights and arithmetic are untouched.
+export K3_NOPREFETCH=1
+export OMP_NUM_THREADS="${OMP_NUM_THREADS:-$(nproc)}"
+export OMP_PROC_BIND="${OMP_PROC_BIND:-close}"
+export OMP_PLACES="${OMP_PLACES:-cores}"
+
+echo "starting full Kimi K3 proof-of-life"
+echo " model : $MODEL"
+echo " trunk : $TRUNK"
+echo " output: $OUT"
+echo " required first token: $EXPECT_TOKEN (' Paris'; exact gate)"
+
+K3_CMD=(
+ "$ROOT/bin/k3" "$MODEL"
+ --trunk "$TRUNK" --preset ultra
+ --tok "$MODEL" --prompt "The capital of France is"
+ --gen 1
+ --dump-logits "$OUT/logits.f32" --out "$OUT/result.json"
+)
+if [ -x /usr/bin/time ]; then
+ /usr/bin/time -v -o "$OUT/time.txt" "${K3_CMD[@]}" \
+ > >(tee "$OUT/run.log") 2> >(tee -a "$OUT/run.log" >&2)
+else
+ echo "/usr/bin/time unavailable; engine getrusage remains authoritative" >"$OUT/time.txt"
+ "${K3_CMD[@]}" > >(tee "$OUT/run.log") 2> >(tee -a "$OUT/run.log" >&2)
+fi
+
+python3 - "$OUT/result.json" "$MAX_RSS_BYTES" "$OUT/acceptance.json" <<'PY'
+import json, sys
+path, limit, acceptance_path = sys.argv[1], int(sys.argv[2]), sys.argv[3]
+with open(path, encoding="utf-8") as f:
+ r = json.load(f)
+hard_checks = {
+ "prompt tokenization": r.get("prompt_ids") == [1008, 10484, 318, 15383, 387],
+ "official 93-layer walk": r.get("layers_requested") == 93 and r.get("layers_completed") == 93,
+ "no expert drops": r.get("expert_drops") == 0,
+ "exactly one generated token": len(r.get("generated_ids") or []) == 1,
+ "exact token ID 17374": r.get("generated_ids") == [17374],
+ "exact decoded token ' Paris'": r.get("generated_text") == " Paris",
+ "ultra path active": r.get("ultra_low_memory") is True,
+ "peak RSS <= 6 GiB": 0 < r.get("peak_rss_bytes", 0) <= limit,
+ "trunk was read": r.get("trunk_bytes_read", 0) > 0,
+ "experts were read": r.get("expert_bytes_read", 0) > 0,
+ "embedding was streamed": r.get("embedding_bytes_read", 0) > 0,
+ "lm_head was streamed": r.get("lm_head_bytes_read", 0) > 0,
+}
+ids = r.get("generated_ids") or []
+text = r.get("generated_text") or ""
+reference_match = ids == [17374] and text == " Paris"
+semantic_reasonable = "paris" in text.casefold()
+report = {
+ "hard_checks": hard_checks,
+ "hard_pass": all(hard_checks.values()),
+ "reference_token_id": 17374,
+ "reference_decoded": " Paris",
+ "reference_match": reference_match,
+ "generated_ids": ids,
+ "generated_text": text,
+ "semantic_reasonable": semantic_reasonable,
+ "semantic_rule": "the single decoded token contains Paris, case-insensitive",
+}
+with open(acceptance_path, "w", encoding="utf-8") as f:
+ json.dump(report, f, ensure_ascii=False, indent=2)
+ f.write("\n")
+for name, ok in hard_checks.items():
+ print(("PASS" if ok else "FAIL") + ": " + name)
+print(("MATCH" if reference_match else "MISMATCH") + ": exact token 17374 (' Paris')")
+print("DIAGNOSTIC: semantic token " + repr(text) +
+ (" contains Paris" if semantic_reasonable else " does not contain Paris"))
+if not all(hard_checks.values()):
+ raise SystemExit(1)
+PY
+
+echo "PROOF-OF-LIFE PASSED: exact token 17374 (' Paris'), 93/93 layers, no drops."
diff --git a/src/cli/k3_run.c b/src/cli/k3_run.c
index db3c4c7..d31e4d7 100644
--- a/src/cli/k3_run.c
+++ b/src/cli/k3_run.c
@@ -123,6 +123,27 @@ static int real_cfg(K3Cfg *c, int *fa, int fa_max,
static int argmax_(const float *v, int n)
{ int b = 0; for (int i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; }
+static void json_string(FILE *f, const char *s)
+{
+ if (!s) { fputs("null", f); return; }
+ fputc('"', f);
+ for (const unsigned char *p = (const unsigned char *)s; *p; p++) {
+ switch (*p) {
+ case '"': fputs("\\\"", f); break;
+ case '\\': fputs("\\\\", f); break;
+ case '\b': fputs("\\b", f); break;
+ case '\f': fputs("\\f", f); break;
+ case '\n': fputs("\\n", f); break;
+ case '\r': fputs("\\r", f); break;
+ case '\t': fputs("\\t", f); break;
+ default:
+ if (*p < 0x20) fprintf(f, "\\u%04x", (unsigned)*p);
+ else fputc(*p, f);
+ }
+ }
+ fputc('"', f);
+}
+
/* ------------------------------------------------------- conversation state ----
* Everything the engine carries between tokens, on disk. The point is turn two of a
* conversation: without this, resuming re-reads the whole prompt through all 93 layers,
@@ -320,13 +341,15 @@ static void usage(FILE *f)
" --ids 1,2,3 raw token ids; the reproducible channel used by the tests\n"
"\n"
"memory:\n"
-" --preset NAME auto | laptop | desktop | workstation | server | max\n"
+" --preset NAME auto | ultra | laptop | desktop | workstation | server | max\n"
" auto sizes both budgets from this machine's free RAM,\n"
" trunk-first; also spelled --trunk-gb auto\n"
" --list-presets show each preset's split and expected speed\n"
" --trunk DIR packed trunk directory; enables streaming (see scripts/)\n"
" --trunk-gb X trunk ring / pinned-layer budget\n"
" --cache-gb X routed-expert cache budget\n"
+" --ultra-low-memory stream embedding rows and lm_head chunks, and reuse one\n"
+" recurrent-state slot during full recompute; needs --trunk\n"
"\n"
"generation:\n"
" --gen N tokens to generate (default 8)\n"
@@ -375,7 +398,12 @@ static void usage(FILE *f)
* Measured consequence: at a fixed 128 GB budget, trunk-first runs 1.69x faster than
* cache-first. So every preset fills the trunk before it feeds the cache.
* docs/PERFORMANCE.md carries the data and the noise floor that bounds it. */
-typedef struct { const char *name; double trunk_gb, cache_gb; const char *note; } K3Preset;
+typedef struct {
+ const char *name;
+ double trunk_gb, cache_gb;
+ int ultra;
+ const char *note;
+} K3Preset;
/* The trunk/cache figures are BUDGETS passed to the two allocators. The description
* quotes measured peak RSS for the whole process, which is the number that decides
@@ -383,11 +411,16 @@ typedef struct { const char *name; double trunk_gb, cache_gb; const char *note;
* cache and scratch, none of which appear in either budget. Measured on the reference
* machine in docs/PERFORMANCE.md; expect a little variation elsewhere. */
static const K3Preset K3_PRESETS[] = {
- { "laptop", 3.0, 1.0, "8.2 GB peak RSS. The floor. Runs, slowly." },
- { "desktop", 16.0, 10.0, "31.9 GB peak RSS." },
- { "workstation", 60.0, 30.0, "95.5 GB peak RSS; the expert cache starts to matter here." },
- { "server", 110.0, 13.0, "~128 GB peak RSS; 90 of 93 trunk layers pinned. Fastest." },
- { "max", 110.0,109.0, "~224 GB peak RSS; trunk pinned and a large expert cache." },
+ { "ultra", 2.5, 0.31, 1,
+ "~3 GB planned: streamed model tables, one state slot. Slow." },
+ { "laptop", 3.0, 1.0, 0, "8.2 GB peak RSS. The ordinary-path floor." },
+ { "desktop", 16.0, 10.0, 0, "31.9 GB peak RSS." },
+ { "workstation", 60.0, 30.0, 0,
+ "95.5 GB peak RSS; the expert cache starts to matter here." },
+ { "server", 110.0, 13.0, 0,
+ "~128 GB peak RSS; 90 of 93 trunk layers pinned. Fastest." },
+ { "max", 110.0,109.0, 0,
+ "~224 GB peak RSS; trunk pinned and a large expert cache." },
};
enum { K3_NPRESET = (int)(sizeof K3_PRESETS / sizeof K3_PRESETS[0]) };
@@ -402,7 +435,7 @@ static void k3_preset_list(FILE *f)
{
fprintf(f, "presets (trunk / expert-cache, in GB):\n");
for (int i = 0; i < K3_NPRESET; i++)
- fprintf(f, " %-12s %6.1f / %-6.1f %s\n", K3_PRESETS[i].name,
+ fprintf(f, " %-12s %6.2f / %-6.2f %s\n", K3_PRESETS[i].name,
K3_PRESETS[i].trunk_gb, K3_PRESETS[i].cache_gb, K3_PRESETS[i].note);
fprintf(f, " %-12s %6s / %-6s %s\n", "auto", "fit", "fit",
"sizes both from this machine's free RAM, trunk-first. Recommended.");
@@ -446,7 +479,10 @@ static double mem_available_bytes(void)
typedef struct {
K3LayerBind *lay;
K3ModelBind mb;
+ K3ModelStream ms;
int n_bound;
+ int layers_completed;
+ int ultra;
K3Trunk *trunk; /* non-NULL when the trunk is streamed rather than resident */
/* Incremental decode state. Only MLA layers need a KV cache, so the 24 of them are
* numbered densely rather than indexing all 93 and wasting 74% of the allocation. */
@@ -476,14 +512,27 @@ static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, i
const int P = c->kda_heads * c->kda_head_dim;
const size_t kper = (size_t)P * c->kda_head_dim + (size_t)3 * P * (c->conv_k - 1);
- for (int t = 0; t < T; t++)
- k3_embed_row(h + (size_t)t * E, w->mb.embed, w->mb.wdt, ids[t], E);
+ for (int t = 0; t < T; t++) {
+ if (w->ultra) {
+ if (k3_model_stream_embed_row(&w->ms, h + (size_t)t * E, ids[t]) != 0) {
+ fprintf(stderr, "embedding row load failed for token %d at position %d\n",
+ ids[t], t);
+ return -1;
+ }
+ } else {
+ k3_embed_row(h + (size_t)t * E, w->mb.embed, w->mb.wdt, ids[t], E);
+ }
+ }
memset(br, 0, (size_t)T * maxb * E * sizeof(float));
/* Incremental decode carries the KDA recurrent matrix and ShortConv history across
* steps, so it must NOT be cleared here; the full-recompute path rebuilds from
* scratch every step and must be. */
- if (!w->kvc) memset(kstate, 0, kper * (size_t)w->n_bound * sizeof(float));
+ if (!w->kvc) {
+ const size_t slots = w->ultra ? 1u : (size_t)w->n_bound;
+ memset(kstate, 0, kper * slots * sizeof(float));
+ }
+ w->layers_completed = 0;
int nb = 0;
for (int L = 0; L < w->n_bound; L++) {
/* Streaming: bring this layer in, and hint the next one so its read overlaps
@@ -505,20 +554,35 @@ static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, i
* the exact model keeps true routing. This is what makes a draft step cheap. */
w->lay[L].moe.cache_only = w->draft_mode;
}
+ /* Full recompute consumes a layer's KDA/ShortConv state only while that layer is
+ * executing over the complete sequence. Once the layer returns, no later layer
+ * can observe it, so ultra mode may clear and reuse one slot. Incremental decode
+ * still needs one persistent slot per layer and therefore never takes this
+ * path. */
+ float *layer_state = kstate + ((w->ultra && !w->kvc) ? 0 : kper * (size_t)L);
+ if (w->ultra && !w->kvc)
+ memset(layer_state, 0, kper * sizeof(float));
+ const long drops_before = k3_expert_drops;
if (w->kvc && w->mla_slot[L] >= 0) {
const size_t kvper = (size_t)w->kv_cap * c->n_heads * (c->qk_nope + c->v_head);
const size_t rpper = (size_t)w->kv_cap * c->qk_rope;
const int mi = w->mla_slot[L];
k3_decoder_layer_inc(h, br, &nb, &w->lay[L].lay, c, L, T,
- kstate + kper * (size_t)L, scratch,
+ layer_state, scratch,
w->kvc + kvper * (size_t)mi,
w->ropec + rpper * (size_t)mi,
w->cached, w->kv_cap);
} else {
k3_decoder_layer_inc(h, br, &nb, &w->lay[L].lay, c, L, T,
- kstate + kper * (size_t)L, scratch,
+ layer_state, scratch,
NULL, NULL, 0, 0);
}
+ if (k3_expert_drops != drops_before) {
+ fprintf(stderr, "routed expert load failed at layer %d; refusing partial "
+ "MoE output\n", L);
+ return -1;
+ }
+ w->layers_completed = L + 1;
}
/* The model-level aggregator, beyond the two per layer. Exactly one pair exists in
@@ -540,14 +604,22 @@ static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, i
if (arg_all) {
for (int t = 0; t < T; t++) {
k3_rmsnorm(nrm, h + (size_t)t * E, w->mb.norm, E, c->rms_eps);
- k3_mmw(logits_last, nrm, w->mb.lm_head, w->mb.wdt, E, c->vocab);
+ if (w->ultra) {
+ if (k3_model_stream_project(&w->ms, logits_last, nrm) != 0) return -1;
+ } else {
+ k3_mmw(logits_last, nrm, w->mb.lm_head, w->mb.wdt, E, c->vocab);
+ }
arg_all[t] = argmax_(logits_last, c->vocab);
}
/* logits_last now holds the FINAL position's vector, same as the plain path. */
return 0;
}
k3_rmsnorm(nrm, h + (size_t)(T - 1) * E, w->mb.norm, E, c->rms_eps);
- k3_mmw(logits_last, nrm, w->mb.lm_head, w->mb.wdt, E, c->vocab);
+ if (w->ultra) {
+ if (k3_model_stream_project(&w->ms, logits_last, nrm) != 0) return -1;
+ } else {
+ k3_mmw(logits_last, nrm, w->mb.lm_head, w->mb.wdt, E, c->vocab);
+ }
return 0;
}
@@ -586,7 +658,7 @@ int main(int argc, char **argv)
double draft_gb = 6.0;
const char *load_state = NULL, *save_state = NULL;
const char *preset_name = NULL;
- int incremental = 0;
+ int incremental = 0, ultra = 0;
for (int i = 2; i < argc; i++) {
if (!strcmp(argv[i], "--ids") && i + 1 < argc) ids_s = argv[++i];
else if (!strcmp(argv[i], "--prompt") && i + 1 < argc) prompt_text = argv[++i];
@@ -610,6 +682,7 @@ int main(int argc, char **argv)
else { trunk_gb = atof(v); budget_auto = 0; }
}
else if (!strcmp(argv[i], "--incremental")) incremental = 1;
+ else if (!strcmp(argv[i], "--ultra-low-memory")) ultra = 1;
else if (!strcmp(argv[i], "--dump-logits") && i + 1 < argc) logits_path = argv[++i];
else if (!strcmp(argv[i], "--dump-cache-trace") && i + 1 < argc) trace_dir = argv[++i];
else if (!strcmp(argv[i], "--preset") && i + 1 < argc && !strcmp(argv[i + 1], "auto")) {
@@ -618,6 +691,7 @@ int main(int argc, char **argv)
i++;
budget_auto = 1;
preset_name = "auto";
+ ultra = 0;
}
else if (!strcmp(argv[i], "--preset") && i + 1 < argc) {
const K3Preset *p = k3_preset_find(argv[++i]);
@@ -631,6 +705,7 @@ int main(int argc, char **argv)
trunk_gb = p->trunk_gb;
cache_gb = p->cache_gb;
preset_name = p->name;
+ ultra = p->ultra;
}
else if (!strcmp(argv[i], "--list-presets")) { k3_preset_list(stdout); return 0; }
else if (!strcmp(argv[i], "--version")) {
@@ -640,6 +715,23 @@ int main(int argc, char **argv)
else if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { usage(stdout); return 0; }
else { fprintf(stderr, "unknown option %s\n\n", argv[i]); usage(stderr); return 2; }
}
+
+ if (ultra && !trunk_dir) {
+ fprintf(stderr, "--ultra-low-memory needs --trunk; resident trunk cannot fit its "
+ "memory contract\n");
+ return 2;
+ }
+ if (ultra && budget_auto) {
+ fprintf(stderr, "--ultra-low-memory uses explicit bounded budgets; use "
+ "--preset ultra or pass --trunk-gb/--cache-gb\n");
+ return 2;
+ }
+ if (ultra && (spec_n > 0 || draft_dir)) {
+ fprintf(stderr,
+ "--ultra-low-memory does not yet support --spec or --draft-trunk; "
+ "use deterministic serial decode\n");
+ return 2;
+ }
{
int nsrc = (ids_s != NULL) + (prompt_text != NULL) + (prompt_file != NULL);
if (nsrc == 0) {
@@ -831,7 +923,7 @@ int main(int argc, char **argv)
/* Echo the preset so a captured log is self-describing: a timing figure is
* meaningless without the budget that produced it. */
if (preset_name)
- printf(" preset : %s (trunk %.1f GB / expert cache %.1f GB)\n",
+ printf(" preset : %s (trunk %.2f GB / expert cache %.2f GB)\n",
preset_name, trunk_gb, cache_gb);
printf("\n");
@@ -871,14 +963,16 @@ int main(int argc, char **argv)
{
const int64_t E64 = c.hidden;
const double w_trunk = trunk_dir ? trunk_gb * 1e9 : (double)total;
- const double w_model = 2.0 * (double)c.vocab * E64 * 2 /* embed + lm_head, bf16 */
- + 3.0 * E64 * 4; /* norms, aggregator */
+ const double w_model = ultra
+ ? (double)K3_MODEL_STREAM_CHUNK + 2.0 * K3_ST_ALIGN + 3.0 * E64 * 4
+ : 2.0 * (double)c.vocab * E64 * 2 + 3.0 * E64 * 4;
const double w_cache = cache_gb * 1e9;
const int Tm = np + gen + 1;
const int mb = c.n_layers / c.attn_res_block + 2;
const int Pp = c.kda_heads * c.kda_head_dim;
+ const int state_layers = (ultra && !incremental) ? 1 : NL;
const double w_state = (double)((size_t)Pp * c.kda_head_dim
- + (size_t)3 * Pp * (c.conv_k - 1)) * NL * 4;
+ + (size_t)3 * Pp * (c.conv_k - 1)) * state_layers * 4;
const double w_buf = ((double)Tm * E64 + (double)Tm * mb * E64
+ (double)k3_layer_scratch(&c, Tm) + (double)c.vocab) * 4;
/* The KV cache MUST be in this total: it is the only term that grows with
@@ -901,10 +995,11 @@ int main(int argc, char **argv)
human(w_cache, b3, sizeof b3); human(w_state, b4, sizeof b4);
human(w_buf, b5, sizeof b5); human(need_b, b6, sizeof b6);
printf("\nmemory plan\n");
- printf(" trunk %-10s %s\n embed + lm_head %s\n expert cache %s\n"
+ printf(" trunk %-10s %s\n embed + lm_head %s %s\n expert cache %s\n"
" recurrent state %s\n buffers %s\n KV cache %s\n"
" TOTAL %s\n",
- trunk_dir ? "(STREAMED)" : "(resident)", b1, b2, b3, b4, b5, b7, b6);
+ trunk_dir ? "(STREAMED)" : "(resident)", b1, b2,
+ ultra ? "(STREAMED)" : "(resident)", b3, b4, b5, b7, b6);
if (have > 0.0) {
human(have, b1, sizeof b1);
printf(" available %s\n", b1);
@@ -958,9 +1053,15 @@ int main(int argc, char **argv)
}
t0 = now_s();
- if (k3_bind_model(&st, &c, 1, &w.mb) != 0) return 1;
+ w.ultra = ultra;
+ if (k3_bind_model_parts(&st, &c, !ultra, !ultra, &w.mb) != 0) return 1;
+ if (ultra && k3_model_stream_init(&w.ms, &st, &c) != 0) return 1;
human((double)w.mb.nbytes, b1, sizeof b1);
- printf("embedding, final norm and lm_head: %s in %.1f s\n\n", b1, now_s() - t0);
+ if (ultra)
+ printf("final norms: %s resident; embedding and lm_head streamed in %.1f s\n\n",
+ b1, now_s() - t0);
+ else
+ printf("embedding, final norm and lm_head: %s in %.1f s\n\n", b1, now_s() - t0);
K3Cache cache;
if (k3_cache_init(&cache, &st, &c, (int64_t)(cache_gb * 1e9)) != 0) return 1;
@@ -1014,7 +1115,8 @@ int main(int argc, char **argv)
float *h = (float *)malloc((size_t)Tmax * E * sizeof(float));
float *br = (float *)malloc((size_t)Tmax * maxb * E * sizeof(float));
- float *ks = (float *)malloc(kper * (size_t)NL * sizeof(float));
+ const int state_layers = (ultra && !incremental) ? 1 : NL;
+ float *ks = (float *)malloc(kper * (size_t)state_layers * sizeof(float));
size_t sc_need = k3_layer_scratch(&c, Tmax);
{ /* the cached MLA path sizes its score buffer by cache capacity, not by T */
const size_t ic = k3_mla_scratch_cached(&c, Tmax, Tmax, 1);
@@ -1023,8 +1125,12 @@ int main(int argc, char **argv)
float *sc = (float *)malloc(sc_need * sizeof(float));
float *lg = (float *)malloc((size_t)c.vocab * sizeof(float));
if (!h || !br || !ks || !sc || !lg) { fprintf(stderr, "buffer allocation failed\n"); return 1; }
- human((double)(kper * NL) * 4, b1, sizeof b1);
- printf("recurrent state for %d layers: %s\n\n", NL, b1);
+ human((double)(kper * state_layers) * 4, b1, sizeof b1);
+ if (state_layers == 1 && NL > 1)
+ printf("recurrent state: one %s slot, cleared and reused across %d layers\n\n",
+ b1, NL);
+ else
+ printf("recurrent state for %d layers: %s\n\n", state_layers, b1);
/* ---- generate ----
* Heap and sized from the ACTUAL request, not from the ceiling. These were
@@ -1183,13 +1289,14 @@ int main(int argc, char **argv)
printf("%-6s %-10s %-12s %-10s %-10s %s\n",
"STEP", "TOKEN", "SECONDS", "CACHE HIT", "READ GB", "TOK/S");
printf("--------------------------------------------------------------------\n");
+ k3_expert_drops = 0;
double t_total = 0.0;
/* Per-step cache statistics are reset each iteration so the columns below describe
* that step alone. The end-of-run summary needs whole-run totals, so accumulate the
* expert side here; the trunk side is already cumulative. Comparing a cumulative
* figure against a single step would misstate the I/O share. */
double expert_s_total = 0.0, expert_gb_total = 0.0;
- uint64_t expert_reqs_total = 0, expert_evict_total = 0;
+ uint64_t expert_reqs_total = 0, expert_evict_total = 0, expert_bytes_total = 0;
for (int g = 0; nout < gen; g++) {
k3_cache_reset_stats(&cache);
const double ts = now_s();
@@ -1339,6 +1446,7 @@ int main(int argc, char **argv)
/* Roll the per-step figures up before the next reset wipes them. */
expert_s_total += cache.load_seconds;
expert_gb_total += (double)cache.bytes_read / 1e9;
+ expert_bytes_total += cache.bytes_read;
expert_reqs_total += cache.hits + cache.misses;
expert_evict_total += cache.evictions;
for (int i = 0; i < emitn && nout < gen && T < Tmax; i++) {
@@ -1383,19 +1491,23 @@ int main(int argc, char **argv)
/* Decoded text, when a tokenizer is loaded. Printed as a distinct block rather than
* streamed per token: a partially-decoded multi-byte sequence is not valid UTF-8, so
* streaming would emit mojibake at every token boundary that splits a codepoint. */
+ char *generated_text = NULL;
if (have_tok && nout > 0) {
- char *txt = (char *)malloc((size_t)nout * 8 + 1);
- if (txt) {
- int m = tok_decode(&tok, outtok, nout, txt, nout * 8);
- txt[m] = 0;
- printf("\n--- generated text ---\n%s\n----------------------\n\n", txt);
- free(txt);
+ generated_text = (char *)malloc((size_t)nout * 8 + 1);
+ if (generated_text) {
+ int m = tok_decode(&tok, outtok, nout, generated_text, nout * 8);
+ generated_text[m] = 0;
+ printf("\n--- generated text ---\n%s\n----------------------\n\n",
+ generated_text);
}
}
+ const double peak_b = peak_rss_bytes();
{
char rb[32];
- human(peak_rss_bytes(), rb, sizeof rb);
- printf("PEAK RSS for the whole run: %s <- quote this, not the plan\n\n", rb);
+ human(peak_b, rb, sizeof rb);
+ printf("PEAK RSS for the whole run: %s <- quote this, not the plan\n", rb);
+ printf("layers completed: %d/%d; routed expert drops: %ld\n\n",
+ w.layers_completed, NL, k3_expert_drops);
}
k3_cache_report(&cache, "final step");
@@ -1407,7 +1519,21 @@ int main(int argc, char **argv)
for (int i = 0; i < nout; i++) fprintf(f, "%s%d", i ? "," : "", outtok[i]);
fprintf(f, "],\"full_ids\":[");
for (int i = 0; i < T; i++) fprintf(f, "%s%d", i ? "," : "", seq[i]);
- fprintf(f, "],\"layers\":%d,\"seconds_per_token\":%.4f}\n", NL, t_total / nout);
+ fprintf(f,
+ "],\"layers\":%d,\"layers_requested\":%d,\"layers_completed\":%d,"
+ "\"expert_drops\":%ld,\"peak_rss_bytes\":%.0f,\"wall_seconds\":%.4f,"
+ "\"seconds_per_token\":%.4f,\"expert_bytes_read\":%llu,"
+ "\"trunk_bytes_read\":%llu,\"embedding_bytes_read\":%llu,"
+ "\"lm_head_bytes_read\":%llu,\"ultra_low_memory\":%s,"
+ "\"generated_text\":",
+ NL, NL, w.layers_completed, k3_expert_drops, peak_b, t_total,
+ t_total / nout, (unsigned long long)expert_bytes_total,
+ (unsigned long long)(w.trunk ? w.trunk->bytes_read : 0),
+ (unsigned long long)w.ms.embed_bytes_read,
+ (unsigned long long)w.ms.lm_head_bytes_read,
+ w.ultra ? "true" : "false");
+ json_string(f, generated_text);
+ fputs("}\n", f);
fclose(f);
printf("\nwrote %s\n", outp);
}
@@ -1429,13 +1555,15 @@ int main(int argc, char **argv)
* separates them. */
{
const double trunk_s = w.trunk ? w.trunk->load_seconds : 0.0;
+ const double model_s = w.ultra ? w.ms.read_seconds : 0.0;
/* Both terms MUST be whole-run totals over the same window. Mixing a cumulative
* trunk time with a last-step expert time and dividing by the whole run
* understates the expert share by roughly the token count. */
- const double io_s = trunk_s + expert_s_total;
+ const double io_s = trunk_s + expert_s_total + model_s;
const double share = t_total > 0 ? 100.0 * io_s / t_total : 0.0;
- printf("I/O share of wall clock: %.1f%% (trunk %.1f s + experts %.1f s of %.1f s)\n",
- share, trunk_s, expert_s_total, t_total);
+ printf("I/O share of wall clock: %.1f%% (trunk %.1f s + experts %.1f s + "
+ "model tables %.1f s of %.1f s)\n",
+ share, trunk_s, expert_s_total, model_s, t_total);
printf(" both figures are WHOLE-RUN totals over %d steps\n", nout);
/* Above 100% is not a bug in the arithmetic: with more than one trunk ring slot
* the reader thread does device work while the main thread computes, so the two
@@ -1468,9 +1596,10 @@ int main(int argc, char **argv)
k3_cache_free(&cache);
for (int L = 0; L < w.n_bound; L++) k3_bind_free(&w.lay[L]);
free(w.lay);
+ k3_model_stream_free(&w.ms);
k3_bind_model_free(&w.mb);
k3_st_close(&st);
- free(h); free(br); free(ks); free(sc); free(lg);
+ free(h); free(br); free(ks); free(sc); free(lg); free(generated_text);
/* A dropped expert means some token was computed with part of its routed sum
* missing. The run still produced token ids and they still look plausible, which is
diff --git a/src/model/k3_bind.c b/src/model/k3_bind.c
index 91391f6..d8e3518 100644
--- a/src/model/k3_bind.c
+++ b/src/model/k3_bind.c
@@ -5,6 +5,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <time.h>
#include "k3_bind.h"
@@ -447,10 +448,12 @@ int k3_bind_layer_mem(const K3Cfg *c, int L, K3LayerBind *b,
/* embed is gathered a row at a time rather than multiplied, so k3_run widens the row it
* needs. lm_head goes through k3_mmw. Both are 2.35 GB as bf16 and 4.70 GB widened,
* which is why neither is widened here. */
-static void plan_model(Plan *p, const K3Cfg *c, int want_lm_head, K3ModelBind *m)
+static void plan_model(Plan *p, const K3Cfg *c, int want_embed, int want_lm_head,
+ K3ModelBind *m)
{
const int64_t H = c->hidden;
- reqn(p, &m->embed, (int64_t)c->vocab * H, PRE "embed_tokens.weight");
+ if (want_embed)
+ reqn(p, &m->embed, (int64_t)c->vocab * H, PRE "embed_tokens.weight");
reqw(p, &m->norm, H, -1, PRE "norm.weight");
reqw(p, &m->out_res_norm, H, -1, PRE "output_attn_res_norm.weight");
reqw(p, &m->out_res_proj, H, -1, PRE "output_attn_res_proj.weight");
@@ -458,12 +461,13 @@ static void plan_model(Plan *p, const K3Cfg *c, int want_lm_head, K3ModelBind *m
reqn(p, &m->lm_head, (int64_t)c->vocab * H, "language_model.lm_head.weight");
}
-int k3_bind_model(const K3St *s, const K3Cfg *c, int want_lm_head, K3ModelBind *m)
+int k3_bind_model_parts(const K3St *s, const K3Cfg *c,
+ int want_embed, int want_lm_head, K3ModelBind *m)
{
memset(m, 0, sizeof *m);
Plan p; memset(&p, 0, sizeof p);
p.narrow_ok = 1;
- plan_model(&p, c, want_lm_head, m);
+ plan_model(&p, c, want_embed, want_lm_head, m);
int64_t need = plan_resolve(&p, s);
if (need < 0) return -1;
@@ -473,7 +477,7 @@ int k3_bind_model(const K3St *s, const K3Cfg *c, int want_lm_head, K3ModelBind *
memset(m, 0, sizeof *m);
memset(&p, 0, sizeof p);
p.narrow_ok = 0;
- plan_model(&p, c, want_lm_head, m);
+ plan_model(&p, c, want_embed, want_lm_head, m);
need = plan_resolve(&p, s);
if (need < 0) return -1;
}
@@ -491,8 +495,141 @@ int k3_bind_model(const K3St *s, const K3Cfg *c, int want_lm_head, K3ModelBind *
return 0;
}
+int k3_bind_model(const K3St *s, const K3Cfg *c, int want_lm_head, K3ModelBind *m)
+{
+ return k3_bind_model_parts(s, c, 1, want_lm_head, m);
+}
+
void k3_bind_model_free(K3ModelBind *m)
{
free(m->blob);
memset(m, 0, sizeof *m);
}
+
+/* ------------------------------------------------------ streamed model matrices */
+
+static int model_matrix(const K3St *s, const char *name, int rows, int cols,
+ const K3Tensor **out, int *wdt)
+{
+ const K3Tensor *t = k3_st_find(s, name);
+ if (!t) {
+ fprintf(stderr, "k3_model_stream: missing tensor %s\n", name);
+ return -1;
+ }
+ if (t->ndim != 2 || t->shape[0] != rows || t->shape[1] != cols) {
+ fprintf(stderr,
+ "k3_model_stream: %s has shape [%lld,%lld] rank %d; expected [%d,%d]\n",
+ name, (long long)(t->ndim > 0 ? t->shape[0] : -1),
+ (long long)(t->ndim > 1 ? t->shape[1] : -1), t->ndim, rows, cols);
+ return -1;
+ }
+ if (t->dtype == K3_DT_BF16) *wdt = K3_WBF16;
+ else if (t->dtype == K3_DT_F32) *wdt = K3_WF32;
+ else {
+ fprintf(stderr, "k3_model_stream: %s must be BF16 or F32, got dtype %d\n",
+ name, (int)t->dtype);
+ return -1;
+ }
+ *out = t;
+ return 0;
+}
+
+static double model_now_s(void)
+{
+ struct timespec t;
+ clock_gettime(CLOCK_MONOTONIC, &t);
+ return t.tv_sec + t.tv_nsec * 1e-9;
+}
+
+int k3_model_stream_init(K3ModelStream *m, const K3St *s, const K3Cfg *c)
+{
+ memset(m, 0, sizeof *m);
+ m->st = s;
+ m->hidden = c->hidden;
+ m->vocab = c->vocab;
+ if (model_matrix(s, PRE "embed_tokens.weight", c->vocab, c->hidden,
+ &m->embed, &m->embed_wdt) != 0 ||
+ model_matrix(s, "language_model.lm_head.weight", c->vocab, c->hidden,
+ &m->lm_head, &m->lm_head_wdt) != 0)
+ return -1;
+
+ m->bufcap = K3_MODEL_STREAM_CHUNK + 2u * K3_ST_ALIGN;
+ if (posix_memalign((void **)&m->buf, K3_ST_ALIGN, m->bufcap) != 0) {
+ fprintf(stderr, "k3_model_stream: cannot allocate %zu-byte aligned I/O buffer\n",
+ m->bufcap);
+ memset(m, 0, sizeof *m);
+ return -1;
+ }
+ return 0;
+}
+
+void k3_model_stream_free(K3ModelStream *m)
+{
+ free(m->buf);
+ memset(m, 0, sizeof *m);
+}
+
+static int model_read_rows(K3ModelStream *m, const K3Tensor *t, int first, int n,
+ const void **rows, uint64_t *counter)
+{
+ const int esz = k3_st_elemsize(t->dtype);
+ const int64_t row_bytes = (int64_t)m->hidden * esz;
+ const int64_t nbytes = (int64_t)n * row_bytes;
+ int64_t payload = 0;
+ if (first < 0 || n <= 0 || first > m->vocab - n ||
+ nbytes > (int64_t)K3_MODEL_STREAM_CHUNK)
+ return -1;
+ const double t0 = model_now_s();
+ const int64_t got = k3_st_read_aligned(m->st, t->shard,
+ t->off + (int64_t)first * row_bytes, nbytes,
+ m->buf, (int64_t)m->bufcap, &payload);
+ m->read_seconds += model_now_s() - t0;
+ if (got != nbytes) {
+ fprintf(stderr,
+ "k3_model_stream: short read of %s rows %d..%d (%lld of %lld bytes)\n",
+ t->name, first, first + n, (long long)got, (long long)nbytes);
+ return -1;
+ }
+ unsigned char *src = m->buf + payload;
+ /* Safetensors guarantees byte ranges, not C type alignment. A BF16 tensor may
+ * legally follow an odd-sized U8 tensor, making its payload address odd even though
+ * the O_DIRECT destination itself is page aligned. Typed uint16_t/float loads from
+ * that address are undefined on strict-alignment targets. Compact only in that rare
+ * case; memmove is overlap-safe and the existing buffer has enough room. */
+ if ((uintptr_t)src % (uintptr_t)esz != 0) {
+ memmove(m->buf, src, (size_t)nbytes);
+ src = m->buf;
+ }
+ *rows = src;
+ *counter += (uint64_t)got;
+ return 0;
+}
+
+int k3_model_stream_embed_row(K3ModelStream *m, float *dst, int64_t row)
+{
+ const void *src = NULL;
+ if (row < 0 || row >= m->vocab ||
+ model_read_rows(m, m->embed, (int)row, 1, &src, &m->embed_bytes_read) != 0)
+ return -1;
+ k3_embed_row(dst, src, m->embed_wdt, 0, m->hidden);
+ return 0;
+}
+
+int k3_model_stream_project(K3ModelStream *m, float *logits, const float *x)
+{
+ const int esz = k3_st_elemsize(m->lm_head->dtype);
+ const int64_t row_bytes = (int64_t)m->hidden * esz;
+ const int rows_per_chunk = (int)(K3_MODEL_STREAM_CHUNK / row_bytes);
+ if (rows_per_chunk < 1) return -1;
+
+ for (int first = 0; first < m->vocab; first += rows_per_chunk) {
+ const int n = (m->vocab - first < rows_per_chunk)
+ ? m->vocab - first : rows_per_chunk;
+ const void *rows = NULL;
+ if (model_read_rows(m, m->lm_head, first, n, &rows,
+ &m->lm_head_bytes_read) != 0)
+ return -1;
+ k3_mmw(logits + first, x, rows, m->lm_head_wdt, m->hidden, n);
+ }
+ return 0;
+}
diff --git a/src/model/k3_bind.h b/src/model/k3_bind.h
index 450c61a..c77a3c8 100644
--- a/src/model/k3_bind.h
+++ b/src/model/k3_bind.h
@@ -81,8 +81,41 @@ typedef struct {
} K3ModelBind;
int k3_bind_model(const K3St *s, const K3Cfg *c, int want_lm_head, K3ModelBind *m);
+/* Selective form used by the ultra-low-memory path. The ordinary entry point above
+ * remains the compatibility wrapper that always binds the embedding table. */
+int k3_bind_model_parts(const K3St *s, const K3Cfg *c,
+ int want_embed, int want_lm_head, K3ModelBind *m);
void k3_bind_model_free(K3ModelBind *m);
+/* ---- streamed model-level matrices ------------------------------------------------
+ *
+ * embed_tokens and lm_head are 2.35 GB each in the released BF16 checkpoint. A short
+ * prompt needs only a few embedding rows, and greedy projection can walk lm_head in
+ * bounded row chunks. Each chunk still goes through k3_mmw, so the per-row arithmetic
+ * and reduction tree are identical to the resident path; only ownership and I/O
+ * lifetime change.
+ *
+ * One page-aligned buffer is shared by both operations. Returned values never point
+ * into it: embedding rows are widened into caller memory, and logits are completed
+ * before the next chunk overwrites the buffer. */
+typedef struct {
+ const K3St *st;
+ const K3Tensor *embed, *lm_head;
+ unsigned char *buf;
+ size_t bufcap;
+ int hidden, vocab;
+ int embed_wdt, lm_head_wdt;
+ uint64_t embed_bytes_read, lm_head_bytes_read;
+ double read_seconds;
+} K3ModelStream;
+
+#define K3_MODEL_STREAM_CHUNK (4u << 20)
+
+int k3_model_stream_init(K3ModelStream *m, const K3St *s, const K3Cfg *c);
+void k3_model_stream_free(K3ModelStream *m);
+int k3_model_stream_embed_row(K3ModelStream *m, float *dst, int64_t row);
+int k3_model_stream_project(K3ModelStream *m, float *logits, const float *x);
+
/* BYTES one layer needs, without loading it. For sizing and for reporting. */
int64_t k3_bind_layer_bytes(const K3St *s, const K3Cfg *c, int layer);
diff --git a/tests/fixtures/st/model-00001-of-00002.safetensors b/tests/fixtures/st/model-00001-of-00002.safetensors
index e808e71..fe38a78 100644
Binary files a/tests/fixtures/st/model-00001-of-00002.safetensors and b/tests/fixtures/st/model-00001-of-00002.safetensors differ
diff --git a/tests/unit/k3_model.c b/tests/unit/k3_model.c
index 64f7caa..06080c9 100644
--- a/tests/unit/k3_model.c
+++ b/tests/unit/k3_model.c
@@ -183,7 +183,7 @@ static int model_bind(Model *m, Store *s, const K3Cfg *c)
}
static void forward(Model *m, const K3Cfg *c, const int *ids, int T, float *logits,
- float *scratch, float *h, float *br, float *kstate)
+ float *scratch, float *h, float *br, float *kstate, int reuse_state)
{
const int E = c->hidden;
const int maxb = c->n_layers / c->attn_res_block + 2;
@@ -196,11 +196,14 @@ static void forward(Model *m, const K3Cfg *c, const int *ids, int T, float *logi
(size_t)E * sizeof(float));
memset(br, 0, (size_t)T * (size_t)maxb * (size_t)E * sizeof(float));
- memset(kstate, 0, kper * (size_t)c->n_layers * sizeof(float));
+ if (!reuse_state) memset(kstate, 0, kper * (size_t)c->n_layers * sizeof(float));
int nb = 0;
- for (int L = 0; L < c->n_layers; L++)
+ for (int L = 0; L < c->n_layers; L++) {
+ float *state = kstate + (reuse_state ? 0 : kper * (size_t)L);
+ if (reuse_state) memset(state, 0, kper * sizeof(float));
k3_decoder_layer(h, br, &nb, &m->lay[L], c, L, T,
- kstate + kper * (size_t)L, scratch);
+ state, scratch);
+ }
/* The MODEL-LEVEL aggregator. Beyond the 2 per layer there is one more:
* output_attn_res_{norm,proj}. The tensor census counts exactly 1 of these.
@@ -309,7 +312,7 @@ int main(int argc, char **argv)
float *ks = (float *)malloc(kper * (size_t)c.n_layers * sizeof(float));
float *lg = (float *)malloc((size_t)T * (size_t)c.vocab * sizeof(float));
- forward(m, &c, full, T, lg, scratch, h, br, ks);
+ forward(m, &c, full, T, lg, scratch, h, br, ks, 0);
int tf_all = 0, tf_gen = 0, tf_gen_ok = 0;
for (int i = 0; i < T; i++) {
const int got = argmax_(lg + (size_t)i * (size_t)c.vocab, c.vocab);
@@ -320,11 +323,27 @@ int main(int argc, char **argv)
printf("GATE 1 teacher forcing : %d/%d positions match tf_pred\n", tf_all, T);
printf(" generated span : %d/%d <- must be exact\n", tf_gen_ok, tf_gen);
+ /* Full recompute never returns to a layer after its whole sequence has finished, so
+ * its KDA matrix and ShortConv history have no lifetime beyond that layer. The CLI's
+ * ultra path therefore reuses one slot instead of retaining n_layers copies. Demand
+ * bit-identical logits against the old layout; token-only equality would hide a
+ * near-tie or a stale-state error. */
+ float *ks_reuse = (float *)malloc(kper * sizeof(float));
+ float *lg_reuse = (float *)malloc((size_t)T * (size_t)c.vocab * sizeof(float));
+ int reuse_ok = 0;
+ if (ks_reuse && lg_reuse) {
+ forward(m, &c, full, T, lg_reuse, scratch, h, br, ks_reuse, 1);
+ reuse_ok = memcmp(lg, lg_reuse,
+ (size_t)T * (size_t)c.vocab * sizeof(float)) == 0;
+ }
+ printf("GATE 1b state reuse : %s <- all logits bit-identical\n",
+ reuse_ok ? "PASS" : "FAIL");
+
int *gen = (int *)malloc((size_t)T * sizeof(int));
memcpy(gen, full, (size_t)np * sizeof(int));
int cur = np, gok = 0;
while (cur < T) {
- forward(m, &c, gen, cur, lg, scratch, h, br, ks);
+ forward(m, &c, gen, cur, lg, scratch, h, br, ks, 0);
gen[cur] = argmax_(lg + (size_t)(cur - 1) * (size_t)c.vocab, c.vocab);
if (gen[cur] == full[cur]) gok++;
cur++;
@@ -414,7 +433,7 @@ int main(int argc, char **argv)
free(kvc); free(rpc); free(sc_i); free(h_i); free(br_i); free(ks_i); free(lg_i); free(gi);
}
- const int pass = (tf_gen_ok == tf_gen) && (gok == T - np);
+ const int pass = (tf_gen_ok == tf_gen) && reuse_ok && (gok == T - np);
printf("\nVERDICT: %s\n", pass ? "ENGINE MATCHES THE REFERENCE EXACTLY"
: "MISMATCH, see the counts above");
if (!pass) {
@@ -426,6 +445,7 @@ int main(int argc, char **argv)
}
free(full); free(gen); free(scratch); free(h); free(br); free(ks); free(lg);
+ free(ks_reuse); free(lg_reuse);
for (int L = 0; L < c.n_layers; L++) { free(m->w1[L]); free(m->w3[L]); free(m->w2[L]); }
free(m);
diff --git a/tests/unit/test_model_stream.c b/tests/unit/test_model_stream.c
new file mode 100644
index 0000000..33d7b13
--- /dev/null
+++ b/tests/unit/test_model_stream.c
@@ -0,0 +1,112 @@
+/* test_model_stream.c - streamed model-level matrices must equal resident BF16 math.
+ *
+ * The full tables are 4.70 GB on Kimi K3, so the production path reads embedding rows
+ * and lm_head chunks on demand. This fixture is intentionally tiny, but it crosses the
+ * same safetensors/aligned-read boundary and demands bit-identical float32 outputs. */
+#define _POSIX_C_SOURCE 200809L
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "k3.h"
+#include "k3_bind.h"
+#include "k3_st.h"
+
+int main(int argc, char **argv)
+{
+ if (argc != 2) {
+ fprintf(stderr, "usage: test_model_stream <safetensors_fixture_dir>\n");
+ return 2;
+ }
+
+ K3St st;
+ if (k3_st_open(&st, argv[1]) != 0) return 1;
+
+ K3Cfg c;
+ memset(&c, 0, sizeof c);
+ c.hidden = 7;
+ c.vocab = 11;
+
+ K3ModelStream ms;
+ if (k3_model_stream_init(&ms, &st, &c) != 0) {
+ k3_st_close(&st);
+ return 1;
+ }
+
+ const K3Tensor *et = k3_st_find(&st, "language_model.model.embed_tokens.weight");
+ const K3Tensor *ht = k3_st_find(&st, "language_model.lm_head.weight");
+ uint16_t *embed = (uint16_t *)malloc((size_t)et->nbytes);
+ uint16_t *head = (uint16_t *)malloc((size_t)ht->nbytes);
+ if (!embed || !head || k3_st_read(&st, et, embed) != et->nbytes ||
+ k3_st_read(&st, ht, head) != ht->nbytes) {
+ fprintf(stderr, "could not read resident comparison matrices\n");
+ free(embed); free(head); k3_model_stream_free(&ms); k3_st_close(&st);
+ return 1;
+ }
+
+ int bad = 0;
+ float got_row[7], ref_row[7];
+ const int row = 6;
+ if (k3_model_stream_embed_row(&ms, got_row, row) != 0) bad++;
+ k3_embed_row(ref_row, embed, K3_WBF16, row, c.hidden);
+ if (memcmp(got_row, ref_row, sizeof got_row) != 0) {
+ fprintf(stderr, "streamed embedding row differs from resident gather\n");
+ bad++;
+ }
+
+ const float x[7] = { 0.125f, -0.25f, 0.5f, 1.0f, -1.5f, 0.0625f, 0.75f };
+ float got_logits[11], ref_logits[11];
+ if (k3_model_stream_project(&ms, got_logits, x) != 0) bad++;
+ k3_matmul_bf16(ref_logits, x, head, c.hidden, c.vocab);
+ if (memcmp(got_logits, ref_logits, sizeof got_logits) != 0) {
+ fprintf(stderr, "streamed lm_head logits differ from resident BF16 matmul\n");
+ bad++;
+ }
+
+ if (ms.embed_bytes_read != (uint64_t)c.hidden * 2 ||
+ ms.lm_head_bytes_read != (uint64_t)c.hidden * c.vocab * 2) {
+ fprintf(stderr, "wrong I/O accounting: embed %llu head %llu\n",
+ (unsigned long long)ms.embed_bytes_read,
+ (unsigned long long)ms.lm_head_bytes_read);
+ bad++;
+ }
+ if (k3_model_stream_embed_row(&ms, got_row, -1) == 0 ||
+ k3_model_stream_embed_row(&ms, got_row, c.vocab) == 0) {
+ fprintf(stderr, "out-of-range embedding row was accepted\n");
+ bad++;
+ }
+
+ /* A corrupt index offset must become a hard short-read failure. The copy leaves the
+ * opened index and fixture untouched while exercising the same aligned pread path a
+ * truncated checkpoint would take; accounting must not claim bytes that never
+ * arrived. */
+ K3Tensor corrupt = *et;
+ corrupt.off = INT64_C(1) << 60;
+ ms.embed = &corrupt;
+ const uint64_t before_short = ms.embed_bytes_read;
+ if (k3_model_stream_embed_row(&ms, got_row, row) == 0 ||
+ ms.embed_bytes_read != before_short) {
+ fprintf(stderr, "short embedding read was accepted or counted\n");
+ bad++;
+ }
+ ms.embed = et;
+
+ /* Shape mismatch must fail before allocating or reading. */
+ K3Cfg wrong = c;
+ wrong.vocab++;
+ K3ModelStream reject;
+ if (k3_model_stream_init(&reject, &st, &wrong) == 0) {
+ fprintf(stderr, "model-stream shape mismatch was accepted\n");
+ k3_model_stream_free(&reject);
+ bad++;
+ }
+
+ free(embed);
+ free(head);
+ k3_model_stream_free(&ms);
+ k3_st_close(&st);
+ printf("model stream parity: %s\n", bad ? "FAILED" : "PASSED");
+ return bad ? 1 : 0;
+}
diff --git a/tools/make_st_fixture.py b/tools/make_st_fixture.py
index eaa99f1..bbc1530 100644
--- a/tools/make_st_fixture.py
+++ b/tools/make_st_fixture.py
@@ -82,11 +82,26 @@ def main():
u8 = rng.integers(0, 256, size=(7, 32), dtype=np.uint8)
+ # Small, deliberately non-vector-width model matrices for the streamed
+ # embedding/lm_head parity gate. Seven columns exercises the scalar tail after the
+ # four-accumulator loop; eleven rows makes chunk/order mistakes visible.
+ stream_rng = np.random.default_rng(29)
+ stream_embed = bf16_bits(
+ (stream_rng.standard_normal((11, 7)) * 0.25).astype(np.float32)
+ )
+ stream_head = bf16_bits(
+ (stream_rng.standard_normal((11, 7)) * 0.5).astype(np.float32)
+ )
+
A = {
"plain.f32.2d": ("F32", f32, (16, 16)),
"plain.bf16.1d": ("BF16", bf16, (128,)),
"tricky.f16.1d": ("F16", f16, (64,)),
"packed.u8.2d": ("U8", u8, (7, 32)),
+ "language_model.model.embed_tokens.weight":
+ ("BF16", stream_embed, (11, 7)),
+ "language_model.lm_head.weight":
+ ("BF16", stream_head, (11, 7)),
# A scalar has shape []. numel must be 1, not 0, or the size check rejects it.
"scalar.f32": ("F32", np.float32([3.5]), ()),
# A zero-element tensor is legal and spans zero bytes. A reader that treats
diff --git a/tools/pack_trunk.py b/tools/pack_trunk.py
index 05cbcb7..08182a1 100644
--- a/tools/pack_trunk.py
+++ b/tools/pack_trunk.py
@@ -51,20 +51,31 @@ def main():
nlayers = int(sys.argv[3]) if len(sys.argv) > 3 else 93
os.makedirs(out, exist_ok=True)
- print("indexing %d shards..." % len(os.listdir(src)))
+ shard_names = sorted(fn for fn in os.listdir(src) if fn.endswith(".safetensors"))
+ print("indexing %d safetensors shards..." % len(shard_names))
# name -> (shard_path, absolute_offset, nbytes, dtype, shape)
where = {}
- for fn in sorted(os.listdir(src)):
- if not fn.endswith(".safetensors"):
- continue
+ skipped_routed = 0
+ for fn in shard_names:
p = os.path.join(src, fn)
hdr, base = shard_header(p)
for name, e in hdr.items():
if name == "__metadata__":
continue
+ # Routed experts remain in the official shards and are streamed from there;
+ # they are never copied into trunk.bin. Avoid retaining their hundreds of
+ # thousands of Python dict entries just to reject them again per layer.
+ # Routers and shared experts do not match this path and remain in the exact
+ # dense trunk.
+ if ".block_sparse_moe.experts." in name:
+ skipped_routed += 1
+ continue
a, b = e["data_offsets"]
where[name] = (p, base + a, b - a, e["dtype"], e["shape"])
+ print("indexed %d trunk tensors; skipped %d routed-expert metadata entries"
+ % (len(where), skipped_routed))
+
manifest = {"n_layers": nlayers, "align": ALIGN, "layers": []}
total = 0
t0 = time.time()