# SparseControlNetModel

SparseControlNetModel 是 [AnimateDiff](https://huggingface.co/papers/2307.04725) 的 ControlNet 实现。

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

ControlNet 的 SparseCtrl 版本由 Yuwei Guo、Ceyuan Yang、Anyi Rao、Maneesh Agrawala、Dahua Lin 和 Bo Dai 在 [SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion Models](https://huggingface.co/papers/2311.16933) 中提出，旨在通过为文本到视频扩散模型添加稀疏控制来实现受控生成。

该论文的摘要如下：

*近年来，文本生成视频（T2V）技术，即根据给定的文本提示生成视频，取得了显著进展。然而，仅依赖文本提示往往会导致空间不确定性，从而造成模糊的帧构图。因此，研究界利用密集的结构信号（例如逐帧的深度/边缘序列）来增强可控性，但这相应地增加了推理的负担。在本工作中，我们提出了 SparseCtrl，它通过时间上稀疏的信号实现灵活的结构控制，仅需一个或少数几个输入，如图 1 所示。该方法引入一个额外的条件编码器来处理这些稀疏信号，同时保持预训练的 T2V 模型不变。所提出的方法兼容多种模态，包括草图、深度图和 RGB 图像，为视频生成提供了更实用的控制，并促进了分镜设计、深度渲染、关键帧动画和插值等应用。大量实验证明了 SparseCtrl 在原始和个性化 T2V 生成器上的泛化能力。代码和模型将在 [this https URL](https://guoyww.github.io/projects/SparseCtrl) 公开。*

## 加载 SparseControlNetModel 的示例

```python
import torch
from diffusers import SparseControlNetModel

# fp32 variant in float16
# 1. Scribble checkpoint
controlnet = SparseControlNetModel.from_pretrained("guoyww/animatediff-sparsectrl-scribble", dtype=torch.float16)

# 2. RGB checkpoint
controlnet = SparseControlNetModel.from_pretrained("guoyww/animatediff-sparsectrl-rgb", dtype=torch.float16)

# For loading fp16 variant, pass `variant="fp16"` as an additional parameter
```

## SparseControlNetModel[[diffusers.SparseControlNetModel]]

#### diffusers.SparseControlNetModel[[diffusers.SparseControlNetModel]]

```python
diffusers.SparseControlNetModel(in_channels: int = 4, conditioning_channels: int = 4, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: tuple[str, ...] = ('CrossAttnDownBlockMotion', 'CrossAttnDownBlockMotion', 'CrossAttnDownBlockMotion', 'DownBlockMotion'), 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 | None = 32, norm_eps: float = 1e-05, cross_attention_dim: int = 768, transformer_layers_per_block: int | tuple[int, ...] = 1, transformer_layers_per_mid_block: int | tuple[int] | None = None, temporal_transformer_layers_per_block: int | tuple[int, ...] = 1, attention_head_dim: int | tuple[int, ...] = 8, num_attention_heads: int | tuple[int, ...] | None = None, use_linear_projection: bool = False, upcast_attention: bool = False, resnet_time_scale_shift: str = 'default', conditioning_embedding_out_channels: tuple[int, ...] | None = (16, 32, 96, 256), global_pool_conditions: bool = False, controlnet_conditioning_channel_order: str = 'rgb', motion_max_seq_length: int = 32, motion_num_attention_heads: int = 8, concat_conditioning_mask: bool = True, use_simplified_condition_embedding: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/controlnets/controlnet_sparsectrl.py#L97)

**参数：**

in_channels (`int`，默认为 4)：输入样本的通道数。

conditioning_channels (`int`，默认为 4)：ControlNet 条件嵌入模块中的输入通道数。如果 `concat_condition_embedding` 为 True，则此处提供的值会加 1。

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)`)：每个 block 的输出通道数元组。

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` 有效。

transformer_layers_per_mid_block (`int` 或 `tuple[int]`，*可选*，默认为 1)：中间块中每一层所使用的 transformer 层数。

attention_head_dim (`int` 或 `tuple[int]`，默认为 8)：注意力头的维度。

num_attention_heads (`int` 或 `tuple[int]`，*可选*)：用于多头注意力的头数。

use_linear_projection (`bool`，默认为 `False`) --

upcast_attention (`bool`，默认为 `False`) --

resnet_time_scale_shift (`str`，默认为 `"default"`)：ResNet 块的时间尺度偏移配置（参见 `ResnetBlock2D`）。可选值为 `default` 或 `scale_shift`。

conditioning_embedding_out_channels (`tuple[int]`，默认为 `(16, 32, 96, 256)`)：`conditioning_embedding` 层中每个块的输出通道数元组。

global_pool_conditions (`bool`，默认为 `False`)：TODO(Patrick) - 未使用的参数

controlnet_conditioning_channel_order (`str`，默认为 `rgb`) --

motion_max_seq_length (`int`，默认为 `32`)：在运动模块中使用的最大序列长度。

motion_num_attention_heads (`int` 或 `tuple[int]`，默认为 `8`)：运动模块中每个注意力层使用的注意力头数量。

concat_conditioning_mask (`bool`，默认为 `True`) --

use_simplified_condition_embedding (`bool`，默认为 `True`) --

如[SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion Models](https://huggingface.co/papers/2311.16933)中所述的 SparseControlNet 模型。

#### forward[[diffusers.SparseControlNetModel.forward]]

```python
forward(sample: Tensor, timestep: typing.Union[torch.Tensor, float, int], encoder_hidden_states: Tensor, controlnet_cond: Tensor, conditioning_scale: float = 1.0, timestep_cond: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, cross_attention_kwargs: dict[str, typing.Any] | None = None, conditioning_mask: typing.Optional[torch.Tensor] = None, guess_mode: bool = False, return_dict: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/controlnets/controlnet_sparsectrl.py#L534)

**参数：**

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 输出的缩放因子。

timestep_cond (`torch.Tensor`，*可选*，默认为 `None`)：用于时间步的额外条件嵌入。如果提供，这些嵌入将与通过 `self.time_embedding` 层传入的 timestep_embedding 相加，以得到最终的时间步嵌入。

attention_mask (`torch.Tensor`，*可选*，默认为 `None`)：形状为 `(batch, key_tokens)` 的注意力掩码将应用于 `encoder_hidden_states`。如果值为 `1`，则保留该掩码；如果值为 `0`，则丢弃该掩码。掩码将被转换为偏置，向对应于“丢弃”标记的注意力分数添加较大的负值。

conditioning_mask (`torch.Tensor`，*可选*，默认为 `None`)：可选的掩码，用于指示 `controlnet_cond` 中哪些帧是有效的条件帧。

cross_attention_kwargs (`dict[str]`，*可选*，默认为 `None`)：一个 kwargs 字典，如果指定，将传递给 `AttnProcessor`。

guess_mode (`bool`，默认为 `False`)：在此模式下，即使您移除了所有提示词，ControlNet 编码器也会尽力识别输入内容。建议 `guidance_scale` 设置在 3.0 到 5.0 之间。

return_dict (`bool`，默认为 `True`)：是否返回 `~models.controlnet.ControlNetOutput` 而不是普通元组。

**返回：** `~models.controlnet.ControlNetOutput` **或** `tuple`

如果 `return_dict` 为 `True`，则返回 `~models.controlnet.ControlNetOutput`，否则返回一个元组，其中第一个元素是样本张量。

[SparseControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet_sparsectrl#diffusers.SparseControlNetModel) 的前向方法。

#### from_unet[[diffusers.SparseControlNetModel.from_unet]]

```python
from_unet(unet: UNet2DConditionModel, controlnet_conditioning_channel_order: str = 'rgb', conditioning_embedding_out_channels: tuple[int, ...] | None = (16, 32, 96, 256), load_weights_from_unet: bool = True, conditioning_channels: int = 3)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/controlnets/controlnet_sparsectrl.py#L388)

**参数：**

unet (`UNet2DConditionModel`)：要复制到 [SparseControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet_sparsectrl#diffusers.SparseControlNetModel) 的 UNet 模型权重。所有适用的配置选项也会一并复制。

从 [UNet2DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet2d-cond#diffusers.UNet2DConditionModel) 实例化一个 [SparseControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet_sparsectrl#diffusers.SparseControlNetModel)。

#### set_attention_slice[[diffusers.SparseControlNetModel.set_attention_slice]]

```python
set_attention_slice(slice_size: str | int | list[int])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/controlnets/controlnet_sparsectrl.py#L469)

**参数：**

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

启用切片注意力计算。

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

#### set_default_attn_processor[[diffusers.SparseControlNetModel.set_default_attn_processor]]

```python
set_default_attn_processor()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/controlnets/controlnet_sparsectrl.py#L453)

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

## SparseControlNetOutput[[diffusers.models.controlnets.SparseControlNetOutput]]

#### diffusers.models.controlnets.SparseControlNetOutput[[diffusers.models.controlnets.SparseControlNetOutput]]

```python
diffusers.models.controlnets.SparseControlNetOutput(down_block_res_samples: tuple[torch.Tensor], mid_block_res_sample: Tensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/controlnets/controlnet_sparsectrl.py#L44)

**参数：**

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 的中间块激活值进行条件控制。

[SparseControlNetModel](/docs/diffusers/v0.43.0/zh/api/models/controlnet_sparsectrl#diffusers.SparseControlNetModel) 的输出。

