Repository navigation
feat(imagegen): port Z-Image text-to-image and img2img - #2662
Conversation
Register the z_image family: a port of mlx-vlm's z_image pipeline on the shared Qwen3 conditioner, DiT blocks, FLUX.2 VAE and static-shift scheduler. It loads the raw Diffusers tree and mlx-vlm converted trees (affine, mxfp4, mxfp8, nvfp4 dequantized at load), with Turbo 8 steps / guidance 0 and base 50 / 4 defaults, cfg_truncation, negative_prompt and strength options. The CUDA build of mlxcel's MLX promotes bf16 with f32 to bf16, which would run upstream's f32 latent stream in bf16. Transformer and VAE weights are stored as f16 (exact for these checkpoints) and the DiT blocks cast to upstream's promotion at rotation, SDPA and residual adds; the caption embedder and the first context-refiner block's pre-attention path keep bf16 as upstream computes them. Shared changes: the VAE quant_conv is optional (FLUX.1 AutoencoderKL with use_quant_conv false), apply_rotary broadcasts a batch-1 table, and a model's InvalidImageRequest maps to 400 on the image server instead of 500. Parity vs upstream CUDA at 512x512 seed 42 (TF32 off): noise bit-identical; final latents rel-RMS 8.6e-2 Turbo, 6.2e-2 base, 1.7e-2 img2img; PSNR 32.9, 34.7, 46.1 dB. The issue's 1e-2 latents bound is below upstream's own rounding sensitivity (2.7e-2 to 1.0e-1), so the tests use documented per-case bounds. Closes #2425
The loader cast every transformer and VAE weight to f16 on the claim that f16 holds these checkpoints exactly. It does not: on Z-Image-Turbo and Z-Image 355/521 transformer and 76/244 VAE tensors change under an f16 round trip (bf16 values below f16's normal range lose low bits), and a different checkpoint could exceed f16's 65504 and turn into infinities with no error. The CUDA promotion claim itself holds (the patched dtype.cpp gives bf16 for bf16 with f32), so f16 storage stays. cast_floats now measures each tensor's f16 round trip and stores it as f32 when the relative RMS error exceeds 1e-5 or the cast overflows, returning the widened keys for a load-time warning. The VAE picks f16 only when every tensor fits, else f32. f32 source tensors are no longer rounded to f16. The published checkpoints measure 2.0e-7 worst case, so their weights and outputs are unchanged. Tests: the f16/bf16 promotion against f32 on this backend, round-trip error for overflow, flush-to-zero and NaN, cast_floats widening and keep keys, the VAE fallback, and quant_conv_is_loaded_and_applied_when_present for the FLUX.2 VAE default path. imagegen:: 168 passed, server::image 12, models::registry 16; Turbo real-checkpoint parity test passes. Refs #2425
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
A valid /v1/images/generations request could abort mlxcel-server. The DiT attention called the raw SDPA FFI with f32 q/k, which MLX CUDA never sends to cuDNN, so the ops fallback materialized the full [B, 30, L, L] f32 score matrix: about 34 GB per layer at 2048x2048 and about 500 GB at the accepted 4096x4096 limit. The VAE mid-block attention (one head, head_dim 512) had the same shape problem at H/8*W/8 tokens. The allocation failure was a C++ exception from a non-try eval, which crosses the cxx boundary and terminates the process; run_guarded only catches Rust panics. The DiT Attention and the VAE AttentionBlock now go through mlxcel_core::layers::attention, which query-chunks the score matrix to MLXCEL_ATTENTION_CHUNK_BUDGET_MB (default 1024) with row-identical math and is the same single SDPA call below the budget. The Z-Image denoise, reference encode, VAE decode and prompt encode use try_eval / try_array_to_raw_bytes with context, so a runtime MLX failure returns a 500. New tests rerun the DiT block and the VAE attention in a child process with a 1 MiB budget (the budget is read once per process) and compare against the default run: max abs diff 0 and 3.6e-7. The ignored Turbo 512x512 parity test with TF32 off gives pooled latents rel-RMS 3.152e-2 and 36.25 dB on the baseline head, with the fix, and with MLXCEL_ATTENTION_CHUNK_BUDGET_MB=64 (chunking every DiT layer); the three PNGs are byte-identical. The OOM itself was argued from the arithmetic, not reproduced.
Security and performance reviewFixed (HIGH), commit ab73204. A request the server accepted as valid could abort Open, not fixed (MEDIUM):
LOW: position ids, RoPE tables, the caption embed and the context refiner are recomputed every forward even though they do not depend on Request bounds and error text check out: cfg_truncation, strength, negative_prompt, num_images and guidance are validated, and request-time errors leak no paths. |
A malformed mlx-vlm converted checkpoint reached MLX `dequantize` with inconsistent metadata or tensors and threw across the FFI boundary. Upstream's `_apply_weights` errors on anything outside its table, so the loader now does the same in Rust. `quant_spec` limits affine to 2, 3, 4, 5, 6 or 8 bits and group size 32, 64 or 128. `dequantize_weights` checks each triple before MLX sees it: uint32 packed weight of at least two dimensions, a packed width that is whole at the bit width and a multiple of the group size, scales shaped `[..., in / group_size]`, float scales and matching biases for affine, uint8 scales and no biases for mxfp4, mxfp8 and nvfp4. Errors name the tensor key. The opt-in Z-Image parity test variables and the chunked-attention test helper variable are allowlisted in the env-var docs check, and docs/image-generation.md states the accepted affine range, the per-tensor checks and the attention chunk budget. Validation: 14 `imagegen::z_image::weights` tests, 173 `imagegen::` tests and 12 `server::image` tests pass on CUDA with `--test-threads=1`; `cargo fmt --check`, clippy with `-D warnings` and `make verify-env-var-docs` are clean. Refs #2425
Z-Image (#2662) landed on main and conflicted with the Bonsai rows in the four files both units edit. The resolution keeps every main row and appends Bonsai after it: `FAMILIES` and `STANDALONE_ARCHITECTURE_FAMILIES` are flux2, z_image, bonsai; docs/image-generation.md lists the three families and gains a `bonsai` row in main's family table; docs/supported-models.md keeps both bullets. The Bonsai bullet in supported-models.md now says the 31.18 dB uses the checkpoint `vae/` on both sides and gives the 29.82 dB against upstream as shipped (which downloads FLUX.2-small-decoder at load), matching the PR body and the Bonsai section. Refs #2428
## Summary Adds the `bonsai` image-generation family for `prism-ml/bonsai-image-ternary-4B-mlx-2bit`: FLUX.2 Klein 4B with ternary transformer linears packed as 2-bit MLX affine weights and a 4-bit Qwen3 text encoder. It runs through `mlxcel generate-image`, `mlxcel-server --image-model` (`/v1/images/generations`) and is listed by `mlxcel arch --json` (`image_generate`, output `image`). Generation only. - **Loader.** `src/imagegen/bonsai/` reads `transformer-packed-mflux/quantization_config.json`. `format` must be `mlx-packed-affine`, and `bits` and `group_size` must be in mlxcel-core's affine sets; a bad value is rejected by name (the 1-bit binary variant fails on `bits (1)`). Listed modules load as affine `UnifiedLinear` (2-bit, group 128, bf16 scales and biases as stored) and everything else loads dense. A listed module without `.scales` fails, and so does an unlisted module with `.scales`. Every packed layer also passes mlxcel-core's `validate_quantized_packing` at load, so mismatched weight/scales/biases shapes fail with an error instead of aborting the server on the first forward pass. - **Pipeline reuse.** `Flux2Pipeline::with_linear_source` injects the Bonsai `LinearSource` and turns off prompt bucketing (upstream `bucketed_seq_len=False`). `LinearSource::check_weights` is a default-accepting hook that `Flux2Transformer::load` calls. FLUX.2 construction is unchanged, and its parity tests reproduce #2660's numbers exactly. - **`n > 1`.** Runs image by image with seed `seed + i`, which is how upstream's server loops for Bonsai. - **Probe.** The manifest rule was already on main from #2341, covered by `bonsai_manifest_beats_the_flux2_class_name` and `partial_bonsai_manifest_falls_back_to_the_class_name`. This PR adds `flux2_klein_index_without_a_manifest_is_flux2` for the no-manifest case, plus the registration in `FAMILIES` and `STANDALONE_ARCHITECTURE_FAMILIES`. **Deviation: the VAE.** Upstream Bonsai ignores the checkpoint's `vae/` and downloads `black-forest-labs/FLUX.2-small-decoder` at load time, which is a different decoder with channels 96/192/384/384. This port uses the checkpoint's own `vae/`, as the issue specifies, and fetches no second repository. The parity fixtures decode with `vae/` in both arms. Measured against upstream as shipped (small decoder), the result is 29.82 dB; the two decoders differ by 34.96 dB from each other. ## Parity (CUDA oracle) Oracle: mlx-vlm 0.7.8 at git 73d366ec, mlx 0.32.4, CUDA on GB10, `MLX_ENABLE_TF32=0`. The case is "A tiny glass bonsai tree on a moonlit desk" at 512x512, 4 steps, seed 9909. `tests/fixtures/bonsai/generate_bonsai_fixtures.py` runs upstream's own `BonsaiImage` pipeline, with the Metal-only fused norm-RoPE kernels replaced by their arithmetic (f32 RMSNorm times the gain, interleaved-pair RoPE, cast to bf16). `--flux2-transformer` loads Bonsai's weights into upstream's FLUX.2 transformer for the f32 check. That check dequantizes the weights, because mlx 0.32.4 CUDA fails f32 2-bit `quantized_matmul` with M > 1. Committed fixtures total 1.45 MB. | Check | Result | | --- | --- | | Initial noise | bit-identical | | f32 transformer vs upstream f32, same inputs | rel RMS 1.19e-6 | | One bf16 step on upstream's exact step-0 inputs | rel RMS 8.1e-3 | | VAE decoding upstream's final latents | 57.61 dB | | End-to-end PNG | 31.18 dB | | Recorded drift: final latents / prompt embeds | 1.0e-1 / 2.3e-2 | Following the orchestrator's revised gate, the tests assert PSNR >= 30 dB, bit-identical noise, a 0.2 latent bound (a wrong port scores about 1.4) and 0.1 on the embeddings. The drift is bf16 rounding, not a port error. Upstream's bf16 4-bit conditioner is 1.95e-2 from its own f32 run, and this port is 1.74e-2 from that f32 run, with the same growth along the 448 padding rows. Upstream also disagrees with itself by 3.5e-2 in the final latents when its FLUX.2 transformer replaces `klein_fast` on the same weights. The megakernel cannot be run against `quantized_matmul` here because it is Metal-only. By code reading, `QuantizedLinearKernel` calls `mx.quantized_matmul`, and the fused kernels compute the arithmetic described above. **Precision.** The transformer is bf16. The VAE and the text encoder follow FLUX.2's policy. Under `MLXCEL_CUDA_F16_NORMALIZE=1` the case gives 31.21 dB. ## Real checkpoint (GB10) | Run | Result | PNG | | --- | --- | --- | | CLI acceptance command | 512x512, 11.5 s wall including load, 3.6 GB RSS, 31.18 dB | A leafy green bonsai in a dark pot with a glass bulb at the trunk, on a wooden desk in blue moonlight with books at the edges. | | Server, same request | 200, pixel-identical to the CLI (PSNR inf) | Same image. | | Server `n=2`, 256x256, seed 5 | seeds 5 and 6, distinct images (10.3 dB apart) | A small bonsai under a desk lamp, in two compositions. | | Server `4096x512`, `520x512`, `max_sequence_length: 0` | 400 with the range, multiple-of-16, or option message | | | CLI `--task edit` | `image model family bonsai does not support task "edit"` | | ## Changes during review - Merged origin/main twice: Z-Image (#2662) conflicted in both registries and both docs pages; every main row was kept and Bonsai appended (`FAMILIES` is now flux2, z_image, bonsai). - Security: packed layers are now shape-validated with `validate_quantized_packing` (three malformed-checkpoint rejection tests added). Open MEDIUM, shared with FLUX.2 and out of scope: a checkpoint whose tensors agree with each other but were packed for a different `hidden_size` than `config.json` still fails on the first forward pass; fixing it needs the expected input width passed through `LinearSource::load`. - Removed the unused `PackedLinears::config()`; pinned the default `LinearSource::check_weights` with a unit test. - `docs/supported-models.md` now gives both the 31.18 dB (`vae/` on both sides) and 29.82 dB (upstream as shipped) figures. ## Test plan - [x] `imagegen::` lib-test filter (220 pass, 15 ignored, includes the bonsai unit tests); `models::registry` passes 16. Removing the `FAMILIES` row fails `bonsai_is_registered_in_both_tables` and `a_bonsai_checkpoint_resolves_to_the_bonsai_loader`. The loader and config tests do not exist on main. - [x] `bonsai::parity --ignored` 5/5 and `flux2::parity --ignored` 6/6 on the real checkpoints, `MLX_ENABLE_TF32=0`. - [x] clippy (`--lib --bins --tests --no-deps -D warnings`), `cargo fmt --check`, and `make verify-env-var-docs` pass. The two test-only variables are allowlisted. - Not verifiable here: Metal runs, and the megakernel against `quantized_matmul`. Closes #2428
Ports mlx-vlm's
z_image(git73d366ec) as the first registered image family: text-to-image and img2img on Z-Image-Turbo and Z-Image, from the raw Diffusers tree or an mlx-vlm conversion (affine, mxfp4, mxfp8, nvfp4 dequantized at load).mlxcel arch --jsonlistsz_image.Closes #2425
Acceptance criterion not met: final latents rel-RMS < 1e-2
Seed-fixed parity at 512x512, seed 42, against upstream on mlx 0.32.4 CUDA (GB10),
MLX_ENABLE_TF32=0on both sides. Initial noise is bit-identical in every case.The 1e-2 bound is below upstream's own reproducibility. Upstream against itself on the Turbo case: caption embedder linear in f32 instead of bf16 moves it 2.7e-2 (41.3 dB); its text encoder attention in bf16 instead of f32 moves it 1.0e-1 (32.1 dB); TF32 on moves it 9.5e-2 (31.6 dB). Attribution of this port's drift: the shared Qwen3 conditioner runs attention in bf16 where upstream casts to f32 (caption features differ 9.3e-3); feeding upstream's caption features to this denoiser drops Turbo to 3.4e-2. I did not change
Qwen3Model(live text model, shared with FLUX.2 and Bonsai, would need a logit-trace regression); that is a follow-up, and FLUX.2 Klein will see the same gap. The ignored real-checkpoint tests compare against the committed 198 KB fixture, which stores 4x4-pooled latents and images (Turbo there: pooled latents 3.15e-2, pooled PSNR 36.25 dB), with documented per-case bounds (1.2e-1, 1.0e-1, 5e-2), the issue's PSNR >= 30 dB, and bit-identical noise. The full-resolution numbers in the table come from the scratch oracle tensors. Recommend revising the criterion.Precision
The CUDA build of mlxcel's MLX promotes bf16 with f32 to bf16, so upstream's f32 latent stream would run in bf16 (2.1e-2 on one forward, 1.1e-1 final). Transformer and VAE weights are stored as f16. The cast is range-safe but not bit-exact here (max magnitude 47.75; subnormal bf16 values lose low bits; worst per-tensor error 2.0e-7 relative RMS), so the loader measures each tensor's f16 round trip and keeps any tensor above 1e-5 (or one that overflows) in f32, and puts the whole VAE in f32 if any VAE tensor fails. The DiT blocks cast to upstream promotion at rotation, SDPA and residual adds (no-op on Metal). The caption embedder and the first context-refiner pre-attention path keep bf16, as upstream computes them.
Shared changes
Flux2Vae:quant_convoptional. ERNIE VAE ignored test: f32 numbers unchanged (3.3e-6 / 1.2e-6 / 3.0e-6); its default-dtype assert fails on CUDA (bf16 default, 9.97e-3 vs bound) identically with main'svae/model.rs, so pre-existing.apply_rotarybroadcasts a batch-1 table.InvalidImageRequest: a model's content error is 400 on the server, not 500.dit_blocks::Attention) and the VAE mid-block attention (vae/layers.rs) callmlxcel_core::layers::attention, which splits the score matrix into query chunks aboveMLXCEL_ATTENTION_CHUNK_BUDGET_MB(default 1 GB) and is the same single SDPA call below it. Forced-chunking tests compare against the unchunked path (max abs diff 0 for the DiT block, 3.6e-7 for the VAE attention); Turbo parity PNGs are byte-identical with chunking forced.scripts/ci/check_env_var_docs.py: one test-only allowlist entry for the Z-Image parity test variables (MLXCEL_Z_IMAGE_TURBO,MLXCEL_Z_IMAGE_BASE,MLXCEL_Z_IMAGE_ORACLE_DIR,MLXCEL_Z_IMAGE_OUT) andMLXCEL_IMAGEGEN_CHUNK_CHILD_OUT.Validation
mlxcel-server -m qwen3-0.6b --image-model z-image-turbo-bf16): generations 200 (10.7 s, 512), edits 200 with a data-URL image and strength 0.6 (5.9 s); strength 0, 1.5, two images and Turbo guidance 4 all 400. Server ran with TF32 default on; its PNGs are 32.4 dB (generation) and 46.6 dB (edit) vs the oracle.z_image_tiny_refs(1.6 KB) andz_image_parity(198 KB, pooled summaries) from the oracle above, scripttests/fixtures/generate_z_image_fixtures.py._img2img_start_indextable, transformer key sanitize, VAE sanitize no-op on converted dirs, quant table, validation, worker 400 mapping) do not compile on main (module and type absent).quant_convpresent/absent, forced attention chunking and quantized tensor validation tests),server::image12,server::routes::images17,models::registry16, CUDA with TF32 off; clippy-D warningsand fmt clean.Upstream's Turbo generation default is 9 steps; this port uses the issue's 8 (upstream's img2img default).
Changes during review
quant_convis loaded and applied when present.[1, 30, L, L]score matrix per layer (about 500 GB) and aborted the server through a C++ exception. Attention is now query-chunked, and the Z-Image denoise, encode, decode and prompt paths usetry_eval/try_array_to_raw_bytesso an MLX failure returns 500 instead of terminating. The OOM itself was not reproduced on GB10 (driver-wedge risk); the case rests on the arithmetic.dequantize(affine bits {2,3,4,5,6,8} and group size {32,64,128}; mxfp4 32, mxfp8 32, nvfp4 16; packed uint32; scale and bias shapes and dtypes), each failure naming the tensor key.Open, reported but not fixed: transformer tensor shapes are not checked against the config at load; one request within the shared limits (1000 steps, n=10, 16M pixels) can hold the worker for a long time; timestep-independent work (position ids, RoPE tables, caption embedding, context refiner) is recomputed each step (about 1 to 2%); the text encoder stays resident rather than being evicted before the denoiser.
server::image_worker::tests::a_full_queue_sheds_loadis a pre-existing timing flake on main.