Diffusers documentation
Flux2
Flux2
Flux.2 是 Black Forest Labs 近期推出的图像生成模型系列,其前身为 Flux.1 系列。这是一个全新的模型,采用了新的架构,并从头开始进行了预训练!
Flux 的原始模型检查点可在此处找到。原始推理代码可在此处找到。
Flux2 在消费级硬件设备上运行成本可能较高。不过,你可以执行一系列优化,使其运行得更快且对内存更友好。有关更多详细信息,请参阅 本节。此外,Flux 可以通过量化来提升内存效率,但代价是推理延迟会增加。要了解更多信息,请参考 这篇博客文章。
缓存还可以通过存储和复用中间输出来加速推理。
标题上采样
Flux.2 在配合更优质的提示词时,有可能生成更好的输出。我们可以通过在管道调用参数中设置 caption_upsample_temperature 参数,对输入提示词进行“上采样”。官方实现 建议将该值设为 0.15。
Flux2Pipeline
class diffusers.Flux2Pipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLFlux2text_encoder: Mistral3ForConditionalGenerationtokenizer: AutoProcessortransformer: Flux2Transformer2DModel )
参数
- transformer (Flux2Transformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer(MMDiT)架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (
AutoencoderKLFlux2) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。 - text_encoder (
Mistral3ForConditionalGeneration) — Mistral3ForConditionalGeneration - tokenizer (
AutoProcessor) — PixtralProcessor 类的分词器。
用于文本到图像生成的 Flux2 流水线。
__call__
< source >( image: PIL.Image.Image | list[PIL.Image.Image] | None = Noneprompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float | None = 4.0num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512text_encoder_out_layers: tuple = (10, 20, 30)caption_upsample_temperature: float = None ) → ~pipelines.flux2.Flux2PipelineOutput or tuple
参数
- image (
torch.Tensor、PIL.Image.Image、np.ndarray、list[torch.Tensor]、list[PIL.Image.Image]或list[np.ndarray]) —Image、numpy 数组或张量,表示用作起点的图像批次。对于 numpy 数组和 PyTorch 张量,预期的取值范围为[0, 1]。如果是张量或张量列表,预期的形状应为(B, C, H, W)或(C, H, W)。如果是 numpy 数组或数组列表,预期的形状应为(B, H, W, C)或(H, W, C)。它也可以接受图像潜变量作为image,但如果直接传入潜变量,则不会再次进行编码。 - prompt (
str或list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - guidance_scale (
float, 可选, ,默认值为 1.0)—— 通过设置guidance_scale> 1. 更高的guidance_scale值,可以促使模型生成与prompt更加一致的图像,但代价是图像质量会降低。Guidance-distilled 模型近似了
guidance_scale> 1 时的真实 classifier-free guidance。有关详细信息,请参阅 论文。 - height (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - width (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - sigmas (
list[float],可选) — 用于在支持sigmas参数的调度器的set_timesteps方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - generator (
torch.Generator或list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.qwenimage.QwenImagePipelineOutput而不是普通元组。 - attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的AttentionProcessor,该处理器在self.processor下定义。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传入。您只能包含流水线类的._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为 512)— 与prompt配合使用的最大序列长度。 - text_encoder_out_layers (
tuple[int]) — 用于从text_encoder中获取最终提示嵌入的层索引。 - caption_upsample_temperature (
float) — 如果指定了该参数,我们将尝试执行 caption upsampling,以可能获得更好的输出。如果打算执行 caption upsampling,我们建议将其设置为 0.15。
返回值
~pipelines.flux2.Flux2PipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.flux2.Flux2PipelineOutput,否则返回 tuple。当返回元组时,第一个元素是一个包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers import Flux2Pipeline
>>> pipe = Flux2Pipeline.from_pretrained("black-forest-labs/FLUX.2-dev", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> # Depending on the variant being used, the pipeline call will slightly vary.
>>> # Refer to the pipeline documentation for more details.
>>> image = pipe(prompt, num_inference_steps=50, guidance_scale=2.5).images[0]
>>> image.save("flux.png")Flux2KleinPipeline
class diffusers.Flux2KleinPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLFlux2text_encoder: Qwen3ForCausalLMtokenizer: Qwen2Tokenizertransformer: Flux2Transformer2DModelis_distilled: bool = False )
参数
- transformer (Flux2Transformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer(MMDiT)架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (
AutoencoderKLFlux2) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。 - text_encoder(
Qwen3ForCausalLM)— Qwen3ForCausalLM - tokenizer(
Qwen2TokenizerFast)— Qwen2TokenizerFast 类的分词器。
用于文本到图像生成的 Flux2 Klein 流水线。
参考:https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence
__call__
< source >( image: list[PIL.Image.Image] | PIL.Image.Image | None = Noneprompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 4.0num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: str | list[str] | None = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512text_encoder_out_layers: tuple = (9, 18, 27) ) → ~pipelines.flux2.Flux2PipelineOutput or tuple
参数
- image (
torch.Tensor、PIL.Image.Image、np.ndarray、List[torch.Tensor]、List[PIL.Image.Image]或List[np.ndarray]) —Image、numpy 数组或张量,表示用作起点的图像批次。对于 numpy 数组和 PyTorch 张量,预期的取值范围为[0, 1]。如果是张量或张量列表,预期的形状应为(B, C, H, W)或(C, H, W)。如果是 numpy 数组或数组列表,预期的形状应为(B, H, W, C)或(H, W, C)。它也可以接受图像潜变量作为image,但如果直接传入潜变量,则不会再次进行编码。 - prompt (
str或List[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入prompt_embeds。 - guidance_scale (
float,可选,默认为 4.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale定义为 Imagen Paper 中公式 2 的w。通过设置guidance_scale > 1来启用引导尺度。较高的引导尺度会促使生成与文本prompt紧密关联的图像,通常以牺牲图像质量为代价。对于逐步蒸馏模型,guidance_scale将被忽略。 - height (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的高度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - width (
int,可选,默认为 self.unet.config.sample_size * self.vae_scale_factor) — 生成图像的宽度(以像素为单位)。默认设置为 1024,以获得最佳效果。 - num_inference_steps (
int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。 - sigmas (
List[float], 可选) — 用于支持在set_timesteps方法中接受sigmas参数的调度器的去噪过程的自定义 sigmas。如果未定义,则使用传入num_inference_steps时的默认行为。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - generator (
torch.Generator或List[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。 - latents (
torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样得到,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从prompt输入参数生成。 - negative_prompt_embeds (
torch.Tensor, 可选) — 预生成的负向文本嵌入。请注意,在此流水线中,"" 被用作负向提示词。 如果未提供,将从 "" 生成。 - output_type (
str,可选,默认为"pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image或np.array。 - return_dict (
bool,可选,默认为True) — 是否返回~pipelines.qwenimage.QwenImagePipelineOutput而不是普通元组。 - attention_kwargs (
dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的AttentionProcessor,该处理器在self.processor下定义。 - callback_on_step_end (
Callable, 可选) — 一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)。callback_kwargs将包含由callback_on_step_end_tensor_inputs指定的所有张量列表。 - callback_on_step_end_tensor_inputs (
List,可选) —callback_on_step_end函数的张量输入列表。列表中指定的张量将作为callback_kwargs参数传入。您只能包含流水线类的._callback_tensor_inputs属性中列出的变量。 - max_sequence_length(
int,默认为 512)— 与prompt配合使用的最大序列长度。 - text_encoder_out_layers (
tuple[int]) — 用于从text_encoder中获取最终提示嵌入的层索引。
返回值
~pipelines.flux2.Flux2PipelineOutput 或 tuple
如果 return_dict 为 True,则返回 ~pipelines.flux2.Flux2PipelineOutput,否则返回 tuple。当返回元组时,第一个元素是一个包含生成图像的列表。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from diffusers import Flux2KleinPipeline
>>> pipe = Flux2KleinPipeline.from_pretrained(
... "black-forest-labs/FLUX.2-klein-base-9B", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> # Depending on the variant being used, the pipeline call will slightly vary.
>>> # Refer to the pipeline documentation for more details.
>>> image = pipe(prompt, num_inference_steps=50, guidance_scale=4.0).images[0]
>>> image.save("flux2_output.png")Flux2KleinKVPipeline
class diffusers.Flux2KleinKVPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLFlux2text_encoder: Qwen3ForCausalLMtokenizer: Qwen2Tokenizertransformer: Flux2Transformer2DModelis_distilled: bool = True )
参数
- transformer (Flux2Transformer2DModel) — 用于对编码后的图像潜变量进行去噪的条件 Transformer(MMDiT)架构。
- scheduler (FlowMatchEulerDiscreteScheduler) —
用于与
transformer配合,对编码后的图像潜变量进行去噪的调度器。 - vae (
AutoencoderKLFlux2) — 变分自编码器(VAE)模型,用于将图像编码为潜在表示,以及从潜在表示解码为图像。 - text_encoder(
Qwen3ForCausalLM)— Qwen3ForCausalLM - tokenizer(
Qwen2TokenizerFast)— Qwen2TokenizerFast 类的分词器。
用于文本到图像生成的 Flux2 Klein KV 流水线,支持基于 KV 缓存的参考图像条件输入。
在第一个去噪步骤中,参考图像的 token 会包含在前向传播中,其注意力的 K/V 投影会被缓存。在后续步骤中,缓存的 K/V 会被直接复用而无需重新计算,从而在使用参考图像时提供更快的推理速度。
参考:https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence
__call__
< source >( image: list[PIL.Image.Image] | PIL.Image.Image | None = Noneprompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 4sigmas: list[float] | None = Nonenum_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512text_encoder_out_layers: tuple = (9, 18, 27) )
参数
- image (
PIL.Image.Image或List[PIL.Image.Image],可选) — 用于条件控制的参考图像。在第一个去噪步骤中,参考 token 会被包含在前向传播中,其注意力 K/V 会被缓存。在后续步骤中,将直接复用缓存的 K/V,而无需重新计算。 - prompt (
str或List[str],可选) — 用于引导图像生成的提示词或提示词列表。 - height (
int, 可选) — 生成图像的高度(以像素为单位)。 - width (
int, 可选) — 生成图像的宽度(以像素为单位)。 - num_inference_steps (
int,可选,默认为 4) — 去噪步数。 - sigmas (
List[float],可选) — 用于去噪调度的自定义 sigmas。 - num_images_per_prompt (
int,可选,默认为 1) — 每个提示词生成的图像数量。 - generator (
torch.Generator或List[torch.Generator],可选) — 用于确定性生成的生成器。 - latents (
torch.Tensor, 可选) — 预生成的含噪潜变量。 - prompt_embeds (
torch.Tensor, 可选) — 预生成的文本嵌入。 - output_type (
str,可选,默认为"pil") — 输出格式:"pil"或"np"。 - return_dict (
bool,可选,默认为True) — 是否返回Flux2PipelineOutput或普通元组。 - attention_kwargs (
dict,可选) — 传递给注意力处理器的额外 kwargs。 - callback_on_step_end (
Callable, 可选) — 在每个去噪步骤结束时调用的回调函数。 - callback_on_step_end_tensor_inputs(
List,可选)— 回调函数的张量输入。 - max_sequence_length (
int,默认为 512) — 提示词的最大序列长度。 - text_encoder_out_layers (
tuple[int]) — 用于提取文本编码器隐藏状态的层索引。
调用生成 pipeline 时调用的函数。
示例:
>>> import torch
>>> from PIL import Image
>>> from diffusers import Flux2KleinKVPipeline
>>> pipe = Flux2KleinKVPipeline.from_pretrained(
... "black-forest-labs/FLUX.2-klein-9b-kv", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> ref_image = Image.open("reference.png")
>>> image = pipe("A cat dressed like a wizard", image=ref_image, num_inference_steps=4).images[0]
>>> image.save("flux2_kv_output.png")