Skip to content

A 2.78-trillion-parameter Kimi K3 running inference on a single CPU in 8.24 GB of RAM. Portable C99: no BLAS, no framework, no GPU.

feat: add native Windows support via MinGW-w64

Fareed Khan1f19bbe3251f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 40f0005..b2eb7d9 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -100,6 +100,91 @@ jobs:
grep -q "VERDICT: ENGINE MATCHES THE REFERENCE EXACTLY" "$RUNNER_TEMP/t.log"
grep -q "ALL WEIGHTLESS TESTS PASSED" "$RUNNER_TEMP/t.log"
+ # A separate job rather than a matrix leg, for the same reason as macOS: the setup
+ # action is MSYS2-specific, and the platform-detection block in the Makefile has a
+ # dedicated Windows branch (matched on the MINGW substring of `uname -s`) that only
+ # this job exercises. `make`, not the individual binaries -- the defect this job
+ # guards against is `make` itself failing on Windows, the same rationale as the
+ # macOS "default flags, platform detection" step.
+ build-and-test-windows:
+ name: build + test (windows-latest, mingw64 gcc)
+ runs-on: windows-latest
+ defaults:
+ run:
+ shell: msys2 {0}
+ steps:
+ - uses: actions/checkout@v7
+
+ # MSYS2's MinGW64 environment, not the POSIX-emulation MSYS one: `cc`/`make` must
+ # resolve to the native-Windows-target toolchain. See README.md's "macOS, Windows,
+ # WSL?" section and src/io/k3_portable_io.h for what O_DIRECT, pread,
+ # posix_memalign and getrusage become on this platform, and why -static and
+ # -lpsapi (which the Makefile's Windows branch adds automatically) are
+ # load-bearing rather than stylistic here.
+ - uses: msys2/setup-msys2@v2
+ with:
+ msystem: MINGW64
+ update: true
+ install: mingw-w64-x86_64-gcc make
+
+ - name: Build (default flags, platform detection)
+ run: make
+
+ - name: make test
+ run: make test
+
+ - name: Assert the suite was not silently empty
+ run: |
+ make test 2>&1 | tee /tmp/t.log
+ grep -q "22 passed, 0 failed, 0 skipped" /tmp/t.log
+ grep -q "SCALE TEST PASSED" /tmp/t.log
+ grep -q "VERDICT: ENGINE MATCHES THE REFERENCE EXACTLY" /tmp/t.log
+ grep -q "ALL WEIGHTLESS TESTS PASSED" /tmp/t.log
+
+ # Windows sanitizer coverage needs a second MSYS2 environment: MinGW-w64's GCC package
+ # ships no libasan/libubsan runtime at all (confirmed directly -- `-lasan`/`-lubsan`
+ # fail to link, and no such file exists anywhere under /mingw64), unlike its Linux and
+ # macOS counterparts. MSYS2's separate Clang/LLVM environment carries a real one.
+ sanitizers-windows:
+ name: ASan + UBSan (windows-latest, clang)
+ runs-on: windows-latest
+ defaults:
+ run:
+ shell: msys2 {0}
+ steps:
+ - uses: actions/checkout@v7
+ - uses: msys2/setup-msys2@v2
+ with:
+ msystem: CLANG64
+ update: true
+ install: mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-compiler-rt make
+
+ # These are dynamic DLLs, not statically linked, and Windows resolves them by
+ # searching the executable's own directory before anything on PATH -- confirmed
+ # directly against a PATH already containing the exact directory these ship in.
+ # libc++.dll is not an obvious dependency of a C99 project; it is pulled in
+ # transitively because libclang_rt.asan_dynamic itself links against it.
+ - name: Build instrumented tests
+ run: |
+ make CC=clang CFLAGS="-O1 -g -std=gnu99 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer" \
+ LDFLAGS="-lm -fsanitize=address,undefined -lpsapi -lwinpthread" ARCH= \
+ bin/test_ops bin/test_cfg bin/test_cache bin/test_st bin/k3_model
+ cp /clang64/bin/libclang_rt.asan_dynamic-x86_64.dll /clang64/bin/libwinpthread-1.dll /clang64/bin/libc++.dll bin/
+ - name: Run under sanitizers
+ env:
+ ASAN_OPTIONS: detect_leaks=0:abort_on_error=1
+ UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1
+ run: |
+ ./bin/test_ops.exe tests/fixtures/ops
+ ./bin/test_cfg.exe fixture tests/fixtures/ref_k3.json
+ for f in no_layermap bad_layer_index bad_topk; do
+ ./bin/test_cfg.exe reject "tests/fixtures/cfg/$f.json"
+ done
+ ./bin/test_cache.exe tests/fixtures/cache
+ ./bin/test_st.exe tests/fixtures/st /tmp/idx.json \
+ plain.f32.2d plain.bf16.1d tricky.f16.1d packed.u8.2d scalar.f32 second.shard.f32
+ ./bin/k3_model.exe tests/fixtures
+
# Warnings are defects here. The engine does arithmetic on `const void *` weight
# pointers, where a missing -Wpointer-arith silently strides by one byte.
strict-warnings:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a5d9b76..9c284df 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,36 @@ versioning follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Added
+
+- **Windows support**: builds natively via MSYS2's MinGW-w64 GCC, no WSL required.
+ `make`, `make test`, and `make test-all` pass every gate unmodified, including the
+ full-model oracle and tokenizer parity (45/45) against real Kimi K3 weights.
+ `src/io/k3_portable_io.h` gained a Windows branch alongside the existing Darwin one,
+ porting `O_DIRECT` (via `FILE_FLAG_NO_BUFFERING`, intercepted at `open()` since
+ Windows -- unlike Darwin -- cannot add it to an already-open handle), `pread` (via
+ `ReadFile`'s `OVERLAPPED` offset fields, chosen specifically because it does not
+ share mutable file-pointer state across threads the way `SetFilePointerEx` +
+ `ReadFile` would), `posix_memalign` (via `_aligned_malloc`), and `getrusage`/
+ `MemAvailable` (via `GetProcessMemoryInfo`/`GlobalMemoryStatusEx`). `make asan`/
+ `make ubsan` switch to Clang on Windows (MinGW-w64's GCC package ships no sanitizer
+ runtime at all, confirmed directly rather than assumed).
+
+### Fixed
+
+- **Heap corruption on Windows** (`STATUS_HEAP_CORRUPTION`) in the trunk and expert-
+ cache arena allocators: `_aligned_malloc`, which backs the Windows `posix_memalign`
+ shim, must be freed with `_aligned_free`, not plain `free`. POSIX's `posix_memalign`
+ carries no such restriction, so this compiled cleanly and only crashed once the
+ corrupted allocator metadata was actually used, well after the allocation itself.
+ Three call sites needed the fix: `k3_cache.c`'s cache arena, and `k3_trunk.c`'s
+ trunk arena and per-layer pinned buffers.
+- **`SHARD_DIR`/`TOK_FILES` unquoted in the Makefile**: a path containing a space
+ (routine on Windows, e.g. an "AI LOCAL MODELS" folder) silently split into extra
+ argv entries instead of failing loudly, and `test_expert`/`test_real_layer`/
+ `test_tok`/`test_cfg` read whichever truncated token happened to resolve to a path,
+ rather than refusing outright.
+
## [1.0.0] - 2026-08-07
Verified end to end on the full released checkpoint, and made substantially faster, with
diff --git a/Makefile b/Makefile
index c1c8ff3..0443fba 100644
--- a/Makefile
+++ b/Makefile
@@ -13,7 +13,13 @@
#
# PLATFORMS. Linux/x86-64 is the reference. macOS/arm64 builds with plain `make` too,
# but needs Homebrew's libomp for OpenMP (`brew install libomp`) because Apple Clang
-# ships no OpenMP runtime; the platform block below detects and wires it up.
+# ships no OpenMP runtime; the platform block below detects and wires it up. Windows
+# builds under MSYS2's MinGW64 environment (`pacman -S mingw-w64-x86_64-gcc`) -- open
+# the "MSYS2 MinGW x64" shell specifically, not the plain MSYS2 shell, so `cc`/`make`
+# resolve to the native-Windows-target toolchain rather than the POSIX-emulation one;
+# then plain `make` works, no flags to remember. See src/io/k3_portable_io.h for what
+# O_DIRECT, pread, posix_memalign and getrusage become there, and why -static and
+# -lpsapi (below) are load-bearing rather than stylistic on this platform.
# ---------------------------------------------------------------------------- config --
CC ?= cc
@@ -64,6 +70,41 @@ ifeq ($(UNAME_S),Darwin)
$(warning libomp not found at $(OMP_PREFIX). Install it with `brew install libomp`,)
$(warning or point the build at another copy with `make OMP_PREFIX=/path/to/libomp`.)
endif
+else ifneq ($(findstring MINGW,$(UNAME_S)),)
+ # MSYS2's uname reports e.g. MINGW64_NT-10.0-26200 -- match the MINGW substring
+ # rather than the whole string, since the trailing Windows build number varies.
+ #
+ # -march=native and -fopenmp behave exactly as on Linux; MinGW-w64's GCC needs no
+ # Apple-Clang-style preprocessor dance for OpenMP.
+ #
+ # -static: the MinGW runtime is POSIX-threads-model (winpthreads), which pulls in
+ # libwinpthread-1.dll dynamically by default. A binary launched from outside this
+ # shell's PATH then fails immediately with STATUS_DLL_NOT_FOUND -- confirmed
+ # directly, not a theoretical risk. Static linking removes the dependency instead
+ # of asking every caller to keep MSYS2's bin directory on PATH.
+ #
+ # -lpsapi: peak_rss_bytes() (k3_run.c) calls GetProcessMemoryInfo for Windows' RSS
+ # equivalent, which lives in psapi.dll; nothing else in this build needs it, so it
+ # is not pulled in by default the way -lm is.
+ ARCH ?= -march=native
+ OMP_CFLAGS ?= -fopenmp
+ OMP_LDFLAGS ?= -fopenmp -static -lpsapi
+ # The MinGW-w64 GCC package ships no libasan/libubsan runtime at all (confirmed:
+ # `-lasan`/`-lubsan` fail to link, and no such file exists anywhere under /mingw64),
+ # unlike its Linux and macOS counterparts. MSYS2's separate Clang/LLVM environment
+ # (`pacman -S mingw-w64-clang-x86_64-clang mingw-w64-clang-x86_64-compiler-rt`) does
+ # carry a real one, so the sanitizer targets switch compilers on this platform only.
+ SANITIZER_CC ?= clang
+ SANITIZER_LDFLAGS ?= -lpsapi -lwinpthread
+ # These are dynamic DLLs, not statically linked, and Windows resolves them by
+ # searching the executable's OWN directory before anything on PATH -- confirmed
+ # directly: a PATH containing the exact directory these ship in still failed with
+ # STATUS_DLL_NOT_FOUND, and copying them next to bin/k3.exe fixed it immediately.
+ # libc++.dll is not an obvious dependency of a C99 project; it is pulled in
+ # transitively because libclang_rt.asan_dynamic itself links against it.
+ SANITIZER_DLLS ?= $(wildcard /clang64/bin/libclang_rt.asan_dynamic-x86_64.dll) \
+ $(wildcard /clang64/bin/libwinpthread-1.dll) \
+ $(wildcard /clang64/bin/libc++.dll)
else
# GCC uses -mcpu=native for AArch64 tuning. Keep -march=native on the x86 reference;
# `make portable` drops both so the produced binary is not tied to the build host.
@@ -76,6 +117,13 @@ else
OMP_LDFLAGS ?= -fopenmp
endif
+# Linux and macOS: the platform's own CC already has a working sanitizer runtime, so
+# the asan/ubsan targets need no compiler override and no extra link libraries or DLL
+# copying. Windows sets all three itself, above.
+SANITIZER_CC ?= $(CC)
+SANITIZER_LDFLAGS ?=
+SANITIZER_DLLS ?=
+
# -Wpointer-arith is not cosmetic: weight pointers are `const void *`, and arithmetic on
# a void pointer is a silent GNU extension that strides by ONE BYTE. Without this flag
# that mistake compiles clean under -Wall -Wextra and returns the wrong tensor.
@@ -198,7 +246,7 @@ test: $(CLI_BIN) $(TEST_BINS)
done
@echo "== tokenizer =="; \
if [ -f "$(TOK_FILES)/tiktoken.model" ]; then \
- ./$(BIN)/test_tok $(TOK_FILES) roundtrip src/core/k3_ops.c; \
+ ./$(BIN)/test_tok "$(TOK_FILES)" roundtrip src/core/k3_ops.c; \
else \
echo " NOT RUN: no tiktoken.model at $(TOK_FILES)"; \
echo " the vocabulary ships with the checkpoint, not with this"; \
@@ -216,11 +264,15 @@ test: $(CLI_BIN) $(TEST_BINS)
## test-all: adds tests that need a real checkpoint (set SHARD_DIR)
test-all: test
@test -n "$(SHARD_DIR)" || { echo "set SHARD_DIR=/path/to/shards"; exit 2; }
- $(MAKE) weights-test SHARD_DIR=$(SHARD_DIR)
+ $(MAKE) weights-test SHARD_DIR="$(SHARD_DIR)"
+# SHARD_DIR is quoted: unquoted, a path containing a space (routine on Windows, e.g.
+# an "AI LOCAL MODELS" folder) silently splits into extra argv entries instead of
+# failing loudly, and the program reads whatever the truncated first token happens to
+# resolve to rather than refusing outright.
weights-test: $(WEIGHT_BINS)
- ./$(BIN)/test_expert $(SHARD_DIR) 1 64
- ./$(BIN)/test_real_layer $(SHARD_DIR) 1 4 8
+ ./$(BIN)/test_expert "$(SHARD_DIR)" 1 64
+ ./$(BIN)/test_real_layer "$(SHARD_DIR)" 1 4 8
$(BIN)/test_expert: tests/unit/test_expert.c $(BUILD)/src/io/k3_load.o \
$(BUILD)/src/io/k3_st.o $(BUILD)/src/core/k3_ops.o | $(BIN)
@@ -236,7 +288,7 @@ tok: $(BIN)/test_tok
## cfg: config reader against both supported config layouts
cfg: $(BIN)/test_cfg
@./$(BIN)/test_cfg fixture $(FIXTURES)/ref_k3.json
- @test -f "$(TOK_FILES)/config.json" && ./$(BIN)/test_cfg real $(TOK_FILES)/config.json \
+ @test -f "$(TOK_FILES)/config.json" && ./$(BIN)/test_cfg real "$(TOK_FILES)/config.json" \
|| echo " (skipped real config: none at $(TOK_FILES))"
## bench: kernel microbenchmarks, no weights required
@@ -262,12 +314,18 @@ debug:
# point of a sanitizer run. OMP_CFLAGS is still omitted rather than replaced, so the
# #pragma omp lines compile to nothing on every platform alike.
asan:
- $(MAKE) CFLAGS="-O1 -g -std=gnu99 $(WARN) -fsanitize=address,undefined -fno-omit-frame-pointer" \
- LDFLAGS="-lm -fsanitize=address,undefined" ARCH= all
+ $(MAKE) CC=$(SANITIZER_CC) CFLAGS="-O1 -g -std=gnu99 $(WARN) -fsanitize=address,undefined -fno-omit-frame-pointer" \
+ LDFLAGS="-lm -fsanitize=address,undefined $(SANITIZER_LDFLAGS)" ARCH= all
+ifneq ($(strip $(SANITIZER_DLLS)),)
+ cp -f $(SANITIZER_DLLS) $(BIN)/
+endif
ubsan:
- $(MAKE) CFLAGS="-O1 -g -std=gnu99 $(WARN) -fsanitize=undefined" \
- LDFLAGS="-lm -fsanitize=undefined" ARCH= all
+ $(MAKE) CC=$(SANITIZER_CC) CFLAGS="-O1 -g -std=gnu99 $(WARN) -fsanitize=undefined" \
+ LDFLAGS="-lm -fsanitize=undefined $(SANITIZER_LDFLAGS)" ARCH= all
+ifneq ($(strip $(SANITIZER_DLLS)),)
+ cp -f $(SANITIZER_DLLS) $(BIN)/
+endif
format:
@command -v clang-format >/dev/null || { echo "clang-format not installed"; exit 1; }
diff --git a/README.md b/README.md
index cf9dc9d..3554ea1 100644
--- a/README.md
+++ b/README.md
@@ -200,7 +200,7 @@ The gate is storage: **the checkpoint is 1.56 TB.** Everything else is ordinary.
| | | |
|---|---|---|
-| **OS** | Linux, x86-64 | uses `O_DIRECT`, `posix_memalign`, `getrusage` |
+| **OS** | Linux, x86-64 (reference); macOS/arm64 and Windows/x86-64 also build and pass every gate | uses `O_DIRECT`, `posix_memalign`, `getrusage` -- ported for Windows via MSYS2's MinGW-w64 (see `src/io/k3_portable_io.h`) |
| **CPU** | AVX2 + FMA | AVX-512 unnecessary. `make portable` targets generic AVX2 |
| **RAM** | 8 GB and up | every preset works; more memory is faster, never different |
| **Storage** | ~1.7 TB free | 1.56 TB checkpoint + 109 GB packed trunk, ideally on fast local disk |
@@ -592,8 +592,23 @@ hour in. Shorten the request, or drop `--incremental`, which carries no KV cache
**Is the whole 1.56 TB needed?** For generation, yes. For development, no: `make test`
needs nothing at all, and `--layers N` runs against partial shard sets.
-**macOS, Windows, WSL?** The engine targets Linux. The tokenizer and config reader are
-portable C99 and are built portably in CI.
+**macOS, Windows, WSL?** Linux is the reference platform. macOS/arm64 builds with plain
+`make` (see the Makefile's platform block). Windows builds natively too, via MSYS2's
+MinGW-w64 GCC (`pacman -S mingw-w64-x86_64-gcc`, then open the "MSYS2 MinGW x64" shell
+specifically -- `make`, `make test`, and `make test-all` all pass every gate unmodified,
+including the full-model oracle and tokenizer parity against real Kimi K3 weights.
+Four Linux-only calls needed porting -- `O_DIRECT`, `pread`, `posix_memalign`, and
+`getrusage` -- documented in `src/io/k3_portable_io.h`. One real bug surfaced during the
+port and is worth knowing if you extend this code on Windows: `_aligned_malloc`, which
+backs the `posix_memalign` shim, must be freed with `_aligned_free`, not plain `free`;
+POSIX's `posix_memalign` carries no such restriction, so this is easy to get wrong
+silently -- it compiles, and Windows terminates the process with `STATUS_HEAP_CORRUPTION`
+only once the corrupted allocator metadata is actually used. `make asan`/`make ubsan`
+switch to Clang on Windows (`pacman -S mingw-w64-clang-x86_64-clang
+mingw-w64-clang-x86_64-compiler-rt`): MinGW-w64's GCC package ships no sanitizer runtime
+at all, confirmed directly rather than assumed. WSL works too, unmodified, since it is
+just Linux -- the tokenizer and config reader are portable C99 either way and build
+anywhere, in CI included.
---
diff --git a/src/cache/k3_cache.c b/src/cache/k3_cache.c
index 1b69761..720636b 100644
--- a/src/cache/k3_cache.c
+++ b/src/cache/k3_cache.c
@@ -1,11 +1,16 @@
/* k3_cache.c - see k3_cache.h. */
#define _POSIX_C_SOURCE 200809L
+#include "k3_portable_io.h" /* first: sets _DARWIN_C_SOURCE before any libc header;
+ * on Windows, supplies posix_memalign */
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
-#include <sys/mman.h>
+#ifndef _WIN32
+#include <sys/mman.h> /* MADV_HUGEPAGE; k3_portable_io.h no-ops it on Windows */
+#endif
#include "k3_cache.h"
@@ -349,7 +354,7 @@ int k3_cache_init(K3Cache *c, const K3St *st, const K3Cfg *cfg, int64_t budget_b
void k3_cache_free(K3Cache *c)
{
- free(c->arena); free(c->slot_of); free(c->key_of);
+ k3_aligned_free(c->arena); free(c->slot_of); free(c->key_of);
free(c->used_at); free(c->pinned); free(c->ref); free(c->pad); free(c->hist);
free(c->trace);
memset(c, 0, sizeof *c);
diff --git a/src/cli/k3_run.c b/src/cli/k3_run.c
index d31e4d7..dd0aa5a 100644
--- a/src/cli/k3_run.c
+++ b/src/cli/k3_run.c
@@ -49,7 +49,13 @@
#include <stdlib.h>
#include <string.h>
#include <time.h>
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <psapi.h>
+#else
#include <sys/resource.h>
+#endif
#include "k3.h"
#include "k3_bind.h"
@@ -453,6 +459,13 @@ static void k3_preset_list(FILE *f)
* Quote this value, not the plan. */
static double peak_rss_bytes(void)
{
+#ifdef _WIN32
+ /* PeakWorkingSetSize is Windows' peak-RSS equivalent, already in bytes -- no
+ * kilobyte scaling needed, unlike ru_maxrss on Linux. */
+ PROCESS_MEMORY_COUNTERS pmc;
+ if (!GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)) return 0.0;
+ return (double)pmc.PeakWorkingSetSize;
+#else
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru) != 0) return 0.0;
#if defined(__APPLE__)
@@ -460,12 +473,23 @@ static double peak_rss_bytes(void)
#else
return (double)ru.ru_maxrss * 1024.0; /* kilobytes */
#endif
+#endif
}
/* MemAvailable, which is what the kernel thinks can actually be handed out, not
* MemFree. Returns 0 if it cannot be read. */
static double mem_available_bytes(void)
{
+#ifdef _WIN32
+ /* ullAvailPhys is Windows' MemAvailable equivalent: physical memory that can
+ * actually be handed out (already accounts for the standby/modified page
+ * lists the way MemAvailable accounts for reclaimable cache), not the raw
+ * free count. */
+ MEMORYSTATUSEX ms;
+ ms.dwLength = sizeof ms;
+ if (!GlobalMemoryStatusEx(&ms)) return 0.0;
+ return (double)ms.ullAvailPhys;
+#else
FILE *f = fopen("/proc/meminfo", "r");
if (!f) return 0.0;
char line[256];
@@ -474,6 +498,7 @@ static double mem_available_bytes(void)
if (!strncmp(line, "MemAvailable:", 13)) { kb = atof(line + 13); break; }
fclose(f);
return kb * 1024.0;
+#endif
}
typedef struct {
@@ -789,6 +814,13 @@ int main(int argc, char **argv)
* So below full residency, auto pins only while the whole process stays
* comfortably clear of the RAM ceiling. */
double memtotal = 0.0;
+#ifdef _WIN32
+ {
+ MEMORYSTATUSEX ms;
+ ms.dwLength = sizeof ms;
+ if (GlobalMemoryStatusEx(&ms)) memtotal = (double)ms.ullTotalPhys;
+ }
+#else
FILE *mf = fopen("/proc/meminfo", "r");
if (mf) {
char ln[256];
@@ -796,6 +828,7 @@ int main(int argc, char **argv)
if (!strncmp(ln, "MemTotal:", 9)) { memtotal = atof(ln + 9) * 1024.0; break; }
fclose(mf);
}
+#endif
const double rss_ceiling = memtotal > 0.0 ? 0.55 * memtotal / 1e9
: usable; /* no /proc: keep old cap */
double cap = rss_ceiling - reserve - cache_min;
diff --git a/src/io/k3_portable_io.h b/src/io/k3_portable_io.h
index 279cab5..0516be8 100644
--- a/src/io/k3_portable_io.h
+++ b/src/io/k3_portable_io.h
@@ -1,21 +1,41 @@
/* k3_portable_io.h - shims for the Linux-only I/O calls the readers use.
*
- * The engine asks for two things Linux gives it and Darwin does not spell the same way:
+ * The engine asks for things Linux gives it and the other two platforms do not spell
+ * the same way:
*
* O_DIRECT bypass the page cache on the trunk and expert reads. Darwin's
* equivalent is not an open() flag but fcntl(F_NOCACHE) after the
- * fact, so O_DIRECT is defined to 0 here (open() is unaffected) and
+ * fact, so O_DIRECT is defined to 0 there (open() is unaffected) and
* k3_set_direct() applies the real thing to the returned descriptor.
+ * Windows is the opposite of Darwin: unbuffered I/O (FILE_FLAG_NO_
+ * BUFFERING) can ONLY be set at CreateFile time, same constraint as
+ * Linux's real O_DIRECT, but nothing in the MinGW runtime maps an
+ * open() flag onto it -- so open() itself is intercepted below.
*
- * posix_fadvise a page-cache prefetch hint with no Darwin equivalent. Callers
- * already treat it as advisory -- the one call site returns early on
- * the direct path because the hint has nothing to populate there -- so
- * the shim is a no-op that keeps the buffered path compiling.
+ * posix_fadvise a page-cache prefetch hint with no Darwin or Windows equivalent.
+ * Callers already treat it as advisory -- the one call site returns
+ * early on the direct path because the hint has nothing to populate
+ * there -- so the shim is a no-op that keeps the buffered path
+ * compiling.
*
- * 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.
+ * pread positioned read. Native on Linux and Darwin. The MinGW runtime has
+ * no equivalent, so Windows gets one built on ReadFile's OVERLAPPED
+ * Offset/OffsetHigh fields -- a true positioned read that does not
+ * touch a shared file-pointer, unlike SetFilePointerEx + ReadFile,
+ * which would race when the trunk reader thread and the expert-cache
+ * prefetch threads pread() the same fd concurrently.
*
- * A third difference is not an open() flag at all: pread() itself returns EINVAL on
+ * posix_memalign Native on Linux and Darwin. Windows gets a thin wrapper over
+ * _aligned_malloc, which takes its (size, align) arguments in the
+ * opposite order.
+ *
+ * All four call sites fall back to buffered reads (or, for pread/posix_memalign, have
+ * no fallback because the shim IS the implementation) when the direct path is
+ * unavailable, so none of this changes what the engine computes, only how fast it
+ * reads -- except on Windows, where pread and posix_memalign are load-bearing rather
+ * than a speed path, since the codebase has no buffered-only alternative to either.
+ *
+ * A fifth 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.
@@ -63,10 +83,134 @@ static inline int k3_set_direct(int fd)
return fcntl(fd, F_NOCACHE, 1);
}
+#elif defined(_WIN32)
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <io.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifndef O_DIRECT
+#define O_DIRECT 0x40000000 /* sentinel bit; intercepted by k3_win_open() below */
+#endif
+
+#ifndef POSIX_FADV_WILLNEED
+#define POSIX_FADV_WILLNEED 3
+#endif
+
+static inline int posix_fadvise(int fd, long long off, long long len, int advice)
+{
+ (void)fd; (void)off; (void)len; (void)advice;
+ return 0; /* advisory only; no Windows equivalent */
+}
+
+/* True positioned read: OVERLAPPED with only Offset/OffsetHigh set, on a handle NOT
+ * opened with FILE_FLAG_OVERLAPPED, completes synchronously and does not touch any
+ * shared file-pointer state -- safe for concurrent callers on the same fd. */
+static inline long long k3_pread(int fd, void *buf, size_t count, long long offset)
+{
+ HANDLE h = (HANDLE)_get_osfhandle(fd);
+ if (h == INVALID_HANDLE_VALUE) { errno = EBADF; return -1; }
+
+ OVERLAPPED ov;
+ memset(&ov, 0, sizeof ov);
+ ov.Offset = (DWORD)(offset & 0xFFFFFFFFu);
+ ov.OffsetHigh = (DWORD)((unsigned long long)offset >> 32);
+
+ DWORD got = 0;
+ if (!ReadFile(h, buf, (DWORD)count, &got, &ov)) {
+ if (GetLastError() == ERROR_HANDLE_EOF) return 0;
+ errno = EIO;
+ return -1;
+ }
+ return (long long)got;
+}
+#define pread(fd, buf, count, offset) k3_pread((fd), (buf), (count), (offset))
+
+/* O_DIRECT has to be intercepted at open() itself: unlike Darwin's post-hoc fcntl,
+ * Windows has no way to add FILE_FLAG_NO_BUFFERING to an already-open handle. The
+ * bridge back to a plain int fd -- so every other pread()/close() call site in the
+ * codebase stays untouched -- goes through _open_osfhandle.
+ *
+ * Every reader call site in this codebase passes O_RDONLY, so the access mode below
+ * matters only to a caller outside the streaming path, such as a test that opens a
+ * fixture file for writing: CreateFileA needs GENERIC_WRITE for that, or a later
+ * ftruncate/write on the resulting handle fails with access denied even though the
+ * open() call itself succeeded. */
+static inline int k3_win_open(const char *path, int flags, ...)
+{
+ DWORD fileFlags = FILE_ATTRIBUTE_NORMAL;
+ if (flags & O_DIRECT) fileFlags |= FILE_FLAG_NO_BUFFERING;
+
+ DWORD access = GENERIC_READ;
+ int crtFlags = _O_RDONLY;
+ if ((flags & (O_WRONLY | O_RDWR)) == O_WRONLY) {
+ access = GENERIC_WRITE;
+ crtFlags = _O_WRONLY;
+ } else if (flags & O_RDWR) {
+ access = GENERIC_READ | GENERIC_WRITE;
+ crtFlags = _O_RDWR;
+ }
+
+ HANDLE h = CreateFileA(path, access,
+ FILE_SHARE_READ | FILE_SHARE_WRITE,
+ NULL, OPEN_EXISTING, fileFlags, NULL);
+ if (h == INVALID_HANDLE_VALUE) { errno = ENOENT; return -1; }
+
+ int fd = _open_osfhandle((intptr_t)h, crtFlags | _O_BINARY);
+ if (fd < 0) { CloseHandle(h); errno = EMFILE; return -1; }
+ return fd;
+}
+#define open(path, flags, ...) k3_win_open((path), (flags))
+
+/* GCC/Clang recognise the name posix_memalign as a built-in for optimisation purposes
+ * (constant folding, alias analysis) even though MinGW's headers declare no such
+ * function and its runtime provides no such symbol -- confirmed directly: a call to
+ * it with no other declaration in scope fails with "implicit declaration", not a
+ * link error, meaning nothing backs the built-in's assumed semantics. This
+ * definition is therefore not optional the way the -Wshadow warning below implies;
+ * it is the only real implementation on this platform. The pragma silences the
+ * warning without silencing -Wshadow project-wide. */
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+static inline int posix_memalign(void **out, size_t align, size_t len)
+{
+ *out = _aligned_malloc(len, align);
+ return *out ? 0 : ENOMEM;
+}
+#pragma GCC diagnostic pop
+
+/* On real POSIX, a posix_memalign'd pointer is safe to pass to plain free() -- that is
+ * the entire point of the interface. _aligned_malloc has no such guarantee: pairing it
+ * with free() instead of _aligned_free() corrupts the heap (observed directly: Windows
+ * terminates the process with STATUS_HEAP_CORRUPTION). k3_aligned_free() exists so the
+ * two call sites that free a posix_memalign'd arena (k3_cache.c, k3_trunk.c) can free it
+ * correctly on every platform without special-casing Windows at the call site itself. */
+#define k3_aligned_free(p) _aligned_free(p)
+
+/* madvise(MADV_HUGEPAGE) is a Linux transparent-hugepage hint; every caller already
+ * treats it as advisory ("failure is not an error" -- k3_trunk.c), so a no-op is the
+ * correct port here, not a functional gap. The alternative, VirtualAlloc with
+ * MEM_LARGE_PAGES, needs SeLockMemoryPrivilege and allocations sized to an exact
+ * large-page multiple -- a real feature to build for a hint the code already
+ * tolerates losing. */
+#define madvise(addr, len, advice) ((void)0)
+#define MADV_HUGEPAGE 0
+
+/* O_DIRECT already forced open()-time behavior above; nothing left to do post-open. */
+static inline int k3_set_direct(int fd) { (void)fd; return 0; }
+
#else /* Linux and friends: O_DIRECT on open() already did it */
static inline int k3_set_direct(int fd) { (void)fd; return 0; }
#endif
+/* Linux and Darwin: posix_memalign's contract already makes plain free() safe. */
+#ifndef k3_aligned_free
+#define k3_aligned_free(p) free(p)
+#endif
+
#endif /* K3_PORTABLE_IO_H */
diff --git a/src/io/k3_trunk.c b/src/io/k3_trunk.c
index 3d0824d..d217d0b 100644
--- a/src/io/k3_trunk.c
+++ b/src/io/k3_trunk.c
@@ -10,8 +10,10 @@
#include <stdlib.h>
#include <string.h>
#include <time.h>
+#ifndef _WIN32
#include <unistd.h>
-#include <sys/mman.h>
+#include <sys/mman.h> /* MADV_HUGEPAGE; k3_portable_io.h no-ops both on Windows */
+#endif
#include <pthread.h>
#include "json.h"
@@ -343,8 +345,8 @@ void k3_trunk_close(K3Trunk *tr)
free(io);
}
if (tr->fd >= 0) close(tr->fd);
- if (tr->pin) { for (int i = 0; i < tr->npin; i++) free(tr->pin[i]); free(tr->pin); }
- free(tr->arena); free(tr->layer_of); free(tr->slot_of);
+ if (tr->pin) { for (int i = 0; i < tr->npin; i++) k3_aligned_free(tr->pin[i]); free(tr->pin); }
+ k3_aligned_free(tr->arena); free(tr->layer_of); free(tr->slot_of);
if (tr->lay) { for (int i = 0; i < tr->n_layers; i++) free(tr->lay[i].t); free(tr->lay); }
free(tr->json_arena); /* every K3TrunkTensor.name points into this */
memset(tr, 0, sizeof *tr);
diff --git a/src/model/k3_bind.c b/src/model/k3_bind.c
index d8e3518..39289e0 100644
--- a/src/model/k3_bind.c
+++ b/src/model/k3_bind.c
@@ -1,6 +1,9 @@
/* k3_bind.c - see k3_bind.h. */
#define _POSIX_C_SOURCE 200809L
+#include "k3_portable_io.h" /* first: sets _DARWIN_C_SOURCE before any libc header;
+ * on Windows, supplies posix_memalign */
+
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@@ -565,7 +568,7 @@ int k3_model_stream_init(K3ModelStream *m, const K3St *s, const K3Cfg *c)
void k3_model_stream_free(K3ModelStream *m)
{
- free(m->buf);
+ k3_aligned_free(m->buf);
memset(m, 0, sizeof *m);
}
diff --git a/tests/unit/test_expert.c b/tests/unit/test_expert.c
index 62dcb06..d3083bd 100644
--- a/tests/unit/test_expert.c
+++ b/tests/unit/test_expert.c
@@ -38,6 +38,14 @@
#include "k3.h"
#include "k3_load.h"
+#ifdef _WIN32
+/* sync() and /proc/sys/vm/drop_caches are both Linux-only; drop_caches() below is only
+ * ever reached when have_root() has already confirmed drop_caches exists, which it
+ * never does on Windows, so this body is dead code at runtime -- it only needs to
+ * compile, not do anything. */
+static inline void sync(void) { }
+#endif
+
/* Non-zero if any correctness check failed; becomes the exit status. */
static int g_bad = 0;
diff --git a/tests/unit/test_trunk.c b/tests/unit/test_trunk.c
index 436f6e2..36145ac 100644
--- a/tests/unit/test_trunk.c
+++ b/tests/unit/test_trunk.c
@@ -571,11 +571,32 @@ int main(void)
c.n_full_attn = 1;
c.full_attn = fa;
- /* Create a temp directory for the fixture. */
- char tmpdir[] = "/tmp/k3_test_trunk_XXXXXX";
+ /* Create a temp directory for the fixture. mkdtemp() and /tmp are both POSIX
+ * assumptions: MinGW's native runtime provides neither the function nor the
+ * path, since a compiled .exe sees literal Windows paths, not the MSYS2 shell's
+ * translated view of them. */
+ char tmpdir[512];
+#if defined(_WIN32)
+ {
+ char base[MAX_PATH];
+ DWORD blen = GetTempPathA(sizeof base, base);
+ if (blen == 0 || blen >= sizeof base) {
+ fprintf(stderr, "GetTempPathA failed\n"); return 2;
+ }
+ int made = 0;
+ for (unsigned attempt = 0; attempt < 1000; attempt++) {
+ snprintf(tmpdir, sizeof tmpdir, "%sk3_test_trunk_%lu_%u",
+ base, (unsigned long)GetCurrentProcessId(), attempt);
+ if (CreateDirectoryA(tmpdir, NULL)) { made = 1; break; }
+ }
+ if (!made) { fprintf(stderr, "CreateDirectoryA failed\n"); return 2; }
+ }
+#else
+ snprintf(tmpdir, sizeof tmpdir, "/tmp/k3_test_trunk_XXXXXX");
if (!mkdtemp(tmpdir)) {
perror("mkdtemp"); return 2;
}
+#endif
if (gen_fixture(tmpdir) != 0) {
fprintf(stderr, "FAILED to generate fixture in %s\n", tmpdir);