Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [Unreleased]

### Added

- **FLUX.3 Image Klein** (`flux3`, #3230). `black-forest-labs/flux-3-image-klein` (16-step distilled flow map, guidance 1) and `-klein-base` (50 steps, CFG 3.5) run in `mlxcel generate-image` and on `/v1/images/generations` and `/v1/images/edits`: text-to-image, editing with 1 to 10 reference images, and layout boxes appended to the prompt. The transformer is new (three early streams, a joint single stream, a flow-map target-time embedding); it reuses FLUX.2's RoPE and time embedding, the shared Qwen3 conditioner (now with explicit positions, for FLUX.3's padded tokens, and a load that stops at the deepest tapped layer) and the FLUX.2 VAE, which loads `ae.safetensors` through a BFL-to-Diffusers name map. The probe recognizes the package's root `config.json` before any component, since its `vae/` would otherwise read as `flux2`. Prompt expansion through `flux-3-image-klein-pup` is not implemented: `upsample_prompt: true` is a 400. On GB10 against mlx-vlm the 512x512 Klein image is 47.73 dB end to end and 51.41 dB on upstream's text features (single-reference edit 57.60 dB), with bit-identical initial noise and token ids; the base checkpoint was not run (gated).

## [v0.9.0] - 2026-11-30

### Added
Expand Down
13 changes: 13 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,19 @@ moss-image-mlx NOTICE file, as required by Apache License 2.0 Section 4(d):
torch_randn.py and the strip-decoding VAE are adapted from felix-ab/flux3-mlx (Apache License 2.0).


FLUX.3 Image Klein (mlx-vlm, Black Forest Labs)
-----------------------------------------------

The FLUX.3 Image Klein port under src/imagegen/flux3/ derives from
mlx-vlm's mlx_vlm/models/flux3 (Blaizzy/mlx-vlm#2537), covered by the MIT
notice in the mlx-lm, mlx-vlm, and mlx-audio section below. mlx-vlm in turn
credits Black Forest Labs' reference implementation,
https://github.com/black-forest-labs/flux-3-image-klein, Copyright Black
Forest Labs, licensed under the Apache License, Version 2.0. The FLUX.3 model
weights are not distributed with mlxcel; they are published under the FLUX
Kommunity License and are gated on the Hugging Face Hub.


mlx-lm, mlx-vlm, and mlx-audio
------------------------------

Expand Down
67 changes: 65 additions & 2 deletions docs/image-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

mlxcel generates and edits images through `mlxcel generate-image` and the OpenAI-compatible `POST /v1/images/generations` and `POST /v1/images/edits` server routes. This page covers the model-independent runtime in `src/imagegen/`: the request types, the checkpoint probe, the scheduler, latent packing, the FLUX.2 VAE, the Z-Image DiT blocks, PNG output, the CLI, the server routes, and how a model issue registers a family.

**Current status.** Registered families: `flux2` ([FLUX.2 Klein](#flux2-klein-flux2)), `z_image` ([Z-Image](#z-image)), `bonsai` ([Prism Bonsai](#prism-bonsai-bonsai)), `ernie_image` ([ERNIE-Image](#ernie-image-ernie_image)), `mage_flow` ([Mage-Flow](#mage-flow-mage_flow)), `qwen_image` ([Qwen-Image](#qwen-image-qwen_image)), `ideogram4` ([Ideogram 4](#ideogram-4-ideogram4)), `ming_image` ([Ming-Image](#ming-image-ming_image)), `llada_image` ([LLaDA-Image](#llada-image-llada_image)) and `moss_image` ([MOSS-Image](#moss-image-moss_image)). Each model in the image-generation epic (`lablup/mlxcel#2348`) adds its transformer and text conditioner and one row to the family table. A checkpoint the probe recognizes but `FAMILIES` does not list fails with `image generation family <family> is not supported by this build`, and `mlxcel-server --image-model` fails at startup for it, by design (see [Server](#server)).
**Current status.** Registered families: `flux2` ([FLUX.2 Klein](#flux2-klein-flux2)), `flux3` ([FLUX.3 Image Klein](#flux3-image-klein-flux3)), `z_image` ([Z-Image](#z-image)), `bonsai` ([Prism Bonsai](#prism-bonsai-bonsai)), `ernie_image` ([ERNIE-Image](#ernie-image-ernie_image)), `mage_flow` ([Mage-Flow](#mage-flow-mage_flow)), `qwen_image` ([Qwen-Image](#qwen-image-qwen_image)), `ideogram4` ([Ideogram 4](#ideogram-4-ideogram4)), `ming_image` ([Ming-Image](#ming-image-ming_image)), `llada_image` ([LLaDA-Image](#llada-image-llada_image)) and `moss_image` ([MOSS-Image](#moss-image-moss_image)). Each model in the image-generation epic (`lablup/mlxcel#2348`) adds its transformer and text conditioner and one row to the family table. A checkpoint the probe recognizes but `FAMILIES` does not list fails with `image generation family <family> is not supported by this build`, and `mlxcel-server --image-model` fails at startup for it, by design (see [Server](#server)).

| Family | Checkpoints | Tasks | Default steps / guidance |
|--------|-------------|-------|--------------------------|
| `flux2` | FLUX.2 Klein 4B, 9B, base-4B, base-9B, 9b-kv (Diffusers tree) and the mlx-community 4-bit conversions | generate, edit (reference images) | distilled 4 / 1.0; base 50 / 4.0 |
| `flux3` | `black-forest-labs/flux-3-image-klein`, `-klein-base` (BFL package, bf16; gated) | generate, edit (1 to 10 references), layout boxes | Klein 16 / 1.0 (flow map); base 50 / 3.5 |
| `z_image` | Tongyi-MAI Z-Image-Turbo, Z-Image (raw Diffusers tree or an mlx-vlm conversion) | generate, edit (img2img) | Turbo 8 / 0; base 50 / 4 |
| `bonsai` | Prism Bonsai ternary 2-bit FLUX.2 Klein 4B (`prism-ml/bonsai-image-ternary-4B-mlx-2bit`) | generate | 4 / 1.0 |
| `ernie_image` | Baidu ERNIE-Image-Turbo, ERNIE-Image (raw Diffusers tree) | generate, edit (SDEdit img2img) | Turbo 8 / 1.0 (edit 8 / 3.0); base 50 / 4.0 |
Expand All @@ -21,12 +22,13 @@ mlxcel generates and edits images through `mlxcel generate-image` and the OpenAI

`mlxcel::imagegen::detect_image_family(path)` classifies a checkpoint directory from small JSON files; it never reads weights. It is a port of `_local_image_model_types` in `Blaizzy/mlx-vlm` (`mlx_vlm/generate/image.py`). In order, it reads:

0. The root `config.json` of a FLUX.3 package: BFL's layout names no `model_type`, so a `dit` block whose `in_channels` lists `image`, `image_cond` and `text` under a `model` starting with `flux-3-image` (upstream `is_flux3_config`) is `flux3` before any other rule runs. The package's Diffusers `vae/config.json` declares `AutoencoderKLFlux2`, which the class-name scan below would otherwise call `flux2`.
1. `manifest.json`: a manifest listing `transformer-packed-mflux/diffusion_pytorch_model.safetensors`, `text_encoder-mlx-4bit/model.safetensors` and `tokenizer/tokenizer.json` is `bonsai`. This is checked first because Bonsai ships a `Flux2KleinPipeline` `model_index.json`, which the class-name scan would call `flux2`.
2. `model_index.json` and `config.json`: `model_type`, `_class_name`, and the class names of the `transformer`, `vae`, `scheduler` and `text_encoder` components.
3. The transformer `weight_map` (`transformer/model.safetensors.index.json`, else `transformer/diffusion_pytorch_model.safetensors.index.json`), matched against marker key sets. A `z_image` transformer is `ming_image` when `mllm/config.json` exists.
4. Each `<dir>/config.json`.

The first candidate that names a family in `IMAGE_FAMILIES` wins: `bonsai`, `flux2`, `z_image`, `ming_image`, `ernie_image`, `qwen_image`, `mage_flow`, `ideogram4`, `llada_image`. Candidates come in the order above, so `Ideogram4Pipeline` in `model_index.json` wins over the FLUX.2 VAE class in `vae/config.json`. A path that does not exist, is not a directory, or carries no image metadata yields `None`; unparseable JSON is skipped.
The first candidate that names a family in `IMAGE_FAMILIES` wins: `bonsai`, `flux2`, `flux3`, `z_image`, `ming_image`, `ernie_image`, `qwen_image`, `mage_flow`, `ideogram4`, `llada_image`. Candidates come in the order above, so `Ideogram4Pipeline` in `model_index.json` wins over the FLUX.2 VAE class in `vae/config.json`. A path that does not exist, is not a directory, or carries no image metadata yields `None`; unparseable JSON is skipped.

`mlxcel generate` and `mlxcel serve -m` on an image checkpoint fail with `image generation checkpoint (<family>): use mlxcel generate-image` instead of `model_type not found` or a bare missing-`config.json` error. The hook sits in `src/models/detection.rs` and only fires when the directory has no top-level `model_type`, so no text checkpoint is affected.

Expand Down Expand Up @@ -585,6 +587,67 @@ Components: the Qwen3.5-9B language backbone as the prompt conditioner (`text_en

No numeric parity against the reference has been measured, and no checkpoint-gated test exists in this module yet. The contributor rendered `VisualInference/MOSS-Image-SFT-MLX-compact` end to end through `mlxcel-server --image-model` on an M4 (512x512, 12 steps, CFG 3.0 renders legible prompt text). The same checkpoint also renders on ROCm (gfx1151, `mlxcel generate-image`, 512x512, 12 steps, CFG 3.0, about 2 minutes including load); with the same seed, the decode before the batch-norm denormalization fix gave a washed-out image (pixel std 37.6) and the fixed decode gives full contrast (pixel std 64.4) with the prompt text spelled correctly. The unit tests cover the schedule, the probe, the chat template, the RoPE table, and the load-time weight shape checks, which turn a mis-shaped or mismatched checkpoint into an error before any MLX op runs.

## FLUX.3 Image Klein (`flux3`)

A port of `mlx_vlm/models/flux3` (`Blaizzy/mlx-vlm#2537`; checked against mlx-vlm at git e8035ae), in `src/imagegen/flux3/`. mlx-vlm credits Black Forest Labs' Apache-2.0 reference code; the weights are under the FLUX Kommunity License and the repositories are gated, so accept the terms on the Hub and download with a token.

| Checkpoint | Variant | Steps | Guidance | Notes |
|------------|---------|-------|----------|-------|
| `black-forest-labs/flux-3-image-klein` | `flux3-klein` | 16 | 1.0 | Distilled flow map: each step also embeds its target time, and guidance must be 1. |
| `black-forest-labs/flux-3-image-klein-base` | `flux3-klein-base` | 50 | 3.5 | Guidance other than 1 runs a second pass on the empty prompt (or `--negative-prompt`) and mixes `uncond + g * (cond - uncond)`. |

Each repository is about 43 GB because it also ships a Diffusers `transformer/` copy and CUDA-only `variants/`. mlxcel reads the root package only: `config.json`, `model.safetensors` (11.1 GB, bf16), `ae.safetensors` (0.34 GB) and `text_encoder/` (8.9 GB), about 20.4 GB:

```bash
hf download black-forest-labs/flux-3-image-klein --local-dir models/flux-3-image-klein \
--include config.json manifest.json model.safetensors ae.safetensors 'text_encoder/*'
mlxcel generate-image -m models/flux-3-image-klein \
-p "A studio photograph of a red ceramic teapot" --size 512x512 --seed 42 -o teapot.png
mlxcel generate-image -m models/flux-3-image-klein --task edit --image teapot.png \
-p "Make the teapot cobalt blue" --seed 42 -o blue.png
```

A missing file fails at load with every missing path listed.

- **Architecture.** Three independent early streams (`image`, `image_cond` for references, `text`), five blocks each with their own modulation and RoPE, then 28 joint single-stream blocks in which each token takes its own mode's modulation. Every block modulates an affine-free layer norm, applies a QK RMS norm and an interleaved RoPE together in f32 (rounded once to bf16), and adds attention and a parallel SwiGLU behind one gate. FLUX.2's 4-axis RoPE, time embedding and text ids are reused; the time is held in bf16 and `1000 * t` is rounded to bf16 before it meets the frequencies, as BFL does.
- **Conditioner.** The Qwen3-VL-4B text backbone in `text_encoder/` (vision tower skipped, layers after 32 not loaded) in bf16. The prompt is one user turn through the chat template with the generation prompt, right-padded to a multiple of 80 tokens and truncated at 4096 (`max_tokens` is capped there). Real tokens sit at positions `0..n` and every padded token at position 1; the hidden states after layers 4, 8, ..., 32 are concatenated to `[1, T, 20480]`. The encoder is evicted after each prompt and four prompts are cached; the transformer and VAE load on the first request and stay resident.
- **Sampler.** `t = linspace(1, 0, steps + 1)` mapped through `alpha * t / (1 + (alpha - 1) * t)` (`alpha` 6.93), Euler steps in f32 on the bf16 transformer, initial noise `normal((n, H/16 * W/16, 128), key(seed))` rounded through bf16.
- **VAE.** `ae.safetensors` is the FLUX.2 autoencoder under BFL's tensor names; it loads into the shared `Flux2Vae` through a name map (decoder levels renumbered, 1x1 attention kernels as linear weights) and runs in f32. Its encode and decode are identical to the package's Diffusers `vae/` copy (see Parity), which is not read. Output pixels are `((clip(x, -1, 1) + 1) * 127.5)` truncated to `uint8`.
- **Sizes.** Width and height multiples of 16 in `64..=4096`.
- **Editing.** One to ten references. A lone reference keeps its aspect ratio within 4 MP and 4096 px per side, is Lanczos-resized when it has to shrink and reflect-padded (symmetric below 17 px) to multiples of 16; several references are each capped at 1 MP and center-cropped to multiples of 16. Each is VAE-encoded as the `image_cond` stream on its own RoPE layer (`-1 - index`). Without a size the output takes the first reference's padded size, and a lone padded reference is cropped back to its own area; several references take the first one's 1 MP size. The CLI and the server fill a missing size from the first reference before the model sees the request, so an explicit size equal to that default is treated the same way. The resize uses the `image` crate's Lanczos3 filter, not PIL's, so a reference that has to shrink differs from upstream's by interpolation rounding. Edits run once per image with seed `seed + i`.
- **Batches.** Generation draws `n` images from one noise tensor of batch `n` and reports `seed` for each, as [FLUX.2](#batched-seeds) does.
- **Layout boxes.** `boxes: [{"id", "desc", "bbox": [top, left, bottom, right]}]` in `0..1` (or `src_bbox` / `tgt_bbox` with `from` for edits) are mapped to the `0..1000` canvas and appended to the prompt as one space and their JSON, written as Python's `json.dumps(..., ensure_ascii=False)` writes it. The response's `revised_prompt` is the prompt actually encoded when boxes changed it.
- **Prompt expansion.** Upstream rewrites every prompt through the `flux-3-image-klein-pup` VLM by default. That is not implemented: `upsample_prompt: true` or a `prompt_expansion_model` is a 400 that says so, and every run is upstream's `upsample_prompt=False` path, so pass a detailed caption.
- **`--gen-kwargs` / `extra`.** `max_sequence_length` (1 to 4096), `boxes`, `upsample_prompt` (`false` only), and `num_images`, which must equal `n` when given.

### FLUX.3 parity

Against upstream mlx-vlm at git e8035ae on mlx 0.32.5, CUDA, NVIDIA GB10, `MLX_ENABLE_TF32=0`, with `upsample_prompt=False` on both sides and the `black-forest-labs/flux-3-image-klein` package at revision `3b767ff9`. `tests/fixtures/flux3/generate_flux3_oracle.py` writes the upstream oracle (nothing large is committed); the `#[ignore]` tests in `src/imagegen/flux3/parity_tests.rs` read it from `MLXCEL_FLUX3_ORACLE_DIR` and the package from `MLXCEL_TEST_FLUX3_DIR` (default `models/flux-3-image-klein`), and skip when either is absent:

```bash
PYTHONPATH=<mlx-vlm checkout> python tests/fixtures/flux3/generate_flux3_oracle.py \
models/flux-3-image-klein /tmp/flux3-oracle
MLXCEL_FLUX3_ORACLE_DIR=/tmp/flux3-oracle MLX_ENABLE_TF32=0 \
cargo test --profile test-fast --features cuda --lib imagegen::flux3::parity_tests \
-- --ignored --test-threads=1 --nocapture
```

| Check | Result |
|-------|--------|
| Token ids and masks (the teapot, edit and empty prompts, 80 tokens each) | identical |
| Initial noise, 512x512, seed 42 | bit-identical (131,072 values) |
| Text features of the teapot prompt | 2.09e-3 relative RMS |
| Step-0 velocity on upstream's text features | 5.74e-3 relative RMS |
| `ae.safetensors` through the name map against the package's Diffusers `vae/` | 250 of 250 tensors identical; encode and decode identical |
| Encoded edit reference (bf16 tokens against upstream's f32 encoder output) | 1.66e-3 relative RMS |
| Klein 512x512 generate, 16 steps, seed 42, on upstream's text features | 51.41 dB |
| Klein 512x512 edit of upstream's teapot, "Make the teapot cobalt blue", seed 42, on upstream's text features | 57.60 dB |
| Klein 512x512 generate end to end, on mlxcel's text features | 47.73 dB |

The unit tests check the rest against values upstream's own code produced (`tests/fixtures/flux3/generate_flux3_unit_fixtures.py`): a two-early, two-single-block random transformer in f32 within 2e-6 of upstream on text only, text plus one reference, and a non-flow-map config; `timesteps(16, 6.93)`; the seed-42 noise head; and `prepare_reference` sizes, crops and padded bytes.

The base model (`flux-3-image-klein-base`, 50 steps, guidance 3.5) has not been run against upstream: its repository was still gated for the account that produced these numbers. Only its transformer path without the flow-map embedding is covered, by the tiny-model unit test; the CFG pass has not run on real weights.

## Verification

```bash
Expand Down
Loading