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(cli): stop at a safe point on the first Ctrl-C and still write everything
Fareed Khan5392746c72c2
diff --git a/CMakeLists.txt b/CMakeLists.txtindex f4b25d9..8ddf12b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -152,6 +152,8 @@ k3_add_test(test_tok tests/unit/test_tok.c)k3_add_test(test_chat tests/unit/test_chat.c)k3_add_test(test_st_faults tests/unit/test_st_faults.c)k3_add_test(test_json tests/unit/test_json.c)+k3_add_test(test_cancel tests/unit/test_cancel.c)+target_include_directories(test_cancel PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/cli)target_link_libraries(test_chat PRIVATE k3_chat)k3_add_test(test_sampler tests/unit/test_sampler.c)target_link_libraries(test_sampler PRIVATE k3_chat)@@ -167,6 +169,7 @@ set(FIX ${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures)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 interrupt COMMAND test_cancel)add_test(NAME scale COMMAND scale_test)add_test(NAME trunk COMMAND test_trunk)add_test(NAME oracle COMMAND k3_model ${FIX})diff --git a/Makefile b/Makefileindex 846a4b5..19048d2 100644--- a/Makefile+++ b/Makefile@@ -156,7 +156,7 @@ CHAT_SRC := src/chat/k3_chat.c src/chat/k3_sampler.cCLI_BIN := $(BIN)/k3# Tests that need no checkpoint. These run in CI on every push.-UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat test_sampler scale_test k3_model test_trunk test_st_faults test_json+UNIT_TESTS := test_ops test_cache test_st test_model_stream test_cfg test_tok test_chat test_sampler scale_test k3_model test_trunk test_st_faults test_cancel test_json# 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@@ -221,6 +221,10 @@ $(BIN)/test_json: tests/unit/test_json.c | $(BIN)$(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+# Signal handling only; no OpenMP, no platform calls beyond signal() and write().+$(BIN)/test_cancel: tests/unit/test_cancel.c src/cli/k3_cancel.h | $(BIN)+ $(CC) -O2 -std=gnu99 $(WARN) $(INCLUDES) -Isrc/cli $< -o $@+# 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)@@ -276,6 +280,7 @@ test: $(CLI_BIN) $(TEST_BINS)@echo "== shard faults =="; ./$(BIN)/test_st_faults $(FIXTURES)/st $(BUILD)/stfault@echo "== json refusals =="; ./$(BIN)/test_json@echo "== config reader =="; ./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json+ @echo "== interrupt contract =="; ./$(BIN)/test_cancel@echo "== config refusals =="; \for f in no_layermap bad_layer_index bad_topk; do \./$(BIN)/test_cfg reject $(FIXTURES)/cfg/$$f.json || exit 1; \diff --git a/src/cli/k3_cancel.h b/src/cli/k3_cancel.hnew file mode 100644index 0000000..e4dc50b--- /dev/null+++ b/src/cli/k3_cancel.h@@ -0,0 +1,68 @@+/* k3_cancel.h - stop at a safe point on the first Ctrl-C; die on the second.+ *+ * A token on a streamed trunk takes up to two minutes, and a run is worth keeping+ * even when it is cut short: --save-state carries the conversation into the next+ * turn, --out JSON holds every id decoded so far, and the cache and trunk reports are+ * the reason many runs exist at all. SIGINT's default action throws all of that away+ * at whatever instruction the process was on. The contract here:+ *+ * first Ctrl-C sets a flag. The decode loop reads it once per step, at the top,+ * so the forward pass in flight completes (its KV rows and recurrent+ * state are then exact) and no further step starts. Everything a+ * finished run writes is still written, and the process exits 5,+ * distinct from 0 so a harness cannot mistake a partial run for a+ * complete one, and distinct from the 130 a shell reports for a+ * process SIGINT actually killed.+ * second Ctrl-C the default action: the handler re-arms SIG_DFL before returning,+ * so a user who does not want to wait out the step in flight is not+ * trapped by the first one.+ *+ * The handler touches only a sig_atomic_t and write(2), both async-signal-safe; the+ * message is written from the handler because the next safe point can be two minutes+ * away and silence for that long reads as a hang, which invites the second Ctrl-C.+ *+ * signal() rather than sigaction(): MinGW has no sigaction, and the CRT maps a console+ * Ctrl-C onto SIGINT through signal(), so one spelling covers all three platforms.+ * glibc's signal() has BSD semantics (the handler stays installed, interrupted+ * syscalls restart), which is what the trunk reader thread's blocking reads need.+ *+ * Only the batch decode loop installs this. Ctrl-C during the minutes of weight+ * loading, before the loop, still kills immediately: there is nothing to save yet. */+#ifndef K3_CANCEL_H+#define K3_CANCEL_H++#include <signal.h>+#ifdef _WIN32+#include <io.h>+#define k3_cancel_write(fd, s, n) _write((fd), (s), (unsigned)(n))+#else+#include <unistd.h>+#define k3_cancel_write(fd, s, n) write((fd), (s), (n))+#endif++static volatile sig_atomic_t k3_cancel_flag = 0;++static void k3_cancel_on_sigint(int sig)+{+ (void)sig;+ k3_cancel_flag = 1;+ signal(SIGINT, SIG_DFL); /* the second Ctrl-C is a kill */+ static const char msg[] =+ "\ninterrupt: the step in flight will complete, then state and results are "+ "written and the run exits 5.\n Press Ctrl-C again to kill it now.\n";+ (void)!k3_cancel_write(2, msg, sizeof msg - 1);+}++/* Arms the handler and clears any earlier request. */+static void k3_cancel_install(void)+{+ k3_cancel_flag = 0;+ signal(SIGINT, k3_cancel_on_sigint);+}++static int k3_cancel_requested(void)+{+ return k3_cancel_flag != 0;+}++#endif /* K3_CANCEL_H */diff --git a/src/cli/k3_run.c b/src/cli/k3_run.cindex bb8a9a8..58ea8ed 100644--- a/src/cli/k3_run.c+++ b/src/cli/k3_run.c@@ -69,6 +69,7 @@#include "k3_chat.h"#include "k3_sampler.h"#include "k3_cfg.h" /* read the checkpoint's own config rather than assuming it */+#include "k3_cancel.h" /* first Ctrl-C stops at a safe point; see the header */static double now_s(void){@@ -1820,12 +1821,26 @@ int main(int argc, char **argv)* 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, expert_bytes_total = 0;+ /* From here on the first Ctrl-C is a request to stop at the next safe point, not a+ * kill: the step in flight completes, then --save-state, --out and the reports run+ * exactly as for a finished run, and the exit code is 5. Armed only now, so a+ * Ctrl-C during the minutes of weight loading above still kills at once. */+ k3_cancel_install();+ int interrupted = 0;/* `nout < gen` drives generation; the `g == 0` disjunct additionally runs the* incremental prefill once even when --gen 0, so the prompt's KV and recurrent* state are computed and can be saved with ZERO generated tokens. That is what* lets --gen 0 --save-state warm a reusable prefix (e.g. a chat system prompt)* whose recurrent state is exact rather than one generated token past the end. */for (int g = 0; nout < gen || (incremental && g == 0); g++) {+ if (k3_cancel_requested()) {+ /* Checked at the top, so the step that was in flight when the signal+ * arrived has finished and its KV rows and recurrent state are exact. */+ interrupted = 1;+ printf("interrupted: %d of %d tokens generated; state, results and reports "+ "follow as for a finished run\n", nout, gen);+ break;+ }k3_cache_reset_stats(&cache);const double ts = now_s();int frc;@@ -2070,14 +2085,14 @@ int main(int argc, char **argv)"\"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,"- "\"stopped_at\":%d,"+ "\"stopped_at\":%d,\"interrupted\":%s,""\"generated_text\":",NL, NL, w.layers_completed, k3_expert_drops, peak_b, t_total,nout ? t_total / nout : 0.0, (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", stopped_at);+ w.ultra ? "true" : "false", stopped_at, interrupted ? "true" : "false");json_string(f, generated_text);fputs("}\n", f);fclose(f);@@ -2159,5 +2174,8 @@ int main(int argc, char **argv)return 4;}if (out_fail) return 3;+ /* Everything above ran, so the state and results on disk are complete; the code+ * says the token list is shorter than asked for. */+ if (interrupted) return 5;return 0;}diff --git a/tests/unit/test_cancel.c b/tests/unit/test_cancel.cnew file mode 100644index 0000000..f2217ac--- /dev/null+++ b/tests/unit/test_cancel.c@@ -0,0 +1,94 @@+/* test_cancel.c - Ctrl-C must stop the run at a safe point, not in the middle of one.+ *+ * WHY THIS FILE EXISTS+ * A token on a streamed trunk takes up to two minutes. Before src/cli/k3_cancel.h+ * existed, SIGINT took the default action at whatever instruction the process+ * happened to be on: the forward in flight was lost, --save-state never ran, and the+ * --out file was never written, so the only way to keep any of a long run was to+ * let all of it finish. The contract now is: the first Ctrl-C sets a flag the+ * decode loop checks once per step, the step in flight completes, nothing further+ * starts, and everything a finished run writes is still written; a second Ctrl-C+ * kills, in case the step in flight is the thing the user wants to escape.+ *+ * The decode loop itself needs a checkpoint to run, so what is tested here is the+ * contract the loop relies on: the flag, its stickiness, the placement of the check+ * (after the step in flight, before the next one), and the second-signal escape.+ *+ * usage: test_cancel+ */+#define _POSIX_C_SOURCE 200809L++#include <signal.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#ifndef _WIN32+#include <sys/wait.h>+#include <unistd.h>+#endif++#include "k3_cancel.h"++static int g_fail = 0;++static void ck(int ok, const char *what, const char *detail)+{+ printf(" %s %-44s %s\n", ok ? "PASS" : "FAIL", what, detail ? detail : "");+ if (!ok) g_fail++;+}++int main(void)+{+ printf("cancel: first interrupt is a request, not a kill\n");+ ck(!k3_cancel_requested(), "nothing requested before any signal", NULL);+ k3_cancel_install();+ ck(!k3_cancel_requested(), "install starts clean", NULL);+ raise(SIGINT);+ ck(1, "process survived SIGINT", NULL); /* reaching this line is the assertion */+ ck(k3_cancel_requested(), "request is visible after the signal", NULL);+ ck(k3_cancel_requested(), "and stays visible (sticky)", NULL);+ k3_cancel_install();+ ck(!k3_cancel_requested(), "re-install clears it", NULL);++ printf("cancel: the loop's safe point\n");+ {+ /* A model of the decode loop's check placement: the flag is consulted at the+ * top of each step. A signal arriving DURING step 3 must let step 3 finish and+ * must keep step 4 from starting, so exactly four steps complete. */+ k3_cancel_install();+ int completed = 0;+ for (int g = 0; g < 100; g++) {+ if (k3_cancel_requested()) break;+ if (g == 3) raise(SIGINT); /* arrives mid-step */+ completed++; /* the step in flight completes */+ }+ char d[64]; snprintf(d, sizeof d, "%d steps completed, want 4", completed);+ ck(completed == 4, "step in flight completes, next does not start", d);+ }++ printf("cancel: second interrupt kills\n");+#ifndef _WIN32+ {+ fflush(stdout);+ const pid_t pid = fork();+ if (pid == 0) {+ k3_cancel_install();+ raise(SIGINT); /* first: a request */+ if (!k3_cancel_requested()) _exit(3);+ raise(SIGINT); /* second: default action */+ _exit(4); /* not reached if the contract holds */+ }+ int status = 0;+ ck(pid > 0 && waitpid(pid, &status, 0) == pid, "child ran", NULL);+ char d[64];+ if (WIFSIGNALED(status)) snprintf(d, sizeof d, "killed by signal %d", WTERMSIG(status));+ else snprintf(d, sizeof d, "exited %d (not killed)", WEXITSTATUS(status));+ ck(WIFSIGNALED(status) && WTERMSIG(status) == SIGINT, "child died of SIGINT", d);+ }+#else+ printf(" SKIP %-44s %s\n", "child died of SIGINT", "no fork on Windows");+#endif++ printf("\n%s\n", g_fail ? "CANCEL TESTS FAILED" : "CANCEL TESTS PASSED");+ return g_fail ? 1 : 0;+}