Skip to content

feat: build and run mlxcel natively on Windows with CUDA - #2599

Merged
inureyes merged 7 commits into
mainfrom
feature/issue-58-windows-cuda-build
Oct 25, 2026
Merged

inureyes merged 7 commits into
mainfrom
feature/issue-58-windows-cuda-build

Conversation

@inureyes

@inureyes inureyes commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Native Windows MSVC builds of mlxcel and mlxcel-server with --features cuda now compile, link and run single-GPU inference.

The only NVIDIA Windows host available is ARM64 (RTX Spark N1X, sm_121), so the spike ran on aarch64-pc-windows-msvc (decided with the issue owner); the build glue resolves x64 and arm64 toolkit layouts alike, but no x86_64 GPU host has run it yet.

Phase 1 gate

Upstream MLX at the pin plus mlxcel's CPU and CUDA overlays builds under MSVC 14.51 + nvcc 13.4 with no source patch; only CMake library hints are needed, because FindCUDAToolkit and MLX's FindCUDNN search lib\x64 only.

What changed

  • build_support/windows_cuda.rs (shared by both build scripts): toolkit and cuDNN layout (CUDA 13 redistributable layout, lib\<arch> / bin\<arch>), Ninja generator, forward-slash CMake paths, import libraries, and /DELAYLOAD plus /INCLUDE so MLX's delay-load hook in mlx.lib is linked. OpenBLAS import library and DLL copy for MLX's Windows CPU backend.
  • MSVC flags for the C++ bridge (/std:c++20, MLX_STATIC, /bigobj, /fp:fast); MLXCEL_CXX_MARCH maps to /arch.
  • CUDA overlays: delayload.cpp (new) preloads the DLLs NVRTC and cuDNN open by plain name and resolves each DLL's imports from its own directory, never from the current directory or PATH; jit_module.cpp finds CUDA headers without CUDA_PATH; matmul.cpp gains the missing BlockMaskedMM::eval_gpu, a stale-overlay bug GNU ld hid by discarding the unused vtable.
  • Removed the dead C++ split() and tokenizers' esaxx_fast feature (training-only, static-CRT C++ that cannot link with /MD).
  • Windows is single node: generate, serve and mlxcel-server refuse distributed flags before resolving the model (src/distributed/platform.rs, ServerDistributedFlags). Unix-only code is cfg-gated; the lib tests compile on Windows.
  • Docs: Windows section in docs/installation.md, README, docs/distributed.md, docs/environment-variables.md.

Changes during review

  • Security: listeners no longer set SO_REUSEADDR on Windows, where it lets another socket bind the live port; download tempfiles use exclusive create on Windows.
  • The delay-load hook is compiled once (in mlx.lib), not also into the bridge.

Validation (RTX Spark N1X, no CUDA env vars, cold JIT cache)

  • gemma-4-e4b-it-qat-4bit, gemma-4-26b-a4b-it-4bit and a qwen3_5 27B 4-bit generate correct text; mlxcel-server serves streaming and non-streaming chat completions.
  • Distributed flags are refused in 0.2 s, before model resolution.
  • Windows clippy (--lib --tests --bins -D warnings) and fmt clean; targeted Windows tests pass (17 lib tests, 7 mlxcel-mlx-pin). Linux and macOS are covered by CI.

Not done

Release packaging and a Windows CI job; x86_64 GPU validation; CUDA 12.x layout; Qwen 3.5 MTP stays Metal-only by existing design; decode throughput on this host (27B dense about 4.4 tok/s) is not investigated.

Closes #58

Native Windows MSVC builds of mlxcel and mlxcel-server with the cuda feature now compile, link and run single-GPU inference. Validated on aarch64-pc-windows-msvc (NVIDIA RTX Spark N1X, sm_121, CUDA 13.4.3, cuDNN 9.27, VS 2026); the glue resolves x64 and arm64 toolkit layouts alike.

