【Diffusers】FLUX.1 の派生モデル FLUX.1 Kontext [dev] を使ってみる

はじめに

FLUX.1 Kontextはテキスト指示で画像を編集することができるFlux.1の派生モデルです。
huggingface.co

結果

左が元画像、右がテキスト指示で編集した画像(今回作成した画像)です。

プロンプトは以下の通りです。

Make the lady hold a sign that says 'Black Forest Labs is awesome'

やっていることはOmniGenやMGIEに近いと思います。
touch-sp.hatenablog.com
touch-sp.hatenablog.com

pythonスクリプト

VRAM使用量が多かったのでbitsandbytesを使って4bit量子化をしています。

import torch
from diffusers import FluxKontextPipeline
from diffusers.utils import load_image
from diffusers.quantizers import PipelineQuantizationConfig

pipeline_quant_config = PipelineQuantizationConfig(
    quant_backend="bitsandbytes_4bit",
    quant_kwargs={
        "load_in_4bit": True,
        "bnb_4bit_quant_type":"nf4",
        "bnb_4bit_compute_dtype": torch.bfloat16
    },
    components_to_quantize=["transformer", "text_encoder_2"],
)

pipe = FluxKontextPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-Kontext-dev",
    quantization_config=pipeline_quant_config,
    torch_dtype=torch.bfloat16
)

pipe.to("cuda")

image = load_image("girl.jpg").convert("RGB")

prompt = "Make the lady hold a sign that says 'Black Forest Labs is awesome'"

image = pipe(
    image=image,
    prompt=prompt,
    guidance_scale=2.5,
    generator=torch.Generator().manual_seed(42)
).images[0]

image.save("output.png")

環境構築

pip install torch==2.7.1+cu126 --index-url https://download.pytorch.org/whl/cu126
pip install diffusers
pip install transformers accelerate protobuf sentencepiece bitsandbytes