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 the K3 XTML chat template and REPL

Fareed Khance881020d24c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 639edb1..6768a1c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -118,7 +118,20 @@ endif()
# ------------------------------------------------------------------------------ cli --
add_executable(k3_cli src/cli/k3_run.c)
set_target_properties(k3_cli PROPERTIES OUTPUT_NAME k3)
-target_link_libraries(k3_cli PRIVATE k3)
+
+# Chat is deliberately separate from the inference library: it is CLI policy and
+# transcript handling, not a new framework or a second execution backend.
+add_library(k3_chat STATIC src/chat/k3_chat.c src/chat/k3_sampler.c)
+target_include_directories(k3_chat PUBLIC
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/chat
+ ${CMAKE_CURRENT_SOURCE_DIR}/src/tokenizer
+ ${CMAKE_CURRENT_SOURCE_DIR}/third_party)
+# k3_chat.c includes k3_portable_io.h for the fsync/rename shims its history writer
+# uses on Windows. The Makefile passes -Isrc/io to everything; here only this target
+# needs it, and privately, so the chat library's public surface stays src/chat.
+target_include_directories(k3_chat PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/io)
+target_link_libraries(k3_chat PUBLIC k3_flags m)
+target_link_libraries(k3_cli PRIVATE k3 k3_chat)
# ---------------------------------------------------------------------------- tests --
# Every test below runs WITHOUT model weights. The checkpoint is 1.56 TB; if correctness
@@ -136,6 +149,8 @@ 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(test_chat tests/unit/test_chat.c)
+target_link_libraries(test_chat PRIVATE k3_chat)
k3_add_test(scale_test tests/unit/scale_test.c)
k3_add_test(test_trunk tests/unit/test_trunk.c)
k3_add_test(k3_model tests/unit/k3_model.c)
@@ -151,6 +166,13 @@ add_test(NAME config COMMAND test_cfg fixture ${FIX}/ref_k3.json)
add_test(NAME scale COMMAND scale_test)
add_test(NAME trunk COMMAND test_trunk)
add_test(NAME oracle COMMAND k3_model ${FIX})
+add_test(NAME chat_template
+ COMMAND ${CMAKE_COMMAND}
+ -DTEST_CHAT=$<TARGET_FILE:test_chat>
+ -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/run_chat_test.cmake)
+# Same contract as the tokenizer entry below: without this property a "SKIPPED:" run is
+# recorded as a pass, and a gate that cannot fail is worse than one that is absent.
+set_tests_properties(chat_template PROPERTIES SKIP_REGULAR_EXPRESSION "SKIPPED:")
# The negative half of the config contract. Each fixture is the working flat config with
# exactly one field mutated, so a rejection can only come from that field. Without these
diff --git a/Makefile b/Makefile
index d537ef5..f602dff 100644
--- a/Makefile
+++ b/Makefile
@@ -115,6 +115,7 @@ else
endif
OMP_CFLAGS ?= -fopenmp
OMP_LDFLAGS ?= -fopenmp
+ ASAN_RUN_OPTIONS ?= detect_leaks=1:halt_on_error=1
endif
# Linux and macOS: the platform's own CC already has a working sanitizer runtime, so
@@ -141,7 +142,7 @@ LDFLAGS ?= -lm $(OMP_LDFLAGS) -pthread
# Flat include search across the module dirs: sources use "k3.h", "k3_cache.h" etc
# rather than path-qualified includes, which keeps them relocatable.
INCLUDES := -Iinclude -Iinclude/k3 -Ithird_party \
- -Isrc/core -Isrc/io -Isrc/cache -Isrc/model -Isrc/tokenizer
+ -Isrc/core -Isrc/io -Isrc/cache -Isrc/model -Isrc/tokenizer -Isrc/chat
# ----------------------------------------------------------------------------- files --
ENGINE_SRC := src/core/k3_ops.c \
@@ -151,10 +152,11 @@ ENGINE_SRC := src/core/k3_ops.c \
ENGINE_OBJ := $(patsubst %.c,$(BUILD)/%.o,$(ENGINE_SRC))
CLI_SRC := src/cli/k3_run.c
+CHAT_SRC := src/chat/k3_chat.c src/chat/k3_sampler.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_model_stream 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 test_chat 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
@@ -178,8 +180,8 @@ $(BUILD)/%.o: %.c
@mkdir -p $(dir $@)
$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@
-$(CLI_BIN): $(CLI_SRC) $(ENGINE_OBJ) | $(BIN)
- $(CC) $(CFLAGS) $(INCLUDES) $(CLI_SRC) $(ENGINE_OBJ) -o $@ $(LDFLAGS)
+$(CLI_BIN): $(CLI_SRC) $(CHAT_SRC) $(ENGINE_OBJ) | $(BIN)
+ $(CC) $(CFLAGS) $(INCLUDES) $(CLI_SRC) $(CHAT_SRC) $(ENGINE_OBJ) -o $@ $(LDFLAGS)
$(BIN):
@mkdir -p $(BIN)
@@ -205,6 +207,9 @@ $(BIN)/test_model_stream: tests/unit/test_model_stream.c $(BUILD)/src/model/k3_b
$(BIN)/test_tok: tests/unit/test_tok.c | $(BIN)
$(CC) -O2 -std=c99 $(WARN) -Wno-unused-function $(INCLUDES) $< -o $@
+$(BIN)/test_chat: tests/unit/test_chat.c src/chat/k3_chat.c src/chat/k3_sampler.c | $(BIN)
+ $(CC) $(CFLAGS) -Wno-unused-function $(INCLUDES) $^ -o $@ $(LDFLAGS)
+
$(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
@@ -260,8 +265,26 @@ test: $(CLI_BIN) $(TEST_BINS)
./$(BIN)/test_tok "$(TOK_FILES)" roundtrip src/core/k3_ops.c; \
else \
echo " NOT RUN: no tiktoken.model at $(TOK_FILES)"; \
- echo " the vocabulary ships with the checkpoint, not with this"; \
- echo " repository. Run: make tok TOK_FILES=/path/to/k3model"; \
+ echo " the vocabulary ships with the checkpoint, not with this"; \
+ 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 \
+ 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*) ;; \
+ *) 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"
+ @echo "== chat template =="; \
+ if [ -f "$(TOK_FILES)/tiktoken.model" ]; then \
+ ./$(BIN)/test_chat "$(TOK_FILES)"; \
+ else \
+ echo " NOT RUN: no tiktoken.model at $(TOK_FILES)"; \
+ echo " the XTML template is checked against the released tokenizer,"; \
+ echo " which ships with the checkpoint. Run: make test TOK_FILES=/path/to/k3model"; \
fi
@echo "== real dimensions =="; ./$(BIN)/scale_test
@echo "== trunk streaming =="; ./$(BIN)/test_trunk
diff --git a/README.md b/README.md
index 3554ea1..9083f4d 100644
--- a/README.md
+++ b/README.md
@@ -86,9 +86,10 @@ $ ./bin/k3 ~/k3model --trunk ~/k3trunk --preset laptop \
PEAK RSS for the whole run: 8.24 GB
```
-Slow, and answering correctly, in 8.24 GB, from a checkpoint of 1.56 TB. This is a base
-model, so what follows " Paris." is a continuation rather than a reply; there is no chat
-template. Give it more memory and the answer does not change, only the clock:
+Slow, and answering correctly, in 8.24 GB, from a checkpoint of 1.56 TB. This particular
+batch command deliberately asks for a raw continuation. The official Kimi K3 checkpoint
+is also chat-capable; use the XTML REPL below when you want answers and multi-turn history.
+Give the same batch request more memory and the answer does not change, only the clock:
```console
$ ./bin/k3 ~/k3model --trunk ~/k3trunk --preset server \
@@ -375,8 +376,8 @@ run, but `--help`, `--version` and `--list-presets` work without it:
### Prompt options
-Exactly one of these is required. Passing none, or more than one, is a usage error
-(exit 2).
+Outside `--chat`, exactly one of these is required. Passing none, or more than one, is a
+usage error (exit 2).
| flag | argument | |
|---|---|---|
@@ -431,6 +432,58 @@ entire prefix, which is *O(T²)*; with it, step 0 pays for the prompt and every
costs the same fixed amount. Both paths are gated on producing identical tokens, so this
is a pure speed choice.
+### Text chat (official Kimi K3 XTML)
+
+K3 is chat-capable. `--chat` uses the official XTML segments and tokenizer control tokens;
+it does not fall back to ChatML or a handwritten generic prompt. Version one is text-only:
+there are no tools, images, server, or context compaction.
+
+```bash
+./bin/k3 ~/k3model --trunk ~/k3trunk --preset desktop --tok ~/k3model \
+ --chat --system "You are a helpful assistant." \
+ --history my-session.jsonl --incremental
+```
+
+The REPL accepts ordinary text plus `/help`, `/reset`, and `/exit`. It prints the complete
+canonical record, including `<think>…</think>` and `<response>…</response>`. When
+`--history` is supplied, it writes a portable, human-readable JSONL file such as:
+
+```json
+{"role":"system","content":"You are a helpful assistant."}
+{"role":"user","content":"Explain cache locality."}
+{"role":"assistant","content":"…","reasoning_content":"…"}
+```
+
+Treat that file as sensitive: it can contain every user message and the complete assistant
+reasoning record, which K3 requires to continue a conversation faithfully. On restart the
+engine validates, re-renders, and re-prefills the transcript; it deliberately does not
+serialize opaque KV, MLA, or KDA state. A supplied `--system` must exactly match an existing
+initial system record. Literal control-marker text in user messages is encoded as ordinary
+text, never as an XTML control token.
+
+Chat defaults to `--gen 4096` and, like batch generation, to greedy decoding. Passing any
+of `--temperature`, `--top-p` or `--seed` turns sampling on (temperature `1.0`, top-p
+`0.95` unless given); `--greedy` forces argmax even then. Sampling uses
+PCG32; `--seed N` deterministically derives one stream per assistant turn, so replaying the
+same transcript with the same seed is reproducible. The 32K prompt / 4096 generation limits
+are existing engine limits, not new chat limits; chat fails clearly and retains the history
+when either context or safe KV allocation is reached.
+
+Thinking is on by default with `thinking_effort=max`, which is exactly what the checkpoint's
+own tokenizer does when `apply_chat_template` is given nothing; `--thinking-effort low` or
+`high` changes only that setting. `--no-think` is the encoder's `thinking=False`: no
+thinking-effort system message, prior assistant turns rendered without a think channel, and
+a generation prompt that opens the response channel directly, so the model answers at once
+and the REPL prints no `<think>` block. On a streamed trunk this is the largest speed lever
+there is: in a real-checkpoint run, 119 of the 150 tokens of a five-word answer were the
+think block. Reasoning already stored in the transcript is left in place and is rendered
+again the next time the conversation runs with thinking on. Both flags are byte- and
+id-exact against the official tokenizer in `tests/unit/test_chat.c`.
+
+Chat uses the same CPU-only streamed trunk and routed-expert cache as batch mode. `--preset`,
+`--trunk-gb`, and `--cache-gb` keep exactly their existing meanings: no experts are preloaded
+and the trunk remains disk-streamed unless those existing memory flags ask otherwise.
+
### Diagnostic options
| flag | argument | |
@@ -2826,8 +2879,8 @@ arithmetic and no evidence at all about output quality.
**Paris.** The first token out of a 2.78 trillion parameter model running on a CPU in a few
gigabytes of RAM is the right answer. The trailing quote and the "The Eiffel" continuation
-are not a defect: with no chat template and no instruction tuning in the loop, this is a
-base model continuing text. It has decided it is inside a JSON list of sentences about
+are not a defect: that raw-completion test supplies no XTML chat turn, so the model is
+continuing text. It has decided it is inside a JSON list of sentences about
France, and it is continuing that list.
```text
@@ -3349,9 +3402,11 @@ Raw data: [`docs/data/trunk-quantisation.txt`](docs/data/trunk-quantisation.txt)
## Scope
-- **No chat template.** Base model continuations, not replies.
-- **Greedy decoding only.** No temperature, no top-p, no top-k. Greedy is what keeps the
- output identical across budgets.
+- **Text-only XTML chat.** K3 system/user/assistant conversations and their reasoning
+ history are supported. Tools, vision/image parts, HTTP serving, and context compaction are
+ not yet supported.
+- **Batch remains greedy.** Its outputs remain identical across memory budgets. Chat alone
+ adds opt-in temperature/top-p sampling and `--greedy`.
- **No chunked prefill.** The ceiling is 32,768 tokens, but a 21,000 token prompt is one
quadratic pass.
- **Context is bounded by memory, not by the engine.**
diff --git a/cmake/run_chat_test.cmake b/cmake/run_chat_test.cmake
new file mode 100644
index 0000000..1befe0e
--- /dev/null
+++ b/cmake/run_chat_test.cmake
@@ -0,0 +1,29 @@
+# Runs the XTML chat-template check (test_chat) when the released vocabulary is available, and prints a
+# line ctest recognises as a skip when it is not.
+#
+# tiktoken.model has 163,584 entries and ships with the checkpoint, not with this
+# repository, so this gate cannot run on a clean checkout. It is registered anyway: a
+# check that vanishes from the list when it cannot run reads as "one fewer test to care
+# about", and ctest's count silently stops matching what `make test` runs.
+#
+# K3_TOK_FILES is read here, at TEST time rather than configure time, so
+# `K3_TOK_FILES=/path/to/k3model ctest` works without reconfiguring the build.
+
+set(TOK_FILES "$ENV{K3_TOK_FILES}")
+
+if(TOK_FILES STREQUAL "")
+ message("SKIPPED: K3_TOK_FILES is not set. The vocabulary ships with the checkpoint;"
+ " set K3_TOK_FILES to a model directory to run this gate.")
+ return()
+endif()
+
+if(NOT EXISTS "${TOK_FILES}/tiktoken.model")
+ message("SKIPPED: no tiktoken.model in ${TOK_FILES}")
+ return()
+endif()
+
+execute_process(COMMAND "${TEST_CHAT}" "${TOK_FILES}"
+ RESULT_VARIABLE rc)
+if(NOT rc EQUAL 0)
+ message(FATAL_ERROR "XTML chat-template check failed with status ${rc}")
+endif()
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index f7c4316..752cce5 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -65,8 +65,12 @@ src/model/
src/tokenizer/
k3_tok.h loads the released tiktoken.model directly
+src/chat/
+ k3_chat.c strict JSONL transcripts and official XTML segment rendering
+ k3_sampler.c deterministic PCG32 temperature/top-p sampling
+
src/cli/
- k3_run.c the k3 binary
+ k3_run.c batch CLI plus the text-only chat REPL
```
## Attention: two mechanisms
diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md
index 0d16126..86f8ab7 100644
--- a/docs/QUICKSTART.md
+++ b/docs/QUICKSTART.md
@@ -72,6 +72,17 @@ memory budget adjustable rather than fixed at ~115 GB.
- `examples/`, runnable scripts, including one that proves output is identical across
memory budgets
+For a text conversation rather than a raw continuation, use the official K3 XTML REPL:
+
+```bash
+./bin/k3 ~/k3model --trunk ~/k3trunk --preset desktop --tok ~/k3model \
+ --chat --system "You are a helpful assistant." \
+ --history my-session.jsonl --incremental
+```
+
+The JSONL transcript is portable but sensitive: it retains assistant `reasoning_content`
+as well as visible replies, because K3 needs that complete record for the next turn.
+
## Troubleshooting
**"REFUSING: the KV cache for N positions needs X"**, the context you asked for does not
@@ -84,5 +95,5 @@ quadratic in sequence length. See [ROADMAP.md](ROADMAP.md).
**"config could not be read with confidence"**, the reader found a config it does not
fully understand and refused rather than guessing. The message lists every missing field.
-**Output is a continuation, not an answer**, correct. There is no chat template; the
-model completes your prompt.
+**Output is a continuation, not an answer**, use `--chat`; ordinary `--prompt` deliberately
+keeps raw-completion behavior for compatibility.
diff --git a/docs/README.md b/docs/README.md
index 1c3a6b4..7886456 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -19,6 +19,10 @@
| [ROADMAP.md](ROADMAP.md) | what is missing, in priority order |
| [data/](data/) | the raw measurement output every table is transcribed from |
+Text-only official XTML chat is documented in the main [README](../README.md#text-chat-official-kimi-k3-xtml).
+It remains CPU- and disk-bound and uses the same streamed trunk and expert-cache budgets as
+batch generation.
+
## Upstream material
| | |
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 0c83103..30302a9 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -33,14 +33,17 @@ un-vectorised kernel on the non-I/O path.
## 5. Sampling
-Greedy only today. Adding temperature and top-p is small, but note the trade-off: greedy
-decoding is what makes output identical across memory budgets, which is a property the
-test-suite depends on. Sampling must be opt-in and off by default.
+Batch generation is greedy only. Chat has opt-in temperature, top-p and seed
+(`--temperature`, `--top-p`, `--seed`), and is greedy until one of them is given. Keep
+it that way: greedy decoding is what makes output identical across memory budgets, which
+is a property the test suite depends on.
-## 6. Chat template
+## 6. Chat retained-state equivalence
-K3 ships an XTML chat format. Without it the engine produces base-model continuations,
-which is why asking a question gets the question completed rather than answered.
+Text chat now implements K3's official XTML formatting, JSONL restart, and safe complete
+history re-prefill. The next optimization is retaining in-process KDA/MLA state across
+REPL turns only after an equivalence gate proves that its token stream matches a full
+re-prefill of the same transcript.
## 7. Vision
@@ -48,10 +51,10 @@ K3 is natively multimodal. The vision tower is 27 layers and ~0.4B parameters, s
and its weights are ~0.9 GB, a fraction of a percent of the checkpoint. Self-contained
enough to be tractable.
-## 8. Serving
+## 8. Tools and serving
-No HTTP API. Deliberately last: it is product surface, and everything above changes what
-would be served.
+The message model leaves room for tool calls, but there is no tool execution or HTTP API.
+Both remain deliberately late product surface.
## Explicitly not planned
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 7990fc4..2a56349 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -93,6 +93,14 @@ out of it rather than restating it; without that file the parity run stops befor
first case. The roundtrip leg in `make test` needs only `tiktoken.model` and
`tokenizer_config.json`.
+**`test_chat`**, the official K3 XTML text-chat contract without weights. It takes the
+released tokenizer directory (`TOK_FILES`, the same one the tokenizer gate uses) and
+verifies rendered bytes and token ids, assistant reasoning preservation, control-marker
+injection resistance, the exact assistant turn terminator, strict JSONL
+round-trip/rejection, `/reset`, and fixed-seed PCG32 sampling. Like `test_tok` it
+prints NOT RUN when no `tiktoken.model` is present: the vocabulary ships with the
+checkpoint, not with this repository, and is deliberately not copied into it.
+
**`k3_model`**, the end-to-end gate, on a tiny model whose tensor graph matches the released
architecture exactly:
diff --git a/src/chat/k3_chat.c b/src/chat/k3_chat.c
new file mode 100644
index 0000000..2858364
--- /dev/null
+++ b/src/chat/k3_chat.c
@@ -0,0 +1,480 @@
+/* k3_chat.c - transcript, XTML rendering, and assistant boundary parsing. */
+#define _POSIX_C_SOURCE 200809L
+#include "k3_portable_io.h" /* fsync() shim for MinGW; see the header for why */
+#include "k3_chat.h"
+
+#include <errno.h>
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static void fail(char *err, size_t n, const char *fmt, ...)
+{
+ if (!err || n == 0) return;
+ va_list ap; va_start(ap, fmt); vsnprintf(err, n, fmt, ap); va_end(ap);
+}
+
+static char *dup_(const char *s)
+{
+ size_t n = s ? strlen(s) : 0;
+ char *d = (char *)malloc(n + 1);
+ if (!d) return NULL;
+ if (n) memcpy(d, s, n);
+ d[n] = 0;
+ return d;
+}
+
+static const char *role_name(int role)
+{
+ if (role == K3_CHAT_SYSTEM) return "system";
+ if (role == K3_CHAT_USER) return "user";
+ if (role == K3_CHAT_ASSISTANT) return "assistant";
+ return NULL;
+}
+
+static int role_id(const char *s)
+{
+ if (!strcmp(s, "system")) return K3_CHAT_SYSTEM;
+ if (!strcmp(s, "user")) return K3_CHAT_USER;
+ if (!strcmp(s, "assistant")) return K3_CHAT_ASSISTANT;
+ return -1;
+}
+
+void k3_chat_message_free(K3ChatMessage *m)
+{
+ if (!m) return;
+ free(m->content); free(m->reasoning_content);
+ memset(m, 0, sizeof *m);
+}
+
+void k3_chat_history_init(K3ChatHistory *h) { memset(h, 0, sizeof *h); }
+
+void k3_chat_history_free(K3ChatHistory *h)
+{
+ if (!h) return;
+ for (int i = 0; i < h->n; i++) k3_chat_message_free(&h->v[i]);
+ free(h->v); memset(h, 0, sizeof *h);
+}
+
+int k3_chat_history_reset(K3ChatHistory *h, char *err, size_t err_n)
+{
+ char *system = NULL;
+ if (h->n && h->v[0].role == K3_CHAT_SYSTEM) {
+ system = dup_(h->v[0].content);
+ if (!system) { fail(err, err_n, "out of memory preserving system message"); return -1; }
+ }
+ k3_chat_history_free(h); k3_chat_history_init(h);
+ if (system) {
+ int rc = k3_chat_history_add(h, K3_CHAT_SYSTEM, system, NULL, err, err_n);
+ free(system);
+ return rc;
+ }
+ return 0;
+}
+
+int k3_chat_history_validate(const K3ChatHistory *h, char *err, size_t err_n)
+{
+ int want = K3_CHAT_USER;
+ for (int i = 0; i < h->n; i++) {
+ const K3ChatMessage *m = &h->v[i];
+ if (!role_name(m->role) || !m->content) {
+ fail(err, err_n, "history message %d has an invalid role or missing content", i + 1);
+ return -1;
+ }
+ if (m->role == K3_CHAT_SYSTEM) {
+ if (i != 0) { fail(err, err_n, "system message must be first (line %d)", i + 1); return -1; }
+ continue;
+ }
+ if (m->role != want) {
+ fail(err, err_n, "message %d has role '%s', expected '%s'", i + 1,
+ role_name(m->role), role_name(want));
+ return -1;
+ }
+ if (m->role != K3_CHAT_ASSISTANT && m->reasoning_content) {
+ fail(err, err_n, "message %d has reasoning_content but is not assistant", i + 1);
+ return -1;
+ }
+ want = want == K3_CHAT_USER ? K3_CHAT_ASSISTANT : K3_CHAT_USER;
+ }
+ return 0;
+}
+
+int k3_chat_history_add(K3ChatHistory *h, int role, const char *content,
+ const char *reasoning, char *err, size_t err_n)
+{
+ if (!role_name(role) || !content || (role != K3_CHAT_ASSISTANT && reasoning)) {
+ fail(err, err_n, "invalid chat message"); return -1;
+ }
+ if (h->n == h->cap) {
+ int cap = h->cap ? h->cap * 2 : 8;
+ K3ChatMessage *v = (K3ChatMessage *)realloc(h->v, (size_t)cap * sizeof(*v));
+ if (!v) { fail(err, err_n, "out of memory growing history"); return -1; }
+ h->v = v; h->cap = cap;
+ }
+ K3ChatMessage m; memset(&m, 0, sizeof m); m.role = role;
+ m.content = dup_(content);
+ m.reasoning_content = reasoning ? dup_(reasoning) : NULL;
+ if (!m.content || (reasoning && !m.reasoning_content)) {
+ k3_chat_message_free(&m); fail(err, err_n, "out of memory copying message"); return -1;
+ }
+ h->v[h->n++] = m;
+ if (k3_chat_history_validate(h, err, err_n) != 0) {
+ k3_chat_message_free(&h->v[--h->n]); return -1;
+ }
+ return 0;
+}
+
+/* ---- strict JSON lines ----------------------------------------------------- */
+typedef struct { const char *p; } JScan;
+
+static void jws(JScan *s) { while (*s->p == ' ' || *s->p == '\t' || *s->p == '\r') s->p++; }
+
+static int putc_(char **out, size_t *n, size_t *cap, unsigned char c)
+{
+ if (*n + 1 >= *cap) {
+ size_t nc = *cap ? *cap * 2 : 64;
+ char *v = (char *)realloc(*out, nc);
+ if (!v) return -1;
+ *out = v; *cap = nc;
+ }
+ (*out)[(*n)++] = (char)c; return 0;
+}
+
+static int hex_(char c)
+{
+ if (c >= '0' && c <= '9') return c - '0';
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
+ return -1;
+}
+
+static int jstr(JScan *s, char **out, char *err, size_t err_n)
+{
+ if (*s->p++ != '"') { fail(err, err_n, "expected JSON string"); return -1; }
+ char *v = NULL; size_t n = 0, cap = 0;
+ while (*s->p && *s->p != '"') {
+ unsigned char c = (unsigned char)*s->p++;
+ if (c < 0x20) { free(v); fail(err, err_n, "control byte in JSON string"); return -1; }
+ if (c != '\\') { if (putc_(&v, &n, &cap, c)) goto oom; continue; }
+ char e = *s->p++;
+ if (!e) { free(v); fail(err, err_n, "truncated JSON escape"); return -1; }
+ switch (e) {
+ case '"': case '\\': case '/': if (putc_(&v, &n, &cap, (unsigned char)e)) goto oom; break;
+ case 'b': if (putc_(&v, &n, &cap, '\b')) goto oom; break;
+ case 'f': if (putc_(&v, &n, &cap, '\f')) goto oom; break;
+ case 'n': if (putc_(&v, &n, &cap, '\n')) goto oom; break;
+ case 'r': if (putc_(&v, &n, &cap, '\r')) goto oom; break;
+ case 't': if (putc_(&v, &n, &cap, '\t')) goto oom; break;
+ case 'u': {
+ int a = hex_(s->p[0]), b = hex_(s->p[1]), c1 = hex_(s->p[2]), d = hex_(s->p[3]);
+ if (a < 0 || b < 0 || c1 < 0 || d < 0) { free(v); fail(err, err_n, "bad \\u escape"); return -1; }
+ unsigned cp = (unsigned)((a << 12) | (b << 8) | (c1 << 4) | d);
+ s->p += 4;
+ if (cp >= 0xd800 && cp <= 0xdbff) {
+ if (s->p[0] != '\\' || s->p[1] != 'u') { free(v); fail(err, err_n, "unpaired high surrogate in JSON string"); return -1; }
+ int lo0 = hex_(s->p[2]), lo1 = hex_(s->p[3]);
+ int lo2 = hex_(s->p[4]), lo3 = hex_(s->p[5]);
+ if (lo0 < 0 || lo1 < 0 || lo2 < 0 || lo3 < 0) { free(v); fail(err, err_n, "bad low-surrogate escape"); return -1; }
+ unsigned lo = (unsigned)((lo0 << 12) | (lo1 << 8) | (lo2 << 4) | lo3);
+ if (lo < 0xdc00 || lo > 0xdfff) { free(v); fail(err, err_n, "unpaired high surrogate in JSON string"); return -1; }
+ cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00);
+ s->p += 6;
+ } else if (cp >= 0xdc00 && cp <= 0xdfff) {
+ free(v); fail(err, err_n, "unpaired low surrogate in JSON string"); return -1;
+ }
+ if (cp == 0) { free(v); fail(err, err_n, "NUL is not supported in chat JSON strings"); return -1; }
+ if (cp < 0x80) { if (putc_(&v, &n, &cap, (unsigned char)cp)) goto oom; }
+ else if (cp < 0x800) {
+ if (putc_(&v, &n, &cap, 0xc0 | (cp >> 6)) || putc_(&v, &n, &cap, 0x80 | (cp & 63))) goto oom;
+ } else if (cp < 0x10000) {
+ if (putc_(&v, &n, &cap, 0xe0 | (cp >> 12)) || putc_(&v, &n, &cap, 0x80 | ((cp >> 6) & 63)) || putc_(&v, &n, &cap, 0x80 | (cp & 63))) goto oom;
+ } else {
+ if (putc_(&v, &n, &cap, 0xf0 | (cp >> 18)) || putc_(&v, &n, &cap, 0x80 | ((cp >> 12) & 63)) || putc_(&v, &n, &cap, 0x80 | ((cp >> 6) & 63)) || putc_(&v, &n, &cap, 0x80 | (cp & 63))) goto oom;
+ }
+ break;
+ }
+ default: free(v); fail(err, err_n, "unknown JSON escape"); return -1;
+ }
+ }
+ if (*s->p != '"') { free(v); fail(err, err_n, "unterminated JSON string"); return -1; }
+ s->p++;
+ if (putc_(&v, &n, &cap, 0)) goto oom;
+ *out = v; return 0;
+oom:
+ free(v); fail(err, err_n, "out of memory parsing JSON string"); return -1;
+}
+
+static int parse_record(const char *line, K3ChatMessage *out, char *err, size_t err_n)
+{
+ JScan s = {line}; char *role = NULL, *content = NULL, *reasoning = NULL;
+ int have_role = 0, have_content = 0, have_reason = 0;
+ memset(out, 0, sizeof *out); jws(&s);
+ if (*s.p++ != '{') { fail(err, err_n, "record is not a JSON object"); goto bad; }
+ for (;;) {
+ jws(&s); if (*s.p == '}') { s.p++; break; }
+ char *key = NULL, *value = NULL;
+ if (jstr(&s, &key, err, err_n) || (jws(&s), *s.p++ != ':') || (jws(&s), jstr(&s, &value, err, err_n))) {
+ free(key); free(value); goto bad;
+ }
+ if (!strcmp(key, "role") && !have_role) { role = value; have_role = 1; value = NULL; }
+ else if (!strcmp(key, "content") && !have_content) { content = value; have_content = 1; value = NULL; }
+ else if (!strcmp(key, "reasoning_content") && !have_reason) { reasoning = value; have_reason = 1; value = NULL; }
+ else { free(key); free(value); fail(err, err_n, "unknown or duplicate JSONL field"); goto bad; }
+ free(key); free(value); jws(&s);
+ if (*s.p == ',') { s.p++; continue; }
+ if (*s.p == '}') { s.p++; break; }
+ fail(err, err_n, "expected ',' or '}' in JSON object"); goto bad;
+ }
+ jws(&s); if (*s.p) { fail(err, err_n, "trailing data after JSON object"); goto bad; }
+ int rid = role ? role_id(role) : -1;
+ if (rid < 0 || !content || (rid != K3_CHAT_ASSISTANT && reasoning)) {
+ fail(err, err_n, "record needs role/content; reasoning_content is assistant-only"); goto bad;
+ }
+ out->role = rid; out->content = content; out->reasoning_content = reasoning;
+ free(role); return 0;
+bad:
+ free(role); free(content); free(reasoning); return -1;
+}
+
+int k3_chat_history_load(K3ChatHistory *h, const char *path, char *err, size_t err_n)
+{
+ FILE *f = fopen(path, "rb");
+ if (!f) { if (errno == ENOENT) return 0; fail(err, err_n, "cannot open %s: %s", path, strerror(errno)); return -1; }
+ char *line = NULL; size_t n = 0, cap = 0; int line_no = 0, ch, rc = -1;
+ while ((ch = fgetc(f)) != EOF) {
+ if (ch == '\n') {
+ line_no++; if (!n) { fail(err, err_n, "%s:%d is blank", path, line_no); goto done; }
+ if (putc_(&line, &n, &cap, 0)) { fail(err, err_n, "out of memory reading history"); goto done; }
+ K3ChatMessage m;
+ if (parse_record(line, &m, err, err_n)) { char msg[256]; snprintf(msg, sizeof msg, "%s", err); fail(err, err_n, "%s:%d: %s", path, line_no, msg); goto done; }
+ if (h->n == h->cap) { int nc = h->cap ? h->cap * 2 : 8; K3ChatMessage *v = (K3ChatMessage *)realloc(h->v, (size_t)nc * sizeof(*v)); if (!v) { k3_chat_message_free(&m); fail(err, err_n, "out of memory growing history"); goto done; } h->v = v; h->cap = nc; }
+ h->v[h->n++] = m; n = 0; continue;
+ }
+ if (n >= 16 * 1024 * 1024) { fail(err, err_n, "%s:%d exceeds 16 MiB", path, line_no + 1); goto done; }
+ if (putc_(&line, &n, &cap, (unsigned char)ch)) { fail(err, err_n, "out of memory reading history"); goto done; }
+ }
+ if (ferror(f)) { fail(err, err_n, "failed reading %s", path); goto done; }
+ if (n) { line_no++; if (putc_(&line, &n, &cap, 0)) { fail(err, err_n, "out of memory reading history"); goto done; } K3ChatMessage m; if (parse_record(line, &m, err, err_n)) { char msg[256]; snprintf(msg, sizeof msg, "%s", err); fail(err, err_n, "%s:%d: %s", path, line_no, msg); goto done; } if (h->n == h->cap) { int nc = h->cap ? h->cap * 2 : 8; K3ChatMessage *v = (K3ChatMessage *)realloc(h->v, (size_t)nc * sizeof(*v)); if (!v) { k3_chat_message_free(&m); fail(err, err_n, "out of memory growing history"); goto done; } h->v = v; h->cap = nc; } h->v[h->n++] = m; }
+ rc = k3_chat_history_validate(h, err, err_n);
+done:
+ free(line); fclose(f); if (rc) k3_chat_history_free(h); return rc;
+}
+
+static int jwrite(FILE *f, const char *s)
+{
+ if (fputc('"', f) == EOF) return -1;
+ for (; *s; s++) {
+ unsigned char c = (unsigned char)*s;
+ if (c == '"' || c == '\\') { if (fputc('\\', f) == EOF || fputc(c, f) == EOF) return -1; }
+ else if (c == '\n') { if (fputs("\\n", f) == EOF) return -1; }
+ else if (c == '\r') { if (fputs("\\r", f) == EOF) return -1; }
+ else if (c == '\t') { if (fputs("\\t", f) == EOF) return -1; }
+ else if (c < 0x20) { if (fprintf(f, "\\u%04x", c) < 0) return -1; }
+ else if (fputc(c, f) == EOF) return -1;
+ }
+ return fputc('"', f) == EOF ? -1 : 0;
+}
+
+int k3_chat_history_save(const K3ChatHistory *h, const char *path, char *err, size_t err_n)
+{
+ if (k3_chat_history_validate(h, err, err_n)) return -1;
+ char tmp[4096]; if (snprintf(tmp, sizeof tmp, "%s.tmp.XXXXXX", path) >= (int)sizeof tmp) { fail(err, err_n, "history path too long"); return -1; }
+ int fd = mkstemp(tmp); if (fd < 0) { fail(err, err_n, "cannot create history temp file: %s", strerror(errno)); return -1; }
+ FILE *f = fdopen(fd, "wb"); if (!f) { close(fd); unlink(tmp); fail(err, err_n, "cannot open history temp file"); return -1; }
+ int rc = 0;
+ for (int i = 0; i < h->n && !rc; i++) {
+ const K3ChatMessage *m = &h->v[i];
+ if (fputs("{\"role\":", f) == EOF || jwrite(f, role_name(m->role)) || fputs(",\"content\":", f) == EOF || jwrite(f, m->content)) rc = -1;
+ if (!rc && m->role == K3_CHAT_ASSISTANT && m->reasoning_content) if (fputs(",\"reasoning_content\":", f) == EOF || jwrite(f, m->reasoning_content)) rc = -1;
+ if (!rc && fputs("}\n", f) == EOF) rc = -1;
+ }
+ if (!rc && fflush(f) != 0) rc = -1;
+ if (!rc && fsync(fd) != 0) rc = -1;
+ if (fclose(f) != 0) rc = -1;
+ if (!rc && rename(tmp, path) != 0) rc = -1;
+ if (rc) { unlink(tmp); fail(err, err_n, "failed atomically writing %s: %s", path, strerror(errno)); return -1; }
+ return 0;
+}
+
+/* ---- XTML segments --------------------------------------------------------- */
+void k3_chat_segments_init(K3ChatSegments *s) { memset(s, 0, sizeof *s); }
+void k3_chat_segments_free(K3ChatSegments *s)
+{
+ for (int i = 0; i < s->n; i++) free(s->v[i].text);
+ free(s->v); memset(s, 0, sizeof *s);
+}
+
+static int seg(K3ChatSegments *s, const char *text, int special, char *err, size_t err_n)
+{
+ int len = (int)strlen(text); if (!len) return 0;
+ if (s->n == s->cap) { int nc = s->cap ? s->cap * 2 : 32; K3ChatSegment *v = (K3ChatSegment *)realloc(s->v, (size_t)nc * sizeof(*v)); if (!v) { fail(err, err_n, "out of memory rendering XTML"); return -1; } s->v = v; s->cap = nc; }
+ s->v[s->n].text = dup_(text); if (!s->v[s->n].text) { fail(err, err_n, "out of memory rendering XTML"); return -1; }
+ s->v[s->n].len = len; s->v[s->n].allow_special = special; s->n++; return 0;
+}
+static int ctl(K3ChatSegments *s, const char *x, char *e, size_t n) { return seg(s, x, 1, e, n); }
+static int txt(K3ChatSegments *s, const char *x, char *e, size_t n) { return seg(s, x, 0, e, n); }
+static int open_tag(K3ChatSegments *s, const char *tag, const char *attrs, char *e, size_t n)
+{ return ctl(s, "<|open|>", e, n) || txt(s, tag, e, n) || (attrs && txt(s, attrs, e, n)) || ctl(s, "<|sep|>", e, n); }
+static int close_tag(K3ChatSegments *s, const char *tag, char *e, size_t n)
+{ return ctl(s, "<|close|>", e, n) || txt(s, tag, e, n) || ctl(s, "<|sep|>", e, n); }
+static int eom(K3ChatSegments *s, char *e, size_t n) { return ctl(s, "<|end_of_msg|>", e, n); }
+
+int k3_chat_template_init(Tok *tok, K3ChatTemplate *t, char *err, size_t err_n)
+{
+ t->open_id = tok_id_of(tok, "<|open|>"); t->close_id = tok_id_of(tok, "<|close|>");
+ t->sep_id = tok_id_of(tok, "<|sep|>"); t->eom_id = tok_id_of(tok, "<|end_of_msg|>");
+ t->eos_id = tok_id_of(tok, "[EOS]");
+ if (t->open_id < 0 || t->close_id < 0 || t->sep_id < 0 || t->eom_id < 0) {
+ fail(err, err_n, "K3 tokenizer is missing required XTML control tokens"); return -1;
+ }
+ if (t->eom_id != 163586) { fail(err, err_n, "K3 end_of_msg id is %d, expected official id 163586", t->eom_id); return -1; }
+ if (t->eos_id != 163585) { fail(err, err_n, "K3 [EOS] id is %d, expected official id 163585", t->eos_id); return -1; }
+ return 0;
+}
+
+static const char *const efforts[] = { "low", "high", "max" };
+
+K3ChatOptions k3_chat_options_default(void)
+{
+ K3ChatOptions o; o.thinking = 1; o.thinking_effort = "max"; return o;
+}
+
+int k3_chat_options_validate(const K3ChatOptions *o, char *err, size_t err_n)
+{
+ if (!o->thinking) return 0;
+ for (size_t i = 0; o->thinking_effort && i < sizeof efforts / sizeof efforts[0]; i++)
+ if (!strcmp(o->thinking_effort, efforts[i])) return 0;
+ /* The prompt text itself lists `medium`, but the checkpoint's encoder asserts on it
+ * (_VALID_THINKING_EFFORTS = {"low", "high", "max"}), so it is refused here too. */
+ fail(err, err_n, "thinking_effort must be low, high or max, got '%s'", o->thinking_effort ? o->thinking_effort : "");
+ return -1;
+}
+
+int k3_chat_render(const K3ChatHistory *h, int add_generation_prompt,
+ K3ChatSegments *out, char *err, size_t err_n)
+{
+ K3ChatOptions o = k3_chat_options_default();
+ return k3_chat_render_opts(h, add_generation_prompt, &o, out, err, err_n);
+}
+
+int k3_chat_render_opts(const K3ChatHistory *h, int add_generation_prompt,
+ const K3ChatOptions *o, K3ChatSegments *out, char *err, size_t err_n)
+{
+ /* One segment, never split around the value: the encoder renders this body as a single
+ * text piece, and BPE merges run across "=max", so a split would change the ids. */
+ char thinking[512];
+ k3_chat_segments_init(out);
+ if (k3_chat_options_validate(o, err, err_n) || k3_chat_history_validate(h, err, err_n)) return -1;
+ if (o->thinking) {
+ snprintf(thinking, sizeof thinking,
+ "`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), "
+ "supported values include `low`, `medium`, `high`, and `max`.\n"
+ "Now the system is invoked with `thinking_effort=%s`.", o->thinking_effort);
+ if (open_tag(out, "message", " role=\"system\" type=\"thinking-effort\"", err, err_n) || txt(out, thinking, err, err_n) || close_tag(out, "message", err, err_n) || eom(out, err, err_n)) goto bad;
+ }
+ for (int i = 0; i < h->n; i++) {
+ const K3ChatMessage *m = &h->v[i]; char attrs[64];
+ snprintf(attrs, sizeof attrs, " role=\"%s\"", role_name(m->role));
+ if (open_tag(out, "message", attrs, err, err_n)) goto bad;
+ if (m->role == K3_CHAT_ASSISTANT) {
+ /* With thinking off the encoder drops the think channel entirely, even when the
+ * transcript carries reasoning from an earlier thinking turn. */
+ if (o->thinking && (open_tag(out, "think", NULL, err, err_n) || txt(out, m->reasoning_content ? m->reasoning_content : "", err, err_n) || close_tag(out, "think", err, err_n))) goto bad;
+ if (open_tag(out, "response", NULL, err, err_n) || txt(out, m->content, err, err_n) || close_tag(out, "response", err, err_n)) goto bad;
+ } else if (txt(out, m->content, err, err_n)) goto bad;
+ if (close_tag(out, "message", err, err_n) || eom(out, err, err_n)) goto bad;
+ }
+ if (add_generation_prompt && (open_tag(out, "message", " role=\"assistant\"", err, err_n) || open_tag(out, o->thinking ? "think" : "response", NULL, err, err_n))) goto bad;
+ return 0;
+bad:
+ k3_chat_segments_free(out); return -1;
+}
+
+int k3_chat_segments_text(const K3ChatSegments *s, char **text_out, int *len_out, char *err, size_t err_n)
+{
+ size_t n = 0; for (int i = 0; i < s->n; i++) n += (size_t)s->v[i].len;
+ if (n > (size_t)INT32_MAX) { fail(err, err_n, "rendered XTML is too long"); return -1; }
+ char *out = (char *)malloc(n + 1); if (!out) { fail(err, err_n, "out of memory joining XTML"); return -1; }
+ size_t at = 0; for (int i = 0; i < s->n; i++) { memcpy(out + at, s->v[i].text, (size_t)s->v[i].len); at += (size_t)s->v[i].len; }
+ out[at] = 0; *text_out = out; *len_out = (int)at; return 0;
+}
+
+int k3_chat_encode(Tok *tok, const K3ChatSegments *s, int *ids, int max, char *err, size_t err_n)
+{
+ int n = 0;
+ for (int i = 0; i < s->n; i++) {
+ int room = max - n; if (room <= 0) { fail(err, err_n, "rendered XTML exceeds token buffer"); return -1; }
+ int got = tok_encode_mode(tok, s->v[i].text, s->v[i].len, ids + n, room, s->v[i].allow_special);
+ n += got;
+ }
+ return n;
+}
+
+static int ids_for(Tok *tok, const char *text, int *out)
+{ return tok_encode_mode(tok, text, (int)strlen(text), out, 64, 0); }
+static int match(const int *ids, int n, int at, const int *pat, int pn)
+{ return at + pn <= n && !memcmp(ids + at, pat, (size_t)pn * sizeof(*ids)); }
+static char *decode_ids(Tok *tok, const int *ids, int n)
+{
+ size_t cap = 1;
+ for (int i = 0; i < n; i++) {
+ if (ids[i] < 0 || ids[i] >= tok->n_ids || !tok->id2str[ids[i]]) return NULL;
+ cap += strlen(tok->id2str[ids[i]]);
+ if (cap > (size_t)INT32_MAX) return NULL;
+ }
+ char *s = (char *)malloc(cap);
+ if (!s) return NULL;
+ int got = tok_decode(tok, ids, n, s, (int)cap - 1);
+ s[got] = 0; return s;
+}
+
+int k3_chat_parse_assistant(Tok *tok, const K3ChatTemplate *t, const int *ids, int n,
+ K3ChatMessage *out, char *err, size_t err_n)
+{
+ K3ChatOptions o = k3_chat_options_default();
+ return k3_chat_parse_assistant_opts(tok, t, &o, ids, n, out, err, err_n);
+}
+
+int k3_chat_parse_assistant_opts(Tok *tok, const K3ChatTemplate *t, const K3ChatOptions *o,
+ const int *ids, int n, K3ChatMessage *out, char *err, size_t err_n)
+{
+ int think[64], response[64], message[64], a[128], z[128];
+ int nt = ids_for(tok, "think", think), nr = ids_for(tok, "response", response), nm = ids_for(tok, "message", message);
+ int na = 0, nz = 0;
+ a[na++] = t->close_id; memcpy(a + na, think, (size_t)nt * sizeof(int)); na += nt; a[na++] = t->sep_id; a[na++] = t->open_id; memcpy(a + na, response, (size_t)nr * sizeof(int)); na += nr; a[na++] = t->sep_id;
+ z[nz++] = t->close_id; memcpy(z + nz, response, (size_t)nr * sizeof(int)); nz += nr; z[nz++] = t->sep_id; z[nz++] = t->close_id; memcpy(z + nz, message, (size_t)nm * sizeof(int)); nz += nm; z[nz++] = t->sep_id;
+ /* split: end of the think payload; body: start of the response payload. With thinking
+ * off the generation prompt already opened the response channel, so both are 0. */
+ int split = 0, body = 0, end = -1;
+ if (o->thinking) {
+ split = -1;
+ for (int i = 0; i < n; i++) if (match(ids, n, i, a, na)) { split = i; break; }
+ if (split < 0) { fail(err, err_n, "assistant output has no <think> to <response> boundary"); return -1; }
+ body = split + na;
+ }
+ for (int i = body; i < n; i++) if (match(ids, n, i, z, nz)) { end = i; break; }
+ /* The closure is followed by exactly one end id, and either declared id is accepted:
+ * the released model ends its turn with [EOS], the template inserts <|end_of_msg|>. */
+ if (end < 0 || end + nz != n - 1 || (ids[n - 1] != t->eom_id && ids[n - 1] != t->eos_id)) {
+ fail(err, err_n, "assistant output is missing the official response/message closure and end id"); return -1;
+ }
+ /* Stored transcript text is re-encoded with special tokens disabled. Accepting a
+ * control id in either payload would therefore make a restart differ from the live
+ * turn, so treat it as malformed instead of silently changing the conversation. */
+ for (int i = 0; i < split; i++)
+ if (ids[i] >= 0 && ids[i] < tok->n_ids && tok->id_added[ids[i]]) {
+ fail(err, err_n, "assistant reasoning contains an unexpected control token"); return -1;
+ }
+ for (int i = body; i < end; i++)
+ if (ids[i] >= 0 && ids[i] < tok->n_ids && tok->id_added[ids[i]]) {
+ fail(err, err_n, "assistant response contains an unexpected control token"); return -1;
+ }
+ memset(out, 0, sizeof *out); out->role = K3_CHAT_ASSISTANT;
+ out->reasoning_content = o->thinking ? decode_ids(tok, ids, split) : NULL;
+ out->content = decode_ids(tok, ids + body, end - body);
+ if (!out->content || (o->thinking && !out->reasoning_content)) { k3_chat_message_free(out); fail(err, err_n, "out of memory decoding assistant output"); return -1; }
+ return 0;
+}
diff --git a/src/chat/k3_chat.h b/src/chat/k3_chat.h
new file mode 100644
index 0000000..ec39ba6
--- /dev/null
+++ b/src/chat/k3_chat.h
@@ -0,0 +1,88 @@
+/* k3_chat.h - exact Kimi K3 XTML text-chat helpers. */
+#ifndef K3_CHAT_H
+#define K3_CHAT_H
+
+#include <stddef.h>
+#include "k3_tok.h"
+
+enum { K3_CHAT_SYSTEM, K3_CHAT_USER, K3_CHAT_ASSISTANT };
+
+typedef struct {
+ int role;
+ char *content;
+ char *reasoning_content; /* assistant only; NULL means an empty think channel */
+} K3ChatMessage;
+
+typedef struct {
+ K3ChatMessage *v;
+ int n, cap;
+} K3ChatHistory;
+
+typedef struct {
+ int open_id, close_id, sep_id, eom_id;
+ int eos_id; /* tokenizer_config's [EOS]. The released checkpoint declares TWO end ids that
+ * disagree -- config.json says <|end_of_msg|> (163586), tokenizer_config.json
+ * says [EOS] (163585) -- and the model emits 163585 at the end of a turn. A
+ * turn may legitimately end with either. */
+} K3ChatTemplate;
+
+/* Rendering policy, mirroring the two switches the checkpoint's own encoder exposes
+ * (encoding_k3.build_chat_segments: `thinking`, `thinking_effort`). The defaults are
+ * what tokenization_kimi.apply_chat_template does when given nothing: thinking on with
+ * thinking_effort="max". With thinking off the encoder emits no thinking-effort system
+ * message, renders prior assistant turns with no think channel at all, and opens the
+ * response channel in the generation prompt, so the model answers directly. */
+typedef struct {
+ int thinking; /* 1: think channel + thinking-effort message; 0: response only */
+ const char *thinking_effort; /* "low", "high" or "max"; only read when thinking is 1 */
+} K3ChatOptions;
+
+K3ChatOptions k3_chat_options_default(void);
+int k3_chat_options_validate(const K3ChatOptions *o, char *err, size_t err_n);
+
+typedef struct {
+ char *text;
+ int len;
+ int allow_special;
+} K3ChatSegment;
+
+typedef struct {
+ K3ChatSegment *v;
+ int n, cap;
+} K3ChatSegments;
+
+void k3_chat_history_init(K3ChatHistory *h);
+void k3_chat_history_free(K3ChatHistory *h);
+/* Discard all turns while retaining an initial system message, if any. */
+int k3_chat_history_reset(K3ChatHistory *h, char *err, size_t err_n);
+int k3_chat_history_add(K3ChatHistory *h, int role, const char *content,
+ const char *reasoning, char *err, size_t err_n);
+int k3_chat_history_load(K3ChatHistory *h, const char *path, char *err, size_t err_n);
+int k3_chat_history_save(const K3ChatHistory *h, const char *path, char *err, size_t err_n);
+int k3_chat_history_validate(const K3ChatHistory *h, char *err, size_t err_n);
+
+int k3_chat_template_init(Tok *tok, K3ChatTemplate *tmpl, char *err, size_t err_n);
+void k3_chat_segments_init(K3ChatSegments *s);
+void k3_chat_segments_free(K3ChatSegments *s);
+int k3_chat_render(const K3ChatHistory *h, int add_generation_prompt,
+ K3ChatSegments *out, char *err, size_t err_n); /* default options */
+int k3_chat_render_opts(const K3ChatHistory *h, int add_generation_prompt,
+ const K3ChatOptions *o, K3ChatSegments *out,
+ char *err, size_t err_n);
+int k3_chat_segments_text(const K3ChatSegments *s, char **text_out, int *len_out,
+ char *err, size_t err_n);
+int k3_chat_encode(Tok *tok, const K3ChatSegments *s, int *ids, int max,
+ char *err, size_t err_n);
+
+/* Parse exactly one assistant completion after the generated channel opening: the
+ * <think> opening with thinking on, the <response> opening with thinking off, in which
+ * case reasoning_content is NULL. */
+int k3_chat_parse_assistant(Tok *tok, const K3ChatTemplate *tmpl,
+ const int *ids, int n, K3ChatMessage *out,
+ char *err, size_t err_n); /* default options */
+int k3_chat_parse_assistant_opts(Tok *tok, const K3ChatTemplate *tmpl,
+ const K3ChatOptions *o, const int *ids, int n,
+ K3ChatMessage *out, char *err, size_t err_n);
+void k3_chat_message_free(K3ChatMessage *m);
+
+#endif
diff --git a/src/chat/k3_sampler.c b/src/chat/k3_sampler.c
new file mode 100644
index 0000000..1fb38cf
--- /dev/null
+++ b/src/chat/k3_sampler.c
@@ -0,0 +1,87 @@
+/* k3_sampler.c - PCG32 plus deterministic temperature/top-p selection. */
+#include "k3_sampler.h"
+
+#include <math.h>
+#include <stdlib.h>
+
+static uint64_t splitmix64(uint64_t *x)
+{
+ *x += UINT64_C(0x9e3779b97f4a7c15);
+ uint64_t z = *x;
+ z = (z ^ (z >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);
+ z = (z ^ (z >> 27)) * UINT64_C(0x94d049bb133111eb);
+ return z ^ (z >> 31);
+}
+
+static uint32_t pcg32(K3Sampler *s)
+{
+ uint64_t old = s->state;
+ s->state = old * UINT64_C(6364136223846793005) + s->inc;
+ uint32_t x = (uint32_t)(((old >> 18) ^ old) >> 27);
+ uint32_t rot = (uint32_t)(old >> 59);
+ return (x >> rot) | (x << ((-rot) & 31));
+}
+
+static double unit(K3Sampler *s)
+{
+ /* 53 unbiased bits, so no platform PRNG or libc rand() leaks into output. */
+ uint64_t x = ((uint64_t)pcg32(s) << 21) ^ (pcg32(s) & UINT32_C(0x1fffff));
+ return (double)x * (1.0 / 9007199254740992.0);
+}
+
+void k3_sampler_init(K3Sampler *s, double temperature, double top_p,
+ 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->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;
+}
+
+void k3_sampler_free(K3Sampler *s)
+{
+ free(s->ids); free(s->prob); s->ids = NULL; s->prob = NULL; s->cap = 0;
+}
+
+static int cmp_desc(const void *aa, const void *bb, void *ctx)
+{
+ const double *p = (const double *)ctx;
+ int a = *(const int *)aa, b = *(const int *)bb;
+ if (p[a] > p[b]) return -1;
+ if (p[a] < p[b]) return 1;
+ return a < b ? -1 : a > b;
+}
+
+/* qsort_r has incompatible BSD/GNU argument order. A narrow static comparator keeps
+ * the sampler portable C99; chat uses one sampler on the foreground REPL thread. */
+static const double *sort_prob;
+static int cmp_desc_global(const void *aa, const void *bb) { return cmp_desc(aa, bb, (void *)sort_prob); }
+
+int k3_sampler_next(K3Sampler *s, const float *logits, int n, int greedy, int *out)
+{
+ if (!logits || !out || n <= 0 || !(s->temperature > 0.0) || !(s->top_p > 0.0) || s->top_p > 1.0) return -1;
+ int best = 0;
+ for (int i = 1; i < n; i++) if (logits[i] > logits[best]) best = i;
+ if (greedy) { *out = best; return 0; }
+ if (n > s->cap) {
+ int *ids = (int *)malloc((size_t)n * sizeof(*ids));
+ double *prob = (double *)malloc((size_t)n * sizeof(*prob));
+ if (!ids || !prob) { free(ids); free(prob); return -1; }
+ free(s->ids); free(s->prob);
+ s->ids = ids; s->prob = prob; s->cap = n;
+ }
+ const double max = logits[best] / s->temperature;
+ double sum = 0.0;
+ for (int i = 0; i < n; i++) { s->ids[i] = i; s->prob[i] = exp((double)logits[i] / s->temperature - max); sum += s->prob[i]; }
+ if (!(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;
+ double keep = 0.0; int nk = 0;
+ while (nk < n && 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; } }
+ return -1;
+}
diff --git a/src/chat/k3_sampler.h b/src/chat/k3_sampler.h
new file mode 100644
index 0000000..2cdc83e
--- /dev/null
+++ b/src/chat/k3_sampler.h
@@ -0,0 +1,21 @@
+/* k3_sampler.h - deterministic top-p sampling for chat only. */
+#ifndef K3_SAMPLER_H
+#define K3_SAMPLER_H
+
+#include <stdint.h>
+
+typedef struct {
+ double temperature, top_p;
+ uint64_t state, inc;
+ int *ids;
+ double *prob;
+ int cap;
+} K3Sampler;
+
+void k3_sampler_init(K3Sampler *s, double temperature, double top_p,
+ uint64_t seed, uint64_t turn);
+void k3_sampler_free(K3Sampler *s);
+int k3_sampler_next(K3Sampler *s, const float *logits, int n_vocab,
+ int greedy, int *token_out);
+
+#endif
diff --git a/src/cli/k3_run.c b/src/cli/k3_run.c
index 849712a..1c0e63a 100644
--- a/src/cli/k3_run.c
+++ b/src/cli/k3_run.c
@@ -45,6 +45,8 @@
#endif
#include <math.h>
+#include <errno.h>
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -57,11 +59,14 @@
#include <sys/resource.h>
#endif
+#include "k3_portable_io.h" /* getline() shim for MinGW; see the header for why */
#include "k3.h"
#include "k3_bind.h"
#include "k3_cache.h"
#include "k3_trunk.h"
#include "k3_tok.h" /* text in/out; the --ids path never touches it */
+#include "k3_chat.h"
+#include "k3_sampler.h"
#include "k3_cfg.h" /* read the checkpoint's own config rather than assuming it */
static double now_s(void)
@@ -390,6 +395,18 @@ static void usage(FILE *f)
" streams, so repetitive text decodes up to several times faster\n"
" --tok DIR directory with tiktoken.model and tokenizer_config.json\n"
"\n"
+"chat (text-only Kimi K3 XTML):\n"
+" --chat terminal REPL; uses the official XTML template\n"
+" --system TEXT initial system message (stored in --history)\n"
+" --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"
+" --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"
+" --thinking-effort E low, high or max (default max, as the checkpoint's tokenizer sets)\n"
+"\n"
"diagnostics:\n"
" --config PATH model config; defaults to <model_dir>/config.json\n"
" --layers N bind only the first N layers (partial shard sets)\n"
@@ -661,6 +678,188 @@ static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, i
return 0;
}
+/* ----------------------------------------------------------------------- chat ----
+ * Chat deliberately owns only transcript and decode policy. It calls the exact same
+ * forward() and streamed K3Cache as batch mode, so --preset/--trunk-gb/--cache-gb keep
+ * their meanings. The first version re-prefills the full transcript for every REPL
+ * turn; retaining a live suffix is enabled only after its equivalence gate exists. */
+static int chat_read_line(char **out)
+{
+ char *line = NULL; size_t cap = 0;
+ printf("user> "); fflush(stdout);
+ if (getline(&line, &cap, stdin) < 0) { free(line); return 0; }
+ size_t n = strlen(line);
+ while (n && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = 0;
+ *out = line; return 1;
+}
+
+static int chat_render_ids(Tok *tok, const K3ChatHistory *history, const K3ChatOptions *opts,
+ int **ids_out, int *n_out, char *err, size_t err_n)
+{
+ K3ChatSegments segs;
+ if (k3_chat_render_opts(history, 1, opts, &segs, err, err_n) != 0) return -1;
+ /* One sentinel slot distinguishes a prompt exactly at the engine limit from one
+ * that the tokenizer would otherwise silently truncate. */
+ int *ids = (int *)malloc((size_t)(K3_MAX_PROMPT + 1) * sizeof(*ids));
+ if (!ids) { k3_chat_segments_free(&segs); snprintf(err, err_n, "OOM allocating chat prompt"); return -1; }
+ int n = k3_chat_encode(tok, &segs, ids, K3_MAX_PROMPT + 1, err, err_n);
+ k3_chat_segments_free(&segs);
+ if (n <= 0 || n > K3_MAX_PROMPT) {
+ free(ids);
+ if (n == 0) snprintf(err, err_n, "rendered chat prompt has no tokens");
+ else if (n > K3_MAX_PROMPT) snprintf(err, err_n, "rendered chat prompt exceeds the %d-token engine context limit", K3_MAX_PROMPT);
+ return -1;
+ }
+ *ids_out = ids; *n_out = n; return 0;
+}
+
+static int chat_resize(int want, int *tmax, int nl, int maxb, size_t kper,
+ Weights *w, const K3Cfg *c,
+ float **h, float **br, float **sc, int **seq)
+{
+ if (want <= *tmax) return 0;
+ const int E = c->hidden;
+ size_t sc_need = k3_layer_scratch(c, want);
+ size_t inc_need = k3_mla_scratch_cached(c, want, want, 1);
+ if (inc_need > sc_need) sc_need = inc_need;
+ float *nh = (float *)malloc((size_t)want * E * sizeof(*nh));
+ float *nb = (float *)malloc((size_t)want * maxb * E * sizeof(*nb));
+ float *ns = (float *)malloc(sc_need * sizeof(*ns));
+ int *nq = (int *)malloc((size_t)(want + 8) * sizeof(*nq));
+ float *nk = NULL, *nr = NULL;
+ if (w->kvc) {
+ const size_t kvper = (size_t)want * c->n_heads * (c->qk_nope + c->v_head);
+ const size_t rpper = (size_t)want * c->qk_rope;
+ nk = (float *)calloc(kvper * (size_t)w->n_mla, sizeof(*nk));
+ nr = (float *)calloc(rpper * (size_t)w->n_mla, sizeof(*nr));
+ }
+ if (!nh || !nb || !ns || !nq || (w->kvc && (!nk || !nr))) {
+ free(nh); free(nb); free(ns); free(nq); free(nk); free(nr);
+ fprintf(stderr, "chat: buffer allocation failed for %d positions\n", want); return -1;
+ }
+ free(*h); free(*br); free(*sc); free(*seq);
+ *h = nh; *br = nb; *sc = ns; *seq = nq;
+ if (w->kvc) { free(w->kvc); free(w->ropec); w->kvc = nk; w->ropec = nr; w->kv_cap = want; }
+ *tmax = want;
+ (void)nl; (void)kper;
+ return 0;
+}
+
+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 nl, int *tmax, float **h, float **br, float *ks,
+ float **sc, float *lg, int **seq, int *outtok, int maxb, size_t kper)
+{
+ char err[512]; int turn = 0;
+ int *prompt = *prompt_ref;
+ for (int i = 0; i < history->n; i++) if (history->v[i].role == K3_CHAT_ASSISTANT) turn++;
+ for (;;) {
+ const int need = np + gen + 1;
+ if (np > K3_MAX_PROMPT || need > K3_MAX_PROMPT + K3_MAX_GEN) {
+ fprintf(stderr, "chat: rendered transcript is %d tokens; current engine limit is %d prompt + %d generation tokens\n", np, K3_MAX_PROMPT, K3_MAX_GEN);
+ return 1;
+ }
+ if (incremental) {
+ const double kv_need = (double)need * K3_KV_BYTES_PER_POS;
+ const double avail = mem_available_bytes();
+ if (avail > 0.0 && kv_need > avail * 0.9) {
+ char kb[32], ab[32];
+ human(kv_need, kb, sizeof kb); human(avail, ab, sizeof ab);
+ fprintf(stderr, "chat: KV cache for %d positions needs %s, but only %s is available; history was preserved\n", need, kb, ab);
+ return 1;
+ }
+ }
+ if (chat_resize(need, tmax, nl, maxb, kper, w, c, h, br, sc, seq) != 0) return 1;
+ memcpy(*seq, prompt, (size_t)np * sizeof(**seq));
+ memset(ks, 0, kper * (size_t)nl * sizeof(*ks));
+ if (incremental) {
+ 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;
+ memset(w->kvc, 0, kvper * (size_t)w->n_mla * sizeof(*w->kvc));
+ memset(w->ropec, 0, rpper * (size_t)w->n_mla * sizeof(*w->ropec));
+ }
+ w->cached = 0;
+ int T = np, nraw = 0, frc = 0;
+ K3Sampler sampler; k3_sampler_init(&sampler, temperature, top_p, seed, (uint64_t)(turn + 1));
+ const double t_turn0 = now_s();
+ while (nraw < gen) {
+ if (incremental) {
+ if (!nraw) {
+ frc = forward(w, c, cache, *seq, T, lg, *sc, *h, *br, ks, NULL);
+ if (!frc) w->cached = T;
+ } else {
+ frc = forward(w, c, cache, *seq + T - 1, 1, lg, *sc, *h, *br, ks, NULL);
+ if (!frc) w->cached++;
+ }
+ } else {
+ frc = forward(w, c, cache, *seq, T, lg, *sc, *h, *br, ks, NULL);
+ }
+ if (frc) break;
+ int next = 0;
+ if (k3_sampler_next(&sampler, lg, c->vocab, greedy, &next) != 0) {
+ fprintf(stderr, "chat: sampler failed\n"); frc = -1; break;
+ }
+ (*seq)[T++] = next; outtok[nraw++] = next;
+ /* One line per token on stderr, unbuffered. At the speeds a streamed trunk
+ * runs at (a minute or two per token), a REPL that prints nothing until the
+ * turn is complete is indistinguishable from a hung one, and a turn cut off
+ * by --gen or a timeout would otherwise leave no record of how far it got. */
+ fprintf(stderr, "chat: token %d/%d id %d (%.0f s)\n", nraw, gen, next, now_s() - t_turn0);
+ if (next == tmpl->eom_id || next == tmpl->eos_id) {
+ printf("chat: turn ended by %s (%d)\n", next == tmpl->eom_id ? "<|end_of_msg|>" : "[EOS]", next);
+ break;
+ }
+ }
+ k3_sampler_free(&sampler);
+ if (frc || (nraw == gen && outtok[nraw - 1] != tmpl->eom_id && outtok[nraw - 1] != tmpl->eos_id)) {
+ fprintf(stderr, "chat: assistant did not complete an official turn within --gen %d; transcript is preserved\n", gen);
+ return 1;
+ }
+ K3ChatMessage assistant;
+ if (k3_chat_parse_assistant_opts(tok, tmpl, opts, outtok, nraw, &assistant, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: malformed assistant turn: %s\n", err); return 1;
+ }
+ if (assistant.reasoning_content) printf("<think>%s</think>\n", assistant.reasoning_content);
+ printf("<response>%s</response>\n", assistant.content);
+ if (k3_chat_history_add(history, K3_CHAT_ASSISTANT, assistant.content,
+ assistant.reasoning_content, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); k3_chat_message_free(&assistant); return 1;
+ }
+ k3_chat_message_free(&assistant); turn++;
+ if (history_path && k3_chat_history_save(history, history_path, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 1;
+ }
+
+ for (;;) {
+ char *line = NULL;
+ if (!chat_read_line(&line)) return 0;
+ if (!strcmp(line, "/exit")) { free(line); return 0; }
+ if (!strcmp(line, "/help")) { printf("/help show commands\n/reset clear this conversation\n/exit leave chat\n"); free(line); continue; }
+ if (!strcmp(line, "/reset")) {
+ if (k3_chat_history_reset(history, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); free(line); return 1;
+ }
+ if (history_path && k3_chat_history_save(history, history_path, err, sizeof err)) { fprintf(stderr, "chat: %s\n", err); return 1; }
+ printf("chat reset\n"); free(line); continue;
+ }
+ if (!*line) { free(line); continue; }
+ if (k3_chat_history_add(history, K3_CHAT_USER, line, NULL, err, sizeof err)) { fprintf(stderr, "chat: %s\n", err); free(line); return 1; }
+ free(line);
+ int *new_prompt = NULL, new_np = 0;
+ if (chat_render_ids(tok, history, opts, &new_prompt, &new_np, err, sizeof err) != 0 || new_np > K3_MAX_PROMPT) {
+ if (new_prompt) free(new_prompt);
+ k3_chat_message_free(&history->v[--history->n]);
+ fprintf(stderr, "chat: %s\n", new_np > K3_MAX_PROMPT ? "context limit reached; history was not changed" : err);
+ continue;
+ }
+ if (history_path && k3_chat_history_save(history, history_path, err, sizeof err)) { free(new_prompt); fprintf(stderr, "chat: %s\n", err); return 1; }
+ free(prompt); prompt = new_prompt; *prompt_ref = prompt; np = new_np; break;
+ }
+ }
+}
+
int main(int argc, char **argv)
{
/* Informational flags are answered before anything else, because they must work
@@ -686,8 +885,9 @@ int main(int argc, char **argv)
const char *trace_dir = NULL;
const char *logits_path = NULL;
const char *prompt_text = NULL, *prompt_file = NULL, *tok_dir = NULL;
+ const char *system_text = NULL, *history_path = NULL;
const char *cfg_path = NULL;
- int gen = 8, want_layers = -1;
+ int gen = 8, want_layers = -1, gen_set = 0;
/* --stop-id, repeatable. Generation halts AFTER emitting a listed id, so the state
* written by --save-state still contains it and a later --load-state continues the
* sequence the model actually produced. Without this the engine always runs to
@@ -702,15 +902,20 @@ 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, ultra = 0;
+ int incremental = 0, ultra = 0, chat = 0, greedy = 0;
int trunk_ring = 0; /* 0 selects k3_trunk_open's default of 2 */
+ 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;
+ double temperature = 1.0, top_p = 0.95;
+ uint64_t seed = 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];
else if (!strcmp(argv[i], "--prompt-file") && i + 1 < argc) prompt_file = argv[++i];
else if (!strcmp(argv[i], "--tok") && i + 1 < argc) tok_dir = argv[++i];
else if (!strcmp(argv[i], "--config") && i + 1 < argc) cfg_path = argv[++i];
- else if (!strcmp(argv[i], "--gen") && i + 1 < argc) gen = atoi(argv[++i]);
+ else if (!strcmp(argv[i], "--gen") && i + 1 < argc) { gen = atoi(argv[++i]); gen_set = 1; }
else if (!strcmp(argv[i], "--stop-id") && i + 1 < argc) {
if (n_stop >= (int)(sizeof stop_id / sizeof stop_id[0])) {
fprintf(stderr, "--stop-id given more than %d times\n",
@@ -734,7 +939,7 @@ int main(int argc, char **argv)
}
else if (!strcmp(argv[i], "--cache-gb") && i + 1 < argc) cache_gb = atof(argv[++i]);
else if (!strcmp(argv[i], "--layers") && i + 1 < argc) want_layers = atoi(argv[++i]);
- else if (!strcmp(argv[i], "--out") && i + 1 < argc) outp = argv[++i];
+ else if (!strcmp(argv[i], "--out") && i + 1 < argc) { outp = argv[++i]; out_set = 1; }
else if (!strcmp(argv[i], "--trunk") && i + 1 < argc) trunk_dir = argv[++i];
else if (!strcmp(argv[i], "--spec") && i + 1 < argc) spec_n = atoi(argv[++i]);
else if (!strcmp(argv[i], "--tf-check")) tf_check = 1;
@@ -750,6 +955,21 @@ int main(int argc, char **argv)
else if (!strcmp(argv[i], "--trunk-ring") && i + 1 < argc) trunk_ring = atoi(argv[++i]);
else if (!strcmp(argv[i], "--incremental")) incremental = 1;
else if (!strcmp(argv[i], "--ultra-low-memory")) ultra = 1;
+ else if (!strcmp(argv[i], "--chat")) chat = 1;
+ else if (!strcmp(argv[i], "--system") && i + 1 < argc) system_text = argv[++i];
+ else if (!strcmp(argv[i], "--history") && i + 1 < argc) history_path = argv[++i];
+ else if (!strcmp(argv[i], "--temperature") && i + 1 < argc) { temperature = atof(argv[++i]); temperature_set = 1; }
+ else if (!strcmp(argv[i], "--top-p") && i + 1 < argc) { top_p = atof(argv[++i]); top_p_set = 1; }
+ else if (!strcmp(argv[i], "--seed") && i + 1 < argc) {
+ const char *value = argv[++i];
+ char *end = NULL;
+ errno = 0; seed = strtoull(value, &end, 10);
+ if (value[0] == '-' || errno || !end || *end) { fprintf(stderr, "--seed needs an unsigned integer\n"); return 2; }
+ seed_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; }
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")) {
@@ -799,9 +1019,28 @@ int main(int argc, char **argv)
"use deterministic serial decode\n");
return 2;
}
+ if (chat && !gen_set) gen = K3_MAX_GEN;
+ if ((no_think || effort_set) && !chat) {
+ fprintf(stderr, "%s only applies to --chat\n", no_think ? "--no-think" : "--thinking-effort");
+ return 2;
+ }
+ if (no_think && effort_set) {
+ /* The encoder silently ignores thinking_effort once thinking is off. A CLI that did
+ * the same would run a very long prompt under a setting the user never got. */
+ fprintf(stderr, "--no-think and --thinking-effort contradict each other; pass one of them\n");
+ return 2;
+ }
+ if (chat) {
+ char oerr[256];
+ if (k3_chat_options_validate(&chat_opts, oerr, sizeof oerr) != 0) { fprintf(stderr, "--thinking-effort: %s\n", oerr); return 2; }
+ }
{
int nsrc = (ids_s != NULL) + (prompt_text != NULL) + (prompt_file != NULL);
- if (nsrc == 0) {
+ if (chat && nsrc) {
+ fprintf(stderr, "--chat supplies its prompt through the REPL/history; do not also pass --ids, --prompt, or --prompt-file\n");
+ return 2;
+ }
+ if (!chat && nsrc == 0) {
fprintf(stderr, "one of --ids, --prompt or --prompt-file is required\n");
return 2;
}
@@ -812,6 +1051,39 @@ int main(int argc, char **argv)
return 2;
}
}
+ if (chat) {
+ if (!tok_dir) {
+ fprintf(stderr, "--chat needs --tok DIR with the official Kimi K3 tokenizer files\n");
+ return 2;
+ }
+ if (load_state || save_state || draft_dir || spec_n || tf_check || logits_path || trace_dir || out_set) {
+ fprintf(stderr, "--chat cannot be combined with state files, speculative/draft modes, diagnostics, or --out\n");
+ return 2;
+ }
+ if (!(temperature > 0.0) || !isfinite(temperature) || !(top_p > 0.0) || top_p > 1.0 || !isfinite(top_p)) {
+ fprintf(stderr, "--temperature must be finite and > 0; --top-p must be in (0, 1]\n");
+ return 2;
+ }
+ if (gen <= 0) {
+ 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");
+ return 2;
+ }
+ /* Greedy unless a sampling flag was given. Greedy decoding is what makes output
+ * identical across memory budgets, which the test suite depends on, so sampling
+ * is opt-in here exactly as docs/ROADMAP.md says it must be; a chat REPL that
+ * 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 (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. */
+ seed = (uint64_t)time(NULL) ^ ((uint64_t)(uintptr_t)&seed << 16);
+ }
/* ---- auto budget ----
* RAM-first: per token the engine re-reads the ENTIRE streamed trunk but only
@@ -897,44 +1169,113 @@ int main(int argc, char **argv)
}
/* ---- prompt ----
- * Three entry points, one representation. --ids is the reproducible channel every
- * fixture and the oracle use, and stays the default for validation work. --prompt /
- * --prompt-file tokenize here in C, which is what makes the engine text-in/text-out
- * without a Python step. The tokenizer is loaded ONLY when actually needed, so the
- * id path keeps working on a box that has no tokenizer files at all. */
- /* 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 memory
- * limit. */
- int *prompt = (int *)malloc((size_t)K3_MAX_PROMPT * sizeof(int));
- if (!prompt) { fprintf(stderr, "OOM allocating prompt buffer\n"); return 2; }
+ * Batch keeps its historical three input channels. Chat has one more explicit
+ * representation: transcript records are rendered with the official XTML segment
+ * encoder, never by treating a generic template string as a prompt. */
+ int *prompt = NULL;
int np = 0;
Tok tok; int have_tok = 0;
+ K3ChatHistory chat_history;
+ K3ChatTemplate chat_template;
+ k3_chat_history_init(&chat_history);
- if (prompt_text || prompt_file) {
- if (!tok_dir) {
- fprintf(stderr, "--prompt/--prompt-file need --tok DIR (the directory with "
- "tiktoken.model and tokenizer_config.json)\n");
- return 2;
- }
+ if (chat) {
+ char err[512];
k3_tok_load(&tok, tok_dir);
have_tok = 1;
+ if (k3_chat_template_init(&tok, &chat_template, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 2;
+ }
+ if (history_path && k3_chat_history_load(&chat_history, history_path, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 2;
+ }
+ if (system_text) {
+ if (chat_history.n) {
+ if (chat_history.v[0].role != K3_CHAT_SYSTEM || strcmp(chat_history.v[0].content, system_text)) {
+ fprintf(stderr, "chat: --system does not match the initial system record in %s\n", history_path ? history_path : "history");
+ return 2;
+ }
+ } else if (k3_chat_history_add(&chat_history, K3_CHAT_SYSTEM, system_text, NULL, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 2;
+ }
+ }
+ /* Persist a supplied system record immediately. It is part of the portable
+ * conversation contract even if the user exits before asking a first question. */
+ if (history_path && k3_chat_history_save(&chat_history, history_path, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 2;
+ }
- char *ptext = NULL; long plen = 0;
- if (prompt_file) {
- ptext = tk_read_file(prompt_file, &plen); /* exits if unreadable */
- } else {
- plen = (long)strlen(prompt_text);
- ptext = (char *)malloc((size_t)plen + 1);
- if (!ptext) { fprintf(stderr, "OOM on prompt\n"); return 2; }
- memcpy(ptext, prompt_text, (size_t)plen + 1);
- }
- np = tok_encode(&tok, ptext, (int)plen, prompt, K3_MAX_PROMPT);
- free(ptext);
- printf(" tokenized: %ld bytes -> %d ids\n", plen, np);
+ /* A transcript ending in a user turn can be resumed after an interrupted run.
+ * Otherwise read exactly one fresh user turn before the expensive model setup,
+ * so the buffers and KV plan are sized from the real rendered prompt. */
+ while (!chat_history.n || chat_history.v[chat_history.n - 1].role != K3_CHAT_USER) {
+ char *line = NULL;
+ if (!chat_read_line(&line)) { k3_chat_history_free(&chat_history); return 0; }
+ if (!strcmp(line, "/exit")) { free(line); k3_chat_history_free(&chat_history); return 0; }
+ if (!strcmp(line, "/help")) {
+ printf("/help show commands\n/reset clear this conversation\n/exit leave chat\n");
+ free(line); continue;
+ }
+ if (!strcmp(line, "/reset")) {
+ if (k3_chat_history_reset(&chat_history, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); free(line); return 2;
+ }
+ if (history_path && k3_chat_history_save(&chat_history, history_path, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 2;
+ }
+ printf("chat reset\n"); free(line); continue;
+ }
+ if (!*line) { free(line); continue; }
+ if (k3_chat_history_add(&chat_history, K3_CHAT_USER, line, NULL, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); free(line); return 2;
+ }
+ free(line);
+ break;
+ }
+ if (chat_render_ids(&tok, &chat_history, &chat_opts, &prompt, &np, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 2;
+ }
+ if (history_path && k3_chat_history_save(&chat_history, history_path, err, sizeof err) != 0) {
+ fprintf(stderr, "chat: %s\n", err); return 2;
+ }
+ printf(" XTML prompt: %d ids, generation limit %d, %s, %s%s\n", np, gen,
+ 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);
} else {
- for (const char *p = ids_s; *p && np < K3_MAX_PROMPT; ) {
- prompt[np++] = (int)strtol(p, (char **)&p, 10);
- while (*p == ',' || *p == ' ') p++;
+ /* 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
+ * memory limit. */
+ prompt = (int *)malloc((size_t)K3_MAX_PROMPT * sizeof(int));
+ if (!prompt) { fprintf(stderr, "OOM allocating prompt buffer\n"); return 2; }
+ if (prompt_text || prompt_file) {
+ if (!tok_dir) {
+ fprintf(stderr, "--prompt/--prompt-file need --tok DIR (the directory with "
+ "tiktoken.model and tokenizer_config.json)\n");
+ return 2;
+ }
+ k3_tok_load(&tok, tok_dir);
+ have_tok = 1;
+
+ char *ptext = NULL; long plen = 0;
+ if (prompt_file) {
+ ptext = tk_read_file(prompt_file, &plen); /* exits if unreadable */
+ } else {
+ plen = (long)strlen(prompt_text);
+ ptext = (char *)malloc((size_t)plen + 1);
+ if (!ptext) { fprintf(stderr, "OOM on prompt\n"); return 2; }
+ memcpy(ptext, prompt_text, (size_t)plen + 1);
+ }
+ np = tok_encode(&tok, ptext, (int)plen, prompt, K3_MAX_PROMPT);
+ free(ptext);
+ printf(" tokenized: %ld bytes -> %d ids\n", plen, np);
+ } else {
+ for (const char *p = ids_s; *p && np < K3_MAX_PROMPT; ) {
+ prompt[np++] = (int)strtol(p, (char **)&p, 10);
+ while (*p == ',' || *p == ' ') p++;
+ }
}
}
if (np == 0) { fprintf(stderr, "no prompt ids parsed\n"); return 2; }
@@ -1176,7 +1517,7 @@ int main(int argc, char **argv)
prior = shd.nseq;
printf("resuming from %s: %d prior positions, %d new\n\n", load_state, prior, np);
}
- const int Tmax = prior + np + gen + 1;
+ int Tmax = prior + np + gen + 1;
const int E = c.hidden;
const int maxb = c.n_layers / c.attn_res_block + 2;
const int P = c.kda_heads * c.kda_head_dim;
@@ -1266,6 +1607,25 @@ 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,
+ &sc, lg, &seq, outtok, maxb, kper);
+ free(w.kvc); free(w.ropec); free(w.mla_slot);
+ if (w.trunk) k3_trunk_close(w.trunk);
+ k3_cache_free(&cache);
+ for (int L = 0; L < w.n_bound; L++) k3_bind_free(&w.lay[L]);
+ free(w.lay); k3_bind_model_free(&w.mb); k3_st_close(&st);
+ free(h); free(br); free(ks); free(sc); free(lg); free(seq); free(outtok);
+ free(prompt); k3_chat_history_free(&chat_history);
+ if (k3_expert_drops) {
+ fprintf(stderr, "chat invalid: %ld routed expert load(s) failed; the transcript was preserved\n", k3_expert_drops);
+ return 4;
+ }
+ return rc;
+ }
+
/* --spec needs a snapshot of the carried KDA/ShortConv state to roll back a
* partially-rejected draft batch: the recurrent state is updated in place and is
* not positional, so the only sound recovery is restore-and-replay the accepted
diff --git a/src/io/k3_portable_io.h b/src/io/k3_portable_io.h
index 0516be8..80159f8 100644
--- a/src/io/k3_portable_io.h
+++ b/src/io/k3_portable_io.h
@@ -29,6 +29,22 @@
* _aligned_malloc, which takes its (size, align) arguments in the
* opposite order.
*
+ * getline POSIX.1-2008 line reader used by the chat REPL. Native on Linux and
+ * Darwin; absent from the MinGW runtime. Windows gets a small
+ * fgetc-based implementation with the same contract: it grows *lineptr
+ * with realloc, keeps the delimiter, and returns -1 on EOF with nothing
+ * read, so the REPL's `< 0` check ends the session the same way on
+ * every platform.
+ *
+ * fsync durability barrier the chat history writer uses before its atomic
+ * rename. Native on Linux and Darwin; Windows spells the same thing
+ * _commit(), which flushes the OS buffers for one CRT descriptor.
+ *
+ * rename the atomic replace itself. POSIX rename() overwrites an existing
+ * destination; the CRT's does not, so every history save after the
+ * first failed on Windows. Windows gets MoveFileEx with
+ * MOVEFILE_REPLACE_EXISTING, which has the POSIX semantics.
+ *
* All four call sites fall back to buffered reads (or, for pread/posix_memalign, have
* no fallback because the shim IS the implementation) when the direct path is
* unavailable, so none of this changes what the engine computes, only how fast it
@@ -89,6 +105,7 @@ static inline int k3_set_direct(int fd)
#include <windows.h>
#include <io.h>
#include <errno.h>
+#include <stdio.h> /* FILE, fgetc: k3_getline below */
#include <stdlib.h>
#include <string.h>
@@ -190,6 +207,62 @@ static inline int posix_memalign(void **out, size_t align, size_t len)
* correctly on every platform without special-casing Windows at the call site itself. */
#define k3_aligned_free(p) _aligned_free(p)
+/* getline(3) for MinGW, which ships no such symbol. Same contract as POSIX: *lineptr and
+ * *n describe a caller-owned buffer that this function may grow with realloc; the
+ * delimiter is kept; the return is the number of bytes read, or -1 at EOF with nothing
+ * read or on allocation failure. fgetc rather than fgets so an embedded NUL in the line
+ * cannot silently truncate the count. */
+static inline long long k3_getline(char **lineptr, size_t *n, FILE *stream)
+{
+ if (!lineptr || !n || !stream) { errno = EINVAL; return -1; }
+ if (!*lineptr || *n == 0) {
+ *n = 128;
+ *lineptr = (char *)malloc(*n);
+ if (!*lineptr) { errno = ENOMEM; return -1; }
+ }
+ size_t len = 0;
+ int c;
+ while ((c = fgetc(stream)) != EOF) {
+ if (len + 2 > *n) {
+ size_t cap = *n * 2;
+ char *grown = (char *)realloc(*lineptr, cap);
+ if (!grown) { errno = ENOMEM; return -1; }
+ *lineptr = grown; *n = cap;
+ }
+ (*lineptr)[len++] = (char)c;
+ if (c == '\n') break;
+ }
+ if (len == 0 && c == EOF) return -1;
+ (*lineptr)[len] = '\0';
+ return (long long)len;
+}
+#define getline(lineptr, n, stream) k3_getline((lineptr), (n), (stream))
+
+/* fsync(2) for MinGW: _commit() flushes the OS write buffers for one CRT descriptor,
+ * which is the durability barrier the caller wants before its atomic rename. */
+#define fsync(fd) _commit(fd)
+
+/* rename(2) for MinGW. POSIX rename replaces an existing destination atomically, and
+ * the chat history writer depends on exactly that: every save after the first renames
+ * a fresh temp file over the transcript it is replacing. The CRT's rename() is
+ * MoveFile(), which refuses an existing destination with EEXIST, so on Windows the
+ * second save of a session failed and the transcript was never updated (caught by
+ * test_chat's "atomic JSONL history write", whose destination pre-exists). MoveFileEx
+ * with MOVEFILE_REPLACE_EXISTING is the documented replace-in-place, and
+ * MOVEFILE_WRITE_THROUGH makes it return only once the change is on disk, which is
+ * the same durability the fsync above bought for the data. */
+static inline int k3_win_rename(const char *from, const char *to)
+{
+ if (MoveFileExA(from, to, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) return 0;
+ switch (GetLastError()) {
+ case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: errno = ENOENT; break;
+ case ERROR_ACCESS_DENIED: case ERROR_SHARING_VIOLATION: errno = EACCES; break;
+ default: errno = EIO; break;
+ }
+ return -1;
+}
+#define rename(from, to) k3_win_rename((from), (to))
+
/* madvise(MADV_HUGEPAGE) is a Linux transparent-hugepage hint; every caller already
* treats it as advisory ("failure is not an error" -- k3_trunk.c), so a no-op is the
* correct port here, not a functional gap. The alternative, VirtualAlloc with
diff --git a/src/tokenizer/k3_tok.h b/src/tokenizer/k3_tok.h
index 79f197f..ad4ad5f 100644
--- a/src/tokenizer/k3_tok.h
+++ b/src/tokenizer/k3_tok.h
@@ -44,6 +44,7 @@
#define K3_TOK_H
#include <stdio.h>
+#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "json.h"
@@ -78,13 +79,17 @@ static inline int k3_b64(const char *in, int n, unsigned char *out)
for (int i = 0; i < 64; i++) t[(unsigned char)A[i]] = (signed char)i;
init = 1;
}
- int o = 0, acc = 0, bits = 0;
+ int o = 0, bits = 0;
+ uint32_t acc = 0;
for (int i = 0; i < n; i++) {
unsigned char c = (unsigned char)in[i];
if (c == '=') break;
signed char v = t[c];
if (v < 0) return -1;
- acc = (acc << 6) | v;
+ /* Keeping the low bits in an unsigned accumulator is intentional: groups are
+ * decoded continuously and only the pending low `bits` are observed. Signed
+ * overflow here was undefined behaviour on long tokenizer lines. */
+ acc = (acc << 6) | (uint32_t)v;
bits += 6;
if (bits >= 8) { bits -= 8; out[o++] = (unsigned char)((acc >> bits) & 0xFF); }
}
diff --git a/tests/unit/test_chat.c b/tests/unit/test_chat.c
new file mode 100644
index 0000000..0e4b3ac
--- /dev/null
+++ b/tests/unit/test_chat.c
@@ -0,0 +1,254 @@
+/* test_chat.c - weightless Kimi K3 XTML, transcript, parser, and sampler gates. */
+#define _POSIX_C_SOURCE 200809L
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "k3_chat.h"
+#include "k3_sampler.h"
+
+static int fails;
+
+static void ok(int cond, const char *what)
+{
+ if (cond) printf(" ok %s\n", what);
+ else { printf(" FAIL %s\n", what); fails++; }
+}
+
+static void expect_text(const char *got, const char *want, const char *what)
+{
+ if (!strcmp(got, want)) ok(1, what);
+ else { ok(0, what); fprintf(stderr, "want: %s\ngot : %s\n", want, got); }
+}
+
+static void emit_ids(const int *ids, int n)
+{
+ for (int i = 0; i < n; i++) printf("%s%d", i ? "," : "", ids[i]);
+ printf("\n");
+}
+
+int main(int argc, char **argv)
+{
+ if (argc < 2) { fprintf(stderr, "usage: test_chat <tokenizer-dir> [--emit]\n"); return 2; }
+ Tok tok; k3_tok_load(&tok, argv[1]);
+ K3ChatTemplate tmpl; char err[512];
+ if (k3_chat_template_init(&tok, &tmpl, err, sizeof err)) { fprintf(stderr, "%s\n", err); return 1; }
+ ok(tmpl.open_id == 163587 && tmpl.close_id == 163588 && tmpl.sep_id == 163589 && tmpl.eom_id == 163586,
+ "official control-token ids");
+
+ K3ChatHistory h; k3_chat_history_init(&h);
+ if (k3_chat_history_add(&h, K3_CHAT_SYSTEM, "You are helpful.", NULL, err, sizeof err) ||
+ k3_chat_history_add(&h, K3_CHAT_USER, "Hello", NULL, err, sizeof err)) {
+ fprintf(stderr, "%s\n", err); return 1;
+ }
+ K3ChatSegments segs;
+ if (k3_chat_render(&h, 1, &segs, err, sizeof err)) { fprintf(stderr, "%s\n", err); return 1; }
+ char *rendered = NULL; int rendered_n = 0;
+ if (k3_chat_segments_text(&segs, &rendered, &rendered_n, err, sizeof err)) { fprintf(stderr, "%s\n", err); return 1; }
+ static const char WANT[] =
+ "<|open|>message role=\"system\" type=\"thinking-effort\"<|sep|>"
+ "`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), supported values include `low`, `medium`, `high`, and `max`.\n"
+ "Now the system is invoked with `thinking_effort=max`."
+ "<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"system\"<|sep|>You are helpful.<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"user\"<|sep|>Hello<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"assistant\"<|sep|><|open|>think<|sep|>";
+ expect_text(rendered, WANT, "official system/user generation-prompt bytes");
+ static int ids[4096];
+ int ni = k3_chat_encode(&tok, &segs, ids, 4096, err, sizeof err);
+ ok(ni > 0 && ids[0] == 163587 && ids[ni - 1] == 163589, "XTML token stream has exact control boundaries");
+ static const int WANT_IDS[] = {
+ 163587,2778,6244,878,14062,1,1798,878,130400,59991,470,1,163589,63,130400,
+ 123074,470,63,28560,418,1632,2455,308,2704,306,651,9545,8491,347,2976,3411,
+ 276,4503,8491,904,9141,4661,3867,1268,1332,5713,1268,50004,5713,1268,19421,
+ 5713,316,1268,5354,16518,10048,276,2403,387,42070,472,1268,130400,123074,470,
+ 105281,11369,163588,2778,163589,163586,163587,2778,6244,878,14062,1,163589,
+ 3900,554,13205,13,163588,2778,163589,163586,163587,2778,6244,878,2482,1,
+ 163589,19180,163588,2778,163589,163586,163587,2778,6244,878,69702,1,163589,
+ 163587,39964,163589
+ };
+ ok(ni == (int)(sizeof WANT_IDS / sizeof WANT_IDS[0]) &&
+ !memcmp(ids, WANT_IDS, sizeof WANT_IDS), "official system/user XTML token ids");
+ if (argc > 2 && !strcmp(argv[2], "--emit")) emit_ids(ids, ni);
+
+ K3ChatHistory two; k3_chat_history_init(&two);
+ k3_chat_history_add(&two, K3_CHAT_USER, "Numbers?", NULL, err, sizeof err);
+ k3_chat_history_add(&two, K3_CHAT_ASSISTANT, "473, 921, 235", "I'll remember 215 and 222.", err, sizeof err);
+ k3_chat_history_add(&two, K3_CHAT_USER, "What were the other two?", NULL, err, sizeof err);
+ K3ChatSegments two_s; k3_chat_render(&two, 1, &two_s, err, sizeof err);
+ char *two_txt; int two_n; k3_chat_segments_text(&two_s, &two_txt, &two_n, err, sizeof err);
+ static const char WANT_TWO[] =
+ "<|open|>message role=\"system\" type=\"thinking-effort\"<|sep|>"
+ "`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), supported values include `low`, `medium`, `high`, and `max`.\n"
+ "Now the system is invoked with `thinking_effort=max`."
+ "<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"user\"<|sep|>Numbers?<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"assistant\"<|sep|><|open|>think<|sep|>I'll remember 215 and 222.<|close|>think<|sep|>"
+ "<|open|>response<|sep|>473, 921, 235<|close|>response<|sep|><|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"user\"<|sep|>What were the other two?<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"assistant\"<|sep|><|open|>think<|sep|>";
+ expect_text(two_txt, WANT_TWO, "official two-turn XTML bytes preserve reasoning_content");
+
+ /* thinking=False and thinking_effort, byte- and id-exact against the checkpoint's own
+ * tokenizer (tokenization_kimi.apply_chat_template, which defaults thinking_effort to
+ * "max" and whose encoder asserts on anything but low/high/max; the expected ids
+ * below are its output for these exact messages). */
+ K3ChatOptions nothink = k3_chat_options_default(); nothink.thinking = 0;
+ K3ChatOptions low = k3_chat_options_default(); low.thinking_effort = "low";
+ K3ChatOptions medium = k3_chat_options_default(); medium.thinking_effort = "medium";
+ ok(k3_chat_options_validate(&medium, err, sizeof err) != 0 && strstr(err, "medium") != NULL,
+ "thinking_effort=medium is refused, as the encoder refuses it");
+ K3ChatSegments med_s;
+ ok(k3_chat_render_opts(&h, 1, &medium, &med_s, err, sizeof err) != 0, "render refuses an invalid effort");
+ medium.thinking_effort = NULL;
+ ok(k3_chat_options_validate(&medium, err, sizeof err) != 0, "thinking without an effort is refused");
+ medium.thinking = 0;
+ ok(k3_chat_options_validate(&medium, err, sizeof err) == 0, "thinking off ignores the effort, like the encoder");
+
+ K3ChatSegments nt_s;
+ ok(k3_chat_render_opts(&h, 1, &nothink, &nt_s, err, sizeof err) == 0, "thinking=False render");
+ char *nt_txt; int nt_n; k3_chat_segments_text(&nt_s, &nt_txt, &nt_n, err, sizeof err);
+ static const char WANT_NT[] =
+ "<|open|>message role=\"system\"<|sep|>You are helpful.<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"user\"<|sep|>Hello<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"assistant\"<|sep|><|open|>response<|sep|>";
+ expect_text(nt_txt, WANT_NT, "thinking=False bytes: no effort message, response channel opened");
+ static const int WANT_NT_IDS[] = {
+ 163587,2778,6244,878,14062,1,163589,3900,554,13205,13,163588,2778,163589,163586,
+ 163587,2778,6244,878,2482,1,163589,19180,163588,2778,163589,163586,163587,2778,6244,
+ 878,69702,1,163589,163587,12092,163589
+ };
+ int nti = k3_chat_encode(&tok, &nt_s, ids, 4096, err, sizeof err);
+ ok(nti == (int)(sizeof WANT_NT_IDS / sizeof WANT_NT_IDS[0]) && !memcmp(ids, WANT_NT_IDS, sizeof WANT_NT_IDS),
+ "thinking=False XTML token ids (37, from the official tokenizer)");
+ free(nt_txt); k3_chat_segments_free(&nt_s);
+
+ K3ChatSegments low_s;
+ ok(k3_chat_render_opts(&h, 1, &low, &low_s, err, sizeof err) == 0, "thinking_effort=low render");
+ char *low_txt; int low_n; k3_chat_segments_text(&low_s, &low_txt, &low_n, err, sizeof err);
+ static const char WANT_LOW[] =
+ "<|open|>message role=\"system\" type=\"thinking-effort\"<|sep|>"
+ "`thinking_effort` guides on how much to think in your thinking channel (not including the response channel), supported values include `low`, `medium`, `high`, and `max`.\n"
+ "Now the system is invoked with `thinking_effort=low`."
+ "<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"system\"<|sep|>You are helpful.<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"user\"<|sep|>Hello<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"assistant\"<|sep|><|open|>think<|sep|>";
+ expect_text(low_txt, WANT_LOW, "thinking_effort=low bytes");
+ static const int WANT_LOW_IDS[] = {
+ 163587,2778,6244,878,14062,1,1798,878,130400,59991,470,1,163589,63,130400,
+ 123074,470,63,28560,418,1632,2455,308,2704,306,651,9545,8491,347,2976,
+ 3411,276,4503,8491,904,9141,4661,3867,1268,1332,5713,1268,50004,5713,1268,
+ 19421,5713,316,1268,5354,16518,10048,276,2403,387,42070,472,1268,130400,123074,
+ 470,28,1332,11369,163588,2778,163589,163586,163587,2778,6244,878,14062,1,163589,
+ 3900,554,13205,13,163588,2778,163589,163586,163587,2778,6244,878,2482,1,163589,
+ 19180,163588,2778,163589,163586,163587,2778,6244,878,69702,1,163589,163587,39964,163589
+ };
+ int lowi = k3_chat_encode(&tok, &low_s, ids, 4096, err, sizeof err);
+ ok(lowi == (int)(sizeof WANT_LOW_IDS / sizeof WANT_LOW_IDS[0]) && !memcmp(ids, WANT_LOW_IDS, sizeof WANT_LOW_IDS),
+ "thinking_effort=low XTML token ids (105, from the official tokenizer)");
+ free(low_txt); k3_chat_segments_free(&low_s);
+
+ K3ChatSegments two_nt;
+ ok(k3_chat_render_opts(&two, 1, &nothink, &two_nt, err, sizeof err) == 0, "thinking=False two-turn render");
+ char *two_nt_txt; int two_nt_n; k3_chat_segments_text(&two_nt, &two_nt_txt, &two_nt_n, err, sizeof err);
+ static const char WANT_TWO_NT[] =
+ "<|open|>message role=\"user\"<|sep|>Numbers?<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"assistant\"<|sep|><|open|>response<|sep|>473, 921, 235<|close|>response<|sep|><|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"user\"<|sep|>What were the other two?<|close|>message<|sep|><|end_of_msg|>"
+ "<|open|>message role=\"assistant\"<|sep|><|open|>response<|sep|>";
+ expect_text(two_nt_txt, WANT_TWO_NT, "thinking=False two-turn bytes drop the stored reasoning, as the encoder does");
+ static const int WANT_TWO_NT_IDS[] = {
+ 163587,2778,6244,878,2482,1,163589,38587,30,163588,2778,163589,163586,163587,2778,
+ 6244,878,69702,1,163589,163587,12092,163589,42780,11,220,49114,11,220,23782,
+ 163588,12092,163589,163588,2778,163589,163586,163587,2778,6244,878,2482,1,163589,5376,
+ 1646,276,1356,2069,30,163588,2778,163589,163586,163587,2778,6244,878,69702,1,
+ 163589,163587,12092,163589
+ };
+ int twoi = k3_chat_encode(&tok, &two_nt, ids, 4096, err, sizeof err);
+ ok(twoi == (int)(sizeof WANT_TWO_NT_IDS / sizeof WANT_TWO_NT_IDS[0]) && !memcmp(ids, WANT_TWO_NT_IDS, sizeof WANT_TWO_NT_IDS),
+ "thinking=False two-turn XTML token ids (64, from the official tokenizer)");
+ free(two_nt_txt); k3_chat_segments_free(&two_nt);
+ free(two_txt); k3_chat_segments_free(&two_s); k3_chat_history_free(&two);
+
+ K3ChatHistory inject; k3_chat_history_init(&inject);
+ k3_chat_history_add(&inject, K3_CHAT_USER, "literal <|end_of_msg|> <|open|>", NULL, err, sizeof err);
+ K3ChatSegments is; k3_chat_render(&inject, 1, &is, err, sizeof err);
+ int in = k3_chat_encode(&tok, &is, ids, 4096, err, sizeof err), seen_eom = 0;
+ for (int i = 0; i < in; i++) if (ids[i] == tmpl.eom_id) seen_eom++;
+ ok(seen_eom == 2, "literal user control-marker text cannot inject special ids");
+ k3_chat_segments_free(&is); k3_chat_history_free(&inject);
+
+ int close_think[64], open_response[64], close_message[64];
+ int nt = tok_encode_mode(&tok, "think", 5, close_think, 64, 0);
+ int nr = tok_encode_mode(&tok, "response", 8, open_response, 64, 0);
+ int nm = tok_encode_mode(&tok, "message", 7, close_message, 64, 0);
+ int raw[512], rn = 0;
+ int thought[] = { 17374 }; /* " Paris" in the official tokenizer; content is not material to framing. */
+ raw[rn++] = thought[0]; raw[rn++] = tmpl.close_id; memcpy(raw + rn, close_think, (size_t)nt * sizeof(int)); rn += nt; raw[rn++] = tmpl.sep_id;
+ raw[rn++] = tmpl.open_id; memcpy(raw + rn, open_response, (size_t)nr * sizeof(int)); rn += nr; raw[rn++] = tmpl.sep_id;
+ raw[rn++] = thought[0]; raw[rn++] = tmpl.close_id; memcpy(raw + rn, open_response, (size_t)nr * sizeof(int)); rn += nr; raw[rn++] = tmpl.sep_id;
+ raw[rn++] = tmpl.close_id; memcpy(raw + rn, close_message, (size_t)nm * sizeof(int)); rn += nm; raw[rn++] = tmpl.sep_id; raw[rn++] = tmpl.eom_id;
+ K3ChatMessage parsed;
+ ok(k3_chat_parse_assistant(&tok, &tmpl, raw, rn, &parsed, err, sizeof err) == 0,
+ "assistant stop boundary and think/response parser");
+ k3_chat_message_free(&parsed);
+ ok(k3_chat_parse_assistant(&tok, &tmpl, raw, rn - 1, &parsed, err, sizeof err) != 0,
+ "missing end id is rejected");
+ raw[rn - 1] = tmpl.eos_id;
+ ok(k3_chat_parse_assistant(&tok, &tmpl, raw, rn, &parsed, err, sizeof err) == 0,
+ "turn ended by [EOS], the id the released model emits, is accepted");
+ k3_chat_message_free(&parsed);
+ raw[rn - 1] = tmpl.sep_id;
+ ok(k3_chat_parse_assistant(&tok, &tmpl, raw, rn, &parsed, err, sizeof err) != 0,
+ "a closure followed by a non-end id is rejected");
+ raw[rn - 1] = tmpl.eom_id;
+ int saved = raw[0]; raw[0] = tmpl.open_id;
+ ok(k3_chat_parse_assistant(&tok, &tmpl, raw, rn, &parsed, err, sizeof err) != 0,
+ "assistant payload control tokens are rejected rather than changing restart tokens");
+ raw[0] = saved;
+
+ /* thinking off: the completion starts inside the response channel. */
+ int raw2[64], r2 = 0;
+ raw2[r2++] = thought[0]; raw2[r2++] = tmpl.close_id; memcpy(raw2 + r2, open_response, (size_t)nr * sizeof(int)); r2 += nr; raw2[r2++] = tmpl.sep_id;
+ raw2[r2++] = tmpl.close_id; memcpy(raw2 + r2, close_message, (size_t)nm * sizeof(int)); r2 += nm; raw2[r2++] = tmpl.sep_id; raw2[r2++] = tmpl.eos_id;
+ ok(k3_chat_parse_assistant_opts(&tok, &tmpl, &nothink, raw2, r2, &parsed, err, sizeof err) == 0 &&
+ parsed.reasoning_content == NULL && !strcmp(parsed.content, " Paris"),
+ "thinking=False parser: response only, reasoning_content NULL");
+ k3_chat_message_free(&parsed);
+ ok(k3_chat_parse_assistant_opts(&tok, &tmpl, &nothink, raw2, r2 - 1, &parsed, err, sizeof err) != 0,
+ "thinking=False parser rejects a missing end id");
+ ok(k3_chat_parse_assistant(&tok, &tmpl, raw2, r2, &parsed, err, sizeof err) != 0,
+ "thinking parser rejects a thinking=False completion (no think/response boundary)");
+ ok(k3_chat_parse_assistant_opts(&tok, &tmpl, &nothink, raw, rn, &parsed, err, sizeof err) != 0,
+ "thinking=False parser rejects a thinking completion (control ids in the response)");
+
+ char path[] = "/tmp/k3_chat_history_XXXXXX"; int fd = mkstemp(path); if (fd >= 0) close(fd);
+ ok(fd >= 0 && k3_chat_history_save(&h, path, err, sizeof err) == 0, "atomic JSONL history write");
+ K3ChatHistory loaded; k3_chat_history_init(&loaded);
+ ok(k3_chat_history_load(&loaded, path, err, sizeof err) == 0 && loaded.n == 2 && !strcmp(loaded.v[0].content, "You are helpful."), "JSONL history round trip");
+ ok(k3_chat_history_reset(&loaded, err, sizeof err) == 0 && loaded.n == 1 &&
+ loaded.v[0].role == K3_CHAT_SYSTEM && !strcmp(loaded.v[0].content, "You are helpful."),
+ "/reset retains only the initial system message");
+ FILE *bad = fopen(path, "wb"); if (bad) { fputs("{\"role\":\"user\",\"content\":\n", bad); fclose(bad); }
+ k3_chat_history_free(&loaded); k3_chat_history_init(&loaded);
+ ok(k3_chat_history_load(&loaded, path, err, sizeof err) != 0, "malformed JSONL is rejected");
+ ok(k3_chat_history_save(&h, "/no/such/k3-chat-history.jsonl", err, sizeof err) != 0,
+ "history write failure is reported without replacing a transcript");
+ unlink(path); k3_chat_history_free(&loaded);
+
+ float logits[] = {0.0f, 1.0f, 2.0f, 3.0f}; int a, b, g;
+ K3Sampler sa, sb; k3_sampler_init(&sa, 1.0, .95, 42, 2); k3_sampler_init(&sb, 1.0, .95, 42, 2);
+ ok(k3_sampler_next(&sa, logits, 4, 0, &a) == 0 && k3_sampler_next(&sb, logits, 4, 0, &b) == 0 && a == b,
+ "fixed seed sampler is deterministic");
+ ok(k3_sampler_next(&sa, logits, 4, 1, &g) == 0 && g == 3, "greedy sampler remains argmax");
+ K3Sampler bad_sampler; k3_sampler_init(&bad_sampler, 1.0, 0.0, 1, 1);
+ ok(k3_sampler_next(&bad_sampler, logits, 4, 0, &g) != 0, "invalid top-p is rejected");
+ k3_sampler_free(&bad_sampler);
+ k3_sampler_free(&sa); k3_sampler_free(&sb);
+
+ free(rendered); k3_chat_segments_free(&segs); k3_chat_history_free(&h);
+ printf("\n%s\n", fails ? "CHAT TESTS FAILED" : "CHAT TESTS PASSED");
+ return fails ? 1 : 0;
+}
diff --git a/third_party/tok.h b/third_party/tok.h
index a58954d..812219a 100644
--- a/third_party/tok.h
+++ b/third_party/tok.h
@@ -509,8 +509,19 @@ static void pretok_chunk_kimi(Tok *T, const unsigned char *p, int a, int b, int
}
/* ---------- encode: text -> ids (split on added tokens, then pre-tokenise + BPE) ---------- */
-static int tok_encode(Tok *T, const char *text, int len, int *out, int max){
+/* Encode with an explicit policy for added tokens. Prompt templates need their
+ * structural markers to remain atomic, while untrusted user text must never turn a
+ * spelling such as "<|end_of_msg|>" into a control id. Keep tok_encode() below as
+ * the historical allow-all entry point so existing callers retain their behaviour. */
+static int tok_encode_mode(Tok *T, const char *text, int len, int *out, int max,
+ int allow_added){
const unsigned char *p=(const unsigned char*)text; int no=0; int i=0;
+ if(!allow_added){
+ if(T->kimi) pretok_chunk_kimi(T,p,0,len,out,&no,max);
+ else if(T->o200k) pretok_chunk_o200k(T,p,0,len,out,&no,max);
+ else pretok_chunk(T,p,0,len,out,&no,max);
+ return no;
+ }
while(i<len){
/* next added-token occurrence at or after i (longest match) */
int hitpos=-1, hitlen=0, hitid=-1;
@@ -533,6 +544,10 @@ static int tok_encode(Tok *T, const char *text, int len, int *out, int max){
return no;
}
+static int tok_encode(Tok *T, const char *text, int len, int *out, int max){
+ return tok_encode_mode(T,text,len,out,max,1);
+}
+
/* id of an added token given its content (e.g. "<|endoftext|>"); -1 if absent */
static int tok_id_of(Tok *T, const char *content){
for(int i=0;i<T->nsp;i++) if(!strcmp(T->sp[i].str,content)) return T->sp[i].id;
diff --git a/tools/tok.py b/tools/tok.py
index c6bec0f..e561885 100644
--- a/tools/tok.py
+++ b/tools/tok.py
@@ -3,14 +3,9 @@
tok.py - text to token ids and back, for driving the C engine.
WHY THE TOKENIZER IS IN PYTHON AND THE ENGINE IS IN C
- Kimi K3 uses a tiktoken BPE with 163,584 ranks plus 256 special tokens. Writing that
- in C is a self-contained project of its own and would prove nothing about the
- inference engine, which is what this work is about. So tokenisation happens here,
- ids go to the engine, and ids come back here to be decoded. The boundary is explicit
- rather than hidden.
-
- The engine therefore does text in and text out only in the sense that this script
- wraps it. That is stated plainly rather than glossed over.
+ Kimi K3 uses a tiktoken BPE with 163,584 ranks plus its added control tokens. The
+ C engine loads the same files directly; this script remains a small inspection and
+ parity tool.
FORMAT
tiktoken.model is one "base64(token_bytes) rank" pair per line. The chat template
@@ -19,7 +14,7 @@ FORMAT
usage:
tok.py encode "some text" -> prints comma separated ids
tok.py decode 1,2,3 -> prints the text
- tok.py chat "some text" -> ids with the chat template applied
+ tok.py chat "some text" -> ids for one official XTML user turn
"""
from __future__ import annotations
@@ -116,29 +111,102 @@ def load():
return enc, cfg, special
+THINKING_EFFORT_MAX = (
+ "`thinking_effort` guides on how much to think in your thinking channel "
+ "(not including the response channel), supported values include `low`, "
+ "`medium`, `high`, and `max`.\n"
+ "Now the system is invoked with `thinking_effort=max`."
+)
+
+
+def xctl(out, text):
+ """Append a structural token segment. It alone may use added tokens."""
+ out.append((text, True))
+
+
+def xtxt(out, text):
+ """Append data/tag text, always with special-token recognition disabled."""
+ if text:
+ out.append((text, False))
+
+
+def xopen(out, tag, attrs=""):
+ xctl(out, "<|open|>")
+ xtxt(out, tag)
+ xtxt(out, attrs)
+ xctl(out, "<|sep|>")
+
+
+def xclose(out, tag):
+ xctl(out, "<|close|>")
+ xtxt(out, tag)
+ xctl(out, "<|sep|>")
+
+
+def xmessage(out, role, content, reasoning=None):
+ xopen(out, "message", f' role="{role}"')
+ if role == "assistant":
+ xopen(out, "think")
+ xtxt(out, reasoning or "")
+ xclose(out, "think")
+ xopen(out, "response")
+ xtxt(out, content)
+ xclose(out, "response")
+ else:
+ xtxt(out, content)
+ xclose(out, "message")
+ xctl(out, "<|end_of_msg|>")
+
+
+def xchat_user(user):
+ """Official K3 XTML text-only template for the command's single user message.
+
+ This deliberately does not consult a Jinja `chat_template`: K3's template is
+ implemented in the pinned upstream `encoding_k3.py`, not as a generic ChatML field.
+ Segment boundaries are also security boundaries: literal user spelling of a control
+ marker is encoded as ordinary BPE text.
+ """
+ out = []
+ xopen(out, "message", ' role="system" type="thinking-effort"')
+ xtxt(out, THINKING_EFFORT_MAX)
+ xclose(out, "message")
+ xctl(out, "<|end_of_msg|>")
+ xmessage(out, "user", user)
+ xopen(out, "message", ' role="assistant"')
+ xopen(out, "think")
+ return out
+
+
+def xencode(enc, special, segments):
+ required = {"<|open|>", "<|close|>", "<|sep|>", "<|end_of_msg|>"}
+ missing = sorted(required - set(special))
+ if missing:
+ raise SystemExit("K3 tokenizer is missing XTML controls: " + ", ".join(missing))
+ ids = []
+ for text, structural in segments:
+ if structural:
+ ids.extend(enc.encode(text, allowed_special=set(special), disallowed_special=()))
+ else:
+ # `disallowed_special=()` is essential: rejecting user text is not an
+ # injection defence; recognizing it as a special id would be an injection.
+ ids.extend(enc.encode(text, allowed_special=set(), disallowed_special=()))
+ return ids
+
+
def main():
if len(sys.argv) < 3:
print(__doc__)
return 2
mode, arg = sys.argv[1], sys.argv[2]
- enc, cfg, special = load()
+ enc, _cfg, special = load()
if mode == "encode":
ids = enc.encode(arg, allowed_special=set(special))
print(",".join(str(i) for i in ids))
elif mode == "chat":
- # Apply the released chat template if there is one, so the model sees the format
- # it was trained on. Without it a chat model answers as if mid-document.
- tmpl = cfg.get("chat_template")
- if tmpl:
- from jinja2 import Template
- text = Template(tmpl).render(
- messages=[{"role": "user", "content": arg}],
- add_generation_prompt=True, bos_token=cfg.get("bos_token", ""),
- )
- else:
- text = arg
- ids = enc.encode(text, allowed_special=set(special))
+ segments = xchat_user(arg)
+ text = "".join(piece for piece, _ in segments)
+ ids = xencode(enc, special, segments)
sys.stderr.write("templated prompt:\n%s\n---\n" % text)
print(",".join(str(i) for i in ids))
elif mode == "decode":