- Build glue (build_support/windows_cuda.rs, shared by both build scripts): toolkit and cuDNN layout under lib\<arch> and bin\<arch>, Ninja generator, forward-slash CMake paths, import libraries, /DELAYLOAD for the CUDA and cuDNN DLLs, MLX's delayload.cpp compiled into the bridge, and the OpenBLAS import library plus DLL copy.
- MSVC flags for the C++ bridge (/std:c++20, MLX_STATIC, /bigobj, /fp:fast); MLXCEL_CXX_MARCH maps to /arch.
- CUDA overlays: delayload.cpp preloads the DLLs NVRTC and cuDNN open by name and resolves each DLL's imports beside it; jit_module.cpp finds CUDA headers without CUDA_PATH; matmul.cpp gains the missing BlockMaskedMM::eval_gpu that only MSVC's link rejected.
- Drop the dead C++ split() and tokenizers' esaxx_fast (static-CRT C++ that cannot link with /MD).
- Windows is single-node: distributed flags are refused at startup; Unix-only listener and fd paths are gated.

Smoke tests on the N1X with no CUDA env vars and a cold JIT cache: gemma-4-e4b, gemma-4-26b-a4b and a qwen3_5 27B generate correct text, and mlxcel-server serves streaming and non-streaming chat completions.

Refs #58
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:windows Windows (native) specific labels Oct 25, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Native Windows MSVC build of mlxcel and mlxcel-server with --features cuda (single node, validated on aarch64-pc-windows-msvc per the decision recorded with the issue owner), without changing Linux CUDA, ROCm or macOS builds.

Findings Addressed

No CRITICAL or HIGH findings, so no fixes were committed.

Remaining Items

  • delayload.cpp is compiled twice (MEDIUM). MLX's target_sources(mlx PUBLIC $<BUILD_INTERFACE:delayload.cpp>) also compiles it into mlx.lib itself: lib /list mlx.lib shows CMakeFiles/mlx.dir/mlx/backend/cuda/delayload.cpp.obj. The bridge compile in src/lib/mlxcel-core/build.rs:219-231 therefore adds a second strong definition of __pfnDliNotifyHook2, and /INCLUDE binds whichever copy the linker finds first. Both copies come from the same overlay, so nothing breaks today, but the comment ("only CMake consumers compile it") is wrong. Either drop the bridge compile and let /INCLUDE pull the object out of mlx.lib, or keep it and correct the comment.
  • CUDA 12.9 is documented as supported but the layout assumes CUDA 13 (MEDIUM). docs/installation.md:407 and README.md:269 say "12.9+", but windows_cuda.rs:77 assumes bin\<arch>. CUDA 12.x on Windows ships its DLLs in bin\, and the cuDNN installer layout is lib\12.x\x64. On 12.9, emit_delayload_link_args (windows_cuda.rs:198) finds no DLLs and emits no /DELAYLOAD without saying so, and layout_from_env panics on the cuDNN check. Either list only validated 13.x, or fall back to bin\ and print a cargo:warning when no DLL is selected.
  • Distributed refusal runs after model resolution (MEDIUM). In src/commands/generate.rs:2851-2856 the gate comes after resolve_model_source_with_override (line 2836), so on Windows --tp-size 2 -m owner/repo downloads the checkpoint before it is refused. The server has the same ordering: start_server (src/server/startup.rs:3069) runs after build_startup_input has resolved the model. The refusal is model-independent and can move before resolution. Coverage itself is complete: every serve path goes through start_server, and the --cluster-* flags only take effect with --pp-auto.
  • The Unix-socket refusal message contains 22 literal spaces (LOW). The string at src/server/listen.rs:106 reads "does not support" because the line continuation was lost.
  • docs/distributed.md:14 lists --pp-size for mlxcel-server, which has no such flag. It applies to mlxcel generate only (LOW).
  • Only the root package and mlxcel-core get /DELAYLOAD. Other workspace crates' Windows test binaries import the CUDA DLLs eagerly and need the toolkit's bin\<arch> on PATH (LOW, relevant once the Phase 6 CI job exists).

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (cargo test -p mlxcel-mlx-pin windows_cuda: 7 passed; cargo clippy --release --features cuda --lib -D warnings clean on Windows arm64; Linux and macOS checked by reading the code only)

