Skip to content

Studio: opt-in MLX image engine for Apple Silicon (Z-Image) - #13379

Merged
danielhanchen merged 21 commits into
mainfrom
studio-mlx-engine
Oct 12, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
studio-mlx-engine

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Adds an opt-in MLX image engine for Unsloth Studio on Apple Silicon, starting with Z-Image (Turbo and base). It runs the mflux (MIT) Z-Image implementation in-process on the GGUF the user already picked: the GGUF's Q4_0 / Q4_1 / Q8_0 blocks are repacked exactly into MLX affine group-32 weights. It reads the same files the diffusers GGUF route already stages (the GGUF plus the base repo's text encoder, tokenizer and VAE), so there is no new model to download.

Nothing changes unless UNSLOTH_DIFFUSION_MLX=1 is set:

  • UNSLOTH_DIFFUSION_MLX unset, 0 or auto: today's routing, byte for byte. auto is accepted but behaves like 0 until a real-Mac A/B against diffusers on MPS and sd.cpp Metal decides the default.
  • Linux, Windows, CUDA / ROCm / XPU and Intel Macs never select MLX, even with the variable set.
  • With UNSLOTH_DIFFUSION_MLX=1, MLX is used only on macOS 14+ on Apple Silicon, for a GGUF of a family that declares an MLX config (Z-Image only for now), in a quant the converter handles (Q4_0 / Q4_1 / Q8_0, BF16 / F16 / F32 dense), with mlx and mflux importable. Anything else (K-quants such as Q4_K_M, other families, non-GGUF loads, missing packages, a forced UNSLOTH_DIFFUSION_ENGINE) falls through to today's engine, and the reason is reported as mlx_fallback_reason in /images/status.

What changed

  • core/inference/diffusion_engine_router.py: ENGINE_MLX; one mlx_selection() helper that both select_and_activate_engine and predict_engine call first, with the same inputs (both take a new optional gguf_filename), so the download plan and the load cannot disagree. engine_for, the cancel / retire scans, _activate logging, family_buildable_here and annotate_status know the new engine. The MLX checks run only when the variable is set, so the default path performs no extra probe.
  • core/inference/diffusion_families.py: mlx_model_config / mlx_model_config_by_base fields and family_mlx_supported(), set for z-image (z-image-turbo, and z-image for the undistilled base).
  • core/inference/mlx_diffusion_convert.py (new, numpy + gguf only): streaming GGUF to mflux converter. It checks every tensor type before writing, writes one tensor at a time through a small safetensors writer (peak RSS 4.6 GB on the 4.6 GB Q4_0 file, the prototype needed 7.4 GB), splits fused qkv, maps single-file tensor names to mflux names, and caches the result under $UNSLOTH_STUDIO_HOME/cache/mlx_diffusion/<repo>@<revision>/<file>-d<bits>-bf16/. K-quants are refused with a reason; they are not implemented here.
  • core/inference/mlx_diffusion_backend.py (new): MlxDiffusionBackend with the duck-typed surface the routes already use for diffusers and sd.cpp (begin_load, generate, cancel_generate, unload, status, load_progress, generate_progress, loading_repo_ids, loaded_repo_ids, download_plan, preflight_base_access). Text encoder, tokenizer and VAE come from the family's diffusers base repo (the files the diffusers GGUF plan already stages); the text encoder is quantized on load (4-bit on Macs with 16 GB or less, 8-bit above). Per-step progress and cancel go through mflux's in-loop callback. fp16 compute with mflux's headroom scaling on M1 / M2 (no native bf16 there), bf16 elsewhere. Text-to-image only; img2img, edit, reference, ControlNet, LoRA and prompt / seed lists are refused with a 400 so the user can unset the variable.
  • routes/inference.py: the download plan and the load route pass gguf_filename to the prediction and selection, and treat MLX like the native engine for the "no separate text-encoder / VAE file, no dense precision knob" checks.
  • models/inference.py: mlx_fallback_reason on the status response.
  • main.py: the liveness scan includes the new engine's generation_in_flight().
  • studio/install_python_stack.py: on darwin-arm64 only, after the existing MLX pins (unchanged: mlx==0.32.3, mlx-metal==0.32.3, mlx-lm==0.31.3), a best-effort mflux==0.22.0 --no-deps plus its import-time light deps (piexif, platformdirs, toml). No opencv-python, matplotlib or torch upgrade is pulled. A failure is logged and is not fatal, and mflux is not part of the MLX chat-only gate in utils/mlx_repair.py.

Tests

Linux, this branch vs the merge base (fcee6485fe), same files:

set merge base this branch
New: router matrix test_diffusion_mlx_engine_router.py (125), engine surface with mflux stubbed test_mlx_diffusion_backend.py (29), converter vs gguf.quants.dequantize on synthetic Q4_0 / Q4_1 / Q8_0 blocks test_mlx_diffusion_convert.py (44 + 1 mlx-only skip) collection errors (modules and ENGINE_MLX do not exist) pass
Existing router / route / diffusion files touched or affected (18 files) plus the three new ones 1 failed, 1353 passed, 3 collection errors (the new files) 1 failed, 1551 passed, 2 skipped
Install tests (tests/studio/install/test_mlx_install.py and friends) 536 passed 550 passed
test_mlx_repair, test_mlx_stack_blockers, test_mlx_autorepair_no_torch_optout 93 passed 93 passed

The one failure is the same test on both sides (test_cached_gguf_routes.py::test_pipeline_class_guard_passes_every_shipped_family, pre-existing on the merge base).

On the real Z-Image-Turbo Q4_0 GGUF (150 Q4_0 + 30 Q4_1 + 28 BF16 + 245 F32 tensors), the converter output at dense_bits=0 is byte-identical, tensor by tensor (1001 tensors), to the prototype converter that was validated against mflux's own bf16-loaded parameters.

macOS run (GitHub macos-15, Apple M1 Virtual, 3 vCPU, 7 GB, macOS 15.7)

