Repository navigation
fix(convert): unblock 250GB+ MoE conversions (CPU stream + drain on write) - #63
Conversation
…rite) Two issues prevented `mlx convert` from finishing on a 250 GB Qwen3.5 122B-A10B (256 experts × 48 layers) checkpoint: 1. macOS Metal command-buffer watchdog (~5 s) killed the process when a 1.6 GB sliced view of a fused `experts.gate_up_proj` backed by a cold mmap'd HF shard exceeded the watchdog during materialization. 2. After working around #1, the process silently exited around shard 35/49 with the MLX allocator at 162 GB active memory: each materialized contiguous backing buffer stayed live in the in-memory `HashMap<String, MxArray>` for the entire sharded save, blowing through the 128 GB host RAM and triggering an OOM kill. The fix pins the MLX default device + stream to CPU for the duration of one `convert_model` / `convert_gguf_to_safetensors` call (conversion is slice / reshape / dtype-cast only, no real math, so CPU is correct and immune to the watchdog) and drains the tensor map as each tensor's bytes hit disk so MLX can release the backing buffer immediately. Production logs at `info!` level now expose: - convert begin/end with structured fields (input, output, model_type, quant, total_seconds, num_tensors, num_parameters) - per-shard timing, MB, avg MB/s, MLX active/peak/cache memory - any single-tensor materialization ≥ 2 s `debug!` level keeps full per-tensor trace for deep debugging via `MLX_NODE_LOG="mlx_core::utils::safetensors=debug"`. Verified on Qwen3.5 122B-A10B: - before: died at shard 3/49 (Metal watchdog), then at shard 35/49 (OOM-kill, MLX peak 162 GB) - after: 49/49 in 11:40, MLX peak 4.6 GB, 334 MB/s sustained Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 3 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 6cbdba7. Configure here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6cbdba79bc
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…dedupe) Three follow-ups from PR #63 review: 1. **gguf.rs tensor_names = 0 (P1, codex).** `save_safetensors` drains `weights`, so reading `weights.keys()` to fill `GgufConversionResult` after the save returned an empty list and `num_tensors = 0` for any successful GGUF→SafeTensors conversion. Capture the names before `save_safetensors`, matching the existing pattern in `convert_foreign_weights`. 2. **Process-wide device race (P2, cursor).** `CpuConvertGuard` mutates MLX's process-wide default device + stream; two overlapping conversions in the same Node process could each save the *already flipped* state as "original" and leave the process pinned to CPU on restore. Added `convert_mutex()` (a static `tokio::sync::Mutex<()>` behind `OnceLock`) and `.await`-acquired in both `convert_model` and `convert_gguf_to_safetensors` before constructing a `CpuConvertGuard`. 3. **Duplicated guard (P3, cursor).** Removed `ConvertGgufDefaultStreamGuard`; both entrypoints now share the single `crate::convert::CpuConvertGuard`. `cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` clean. Native addon rebuilt; CLI help still loads. Co-Authored-By: Claude Opus 4.7 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9eb3c498be
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…cess Codex bot review on PR #63 flagged that `CpuConvertGuard` mutates MLX's process-wide default device + stream for the duration of a conversion, and that `convert_mutex` only serializes convert-vs-convert — not convert-vs-inference. Any concurrent inference op resolving its stream via `default_stream(default_device())` is silently routed to CPU until the conversion finishes. The proper fix is to plumb explicit `Stream` arguments through every convert-used MLX FFI op (~20 ops) so the global default is never touched. That's a substantial refactor outside this PR's scope. For the supported usage today — the `mlx convert` CLI exits after the conversion, and no other entrypoint in this codebase invokes convert — the limitation is a non-issue. Document the limitation prominently on `CpuConvertGuard` so future callers who embed convert inside a multi-tenant Node process know they have to serialize inference themselves. Co-Authored-By: Claude Opus 4.7 <[email protected]>
Post-rebase fixes required to land the MTP branch cleanly on the advanced origin/main (#61-#64: lfm2 MoE, E37 prefill opt, drain-on-write convert). All conflicts during the 84-commit replay were resolved within their commits; these are the cross-cutting reconciliations: - convert.rs: origin/main #63 changed `save_safetensors` to drain its argument (`&mut`, drain-on-write). The MTP sidecar + split-drafter writers borrow their tensor maps immutably and the sidecar reuses its map afterward (its `is_empty()` gates config metadata), so drain a small clone instead of the original. - qwen3_5/model.rs: origin/main's E37/E38 last-token prefill slice (`forward_with_optional_last_slice`) auto-merged into the SHARED `forward_pre_norm_inner`, but that primitive must return the full per-position hidden for the MTP prompt-hidden path (`chunked_prefill_with_hidden_with_size` re-slices it by chunk length). Restored the tested plain-`forward` loop. E37's main win (lm_head matmul reduction) is still applied by `project_last_logits_from_pre_norm_hidden`; only the negligible eager last-layer-MLP slice (E38) is dropped. Kept origin/main's chunk_async toggle + our parameterized chunk_size in chunked_prefill. - lfm2 integration tests (origin/main #64): added the MTP ChatConfig fields (enable_mtp/mtp_depth/mtp_adaptive_depth: None) that our branch introduced and the new lfm2 test literals lacked. Verified: build OK; mlx-core 1654 pass / 3 pre-existing Metal-f32 env failures (sources byte-identical to origin/main); paged-attn OK; clippy -D warnings clean; fmt clean; typecheck OK; TS 1260 pass / 6 missing gitignored-GSM8K-fixture failures (present in main checkout). Co-Authored-By: Claude Opus 4.8 <[email protected]>

Summary
mlx converton a 250 GB Qwen3.5 122B-A10B checkpoint (256 experts × 48 layers) failed two different ways:Both fixes are required to convert this checkpoint at all.
Fix 1: CPU device + stream for convert
Conversion does only slice / reshape / dtype-cast — no real math — so the CPU is semantically correct and immune to the Metal watchdog. A new RAII guard (`ConvertDefaultStreamGuard` / `ConvertGgufDefaultStreamGuard`) flips both `set_default_device(CPU)` AND `set_default_stream(cpu_default)` at the start of `convert_model` / `convert_gguf_to_safetensors` and restores the previous values on drop.
Setting the stream alone is NOT enough — MLX dispatches stream-less ops via `default_stream(default_device())`, so the device pin is load-bearing. New FFI shims `mlx_default_device` / `mlx_set_default_device` are added to `mlx-sys`.
Fix 2: Drain the tensor map as each tensor is written
`save_safetensors_single` / `_sharded` / `save_safetensors` now take `&mut HashMap<String, MxArray>` and call `.remove(name)` after each tensor's bytes hit disk. This releases the MLX backing buffer immediately and keeps MLX active memory bounded at ~4.6 GB peak instead of growing unbounded.
All callers updated: `convert.rs`, `training_state.rs`, `gguf.rs`, `foreign_weights.rs`, `qwen3/qwen3_5/qwen3_5_moe/model.rs`.
Production logs
`info!` level now exposes:
`debug!` level keeps the full per-tensor trace for deep debugging via `MLX_NODE_LOG="mlx_core::utils::safetensors=debug"`.
Verification (Qwen3.5 122B-A10B, 250 GB → bf16 MLX)
`cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` both clean.
Test plan
🤖 Generated with Claude Code
Note
Medium Risk
Changes process-wide MLX default device/stream during convert (documented inference overlap risk) and mutates save APIs site-wide; behavior is intentional for CLI convert but embedders must serialize inference.
Overview
Large HuggingFace / GGUF → MLX conversions are made reliable on huge MoE checkpoints by routing convert work on CPU and releasing MLX memory as each tensor is written.
A new
CpuConvertGuardtemporarily sets MLX’s default device and stream to CPU forconvert_modelandconvert_gguf_to_safetensors, then restores them on drop—avoiding Metal watchdog timeouts when materializing multi‑GB mmap-backed expert slices. A process-wideconvert_mutexserializes conversions so global MLX defaults aren’t raced.mlx_default_device/mlx_set_default_deviceare added inmlx-systo support this.SafeTensors writers now take
&mut HashMap<String, MxArray>and.removeeach tensor after it’s serialized, so backing buffers don’t accumulate through 49‑shard saves (fixes silent OOM on ~250 GB models). Call sites in convert, GGUF, foreign weights, Qwen saves, and optimizer state were updated; GGUF/foreign paths snapshot tensor names before save because the map may be drained.Structured logging was added for convert start/end, sharded save duration, per-shard throughput, MLX active/peak/cache MB, and slow (≥2 s) tensor materializations.
Reviewed by Cursor Bugbot for commit 4ba9c3e. Bugbot is set up for automated code reviews on this repo. Configure here.