# Technical Documentation: filipstrand/mflux

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/filipstrand/mflux)

### Overview (README.md)

[](https://pypi.org/project/mflux/)
[](https://pypi.org/project/mlx/)
[](https://github.com/mflux-community/mflux/actions/workflows/tests.yml)
[](https://www.greptile.com/?utm_source=oss_badge&utm_medium=readme&utm_campaign=greptile_for_open_source)

### About

Run the latest state-of-the-art generative image models locally on your Mac in native MLX!

### Table of contents

- [💡 Philosophy](#-philosophy)
- [💿 Installation](#-installation)
- [🎨 Models](#-models)
- [✨ Features](#-features)
- [🦄 Contributors](#-contributors)
- [🌱 Related projects](#related-projects)
- [🙏 Acknowledgements](#-acknowledgements)
- [⚖️ License](#%EF%B8%8F-license)

---

### 💡 Philosophy

MFLUX is a line-by-line MLX port of several state-of-the-art generative image models from the [Huggingface Diffusers](https://github.com/huggingface/diffusers) and [Huggingface Transformers](https://github.com/huggingface/transformers) libraries. All models are implemented from scratch in MLX, using only tokenizers from the [Huggingface Transformers](https://github.com/huggingface/transformers) library. MFLUX is purposefully kept minimal and explicit, [@karpathy](https://gist.github.com/awni/a67d16d50f0f492d94a10418e0592bde?permalink_comment_id=5153531#gistcomment-5153531) style.

---

### 💿 Installation
If you haven't already, [install `uv`](https://github.com/astral-sh/uv?tab=readme-ov-file#installation), then run:

```sh
uv tool install --upgrade mflux
```

After installation, the following command shows all available MFLUX CLI commands: 

```sh
uv tool list 
```

To generate your first image using, for example, the z-image-turbo model, run

```
mflux-generate-z-image-turbo \
  --prompt "A puffin standing on a cliff" \
  --width 1280 \
  --height 500 \
  --seed 42 \
  --steps 9 \
  -q 8
```



The first time you run this, the model will automatically download which can take some time. See the [model section](#-models) for the different options and features, and the [common README](src/mflux/models/common/README.md) for shared CLI patterns and examples.

<details>
<summary>Python API</summary>

Create a standalone `generate.py` script with inline `uv` dependencies:

```python
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#   "mflux",
# ]
# ///
from mflux.models.z_image import ZImageTurbo

model = ZImageTurbo(quantize=8)
image = model.generate_image(
    prompt="A puffin standing on a cliff",
    seed=42,
    num_inference_steps=9,
    width=1280,
    height=500,
)
image.save("puffin.png")
```

Run it with:

```sh
uv run generate.py
```

For more Python API inspiration, look at the [CLI entry points](src/mflux/models/z_image/cli/z_image_turbo_generate.py) for the respective models.
</details>

<details>
<summary>⚠️ Troubleshooting: hf_transfer error</summary>

If you encounter a `ValueError: Fast download using 'hf_transfer' is enabled (HF_HUB_ENABLE_HF_TRANSFER=1) but 'hf_transfer' package is not available`, you can install MFLUX with the `hf_transfer` package included:

```sh
uv tool install --upgrade mflux --with hf_transfer
```

This will enable faster model downloads from Hugging Face.

</details>

<details>
<summary>DGX / NVIDIA (uv tool install)</summary>

```sh
uv tool install --python 3.13 mflux
```
</details>

---

### 🎨 Models

MFLUX supports the following model families. They have different strengths and weaknesses; see each model’s README for full usage details.

| Model | Release date | Size | Type | Training | Description |
| --- | --- | --- | --- | --- | --- |
|[Z-Image](src/mflux/models/z_image/README.md) | Nov 2025 | 6B | Distilled & Base | Yes | Fast, small, very good quality and realism. |
|[Krea 2](src/mflux/models/krea2/README.md) | Jun 2026 | 12B | Turbo (distilled) | Yes | Very good quality with a wide range of styles; good for creative exploration. |
|[FLUX.2](src/mflux/models/flux2/README.md) | Jan 2026 | 4B & 9B | Distilled & Base | Yes | Fastest + smallest with very good quality and edit capabilities. |
|[FLUX 3 Image Klein](src/mflux/models/flux3/README.md) | Oct 2026 | 5.6B (+4B TE) | Distilled & Base | No | Text-to-image and editing with up to 10 reference images in one model; bounding-box layouts, strong text rendering. 16 steps distilled, 50 steps Base. |
|[Iris-3B](src/mflux/models/iris/README.md) | Oct 2026 | 3B (+4B TE) | Turbo (distilled) & Base | Yes | Pixel-space diffusion transformer: no VAE, direct RGB generation. 4 steps Turbo, 100 steps base. |
|[Ideogram 4](src/mflux/models/ideogram4/README.md) | Jun 2026 | 9B | Base | No | JSON-caption-native, typography-focused text-to-image generation. |
|[ERNIE-Image](src/mflux/models/ernie_image/README.md) | Apr 2026 | 8B | Distilled & Base | Yes | Single-stream DiT from Baidu. Vivid, high-contrast output. |
|[Lens](src/mflux/models/lens/README.md) | May 2026 | 3.8B (+20B TE) | Turbo (distilled) | No | Dual-stream MMDiT from Microsoft with a GPT-OSS text encoder. Strong prompt adherence in 4 steps. |
|[Ming-Image](src/mflux/models/ming_image/README.md) | Sep 2026 | 6.15B (+16B MoE TE) | Base | No | Design-focused (posters, cards, UI) with strong typography; outputs RGBA. |
|[MOSS-Image](src/mflux/models/moss_image/README.md) | Oct 2026 | 4.9B (+9B TE) | SFT & Base | No | Single-stream DiT from OpenMOSS with a Qwen3.5 text encoder. Takes natural-language, tag and JSON-layout prompts. Renders English and Chinese text. 50 steps with CFG, or 8 or 4 steps with a community step-distilled LoRA. |
|[SenseNova-U1.5](src/mflux/models/sensenova/README.md) | Nov 2026 | 8B MoT (16.9B loaded) | Base | No | Pixel-space Mixture-of-Transformers on Qwen3-8B from SenseTime: no VAE, direct RGB generation. Text-to-image only. 50 steps with CFG, or 8 steps with the official step-distilled LoRA. |
|[DreamLite](src/mflux/models/dreamlite/README.md) | Apr 2026 | 0.39B (+2B TE) | Base & Mobile (distilled) | No | Compact on-device UNet from ByteDance with a Qwen3-VL text encoder: text-to-image and instruction-based editing in one model. 28 steps with CFG, or 4 steps with Mobile. Non-commercial weights. |
|[Anima](src/mflux/models/anima/README.md) | Jan 2026 | 2B (+0.6B TE) | Turbo (distilled), Aesthetic & Base | Yes | Anime and illustration model from CircleStone Labs and Comfy Org on Cosmos-Predict2, with a Qwen3 text encoder. Danbooru tags and natural language. 10 steps Turbo, 30 steps with CFG for Aesthetic and Base. |
|[Boogu Image](src/mflux/models/boogu/README.md) | Jun 2026 | 10B | Turbo (distilled) | No | DMD-distilled 4-step model with a photographic look and bilingual (EN/ZH) text rendering. |
|[FIBO 2](src/mflux/models/fibo2/README.md) | Oct 2026 | 8.1B (+4B TE) | Base & Edit Turbo (distilled) | Yes | Trained on long structured JSON captions for precise control; renders text. Text-to-image and editing of 1 to 5 images, with masks. 50 steps with CFG; Edit Turbo runs 4 without. |
|[SeedVR2](src/mflux/models/seedvr2/README.md) | Jun 2025 | 3B & 7B | — | No | Best upscaling model. |
|[Qwen Image](src/mflux/models/qwen/README.md) | Aug 2025+ | 20B | Base | No | Large model (slower); strong prompt understanding and world knowledge. Has edit capabilities |
|[Qwen Image 2.1](src/mflux/models/qwen21/README.md) | Sep 2026+ | 7.1B (+8B TE) | Distilled & Base | Yes | Single-stream block-causal DiT with a Qwen3-VL text encoder. Base: 40 steps without guidance. Turbo: 8 steps. [Multi-reference editing, LoRA, and RGBA](src/mflux/models/qwen21/reference/README.md). |
|[Depth Pro](src/mflux/models/depth_pro/README.md) | Oct 2024 | — | — | No | Very fast and accurate depth estimation model from Apple. |
|[FIBO](src/mflux/models/fibo/README.md) | Oct 2025+ | 8B | Distilled & Base | No | Legacy option, superseded by FIBO 2. JSON-based prompt understanding and edit capabilities. |
|[FLUX.1](src/mflux/models/flux/README.md) | Aug 2024 | 12B | Distilled & Base | No (legacy) | Legacy option with decent quality. Has edit capabilities with 'Kontext' model and upscaling support via ControlNet |

**Schedulers**<br>
MFlux supports a small number of schedulers - see;<br>
[Schedulers - User Manual](docs/schedulers.md)<br>
[Schedulers - Technical Overview](src/mflux/models/common/schedulers/README.md)<br>

---

### ✨ Features

**General**
- Quantization and local model loading
- LoRA support (multi-LoRA, scales, library lookup), including LyCORIS LoKr on FLUX.1 and FLUX.2
- Metadata export + reuse, plus prompt file support
- Float16 compute for Apple M1-family GPUs on FLUX.2, FLUX 3 Image Klein, Z-Image, Qwen-Image 2.1 and Anima (`--compute-precision float16`, see the [common README](src/mflux/models/common/README.md#float16-compute-apple-m1-family))

**Model-specific highlights**
- Text-to-image and image-to-image generation.
- LoRA finetuning
- In-context editing, multi-image editing, and virtual try-on
- ControlNet (Canny for FLUX.1, Union for Z-Image and Qwen-Image-2.1, depth for Krea 2), depth conditioning, fill/inpainting, and Redux
- Upscaling (SeedVR2 and Flux ControlNet)
- Depth map extraction and FIBO prompt tooling (VLM inspire/refine)

See the [common README](src/mflux/models/common/README.md) for detailed usage and examples, and use the model section above to browse specific models and capabilities.



> [!NOTE]
> As MFLUX supports a wide variety of CLI tools and options, the easiest way to navigate the CLI in 2026 is to use a coding agent (like [Cursor](https://cursor.com), [Claude Code](https://www.anthropic.com/claude-code), or similar). Ask questions like: “Can you help me generate an image using z-image?”




---

<a id="contributors"></a>

### 🦄 Contributors

<img src="https://contrib.rocks/image?repo=mflux-community/mflux" />

MFlux was originally created by [Filip Strand](https://github.com/filipstrand) in August 2024 and moved to this organisation in August 2026. It is maintained by:

<table>
<tr>
<td align="center" width="150"><a href="https://github.com/filipstrand"><img src="https://github.com/filipstrand.png?size=100" width="72" alt="filipstrand"><br><b>Filip Strand</b></a><br><sub>Created MFlux</sub></td>
<td align="center" width="150"><a href="https://github.com/anthonywu"><img src="https://github.com/anthonywu.png?size=100" width="72" alt="anthonywu"><br><b>Anthony Wu</b></a><br><sub>Toolchain, CI, releases, mflux.web</sub></td>
<td align="center" width="150"><a href="https://github.com/plz12345"><img src="https://github.com/plz12345.png?size=100" width="72" alt="plz12345"><br><b>plz12345</b></a><br><sub>Devops, Krea 2, Boogu</sub></td>
<td align="center" width="150"><a href="https://github.com/fxd0h"><img src="https://github.com/fxd0h.png?size=100" width="72" alt="fxd0h"><br><b>Mariano Abad</b></a><br><sub>ControlNets, training, Lens</sub></td>
<td align="center" width="150"><a href="https://github.com/ianscrivener"><img src="https://github.com/ianscrivener.png?size=100" width="72" alt="ianscrivener"><br><b>Ian Scrivener</b></a><br><sub>HF, community, CUDA, model builds</sub></td>
</tr>
</table>

Where the models and the main features came from, read from the merge history (`gh pr view <n> --json author,mergedAt`):

| Model or feature | Contributor | PR |
|--|--|--|
| FLUX.1 | [@filipstrand](https://github.com/filipstrand) | initial release, 2024-08 |
| Depth Pro | [@filipstrand](https://github.com/filipstrand) | [#159](https://github.com/mflux-community/mflux/pull/159) |
| Qwen Image | [@filipstrand](https://github.com/filipstrand) | [#269](https://github.com/mflux-community/mflux/pull/269) |
| FIBO | [@filipstrand](https://github.com/filipstrand) | [#279](https://github.com/mflux-community/mflux/pull/279) |
| FIBO 2 | [@filipstrand](https://github.com/filipstrand) | — |
| Z-Image | [@filipstrand](https://github.com/filipstrand) | [#284](https://github.com/mflux-community/mflux/pull/284) |
| SeedVR2 | [@filipstrand](https://github.com/filipstrand) | [#297](https://github.com/mflux-community/mflux/pull/297) |
| FLUX.2 Klein | [@filipstrand](https://github.com/filipstrand) | [#323](https://github.com/mflux-community/mflux/pull/323) |
| FLUX 3 Image Klein | [@cguldogan](https://github.com/cguldogan) | [#876](https://github.com/mflux-community/mflux/issues/876) |
| Iris-3B | [@cguldogan](https://github.com/cguldogan) | [#898](https://github.com/mflux-community/mflux/issues/898) |
| FLUX.2 KV cache (klein-9b-kv) | [@michaeltrefry](https://github.com/michaeltrefry) | [#426](https://github.com/mflux-community/mflux/pull/426) |
| ERNIE-Image | [@azrahello](https://github.com/azrahello) | [#417](https://github.com/mflux-community/mflux/pull/417) |
| Ideogram 4 | [@omercelik](https://github.com/omercelik) | [#433](https://github.com/mflux-community/mflux/pull/433) |
| Krea 2 | [@plz12345](https://github.com/plz12345) | [#453](https://github.com/mflux-community/mflux/pull/453) |
| LyCORIS LoKr adapters | [@JanGrohn](https://github.com/JanGrohn) | [#422](https://github.com/mflux-community/mflux/pull/422) |
| Fused-qkv LoRA loading | [@deadmansahil](https://github.com/deadmansahil) | [#459](https://github.com/mflux-community/mflux/pull/459) |
| Boogu-Image | [@plz12345](https://github.com/plz12345) | [#446](https://github.com/mflux-community/mflux/pull/446) |
| MOSS-Image | [@vanch007](https://github.com/vanch007) | [#895](https://github.com/mflux-community/mflux/pull/895) |
| SenseNova-U1.5 | [@cguldogan](https://github.com/cguldogan) | [#989](https://github.com/mflux-community/mflux/pull/989) |
| Anima | [@fxd0h](https://github.com/fxd0h) | [#931](https://github.com/mflux-community/mflux/pull/931) |
| PiD pixel-diffusion decoder | [@azrahello](https://github.com/azrahello) | [#490](https://github.com/mflux-community/mflux/pull/490) |
| Z-Image Union ControlNet | [@fxd0h](https://github.com/fxd0h) | [#482](https://github.com/mflux-community/mflux/pull/482) |
| Krea 2 Raw, LoRA training, diffusers loading | [@fxd0h](https://github.com/fxd0h) | [#462](https://github.com/mflux-community/mflux/pull/462) |
| Lens (Turbo) | [@fxd0h](https://github.com/fxd0h) | [#510](https://github.com/mflux-community/mflux/pull/510) |
| mflux-capabilities, the machine-readable option contract | [@fxd0h](https://github.com/fxd0h) | [#499](https://github.com/mflux-community/mflux/pull/499) |
| Gradient checkpointing for training | [@qruz-hq](https://github.com/qruz-hq) | [#711](https://github.com/mflux-community/mflux/pull/711) |
| Denoised prediction for in-loop callbacks | [@IonDen](https://github.com/IonDen) | [#729](https://github.com/mflux-community/mflux/pull/729) |
| Qwen-Image-2.1 | [@ivanfioravanti](https://github.com/ivanfioravanti) | [#736](https://github.com/mflux-community/mflux/pull/736) |
| Qwen-Image-2.1 reference editing, RGBA, prefix cache | [@dreampuf](https://github.com/dreampuf) | [#741](https://github.com/mflux-community/mflux/pull/741), [#777](https://github.com/mflux-community/mflux/pull/777) |
| Qwen-Image-2.1 masks, auto-mask, strength, verify | [@flyingtimes](https://github.com/flyingtimes) | [#749](https://github.com/mflux-community/mflux/pull/749), [#764](https://github.com/mflux-community/mflux/pull/764) |
| PEFT and ComfyUI LoRA formats (Qwen 2.1, Z-Image) | [@phplego](https://github.com/phplego) | [#756](https://github.com/mflux-community/mflux/pull/756), [#768](https://github.com/mflux-community/mflux/pull/768), [#772](https://github.com/mflux-community/mflux/pull/772) |
| Text-prefix KV cache, Metal kernel, step cache | [@murphymatt](https://github.com/murphymatt) | [#778](https://github.com/mflux-community/mflux/pull/778), [#779](https://github.com/mflux-community/mflux/pull/779) |
| Ming-Image-0.1-Design | [@joeynyc](https://github.com/joeynyc) | [#765](https://github.com/mflux-community/mflux/pull/765) |
| load and generate entry points for UIs | [@IonDen](https://github.com/IonDen) | [#780](https://github.com/mflux-community/mflux/pull/780), [#785](https://github.com/mflux-community/mflux/pull/785) |
| mflux.web UI packages | [@anthonywu](https://github.com/anthonywu) | [#776](https://github.com/mflux-community/mflux/pull/776) |
| CI gates, justfile, ty, the pypi environment | [@anthonywu](https://github.com/anthonywu) | [#576](https://github.com/mflux-community/mflux/pull/576), [#590](https://github.com/mflux-community/mflux/pull/590), [#646](https://github.com/mflux-community/mflux/pull/646) |
| Release process and release notes | [@fxd0h](https://github.com/fxd0h) | [#685](https://github.com/mflux-community/mflux/pull/685) |
| test_tiny fixtures for every model | [@ianscrivener](https://github.com/ianscrivener), [@anthonywu](https://github.com/anthonywu) | [#611](https://github.com/mflux-community/mflux/pull/611), [#620](https://github.com/mflux-community/mflux/pull/620), [#599](https://github.com/mflux-community/mflux/pull/599) |

Everyone else who fixed, tested and reviewed is in the [contributor graph](https://github.com/mflux-community/mflux/graphs/contributors).

---

<a id="related-projects"></a>

### 🌱 Related projects

#### Build a UI under `mflux.web`

We welcome independently distributed `mflux.web.*` implementations using Gradio,
FastAPI, FastHTML, or any other UI framework. Each project can choose its own
framework, dependencies, release schedule, and launch command.

`mflux` owns the parent initializer and inference implementation. Its package
path extends across installed distributions, including separate editable
checkouts. `mflux.web` is an implicit namespace package: Python combines the
`mflux/web/` directories contributed by independently installed UI packages.
No intermediate distribution is required; neither core nor UI packages need to
depend on `mflux-web`. The [`mflux-web`](https://pypi.org/project/mflux-web/)
distribution reserves the generic `mflux-web` name on PyPI; it does not provide
the shared namespace and does not need to be installed. Its optional demo is
just another child module, `mflux.web.demo`.

Your UI distribution owns a unique child, for example
`src/mflux/web/example_ui/__init__.py`. With `uv_build`, configure
`module-name = "mflux.web.example_ui"`. Declare `mflux` and your chosen framework
as dependencies with versions your UI supports. The minimum `mflux` version for
split-directory installs must include this parent path extension.

Do not ship `mflux/__init__.py`, which belongs to core, or
`mflux/web/__init__.py`, which must remain absent for the implicit namespace.
Choose a unique child name to avoid collisions. PyPI distribution names can use
hyphens; Python child names must be valid identifiers, such as `example_ui`.
Reserving a PyPI distribution name does not reserve a Python namespace.

After installation in the same environment, consumers can use
`import mflux.web.example_ui`. Installing a UI does not automatically launch it,
discover applications, or mount routes. UI framework dependencies belong to the
individual UI distributions; this namespace support adds none to `mflux`.

#### Extras under `mflux.extras`

Plugins are optional packages that install next to mflux, put their code under
`mflux.extras` and add their own commands. mflux's own commands do not change.
The mflux-community plugins live in
[mflux-plugins](https://github.com/mflux-community/mflux-plugins). To find,
install or write one, see [Plugins - User Manual](docs/plugins.md).

#### Community applications

- [MindCraft Studio](https://themindstudio.cc/mindcraft#models) — macOS app built on mflux by [@shaoju](https://github.com/shaoju)
- [mflux-paint](https://github.com/Amo643/mflux-paint) — native macOS inpaint/edit app (pywebview), 16 models across edit/inpaint/text-to-image, mask painting, multi-seed batch, by [@Amo643](https://github.com/Amo643)
- [Mflux-ComfyUI](https://github.com/raysers/Mflux-ComfyUI) by [@raysers](https://github.com/raysers)
- [MFLUX-WEBUI](https://github.com/CharafChnioune/MFLUX-WEBUI) by [@CharafChnioune](https://github.com/CharafChnioune)
- [mflux-fasthtml](https://github.com/anthonywu/mflux-fasthtml) by [@anthonywu](https://github.com/anthonywu)
- [mflux-streamlit](https://github.com/elitexp/mflux-streamlit) by [@elitexp](https://github.com/elitexp)
- [mfluxible](https://github.com/wesbiggs/mfluxible) — streaming HTTP API server for mflux models with a browser harness, an MCP tool and an OpenAI-compatible endpoint, by [@wesbiggs](https://github.com/wesbiggs)
- [mlx-taef](https://github.com/IonDen/mlx-taef) — TAESD/TAEF tiny-autoencoder live previews and low-memory FLUX decode for mflux, by [@IonDen](https://github.com/IonDen)
- [mlx-teacache](https://github.com/IonDen/mlx-teacache) — TeaCache step skipping for FLUX.1 dev and Krea, FLUX.2 Klein base, Z-Image base and Qwen-Image (original checkpoint) in mflux, by [@IonDen](https://github.com/IonDen)
- [MLXBits Image Studio](https://github.com/MLXBits/image-studio) - A native macOS Swift app for FLUX, Krea 2, Z-Image and more!
- [Graphis](https://github.com/Campfire7/graphis) - native macOS SwiftUI app for MOSS-Image with a bundled mflux engine, reference image, LoRA modules and a queue, by [@Campfire7](https://github.com/Campfire7)
---

### 🙏 Acknowledgements

MFLUX would not be possible without the great work of:

- The MLX Team for [MLX](https://github.com/ml-explore/mlx) and [MLX examples](https://github.com/ml-explore/mlx-examples)
- Black Forest Labs for the [FLUX project](https://github.com/black-forest-labs/flux)
- Bria for the [FIBO project](https://huggingface.co/briaai/FIBO)
- Tongyi Lab for the [Z-Image project](https://tongyi-mai.github.io/Z-Image-blog/)
- Baidu for the [ERNIE-Image project](https://huggingface.co/baidu/ERNIE-Image)
- Ideogram for the [Ideogram 4 project](https://huggingface.co/ideogram-ai/ideogram-4-fp8)
- Speridlabs for the [Iris-3B project](https://github.com/speridlabs/iris-3b)
- Krea.ai for the [Krea 2 project](https://www.krea.ai/blog/krea-2-technical-report)
- Qwen Team for the [Qwen Image project](https://qwen.ai/blog?id=a6f483777144685d33cd3d2af95136fcbeb57652&from=research.research-list)
- Microsoft for the Lens (Turbo) model, and Comfy-Org for the [weights repackage](https://huggingface.co/Comfy-Org/Lens)
- inclusionAI for the [Ming-Image project](https://github.com/inclusionAI/Ming-Image)
- OpenMOSS for the [MOSS-Image project](https://github.com/OpenMOSS/MOSS-Image)
- SenseTime for the [SenseNova-U1 project](https://github.com/OpenSenseNova/SenseNova-U1)
- ByteDance for the [DreamLite project](https://github.com/ByteVisionLab/DreamLite)
- CircleStone Labs and Comfy Org for the [Anima project](https://huggingface.co/circlestone-labs/Anima)
- The Boogu team for the [Boogu Image project](https://huggingface.co/Boogu/Boogu-Image-0.1-Turbo)
- ByteDance, @numz and @adrientoupet for the [SeedVR2 project](https://github.com/numz/ComfyUI-SeedVR2_VideoUpscaler)
- Hugging Face for the [Diffusers library implementations](https://github.com/huggingface/diffusers) 
- Depth Pro authors for the [Depth Pro model](https://github.com/apple/ml-depth-pro?tab=readme-ov-file#citation)
- The MLX community and all [contributors and testers](https://github.com/mflux-community/mflux/graphs/contributors)

---

### ⚖️ License

This project is licensed under the [MIT License](LICENSE).

---

### How MFlux Uses OpenCV (`docs/How-MFlux-uses-OpenCV.md`)

# How MFlux uses OpenCV

## Summary

MFlux uses OpenCV (`opencv-python`, imported as `cv2`) only to prepare ControlNet control images. OpenCV does no model work. All model math runs in MLX.

All `import cv2` lines are lazy. They are inside the function that needs them, with the comment `# only here: OpenCV is optional`. Thus MFlux starts and runs without OpenCV until a code path needs one of these functions.

Test result (OpenCV blocked with `sys.modules["cv2"] = None`): all 46 CLI entry points import with no error.

## Where MFlux calls OpenCV

| File | OpenCV calls | Purpose |
|---|---|---|
| `models/flux/variants/controlnet/controlnet_util.py` | `cv2.Canny` | Canny edge map from the input image |
| `models/z_image/variants/controlnet/controlnet_util.py` | `cv2.Canny` | `canny` control |
| same file | `cv2.createLineSegmentDetector`, `cv2.line` | `mlsd` control (straight lines, no neural model) |
| `models/openpose/openpose.py` | `cvtColor`, `resize`, `copyMakeBorder`, `GaussianBlur`, `circle`, `ellipse`, `fillConvexPoly`, `addWeighted` | Pre- and post-processing for the MLX OpenPose model, and drawing of the skeleton |

Paths are relative to `src/mflux/`.

## What needs OpenCV

| Feature | Why |
|---|---|
| `mflux-generate-controlnet` with a Canny ControlNet (model name has `Canny`, for example `InstantX/FLUX.1-dev-Controlnet-Canny`) | Canny edges from `--controlnet-image-path` |
| `mflux-generate-z-image-controlnet` with `canny` | `cv2.Canny` |
| `mflux-generate-z-image-controlnet` with `mlsd` | LineSegmentDetector. It needs `opencv-python>=4.8`. |
| `mflux-generate-z-image-controlnet` with `pose` | OpenPose image steps. This control also needs torch for the weights. |

Without OpenCV, these features stop with `ImportError` when they prepare the control image.

## What runs without OpenCV

All other commands. This includes:

- Z-Image ControlNet `depth` and `hed` controls
- Krea 2 depth ControlNet
- Qwen 2.1 ControlNet (you supply a preprocessed control image)
- `mflux-upscale-controlnet`
- all text-to-image and edit commands

## macOS and Linux/CUDA

`pyproject.toml` lists `opencv-python>=4.10.0,<6.0` for all platforms. The installed version in this repo is 4.13.

On macOS, the wheel installs and operates with no extra steps.

On Linux, `opencv-python` is the GUI build. It loads system libraries such as `libGL.so.1`. A minimal server or container image often does not have them, and then `import cv2` fails. Two fixes:

1. Install the system library, for example `apt install libgl1 libglib2.0-0`.
2. Replace `opencv-python` with `opencv-python-headless`. MFlux uses no OpenCV GUI functions, so the headless build is sufficient.

OpenCV runs on the CPU. MFlux does not use OpenCV CUDA.

## How to install without OpenCV

OpenCV is a hard dependency, so a normal install pulls it. Two options:

1. Install as usual, then remove OpenCV: `pip uninstall opencv-python`.
2. Install mflux with `--no-deps`, then install the other dependencies from `pyproject.toml` yourself.

After this, the features in "What needs OpenCV" fail, and all other features operate as usual.

---

### How MFlux Uses PyTorch (`docs/How-MFlux-uses-PyTorch.md`)

# How MFlux uses PyTorch

## Summary

MFlux does all model math in MLX. PyTorch never runs a forward pass. MFlux uses PyTorch for only two jobs:

1. Read weight files that MLX cannot read (`.pt` / `.pth` pickles). The Depth Pro loader calls `torch.load` with `weights_only=False`, so a `.pt` file can run code when it loads. Use only Depth Pro files from a source that you trust.
2. Convert some bf16 safetensors through `torch` to float16 before MLX gets them.

All `import torch` lines are lazy. They are inside the function that needs them. Thus MFlux starts and runs without PyTorch until a code path needs one of these two jobs.

Test result (torch blocked with `sys.modules["torch"] = None`): all 46 CLI entry points import with no error. `transformers` 5.15 shows a warning that PyTorch is not found. The warning is harmless, because MFlux uses only the tokenizers and configs from `transformers`.

## Where MFlux calls torch

| File | What it does with torch | Who calls it |
|---|---|---|
| `models/common/weights/loading/weight_loader.py` | `torch_checkpoint`: `torch.load` of a `.pt` file | Depth Pro |
| same file | `torch_convert`: bf16 safetensors → float16 → MLX | FIBO (VAE, transformer, text encoder) |
| same file | `torch_bfloat16`: same conversion, read from an index file | FIBO VLM |
| `models/common/pid_decoder/pid_weight_mapping.py` | `torch.load` of the PiD `.pth` checkpoint | `--pid-decode` on all models that have it |
| `models/hed/hed.py` | `torch.load` of the HED `.pth` | Z-Image ControlNet, `hed` control |
| `models/openpose/openpose.py` | `torch.load` of the OpenPose `.pth` | Z-Image ControlNet, `pose` control |
| `models/qwen/tokenizer/qwen_vision_language_*.py` | Type check, only if a caller asks for `return_tensors="pt"` | No current call path asks for `"pt"` |
| `models/fibo_vlm/tokenizer/qwen2vl_processor.py` | Same type check | FIBO VLM asks for `"np"`, so this code does not call torch |

Paths are relative to `src/mflux/`.

## What runs without torch

These commands do not need torch, if you do not use a feature from "What needs torch" (for example `--pid-decode`):

- `mflux-generate` (FLUX.1), `-controlnet` (canny), `-fill`, `-redux`, `-kontext`, `-in-context*`, `mflux-concept*`
- `mflux-generate-flux2`, `-flux2-edit`, `-flux3`, `-flux3-edit`
- `mflux-generate-qwen`, `-qwen-edit`, `-qwen-2.1`, `-qwen-2.1-edit`, `-qwen-2.1-controlnet` (you supply a preprocessed control image)
- `mflux-generate-z-image`, `-z-image-turbo`
- `mflux-generate-z-image-controlnet` with `canny` or `mlsd` controls
- `mflux-generate-krea2`, `mflux-generate-krea2-controlnet` with `--depth-image-path`
- `mflux-generate-ernie-image*`, `-ideogram4`, `-lens`, `-ming`, `-iris`, `-boogu`, `-anima`
- `mflux-upscale-seedvr2`, `mflux-upscale-controlnet`
- `mflux-train`, `mflux-save` (for the models above), `mflux-info`, `mflux-check`, `mflux-capabilities`, `mflux-lora-library`
- FIBO, if you load a checkpoint that `mflux-save` wrote. The loader reads the mflux saved format first, and that format uses `mx.load`.

## What needs torch

| Feature | Why |
|---|---|
| `mflux-generate-depth` | It loads Depth Pro (`.pt`) at start, also with `--depth-image-path` |
| `mflux-save-depth` | Depth Pro |
| `mflux-generate-krea2-controlnet` from `--image-path` | Depth Pro estimates the depth map |
| `mflux-generate-z-image-controlnet` with `depth`, `hed` or `pose` | Depth Pro, HED, OpenPose weights are `.pt` / `.pth` |
| `--pid-decode` (any model) | PiD checkpoint is `.pth` |
| `mflux-generate-fibo`, `-fibo-edit` from the original Hugging Face repo | `torch_convert` |
| `mflux-refine-fibo`, `mflux-inspire-fibo` | `torch_bfloat16` |
| `mflux-save` of FIBO or FIBO VLM | It reads the original weights first |

Without torch, these features stop with `ImportError` when they load the weights. Other commands are not affected.

## macOS and Linux/CUDA

`pyproject.toml` lists `torch>=2.13.0,<3.0` for all platforms. The MLX line changes by platform:

- macOS: `mlx>=0.32.0,<0.33.0`
- Linux: `mlx[cuda13]==0.32.2`

On both platforms, MLX does the GPU work. Torch only reads files on the CPU (`map_location="cpu"`). On Linux, the default `pip install torch` downloads the CUDA build with the NVIDIA libraries, which is a large download. MFlux does not use torch CUDA. If you want torch for the features above, the CPU-only wheel is sufficient:

```sh
pip install torch --index-url https://download.pytorch.org/whl/cpu
```

If the CUDA build is already installed, remove it first. `pip uninstall` alone does not install the CPU wheel:

```sh
pip uninstall -y torch && pip install torch --index-url https://download.pytorch.org/whl/cpu
```

## How to install without torch

Torch is a hard dependency, so a normal install pulls it. Two options:

1. Install as usual, then remove torch: `pip uninstall torch`.
2. Install mflux with `--no-deps`, then install the other dependencies from `pyproject.toml` yourself.

After this, the features in "What needs torch" fail, and all other features operate as usual.

---

### Check Model (`docs/check-model.md`)

# Model compatibility check

## Purpose

`mflux-check model` verifies safetensors package structure. For a known MFlux
model layout, it also verifies the required parts for the supported MFlux CLI.
For an unrecognized safetensors layout, `pass` reports only a structural check.

The command supports both Hugging Face safetensors packages and MFlux-saved
packages. A package passes only when MFlux can identify a supported model
layout and all required model parts are available.

## Command interface

```text
mflux-check model <model-reference>
mflux-check model --fix <model-reference>
mflux-check model --base-model <model-name> <model-reference>
```

Examples:

```text
mflux-check model black-forest-labs/flux-3-image-klein
mflux-check model ./models/flux-3-image-klein
mflux-check model mflux-community/qwen-image-edit-2511-mflux-q6
mflux-check model --fix ./models/qwen-image-edit-2511-mflux-q6
mflux-check model --base-model schnell ~/models/my-finetune
```

There is no `--format` option. The command determines the format from the
resolved model package.

Use `--base-model` when the path of a saved package does not identify its
model. `mflux-save` does not write the model name into the files, so the
checker gets the model from the path. The value is the same as the
`--base-model` value of the generate commands.

## Model reference resolution

Resolution follows the existing model path rules:

- An existing local path is a local model package.
- A value in `org/model` form is a Hugging Face repository reference.
- A value that starts with `./`, `../`, or `~/` is always a local path.

For a Hugging Face reference, the normal check reads only the default Hugging
Face cache. It does not download files, contact Hugging Face, or repair the
cache. A missing or incomplete cache is a check failure.

The cache can contain more than one snapshot of a repository. When MFlux pins
the repository to a commit, the checker checks only the snapshot of that
commit, because MFlux loads only that snapshot. When the pinned snapshot is not
in the cache, the check fails. For a repository without a pin, the checker
checks the newest snapshot.

## Format and model identification

The checker reads safetensors headers and tensor key ordering. Hugging Face
safetensors and MFlux safetensors use different key ordering.

The checker must:

1. Find the model safetensors files and their shard index files.
2. Identify the package as MFlux or Hugging Face safetensors.
3. Match the observed layout to a model supported by the MFlux CLI.
4. Determine the components, subdirectories, and shards required for that
   model.

A safetensors package with no known MFlux CLI layout passes the structural
check. The output does not claim that an MFlux CLI can run that package.

## Validation

For both formats, the checker checks:

- Every required component is present.
- Every shard named by a safetensors index exists.
- Index files are readable and name only local shard files.
- Safetensors headers are readable.
- When MFlux recognizes the layout, each package layout matches its supported
  MFlux CLI model.

For MFlux packages, the checker also checks MFlux metadata such as
`mflux_version` and `quantization_level` where required by the format.

The checker counts only model weight files for `size`. It does not count
tokenizer files, configuration files, or duplicate Hugging Face cache blobs.
The displayed unit is decimal `GB`.

## Results

Successful output is concise:

```text
#################
MFlux Check Model:
 check: pass
 format: safetensors
 size: 13.35 GB
```

An incomplete MFlux package reports a warning and gives the repair command:

```text
#################
MFlux Check Model:
 check: warn
 format: mflux
 size: 9.21 GB
 model: flux-3-image-klein
 problem: Missing component: transformer.
 problem: Missing component: vae.
 fix: mflux-check model --fix ./models/flux-3-image-klein
```

A package fails when it cannot run with an MFlux CLI. The failure output must
name the failed check and the specific missing, invalid, or unsupported part.

## Repair mode

`mflux-check model --fix <model-reference>` is available when the checker can
identify an incomplete MFlux package and the exact parts that it requires.
After an attempted repair, it runs the full check again and reports either
`pass` or the remaining problems.

The source and download policy for missing files is not decided yet:

- The normal check is strictly offline and never downloads.
- Repair restores a missing cache shard only when the snapshot entry is a link
  to a missing blob in the same cache repository. The blob name is the SHA-256
  of the file. Repair copies a shard from another local snapshot only when its
  SHA-256 is equal to the blob name.
- Repair does not write through a link that points outside the blobs directory
  of the cache repository.
- Repair does not restore a shard that has no expected hash. Matching tensor
  names do not prove that two revisions contain the same weights.
- Repair of genuinely absent files needs an explicit source policy before
  implementation. It must not silently download files.

---

### Plugins (`docs/plugins.md`)

# Plugins - User Manual

## What is a plugin?

A plugin is an optional package that installs next to mflux. It puts its code under `mflux.extras.<name>` and adds its own commands. The mflux commands do not change.

## Where to find plugins

The Plugins table in the [mflux-plugins README](https://github.com/mflux-community/mflux-plugins/blob/main/README.md) lists each plugin, its commands and its maintainer. Each plugin README tells which mflux versions it works with.

## How to install a plugin

Install mflux and the plugin together with one `uv` command. This example installs `mflux-teacache`:

```sh
uv tool install mflux --with-executables-from mflux-teacache
```

This gives you the mflux commands and the plugin commands side by side. If you install only the plugin with `uv tool install`, uv gives it its own environment with its own mflux. Then only the plugin commands go on your path.

In a Python environment that already has mflux, use pip. The example below installs `mflux-teacache`:

```sh
pip install mflux-teacache
```

For a different plugin, use its package name from the Plugins table linked above.

## How to see the plugin commands

`mflux-capabilities` lists the image commands of all packages in its environment, plugins included. To print only the command names, run:

```sh
mflux-capabilities --format markdown | grep "^## "
```

It lists a command only when the name starts with `mflux-generate`, `mflux-concept` or `mflux-upscale`. Shell completions show only the mflux commands.

## Where to report a problem

Run the plain mflux command with the same options. If it also fails, report the problem in the [mflux issues](https://github.com/mflux-community/mflux/issues). If only the plugin command fails, report it in the [mflux-plugins issues](https://github.com/mflux-community/mflux-plugins/issues).

## How to write a plugin

A plugin uses the command steps of an mflux command. These are the `validate`, `load` and `generate` methods and the `latent_creator` attribute of its command class, for example `ZImageCommand`. Only some mflux commands have them.

Follow these rules:

1. Put your code in one package under `mflux.extras`. Use a name that no other package uses.
2. Do not ship `mflux/__init__.py` or `mflux/extras/__init__.py`. The first file belongs to mflux. The second file hides all other plugins.
3. Call the `build_parser()` function and the command steps of the mflux command. Do not write your own. The guide tells you what to do when a part of `main()` has no step.
4. Test against mflux `main`. The command steps have no stability promise and can change in any release.

The [plugin guide](https://github.com/mflux-community/mflux-plugins/blob/main/docs/writing-a-plugin.md) gives the full procedure. Start from the [plugin template](https://github.com/mflux-community/mflux-plugins/tree/main/template).

---

### Quantization Strategies (`docs/quantization_strategies.md`)

# Quantization by saved model

Models that `mflux-save` can save, except the FLUX.1 and SeedVR2 models. Source: `MODEL_CLASSES` in `src/mflux/models/common/cli/save.py`.


| Line | Model name | TE Q | DiT Q | GS | Text encoder | HS | State(s) Used | FP8 | NVFP4 |
|:---:|---|:---:|:---:|:---:|---|:---:|---|:---:|:---:|
| 1 | `boogu-image-turbo` | ✅ | ✅ | 32 | Qwen3-VL | 4096 | Final |  |  |
| 2 | `ernie-image` | ✅ | ✅ | 64 | Ministral-3 3B | 3072 | Inter -2 |  |  |
| 3 | `ernie-image-turbo` | ✅ | ✅ | 64 | Ministral-3 3B | 3072 | Inter -2 |  |  |
| 4 | `fibo` | ✅ | ✅ | 64 | SmolLM3-3B | 2048 | Inter -2 |  |  |
| 5 | `fibo-edit` | ✅ | ✅ | 64 | SmolLM3-3B | 2048 | Inter -2 |  |  |
| 6 | `fibo-edit-rmbg` | ✅ | ✅ | 64 | SmolLM3-3B | 2048 | Inter -2 |  |  |
| 7 | `fibo-lite` | ✅ | ✅ | 64 | SmolLM3-3B | 2048 | Inter -2 |  |  |
| 8 | `flux2-klein-4b` | ✅ | ✅ | 64 | Qwen3-4B | 2560 | Inter 9, 18, 27 | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-4b-fp8) | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-4b-nvfp4) |
| 9 | `flux2-klein-9b` | ✅ | ✅ | 64 | Qwen3-8B | 4096 | Inter 9, 18, 27 | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-9b-fp8) | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-9b-nvfp4) |
| 10 | `flux2-klein-9b-kv` | ✅ | ✅ | 64 | Qwen3-8B | 4096 | Inter 9, 18, 27 | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-9b-kv-fp8) |  |
| 11 | `flux2-klein-base-4b` | ✅ | ✅ | 64 | Qwen3-4B | 2560 | Inter 9, 18, 27 | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4b-fp8) | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-4b-nvfp4) |
| 12 | `flux2-klein-base-9b` | ✅ | ✅ | 64 | Qwen3-8B | 4096 | Inter 9, 18, 27 | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9b-fp8) | [X](https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9b-nvfp4) |
| 13 | `ideogram-4-fp8` | ✅ | ✅ | 64 | Qwen3-VL FP8 | 4096 | Inter 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 35 | [X](https://huggingface.co/ideogram-ai/ideogram-4-fp8) |  |
| 14 | `krea-2` | ❌ | ✅ | 64 | Qwen3-VL-4B | 2560 | Inter 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 |  |  |
| 15 | `krea-2-raw` | ❌ | ✅ | 64 | Qwen3-VL-4B | 2560 | Inter 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35 |  |  |
| 16 | `ming-image-design` | ✅ | ✅ | 64 | Ling-mini-2.0 MoE | 2048 | Final (layer 20) + Inter 5, 12, 20 |  |  |
| 17 | `qwen-image` | ❌ | ✅ | 64 | Qwen2.5-VL 7B | 3584 | Final |  |  |
| 18 | `qwen-image-2.1` | ❌ | ✅ | 64 | Qwen3-VL | 4096 | Final |  |  |
| 19 | `qwen-image-2.1-controlnet-union` | ✅ | ✅ | 64 | Qwen3-VL | 4096 | Final |  |  |
| 20 | `qwen-image-edit` | ❌ | ✅ | 64 | Qwen2.5-VL 7B | 3584 | Final |  |  |
| 21 | `qwen-image-edit-2511` | ❌ | ✅ | 64 | Qwen2.5-VL 7B | 3584 | Final |  |  |
| 22 | `z-image` | ✅ | ✅ | 64 | Qwen3 | 2560 | Inter -2 |  |  |
| 23 | `z-image-turbo` | ✅ | ✅ | 64 | Qwen3 | 2560 | Inter -2 |  |  |
| 24 | `z-image-turbo-controlnet-union-2.1` | ✅ | ✅ | 64 | Qwen3 | 2560 | Inter -2 |  |  |

**Legend:**
- ✅ means `-q` quantizes the component.
- ❌ means the model keeps the component in BF16 (`skip_quantization=True`).

- `GS` is the affine group size that `-q` uses.
- `HS` is the hidden size of the text encoder.
- `FP8` and `NVFP4` link to a release of that model by its original authors on Hugging Face. A blank cell means no such release was found. Community conversions are not listed.
- `Final` means the last hidden state. `Inter` means intermediate hidden states. Numbers are layer indexes. `-2` means the second from last.


**Notes:**
- `ming-image-design` takes a separate `--text-encoder-quantize` flag for the text encoder. It falls back to `-q`.
- `lens-turbo` is not in the table. `mflux-save` cannot save it. Its DiT takes `-q`. Its GPT-OSS encoder ships pre-quantized.
- `qwen-image-2.1` (text-to-image) skips the text encoder. The `qwen-image-2.1-controlnet-union` model does not skip it.
- Each ✅ means the component can be quantized. Some layers inside it stay in full precision.
- Black Forest Labs also publishes `FLUX.2-dev-NVFP4`. It is not a saveable model here, so it has no row.
- Third-party FP8 and NVFP4 builds of Z-Image-Turbo, ERNIE-Image, Qwen-Image and Ideogram 4 exist. They are not listed.
- The FP8 and NVFP4 links come from a web search. Nobody checked the linked pages.

---

### Schedulers (`docs/schedulers.md`)

# Schedulers - User Manual

## What is a scheduler?

A scheduler decides how the model removes noise at each step. Most users do not need to change it. The default for each model gives good results.

## How to use it

Add `--scheduler` to a generate command:

```sh
mflux-generate-krea2 --prompt "a chrome teapot" --steps 8 --scheduler euler -q 8
```

## Which values you can use

| Model | Values | Default |
| --- | --- | --- |
| FLUX.1 | `linear`, `flow_match_euler_discrete` | `linear` |
| Qwen Image, Qwen Image Edit | `linear`, `flow_match_euler_discrete` | `linear` |
| Qwen Image 2.1 (generate) | `linear`, `flow_match_euler_discrete`, `viggle_turbo` | `linear` |
| Qwen Image 2.1 (edit) | `linear`, `viggle_turbo` only | `linear` |
| Z-Image (base command, including `--model z-image-turbo`) | `linear`, `flow_match_euler_discrete` | `flow_match_euler_discrete` |
| Z-Image Turbo (dedicated command) | `linear`, `flow_match_euler_discrete` | `linear` |
| ERNIE-Image | `linear`, `flow_match_euler_discrete` | `linear` |
| Krea 2 | `er_sde`, `euler` | `er_sde` |
| Anima | `er_sde`, `euler` | `er_sde` |

Other models set the scheduler for you: FLUX.2, FIBO, Ideogram 4, SeedVR2, Lens, Ming-Image and Boogu Image. Lens, Ming-Image and Boogu Image ignore `--scheduler`. Lens and Ming-Image show a warning. Boogu Image shows no warning. FLUX.2 and FIBO commands also use their own scheduler.

Ideogram 4 has `--preset`. It selects the step count and noise schedule. Ideogram 4 does not use the `linear` scheduler.

## What the values mean

- `linear`: the standard schedule. Use it unless you have a reason not to.
- `flow_match_euler_discrete`: a different noise schedule for flow-match models.
- `er_sde`, `euler`: two samplers for Krea 2 and Anima. `er_sde` is the default.
- `viggle_turbo`: for the Viggle turbo LoRA on Qwen Image 2.1. Use `--steps 6` and `--lora-paths` with the turbo LoRA. Other step counts give an error.

## Use your own scheduler

A developer can write a scheduler class. You then pass its full Python path:

```sh
mflux-generate --prompt "a lighthouse" --scheduler my_package.my_module.MyScheduler
```

The package must be installed in the same Python environment as MFLUX.

## Errors

- `The scheduler 'x' is not implemented by mflux.`: the name is wrong. Check the table above.
- `viggle_turbo ... --steps`: the step count is not 6. Set `--steps 6`.
- The help text for `--scheduler` says "linear only for now". That text is out of date.

---

### Validate Load Generate (`docs/validate-load-generate.md`)

# The validate, load and generate command steps

## Why plugins need three steps

A plugin cannot call `main()` of an mflux command. `main()` parses `sys.argv`, loads the model, generates the images and saves them in one function. A plugin must change one part of this flow and keep the other parts.

For this reason, a command that supports plugins puts its work in a command class, for example `QwenImageCommand`. The class has three static methods and one attribute:

| Member | Input | Output |
|---|---|---|
| `validate(args)` | parsed arguments | `ModelConfig` |
| `load(args)` | parsed arguments | the model object |
| `generate(model, args, seed, prompt)` | model, arguments, one seed, one prompt | `GeneratedImage` |
| `latent_creator` | not applicable | the latent creator class for callbacks |

`main()` of the command uses these same steps. Thus a plugin and the mflux command run the same code.

## validate

This step examines the request before the model loads. It does not read weights, so it is fast.

It does these tests:

1. It resolves `--model` against the model registry. It accepts only the models that this command can run. A wrong model name fails here.
2. Some commands also test the arguments. For example, some flags must occur together. The width and height must be multiples of 32. The output format must keep transparency.

It returns the `ModelConfig`. If a test fails, it raises an error.

## load

`load` makes the model object. It calls `validate` first, then gives the `ModelConfig` to the model class. It also gives the quantization, the model path, the LoRA arguments and, for some models, the compute precision.

This step reads the weights into memory. It is the slow step and uses the most memory. Call it one time and use the model again for each image.

There is one exception. If you register the callbacks with one seed and `--low-ram` or `--pid-decode`, the memory saver removes the transformer after the image. Call `load` again before the next `generate`.

Usually the model has three components:

- The text encoder. It changes the prompt into embeddings.
- The transformer. This is the diffusion model. It removes noise from the latents at each step.
- The VAE. It decodes the latents into the image.

Some models have more components. For example, FLUX.1 has two text encoders, an edit model has a vision encoder, and a ControlNet model has a ControlNet.

The load step does these tasks in this sequence:

1. It reads the weight files.
2. It loads the tokenizers.
3. It makes the components.
4. It puts the weights into the components. If you give `--quantize`, it quantizes them.
5. If you give `--lora`, it applies each LoRA to the transformer. By default, it merges the LoRA into the weights. Use `--no-bake-lora` to keep the LoRA separate. MOSS-Image keeps the LoRA separate by default. Use `--bake-lora` to merge it.

## generate

`generate` makes one image from one seed and one prompt. It reads the other settings from `args`, for example the size, the steps, the guidance, the negative prompt and the input image paths. Then it calls `model.generate_image()` and returns a `GeneratedImage`.

`generate` applies the command defaults itself, for example the guidance value or the image size from a reference image. Thus a plugin that calls `generate` directly gets the same result as `main()`.

`generate` does not save the image. The caller saves it.

## How main() uses the steps

```python
model = QwenImageCommand.load(args)          # validate runs inside load
memory_saver = CallbackManager.register_callbacks(
    args=args, model=model, latent_creator=QwenImageCommand.latent_creator
)
for seed in args.seed:
    image = QwenImageCommand.generate(model, args, seed, PromptUtil.read_prompt(args))
    image.save(path=args.output.format(seed=seed), export_json_metadata=args.metadata)
```

A plugin follows the same order. It can add work between the steps, or replace one step.

## Stability

The command steps have no stability promise. They can change in any mflux release. Test each plugin against mflux `main`. See [plugins.md](plugins.md) for the plugin rules.

---

### Ci Ci Extract Models (`docs/ci/ci-extract-models.md`)

# CI Extract Models

The CI processes need to know _**what models MFlux supports**_ - so we have set up;

**[https://huggingface.co/buckets/mflux-community/ci/tree/models_mflux.json](https://huggingface.co/buckets/mflux-community/ci/tree/models_mflux.json)**

This JSON data file is updated automatically by a GitHub Workflow (`.github/workflows/ci-extract.yml`) which runs when a new main branch is merged to MFlux.

**`just ci-extract`** is a CLI command runner that calls `scripts/ci_extract_models.py` to generate the JSON data file **`.ci_cache/models_mflux.json`**

Developers can manually run the GitHub Action on their own private GitHub account to push the JSON manifest to a dev directory on HuggingFace - eg [https://huggingface.co/buckets/mflux-community/ci/dev/@ianscrivener/tree/models_mflux.json](https://huggingface.co/buckets/mflux-community/ci/dev/@ianscrivener/tree/models_mflux.json).

Developers will need to set up a GitHub Secret `HF_CI_BUCKET_TOKEN` in order to push to HuggingFace.

---

### Development Claude Setup (`docs/development/Claude-setup.md`)

# Claude Setup

### *...separating shared MFlux Claude files from personal Claude files!*
<br><br>

### Claude Code Scopes
Claude Code separates shared files from personal files by file name and location. Git decides which files other developers get:

|Scope|Files|Committed?|
|---|---|---|
|**Shared (project)**<br><br><br>|`AGENTS.md`,<br>`.claude/settings.json`,<br>`.claude/skills/`|Yes|
|**Personal, this project only**<br><br><br>|`CLAUDE.md`,<br>`CLAUDE.local.md`,<br>`.claude/settings.local.json`|No (gitignored)|
|**Personal, all projects**<br><br><br>|`~/.claude/CLAUDE.md`,<br>`~/.claude/skills/`,<br>`~/.claude/settings.json`|Not in the repo|

- This repo ignores `CLAUDE.md`. Put shared agent rules in `AGENTS.md`.
- This repo also ignores `.claude/agents/` and `.mcp.json`. To share one of them, add a `!` rule to `.gitignore`.


### Skills
Each folder in `.claude/skills/` is a symlink to a folder in `.cursor/skills/`. Edit the skill in `.cursor/skills/`. Cursor and Claude Code then read the same file.

To add a skill:
1. Create `.cursor/skills/<name>/SKILL.md`.
2. Make the symlink: `ln -s ../../.cursor/skills/<name> .claude/skills/<name>`.


### Personal scratch files
Add personal files that are not Claude files to `.git/info/exclude`. Git reads this file only on your computer. Other developers do not get it. Example: `z*.*`.


### `.gitignore` setup

Git reads `#` as a comment only at the start of a line. Thus each comment is on its own line.

```
# Ignore the whole .claude directory by default.
.claude/*
# Share the skills.
!.claude/skills/
# Share the settings.
!.claude/settings.json
# Ignore the personal settings.
.claude/settings.local.json
# Ignore the GitNexus skills that `gitnexus analyze` makes.
.claude/skills/gitnexus-*/
# Ignore CLAUDE.md. Use AGENTS.md for shared rules.
CLAUDE.md
# Ignore the personal agent instructions.
CLAUDE.local.md
# Ignore the PR files that /mflux-pr-docs makes.
tmp-PR-content.md
tmp-PR-body.md
```

### Sources
- [Claude Code settings](https://code.claude.com/docs/en/settings.md)
- [Explore the .claude directory](https://code.claude.com/docs/en/claude-directory)

---

### For Ai Agents Quantization (`docs/for_ai_agents/quantization.md`)

# Quantization in MFlux (reference for AI agents)

Scope: diffusion transformers (DiT) and text encoders. This file does not cover depth, upscale (SeedVR2), Redux, or ControlNet internals, except where noted.

Verified against: MLX 0.32.0 (`pyproject.toml` pins `mlx>=0.32.0,<0.33.0` on macOS), git commit `02bbe7b` (#844, 2026-10-08). Paths are relative to `src/mflux/` unless noted.

## 1. Short answers

| Question | Answer |
|---|---|
| Are all weights quantized equally? | No. A module must expose `to_quantized` and pass the model-family predicate. `nn.Linear` and `nn.Embedding` are examples. A predicate can return a per-layer override (Qwen-Image keeps `img_mod_linear` at 8-bit when the request is 4-bit). |
| Is there activation quantization (W4A8 style)? | No. MFlux does weight-only quantization. `quantize_input` stays `False` in every call. `Fp8Linear.to_quantized` raises `ValueError` if `quantize_input=True`. |
| Which text encoders stay in BF16? | Qwen-Image 1.x, Qwen-Image-2.1 txt2img, Krea 2. These set `skip_quantization=True` on the component. Section 6 has the full table. Section 11 has the per-model matrix. |
| Why do they stay in BF16? | Code comments only: "Quantization causes significant semantic degradation" (Qwen) and "quantizing the TE degrades conditioning" (Krea 2). No measurement or issue number is in the repo for these flags. |
| Who decides? | The model author, in the `ComponentDefinition` of the family. The user cannot override it with a flag. |
| Lower limit on bits? | CLI accepts `-q 3, 4, 5, 6, 8`. No code blocks a text encoder from Q3. MLX itself accepts 2, 3, 4, 5, 6, 8 bits. See section 4. |
| Only affine quantization? | MFlux code paths use `mode="affine"` (the MLX default). One exception: the Lens GPT-OSS encoder reads `mode` from its own checkpoint config (MXFP4 experts). |
| NVFP4 support? | No. `nvfp4` appears nowhere in `src/`. MLX 0.32.0 supports it, but MFlux has no flag, no code, and no layout inference for it. |

## 2. Core mechanism

All quantization goes through `nn.quantize(model, class_predicate=..., bits=..., group_size=...)` from MLX. The wrapper is `WeightApplier` in `models/common/weights/loading/weight_applier.py`.

- `WeightApplier.apply_and_quantize(weights, models, quantize_arg, weight_definition)` handles multi-component models.
- `WeightApplier.apply_and_quantize_single(...)` handles one component. Lens and the Z-Image ControlNet use it. The Qwen-Image-2.1 ControlNet calls `nn.quantize` directly.
- `nn.quantize` quantizes a module only if it exposes `to_quantized` and the predicate accepts it. `nn.Linear` and `nn.Embedding` are examples.
- `nn.Linear` and `nn.Embedding` have `to_quantized`. `nn.Conv2d`, `LayerNorm` and `RMSNorm` do not (checked in the project venv).
- A quantized layer stores `weight` (packed `uint32`), `scales`, and `biases` (affine). A linear layer's own `bias` stays in the model dtype.
- `group_size` defaults to 64. Only `BooguWeightDefinition` overrides it (`quantization_group_size = 32`, because its 3360-wide linears do not divide by 64).
- The call sites never pass `mode=`. MLX defaults to `affine`.
- `mx.quantize` needs the last dimension divisible by `group_size`. A layer that does not divide makes the load fail, unless the predicate skips it (section 5).
- Quantization is lazy. Parameters are read and quantized when a forward pass first needs them (see `Qwen21Initializer.load_components`).

### 2.1 Entry points

| Source | Where |
|---|---|
| CLI `--quantize` / `-q` | `cli/parser/parsers.py` lines 156 and 253. `choices=ui_defaults.QUANTIZE_CHOICES`. |
| Choices list | `cli/defaults/defaults.py:64`, `QUANTIZE_CHOICES = [3, 5, 4, 6, 8]` |
| Python API | `quantize=<int>` on each model class, for example `ZImageTurbo(quantize=8)`. MFlux does not check the value. MLX raises if bits is not in 2, 3, 4, 5, 6, 8. |
| Save | `mflux-save` (`models/common/cli/save.py`) loads with `quantize=args.quantize`, then calls `ModelSaver.save_model`. |
| Training | `training_spec.quantize` goes to the model constructor (`models/common/training/runner.py`). The base is quantized and only the LoRA trains (QLoRA). |

## 3. Resolution of stored versus requested bits

`models/common/resolution/quantization_resolution.py`. `QuantizationResolution.resolve(stored, requested)` returns `(bits, warning)`.

| stored | requested | Rule | Result |
|---|---|---|---|
| None | None | `none` | No quantization. |
| None | N | `on_the_fly` | Quantize at N bits. |
| S | None | `pre_quantized` | Use S. |
| S | N | `conflict` | Use S. If S differs from N, print `Model is pre-quantized at S-bit. Ignoring -q N flag.` |

`stored` comes from safetensors metadata (`quantization_level`, a string) or from `model.safetensors.index.json` (`weight_loader.py` around line 265). A save writes one level per component directory (`model_saver.py:_save_weights`).

### 3.1 Three load flows in `apply_and_quantize`

1. `bits is None`: `_set_weights` only. Weights load as saved (BF16, or FP8 for Ideogram).
2. `stored is None` and `bits` set (on-the-fly): `_set_weights` first, then `_quantize`. The full-precision weights load, then MLX quantizes them.
3. `stored` set (pre-quantized checkpoint): `_quantize` first on the empty skeleton, then `_set_weights`. The skeleton must have the same layer types as the file, so the file's packed tensors fit.

### 3.2 Per-layer layout recovery (`_stored_layer_predicate`)

For a pre-quantized checkpoint, the predicate does not trust the global level. It reads each layer's stored tensors:

- `bits = stored_weight.shape[-1] * 32 / input_dims`
- `group_size = input_dims / scales.shape[-1]`
- If `{bits, group_size}` is in `{2, 3, 4, 5, 6, 8}` x `{32, 64, 128}`, it returns `{"bits": b, "group_size": g}` for that layer.
- If the layer has no `scales` in the file, the layer stays unquantized (`return False`).
- If the numbers do not match a known pair, it prints a warning and falls back to the requested level. `update()` may then reject the shapes.

This is how mixed-precision files reload. The metadata holds one number. The shapes hold the truth per layer.

The inference assumes the affine layout. It does not read or pass `mode`. An MXFP4 or NVFP4 layer saved by MFlux would not round-trip (MFlux never saves one).

## 4. Bit-width limits

| Layer | Limit | Source |
|---|---|---|
| CLI | 3, 4, 5, 6, 8 | `QUANTIZE_CHOICES` |
| Resolution tests | 3, 4, 5, 6, 8 | `tests/resolution/test_quantization_resolution.py` |
| Layout inference | 2, 3, 4, 5, 6, 8 bits and group 32, 64, 128 | `_INFERABLE_BITS`, `_INFERABLE_GROUP_SIZES` |
| MLX affine | 2, 3, 4, 5, 6, 8 | Verified: `mx.quantize(..., bits=1)` and `bits=7` raise. Bits 2, 3, 5 work. |

- No code forces a text encoder to stay at 8-bit or above. If a text encoder is not skipped, it receives the same `bits` as the transformer.
- 2-bit is reachable only through the Python API. The CLI rejects it, and no test covers it.
- Quality guidance is in READMEs only. `models/qwen/README.md` says 6-bit or below can degrade the image much more than FLUX.
- Ming Image is the exception: `--text-encoder-quantize` sets the text encoder level apart from `-q` (`ming_image_initializer.py` line 77). If you omit it, `-q` applies.
- Otherwise the same level applies to all quantized components in a run. `Qwen21Initializer.load_components` raises `ValueError` if two components resolve to different levels (`Conflicting component quantization levels`).

## 5. Which layers inside a component are quantized

A layer is quantized only if it has `to_quantized` and the family predicate accepts it. `nn.Linear` and `nn.Embedding` are examples. Default predicate: `hasattr(module, "to_quantized")`.

Always unquantized: convolutions, norms, positional or rotary buffers, scalar parameters, and the `bias` vector of a linear layer. Embeddings are quantized (`embed_tokens` in a text encoder) unless the predicate or the component skip blocks them.

| Family | Predicate behavior | File |
|---|---|---|
| FLUX.1, FLUX.2 Klein, Z-Image, Ernie, Boogu, Lens DiT, Ideogram 4 | Default. Every Linear and Embedding. | `*_weight_definition.py` |
| Qwen-Image 1.x (and edit) | Default, plus a 3-argument form `predicate(path, module, bits)`. If `bits == 4` and `".img_mod_linear"` is in the path, return `{"bits": 8}`. This is mixed precision. The reason is in the comment: adaLN modulation error grows over the denoising steps at 4-bit (issue #484). | `qwen/weights/qwen_weight_definition.py` |
| Qwen-Image-2.1 txt2img (`Qwen21WeightDefinition`) | Default. | `qwen21/weights/qwen21_weight_definition.py` |
| Qwen-Image-2.1 edit and ControlNet (`QwenImage21WeightDefinition`) | Linear/Embedding only if `weight.shape[-1] % 64 == 0` and the path does not contain `modulation`, `time_text_embed`, or `norm_out`. | `qwen21/weights/qwen_image21_weight_definition.py` |
| Krea 2 | Skip any layer whose last dimension is not divisible by 64 (for example the `txtfusion` projector, Linear 12 to 1). | `krea2/weights/krea2_weight_definition.py` |
| FIBO | Skip Conv2d, shape `(1152, 4304)`, and last dimension not divisible by 64. | `fibo/weights/fibo_weight_definition.py` |
| FIBO VLM | Skip any path containing `lm_head`. | `fibo_vlm/weights/fibo_vlm_weight_definition.py` |
| Ming Image | Default. Routers stay full precision because gate modules have no `to_quantized`. | `ming_image/weights/ming_image_weight_definition.py` |
| Redux | Skip Conv2d, shape `(1152, 4304)`, and last dimension not divisible by 64. | `flux/weights/flux_weight_definition.py` |

The 3-argument predicate form is detected with `inspect.signature` in `WeightApplier._predicate_with_bits`. Keyword-only third parameters do not count.

A predicate may return `True`, `False`, or a dict such as `{"bits": 8}` (and `group_size`). MLX treats a dict as the per-layer override.

### 5.1 VAE note (from code reading, not run)

Flux, Flux2, and Z-Image pass `"vae"` in the `models` dict. Their VAE attention blocks use `nn.Linear(512, 512)` (`flux_vae/common/attention.py`, `flux2_vae/common/attention.py`, `z_image_vae/common/attention.py`). The default predicate accepts them, and 512 divides by 64. So these few linear layers appear to be quantized with the DiT. All VAE convolutions stay unquantized. `QwenImage21WeightDefinition` sets `skip_quantization=True` for its VAE and uses FP32.

## 6. Component-level skip (`skip_quantization`)

Defined in `ComponentDefinition` (`models/common/weights/loading/weight_definition.py`, default `False`).

| Component | Skipped? | Comment in code |
|---|---|---|
| Qwen-Image 1.x text encoder (Qwen2.5-VL) | Yes | "Quantization causes significant semantic degradation" |
| Qwen-Image-2.1 txt2img text encoder (Qwen3-VL) | Yes | Same comment |
| Krea 2 text encoder | Yes | "quantizing the TE degrades conditioning" |
| Ming Image `heads` | Yes | "~30M params that feed the DiT directly" |
| Qwen-Image-2.1 edit/ControlNet VAE | Yes | none |
| FLUX.1 T5 and CLIP | No | |
| FLUX.2 Klein text encoder (Qwen3) | No | |
| Z-Image text encoder | No | |
| Ernie text encoder | No | |
| Boogu text encoder (Qwen3-VL language model) | No | |
| Ming Image text encoder (`mllm`) and connector | No | |
| FIBO text encoder | No | |
| Ideogram 4 text encoder (FP8 layers) | No. `Fp8Linear.to_quantized` converts it. | |
| Qwen-Image-2.1 **edit** text/vision encoder | No. `reference/README.md` says eligible encoder layers quantize. | |
| Lens GPT-OSS encoder | Not applicable. It never enters `WeightApplier`. | |

Inconsistency to know: Qwen-Image-2.1 txt2img keeps the text encoder in BF16, but the 2.1 edit and ControlNet definitions do not set the flag. `qwen21/README.md` says the text encoder "is never quantized". `qwen21/reference/README.md` says eligible text/vision encoder layers quantize. The code follows the second statement for edit.

Why the skip exists: the repo gives no measurement. Both `qwen/README.md` and `qwen21/README.md` state that `-q` does not shrink the encoder (about 14 to 17.5 GB stays resident). The flag came with the Z-Image and Qwen work (`git log -S skip_quantization` shows `37d202d` for Qwen).

### 6.1 Skip with a pre-quantized checkpoint

`_quantize` (multi-component models) treats `skip_quantization` as "do not quantize BF16 weights on load". It does not block a checkpoint that already ships quantized tensors for that component:

- Component has stored weights: the stored-layout predicate builds quantized modules where `scales` exist. Layers without `scales` stay Linear.
- Component has no weights in the file: the skip holds.
- `mflux-save -q 8` on Qwen writes the text encoder in BF16. It reloads as BF16.

`apply_and_quantize_single` (Lens, Z-Image ControlNet) is different. If `skip_quantization` is set, it never calls `nn.quantize`, also for a pre-quantized checkpoint. The layers stay Linear.

Test: `tests/weights/test_skip_quantization_prequantized.py`.

## 7. Special paths

### 7.1 Ideogram 4 (FP8 source)

- Components load with `loading_mode="fp8_safetensors"`. Layers are `Fp8Linear` (`ideogram4/model/ideogram4_transformer/fp8_linear.py`): `uint8` weight plus a per-row `float32` `weight_scale`, dequantized in every forward with `mx.from_fp8`.
- `Fp8Linear.to_quantized(group_size, bits, mode="affine", quantize_input=False)` makes `nn.quantize` reach these layers. Weights already loaded: dequantize through the row scale, then `mx.quantize`. Weights not loaded (skeleton for a saved checkpoint): return an empty `QuantizedLinear`.
- `Ideogram4Initializer._rebuild_q8_folded_layers` rebuilds layers that a LoRA bake or a save already turned into quantized form, inferring bits and group size from shapes.
- On-disk size: FP8 26 GB, `-q 8` 26 GB, `-q 4` 14 GB (`ideogram4/README.md`).
- Tests: `tests/test_ideogram4_quantization.py`, `tests/image_generation/test_ideogram4_quantized_roundtrip.py`.

### 7.2 Lens

- DiT: `apply_and_quantize_single` with `LensWeightDefinition.quantization_predicate`. The `-q` flag affects only this part.
- Text encoder: `LensGptOssEncoder` (`lens/model/text_encoder/lens_gpt_oss_encoder.py`) loads `mlx-community/gpt-oss-20b-MXFP4-Q8`. It reads `config["quantization"]`, then calls `nn.quantize(..., group_size, bits, mode=quantization.get("mode", "affine"))`. A path listed in the config uses its own settings (MXFP4 experts, Q8 elsewhere). `-q` has no effect on it.
- This is the only place in `src/` where a non-affine mode can run, and it follows the checkpoint, not an MFlux option.

### 7.3 ControlNets

- Qwen-Image-2.1 ControlNet: `nn.quantize(model.controlnet, bits=model.bits, class_predicate=QwenImage21WeightDefinition.quantization_predicate)`. A saved ControlNet with a different level than the base raises `ValueError`.
- Z-Image ControlNet: `apply_and_quantize_single` with its own predicate.

### 7.4 LoRA on quantized bases

- Runtime LoRA layers wrap `nn.QuantizedLinear` (`lora/layer/linear_lora_layer.py`). The base stays quantized. The delta stays dense.
- Bake (default) merges the delta into the weight. For a quantized base, `LoRASaver` dequantizes, merges, and requantizes (`lora/mapping/lora_saver.py`).
- Bake into a 4-bit (or lower) layer upgrades that layer to 8-bit with group size 64. Reason: at 4-bit the quantization step is larger than a small delta, so the delta disappears (issue #665). Test: `tests/lora/test_bake_low_bit_quantized.py`. Order test: `tests/lora/test_bake_folds_before_quantizing.py`.
- Result: after a bake, a "4-bit" model can hold some 8-bit layers. The layout recovery in section 3.2 handles this on reload.

### 7.5 Compute precision

`ComputePrecision` (`models/common/compute_precision/compute_precision.py`) casts attention and feed-forward parameters to float16. It runs after quantization and LoRA. Float activations against BF16 quantization scales would promote `quantized_matmul` to float32. `ComputePrecision.ensure_savable` blocks `mflux-save` for such a model. It is separate from bit-width quantization.

## 8. Saving and reloading

- `ModelSaver.save_model(model, bits, base_path, weight_definition)` writes each component in 2 GB shards (`{i}.safetensors`) with metadata `quantization_level` and `mflux_version`. It also writes `model.safetensors.index.json` with the same metadata.
- Saved parameters are the post-quantization tree: packed `weight`, `scales`, `biases` for quantized layers, plain tensors for the rest. A skipped component is saved in BF16 but is stamped with the same `quantization_level`.
- Loading a saved model with `-q N` ignores N and prints the conflict warning (section 3).
- Models saved with MFlux before v0.6.0 do not load. Re-save them (`models/common/README.md`).

## 9. Invariants for agents who change this code

1. Add a new family: write `quantization_predicate` in its `*WeightDefinition`. Skip layers where `weight.shape[-1] % group_size != 0`. Otherwise the load fails inside `mx.quantize`.
2. Add a text encoder skip: set `skip_quantization=True` on its `ComponentDefinition`. Add a comment with the evidence. Pre-quantized files still work (section 6.1).
3. Use a dict return (`{"bits": 8}`) for per-layer precision. Use the 3-argument predicate form if it depends on the requested level. Saves from before the change still load because of section 3.2.
4. Do not pass `mode=` or `quantize_input=True` to `nn.quantize` without changing `_stored_layer_predicate`, `Fp8Linear`, and `LoRASaver`. All three assume affine, weight-only layouts.
5. To add NVFP4 or MXFP4, add a `mode` option to the CLI, `WeightApplier._quantize`, the layout inference, the metadata, `LoRASaver`, and the tests. Nothing of this exists now. The scale layout differs from affine: MLX 0.32.0 gives `uint8` scales and no `biases`. NVFP4 uses group size 16. MXFP4 uses group size 32.
6. `QUANTIZE_CHOICES` is the only CLI gate on bits. The Python API has no gate besides MLX.

## 10. Quick lookup

| Task | Where |
|---|---|
| Change the allowed `-q` values | `cli/defaults/defaults.py:64` |
| Find why a layer is not quantized | The family predicate in `models/<family>/weights/*_weight_definition.py` |
| Find why a component is not quantized | `skip_quantization` in the same file |
| Change group size for a family | `quantization_group_size` class attribute (Boogu example) |
| Resolve a stored versus requested conflict | `models/common/resolution/quantization_resolution.py` |
| Debug a shape error on reload | `WeightApplier._stored_layer_predicate` warning text |
| Fast tests | `tests/resolution/test_quantization_resolution.py`, `tests/weights/test_skip_quantization_prequantized.py`, `tests/test_qwen_mixed_q4.py`, `tests/test_ideogram4_quantization.py` |

## 11. Per-model matrix (canonical copy: `docs/quantization_strategies.md`)

`docs/quantization_strategies.md` holds the maintained table (one row per model that `mflux-save` can save, FLUX.1 and SeedVR2 rows removed by request). Columns: TE Q, DiT Q, GS (group size), text encoder, HS (hidden size), tapped hidden states. Summary of what is in it:

| Text encoder | Models | HS | Quantized by `-q`? | Hidden states read |
|---|---|---|---|---|
| Qwen2.5-VL 7B | qwen-image, qwen-image-edit, qwen-image-edit-2511 | 3584 | No (skip) | Final |
| Qwen3-VL (8B-class) | qwen-image-2.1 | 4096 | No for txt2img (skip). Yes for the ControlNet-union definition. | Final |
| Qwen3-VL-4B | krea-2, krea-2-raw | 2560 | No (skip) | 12 taps: 2, 5, ... 35 |
| Qwen3-VL (FP8) | ideogram-4-fp8 | 4096 | Yes (FP8 converted to affine) | 13 taps: 0, 3, ... 33, 35 |
| Qwen3-VL | boogu-image-turbo | 4096 | Yes, group size 32 | Final |
| Qwen3-4B | flux2-klein-4b, flux2-klein-base-4b | 2560 | Yes | Layers 9, 18, 27 |
| Qwen3-8B-sized | flux2-klein-9b, 9b-kv, base-9b | 4096 | Yes | Layers 9, 18, 27 |
| Qwen3 | z-image, z-image-turbo, z-image-turbo-controlnet-union-2.1 | 2560 | Yes | Second from last |
| Ministral-3 3B | ernie-image, ernie-image-turbo | 3072 | Yes | Second from last |
| SmolLM3-3B | fibo, fibo-lite, fibo-edit, fibo-edit-rmbg | 2048 | Yes | Second from last |
| Ling-mini-2.0 MoE | ming-image-design | 2048 | Yes, with its own `--text-encoder-quantize` | Layer 20 (final) plus layers 5, 12, 20 (DirectVLM) |
| T5-XXL + CLIP-L | FLUX.1 family (dev, schnell, krea-dev, kontext, fill, depth, redux, controlnets) | 4096 / 768 | Yes (both) | T5 final after final layer norm. CLIP pooled at the EOS token. |
| GPT-OSS 20B (MXFP4-Q8, pre-quantized) | lens-turbo (not saveable) | n/a | Not applicable | Layers 5, 11, 17, 23, no final norm |

Hidden sizes come from constructor defaults in each encoder class, except the FLUX.1 values (standard T5-XXL and CLIP-L sizes, not read from the repo). Qwen3-4B and Qwen3-8B names for Klein are inferred from `text_encoder_overrides` in `model_config.py` (hidden 2560/inter 9728 and hidden 4096/inter 12288). The repo does not name those sizes.

## 12. Hidden-state tap styles

Three styles exist in the encoders:

1. **Final**: last layer output (Qwen-Image 1.x, Qwen-Image-2.1, Boogu, T5).
2. **Single intermediate**: second from last layer (Z-Image `all_hidden_states[-2]`, Ernie layer `num_hidden_layers - 2`, FIBO `hidden_states_list[-2]`).
3. **Multi-layer stack**: several layers concatenated or stacked (Klein 9, 18, 27. Krea 2 twelve taps. Ideogram 4 thirteen taps. Lens four taps. Ming 5, 12, 20).

Relevance to quantization:
- The skip flag does not follow the tap style. Qwen 1.x and 2.1 (final) and Krea 2 (12 taps) are skipped. Klein, Ideogram (multi-tap) and Z-Image (single) are quantized.
- Hypothesis, not tested in this repo: quantization error accumulates with depth, so any style that reads late layers sees the sum of all earlier layers' error. Multi-tap styles also expose early-layer error directly.
- When you tap layers `k < N`, layers after the last tap run but their output is unused for that tap (Z-Image, Ernie, FIBO read layer `N-2`, so the last layer's weights affect nothing). Quantizing them gains memory and loses nothing. This is an inference from the code, not a measured result.

## 13. Ernie text encoder identity and drop-in rules

Findings from the repo and the web (checked 2026-10-08):

- `ErnieMistralTextEncoder` (`ernie_image/model/ernie_text_encoder/text_encoder.py`) is a text-only decoder: 26 layers, hidden 3072, 32 heads, 8 KV heads, head dim 128, MLP 9216, vocab 131072, rope theta 1e6, max positions 262144.
- `ErnieWeightDefinition` loads `text_encoder/` with `weight_prefix_filters=["language_model.model."]` and no key mapping. The vision tower in the file is ignored.
- `baidu/ERNIE-Image/text_encoder/config.json`: architecture `Mistral3Model`, `model_type: mistral3` (text `ministral3`, vision `pixtral`), hidden 3072, 26 layers, 32 heads, intermediate 9216, vocab 131072, RoPE type **YARN** with theta 1e6, bfloat16, vision tower 24 layers, no `_name_or_path`.
- ComfyUI docs list `ministral-3-3b.safetensors` (repo `Comfy-Org/ERNIE-Image`) as the ERNIE-Image text encoder.
- Baidu's model card says nothing about the text encoder. No source states whether the weights are stock, base or instruct, or fine-tuned.

Drop-in rules for a Ministral-3 VLM checkpoint:
1. Shapes must match the constants above, or the load fails.
2. Text keys must sit under `language_model.model.`. Other layouts need a key mapping (none exists).
3. The tokenizer must match. Ernie ships its own `tokenizer/` folder.
4. The DiT was trained on one set of features. Any other fine-tune (base versus instruct) gives off-distribution features even when shapes match.
5. Possible mismatch in MFlux: the config says YARN RoPE but the class computes plain RoPE (`inv_freq = 1 / theta^(...)`, lines 139 to 144). Effect on short prompts is untested.

Cheap verification that loads no model: compare safetensors headers (key names and shapes), then tensor hashes, against the `mistralai` Ministral-3 3B release.

## 14. Group size summary

| Case | Group size |
|---|---|
| Default | 64 (`_quantize` passes 64. `apply_and_quantize_single` passes none, so MLX uses 64) |
| Boogu | 32 (whole model) |
| LoRA bake into layer < 8-bit | 64, layer becomes 8-bit |
| LoRA bake into 8-bit layer | the layer's own group size |
| Pre-quantized checkpoint | stored size, inferred as 32, 64 or 128 |
| Lens GPT-OSS encoder | from checkpoint `config.json` (value not checked) |

MFlux never sets a per-layer group size when quantizing. Mixed group sizes arise only from loaded checkpoints, after a bake.

## 15. Ming Image: separate text-encoder level

`MingImage(quantize=..., text_encoder_quantize=...)` and CLI `--text-encoder-quantize`. `ming_image_initializer.py` line 77 passes `text_encoder_quantize` if set, otherwise `quantize`. This is the only model with two independent levels. README example: `-q 8 --text-encoder-quantize 4` (8-bit DiT and connector, 4-bit MoE encoder). The `heads` component (about 30M parameters) is skipped.

## 16. Known gaps and inconsistencies (found by code reading)

1. Qwen-Image `img_mod_linear` protection is `bits == 4` only. At `-q 3` these layers stay at 3-bit.
2. Qwen-Image-2.1 txt2img skips the text encoder. The 2.1 edit and ControlNet definition does not. `qwen21/README.md` says the encoder "is never quantized". `qwen21/reference/README.md` says eligible encoder layers quantize.
3. The VAE attention `nn.Linear` layers (FLUX.1, FLUX.2, Z-Image, and SeedVR2) are in the `models` dict and the default predicate accepts them, so they appear to be quantized. All VAE convolutions stay in full precision.
4. `_INFERABLE_BITS` includes 2, but the CLI rejects `-q 2`. The Python API passes 2 to MLX, which accepts it. No test covers it.
5. Layout recovery assumes affine tensors. A non-affine layer (MXFP4, NVFP4) would not round-trip. Only Lens loads such layers, through its own code.
6. A skipped component in a saved model is stamped with the model's `quantization_level` although it is BF16.
7. Ernie RoPE: YARN in the checkpoint config, plain RoPE in the class (section 13).

## 17. How this document was verified

Read from source: all `*_weight_definition.py` files, `weight_applier.py`, `quantization_resolution.py`, `model_saver.py`, `lora_saver.py`, `fp8_linear.py`, the Lens encoder, initializers, encoder classes (taps), `model_config.py` overrides, READMEs.

Executed in the project venv (no model weights loaded):
- `inspect.signature` of `nn.quantize` and `mx.quantize`.
- `mx.quantize` on a random 128x128 array: affine group 64 bits 4 gives `uint32` weight, bfloat16 scales and biases. `mxfp4` (group 32), `nvfp4` (group 16) and `mxfp8` (group 32) give `uint8` scales and no biases. Bits 1 and 7 raise. Bits 2, 3, 5 work.
- `hasattr(cls, "to_quantized")`: true for `nn.Linear` and `nn.Embedding`, false for `Conv2d`, `LayerNorm`, `RMSNorm`, `QuantizedLinear`.

Not done: no model load, no inference, no image comparison, no measurement of quality at any bit width. Statements about quality come from READMEs or code comments only.

Web sources: [baidu/ERNIE-Image](https://huggingface.co/baidu/ERNIE-Image), its [text_encoder config.json](https://huggingface.co/baidu/ERNIE-Image/raw/main/text_encoder/config.json), [ComfyUI ERNIE-Image docs](https://docs.comfy.org/tutorials/image/ernie-image).

Re-verify commands:
- `grep -rn "skip_quantization" src/mflux/models`
- `grep -rn "quantization_predicate" src/mflux/models`
- `grep -rn "nvfp4\|mxfp" src` (expect only Lens comments)
- `sed -n 64p src/mflux/cli/defaults/defaults.py` (expect `QUANTIZE_CHOICES`)

---

### Development Ai Skills Mflux Pr Docs (`docs/development/ai-skills/mflux-pr-docs.md`)

# `mflux-pr-docs` AI Agent Skill


***An AI skill that helps you write the PR body. It works in Claude Code, Cursor and GitHub Copilot.***


### Goals
 1. The AI writes short, clear text in Simplified Technical English \*.
 2. The AI fills the `What` section. See `pr-what-prompt.md`.
 3. The AI fills the `release-note` block. See `release-note-prompt.md`.


### Process:
1. Read `git diff main...HEAD`, the commit log and the linked issues.
1. Copy `.github/pull_request_template.md` to `tmp-PR-content.md`.
1. Fill in the PR title on a `Title:` line. If the PR is open, keep its current title unless the developer asks to change it. Fill in the `What` section (the benefit prompt), the `release-note` block, and the `Verification` section from commands that were actually run.
1. Run the same regex check as CI on `tmp-PR-content.md`.
1. Show `tmp-PR-content.md` to the developer for approval or edits. Only after approval does it run `gh pr create`, or `gh pr edit` if the PR already exists. It passes the title from the `Title:` line, and the body without the two draft lines as `tmp-PR-body.md`.


\* Simplified Technical English skill - [asd-ste100-skill](https://github.com/danyuchn/asd-ste100-skill)

---

--- METRICS ---
- Files Extracted: 12
- Estimated Token Budget: ~20669 tokens
- Canonical Reference: https://codewiki.google/github.com/filipstrand/mflux
