Technical Documentation: filipstrand/mflux
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (README.md)
About
Run the latest state-of-the-art generative image models locally on your Mac in native MLX!
Table of contents
- ๐ก Philosophy
- ๐ฟ Installation
- ๐จ Models
- โจ Features
- ๐ฆ Contributors
- ๐ฑ Related projects
- ๐ Acknowledgements
- โ๏ธ License
๐ก Philosophy
MFLUX is a line-by-line MLX port of several state-of-the-art generative image models from the Huggingface Diffusers and Huggingface Transformers libraries. All models are implemented from scratch in MLX, using only tokenizers from the Huggingface Transformers library. MFLUX is purposefully kept minimal and explicit, @karpathy style.
๐ฟ Installation
If you haven't already, install uv, then run:
uv tool install --upgrade mfluxAfter installation, the following command shows all available MFLUX CLI commands:
uv tool listTo 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 8The first time you run this, the model will automatically download which can take some time. See the model section for the different options and features, and the common README for shared CLI patterns and examples.
Python API
Create a standalone generate.py script with inline uv dependencies:
#!/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:
uv run generate.pyFor more Python API inspiration, look at the CLI entry points for the respective models.
โ ๏ธ Troubleshooting: hf_transfer error
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:
uv tool install --upgrade mflux --with hf_transferThis will enable faster model downloads from Hugging Face.
DGX / NVIDIA (uv tool install)
uv tool install --python 3.13 mflux๐จ 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 | Nov 2025 | 6B | Distilled & Base | Yes | Fast, small, very good quality and realism. |
| Krea 2 | Jun 2026 | 12B | Turbo (distilled) | Yes | Very good quality with a wide range of styles; good for creative exploration. |
| FLUX.2 | Jan 2026 | 4B & 9B | Distilled & Base | Yes | Fastest + smallest with very good quality and edit capabilities. |
| FLUX 3 Image Klein | 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 | 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 | Jun 2026 | 9B | Base | No | JSON-caption-native, typography-focused text-to-image generation. |
| ERNIE-Image | Apr 2026 | 8B | Distilled & Base | Yes | Single-stream DiT from Baidu. Vivid, high-contrast output. |
| Lens | 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 | Sep 2026 | 6.15B (+16B MoE TE) | Base | No | Design-focused (posters, cards, UI) with strong typography; outputs RGBA. |
| MOSS-Image | 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 | 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 | 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 | 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 | Jun 2026 | 10B | Turbo (distilled) | No | DMD-distilled 4-step model with a photographic look and bilingual (EN/ZH) text rendering. |
| FIBO 2 | 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 | Jun 2025 | 3B & 7B | โ | No | Best upscaling model. |
| Qwen Image | Aug 2025+ | 20B | Base | No | Large model (slower); strong prompt understanding and world knowledge. Has edit capabilities |
| Qwen Image 2.1 | 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. |
| Depth Pro | Oct 2024 | โ | โ | No | Very fast and accurate depth estimation model from Apple. |
| FIBO | Oct 2025+ | 8B | Distilled & Base | No | Legacy option, superseded by FIBO 2. JSON-based prompt understanding and edit capabilities. |
| FLUX.1 | Aug 2024 | 12B | Distilled & Base | No (legacy) | Legacy option with decent quality. Has edit capabilities with 'Kontext' model and upscaling support via ControlNet |
Schedulers
MFlux supports a small number of schedulers - see;
Schedulers - User Manual
Schedulers - Technical Overview
โจ 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)
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 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, Claude Code, or similar). Ask questions like: โCan you help me generate an image using z-image?โ
๐ฆ Contributors
MFlux was originally created by Filip Strand in August 2024 and moved to this organisation in August 2026. It is maintained by:
| Filip StrandCreated MFlux | Anthony WuToolchain, CI, releases, mflux.web | plz12345Devops, Krea 2, Boogu | Mariano AbadControlNets, training, Lens | Ian ScrivenerHF, community, CUDA, model builds |
|---|
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 | initial release, 2024-08 |
| Depth Pro | @filipstrand | #159 |
| Qwen Image | @filipstrand | #269 |
| FIBO | @filipstrand | #279 |
| FIBO 2 | @filipstrand | โ |
| Z-Image | @filipstrand | #284 |
| SeedVR2 | @filipstrand | #297 |
| FLUX.2 Klein | @filipstrand | #323 |
| FLUX 3 Image Klein | @cguldogan | #876 |
| Iris-3B | @cguldogan | #898 |
| FLUX.2 KV cache (klein-9b-kv) | @michaeltrefry | #426 |
| ERNIE-Image | @azrahello | #417 |
| Ideogram 4 | @omercelik | #433 |
| Krea 2 | @plz12345 | #453 |
| LyCORIS LoKr adapters | @JanGrohn | #422 |
| Fused-qkv LoRA loading | @deadmansahil | #459 |
| Boogu-Image | @plz12345 | #446 |
| MOSS-Image | @vanch007 | #895 |
| SenseNova-U1.5 | @cguldogan | #989 |
| Anima | @fxd0h | #931 |
| PiD pixel-diffusion decoder | @azrahello | #490 |
| Z-Image Union ControlNet | @fxd0h | #482 |
| Krea 2 Raw, LoRA training, diffusers loading | @fxd0h | #462 |
| Lens (Turbo) | @fxd0h | #510 |
| mflux-capabilities, the machine-readable option contract | @fxd0h | #499 |
| Gradient checkpointing for training | @qruz-hq | #711 |
| Denoised prediction for in-loop callbacks | @IonDen | #729 |
| Qwen-Image-2.1 | @ivanfioravanti | #736 |
| Qwen-Image-2.1 reference editing, RGBA, prefix cache | @dreampuf | #741, #777 |
| Qwen-Image-2.1 masks, auto-mask, strength, verify | @flyingtimes | #749, #764 |
| PEFT and ComfyUI LoRA formats (Qwen 2.1, Z-Image) | @phplego | #756, #768, #772 |
| Text-prefix KV cache, Metal kernel, step cache | @murphymatt | #778, #779 |
| Ming-Image-0.1-Design | @joeynyc | #765 |
| load and generate entry points for UIs | @IonDen | #780, #785 |
| mflux.web UI packages | @anthonywu | #776 |
| CI gates, justfile, ty, the pypi environment | @anthonywu | #576, #590, #646 |
| Release process and release notes | @fxd0h | #685 |
| test_tiny fixtures for every model | @ianscrivener, @anthonywu | #611, #620, #599 |
Everyone else who fixed, tested and reviewed is in the contributor graph.
๐ฑ 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 themflux/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
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 examplesrc/mflux/web/example_ui/__init__.py. With uv_build, configuremodule-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, ormflux/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 useimport 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 undermflux.extras and add their own commands. mflux's own commands do not change.
The mflux-community plugins live in
mflux-plugins. To find,
install or write one, see Plugins - User Manual.
Community applications
- MindCraft Studio โ macOS app built on mflux by @shaoju
- mflux-paint โ native macOS inpaint/edit app (pywebview), 16 models across edit/inpaint/text-to-image, mask painting, multi-seed batch, by @Amo643
- Mflux-ComfyUI by @raysers
- MFLUX-WEBUI by @CharafChnioune
- mflux-fasthtml by @anthonywu
- mflux-streamlit by @elitexp
- mfluxible โ streaming HTTP API server for mflux models with a browser harness, an MCP tool and an OpenAI-compatible endpoint, by @wesbiggs
- mlx-taef โ TAESD/TAEF tiny-autoencoder live previews and low-memory FLUX decode for mflux, by @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
- MLXBits Image Studio - A native macOS Swift app for FLUX, Krea 2, Z-Image and more!
- Graphis - native macOS SwiftUI app for MOSS-Image with a bundled mflux engine, reference image, LoRA modules and a queue, by @Campfire7
๐ Acknowledgements
MFLUX would not be possible without the great work of:
- The MLX Team for MLX and MLX examples
- Black Forest Labs for the FLUX project
- Bria for the FIBO project
- Tongyi Lab for the Z-Image project
- Baidu for the ERNIE-Image project
- Ideogram for the Ideogram 4 project
- Speridlabs for the Iris-3B project
- Krea.ai for the Krea 2 project
- Qwen Team for the Qwen Image project
- Microsoft for the Lens (Turbo) model, and Comfy-Org for the weights repackage
- inclusionAI for the Ming-Image project
- OpenMOSS for the MOSS-Image project
- SenseTime for the SenseNova-U1 project
- ByteDance for the DreamLite project
- CircleStone Labs and Comfy Org for the Anima project
- The Boogu team for the Boogu Image project
- ByteDance, @numz and @adrientoupet for the SeedVR2 project
- Hugging Face for the Diffusers library implementations
- Depth Pro authors for the Depth Pro model
- The MLX community and all contributors and testers
โ๏ธ License
This project is licensed under the MIT 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
depthandhedcontrols - 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:
- Install the system library, for example
apt install libgl1 libglib2.0-0. - Replace
opencv-pythonwithopencv-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:
- Install as usual, then remove OpenCV:
pip uninstall opencv-python. - Install mflux with
--no-deps, then install the other dependencies frompyproject.tomlyourself.
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:
- Read weight files that MLX cannot read (
.pt/.pthpickles). The Depth Pro loader callstorch.loadwithweights_only=False, so a.ptfile can run code when it loads. Use only Depth Pro files from a source that you trust. - Convert some bf16 safetensors through
torchto 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-editmflux-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-turbomflux-generate-z-image-controlnetwithcannyormlsdcontrolsmflux-generate-krea2,mflux-generate-krea2-controlnetwith--depth-image-pathmflux-generate-ernie-image*,-ideogram4,-lens,-ming,-iris,-boogu,-animamflux-upscale-seedvr2,mflux-upscale-controlnetmflux-train,mflux-save(for the models above),mflux-info,mflux-check,mflux-capabilities,mflux-lora-library- FIBO, if you load a checkpoint that
mflux-savewrote. The loader reads the mflux saved format first, and that format usesmx.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:
pip install torch --index-url https://download.pytorch.org/whl/cpuIf the CUDA build is already installed, remove it first. pip uninstall alone does not install the CPU wheel:
pip uninstall -y torch && pip install torch --index-url https://download.pytorch.org/whl/cpuHow to install without torch
Torch is a hard dependency, so a normal install pulls it. Two options:
- Install as usual, then remove torch:
pip uninstall torch. - Install mflux with
--no-deps, then install the other dependencies frompyproject.tomlyourself.
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
mflux-check model <model-reference>
mflux-check model --fix <model-reference>
mflux-check model --base-model <model-name> <model-reference>Examples:
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-finetuneThere 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/modelform 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:
- Find the model safetensors files and their shard index files.
- Identify the package as MFlux or Hugging Face safetensors.
- Match the observed layout to a model supported by the MFlux CLI.
- 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 asmflux_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:
#################
MFlux Check Model:
check: pass
format: safetensors
size: 13.35 GBAn incomplete MFlux package reports a warning and gives the repair command:
#################
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-kleinA 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 eitherpass 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 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:
uv tool install mflux --with-executables-from mflux-teacacheThis 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:
pip install mflux-teacacheFor 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:
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. If only the plugin command fails, report it in the 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:
- Put your code in one package under
mflux.extras. Use a name that no other package uses. - Do not ship
mflux/__init__.pyormflux/extras/__init__.py. The first file belongs to mflux. The second file hides all other plugins. - 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 ofmain()has no step. - Test against mflux
main. The command steps have no stability promise and can change in any release.
The plugin guide gives the full procedure. Start from the plugin 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 | X |
| 9 | flux2-klein-9b |
โ | โ | 64 | Qwen3-8B | 4096 | Inter 9, 18, 27 | X | X |
| 10 | flux2-klein-9b-kv |
โ | โ | 64 | Qwen3-8B | 4096 | Inter 9, 18, 27 | X | |
| 11 | flux2-klein-base-4b |
โ | โ | 64 | Qwen3-4B | 2560 | Inter 9, 18, 27 | X | X |
| 12 | flux2-klein-base-9b |
โ | โ | 64 | Qwen3-8B | 4096 | Inter 9, 18, 27 | X | X |
| 13 | ideogram-4-fp8 |
โ | โ | 64 | Qwen3-VL FP8 | 4096 | Inter 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 35 | X | |
| 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
-qquantizes the component.โ means the model keeps the component in BF16 (
skip_quantization=True).GSis the affine group size that-quses.HSis the hidden size of the text encoder.FP8andNVFP4link 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.Finalmeans the last hidden state.Intermeans intermediate hidden states. Numbers are layer indexes.-2means the second from last.
Notes:
ming-image-designtakes a separate--text-encoder-quantizeflag for the text encoder. It falls back to-q.lens-turbois not in the table.mflux-savecannot save it. Its DiT takes-q. Its GPT-OSS encoder ships pre-quantized.qwen-image-2.1(text-to-image) skips the text encoder. Theqwen-image-2.1-controlnet-unionmodel 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:
mflux-generate-krea2 --prompt "a chrome teapot" --steps 8 --scheduler euler -q 8Which 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_sdeis the default.viggle_turbo: for the Viggle turbo LoRA on Qwen Image 2.1. Use--steps 6and--lora-pathswith 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:
mflux-generate --prompt "a lighthouse" --scheduler my_package.my_module.MySchedulerThe 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
--schedulersays "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:
- It resolves
--modelagainst the model registry. It accepts only the models that this command can run. A wrong model name fails here. - 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:
- It reads the weight files.
- It loads the tokenizers.
- It makes the components.
- It puts the weights into the components. If you give
--quantize, it quantizes them. - If you give
--lora, it applies each LoRA to the transformer. By default, it merges the LoRA into the weights. Use--no-bake-lorato keep the LoRA separate. MOSS-Image keeps the LoRA separate by default. Use--bake-lorato 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
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 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
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.
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!*
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) | AGENTS.md,.claude/settings.json,.claude/skills/ |
Yes |
| Personal, this project only | CLAUDE.md,CLAUDE.local.md,.claude/settings.local.json |
No (gitignored) |
| Personal, all projects | ~/.claude/CLAUDE.md,~/.claude/skills/,~/.claude/settings.json |
Not in the repo |
- This repo ignores
CLAUDE.md. Put shared agent rules inAGENTS.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:
- Create
.cursor/skills/<name>/SKILL.md. - 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.mdSources
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 callsnn.quantizedirectly.nn.quantizequantizes a module only if it exposesto_quantizedand the predicate accepts it.nn.Linearandnn.Embeddingare examples.nn.Linearandnn.Embeddinghaveto_quantized.nn.Conv2d,LayerNormandRMSNormdo not (checked in the project venv).- A quantized layer stores
weight(packeduint32),scales, andbiases(affine). A linear layer's ownbiasstays in the model dtype. group_sizedefaults to 64. OnlyBooguWeightDefinitionoverrides it (quantization_group_size = 32, because its 3360-wide linears do not divide by 64).- The call sites never pass
mode=. MLX defaults toaffine. mx.quantizeneeds the last dimension divisible bygroup_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= 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`
bits is None:_set_weightsonly. Weights load as saved (BF16, or FP8 for Ideogram).stored is Noneandbitsset (on-the-fly):_set_weightsfirst, then_quantize. The full-precision weights load, then MLX quantizes them.storedset (pre-quantized checkpoint):_quantizefirst 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_dimsgroup_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
scalesin 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
bitsas 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.mdsays 6-bit or below can degrade the image much more than FLUX. - Ming Image is the exception:
--text-encoder-quantizesets the text encoder level apart from-q(ming_image_initializer.pyline 77). If you omit it,-qapplies. - Otherwise the same level applies to all quantized components in a run.
Qwen21Initializer.load_componentsraisesValueErrorif 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
scalesexist. Layers withoutscalesstay Linear. - Component has no weights in the file: the skip holds.
mflux-save -q 8on 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 areFp8Linear(ideogram4/model/ideogram4_transformer/fp8_linear.py):uint8weight plus a per-rowfloat32weight_scale, dequantized in every forward withmx.from_fp8. Fp8Linear.to_quantized(group_size, bits, mode="affine", quantize_input=False)makesnn.quantizereach these layers. Weights already loaded: dequantize through the row scale, thenmx.quantize. Weights not loaded (skeleton for a saved checkpoint): return an emptyQuantizedLinear.Ideogram4Initializer._rebuild_q8_folded_layersrebuilds 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 826 GB,-q 414 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_singlewithLensWeightDefinition.quantization_predicate. The-qflag affects only this part. - Text encoder:
LensGptOssEncoder(lens/model/text_encoder/lens_gpt_oss_encoder.py) loadsmlx-community/gpt-oss-20b-MXFP4-Q8. It readsconfig["quantization"], then callsnn.quantize(..., group_size, bits, mode=quantization.get("mode", "affine")). A path listed in the config uses its own settings (MXFP4 experts, Q8 elsewhere).-qhas 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 raisesValueError. - Z-Image ControlNet:
apply_and_quantize_singlewith 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,
LoRASaverdequantizes, 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 metadataquantization_levelandmflux_version. It also writesmodel.safetensors.index.jsonwith the same metadata.- Saved parameters are the post-quantization tree: packed
weight,scales,biasesfor quantized layers, plain tensors for the rest. A skipped component is saved in BF16 but is stamped with the samequantization_level. - Loading a saved model with
-q Nignores 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
- Add a new family: write
quantization_predicatein its*WeightDefinition. Skip layers whereweight.shape[-1] % group_size != 0. Otherwise the load fails insidemx.quantize. - Add a text encoder skip: set
skip_quantization=Trueon itsComponentDefinition. Add a comment with the evidence. Pre-quantized files still work (section 6.1). - 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. - Do not pass
mode=orquantize_input=Truetonn.quantizewithout changing_stored_layer_predicate,Fp8Linear, andLoRASaver. All three assume affine, weight-only layouts. - To add NVFP4 or MXFP4, add a
modeoption 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 givesuint8scales and nobiases. NVFP4 uses group size 16. MXFP4 uses group size 32. QUANTIZE_CHOICESis 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:
- Final: last layer output (Qwen-Image 1.x, Qwen-Image-2.1, Boogu, T5).
- Single intermediate: second from last layer (Z-Image
all_hidden_states[-2], Ernie layernum_hidden_layers - 2, FIBOhidden_states_list[-2]). - 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 layerN-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.ErnieWeightDefinitionloadstext_encoder/withweight_prefix_filters=["language_model.model."]and no key mapping. The vision tower in the file is ignored.baidu/ERNIE-Image/text_encoder/config.json: architectureMistral3Model,model_type: mistral3(textministral3, visionpixtral), 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(repoComfy-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:
- Shapes must match the constants above, or the load fails.
- Text keys must sit under
language_model.model.. Other layouts need a key mapping (none exists). - The tokenizer must match. Ernie ships its own
tokenizer/folder. - The DiT was trained on one set of features. Any other fine-tune (base versus instruct) gives off-distribution features even when shapes match.
- 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)
- Qwen-Image
img_mod_linearprotection isbits == 4only. At-q 3these layers stay at 3-bit. - Qwen-Image-2.1 txt2img skips the text encoder. The 2.1 edit and ControlNet definition does not.
qwen21/README.mdsays the encoder "is never quantized".qwen21/reference/README.mdsays eligible encoder layers quantize. - The VAE attention
nn.Linearlayers (FLUX.1, FLUX.2, Z-Image, and SeedVR2) are in themodelsdict and the default predicate accepts them, so they appear to be quantized. All VAE convolutions stay in full precision. _INFERABLE_BITSincludes 2, but the CLI rejects-q 2. The Python API passes 2 to MLX, which accepts it. No test covers it.- Layout recovery assumes affine tensors. A non-affine layer (MXFP4, NVFP4) would not round-trip. Only Lens loads such layers, through its own code.
- A skipped component in a saved model is stamped with the model's
quantization_levelalthough it is BF16. - 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.signatureofnn.quantizeandmx.quantize.mx.quantizeon a random 128x128 array: affine group 64 bits 4 givesuint32weight, bfloat16 scales and biases.mxfp4(group 32),nvfp4(group 16) andmxfp8(group 32) giveuint8scales and no biases. Bits 1 and 7 raise. Bits 2, 3, 5 work.hasattr(cls, "to_quantized"): true fornn.Linearandnn.Embedding, false forConv2d,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, its text_encoder config.json, ComfyUI ERNIE-Image docs.
Re-verify commands:
grep -rn "skip_quantization" src/mflux/modelsgrep -rn "quantization_predicate" src/mflux/modelsgrep -rn "nvfp4\|mxfp" src(expect only Lens comments)sed -n 64p src/mflux/cli/defaults/defaults.py(expectQUANTIZE_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
- The AI writes short, clear text in Simplified Technical English *.
- The AI fills the
Whatsection. Seepr-what-prompt.md. - The AI fills the
release-noteblock. Seerelease-note-prompt.md.
Process:
- Readย
git diff main...HEAD, the commit log and the linked issues. - Copyย
.github/pull_request_template.mdย toยtmp-PR-content.md. - 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. - Run the same regex check as CI onย
tmp-PR-content.md. - 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 theTitle:line, and the body without the two draft lines asยtmp-PR-body.md.
* Simplified Technical English skill - asd-ste100-skill
--- METRICS ---
- Files Extracted: 12
- Estimated Token Budget: ~20669 tokens
- Canonical Reference: https://codewiki.google/github.com/filipstrand/mflux