Diffusers documentation

UNet2DConditionModel

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

UNet2DConditionModel

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

该论文的摘要如下:

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

UNet2DConditionModel

类 diffusers.UNet2DConditionModel

< >

( sample_size: int | tuple[int, int] | None = Nonein_channels: int = 4out_channels: int = 4center_input_sample: bool = Falseflip_sin_to_cos: bool = Truefreq_shift: int = 0down_block_types: tuple = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D')mid_block_type: str | None = 'UNetMidBlock2DCrossAttn'up_block_types: tuple = ('UpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D')only_cross_attention: bool | tuple[bool] = Falseblock_out_channels: tuple = (320, 640, 1280, 1280)layers_per_block: int | tuple[int] = 2downsample_padding: int = 1mid_block_scale_factor: float = 1dropout: float = 0.0act_fn: str = 'silu'norm_num_groups: int | None = 32norm_eps: float = 1e-05cross_attention_dim: int | tuple[int] = 1280transformer_layers_per_block: int | tuple[int] | tuple[tuple] = 1reverse_transformer_layers_per_block: tuple[tuple[int]] | None = Noneencoder_hid_dim: int | None = Noneencoder_hid_dim_type: str | None = Noneattention_head_dim: int | tuple[int] = 8num_attention_heads: int | tuple[int] | None = Nonedual_cross_attention: bool = Falseuse_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'resnet_skip_time_act: bool = Falseresnet_out_scale_factor: float = 1.0time_embedding_type: str = 'positional'time_embedding_dim: int | None = Nonetime_embedding_act_fn: str | None = Nonetimestep_post_act: str | None = Nonetime_cond_proj_dim: int | None = Noneconv_in_kernel: int = 3conv_out_kernel: int = 3projection_class_embeddings_input_dim: int | None = Noneattention_type: str = 'default'class_embeddings_concat: bool = Falsemid_block_only_cross_attention: bool | None = Nonecross_attention_norm: str | None = Noneaddition_embed_type_num_heads: int = 64 )

参数

  • sample_size (int 或 tuple[int, int],可选,默认为 None) — 输入/输出样本的高度和宽度。
  • in_channels (int,可选,默认为 4) — 输入样本的通道数。
  • out_channels (int,可选,默认为 4) — 输出中的通道数。
  • center_input_sample (bool,可选,默认为 False) — 是否对输入样本进行居中处理。
  • flip_sin_to_cos (bool,可选,默认为 True) — 是否将时间嵌入中的 sin 翻转为 cos。
  • freq_shift(int,可选,默认值为 0)——应用于时间嵌入的频率偏移量。
  • down_block_types (tuple[str],可选,默认为 ("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")) — 要使用的下采样块元组。
  • mid_block_type (str,可选,默认为 "UNetMidBlock2DCrossAttn") — UNet 中间部分的块类型,可以是 UNetMidBlock2DCrossAttn、UNetMidBlock2D 或 UNetMidBlock2DSimpleCrossAttn 之一。如果为 None,则跳过中间块层。
  • up_block_types (tuple[str],可选,默认为 ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")) — 要使用的上采样块元组。
  • only_cross_attention(bool 或 tuple[bool],可选,默认为 False) — 是否在基础 Transformer 块中包含自注意力,参见 BasicTransformerBlock。
  • 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.0)—— 用于中间块的缩放因子。
  • dropout (float,可选,默认值为 0.0) — 要使用的 dropout 概率。
  • act_fn (str,可选,默认为 "silu") — 要使用的激活函数。
  • norm_num_groups (int,可选,默认为 32) — 归一化所使用的组数。 如果 None,后处理中将跳过归一化和激活层。
  • norm_eps (float,可选,默认值为 1e-5) — 归一化所使用的 epsilon 值。
  • cross_attention_dim (int 或 tuple[int],可选,默认值为 1280) — 交叉注意力特征的维度。
  • transformer_layers_per_block(int、tuple[int] 或 tuple[tuple],可选,默认为 1)—— BasicTransformerBlock 类型 transformer 块的数量。仅对 CrossAttnDownBlock2D、CrossAttnUpBlock2D、 UNetMidBlock2DCrossAttn 有效。
  • reverse_transformer_layers_per_block — (tuple[tuple],可选,默认为 None): U-Net 的上采样块中类型为 BasicTransformerBlock 的 transformer 块的数量。仅当 transformer_layers_per_block 的类型为 tuple[tuple] 且针对 CrossAttnDownBlock2D、CrossAttnUpBlock2D、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,可选,默认为 8) — 注意力头的维度。
  • num_attention_heads (int, 可选) — 注意力头的数量。如果未定义,则默认为 attention_head_dim
  • resnet_time_scale_shift (str,可选,默认为 "default") — ResNet 块的时间缩放偏移配置(参见 ResnetBlock2D)。可选值为 default 或 scale_shift。
  • class_embed_type (str,可选,默认为 None) — 要使用的类别嵌入类型,最终会与时间嵌入相加。可选值包括 None、 "timestep"、"identity"、"projection" 或 "simple_projection"。
  • addition_embed_type (str,可选,默认为 None) — 配置一个可选的嵌入,该嵌入将与时间嵌入相加。可选值为 None 或 “text”。选择 “text” 时将使用 TextTimeEmbedding 层。
  • addition_time_embed_dim — (int,可选,默认为 None): 时间步嵌入的维度。
  • num_class_embeds (int,可选,默认为 None) — 当使用 class_embed_type 等于 None 的类别条件时,可学习嵌入矩阵的输入维度,该矩阵将被投影到 time_embed_dim。
  • time_embedding_type (str,可选,默认为 positional) — 用于时间步的位置嵌入类型。可选值为 positional 或 fourier。
  • time_embedding_dim (int,可选,默认为 None) — 用于覆盖投影后时间嵌入维度的可选参数。
  • time_embedding_act_fn (str,可选,默认为 None) — 可选的激活函数,仅在时间嵌入传递到 UNet 其余部分之前使用一次。可从 silu、mish、gelu 和 swish 中选择。
  • timestep_post_act (str,可选,默认为 None) — 用于时间步嵌入的第二个激活函数。可从 silu、mish 和 gelu 中选择。
  • time_cond_proj_dim (int,可选,默认为 None) — 时间步嵌入中 cond_proj 层的维度。
  • conv_in_kernel (int,可选,默认为 3) — conv_in 层的卷积核大小。
  • conv_out_kernel (int,可选,默认为 3) — conv_out 层的卷积核大小。
  • projection_class_embeddings_input_dim (int, 可选) — 当 class_embed_type="projection" 时,class_labels 输入的维度。当 class_embed_type="projection" 时必填。
  • class_embeddings_concat (bool,可选,默认为 False) — 是否将时间嵌入与类别嵌入进行拼接。
  • mid_block_only_cross_attention (bool,可选,默认为 None) — 在使用 UNetMidBlock2DSimpleCrossAttn 时,是否对中间块使用交叉注意力。如果 only_cross_attention 被指定为单个布尔值,且 mid_block_only_cross_attention 为 None,则 使用 only_cross_attention 的值作为 mid_block_only_cross_attention 的值。否则默认为 False。