A throwaway workflow installed only the engine's dependencies (MLX pins, mflux --no-deps + the three light deps, transformers 5.5.0, no torch), then drove MlxDiffusionBackend through its route-facing methods with Studio's own unsloth/Z-Image-Turbo-GGUF z-image-turbo-Q4_0.gguf:

  • Router on the real host: UNSLOTH_DIFFUSION_MLX=1 + Q4_0 selects MLX; Q4_K_M and SDXL fall back with a reason; 0 and auto do not select MLX.
  • Converter unit tests pass on macOS, including loading the converted file with mx.load and checking mx.dequantize against the reference.
  • First load: Hub fetch 57 to 71 s (GGUF + base text encoder / tokenizer / VAE, 12 GB), conversion 64 to 66 s, build 26 to 28 s. A second load reuses the cached conversion: 22 to 41 s wall.
  • Z-Image-Turbo 512 x 512, 4 steps, seed 42, fp16 compute (M1 path), 4-bit text encoder, refiners 4-bit (the 7 GB defaults), two timed repeats after a warm-up, one VM per run:
run s/step (median [spread]) s/image (median [spread])
1 7.18 [7.15, 7.18] 43.5 [43.5, 43.5]
2 7.11 [7.04, 7.11] 36.8 [36.5, 36.8]
3 7.08 [7.05, 7.08] 37.7 [33.6, 37.7]
4 8.51 [8.41, 8.51] 43.4 [41.7, 43.4]
5 (final code) 6.99 [6.96, 6.99] 37.0 [36.7, 37.0]

This matches the earlier standalone mflux measurement of the same layout on this runner type (7.19 to 7.60 s/step, 39.6 to 40.5 s/image). For scale, the sd.cpp CPU route measured 274.5 s/step and 1154 s/image at the same settings on this runner type (separate VMs).

  • Repeats are bit-identical, and the 512 px image is identical across VMs; a batch of 2 gets seeds base and base + 1; a cancel after step 1 of 8 returns "Diffusion generation was cancelled." at the next step boundary; after unload() MLX active memory is 0.0 GB and the model object is gone.
    • LPIPS (alex) of the 512 px image: 0.016 (PSNR 31.2 dB) against the same GGUF rendered by MLX's CUDA backend (exact refiners, bf16 compute), 0.108 against MLX's own bf16 Z-Image-Turbo render (the earlier measurement of this layout was 0.115), 0.020 against the earlier standalone prototype on the same runner type.

Two things found on the runner and fixed in this branch: a cancelled or otherwise retained traceback could keep the whole model (6.3 GB) alive after unload() (the load worker and generate now never leave the model in a frame-local, and cancel clears its frames), with a unit test that fails without the fix.

Not proven

  • No real Apple hardware. The runner GPU is Apple's paravirtual device (no simdgroup matrix, 3 vCPU, 7 GB), so absolute numbers and relative speeds may not carry over to an M1..M4.
  • No A/B against diffusers on MPS (Studio's default on a Mac with torch) or sd.cpp Metal on the same machine. That A/B is what should decide auto; until then MLX stays opt-in.
  • Only Z-Image (Turbo) was rendered; the undistilled base mapping is wired but not rendered. Other families stay on today's engines.
  • K-quants (Q4_K_M and friends) are refused, not converted.
  • Accuracy by quant, from a separate 8 prompts x 2 seeds sweep at 1024 px, 9 steps (LPIPS against each engine's own bf16 render): 8-bit model weights are within the usual quantization band (0.051 with a bf16 text encoder, 0.062 with an 8-bit one), while any 4-bit model weights are not (0.25 to 0.31, the same as today's sd.cpp Q4_0 route at 0.25). Q8_0 is the recommended pick for this engine; Q4_0 / Q4_1 are for Macs that cannot hold 8-bit and visibly change composition on some prompts.
  • Quality was checked on one prompt and one seed; there is no LPIPS gate in CI.
  • The Studio routes themselves were not exercised on macOS (the runner drove the engine object directly); the route changes are covered by the Linux route tests only.
  • Every runner process segfaulted at interpreter exit, after all work had finished and memory was released (faulthandler printed nothing, so it happens in late native teardown). Small MLX scripts, including work on a worker thread, exit cleanly, so the trigger is not isolated. In Studio this would only show at server shutdown.
  • One of five runs hit a Metal command-buffer timeout while building the model on its second load; the load reported the error through load_progress as designed. The paravirtual GPU is the likely cause, but it is not proven.
  • The memory policy (4-bit text encoder and 4-bit refiners at 16 GB or less) is sized from the 7 GB runner only; there is no mlx_memory.py-style limit or free-RAM check yet.
  • The --no-deps mflux install leaves pip check reporting mflux's undeclared extras (opencv-python, matplotlib, torch), which the installer ignores.

…IFFUSION_MLX=1)

Adds an MLX engine beside diffusers and sd.cpp, used only when
UNSLOTH_DIFFUSION_MLX=1 on macOS 14+ Apple Silicon for a Z-Image GGUF in a
quant that converts exactly (Q4_0 / Q4_1 / Q8_0, BF16 / F16 dense). auto is
accepted and behaves like 0 until a real-Mac A/B. Every refusal records
mlx_fallback_reason and keeps today's engine.

- diffusion_engine_router: ENGINE_MLX, shared mlx_selection() used by both
  select_and_activate_engine and predict_engine, engine_for, cancel / retire
  scans, family_buildable_here.
- diffusion_families: mlx_model_config + family_mlx_supported().
- mlx_diffusion_convert: numpy + gguf streaming GGUF -> mflux converter,
  Q4_0/Q4_1/Q8_0 repacked to MLX affine g32, cached under
  $UNSLOTH_STUDIO_HOME/cache/mlx_diffusion/. K-quants refused.
- mlx_diffusion_backend: in-process mflux engine with the route-facing
  surface (begin_load, generate, cancel_generate, unload, status, progress).
- install: mflux==0.22.0 --no-deps + piexif / platformdirs / toml on
  darwin-arm64, best effort, outside the MLX chat gate; mlx pins unchanged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T11:42:05.142913Z 6f5b825 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

An unknown error occurred
ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

- unload() joins a superseded load worker, so a build in progress is freed
  before the router treats memory as free
- the load route takes the GPU arbiter for MLX even where torch resolves cpu
- base repo fetch is cancellable per file
- resolve the variant base (base_model card tag) like the diffusers loader,
  so an undistilled Z-Image GGUF gets its own base and mflux config
- enforce the family output size limits before rendering
- clear frame locals on any generation failure, not only cancel
- record the MLX text-encoder / dense quantization in the image recipe
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 1129572222

ℹ️ 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 on lines +556 to +558
with self._lock:
self._load_thread = worker
worker.start()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make load-worker publication atomic with thread startup

