UNetMotionModel
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 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.
UNetMotionModel
class diffusers.UNetMotionModel
< source >( sample_size: typing.Optional[int] = None in_channels: int = 4 out_channels: int = 4 down_block_types: typing.Tuple[str] = ('CrossAttnDownBlockMotion', 'CrossAttnDownBlockMotion', 'CrossAttnDownBlockMotion', 'DownBlockMotion') up_block_types: typing.Tuple[str] = ('UpBlockMotion', 'CrossAttnUpBlockMotion', 'CrossAttnUpBlockMotion', 'CrossAttnUpBlockMotion') block_out_channels: typing.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: typing.Optional[int] = 32 norm_eps: float = 1e-05 cross_attention_dim: int = 1280 use_linear_projection: bool = False num_attention_heads: typing.Union[int, typing.Tuple[int], NoneType] = 8 motion_max_seq_length: typing.Optional[int] = 32 motion_num_attention_heads: int = 8 use_motion_mid_block: int = True )
A modified 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_forward_chunking
< source >( chunk_size = None dim = 0 )
Parameters
- chunk_size (
int
, optional) — The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually over each tensor of dim=dim
. - dim (
int
, optional, defaults to0
) — The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch) or dim=1 (sequence length).
Sets the attention processor to use feed forward chunking.
enable_freeu
< source >( s1 s2 b1 b2 )
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: 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: typing.Union[typing.Dict[str, typing.Any], NoneType] = None down_block_additional_residuals: typing.Optional[typing.Tuple[torch.Tensor]] = None mid_block_additional_residual: typing.Optional[torch.Tensor] = None return_dict: bool = True ) → UNet3DConditionOutput or tuple
Parameters
- sample (
torch.FloatTensor
) — The noisy input tensor with the following shape(batch, num_frames, 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)
. 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. 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. - return_dict (
bool
, optional, defaults toTrue
) — Whether or not to return a UNet3DConditionOutput instead of a plain tuple.
Returns
UNet3DConditionOutput or tuple
If return_dict
is True, an UNet3DConditionOutput is returned, otherwise
a tuple
is returned where the first element is the sample tensor.
The UNetMotionModel forward method.
Freeze the weights of just the UNet2DConditionModel, and leave the motion modules unfrozen for fine tuning.
set_attn_processor
< source >( processor: typing.Union[diffusers.models.attention_processor.AttnProcessor, diffusers.models.attention_processor.AttnProcessor2_0, diffusers.models.attention_processor.XFormersAttnProcessor, diffusers.models.attention_processor.SlicedAttnProcessor, diffusers.models.attention_processor.AttnAddedKVProcessor, diffusers.models.attention_processor.SlicedAttnAddedKVProcessor, diffusers.models.attention_processor.AttnAddedKVProcessor2_0, diffusers.models.attention_processor.XFormersAttnAddedKVProcessor, diffusers.models.attention_processor.CustomDiffusionAttnProcessor, diffusers.models.attention_processor.CustomDiffusionXFormersAttnProcessor, diffusers.models.attention_processor.CustomDiffusionAttnProcessor2_0, diffusers.models.attention_processor.LoRAAttnProcessor, diffusers.models.attention_processor.LoRAAttnProcessor2_0, diffusers.models.attention_processor.LoRAXFormersAttnProcessor, diffusers.models.attention_processor.LoRAAttnAddedKVProcessor, typing.Dict[str, typing.Union[diffusers.models.attention_processor.AttnProcessor, diffusers.models.attention_processor.AttnProcessor2_0, diffusers.models.attention_processor.XFormersAttnProcessor, diffusers.models.attention_processor.SlicedAttnProcessor, diffusers.models.attention_processor.AttnAddedKVProcessor, diffusers.models.attention_processor.SlicedAttnAddedKVProcessor, diffusers.models.attention_processor.AttnAddedKVProcessor2_0, diffusers.models.attention_processor.XFormersAttnAddedKVProcessor, diffusers.models.attention_processor.CustomDiffusionAttnProcessor, diffusers.models.attention_processor.CustomDiffusionXFormersAttnProcessor, diffusers.models.attention_processor.CustomDiffusionAttnProcessor2_0, diffusers.models.attention_processor.LoRAAttnProcessor, diffusers.models.attention_processor.LoRAAttnProcessor2_0, diffusers.models.attention_processor.LoRAXFormersAttnProcessor, diffusers.models.attention_processor.LoRAAttnAddedKVProcessor]]] _remove_lora = False )
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.
UNet3DConditionOutput
class diffusers.models.unet_3d_condition.UNet3DConditionOutput
< source >( sample: FloatTensor )
The output of UNet3DConditionModel.