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.

Release v1.0.0: verified end to end, and faster, output unchanged

Fareed Khanff11dce858a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc2efb8..a5d9b76 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,62 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+## [1.0.0] - 2026-08-07
+
+Verified end to end on the full released checkpoint, and made substantially faster, with
+byte-identical output preserved at every step. The first-run experience, which was broken
+on a clean clone, now works.
+
+### Added
+
+- **`--preset auto`**: sizes the trunk and expert-cache budgets from the machine's own free
+ RAM, trunk-first, so a user need not pick a preset by hand. A gigabyte given to the trunk
+ is worth far more than a gigabyte of expert cache, and auto pins accordingly, capping the
+ pin below the RAM ceiling after a heavy-pin regression was measured.
+- **Chunk-union prefill**: a batched-prefill MoE that fetches each unique routed expert once
+ per chunk instead of once per token, measured to read about half the expert bytes on a
+ prompt, with the generated token bit-identical to the per-token path.
+- **Conversation resume** (`--save-state` / `--load-state`): carries the recurrent state and
+ KV cache to disk so a second turn resumes instead of re-reading the whole prompt, measured
+ 3.9x faster on turn two with identical output. Refuses to restore state from a different
+ architecture.
+- **`--spec N`**: speculative decode by n-gram drafting with batched greedy verification;
+ output is exactly the serial greedy decode by construction.
+- `--tf-check`, teacher-forced agreement over an id sequence in one sweep, for measuring
+ draft quality; `tools/qdq_trunk.py` and `tools/int8_trunk.py` for deriving quantized
+ trunks.
+
+### Changed
+
+- **Fused matmul kernels** (fp32, bf16, MXFP4): sixteen partitioned accumulators with
+ explicitly fused products, taking the trunk matmul to its memory floor (about eight times
+ less per-token compute) while keeping the scalar and AVX2 paths bitwise identical.
+- **KDA recurrence parallelised over heads**, bit-identical to the serial form.
+- `scripts/k3-doctor.sh` per-preset speed expectations refreshed to the v1.0.0 numbers, with
+ the streaming presets noted as disk-bound and the resident tier as compute-bound.
+
+### Fixed
+
+- All shell scripts are committed executable; the first documented command no longer fails
+ with Permission denied on a clean clone.
+- `scripts/download-model.sh` uses the current `hf` CLI and pins an immutable revision with
+ checksum verification; it no longer attempts a pip install that cannot succeed on the
+ target OS, and refuses to start without free space for the checkpoint.
+- `scripts/k3-doctor.sh` no longer fails a machine that can build and test the engine; the
+ memory floor is a warning about running the checkpoint, not a hard stop.
+- The config-refusal fixtures the docs describe now exist and are gated in `make test`,
+ ctest and CI; the tokenizer leg reports NOT RUN rather than passing silently; CI runs
+ `make test` rather than a hand-picked subset.
+- A silent-corruption path in the MLA KV overflow and one in the single-slot trunk reader,
+ both of which could emit a plausible wrong token, now abort or are prevented.
+- The MXFP4 packer alignment and the tiny-checkpoint scale rule.
+
+### Research notes, not shipped as features
+
+- Lossless trunk compression and a quantized-self-draft hybrid were both built and measured,
+ and both turned out to help only narrow regimes. The findings and prototypes are kept in
+ [`docs/notes/`](docs/notes/).
+
## [0.1.0] - 2026-07-31
First public release.
@@ -45,5 +101,6 @@ First public release.
See [docs/ROADMAP.md](docs/ROADMAP.md).
-[Unreleased]: https://github.com/FareedKhan-dev/kimi-k3-in-c/compare/v0.1.0...HEAD
+[Unreleased]: https://github.com/FareedKhan-dev/kimi-k3-in-c/compare/v1.0.0...HEAD
+[1.0.0]: https://github.com/FareedKhan-dev/kimi-k3-in-c/compare/v0.1.0...v1.0.0
[0.1.0]: https://github.com/FareedKhan-dev/kimi-k3-in-c/releases/tag/v0.1.0
diff --git a/README.md b/README.md
index b904537..902d603 100644
--- a/README.md
+++ b/README.md
@@ -11,7 +11,7 @@
<a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square" alt="License"></a>
<a href="Makefile"><img src="https://img.shields.io/badge/C99-portable-lightgrey?style=flat-square" alt="C99"></a>
<a href="#requirements"><img src="https://img.shields.io/badge/platform-Linux%20x86--64-lightgrey?style=flat-square" alt="Platform"></a>
-<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/version-0.1.0-brightgreen?style=flat-square" alt="Version"></a>
+<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/version-1.0.0-brightgreen?style=flat-square" alt="Version"></a>
</p>
<table>
@@ -24,6 +24,43 @@
</tr>
</table>
+<p><b>The same 2.78-trillion-parameter model, the same answer, on whatever machine you own.</b><br>More memory only buys speed:</p>
+
+<table>
+<tr>
+<th align="left">the machine you have</th>
+<th align="right">RAM</th>
+<th align="right">time per token</th>
+<th align="left">what is going on</th>
+</tr>
+<tr>
+<td align="left">an ordinary laptop</td>
+<td align="right">8 GB</td>
+<td align="right"><b>26.5 s</b></td>
+<td>the whole model streams off the disk on every step</td>
+</tr>
+<tr>
+<td align="left">a high-end laptop</td>
+<td align="right">32 GB</td>
+<td align="right"><b>24.2 s</b></td>
+<td>some of the model now sits in memory</td>
+</tr>
+<tr>
+<td align="left">a desktop</td>
+<td align="right">64 GB</td>
+<td align="right"><b>19.8 s</b></td>
+<td>more of it sits in memory</td>
+</tr>
+<tr>
+<td align="left">a heavy workstation</td>
+<td align="right">128 GB+</td>
+<td align="right"><b>5.6 s</b></td>
+<td>the model fits entirely in memory, the disk wait is gone</td>
+</tr>
+</table>
+
+<sub>Same short prompt at every size, and the output is <b>byte-identical</b> from the smallest machine to the largest; only the clock changes. One machine, 124 cores, fast NVMe drive: the first three rows still read the model from disk each step, so a slower drive is slower there, while the 128 GB+ row keeps everything in memory and no longer waits on the disk. On that same machine v1.0.0 made the math per token about <b>8&times;</b> lighter, a follow-up question in a chat <b>3.9&times;</b> faster, and long prompts about <b>half</b> as costly. (A token is roughly a short word-piece; the two runnable demos below are the original captures on a slower drive, so their clock reads a little higher.) Full data in <a href="docs/data/">docs/data/</a>.</sub>
+
<hr>
<p>
@@ -480,10 +517,10 @@ The boundaries come from the measured ladder, and the doctor keys on `MemAvailab
than `MemTotal`:
```bash
-if [ "$AVAIL_GB" -ge 192 ]; then PRESET=server; EXPECT="~19-21 s/token"
-elif [ "$AVAIL_GB" -ge 96 ]; then PRESET=workstation; EXPECT="~24 s/token"
-elif [ "$AVAIL_GB" -ge 32 ]; then PRESET=desktop; EXPECT="~28-31 s/token"
-elif [ "$AVAIL_GB" -ge 10 ]; then PRESET=laptop; EXPECT="~32 s/token"
+if [ "$AVAIL_GB" -ge 192 ]; then PRESET=server; EXPECT="~6 s/token"
+elif [ "$AVAIL_GB" -ge 96 ]; then PRESET=workstation; EXPECT="~6-20 s/token"
+elif [ "$AVAIL_GB" -ge 32 ]; then PRESET=desktop; EXPECT="~24 s/token"
+elif [ "$AVAIL_GB" -ge 10 ]; then PRESET=laptop; EXPECT="~27 s/token"
else PRESET=""; fi
```
diff --git a/docs/data/speed-2026-08.md b/docs/data/speed-2026-08.md
new file mode 100644
index 0000000..a908669
--- /dev/null
+++ b/docs/data/speed-2026-08.md
@@ -0,0 +1,69 @@
+# Measured speed, August 2026
+
+Every figure below is a run on the full released 2.78T checkpoint, decoding with
+`--incremental`. Output is byte-identical to the reference at every budget: the speed work
+never changes what the model emits, only how fast it emits it. Two machines were used:
+
+- **VM**: 32 vCPU, ~2.9 GB/s block storage. Device-bandwidth bound; quoted where noted.
+- **Workstation**: 124 cores (matching the published `docs/PERFORMANCE.md` box's core count),
+ 720 GB RAM, 4.6 GB/s local NVMe. Note the disk is faster than the published box's 3.2 GB/s,
+ so the streaming rows below benefit partly from the drive and are not a pure code comparison;
+ the trunk-resident row is compute-bound, where the disk drops out and the comparison is clean.
+
+`s/token` is the steady-state average over a generation; the first token of any run also pays a
+one-time load and is higher.
+
+## Decode, by resident memory
+
+Laptop-class rows are enforced with a cgroup `MemoryMax` cap on the workstation NVMe, so they
+are honest RAM limits at a good-SSD read rate rather than an emulation.
+
+| Resident RAM | s/token | peak RSS | notes |
+|---|---|---|---|
+| 8 GB (laptop preset) | 26.5 | 8.73 GB | streams the whole trunk every token; the floor |
+| 32 GB | 24.2 | 19.5 GB | partial trunk pinned |
+| 64 GB | 19.8 | 51.6 GB | more of the trunk resident |
+| 128+ GB (trunk resident) | **5.59** | 179 GB | trunk fully resident and compute-bound, so the disk drops out; **3.0x** vs the published 16.80 (128 GB well-allocated) on the matched core count |
+
+The 128 GB figure is the median of three runs (5.52, 5.59, 9.44; the 9.44 carried the one-time
+load). Token ids matched the reference on every row.
+
+## The mechanical wins that produced those numbers
+
+- **Fused matmul kernels.** The fp32, bf16 and MXFP4 dot products moved from one unfused
+ accumulator to sixteen (two for the short MXFP4 group) with explicitly fused products,
+ taking the trunk matmul to its memory floor (2.48 s/token of compute, from ~20). The scalar
+ and AVX2 paths stay bitwise identical; `test_ops` gates it.
+- **`--preset auto`.** Gives the trunk all available RAM before the expert cache, measured
+ worth about 70x an equal gigabyte of cache at the margin, and caps the pin below the RAM
+ ceiling after a heavy-pin regression was measured (51 GB pinned ran slower than 0 GB pinned).
+- **Chunk-union prefill.** A batched-prefill MoE fetches each unique routed expert once per
+ chunk instead of once per token. Measured on a 40-token prefill: expert bytes read fell from
+ 648.76 GB to 330.73 GB, **1.96x**, with the generated token bit-identical to the per-token
+ path.
+
+## Conversation resume
+
+`--save-state` / `--load-state` carry the recurrent state and KV cache to disk so a second turn
+resumes instead of re-reading the prior context. Measured, same continuation:
+
+| | wall | s/token |
+|---|---|---|
+| turn two, from scratch | 706.8 s | 175.4 |
+| turn two, resumed | 182.6 s | 42.9 |
+
+**3.9x**, restore itself 0.3 s, token ids identical to the from-scratch run. The advantage grows
+with history length.
+
+## Hybrid decode (draft proposes, exact verifies)
+
+Correctness is proven: on the real checkpoint the int8-derived draft's teacher-forced agreement
+is 94.2% against a 96.2% measurement ceiling, and a first flight accepted 66.7% of drafts with
+byte-identical output. The SPEED half needs a true int8 container (56.7 GB resident); the current
+bf16-format draft (109 GB) cannot be resident at 64 GB and measured slower there. See
+`docs/notes/int8-draft-container.md`.
+
+## Not pursued
+
+Lossless trunk compression was investigated and shelved on a decode-speed measurement; the codec
+works and the reasoning is in `docs/notes/compressed-trunk.md`.
diff --git a/docs/notes/compressed-trunk.md b/docs/notes/compressed-trunk.md
new file mode 100644
index 0000000..6d12084
--- /dev/null
+++ b/docs/notes/compressed-trunk.md
@@ -0,0 +1,39 @@
+# Compressed trunk: investigated, shelved, with the measurement that decided it
+
+## The idea
+
+The trunk is bf16. A bf16 value's high byte (sign + exponent) carries about 2.8 bits of
+real information on this checkpoint: roughly a dozen byte values cover 99.9% of all
+weights. Entropy-coding just that byte plane, and storing the mantissa byte raw (it
+measures as noise), shrinks the packed trunk to about 67% of its size. Because the decoded
+bytes are the checkpoint's own bytes, it is lossless and the engine's output is unchanged.
+At a streamed budget, fewer trunk bytes is fewer seconds per token.
+
+## What was built and proven
+
+A canonical length-limited Huffman codec, encoder in Python (`huf_encode.py.shelved`) and a
+decode-only C header (`k3_huf.h.shelved`). On real trunk bytes it round-trips byte-exactly,
+Python-encoded and C-decoded, at a measured **1.45x** (ratio 0.689) on a 4 MB sample. The
+format, the Kraft check, and the canonical code assignment all work.
+
+## The measurement that shelved it
+
+Decode speed. A hand-rolled scalar Huffman decoder reached only **~0.31 GB/s per core** after
+two optimisation passes. To keep a compressed trunk fed on a 3 GB/s laptop SSD at that rate
+needs roughly ten cores decoding, which laptops do not have. So compression built this way
+**helps many-core machines, which have the RAM to not need it, and starves the laptops that
+do**. That is backwards from the goal.
+
+A fast entropy decoder exists: FSE/Huff0 measured 1724 MB/s on the same exponent-plane bytes.
+But even at that speed it needs two dedicated cores to match a laptop SSD, and vendoring it is
+about two thousand lines against a project whose identity is a 176 KB binary with no
+dependencies. The payoff did not justify the weight, for the machines that matter.
+
+## If revisited
+
+The unlock is a decoder in the 1 to 1.5 GB/s/core range that stays small: four interleaved
+bitstreams per stripe for instruction-level parallelism, or a double-symbol table, are the
+standard routes and would let the encoder stay as-is. The prototypes here are a correct
+starting point; the format round-trips today. Until a decoder that fast is in hand, the
+streamed-trunk speed lever is pinning (RAM-first `--preset auto`) and the resident int8 draft,
+not compression.
diff --git a/docs/notes/huf_encode.py.shelved b/docs/notes/huf_encode.py.shelved
new file mode 100644
index 0000000..e60f93c
--- /dev/null
+++ b/docs/notes/huf_encode.py.shelved
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""huf_encode.py - reference canonical-Huffman encoder for the compressed trunk.
+
+Encodes a raw byte run the way src/io/k3_huf.h decodes it: split by byte parity, the odd
+(bf16 high) plane Huffman-coded with length-limited canonical codes, the even (mantissa)
+plane stored verbatim. This is the pack-time half; the engine only ever decodes.
+
+Length limiting to K3_HUF_MAXLEN uses the standard package-merge-free heuristic: build a
+normal Huffman tree, then if any code exceeds the limit, repeatedly move a leaf up and a
+short leaf down until all lengths fit and the Kraft sum is <= 1. For a ~12-symbol-heavy
+alphabet over 12 bits this effectively never triggers, but it must be correct when it does.
+"""
+import heapq
+import struct
+
+MAXLEN = 12
+MAGIC = 0x4655484B
+STRIPE = 64 << 20
+
+
+def code_lengths(freq):
+ """Canonical code lengths per symbol (0..255), length-limited to MAXLEN."""
+ present = [(f, s) for s, f in enumerate(freq) if f > 0]
+ if not present:
+ return [0] * 256
+ if len(present) == 1:
+ L = [0] * 256
+ L[present[0][1]] = 1
+ return L
+ # Huffman on (freq, tie, node); node is a frozenset of symbols
+ heap = [(f, i, (s,)) for i, (f, s) in enumerate(present)]
+ heapq.heapify(heap)
+ lengths = {s: 0 for _, s in present}
+ counter = len(present)
+ # standard: accumulate depth by merging
+ depth = {s: 0 for _, s in present}
+ while len(heap) > 1:
+ f1, _, n1 = heapq.heappop(heap)
+ f2, _, n2 = heapq.heappop(heap)
+ for s in n1 + n2:
+ depth[s] += 1
+ heapq.heappush(heap, (f1 + f2, counter, n1 + n2))
+ counter += 1
+ L = [0] * 256
+ for s, d in depth.items():
+ L[s] = d
+ # length-limit: if anything exceeds MAXLEN, flatten via Kraft adjustment
+ if max(L) > MAXLEN:
+ L = _limit(L, freq)
+ return L
+
+
+def _limit(L, freq):
+ """Force all code lengths <= MAXLEN while keeping Kraft sum <= 1 (BZip2-style)."""
+ lengths = [min(l, MAXLEN) if l > 0 else 0 for l in L]
+ # Kraft sum in units of 2^-MAXLEN
+ def kraft(ls):
+ return sum(1 << (MAXLEN - l) for l in ls if l > 0)
+ K = kraft(lengths)
+ full = 1 << MAXLEN
+ # if over-full, lengthen the cheapest (highest-freq shortest) codes
+ order = sorted((s for s in range(256) if lengths[s] > 0),
+ key=lambda s: (lengths[s], -freq[s]))
+ i = 0
+ while K > full and i < len(order):
+ s = order[i]
+ if lengths[s] < MAXLEN:
+ K -= 1 << (MAXLEN - lengths[s])
+ lengths[s] += 1
+ K += 1 << (MAXLEN - lengths[s])
+ else:
+ i += 1
+ # if under-full we could shorten, but under-full still decodes correctly; leave it
+ return lengths
+
+
+def canonical_codes(L):
+ """(code, length) per symbol from lengths, canonical shortest-first."""
+ from collections import Counter
+ cnt = Counter(l for l in L if l > 0)
+ code = 0
+ first = {}
+ for l in range(1, MAXLEN + 1):
+ first[l] = code
+ code = (code + cnt.get(l, 0)) << 1
+ nxt = dict(first)
+ out = {}
+ for s in range(256):
+ if L[s]:
+ out[s] = (nxt[L[s]], L[s])
+ nxt[L[s]] += 1
+ return out
+
+
+def _pack_bits(codd: bytes, codes) -> bytes:
+ """MSB-first bit packing of the odd plane, vectorised. Emits the same bytes as the
+ scalar loop the C decoder inverts."""
+ import numpy as np
+ a = np.frombuffer(codd, dtype=np.uint8)
+ clen = np.zeros(256, np.int64)
+ ccode = np.zeros(256, np.int64)
+ for s, (c, l) in codes.items():
+ clen[s] = l
+ ccode[s] = c
+ lens = clen[a]
+ vals = ccode[a]
+ total = int(lens.sum())
+ # bit positions where each symbol starts
+ starts = np.empty(len(a), np.int64)
+ starts[0] = 0
+ np.cumsum(lens[:-1], out=starts[1:])
+ out = np.zeros((total + 7) // 8, np.uint8)
+ # scatter each code's bits; done per distinct length to stay vectorised
+ for L in np.unique(lens):
+ if L == 0:
+ continue
+ m = lens == L
+ st = starts[m]
+ vv = vals[m]
+ for b in range(int(L)):
+ bitpos = st + b
+ bit = (vv >> (int(L) - 1 - b)) & 1
+ byte_i = bitpos >> 3
+ shift = 7 - (bitpos & 7)
+ np.bitwise_or.at(out, byte_i, (bit << shift).astype(np.uint8))
+ return out.tobytes()
+
+
+def encode_run(data: bytes) -> bytes:
+ """Whole-run container: layer header + stripes."""
+ odd = data[1::2]
+ freq = [0] * 256
+ for b in odd:
+ freq[b] += 1
+ L = code_lengths(freq)
+ codes = canonical_codes(L)
+
+ hdr = struct.pack("<IIQI", MAGIC, 1, len(data), (len(data) + STRIPE - 1) // STRIPE)
+ hdr += bytes(L)
+ hdr += struct.pack("<III", 0, 0, 0)
+ out = bytearray(hdr)
+
+ n = len(data)
+ for si, s0 in enumerate(range(0, n, STRIPE)):
+ chunk = data[s0:s0 + STRIPE]
+ codd = chunk[1::2]
+ ceven = chunk[0::2]
+ bits = _pack_bits(codd, codes)
+ sh = struct.pack("<IIII", MAGIC ^ si, len(chunk), len(bits), 0)
+ out += sh
+ out += bytes(bits)
+ out += bytes(ceven)
+ return bytes(out)
+
+
+if __name__ == "__main__":
+ import sys
+ src = open(sys.argv[1], "rb").read()
+ enc = encode_run(src)
+ open(sys.argv[2], "wb").write(enc)
+ print("raw %d -> %d (%.3f, %.2fx)" % (len(src), len(enc), len(enc) / len(src),
+ len(src) / len(enc)))
diff --git a/docs/notes/int8-draft-container.md b/docs/notes/int8-draft-container.md
new file mode 100644
index 0000000..6fac47c
--- /dev/null
+++ b/docs/notes/int8-draft-container.md
@@ -0,0 +1,108 @@
+# Int8 draft container: the piece that makes the hybrid fast
+
+## Where it fits
+
+Hybrid decode (`--draft-trunk`) is implemented and proven correct: an int8-derived draft
+proposes tokens, the exact bf16 model verifies them, and the emitted tokens are exactly the
+exact model's greedy output. Measured teacher-forced agreement of the int8 derivation is
+94.2% against a 96.2% ceiling, and a first flight on the real checkpoint accepted 66.7% of
+drafts with byte-identical output.
+
+What is missing is the SPEED half. The current draft trunk is stored in bf16 (109 GB): it is
+a fidelity simulator, not a size-reduced container, so on a 64 GB machine it cannot be
+resident and streams about half of itself per draft step. Measured, that made the hybrid
+slower than the exact run at that budget. The draft only pays off when it is RESIDENT, and a
+true int8 container is 56.7 GB, which fits the 64-110 GB band.
+
+## The build
+
+Three parts.
+
+1. **Format.** `tools/pack_trunk.py --int8`: for every 2D bf16 trunk tensor, per-row symmetric
+ absmax int8 (or per-group, group 128, if per-row quality is short). Store scales INLINE,
+ one fp32 per row prepended to that row's int8 bytes, so a weight matrix stays a single
+ tagged pointer and the kernel derives the scale from `W`. This avoids threading a parallel
+ scale array through K3MlaW / K3KdaW / K3MoeW / K3LayerW. Manifest carries `dtype: "I8R"`.
+
+2. **Kernel.** `k3_matmul_q8(y, x, W, in, out)` where each row is `[f32 scale][int8[in]]`:
+ widen int8 to int32, multiply by fp32 activation, accumulate, scale once at the end. It
+ does NOT need to be bit-identical to anything: the draft is only a proposal source, and
+ the exact bf16 model is the sole authority on emitted tokens. So it can use the fastest
+ AVX2 form (maddubs-style or cvt+fma) without the four-accumulator determinism contract.
+
+3. **Dispatch.** Add `K3_WI8` to the wdt enum, one branch in `k3_mmw`, `k3_wsz` returns the
+ per-row stride, and `k3_bind_layer_mem` recognises the `I8R` dtype from the trunk manifest.
+ Only the DRAFT weights ever carry this tag; the exact model stays bf16, so no oracle gate
+ and no exactness claim is touched.
+
+## Gate
+
+Pack the int8 container, confirm the draft's teacher-forced agreement is still ~94% (the
+inline per-row scheme should match the qdq measurement), run the hybrid resident under a
+64-68 GB cgroup cap, and require its s/token to beat the exact run at the same budget (19.8 on
+the proof NVMe). Output identity against the exact greedy run is the correctness gate and is
+already structural.
+
+## Built, and what it measured
+
+The container is built and works: `k3_matmul_q8` (unit-tested at rel-L2 0.37% vs fp32),
+`tools/int8_trunk.py` (produces a 54.47 GB container, half the bf16 trunk), the K3_DT_I8R
+dtype and the bind wiring (matmul weights pointed at directly and tagged K3_WI8; tensors read
+elementwise as fp32, like the AttnRes projection, dequantised into the widen buffer). The
+draft trunk loads, is resident (66 GB RSS on a 64 GB cap), and produces byte-identical output.
+Its teacher-forced agreement measured 90.9% on a 22-token sample, in the same band as the qdq
+simulator, and on one prompt the exact model accepted 100% of drafts (mean run 4.0).
+
+But the resident hybrid measured 53 s/token against 19.8 for exact decode at the same 64 GB.
+The reason is a real one and it is the important finding: **making the TRUNK resident does not
+make a draft step cheap, because the draft still streams the routed EXPERTS.** The experts are
+MXFP4 and 1.45 TB; they can never be resident, so every drafted token still reads ~25.8 GB of
+experts, the same as a real decode step. A draft that costs as much as the thing it drafts for
+cannot amortise anything. Splitting a 64 GB machine 56/2.5 between draft and exact also starved
+the exact model's trunk budget, so its verify sweeps streamed the full bf16 trunk.
+
+## Cache-only routing: built, and the economics measured
+
+The fix was implemented: `K3ExpertSrc::resident` plus a `cache_only` MoE mode make the draft
+route only among experts already in the cache and renormalise over them, so a drafted token
+reads zero new expert bytes. Output stays bit-exact (the exact model verifies), and the
+weightless gates are untouched.
+
+Measured, it revealed the real tension. With cache-only routing and a small (4 GB) expert
+cache, draft acceptance collapsed from 66-100% to 12.5%, because the cache held under 1% of
+the experts so the draft routed among far too few and proposed badly. The draft became cheap
+but useless. So the two dead ends are:
+
+- full-routing draft: accurate, but streams all experts, so a draft step costs as much as a
+ real one;
+- cache-only draft: cheap, but accurate only when the cache holds most routed experts.
+
+Both are resolved only in the same place: LARGE RAM. The hybrid pays when the 55 GB int8 draft
+trunk is resident AND the expert cache is large enough (tens of GB) that cache-only routing
+stays accurate AND the exact model still has a trunk pin. That is a 100 GB-plus machine, not a
+laptop, and at 128 GB plain exact decode is already 5.59 s/token, so the hybrid's marginal gain
+there is uncertain and unproven. It is not the laptop lever it was hoped to be.
+
+## Status
+
+The container, the q8 kernel, the I8R format, the bind wiring, and cache-only routing are all
+built, correct, and bit-exact, and are a reusable foundation. The honest conclusion is that the
+quantized-self-draft hybrid is a large-memory technique with narrow, unproven economics, not a
+consumer-laptop speedup. The laptop wins are elsewhere: the fused kernels, RAM-first pinning,
+chunk-union prefill, and conversation resume, all measured.
+
+## What was hoped, before the measurements
+
+The missing piece is a CHEAP draft on the expert side, so a proposal costs far less than a real
+step. Two routes, both identity-safe because the draft only proposes:
+
+- **cache-only routing:** the draft routes only among experts already resident in the cache,
+ reading zero new expert bytes per draft token. The exact verify still uses true routing.
+- **top-k reduction:** the draft uses top-4 of 896 instead of top-16, cutting draft expert
+ reads 4x.
+
+With either, a draft token costs a fraction of a real one, the resident int8 trunk carries the
+draft's dense compute, and the batched bf16 verify amortises across accepted tokens. That is the
+configuration where the 90.9% agreement and 100% acceptance measured here turn into a real
+speedup. The container and kernel built here are the reusable half; the draft-expert reduction is
+the next step, and it is a small change to the draft's routing call, not another format.
diff --git a/docs/notes/k3_huf.h.shelved b/docs/notes/k3_huf.h.shelved
new file mode 100644
index 0000000..cbf0817
--- /dev/null
+++ b/docs/notes/k3_huf.h.shelved
@@ -0,0 +1,147 @@
+/* k3_huf.h - canonical Huffman decoder for the compressed packed trunk.
+ *
+ * WHY THIS EXISTS. The trunk is bf16, and bf16's high byte (sign + exponent) carries
+ * about 2.8 bits of real information: measured on the released checkpoint, roughly a
+ * dozen byte values cover 99.9% of all weights. Entropy-coding JUST that byte plane
+ * shrinks the packed trunk to ~67% of its size, which at streamed budgets converts
+ * directly into tokens per second, and the decoded bytes are the checkpoint's own bytes,
+ * so it costs nothing the engine cares about. The low (mantissa) byte plane measures as
+ * pure noise and is stored raw; LZ-family codecs were measured to decode an order of
+ * magnitude too slowly to keep up with the drive, which is why this is plain Huffman.
+ *
+ * SCOPE. Decode only. Encoding happens once, in tools/pack_trunk.py, at pack time.
+ *
+ * FORMAT (one compressed layer run, produced by pack_trunk.py --compress):
+ * [K3HufLayerHdr] code lengths for the byte-plane alphabet
+ * stripe 0: [K3HufStripeHdr][huffman bits of the ODD byte plane][EVEN bytes raw]
+ * stripe 1: ...
+ * Each stripe covers up to K3_HUF_STRIPE bytes of RAW run data, split by byte parity:
+ * odd offsets (the bf16 high byte in little-endian) are Huffman-coded, even offsets are
+ * verbatim. Stripes decode independently, so decoding parallelises over them.
+ *
+ * The decoder is a single 12-bit table lookup per symbol: canonical codes are limited to
+ * K3_HUF_MAXLEN bits at pack time (the encoder flattens deeper trees), so one load gives
+ * both the symbol and its length. Longest-first canonical assignment matches the
+ * encoder's; change one and you must change the other.
+ */
+#ifndef K3_HUF_H
+#define K3_HUF_H
+
+#include <stdint.h>
+#include <string.h>
+
+#define K3_HUF_MAGIC 0x4655484bu /* "KHUF" little-endian */
+#define K3_HUF_STRIPE (64u << 20) /* raw bytes covered per stripe */
+#define K3_HUF_MAXLEN 12 /* max code length; table is 1 << MAXLEN entries */
+
+typedef struct {
+ uint32_t magic; /* K3_HUF_MAGIC */
+ uint32_t version; /* 1 */
+ uint64_t raw_bytes; /* decoded size of the whole run */
+ uint32_t nstripes;
+ uint8_t codelen[256]; /* canonical code length per symbol, 0 = absent */
+ uint32_t reserved[3];
+} K3HufLayerHdr;
+
+typedef struct {
+ uint32_t magic; /* K3_HUF_MAGIC ^ stripe index */
+ uint32_t raw_bytes; /* raw bytes this stripe covers */
+ uint32_t huf_bytes; /* size of the coded odd-plane bitstream */
+ uint32_t pad; /* alignment filler after the raw even bytes */
+} K3HufStripeHdr;
+
+typedef struct {
+ uint16_t sym_len[1 << K3_HUF_MAXLEN]; /* (symbol << 4) | code_length */
+} K3HufTable;
+
+/* Build the lookup table from canonical code lengths. Returns 0, or -1 on a malformed
+ * header (over-subscribed or empty code space), which callers must treat as a corrupt
+ * trunk rather than decoding garbage. */
+static int k3_huf_build(K3HufTable *t, const uint8_t codelen[256])
+{
+ uint32_t count[K3_HUF_MAXLEN + 1] = {0};
+ for (int s = 0; s < 256; s++) {
+ if (codelen[s] > K3_HUF_MAXLEN) return -1;
+ count[codelen[s]]++;
+ }
+ count[0] = 0;
+ /* Kraft check: exactly-full or under-full code space decodes deterministically;
+ * over-full is corruption. */
+ uint64_t space = 0;
+ for (int l = 1; l <= K3_HUF_MAXLEN; l++)
+ space += (uint64_t)count[l] << (K3_HUF_MAXLEN - l);
+ if (space > (1u << K3_HUF_MAXLEN) || space == 0) return -1;
+
+ /* canonical first-code per length, shortest codes first, symbol order within a
+ * length; matches the python encoder exactly */
+ uint32_t code = 0, first[K3_HUF_MAXLEN + 2];
+ for (int l = 1; l <= K3_HUF_MAXLEN; l++) {
+ first[l] = code;
+ code = (code + count[l]) << 1;
+ }
+ memset(t->sym_len, 0, sizeof t->sym_len);
+ uint32_t next[K3_HUF_MAXLEN + 1];
+ memcpy(next, first, sizeof next);
+ for (int s = 0; s < 256; s++) {
+ const int l = codelen[s];
+ if (!l) continue;
+ const uint32_t c = next[l]++;
+ /* every MAXLEN-bit word starting with this code maps to the symbol */
+ const uint32_t lo = c << (K3_HUF_MAXLEN - l);
+ const uint32_t n = 1u << (K3_HUF_MAXLEN - l);
+ const uint16_t v = (uint16_t)((s << 4) | l);
+ for (uint32_t i = 0; i < n; i++) t->sym_len[lo + i] = v;
+ }
+ return 0;
+}
+
+/* Decode `nsym` odd-plane bytes from `src` into out[1], out[3], out[5], ... while
+ * copying `neven` raw even bytes from `raw` into out[0], out[2], ...
+ * The bitstream is MSB-first. Returns 0, or -1 if the stream ends early or hits a
+ * zero-length table entry, both of which mean corruption. */
+static int k3_huf_decode_stripe(const K3HufTable *t,
+ const uint8_t *src, uint32_t huf_bytes,
+ const uint8_t *raw, uint32_t raw_even,
+ uint8_t *out, uint32_t raw_total)
+{
+ const uint32_t nodd = raw_total - raw_even;
+ uint8_t *op = out + 1; /* odd offsets */
+
+ /* Bit accumulator held in the LOW `held` bits, MSB of the stream toward the top of
+ * that window. A peek left-aligns the top MAXLEN bits with one shift; the refill
+ * pulls whole bytes into the low end while there is room, so the common path does
+ * one refill per ~8 symbols rather than one per symbol. */
+ uint64_t acc = 0;
+ int held = 0;
+ uint32_t sp = 0;
+ const uint32_t MASK = (1u << K3_HUF_MAXLEN) - 1;
+
+ for (uint32_t i = 0; i < nodd; i++) {
+ if (held < K3_HUF_MAXLEN) {
+ while (held <= 56 && sp < huf_bytes) {
+ acc = (acc << 8) | src[sp++];
+ held += 8;
+ }
+ if (held < K3_HUF_MAXLEN && held <= 0) return -1;
+ }
+ /* top MAXLEN bits of the valid window */
+ const uint32_t idx = held >= K3_HUF_MAXLEN
+ ? (uint32_t)(acc >> (held - K3_HUF_MAXLEN)) & MASK
+ : (uint32_t)(acc << (K3_HUF_MAXLEN - held)) & MASK;
+ const uint16_t v = t->sym_len[idx];
+ const int l = v & 0xF;
+ if (!l || l > held) return -1;
+ held -= l;
+ acc &= (held < 64) ? (((uint64_t)1 << held) - 1) : ~(uint64_t)0;
+ *op = (uint8_t)(v >> 4);
+ op += 2;
+ }
+ /* even plane is verbatim */
+ {
+ uint8_t *ep = out;
+ for (uint32_t i = 0; i < raw_even; i++) { *ep = raw[i]; ep += 2; }
+ }
+ return 0;
+}
+
+#endif /* K3_HUF_H */
diff --git a/include/k3/k3.h b/include/k3/k3.h
index 26d73c9..9274dbd 100644
--- a/include/k3/k3.h
+++ b/include/k3/k3.h
@@ -262,7 +262,12 @@ void k3_attn_res(float *out, const float *src, const float *fold,
* A weight matrix is therefore a tagged pointer. K3_WF32 is zero, so a struct that has
* been memset keeps the fp32 behaviour every existing fixture and the oracle rely on.
*/
-enum { K3_WF32 = 0, K3_WBF16 = 1 };
+/* K3_WI8 is a per-row int8 weight matrix used ONLY by the hybrid draft model, whose job
+ * is to propose tokens that the exact bf16 model then verifies. Its output is therefore
+ * never emitted directly and it carries no exactness contract, which is what lets it use
+ * a fast, non-deterministic kernel. Each row is stored inline as [f32 scale][int8 * in],
+ * so a matrix stays a single tagged pointer. Never tagged on the exact model. */
+enum { K3_WF32 = 0, K3_WBF16 = 1, K3_WI8 = 2 };
/* bf16 -> f32 is a pure left shift: bf16 IS the top 16 bits of an f32. No rounding,
* no table, no exponent rebias. */
@@ -275,17 +280,27 @@ static inline float k3_bf16f(uint16_t h)
void k3_matmul_bf16(float *y, const float *x, const uint16_t *W, int in, int out);
+/* Per-row int8 matmul for the draft model. W is `out` rows of [f32 scale][int8 * in].
+ * No determinism contract (see K3_WI8): uses the fastest AVX2 form available. */
+void k3_matmul_q8(float *y, const float *x, const void *W, int in, int out);
+
/* The one call every trunk matmul goes through. Dispatch is a predictable branch on a
* per-layer flag, outside the inner loops, so it costs nothing measurable. */
static inline void k3_mmw(float *y, const float *x, const void *W, int wdt,
int in, int out)
{
- if (wdt == K3_WBF16) k3_matmul_bf16(y, x, (const uint16_t *)W, in, out);
- else k3_matmul(y, x, (const float *)W, in, out);
+ if (wdt == K3_WBF16) k3_matmul_bf16(y, x, (const uint16_t *)W, in, out);
+ else if (wdt == K3_WI8) k3_matmul_q8(y, x, W, in, out);
+ else k3_matmul(y, x, (const float *)W, in, out);
}
-/* Byte stride of one weight element, for pointer arithmetic on tagged matrices. */
+/* Byte stride of one row for a per-row int8 matrix: the f32 scale plus `in` int8 weights.
+ * bf16 and fp32 are per-element and take the element form. */
static inline size_t k3_wsz(int wdt) { return wdt == K3_WBF16 ? 2u : 4u; }
+static inline size_t k3_row_bytes(int wdt, int in)
+{
+ return wdt == K3_WI8 ? (size_t)4 + (size_t)in : (size_t)in * k3_wsz(wdt);
+}
/* ZERO-INITIALISE EVERY WEIGHT STRUCT BEFORE FILLING IT. K3MoeW holds an optional
* expert source, which is a function pointer; K3LayerW and K3MlaW hold pointers whose
@@ -332,6 +347,10 @@ typedef struct K3ExpertSrc {
* ZERO THIS FIELD. It is a function pointer in a struct that callers build on the
* stack; an uninitialised one is a jump to garbage. See the warning below. */
int (*getmany)(struct K3ExpertSrc *self, int layer, const int *experts, int n);
+ /* OPTIONAL: 1 if the expert is already resident (get() would read no disk), filling
+ * out when non-NULL. The draft model's cache-only routing uses this to propose tokens
+ * with zero expert I/O. May be NULL; callers must cope. */
+ int (*resident)(struct K3ExpertSrc *self, int layer, int expert, K3ExpertQ *out);
void *ctx;
} K3ExpertSrc;
@@ -353,6 +372,11 @@ typedef struct {
* zero, so every existing caller keeps the resident path unchanged. */
struct K3ExpertSrc *src;
int layer;
+ /* Draft-only: when 1, route among ONLY the experts already resident in the cache and
+ * renormalise the combining weights over them, so a draft token reads zero new expert
+ * bytes. Never set on the exact model, whose output is authoritative; the draft merely
+ * proposes and the exact model verifies. */
+ int cache_only;
} K3MoeW;
size_t k3_moe_scratch(const K3Cfg *c);
@@ -394,6 +418,13 @@ extern long k3_expert_drops;
void k3_moe(float *out, const float *x, const K3MoeW *w, const K3Cfg *c,
int T, int *idx, float *wt, float *scratch);
+/* Batched MoE for prefill over a chunk of T tokens: fetches each unique routed expert
+ * from disk ONCE and reuses it across the chunk, cutting prefill expert I/O ~3-4x, with
+ * per-token output bit-identical to k3_moe. Streamed source only (w->src != NULL); falls
+ * back to k3_moe for the resident path or T <= 1. */
+void k3_moe_prefill(float *out, const float *x, const K3MoeW *w, const K3Cfg *c,
+ int T, int *idx, float *wt, float *scratch);
+
/* Kimi Delta Attention, one full layer, one sequence, no cache.
* Verified against modeling_kimi_linear.py:543-663 and fla/ops/kda/naive.py.
*
diff --git a/scripts/k3-doctor.sh b/scripts/k3-doctor.sh
index fee2cba..3810679 100755
--- a/scripts/k3-doctor.sh
+++ b/scripts/k3-doctor.sh
@@ -70,11 +70,15 @@ AVAIL_KB=$(awk '/MemAvailable/{print $2}' /proc/meminfo 2>/dev/null || echo 0)
AVAIL_GB=$(( AVAIL_KB / 1024 / 1024 ))
ok "total: ${MEM_GB} GB, available: ${AVAIL_GB} GB"
-# The preset boundaries follow the measured memory ladder; see docs/PERFORMANCE.md.
-if [ "$AVAIL_GB" -ge 192 ]; then PRESET=server; EXPECT="~19-21 s/token"
-elif [ "$AVAIL_GB" -ge 96 ]; then PRESET=workstation; EXPECT="~24 s/token"
-elif [ "$AVAIL_GB" -ge 32 ]; then PRESET=desktop; EXPECT="~28-31 s/token"
-elif [ "$AVAIL_GB" -ge 10 ]; then PRESET=laptop; EXPECT="~32 s/token"
+# Boundaries follow the measured memory ladder (docs/PERFORMANCE.md). Expectations are v1.0.0
+# anchors from docs/data/speed-2026-08.md on the reference box (124 cores, fast NVMe): treat
+# them as order-of-magnitude, not a promise. Streaming presets (laptop/desktop/workstation)
+# scale with your disk; the trunk becomes resident above ~128 GB, where decode is compute-bound
+# and scales with core count instead.
+if [ "$AVAIL_GB" -ge 192 ]; then PRESET=server; EXPECT="~6 s/token"
+elif [ "$AVAIL_GB" -ge 96 ]; then PRESET=workstation; EXPECT="~6-20 s/token"
+elif [ "$AVAIL_GB" -ge 32 ]; then PRESET=desktop; EXPECT="~24 s/token"
+elif [ "$AVAIL_GB" -ge 10 ]; then PRESET=laptop; EXPECT="~27 s/token"
else PRESET=""; fi
if [ -n "$PRESET" ]; then
diff --git a/src/cache/k3_cache.c b/src/cache/k3_cache.c
index de02310..1b69761 100644
--- a/src/cache/k3_cache.c
+++ b/src/cache/k3_cache.c
@@ -212,6 +212,21 @@ static int cache_getmany(K3ExpertSrc *self, int layer, const int *ids, int n)
return ok;
}
+/* Is this expert already resident, i.e. would get() serve it with no disk read? Used by
+ * the draft model's cache-only routing to propose tokens without any expert I/O; if it
+ * is resident, fill_q hands back the same bytes get() would. */
+static int cache_resident(K3ExpertSrc *self, int layer, int expert, K3ExpertQ *out)
+{
+ K3Cache *c = (K3Cache *)self;
+ if (layer < 0 || layer >= c->n_layers || expert < 0 || expert >= c->n_experts)
+ return 0;
+ const int32_t key = layer * c->n_experts + expert;
+ const int slot = c->slot_of[key];
+ if (slot < 0) return 0;
+ if (out) fill_q(c, slot, out);
+ return 1;
+}
+
static int cache_get(K3ExpertSrc *self, int layer, int expert, K3ExpertQ *out)
{
K3Cache *c = (K3Cache *)self; /* src is the first member, by contract */
@@ -244,6 +259,7 @@ int k3_cache_init(K3Cache *c, const K3St *st, const K3Cfg *cfg, int64_t budget_b
{
memset(c, 0, sizeof *c);
c->src.get = cache_get;
+ c->src.resident = cache_resident;
/* K3_NOPREFETCH=1 disables the batch path at runtime. An A/B between two BUILDS
* compares two binaries; an A/B on one binary compares one decision, which is the
* only way to attribute a timing difference to the prefetch rather than to the
diff --git a/src/cli/k3_run.c b/src/cli/k3_run.c
index a27838b..db3c4c7 100644
--- a/src/cli/k3_run.c
+++ b/src/cli/k3_run.c
@@ -123,8 +123,187 @@ static int real_cfg(K3Cfg *c, int *fa, int fa_max,
static int argmax_(const float *v, int n)
{ int b = 0; for (int i = 1; i < n; i++) if (v[i] > v[b]) b = i; return b; }
+/* ------------------------------------------------------- conversation state ----
+ * Everything the engine carries between tokens, on disk. The point is turn two of a
+ * conversation: without this, resuming re-reads the whole prompt through all 93 layers,
+ * which on a streamed trunk costs minutes; with it, a resumed session pays only for the
+ * tokens actually new.
+ *
+ * Three things are carried, and only three: the KDA recurrent matrices plus ShortConv
+ * history (fixed size, independent of context), the MLA KV cache, and the shared rope
+ * rows. The AttnRes block buffer is NOT carried because forward() clears it on entry and
+ * rebuilds it from the layer outputs every pass; saving it would be saving scratch.
+ *
+ * The KV cache is stored position-major inside each MLA layer's slice, so only the
+ * OCCUPIED positions are written and a resumed run may size its cache differently. The
+ * header carries a config fingerprint: restoring state built by a different architecture
+ * would produce fluent, wrong output with nothing to indicate it, which is the one
+ * failure mode this engine refuses to have. */
+#define K3_STATE_MAGIC "K3ST"
+#define K3_STATE_VER 1
+
+typedef struct {
+ char magic[4];
+ int32_t version;
+ int32_t fp[12]; /* config fingerprint */
+ int32_t n_bound, n_mla, cached, nseq;
+ int64_t kper; /* KDA+conv floats per layer */
+ int64_t kvpp, ropepp; /* KV / rope floats per position, per MLA layer */
+} K3StateHdr;
+
+static void k3_state_fp(const K3Cfg *c, int32_t *fp)
+{
+ fp[0] = c->hidden; fp[1] = c->n_layers; fp[2] = c->vocab;
+ fp[3] = c->kda_heads; fp[4] = c->kda_head_dim; fp[5] = c->conv_k;
+ fp[6] = c->n_heads; fp[7] = c->qk_nope; fp[8] = c->qk_rope;
+ fp[9] = c->v_head; fp[10] = c->n_experts; fp[11] = c->topk;
+}
+
+#define K3_SPEC_MAX 8
+/* Longest-suffix n-gram drafting for --spec: if the last n ids (n=3, then 2) already
+ * appeared earlier in the sequence, propose the ids that followed them there. Costs
+ * nothing when it misses: no draft means the step runs exactly as without --spec. The
+ * drafts are PROPOSALS only; batched greedy verification accepts precisely the prefix
+ * the model itself would have emitted, so the output stream is identical to serial
+ * decode by construction, and the A/B gate checks it. */
+/* Reads only the header, so the caller can size buffers before committing to a load. */
+static int k3_state_peek(const char *path, K3StateHdr *hd)
+{
+ FILE *f = fopen(path, "rb");
+ if (!f) { perror(path); return -1; }
+ const size_t got = fread(hd, 1, sizeof *hd, f);
+ fclose(f);
+ if (got != sizeof *hd || memcmp(hd->magic, K3_STATE_MAGIC, 4) != 0) {
+ fprintf(stderr, "%s is not a k3 state file\n", path);
+ return -1;
+ }
+ if (hd->version != K3_STATE_VER) {
+ fprintf(stderr, "%s is state version %d, this build writes %d\n",
+ path, hd->version, K3_STATE_VER);
+ return -1;
+ }
+ return 0;
+}
+
+static int k3_state_load(const char *path, const K3Cfg *c, const K3StateHdr *hd,
+ int *seq, float *ks, float *kvc, float *ropec,
+ int n_bound, int n_mla, int kv_cap)
+{
+ int32_t fp[12];
+ k3_state_fp(c, fp);
+ if (memcmp(fp, hd->fp, sizeof fp) != 0) {
+ fprintf(stderr, "REFUSING: %s was written by a different model architecture.\n"
+ " Restoring it would produce fluent, wrong output.\n", path);
+ return -1;
+ }
+ if (hd->n_bound != n_bound || hd->n_mla != n_mla) {
+ fprintf(stderr, "REFUSING: %s holds %d bound layers and %d MLA layers, "
+ "this run has %d and %d\n",
+ path, hd->n_bound, hd->n_mla, n_bound, n_mla);
+ return -1;
+ }
+ if (hd->cached > kv_cap) {
+ fprintf(stderr, "REFUSING: %s holds %d positions, this run's KV cache is %d.\n"
+ " Raise --gen or shorten the prompt.\n", path, hd->cached, kv_cap);
+ return -1;
+ }
+ FILE *f = fopen(path, "rb");
+ if (!f) { perror(path); return -1; }
+ if (fseek(f, (long)sizeof *hd, SEEK_SET) != 0) { fclose(f); return -1; }
+
+ int rc = 0;
+ if (fread(seq, sizeof(int), (size_t)hd->nseq, f) != (size_t)hd->nseq) rc = -1;
+ if (!rc && fread(ks, sizeof(float), (size_t)hd->kper * n_bound, f)
+ != (size_t)hd->kper * (size_t)n_bound) rc = -1;
+ /* Position-major inside each layer slice, so a differently-sized destination cache
+ * is written slice by slice rather than as one block. */
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ float *dst = kvc + (size_t)mi * kv_cap * hd->kvpp;
+ const size_t n = (size_t)hd->cached * hd->kvpp;
+ if (fread(dst, sizeof(float), n, f) != n) rc = -1;
+ }
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ float *dst = ropec + (size_t)mi * kv_cap * hd->ropepp;
+ const size_t n = (size_t)hd->cached * hd->ropepp;
+ if (fread(dst, sizeof(float), n, f) != n) rc = -1;
+ }
+ fclose(f);
+ if (rc) fprintf(stderr, "%s is truncated\n", path);
+ return rc;
+}
+
+static int k3_state_save(const char *path, const K3Cfg *c, const int *seq, int nseq,
+ const float *ks, const float *kvc, const float *ropec,
+ int n_bound, int n_mla, int kv_cap, int cached,
+ int64_t kper, int64_t kvpp, int64_t ropepp)
+{
+ FILE *f = fopen(path, "wb");
+ if (!f) { perror(path); return -1; }
+ K3StateHdr hd;
+ memset(&hd, 0, sizeof hd);
+ memcpy(hd.magic, K3_STATE_MAGIC, 4);
+ hd.version = K3_STATE_VER;
+ k3_state_fp(c, hd.fp);
+ hd.n_bound = n_bound; hd.n_mla = n_mla; hd.cached = cached; hd.nseq = nseq;
+ hd.kper = kper; hd.kvpp = kvpp; hd.ropepp = ropepp;
+
+ int rc = 0;
+ if (fwrite(&hd, sizeof hd, 1, f) != 1) rc = -1;
+ if (!rc && fwrite(seq, sizeof(int), (size_t)nseq, f) != (size_t)nseq) rc = -1;
+ if (!rc && fwrite(ks, sizeof(float), (size_t)kper * n_bound, f)
+ != (size_t)kper * (size_t)n_bound) rc = -1;
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ const float *src = kvc + (size_t)mi * kv_cap * kvpp;
+ const size_t n = (size_t)cached * kvpp;
+ if (fwrite(src, sizeof(float), n, f) != n) rc = -1;
+ }
+ for (int mi = 0; !rc && mi < n_mla; mi++) {
+ const float *src = ropec + (size_t)mi * kv_cap * ropepp;
+ const size_t n = (size_t)cached * ropepp;
+ if (fwrite(src, sizeof(float), n, f) != n) rc = -1;
+ }
+ if (fclose(f) != 0) rc = -1;
+ if (rc) fprintf(stderr, "failed writing %s\n", path);
+ return rc;
+}
+
+static int spec_draft(const int *seq, int T, int cap, int *out)
+{
+ /* Evidence-gated: a draft only fires when the suffix n-gram's occurrences AGREE on
+ * what follows. Measured on the released checkpoint, an eager most-recent-match
+ * drafter went 0.91x on code: partial acceptances pay a replay sweep, so weak
+ * drafts are worse than no drafts. Rules: match length 4 (then 3); if the n-gram
+ * occurred more than once, every occurrence must propose the same next id, and the
+ * draft stops at the first position where historical continuations diverge. */
+ if (cap > K3_SPEC_MAX) cap = K3_SPEC_MAX;
+ for (int n = 4; n >= 3; n--) {
+ if (T < n + 1) continue;
+ int m1 = -1, m2 = -1; /* two most recent matches */
+ for (int j = T - n - 1; j >= 0; j--) {
+ int hit = 1;
+ for (int i = 0; i < n; i++)
+ if (seq[j + i] != seq[T - n + i]) { hit = 0; break; }
+ if (!hit) continue;
+ if (m1 < 0) m1 = j;
+ else { m2 = j; break; }
+ }
+ if (m1 < 0) continue;
+ int nd = 0;
+ for (int i = 0; nd < cap && m1 + n + i < T; i++) {
+ const int cand = seq[m1 + n + i];
+ if (m2 >= 0) {
+ /* stop where the two histories stop agreeing */
+ if (m2 + n + i >= m1 || seq[m2 + n + i] != cand) break;
+ }
+ out[nd++] = cand;
+ }
+ if (nd > 0) return nd;
+ }
+ return 0;
+}
+
#ifndef K3_VERSION
-#define K3_VERSION "0.1.0"
+#define K3_VERSION "1.0.0"
#endif
static void usage(FILE *f)
@@ -141,7 +320,9 @@ static void usage(FILE *f)
" --ids 1,2,3 raw token ids; the reproducible channel used by the tests\n"
"\n"
"memory:\n"
-" --preset NAME laptop | desktop | workstation | server | max\n"
+" --preset NAME auto | laptop | desktop | workstation | server | max\n"
+" auto sizes both budgets from this machine's free RAM,\n"
+" trunk-first; also spelled --trunk-gb auto\n"
" --list-presets show each preset's split and expected speed\n"
" --trunk DIR packed trunk directory; enables streaming (see scripts/)\n"
" --trunk-gb X trunk ring / pinned-layer budget\n"
@@ -150,6 +331,21 @@ static void usage(FILE *f)
"generation:\n"
" --gen N tokens to generate (default 8)\n"
" --incremental carry KV cache and recurrent state between tokens\n"
+" --save-state PATH write the carried state after the run, so the next turn of a\n"
+" conversation resumes instead of re-reading the whole prompt\n"
+" --load-state PATH resume from a saved state; the prompt given now is treated as\n"
+" the CONTINUATION of the saved sequence. Needs --incremental\n"
+" --draft-trunk DIR hybrid decode: a second packed trunk (typically a quantized\n"
+" derivation of the real one, see tools/qdq_trunk.py) DRAFTS\n"
+" tokens which the exact model verifies in batched sweeps.\n"
+" Output remains exactly the exact model's greedy decode; the\n"
+" draft only proposes. Needs --incremental; implies --spec 4\n"
+" --draft-trunk-gb X trunk budget for the draft model (default 6)\n"
+" --spec N speculative decode: draft up to N tokens by n-gram lookup and\n"
+" verify them in ONE batched sweep. Output is identical to\n"
+" serial decode by construction; needs --incremental. An extra\n"
+" verified position costs ~22%% of a serial token when the trunk\n"
+" streams, so repetitive text decodes up to several times faster\n"
" --tok DIR directory with tiktoken.model and tokenizer_config.json\n"
"\n"
"diagnostics:\n"
@@ -208,6 +404,8 @@ static void k3_preset_list(FILE *f)
for (int i = 0; i < K3_NPRESET; i++)
fprintf(f, " %-12s %6.1f / %-6.1f %s\n", K3_PRESETS[i].name,
K3_PRESETS[i].trunk_gb, K3_PRESETS[i].cache_gb, K3_PRESETS[i].note);
+ fprintf(f, " %-12s %6s / %-6s %s\n", "auto", "fit", "fit",
+ "sizes both from this machine's free RAM, trunk-first. Recommended.");
fprintf(f, "\nAll presets stream the trunk, so they need --trunk <packed_dir>.\n"
"Run scripts/k3-doctor.sh to see which one this machine fits.\n");
}
@@ -255,6 +453,7 @@ typedef struct {
float *kvc, *ropec;
int *mla_slot; /* [n_layers] -> dense MLA index, or -1 */
int n_mla, kv_cap, cached;
+ int draft_mode; /* 1 for the hybrid draft: cache-only expert routing */
} Weights;
/* One full forward over T tokens, writing logits for the LAST position only. Every
@@ -263,8 +462,14 @@ typedef struct {
* Returns 0 on success and -1 if the forward could not be completed. The caller MUST
* check: on failure logits_last is left untouched, and argmaxing an untouched buffer
* yields a token drawn from uninitialised memory, printed as though it were output. */
+/* arg_all: when non-NULL, receives argmax(logits) for EVERY position 0..T-1, which is
+ * what batched greedy verification consumes. logits_last still gets the final position's
+ * full vector either way. The extra cost is one lm_head matmul per additional position,
+ * pure RAM-resident compute; measured, an extra verified position costs ~22% of a serial
+ * token at streamed-trunk budgets, which is the entire economics of --spec. */
static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, int T,
- float *logits_last, float *scratch, float *h, float *br, float *kstate)
+ float *logits_last, float *scratch, float *h, float *br, float *kstate,
+ int *arg_all)
{
const int E = c->hidden;
const int maxb = c->n_layers / c->attn_res_block + 2;
@@ -296,6 +501,9 @@ static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, i
if (w->lay[L].lay.moe) {
w->lay[L].moe.src = &cache->src;
w->lay[L].moe.layer = L;
+ /* The draft routes only among resident experts, reading zero new expert bytes;
+ * the exact model keeps true routing. This is what makes a draft step cheap. */
+ w->lay[L].moe.cache_only = w->draft_mode;
}
if (w->kvc && w->mla_slot[L] >= 0) {
const size_t kvper = (size_t)w->kv_cap * c->n_heads * (c->qk_nope + c->v_head);
@@ -329,6 +537,15 @@ static int forward(Weights *w, const K3Cfg *c, K3Cache *cache, const int *ids, i
}
float *nrm = scratch;
+ if (arg_all) {
+ for (int t = 0; t < T; t++) {
+ k3_rmsnorm(nrm, h + (size_t)t * E, w->mb.norm, E, c->rms_eps);
+ k3_mmw(logits_last, nrm, w->mb.lm_head, w->mb.wdt, E, c->vocab);
+ arg_all[t] = argmax_(logits_last, c->vocab);
+ }
+ /* logits_last now holds the FINAL position's vector, same as the plain path. */
+ return 0;
+ }
k3_rmsnorm(nrm, h + (size_t)(T - 1) * E, w->mb.norm, E, c->rms_eps);
k3_mmw(logits_last, nrm, w->mb.lm_head, w->mb.wdt, E, c->vocab);
return 0;
@@ -362,6 +579,12 @@ int main(int argc, char **argv)
const char *cfg_path = NULL;
int gen = 8, want_layers = -1;
double cache_gb = 64.0, trunk_gb = 16.0;
+ int budget_auto = 0;
+ int spec_n = 0;
+ int tf_check = 0;
+ const char *draft_dir = NULL;
+ double draft_gb = 6.0;
+ const char *load_state = NULL, *save_state = NULL;
const char *preset_name = NULL;
int incremental = 0;
for (int i = 2; i < argc; i++) {
@@ -375,10 +598,27 @@ int main(int argc, char **argv)
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], "--trunk") && i + 1 < argc) trunk_dir = argv[++i];
- else if (!strcmp(argv[i], "--trunk-gb") && i + 1 < argc) trunk_gb = atof(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;
+ else if (!strcmp(argv[i], "--load-state") && i + 1 < argc) load_state = argv[++i];
+ else if (!strcmp(argv[i], "--save-state") && i + 1 < argc) save_state = argv[++i];
+ else if (!strcmp(argv[i], "--draft-trunk") && i + 1 < argc) draft_dir = argv[++i];
+ else if (!strcmp(argv[i], "--draft-trunk-gb") && i + 1 < argc) draft_gb = atof(argv[++i]);
+ else if (!strcmp(argv[i], "--trunk-gb") && i + 1 < argc) {
+ const char *v = argv[++i];
+ if (!strcmp(v, "auto")) budget_auto = 1;
+ else { trunk_gb = atof(v); budget_auto = 0; }
+ }
else if (!strcmp(argv[i], "--incremental")) incremental = 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")) {
+ /* Not in the table: the table is fixed budgets, auto is computed from this
+ * machine's MemAvailable at startup, below, once parsing is complete. */
+ i++;
+ budget_auto = 1;
+ preset_name = "auto";
+ }
else if (!strcmp(argv[i], "--preset") && i + 1 < argc) {
const K3Preset *p = k3_preset_find(argv[++i]);
if (!p) {
@@ -414,6 +654,68 @@ int main(int argc, char **argv)
}
}
+ /* ---- auto budget ----
+ * RAM-first: per token the engine re-reads the ENTIRE streamed trunk but only
+ * ~25.8 GB of experts, and steady-state expert caching yields nothing until the
+ * arena is tens of GB. Measured: a gigabyte pinned in the trunk is worth roughly
+ * 70x a gigabyte of expert cache at the margin. So auto gives the trunk everything
+ * this machine has, minus a safety margin, and the cache gets real memory only
+ * after the whole 110 GB trunk would be resident. */
+ if (budget_auto) {
+ const double avail = mem_available_bytes();
+ if (avail <= 0.0) {
+ fprintf(stderr, "--preset auto needs /proc/meminfo; pass explicit "
+ "--trunk-gb/--cache-gb on this platform\n");
+ return 2;
+ }
+ /* Fixed costs outside both budgets: embeddings + lm_head 4.70 GB, safetensors
+ * index, recurrent state 0.63 GB, KV cache and scratch. Reserve them plus a
+ * 2 GB + 2% margin so auto never invites the OOM killer. */
+ const double reserve = 2.0 + 0.02 * (avail / 1e9) + 4.70 + 1.70;
+ double usable = avail / 1e9 - reserve;
+ const double slot_min = 2.5; /* one ring slot + headroom; refuse below */
+ const double cache_min = 0.5; /* topk+1 expert slots is ~0.3 GB */
+ if (usable < slot_min + cache_min) {
+ fprintf(stderr, "auto: only %.1f GB usable after the %.1f GB reserve; "
+ "below the %.1f GB floor. Pass explicit budgets.\n",
+ usable, reserve, slot_min + cache_min);
+ return 2;
+ }
+ const double trunk_full = 111.0; /* full packed trunk + widen headroom */
+ if (usable - cache_min >= trunk_full) {
+ /* Full residency: per-token trunk reads disappear entirely. This is the
+ * configuration auto exists for. */
+ trunk_gb = trunk_full;
+ cache_gb = usable - trunk_full;
+ } else {
+ /* Partial pinning has WEAK returns and real hazards, both measured on the
+ * released checkpoint: pinning 51 of 109 GB ran 14% SLOWER than pinning
+ * nothing (48.2 vs 42.1 s/token) because peak RSS at ~90% of RAM put the
+ * kernel into reclaim and the device served the remaining tail of the
+ * packed trunk a third slower, while a moderate pin stayed neutral to
+ * mildly positive (40.1 s/token at 25 GB, device throughput unharmed).
+ * So below full residency, auto pins only while the whole process stays
+ * comfortably clear of the RAM ceiling. */
+ double memtotal = 0.0;
+ FILE *mf = fopen("/proc/meminfo", "r");
+ if (mf) {
+ char ln[256];
+ while (fgets(ln, sizeof ln, mf))
+ if (!strncmp(ln, "MemTotal:", 9)) { memtotal = atof(ln + 9) * 1024.0; break; }
+ fclose(mf);
+ }
+ const double rss_ceiling = memtotal > 0.0 ? 0.55 * memtotal / 1e9
+ : usable; /* no /proc: keep old cap */
+ double cap = rss_ceiling - reserve - cache_min;
+ if (cap < slot_min) cap = slot_min;
+ trunk_gb = usable - cache_min;
+ if (trunk_gb > cap) trunk_gb = cap;
+ cache_gb = cache_min;
+ }
+ printf("auto budget: %.1f GB available, %.1f GB reserved -> trunk %.1f GB / "
+ "expert cache %.1f GB\n", avail / 1e9, reserve, trunk_gb, cache_gb);
+ }
+
/* fa is sized for the released 24 MLA layers with generous headroom; k3_cfg_load
* refuses a config that would overrun it rather than truncating the layer map. */
K3Cfg c; static int fa[128];
@@ -673,8 +975,22 @@ int main(int argc, char **argv)
(double)cache.nslot * cache.slot_bytes / 1e9,
100.0 * cache.nslot / (double)(92 * c.n_experts));
- /* ---- buffers ---- */
- const int Tmax = np + gen + 1;
+ /* ---- buffers ----
+ * A resumed session must hold the saved history as well as the new tokens, so the
+ * KV cache and every per-position buffer are sized for both. The header is read
+ * here, before anything is allocated; the payload is restored after. */
+ K3StateHdr shd;
+ int prior = 0;
+ if (load_state) {
+ if (!incremental) {
+ fprintf(stderr, "--load-state needs --incremental\n");
+ return 2;
+ }
+ if (k3_state_peek(load_state, &shd) != 0) return 1;
+ 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;
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;
@@ -714,11 +1030,13 @@ int main(int argc, char **argv)
* Heap and sized from the ACTUAL request, not from the ceiling. These were
* `int seq[K3_MAX_PROMPT + K3_MAX_GEN]` and `int outtok[K3_MAX_GEN]` on the stack,
* which is why the ceiling had to stay small enough to be a stack array. */
- int *seq = (int *)malloc((size_t)(np + gen + 8) * sizeof(int));
+ int *seq = (int *)malloc((size_t)(prior + np + gen + 8) * sizeof(int));
int *outtok = (int *)malloc((size_t)(gen + 8) * sizeof(int));
if (!seq || !outtok) { fprintf(stderr, "OOM allocating sequence buffers\n"); return 1; }
- memcpy(seq, prompt, (size_t)np * sizeof(int));
- int T = np;
+ /* On a resume the saved history occupies the front of the sequence and the prompt
+ * given now is its continuation; the restore below fills seq[0..prior). */
+ memcpy(seq + prior, prompt, (size_t)np * sizeof(int));
+ int T = prior + np;
int nout = 0;
/* ---- optional incremental decode ----
@@ -745,6 +1063,121 @@ int main(int argc, char **argv)
if (!w.kvc || !w.ropec) { fprintf(stderr, "KV cache allocation failed\n"); return 1; }
memset(ks, 0, kper * (size_t)NL * sizeof(float));
w.cached = 0;
+
+ if (load_state) {
+ const double tl = now_s();
+ if (k3_state_load(load_state, &c, &shd, seq, ks, w.kvc, w.ropec,
+ w.n_bound, w.n_mla, w.kv_cap) != 0)
+ return 1;
+ w.cached = shd.cached;
+ printf("restored %d positions in %.2f s: decode continues without "
+ "re-reading the prior context\n\n", w.cached, now_s() - tl);
+ }
+ }
+
+ /* --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
+ * prefix. The snapshot is one memcpy; the replay is one short batched sweep. */
+ const size_t kperP = (size_t)c.kda_heads * c.kda_head_dim;
+ const size_t kper_f = kperP * c.kda_head_dim + 3 * kperP * (c.conv_k - 1);
+ float *spec_snap = NULL;
+ if (spec_n > 0) {
+ if (!incremental) {
+ fprintf(stderr, "--spec needs --incremental; ignoring --spec\n");
+ spec_n = 0;
+ } else {
+ if (spec_n > K3_SPEC_MAX) spec_n = K3_SPEC_MAX;
+ spec_snap = (float *)malloc(kper_f * (size_t)w.n_bound * sizeof(float));
+ if (!spec_snap) { fprintf(stderr, "OOM for the --spec snapshot\n"); return 1; }
+ printf("speculative decode: up to %d drafted tokens per sweep, n-gram lookup, "
+ "verified batched\n\n", spec_n);
+ }
+ }
+
+ /* ---- hybrid decode: a second, typically quantized, trunk drafts ----
+ * The draft model shares everything that is identical between the two models: the
+ * embedding, the lm_head, the layer map, and the routed experts (the qdq derivation
+ * touches only 2D trunk tensors). It differs ONLY in trunk weights, so it needs its
+ * own trunk stream, its own layer bindings, and its own recurrent/KV state. Output
+ * exactness is structural: drafts feed the SAME batched greedy verification as
+ * --spec, so what gets emitted is precisely what the exact model would have chosen.
+ * Measured teacher-forced agreement of an int8-derived draft on the released
+ * checkpoint is 94.2 percent against a 96.2 percent measurement ceiling, which is
+ * what makes the draft worth consulting at all. */
+ static K3Trunk trunk_d;
+ Weights dw; memset(&dw, 0, sizeof dw);
+ float *dks = NULL, *dsnap = NULL;
+ long hyb_rounds = 0, hyb_drafted = 0, hyb_accepted = 0;
+ if (draft_dir) {
+ if (!incremental || !trunk_dir) {
+ fprintf(stderr, "--draft-trunk needs --incremental and --trunk; ignoring\n");
+ draft_dir = NULL;
+ } else {
+ if (spec_n <= 0) spec_n = 4;
+ if (spec_n > K3_SPEC_MAX) spec_n = K3_SPEC_MAX;
+ if (!spec_snap) {
+ spec_snap = (float *)malloc(kper_f * (size_t)w.n_bound * sizeof(float));
+ if (!spec_snap) { fprintf(stderr, "OOM for the --spec snapshot\n"); return 1; }
+ }
+ if (k3_trunk_open(&trunk_d, draft_dir, &c, (int64_t)(draft_gb * 1e9)) != 0)
+ return 1;
+ dw.lay = (K3LayerBind *)calloc((size_t)NL, sizeof(K3LayerBind));
+ dks = (float *)calloc(kper_f * (size_t)w.n_bound, sizeof(float));
+ dsnap = (float *)malloc(kper_f * (size_t)w.n_bound * sizeof(float));
+ const size_t kvperd = (size_t)w.kv_cap * c.n_heads * (c.qk_nope + c.v_head);
+ const size_t rpperd = (size_t)w.kv_cap * c.qk_rope;
+ dw.kvc = (float *)calloc(kvperd * (size_t)w.n_mla, sizeof(float));
+ dw.ropec = (float *)calloc(rpperd * (size_t)w.n_mla, sizeof(float));
+ if (!dw.lay || !dks || !dsnap || !dw.kvc || !dw.ropec) {
+ fprintf(stderr, "OOM for the draft model state\n"); return 1;
+ }
+ dw.mb = w.mb; /* embed + lm_head are the same tensors */
+ dw.trunk = &trunk_d;
+ dw.n_bound = w.n_bound;
+ dw.mla_slot = w.mla_slot; /* read-only map, safely shared */
+ dw.n_mla = w.n_mla;
+ dw.kv_cap = w.kv_cap;
+ dw.cached = 0;
+ dw.draft_mode = 1; /* cache-only routing: draft tokens read no new experts */
+ printf("hybrid decode: draft trunk %s (%.1f GB budget) proposes up to %d "
+ "tokens per sweep;\n the exact model verifies every one "
+ "before it is emitted\n\n", draft_dir, draft_gb, spec_n);
+ }
+ }
+
+ /* --tf-check: teacher-forced agreement over the whole --ids sequence in ONE sweep.
+ * Prediction i is the argmax after positions 0..i; it is compared to the id the
+ * sequence actually continues with. This is the acceptance rate a draft model
+ * would see under batched greedy verification, measured directly, and it is the
+ * one number a quantized-draft design stands on. Free-running comparisons cannot
+ * measure it: a single early divergence changes every later context. */
+ if (tf_check) {
+ if (np < 2) { fprintf(stderr, "--tf-check needs at least 2 ids\n"); return 2; }
+ int *arg = (int *)malloc((size_t)np * sizeof(int));
+ if (!arg) { fprintf(stderr, "OOM for --tf-check\n"); return 1; }
+ const double t0c = now_s();
+ if (forward(&w, &c, &cache, seq, np, lg, sc, h, br, ks, arg) != 0) {
+ fprintf(stderr, "forward failed in --tf-check\n");
+ return 1;
+ }
+ int match = 0;
+ for (int i = 0; i + 1 < np; i++) match += (arg[i] == seq[i + 1]);
+ printf("teacher-forced agreement: %d/%d positions (%.1f%%) in %.1f s\n",
+ match, np - 1, 100.0 * match / (np - 1), now_s() - t0c);
+ printf(" per-position (p=predicted a=actual): ");
+ for (int i = 0; i + 1 < np; i++)
+ if (arg[i] != seq[i + 1])
+ printf("[%d p=%d a=%d] ", i, arg[i], seq[i + 1]);
+ printf("\n");
+ FILE *tf = fopen(outp, "w");
+ if (tf) {
+ fprintf(tf, "{\"tf_positions\":%d,\"tf_matches\":%d,\"tf_agreement\":%.4f}\n",
+ np - 1, match, (double)match / (np - 1));
+ fclose(tf);
+ }
+ free(arg);
+ return 0;
}
printf("%-6s %-10s %-12s %-10s %-10s %s\n",
@@ -757,25 +1190,128 @@ int main(int argc, char **argv)
* figure against a single step would misstate the I/O share. */
double expert_s_total = 0.0, expert_gb_total = 0.0;
uint64_t expert_reqs_total = 0, expert_evict_total = 0;
- for (int g = 0; g < gen; g++) {
+ for (int g = 0; nout < gen; g++) {
k3_cache_reset_stats(&cache);
const double ts = now_s();
int frc;
- if (incremental) {
- /* step 0 feeds the whole prompt; later steps feed only the new token */
+ int emit[K3_SPEC_MAX + 1];
+ int emitn = 0;
+ if (incremental && g == 0) {
+ /* Step 0 feeds everything not yet consumed: the whole prompt on a fresh
+ * run, and on a resume the carried pending token PLUS the new prompt.
+ * T - base covers both exactly; feeding np here instead dropped the last
+ * new token from a resumed batch, and the first generated token then came
+ * from a context one token short: fluent, plausible, and wrong. */
+ const int base = w.cached;
+ const int nT0 = T - base;
+ frc = forward(&w, &c, &cache, seq + base, nT0, lg, sc, h, br, ks, NULL);
+ if (frc == 0) { w.cached = base + nT0; emit[emitn++] = argmax_(lg, c.vocab); }
+ /* The draft model must absorb the same context, or its first proposals
+ * come from a shorter one; one draft sweep, paid once. Saved state does
+ * not include the draft's, so a resumed run replays the WHOLE sequence
+ * through the draft once; correctness never depends on this, only
+ * acceptance does. */
+ if (dw.trunk && frc == 0) {
+ const int db = load_state ? 0 : base;
+ if (forward(&dw, &c, &cache, seq + db, base + nT0 - db, lg, sc, h, br,
+ dks, NULL) == 0)
+ dw.cached = base + nT0;
+ else frc = -1;
+ }
+ } else if (incremental) {
const int base = w.cached;
- const int nT = (g == 0) ? np : 1;
- frc = forward(&w, &c, &cache, seq + base, nT, lg, sc, h, br, ks);
- w.cached = base + nT;
+ int d[K3_SPEC_MAX], nd = 0;
+ if (spec_snap && T + spec_n + 1 < Tmax && base + spec_n + 1 <= w.kv_cap) {
+ if (dw.trunk) {
+ /* The draft model proposes: k sequential one-token steps through
+ * the draft trunk, chaining its own argmax. Its state is
+ * snapshotted first so a partial acceptance can rewind it the
+ * same way the exact side rewinds. */
+ memcpy(dsnap, dks, kper_f * (size_t)w.n_bound * sizeof(float));
+ int prev = seq[base];
+ while (nd < spec_n) {
+ if (forward(&dw, &c, &cache, &prev, 1, lg, sc, h, br,
+ dks, NULL) != 0) break;
+ dw.cached += 1;
+ prev = argmax_(lg, c.vocab);
+ d[nd++] = prev;
+ }
+ hyb_rounds += 1;
+ hyb_drafted += nd;
+ } else {
+ nd = spec_draft(seq, T, spec_n, d);
+ }
+ }
+ if (nd > 0) {
+ /* One sweep verifies the pending token plus nd drafts. arg[i] is the
+ * model's own next token after batch position i; the accepted prefix is
+ * exactly what serial decode would have emitted, and arg[m] after it is
+ * clean because its context contains only accepted tokens. */
+ int arg[K3_SPEC_MAX + 1];
+ memcpy(spec_snap, ks, kper_f * (size_t)w.n_bound * sizeof(float));
+ for (int i = 0; i < nd; i++) seq[T + i] = d[i];
+ frc = forward(&w, &c, &cache, seq + base, nd + 1, lg, sc, h, br, ks, arg);
+ if (frc == 0) {
+ int m = 0;
+ while (m < nd && arg[m] == d[m]) m++;
+ if (m == nd) {
+ /* every fed position had true context; state is exact */
+ w.cached = base + nd + 1;
+ } else {
+ /* the recurrent state absorbed rejected tokens: restore, then
+ * replay only the accepted prefix. The replay also rewrites the
+ * KV rows those positions touched, so nothing stale survives. */
+ memcpy(ks, spec_snap, kper_f * (size_t)w.n_bound * sizeof(float));
+ w.cached = base;
+ frc = forward(&w, &c, &cache, seq + base, m + 1, lg, sc, h, br,
+ ks, NULL);
+ if (frc == 0) w.cached = base + m + 1;
+ }
+ /* Resync the draft model to the ACCEPTED sequence. On full
+ * acceptance its state already contains every fed token except
+ * the last draft, so one step closes the gap; on partial
+ * acceptance it rewinds to its snapshot and replays only the
+ * accepted prefix, mirroring the exact side. */
+ if (dw.trunk && frc == 0) {
+ hyb_accepted += m;
+ if (m == nd) {
+ int last = d[nd - 1];
+ if (forward(&dw, &c, &cache, &last, 1, lg, sc, h, br,
+ dks, NULL) == 0) dw.cached += 1;
+ else frc = -1;
+ } else {
+ memcpy(dks, dsnap, kper_f * (size_t)w.n_bound * sizeof(float));
+ dw.cached = base;
+ if (forward(&dw, &c, &cache, seq + base, m + 1, lg, sc,
+ h, br, dks, NULL) == 0) dw.cached = base + m + 1;
+ else frc = -1;
+ }
+ }
+ if (frc == 0) {
+ for (int i = 0; i < m; i++) emit[emitn++] = d[i];
+ emit[emitn++] = arg[m];
+ }
+ }
+ } else {
+ frc = forward(&w, &c, &cache, seq + base, 1, lg, sc, h, br, ks, NULL);
+ if (frc == 0) { w.cached = base + 1; emit[emitn++] = argmax_(lg, c.vocab); }
+ /* keep the draft in lockstep through non-drafted steps */
+ if (dw.trunk && frc == 0) {
+ if (forward(&dw, &c, &cache, seq + base, 1, lg, sc, h, br,
+ dks, NULL) == 0) dw.cached = base + 1;
+ else frc = -1;
+ }
+ }
} else {
- frc = forward(&w, &c, &cache, seq, T, lg, sc, h, br, ks);
+ frc = forward(&w, &c, &cache, seq, T, lg, sc, h, br, ks, NULL);
+ if (frc == 0) emit[emitn++] = argmax_(lg, c.vocab);
}
/* Abort the run rather than argmax a buffer the forward never wrote. */
- if (frc != 0) {
+ if (frc != 0 || emitn == 0) {
fprintf(stderr, "forward pass failed at generation step %d; aborting.\n", g);
return 1;
}
- const int nxt = argmax_(lg, c.vocab);
+ const int nxt = emit[emitn - 1];
/* Dump the FIRST step's logits as raw float32 bits.
* Comparing generated tokens against a reference only compares argmax, which
* hides near-ties: two engines can agree on every token while disagreeing
@@ -805,10 +1341,42 @@ int main(int argc, char **argv)
expert_gb_total += (double)cache.bytes_read / 1e9;
expert_reqs_total += cache.hits + cache.misses;
expert_evict_total += cache.evictions;
- seq[T++] = nxt;
- outtok[nout++] = nxt;
+ for (int i = 0; i < emitn && nout < gen && T < Tmax; i++) {
+ seq[T++] = emit[i];
+ outtok[nout++] = emit[i];
+ }
if (T >= Tmax) break;
}
+ if (save_state) {
+ if (!incremental) {
+ fprintf(stderr, "--save-state needs --incremental; nothing written\n");
+ } else {
+ const double tsv = now_s();
+ const int64_t kvpp = (int64_t)c.n_heads * (c.qk_nope + c.v_head);
+ const int64_t ropepp = (int64_t)c.qk_rope;
+ if (k3_state_save(save_state, &c, seq, T, ks, w.kvc, w.ropec,
+ w.n_bound, w.n_mla, w.kv_cap, w.cached,
+ (int64_t)kper, kvpp, ropepp) == 0) {
+ const double bytes = (double)sizeof(K3StateHdr) + (double)T * sizeof(int)
+ + (double)kper * w.n_bound * sizeof(float)
+ + (double)w.cached * (kvpp + ropepp) * w.n_mla * sizeof(float);
+ char sb[32]; human(bytes, sb, sizeof sb);
+ printf("wrote %s (%s, %d positions) in %.2f s\n",
+ save_state, sb, w.cached, now_s() - tsv);
+ }
+ }
+ }
+
+ if (dw.trunk && hyb_rounds > 0) {
+ printf("\nhybrid decode: %ld rounds, %ld drafted, %ld accepted (%.1f%%), "
+ "mean accepted run %.2f\n",
+ hyb_rounds, hyb_drafted, hyb_accepted,
+ hyb_drafted ? 100.0 * hyb_accepted / hyb_drafted : 0.0,
+ (double)hyb_accepted / hyb_rounds);
+ k3_trunk_close(&trunk_d);
+ free(dw.lay); free(dks); free(dsnap); free(dw.kvc); free(dw.ropec);
+ }
+ free(spec_snap);
printf("--------------------------------------------------------------------\n");
printf("%d tokens in %.1f s, %.2f s/token average\n", nout, t_total, t_total / nout);
diff --git a/src/core/k3_ops.c b/src/core/k3_ops.c
index 417c3b8..d5b3364 100644
--- a/src/core/k3_ops.c
+++ b/src/core/k3_ops.c
@@ -247,16 +247,23 @@ void k3_matmul(float *y, const float *x, const float *W, int in, int out)
#endif
for (int o = 0; o < out; o++) {
const float *row = W + (size_t)o * in;
- double a0 = 0.0, a1 = 0.0, a2 = 0.0, a3 = 0.0;
+ /* Sixteen accumulators, EXPLICITLY fused products. fma() in double is the
+ * same IEEE operation as _mm256_fmadd_pd per lane, so the scalar and vector
+ * paths stay bit-identical while the dependent-add latency chain that made
+ * one accumulator ~10x slower than the machine's floor disappears. The
+ * reduction pairs lanes exactly the way the vector path's (v0+v1)+(v2+v3)
+ * then cross-lane tree does; change one and you must change the other. */
+ double a[16] = {0};
int i = 0;
- for (; i + 3 < in; i += 4) {
- a0 += (double)row[i ] * (double)x[i ];
- a1 += (double)row[i + 1] * (double)x[i + 1];
- a2 += (double)row[i + 2] * (double)x[i + 2];
- a3 += (double)row[i + 3] * (double)x[i + 3];
- }
- double acc = (a0 + a1) + (a2 + a3);
- for (; i < in; i++) acc += (double)row[i] * (double)x[i];
+ for (; i + 15 < in; i += 16)
+ for (int l = 0; l < 16; l++)
+ a[l] = fma((double)row[i + l], (double)x[i + l], a[l]);
+ double b0 = (a[0] + a[4]) + (a[8] + a[12]);
+ double b1 = (a[1] + a[5]) + (a[9] + a[13]);
+ double b2 = (a[2] + a[6]) + (a[10] + a[14]);
+ double b3 = (a[3] + a[7]) + (a[11] + a[15]);
+ double acc = (b0 + b1) + (b2 + b3);
+ for (; i < in; i++) acc = fma((double)row[i], (double)x[i], acc);
y[o] = (float)acc;
}
}
@@ -547,6 +554,22 @@ void k3_moe(float *out, const float *x, const K3MoeW *w, const K3Cfg *c,
k3_router(idx, wt, xt, w->gate, w->bias, E, c->n_experts, c->topk,
c->moe_renorm, c->routed_scale);
+ int nk = c->topk;
+ /* Draft cache-only routing: keep only the top-k experts already resident, and
+ * renormalise their weights so the mixture still sums as intended. This makes a
+ * draft token read ZERO new expert bytes. It is an approximation, which is exactly
+ * what a draft is; the exact model verifies every proposed token. */
+ if (w->cache_only && w->src && w->src->resident) {
+ int m = 0; float wsum = 0.0f;
+ for (int j = 0; j < c->topk; j++) {
+ if (w->src->resident(w->src, w->layer, idx[j], NULL)) {
+ idx[m] = idx[j]; wt[m] = wt[j]; wsum += wt[j]; m++;
+ }
+ }
+ nk = m;
+ if (wsum > 0.0f) for (int j = 0; j < nk; j++) wt[j] /= wsum;
+ }
+
/* 2. down-project into the latent space */
k3_mmw(z, xt, w->down, w->wdt, E, L);
@@ -557,20 +580,24 @@ void k3_moe(float *out, const float *x, const K3MoeW *w, const K3Cfg *c,
* again: a queue depth of one against a drive that needs depth to reach its
* rated bandwidth. getmany is optional and may be NULL, in which case nothing
* changes and the loop reads them one at a time exactly as before. */
- if (w->src && w->src->getmany) w->src->getmany(w->src, w->layer, idx, c->topk);
- for (int j = 0; j < c->topk; j++) {
+ if (!w->cache_only && w->src && w->src->getmany)
+ w->src->getmany(w->src, w->layer, idx, nk);
+ for (int j = 0; j < nk; j++) {
if (w->src) {
- /* Streamed: the expert stays MXFP4 and the matmul reads nibbles. */
+ /* Streamed: the expert stays MXFP4 and the matmul reads nibbles. In
+ * cache-only mode every idx[j] is known resident, so resident() serves it
+ * with no disk read; otherwise get() may read it. */
K3ExpertQ q;
- if (w->src->get(w->src, w->layer, idx[j], &q) != 0) {
- /* Never drop an expert silently. A bare `continue` here is
- * invisible from the outside: one transient short read or EIO
- * leaves this token's routed output missing 1/16 of its weighted
- * sum, the run completes, prints a plausible token, and reports
- * success. Wrong output that looks right is the worst failure this
- * engine can produce, so the drop is counted in the global
- * k3_expert_drops and every caller MUST fail the run on a non-zero
- * count (src/cli/k3_run.c does; see docs/API.md). */
+ int miss = w->cache_only
+ ? !w->src->resident(w->src, w->layer, idx[j], &q)
+ : (w->src->get(w->src, w->layer, idx[j], &q) != 0);
+ if (miss) {
+ /* A cache-only draft filtered to resident experts already, so a miss
+ * here is a benign race at worst; skip it, since the draft is
+ * approximate by construction and the exact model verifies. On the
+ * exact path a miss is the unacceptable silent-corruption case: count
+ * it in k3_expert_drops so the caller fails the run (see docs/API.md). */
+ if (w->cache_only) continue;
k3_expert_drops++;
fprintf(stderr, "EXPERT DROP: layer %d expert %d failed to load; "
"this token is CORRUPT\n", w->layer, idx[j]);
@@ -616,6 +643,148 @@ size_t k3_moe_scratch(const K3Cfg *c)
+ (size_t)c->hidden; /* sdn */
}
+/* Batched MoE for PREFILL over a chunk of T tokens, streamed experts only.
+ *
+ * k3_moe walks the top-k for each token independently, so across a T-token chunk it
+ * fetches an expert once per token that routes to it. Under near-uniform routing that is
+ * mostly waste: measured on the released trace, a 32-token chunk touches only ~2.7x fewer
+ * unique experts than 16*32 draws, so reading each unique expert ONCE and reusing it for
+ * every token in the chunk cuts prefill expert bytes ~3-4x. Prefill is where that matters,
+ * because decode feeds one token at a time and has nothing to batch.
+ *
+ * Exactness is preserved to the last bit. Per token the arithmetic is identical to
+ * k3_moe: the routed latent contributions are accumulated in the ORIGINAL top-k order
+ * (j = 0..k-1) from a per-(token, slot) buffer, then normalised, up-projected and given
+ * the shared expert exactly as before. Only the ORDER in which experts are fetched from
+ * disk changes, and that touches no floating-point result.
+ *
+ * out/x are [T][E], idx/wt scratch are topk-wide (reused per token), scratch is one
+ * k3_moe_scratch. This path requires w->src (streamed); the resident path stays on
+ * k3_moe, which is what the oracle gates exercise. */
+static void moe_prefill_chunk(float *out, const float *x, const K3MoeW *w,
+ const K3Cfg *c, int T, float *scratch);
+
+void k3_moe_prefill(float *out, const float *x, const K3MoeW *w, const K3Cfg *c,
+ int T, int *idx, float *wt, float *scratch)
+{
+ /* K3_NO_BATCH_PREFILL forces the per-token path, so one binary can produce both the
+ * batched and the reference token streams for a bit-identity A/B. */
+ static int no_batch = -1;
+ if (no_batch < 0) no_batch = getenv("K3_NO_BATCH_PREFILL") ? 1 : 0;
+ /* cache_only renormalises per token over the resident subset, which the per-token
+ * path already does; the draft's prompt prefill is one-time, so defer rather than
+ * duplicate the renorm in the batch. */
+ if (!w->src || T <= 1 || no_batch || w->cache_only) {
+ k3_moe(out, x, w, c, T, idx, wt, scratch);
+ return;
+ }
+ /* Fixed sub-chunks bound the contribution buffer (14.7 MB at 64 tokens) no matter
+ * how long the prompt is; a 32k prefill would otherwise want 7.3 GB of it. Most of
+ * the dedup is already captured at this width: the unique-expert count grows far
+ * slower than the request count under near-uniform routing. */
+ const int CHUNK = 64;
+ for (int t0 = 0; t0 < T; t0 += CHUNK) {
+ const int n = (T - t0) < CHUNK ? (T - t0) : CHUNK;
+ if (n == 1) { k3_moe(out + (size_t)t0 * c->hidden, x + (size_t)t0 * c->hidden,
+ w, c, 1, idx, wt, scratch); continue; }
+ moe_prefill_chunk(out + (size_t)t0 * c->hidden, x + (size_t)t0 * c->hidden,
+ w, c, n, scratch);
+ }
+}
+
+static void moe_prefill_chunk(float *out, const float *x, const K3MoeW *w,
+ const K3Cfg *c, int T, float *scratch)
+{
+ const int E = c->hidden, Ll = c->latent, I = c->moe_inter;
+ const int SI = I * c->n_shared, K = c->topk;
+
+ /* Per-token routing decisions and latent inputs, plus a contribution buffer holding
+ * every routed expert's latent output for every token: [T][K][Ll]. At T=32, K=16,
+ * Ll=3584 that is ~7.3 MB, trivial beside the tens of GB already reserved. */
+ int *ridx = (int *) malloc((size_t)T * K * sizeof(int));
+ float *rwt = (float *)malloc((size_t)T * K * sizeof(float));
+ float *zz = (float *)malloc((size_t)T * Ll * sizeof(float));
+ float *contrib = (float *)malloc((size_t)T * K * Ll * sizeof(float));
+ if (!ridx || !rwt || !zz || !contrib)
+ k3_fatal_oom("MoE prefill batch", (size_t)T * K * Ll * sizeof(float));
+
+ /* 1. route every token and down-project it, and collect the batch's unique experts. */
+ int *uniq = (int *)malloc((size_t)T * K * sizeof(int));
+ char *seen = (char *)calloc((size_t)c->n_experts, 1);
+ if (!uniq || !seen) k3_fatal_oom("MoE prefill index", (size_t)c->n_experts);
+ int nu = 0;
+ for (int t = 0; t < T; t++) {
+ const float *xt = x + (size_t)t * E;
+ int *it = ridx + (size_t)t * K;
+ float *wtt = rwt + (size_t)t * K;
+ k3_router(it, wtt, xt, w->gate, w->bias, E, c->n_experts, K,
+ c->moe_renorm, c->routed_scale);
+ k3_mmw(zz + (size_t)t * Ll, xt, w->down, w->wdt, E, Ll);
+ for (int j = 0; j < K; j++) {
+ const int e = it[j];
+ if (e >= 0 && e < c->n_experts && !seen[e]) { seen[e] = 1; uniq[nu++] = e; }
+ }
+ }
+
+ /* 2. expert-major: fetch each unique expert ONCE, apply it to every (token, slot)
+ * that selected it. gu/act/edn are reused per (expert, token). */
+ float *gu = scratch; /* [2*I] */
+ float *act = gu + 2 * I; /* [I] */
+ float *edn = act + I; /* [Ll] */
+ if (w->src->getmany) w->src->getmany(w->src, w->layer, uniq, nu);
+ for (int u = 0; u < nu; u++) {
+ const int e = uniq[u];
+ K3ExpertQ q;
+ if (w->src->get(w->src, w->layer, e, &q) != 0) {
+ k3_expert_drops++;
+ fprintf(stderr, "EXPERT DROP: layer %d expert %d failed to load; "
+ "this chunk is CORRUPT\n", w->layer, e);
+ continue;
+ }
+ for (int t = 0; t < T; t++) {
+ const int *it = ridx + (size_t)t * K;
+ const float *zt = zz + (size_t)t * Ll;
+ for (int j = 0; j < K; j++) {
+ if (it[j] != e) continue;
+ k3_matmul_mxfp4(gu, zt, q.p1, q.s1, Ll, I, K3_MXFP4_GROUP);
+ k3_matmul_mxfp4(gu + I, zt, q.p3, q.s3, Ll, I, K3_MXFP4_GROUP);
+ k3_situ_glu(act, gu, I, c->situ_b1, c->situ_b2);
+ k3_matmul_mxfp4(edn, act, q.p2, q.s2, I, Ll, K3_MXFP4_GROUP);
+ memcpy(contrib + ((size_t)t * K + j) * Ll, edn, (size_t)Ll * sizeof(float));
+ }
+ }
+ }
+
+ /* 3. per token, sum contributions in the ORIGINAL top-k order, then the tail of the
+ * MoE exactly as k3_moe does it, so every float matches the per-token path. */
+ for (int t = 0; t < T; t++) {
+ const float *xt = x + (size_t)t * E;
+ float *ot = out + (size_t)t * E;
+ const float *wtt = rwt + (size_t)t * K;
+ /* Reuse this token's now-dead down-projection slot as the aggregate. */
+ float *acc = zz + (size_t)t * Ll;
+ for (int i = 0; i < Ll; i++) acc[i] = 0.0f;
+ for (int j = 0; j < K; j++) {
+ const float wj = wtt[j];
+ const float *cb = contrib + ((size_t)t * K + j) * Ll;
+ for (int i = 0; i < Ll; i++) acc[i] += wj * cb[i];
+ }
+ if (c->latent_norm) k3_rmsnorm(acc, acc, w->latent_norm, Ll, c->rms_eps);
+ k3_mmw(ot, acc, w->up, w->wdt, Ll, E);
+
+ float *sgu = gu; /* [2*SI] */
+ float *sact = sgu + 2 * SI; /* [SI] */
+ float *sdn = sact + SI; /* [E] */
+ k3_mmw(sgu, xt, w->sh1, w->wdt, E, SI);
+ k3_mmw(sgu + SI, xt, w->sh3, w->wdt, E, SI);
+ k3_situ_glu(sact, sgu, SI, c->situ_b1, c->situ_b2);
+ k3_mmw(sdn, sact, w->sh2, w->wdt, SI, E);
+ for (int i = 0; i < E; i++) ot[i] += sdn[i];
+ }
+
+ free(ridx); free(rwt); free(zz); free(contrib); free(uniq); free(seen);
+}
+
/* --------------------------------------------------------- KDA full layer ---- */
/* L2 normalisation over the last dimension. The reference uses the SUM of squares
* with eps inside the rsqrt, NOT the mean: k3_ref.py l2norm(). Using the mean here
@@ -694,13 +863,26 @@ void k3_kda_layer(float *out, const float *x, const K3KdaW *w, const K3Cfg *c,
S = Sown;
}
const float qscale = 1.0f / sqrtf((float)D);
- for (int t = 0; t < T; t++)
- for (int h = 0; h < H; h++) {
+ /* Heads are independent: each reads and writes only its own S block, its own D-wide
+ * slice of q/k/v/al/o, and its own beta column. The recurrence is sequential in t
+ * WITHIN a head, so the loops nest head-outer here and each head walks its own t in
+ * order; per-head arithmetic is untouched and the results are bit-identical to the
+ * serial form (gated by test_ops' kda fixtures under 1 vs N threads). The recurrence
+ * is 0.4% of FLOPs but, serial, it is a majority of non-matmul wall time at high
+ * core counts. wr is a full P-wide work row, so wr + h*D gives each head a private
+ * slice with no new allocation. */
+#ifdef _OPENMP
+#pragma omp parallel for schedule(static)
+#endif
+ for (int h = 0; h < H; h++) {
+ float *wh = wr + (size_t)h * D;
+ for (int t = 0; t < T; t++) {
const size_t off = (size_t)t * P + (size_t)h * D;
- for (int i = 0; i < D; i++) wr[i] = q[off + i] * qscale;
- k3_kda_step(S + (size_t)h * D * D, o + off, wr, k + off, v + off,
+ for (int i = 0; i < D; i++) wh[i] = q[off + i] * qscale;
+ k3_kda_step(S + (size_t)h * D * D, o + off, wh, k + off, v + off,
al + off, bt[(size_t)t * H + h], D, D);
}
+ }
/* 7/8/9. head-wise RMSNorm, THEN the gate, THEN the output projection */
for (int t = 0; t < T; t++) {
@@ -814,7 +996,10 @@ void k3_decoder_layer_inc(float *h, float *block_residual, int *n_blocks,
if (w->moe) {
int idx[K3_MAX_TOPK]; float wt[K3_MAX_TOPK];
- k3_moe(tmp, hin, w->moe, c, T, idx, wt, sub);
+ /* Prefill batches (T > 1, streamed source) fetch each unique expert once for
+ * the whole chunk; decode (T == 1) and the resident path fall straight through
+ * to k3_moe inside, byte-identical. */
+ k3_moe_prefill(tmp, hin, w->moe, c, T, idx, wt, sub);
} else {
for (int t = 0; t < T; t++) {
k3_mmw(dgu, hin + (size_t)t * E, w->dense_gate, w->wdt, E, c->dense_inter);
@@ -889,34 +1074,111 @@ void k3_matmul_bf16(float *y, const float *x, const uint16_t *W, int in, int out
double acc;
#if defined(__AVX2__)
{
- __m256d v = _mm256_setzero_pd();
- for (; i + 3 < in; i += 4) {
- /* bf16 -> f32 is a 16-bit left shift, so widen the four u16 to u32,
- * shift, and reinterpret. No table, no rounding. */
- const __m128i h = _mm_loadl_epi64((const __m128i *)(row + i));
- const __m128i b32 = _mm_slli_epi32(_mm_cvtepu16_epi32(h), 16);
- const __m256d wd = _mm256_cvtps_pd(_mm_castsi128_ps(b32));
- const __m256d xd = _mm256_cvtps_pd(_mm_loadu_ps(x + i));
- v = _mm256_add_pd(v, _mm256_mul_pd(wd, xd)); /* NOT fmadd: see above */
+ /* Four vector accumulators, fused. _mm256_fmadd_pd per lane is the same
+ * IEEE operation as scalar fma() in double, and the reduction below is
+ * lane-for-lane the tree k3_matmul's sixteen scalar accumulators use, so
+ * the two kernels remain BITWISE identical (test_ops asserts it). The old
+ * one-accumulator mul+add form serialized on add latency at 4 elements
+ * per ~4 cycles; this runs the memory-bound side of the roof instead. */
+ __m256d v0 = _mm256_setzero_pd(), v1 = _mm256_setzero_pd();
+ __m256d v2 = _mm256_setzero_pd(), v3 = _mm256_setzero_pd();
+ for (; i + 15 < in; i += 16) {
+ /* bf16 -> f32 is a 16-bit left shift, so widen u16 to u32, shift,
+ * and reinterpret. No table, no rounding. */
+ const __m128i h0 = _mm_loadl_epi64((const __m128i *)(row + i));
+ const __m128i h1 = _mm_loadl_epi64((const __m128i *)(row + i + 4));
+ const __m128i h2 = _mm_loadl_epi64((const __m128i *)(row + i + 8));
+ const __m128i h3 = _mm_loadl_epi64((const __m128i *)(row + i + 12));
+ v0 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm_castsi128_ps(_mm_slli_epi32(_mm_cvtepu16_epi32(h0), 16))),
+ _mm256_cvtps_pd(_mm_loadu_ps(x + i)), v0);
+ v1 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm_castsi128_ps(_mm_slli_epi32(_mm_cvtepu16_epi32(h1), 16))),
+ _mm256_cvtps_pd(_mm_loadu_ps(x + i + 4)), v1);
+ v2 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm_castsi128_ps(_mm_slli_epi32(_mm_cvtepu16_epi32(h2), 16))),
+ _mm256_cvtps_pd(_mm_loadu_ps(x + i + 8)), v2);
+ v3 = _mm256_fmadd_pd(
+ _mm256_cvtps_pd(_mm_castsi128_ps(_mm_slli_epi32(_mm_cvtepu16_epi32(h3), 16))),
+ _mm256_cvtps_pd(_mm_loadu_ps(x + i + 12)), v3);
}
+ /* (v0+v1)+(v2+v3) lanewise, then the same cross-lane pairing as scalar */
+ const __m256d vt = _mm256_add_pd(_mm256_add_pd(v0, v1),
+ _mm256_add_pd(v2, v3));
double a[4];
- _mm256_storeu_pd(a, v);
+ _mm256_storeu_pd(a, vt);
acc = (a[0] + a[1]) + (a[2] + a[3]);
}
#else
{
- double a0 = 0.0, a1 = 0.0, a2 = 0.0, a3 = 0.0;
+ double a[16] = {0};
+ for (; i + 15 < in; i += 16)
+ for (int l = 0; l < 16; l++)
+ a[l] = fma((double)k3_bf16f(row[i + l]), (double)x[i + l], a[l]);
+ double b0 = (a[0] + a[4]) + (a[8] + a[12]);
+ double b1 = (a[1] + a[5]) + (a[9] + a[13]);
+ double b2 = (a[2] + a[6]) + (a[10] + a[14]);
+ double b3 = (a[3] + a[7]) + (a[11] + a[15]);
+ acc = (b0 + b1) + (b2 + b3);
+ }
+#endif
+ for (; i < in; i++) acc = fma((double)k3_bf16f(row[i]), (double)x[i], acc);
+ y[o] = (float)acc;
+ }
+}
+
+/* Per-row int8 matmul for the draft model: each row is [f32 scale][int8 * in]. The int8
+ * weights are widened to float, dotted with the fp32 activation, and the row's scale is
+ * applied once at the end. Unlike the trunk kernels this carries NO cross-path
+ * determinism contract (K3_WI8 is draft-only, and the exact model decides every emitted
+ * token), so it accumulates in float with fused products and the natural AVX2 reduction,
+ * which is what makes it fast. */
+void k3_matmul_q8(float *y, const float *x, const void *W, int in, int out)
+{
+ const unsigned char *base = (const unsigned char *)W;
+ const size_t rowb = (size_t)4 + (size_t)in;
+#ifdef _OPENMP
+#pragma omp parallel for schedule(static) if (out > 64)
+#endif
+ for (int o = 0; o < out; o++) {
+ const unsigned char *row = base + (size_t)o * rowb;
+ float scale;
+ memcpy(&scale, row, 4);
+ const int8_t *w = (const int8_t *)(row + 4);
+ int i = 0;
+ float acc;
+#if defined(__AVX2__)
+ {
+ __m256 v0 = _mm256_setzero_ps(), v1 = _mm256_setzero_ps();
+ for (; i + 15 < in; i += 16) {
+ const __m128i b0 = _mm_loadl_epi64((const __m128i *)(w + i));
+ const __m128i b1 = _mm_loadl_epi64((const __m128i *)(w + i + 8));
+ v0 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b0)),
+ _mm256_loadu_ps(x + i), v0);
+ v1 = _mm256_fmadd_ps(_mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(b1)),
+ _mm256_loadu_ps(x + i + 8), v1);
+ }
+ __m256 vs = _mm256_add_ps(v0, v1);
+ __m128 lo = _mm_add_ps(_mm256_castps256_ps128(vs),
+ _mm256_extractf128_ps(vs, 1));
+ lo = _mm_add_ps(lo, _mm_movehl_ps(lo, lo));
+ lo = _mm_add_ss(lo, _mm_shuffle_ps(lo, lo, 1));
+ acc = _mm_cvtss_f32(lo);
+ }
+#else
+ {
+ float a0 = 0, a1 = 0, a2 = 0, a3 = 0;
for (; i + 3 < in; i += 4) {
- a0 += (double)k3_bf16f(row[i ]) * (double)x[i ];
- a1 += (double)k3_bf16f(row[i + 1]) * (double)x[i + 1];
- a2 += (double)k3_bf16f(row[i + 2]) * (double)x[i + 2];
- a3 += (double)k3_bf16f(row[i + 3]) * (double)x[i + 3];
+ a0 += (float)w[i] * x[i];
+ a1 += (float)w[i + 1] * x[i + 1];
+ a2 += (float)w[i + 2] * x[i + 2];
+ a3 += (float)w[i + 3] * x[i + 3];
}
acc = (a0 + a1) + (a2 + a3);
}
#endif
- for (; i < in; i++) acc += (double)k3_bf16f(row[i]) * (double)x[i];
- y[o] = (float)acc;
+ for (; i < in; i++) acc += (float)w[i] * x[i];
+ y[o] = acc * scale;
}
}
@@ -1027,30 +1289,39 @@ void k3_matmul_mxfp4(float *y, const float *x, const unsigned char *packed,
*
* The lane split changes the summation order. See the accuracy contract on
* the function above for why that is bounded at ~1e-16 relative. */
- double s0 = 0.0, s1 = 0.0, s2 = 0.0, s3 = 0.0;
+ /* Two fused vector accumulators over the 32-element group, element i to
+ * accumulator (i/4)%2, lanewise-summed then cross-lane paired; the scalar
+ * path is the identical partition with fma(), which is the same IEEE
+ * operation, so both paths stay bit-identical. Same reasoning as the
+ * fp32/bf16 kernels above; the group is short, so two accumulators
+ * suffice to break the add-latency chain. */
+ double sub;
int i = 0;
#if defined(__AVX2__)
{
- __m256d v = _mm256_setzero_pd();
- for (; i + 3 < n; i += 4) {
- const __m256d wd = _mm256_cvtps_pd(_mm_loadu_ps(wf + i));
- const __m256d xd = _mm256_cvtps_pd(_mm_loadu_ps(xg + i));
- v = _mm256_add_pd(v, _mm256_mul_pd(wd, xd)); /* not fmadd */
+ __m256d v0 = _mm256_setzero_pd(), v1 = _mm256_setzero_pd();
+ for (; i + 7 < n; i += 8) {
+ v0 = _mm256_fmadd_pd(_mm256_cvtps_pd(_mm_loadu_ps(wf + i)),
+ _mm256_cvtps_pd(_mm_loadu_ps(xg + i)), v0);
+ v1 = _mm256_fmadd_pd(_mm256_cvtps_pd(_mm_loadu_ps(wf + i + 4)),
+ _mm256_cvtps_pd(_mm_loadu_ps(xg + i + 4)), v1);
}
double a[4];
- _mm256_storeu_pd(a, v);
- s0 = a[0]; s1 = a[1]; s2 = a[2]; s3 = a[3];
+ _mm256_storeu_pd(a, _mm256_add_pd(v0, v1));
+ sub = (a[0] + a[1]) + (a[2] + a[3]);
}
#else
- for (; i + 3 < n; i += 4) {
- s0 += (double)wf[i ] * (double)xg[i ];
- s1 += (double)wf[i + 1] * (double)xg[i + 1];
- s2 += (double)wf[i + 2] * (double)xg[i + 2];
- s3 += (double)wf[i + 3] * (double)xg[i + 3];
+ {
+ double s[8] = {0};
+ for (; i + 7 < n; i += 8)
+ for (int l = 0; l < 8; l++)
+ s[l] = fma((double)wf[i + l], (double)xg[i + l], s[l]);
+ double b0 = s[0] + s[4], b1 = s[1] + s[5];
+ double b2 = s[2] + s[6], b3 = s[3] + s[7];
+ sub = (b0 + b1) + (b2 + b3);
}
#endif
- double sub = (s0 + s1) + (s2 + s3);
- for (; i < n; i++) sub += (double)wf[i] * (double)xg[i];
+ for (; i < n; i++) sub = fma((double)wf[i], (double)xg[i], sub);
acc += sub * (double)K3_E8M0[sb];
}
y[r] = (float)acc;
diff --git a/src/io/k3_st.h b/src/io/k3_st.h
index d77d7a9..495e10f 100644
--- a/src/io/k3_st.h
+++ b/src/io/k3_st.h
@@ -30,7 +30,10 @@
#include <stddef.h>
#include <stdint.h>
-typedef enum { K3_DT_UNKNOWN = 0, K3_DT_U8, K3_DT_BF16, K3_DT_F16, K3_DT_F32 } K3Dtype;
+/* K3_DT_I8R is the packed trunk's per-row int8 draft format: each row is [f32 scale]
+ * [int8 * cols]. It only ever appears in a draft trunk written by tools/int8_trunk.py. */
+typedef enum { K3_DT_UNKNOWN = 0, K3_DT_U8, K3_DT_BF16, K3_DT_F16, K3_DT_F32,
+ K3_DT_I8R } K3Dtype;
typedef struct {
char *name;
diff --git a/src/io/k3_trunk.c b/src/io/k3_trunk.c
index 83b8c9d..81e4613 100644
--- a/src/io/k3_trunk.c
+++ b/src/io/k3_trunk.c
@@ -62,6 +62,7 @@ static int dt_of(const char *s)
if (!strcmp(s, "F32")) return K3_DT_F32;
if (!strcmp(s, "U8")) return K3_DT_U8;
if (!strcmp(s, "F16")) return K3_DT_F16;
+ if (!strcmp(s, "I8R")) return K3_DT_I8R;
return K3_DT_UNKNOWN;
}
diff --git a/src/model/k3_bind.c b/src/model/k3_bind.c
index 1874b22..91391f6 100644
--- a/src/model/k3_bind.c
+++ b/src/model/k3_bind.c
@@ -331,6 +331,7 @@ int k3_bind_layer_mem(const K3Cfg *c, int L, K3LayerBind *b,
size_t w = 0;
int narrowed_all = 1;
+ int i8_seen = 0;
for (int i = 0; i < p.n; i++) {
Req *q = &p.r[i];
int64_t off = 0, nb = 0; int dt = 0;
@@ -338,6 +339,52 @@ int k3_bind_layer_mem(const K3Cfg *c, int L, K3LayerBind *b,
fprintf(stderr, "k3_bind_mem: %s not present in the packed run\n", q->name);
return -1;
}
+ /* Per-row int8 draft weight: [f32 scale][int8 * cols] per row. A matmul weight is
+ * pointed at directly and the layer is tagged K3_WI8; a tensor the engine reads
+ * elementwise as fp32 (the AttnRes projection) is DEQUANTISED into the widen
+ * buffer here, row scale times int8, exactly parallel to the bf16 widen path.
+ * The element-count check does not apply to the scale-interleaved layout; the
+ * packer owns the shape. */
+ if (dt == K3_DT_I8R) {
+ if (q->narrow) {
+ *q->dest = run + off;
+ i8_seen = 1;
+ continue;
+ }
+ /* want fp32: dequantise. take is the logical element count (rows*cols); the
+ * row width is derivable because each row is [4 bytes scale][cols int8] and
+ * nb = rows*(4+cols) with rows*cols == take. Solve rows from nb and take. */
+ const int64_t take = q->take;
+ /* nb = rows*4 + take -> rows = (nb - take)/4 */
+ if ((nb - take) % 4 != 0) {
+ fprintf(stderr, "k3_bind_mem: %s bad int8 layout\n", q->name);
+ return -1;
+ }
+ const int64_t rows = (nb - take) / 4;
+ if (rows <= 0 || take % rows != 0) {
+ fprintf(stderr, "k3_bind_mem: %s bad int8 shape\n", q->name);
+ return -1;
+ }
+ const int64_t cols = take / rows;
+ w = (w + 7u) & ~(size_t)7u;
+ if (w + (size_t)take * 4 > widen_cap) {
+ fprintf(stderr, "k3_bind_mem: widen area too small at %s\n", q->name);
+ return -1;
+ }
+ float *dst = (float *)(widen + w);
+ const unsigned char *rp = run + off;
+ const size_t rowb = 4u + (size_t)cols;
+ for (int64_t r = 0; r < rows; r++) {
+ float scale;
+ memcpy(&scale, rp + (size_t)r * rowb, 4);
+ const signed char *q8 = (const signed char *)(rp + (size_t)r * rowb + 4);
+ for (int64_t k = 0; k < cols; k++)
+ dst[r * cols + k] = (float)q8[k] * scale;
+ }
+ *q->dest = dst;
+ w += (size_t)take * 4;
+ continue;
+ }
const int esz = (dt == K3_DT_F32) ? 4 : (dt == K3_DT_U8 ? 1 : 2);
const int64_t have = nb / esz;
if (q->want >= 0 && have != q->want) {
@@ -377,14 +424,17 @@ int k3_bind_layer_mem(const K3Cfg *c, int L, K3LayerBind *b,
w += (size_t)q->take * 4;
}
- if (!narrowed_all) {
+ if (!narrowed_all && !i8_seen) {
/* A large matrix was not BF16 in the packed run. The tag is per struct, so this
* cannot be described; refuse rather than read fp32 bytes as bf16. */
fprintf(stderr, "k3_bind_mem: layer %d has a non-BF16 large tensor\n", L);
return -1;
}
- b->kda.wdt = b->mla.wdt = b->moe.wdt = b->lay.wdt = K3_WBF16;
+ /* An int8 draft trunk has every matmul weight as I8R (norms stay f32), so one tag
+ * describes the layer. The two formats are never mixed within a packed trunk. */
+ const int lw = i8_seen ? K3_WI8 : K3_WBF16;
+ b->kda.wdt = b->mla.wdt = b->moe.wdt = b->lay.wdt = lw;
b->lay.kda = is_mla ? NULL : &b->kda;
b->lay.mla = is_mla ? &b->mla : NULL;
b->lay.moe = is_dense ? NULL : &b->moe;
diff --git a/tools/int8_trunk.py b/tools/int8_trunk.py
new file mode 100644
index 0000000..99e0d15
--- /dev/null
+++ b/tools/int8_trunk.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+"""int8_trunk.py - derive a per-row int8 draft trunk from a packed bf16 trunk.
+
+The hybrid decoder (--draft-trunk) uses a quantized copy of the trunk as a DRAFT that
+proposes tokens; the exact bf16 model then verifies every one, so the draft's precision
+affects only speed, never output. A bf16-format draft is 109 GB and cannot be resident on
+a 64 GB machine, which is where the hybrid pays off. This writes a true int8 container at
+~56 GB.
+
+Input is a packed trunk (trunk.bin + trunk.json from pack_trunk.py). For every 2D BF16
+tensor, each row becomes [f32 scale][int8 * cols] with a symmetric per-row absmax scale,
+which is exactly the layout k3_matmul_q8 reads. Everything else (norms, 1D tensors,
+anything not BF16) is copied verbatim. Run alignment and the manifest structure are
+preserved so the engine's trunk reader and bind path handle it unchanged apart from the
+I8R dtype.
+
+ python3 tools/int8_trunk.py <bf16_trunk_dir> <int8_out_dir>
+"""
+import json
+import os
+import sys
+
+import numpy as np
+
+ALIGN = 4096
+CHUNK = 64 << 20
+
+
+def bf16_to_f32(u16):
+ return (u16.astype(np.uint32) << 16).view(np.float32)
+
+
+def quant_row_int8(f32_2d):
+ """[rows, cols] f32 -> bytes: per row [f32 scale][int8 * cols]."""
+ rows, cols = f32_2d.shape
+ amax = np.abs(f32_2d).max(axis=1)
+ scale = (amax / 127.0).astype(np.float32)
+ scale[scale == 0] = 1.0
+ q = np.rint(f32_2d / scale[:, None]).clip(-128, 127).astype(np.int8)
+ # each row is [4 scale bytes][cols int8]; build [rows, 4+cols] uint8 in one shot
+ row = np.empty((rows, 4 + cols), dtype=np.uint8)
+ row[:, :4] = scale.view(np.uint8).reshape(rows, 4)
+ row[:, 4:] = q.view(np.uint8)
+ return row.tobytes(), rows * (4 + cols)
+
+
+def main():
+ if len(sys.argv) < 3:
+ print("usage: int8_trunk.py <bf16_trunk_dir> <int8_out_dir>")
+ return 2
+ src, out = sys.argv[1], sys.argv[2]
+ os.makedirs(out, exist_ok=True)
+ man = json.load(open(os.path.join(src, "trunk.json")))
+ binp = open(os.path.join(src, "trunk.bin"), "rb")
+ outp = open(os.path.join(out, "trunk.bin"), "wb")
+
+ newman = {k: v for k, v in man.items() if k != "layers"}
+ newman["layers"] = []
+ nq = 0
+ for li, lay in enumerate(man["layers"]):
+ base = lay["file_off"]
+ # read the whole run once
+ binp.seek(base)
+ run = binp.read(lay["nbytes"])
+
+ # rebuild the run tensor by tensor, in ascending source offset so the packed
+ # order is preserved; new offsets are assigned as we append.
+ items = sorted(lay["tensors"].items(), key=lambda kv: kv[1]["off"])
+ pad = (-outp.tell()) % ALIGN
+ if pad:
+ outp.write(b"\0" * pad)
+ file_off = outp.tell()
+ assert file_off % ALIGN == 0
+
+ new_tensors = {}
+ run_pos = 0
+ for name, t in items:
+ o, nb, dt, shape = t["off"], t["nbytes"], t["dtype"], t.get("shape", [])
+ raw = run[o:o + nb]
+ if dt == "BF16" and len(shape) == 2:
+ f = bf16_to_f32(np.frombuffer(raw, dtype=np.uint16)).reshape(shape[0], shape[1])
+ enc, enb = quant_row_int8(f)
+ outp.write(enc)
+ new_tensors[name] = {"off": run_pos, "nbytes": enb, "dtype": "I8R",
+ "shape": shape}
+ run_pos += enb
+ nq += 1
+ else:
+ outp.write(raw)
+ new_tensors[name] = {"off": run_pos, "nbytes": nb, "dtype": dt,
+ "shape": shape}
+ run_pos += nb
+
+ pad = (-outp.tell()) % ALIGN
+ if pad:
+ outp.write(b"\0" * pad)
+ run_bytes = (run_pos + ALIGN - 1) & ~(ALIGN - 1)
+ nl = {k: v for k, v in lay.items() if k not in ("file_off", "nbytes", "tensors")}
+ nl.update({"file_off": file_off, "nbytes": run_bytes, "tensors": new_tensors})
+ newman["layers"].append(nl)
+ if (li + 1) % 10 == 0 or li + 1 == len(man["layers"]):
+ print(" int8 %d/%d layers, %.1f GB out" % (li + 1, len(man["layers"]),
+ outp.tell() / 1e9), flush=True)
+
+ binp.close()
+ outp.close()
+ json.dump(newman, open(os.path.join(out, "trunk.json"), "w"))
+ sz = os.path.getsize(os.path.join(out, "trunk.bin"))
+ print("wrote %s: %.2f GB, %d tensors int8-quantised" % (out, sz / 1e9, nq))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/qdq_trunk.py b/tools/qdq_trunk.py
new file mode 100644
index 0000000..d21e627
--- /dev/null
+++ b/tools/qdq_trunk.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python3
+"""qdq_trunk.py: quantize-dequantize a packed trunk in place, for draft-quality tests.
+
+Reads a packed trunk (trunk.bin + trunk.json), simulates storing every 2D bf16 weight
+tensor at reduced precision (int8 or int4, per-row or per-group symmetric absmax), and
+writes the dequantized result back as ORDINARY bf16 in an identical container. The
+output trunk is byte-compatible with the engine: same manifest schema, same offsets,
+same dtypes. Running the unmodified engine against it answers, with no new C code, the
+question every quantized-draft design stands on: how often does the quantized model's
+greedy token agree with the exact model's?
+
+ python3 tools/qdq_trunk.py <src_trunk_dir> <dst_trunk_dir> --bits 8 [--group 0]
+
+--group 0 means per-row scales; a positive value means per-group along the row.
+Norms, biases and anything 1D pass through untouched, as do non-bf16 tensors.
+Deterministic: same input bytes always produce the same output bytes.
+"""
+import argparse
+import json
+import os
+import shutil
+import sys
+
+import numpy as np
+
+
+def bf16_to_f32(u16):
+ return (u16.astype(np.uint32) << 16).view(np.float32)
+
+
+def f32_to_bf16(f32):
+ u = f32.view(np.uint32)
+ # round-to-nearest-even on the dropped mantissa bits, matching torch's cast
+ rounding = ((u >> 16) & 1) + 0x7FFF
+ return ((u + rounding) >> 16).astype(np.uint16)
+
+
+def qdq(f32, bits, group):
+ rows, cols = f32.shape
+ qmax = (1 << (bits - 1)) - 1 # 127 for int8, 7 for int4
+ if group and group > 0 and cols % group == 0:
+ g = f32.reshape(rows, cols // group, group)
+ scale = np.abs(g).max(axis=2, keepdims=True) / qmax
+ scale[scale == 0] = 1.0
+ q = np.clip(np.rint(g / scale), -qmax, qmax)
+ return (q * scale).reshape(rows, cols).astype(np.float32)
+ scale = np.abs(f32).max(axis=1, keepdims=True) / qmax
+ scale[scale == 0] = 1.0
+ q = np.clip(np.rint(f32 / scale), -qmax, qmax)
+ return (q * scale).astype(np.float32)
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("src")
+ ap.add_argument("dst")
+ ap.add_argument("--bits", type=int, default=8, choices=(4, 8))
+ ap.add_argument("--group", type=int, default=0)
+ args = ap.parse_args()
+
+ man = json.load(open(os.path.join(args.src, "trunk.json")))
+ os.makedirs(args.dst, exist_ok=True)
+ shutil.copyfile(os.path.join(args.src, "trunk.json"),
+ os.path.join(args.dst, "trunk.json"))
+
+ src = open(os.path.join(args.src, "trunk.bin"), "rb")
+ total = os.path.getsize(os.path.join(args.src, "trunk.bin"))
+ dst = open(os.path.join(args.dst, "trunk.bin"), "wb")
+ # start from a byte-identical copy so padding and non-quantized regions carry over
+ print("copying %.1f GB container..." % (total / 1e9))
+ shutil.copyfileobj(src, dst, 64 << 20)
+ dst.flush()
+ src.close()
+ dst.close()
+
+ dst = open(os.path.join(args.dst, "trunk.bin"), "r+b")
+ done_t = 0
+ done_b = 0
+ for lay in man["layers"]:
+ base = lay["file_off"]
+ for _name, t in lay["tensors"].items():
+ if t.get("dtype") not in ("BF16", "bf16"):
+ continue
+ shape = t.get("shape") or []
+ if len(shape) != 2:
+ continue # norms, biases: pass through exact
+ rows, cols = int(shape[0]), int(shape[1])
+ nb = int(t["nbytes"])
+ if nb != rows * cols * 2:
+ continue # unexpected layout: leave untouched
+ off = base + int(t["off"])
+ dst.seek(off)
+ raw = np.frombuffer(dst.read(nb), dtype=np.uint16).copy()
+ f32 = bf16_to_f32(raw).reshape(rows, cols)
+ out = f32_to_bf16(qdq(f32, args.bits, args.group).ravel())
+ dst.seek(off)
+ dst.write(out.tobytes())
+ done_t += 1
+ done_b += nb
+ print(" layer %3d done (%d tensors, %.1f GB so far)"
+ % (lay.get("layer", -1), done_t, done_b / 1e9), flush=True)
+ dst.close()
+ print("qdq complete: %d tensors, %.1f GB re-quantized at int%d group=%s"
+ % (done_t, done_b / 1e9, args.bits, args.group or "row"))
+
+
+if __name__ == "__main__":
+ sys.exit(main())