When /images/unload races with begin_load, it can observe _load_thread after this lock is released but before worker.start() runs; unload() then calls join() on an unstarted thread and raises RuntimeError: cannot join thread before it is started. If unload enters slightly earlier, it instead sees no worker and returns without its intended worker barrier. Publish and start the worker under one synchronization boundary, or add an explicit startup handshake.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b8f28f6. The worker is now created, published to _load_thread and started inside the same self._lock section that bumps the load token, so unload() can never see an unstarted thread, and it cannot slip in between the token bump and publication either. Test: test_unload_racing_begin_load_never_joins_an_unstarted_worker.

Comment on lines +663 to +668
model = runtime.build(
str(out_dir),
model_config = model_config,
precision = precision,
te_bits = te_bits,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recheck cancellation before starting the MLX build

When unload sets the cancellation event after the check at line 647—particularly while a replacement load is waiting for an active generation at line 660—the worker still unconditionally starts this multi-GB, non-interruptible build. The teardown join prevents engine overlap, but fresh evidence after that fix is that unload can now block for the entire unnecessary build and allocate the model after cancellation was already requested; recheck the event or load token immediately before invoking runtime.build().

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b8f28f6. The worker checks the cancel event again after it waits for the active generation and frees the displaced model, right before runtime.build(), so an unload that arrives during that wait no longer pays for a full build. Test: test_a_load_cancelled_while_waiting_on_generation_skips_the_build.

Comment on lines +1064 to +1065
"text_encoder_quant": None,
"transformer_quant": None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Report engaged MLX quantization in live status

Although generation results now record the MLX precision policy, fresh evidence is that every loaded /images/status response still hard-codes both quantization fields to null. The extra mlx dictionary is not declared by DiffusionStatusResponse and is discarded, so the Loaded build panel labels a dense-converted transformer as “GGUF (as-is)” and a 4/8-bit text encoder as FP16/BF16. Populate these public fields from state.dense_bits and state.te_bits, as the generation result already does.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b8f28f6. status() now fills transformer_quant and text_encoder_quant from dense_bits / te_bits using the same names the generation result records (mlx_int4_dense, mlx_int4), so the Loaded panel no longer shows "GGUF" for a dense-converted transformer. Test: test_status_reports_the_engaged_mlx_quantization.

gpu_ordinal: Optional[int] = None,
**_ignored: Any,
) -> dict[str, Any]:
hf_token = hf_token.strip() if hf_token and hf_token.strip() else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve the anonymous Hugging Face token sentinel

On a managed-account request without a user token, the route deliberately passes False so Hugging Face will not borrow the installation owner's cached credential, but this normalization converts that sentinel to None. Subsequent GGUF, card-metadata, and companion downloads may therefore authenticate with the owner's ambient token, allowing an MLX load to access assets the requesting account did not authorize; strip only string tokens and preserve False unchanged.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b8f28f6. You are right: huggingface_hub's get_token_to_send sends no token for False and falls back to the cached login for None. begin_load now strips only string tokens and passes False through unchanged, so the GGUF fetch, the base snapshot and the card lookup all stay anonymous for a managed account. Test: test_the_anonymous_token_sentinel_reaches_every_fetch.

