Repository navigation
Description
Part of #2348
Problem / Background
Z-Image (Tongyi-MAI, Z-Image-Turbo and Z-Image base) is a 6B single-stream DiT text-to-image model with image-to-image editing. #2341 already ports its DiT blocks as shared code for LLaDA-Image and Ming-Image, but Z-Image itself has no issue and does not load: its Diffusers directory has no top-level model_type, and after #2341 the probe recognizes it as z_image with no registered family. This issue adds the family on top of the #2341 blocks.
Upstream reference
- Model directory: https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/z_image (README). PRs: Add Z-Image generation and conversion support Neywa-Labs/mlx-vlm#1952 (generation, img2img, conversion), Feat/z image num images Neywa-Labs/mlx-vlm#2354 (
num_images), Use model-based sampling defaults for image generation Neywa-Labs/mlx-vlm#2373 (sampling defaults). - Transformer top level:
transformer.py#L193-L372(ZImageTransformer:_patchify/_unpatchify,_build_position_ids,noise_refiner,context_refiner, mainlayers,final_layer), key remapsanitize_transformer_weightsat L374-L392 (all_final_layer.2-1.tofinal_layer.,all_x_embedder.2-1.tox_embedder.,t_embedder.mlp.0/2tolinear1/2). The blocks at L14-L177 are the ones feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 ports. - VAE:
vae.py: the FLUX.2Flux2Encoder/Flux2Decoderbuilt from the FLUX.1AutoencoderKLconfig (16 latent channels,block_out_channels [128, 256, 512, 512], nopost_quant_conv, no batch-norm stats), withsanitize_vae_weightstransposing 4-D convs only for source-layout checkpoints (encoder.conv_in.weightpresent). - Text encoder:
text_encoder.py: the FLUX.2 Qwen3 encoder, returning the penultimate hidden state (hidden_states[-2], pre-norm output of the second-to-last layer); prompt formatted with the chat template andenable_thinking=True, padded to 512, then trimmed to the valid length (pipeline.py#L42-L78). - Sampling:
pipeline.py#L112-L210: static-shift scheduler frommage_flow/scheduler.pywithshiftfromscheduler/scheduler_config.jsonandsteps - 1scheduler steps; transformer time inputt = 1 - sigma; Euler step on-prediction; CFG only when guidance > 1 and only whilet <= cfg_truncation, with the conditional prediction as base (pred + g * (pred - neg)); noise[n, 16, 1, H/8, W/8]f32 frommx.random.key(seed); decodez / scaling_factor + shift_factor. Img2img at L212-L292:start_index = int(max(steps - min(steps * strength, steps), 0)),strengthin (0, 1]. - Variant and defaults:
config.py#L155-L180picks turbo when schedulershift <= 3.0, else base; guidance turbo 0.0, base 4.0. Default steps resolve throughmodel.py#L128-L142: turbo 8, base 50 (the README recommends 9 for turbo; mlxcel follows the code, 8). - Checkpoints:
mlx-community/Z-Image-Turbo-bf16andmlx-community/Z-Image-bf16(Diffusers trees,_class_name: ZImagePipeline, Apache-2.0), identical in layout toTongyi-MAI/Z-Image-TurboandTongyi-MAI/Z-Image.
Current Behavior
- No image generation on
main; feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 addssrc/imagegen/includingdit_blocks.rs(the Z-Image blocks),vae/flux2.rs, the probe (z_imagevsming_imageviamllm/config.json) and the Qwen-ImageFlowMatchEulerDiscrete. src/models/qwen3.rs:678returns only the final-normed hidden state; the penultimate state comes from the shared Qwen3 conditioner feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 owns.
Proposed Solution
New module src/imagegen/z_image/ (config.rs, transformer.rs, vae.rs, pipeline.rs, mod.rs) implementing ImageGenerationModel with supports(Generate) and supports(Edit) true, family id z_image.
- Direct load, no conversion step. Upstream asks users to run
convert.pyfirst, but its load path already sanitizes raw Diffusers weights on the fly (weights.py#L85-L117: transformer key remap, VAE conv transpose when source layout, text encodermodel.prefix strip andlm_headdrop); conversion only casts and optionally quantizes. mlxcel loads the raw tree directly, per the project's direct-checkpoint rule. Also accept an mlx-vlm converted directory: whenvae/model.safetensors.index.jsonmetadata hasmlx_vlm_format: "z_image", skip the VAE transpose; when weights carry.scales, load quantized throughUnifiedLinearwith mode, bits and group size from that metadata (affine, mxfp4 32, mxfp8 32, nvfp4 16; anything else errors, as upstream_apply_weights). transformer.rs: the top-levelZImageTransformercomposed fromimagegen::dit_blocks(do not copy the blocks), plussanitize_transformer_weights.vae.rs: build the feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 FLUX.2 encoder and decoder fromvae/config.json. If feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341'sFlux2Vaehard-codes 32 latent channels, the batch-norm stats orpost_quant_conv, make those config-driven insrc/imagegen/vae/flux2.rshere (latent_channels,block_out_channels,layers_per_block,use_post_quant_conv, optionalbn.*) and update its// Used by:comment to add ZImage. ERNIE-Image and LLaDA-Image behavior must not change.- Text conditioning: the shared Qwen3 conditioner's
hidden_states(...)[num_layers - 1], trimmed to the valid token count. - Scheduler:
FlowMatchEulerDiscrete::static_shift(steps - 1, shift)fromsrc/imagegen/scheduler.rs(contract below). pipeline.rs: generate and edit as upstream, includingcfg_truncationandnegative_prompt(via--negative-promptor--gen-kwargs),strength(default 0.6, edit only, exactly one reference image).- Register
z_imagein the feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341FAMILIEStable and the registry standalone family table.
Scope
In scope: the module above, the VAE generalization if needed, docs (docs/image-generation.md row with turbo 8 steps / guidance 0 and base 50 / 4, docs/supported-models.md).
Out of scope: a conversion or quantization command, ControlNet and LoRA checkpoints, multi-reference editing (upstream accepts exactly one image).
Implementation Notes
- Reuse: feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341
dit_blocks,Flux2Vaeencoder and decoder, probe, PNG output; shared Qwen3 conditioner;UnifiedLinearquantized path. - Shared contracts (owned by feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 per its amendment comment; if feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 merged without them, whichever of this issue and feat: Port Mage-Flow (mage_flow) image generation and editing #2426 (Mage-Flow) lands first adds them at these exact paths):
src/imagegen/qwen3_text_encoder.rsQwen3TextEncoder::load(dir)(top-level Qwen3 config or nestedtext_config, stripsmodel./language_model., dropslm_head.*, MLX affine quantization) andhidden_states(input_ids, attention_mask) -> Vec<MlxArray>(num_layers + 1entries, index 0 the embeddings, indexilayerioutput before the final norm, causal plus padding mask);FlowMatchEulerDiscrete::static_shift(num_steps, shift)withbase = linspace(1, 1/n, n)f32,sigmas = shift * base / (1 + (shift - 1) * base),timesteps = sigmas * 1000, a trailing 0 sigma, andstep(velocity, i, latents) = latents + (sigma[i+1] - sigma[i]) * velocitycomputed in the latent dtype. - Precision: upstream draws noise in f32 and runs the transformer in bf16; apply the feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 precision rule and record the outcome.
- Edge cases:
steps < 2errors (the scheduler runssteps - 1);strengthproducing no denoising step errors with the upstream message;cfg_truncationoutside [0, 1] errors; guidance in [0, 1] disables CFG (turbo has no CFG); dimensions not a multiple of 16 error.
Acceptance Criteria
-
mlxcel generate-image -m models/Z-Image-Turbo-bf16 -p "A red panda serving tea in a moonlit bamboo forest" --size 1024x1024 --seed 42 -o out.pngwrites a PNG with defaults 8 steps and guidance 0, loading the raw Diffusers tree with no conversion. - Seed-fixed parity against mlx-vlm on
mlx-community/Z-Image-Turbo-bf16at 512x512, 8 steps, seed 42: initial noise bit-identical, PNG PSNR at least 30 dB, and final latents within the per-case bound documented in the test, which must reject a wrong port (committed fixture). It fails on current main. Revised during epic epic: image generation runtime and model families #2348: the original final-latents relative RMS below 1e-2 bound is not reachable in bf16. Upstream moves its own latents by 2.7e-2 to 1.0e-1 when a single precision setting changes, so measured rel-RMS is recorded in the PR as drift and does not gate the merge. - Base model:
mlx-community/Z-Image-bf16with--negative-prompt "blurry, low quality" --gen-kwargs '{"cfg_truncation":1.0}'runs 50 steps at guidance 4 and matches upstream under the same thresholds at 512x512. - Img2img:
--task edit --image fox.png --gen-kwargs '{"strength":0.6}'matches upstream;strength0 and 1.5 are rejected. - Unit tests, each failing on current main:
static_shiftsigmas for shift 3.0 and 6.0 at 8 and 49 steps against upstream literals;_img2img_start_indextable; transformer key sanitize on a synthetic raw key set; VAE sanitize is a no-op on anmlx_vlm_format: "z_image"directory. - If the VAE was generalized: the ERNIE-Image or LLaDA-Image VAE parity test from feat: Add image generation runtime: generate-image CLI, /v1/images routes, shared VAE and scheduler #2341 still passes.
-
mlxcel arch --jsonlistsz_image; docs updated.
Verification
cargo build --release --features metal,accelerate
cargo test --workspace --profile test-fast --features metal,accelerate z_image
cargo test --workspace --profile test-fast --features metal,accelerate imagegen
cargo test --workspace --profile test-fast --features metal,accelerate
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --check
./target/release/mlxcel generate-image -m models/Z-Image-Turbo-bf16 -p "A red panda serving tea in a moonlit bamboo forest" --size 1024x1024 --seed 42 -o /tmp/z-image.pngDependencies
Blocked by #2341 (runtime, DiT blocks, FLUX.2 VAE, probe, shared Qwen3 conditioner and static-shift scheduler).
Activity
feat(imagegen): add shared image generation runtime and APIs (#2497)
fix(imagegen): guard the Z-Image bf16 to f16 weight cast
fix(imagegen): validate Z-Image quantized tensors before MLX dequantize
feat(imagegen): port Z-Image text-to-image and img2img (lablup#2662)