Diffusers documentation
FLUX 3 Image Klein
FLUX 3 Image Klein
FLUX 3 Image Klein 是 Black Forest Labs 推出的 5.6B 图像生成模型:单个 Transformer(Flux3Transformer2DModel)可根据文本提示生成图像,也可结合一张或多张参考图像进行生成。文本条件来自 Qwen3-VL,图像则使用 FLUX.2 打包自编码器(AutoencoderKLFlux2)。
FLUX 3 Image Klein 以模块化流水线的形式发布。从文本到图像生成开始:
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 是唯一必需的输入:该流水线会携带推荐的采样设置(50 步、guidance scale 3.5、scheduler shift 6.93),并默认生成 1024 x 1024 的图像。每次调用仅接受一个 prompt;若需为同一 prompt 生成多张图像,请使用 num_images_per_prompt。
如上例所示,加载和运行方式与 DiffusionPipeline 略有不同。加载是惰性的:from_pretrained() 仅构建流水线,你需要调用 load_components() 来加载权重。调用后返回流水线状态,你可以通过 output 来指定所需内容:此处为 output="images",或者使用 output=["images", "prompt"] 以同时获取提示词上采样器生成的说明文本。
如果您首次使用
ModularPipeline,请先阅读快速入门;如果您熟悉标准流水线,请阅读从 DiffusionPipeline 迁移。除了加载和输出之外,还有几处不同:guidance、callbacks 和 offloading。
提示词上采样
提示词至关重要:FLUX 3 Image Klein 需要完整的场景描述,涵盖主体、构图、光照和氛围,而非简短的提示词;直接输入简短请求只会得到泛化的输出。正因如此,该流水线在处理每个请求时(无论是文生图还是图像编辑)都会先运行提示词扩展器。这是 Black Forest Labs 的一个独立 9B 模型(black-forest-labs/flux-3-image-klein-pup),它会在文本编码器之前将 prompt 扩展为上述类型的场景描述,因此只需提供简短的提示词即可。
提示词扩展器会将简短的请求(在编辑时还包括参考图像)转化为模型所需的完整场景描述:涵盖中景与风格、场景、光照与镜头,以及每个主体的颜色、材质和在画面中的位置。一个模型即可覆盖文生图、基于参考图像的编辑以及基于框的布局。它生成的描述会作为 prompt 输出返回。在上面的示例中,可以请求同时返回图像,以查看图像模型实际接收到的内容:
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. ...完整字幕长度约为 240 个词;max_new_tokens 用于限制其长度(默认值为 3584)。
您可以打印该步骤的 doc,以查看其输入和输出内容:
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.与流水线中的其他块一样,prompt_upsampler 块也是独立运行的。推荐的做法是将其从块中弹出:弹出的块将成为一个独立的提示词扩展器,而剩余的块则构成一个流水线,将扩展后的描述作为 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]这样,它可以作为一个独立的阶段进行部署,运行在单独的 GPU 上或位于独立的端点之后,UI 可以展示其生成的描述文本,并允许用户在生成图像前对其进行编辑。任何其他 LLM 都可以替代上采样器,使用相同的系统提示词:将上采样器仓库中的 system_prompts["t2i"](或 "i2i",其中参考图像位于用户消息的开头)作为系统提示词,将请求作为用户消息,并将其返回的描述文本作为 prompt 传递给 pipe。
图像到图像
通过 image 传入一张或多张参考图像。单张参考图像会保持完整:仅在超过 400 万像素时进行下采样,填充至 16 像素网格,且生成默认采用其尺寸,因此编辑结果与输入尺寸一致。多张参考图像则各自被调整至 100 万像素以内并裁剪至网格,生成默认采用第一张的尺寸。指定的 height/width 会覆盖默认值。请将 目标 图像描述为包含编辑内容的参考图像完整说明,而非单行指令;或者让 prompt upsampler 根据指令和参考图像来撰写该说明:
night = pipe(
prompt="the same scene at night under a full moon",
image=image,
generator=torch.Generator().manual_seed(0),
output=["images", "prompt"],
)当提供多个参考图像时,请按照传入 image 的顺序,将它们称为第一张图像、第二张图像……;在图像模型中,标题将它们命名为 <ref_image_0>、<ref_image_1>……
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]传入 height 和/或 width 以覆盖推导出的尺寸。
布局控制
若要显式放置内容,请传入 boxes:为每个元素指定一个 id、简短的 desc,以及一个 bbox,其格式为 [y_min, x_min, y_max, x_max],取值范围为 0-1(原点位于左上角),从而使其与输出尺寸无关。上采样器会在这些框周围生成描述,并以 <id> 的形式引用每个元素,最后附上框的表格,其中您提供的框将原样保留:
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"])在编辑时,一个框通过 from 指定其来源:"target" 配合 tgt_bbox 会在该位置添加一个新元素;"ref_image_0" 配合 src_bbox 和 tgt_bbox 会移动该参考图像中的一个元素(若两个框相同,则元素保持原位):
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"])图像模型读取的说明文本中,元素以 <id> 标记,表格以 JSON 形式附加,且框的位置基于 0-1000 的画布;打印 prompt 的输出即可查看。若手动编写该形式的说明文本,则无需经过此步骤即可传入流水线,如 Prompt upsampling 中所述。
引导比例
该 pipeline 通过其 guider 组件应用 classifier-free guidance,并且在调用时不接受 guidance_scale 参数。默认的 guider 是 ClassifierFreeGuidance,其 guidance_scale=3.5,这是两种工作流均推荐的设置。若要更改它,请创建一个更新后的 guider 副本:
pipe.guider = pipe.guider.new(guidance_scale=5.0)请参阅guiders 指南以切换到不同的引导方法。
步数蒸馏模型
步数蒸馏检查点可在 16 步内生成,且无需分类器自由引导。其 Transformer 是一个流映射:在每一步中,它都会被告知当前时间步以及该步所跳转到的目标时间步。它的加载方式与基础模型相同(该仓库的 modular_model_index.json 解析为 Flux3DistilledModularPipeline 和 Flux3DistilledAutoBlocks);该流水线没有 guider,也不接受 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]它支持与基础模型相同的两种工作流。num_inference_steps 的默认值为 16;该模型经过 4 到 16 步的训练。
可复现的生成
generator 用于固定流水线所采样的噪声(参见 可复现性)。若要复用其他位置采样的噪声,请将其作为 latents 传入,其形状应为 (batch_size, 128, height // 16, width // 16)。例如,BFL 实现 在 CPU 上将噪声采样为图像 token,并将其转换为 bf16;对于给定的种子,这可以复现其采样结果:
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]工作流程
该流水线支持两种工作流:text2image 和 image_conditioned;实际执行哪一种由输入决定(传入 image 即选择图生图)。from_pretrained() 也可以通过 workflow 参数为单一工作流构建流水线,此时它只会加载该工作流所需的组件:
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)逐步回调
若要使用现有的回调函数,请在去噪循环中插入一个代码块。callbacks 指南提供了一个使用 CallbackOnStepEnd 代码块和 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]若要提前停止,请从回调中抛出异常;不存在 interrupt 标志。
内存
以 bf16 格式加载所有内容大约需要 39 GB 的权重:transformer 为 5.5B 参数,Qwen3-VL-4B 文本编码器为 4B,prompt upsampler 为 9B(单独占用约 19 GB),图像 VAE 则以 fp32 格式加载。如果构建的 pipeline 不包含 upsampler 步骤(参见此处),则加载量约为 20 GB。对于显存较小的 GPU,请启用组件卸载(component offloading);管理器会在每个步骤需要时,在 CPU 和 GPU 之间移动组件,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")单文件加载
Flux3Transformer2DModel 通过 from_single_file() 直接从 Black Forest Labs 的模型包中加载 transformer。该包中的 config.json 不会被读取;请通过 config 和 subfolder 传入 diffusers 配置。
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")首先按名称加载其他组件:如果不指定 names,load_components() 也会从流水线仓库中加载 transformer。
同样支持加载 FP8r 和 NVFP4 单文件检查点。两者均通过相同的调用方式加载,并使用 BFLQuantizationConfig。有关每种方案的 kernel 要求,请参阅 BFL 量化指南。
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,
)加载步数蒸馏检查点时,我们需要它们的配置(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
class 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 )
用于 FLUX.3 的 ModularPipeline。
Flux3AutoBlocks
使用 FLUX.3 执行文本生成图像和图像生成图像任务的 Auto 块。prompt 会先经过提示词上采样器;若弹出 prompt_upsampler 步骤,则会按原样对其进行编码。
支持的工作流:
text2image:需要promptimage_conditioned:需要prompt、image
组件:
prompt_upsampler (Qwen3_5ForConditionalGeneration):提示词增强器。prompt_upsampler_processor
(AutoProcessor):其对应的处理器。text_encoder (Qwen3VLForConditionalGeneration) tokenizer
(AutoProcessor) image_processor (Flux3ImageProcessor) vae (AutoencoderKLFlux2) transformer
(Flux3Transformer2DModel) scheduler (FlowMatchEulerDiscreteScheduler) guider (ClassifierFreeGuidance)
输入:
prompt (str):
用于扩展为完整描述的编辑指令(每次调用一个)。
image (Image | list,可选):
编辑的参考图像,最多 10 张;与流水线接收的图像相同。
boxes (list,可选):
布局框,每个框为 {‘id’, ‘desc’, ‘from’, ‘src_bbox’, ‘tgt_bbox’},其中框的坐标为 [y_min, x_min, y_max, x_max],取值范围为 0-1:‘from’: ‘target’ 配合 tgt_bbox 表示在该位置添加一个元素;‘from’: ‘ref_image_0’,… 配合 src_bbox 和 tgt_bbox 表示从参考图像中移动一个元素。
max_new_tokens (int,可选,默认为 3584):
upsampler 为描述生成的最大 token 数。
negative_prompt (str,可选):
用于不引导生成的提示词。
max_sequence_length (int,可选,默认为 8192):
提示词 token 的最大数量;较长的提示词将被截断。
text_encoder_out_layers (tuple,可选,默认为 (4, 8, 12, 16, 20, 24, 28, 32)):
文本编码器隐藏层的索引,这些层的状态将被堆叠以形成文本嵌入。
num_images_per_prompt (int,可选,默认为 1):
每个提示词生成的图像数量。
image_cond_latents (list,可选):
参考图像的归一化打包潜变量,每张图像对应一个形状为 (B, C, height_i//16, width_i//16) 的张量。
height (int,可选,默认为 None 或 1024,具体取决于工作流):
生成图像的高度(像素);默认为第一张参考图像自身的高度。
width (int,可选,默认为 None 或 1024,具体取决于工作流):
生成图像的宽度(像素);默认为第一张参考图像自身的宽度。
reference_crop (list | NoneType,可选):
对于每个参考图像,其在填充画布内的框,或 None,来自预处理步骤。
latents (Tensor):
用于图像生成的预生成噪声潜变量。
generator (Generator,可选):
用于确定性生成的 Torch 生成器。
num_inference_steps (int):
去噪步骤数。
timesteps (Tensor):
去噪过程的时间步。(提供时会覆盖 num_inference_steps)
sigmas (list,可选):
去噪过程的自定义 sigmas。(提供时会覆盖 num_inference_steps)
*denoiser_input_fields (None,optional):
去噪器的条件模型输入:例如 prompt_embeds、negative_prompt_embeds 等。
attention_kwargs (dict,optional):
注意力处理器的额外 kwargs。
output_type (str,optional*,默认为 pil):
输出格式:‘pil’、‘np’、‘pt’。
输出:
images (list):
生成的图像。
latents (Tensor):
去噪后的潜在变量。
Flux3DistilledAutoBlocks
Auto 块使用步数蒸馏的 FLUX.3 模型(16 步,无分类器自由引导)执行文本到图像和图像到图像生成。prompt 会先经过提示词增强器;若弹出 prompt_upsampler 步骤,则按原样对其进行编码。
支持的工作流:
text2image:需要promptimage_conditioned:需要prompt、image
组件:
prompt_upsampler (Qwen3_5ForConditionalGeneration):提示词增强器。prompt_upsampler_processor
(AutoProcessor):其对应的处理器。text_encoder (Qwen3VLForConditionalGeneration) tokenizer
(AutoProcessor) image_processor (Flux3ImageProcessor) vae (AutoencoderKLFlux2) transformer
(Flux3Transformer2DModel) scheduler (FlowMatchEulerDiscreteScheduler)
输入:
prompt (str):
用于扩展为完整描述的编辑指令(每次调用一个)。
image (Image | list,可选):
编辑的参考图像,最多 10 张;与流水线接收的图像相同。
boxes (list,可选):
布局框,每个框为 {‘id’, ‘desc’, ‘from’, ‘src_bbox’, ‘tgt_bbox’},其中框的坐标为 [y_min, x_min, y_max, x_max],取值范围为 0-1:‘from’: ‘target’ 且带有 tgt_bbox 表示在该位置添加一个元素;‘from’: ‘ref_image_0’,… 且带有 src_bbox 和 tgt_bbox 表示从参考图像中移动一个元素。
max_new_tokens (int,可选,默认为 3584):
描述生成器为描述生成的最大 token 数。
max_sequence_length (int,可选,默认为 8192):
提示词 token 的最大数量;较长的提示词将被截断。
text_encoder_out_layers (tuple,可选,默认为 (4, 8, 12, 16, 20, 24, 28, 32)):
文本编码器隐藏层的索引,这些层的状态将被堆叠以形成文本嵌入
num_images_per_prompt (int,可选,默认为 1):
每个提示词生成的图像数量。
image_cond_latents (list,可选):
参考图像的归一化打包潜在变量,每张图像对应一个形状为 (B, C, height_i//16, width_i//16) 的张量
height (int,可选,默认为 None 或 1024,具体取决于工作流):
生成图像的高度(像素);默认为第一张参考图像自身的高度
width (int,可选,默认为 None 或 1024,具体取决于工作流):
生成图像的宽度(像素);默认为第一张参考图像自身的宽度
reference_crop (list | NoneType,可选):
对于每个参考图像,其在填充画布内的框,或 None,来自预处理步骤
latents (Tensor):
用于图像生成的预生成噪声潜在变量。
generator (Generator,可选):
用于确定性生成的 Torch 生成器。
num_inference_steps (int):
去噪步骤数。
timesteps (Tensor):
去噪过程的时间步。(提供时会覆盖 num_inference_steps)
sigmas (list,可选):
去噪过程的自定义 sigmas。(提供时会覆盖 num_inference_steps)
*denoiser_input_fields (None,optional):
去噪器的条件模型输入:例如 prompt_embeds、negative_prompt_embeds 等。
output_type (str,optional*,默认为 pil):
输出格式:‘pil’、‘np’、‘pt’。
输出:
images (list):
生成的图像。
latents (Tensor):
去噪后的潜在变量。
Flux3DistilledModularPipeline
class 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 )
用于步数蒸馏 FLUX.3 模型(16 步,无分类器自由引导)的 ModularPipeline。