Comment on lines +707 to +710
except Exception as exc: # noqa: BLE001 -- surfaced via load_progress
if self._load_token != _load_token or _cancel_event.is_set():
return
logger.error("mlx_diffusion.load_failed: %s", exc, exc_info = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Free MLX allocations after a failed model build

If runtime.build() or cache_text_encodings() fails after allocating MLX arrays—most importantly on an OOM—this handler records the error but never calls runtime.free(). No state is published, and unload() only frees the runtime when had_model is true, so MLX's cache and any partially materialized allocations can remain resident and make every retry or subsequent GPU handoff fail until the process exits. Drop partial model references and clear the runtime cache on this failure path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b8f28f6. If build() or cache_text_encodings() raises, the handler now clears the exception frame locals, drops the partial model references and calls runtime.free() (gc plus mx.clear_cache()) before the worker exits. Test: test_a_failed_build_frees_the_runtime[build|cache_text_encodings].

self._gen = _MlxGen(total_steps = steps * batch)
try:
runtime = self._rt()
cfg = float(guidance or 0.0) if runtime.supports_guidance(state.model) else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Translate Z-Image base guidance to mflux semantics

For the undistilled z-image config, the shared recipe supplies guidance 3.0 specifically because the diffusers implementation uses pos + g * (pos - neg) (diffusion_families.py:1391-1392), while mflux uses the standard CFG form where the equivalent value is 4.0. Forwarding the diffusers value unchanged makes every default MLX base render one guidance point weaker and prevents the same saved recipe from reproducing across engines; convert the value for the guidance-capable mflux config or expose an engine-specific default.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not a bug for the mflux version we pin (mflux==0.22.0). Its Z-Image denoiser already uses the same form as diffusers: mflux/models/z_image/variants/z_image.py returns noise + guidance * (noise - negative_noise), which is the same form as diffusers' ZImagePipeline (pos + guidance_scale * (pos - neg)). So the recipe's 3.0 means the same thing on both engines, and converting it to 4.0 would make MLX renders one point stronger than diffusers. No change.

seeds_out = []
per_image: list[dict[str, float]] = []
for index in range(batch):
image_seed = base_seed + index

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Mask derived MLX batch seeds to the JSON-safe range

When a caller requests batch_size > 1 with a seed near 2**53 - 1, later images use base_seed + index without the JSON-safe mask applied by the shared resolve_batch_jobs path. For example, seed 2**53 - 1 with a two-image batch returns 2**53 for the second image, which JavaScript rounds and the gallery cannot replay exactly despite the request contract promising reproducible JSON-safe seeds. Wrap each derived seed with the same 2**53 - 1 mask used by the other engine.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in b8f28f6. Derived batch seeds are now (base_seed + index) & SEED_MASK, using the shared SEED_MASK from diffusion_batched, so seed 2**53 - 1 with two images gives [2**53 - 1, 0], the same as the diffusers path. Test: test_derived_batch_seeds_stay_json_safe.

…LX quant in status

Start the load worker inside the same lock that publishes it, recheck
cancellation before the build, free the runtime when a build fails,
keep hf_token=False for managed accounts, report the MLX quantization
in /images/status, and mask derived batch seeds to 2**53 - 1.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: b8f28f6cb7

ℹ️ 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 on lines +1000 to +1002
self._loading = None
worker = self._load_thread
self._load_thread = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep unload exclusive until the old load worker exits

When /images/unload races with a new /images/load, clearing _loading and _load_thread before releasing this lock lets begin_load() immediately register and start another worker while unload() is still joining the superseded one. If the old worker is inside the non-interruptible build, both multi-GB builds can overlap; afterward either the old worker or unload() can also call runtime.free() against the singleton runtime while the new build is active, risking an OOM or invalidating its MLX allocations. Preserve an unloading/loading marker or otherwise prevent a new load from starting until the worker join and final free have completed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in f3d9c3e. unload() now holds an _unloading counter from its critical section until the generation barrier, the worker join and the final runtime.free() have finished, and begin_load() refuses with "A diffusion unload is in progress." (409 on /images/load) while it is set, so a new build can no longer start beside the superseded one. Test: test_a_load_racing_unload_waits_until_the_superseded_build_is_gone in tests/test_mlx_diffusion_backend.py.

Comment on lines +593 to +596
if not explicit_base:
# The repo's base_model card tag can name the undistilled base: resolve it the way the
# diffusers loader and the delegated download plan do, before picking the mflux config.
base = resolve_variant_base(repo_id, fam, hf_token, gguf_filename, fallback = base)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep variant resolution cache-only for automatic loads

When an automatic load passes local_files_only=True with no explicit base_repo, this unconditional resolver still calls _resolve_base_repo, whose _hf_base_model performs HfApi.model_info. The load can therefore contact the Hub despite the route's cache-only contract; if that lookup fails offline for a repo whose card tag is the only indication that it is undistilled Z-Image, the resolver falls back to the Turbo companion and model config and silently produces results with the wrong variant. Thread local_files_only into variant resolution and use cached metadata or the previously recorded companion mapping instead of making a network lookup.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in f3d9c3e. resolve_variant_base now takes local_files_only, and _run_load passes it through. A cache-only load no longer calls _resolve_base_repo and so never reaches HfApi.model_info. It uses the base an earlier online load recorded for this repo in the companion links, when that base is one of the family's known bases. Otherwise it falls back to the name match, then the family default. Test: test_a_cache_only_load_resolves_the_variant_without_the_hub in tests/test_mlx_diffusion_backend.py.

Comment on lines +202 to +207
def _mlx_runtime_refusal() -> Optional[str]:
"""find_spec only: never import mlx / mflux here."""
missing = [name for name in ("mlx", "mflux") if importlib.util.find_spec(name) is None]
if missing:
return f"{' and '.join(missing)} not installed"
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject incompatible installed MLX runtime versions

On a Mac with any importable mlx and mflux packages, this check enables the engine without verifying the versions or the lightweight runtime dependencies that the installer explicitly validates. In particular, a best-effort upgrade from an older mflux can fail while leaving that old distribution present; selection then proceeds even though the converter labels its files as mflux 0.22.0 and the backend calls the pinned 0.22 APIs, so the load can fail only after switching engines and evicting the resident model or can interpret the converted checkpoint with incompatible semantics. Use distribution metadata here to enforce the supported mflux/MLX ranges and required dependencies before selecting this engine.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in f3d9c3e. _mlx_runtime_refusal still uses find_spec for presence. It now also reads distribution metadata via importlib.metadata.version, without importing mlx or mflux. It requires mflux==MFLUX_VERSION (0.22.0), mflux 0.22.0's own darwin range mlx>=0.32.0,<0.33.0, and the piexif / platformdirs / toml ranges the installer puts down beside the --no-deps mflux install. A mismatch falls back to the current engine with the reason in mlx_fallback_reason. Tests: test_an_incompatible_installed_runtime_falls_back and test_runtime_requirements_match_the_installer (keeps the router in step with _MLX_DIFFUSION_PINS / _MLX_DIFFUSION_DEPS) in tests/test_diffusion_mlx_engine_router.py.

…variant from cache on cache-only loads, check installed mflux and mlx versions
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: f3d9c3eb88

ℹ️ 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".

# The attention / FFN branches overflow float16 before their post-norm.
fp16_guard = "rescale_post_norm",
mlx_model_config = "z-image-turbo",
mlx_model_config_by_base = (("tongyi-mai/z-image", "z-image"),),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Recognize undistilled Z-Image without Hub metadata

Fresh evidence after the variant-resolver fix is that local or cache-only undistilled picks still cannot reach this mapping when no companion link was previously recorded. Both _resolve_base_repo and _cached_variant_base fall back to named_variant_base, but this family declares no named_variant_bases; therefore a local Z-Image GGUF or a manually/previously cached undistilled repo resolves to the Turbo fallback, fetches Turbo companions, and builds with z-image-turbo instead of the intended z-image configuration. Add unambiguous offline/local recognition for the undistilled variant before applying the Turbo fallback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed: with no card and no recorded link, a local z-image-Q4_0.gguf or a cache-only unsloth/Z-Image-GGUF pick fell through to the Turbo default and built with z-image-turbo. Fixed in e570a73 and d46b836 inside the MLX resolver only. When neither a card tag nor a recorded link decides, a Z-Image name with no Turbo token now resolves to Tongyi-MAI/Z-Image and the z-image config. A Turbo spelling in either the repo or the file name keeps Turbo, so z-image-turbo-* and any file in a *-Turbo-* repo stay Turbo, and a name with no Z-Image token keeps the Turbo default. A recorded family default also no longer overrules an undistilled name, because an earlier offline load can record that default as a fallback. named_variant_bases is unchanged, so the diffusers and sd.cpp routes resolve exactly as before. The tests cover the real unsloth/Z-Image-GGUF and unsloth/Z-Image-Turbo-GGUF file names, a local directory, and an end-to-end cache-only load.

…ocal and cache-only loads

A Z-Image name without a Turbo token now resolves to Tongyi-MAI/Z-Image and the z-image mflux config when no card or recorded link decides, and a recorded family default no longer overrules that name. Turbo names and names without a Z-Image token keep the Turbo default. Only the MLX resolver reads this, so the diffusers and sd.cpp routes are unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: d46b8362de

ℹ️ 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".

bits,
timings,
)
except Exception as exc: # noqa: BLE001 -- surfaced via load_progress

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Restore prior account ownership after a failed replacement

