Diffusers documentation
FLUX 3 Image Klein
FLUX 3 Image Klein
FLUX 3 Image Klein adalah model generasi gambar 5.6B dari Black Forest Labs: satu transformer (Flux3Transformer2DModel) menghasilkan gambar dari prompt teks, baik secara mandiri maupun bersama satu atau lebih gambar referensi. Kondisioning teks berasal dari Qwen3-VL, dan gambar menggunakan autoencoder terkemas FLUX.2 (AutoencoderKLFlux2).
FLUX 3 Image Klein hadir sebagai pipeline modular. Mulai dengan generasi teks-ke-gambar:
import torch
from diffusers import ModularPipeline
pipe = ModularPipeline.from_pretrained("black-forest-labs/flux-3-image-klein-base")
pipe.load_components(dtype={"vae": torch.float32, "default": torch.bfloat16})
pipe.to("cuda")
image = pipe(
prompt="A red fox in a snow-covered forest clearing at golden hour",
generator=torch.Generator().manual_seed(0),
output="images",
)[0]
image.save("fox.png")prompt adalah satu-satunya input yang wajib: pipeline membawa pengaturan sampling yang direkomendasikan (50 langkah, skala panduan 3.5, pergeseran penjadwal 6.93) dan secara default menghasilkan gambar berukuran 1024 x 1024. Menerima satu prompt per pemanggilan; gunakan num_images_per_prompt untuk beberapa gambar dari prompt yang sama.
Seperti yang dapat Anda lihat pada contoh di atas, proses pemuatan dan eksekusi sedikit berbeda dari DiffusionPipeline. Pemuatan bersifat lazy: from_pretrained() hanya membangun pipeline, dan Anda memanggil load_components() untuk memuat bobot. Panggilan mengembalikan status pipeline, dan Anda meminta apa yang Anda butuhkan dengan output: output="images" di sini, atau output=["images", "prompt"] untuk juga mendapatkan caption yang ditulis oleh prompt upsampler.
Jika Anda baru pertama kali bekerja dengan
ModularPipeline, baca quickstart, dan Coming from DiffusionPipeline jika Anda sudah familiar dengan pipeline standar. Selain pemuatan dan output, beberapa hal lain yang berbeda: guidance, callbacks, dan offloading.
Upsampling prompt
Prompting sangat penting: FLUX 3 Image Klein menerima caption adegan lengkap yang menggambarkan subjek, komposisi, pencahayaan, dan suasana, bukan prompt pendek; permintaan yang dikirimkan apa adanya akan menghasilkan output generik. Itulah mengapa pipeline menjalankan prompt upsampler terlebih dahulu untuk setiap permintaan, baik untuk text-to-image maupun editing. Ini adalah model 9B terpisah dari Black Forest Labs (black-forest-labs/flux-3-image-klein-pup) yang memperluas prompt menjadi caption seperti itu sebelum text encoder, dan prompt pendek saja sudah cukup.
Prompt upsampler mengubah permintaan singkat, beserta gambar referensi saat mengedit, menjadi caption adegan lengkap yang digunakan model: medium dan gaya, adegan, pencahayaan dan kamera, serta setiap subjek dengan warna, material, dan posisinya dalam bingkai. Satu model mencakup text-to-image, pengeditan dengan gambar referensi, dan tata letak dengan kotak. Caption yang ditulisnya dikembalikan sebagai output prompt. Pada contoh di atas, mintalah caption tersebut bersamaan dengan gambar untuk melihat apa yang diterima model gambar:
out = pipe(
prompt="A red fox in a snow-covered forest clearing at golden hour",
generator=torch.Generator().manual_seed(0),
output=["images", "prompt"],
)
print(out["prompt"])Full-color outdoor wildlife photograph taken from a low eye-level perspective in a snow-covered forest clearing at golden hour. In the center foreground, a red fox stands in profile facing left, its body turned toward the viewer and its head raised as it looks across the clearing. The fox has dense rust-red winter fur, a white throat and chest, black lower legs, pointed ears with dark tips, and a long bushy tail ending in white. ...Caption lengkapnya mencapai sekitar 240 kata; max_new_tokens membatasi panjangnya (3584 secara default).
Anda dapat mencetak doc langkah untuk melihat apa yang dibutuhkan dan apa yang ditulis:
print(pipe.blocks.sub_blocks["prompt_upsampler"].doc) Inputs:
prompt (`str`):
The edit instruction to expand into the full caption (one per call).
image (`Image | list`, *optional*):
The reference image(s) of the edit, at most 10; the same ones the pipeline receives.
boxes (`list`, *optional*):
Layout boxes, each {'id', 'desc', 'from', 'src_bbox', 'tgt_bbox'} with the boxes as [y_min, x_min, y_max, x_max] in
0-1: ...
max_new_tokens (`int`, *optional*, defaults to 3584):
The most tokens the upsampler may generate for the caption.
Outputs:
prompt (`str`):
The full caption, replacing the request.Seperti blok lain dalam pipeline, blok prompt_upsampler juga berjalan secara mandiri. Cara yang direkomendasikan adalah memisahkan blok tersebut: blok yang dipisahkan menjadi upsampler mandiri, dan blok-blok yang tersisa menjadi pipeline yang menerima caption yang diperluas sebagai prompt:
blocks = ModularPipeline.from_pretrained("black-forest-labs/flux-3-image-klein-base").blocks
pup_block = blocks.sub_blocks.pop("prompt_upsampler")
pup = pup_block.init_pipeline("black-forest-labs/flux-3-image-klein-base")
pup.load_components(dtype=torch.bfloat16)
pup.to("cuda")
caption = pup(prompt="A red fox in a snow-covered forest clearing at golden hour", output="prompt")
pipe = blocks.init_pipeline("black-forest-labs/flux-3-image-klein-base")
pipe.load_components(dtype={"vae": torch.float32, "default": torch.bfloat16})
pipe.to("cuda")
image = pipe(prompt=caption, generator=torch.Generator().manual_seed(0), output="images")[0]Dengan cara ini, tahap tersebut dapat disajikan sebagai tahap terpisah, pada GPU-nya sendiri atau di belakang endpoint-nya sendiri, dan UI dapat menampilkan caption yang ditulisnya serta memungkinkan pengguna mengeditnya sebelum menghasilkan gambar. LLM lain apa pun dapat menggantikan peran upsampler, dengan system prompt yang sama: berikan system_prompts["t2i"] dari repositori upsampler (atau "i2i", dengan referensi di awal pesan pengguna) sebagai system prompt dan permintaan sebagai pesan pengguna, lalu teruskan caption yang dikembalikannya sebagai prompt ke pipe.
Gambar-ke-gambar
Lewati satu atau lebih gambar referensi dengan image. Satu referensi dipertahankan utuh: hanya dikecilkan jika melebihi 4 megapiksel, ditambahkan padding ke grid 16 piksel, dan generasi secara default menggunakan ukurannya, sehingga hasil edit kembali dengan ukuran input. Beberapa referensi masing-masing disesuaikan di bawah 1 megapiksel dan dipotong ke grid, dan generasi secara default menggunakan ukuran yang pertama. Nilai height/width tertentu menimpa default. Jelaskan gambar target sebagai caption lengkap dari referensi dengan edit Anda yang sudah dimasukkan, bukan sebagai instruksi satu baris, atau biarkan prompt upsampler menulisnya dari instruksi dan referensi:
night = pipe(
prompt="the same scene at night under a full moon",
image=image,
generator=torch.Generator().manual_seed(0),
output=["images", "prompt"],
)Dengan beberapa referensi, sebutkan sebagai gambar pertama, gambar kedua, … sesuai urutan yang diteruskan ke image; caption menamainya <ref_image_0>, <ref_image_1>, … untuk model gambar:
combined = pipe(
prompt="the fox from the first image sitting on the wooden bench from the second image",
image=[image, bench],
height=768,
width=1360,
output="images",
)[0]Lewati height dan/atau width untuk menimpa ukuran yang diturunkan.
Kontrol tata letak
Untuk menempatkan konten secara eksplisit, berikan boxes: untuk setiap elemen, sebuah id, desc singkat, dan bbox berupa [y_min, x_min, y_max, x_max] dalam rentang 0-1 (asal di kiri-atas), sehingga tidak bergantung pada ukuran keluaran. Upsampler akan menulis caption di sekitar mereka, mengutip setiap elemen sebagai <id>, dan menambahkan tabel kotak, dengan milik Anda dipertahankan persis:
boxes = [
{"id": "balloon_1", "desc": "a red and yellow striped hot-air balloon", "bbox": [0.08, 0.06, 0.48, 0.38]},
{"id": "balloon_2", "desc": "a small blue hot-air balloon", "bbox": [0.20, 0.62, 0.42, 0.80]},
]
out = pipe(prompt="hot-air balloons over a green valley at sunrise", boxes=boxes, output=["images", "prompt"])Saat mengedit, sebuah kotak menamai sumbernya dengan from: "target" dengan tgt_bbox menambahkan elemen baru di sana, "ref_image_0" dengan src_bbox dan tgt_bbox memindahkan elemen dari referensi tersebut (kotak yang sama akan mempertahankan posisinya):
boxes = [{"id": "cactus", "desc": "a small potted cactus", "from": "target", "src_bbox": None, "tgt_bbox": [0.55, 0.62, 0.85, 0.85]}]
out = pipe(prompt="add a small potted cactus in the marked spot", image=mug, boxes=boxes, output=["images", "prompt"])
boxes = [{"id": "knight", "desc": "the knight figure", "from": "ref_image_0", "src_bbox": [0.50, 0.15, 0.85, 0.35], "tgt_bbox": [0.19, 0.06, 0.54, 0.26]}]
out = pipe(prompt="move the knight up and to the left, keep the rest unchanged", image=knight, boxes=boxes, output=["images", "prompt"])Caption yang dibaca model gambar memiliki elemen yang diberi tag <id> dalam teks dan tabel yang ditambahkan sebagai JSON, dengan kotak pada kanvas 0-1000; cetak output prompt untuk melihatnya. Caption yang ditulis dalam bentuk tersebut secara manual masuk ke pipeline tanpa langkah tersebut, seperti pada Prompt upsampling.
Skala panduan
Pipeline menerapkan classifier-free guidance melalui komponen guider dan tidak menerima argumen guidance_scale saat pemanggilan. Guider default adalah ClassifierFreeGuidance dengan guidance_scale=3.5, pengaturan yang direkomendasikan untuk kedua alur kerja. Untuk mengubahnya, buat salinan diperbarui dari guider:
pipe.guider = pipe.guider.new(guidance_scale=5.0)Lihat panduan panduan untuk beralih ke metode panduan yang berbeda.
Model yang telah di-distilasi per langkah
Checkpoint step-distilled menghasilkan dalam 16 langkah tanpa classifier-free guidance. Transformer-nya adalah flow map: pada setiap langkah, ia diberi tahu timestep saat ini dan timestep yang menjadi tujuan lompatan langkah tersebut. Ia dimuat seperti model dasar (file modular_model_index.json di repo merujuk ke Flux3DistilledModularPipeline dan Flux3DistilledAutoBlocks); pipeline tidak memiliki guider dan tidak menerima negative_prompt:
pipe = ModularPipeline.from_pretrained("black-forest-labs/flux-3-image-klein")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda")
image = pipe(prompt=prompt, generator=torch.Generator().manual_seed(0), output="images")[0]Itu melayani dua alur kerja yang sama seperti model dasar. num_inference_steps secara default adalah 16; model dilatih untuk 4 hingga 16 langkah.
Generasi yang dapat direproduksi
A generator fixes the noise the pipeline draws (see Reproducibility). To reuse noise drawn elsewhere, pass it as latents with shape (batch_size, 128, height // 16, width // 16). For example, the BFL implementation draws its noise as image tokens on the CPU and casts it to bf16; this reproduces its sample for a given seed:
height, width = 1024, 1024
h, w = height // 16, width // 16
noise = torch.randn((h * w, 128), generator=torch.Generator().manual_seed(0)).to(torch.bfloat16)
latents = noise.T.reshape(1, 128, h, w)
image = pipe(prompt=prompt, latents=latents, height=height, width=width, output="images")[0]Alur Kerja
Pipeline melayani dua alur kerja, text2image dan image_conditioned; alur kerja yang dijalankan dipilih berdasarkan input (image memilih image-to-image). from_pretrained() juga dapat membangun pipeline untuk satu alur kerja dengan argumen workflow, yang kemudian hanya mengharapkan dan memuat komponen yang dibutuhkan oleh alur kerja tersebut:
from diffusers.modular_pipelines import Flux3AutoBlocks
print(Flux3AutoBlocks().available_workflows)
# ["text2image", "image_conditioned"]
t2i = ModularPipeline.from_pretrained("black-forest-labs/flux-3-image-klein-base", workflow="text2image")
print(t2i.blocks.doc)Callback per langkah
Untuk menggunakan fungsi callback yang sudah ada, sisipkan blok ke dalam loop denoising. panduan callback memiliki contoh sederhana dengan blok CallbackOnStepEnd dan helper walk_denoise_loops:
blocks = Flux3AutoBlocks() # or Flux3DistilledAutoBlocks
for loop in walk_denoise_loops(blocks):
loop.sub_blocks["callback"] = CallbackOnStepEnd()
pipe = blocks.init_pipeline("black-forest-labs/flux-3-image-klein-base")
image = pipe(prompt=caption, callback_on_step_end=my_callback, output="images")[0]Untuk menghentikan lebih awal, lempar dari callback; tidak ada flag interrupt.
Memori
Memuat semuanya dalam bf16 membutuhkan sekitar 39 GB untuk bobot: transformer memiliki 5,5B parameter, encoder teks Qwen3-VL-4B 4B, dan prompt upsampler 9B (sekitar 19 GB sendirian), dengan VAE gambar dalam fp32. Pipeline yang dibangun tanpa langkah upsampler (lihat di sana) memuat sekitar 20 GB. Untuk GPU dengan memori lebih sedikit, aktifkan offloading komponen; manajer memindahkan komponen antara CPU dan GPU sesuai kebutuhan setiap langkah, termasuk upsampler:
from diffusers import ComponentsManager, ModularPipeline
manager = ComponentsManager()
pipe = ModularPipeline.from_pretrained("black-forest-labs/flux-3-image-klein-base", components_manager=manager)
pipe.load_components(dtype={"vae": torch.float32, "default": torch.bfloat16})
manager.enable_auto_cpu_offload(device="cuda")Memuat file tunggal
Flux3Transformer2DModel memuat transformer langsung dari paket model Black Forest Labs dengan from_single_file(). Paket config.json tidak dibaca; berikan konfigurasi diffusers dengan config dan subfolder.
import torch
from diffusers import Flux3Transformer2DModel, ModularPipeline
transformer = Flux3Transformer2DModel.from_single_file(
"https://huggingface.co/black-forest-labs/flux-3-image-klein-base/blob/main/model.safetensors",
config="black-forest-labs/flux-3-image-klein-base",
subfolder="transformer",
dtype=torch.bfloat16,
)
pipe = ModularPipeline.from_pretrained("black-forest-labs/flux-3-image-klein-base")
pipe.load_components(dtype={"vae": torch.float32, "default": torch.bfloat16})
pipe.update_components(transformer=transformer)
pipe.to("cuda")Muat komponen lainnya berdasarkan nama terlebih dahulu: load_components() tanpa names juga akan memuat transformer dari repo pipeline.
Memuat checkpoint single-file FP8r dan NVFP4 juga didukung. Keduanya dimuat melalui pemanggilan yang sama dengan BFLQuantizationConfig. Lihat panduan kuantisasi BFL untuk persyaratan kernel dari masing-masing skema.
from diffusers import BFLQuantizationConfig
transformer = Flux3Transformer2DModel.from_single_file(
"https://huggingface.co/black-forest-labs/flux-3-image-klein-base/blob/main/variants/nvfp4/model.safetensors",
config="black-forest-labs/flux-3-image-klein-base",
subfolder="transformer",
quantization_config=BFLQuantizationConfig(compute_dtype=torch.bfloat16),
dtype=torch.bfloat16,
)Saat memuat checkpoint step-distilled, kita membutuhkan konfigurasi mereka (flow_map=True):
transformer = Flux3Transformer2DModel.from_single_file(
"https://huggingface.co/black-forest-labs/flux-3-image-klein/blob/main/variants/nvfp4/model.safetensors",
config="black-forest-labs/flux-3-image-klein",
subfolder="transformer",
quantization_config=BFLQuantizationConfig(compute_dtype=torch.bfloat16),
dtype=torch.bfloat16,
)Flux3ModularPipeline
kelas diffusers.Flux3ModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
A ModularPipeline untuk FLUX.3.
Flux3AutoBlocks
Auto blocks yang melakukan generasi teks-ke-gambar dan gambar-ke-gambar menggunakan FLUX.3. prompt melewati prompt upsampler terlebih dahulu; hapus langkah prompt_upsampler untuk mengenkodnya sesuai yang diberikan.
Alur kerja yang didukung:
text2image: membutuhkanpromptimage_conditioned: membutuhkanprompt,image
Komponen:
prompt_upsampler (Qwen3_5ForConditionalGeneration): Prompt upsampler. prompt_upsampler_processor
(AutoProcessor): Prosesornya. text_encoder (Qwen3VLForConditionalGeneration) tokenizer
(AutoProcessor) image_processor (Flux3ImageProcessor) vae (AutoencoderKLFlux2) transformer
(Flux3Transformer2DModel) scheduler (FlowMatchEulerDiscreteScheduler) guider (ClassifierFreeGuidance)
Inputs:
prompt (str):
The edit instruction to expand into the full caption (one per call).
image (Image | list, optional):
The reference image(s) of the edit, at most 10; the same ones the pipeline receives.
boxes (list, optional):
Layout boxes, each {‘id’, ‘desc’, ‘from’, ‘src_bbox’, ‘tgt_bbox’} with the boxes as [y_min, x_min, y_max,
x_max] in 0-1: ‘from’: ‘target’ with tgt_bbox adds an element there, ‘from’: ‘ref_image_0’, … with src_bbox and tgt_bbox moves one from a reference image.
max_new_tokens (int, optional, defaults to 3584):
The most tokens the upsampler may generate for the caption.
negative_prompt (str, optional):
The prompt not to guide the generation
max_sequence_length (int, optional, defaults to 8192):
Maximum number of prompt tokens; longer prompts are truncated.
text_encoder_out_layers (tuple, optional, defaults to (4, 8, 12, 16, 20, 24, 28, 32)):
Indices of the text-encoder hidden layers whose states are stacked to form the text embeddings
num_images_per_prompt (int, optional, defaults to 1):
The number of images to generate per prompt.
image_cond_latents (list, optional):
Normalized packed latents of the reference images, one tensor of shape (B, C, height_i//16, width_i//16)
per image
height (int, optional, defaults to None or 1024, depending on the workflow):
The height in pixels of the generated image; defaults to the first reference image’s own height
width (int, optional, defaults to None or 1024, depending on the workflow):
The width in pixels of the generated image; defaults to the first reference image’s own width
reference_crop (list | NoneType, optional):
Per reference, the box of the reference inside its padded canvas or None, from the preprocess step
latents (Tensor):
Pre-generated noisy latents for image generation.
generator (Generator, optional):
Torch generator for deterministic generation.
num_inference_steps (int):
The number of denoising steps.
timesteps (Tensor):
Timesteps for the denoising process. (overrides num_inference_steps when provided)
sigmas (list, optional):
Custom sigmas for the denoising process. (overrides num_inference_steps when provided)
*denoiser_input_fields (None,optional):
conditional model inputs for the denoiser: e.g. prompt_embeds, negative_prompt_embeds, etc.
attention_kwargs (dict,optional):
Additional kwargs for attention processors.
output_type (str,optional*, defaults to pil):
Output format: ‘pil’, ‘np’, ‘pt’.
Output:
images (list):
Gambar yang dihasilkan.
latents (Tensor):
Latents yang telah didenois.
Flux3DistilledAutoBlocks
Auto memblokir yang melakukan generasi teks-ke-gambar dan gambar-ke-gambar menggunakan model FLUX.3 yang telah di-distilkan langkahnya (16 langkah, tanpa classifier-free guidance). prompt melewati prompt upsampler terlebih dahulu; hapus langkah prompt_upsampler untuk mengenkodnya sesuai yang diberikan.
Alur kerja yang didukung:
text2image: membutuhkanpromptimage_conditioned: membutuhkanprompt,image
Komponen:
prompt_upsampler (Qwen3_5ForConditionalGeneration): Upsampler prompt. prompt_upsampler_processor
(AutoProcessor): Prosesornya. text_encoder (Qwen3VLForConditionalGeneration) tokenizer
(AutoProcessor) image_processor (Flux3ImageProcessor) vae (AutoencoderKLFlux2) transformer
(Flux3Transformer2DModel) scheduler (FlowMatchEulerDiscreteScheduler)
Inputs:
prompt (str):
The edit instruction to expand into the full caption (one per call).
image (Image | list, optional):
The reference image(s) of the edit, at most 10; the same ones the pipeline receives.
boxes (list, optional):
Layout boxes, each {‘id’, ‘desc’, ‘from’, ‘src_bbox’, ‘tgt_bbox’} with the boxes as [y_min, x_min, y_max,
x_max] in 0-1: ‘from’: ‘target’ with tgt_bbox adds an element there, ‘from’: ‘ref_image_0’, … with src_bbox and tgt_bbox moves one from a reference image.
max_new_tokens (int, optional, defaults to 3584):
The most tokens the upsampler may generate for the caption.
max_sequence_length (int, optional, defaults to 8192):
Maximum number of prompt tokens; longer prompts are truncated.
text_encoder_out_layers (tuple, optional, defaults to (4, 8, 12, 16, 20, 24, 28, 32)):
Indices of the text-encoder hidden layers whose states are stacked to form the text embeddings
num_images_per_prompt (int, optional, defaults to 1):
The number of images to generate per prompt.
image_cond_latents (list, optional):
Normalized packed latents of the reference images, one tensor of shape (B, C, height_i//16, width_i//16)
per image
height (int, optional, defaults to None or 1024, depending on the workflow):
The height in pixels of the generated image; defaults to the first reference image’s own height
width (int, optional, defaults to None or 1024, depending on the workflow):
The width in pixels of the generated image; defaults to the first reference image’s own width
reference_crop (list | NoneType, optional):
Per reference, the box of the reference inside its padded canvas or None, from the preprocess step
latents (Tensor):
Pre-generated noisy latents for image generation.
generator (Generator, optional):
Torch generator for deterministic generation.
num_inference_steps (int):
The number of denoising steps.
timesteps (Tensor):
Timesteps for the denoising process. (overrides num_inference_steps when provided)
sigmas (list, optional):
Custom sigmas for the denoising process. (overrides num_inference_steps when provided)
*denoiser_input_fields (None,optional):
conditional model inputs for the denoiser: e.g. prompt_embeds, negative_prompt_embeds, etc.
output_type (str,optional*, defaults to pil):
Output format: ‘pil’, ‘np’, ‘pt’.
Output:
images (list):
Gambar yang dihasilkan.
latents (Tensor):
Latents yang telah didenois.
Flux3DistilledModularPipeline
kelas diffusers.Flux3DistilledModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
ModularPipeline untuk model FLUX.3 yang telah di-distil langkah (16 langkah, tanpa classifier-free guidance).