FLUX.2 Documentation

repository·main·Indexed 25 days ago

https://github.com/black-forest-labs/flux2

Inference codebase for FLUX.2, a suite of visual intelligence models from Black Forest Labs for text-to-image generation and image editing. Includes the high-speed [klein] family (4B, 9B, and 9B KV with KV caching for fast editing) and the high-parameter [dev] 32B model for maximum quality. Documentation covers installation via pip, interactive CLI usage, and integration with the diffusers library using 4-bit quantization or remote text-encoders for various VRAM configurations.

Tokens
9.7K
Snippets
12
Records
45
Agent score
82%

What's inside FLUX.2

  1. Overview of FLUX.2 [dev]

    main

    FLUX.2 [dev] is a 32 billion parameter rectified flow transformer designed for high-quality image generation, editing, and combining based on text instructions.

    Key Capabilities:

    • State-of-the-art open text-to-image generation.
    • Single-reference and multi-reference editing.
    • Character, object, and style reference without the need for additional fine-tuning.
    • Efficient inference due to guidance distillation training.

    Usage Options:

  2. Compare FLUX.2 model families

    main

    FLUX.2 offers different model families optimized for different use cases.

    FLUX.2 [klein]

    Designed for real-time applications and consumer hardware (e.g., RTX 3090/4070).

    • [klein] 4B: Maximum speed, fits in ~8GB VRAM. Apache 2.0 license.
    • [klein] 9B: High quality text-to-image. Non-commercial license.
    • [klein] 9B KV: Best quality-to-latency ratio; faster than 4B for multi-reference editing via KV caching.
    • Base models: Use [klein] 4B Base or [klein] 9B Base for fine-tuning and LoRA training.
    • Distilled vs Base: Use Distilled (4-step) for production/real-time; use Base (50-step) for fine-tuning and maximum flexibility.

    FLUX.2 [dev]

    • [dev]: A 32B parameter model for maximum quality. Requires significant VRAM (H100-equivalent). Non-commercial license.
    • Prompt Upsampling: Benefits significantly from prompt upsampling using Mistral-Small-3.2-24B-Instruct-2506 or via OpenRouter API.
  3. How FLUX.2 [klein] 9B KV Cache works

    main

    The FLUX.2 [klein] 9B KV variant is optimized for fast image editing by using KV caching. In standard editing, reference image tokens are recomputed at every denoising step. The KV cache variant avoids this redundancy by splitting the process into two phases:

    1. Step 0 (forward_kv_extract): Performs a full forward pass including reference tokens to extract and cache their key/value (KV) projections.
    2. Steps 1+ (forward_kv_cached): Performs the forward pass using only output and text tokens, reusing the cached reference KVs in the attention layers.

    This results in significant speedups, especially when using multiple reference images or lower output resolutions.

  4. When to use prompt upsampling with FLUX.2

    main

    Prompt upsampling uses a large vision language model to expand and enrich prompts before generation. This is particularly effective for tasks requiring reasoning or complex interpretation, such as:

    • Text generation in images: Creating memes, posters, or images requiring creative/contextual text.
    • Image-based instructions: Interpreting overlaid text, arrows, or annotations (e.g., "follow the instructions in the image").
    • Code and math reasoning: Visualizing algorithms, mathematical concepts, or code flow diagrams.

    For simple, direct prompts (e.g., "a red car"), upsampling may not provide significant benefits.

  5. Run FLUX.2 [klein] 9B KV Cache via CLI

    main

    The CLI automatically utilizes the KV cache when the --model_name is set to flux.2-klein-9b-kv.

    1. Start the CLI script:
      PYTHONPATH=src python scripts/cli.py --model_name flux.2-klein-9b-kv
    2. Once inside the interactive session, provide the reference images and prompt:
      • Set input_images as a comma-separated list of file paths.
      • Set prompt with your text description.
      • Execute the run command.
    PYTHONPATH=src python scripts/cli.py --model_name flux.2-klein-9b-kv
    
    # Inside the CLI session:
    > input_images="ref1.jpg,ref2.jpg"
    > prompt="a cat wearing sunglasses"
    > run
  6. Use FLUX.2 [dev] with Diffusers

    main

    For local deployment on consumer GPUs (e.g., RTX 4090 or RTX 5090), use the diffusers library. You can load a 4-bit quantized model and use a remote text-encoder to save local VRAM.

    To use a remote text-encoder, you must send a POST request to the Hugging Face prediction endpoint with your prompt and authorization token, then load the resulting prompt_embeds into the Flux2Pipeline.

    import torch
    from diffusers import Flux2Pipeline, Flux2Transformer2DModel
    from diffusers.utils import load_image
    from huggingface_hub import get_token
    import requests
    import io
    
    repo_id = "diffusers/FLUX.2-dev-bnb-4bit"
    device = "cuda:0"
    torch_dtype = torch.bfloat16
    
    def remote_text_encoder(prompts):
        response = requests.post(
            "https://remote-text-encoder-flux-2.huggingface.co/predict",
            json={"prompt": prompts},
            headers={
                "Authorization": f"Bearer {get_token()}",
                "Content-Type": "application/json"
            }
        )
        prompt_embeds = torch.load(io.BytesIO(response.content))
    
        return prompt_embeds.to(device)
    
    pipe = Flux2Pipeline.from_pretrained(
        repo_id, transformer=transformer, text_encoder=None, torch_dtype=torch_dtype
    ).to(device)
    
    prompt = "Realistic macro photograph of a hermit crab using a soda can as its shell, partially emerging from the can, captured with sharp detail and natural colors, on a sunlit beach with soft shadows and a shallow depth of field, with blurred ocean waves in the background. The can has the text `BFL Diffusers` on it and it has a color gradient that start with #FF5733 at the top and transitions to #33FF57 at the bottom."
    
    image = pipe(
        prompt_embeds=remote_text_encoder(prompt),
        #image=load_image("https://huggingface.co/spaces/zerogpu-aoti/FLUX.1-Kontext-Dev-fp8-dynamic/resolve/main/cat.png") #optional image input
        generator=torch.Generator(device=device).manual_seed(42),
        num_inference_steps=50, #28 steps can be a good trade-off
        guidance_scale=4,
    ).images[0]
    
    image.save("flux2_output.png")
  7. Choose the right FLUX.2 model for your needs

    main

    Select a model based on your hardware and application requirements:

    NeedRecommended
    Real-time apps, interactive workflows[klein] 4B, 9B, or 9B KV (distilled)
    Consumer GPU (e.g. RTX 3090/4070)[klein] 4B
    Fine-tuning, LoRA training[klein] Base or FLUX.2 [dev]
    Maximum quality, no latency constraintsFLUX.2 [dev]
  8. Use API-based prompt upsampling via OpenRouter

    main

    API-based upsampling via OpenRouter is the recommended method as it leverages more capable models.

    To use this method:

    1. Set your OPENROUTER_API_KEY environment variable.
    2. Run the CLI with --upsample_prompt_mode=openrouter.
    3. (Optional) Specify a specific model using --openrouter_model=<model_name>.

    Alternatively, you can run the CLI without the flag and choose the model interactively.

    export OPENROUTER_API_KEY="<api_key>"
    export PYTHONPATH=src
    python scripts/cli.py --upsample_prompt_mode=openrouter
  9. Install FLUX.2 via pip

    main

    To set up the inference environment, create a Python 3.12 virtual environment and install the package in editable mode. The code was tested on GB200 using CUDA 12.9.

    python3.12 -m venv .venv
    source .venv/bin/activate
    pip install -e . --extra-index-url https://download.pytorch.org/whl/cu129 --no-cache-dir
  10. Install dependencies for FLUX.2 with diffusers

    main

    To run FLUX.2 using the diffusers library, you must install the main branch of diffusers and upgrade transformers, accelerate, and bitsandbytes to their latest versions. Additionally, you must accept the gating on the FLUX.2-dev repository on Hugging Face and authenticate via the terminal.

    pip install git+https://github.com/huggingface/diffusers.git
    pip install --upgrade transformers accelerate bitsandbytes
    hf auth login
  11. Configure prompt upsampling modes

    main

    FLUX.2 supports three modes for upsampling prompts to improve generation quality:

    1. none (Default): Uses the provided prompt directly.
    2. local: Uses a local model to expand/upsample the prompt.
    3. openrouter: Uses an external model via the OpenRouter API. This requires an OPENROUTER_API_KEY environment variable. You can also specify a custom openrouter_model (e.g., qwen/qwen3-vl-235b-a22b-instruct).

    When using openrouter mode, you can optionally provide custom sampling parameters as a JSON object or key=value pairs.