Diffusers documentation

ControlNetModel

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

ControlNetModel

ControlNet 模型由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 Adding Conditional Control to Text-to-Image Diffusion Models 中提出。它通过以边缘图、深度图、分割图以及用于姿态检测的关键点等额外输入作为条件,为文本到图像生成提供了更强的控制能力。

该论文的摘要如下:

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

从原始格式加载

默认情况下,ControlNetModel 应使用 from_pretrained() 加载,但也可以使用 FromOriginalModelMixin.from_single_file 从原始格式加载,如下所示:

from diffusers import StableDiffusionControlNetPipeline, ControlNetModel

url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth"  # can also be a local path
controlnet = ControlNetModel.from_single_file(url)

url = "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors"  # can also be a local path
pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)

从 Control LoRA 加载

Stability AI 在 stabilityai/control-lora 中提出了 Control-LoRA,该方法通过在 ControlNet 中引入低秩参数高效微调,提供了一种更高效、更紧凑的方式,使更多消费级 GPU 也能实现模型控制。

from diffusers import ControlNetModel, UNet2DConditionModel

lora_id = "stabilityai/control-lora"
lora_filename = "control-LoRAs-rank128/control-lora-canny-rank128.safetensors"

unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="unet", dtype=torch.bfloat16).to("cuda")  # or "mps", "xpu", "cpu"
controlnet = ControlNetModel.from_unet(unet).to(device="cuda", dtype=torch.bfloat16)
controlnet.load_lora_adapter(lora_id, weight_name=lora_filename, prefix=None, controlnet_config=controlnet.config)

ControlNetModel

类 diffusers.ControlNetModel

< >

