# Hunyuan-DiT 的 ControlNet

HunyuanDiTControlNetPipeline 是 [Hunyuan-DiT](https://huggingface.co/papers/2405.08748) 的 ControlNet 实现。

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

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

该论文的摘要如下：

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

此代码由腾讯混元团队实现。您可以在 [腾讯混元](https://huggingface.co/Tencent-Hunyuan) 上找到 Hunyuan-DiT ControlNet 的预训练检查点。

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

## HunyuanDiTControlNetPipeline[[diffusers.HunyuanDiTControlNetPipeline]]

#### diffusers.HunyuanDiTControlNetPipeline[[diffusers.HunyuanDiTControlNetPipeline]]

```python
diffusers.HunyuanDiTControlNetPipeline(vae: AutoencoderKL, text_encoder: BertModel, tokenizer: BertTokenizer, transformer: HunyuanDiT2DModel, scheduler: DDPMScheduler, safety_checker: StableDiffusionSafetyChecker, feature_extractor: CLIPImageProcessorPil, controlnet: diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel | list[diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel] | tuple[diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DControlNetModel] | diffusers.models.controlnets.controlnet_hunyuan.HunyuanDiT2DMultiControlNetModel, text_encoder_2: transformers.models.t5.modeling_t5.T5EncoderModel | None = None, tokenizer_2: transformers.models.t5.tokenization_t5.T5Tokenizer | None = None, requires_safety_checker: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L165)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，以及从潜在表示解码为图像。我们使用 `sdxl-vae-fp16-fix`。

text_encoder (`~transformers.BertModel`, `~transformers.CLIPTextModel` | None) : 冻结的文本编码器 ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14))。HunyuanDiT 使用经过微调的 [bilingual CLIP]。

tokenizer (`~transformers.BertTokenizer`、`~transformers.CLIPTokenizer` | None) : 用于对文本进行分词的 `BertTokenizer` 或 `CLIPTokenizer`。

transformer ([HunyuanDiT2DModel](/docs/diffusers/v0.43.0/zh/api/models/hunyuan_transformer2d#diffusers.HunyuanDiT2DModel))：由腾讯混元设计的 HunyuanDiT 模型。

text_encoder_2 (`T5EncoderModel`)：mT5 嵌入器。具体而言，它是 't5-v1_1-xxl'。

tokenizer_2 (`T5Tokenizer`)：mT5 嵌入器的分词器。

scheduler ([DDPMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddpm#diffusers.DDPMScheduler))：用于配合 HunyuanDiT 对编码后的图像潜在表示进行去噪的调度器。

controlnet （[HunyuanDiT2DControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet_hunyuandit#diffusers.HunyuanDiT2DControlNetModel) 或 `list[HunyuanDiT2DControlNetModel]` 或 [HunyuanDiT2DControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet_hunyuandit#diffusers.HunyuanDiT2DControlNetModel)）：在去噪过程中为 `unet` 提供额外的条件信息。如果以列表形式设置多个 ControlNet，则会将每个 ControlNet 的输出相加，以生成一个合并的额外条件。

用于使用 HunyuanDiT 进行英语/中文到图像生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

HunyuanDiT 使用两个文本编码器：[mT5](https://huggingface.co/google/mt5-base) 和 [双语 CLIP](由我们自行微调)

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

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int | None = 50, guidance_scale: float | None = 5.0, control_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]] = None, controlnet_conditioning_scale: float | list[float] = 1.0, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, eta: float | None = 0.0, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_2: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_2: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask_2: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], guidance_rescale: float = 0.0, original_size: tuple[int, int] | None = (1024, 1024), target_size: tuple[int, int] | None = None, crops_coords_top_left: tuple[int, int] = (0, 0), use_resolution_binning: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L632)

**参数：**

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

height (`int`) : 生成图像的高度（以像素为单位）。

width (`int`) : 生成图像的宽度（以像素为单位）。

num_inference_steps (`int`，*可选*，默认值为 50)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。此参数受 `strength` 调节。

guidance_scale (`float`, *可选*，默认值为 7.5)：较高的 guidance scale 值会促使模型生成与文本 `prompt` 紧密相关的图像，但代价是图像质量降低。当 `guidance_scale > 1` 时，guidance scale 生效。

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 设置为列表。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于指导图像生成中不应包含的内容的提示词或提示词列表。如果未定义，则需要改为传入 `negative_prompt_embeds`。在未使用引导（`guidance_scale < 1`）时将被忽略。

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

eta (`float`，*可选*，默认值为 0.0)：对应 [DDIM](https://huggingface.co/papers/2010.02502) 论文中的参数 eta (η)。仅适用于 [DDIMScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/ddim#diffusers.DDIMScheduler)，在其他调度器中会被忽略。

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

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

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

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

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

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

prompt_attention_mask (`torch.Tensor`, *可选*) : 提示词的注意力掩码。当直接传入 `prompt_embeds` 时，此项为必填。

prompt_attention_mask_2 (`torch.Tensor`，*可选*)：提示词的注意力掩码。当直接传入 `prompt_embeds_2` 时，此项为必填。

negative_prompt_attention_mask (`torch.Tensor`，*可选*)：用于负面提示词的注意力掩码。当直接传入 `negative_prompt_embeds` 时，此参数为必填项。

negative_prompt_attention_mask_2 (`torch.Tensor`, *可选*) : 负面提示词的注意力掩码。当直接传入 `negative_prompt_embeds_2` 时，此参数为必填项。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 `PIL.Image` 或 `np.array` 之间选择。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 而不是普通元组。

callback_on_step_end (`Callable[[int, int], None]`、`PipelineCallback`、`MultiPipelineCallbacks`、*可选*)：在每个去噪步骤结束时调用的回调函数或回调函数列表。

callback_on_step_end_tensor_inputs (`list[str]`，*可选*) : 应传递给回调函数的张量输入列表。如果未定义，则所有张量输入都会被传递。

guidance_rescale (`float`, *optional*, defaults to 0.0) : Rescale the noise_cfg according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://huggingface.co/papers/2305.08891). See Section 3.4

original_size (`tuple[int, int]`，*可选*，默认为 `(1024, 1024)`)：图像的原始尺寸。用于计算时间 ID。

target_size (`tuple[int, int]`，*可选*)：图像的目标尺寸。用于计算时间 ID。

crops_coords_top_left (`tuple[int, int]`，*可选*，默认为 `(0, 0)`)：裁剪区域的左上角坐标。用于计算时间 ID。

use_resolution_binning (`bool`，*可选*，默认为 `True`)：是否使用分辨率分箱。如果为 `True`，输入分辨率将被映射到最接近的标准分辨率。支持的分辨率为 1024x1024、1280x1280、1024x768、1152x864、1280x960、768x1024、864x1152、960x1280、1280x768 和 768x1280。建议将此值设置为 `True`。

**返回：** [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [StableDiffusionPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/stable_diffusion/img2img#diffusers.pipelines.stable_diffusion.StableDiffusionPipelineOutput)；否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表，第二个元素是 `bool` 列表，用于指示对应的生成图像是否包含“不适合工作场所”（nsfw）内容。

调用 pipeline 的 call 函数，使用 HunyuanDiT 进行生成。

示例：
```py
from diffusers import HunyuanDiT2DControlNetModel, HunyuanDiTControlNetPipeline
import torch

controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
    "Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny", torch_dtype=torch.float16
)

pipe = HunyuanDiTControlNetPipeline.from_pretrained(
    "Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
)
pipe.to("cuda")

from diffusers.utils import load_image

cond_image = load_image(
    "https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny/resolve/main/canny.jpg?download=true"
)

## You may also use English prompt as HunyuanDiT supports both English and Chinese
prompt = "在夜晚的酒店门前，一座古老的中国风格的狮子雕像矗立着，它的眼睛闪烁着光芒，仿佛在守护着这座建筑。背景是夜晚的酒店前，构图方式是特写，平视，居中构图。这张照片呈现了真实摄影风格，蕴含了中国雕塑文化，同时展现了神秘氛围"
# prompt="At night, an ancient Chinese-style lion statue stands in front of the hotel, its eyes gleaming as if guarding the building. The background is the hotel entrance at night, with a close-up, eye-level, and centered composition. This photo presents a realistic photographic style, embodies Chinese sculpture culture, and reveals a mysterious atmosphere."
image = pipe(
    prompt,
    height=1024,
    width=1024,
    control_image=cond_image,
    num_inference_steps=50,
).images[0]
```

#### encode_prompt[[diffusers.HunyuanDiTControlNetPipeline.encode_prompt]]

```python
encode_prompt(prompt: str, device: device = None, dtype: dtype = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | None = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int | None = None, text_encoder_index: int = 0)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py#L276)

**参数：**

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

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

dtype (`torch.dtype`)：torch 数据类型

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

do_classifier_free_guidance (`bool`) : 是否使用 classifier free guidance

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

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

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

prompt_attention_mask (`torch.Tensor`, *可选*) : 提示词的注意力掩码。当直接传入 `prompt_embeds` 时，此项为必填。

negative_prompt_attention_mask (`torch.Tensor`，*可选*)：用于负面提示词的注意力掩码。当直接传入 `negative_prompt_embeds` 时，此参数为必填项。

max_sequence_length (`int`, *可选*) : 用于提示词的最大序列长度。

text_encoder_index (`int`, *可选*) : 要使用的文本编码器索引。`0` 表示 clip，`1` 表示 T5。

将提示词编码为文本编码器的隐藏状态。

