# Flux2

  
  

Flux.2 是 Black Forest Labs 近期推出的图像生成模型系列，其前身为 [Flux.1](./flux) 系列。这是一个全新的模型，采用了新的架构，并从头开始进行了预训练！

Flux 的原始模型检查点可在[此处](https://huggingface.co/black-forest-labs)找到。原始推理代码可在[此处](https://github.com/black-forest-labs/flux2)找到。

> [!TIP]
> Flux2 在消费级硬件设备上运行成本可能较高。不过，你可以执行一系列优化，使其运行得更快且对内存更友好。有关更多详细信息，请参阅 [本节](https://huggingface.co/blog/sd3#memory-optimizations-for-sd3)。此外，Flux 可以通过量化来提升内存效率，但代价是推理延迟会增加。要了解更多信息，请参考 [这篇博客文章](https://huggingface.co/blog/quanto-diffusers)。
>
> [缓存](../../optimization/cache)还可以通过存储和复用中间输出来加速推理。

## 标题上采样

Flux.2 在配合更优质的提示词时，有可能生成更好的输出。我们可以通过在 pipeline 调用参数中设置 `caption_upsample_temperature` 参数，对输入提示词进行“上采样”。[官方实现](https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/text_encoder.py#L140)建议将该值设为 0.15。

## Flux2Pipeline[[diffusers.Flux2Pipeline]]

#### diffusers.Flux2Pipeline[[diffusers.Flux2Pipeline]]

```python
diffusers.Flux2Pipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLFlux2, text_encoder: Mistral3ForConditionalGeneration, tokenizer: AutoProcessor, transformer: Flux2Transformer2DModel)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux2/pipeline_flux2.py#L251)

**参数：**

transformer ([Flux2Transformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/flux2_transformer#diffusers.Flux2Transformer2DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

vae (`AutoencoderKLFlux2`)：变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码为图像。

text_encoder (`Mistral3ForConditionalGeneration`)：[Mistral3ForConditionalGeneration](https://huggingface.co/docs/transformers/en/model_doc/mistral3#transformers.Mistral3ForConditionalGeneration)

tokenizer (`AutoProcessor`)：[PixtralProcessor](https://huggingface.co/docs/transformers/en/model_doc/pixtral#transformers.PixtralProcessor) 类的分词器。

用于文本到图像生成的 Flux2 流水线。

参考：[https://bfl.ai/blog/flux-2](https://bfl.ai/blog/flux-2)

#### __调用__[[diffusers.Flux2Pipeline.__call__]]

```python
__call__(image: PIL.Image.Image | list[PIL.Image.Image] | None = None, prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float | None = 4.0, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, text_encoder_out_layers: tuple[int] = (10, 20, 30), caption_upsample_temperature: float = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux2/pipeline_flux2.py#L746)

**参数：**

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_scale` > 1 的情况，引导蒸馏模型近似于真正的无分类器引导。请参阅[论文](https://huggingface.co/papers/2210.03142)以了解更多信息。

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 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.qwenimage.QwenImagePipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

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`) : 指定后，我们将尝试执行字幕上采样，以获得可能更好的输出效果。如果打算执行字幕上采样，我们建议将其设置为 0.15。

**返回：** `~pipelines.flux2.Flux2PipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `~pipelines.flux2.Flux2PipelineOutput`，否则返回 `tuple`。当返回元组时，第一个元素是一个包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```py
>>> 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[[diffusers.Flux2KleinPipeline]]

#### diffusers.Flux2KleinPipeline[[diffusers.Flux2KleinPipeline]]

```python
diffusers.Flux2KleinPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLFlux2, text_encoder: Qwen3ForCausalLM, tokenizer: Qwen2Tokenizer, transformer: Flux2Transformer2DModel, is_distilled: bool = False)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py#L155)

**参数：**

transformer ([Flux2Transformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/flux2_transformer#diffusers.Flux2Transformer2DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

vae (`AutoencoderKLFlux2`)：变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码为图像。

text_encoder (`Qwen3ForCausalLM`)：[Qwen3ForCausalLM](https://huggingface.co/docs/transformers/en/model_doc/qwen3#transformers.Qwen3ForCausalLM)

tokenizer (`Qwen2TokenizerFast`)：[Qwen2TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/qwen2#transformers.Qwen2TokenizerFast) 类的分词器。

用于文本到图像生成的 Flux2 Klein 流水线。

参考：[https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence](https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence)

#### __调用__[[diffusers.Flux2KleinPipeline.__call__]]

```python
__call__(image: list[PIL.Image.Image] | PIL.Image.Image | None = None, prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 50, sigmas: list[float] | None = None, guidance_scale: float = 4.0, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: str | list[str] | None = None, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, text_encoder_out_layers: tuple[int] = (9, 18, 27))
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux2/pipeline_flux2_klein.py#L614)

**参数：**

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](https://huggingface.co/papers/2207.12598) 中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 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]`, *可选*) : 用于去噪过程的自定义 sigmas，适用于其 `set_timesteps` 方法支持 `sigmas` 参数的调度器。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `List[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负文本嵌入。请注意，在此流水线中，"" 用作负提示。如果未提供，将从 "" 生成。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.qwenimage.QwenImagePipelineOutput` 而不是普通元组。

attention_kwargs (`dict`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

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 时调用的函数。

示例：
```py
>>> 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[[diffusers.Flux2KleinKVPipeline]]

#### diffusers.Flux2KleinKVPipeline[[diffusers.Flux2KleinKVPipeline]]

```python
diffusers.Flux2KleinKVPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLFlux2, text_encoder: Qwen3ForCausalLM, tokenizer: Qwen2Tokenizer, transformer: Flux2Transformer2DModel, is_distilled: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux2/pipeline_flux2_klein_kv.py#L155)

**参数：**

transformer ([Flux2Transformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/flux2_transformer#diffusers.Flux2Transformer2DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

vae (`AutoencoderKLFlux2`)：变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码为图像。

text_encoder (`Qwen3ForCausalLM`)：[Qwen3ForCausalLM](https://huggingface.co/docs/transformers/en/model_doc/qwen3#transformers.Qwen3ForCausalLM)

tokenizer (`Qwen2TokenizerFast`)：[Qwen2TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/qwen2#transformers.Qwen2TokenizerFast) 类的分词器。

用于文本到图像生成的 Flux2 Klein KV 流水线，支持基于 KV 缓存的参考图像条件输入。

在第一个去噪步骤中，参考图像的 token 会包含在前向传播中，并且它们的注意力 K/V 投影会被缓存。在后续步骤中，会直接复用已缓存的 K/V 而无需重新计算，从而在使用参考图像时提供更快的推理速度。

参考：[https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence](https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence)

#### __调用__[[diffusers.Flux2KleinKVPipeline.__call__]]

```python
__call__(image: list[PIL.Image.Image] | PIL.Image.Image | None = None, prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 4, sigmas: list[float] | None = None, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, output_type: str = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], max_sequence_length: int = 512, text_encoder_out_layers: tuple[int] = (9, 18, 27))
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux2/pipeline_flux2_klein_kv.py#L610)

**参数：**

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`, *可选*) : 传递给注意力处理器的额外关键字参数。

callback_on_step_end (`Callable`，*可选*)：在每个去噪步骤结束时调用的回调函数。

callback_on_step_end_tensor_inputs (`List`，*可选*)：回调函数的 Tensor 输入。

max_sequence_length (`int`，默认为 512)：提示词的最大序列长度。

text_encoder_out_layers (`tuple[int]`) : 用于提取文本编码器隐藏状态的层索引。

**返回值：**

`~pipelines.flux2.Flux2PipelineOutput` 或 `tuple`。

调用生成 pipeline 时调用的函数。

示例：
```py
>>> 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")
```

