UNet2DConditionModel
The UNet model was originally introduced by Ronneberger et al. for biomedical image segmentation, but it is also commonly used in 🤗 Diffusers because it outputs images that are the same size as the input. It is one of the most important components of a diffusion system because it facilitates the actual diffusion process. There are several variants of the UNet model in 🤗 Diffusers, depending on it’s number of dimensions and whether it is a conditional model or not. This is a 2D UNet conditional model.
The abstract from the paper is:
There is large consent that successful training of deep networks requires many thousand annotated training samples. In this paper, we present a network and training strategy that relies on the strong use of data augmentation to use the available annotated samples more efficiently. The architecture consists of a contracting path to capture context and a symmetric expanding path that enables precise localization. We show that such a network can be trained end-to-end from very few images and outperforms the prior best method (a sliding-window convolutional network) on the ISBI challenge for segmentation of neuronal structures in electron microscopic stacks. Using the same network trained on transmitted light microscopy images (phase contrast and DIC) we won the ISBI cell tracking challenge 2015 in these categories by a large margin. Moreover, the network is fast. Segmentation of a 512x512 image takes less than a second on a recent GPU. The full implementation (based on Caffe) and the trained networks are available at http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net.
UNet2DConditionModel
class diffusers.UNet2DConditionModel
< source >( sample_size: Optional = None in_channels: int = 4 out_channels: int = 4 center_input_sample: bool = False flip_sin_to_cos: bool = True freq_shift: int = 0 down_block_types: Tuple = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D') mid_block_type: Optional = 'UNetMidBlock2DCrossAttn' up_block_types: Tuple = ('UpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D') only_cross_attention: Union = False block_out_channels: Tuple = (320, 640, 1280, 1280) layers_per_block: Union = 2 downsample_padding: int = 1 mid_block_scale_factor: float = 1 dropout: float = 0.0 act_fn: str = 'silu' norm_num_groups: Optional = 32 norm_eps: float = 1e-05 cross_attention_dim: Union = 1280 transformer_layers_per_block: Union = 1 reverse_transformer_layers_per_block: Optional = None encoder_hid_dim: Optional = None encoder_hid_dim_type: Optional = None attention_head_dim: Union = 8 num_attention_heads: Union = None dual_cross_attention: bool = False use_linear_projection: bool = False class_embed_type: Optional = None addition_embed_type: Optional = None addition_time_embed_dim: Optional = None num_class_embeds: Optional = None upcast_attention: bool = False resnet_time_scale_shift: str = 'default' resnet_skip_time_act: bool = False resnet_out_scale_factor: float = 1.0 time_embedding_type: str = 'positional' time_embedding_dim: Optional = None time_embedding_act_fn: Optional = None timestep_post_act: Optional = None time_cond_proj_dim: Optional = None conv_in_kernel: int = 3 conv_out_kernel: int = 3 projection_class_embeddings_input_dim: Optional = None attention_type: str = 'default' class_embeddings_concat: bool = False mid_block_only_cross_attention: Optional = None cross_attention_norm: Optional = None addition_embed_type_num_heads: int = 64 )
Parameters
- sample_size (
int
orTuple[int, int]
, optional, defaults toNone
) — Height and width of input/output sample. - in_channels (
int
, optional, defaults to 4) — Number of channels in the input sample. - out_channels (
int
, optional, defaults to 4) — Number of channels in the output. - center_input_sample (
bool
, optional, defaults toFalse
) — Whether to center the input sample. - flip_sin_to_cos (
bool
, optional, defaults toTrue
) — Whether to flip the sin to cos in the time embedding. - freq_shift (
int
, optional, defaults to 0) — The frequency shift to apply to the time embedding. - down_block_types (
Tuple[str]
, optional, defaults to("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")
) — The tuple of downsample blocks to use. - mid_block_type (
str
, optional, defaults to"UNetMidBlock2DCrossAttn"
) — Block type for middle of UNet, it can be one ofUNetMidBlock2DCrossAttn
,UNetMidBlock2D
, orUNetMidBlock2DSimpleCrossAttn
. IfNone
, the mid block layer is skipped. - up_block_types (
Tuple[str]
, optional, defaults to("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")
) — The tuple of upsample blocks to use. - only_cross_attention(
bool
orTuple[bool]
, optional, default toFalse
) — Whether to include self-attention in the basic transformer blocks, seeBasicTransformerBlock
. - block_out_channels (
Tuple[int]
, optional, defaults to(320, 640, 1280, 1280)
) — The tuple of output channels for each block. - layers_per_block (
int
, optional, defaults to 2) — The number of layers per block. - downsample_padding (
int
, optional, defaults to 1) — The padding to use for the downsampling convolution. - mid_block_scale_factor (
float
, optional, defaults to 1.0) — The scale factor to use for the mid block. - dropout (
float
, optional, defaults to 0.0) — The dropout probability to use. - act_fn (
str
, optional, defaults to"silu"
) — The activation function to use. - norm_num_groups (
int
, optional, defaults to 32) — The number of groups to use for the normalization. IfNone
, normalization and activation layers is skipped in post-processing. - norm_eps (
float
, optional, defaults to 1e-5) — The epsilon to use for the normalization. - cross_attention_dim (
int
orTuple[int]
, optional, defaults to 1280) — The dimension of the cross attention features. - transformer_layers_per_block (
int
,Tuple[int]
, orTuple[Tuple]
, optional, defaults to 1) — The number of transformer blocks of typeBasicTransformerBlock
. Only relevant for~models.unet_2d_blocks.CrossAttnDownBlock2D
,~models.unet_2d_blocks.CrossAttnUpBlock2D
,~models.unet_2d_blocks.UNetMidBlock2DCrossAttn
. - reverse_transformer_layers_per_block — (
Tuple[Tuple]
, optional, defaults to None): The number of transformer blocks of typeBasicTransformerBlock
, in the upsampling blocks of the U-Net. Only relevant iftransformer_layers_per_block
is of typeTuple[Tuple]
and for~models.unet_2d_blocks.CrossAttnDownBlock2D
,~models.unet_2d_blocks.CrossAttnUpBlock2D
,~models.unet_2d_blocks.UNetMidBlock2DCrossAttn
. - encoder_hid_dim (
int
, optional, defaults to None) — Ifencoder_hid_dim_type
is defined,encoder_hidden_states
will be projected fromencoder_hid_dim
dimension tocross_attention_dim
. - encoder_hid_dim_type (
str
, optional, defaults toNone
) — If given, theencoder_hidden_states
and potentially other embeddings are down-projected to text embeddings of dimensioncross_attention
according toencoder_hid_dim_type
. - attention_head_dim (
int
, optional, defaults to 8) — The dimension of the attention heads. - num_attention_heads (
int
, optional) — The number of attention heads. If not defined, defaults toattention_head_dim
- resnet_time_scale_shift (
str
, optional, defaults to"default"
) — Time scale shift config for ResNet blocks (seeResnetBlock2D
). Choose fromdefault
orscale_shift
. - class_embed_type (
str
, optional, defaults toNone
) — The type of class embedding to use which is ultimately summed with the time embeddings. Choose fromNone
,"timestep"
,"identity"
,"projection"
, or"simple_projection"
. - addition_embed_type (
str
, optional, defaults toNone
) — Configures an optional embedding which will be summed with the time embeddings. Choose fromNone
or “text”. “text” will use theTextTimeEmbedding
layer. addition_time_embed_dim — (int
, optional, defaults toNone
): Dimension for the timestep embeddings. - num_class_embeds (
int
, optional, defaults toNone
) — Input dimension of the learnable embedding matrix to be projected totime_embed_dim
, when performing class conditioning withclass_embed_type
equal toNone
. - time_embedding_type (
str
, optional, defaults topositional
) — The type of position embedding to use for timesteps. Choose frompositional
orfourier
. - time_embedding_dim (
int
, optional, defaults toNone
) — An optional override for the dimension of the projected time embedding. - time_embedding_act_fn (
str
, optional, defaults toNone
) — Optional activation function to use only once on the time embeddings before they are passed to the rest of the UNet. Choose fromsilu
,mish
,gelu
, andswish
. - timestep_post_act (
str
, optional, defaults toNone
) — The second activation function to use in timestep embedding. Choose fromsilu
,mish
andgelu
. - time_cond_proj_dim (
int
, optional, defaults toNone
) — The dimension ofcond_proj
layer in the timestep embedding. - conv_in_kernel (
int
, optional, default to3
) — The kernel size ofconv_in
layer. - conv_out_kernel (
int
, optional, default to3
) — The kernel size ofconv_out
layer. - projection_class_embeddings_input_dim (
int
, optional) — The dimension of theclass_labels
input whenclass_embed_type="projection"
. Required whenclass_embed_type="projection"
. - class_embeddings_concat (
bool
, optional, defaults toFalse
) — Whether to concatenate the time embeddings with the class embeddings. - mid_block_only_cross_attention (
bool
, optional, defaults toNone
) — Whether to use cross attention with the mid block when using theUNetMidBlock2DSimpleCrossAttn
. Ifonly_cross_attention
is given as a single boolean andmid_block_only_cross_attention
isNone
, theonly_cross_attention
value is used as the value formid_block_only_cross_attention
. Default toFalse
otherwise.
A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample shaped output.
This model inherits from ModelMixin. Check the superclass documentation for it’s generic methods implemented for all models (such as downloading or saving).
Disables the FreeU mechanism.
enable_freeu
< source >( s1: float s2: float b1: float b2: float )
Parameters
- s1 (
float
) — Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to mitigate the “oversmoothing effect” in the enhanced denoising process. - s2 (
float
) — Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to mitigate the “oversmoothing effect” in the enhanced denoising process. - b1 (
float
) — Scaling factor for stage 1 to amplify the contributions of backbone features. - b2 (
float
) — Scaling factor for stage 2 to amplify the contributions of backbone features.
Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
The suffixes after the scaling factors represent the stage blocks where they are being applied.
Please refer to the official repository for combinations of values that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
forward
< source >( sample: FloatTensor timestep: Union encoder_hidden_states: Tensor class_labels: Optional = None timestep_cond: Optional = None attention_mask: Optional = None cross_attention_kwargs: Optional = None added_cond_kwargs: Optional = None down_block_additional_residuals: Optional = None mid_block_additional_residual: Optional = None down_intrablock_additional_residuals: Optional = None encoder_attention_mask: Optional = None return_dict: bool = True ) → UNet2DConditionOutput or tuple
Parameters
- sample (
torch.FloatTensor
) — The noisy input tensor with the following shape(batch, channel, height, width)
. - timestep (
torch.FloatTensor
orfloat
orint
) — The number of timesteps to denoise an input. - encoder_hidden_states (
torch.FloatTensor
) — The encoder hidden states with shape(batch, sequence_length, feature_dim)
. - class_labels (
torch.Tensor
, optional, defaults toNone
) — Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings. timestep_cond — (torch.Tensor
, optional, defaults toNone
): Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed through theself.time_embedding
layer to obtain the timestep embeddings. - attention_mask (
torch.Tensor
, optional, defaults toNone
) — An attention mask of shape(batch, key_tokens)
is applied toencoder_hidden_states
. If1
the mask is kept, otherwise if0
it is discarded. Mask will be converted into a bias, which adds large negative values to the attention scores corresponding to “discard” tokens. - cross_attention_kwargs (
dict
, optional) — A kwargs dictionary that if specified is passed along to theAttentionProcessor
as defined underself.processor
in diffusers.models.attention_processor. added_cond_kwargs — (dict
, optional): A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that are passed along to the UNet blocks. down_block_additional_residuals — (tuple
oftorch.Tensor
, optional): A tuple of tensors that if specified are added to the residuals of down unet blocks. mid_block_additional_residual — (torch.Tensor
, optional): A tensor that if specified is added to the residual of the middle unet block. - down_intrablock_additional_residuals (
tuple
oftorch.Tensor
, optional) — additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s) - encoder_attention_mask (
torch.Tensor
) — A cross-attention mask of shape(batch, sequence_length)
is applied toencoder_hidden_states
. IfTrue
the mask is kept, otherwise ifFalse
it is discarded. Mask will be converted into a bias, which adds large negative values to the attention scores corresponding to “discard” tokens. - return_dict (
bool
, optional, defaults toTrue
) — Whether or not to return a UNet2DConditionOutput instead of a plain tuple.
Returns
UNet2DConditionOutput or tuple
If return_dict
is True, an UNet2DConditionOutput is returned, otherwise
a tuple
is returned where the first element is the sample tensor.
The UNet2DConditionModel forward method.
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
This API is 🧪 experimental.
set_attention_slice
< source >( slice_size: Union = 'auto' )
Parameters
- slice_size (
str
orint
orlist(int)
, optional, defaults to"auto"
) — When"auto"
, input to the attention heads is halved, so attention is computed in two steps. If"max"
, maximum amount of memory is saved by running only one slice at a time. If a number is provided, uses as many slices asattention_head_dim // slice_size
. In this case,attention_head_dim
must be a multiple ofslice_size
.
Enable sliced attention computation.
When this option is enabled, the attention module splits the input tensor in slices to compute attention in several steps. This is useful for saving some memory in exchange for a small decrease in speed.
set_attn_processor
< source >( processor: Union )
Parameters
- processor (
dict
ofAttentionProcessor
or onlyAttentionProcessor
) — The instantiated processor class or a dictionary of processor classes that will be set as the processor for allAttention
layers.If
processor
is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.
Sets the attention processor to use to compute attention.
Disables custom attention processors and sets the default attention implementation.
Disables the fused QKV projection if enabled.
This API is 🧪 experimental.
Unloads LoRA weights.
UNet2DConditionOutput
class diffusers.models.unets.unet_2d_condition.UNet2DConditionOutput
< source >( sample: FloatTensor = None )
The output of UNet2DConditionModel.
FlaxUNet2DConditionModel
class diffusers.FlaxUNet2DConditionModel
< source >( sample_size: int = 32 in_channels: int = 4 out_channels: int = 4 down_block_types: Tuple = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D') up_block_types: Tuple = ('UpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'CrossAttnUpBlock2D') mid_block_type: Optional = 'UNetMidBlock2DCrossAttn' only_cross_attention: Union = False block_out_channels: Tuple = (320, 640, 1280, 1280) layers_per_block: int = 2 attention_head_dim: Union = 8 num_attention_heads: Union = None cross_attention_dim: int = 1280 dropout: float = 0.0 use_linear_projection: bool = False dtype: dtype = <class 'jax.numpy.float32'> flip_sin_to_cos: bool = True freq_shift: int = 0 use_memory_efficient_attention: bool = False split_head_dim: bool = False transformer_layers_per_block: Union = 1 addition_embed_type: Optional = None addition_time_embed_dim: Optional = None addition_embed_type_num_heads: int = 64 projection_class_embeddings_input_dim: Optional = None parent: Union = <flax.linen.module._Sentinel object at 0x78df362b77f0> name: Optional = None )
Parameters
- sample_size (
int
, optional) — The size of the input sample. - in_channels (
int
, optional, defaults to 4) — The number of channels in the input sample. - out_channels (
int
, optional, defaults to 4) — The number of channels in the output. - down_block_types (
Tuple[str]
, optional, defaults to("FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxDownBlock2D")
) — The tuple of downsample blocks to use. - up_block_types (
Tuple[str]
, optional, defaults to("FlaxUpBlock2D", "FlaxCrossAttnUpBlock2D", "FlaxCrossAttnUpBlock2D", "FlaxCrossAttnUpBlock2D")
) — The tuple of upsample blocks to use. - mid_block_type (
str
, optional, defaults to"UNetMidBlock2DCrossAttn"
) — Block type for middle of UNet, it can be one ofUNetMidBlock2DCrossAttn
. IfNone
, the mid block layer is skipped. - block_out_channels (
Tuple[int]
, optional, defaults to(320, 640, 1280, 1280)
) — The tuple of output channels for each block. - layers_per_block (
int
, optional, defaults to 2) — The number of layers per block. - attention_head_dim (
int
orTuple[int]
, optional, defaults to 8) — The dimension of the attention heads. - num_attention_heads (
int
orTuple[int]
, optional) — The number of attention heads. - cross_attention_dim (
int
, optional, defaults to 768) — The dimension of the cross attention features. - dropout (
float
, optional, defaults to 0) — Dropout probability for down, up and bottleneck blocks. - flip_sin_to_cos (
bool
, optional, defaults toTrue
) — Whether to flip the sin to cos in the time embedding. - freq_shift (
int
, optional, defaults to 0) — The frequency shift to apply to the time embedding. - use_memory_efficient_attention (
bool
, optional, defaults toFalse
) — Enable memory efficient attention as described here. - split_head_dim (
bool
, optional, defaults toFalse
) — Whether to split the head dimension into a new axis for the self-attention computation. In most cases, enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample shaped output.
This model inherits from FlaxModelMixin. Check the superclass documentation for it’s generic methods implemented for all models (such as downloading or saving).
This model is also a Flax Linen flax.linen.Module subclass. Use it as a regular Flax Linen module and refer to the Flax documentation for all matters related to its general usage and behavior.
Inherent JAX features such as the following are supported:
FlaxUNet2DConditionOutput
class diffusers.models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput
< source >( sample: Array )
The output of FlaxUNet2DConditionModel.
“Returns a new object replacing the specified fields with new values.