Checked against Linux CUDA, ROCm and macOS by reading the code. On those builds CUDA_LINK_LIBS keeps the same names in the same order, the bridge flags and the -march/-flto handling are unchanged off MSVC, and the OpenBLAS link is gated on target_os = "windows". The CMake include-dir block is guarded by WIN32. In the overlays, the jit_module.cpp edits sit behind _WIN32, delayload.cpp is compiled by upstream only under WIN32, and BlockMaskedMM::eval_gpu has no other definition in mlx/backend/cuda at bff10220 (gemms/block_mask.cu is in the source list). Dropping esaxx_fast only affects Unigram training, which nothing in the workspace uses.

- Refuse distributed flags on Windows before the model is resolved, in mlxcel generate, mlxcel serve and mlxcel-server, so a repo id is not downloaded only to be turned away. The shared ServerDistributedFlags helper backs both server CLIs and the start_server check.
- Stop compiling MLX's delayload.cpp into the bridge: CMake already builds it into mlx.lib, so the hook was defined twice. /INCLUDE now pulls the single copy from mlx.lib, which is linked ahead of delayimp.lib.
- Document CUDA 13.x only on Windows; CUDA 12.x keeps its DLLs in bin\ and the cuDNN installer layout is not searched.
- Fix the Unix-socket refusal message and the per-CLI flag list in docs/distributed.md.

Verified on the RTX Spark N1X: cold-JIT generate with no CUDA env vars, and the three entry points refuse --tp-size / --pp-auto with a nonexistent repo id in 0.2 s.

Refs #58
bind_tcp set SO_REUSEADDR unconditionally. On Unix that only allows rebinding past TIME_WAIT, but on Windows it marks the port as sharable: any other socket that also sets SO_REUSEADDR can bind the same address and port while mlxcel-server is listening and receive its incoming connections, including API keys and prompts. std, mio and tokio leave the option unset on Windows for this reason, and Windows rebinds a listener past TIME_WAIT without it. SO_EXCLUSIVEADDRUSE is not used because it delays restarts while connections sit in TIME_WAIT, and a plain socket already refuses a second SO_REUSEADDR bind (WSAEACCES).

The option is now set only under cfg(not(windows)), so Linux and macOS behavior is unchanged. This also makes the existing a_second_bind_without_reuse_port_fails test hold on Windows.

New test a_second_socket_with_so_reuseaddr_cannot_take_a_live_port binds the server listener, then asserts that a raw socket2 socket with SO_REUSEADDR cannot bind and listen on the same port. It runs on every platform.

Validated on Windows 11 ARM64: cargo fmt --check and cargo clippy --release --features cuda --lib -D warnings pass. Clippy with --tests reports no findings in the listen files; its remaining errors are pre-existing Windows dead-code and unused-import findings in other test modules. A Winsock probe confirmed the four REUSEADDR combinations behave as described. Tests were not run locally.

Refs #58
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review

Scope: what this PR adds or newly exposes by making native Windows a documented platform. The DLL loader was compared against upstream MLX bff10220 delayload.cpp and CMakeLists.txt, so only the differences are judged.

Fixed

  • HIGH, src/server/listen.rs bind_tcp: SO_REUSEADDR was set on every platform. On Windows that makes the port sharable, so another socket that also sets SO_REUSEADDR can bind the live port and receive the server's connections, including API keys and prompts. A Winsock probe on the ARM64 host confirmed a second SO_REUSEADDR listener binds successfully. The option is now set only off Windows (Unix behavior unchanged), and a new cross-platform test asserts that a second SO_REUSEADDR socket cannot take a live port. Fixed in 5c08c0f.

