Repository navigation
fix(cuda): cache custom kernels on disk to drop a per-process compile - #2538
Conversation
granite-4.0-h single-sequence decode on GB10 read about 20% slower with the fused MoE kernel than without it. The kernel is not slower per token: MLX builds every mx.fast.cuda_kernel with use_disk_cache=false, so each process NVRTC-compiled the fused gate-up and down pair again inside its first decode step, about 1.2 s that decode_tok_per_sec counts. lfm2 lost the same way (-31% at -n 256), so a per-device routing default would have given up a 6-17% decode win to remove a fixed per-process cost. The jit_module.cpp overlay now writes custom kernels to MLX_PTX_CACHE_DIR like the built-in ones (their module name already keys on a hash of the full source), and publishes every cache file by rename so a concurrent reader never loads a partial one. The MLXCEL_FUSED_MOE default is unchanged on every device. GraniteMoeHybridMoE::forward takes the routing decision through forward_routed, so the #2283 routing test is split into a forced fused arm, a forced gather arm and a test that forward follows the gate; none of them skips when MLXCEL_FUSED_MOE=0. A new CUDA integration test fails without the overlay change and requires a second process on the same cache to compile nothing. Measured on GB10 (sm_121, driver 580.178.04, test-fast), -n 256, interleaved with a null arm: granite default 89.20 tok/s against 81.63 with MLXCEL_FUSED_MOE=0 and 53.63 on main; lfm2 109.65 / 102.25 / 70.74; qwen3-30b-a3b 56.20 / 46.56 / 45.05. Record: docs/benchmark_results/fused-moe-jit-cache-gb10-2026-10-22.md. Closes #2492
The publish step added for #2492 checked each temporary file before closing it, so a final flush that failed (a full disk) still renamed a truncated file into place, and a failed .txt publish did not stop the .ptx publish. Either leaves a cache hit that every later process loads and then fails on (cuModuleLoadDataEx, or "There is no kernel named"), until the entry is deleted by hand, which is the state the comment says cannot arise. Each temporary is now closed before its state is checked, the .ptx is published only when the .txt was, and the temporary name carries the process id in place of the thread-id hash: get_jit_module already serializes writers within a process, so the id that separates writers is the process's. Verified on GB10: cuda_custom_kernel_disk_cache passes; four concurrent processes on one fresh cache dir all pass, leave no temporary, and a fifth compiles nothing; a read-only and an uncreatable MLX_PTX_CACHE_DIR both run with no cache written; granitemoehybrid (17, also with MLXCEL_FUSED_MOE=0) and switch_layers:: (57) pass. Refs #2492
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
Security and performance reviewNo CRITICAL or HIGH findings, no fix commits. Caching custom kernels does not widen the code-injection surface: MEDIUM (follow-up candidates)
LOW
PerformanceNo hot-path change: the write happens once per miss inside the compile that already holds the JIT lock. Disk growth is bounded (template args are model constants, dtypes, or capped counts such as TestsGB10 at 83df448 (test-fast, cuda, |
This PR caches the fused decode kernels on disk, so a bad entry would now break decode on every launch. In the jit_module.cpp overlay, read_cached_ptx treats an empty or short .ptx and an empty or unparseable kernel map as a miss, and JitModule discards a cached entry that fails to load, recompiles from source and republishes it once before taking the original error path. write_cached_ptx now returns quietly when create_directories fails, so a failed write only leaves the cache cold. The cuda_custom_kernel_disk_cache test now compares the child's output with the parent's bit for bit, and a third process run on a cache with a truncated .ptx and a corrupt kernel map must recompile, republish and still match. The ensure_persistent_ptx_cache doc now says built-ins are keyed by name and custom kernels by name, template arguments and a source hash. Validation: cuda_custom_kernel_disk_cache passes on GB10; clippy -D warnings clean for mlxcel lib and tests; granitemoehybrid (17) and switch_layers:: (57) pass; fmt and env-var docs checks pass. Refs #2492
A cached entry whose cuModuleGetFunction fails leaves the module loaded, so the self-healing retry leaked that handle. The catch branch now unloads it before recompiling.
The #2538 overlay publishes each cache file through a temporary named <final name>.tmp<pid>_<tick>. get_ptx_path keeps a module name of up to 245 characters in one path component, so for names of roughly 229-245 characters the temporary passed the 255-byte NAME_MAX, the open failed with ENAMETOOLONG, the entry was never written, and every process compiled that kernel again with NVRTC. The fused f32 tanh GELU kernel (a 234-character module name) hit it: each Gemma 3 image prefill paid about 1.7 s of JIT (2505 ms against 869 ms once cached). The temporary is now named from the suffix and the extension only, in the same directory, so the rename stays atomic and the name length no longer depends on the module name. tests/cuda_custom_kernel_disk_cache.rs also runs the compiled tanh GELU in its parent and child processes; it fails on the previous overlay (the child prints the JIT notice) and passes with this change. Refs #2423
…#2552) ## Summary `mlxcel_core::gelu_approx` is the exact erf GELU, while MLX's `nn.gelu_approx` / `approx="precise"` is the tanh form. This PR adds an explicit GELU selector, folds the private tanh copies into it, corrects the comments that claimed erf matched `approx="precise"`, and switches the vision families whose checkpoint and mlx-vlm port both use tanh, evaluated in f32 through a compiled kernel, which keeps the prefill cost small: Gemma 3 +2.8% pooled (same sign in both blocks, so a small real cost), Gemma 4 +2.0%, MiniCPM-V 4.6 and PaliGemma within the null arm (the eager form cost Gemma 3 +17%). - `GeluActivation { Erf, Tanh, TanhF32, TanhF32Compiled, Fast }` plus `from_hf_name` in `mlxcel_core::utils`, backed by `gelu_tanh` / `gelu_tanh_f32` / `compiled_gelu_tanh_f32` on the C++ `gelu_tanh_approx` helper. `gelu_approx` keeps erf. - Folded copies (BERT, Kokoro, Molmo2, SigLIP with a declared `gelu_pytorch_tanh`, Kimi-VL/MoonViT, Qwen3-VL) keep their eager formula and precision; tests prove the folds bit-equal for f32/bf16/f16 (BERT now casts a half result back, bit-equal for f32). - Behavior change, tanh in f32 through `TanhF32Compiled`: MiniCPM-V 4.6 encoder MLP (from `hidden_act`) and window merger; Gemma 3 VLM and PaliGemma SigLIP (missing `hidden_act` resolved to the SigLIP default as `VisionHiddenActivation::SiglipDefaultTanh`, mirrored in the XLA Gemma 3 vision emitter); Gemma 4 vision GeGLU (from `hidden_activation`, also reaching DiffusionGemma and EmbeddingGemma2). - A `hidden_act` / `hidden_activation` that is not a GELU name now fails the load for the MiniCPM-V 4.6 encoder and the Gemma 4 vision tower instead of silently running erf; every local config declares `gelu_pytorch_tanh` or omits the key. - Kept erf deliberately: InternViT and the MiniCPM-V 4.6 downsample merger (Hugging Face evaluates erf there); Gemma3n sparse layers (kernel, fused path and XLA oracle must move together). - CUDA PTX cache fix (outside GELU, affects any kernel): since #2538 the `jit_module.cpp` overlay wrote each cache file through `<module name>.txt.tmp<pid>_<tick>`, which passes NAME_MAX for module names of about 229-245 characters, so those kernels were never cached and every process NVRTC-compiled them again. The compiled tanh kernel (234 characters) hit it: Gemma 3 prefill 2505 ms uncached against 869 ms cached. The temporary is now named from the suffix and the extension only; `tests/cuda_custom_kernel_disk_cache.rs` runs this kernel in a second process, fails on the old overlay and passes now. ## Evidence Inventory: `docs/gelu-call-sites.md`. Measurements: `docs/benchmark_results/gelu-erf-vs-tanh-2026-10-23.md`. - bf16 re-test on gemma-3-4b-it-4bit's 4096-patch bf16 SigLIP tower, MiniCPM-V 4.6 and PaliGemma2: zero NaN, zero Inf for tanh in input dtype and in f32. - Logit traces: the decided-position gate cannot distinguish erf from tanh for any measured family, so decisions follow the checkpoint's declared activation; the perplexity movements are bf16 noise and support neither arm. - Compiled vs eager f32 tanh: bit-equal on a tower-shaped bf16 [64, 4304] input with outliers to +-170 (0 of 275456 lanes differ); within a 4-ulp f32 bound and one bf16/f16 ulp on the sample sweep (exact f32 max diff not printed); greedy 32-token replies identical between the eager and compiled builds on all five smoke checkpoints. Image prefill, `mlxcel generate --image tests/fixtures/test_image_shapes.png -p "Describe the image." -n 8 --temp 0 --profile`, one binary, erf and null arms through symlinked checkpoint copies declaring `gelu`, arm order rotated, `MLX_ENABLE_TF32=0`, one `gpu-lock` hold per block, no CI/cargo/nvcc process during any run. GB10, kernel 7.0.0-1019-nvidia, driver 580.178.04, `MLX_CUDA_ARCHITECTURES=121`. | Family | n | erf median | compiled tanh median | Paired tanh - erf (range) | Null - erf (range) | Outcome | |---|---|---|---|---|---|---| | Gemma 3 SigLIP | 16 | 859.5 ms | 878.7 ms | +23.8 ms, +2.8 % (-11.8..+53.8); blocks +2.4 % and +3.7 % | -0.5 ms (-33.8..+34.8) | tanh kept, residual unresolved | | Gemma 3, eager `TanhF32` (previous state) | 8 | 869.3 ms | 1013.4 ms | +148.0 ms, +17.0 % (+116.5..+174.7) | | reference | | MiniCPM-V 4.6 | 6 | 910.8 ms | 897.1 ms | -14.0 ms, -1.5 % (-36.1..+42.4) | +2.4 ms (-34.5..+31.6) | tanh kept, within null floor | | Gemma 4 vision | 12 | 661.7 ms | 677.9 ms | +13.2 ms, +2.0 % (-6.0..+36.3) | +1.0 ms (-27.9..+24.8) | tanh kept, residual unresolved | | PaliGemma SigLIP | 6 | 995.5 ms | 987.6 ms | -15.1 ms, -1.5 % (-37.5..+12.8) | +8.1 ms (-41.6..+20.3) | tanh kept, within null floor | The Gemma 3 and Gemma 4 residual has the same sign in every block while the null arm is centered on zero, so it is a small real cost; pooled it is under the 3 % acceptance line, though one Gemma 3 block alone (+3.7 %) was over it. On CUDA the compiled region still runs as more than one fused kernel; a fully fused kernel is the #2548 item. The MiniCPM-V erf arm keeps the hard-coded tanh window merger, so that row slightly understates the difference. `# prompt_tokens` disagree with mlx-vlm for InternVL, MiniCPM-V 4.6 and Gemma 3, invalidating those cross-runtime comparisons (#2547). ## Test plan - [x] `-p mlxcel-core --lib gelu` (24 passed, including the compiled-vs-eager bounds) and `activation_helpers_return_the_input_dtype`, `--test-threads=1`, `MLX_ENABLE_TF32=0` - [x] `ffi_tests::shapeless_compile_audit_harness` with `MLXCEL_SHAPELESS_COMPILE_AUDIT=1` (`compiled_gelu_tanh_f32` PASS, 3 signatures warmed) - [x] `--test cuda_custom_kernel_disk_cache` fails on the previous overlay and passes with the fix - [x] `-p mlxcel --lib` filtered to siglip (39), minicpmv4_6 (14), gemma4::activation (2), vision::config (2); earlier on this branch also internvl, molmo2, qwen3_vl, bert, kimi, kokoro, moonvit, and `-p mlxcel-xla --lib vision_config emitter::vision` - [x] `cargo clippy --profile test-fast --features cuda -p mlxcel-core --lib --tests` and `-p mlxcel --lib --tests` with `-D warnings`; `cargo fmt --all --check` - [x] CLI `--image` smoke on minicpm-v-4.6-bf16, gemma-3-4b-it-4bit, paligemma2-3b-6bit, gemma-4-e2b-it-4bit, internvl3-1b (compiled and eager builds, identical text); server request and DiffusionGemma CLI on the earlier commit Unverified: Metal (compiled path and overlay untouched there, not run); EmbeddingGemma2 (no local checkpoint); DiffusionGemma through the server (rejects image input, pre-existing); whole-workspace test and clippy runs. Remaining families are tracked in #2548. Criteria 3, 4 and 6 are met only for the measured families, so this PR does not close the issue. Refs #2423
Summary
The granite-4.0-h decode regression on GB10 was not the fused MoE kernel being slow on sm_121. MLX builds every
mx.fast.cuda_kernelwithuse_disk_cache=false, so each process NVRTC-compiled the fused gate-up and down pair again inside its first decode step (about 1.2 s, counted bydecode_tok_per_sec). The issue's "32% slower than gather" was that fixed cost read as a per-token rate. Per token the fused kernel is the faster path on GB10 for every family measured.No per-device routing policy is added, and the
MLXCEL_FUSED_MOEdefault is unchanged on every device: the data showed no per-device property to key on (lfm2 lost 31% at-n 256for the same reason), and turning the kernel off on sm_121 would have given up a 6-17% decode win.jit_module.cppoverlay: custom kernels are written toMLX_PTX_CACHE_DIRlike built-in ones (the module name already keys on a hash of the full source). Cache files are written to a process-unique temporary, closed and checked, then renamed into place, and the.ptxis published only after its kernel map, so a concurrent reader never loads a partial entry. The cache self-heals: an empty.ptx, a short read or a malformed kernel map is a miss, and a cached entry that fails to load is removed, recompiled and republished once before the original error path. A cache directory that cannot be created or written leaves the cache cold instead of throwing.GraniteMoeHybridMoE::forwardroutes throughforward_routed(x, try_fused); the perf(moe): route granite-4.0-h single-token MoE through the fused kernel #2283 test is now a forced fused arm, a forced gather arm, and a test thatforwardfollows the gate. None skips underMLXCEL_FUSED_MOE=0.tests/cuda_custom_kernel_disk_cache.rs: fails on main's overlay, passes here, requires a second process on the same cache to compile nothing and to match the first process's output bit for bit, and requires a third process on a damaged cache (empty gate-up.ptx, malformed down-kernel map) to recompile, match, and leave a complete entry.Measurement (GB10 sm_121, kernel 7.0.0-1019-nvidia, driver 580.178.04,
MLX_CUDA_ARCHITECTURES=121, test-fast,-n 256, interleaved, null arm)=0Method, per-run numbers and the intercept/slope fit:
docs/benchmark_results/fused-moe-jit-cache-gb10-2026-10-22.md.Test plan
granitemoehybridlib tests (17), also withMLXCEL_FUSED_MOE=0;switch_layers::(57);fused_moe(4), all on CUDA with--test-threads=1cuda_custom_kernel_disk_cache: red with the overlay reverted, green with itcargo clippy --profile test-fast --features cuda -p mlxcel --lib --tests -- -D warnings,cargo fmt --all --check,scripts/ci/check_env_var_docs.pyChanges during review
.ptxeven when its map failed; it now closes before checking and gates the.ptxon the map, and the temporary name uses the process id.Unverified: the retry branch for a non-empty, well-formed entry that
cuModuleLoadDataExrejects (no test plants one; it reuses the cold path's compile-and-publish); ROCm and Metal (the overlay is CUDA-only),mlxcel-serversteady state, release-profile absolute numbers, the overlay on a Windows CUDA build, and the #626/#712FUSED_MOE_MAX_DFF_CUDAprovenance (measured withmlxcel-bench-decode, whose warmup most likely absorbed the compile; re-measurement tracked in #2540). Follow-up for the pre-existing cache trust and keying gaps: #2539.Closes #2492