When a managed-account replacement fails during fetch or conversion, the previous model is still present in _state, but acquire_for_request() and note_resident_components() have already reassigned its ownership and metadata to the requester. This exception path only records the error, so the requester can see or control the previous account's model while its actual owner sees it as foreign; when _state remains populated, restore the prior GPU owner and resident metadata as the other diffusion backends do.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ace4a08. When the MLX load fails and the previous model is still resident, the worker now calls restore_owner_account(DIFFUSION) and restore_resident_metadata("diffusion"), the same as the diffusers and sd.cpp backends. A failure after the old model was already dropped for the build leaves nothing to hand back, so that case is unchanged. Test: test_a_failed_replacement_hands_the_resident_model_back_to_its_owner.

Comment on lines +261 to +263
def _cached(*, prompt, negative_prompt, guidance):
cfg = float(guidance or 0.0) > 1.0
key = (prompt, negative_prompt if cfg else None, cfg)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Distinguish negative prompts at low nonzero guidance

For the undistilled Z-Image config, guidance uses pos + g * (pos - neg) as documented in diffusion_families.py, so a negative prompt affects output for every g > 0, including guidance=1. Classifying CFG only when guidance exceeds 1 collapses all such negative prompts onto the same cache key; a later render with the same positive prompt and a different negative prompt can therefore reuse stale embeddings and produce the wrong image. Use a nonzero-guidance predicate here and for the returned negative-prompt provenance.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not a bug for this engine. The pos + g * (pos - neg) formula is the diffusers convention. mflux 0.22.0 does something else: ZImage._encode_prompts returns (text_encodings, None) when guidance <= 1.0 (mflux/models/z_image/variants/z_image.py:187), and _predict returns the conditional prediction unchanged when negative_encodings is None (line 238). The mflux CLI says the same thing ("CFG is disabled at guidance <= 1.0"). So at guidance in (0, 1] the negative prompt is never encoded or used, two renders that differ only in the negative prompt give the same image, and sharing one cache entry is correct. The > 1.0 predicate matches mflux exactly, and so does the reported negative prompt.

Comment on lines +796 to +798
with self._lock:
if self._load_token == _load_token and self._loading is not None:
self._loading.error = redact_native_paths(str(exc))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep failed loads busy until runtime cleanup completes

On a build() or cache_text_encodings() failure, publishing _loading.error makes begin_load() accept a retry immediately, but the worker does not call runtime.free() until the following finally block. A cached retry can consequently begin a new MLX build while the failed worker is still running gc.collect() and mx.clear_cache(), allowing the old cleanup to invalidate allocations used by the retry. Finish the runtime cleanup before exposing the terminal error, or otherwise keep the worker marked in progress until cleanup ends.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Leaving this as is. runtime.free() is gc.collect() followed by mx.clear_cache(). gc.collect() only frees unreachable objects, and mx.clear_cache() only returns buffers already freed into MLX's allocator cache. Neither one can release arrays that a retry's build is still holding, so a retry that overlaps the old worker's cleanup does not lose memory it is using. Also, a retry has to make a new HTTP request and then go through fetch and the conversion check before it builds anything, while the finally block runs right after the error is published.

Comment on lines +46597 to 46599
elif fam is not None and pending_name in (ENGINE_SD_CPP, ENGINE_MLX):
# The opt-in MLX engine shares the native contract: one GGUF, no dense-quant knobs.
_refuse_native_component_files(request)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject MLX LoRAs before planning or engine activation

When MLX is predicted and the request contains LoRAs, neither the download-plan branch nor this pre-activation gate rejects them, even though MlxDiffusionBackend.begin_load() always does. The delegated diffusers plan can therefore stage dense transformer shards because it interprets the LoRA as requiring a dense build, and the load path can then switch engines and evict the resident chat or diffusion model before returning the guaranteed LoRA error. Apply the MLX LoRA refusal in both route preflights before planning, selection, or GPU acquisition.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ace4a08. The download plan now returns a 400 for LoRAs when MLX is predicted, before it plans anything. The load route does the same when MLX is predicted, before engine selection and before the GPU arbiter. When the prediction missed, it also refuses right after activation if the engine turns out to be MLX, before acquire_for. Tests: test_the_download_plan_refuses_mlx_loras_before_planning, test_the_load_route_refuses_mlx_loras_before_activation_or_eviction.

