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(chat): add --top-k to the existing sampler
Fareed Khana213baeaf7cc
diff --git a/Makefile b/Makefileindex dc3544f..846a4b5 100644--- a/Makefile+++ b/Makefile@@ -289,15 +289,15 @@ test: $(CLI_BIN) $(TEST_BINS)echo " repository. Run: make tok TOK_FILES=/path/to/k3model"; \fi@echo "== chat option contract =="; \- for args in "--no-think" "--thinking-effort low" "--chat --thinking-effort medium" "--chat --no-think --thinking-effort low"; do \+ for args in "--no-think" "--thinking-effort low" "--chat --thinking-effort medium" "--chat --no-think --thinking-effort low" "--ids 1 --top-k 4"; do \out=$$(./$(CLI_BIN) fake $$args 2>&1); rc=$$?; \test $$rc -eq 2 || { echo " k3 fake $$args returned $$rc, expected 2"; exit 1; }; \- case "$$out" in *--no-think*|*--thinking-effort*) ;; \+ case "$$out" in *--no-think*|*--thinking-effort*|*--top-k*) ;; \*) echo " '$$args' was refused, but not because of the thinking flags:"; \echo " $$out"; \echo " the model dir is 'fake', so the exit code alone would pass on the loader's error"; exit 1;; \esac; \- done; echo " 4 misuses of --no-think/--thinking-effort refused, each for the right reason"+ done; echo " 5 misuses of thinking/sampling flags refused, each for the right reason"@echo "== chat template =="; \if [ -f "$(TOK_FILES)/tiktoken.model" ]; then \./$(BIN)/test_chat "$(TOK_FILES)"; \diff --git a/src/chat/k3_sampler.c b/src/chat/k3_sampler.cindex 1fb38cf..d8efe76 100644--- a/src/chat/k3_sampler.c+++ b/src/chat/k3_sampler.c@@ -1,4 +1,4 @@-/* k3_sampler.c - PCG32 plus deterministic temperature/top-p selection. */+/* k3_sampler.c - PCG32 plus deterministic temperature/top-p/top-k selection. */#include "k3_sampler.h"#include <math.h>@@ -29,12 +29,12 @@ static double unit(K3Sampler *s)return (double)x * (1.0 / 9007199254740992.0);}-void k3_sampler_init(K3Sampler *s, double temperature, double top_p,+void k3_sampler_init(K3Sampler *s, double temperature, double top_p, int top_k,uint64_t seed, uint64_t turn){uint64_t x = seed ^ (turn * UINT64_C(0x9e3779b97f4a7c15));uint64_t state = splitmix64(&x), seq = splitmix64(&x);- s->temperature = temperature; s->top_p = top_p;+ s->temperature = temperature; s->top_p = top_p; s->top_k = top_k;s->state = 0; s->inc = (seq << 1u) | 1u;(void)pcg32(s); s->state += state; (void)pcg32(s);s->ids = NULL; s->prob = NULL; s->cap = 0;@@ -78,8 +78,14 @@ int k3_sampler_next(K3Sampler *s, const float *logits, int n, int greedy, int *oif (!(sum > 0.0) || !isfinite(sum)) { *out = best; return 0; }for (int i = 0; i < n; i++) s->prob[i] /= sum;sort_prob = s->prob; qsort(s->ids, (size_t)n, sizeof(*s->ids), cmp_desc_global); sort_prob = NULL;+ /* Top-k first: only the K most probable ids stay eligible for the nucleus+ * below. Disabled (<= 0) or wider than the vocabulary means the whole+ * sorted list, exactly as before. A top-p nucleus is always a prefix of+ * the same order, so the two truncations commute by construction. */+ int nw = n;+ if (s->top_k > 0 && s->top_k < nw) nw = s->top_k;double keep = 0.0; int nk = 0;- while (nk < n && keep < s->top_p) keep += s->prob[s->ids[nk++]];+ while (nk < nw && keep < s->top_p) keep += s->prob[s->ids[nk++]];if (!nk) nk = 1;double r = unit(s) * keep, acc = 0.0;for (int i = 0; i < nk; i++) { int id = s->ids[i]; acc += s->prob[id]; if (r < acc || i + 1 == nk) { *out = id; return 0; } }diff --git a/src/chat/k3_sampler.h b/src/chat/k3_sampler.hindex 2cdc83e..f3a8a83 100644--- a/src/chat/k3_sampler.h+++ b/src/chat/k3_sampler.h@@ -1,4 +1,4 @@-/* k3_sampler.h - deterministic top-p sampling for chat only. */+/* k3_sampler.h - deterministic top-p/top-k sampling for chat only. */#ifndef K3_SAMPLER_H#define K3_SAMPLER_H@@ -6,13 +6,14 @@typedef struct {double temperature, top_p;+ int top_k; /* <= 0 disables: the whole vocabulary stays eligible */uint64_t state, inc;int *ids;double *prob;int cap;} K3Sampler;-void k3_sampler_init(K3Sampler *s, double temperature, double top_p,+void k3_sampler_init(K3Sampler *s, double temperature, double top_p, int top_k,uint64_t seed, uint64_t turn);void k3_sampler_free(K3Sampler *s);int k3_sampler_next(K3Sampler *s, const float *logits, int n_vocab,diff --git a/src/cli/k3_run.c b/src/cli/k3_run.cindex 4c05607..bb8a9a8 100644--- a/src/cli/k3_run.c+++ b/src/cli/k3_run.c@@ -402,7 +402,8 @@ static void usage(FILE *f)" --history PATH portable JSONL transcript; rebuilt on restart\n"" --temperature X turn chat sampling on, at this temperature (default: greedy)\n"" --top-p P nucleus probability for chat sampling (default 0.95)\n"-" --seed N chat sampling seed; any of these three turns sampling on\n"+" --top-k K only the K most probable tokens stay eligible (default: off)\n"+" --seed N chat sampling seed; any of these four turns sampling on\n"" --greedy force argmax even when a sampling flag was given\n"" --no-think answer in the response channel directly: no think channel and\n"" no thinking-effort message (the encoder's thinking=False)\n"@@ -749,7 +750,7 @@ static int chat_resize(int want, int *tmax, int nl, int maxb, size_t kper,static int chat_run(Tok *tok, const K3ChatTemplate *tmpl, K3ChatHistory *history,const K3ChatOptions *opts, const char *history_path, int **prompt_ref, int np, int gen,int incremental, int greedy, double temperature, double top_p,- uint64_t seed, Weights *w, const K3Cfg *c, K3Cache *cache,+ int top_k, uint64_t seed, Weights *w, const K3Cfg *c, K3Cache *cache,int nl, int *tmax, float **h, float **br, float *ks,float **sc, float *lg, int **seq, int *outtok, int maxb, size_t kper){@@ -783,7 +784,7 @@ static int chat_run(Tok *tok, const K3ChatTemplate *tmpl, K3ChatHistory *history}w->cached = 0;int T = np, nraw = 0, frc = 0;- K3Sampler sampler; k3_sampler_init(&sampler, temperature, top_p, seed, (uint64_t)(turn + 1));+ K3Sampler sampler; k3_sampler_init(&sampler, temperature, top_p, top_k, seed, (uint64_t)(turn + 1));const double t_turn0 = now_s();while (nraw < gen) {if (incremental) {@@ -929,6 +930,7 @@ int main(int argc, char **argv)K3ChatOptions chat_opts = k3_chat_options_default();int no_think = 0, effort_set = 0;int temperature_set = 0, top_p_set = 0, seed_set = 0, out_set = 0;+ int top_k = 0, top_k_set = 0;double temperature = 1.0, top_p = 0.95;uint64_t seed = 0;for (int i = 2; i < argc; i++) {@@ -999,6 +1001,19 @@ int main(int argc, char **argv)if (value[0] == '-' || errno || !end || *end) { fprintf(stderr, "--seed needs an unsigned integer\n"); return 2; }seed_set = 1;}+ else if (!strcmp(argv[i], "--top-k") && i + 1 < argc) {+ /* A full integer of 1 or more. 0 would mean disabled, which is+ * already the default, so an explicit 0 is a typo; anything past+ * the vocabulary simply stays eligible, like disabled. */+ char *end = NULL;+ errno = 0;+ const long v = strtol(argv[++i], &end, 10);+ if (errno == ERANGE || end == argv[i] || *end != '\0' || v < 1 || v > INT_MAX) {+ fprintf(stderr, "--top-k %s: expected an integer of 1 or more\n", argv[i]);+ return 2;+ }+ top_k = (int)v; top_k_set = 1;+ }else if (!strcmp(argv[i], "--greedy")) greedy = 1;else if (!strcmp(argv[i], "--no-think")) { chat_opts.thinking = 0; no_think = 1; }else if (!strcmp(argv[i], "--thinking-effort") && i + 1 < argc) { chat_opts.thinking_effort = argv[++i]; effort_set = 1; }@@ -1100,8 +1115,8 @@ int main(int argc, char **argv)fprintf(stderr, "--chat needs --gen greater than zero to complete an assistant turn\n");return 2;}- } else if (system_text || history_path || temperature_set || top_p_set || seed_set || greedy) {- fprintf(stderr, "--system, --history, --temperature, --top-p, --seed, and --greedy require --chat\n");+ } else if (system_text || history_path || temperature_set || top_p_set || top_k_set || seed_set || greedy) {+ fprintf(stderr, "--system, --history, --temperature, --top-p, --top-k, --seed, and --greedy require --chat\n");return 2;}/* Greedy unless a sampling flag was given. Greedy decoding is what makes output@@ -1110,7 +1125,7 @@ int main(int argc, char **argv)* silently sampled would be the one path in the engine whose output could not* be reproduced. --greedy stays as an explicit override for scripts that set a* temperature and then want it ignored. */- if (!(temperature_set || top_p_set || seed_set)) greedy = 1;+ if (!(temperature_set || top_p_set || top_k_set || seed_set)) greedy = 1;if (chat && !seed_set) {/* A supplied seed is reproducible across restarts. Without one, start a fresh* stochastic session; the generated value is printed in the banner. */@@ -1283,8 +1298,12 @@ int main(int argc, char **argv)greedy ? "greedy" : "temperature/top-p sampling",chat_opts.thinking ? "thinking_effort=" : "thinking off",chat_opts.thinking ? chat_opts.thinking_effort : "");- if (!greedy) printf(" sampler : PCG32 seed %llu, temperature %.3f, top-p %.3f\n",- (unsigned long long)seed, temperature, top_p);+ if (!greedy) {+ if (top_k_set) printf(" sampler : PCG32 seed %llu, temperature %.3f, top-p %.3f, top-k %d\n",+ (unsigned long long)seed, temperature, top_p, top_k);+ else printf(" sampler : PCG32 seed %llu, temperature %.3f, top-p %.3f\n",+ (unsigned long long)seed, temperature, top_p);+ }} else {/* Heap, not stack. This was `int prompt[4096]` and it was the reason the engine* refused prompts longer than 4096 ids -- a stack-array size, not a model or@@ -1668,7 +1687,7 @@ int main(int argc, char **argv)if (chat) {const int rc = chat_run(&tok, &chat_template, &chat_history, &chat_opts, history_path,&prompt, np, gen, incremental, greedy, temperature,- top_p, seed, &w, &c, &cache, NL, &Tmax, &h, &br, ks,+ top_p, top_k, seed, &w, &c, &cache, NL, &Tmax, &h, &br, ks,&sc, lg, &seq, outtok, maxb, kper);free(w.kvc); free(w.ropec); free(w.mla_slot);if (w.trunk) k3_trunk_close(w.trunk);diff --git a/tests/unit/test_sampler.c b/tests/unit/test_sampler.cindex b6328e9..cf0c6d2 100644--- a/tests/unit/test_sampler.c+++ b/tests/unit/test_sampler.c@@ -39,8 +39,8 @@ int main(void){K3Sampler sa, sb;int same = 1;- k3_sampler_init(&sa, 0.7, 0.9, 1234, 5);- k3_sampler_init(&sb, 0.7, 0.9, 1234, 5);+ k3_sampler_init(&sa, 0.7, 0.9, 0, 1234, 5);+ k3_sampler_init(&sb, 0.7, 0.9, 0, 1234, 5);for (i = 0; i < 50; i++) {k3_sampler_next(&sa, logits, 4, 0, &a);k3_sampler_next(&sb, logits, 4, 0, &b);@@ -56,8 +56,8 @@ int main(void){K3Sampler sa, sb;int x[3], y;- k3_sampler_init(&sa, 1.0, 0.95, 42, 2);- k3_sampler_init(&sb, 1.0, 0.95, 42, 2);+ k3_sampler_init(&sa, 1.0, 0.95, 0, 42, 2);+ k3_sampler_init(&sb, 1.0, 0.95, 0, 42, 2);ok(k3_sampler_next(&sa, logits, 4, 1, &g) == 0 && g == 3,"greedy sampler remains argmax");k3_sampler_next(&sa, logits, 4, 1, &x[0]);@@ -75,7 +75,7 @@ int main(void)float masked[] = {0.0f, 1.0f, 2.0f, -1e30f};K3Sampler s;int picked = 0;- k3_sampler_init(&s, 1.0, 1.0, 7, 0);+ k3_sampler_init(&s, 1.0, 1.0, 0, 7, 0);for (i = 0; i < 20000; i++) {k3_sampler_next(&s, masked, 4, 0, &a);if (a == 3) picked = 1;@@ -88,28 +88,77 @@ int main(void){float one[] = {5.0f};K3Sampler s;- k3_sampler_init(&s, 1.0, 0.95, 1, 1);+ k3_sampler_init(&s, 1.0, 0.95, 0, 1, 1);ok(k3_sampler_next(&s, one, 1, 0, &a) == 0 && a == 0,"single-logit sampler always picks it");k3_sampler_free(&s);}+ /* Top-k: only the K most probable ids stay eligible for the nucleus that follows.+ * Off, wider than the vocabulary, or negative must replay the disabled stream+ * exactly, so adding the option changes nothing for anyone who does not ask. */+ {+ K3Sampler s_full, s_wide, s_neg, s_one, s_two, s_narrow;+ int same = 1, same_neg = 1, only_best = 1, in_window = 1, seen2 = 0, seen3 = 0;+ k3_sampler_init(&s_full, 1.0, 0.95, 0, 42, 2);+ k3_sampler_init(&s_wide, 1.0, 0.95, 99, 42, 2);+ k3_sampler_init(&s_neg, 1.0, 0.95, -5, 42, 2);+ for (i = 0; i < 20; i++) {+ k3_sampler_next(&s_full, logits, 4, 0, &a);+ k3_sampler_next(&s_wide, logits, 4, 0, &b);+ k3_sampler_next(&s_neg, logits, 4, 0, &g);+ if (a != b) same = 0;+ if (a != g) same_neg = 0;+ }+ ok(same, "top-k wider than the vocabulary replays disabled exactly");+ ok(same_neg, "negative top-k replays disabled exactly");+ k3_sampler_free(&s_full); k3_sampler_free(&s_wide); k3_sampler_free(&s_neg);++ k3_sampler_init(&s_one, 1.0, 1.0, 1, 7, 0);+ for (i = 0; i < 200; i++) {+ k3_sampler_next(&s_one, logits, 4, 0, &a);+ if (a != 3) only_best = 0;+ }+ ok(only_best, "top-k 1 always picks the argmax");+ k3_sampler_free(&s_one);++ k3_sampler_init(&s_two, 1.0, 1.0, 2, 7, 0);+ for (i = 0; i < 2000; i++) {+ k3_sampler_next(&s_two, logits, 4, 0, &a);+ if (a != 2 && a != 3) in_window = 0;+ if (a == 2) seen2 = 1;+ if (a == 3) seen3 = 1;+ }+ ok(in_window, "top-k 2 never picks outside its window");+ ok(seen2 && seen3, "top-k 2 still samples both survivors");+ k3_sampler_free(&s_two);++ k3_sampler_init(&s_narrow, 1.0, 0.5, 2, 7, 0);+ only_best = 1;+ for (i = 0; i < 200; i++) {+ k3_sampler_next(&s_narrow, logits, 4, 0, &a);+ if (a != 3) only_best = 0;+ }+ ok(only_best, "a top-p nucleus stays inside the top-k window");+ k3_sampler_free(&s_narrow);+ }+/* Invalid configurations are refused, never sampled from. */{K3Sampler bad;- k3_sampler_init(&bad, 1.0, 0.0, 1, 1);+ k3_sampler_init(&bad, 1.0, 0.0, 0, 1, 1);ok(k3_sampler_next(&bad, logits, 4, 0, &g) != 0, "top-p 0 is rejected");k3_sampler_free(&bad);- k3_sampler_init(&bad, 1.0, 1.5, 1, 1);+ k3_sampler_init(&bad, 1.0, 1.5, 0, 1, 1);ok(k3_sampler_next(&bad, logits, 4, 0, &g) != 0, "top-p above 1 is rejected");k3_sampler_free(&bad);- k3_sampler_init(&bad, 0.0, 0.95, 1, 1);+ k3_sampler_init(&bad, 0.0, 0.95, 0, 1, 1);ok(k3_sampler_next(&bad, logits, 4, 0, &g) != 0, "temperature 0 is rejected");k3_sampler_free(&bad);- k3_sampler_init(&bad, NAN, 0.95, 1, 1);+ k3_sampler_init(&bad, NAN, 0.95, 0, 1, 1);ok(k3_sampler_next(&bad, logits, 4, 0, &g) != 0, "NaN temperature is rejected");k3_sampler_free(&bad);- k3_sampler_init(&bad, 1.0, 0.95, 1, 1);+ k3_sampler_init(&bad, 1.0, 0.95, 0, 1, 1);ok(k3_sampler_next(&bad, logits, 0, 0, &g) != 0, "empty vocabulary is rejected");ok(k3_sampler_next(&bad, NULL, 4, 0, &g) != 0, "NULL logits are rejected");ok(k3_sampler_next(&bad, logits, 4, 0, NULL) != 0, "NULL out is rejected");