Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
release: Vulkan engines and shaders in every archive, Metal on macOS, a Windows CUDA package
JustVugg8144b1ebdf2e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 70076767..716d4c4f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -122,7 +122,10 @@ jobs:# while backend_vulkan.c compiles perfectly. Assert all four exist.ls -l shaders/qmatmul.spv shaders/qmatmul_gate_up.spv \shaders/attention_absorb.spv shaders/rmsnorm.spv- ldd colibri | grep -q libvulkan || { echo "FAIL: built without linking libvulkan"; exit 1; }+ # Nothing links the loader (vk_load.h): a VK=1 binary starts without one, as+ # the release archives' must. The Vulkan build is the string it opens.+ if ldd colibri | grep -q libvulkan; then echo "FAIL: colibri links libvulkan"; ldd colibri; exit 1; fi+ grep -q libvulkan.so.1 colibri || { echo "FAIL: built without the Vulkan backend"; exit 1; }- name: Initialise the backend against Lavapiperun: |cd c@@ -143,6 +146,12 @@ jobs:grep -q "expert tier active" vk.log || {echo "FAIL: Vulkan initialised but the expert tier did not activate"; exit 1; }echo "OK: shaders compiled, device negotiated, expert tier active"+ # and with no loader, a line saying so instead of a binary that cannot start+ COLI_VK_LOADER=/nonexistent/libvulkan.so.1 COLI_NO_OMP_TUNE=1 COLI_VULKAN=1 SNAP=/tmp/vkprobe \+ timeout 120 ./colibri > vk0.log 2>&1 || true+ cat vk0.log+ grep -q "\[VK\] no Vulkan loader (/nonexistent/libvulkan.so.1)" vk0.log || {+ echo "FAIL: no line for a missing Vulkan loader"; exit 1; }- name: Every qmatmul weight format against a CPU referencerun: |cd cdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 353ec731..1cbd8c5d 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -3,10 +3,18 @@ name: Releaseon:push:tags: ['v*']+ # A change to this file builds and verifies every archive before a tag depends on+ # it, and publishes nothing (the release job runs on tags only).+ pull_request:+ paths: ['.github/workflows/release.yml']permissions:contents: write+env:+ # The version in the archives' names: the tag, or a stand-in on a pull request.+ TAG: ${{ startsWith(github.ref, 'refs/tags/') && github.ref_name || 'v0.0.0-test' }}+jobs:build:strategy:@@ -15,12 +23,21 @@ jobs:- os: ubuntu-latestname: linux-x86_64ext: ""- make_args: "ARCH=x86-64-v3"+ # VK=1: every engine with its Vulkan backend, and shaders/ beside them. The+ # loader is opened at run time (vk_load.h), so the engines start and run on+ # the CPU where there is no Vulkan; COLI_VULKAN=1 (coli setup sets it for a+ # Vulkan GPU) puts them on the GPU.+ make_args: "ARCH=x86-64-v3 VK=1"+ vk: "1"v4: "1"- os: macos-latestname: macos-arm64ext: ""make_args: ""+ # The engines with a Metal backend get it (opt-in at run time: COLI_METAL=1,+ # K3_METAL=1 for Kimi K3; docs/metal.md). Metal is part of macOS, so nothing+ # changes where it is not asked for.+ metal: "colibri inkling kimi_k3"# arm64 macOS joined COLI_V4_SUPPORTED; the archive verify step# asserts the engine is present and dispatchable like the others.v4: "1"@@ -35,7 +52,8 @@ jobs:# and needs nothing installed on the runner. The artifacts and# coli_xdna.dll it would use are NOT built here -- they need XRT# and the AIE toolchain -- and ship as a separate optional asset.- make_args: "XDNA=1"+ make_args: "XDNA=1 VK=1"+ vk: "1"v4: "1"# GitHub shells are format strings: 'msys2 {0}', never bare 'msys2'# (the v1.0.0 tag build failed on exactly this). Same as ci.yml.@@ -55,20 +73,32 @@ jobs:# inherit: the Package step calls the runner's 7z.exe, which lives on# the Windows PATH; the default minimal path would not see it.path-type: inherit+ # the Vulkan headers and glslc for VK=1; nothing links the loaderinstall: >-makemingw-w64-ucrt-x86_64-gcc+ mingw-w64-ucrt-x86_64-vulkan-headers+ mingw-w64-ucrt-x86_64-shaderc- if: matrix.os == 'macos-latest'run: brew install libomp+ # libvulkan-dev for the headers, glslc for the shaders; mesa-vulkan-drivers is+ # Lavapipe, which the verify step runs the packaged engine on.+ - if: matrix.os == 'ubuntu-latest'+ run: |+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends libvulkan-dev glslc mesa-vulkan-drivers+# Every portable sibling engine, not just GLM. CI's all-platform engine# matrix proves the same list builds before these archives are assembled.- name: Build enginesrun: |cd cfor t in colibri glm53 inkling kimi_k3 olmoe qwen36 qwen38 deepseek_v41 mimo qwenimage laya gliner_decide; do- make $t ${{ matrix.make_args }}+ extra=""+ case " ${{ matrix.metal }} " in *" $t "*) extra="METAL=1" ;; esac+ make $t ${{ matrix.make_args }} $extradonels -lh colibri${{ matrix.ext }} glm53${{ matrix.ext }} inkling${{ matrix.ext }} kimi_k3${{ matrix.ext }} olmoe${{ matrix.ext }} qwen36${{ matrix.ext }} qwen38${{ matrix.ext }} deepseek_v41${{ matrix.ext }} mimo${{ matrix.ext }}@@ -111,7 +141,6 @@ jobs:- name: Packagerun: |- TAG=${GITHUB_REF#refs/tags/}mkdir -p dist# The engine goes in under its PLAIN name. `coli` locates the engine by looking for# "colibri"/"colibri.exe" (then "glm") next to itself, so shipping it as@@ -142,6 +171,12 @@ jobs:if [ "${{ matrix.v4 }}" = "1" ]; thencp c/deepseek_v4${{ matrix.ext }} dist/deepseek_v4${{ matrix.ext }}fi+ # The Vulkan engines load their SPIR-V from shaders/ beside the binary+ # (coli_vk_shader_path); coli setup points COLI_VK_SHADERS there as well.+ if [ "${{ matrix.vk }}" = "1" ]; then+ mkdir -p dist/shaders+ cp c/shaders/*.spv dist/shaders/+ fi# Kimi K3 ships tiktoken.model, not tokenizer.json; k3_tokenizer.py synthesizes# it. Without this the engine is in the archive but `coli chat` still cannot# run it -- the second half of #720.@@ -183,7 +218,6 @@ jobs:# green, the tests are green, and the artifact is still unusable. Assert on behaviour.- name: Verify the packaged archive actually runsrun: |- TAG=${GITHUB_REF#refs/tags/}mkdir -p verify && cd verifyif [ "${{ matrix.ext }}" = ".exe" ]; then7z x ../dist/colibri-${TAG}-${{ matrix.name }}.zip > /dev/null@@ -299,6 +333,65 @@ jobs:test -f web/dist/experts.json || { echo "FAIL: expert atlas missing from archive"; exit 1; }python3 -c "import sys; sys.path.insert(0, '.'); from openai_server import APIHandler as A; d = A.WEB_DIST; assert (d / 'index.html').is_file(), 'server resolved WEB_DIST to %s, which has no index.html' % d; assert (d / 'experts.json').is_file(), 'no expert atlas under %s' % d; print('OK: the packaged server resolves the dashboard at', d)"+ # The GPU backends in the archive, by behaviour as above. Vulkan (Linux, Windows):+ # every shader the build compiled is in shaders/, every engine is a Vulkan build+ # (what coli setup reads to offer the GPU), none links the Vulkan loader (a+ # machine without one has to run them on the CPU), and the packaged engine, started+ # from another directory, finds its shaders and a device (Lavapipe on Linux) or,+ # with no loader, says so instead of failing to start.+ - name: Verify the archive's Vulkan engines+ if: matrix.vk == '1'+ run: |+ cd verify+ for f in ../c/shaders/*.spv; do+ test -f "shaders/$(basename "$f")" || { echo "FAIL: shaders/$(basename "$f") missing from archive"; exit 1; }+ done+ ENGINES="colibri glm53 inkling kimi_k3 olmoe qwen36 qwen38 deepseek_v41 mimo qwenimage laya gliner_decide"+ if [ "${{ matrix.v4 }}" = "1" ]; then ENGINES="$ENGINES deepseek_v4"; fi+ COLI_ENGINES="$ENGINES" python3 - <<'PYCHK'+ import os, sys+ sys.path.insert(0, ".")+ from setup_flow import binary_backends+ exe = ".exe" if os.name == "nt" else ""+ bad = [e for e in os.environ["COLI_ENGINES"].split() if "vulkan" not in binary_backends(e + exe)]+ if bad:+ sys.exit("FAIL: not Vulkan builds: " + ", ".join(bad))+ print("OK: every engine is a Vulkan build")+ PYCHK+ for e in $ENGINES; do+ if [ "${{ matrix.ext }}" = ".exe" ]; then deps=$(objdump -p $e.exe | grep 'DLL Name'); else deps=$(ldd $e); fi+ if echo "$deps" | grep -qi vulkan; then echo "FAIL: $e links the Vulkan loader:"; echo "$deps"; exit 1; fi+ done+ echo "OK: no engine links the Vulkan loader"+ mkdir -p probe && echo '{"model_type":"glm_moe_dsa"}' > probe/config.json+ here=$(pwd)+ if [ "${{ matrix.ext }}" = ".exe" ]; then+ # no GPU on the runner: whatever it finds, a [VK] line and not a missing DLL+ (cd .. && COLI_NO_OMP_TUNE=1 COLI_VULKAN=1 SNAP="$(cygpath -w "$here/probe")" \+ timeout 120 "$here/colibri.exe" > vk.log 2>&1; echo "exit $?" >> vk.log)+ cat ../vk.log+ grep -q '^\[VK\]' ../vk.log || { echo "FAIL: the packaged engine did not reach its Vulkan backend"; exit 1; }+ else+ (cd / && VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/lvp_icd.json COLI_NO_OMP_TUNE=1 COLI_VULKAN=1 \+ SNAP="$here/probe" timeout 120 "$here/colibri" > "$here/vk.log" 2>&1 || true)+ cat vk.log+ grep -q '\[VK\] ready:' vk.log || { echo "FAIL: the packaged engine did not find its shaders or Lavapipe"; exit 1; }+ (cd / && COLI_VK_LOADER=/nonexistent/libvulkan.so.1 COLI_NO_OMP_TUNE=1 COLI_VULKAN=1 \+ SNAP="$here/probe" timeout 120 "$here/colibri" > "$here/vk0.log" 2>&1 || true)+ cat vk0.log+ grep -q '\[VK\] no Vulkan loader' vk0.log || { echo "FAIL: no line for a missing loader"; exit 1; }+ fi+ echo "OK: the packaged engine runs its Vulkan backend from the archive"++ - name: Verify the archive's Metal engines+ if: matrix.metal != ''+ run: |+ cd verify+ for e in ${{ matrix.metal }}; do+ otool -L $e | grep -q Metal.framework || { echo "FAIL: $e is not a Metal build"; otool -L $e; exit 1; }+ done+ echo "OK: ${{ matrix.metal }} carry the Metal backend"+# Only the archives -- never the loose files. `dist/colibri-*.*` used to work by accident# (the engine was versioned, so it did not match); now that the engine is plainly named,# be explicit about what gets published.@@ -309,8 +402,101 @@ jobs:dist/colibri-*.zipdist/colibri-*.tar.gz+ # The Windows CUDA package, an archive of its own: coli_cuda.dll (CUDA_ARCH=portable:+ # SASS for sm_80/86/89/90/120 plus compute_120 PTX, so RTX 30, 40 and 50 cards and+ # their datacenter peers), the CUDA runtime it links, and the three engines that load+ # it (colibri, qwen36, kimi_k3; CUDA_DLL=1, with Vulkan and the NPU lane as in the+ # main archive). Unpacked next to windows-x86_64.zip's engines it replaces those three,+ # and coli setup / coli chat turn CUDA on for an NVIDIA card it runs on. A separate+ # archive because the DLL is large and only an NVIDIA card can use it.+ # windows-2022 and CUDA 12.8.1: the pins of ci.yml's windows-cuda-build, which builds+ # the same files on every commit (the toolkit refuses windows-latest's MSVC).+ cuda-windows:+ runs-on: windows-2022+ steps:+ - uses: actions/checkout@v4+ - name: MSVC environment (puts cl.exe on PATH for nvcc -ccbin)+ uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1+ - name: Install CUDA toolkit (compiler and runtime)+ uses: Jimver/cuda-toolkit@b8bf9c6c28f8a92fbb04dcfcaee872e60c57462d # v0.2.36+ with:+ cuda: '12.8.1'+ method: network+ sub-packages: '["nvcc", "cudart"]'+ - uses: msys2/setup-msys2@66cd2cce69caa17b53920067426061ca1de3a884 # v2+ with:+ msystem: UCRT64+ update: false+ path-type: inherit+ install: >-+ make+ mingw-w64-ucrt-x86_64-gcc+ mingw-w64-ucrt-x86_64-vulkan-headers+ mingw-w64-ucrt-x86_64-shaderc+ - name: Build coli_cuda.dll and the engines that load it+ shell: msys2 {0}+ run: |+ cd c+ make cuda-dll CUDA_ARCH=portable+ # .exe names: only colibri has a phony alias (ci.yml, windows-cuda-build)+ for t in colibri.exe qwen36.exe kimi_k3.exe; do make $t CUDA_DLL=1 VK=1 XDNA=1; done+ ls -l coli_cuda.dll colibri.exe qwen36.exe kimi_k3.exe+ - name: Package+ shell: bash+ run: |+ mkdir -p dist/pkg+ cp c/coli_cuda.dll c/colibri.exe c/qwen36.exe c/kimi_k3.exe dist/pkg/+ cp "$CUDA_PATH"/bin/cudart64_*.dll dist/pkg/+ printf '%s\r\n' \+ "colibri ${TAG}: the CUDA backend for Windows" \+ "" \+ "Unpack these files into the folder of colibri-${TAG}-windows-x86_64.zip, next to" \+ "coli.cmd, replacing colibri.exe, qwen36.exe and kimi_k3.exe. They are the same" \+ "engines with CUDA added; coli setup then picks CUDA for an NVIDIA card." \+ "" \+ "coli_cuda.dll runs on compute capability 8.0 and newer (RTX 30, 40, 50 series," \+ "A100, H100 and later) with an NVIDIA driver for CUDA 12. Older cards keep" \+ "Vulkan. cudart64_12.dll is NVIDIA's CUDA runtime, redistributed with it." \+ > dist/pkg/README-CUDA.txt+ cd dist/pkg+ 7z a ../colibri-${TAG}-windows-x86_64-cuda.zip *+ - name: Verify the CUDA package+ shell: msys2 {0}+ run: |+ mkdir -p verify && cd verify+ 7z x ../dist/colibri-${TAG}-windows-x86_64-cuda.zip > /dev/null+ ls -l+ for f in coli_cuda.dll colibri.exe qwen36.exe kimi_k3.exe README-CUDA.txt; do+ test -f $f || { echo "FAIL: $f missing from the CUDA package"; exit 1; }+ done+ # the DLL links the runtime that is beside it, and the engines neither CUDA+ # nor Vulkan: they load coli_cuda.dll (backend_loader.c) and the Vulkan loader+ # at run time+ rt=$(objdump -p coli_cuda.dll | sed -n 's/.*DLL Name: \(cudart64_[0-9]*\.dll\).*/\1/p')+ test -n "$rt" && test -f "$rt" || { echo "FAIL: coli_cuda.dll's runtime ($rt) is not in the package"; exit 1; }+ for e in colibri qwen36 kimi_k3; do+ deps=$(objdump -p $e.exe | grep 'DLL Name')+ if echo "$deps" | grep -qiE 'cudart|vulkan|coli_cuda'; then echo "FAIL: $e.exe links $deps"; exit 1; fi+ done+ python3 - <<'PYCHK'+ import sys+ sys.path.insert(0, "../c")+ from doctor import windows_backend_dll+ from setup_flow import binary_backends+ for e in ("colibri", "qwen36", "kimi_k3"):+ image = open(e + ".exe", "rb").read()+ if windows_backend_dll(image) != "coli_cuda.dll" or binary_backends(e + ".exe") != {"cuda", "vulkan"}:+ sys.exit(f"FAIL: {e}.exe is not a CUDA_DLL + Vulkan build")+ print("OK: colibri, qwen36 and kimi_k3 load coli_cuda.dll and carry Vulkan")+ PYCHK+ - uses: actions/upload-artifact@v4+ with:+ name: colibri-windows-x86_64-cuda+ path: dist/colibri-*-cuda.zip+release:- needs: build+ needs: [build, cuda-windows]+ if: startsWith(github.ref, 'refs/tags/')runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4diff --git a/README.id.md b/README.id.mdindex 2adc682c..57ecfeb5 100644--- a/README.id.md+++ b/README.id.md@@ -80,7 +80,8 @@ menekan Enter akan menerima rekomendasi. Kemudian proses penyiapan:RAM, ditambah cache minimum pakar, harus muat di RAM Anda, dan unduhannyaharus muat di disk;3. **menyiapkan engine**: engine akan di-build untuk mesin Anda jika compiler- tersedia; jika tidak, versi prebuilt yang berjalan di CPU akan diunduh.+ tersedia; jika tidak, versi prebuilt akan diunduh, yang berjalan di CPU dan,+ di Linux dan Windows, juga di GPU Vulkan.Build untuk GPU dibuat ketika memberikan keuntungan: CUDA untuk kartu NVIDIAdi Linux jika CUDA toolkit sudah terinstal, jika tidak maka Vulkan. Pada GPUdiskret, build GPU selalu digunakan; pada GPU terintegrasi yang berbagi RAMdiff --git a/README.it.md b/README.it.mdindex 953b48b3..4934f5d6 100644--- a/README.it.md+++ b/README.it.md@@ -80,7 +80,8 @@ l'installazione:RAM, più una cache minima di expert, deve entrare nella tua RAM, e ildownload sul tuo disco;3. **prepara il motore**: lo compila per la tua macchina se c'è un compilatore,- altrimenti scarica quello già compilato, che gira sulla CPU. Lo compila per+ altrimenti scarica quello già compilato, che gira sulla CPU e, su Linux e+ Windows, anche su una GPU Vulkan. Lo compila perla tua GPU quando conviene: CUDA per una scheda NVIDIA su Linux se èinstallato il CUDA toolkit, altrimenti Vulkan. Su una GPU dedicata lo fasempre; su una GPU integrata, che condivide la RAM della CPU, solo per idiff --git a/README.ja.md b/README.ja.mdindex 504ef670..5a258df5 100644--- a/README.ja.md+++ b/README.ja.md@@ -60,7 +60,7 @@ cd colibri1. **マシンを調べます**:RAM、ディスクの空き容量、CPU、GPU。2. **収まるモデルを推奨します**:モデルのうち常に RAM に置かれる部分と、最小限のエキスパートキャッシュが RAM に収まり、ダウンロードしたファイルがディスクに収まる必要があります。-3. **エンジンを用意します**:コンパイラがあればこのマシン向けにビルドし、なければ CPU で動くビルド済みのものをダウンロードします。GPU 向けのビルドは、それで速くなる場合に行います:Linux の NVIDIA カードで CUDA ツールキットがインストールされていれば CUDA、それ以外は Vulkan です。ディスクリート GPU では常に GPU 向けにビルドします。CPU と RAM を共有する内蔵 GPU では、そこで速くなることが計測されたモデル(Qwen3.6、Qwen3-Coder、Qwen3.8-Flash-Next)の場合だけです。足りないパッケージがある場合は、それをインストールするための正確なコマンドを表示して、CPU で続行します。あとでセットアップをもう一度実行すれば、GPU 向けにビルドし直します。+3. **エンジンを用意します**:コンパイラがあればこのマシン向けにビルドし、なければビルド済みのものをダウンロードします(CPU で動き、Linux と Windows では Vulkan GPU でも動きます)。GPU 向けのビルドは、それで速くなる場合に行います:Linux の NVIDIA カードで CUDA ツールキットがインストールされていれば CUDA、それ以外は Vulkan です。ディスクリート GPU では常に GPU 向けにビルドします。CPU と RAM を共有する内蔵 GPU では、そこで速くなることが計測されたモデル(Qwen3.6、Qwen3-Coder、Qwen3.8-Flash-Next)の場合だけです。足りないパッケージがある場合は、それをインストールするための正確なコマンドを表示して、CPU で続行します。あとでセットアップをもう一度実行すれば、GPU 向けにビルドし直します。4. **モデルをダウンロードします**。進捗を表示し、途中から再開できます:いつ止めてもかまいません。もう一度実行すれば、止まったところから続きます。5. **colibri を起動し、ブラウザでダッシュボードを開きます**。また、ほかのアプリが使えるアドレスを表示します:diff --git a/README.md b/README.mdindex 6ccf2c0f..ef40578a 100644--- a/README.md+++ b/README.md@@ -78,7 +78,8 @@ the setup:RAM, plus a minimum cache of experts, must fit in your RAM, and the downloadon your disk;3. **gets the engine**: it builds it for your machine when a compiler is there,- otherwise it downloads the prebuilt one, which runs on the CPU. It builds+ otherwise it downloads the prebuilt one, which runs on the CPU and, on Linux+ and Windows, on a Vulkan GPU too. It buildsfor your GPU when that pays: CUDA for an NVIDIA card on Linux when the CUDA toolkit is installed,otherwise Vulkan. On a discrete GPU it always does; on an integrated GPU,which shares the CPU's RAM, only for the models measured faster therediff --git a/README.zh-CN.md b/README.zh-CN.mdindex 3ba44403..e381a4b5 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -60,7 +60,7 @@ cd colibri1. **检查你的机器**:内存、磁盘可用空间、CPU 和 GPU;2. **推荐一个装得下的模型**:模型中始终留在内存里的部分,加上最小的专家缓存,必须放得进你的内存,下载的文件必须放得进你的磁盘;-3. **获取引擎**:如果机器上有编译器,就为你的机器编译引擎,否则下载预编译版本,该版本在 CPU 上运行。在值得的时候,它会为你的 GPU 编译:Linux 上的 NVIDIA 显卡在装有 CUDA toolkit 时用 CUDA,否则用 Vulkan。在独立显卡上总是这样做;集成显卡与 CPU 共用内存,只有实测在集成显卡上更快的模型(Qwen3.6、Qwen3-Coder 和 Qwen3.8-Flash-Next)才会这样做。如果缺少某个软件包,它会打印出安装该软件包的确切命令,并继续使用 CPU;之后再运行一次安装程序,它就会为 GPU 重新编译;+3. **获取引擎**:如果机器上有编译器,就为你的机器编译引擎,否则下载预编译版本,该版本在 CPU 上运行,在 Linux 和 Windows 上也能在 Vulkan GPU 上运行。在值得的时候,它会为你的 GPU 编译:Linux 上的 NVIDIA 显卡在装有 CUDA toolkit 时用 CUDA,否则用 Vulkan。在独立显卡上总是这样做;集成显卡与 CPU 共用内存,只有实测在集成显卡上更快的模型(Qwen3.6、Qwen3-Coder 和 Qwen3.8-Flash-Next)才会这样做。如果缺少某个软件包,它会打印出安装该软件包的确切命令,并继续使用 CPU;之后再运行一次安装程序,它就会为 GPU 重新编译;4. **下载模型**,显示进度并支持断点续传:随时可以中断,再次运行就会从中断的地方继续;5. **启动 colibri,并在浏览器中打开仪表盘**,同时打印出其他应用可以使用的地址:diff --git a/README.zh-TW.md b/README.zh-TW.mdindex c83ebfbf..0ce37220 100644--- a/README.zh-TW.md+++ b/README.zh-TW.md@@ -75,7 +75,8 @@ cd colibri2. **推薦一個放得下的模型**:模型中永遠留在 RAM 的部分,加上最少量的專家快取,必須放得進你的 RAM,下載的檔案也必須放得進你的硬碟;3. **取得引擎**:有編譯器時,它會針對你的機器建置引擎;沒有的話,- 就下載預先建置好的版本,在 CPU 上執行。在值得的情況下,它會為你的 GPU 建置:+ 就下載預先建置好的版本,在 CPU 上執行,在 Linux 與 Windows 上也能在 Vulkan GPU 上執行。+ 在值得的情況下,它會為你的 GPU 建置:在 Linux 上,若是 NVIDIA 顯示卡且已安裝 CUDA toolkit,就用 CUDA,否則用 Vulkan。遇到獨立顯示卡時一律如此;遇到與 CPU 共用 RAM 的內建顯示晶片時,則只針對實測在那裡比較快的模型diff --git a/c/Makefile b/c/Makefileindex 7719eaa6..e2333f5b 100644--- a/c/Makefile+++ b/c/Makefile@@ -685,25 +685,21 @@ endif# support (Polaris/RX 580); the VRAM-resident int4 expert-group PRIMITIVE measured ~35%# faster than the ROCm/HIP one on an RX 9070 (per-call incl. readback — end-to-end tok/s# depends on what else bounds the box; see docs/vulkan.md, benchmarking notes included).-# Needs libvulkan + glslc (shaderc). Default build unchanged (all colibri.c hooks under-# #ifdef COLI_VULKAN). The .comp shaders compile to .spv, loaded at runtime from-# COLI_VK_SHADERS (default: alongside the binary / ./shaders).+# Needs the Vulkan headers + glslc (shaderc) to build. Default build unchanged (all+# colibri.c hooks under #ifdef COLI_VULKAN). The .comp shaders compile to .spv, loaded at+# runtime from COLI_VK_SHADERS (default: alongside the binary / ./shaders).VK ?= 0VK_OBJ =VK_SPV =GLSLC ?= glslcifeq ($(VK),1)CFLAGS += -DCOLI_VULKAN-ifneq ($(IS_WIN),)-# Windows has no libvulkan: the loader is vulkan-1.dll, installed by the GPU-# driver, and MSYS2's vulkan-loader package ships only its import library,-# libvulkan-1.dll.a. The -static in the Windows LDFLAGS makes ld skip every-# .dll.a, so neither -lvulkan nor -lvulkan-1 resolved and VK=1 failed at link-# time. Search dynamically for this one library, then switch back: libgomp,-# winpthreads and libgcc stay static, and the only new import is vulkan-1.dll.-LDFLAGS += -Wl,-Bdynamic -lvulkan-1 -Wl,-Bstatic-else-LDFLAGS += -lvulkan+# Nothing links the Vulkan loader: backend_vulkan.c opens it at run time (vk_load.h),+# so a VK=1 binary starts where there is no libvulkan.so.1 or vulkan-1.dll and runs on+# the CPU there. The release archives are built this way. dlopen needs -ldl before+# glibc 2.34; Windows' LoadLibrary is in kernel32.+ifeq ($(IS_WIN),)+LDFLAGS += -ldlendif# vk_tier.o: the routed-expert tier the MoE engines share (vk_tier.h); an engine# that does not call it links nothing from it.diff --git a/c/Makefile.deepseek-v4 b/c/Makefile.deepseek-v4index 54529a14..9a06d71d 100644--- a/c/Makefile.deepseek-v4+++ b/c/Makefile.deepseek-v4@@ -228,12 +228,9 @@ V4_VK_OBJ =V4_VK_SPV =ifeq ($(VK),1)CFLAGS += -DCOLI_VULKAN-ifneq ($(IS_WIN),)-# As in the parent: the loader is vulkan-1.dll, and -static would skip its-# import library, so search dynamically for this one library only.-LDFLAGS += -Wl,-Bdynamic -lvulkan-1 -Wl,-Bstatic-else-LDFLAGS += -lvulkan+# As in the parent: the loader is opened at run time (vk_load.h), never linked.+ifeq ($(IS_WIN),)+LDFLAGS += -ldlendifV4_VK_OBJ = backend_vulkan_v4.o vk_tier_v4.oV4_VK_SPV = shaders/qmatmul.spv shaders/qmatmul_gate_up.spv \diff --git a/c/backend_vulkan.c b/c/backend_vulkan.cindex a9d066ce..48e70efb 100644--- a/c/backend_vulkan.c+++ b/c/backend_vulkan.c@@ -9,7 +9,7 @@// submit/wait per call; async queues and zero-copy import come in M4.#include "backend_vulkan.h"#include "vk_alloc.h"-#include <vulkan/vulkan.h>+#include "vk_load.h"#include <pthread.h>#include <stdio.h>#include <stdlib.h>@@ -19,8 +19,84 @@#ifdef __linux__#include <unistd.h>#endif+#ifdef _WIN32+#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#else+#include <dlfcn.h>+#endif+#ifdef __APPLE__+#include <mach-o/dyld.h> /* _NSGetExecutablePath */+#endifstatic double vk_now(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec*1000.0 + t.tv_nsec/1e6; }+/* ---- the loader (vk_load.h) ------------------------------------------------------+ * Opened the first time a device is asked for: COLI_VK_LOADER when set (a path, or a+ * name the system's search finds), else the system's loader, vulkan-1.dll (which every+ * GPU driver installs on Windows), libvulkan.so.1, or on macOS the Vulkan SDK's+ * libvulkan.1.dylib or MoltenVK. Every function vk_load.h lists must be there: the loader+ * exports all of Vulkan 1.2's, so one that lacks any predates it. */+#define COLI_VK_DEFINE(f) PFN_##f coli_##f;+COLI_VK_FUNCS(COLI_VK_DEFINE)+#undef COLI_VK_DEFINE++static void (*vk_sym(void *lib, const char *name))(void) {+#ifdef _WIN32+ return (void (*)(void))GetProcAddress((HMODULE)lib, name);+#else+ void *p = dlsym(lib, name);+ void (*fn)(void);+ memcpy(&fn, &p, sizeof fn);+ return fn;+#endif+}+int coli_vk_load(void) {+ static int state; /* 0 not tried, 1 loaded, -1 not available */+ if (state) return state > 0;+ state = -1;+ const char *env = getenv("COLI_VK_LOADER"), *name;+ void *lib = NULL;+#ifdef _WIN32+#ifndef LOAD_LIBRARY_SEARCH_DEFAULT_DIRS+#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000+#endif+ if (env && *env) lib = (void *)LoadLibraryA(name = env);+ else { /* the program's directory and System32, never the current one */+ lib = (void *)LoadLibraryExA(name = "vulkan-1.dll", NULL, LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);+ if (!lib) lib = (void *)LoadLibraryA(name);+ }+#else+#ifdef __APPLE__+ static const char *const names[] = {"libvulkan.1.dylib", "libvulkan.dylib", "libMoltenVK.dylib"};+#else+ static const char *const names[] = {"libvulkan.so.1", "libvulkan.so"};+#endif+ if (env && *env) lib = dlopen(name = env, RTLD_NOW | RTLD_LOCAL);+ else for (size_t i = 0; !lib && i < sizeof names / sizeof *names; i++)+ lib = dlopen(name = names[i], RTLD_NOW | RTLD_LOCAL);+#endif+ if (!lib) {+ fprintf(stderr, "[VK] no Vulkan loader (%s): the GPU's driver installs it%s\n", name,+ env && *env ? "" : "; COLI_VK_LOADER=<file> names another");+ return 0;+ }+ const char *missing = NULL;+#define COLI_VK_TAKE(f) if (!(coli_##f = (PFN_##f)vk_sym(lib, #f)) && !missing) missing = #f;+ COLI_VK_FUNCS(COLI_VK_TAKE)+#undef COLI_VK_TAKE+ if (missing) {+ fprintf(stderr, "[VK] the Vulkan loader %s has no %s: it predates Vulkan 1.2\n", name, missing);+#ifdef _WIN32+ FreeLibrary((HMODULE)lib);+#else+ dlclose(lib);+#endif+ return 0;+ }+ state = 1;+ return 1;+}+#define VKCHECK(x, what) do { VkResult _r = (x); if (_r != VK_SUCCESS) { \fprintf(stderr, "[VK] %s failed: %d\n", what, _r); return 0; } } while (0)@@ -98,6 +174,8 @@ static void vk_mem_free(VkDevice d, VkDeviceMemory m, const VkAllocationCallback}vkFreeMemory(d, m, cb);}+#undef vkAllocateMemory /* vk_load.h's, which the two above call */+#undef vkFreeMemory#define vkAllocateMemory vk_mem_alloc#define vkFreeMemory vk_mem_free/* A device just created: which of its memory types count, and the cap. */@@ -720,6 +798,10 @@ static void derive_sibling(const char *spv, const char *suffix, char *out, size_/* "…/qmatmul.spv" -> "…/attention_absorb.spv" (same directory). */static void derive_dir_file(const char *spv, const char *fname, char *out, size_t n) {const char *sl = strrchr(spv, '/');+#ifdef _WIN32+ const char *bs = strrchr(spv, '\\'); /* COLI_VK_SHADERS=C:\...\qmatmul.spv */+ if (bs && (!sl || bs > sl)) sl = bs;+#endifsize_t pre = sl ? (size_t)(sl - spv) + 1 : 0;if (pre + strlen(fname) + 1 < n) { memcpy(out, spv, pre); strcpy(out + pre, fname); }else snprintf(out, n, "%s", fname);@@ -813,6 +895,7 @@ static int g_vk_prof;int coli_vk_init(const char *spv_path) {if (G.ready) return 1;+ if (!coli_vk_load()) return 0;up_fault_init();VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,.apiVersion = VK_API_VERSION_1_2};@@ -2026,17 +2109,30 @@ const char *coli_vk_shader_path(char *buf, size_t n) {if (!stat(env, &st) && S_ISDIR(st.st_mode)) { snprintf(buf, n, "%s/qmatmul.spv", env); return buf; }return env;}-#ifdef __linux__- ssize_t k = readlink("/proc/self/exe", buf, n - 1);+ /* shaders/ next to the binary, wherever it was started from: an unpacked release+ * archive started by its full path found them only from its own directory before */+ long k = -1;+#if defined(__linux__)+ k = readlink("/proc/self/exe", buf, n - 1);+#elif defined(_WIN32)+ k = (long)GetModuleFileNameA(NULL, buf, (DWORD)n);+ if (k >= (long)n - 1) k = -1; /* truncated */+#elif defined(__APPLE__)+ uint32_t sz = (uint32_t)n;+ if (_NSGetExecutablePath(buf, &sz) == 0) k = (long)strlen(buf);+#endifif (k > 0) {buf[k] = 0;char *sl = strrchr(buf, '/');+#ifdef _WIN32+ char *bs = strrchr(buf, '\\');+ if (bs && (!sl || bs > sl)) sl = bs;+#endifif (sl && (size_t)(sl + 1 - buf) + sizeof("shaders/qmatmul.spv") <= n) {strcpy(sl + 1, "shaders/qmatmul.spv");if (!stat(buf, &st)) return buf;}}-#endifreturn "shaders/qmatmul.spv";}diff --git a/c/coli b/c/coliindex 7ec5fe0f..9348d066 100755--- a/c/coli+++ b/c/coli@@ -1037,8 +1037,11 @@ def env_for(a):# engine's "CPU" rows were GPU-assisted). --gpu none remains the# canonical hard off-switch (works on every platform, also clears the# CUDA_* sizing vars).+ # COLI_VULKAN=1 is a backend choice too (coli setup's, on a card the CUDA+ # DLL does not run on): CUDA does not stack on it unasked.if (sys.platform == "win32" and a.gpu is None and not a.vram- and e.get("COLI_CUDA") != "0"):+ and e.get("COLI_CUDA") != "0"+ and str(e.get("COLI_VULKAN","")).strip() in ("","0")):if cuda_binary():from resource_plan import (discover_gpus, plans_placement, build_plan,environment_for_plan, format_bytes)diff --git a/c/colibri.c b/c/colibri.cindex c340a592..89ffa8b5 100644--- a/c/colibri.c+++ b/c/colibri.c@@ -684,28 +684,11 @@ static int g_vk_budget2; /* COLI_VK_EXPERTS2: dev2 expert-tier cap (with COstatic int g_vk_reg_n2; /* experts resident on the dev2 tier *//* Resolve the main shader path (#523): COLI_VK_SHADERS may be the qmatmul.spv file itself* OR a directory containing it; unset, look alongside the binary (<exedir>/shaders/, the- * build layout) before the historical CWD-relative fallback, so launching from outside c/- * works. The other shaders load as siblings of the returned path (backend derive_*). */-static const char *vk_resolve_spv(char *buf, size_t n){- const char *env = getenv("COLI_VK_SHADERS");- struct stat st;- if(env && *env){- if(!stat(env,&st) && S_ISDIR(st.st_mode)){ snprintf(buf,n,"%s/qmatmul.spv",env); return buf; }- return env;- }-#ifdef __linux__- ssize_t k = readlink("/proc/self/exe", buf, n-1);- if(k > 0){- buf[k] = 0;- char *sl = strrchr(buf, '/');- if(sl && (size_t)(sl+1-buf) + sizeof("shaders/qmatmul.spv") <= n){- strcpy(sl+1, "shaders/qmatmul.spv");- if(!stat(buf,&st)) return buf;- }- }-#endif- return "shaders/qmatmul.spv";-}+ * build layout and the release archives') before the historical CWD-relative fallback, so+ * launching from outside c/ works. The other shaders load as siblings of the returned path+ * (backend derive_*). The backend's coli_vk_shader_path, which every other engine uses:+ * this copy of it looked beside the binary on Linux only. */+static const char *vk_resolve_spv(char *buf, size_t n){ return coli_vk_shader_path(buf, n); }/* PROF anatomy of the VK expert block (master-thread accumulated in moe(), printed by* profile_print): where a decode block's wall goes besides t_ecpu/t_ewait/t_egpu. */static double g_vkb_cls, g_vkb_issue, g_vkb_acc, g_vkb_wrk, g_vkb_join;diff --git a/c/setup_flow.py b/c/setup_flow.pyindex d5a163d0..90ef6577 100644--- a/c/setup_flow.py+++ b/c/setup_flow.py@@ -306,8 +306,8 @@ def toolchain(here=None):if os.path.isfile(os.path.join(ucrt, "bin", "gcc.exe")) else Nonetc["glslc"] = os.path.join(ucrt, "bin", "glslc.exe") \if os.path.isfile(os.path.join(ucrt, "bin", "glslc.exe")) else None- tc["vulkan_headers"] = (os.path.isfile(os.path.join(ucrt, "include", "vulkan", "vulkan.h"))- and os.path.isfile(os.path.join(ucrt, "lib", "libvulkan-1.dll.a")))+ # the headers only: nothing links the loader (vk_load.h)+ tc["vulkan_headers"] = os.path.isfile(os.path.join(ucrt, "include", "vulkan", "vulkan.h"))elif tc["cc"]:prefix = os.path.dirname(os.path.dirname(tc["cc"]))tc["vulkan_headers"] = os.path.isfile(os.path.join(prefix, "include", "vulkan", "vulkan.h"))@@ -355,13 +355,14 @@ PACKAGES = {"python": ["python3"]}),"msys2": ("pacman -S --needed", {"build": ["mingw-w64-ucrt-x86_64-gcc", "mingw-w64-ucrt-x86_64-libgomp", "make"],"vulkan": ["mingw-w64-ucrt-x86_64-vulkan-headers",- "mingw-w64-ucrt-x86_64-vulkan-loader","mingw-w64-ucrt-x86_64-shaderc"]}),}#: What is not one package: said in words, with where to get it.TEXT_HINTS = {"cuda": "install the CUDA Toolkit from https://developer.nvidia.com/cuda-downloads","cuda-win32": "the Windows CUDA build needs the CUDA Toolkit and MSVC: see docs/windows.md",+ "cuda-win32-release": ("unpack the release's windows-x86_64-cuda.zip next to the engines "+ "(coli_cuda.dll and the CUDA builds of colibri, qwen36 and kimi_k3)"),"build-other": "install gcc (with OpenMP) and make from your distribution","vulkan-other": ("install the Vulkan loader development files, glslc (shaderc) and the ""Mesa Vulkan drivers from your distribution"),@@ -502,7 +503,8 @@ def choose_backend(hw, family, tc, requested="auto", exclude=()):CUDA first for an NVIDIA card when this engine has a CUDA path (CUDA_ENGINES)and the toolkit here builds for every card (cuda_problem); its VRAM experttier is the measured fast path. Else Vulkan when a Vulkan GPU answered and- the build has its headers and glslc; else the CPU. On an integrated GPU,+ the build has its headers and glslc, or a Vulkan engine needs no build (a+ release archive's, prebuilt_vulkan); else the CPU. On an integrated GPU,Vulkan only for the engines measured faster there (VULKAN_IGPU_MEASURED)unless Vulkan was asked for by name. Every GPU path the machine has butcannot build yet comes back in `missing` with what would enable it.@@ -518,9 +520,24 @@ def choose_backend(hw, family, tc, requested="auto", exclude=()):decision["reason"] = "CPU only, as requested"return decisioncuda_engine = family.id in CUDA_ENGINES and host_os().startswith("linux")+ win_cuda = host_os() == "win32" and family.id in WINDOWS_CUDA_ENGINESblocked = Noneif nvidia and requested in ("auto", "cuda") and "cuda" not in exclude:- if cuda_engine and tc.get("can_build_cuda"):+ if win_cuda and prebuilt_runs(family, "cuda"):+ card = nvidia[0]+ sm = setup_hw.compute_cap_sm(card.get("compute_cap"))+ if requested == "cuda" or (sm is not None and sm >= WINDOWS_CUDA_FLOOR):+ detail = f" (compute {card['compute_cap']})" if card.get("compute_cap") else ""+ decision.update(backend="cuda", gpu=card["name"],+ reason=f"NVIDIA {card['name']}{detail} with coli_cuda.dll beside the engine")+ return decision+ blocked = {"why": f"the coli_cuda.dll here runs on compute {WINDOWS_CUDA_FLOOR / 10:.1f} and "+ f"newer, and the {card['name']} is "+ + (f"compute {card['compute_cap']}" if sm is not None else "of unknown compute"),+ "fix": ""}+ elif win_cuda:+ decision["missing"].append(("cuda", TEXT_HINTS["cuda-win32-release"]))+ elif cuda_engine and tc.get("can_build_cuda"):blocked = cuda_problem(nvidia, family, tc)if blocked is None:card = nvidia[0]@@ -561,7 +578,7 @@ def choose_backend(hw, family, tc, requested="auto", exclude=()):decision["reason"] = igpu if blocked is None else f"{because('the CPU', '')}. {igpu}"return decisionif vk and requested in ("auto", "vulkan", "cuda") and "vulkan" not in exclude:- if tc.get("can_build_vulkan"):+ if tc.get("can_build_vulkan") or prebuilt_vulkan(family, tc):kind = vk.get("type")decision.update(backend="vulkan", gpu=vk["name"],reason=because("Vulkan", f"{vk['name']}, {kind} GPU"))@@ -600,12 +617,53 @@ def binary_links(path, needles):return any(needle.lower() in lowered for needle in needles)-def binary_backend(path):+def binary_backends(path):+ """The GPU backends the binary was built with: none for a CPU build; a Windows+ release engine can have both (CUDA through coli_cuda.dll, Vulkan)."""+ found = set()if binary_links(path, (b"libcudart", b"coli_cuda.dll", b"libamdhip64")):- return "cuda"+ found.add("cuda")if binary_links(path, (b"libvulkan.so", b"vulkan-1.dll", b"libvulkan.1.dylib")):- return "vulkan"- return "cpu"+ found.add("vulkan")+ return found+++def binary_backend(path):+ """The kind of build the binary is, which a rebuild keeps: CUDA before Vulkan."""+ found = binary_backends(path)+ return "cuda" if "cuda" in found else "vulkan" if "vulkan" in found else "cpu"+++def prebuilt_runs(family, backend, directory=None):+ """Does the engine in `directory` (default: next to this file) run `backend` as it+ is, with nothing to build: a release archive's engines (Vulkan builds since 2.0),+ or one built here before. A Vulkan engine needs its shaders beside it."""+ path = engine_path(directory or HERE, family)+ if not os.path.isfile(path) or backend not in binary_backends(path):+ return False+ if backend == "vulkan":+ return os.path.isfile(os.path.join(os.path.dirname(path), "shaders", "qmatmul.spv"))+ if backend == "cuda" and host_os() == "win32": # the engine loads its backend at run time+ return os.path.isfile(os.path.join(os.path.dirname(path), "coli_cuda.dll"))+ return True+++#: The release archives whose engines are built with Vulkan (release.yml, VK=1).+RELEASE_VULKAN = ("linux-x86_64.tar.gz", "windows-x86_64.zip")+#: The engines the release's windows-x86_64-cuda.zip carries, built against+#: coli_cuda.dll (release.yml, the cuda-windows job), and the oldest card its DLL+#: runs on: CUDA_ARCH=portable is SASS for sm_80 and newer plus compute_120 PTX.+WINDOWS_CUDA_ENGINES = ("glm", "qwen36", "kimi")+WINDOWS_CUDA_FLOOR = 80+++def prebuilt_vulkan(family, tc):+ """A Vulkan engine with nothing to build: the one here when there is one (a+ release archive's, or built before), else, where nothing here can build one, the+ release's that resolve_engine downloads for this system."""+ if os.path.isfile(engine_path(HERE, family)):+ return prebuilt_runs(family, "vulkan")+ return not tc.get("can_build") and release_asset_suffix() in RELEASE_VULKANdef engine_path(directory, family):@@ -862,11 +920,11 @@ def current_version():def resolve_engine(family, entry, decision, tc, out=print, allow_prebuilt=True):"""Make sure an engine for this family exists. Returns{"launcher_dir", "engine", "backend", "source"}; may lower the backend to- "cpu" when only a prebuilt (CPU) engine is possible."""+ "cpu" when only a prebuilt engine without it is possible."""local = engine_path(HERE, family)if os.path.exists(local):have = binary_backend(local)- if decision["backend"] == "cpu" or have == decision["backend"]:+ if decision["backend"] == "cpu" or decision["backend"] in binary_backends(local):make_args = decision.get("make_args", ()) if have == decision["backend"] else ()source = refresh_engine(family, have, tc, local, out=out, make_args=make_args)return {"launcher_dir": HERE, "engine": local, "backend": decision["backend"],@@ -895,10 +953,12 @@ def resolve_engine(family, entry, decision, tc, out=print, allow_prebuilt=True):engine = engine_path(runtime, family)if not os.path.exists(engine):raise SetupError(f"release {tag} has no {family.engine_artifact} engine for this system")- if decision["backend"] != "cpu":- out(f" the prebuilt engine runs on the CPU; the {decision['backend']} build needs a "- f"source checkout and a compiler: {package_hint(['build', decision['backend']])}")- return {"launcher_dir": runtime, "engine": engine, "backend": "cpu", "source": f"release {tag}"}+ backend = decision["backend"]+ if backend != "cpu" and not prebuilt_runs(family, backend, runtime):+ out(f" the prebuilt engine has no {backend} build; it needs a source checkout and a "+ f"compiler: {package_hint(['build', backend])}")+ backend = "cpu"+ return {"launcher_dir": runtime, "engine": engine, "backend": backend, "source": f"release {tag}"}# Starting expert histories, one per catalog model that has one (profiles/<id>.coli_usage).diff --git a/c/tests/test_makefile_platform.py b/c/tests/test_makefile_platform.pyindex f8943083..3e633d19 100644--- a/c/tests/test_makefile_platform.py+++ b/c/tests/test_makefile_platform.py@@ -60,14 +60,13 @@ class MakefilePlatformTests(unittest.TestCase):result = self._dry_run("portable", triplet)self.assertIn(expected_flag, result.stdout)- def test_vk_links_the_platform_vulkan_loader(self):- # Windows links -static, and ld skips import libraries under it: MSYS2- # ships the Vulkan loader only as libvulkan-1.dll.a, so -lvulkan never- # resolved. Dynamic lookup for that one library, then back to static.+ def test_vk_links_no_vulkan_loader(self):+ # The loader is opened at run time (vk_load.h): a VK=1 binary has to+ # start where there is none, as the release archives' do. Linux takes+ # -ldl for dlopen; Windows stays fully -static (LoadLibrary is kernel32).cases = (- ("x86_64-unknown-linux-gnu", "-o colibri ", ["-pthread", "-lvulkan"]),- ("x86_64-w64-mingw32", "-o colibri.exe ",- ["-static", "-lpsapi", "-Wl,-Bdynamic", "-lvulkan-1", "-Wl,-Bstatic"]),+ ("x86_64-unknown-linux-gnu", "-o colibri ", ["-pthread", "-ldl"]),+ ("x86_64-w64-mingw32", "-o colibri.exe ", ["-static", "-lpsapi"]),)for triplet, output, tail in cases:@@ -77,6 +76,8 @@ class MakefilePlatformTests(unittest.TestCase):line for line in result.stdout.splitlines() if output in line)self.assertEqual(link.split()[-len(tail):], tail)+ self.assertNotIn("-lvulkan", link)+ self.assertNotIn("-Bdynamic", link)def test_darwin_portable_build_does_not_force_x86_architecture(self):missing_libomp = "/colibri-test/missing-libomp"diff --git a/c/tests/test_setup_flow.py b/c/tests/test_setup_flow.pyindex 705c5056..bc526fe9 100644--- a/c/tests/test_setup_flow.py+++ b/c/tests/test_setup_flow.py@@ -137,8 +137,11 @@ class HomeTestCase(unittest.TestCase):class BackendChoice(unittest.TestCase):- def choose(self, hw, family="qwen36", tc=None, requested="auto", platform="linux"):- with modeled(platform):+ def choose(self, hw, family="qwen36", tc=None, requested="auto", platform="linux", here=None):+ """choose_backend with `here` as the engines' directory (default: an empty one,+ so an engine built in this checkout does not decide the answer)."""+ with modeled(platform), tempfile.TemporaryDirectory() as empty, \+ mock.patch.object(setup_flow, "HERE", here or empty):return setup_flow.choose_backend(hw, family_by_id(family), tc or TC_ALL, requested)def test_no_gpu_is_cpu(self):@@ -203,10 +206,13 @@ class BackendChoice(unittest.TestCase):self.assertEqual(self.choose(hw_report(vulkan=IGPU, nvidia=[RTX]), requested="cpu")["backend"],"cpu")- def test_windows_without_msys2_points_at_it(self):+ def test_windows_release_archive_with_a_cpu_engine_points_at_msys2(self):+ # an archive from before 2.0: its engine has no Vulkan and cannot be rebuilttc = dict(TC_ALL, source_checkout=False, make=None, cc=None, can_build=False,can_build_vulkan=False, can_build_cuda=False)- decision = self.choose(hw_report(vulkan=IGPU), tc=tc, platform="win32")+ with tempfile.TemporaryDirectory() as here:+ Path(here, "qwen36.exe").write_bytes(b"MZ plain")+ decision = self.choose(hw_report(vulkan=IGPU), tc=tc, platform="win32", here=here)self.assertEqual(decision["backend"], "cpu")hint = decision["missing"][0][1]self.assertIn("msys2.org", hint)@@ -214,6 +220,77 @@ class BackendChoice(unittest.TestCase):self.assertIn("mingw-w64-ucrt-x86_64-shaderc", hint)self.assertIn("source checkout", hint) # a release archive cannot rebuild itself+ def test_a_vulkan_engine_here_needs_no_vulkan_toolchain(self):+ # a release archive since 2.0: Vulkan engines and their shaders, no compiler+ tc = dict(TC_ALL, source_checkout=False, make=None, cc=None, can_build=False,+ can_build_vulkan=False, can_build_cuda=False)+ for os_name, content in (("linux", b"\x7fELF libvulkan.so.1"), ("win32", b"MZ vulkan-1.dll")):+ with self.subTest(os=os_name), tempfile.TemporaryDirectory() as here:+ Path(here, engine_name(os_name)).write_bytes(content)+ decision = self.choose(hw_report(vulkan=IGPU), tc=tc, platform=os_name, here=here)+ self.assertEqual(decision["backend"], "cpu") # no shaders beside it+ os.makedirs(os.path.join(here, "shaders"))+ Path(here, "shaders", "qmatmul.spv").write_bytes(b"\x03\x02\x23\x07")+ decision = self.choose(hw_report(vulkan=IGPU), tc=tc, platform=os_name, here=here)+ self.assertEqual(decision["backend"], "vulkan")+ self.assertEqual(decision["missing"], [])++ def windows_cuda_here(self, here, dll=True):+ """The release's windows-x86_64-cuda.zip unpacked: CUDA and Vulkan engines,+ their shaders and coli_cuda.dll."""+ Path(here, "qwen36.exe").write_bytes(b"MZ coli_cuda.dll vulkan-1.dll")+ os.makedirs(os.path.join(here, "shaders"), exist_ok=True)+ Path(here, "shaders", "qmatmul.spv").write_bytes(b"\x03\x02\x23\x07")+ if dll:+ Path(here, "coli_cuda.dll").write_bytes(b"MZ")++ def test_windows_cuda_package_takes_cuda_on_an_ampere_card(self):+ tc = dict(TC_ALL, source_checkout=False, make=None, cc=None, can_build=False,+ can_build_vulkan=False, can_build_cuda=False)+ rtx_vk = {"name": RTX["name"], "type": "discrete", "api_version": "1.3.289",+ "api_version_raw": (1 << 22) | (3 << 12) | 289}+ with tempfile.TemporaryDirectory() as here:+ self.windows_cuda_here(here)+ card = dict(RTX, compute_cap="8.9")+ decision = self.choose(hw_report(vulkan=rtx_vk, nvidia=[card]), tc=tc, platform="win32", here=here)+ self.assertEqual(decision["backend"], "cuda")+ self.assertIn("coli_cuda.dll beside the engine", decision["reason"])+ # a card older than the DLL's sm_80: Vulkan, saying why+ old = dict(RTX, name="NVIDIA GeForce RTX 2070", compute_cap="7.5")+ decision = self.choose(hw_report(vulkan=rtx_vk, nvidia=[old]), tc=tc, platform="win32", here=here)+ self.assertEqual(decision["backend"], "vulkan")+ self.assertIn("compute 8.0 and newer, and the NVIDIA GeForce RTX 2070 is compute 7.5",+ decision["reason"])+ # unless CUDA is asked for by name+ decision = self.choose(hw_report(vulkan=rtx_vk, nvidia=[old]), tc=tc, platform="win32",+ here=here, requested="cuda")+ self.assertEqual(decision["backend"], "cuda")+ # an engine without a CUDA path in that archive: Vulkan+ decision = self.choose(hw_report(vulkan=rtx_vk, nvidia=[card]), family="mimo", tc=tc,+ platform="win32", here=here)+ self.assertNotEqual(decision["backend"], "cuda")+ with tempfile.TemporaryDirectory() as here: # the engines without the DLL+ self.windows_cuda_here(here, dll=False)+ decision = self.choose(hw_report(vulkan=rtx_vk, nvidia=[dict(RTX, compute_cap="8.9")]),+ tc=tc, platform="win32", here=here)+ self.assertEqual(decision["backend"], "vulkan")+ self.assertEqual(decision["missing"][0][0], "cuda")+ self.assertIn("windows-x86_64-cuda.zip", decision["missing"][0][1])++ def test_no_compiler_counts_on_the_release_vulkan_engine(self):+ # nothing here builds and no engine is here: resolve_engine downloads the+ # release's, which are Vulkan builds on Linux and Windows x86_64+ tc = dict(TC_ALL, make=None, cc=None, can_build=False, can_build_vulkan=False,+ can_build_cuda=False)+ for os_name in ("linux", "win32"):+ with self.subTest(os=os_name):+ self.assertEqual(self.choose(hw_report(vulkan=DGPU), tc=tc, platform=os_name)["backend"],+ "vulkan")+ with modeled("linux", "aarch64"), tempfile.TemporaryDirectory() as empty, \+ mock.patch.object(setup_flow, "HERE", empty): # no release for it+ decision = setup_flow.choose_backend(hw_report(vulkan=DGPU), family_by_id("qwen36"), tc)+ self.assertEqual(decision["backend"], "cpu")+#: What NVIDIA's own nvcc prints, measured: 11.x and 12.x from the#: redistributable archives (developer.download.nvidia.com/compute/cuda/redist/@@ -576,10 +653,22 @@ class RunConfiguration(HomeTestCase):class EngineResolution(HomeTestCase):def test_binary_backend(self):for content, expected in ((b"\0libvulkan.so.1\0", "vulkan"), (b"VULKAN-1.DLL", "vulkan"),- (b"libcudart.so.12", "cuda"), (b"plain", "cpu")):+ (b"libcudart.so.12", "cuda"), (b"plain", "cpu"),+ (b"coli_cuda.dll vulkan-1.dll", "cuda")):path = Path(self.tmp.name, "engine")path.write_bytes(b"\x7fELF" + content)self.assertEqual(setup_flow.binary_backend(str(path)), expected)+ self.assertEqual(setup_flow.binary_backends(str(path)), {"cuda", "vulkan"})++ def test_an_engine_with_both_backends_is_used_for_vulkan(self):+ # a Windows release engine built with CUDA_DLL=1 and VK=1, no compiler here+ no_build = dict(TC_ALL, source_checkout=False, can_build=False, can_build_vulkan=False,+ can_build_cuda=False)+ info, build, said = self.resolve_present("win32", lambda path, *a, **k: str(path), tc=no_build,+ content=b"MZ coli_cuda.dll vulkan-1.dll")+ build.assert_not_called()+ self.assertEqual(info["backend"], "vulkan")+ self.assertEqual(info["source"], "present")def resolve_present(self, os_name, make, tc=TC_ALL, content=b"libvulkan.so.1"):"""resolve_engine with an engine already here and `make` standing in for@@ -755,10 +844,15 @@ class Releases(HomeTestCase):LAYOUTS = {"linux": ("linux-x86_64.tar.gz", ("coli", "qwen36")),"win32": ("windows-x86_64.zip", ("coli", "coli.cmd", "qwen36.exe"))}- def make_archive(self, os_name):+ def make_archive(self, os_name, vulkan=False):+ """A release archive; `vulkan`, one since 2.0: Vulkan engines and their shaders."""suffix, binaries = self.LAYOUTS[os_name]- members = [(name, b"engine" if name.startswith("qwen36") else b"# launcher") for name in binaries]+ engine = (b"engine vulkan-1.dll" if os_name == "win32" else b"engine libvulkan.so.1") \+ if vulkan else b"engine"+ members = [(name, engine if name.startswith("qwen36") else b"# launcher") for name in binaries]members += [("web/dist/index.html", b"<html></html>"), ("tools/k3_tokenizer.py", b"")]+ if vulkan:+ members.append(("shaders/qmatmul.spv", b"\x03\x02\x23\x07"))buffer = io.BytesIO()if suffix.endswith(".zip"):with zipfile.ZipFile(buffer, "w") as zf:@@ -777,25 +871,32 @@ class Releases(HomeTestCase):with self.subTest(os=os_name):self.check_prebuilt(os_name)- def check_prebuilt(self, os_name):+ def test_prebuilt_vulkan_engine_when_there_is_no_compiler(self):+ for os_name in ("linux", "win32"):+ with self.subTest(os=os_name):+ self.check_prebuilt(os_name, vulkan=True)++ def check_prebuilt(self, os_name, vulkan=False):tag = "v1.12.1"name = f"colibri-{tag}-{self.LAYOUTS[os_name][0]}"- archive = self.make_archive(os_name)+ archive = self.make_archive(os_name, vulkan)sums = f"{hashlib.sha256(archive).hexdigest()} {name}\n".encode()urls = self.serve_release({name: archive, "SHA256SUMS.txt": sums}, folder=os_name)getter = lambda url: {"tag_name": tag, "assets": [{"name": n, "browser_download_url": u}for n, u in urls.items()]}tc = dict(TC_ALL, source_checkout=False, can_build=False, can_build_vulkan=False)- empty = os.path.join(self.tmp.name, f"nothing-here-{os_name}")+ empty = os.path.join(self.tmp.name, f"nothing-here-{os_name}-{vulkan}")os.makedirs(empty)- home = os.path.join(self.tmp.name, f"home-{os_name}")+ home = os.path.join(self.tmp.name, f"home-{os_name}-{vulkan}")with modeled(os_name), mock.patch.object(setup_flow, "HERE", empty), \mock.patch.dict(os.environ, {"COLI_SETUP_HOME": home}), \mock.patch.object(setup_flow, "_api_get", side_effect=getter):out = []info = setup_flow.resolve_engine(family_by_id("qwen36"), setup_catalog.by_id("qwen36-35b"),{"backend": "vulkan", "missing": []}, tc, out=out.append)- self.assertEqual(info["backend"], "cpu") # prebuilt engines are CPU builds+ # an archive from before 2.0 has CPU engines; one since, Vulkan engines+ self.assertEqual(info["backend"], "vulkan" if vulkan else "cpu")+ self.assertEqual("no vulkan build" in "\n".join(out), not vulkan)self.assertTrue(info["source"].startswith("release v1.12.1"))self.assertTrue(os.path.isfile(info["engine"]))self.assertEqual(os.path.basename(info["engine"]), engine_name(os_name))diff --git a/c/tests/vulkan_engines.sh b/c/tests/vulkan_engines.shindex 92139bb4..1c79878c 100755--- a/c/tests/vulkan_engines.sh+++ b/c/tests/vulkan_engines.sh@@ -84,7 +84,7 @@ same_tokens() { # <cpu log> <vk log> <tag>: the engines' "C engine" token lines# tier (vk_tier.c) on a synthetic model in every source format.shader_formats() {make tests/test_vk_tier tests/test_glm53_vk_f32 VK=1 # every shader too: the harness's expert batch needs them- cc -O2 -pthread -DVK_TEST backend_vulkan.c -o vk_test -lvulkan -lm+ cc -O2 -pthread -DVK_TEST backend_vulkan.c -o vk_test -ldl -lmCOLI_VK_TEST_MATMUL_ONLY=1 ./vk_test shaders/qmatmul.spv | tee vk_test.logtail -1 vk_test.log | grep -qx PASS || fail "qmatmul format cases"./tests/test_vk_tier shaders/qmatmul.spv | tee vk_tier.log@@ -108,7 +108,7 @@ staged_check() { # <err log> <tag>: staged, and nothing resident left in host m}family_staged() {make tests/test_vk_tier tests/test_vk_chain VK=1 # the shaders too- cc -O2 -pthread -DVK_TEST backend_vulkan.c -o vk_test -lvulkan -lm+ cc -O2 -pthread -DVK_TEST backend_vulkan.c -o vk_test -ldl -lmlocal m e d d0=""for m in mapped staged staged-again staged-noimport window; docase $m indiff --git a/c/vk_chain.c b/c/vk_chain.cindex d0e151ea..d6769eae 100644--- a/c/vk_chain.c+++ b/c/vk_chain.c@@ -14,7 +14,7 @@* never cause one. */#include "vk_chain.h"#include "vk_alloc.h"-#include <vulkan/vulkan.h>+#include "vk_load.h"#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -32,6 +32,8 @@ static void vkc_mem_free(VkDevice d, VkDeviceMemory m, const VkAllocationCallbac(void)cb;coli_vk_mem_free((void *)d, &m);}+#undef vkAllocateMemory /* vk_load.h's: the chain's go through the books above */+#undef vkFreeMemory#define vkAllocateMemory vkc_mem_alloc#define vkFreeMemory vkc_mem_free@@ -288,6 +290,10 @@ VkcBuf *vkc_host(const void *ptr, size_t bytes, size_t *off) {static VkShaderModule load_module(const char *dir_spv, const char *file) {char path[1200];const char *sl = strrchr(dir_spv, '/');+#ifdef _WIN32+ const char *bs = strrchr(dir_spv, '\\');+ if (bs && (!sl || bs > sl)) sl = bs;+#endifsize_t pre = sl ? (size_t)(sl - dir_spv) + 1 : 0;if (pre + strlen(file) + 1 >= sizeof path) return VK_NULL_HANDLE;memcpy(path, dir_spv, pre); strcpy(path + pre, file);diff --git a/c/vk_load.h b/c/vk_load.hnew file mode 100644index 00000000..8ee6bbe5--- /dev/null+++ b/c/vk_load.h@@ -0,0 +1,112 @@+/* The Vulkan functions the backend calls (backend_vulkan.c, vk_chain.c), taken from the+ * loader at run time instead of linked: no binary built with VK=1 names libvulkan.so.1+ * or vulkan-1.dll among the libraries it needs, so it starts on a machine with no Vulkan+ * at all (the release archives are built with VK=1) and runs on the CPU there.+ * coli_vk_load (backend_vulkan.c) opens the loader the first time a device is asked for+ * and fills one pointer per function below; the macros at the end send every call in the+ * files that include this header through them. A function the backend starts calling+ * joins COLI_VK_FUNCS and gets its #define, or the build fails (no prototype, and no+ * library to link it from). */+#ifndef COLI_VK_LOAD_H+#define COLI_VK_LOAD_H+#ifndef VK_NO_PROTOTYPES+#define VK_NO_PROTOTYPES+#endif+#include <vulkan/vulkan.h>++#define COLI_VK_FUNCS(X) \+ X(vkAllocateCommandBuffers) X(vkAllocateDescriptorSets) X(vkAllocateMemory) \+ X(vkBeginCommandBuffer) X(vkBindBufferMemory) X(vkCmdBindDescriptorSets) \+ X(vkCmdBindPipeline) X(vkCmdCopyBuffer) X(vkCmdDispatch) X(vkCmdFillBuffer) \+ X(vkCmdPipelineBarrier) X(vkCmdPushConstants) X(vkCmdResetQueryPool) \+ X(vkCmdWriteTimestamp) X(vkCreateBuffer) X(vkCreateCommandPool) \+ X(vkCreateComputePipelines) X(vkCreateDescriptorPool) X(vkCreateDescriptorSetLayout) \+ X(vkCreateDevice) X(vkCreateFence) X(vkCreateInstance) X(vkCreatePipelineLayout) \+ X(vkCreateQueryPool) X(vkCreateShaderModule) X(vkDestroyBuffer) X(vkDestroyCommandPool) \+ X(vkDestroyDescriptorPool) X(vkDestroyDescriptorSetLayout) X(vkDestroyDevice) \+ X(vkDestroyFence) X(vkDestroyInstance) X(vkDestroyPipeline) X(vkDestroyPipelineLayout) \+ X(vkDestroyQueryPool) X(vkDestroyShaderModule) X(vkDeviceWaitIdle) X(vkEndCommandBuffer) \+ X(vkEnumerateDeviceExtensionProperties) X(vkEnumeratePhysicalDevices) \+ X(vkFreeCommandBuffers) X(vkFreeDescriptorSets) X(vkFreeMemory) \+ X(vkGetBufferDeviceAddress) X(vkGetBufferMemoryRequirements) X(vkGetDeviceProcAddr) \+ X(vkGetDeviceQueue) X(vkGetFenceStatus) X(vkGetInstanceProcAddr) \+ X(vkGetPhysicalDeviceFeatures2) X(vkGetPhysicalDeviceMemoryProperties) \+ X(vkGetPhysicalDeviceMemoryProperties2) X(vkGetPhysicalDeviceProperties) \+ X(vkGetPhysicalDeviceProperties2) X(vkGetPhysicalDeviceQueueFamilyProperties) \+ X(vkGetQueryPoolResults) X(vkMapMemory) X(vkQueueSubmit) X(vkResetCommandBuffer) \+ X(vkResetDescriptorPool) X(vkResetFences) X(vkUnmapMemory) X(vkUpdateDescriptorSets) \+ X(vkWaitForFences)++#define COLI_VK_EXTERN(f) extern PFN_##f coli_##f;+COLI_VK_FUNCS(COLI_VK_EXTERN)+#undef COLI_VK_EXTERN++/* Open the loader (COLI_VK_LOADER, else the system's) and take every function above:+ * 1 when all are there; 0 with a line saying what is missing, every later call too. */+int coli_vk_load(void);++#define vkAllocateCommandBuffers coli_vkAllocateCommandBuffers+#define vkAllocateDescriptorSets coli_vkAllocateDescriptorSets+#define vkAllocateMemory coli_vkAllocateMemory+#define vkBeginCommandBuffer coli_vkBeginCommandBuffer+#define vkBindBufferMemory coli_vkBindBufferMemory+#define vkCmdBindDescriptorSets coli_vkCmdBindDescriptorSets+#define vkCmdBindPipeline coli_vkCmdBindPipeline+#define vkCmdCopyBuffer coli_vkCmdCopyBuffer+#define vkCmdDispatch coli_vkCmdDispatch+#define vkCmdFillBuffer coli_vkCmdFillBuffer+#define vkCmdPipelineBarrier coli_vkCmdPipelineBarrier+#define vkCmdPushConstants coli_vkCmdPushConstants+#define vkCmdResetQueryPool coli_vkCmdResetQueryPool+#define vkCmdWriteTimestamp coli_vkCmdWriteTimestamp+#define vkCreateBuffer coli_vkCreateBuffer+#define vkCreateCommandPool coli_vkCreateCommandPool+#define vkCreateComputePipelines coli_vkCreateComputePipelines+#define vkCreateDescriptorPool coli_vkCreateDescriptorPool+#define vkCreateDescriptorSetLayout coli_vkCreateDescriptorSetLayout+#define vkCreateDevice coli_vkCreateDevice+#define vkCreateFence coli_vkCreateFence+#define vkCreateInstance coli_vkCreateInstance+#define vkCreatePipelineLayout coli_vkCreatePipelineLayout+#define vkCreateQueryPool coli_vkCreateQueryPool+#define vkCreateShaderModule coli_vkCreateShaderModule+#define vkDestroyBuffer coli_vkDestroyBuffer+#define vkDestroyCommandPool coli_vkDestroyCommandPool+#define vkDestroyDescriptorPool coli_vkDestroyDescriptorPool+#define vkDestroyDescriptorSetLayout coli_vkDestroyDescriptorSetLayout+#define vkDestroyDevice coli_vkDestroyDevice+#define vkDestroyFence coli_vkDestroyFence+#define vkDestroyInstance coli_vkDestroyInstance+#define vkDestroyPipeline coli_vkDestroyPipeline+#define vkDestroyPipelineLayout coli_vkDestroyPipelineLayout+#define vkDestroyQueryPool coli_vkDestroyQueryPool+#define vkDestroyShaderModule coli_vkDestroyShaderModule+#define vkDeviceWaitIdle coli_vkDeviceWaitIdle+#define vkEndCommandBuffer coli_vkEndCommandBuffer+#define vkEnumerateDeviceExtensionProperties coli_vkEnumerateDeviceExtensionProperties+#define vkEnumeratePhysicalDevices coli_vkEnumeratePhysicalDevices+#define vkFreeCommandBuffers coli_vkFreeCommandBuffers+#define vkFreeDescriptorSets coli_vkFreeDescriptorSets+#define vkFreeMemory coli_vkFreeMemory+#define vkGetBufferDeviceAddress coli_vkGetBufferDeviceAddress+#define vkGetBufferMemoryRequirements coli_vkGetBufferMemoryRequirements+#define vkGetDeviceProcAddr coli_vkGetDeviceProcAddr+#define vkGetDeviceQueue coli_vkGetDeviceQueue+#define vkGetFenceStatus coli_vkGetFenceStatus+#define vkGetInstanceProcAddr coli_vkGetInstanceProcAddr+#define vkGetPhysicalDeviceFeatures2 coli_vkGetPhysicalDeviceFeatures2+#define vkGetPhysicalDeviceMemoryProperties coli_vkGetPhysicalDeviceMemoryProperties+#define vkGetPhysicalDeviceMemoryProperties2 coli_vkGetPhysicalDeviceMemoryProperties2+#define vkGetPhysicalDeviceProperties coli_vkGetPhysicalDeviceProperties+#define vkGetPhysicalDeviceProperties2 coli_vkGetPhysicalDeviceProperties2+#define vkGetPhysicalDeviceQueueFamilyProperties coli_vkGetPhysicalDeviceQueueFamilyProperties+#define vkGetQueryPoolResults coli_vkGetQueryPoolResults+#define vkMapMemory coli_vkMapMemory+#define vkQueueSubmit coli_vkQueueSubmit+#define vkResetCommandBuffer coli_vkResetCommandBuffer+#define vkResetDescriptorPool coli_vkResetDescriptorPool+#define vkResetFences coli_vkResetFences+#define vkUnmapMemory coli_vkUnmapMemory+#define vkUpdateDescriptorSets coli_vkUpdateDescriptorSets+#define vkWaitForFences coli_vkWaitForFences+#endifdiff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.mdindex e5ec0114..2423727d 100644--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@ -214,9 +214,10 @@ Per-drive byte counts are reported in a `MIRROR:` stats line. Combine with `DIRE| Variable | Default | Effect ||---|---|---|-| `COLI_VULKAN` | off | Enable the Vulkan backend. Requires a `make VK=1` build. The GLM engine fails at startup (no silent fallback) if libvulkan or the compiled shaders are missing. The other engines (qwen36, qwen38, inkling, olmoe, deepseek_v41, deepseek_v4, kimi_k3, mimo, glm53, qwenimage) print one line and run on the CPU. What each one puts on the device: [vulkan.md](vulkan.md#the-other-engines). |+| `COLI_VULKAN` | off | Enable the Vulkan backend. Requires a `make VK=1` build (the release archives for Linux and Windows are). The GLM engine fails at startup (no silent fallback) if the Vulkan loader, a device or the compiled shaders are missing. The other engines (qwen36, qwen38, inkling, olmoe, deepseek_v41, deepseek_v4, kimi_k3, mimo, glm53, qwenimage) print one line and run on the CPU. What each one puts on the device: [vulkan.md](vulkan.md#the-other-engines). || `COLI_VK_DEV` | unset | The primary Vulkan device by its index in the enumeration (0, 1, ...: the order `vulkaninfo --summary` lists as GPU0, GPU1, ...), for a machine with two GPUs of the same kind. Without it, the backend prefers a discrete GPU, then integrated/virtual devices, and with two discrete GPUs takes the first. An index out of range is ignored with a `[VK] COLI_VK_DEV=... ignored` line. `[VK] ready:` names the device chosen. |-| `COLI_VK_SHADERS` | auto | Path to the compiled `qmatmul.spv` **or** the directory holding the `.spv` set; the other shaders are found next to it. Unset: `shaders/` next to the binary, then CWD-relative `shaders/qmatmul.spv`. |+| `COLI_VK_SHADERS` | auto | Path to the compiled `qmatmul.spv` **or** the directory holding the `.spv` set; the other shaders are found next to it. Unset: `shaders/` next to the binary (Linux, Windows, macOS), then CWD-relative `shaders/qmatmul.spv`. |+| `COLI_VK_LOADER` | system's | The Vulkan loader the backend opens at run time (nothing links it, `vk_load.h`): a path, or a name the system's search finds. Unset: `vulkan-1.dll` (Windows: the program's directory, then `System32`), `libvulkan.so.1` then `libvulkan.so` (Linux), `libvulkan.1.dylib`, `libvulkan.dylib` then `libMoltenVK.dylib` (macOS). Not found, or without one of the Vulkan 1.2 functions the backend calls: a `[VK]` line naming it, and no device. || `COLI_VK_EXPERTS` | unset | Deprecated. The GLM engine's routed experts are on the shared expert tier (below), sized by its budget. `N`: the tier holds at most N experts (it was the size of a fixed top-N set, 320 by default); `0`: no tier, as `COLI_VK_TIER=0`. ~19 MB per int4 expert. || `COLI_VK_DENSE` | `0` in this engine | Run the resident dense matmuls (attention projections, shared expert) on the GPU. The other engines read the same variable with a default of on (see the expert tier below); all of them go through `coli_vk_dense_decide()` in the backend. || `COLI_VK_ATTN` | `0` | Run the S≤4 MLA absorb attention core (+ fused o-projection) on the GPU, with a persistent device-side KV mirror. |diff --git a/docs/deepseek-v4.md b/docs/deepseek-v4.mdindex 5b61741a..eeae9924 100644--- a/docs/deepseek-v4.md+++ b/docs/deepseek-v4.md@@ -335,7 +335,7 @@ card fails at launch with `"no kernel image is available"` rather than producinga wrong answer. Build with `portable-pre-ampere` for those cards.## Vulkan (`VK=1`, any GPU with a Vulkan 1.2 driver)-`make deepseek-v4 VK=1` (libvulkan and `glslc` at build time) links the shared+`make deepseek-v4 VK=1` (the Vulkan headers and `glslc` at build time) links the sharedVulkan backend and its routed-expert tier; `COLI_VULKAN=1` opens the device oncethe engine has loaded. No usable device, or no shaders, and the run stays on theCPU with one `[VK] deepseek_v4:` line that says so. Two things go to the device:diff --git a/docs/metal.md b/docs/metal.mdindex 067debd7..2cff00af 100644--- a/docs/metal.md+++ b/docs/metal.md@@ -35,6 +35,10 @@ make metal-test # standalone kernel/attention correctness vs CPU referCOLI_METAL=1 COLI_MODEL=/path/glm52_i4 ./coli chat --ram 96```+The release's `macos-arm64.tar.gz` has `colibri`, `inkling` and `kimi_k3` built+with `METAL=1`: `COLI_METAL=1` (`K3_METAL=1` for Kimi K3) turns the backend on+with nothing to build, and without it they run on the CPU as before.+Measured on an M4 Max (128 GB, warm cache, MTP on): CPU 0.30 → Metal**0.42 tok/s (~1.4×)** (best config adds `DIRECT=1`; ~3× vs this machine'sfirst cold run). An M5 Max with a 46.9 GB learned pin reached **2.06 tok/s**diff --git a/docs/quickstart.md b/docs/quickstart.mdindex dd971638..852c7506 100644--- a/docs/quickstart.md+++ b/docs/quickstart.md@@ -37,7 +37,8 @@ Both run `coli setup`, which does the rest:in your RAM, and the download fits on your disk.3. **Gets the engine**: it builds it for your machine when a compiler isthere, with Vulkan or CUDA when your GPU can use it, or downloads the- prebuilt one (CPU) when there is no compiler. If a package is missing for+ prebuilt one when there is no compiler (CPU, and on Linux and Windows+ Vulkan too). If a package is missing foryour GPU it prints the exact command to install it and carries on with theCPU; nothing is installed system-wide without you. Run the setup again onceyou have installed it, and it rebuilds the engine for the GPU. CUDA is used@@ -177,6 +178,8 @@ Inside you'll find:| File | What it is ||---|---|| `colibri.exe` | **the engine** — the C program that actually runs the model |+| `qwen36.exe`, `kimi_k3.exe`, … | the engines of the other model families, chosen from the model's `config.json` |+| `shaders\` | the Vulkan shaders: the engines run on a Vulkan GPU too, with nothing to build || `coli` | the command-line launcher (`chat`, `serve`, `convert`, `doctor`, …) || `openai_server.py`, `resource_plan.py`, `doctor.py`, `autotune.py` | Python support for the API server, placement planner, diagnostics, and measured tuning |@@ -184,6 +187,9 @@ One setup step: **install Python 3** from[python.org](https://www.python.org/downloads/) — the `coli` launcher and theAPI gateway are Python scripts (the engine itself is pure C and needs nothing).No renaming, no configuration: the launcher finds `colibri.exe` next to itself.+With an NVIDIA RTX 30, 40 or 50 series card, also unpack+`colibri-<version>-windows-x86_64-cuda.zip` into the same folder for CUDA+([windows.md](windows.md#if-you-downloaded-a-release-archive-start-here)).For better understanding, from powershell prompt, a complete invocation line(relying on py launcher, to be launched from the folder where colibri.exe is) is:diff --git a/docs/vulkan.md b/docs/vulkan.mdindex 3a883e61..9d52b42a 100644--- a/docs/vulkan.md+++ b/docs/vulkan.md@@ -8,19 +8,29 @@ an RX 580 runs here via RADV) and, measured on an RX 9070 (RDNA4), it is```bashcd c-make glm VK=1 # needs libvulkan + glslc (shaderc) for the shaders+make glm VK=1 # needs the Vulkan headers + glslc (shaderc) for the shadersCOLI_VULKAN=1 COLI_VK_DENSE=1 COLI_VK_ATTN=1 \PIN=<model>/.coli_usage PIN_GB=0 COLI_NO_OMP_TUNE=1 \./coli run "Hello" --topp 0.7```-Requirements: `libvulkan` and a Vulkan **1.2** ICD with+Requirements: a Vulkan **1.2** driver with`GL_KHR_shader_subgroup_arithmetic` (any Mesa RADV, AMDVLK, NVIDIA or Intel-ANV driver from the last several years), plus `glslc` at build time. The+ANV driver from the last several years), plus the Vulkan headers and `glslc`+at build time. Thebackend picks the most capable physical device (discrete > integrated) anddegrades to the CPU path on any failure — a wedged GPU can slow a run, nevercorrupt it.+Nothing links the Vulkan loader: the backend opens it (`libvulkan.so.1`,+`vulkan-1.dll`, on macOS `libvulkan.1.dylib` or MoltenVK; `COLI_VK_LOADER`+names another) when `COLI_VULKAN=1` asks for a device. A `VK=1` binary therefore+starts on a machine with no Vulkan at all and runs on the CPU there, and with+`COLI_VULKAN=1` says `[VK] no Vulkan loader (...)`. The release archives for+Linux and Windows are built this way, with the shaders in `shaders/` next to the+engines: unpacked, they run on a Vulkan GPU with nothing to build, and+`coli setup` turns the GPU on when it finds one.+Set `COLI_NO_OMP_TUNE=1` on multi-core boxes: the engine's OMP self-tune(active spin-wait) is skipped under `COLI_CUDA`/`COLI_METAL` but not underVulkan, and spinning worker threads starve the async I/O pool (measured@@ -37,24 +47,27 @@ Unified-memory APUs and cards with Resizable BAR keep the mapped path.The compiled shaders are found via `COLI_VK_SHADERS` (either the`qmatmul.spv` file or the directory holding the `.spv` set); unset, the-engine looks in `shaders/` next to the binary, then relative to the CWD.+engine looks in `shaders/` next to the binary (Linux, Windows and macOS),+then relative to the CWD.### Windows (MSYS2)-In the MSYS2 **UCRT64** shell ([quickstart.md](quickstart.md)), add the Vulkan-headers, the loader's import library and `glslc`, then build:+The release's `windows-x86_64.zip` has the engines built this way. To build+them, in the MSYS2 **UCRT64** shell ([quickstart.md](quickstart.md)) add the+Vulkan headers and `glslc`:```bash-pacman -S --needed mingw-w64-ucrt-x86_64-vulkan-headers \- mingw-w64-ucrt-x86_64-vulkan-loader mingw-w64-ucrt-x86_64-shaderc+pacman -S --needed mingw-w64-ucrt-x86_64-vulkan-headers mingw-w64-ucrt-x86_64-shaderccd cmake colibri.exe VK=1```-The binary is statically linked like the default Windows build, plus one-import: `vulkan-1.dll`, the loader the GPU driver installs in `System32`, so it-runs outside MSYS2 with nothing added to `PATH`. The next-to-the-binary shader-lookup above is Linux-only: on Windows run from `c\` or set `COLI_VK_SHADERS`.+The binary is statically linked like the default Windows build and imports+nothing for Vulkan: it opens `vulkan-1.dll`, the loader every GPU driver+installs in `System32`, from the program's directory or `System32` (never the+current one), so it runs outside MSYS2 with nothing added to `PATH`, and on a+machine without a Vulkan driver it runs on the CPU. It finds `shaders\` next to+itself wherever it is started from.To check the driver before downloading a model, point `SNAP` at a folderholding only a `config.json`, as the CI's Lavapipe job does; the backendinitialises before any weight is read:diff --git a/docs/windows.md b/docs/windows.mdindex f0322e8f..de06d536 100644--- a/docs/windows.md+++ b/docs/windows.md@@ -10,7 +10,8 @@ Download the repository (**Code**, then **Download ZIP**, or `git clone`), unzipit and double-click **`START-HERE.bat`**. It checks for Python (and offers toinstall it with winget), finds your hardware, recommends a model that fits,gets the engine (built with MSYS2 when it is installed, with Vulkan when your-GPU can use it; otherwise the prebuilt CPU engine from the release), downloads+GPU can use it; otherwise the prebuilt one from the release, which runs on the+CPU or with Vulkan), downloadsthe model with resume and opens the dashboard. Running it again starts colibridirectly. The same from a terminal: `py -3 c\coli setup`. See[quickstart.md](quickstart.md#the-one-step-way).@@ -34,6 +35,20 @@ Explorer looks like a window that flashes and disappears (#1241). The launcherneeds Python 3 from https://www.python.org/downloads/ with "Add python.exe toPATH" ticked; the engines themselves need nothing.+The engines are built with Vulkan, their shaders in `shaders\`: `coli.cmd+setup` runs them on a GPU with a Vulkan driver (NVIDIA's, AMD's and Intel's+drivers all install one) and on the CPU everywhere else, with nothing to build.++**NVIDIA, CUDA.** For an RTX 30, 40 or 50 series card (compute capability 8.0+and newer: A100, H100 and later too) the release also has+**`colibri-<version>-windows-x86_64-cuda.zip`**. Unpack it into the same folder:+it replaces `colibri.exe`, `qwen36.exe` and `kimi_k3.exe` with the same engines+plus CUDA, and adds `coli_cuda.dll` and NVIDIA's CUDA runtime+(`cudart64_12.dll`), so no CUDA toolkit is needed, only an NVIDIA driver for+CUDA 12. `coli.cmd setup` then picks CUDA for the models those three engines+run; an older card keeps Vulkan. To build the DLL yourself, for a card the+package does not cover, see below.+The rest of this page is for building from source.---