Local Image Generation on Apple Silicon: A Practical Guide to mflux
The two most common elements in the universe are hydrogen and stupidity, Harlan Ellison
Generating high-quality images locally has historically required massive GPU resources and complex background server setups. However, with the advent of Apple Silicon and the MLX framework, state-of-the-art generative models are now accessible directly on your Mac.
This article provides a practical, no-nonsense guide to mflux, a lightweight Python library and CLI that runs models like FLUX.2 Klein and Z-Image Turbo natively on Apple Silicon. We will cover everything from navigating Hugging Face’s gated repositories and understanding disk requirements, to building a hardened Python wrapper for reliable automation and seamlessly integrating mflux into your OpenClaw autonomous agent workflows. Whether you are a developer building local AI tools or an enthusiast exploring on-device generation, this guide will help you avoid common pitfalls and get your local image pipeline running smoothly.
mflux — Local Image Generation from Python on Apple Silicon
mflux runs state-of-the-art generative image models — Z-Image-Turbo, FLUX.1-schnell, FLUX.2 Klein (4B and 9B), and a growing list including Krea 2, Ideogram 4, Qwen-Image, and FIBO 2 — natively on Apple Silicon via MLX. Because it is a Python library and CLI rather than a background server, your script blocks until the PNG is written to disk. There is no port to manage, no async polling loop, and no daemon to keep alive.
That synchronous model is mflux’s defining advantage for automation. It is also where most integration mistakes happen: treating a slow, memory-hungry, license-gated model download as if it were a fast, unconditional function call.
What mflux Actually Is
mflux is a line-by-line MLX port of several state-of-the-art generative image models from Hugging Face Diffusers and Transformers, implemented from scratch in MLX using only the tokenizers from Transformers. The design philosophy is deliberately minimal and explicit — “Karpathy style,” in the project’s own words — which means the CLI surface is large but predictable, and the Python API mirrors the CLI closely enough that you can move between them without relearning concepts.
Each model family gets its own CLI entry point: mflux-generate-flux2 for FLUX.2 Klein, mflux-generate-z-image-turbo for Z-Image Turbo, mflux-generate for FLUX.1, and so on. The Python API is organized by model under mflux.models.<family>, with variant classes such as Flux2Klein and ZImageTurbo.
For Python automation, this matters because you have two integration paths:
- Shell out to the CLI via subprocess.run — simple, isolated, and exactly synchronous.
- Import the Python API directly — more control over the model object, useful when you want to generate multiple images from one loaded model or manipulate latents.
2. Installation
# Install into your script's virtual environment
pip install mflux
# Or globally as a CLI tool
uv tool install mflux
# If you encounter the hf_transfer error — ValueError: Fast download using 'hf_transfer'
# is enabled but 'hf_transfer' package is not available — install with the extra included:
uv tool install mflux --with hf_transfer
# This enables faster model downloads from Hugging Face.
# Verify that the CLI entry points exist:
uv tool list
3. Model Access and Gated Repositories
There are two different gates
-
FLUX.1-schnell is gated on Hugging Face. You must open the model page, log in, and click Agree and access repository. The original draft covered this correctly.
-
FLUX.2 Klein 9B is also gated, but the mechanics are slightly different and the license is stricter. black-forest-labs/FLUX.2-klein-9B is set to gated: “auto” on Hugging Face, and the model page surfaces an “Agree and access repository” button for the FLUX Non-Commercial License Agreement and the Acceptable Use Policy. Clicking it grants access immediately — there is no manual review queue.
The critical detail: CLI token authentication alone gets a 403. Logging in with hf auth login is necessary but not sufficient. The browser-side agreement must be acknowledged separately. Even if hf auth whoami succeeds, the gated-repo error will persist until the license form has been submitted.
The error you will see.
If the license has not been accepted, mflux fails with:
Cannot access gated repo for url https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B/resolve/.../text_encoder/config.json
This is not an authentication failure. It is a terms-acceptance failure. The fix is a browser visit to the model page, not a new token.
Hugging Face login. Create a Read token at huggingface.co/settings/tokens, then:
hf auth login
Paste the token when prompted. Notice that login and license acceptance are independent steps.
Disk and download cost
The 9B model is large. On first invocation, mflux downloads roughly 20 files totaling about 30 GB, landing at around 32 GB in ~/.cache/huggingface/hub/models--black-forest-labs--FLUX.2-klein-9B/ after download. The 4B model is about half that, roughly 15 GB on disk. Budget at least 40 GB of free space before starting with the 9B variant.
The model cache location depends on version. Newer mflux uses platform-native caching via platformdirs, with macOS-idiomatic locations under ~/Library/Caches/mflux/, while Hugging Face downloads also land in the standard ~/.cache/huggingface hub directory.
4. The CLI: Flags That Actually Matter
The core flags
| Flag | Purpose | What to know |
|---|---|---|
--model |
Selects the model variant | Accepts predefined names (flux2-klein-9b, flux2-klein-4b), local paths, or full HF repos |
--quantize / -q |
Quantization level | 4 or 8; 8 is the recommended default for quality/memory balance |
--low-ram |
Reduce peak memory | Requests a memory-saving execution mode; it may run more slowly |
--steps |
Sets the number of image-generation sampling steps | The fast model is designed for few steps; the base model generally uses more |
--guidance |
Controls how strongly generation is guided by the prompt | The appropriate value depends on the model; higher is not always better |
--width / --height |
Set the image dimensions | 1280 × 720 is a 16:9 landscape image. Larger dimensions generally need more memory and time |
--seed |
Sets the random seed | Same seed + same settings produces pixel-identical output |
--output |
Sets the path and filename for the generated image | Use a new filename if you want to keep earlier results |
Scripts
These scripts ask mflux-generate-flux2 to create an image from a text prompt. The first uses the fast/distilled Klein 9B model; the second uses the non-distilled base 9B model. The settings differ because the two model variants are intended to use different sampling step counts and guidance strengths.
mflux-generate-flux2 \
--model flux2-klein-9b \
--quantize 8 \
--low-ram \
--steps 4 \
--guidance 1.0 \
--width 1280 \
--height 720 \
--seed 42 \
--prompt "your prompt" \
--output output.png
If you specifically want the base (non-distilled) 9B model and 50 steps:
mflux-generate-flux2 \
--model flux2-klein-base-9b \
--quantize 8 \
--low-ram \
--steps 50 \
--guidance 3.5 \
--width 1280 \
--height 720 \
--seed 42 \
--prompt "your prompt" \
--output output.png
5. A Hardened Python Wrapper
The original subprocess.run(cmd, check=True) is the right primitive, but it fails silently in ways that matter for automation: a gated-repo error raises CalledProcessError with a long stderr, and the caller has no structured way to distinguish “license not accepted” from “out of memory” from “model not found.”
Here is a more robust version:
# =====================================================================
# IMPORTS
# In Python, we "import" modules (toolkits) that give us extra abilities
# beyond basic math and text manipulation.
# =====================================================================
# 'subprocess' allows Python to run other programs on your computer,
# just like you would type commands into a Terminal or Command Prompt.
import subprocess
# 'shutil' stands for "shell utilities". It helps with file operations
# and finding out if certain programs are installed on your computer.
import shutil
# 'pathlib' is the modern Python toolkit for working with file and folder
# paths across different operating systems (Mac, Windows, Linux).
from pathlib import Path
# =====================================================================
# CUSTOM ERROR DEFINITION
# =====================================================================
# Here we create a custom error type called 'MfluxGenerationError'.
# By putting '(RuntimeError)' in parentheses, we tell Python that our
# new error is a specific category of a standard 'RuntimeError'.
# Making a custom error makes it easier to know *exactly* what went wrong later.
class MfluxGenerationError(RuntimeError):
# Triple quotes create a "docstring" – an official description of what
# this class or function does.
"""Raised when mflux fails, with the underlying stderr preserved."""
# 'pass' is a keyword that means "do nothing". We use it here because
# we don't need to add any special code to our custom error;
# inheriting behavior from 'RuntimeError' is enough.
pass
# =====================================================================
# MAIN FUNCTION DEFINITION
# =====================================================================
# 'def' starts a function definition named 'generate_image'.
# Inside the parentheses are the "parameters" (inputs) the function accepts.
#
# Notice the format: `parameter_name: data_type = default_value`
# - `: str`, `: int`, `: float`, `: bool` are "Type Hints". They tell the
# programmer what kind of data is expected (text, whole number, decimal, True/False).
# - `= "output.png"` is a default value. If you don't provide this input when
# calling the function, Python will automatically use this default.
def generate_image(
prompt: str, # Required: The text description of the image you want.
output_path: str = "output.png", # Optional: Where to save the image file.
model: str = "flux2-klein-9b", # Optional: Which AI model to use.
quantize: int = 8, # Optional: Compression level (8-bit saves memory).
low_ram: bool = True, # Optional: Whether to use low-memory mode (True/False).
steps: int = 4, # Optional: How many passes the AI takes to draw the image.
guidance: float = 1.0, # Optional: How strictly the AI follows your prompt (decimal).
width: int = 1280, # Optional: Image width in pixels.
height: int = 720, # Optional: Image height in pixels.
seed: int | None = 42, # Optional: A number to make randomness repeatable.
# `int | None` means it can be a whole number OR 'None' (empty).
) -> Path: # `-> Path` is a type hint saying this function will return a 'Path' object at the end.
# -----------------------------------------------------------------
# STEP 1: Check if the required tool is actually installed
# -----------------------------------------------------------------
# `shutil.which()` looks at your computer's "PATH" to see if the command "mflux-generate-flux2" exists.
# If it returns `None`, the program isn't installed (or can't be found).
if shutil.which("mflux-generate-flux2") is None:
# `raise` immediately stops the function and triggers our custom error
# with a helpful message telling the user how to fix the problem.
# Note: Python automatically joins strings that are next to each other on separate lines.
raise MfluxGenerationError(
"mflux-generate-flux2 not found on PATH. "
"Install with `uv tool install mflux` or `pip install mflux`."
)
# -----------------------------------------------------------------
# STEP 2: Build the terminal command as a Python list
# -----------------------------------------------------------------
# When using `subprocess` to run a terminal command, it wants the command
# broken up into a list of individual words (strings), inside square brackets `[]`.
#
# IMPORTANT: Terminal commands only understand text (strings). Because inputs
# like `quantize`, `steps`, and `width` are numbers (`int` or `float`), we must
# wrap them in `str()` to convert them into text before putting them in the list.
cmd = [
"mflux-generate-flux2",
"--model", model,
"--quantize", str(quantize),
"--steps", str(steps),
"--guidance", str(guidance),
"--width", str(width),
"--height", str(height),
"--prompt", prompt,
"--output", output_path,
]
# If `low_ram` is True, we need to add the "--low-ram" flag to our command list.
if low_ram:
# `.insert(3, ...)` puts "--low-ram" at position 3 in the list (right after `model`).
# Remember, Python (as many other programming languages) counts list positions starting from 0!
# Position 0: "mflux-generate-flux2", 1: "--model", 2: model, 3: "--low-ram"
cmd.insert(3, "--low-ram")
# If the user provided a `seed` (meaning it is not `None`), we add it to the command.
if seed is not None:
# `.extend()` adds multiple items to the very end of our `cmd` list.
cmd.extend(["--seed", str(seed)])
# -----------------------------------------------------------------
# STEP 3: Run the command and watch out for errors
# -----------------------------------------------------------------
# `try:` starts an error-handling block. Python will attempt to run the code
# inside the `try` block. If it crashes, instead of stopping the whole program,
# Python jumps down to the `except` block to handle the crash gracefully.
try:
# `subprocess.run()` actually executes our command list in the background.
# - `cmd`: The list of command words we have already built.
# - `check=True`: Tells Python to **automatically trigger an error** (`CalledProcessError`)
# if the command fails (returns a non-zero exit code).
# - `capture_output=True`: Tells Python to record whatever text the program prints out,
# so we can read its error messages if it fails.
# - `text=True`: Tells Python to decode that recorded output as normal readable text
# (strings) instead of raw computer bytes.
subprocess.run(cmd, check=True, capture_output=True, text=True)
# If `subprocess.run` fails (because of `check=True`), Python catches the
# `CalledProcessError` here and names the error object `exc` (short for exception)
# so we can inspect it.
except subprocess.CalledProcessError as exc:
# Command-line programs print normal messages to `stdout` (standard output)
# and error messages to `stderr` (standard error).
# Here, we grab the error text from `exc.stderr`.
# The `or ""` is a safety trick (defensive programming): if `exc.stderr` is `None` (empty),
# it falls back to an empty string `""` so our text searches below don't crash.
stderr = exc.stderr or ""
# --- Error Diagnosis 1: Hugging Face Permission Issue ---
# We check if the phrase "Cannot access gated repo" is in the error text,
# OR if the word "gated" is in a lowercase version (`.lower()`) of the error text.
if "Cannot access gated repo" in stderr or "gated" in stderr.lower():
# An 'f-string' (`f"..."`) lets us insert variables directly into text
# using curly braces, like `{model}`.
# `from exc` attaches the original technical error to our friendly custom error,
# preserving the full history of what went wrong for debugging.
raise MfluxGenerationError(
f"Model '{model}' is gated on Hugging Face. "
"Open the model page in a browser, log in, and click "
"'Agree and access repository'. Then run `hf auth login`. "
"Token login alone does not satisfy the gate."
) from exc
# --- Error Diagnosis 2: Not Enough Computer Memory (RAM/VRAM) ---
# We check if the error message complains about "memory".
if "out of memory" in stderr.lower() or "memory" in stderr.lower():
raise MfluxGenerationError(
"mflux ran out of memory. Try --quantize 4, --low-ram, "
"--vae-tiling, a smaller model (4B), or a smaller resolution."
) from exc
# --- Error Diagnosis 3: Anything else ---
# If it failed for some other unknown reason, we raise our custom error
# and show the program's exit code (`exc.returncode`) along with the
# last 2000 characters of the error message (`stderr[-2000:]`).
# Slicing with `[-2000:]` prevents dumping a massive wall of text to the screen.
raise MfluxGenerationError(
f"mflux failed with exit code {exc.returncode}:\n{stderr[-2000:]}"
) from exc
# -----------------------------------------------------------------
# STEP 4: Verify the output file actually exists and isn't broken
# -----------------------------------------------------------------
# Convert the text string `output_path` (e.g., "output.png") into a
# smart `Path` object, which has built-in tools for checking files.
out = Path(output_path)
# Sometimes a command-line tool claims it succeeded, but silently failed to
# write the file. Here we double-check two things:
# 1. `not out.exists()`: Did the file fail to appear on the hard drive?
# 2. `out.stat().st_size == 0`: Does the file exist, but its size is 0 bytes (empty)?
if not out.exists() or out.stat().st_size == 0:
raise MfluxGenerationError(
f"mflux exited successfully but '{output_path}' is missing or empty."
)
# -----------------------------------------------------------------
# STEP 5: Success! Return the result
# -----------------------------------------------------------------
# Everything worked! Send the `Path` object pointing to the new image
# back to whatever part of the program called this function.
return out
6. The Python API Alternative
If you are generating multiple images in one process, loading the model once and calling generate_image repeatedly is faster than shelling out each time. The documented pattern for Z-Image Turbo is:
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")
For FLUX.2 Klein, the pattern uses Flux2Klein and a ModelConfig:
from mflux.models.common.config import ModelConfig
from mflux.models.flux2.variants import Flux2Klein
model = Flux2Klein(
model_config=ModelConfig.flux2_klein_9b(),
quantize=8,
)
image = model.generate_image(
prompt="A cinematic wide shot of a Galilean shoreline at dawn",
seed=42,
num_inference_steps=4,
width=1280,
height=720,
)
image.save("output.png")
The exact import paths and constructor signatures have shifted across mflux versions. For production automation, the CLI wrapper is more stable across upgrades; the Python API is faster for batches but more sensitive to version drift. A reasonable rule: use the CLI for one-off generation and the Python API for loops where model load time dominates.
7. Performance Expectations
Numbers from real runs on Apple Silicon:
- FLUX.2 Klein 9B, 4-bit, 20 steps: 512×512 in 1m51s, 1024×1024 in 5m37s on an M1 Max 64 GB.
- FLUX.2 Klein 4B, 8-bit: roughly 8 seconds per image, about 5 GB RAM.
- FLUX.2 Klein 4B, 4-bit: roughly 4 GB RAM.
The 9B model is a different class of resource commitment. If your pipeline is generating one image per request, the 4B model at 8-bit is usually the right default; the 9B model is worth its cost only when its quality advantage matters for the specific prompt.
Quantization on Klein 9B is a memory optimization, not a speed optimization: 9B at BF16 is roughly 18 GB, and 4-bit brings it to roughly 9 GB to fit 16 GB Macs, but it does not make generation faster.
8. Integration with OpenClaw
mflux is a natural fit for OpenClaw because it is fully local: no API key, no rate limit, no prompt leaving the machine. There is an existing OpenClaw skill that wraps it:
openclaw skills install @pjain/mflux
The skill defaults to FLUX.2 Klein 4B (fastest, Apache 2.0) and exposes Z-Image Turbo as the higher-quality option, with all processing on-device. Requirements are an Apple Silicon Mac (M1 or later), Python 3.10+, and macOS 13.5+; 16 GB RAM recommended, 8 GB workable with quantization.
The trade-off versus OpenRouter free models is the usual local-vs-cloud one. OpenRouter gives you access to frontier image models without local hardware but imposes daily request caps and may retain prompts on free endpoints. mflux gives you unlimited local generation but confines you to Apple Silicon and to the models mflux supports, and the first run downloads tens of gigabytes.
For a daily devotional workflow, mflux is attractive precisely because the image step is synchronous and local — the agent outputs the command, the subprocess blocks, the PNG appears, and the next step proceeds. There is no async placeholder to manage and no provider that can rate-limit you mid-prayer.
import subprocess
from pathlib import Path
def generate_image(prompt: str, output_path: str = "output.png") -> Path:
cmd = [
"mflux-generate-flux2",
"--model",
"flux2-klein-base-9b",
"--quantize",
"8",
"--low-ram",
"--steps",
"50",
"--guidance",
"3.5",
"--width",
"1280",
"--height",
"720", # 16:9
"--prompt",
prompt,
"--output",
output_path,
]
subprocess.run(cmd, check=True)
return Path(output_path)
if __name__ == "__main__":
prompt = (
"Cinematic wide shot of Jesus teaching a crowd by the shore of the Sea of Galilee, "
"golden hour sunlight, wooden fishing boats in the background, natural linen robes, "
"35mm film grain, reverent atmosphere, realistic lighting and textures"
)
generate_image(prompt, "output.png")
You may get Cannot access gated repo for url https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B/resolve/32773329fbe7e81a90ef971740e8ba4b0364ecf3/text_encoder/config.json. Like schnell, black-forest-labs/FLUX.2-klein-base-9B is gated on Hugging Face—accept its license once on HF