( in_channels: int = 4conditioning_channels: int = 3flip_sin_to_cos: bool = Truefreq_shift: int = 0down_block_types: tuple = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D')mid_block_type: str | None = 'UNetMidBlock2DCrossAttn'only_cross_attention: bool | tuple[bool] = Falseblock_out_channels: tuple = (320, 640, 1280, 1280)layers_per_block: int = 2downsample_padding: int = 1mid_block_scale_factor: float = 1act_fn: str = 'silu'norm_num_groups: int | None = 32norm_eps: float = 1e-05cross_attention_dim: int = 1280transformer_layers_per_block: int | tuple[int, ...] = 1encoder_hid_dim: int | None = Noneencoder_hid_dim_type: str | None = Noneattention_head_dim: int | tuple[int, ...] = 8num_attention_heads: int | tuple[int, ...] | None = Noneuse_linear_projection: bool = Falseclass_embed_type: str | None = Noneaddition_embed_type: str | None = Noneaddition_time_embed_dim: int | None = Nonenum_class_embeds: int | None = Noneupcast_attention: bool = Falseresnet_time_scale_shift: str = 'default'projection_class_embeddings_input_dim: int | None = Nonecontrolnet_conditioning_channel_order: str = 'rgb'conditioning_embedding_out_channels: tuple[int, ...] | None = (16, 32, 96, 256)global_pool_conditions: bool = Falseaddition_embed_type_num_heads: int = 64 )

参数

  • in_channels (int,默认为 4) — 输入样本的通道数。
  • flip_sin_to_cos (bool,默认为 True) — 是否将时间嵌入中的 sin 翻转为 cos。
  • freq_shift (int,默认为 0) — 应用于时间嵌入的频率偏移量。
  • down_block_types(tuple[str],默认为 ("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D"))— 要使用的下采样块元组。
  • only_cross_attention(bool | tuple[bool],默认为 False) —
  • block_out_channels (tuple[int],默认为 (320, 640, 1280, 1280)) — 每个块的输出通道数元组。
  • layers_per_block (int,默认为 2) — 每个块中的层数。
  • downsample_padding (int,默认为 1) — 用于下采样卷积的填充值。
  • mid_block_scale_factor (float,默认为 1) — 用于中间块的缩放因子。
  • act_fn (str,默认为 “silu”) — 要使用的激活函数。
  • norm_num_groups (int,可选,默认为 32) — 用于归一化的组数。如果为 None,则在后处理中跳过归一化和激活层。
  • norm_eps (float,默认为 1e-5) — 用于归一化的 epsilon 值。
  • cross_attention_dim (int,默认为 1280) — 交叉注意力特征的维度。
  • transformer_layers_per_block(int 或 tuple[int],可选,默认为 1)— BasicTransformerBlock 类型 transformer 块的数量。仅对 ~models.unet_2d_blocks.CrossAttnDownBlock2D、~models.unet_2d_blocks.CrossAttnUpBlock2D、 ~models.unet_2d_blocks.UNetMidBlock2DCrossAttn 有效。
  • encoder_hid_dim (int,可选,默认为 None) — 如果定义了 encoder_hid_dim_type,encoder_hidden_states 将从 encoder_hid_dim 维度投影到 cross_attention_dim。
  • encoder_hid_dim_type (str,可选,默认为 None) — 如果指定,encoder_hidden_states 以及其他潜在嵌入将根据 encoder_hid_dim_type 下投影到维度为 cross_attention 的文本嵌入。
  • attention_head_dim (int | tuple[int],默认为 8) — 注意力头的维度。
  • use_linear_projection (bool,默认为 False) —
  • class_embed_type (str,可选,默认为 None) — 要使用的类别嵌入类型,最终会与时间嵌入相加。可选值:None、 "timestep"、"identity"、"projection" 或 "simple_projection"。
  • addition_embed_type (str,可选,默认为 None) — 配置一个可选的嵌入,该嵌入将与时间嵌入相加。可选值为 None 或 “text”。选择 “text” 时将使用 TextTimeEmbedding 层。
  • num_class_embeds (int,可选,默认为 0) — 当使用 class_embed_type 等于 None 的类别条件时,可学习嵌入矩阵的输入维度,该矩阵将被投影到 time_embed_dim。
  • upcast_attention(bool,默认为 False)—
  • resnet_time_scale_shift(str,默认为 "default") — ResNet 块的时间缩放偏移配置(参见 ResnetBlock2D)。可选值为 default 或 scale_shift。
  • projection_class_embeddings_input_dim (int,可选,默认为 None) — 当 class_embed_type="projection" 时,class_labels 输入的维度。当 class_embed_type="projection" 时必填。
  • controlnet_conditioning_channel_order (str,默认为 "rgb") — 条件图像的通道顺序。如果为 bgr,将转换为 rgb。
  • conditioning_embedding_out_channels (tuple[int],可选,默认为 (16, 32, 96, 256)) — conditioning_embedding 层中每个块的输出通道数元组。
  • global_pool_conditions(bool,默认为 False)— TODO(Patrick) - 未使用的参数。
  • addition_embed_type_num_heads (int,默认为 64) — TextTimeEmbedding 层使用的注意力头数量。

ControlNet 模型。

forward

< >

( sample: Tensortimestep: typing.Union[torch.Tensor, float, int]encoder_hidden_states: Tensorcontrolnet_cond: Tensorconditioning_scale: float = 1.0class_labels: typing.Optional[torch.Tensor] = Nonetimestep_cond: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneadded_cond_kwargs: dict[str, torch.Tensor] | None = Nonecross_attention_kwargs: dict[str, typing.Any] | None = Noneguess_mode: bool = Falsereturn_dict: bool = True ) → ControlNetOutput or tuple

参数

  • sample (torch.Tensor) — 带噪声的输入张量。
  • timestep (torch.Tensor | float | int) — 用于对输入进行去噪的时间步数。
  • encoder_hidden_states (torch.Tensor) — 编码器的隐藏状态。
  • controlnet_cond (torch.Tensor) — 形状为 (batch_size, sequence_length, hidden_size) 的条件输入张量。
  • conditioning_scale (float,默认为 1.0) — ControlNet 输出的缩放因子。
  • class_labels (torch.Tensor,可选,默认为 None) — 用于条件控制的可选类别标签。它们的嵌入将与时间步嵌入相加。
  • timestep_cond (torch.Tensor,可选,默认为 None) — 用于时间步的额外条件嵌入。如果提供,这些嵌入将与通过 self.time_embedding 层传入的 timestep_embedding 相加,以得到最终的时间步嵌入。
  • attention_mask (torch.Tensor,可选,默认为 None) — 形状为 (batch, key_tokens) 的注意力掩码将应用于 encoder_hidden_states。如果值为 1,则保留该掩码;如果值为 0,则将其丢弃。掩码会被转换为偏置,向对应于“丢弃”标记的注意力分数添加较大的负值。
  • added_cond_kwargs (dict) — Stable Diffusion XL UNet 的附加条件。
  • cross_attention_kwargs (dict[str],可选,默认为 None) — 一个 kwargs 字典,如果指定,将传递给 AttnProcessor。
  • guess_mode(bool,默认为 False) — 在此模式下,即使您移除了所有提示词,ControlNet 编码器也会尽力识别输入内容。建议将 guidance_scale 设置在 3.0 到 5.0 之间。
  • return_dict (bool,默认为 True) — 是否返回 ControlNetOutput 而不是普通元组。

返回值

ControlNetOutput 或 tuple

如果 return_dict 为 True,则返回 ControlNetOutput,否则返回一个元组,其中第一个元素是样本张量。

ControlNetModel 的前向方法。

from_unet

< >

( unet: UNet2DConditionModelcontrolnet_conditioning_channel_order: str = 'rgb'conditioning_embedding_out_channels: tuple[int, ...] | None = (16, 32, 96, 256)load_weights_from_unet: bool = Trueconditioning_channels: int = 3 )

参数

  • unet (UNet2DConditionModel) — 要复制到 ControlNetModel 的 UNet 模型权重。所有适用的配置选项也会一并复制。

从 UNet2DConditionModel 实例化一个 ControlNetModel。

set_attention_slice

< >

( slice_size: str | int | list[int] )

参数

  • slice_size (str 或 int 或 list(int),可选,默认为 "auto") — 当值为 "auto" 时,输入到注意力头的张量会被减半,因此注意力计算分两步进行。如果值为 "max",则每次只运行一个切片,以节省最大量的内存。如果提供了数值,则使用 attention_head_dim // slice_size 个切片。在这种情况下,attention_head_dim 必须是 slice_size 的倍数。

启用切片注意力计算。

启用此选项后,注意力模块会将输入张量切分为多个切片,分步计算注意力。这有助于节省部分内存,但会略微降低速度。

set_default_attn_processor

< >

( )

禁用自定义注意力处理器并设置默认的注意力实现。

ControlNetOutput

class diffusers.models.controlnets.ControlNetOutput

< >

( down_block_res_samples: tuplemid_block_res_sample: Tensor )

参数

  • down_block_res_samples (tuple[torch.Tensor]) — 一个元组,包含每个下采样块在不同分辨率下的下采样激活值。每个张量的形状应为 (batch_size, channel * resolution, height //resolution, width // resolution)。输出可用于对原始 UNet 的下采样激活值进行条件化。
  • mid_down_block_re_sample (torch.Tensor) — 中间块的激活值(最低采样分辨率)。每个张量的形状应为 (batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)。 输出可用于对原始 UNet 的中间块激活值进行条件化。

ControlNetModel 的输出。

Update on GitHub