# UNetMotionModel

[UNet](https://huggingface.co/papers/1505.04597) 模型最初由 Ronneberger 等人提出，用于生物医学图像分割，但由于其输出的图像尺寸与输入相同，因此在 🤗 Diffusers 中也被广泛使用。它是扩散系统中最关键的组件之一，负责实现实际的扩散过程。🤗 Diffusers 中包含多种 UNet 模型变体，具体取决于其维度数量以及是否为条件模型。这里介绍的是一个 2D UNet 模型。

该论文的摘要如下：

*人们普遍认为，成功训练深度网络需要数千个带标注的训练样本。在本文中，我们提出了一种网络架构和训练策略，该策略通过充分利用数据增强，更高效地利用现有的带标注样本。该架构由一条用于捕获上下文的收缩路径和一条对称的扩展路径组成，后者能够实现精确定位。我们证明，这样的网络可以从极少量的图像中进行端到端训练，并且在 ISBI 电子显微镜堆叠图像中神经元结构分割挑战赛中，其性能优于此前最佳方法（滑动窗口卷积网络）。使用在透射光显微镜图像（相差和 DIC）上训练的同一网络，我们在 2015 年 ISBI 细胞追踪挑战赛中以较大优势赢得了这些类别的冠军。此外，该网络速度很快。在最新的 GPU 上，对一张 512x512 图像进行分割所需时间不到一秒。完整的实现（基于 Caffe）和训练好的网络可在 http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net 获取。*

## UNetMotionModel[[diffusers.UNetMotionModel]]

#### diffusers.UNetMotionModel[[diffusers.UNetMotionModel]]

```python
diffusers.UNetMotionModel(sample_size: int | None = None, in_channels: int = 4, out_channels: int = 4, down_block_types: tuple[str, ...] = ('CrossAttnDownBlockMotion', 'CrossAttnDownBlockMotion', 'CrossAttnDownBlockMotion', 'DownBlockMotion'), up_block_types: tuple[str, ...] = ('UpBlockMotion', 'CrossAttnUpBlockMotion', 'CrossAttnUpBlockMotion', 'CrossAttnUpBlockMotion'), block_out_channels: tuple[int, ...] = (320, 640, 1280, 1280), layers_per_block: int | tuple[int] = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = 'silu', norm_num_groups: int = 32, norm_eps: float = 1e-05, cross_attention_dim: int = 1280, transformer_layers_per_block: int | tuple[int] | tuple[tuple] = 1, reverse_transformer_layers_per_block: int | tuple[int] | tuple[tuple] | None = None, temporal_transformer_layers_per_block: int | tuple[int] | tuple[tuple] = 1, reverse_temporal_transformer_layers_per_block: int | tuple[int] | tuple[tuple] | None = None, transformer_layers_per_mid_block: int | tuple[int] | None = None, temporal_transformer_layers_per_mid_block: int | tuple[int] | None = 1, use_linear_projection: bool = False, num_attention_heads: int | tuple[int, ...] = 8, motion_max_seq_length: int = 32, motion_num_attention_heads: int | tuple[int, ...] = 8, reverse_motion_num_attention_heads: int | tuple[int, ...] | tuple[tuple[int, ...], ...] | None = None, use_motion_mid_block: bool = True, mid_block_layers: int = 1, encoder_hid_dim: int | None = None, encoder_hid_dim_type: str | None = None, addition_embed_type: str | None = None, addition_time_embed_dim: int | None = None, projection_class_embeddings_input_dim: int | None = None, time_cond_proj_dim: int | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1201)

一个经过修改的条件 2D UNet 模型，它接收一个带噪声的样本、条件状态和时间步，并返回一个具有样本形状的样本。

该模型继承自 [ModelMixin](/docs/diffusers/v0.43.0/zh/api/models/overview#diffusers.ModelMixin)。请查阅其父类文档，了解为所有模型实现的通用方法（例如下载或保存）。

#### disable_freeu[[diffusers.UNetMotionModel.disable_freeu]]

```python
disable_freeu()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1842)

禁用 FreeU 机制。

#### enable_forward_chunking[[diffusers.UNetMotionModel.enable_forward_chunking]]

```python
enable_forward_chunking(chunk_size: int | None = None, dim: int = 0)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1760)

**参数：**

chunk_size (`int`, *可选*) : 前馈层的块大小。如果未指定，则对每个 dim=`dim` 的张量单独运行前馈层。

dim (`int`，*可选*，默认为 `0`)：前馈计算应进行分块的维度。在 dim=0（批次）或 dim=1（序列长度）之间选择。

将注意力处理器设置为使用 [前馈分块](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers)。

#### enable_freeu[[diffusers.UNetMotionModel.enable_freeu]]

```python
enable_freeu(s1: float, s2: float, b1: float, b2: float)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1817)