Comment on lines +685 to +689
base_dir = fetch_base_snapshot(
base,
hf_token,
local_files_only = local_files_only,
cancel_event = _cancel_event,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fetch companions from the repo staged by the MLX plan

For the normal Z-Image-Turbo load with no explicit base, the delegated diffusers plan applies prefer_ungated_mirror and stages companions from unsloth/Z-Image-Turbo when the upstream snapshot is not already complete, but the worker passes the canonical Tongyi-MAI/Z-Image-Turbo id here. A fresh interactive load consequently downloads the multi-GB companions a second time under another cache key, while a cache-only automatic load fails despite the plan having declared and staged every required file. Resolve the same fetch repo used by the planner before calling fetch_base_snapshot().

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ace4a08. fetch_base_snapshot now picks the fetch repo with prefer_ungated_mirror(base, token, files=<the companion files>), the same helper the delegated plan uses, so the default Z-Image-Turbo load reads unsloth/Z-Image-Turbo unless the upstream already has those files cached. It lists and downloads from that repo. The base shown in status is still the upstream id. Cache-only loads try the mirror choice first and then the upstream. Test: test_base_companions_come_from_the_repo_the_plan_staged.

Comment on lines +368 to +374
if local_files_only:
return snapshot_download(
base_repo,
allow_patterns = list(BASE_ALLOW_PATTERNS),
token = hf_token,
local_files_only = True,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve cache-only companions from the active cache root

In a cache-only load after Studio's cache-folder setting changes during the process lifetime, this unpinned snapshot_download() searches Hugging Face's import-time default cache rather than the active root where the delegated plan staged the files. The same companions can therefore be fully present in the configured cache while an automatic MLX load raises LocalEntryNotFoundError; pass hub_cache_dir() or use the same cross-root per-file resolution as the online branch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ace4a08. The cache-only snapshot_download now passes cache_dir and tries the live Studio root (active_hf_hub_cache()) first, then huggingface_hub's import-time HF_HUB_CACHE. Without that, snapshot_download falls back to constants.HF_HUB_CACHE when cache_dir is None. The online path already reuses either root per file. Test: test_cache_only_companions_read_the_mirror_and_the_live_cache_root.

Comment on lines +530 to +534
return (
cache_root()
/ "mlx_diffusion"
/ f"{_safe(repo_id)}@{_safe(revision or 'local')}"
/ f"{_safe(stem)}-d{int(dense_bits)}-{_safe(scale_dtype)}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Purge converted checkpoints when deleting their source model

Each first MLX load writes another multi-GB transformer under cache_root()/mlx_diffusion, but the model-deletion and cache-inventory paths have no hook for this namespace and only reclaim the Hugging Face source snapshot. Deleting a GGUF variant therefore leaves its now-unusable converted copy on disk indefinitely, and loading multiple variants or revisions accumulates further orphaned copies; tie this cache directory to variant/repository deletion or expose it through the cache cleanup inventory.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed that the converted copy is not reclaimed when its source GGUF is deleted. I'm not changing it in this PR, though. Neither the model deletion path nor the cache inventory has a hook for mlx_diffusion/ today, and adding one touches both of those modules, which goes beyond this opt-in engine change. The converted copy is keyed by repo, revision and GGUF file, so reloading the same variant reuses it rather than adding another copy. I'll handle cleanup in a follow-up.

…before activation, fetch companions from the staged repo and live cache root
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 16f629a6a5

ℹ️ 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 on lines +1105 to +1106
worker = self._load_thread
self._load_thread = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Make concurrent unloads wait for the active teardown

Fresh evidence after the _unloading counter fix is that the first unload clears _load_thread before joining it, so a concurrent second unload observes no worker and returns immediately while the first is still waiting for a non-interruptible build. The second /images/unload then sees no loading repos or resident state and can release the GPU, allowing another modality or engine to allocate beside the old MLX build. Keep the worker/teardown visible to all unload callers or make later unloads wait for the active teardown.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 6821885. unload() no longer clears _load_thread before the join; it is cleared only after the worker has been joined. The join and the runtime free now run under a new _teardown_lock, and the free is driven by a shared _free_pending flag, so whichever unload gets the lock does the join and free and any other unload returns only after that finishes. Covered by test_a_concurrent_unload_waits_for_the_active_teardown, which fails on 16f629a.

Comment on lines +841 to +845
def preflight_base_access(
self, repo_id: str, fam: Optional[DiffusionFamily], **kwargs: Any
) -> None:
from core.inference.diffusion import get_diffusion_backend
get_diffusion_backend().preflight_base_access(repo_id, fam, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep MLX preflight offline for automatic loads

Fresh evidence after making the worker's variant resolution cache-only is that this delegated preflight still reaches the Hub on every automatic MLX load: the route passes allow_network=False, but the diffusers implementation unconditionally calls _resolve_base_repo() and _assert_base_repo_accessible() before using that flag only for the speech probe. Because MLX forces needs_gpu=True, the preflight runs even without an engine switch, violating the automatic-load cache-only contract and leaking outbound metadata requests; use the cached MLX resolver and skip remote accessibility probes when networking is disallowed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not changing this one. The MLX preflight passes everything through to DiffusionBackend.preflight_base_access unchanged, so an automatic MLX load makes the same metadata calls as an automatic diffusers load. On the same Mac the route already sets needs_gpu for diffusers, because the device resolves to mps, so the preflight ran with network there before this PR. Its docstring says this is the one deliberate network step before eviction and that it fails open when offline. In that shared preflight only the speech probe follows allow_network, and the sd.cpp preflight ignores the flag entirely. Making the shared preflight cache-only on automatic loads would be a change to diffusers behaviour too, so it belongs in its own PR, not the MLX engine.

Comment on lines +653 to +654
if mlx_selection(fam, model_kind = model_kind, gguf_filename = gguf_filename)[0]:
return ENGINE_MLX

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Pass the GGUF name when selecting auto-switch planners

When MLX and sd.cpp are both eligible on a Mac, media_locality.planners_for() still calls predict_engine(fam, model_kind=kind) without the pick's GGUF filename. This new MLX gate therefore rejects the prediction as an unknown quant and falls through to sd.cpp, so the automatic cache-only switch verifies sd.cpp's ComfyUI companion assets even though /images/load later supplies the filename and selects MLX, which needs the diffusers base snapshot instead. A cache containing only the sd.cpp assets can consequently pass locality and then fail the MLX load, while a complete MLX cache can be refused; pass pick.gguf_filename into that prediction.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 6821885. media_locality.planners_for() now passes pick.gguf_filename to predict_engine, so the auto-switch locality check plans for the same engine that /images/load selects. Covered by test_auto_switch_planner_judges_mlx_with_the_picks_gguf, which fails on 16f629a (it predicted diffusers there).

Comment on lines +421 to +423
if snapshot_dir is None:
snapshot_dir = str(Path(path).parents[len(Path(filename).parts) - 1])
return snapshot_dir

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Assemble base components under one cache root

Fresh evidence after the cache-root fix is that the online path resolves every companion file independently with reuse_other_cache_root=True but returns the snapshot containing only the first file. If Studio's cache setting changed and the required text-encoder, tokenizer, and VAE files are split between the active and import-time roots, later downloads can return paths from different snapshots while model_path points at just the first one; _link_base_components() may find its three directories yet mflux then fails on missing configs or shards. This is reachable when /images/load is called directly or the download plan fails and the UI falls back to inline loading, so pin all files to one root or assemble a unified local directory.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 6821885. The online path in fetch_base_snapshot no longer resolves each file with reuse_other_cache_root. It picks one cache root for the whole file list: the active root, or the import-time root only when that root already holds every wanted file at the listed revision and the active root does not. Every file is then downloaded with that cache_dir, so all of them land in the same snapshot directory. Covered by test_online_companions_land_under_one_cache_root, which fails on 16f629a.

…e, keep base companions under one cache root

A second unload now waits for the worker join and runtime free that an earlier
unload is still running. The auto-switch locality planner passes the pick's GGUF
filename to predict_engine so it selects the MLX engine the load will use. The
online base snapshot fetch picks one cache root for every companion file so the
text encoder, tokenizer and VAE share a snapshot directory.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 6821885fb4

ℹ️ 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".

from core.inference.diffusion import get_diffusion_backend

kwargs.setdefault("memory_verdict", False)
return get_diffusion_backend().download_plan(repo_id, **kwargs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Prevent MLX plans from substituting Comfy encoders

When the MLX pick is a local GGUF beside a compatible ComfyUI text encoder, this delegated planner calls DiffusionBackend._comfy_text_encoders() and marks the base text_encoder component as replaced, so the returned plan omits the base encoder shards. The MLX loader ignores that discovered override and unconditionally loads base_dir/text_encoder, causing an automatic cache-only load to fail despite its locality plan passing (or an interactive load to fetch several GB outside the plan). Disable automatic component substitution for the MLX plan or make the loader consume the planned override.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 12, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, this was real: the delegated plan could pick a single-file text encoder beside a local GGUF and drop the base text_encoder shards, while the MLX loader always opens the base repo's text_encoder/. Fixed in 614af39. DiffusionBackend.download_plan takes a new discover_text_encoders keyword (default True, so the diffusers plan is unchanged), and MlxDiffusionBackend.download_plan passes False and drops any explicit text_encoder_files / vae_file, since the MLX loader never opens those. The MLX plan now keeps the base encoder. Added test_the_mlx_plan_keeps_the_base_encoder_it_always_opens, which fails before the change and passes after.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

The MLX loader always opens the base repo's text_encoder and vae, so its
plan no longer swaps in a single-file text encoder found beside a local
GGUF, and ignores explicit component files it would not load.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 614af39519

ℹ️ 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 on lines +465 to +468
return _resolve_base_repo(repo_id, None, fam, hf_token, gguf_filename)
except Exception as exc: # noqa: BLE001 -- a metadata failure keeps the family default
logger.debug("mlx_diffusion.base_resolve_failed: %s", exc)
return fallback

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Fall back to the named MLX variant after metadata failures

When an interactive load uses an unambiguously undistilled remote pick such as unsloth/Z-Image-GGUF, a transient Hub metadata failure makes _resolve_base_repo() return the family default, and this exception fallback preserves that Turbo base instead of consulting _named_mlx_base. Because local_files_only=False is used for user-initiated loads even when all files are cached, the worker can then build the undistilled GGUF with z-image-turbo and Turbo companions, silently changing guidance and negative-prompt behavior. Fresh evidence beyond the earlier local/cache-only fix is that this online branch still ignores the name whenever the metadata request fails.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in a441e37. _hf_base_model swallows Hub errors and returns None, and Z-Image has no named_variant_bases, so a failed card read on unsloth/Z-Image-GGUF did resolve to the Turbo default. resolve_variant_base now passes the _named_mlx_base match as the base when the card yields no tag, and returns it from the exception path too. A trusted card tag still wins. Tests: test_an_online_undistilled_pick_without_a_card_tag_keeps_the_named_variant, test_a_resolver_error_keeps_the_named_variant.

from utils.hf_cache_settings import active_hf_hub_cache

missing: Optional[Exception] = None
for repo in dict.fromkeys((prefer_ungated_mirror(base_repo, hf_token), base_repo)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Select cache-only mirrors using the required companion files

For an automatic cache-only load, this call omits files, so prefer_ungated_mirror() keeps the upstream repo whenever it contains any cached weight, even if its text encoder/VAE snapshot is incomplete. The delegated download plan makes the same decision using the complete companion file list and may therefore have staged all required files under the mirror; because both tuple entries then collapse to the upstream ID, the loader never checks that mirror and fails offline despite the successful locality plan. Resolve the fetch repo using the required companion filenames, or try both the upstream and its configured mirror independently.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in a441e37. The cache-only branch now tries the preferred repo, the upstream, and the configured mirror (unless UNSLOTH_DIFFUSION_NO_MIRROR is set), and only accepts a snapshot that holds text_encoder, tokenizer and vae with a weight file, plus every shard a safetensors index names. A partial upstream snapshot no longer hides a complete staged mirror. Test: test_cache_only_companions_skip_an_incomplete_upstream_for_the_staged_mirror.

Comment on lines +431 to +434
if bits_count[4] or bits_count[8]:
level = "8" if bits_count[8] > bits_count[4] else "4"
else:
level = "None"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject mixed bit widths in one mflux checkpoint

When the source contains both 4-bit and 8-bit tensors, this chooses one global quantization_level by tensor majority even though the emitted weights retain their individual packing widths. mflux uses that single metadata value to construct the quantized transformer, so layers packed at the other width have incompatible weight shapes or are interpreted with the wrong number of bits. This is reachable without a malformed file: on a low-memory Mac, a Q8_0 source combined with the default dense_bits=4 produces exactly such a mixed checkpoint. Either normalize every quantized output to one width or refuse the combination before publishing the conversion.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not a bug for the pinned runtime (mflux==0.22.0, enforced at install and by the runtime check). mflux 0.22.0 does not structure the transformer from the single metadata value alone: on a pre-quantized load WeightApplier._quantize uses _stored_layer_predicate, which reads each layer's bits and group size from the stored shapes (packed weight width * 32 / input dims, input dims / scales width) and only falls back to the global level if the shapes do not resolve. The global quantization_level picks the pre-quantized path and is the fallback width. Real Z-Image GGUFs do mix: the Q8_0 files hold 180 Q8_0 tensors plus 28 BF16 2D weights, so on a low-RAM Mac (dense_bits=4) the converter emits 8-bit and 4-bit layers, both at group size 32. Each of those resolves to valid per-layer {bits, group_size}, so the checkpoint loads as saved.

…complete cached companion snapshots, trying the mirror too
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: a441e37555

ℹ️ 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 on lines +1165 to +1166
self._load_token += 1
self._loading = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep cancelled load repositories visible until teardown finishes

When an unload cancels an in-flight MLX load, clearing _loading here immediately makes both loading_repo_ids() and the cache-deletion guard report that no repository is in use, even though unload() can still be blocked joining a worker that is converting the GGUF or reading companion shards during runtime.build(). A concurrent model deletion or whole-cache clear can therefore remove those files underneath the worker; the other diffusion backend handles this interval through draining_repo_ids(). Preserve the cancelled load's repository IDs until the worker join completes, or expose an equivalent draining-repository method.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 73fa03d. unload() now records the cancelled load's repo and base repo before it clears _loading, and drops them only after the worker is joined. They are exposed through a new draining_repo_ids(), which is what _diffusion_blocks_delete and any_model_load_blocks_cache_clear already consult for the diffusers engine, so a delete or a cache clear during that window is refused with the "still releasing" message. loading_repo_ids() keeps its "load in flight" meaning. Test: test_a_cancelled_load_keeps_its_repos_draining_until_the_worker_is_joined, which fails on a441e37.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 73fa03d1a5

ℹ️ 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 on lines +900 to +902
return get_diffusion_backend().download_plan(
repo_id, discover_text_encoders = False, **kwargs
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Resolve the MLX variant before delegating the plan

For an automatic undistilled Z-Image pick, model_path is a local cached directory, but this delegates to the diffusers planner, whose _resolve_base_repo() cannot infer the undistilled variant because this family has no named_variant_bases; it therefore plans the Turbo companions. The MLX worker separately recognizes the filename via _named_mlx_base() and requests Tongyi-MAI/Z-Image, so locality can reject a complete undistilled cache or, if Turbo is cached, approve the switch and then let the cache-only load fail after activation. Resolve the base with the same MLX variant logic and pass that base into the delegated plan.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. When no base_repo is given, download_plan now resolves the base with the same resolve_variant_base the MLX worker uses (named variant for a local pick, card tag online, recorded base cache-only) and passes it to the delegated planner, so a local undistilled Z-Image pick is planned against Tongyi-MAI/Z-Image instead of the Turbo default. An explicit base_repo is still passed through unchanged. Test: test_the_mlx_plan_names_the_base_the_load_will_read.

Comment on lines +360 to +363
if not all((root / sub).is_dir() for sub in _LINKED_SUBDIRS):
return False
if not any((root / "tokenizer").iterdir()):
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require component configs before accepting an offline snapshot

When a cache-only load finds a partial upstream snapshot before the complete staged mirror, this check accepts any tokenizer file plus complete weight shards without requiring the text_encoder/config.json, vae/config.json, or usable tokenizer metadata that mflux needs to construct those components. An interrupted snapshot containing the weights and tokenizer.json but missing either component config therefore wins over the later complete mirror and fails during runtime.build(). Include the required configuration and tokenizer assets in the completeness predicate before returning a cached snapshot.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Partly fixed. mflux 0.22.0 does not read text_encoder/config.json or vae/config.json for Z-Image: the component layout is fixed in ZImageWeightDefinition and WeightLoader only resolves *.safetensors. The tokenizer is different: it loads through AutoTokenizer.from_pretrained(..., local_files_only=True), which needs tokenizer_config.json. The completeness check now requires tokenizer/tokenizer.json and tokenizer/tokenizer_config.json (both shipped by the upstream Turbo, the mirror and the undistilled base) instead of any file in tokenizer/, so a snapshot missing them falls through to the next candidate. Test: test_cache_only_companions_skip_a_snapshot_without_tokenizer_config.

Comment on lines +923 to +928
def loading_repo_ids(self) -> tuple[str, ...]:
with self._lock:
loading = self._loading
if loading is None or loading.error is not None:
return ()
return tuple(dict.fromkeys((loading.repo_id, loading.base_repo)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Track the fetched mirror in load repository guards

For the normal Turbo load, fetch_base_snapshot() can read companions from unsloth/Z-Image-Turbo, while _loading.base_repo remains the canonical Tongyi-MAI/Z-Image-Turbo; this method consequently exposes neither the actual mirror nor its cache path. A targeted deletion of the mirror is therefore allowed while the worker is downloading it or while runtime.build() is reading its linked components, and the same omission is copied into draining_repo_ids() when the load is cancelled. Record the resolved fetch repository in the loading state and include it in both loading and draining repository guards.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. The loading state now records the companion mirror for the resolved base (none under UNSLOTH_DIFFUSION_NO_MIRROR or for a local base), and both loading_repo_ids() and draining_repo_ids() include it, matching what the diffusers backend reports through its fetch_repo. Deleting unsloth/Z-Image-Turbo is refused while a Turbo load is running and while a cancelled one is still unwinding. Test: test_a_cancelled_load_keeps_the_companion_mirror_guarded.

"""The diffusers GGUF plan stages exactly the files this engine opens; its memory verdict does not apply."""
from core.inference.diffusion import get_diffusion_backend

kwargs.setdefault("memory_verdict", False)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Force off the diffusers memory verdict for MLX plans

The normal /images/download-plan route explicitly passes memory_verdict=True when training is idle, so setdefault() preserves that value despite this method's statement that the diffusers verdict does not apply. The delegated planner can then mark a low-memory Mac incompatible using the dense diffusers/text-encoder footprint even though the MLX loader quantizes those components according to RAM; the Images page treats that incompatible_reason as a hard refusal and never starts a load that MLX could run. Assign False unconditionally before delegating.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. The download-plan route passes memory_verdict = not training, so setdefault kept True and the diffusers footprint check could mark a pick incompatible that MLX would load quantized. download_plan now sets memory_verdict = False unconditionally. Test: test_the_mlx_plan_forces_off_the_memory_verdict.

…n off the diffusers memory verdict, guard the companion mirror, and require tokenizer files in a cached snapshot
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 6f5b8257a0

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 10bddef into main Oct 12, 2026
@danielhanchen
danielhanchen deleted the studio-mlx-engine branch October 12, 2026 11:48
danielhanchen added a commit that referenced this pull request Oct 12, 2026
#13379 added a subprocess.run(text=True) with no encoding in _chip_name, which test_text_io_encoding flags on main (it would fall back to the locale codec under a C/POSIX locale). Pass encoding='utf-8', errors='replace' like the other inference subprocess calls, and apply the formatter hook to the file.
danielhanchen added a commit that referenced this pull request Oct 12, 2026
…3445)

test_return_logits_survives_for_training lifts for_training into a stub namespace that predates #13374's switch_training_mode, so the missing name came back as None. Stub it and the three-argument resolve, and make that namespace raise NameError on any unstubbed name.
test_windows_torch_flavor_invariant: count #13396's causal-conv1d + mamba-ssm slot in the torch totals and its call in step 13.
test_token_count_prompt_parity: stub #13372's browser agent store with its defaults; the count and the request both call browserAgentToolsForTurn.
test_diffusion_mlx_engine_router (from #13379): read install_python_stack.py as UTF-8 for test_source_read_encoding.
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