A 2.78-trillion-parameter Kimi K3 running inference on a single CPU in 8.24 GB of RAM. Portable C99: no BLAS, no framework, no GPU.
C avx2c99cpu-inferencedeep-learningfrom-scratchinference-enginekimi-k3linear-attentionllmllm-inferencemachine-learningmemory-efficientmixture-of-expertsmoemxfp4quantizationsimdsystems-programmingtransformerzero-dependencies
fix: macOS/Apple Silicon download script portability and Darwin pread 2 GiB ceiling
Yongsheng Gao0fe6d0b66bb3
diff --git a/scripts/download-model.sh b/scripts/download-model.shindex 0a78d7b..ab42324 100755--- a/scripts/download-model.sh+++ b/scripts/download-model.sh@@ -13,6 +13,14 @@set -euo pipefail+# `stat` and `find -printf` are spelled differently on BSD/macOS than on GNU/Linux.+# Resolve the stat flavour once here rather than shelling out per file.+case "$(uname -s)" in+ Darwin) STAT_FMT='-f%z' ;;+ *) STAT_FMT='-c%s' ;;+esac+filesize() { stat $STAT_FMT "$1"; }+DEST="${1:?usage: download-model.sh <dest_dir>}"REPO="moonshotai/Kimi-K3"@@ -60,14 +68,22 @@ hf cache verify --help >/dev/null 2>&1 || {# recommended installs above put the library in an isolated environment and expose only# the `hf` executable, so importing it from the system interpreter fails on exactly the# setups this script just told the user to create.-# NOTE: awk must read to EOF here. Exiting on the first match closes the pipe, `hf` takes-# SIGPIPE, and under `set -o pipefail` that kills the script with 141 before it prints-# anything at all.+#+# The `hf models info` JSON is parsed with the stdlib `json` module, not a text scan --+# huggingface_hub 1.28 prints it as one compact line rather than the pretty-printed,+# one-key-per-line form an earlier `tr | awk '/^sha:/'` scan assumed, and that scan+# silently found nothing against compact output. `json` needs no import of+# huggingface_hub itself, so it does not hit the isolated-environment problem above.+# NOTE: json.load reads its input to EOF, so `hf` still runs to completion rather than+# taking SIGPIPE from an early-exiting consumer under `set -o pipefail`.REVISION="${K3_REVISION:-}"if [ -z "$REVISION" ]; thenREVISION="$(hf models info "$REPO" 2>/dev/null \- | tr -d ' ",' \- | awk -F: '!v && /^sha:/ {v = $2} END {print v}')"+ | python3 -c 'import json, sys+try:+ print(json.load(sys.stdin).get("sha", ""))+except Exception:+ print("")')"ficase "$REVISION" in????????????????????????????????????????) ;; # 40 hex characters@@ -110,8 +126,14 @@ echo "verifying…"# find, not `ls | wc -l`: under `set -euo pipefail` a glob that matches nothing makes# ls exit non-zero and the script dies HERE, so the "download is incomplete" message# below -- the entire point of this verification block -- would never be reached.+#+# Summed with a loop rather than `find -printf '%s\n'`: -printf is a GNU find+# extension that BSD/macOS find does not support. -print0 is POSIX-portable.N=$(find "$DEST" -maxdepth 1 -name '*.safetensors' | wc -l)-B=$(find "$DEST" -maxdepth 1 -name '*.safetensors' -printf '%s\n' | awk '{s+=$1} END{print s+0}')+B=0+while IFS= read -r -d '' f; do+ B=$((B + $(filesize "$f")))+done < <(find "$DEST" -maxdepth 1 -name '*.safetensors' -print0)printf ' shards : %s (expect %s)\n' "$N" "$EXPECT_SHARDS"printf ' bytes : %s (expect %s)\n' "$B" "$EXPECT_BYTES"@@ -135,7 +157,7 @@ if [ -f "$SIZES" ]; thenbad=0while read -r name want; do[ -n "$name" ] || continue- got=$(stat -c%s "$DEST/$name" 2>/dev/null || echo 0)+ got=$(filesize "$DEST/$name" 2>/dev/null || echo 0)if [ "$got" != "$want" ]; thenprintf ' BAD %s: %s bytes, expected %s\n' "$name" "$got" "$want"bad=$((bad + 1))@@ -155,7 +177,7 @@ fi# commit resolved earlier. It re-reads all 1.56 TB, so it is not free -- on a machine# without SHA-NI it can take longer than the download did.echo-echo "verifying checksums against Hub metadata for $REVISION…"+echo "verifying checksums against Hub metadata for ${REVISION}…"echo " (re-reads the full 1.56 TB; set K3_SKIP_CHECKSUM=1 to skip)"if [ "${K3_SKIP_CHECKSUM:-0}" = "1" ]; thenecho " SKIPPED by K3_SKIP_CHECKSUM=1; sizes were still checked above."diff --git a/src/io/k3_portable_io.h b/src/io/k3_portable_io.hindex a9da467..279cab5 100644--- a/src/io/k3_portable_io.h+++ b/src/io/k3_portable_io.h@@ -14,6 +14,14 @@** Both call sites fall back to buffered reads when the direct path is unavailable, so* neither shim changes what the engine computes, only how fast it reads.+ *+ * A third difference is not an open() flag at all: pread() itself returns EINVAL on+ * Darwin for a single request of 2^31 bytes or more, where Linux either succeeds or+ * returns a short read that a retry loop already handles. The embedding table (2.35 GB)+ * and a packed trunk layer (up to 2.37 GB) both exceed that in one contiguous span.+ * K3_PREAD_MAX is the per-syscall cap every such read loop chunks against; on platforms+ * without the limit it just turns one syscall into a few, which costs nothing measurable+ * against a multi-gigabyte transfer.*/#ifndef K3_PORTABLE_IO_H#define K3_PORTABLE_IO_H@@ -26,6 +34,9 @@#endif#include <fcntl.h>+#include <stdint.h>++#define K3_PREAD_MAX ((int64_t)1 << 30) /* 1 GiB per syscall; see file header */#if defined(__APPLE__)diff --git a/src/io/k3_st.c b/src/io/k3_st.cindex 2be9165..018f5a3 100644--- a/src/io/k3_st.c+++ b/src/io/k3_st.c@@ -483,7 +483,8 @@ int64_t k3_st_read_aligned(const K3St *s, int shard, int64_t off, int64_t nbytesint64_t got = 0;while (got < len) {- ssize_t r = pread(dfd, (char *)buf + got, (size_t)(len - got), (off_t)(lo + got));+ const int64_t req = (len - got < K3_PREAD_MAX) ? (len - got) : K3_PREAD_MAX;+ ssize_t r = pread(dfd, (char *)buf + got, (size_t)req, (off_t)(lo + got));if (r <= 0) {/* The final window of a shard can extend past EOF, which is a short read* rather than an error. Accept it once the payload itself is covered. */@@ -500,8 +501,10 @@ int64_t k3_st_read(const K3St *s, const K3Tensor *t, void *buf)* call the streaming tier will make per expert: a 17.55 MB contiguous span. */int64_t got = 0;while (got < t->nbytes) {+ const int64_t remain = t->nbytes - got;+ const int64_t req = remain < K3_PREAD_MAX ? remain : K3_PREAD_MAX;ssize_t r = pread(s->fd[t->shard], (char *)buf + got,- (size_t)(t->nbytes - got), (off_t)(t->off + got));+ (size_t)req, (off_t)(t->off + got));if (r <= 0) {fprintf(stderr, "k3_st: short read on %s at +%lld\n", t->name, (long long)got);return got;diff --git a/src/io/k3_trunk.c b/src/io/k3_trunk.cindex 81e4613..3d0824d 100644--- a/src/io/k3_trunk.c+++ b/src/io/k3_trunk.c@@ -390,8 +390,9 @@ static int load_run(K3Trunk *tr, int L, unsigned char *dst)const double t0 = now_s();int64_t got = 0;while (got < lay->nbytes) {- ssize_t r = pread(tr->fd, dst + got, (size_t)(lay->nbytes - got),- (off_t)(lay->file_off + got));+ const int64_t remain = lay->nbytes - got;+ const int64_t req = remain < K3_PREAD_MAX ? remain : K3_PREAD_MAX;+ ssize_t r = pread(tr->fd, dst + got, (size_t)req, (off_t)(lay->file_off + got));if (r <= 0) { fprintf(stderr, "k3_trunk: short read on layer %d\n", L); return -1; }got += r;}