**参数：**

s1 (`float`) : 用于第一阶段以衰减跳跃特征贡献的缩放因子。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

s2 (`float`) : 用于阶段 2 的缩放因子，以衰减跳跃特征的贡献。这样做是为了缓解增强去噪过程中的“过度平滑效应”。

b1 (`float`) : 用于放大骨干网络特征贡献的阶段 1 缩放因子。

b2 (`float`) : 用于放大骨干网络特征贡献的第二阶段缩放因子。

启用来自 https://huggingface.co/papers/2309.11497 的 FreeU 机制。

缩放因子后面的后缀表示它们所应用的阶段块。

有关适用于 Stable Diffusion v1、v2 和 Stable Diffusion XL 等不同流水线的已知良好参数组合，请参阅[官方仓库](https://github.com/ChenyangSi/FreeU)。

#### forward[[diffusers.UNetMotionModel.forward]]

```python
forward(sample: Tensor, timestep: typing.Union[torch.Tensor, float, int], encoder_hidden_states: Tensor, timestep_cond: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, cross_attention_kwargs: dict[str, typing.Any] | None = None, added_cond_kwargs: dict[str, torch.Tensor] | None = None, down_block_additional_residuals: tuple[torch.Tensor] | None = None, mid_block_additional_residual: typing.Optional[torch.Tensor] = None, return_dict: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1882)

**参数：**

sample (`torch.Tensor`) : 具有如下形状 `(batch, num_frames, channel, height, width` 的含噪输入张量。

timestep (`torch.Tensor` 或 `float` 或 `int`)：用于对输入进行去噪的时间步数。

encoder_hidden_states (`torch.Tensor`) : 形状为 `(batch, sequence_length, feature_dim)` 的编码器隐藏状态。

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

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

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

added_cond_kwargs (`dict`, *可选*) : 用于为模型提供条件的额外嵌入字典（例如文本嵌入和时间嵌入）。

down_block_additional_residuals : (`tuple` of `torch.Tensor`，*可选*)：一个张量元组，如果指定，将被添加到下采样 unet 块的残差中。

mid_block_additional_residual : (`torch.Tensor`, *可选*): 一个张量，如果指定，将添加到中间 unet 块的残差中。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `UNetMotionOutput` 而非普通元组。

**返回：** `UNetMotionOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `UNetMotionOutput`，否则返回 `tuple`，其中第一个元素为样本张量。

[UNetMotionModel](/docs/diffusers/v0.43.0/zh/api/models/unet-motion#diffusers.UNetMotionModel) 的前向方法。

#### freeze_unet2d_params[[diffusers.UNetMotionModel.freeze_unet2d_params]]

```python
freeze_unet2d_params()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1691)

仅冻结 UNet2DConditionModel 的权重，而保持运动模块未冻结，以便进行微调。

#### fuse_qkv_projections[[diffusers.UNetMotionModel.fuse_qkv_projections]]

```python
fuse_qkv_projections()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1851)

启用融合的 QKV 投影。对于自注意力模块，所有投影矩阵（即 query、key、value）均会被融合。对于交叉注意力模块，key 和 value 投影矩阵会被融合。

> [!WARNING] > 此 API 处于 🧪 实验阶段。

#### set_default_attn_processor[[diffusers.UNetMotionModel.set_default_attn_processor]]

```python
set_default_attn_processor()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1801)

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

#### unfuse_qkv_projections[[diffusers.UNetMotionModel.unfuse_qkv_projections]]

```python
unfuse_qkv_projections()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_motion_model.py#L1873)

如果已启用，则禁用融合的 QKV 投影。

> [!WARNING] > 此 API 处于 🧪 实验阶段。

## UNet3DConditionOutput[[diffusers.models.unets.unet_3d_condition.UNet3DConditionOutput]]

#### diffusers.models.unets.unet_3d_condition.UNet3DConditionOutput[[diffusers.models.unets.unet_3d_condition.UNet3DConditionOutput]]

```python
diffusers.models.unets.unet_3d_condition.UNet3DConditionOutput(sample: Tensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/models/unets/unet_3d_condition.py#L50)

**参数：**

sample (`torch.Tensor`，形状为 `(batch_size, num_channels, num_frames, height, width)`)：基于 `encoder_hidden_states` 输入条件生成的隐藏状态输出。模型最后一层的输出。

[UNet3DConditionModel](/docs/diffusers/v0.43.0/zh/api/models/unet3d-cond#diffusers.UNet3DConditionModel) 的输出。