Not fixed (MEDIUM/LOW, left for follow-up)

  • LOW, delayload.cpp: the overlay loads from the same build-time directories upstream uses (upstream defaults MLX_CUDA_BIN_DIR to the absolute toolkit bin\x64), so the trust boundary is unchanged. LOAD_WITH_ALTERED_SEARCH_PATH swaps the application directory for the DLL's own directory in the dependency search order. CWD and PATH remain reachable, as they already were with upstream's plain LoadLibraryW. The one delta is that prefix preloading (cudnn_*, cublas64_*, cublasLt64_*, nvrtc-builtins*) loads any matching file, where upstream loaded only exact names plus the first cudnn_graph*. Hardening option: LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS drops CWD and PATH for these loads. The relative ../nvidia/... fallback is unreachable in this build because both bin dirs are always defined.
  • LOW, jit_module.cpp: MLXCEL_CUDA_INCLUDE_DIR is a sibling of the baked DLL directory under the same toolkit root, so it adds no new trust root.
  • LOW, OpenBLAS: openblas.dll is a static import, so if the exe is copied without it Windows resolves it from CWD (DLL search-order hijack). Packaging is out of scope; worth noting when bundling lands. Upstream's OpenBLAS fetch has no URL_HASH.
  • LOW, newly exposed Unix-only protections: on Windows, open_tempfile_no_symlink falls back to File::create (create_new(true) would give O_EXCL parity, and its comment still says mlxcel targets only macOS and Linux). The --log-file 0600 mode, the world-writable check in scan_insecure_allowlist_dirs, and video O_NOFOLLOW (startup already warns) are skipped there. Router download and remove fail closed.
  • LOW, docs: the "Current limits on Windows" row says the fd-anchored model-library operations "use the non-Unix fallbacks", but router_cache refuses router downloads and cache removal on non-Unix.
  • LOW, perf: preloading every cuDNN sub-library maps several hundred MB of DLLs at the first cuDNN call. This is a one-time cost.

The distributed refusal covers the server CLI, serve, start_server and generate. Cluster discovery listeners only start under --pp-auto / --pp-peer, which are refused.

Validation: cargo fmt --check and cargo clippy --release --features cuda --lib -D warnings pass. clippy --lib --tests on Windows still reports dead-code and unused-import errors in other test modules (split_mtp.rs:283, media_temp_tests.rs, media_tests.rs, router_models_discovery_tests.rs, startup_tests.rs). Tests were not run, because of the build watchdog.

- The delay-load overlay loads CUDA, cuDNN and NVRTC DLLs with LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS instead of LOAD_WITH_ALTERED_SEARCH_PATH, so their imports never come from the current directory or PATH (security review LOW).
- Download tempfiles are opened with create_new on Windows too, so an existing entry at the path, a symlink included, fails the open instead of being truncated through.
- docs/installation.md: router-mode downloads and cache removal are refused on Windows, not served by a fallback.
- Tests: the non-UTF-8 argument test builds an unpaired-surrogate OsString on Windows; symlink and Unix-socket tests and their imports are cfg(unix); a new test checks that a Unix socket target is refused off Unix. The mlxcel lib tests now compile on Windows, and clippy --lib --tests --bins -D warnings is clean there.

Verified on the RTX Spark N1X: 17 listen, distributed and short-flag tests pass; gemma-4-e4b (cold JIT) and qwen3_5 27B (cuDNN path) generate with no CUDA env vars and no DLL warnings.

Refs #58
The Windows CUDA build reads CUDA_PATH (after CUDA_HOME) and CUDNN_PATH, but environment-variables.md only named CUDA_HOME. Add them next to the existing CUDA note, linking the Windows install section.

Refs #58
@inureyes inureyes added status:done Completed and removed status:review Under review labels Oct 25, 2026
The previous commit moved the scan_insecure_allowlist_dirs import into one cfg(unix) test, but a second cfg(unix) test in the same file also calls it, so the Linux lib-test build failed (clippy, OpenXLA compile, WebUI installed artifact and 2-host CI jobs). The import is module-level again, gated on cfg(unix).

Refs #58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:windows Windows (native) specific priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Native Windows + CUDA build feasibility spike and porting plan (x86_64-pc-windows-msvc)

1 participant