Skip to content

fix(core): make MLX's default device per thread - #3069

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-3066-per-thread-default-device
Nov 15, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-3066-per-thread-default-device

Conversation

@inureyes

Copy link
Copy Markdown
Member

Summary

MLX keeps one process-global default device, while its default streams are per thread. Tests that pin the CPU with DefaultDeviceGuard::cpu() (conv_no_plan_tests, cpu_qmm_accum_tests) moved every concurrently running test's unstreamed ops onto the CPU. In a parallel cargo test -p mlxcel-core --lib, 5 of 6 runs failed. The failures were metal_few_row_qmm_matches_dequantized_reference, the direct_decode_rows seeded-sampler streams and a sampling_row_step loop test, each of which passes 20 of 20 runs alone.

  • Per-thread default device: a core overlay, mlx/device.cpp, stores the default device per thread. It is applied on every backend, and the ROCm copy carries the same block. set_default_device now moves only the calling thread.
  • Process default: set_process_default_device sets the default for threads that never set their own. The runtime uses it for --device cpu, so generation and worker threads spawned after startup stay on the CPU.
  • Overlay survives CMake: on non-CUDA builds, the CMake step that restores modified top-level mlx/*.cpp files now keeps the core overlay. Without this, the overlay was silently reverted.
  • Memory-reading tests moved: the fix(models): release long prefill inputs held by lazy recurrent state #3063 state-tail retention guards read process-wide MLX memory, so they move to their own test binary. In the lib suite they flaked once the other failures were gone.

Validation (M5 Max, metal,accelerate)

  • Parallel lib suite: cargo test -p mlxcel-core --lib passed 5 of 5 parallel runs (2272 tests each). The same suite failed in 2 of 3 runs on main 37b053af.
  • New tests:
    • streams::a_cpu_guard_moves_only_its_own_thread.
    • tests/process_default_device.rs: the process default reaches later threads, and a thread override takes precedence over it.
    • tests/state_tail_retention.rs.
  • CI-faithful gate: cargo test --workspace --profile test-fast --features metal,accelerate --no-fail-fast -- --test-threads=1 passed 15545 tests and failed 4. The four fail identically on main: server_exit_joins_worker::embedding_worker_is_joined_when_a_later_side_model_fails_to_load and three mlxcel-xla golden-MLIR tests (emitter::tests::from_json_reproduces_bundled_assets_byte_for_byte, validation::tests::{emit_all_reproduces_registered_goldens, registered_fixtures_are_byte_exact}).
  • Lint: workspace clippy, fmt and env-var docs pass.
  • Not covered: CUDA and ROCm builds are not run here. The overlay is backend-agnostic C++, and the CPU-only link job builds it.

Closes #3066

@inureyes inureyes added status:review Under review type:test Test related changes priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers labels Nov 15, 2026
inureyes added a commit that referenced this pull request Nov 15, 2026
The Windows build job's `tests/` Python suite fails in `test_bench_fused_moe_dff`:

- **`/proc/loadavg`:** `scripts/bench_fused_moe_dff.py::loadavg()` reads it, and only Linux has it (`FileNotFoundError`).
- **Open log file:** `main()` returns on several paths without closing `harness.log`, so Windows cannot remove the test's temporary directory (`PermissionError: [WinError 32]`).

The job is path-filtered and seldom runs, which is how this reached main; #3069 triggered it.

The fix:

- `loadavg()` falls back to `os.getloadavg()`, then to `"na"`.
- `main()` opens the log and the run CSV through a `contextlib.ExitStack`, so every return path closes both files.
- New tests cover both `loadavg()` fallbacks.

Validation: `python3 -m unittest discover -s tests -p 'test_*.py'` passes locally (240 tests, 28 skipped). The Windows job runs on this PR only if its path filter matches.
MLX keeps one process-global default device while its default streams are per thread, so a test that pinned the CPU with DefaultDeviceGuard moved every concurrent test's ops onto the CPU. In a parallel `cargo test -p mlxcel-core --lib`, 5 of 6 runs failed. The failures were metal_few_row_qmm_matches_dequantized_reference, the direct_decode_rows seeded-sampler streams and the sampling_row_step loop test, each of which passes alone. conv_no_plan_tests and cpu_qmm_accum_tests were the movers.

A core overlay, mlx/device.cpp, applied on every backend (with the same block in the ROCm copy), stores the default device per thread. A thread that never set one follows a process default, which the new set_process_default_device sets. The runtime now uses it for `--device cpu`, so worker threads spawned after startup stay on the CPU. On non-CUDA builds the CMake step that restores modified top-level mlx/*.cpp files now keeps the core overlay. The #3063 state-tail retention guards read process-wide MLX memory, so they move to their own test binary.

The mlxcel-core lib suite passed 5 of 5 parallel runs, and new tests cover a CPU guard confined to its thread and a process default that reaches later threads.

Closes #3066
The ROCm copy of mlx/device.cpp now carries the per-thread default-device block, so the recorded core residual changed. The residual is regenerated with rocm_overlay.py drift --write, and LOCAL_FIXES.md item 75 explains it, which make verify-rocm-overlay requires.

Refs #3066
@inureyes
inureyes force-pushed the fix/issue-3066-per-thread-default-device branch from a6da93b to 6c62608 Compare November 15, 2026 11:22
@inureyes
inureyes merged commit 712f392 into main Nov 15, 2026
32 checks passed
@inureyes
inureyes deleted the fix/issue-3066-per-thread-default-device branch November 15, 2026 11:38
inureyes added a commit that referenced this pull request Nov 15, 2026
…binary

The rotating first-fill memory guards read process-wide MLX memory. After the rebase onto #3069 they no longer compiled in the lib suite, because that PR moved the shared constants and lock into tests/state_tail_retention.rs. They now live in that binary beside the state-tail guards, so concurrent lib tests cannot skew them.
inureyes added a commit that referenced this pull request Nov 15, 2026
…binary

The rotating first-fill memory guards read process-wide MLX memory. After the rebase onto #3069 they no longer compiled in the lib suite, because that PR moved the shared constants and lock into tests/state_tail_retention.rs. They now live in that binary beside the state-tail guards, so concurrent lib tests cannot skew them.
inureyes added a commit that referenced this pull request Nov 15, 2026
The 22 kernel holders in mlx_cxx_kernels.cpp built their CustomKernelFunction on first use behind a plain `if (!initialized)` flag. Two threads entering the same holder raced: one read an empty std::optional<std::function>, and concurrent assignment corrupted the function object. In parallel `cargo test -p mlxcel --lib granitemoehybrid` runs, the fused MoE launch threw std::bad_function_call or "__next_prime overflow", which switch_layers turned into a declined fused path, and the process sometimes died with SIGSEGV. On an M5 Max, 7 of 10 runs failed at 712f392. The race predates #3069, but #3069 changed thread timing enough to expose it (0 of 10 runs failed at bb76daa).

Each holder now initializes through a std::once_flag and std::call_once, the same pattern the holders above them already use. With the change the granite module passed 12 of 12 parallel runs, the mlxcel-core lib suite passed 3 of 3 parallel runs, and the switch_layers, fused_moe, granitemoehybrid and gemma3n tests pass.
inureyes added a commit that referenced this pull request Nov 15, 2026
…ads (#3089)

The 22 custom-kernel holders in `src/lib/mlxcel-core/cpp/mlx_cxx_kernels.cpp` built their `CustomKernelFunction` on first use behind a plain `if (!initialized)` flag, so two threads entering the same holder raced. In parallel `cargo test -p mlxcel --lib granitemoehybrid` runs:

- **Exceptions:** the fused MoE launch threw `std::bad_function_call` or `__next_prime overflow`, which `switch_layers::forward_fused_kernel` turns into a declined fused path. The tests then failed at "must dispatch the fused kernel".
- **Crashes:** the process sometimes died with SIGSEGV.

On an M5 Max, 7 of 10 runs failed at 712f392 (#3069). The race predates #3069, which changed thread timing enough to expose it: 0 of 10 runs failed at bb76daa. A server that dispatches the same kernel from two threads on first use would hit it too.

Each holder now initializes through a `std::once_flag` and `std::call_once`, the same pattern the holders above them in the file already use.

## Validation (M5 Max, metal,accelerate)

- Granite module, parallel: 12 of 12 runs pass (was 3 of 10 failing on main 05312c6).
- `mlxcel-core` lib suite, parallel: 3 of 3 runs pass (2292 tests).
- The `switch_layers`, `fused_moe`, `granitemoehybrid` and `gemma3n` tests pass (124).
- Clippy for `mlxcel-core` lib and tests passes.
inureyes added a commit that referenced this pull request Nov 15, 2026
)

These four PRs merged without their technical reports (the repository keeps reports via `TECHNICAL_REPORTS/.keep-reports`). This adds the English and Korean reports for each:

- #3069: per-thread default device
- #3082: Windows bench harness test
- #3086: create_causal_mask roster count
- #3089: thread-safe kernel holders

Docs only.
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
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 priority:medium Medium priority status:review Under review type:test Test related changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test(core): parallel lib tests run GPU checks on a CPU default another test pinned

1 participant