一个条件 2D UNet 模型,接收带噪样本、条件状态和时间步,并返回具有样本形状的。

该模型继承自 ModelMixin。请查阅其父类文档,了解为所有模型实现的通用方法(例如下载或保存)。

disable_freeu

< >

( )

禁用 FreeU 机制。

enable_freeu

< >

( s1: floats2: floatb1: floatb2: float )

参数

  • s1 (float) — 用于第一阶段的比例因子,用于衰减跳跃特征的贡献。这样做是为了缓解增强去噪过程中的“过度平滑效应”。
  • s2 (float) — 用于衰减 skip features 贡献的第二阶段缩放因子。这样做是为了缓解增强去噪过程中的“过度平滑效应”。
  • b1 (float) — 用于放大骨干网络特征贡献的第一阶段缩放因子。
  • b2 (float) — 用于放大骨干网络特征贡献的第二阶段缩放因子。

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

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

有关适用于 Stable Diffusion v1、v2 和 Stable Diffusion XL 等不同流水线的已知良好参数组合,请参阅官方仓库。

forward

< >

( sample: Tensortimestep: typing.Union[torch.Tensor, float, int]encoder_hidden_states: Tensorclass_labels: typing.Optional[torch.Tensor] = Nonetimestep_cond: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonecross_attention_kwargs: dict[str, typing.Any] | None = Noneadded_cond_kwargs: dict[str, torch.Tensor] | None = Nonedown_block_additional_residuals: tuple[torch.Tensor] | None = Nonemid_block_additional_residual: typing.Optional[torch.Tensor] = Nonedown_intrablock_additional_residuals: tuple[torch.Tensor] | None = Noneencoder_attention_mask: typing.Optional[torch.Tensor] = Nonereturn_dict: bool = True ) → UNet2DConditionOutput or tuple

参数

  • sample (torch.Tensor) — 形状为 (batch, channel, height, width) 的含噪输入张量。
  • timestep(torch.Tensor 或 float 或 int)— 用于对输入进行去噪的时间步数。
  • encoder_hidden_states (torch.Tensor) — 形状为 (batch, sequence_length, feature_dim) 的编码器隐藏状态。
  • class_labels (torch.Tensor,可选,默认为 None) — 用于条件控制的可选类别标签。它们的嵌入将与时间步嵌入相加。
  • 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 中 self.processor 下定义的 AttentionProcessor。
  • added_cond_kwargs — (dict,可选): 一个 kwargs 字典,包含额外的嵌入。如果指定了这些嵌入,它们将被添加到传递给 UNet 块的嵌入中。
  • down_block_additional_residuals — (tuple of torch.Tensor, optional): 一个张量元组,如果指定,将添加到下采样 unet 块的残差中。
  • mid_block_additional_residual — (torch.Tensor, 可选): 如果指定,该张量将被添加到中间 unet 块的残差中。
  • down_intrablock_additional_residuals(tuple of torch.Tensor,可选)— 在 UNet 下采样块内部需要额外添加的残差,例如来自 T2I-Adapter 侧模型的残差
  • encoder_attention_mask (torch.Tensor) — 应用于 encoder_hidden_states 的交叉注意力掩码,形状为 (batch, sequence_length)。如果 True,则保留该掩码;否则,如果 False,则丢弃该掩码。掩码将被转换为偏置, 向对应于“丢弃”标记的注意力分数添加较大的负值。
  • return_dict (bool,可选,默认为 True) — 是否返回 UNet2DConditionOutput 而不是普通元组。

返回值

UNet2DConditionOutput 或 tuple

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

UNet2DConditionModel 的前向方法。

fuse_qkv_projections

< >

( )

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

> 此 API 处于 🧪 实验阶段。

set_attention_slice

< >

( slice_size: str | int | list[int] = 'auto' )

参数

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

启用切片注意力计算。

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

set_default_attn_processor

< >

( )

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

unfuse_qkv_projections

< >

( )

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

> 此 API 处于 🧪 实验阶段。

UNet2DConditionOutput

类 diffusers.models.unets.unet_2d_condition.UNet2DConditionOutput

< >

( sample: Tensor = None )

参数

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

UNet2DConditionModel 的输出。

Update on GitHub