Skip to content

fix(convert): unblock 250GB+ MoE conversions (CPU stream + drain on write) - #63

Merged
Brooooooklyn merged 3 commits into
mainfrom
fix/convert-cpu-stream-drain-memory
May 27, 2026
Merged

Brooooooklyn merged 3 commits into
mainfrom
fix/convert-cpu-stream-drain-memory

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

mlx convert on a 250 GB Qwen3.5 122B-A10B checkpoint (256 experts × 48 layers) failed two different ways:

  1. macOS Metal watchdog kill (~5 s) when materializing a 1.6 GB sliced view of a fused `experts.gate_up_proj` backed by a cold mmap'd HF shard — surfaces as `kIOGPUCommandBufferCallbackErrorTimeout` mid-shard.
  2. Silent OOM-kill at shard 35/49 with 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 128 GB RAM.

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:

  • convert begin/end with structured fields (`input_dir`, `output_dir`, `model_type`, `quantize`, `total_seconds`, `num_tensors`, `num_parameters`)
  • per-shard timing, MB, avg MB/s, MLX `active_mb` / `peak_mb` / `cache_mb`
  • any single-tensor materialization ≥ 2 s (watchdog / cold-mmap signal)

`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)

Before After
Result Died at shard 3/49 (Metal watchdog), then shard 35/49 (OOM-kill) ✓ 49/49 in 11:40
MLX peak memory 162 GB 4.6 GB
MLX active (steady-state) growing unbounded 0 MB
Avg throughput n/a (crash) 334 MB/s sustained

`cargo clippy --all-targets -- -D warnings` and `cargo fmt --check` both clean.

Test plan

  • Qwen3.5 122B-A10B full bf16 conversion completes end-to-end (49 shards + index)
  • `cargo clippy --all-targets -- -D warnings`
  • `cargo fmt --check`
  • Spot-check that small / already-working conversions (Qwen3 0.6B, smaller MoE) still work — same code path now uses CPU stream, expected to be a no-op or trivially faster
  • Spot-check that GGUF→SafeTensors path is unaffected

🤖 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 CpuConvertGuard temporarily sets MLX’s default device and stream to CPU for convert_model and convert_gguf_to_safetensors, then restores them on drop—avoiding Metal watchdog timeouts when materializing multi‑GB mmap-backed expert slices. A process-wide convert_mutex serializes conversions so global MLX defaults aren’t raced. mlx_default_device / mlx_set_default_device are added in mlx-sys to support this.

SafeTensors writers now take &mut HashMap<String, MxArray> and .remove each 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.

…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]>
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 964c2ae9-8186-4e5d-97ac-a711bd7a490c

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/convert-cpu-stream-drain-memory

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 3 potential issues.

Fix All in Cursor

❌ 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.

Comment thread crates/mlx-core/src/convert.rs Resolved
Comment thread crates/mlx-core/src/utils/gguf.rs Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/utils/gguf.rs Resolved
…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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/convert.rs Resolved
…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]>
@Brooooooklyn
Brooooooklyn merged commit cf654d4 into main May 27, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/convert-cpu-stream-drain-memory branch May 27, 2026 08:53
Brooooooklyn added a commit that referenced this pull request Jun 2, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant