# Flux.1 的 ControlNet

  

FluxControlNetPipeline 是 Flux.1 的 ControlNet 实现。

ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 [Adding Conditional Control to Text-to-Image Diffusion Models](https://huggingface.co/papers/2302.05543) 中提出。

使用 ControlNet 模型，您可以提供额外的控制图像来调节并控制 Stable Diffusion 的生成过程。例如，如果您提供一张深度图，ControlNet 模型将生成一张保留深度图中空间信息的图像。这是一种更灵活、更精确地控制图像生成过程的方式。

该论文的摘要如下：

*我们提出了 ControlNet，一种用于为大型预训练文本到图像扩散模型添加空间条件控制的神经网络架构。ControlNet 锁定生产就绪的大型扩散模型，并复用其使用数十亿张图像预训练得到的深层且鲁棒的编码层作为强大的骨干网络，以学习多样化的条件控制。该神经架构通过“零卷积”（零初始化的卷积层）进行连接，这些层使参数从零开始逐步增长，并确保在微调过程中不会产生有害噪声。我们使用 Stable Diffusion 测试了多种条件控制，例如边缘、深度、分割、人体姿态等，支持使用单一或多个条件，以及有或无提示词的情况。我们展示了 ControlNet 的训练在小规模（<50k）和大规模（>1m）数据集上均具有鲁棒性。大量结果表明，ControlNet 有助于将图像扩散模型的应用扩展到更广泛的领域。*

This controlnet code is implemented by [The InstantX Team](https://huggingface.co/InstantX). You can find pre-trained checkpoints for Flux-ControlNet in the table below:

| ControlNet 类型 | 开发者 | 链接 |
| -------- | ---------- | ---- |
| Canny | [InstantX 团队](https://huggingface.co/InstantX) | [链接](https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny) |
| 深度 | [InstantX 团队](https://huggingface.co/InstantX) | [链接](https://huggingface.co/Shakker-Labs/FLUX.1-dev-ControlNet-Depth) |
| Union | [InstantX 团队](https://huggingface.co/InstantX) | [链接](https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Union) |

XLabs ControlNets 也得到支持，由 [XLabs 团队](https://huggingface.co/XLabs-AI) 贡献。

| ControlNet 类型 | 开发者 | 链接 |
| -------- | ---------- | ---- |
| Canny | [XLabs 团队](https://huggingface.co/XLabs-AI) | [链接](https://huggingface.co/XLabs-AI/flux-controlnet-canny-diffusers) |
| 深度 | [XLabs 团队](https://huggingface.co/XLabs-AI) | [链接](https://huggingface.co/XLabs-AI/flux-controlnet-depth-diffusers) |
| HED | [XLabs 团队](https://huggingface.co/XLabs-AI) | [链接](https://huggingface.co/XLabs-AI/flux-controlnet-hed-diffusers) |

> [!TIP]
> 请务必参阅 [调度器指南](../../using-diffusers/schedulers)，了解如何探索调度器速度与质量之间的权衡，并查看 [跨流水线复用组件](../../using-diffusers/loading#reusing-models-in-multiple-pipelines) 部分，了解如何高效地将相同组件加载到多个流水线中。

## FluxControlNetPipeline[[diffusers.FluxControlNetPipeline]]

#### diffusers.FluxControlNetPipeline[[diffusers.FluxControlNetPipeline]]

```python
diffusers.FluxControlNetPipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text_encoder_2: T5EncoderModel, tokenizer_2: T5Tokenizer, transformer: FluxTransformer2DModel, controlnet: diffusers.models.controlnets.controlnet_flux.FluxControlNetModel | list[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | tuple[diffusers.models.controlnets.controlnet_flux.FluxControlNetModel] | diffusers.models.controlnets.controlnet_flux.FluxMultiControlNetModel, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_flux_controlnet.py#L177)

**参数：**

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

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

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder (`CLIPTextModel`)：即 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

text_encoder_2 (`T5EncoderModel`)：即 [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel)，具体为 [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) 变体。

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

tokenizer_2 (`T5TokenizerFast`)：第二个 [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast) 类的 Tokenizer。

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

参考：https://blackforestlabs.ai/announcing-black-forest-labs/

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

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] | None = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] | None = None, true_cfg_scale: float = 1.0, height: int | None = None, width: int | None = None, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 7.0, control_guidance_start: float | list[float] = 0.0, control_guidance_end: float | list[float] = 1.0, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, control_mode: int | list[int] | None = None, controlnet_conditioning_scale: float | list[float] = 1.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = None, negative_ip_adapter_image_embeds: list[torch.Tensor] | None = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, joint_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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_flux_controlnet.py#L677)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

prompt_2 (`str` 或 `list[str]`，*可选*) : 要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则使用 `prompt` 代替

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。在未使用引导时会被忽略（即当 `true_cfg_scale` 不大于 `1` 时会被忽略）。

negative_prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的、用于引导图像生成的提示词或提示词列表。如果未定义，则所有文本编码器都会使用 `negative_prompt`。

true_cfg_scale (`float`，*可选*，默认值为 1.0)：当 `true_cfg_scale` > 1 且提供了 `negative_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` 时的默认行为。

guidance_scale (`float`，*可选*，默认值为 7.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` 紧密关联的图像，但通常以牺牲图像质量为代价。

control_guidance_start (`float` 或 `list[float]`，*可选*，默认为 0.0)：ControlNet 开始生效的总步数百分比。

control_guidance_end (`float` 或 `list[float]`，*可选*，默认为 1.0)：ControlNet 停止应用时的总步数百分比。

control_image (`torch.Tensor`、`PIL.Image.Image`、`np.ndarray`、`list[torch.Tensor]`、`list[PIL.Image.Image]`、`list[np.ndarray]`、`list[list[torch.Tensor]]`、`list[list[np.ndarray]]` 或 `list[list[PIL.Image.Image]]`)：用于为 `unet` 提供生成引导的 ControlNet 输入条件。如果类型指定为 `torch.Tensor`，则会原样传递给 ControlNet。也可以接受 `PIL.Image.Image` 作为图像。输出图像的默认尺寸与 `image` 的尺寸相同。如果传入了高度和/或宽度，`image` 将相应地调整大小。如果在 `init` 中指定了多个 ControlNet，则必须以列表形式传入图像，以便列表中的每个元素都能被正确批处理，作为单个 ControlNet 的输入。

controlnet_conditioning_scale (`float` 或 `list[float]`，*可选*，默认为 1.0) : ControlNet 的输出在加到原始 `unet` 的残差之前，会先乘以 `controlnet_conditioning_scale`。如果在 `init` 中指定了多个 ControlNet，可以将对应的 scale 设置为列表。

control_mode (`int` 或 `list[int]`，*可选*，默认为 None)：应用 ControlNet-Union 时的控制模式。

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

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

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

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如*提示词权重。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

negative_pooled_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向池化文本嵌入。可用于轻松调整文本输入，*例如*提示词权重。如果未提供，将从 `negative_prompt` 输入参数生成 pooled negative_prompt_embeds。

ip_adapter_image : (`PipelineImageInput`，*可选*)：用于配合 IP Adapter 使用的可选图像输入。

ip_adapter_image_embeds (`list[torch.Tensor]`, *可选*) : 为 IP-Adapter 预生成的图像嵌入。它应是一个列表，长度与 IP-Adapter 的数量相同。每个元素应为形状为 `(batch_size, num_images, emb_dim)` 的张量。如果未提供，则从 `ip_adapter_image` 输入参数计算嵌入。

negative_ip_adapter_image : (`PipelineImageInput`，*可选*)：用于配合 IP Adapter 使用的可选图像输入。

negative_ip_adapter_image_embeds (`list[torch.Tensor]`, *可选*) : 为 IP-Adapter 预生成的图像嵌入。它应是一个列表，长度与 IP-Adapter 的数量相同。每个元素应为形状为 `(batch_size, num_images, emb_dim)` 的张量。如果未提供，则从 `ip_adapter_image` 输入参数计算嵌入。

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

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

joint_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` 的最大序列长度。

**返回：** `~pipelines.flux.FluxPipelineOutput` 或 `tuple`

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

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

示例：
```py
>>> import torch
>>> from diffusers.utils import load_image
>>> from diffusers import FluxControlNetPipeline
>>> from diffusers import FluxControlNetModel

>>> base_model = "black-forest-labs/FLUX.1-dev"
>>> controlnet_model = "InstantX/FLUX.1-dev-controlnet-canny"
>>> controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16)
>>> pipe = FluxControlNetPipeline.from_pretrained(
...     base_model, controlnet=controlnet, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
>>> prompt = "A girl in city, 25 years old, cool, futuristic"
>>> image = pipe(
...     prompt,
...     control_image=control_image,
...     control_guidance_start=0.2,
...     control_guidance_end=0.8,
...     controlnet_conditioning_scale=1.0,
...     num_inference_steps=28,
...     guidance_scale=3.5,
... ).images[0]
>>> image.save("flux.png")
```

#### encode_prompt[[diffusers.FluxControlNetPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], prompt_2: str | list[str] | None = None, device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, pooled_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 512, lora_scale: float | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_flux_controlnet.py#L344)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

prompt_2 (`str` 或 `list[str]`，*可选*)：要发送给 `tokenizer_2` 和 `text_encoder_2` 的提示词或提示词列表。如果未定义，则所有文本编码器均使用 `prompt`。

device : (`torch.device`): torch 设备

num_images_per_prompt (`int`) : 每个提示词应生成的图像数量

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

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

lora_scale (`float`, *可选*) : 如果加载了 LoRA 层，将应用于文本编码器所有 LoRA 层的 LoRA 缩放系数。

## FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]

#### diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput[[diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput]]

```python
diffusers.pipelines.flux.pipeline_output.FluxPipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/flux/pipeline_output.py#L11)

**参数：**

images (`list[PIL.Image.Image]` 或 `torch.Tensor` 或 `np.ndarray`)：长度为 `batch_size` 的去噪 PIL 图像列表，或形状为 `(batch_size, height, width, num_channels)` 的 numpy 数组或 torch 张量。PIL 图像或 numpy 数组表示扩散流水线生成的去噪图像。Torch 张量可以表示去噪图像，也可以表示可直接传入解码器的中间潜变量。

Flux 图像生成流水线的输出类。

