ControlNet
ControlNet
The ControlNet model was introduced in Adding Conditional Control to Text-to-Image Diffusion Models by Lvmin Zhang and Maneesh Agrawala. It provides a greater degree of control over text-to-image generation by conditioning the model on additional inputs such as edge maps, depth maps, segmentation maps, and keypoints for pose detection.
The abstract from the paper is:
We present a neural network structure, ControlNet, to control pretrained large diffusion models to support additional input conditions. The ControlNet learns task-specific conditions in an end-to-end way, and the learning is robust even when the training dataset is small (< 50k). Moreover, training a ControlNet is as fast as fine-tuning a diffusion model, and the model can be trained on a personal devices. Alternatively, if powerful computation clusters are available, the model can scale to large amounts (millions to billions) of data. We report that large diffusion models like Stable Diffusion can be augmented with ControlNets to enable conditional inputs like edge maps, segmentation maps, keypoints, etc. This may enrich the methods to control large diffusion models and further facilitate related applications.
Loading from the original format
By default the ControlNetModel should be loaded with from_pretrained(), but it can also be loaded from the original format using FromOriginalControlnetMixin.from_single_file as follows:
Copied
from diffusers import StableDiffusionControlnetPipeline, ControlNetModel
url = "https://boincai.com/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
controlnet = ControlNetModel.from_single_file(url)
url = "https://boincai.com/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
pipe = StableDiffusionControlnetPipeline.from_single_file(url, controlnet=controlnet)ControlNetModel
class diffusers.ControlNetModel
( in_channels: int = 4conditioning_channels: int = 3flip_sin_to_cos: bool = Truefreq_shift: int = 0down_block_types: typing.Tuple[str] = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D')only_cross_attention: typing.Union[bool, typing.Tuple[bool]] = Falseblock_out_channels: typing.Tuple[int] = (320, 640, 1280, 1280)layers_per_block: int = 2downsample_padding: int = 1mid_block_scale_factor: float = 1act_fn: str = 'silu'norm_num_groups: typing.Optional[int] = 32norm_eps: float = 1e-05cross_attention_dim: int = 1280transformer_layers_per_block: typing.Union[int, typing.Tuple[int]] = 1encoder_hid_dim: typing.Optional[int] = Noneencoder_hid_dim_type: typing.Optional[str] = Noneattention_head_dim: typing.Union[int, typing.Tuple[int]] = 8num_attention_heads: typing.Union[int, typing.Tuple[int], NoneType] = Noneuse_linear_projection: bool = Falseclass_embed_type: typing.Optional[str] = Noneaddition_embed_type: typing.Optional[str] = Noneaddition_time_embed_dim: typing.Optional[int] = Nonenum_class_embeds: typing.Optional[int] = Noneupcast_attention: bool = Falseresnet_time_scale_shift: str = 'default'projection_class_embeddings_input_dim: typing.Optional[int] = Nonecontrolnet_conditioning_channel_order: str = 'rgb'conditioning_embedding_out_channels: typing.Optional[typing.Tuple[int]] = (16, 32, 96, 256)global_pool_conditions: bool = Falseaddition_embed_type_num_heads = 64 )
Parameters
in_channels (
int, defaults to 4) โ The number of channels in the input sample.flip_sin_to_cos (
bool, defaults toTrue) โ Whether to flip the sin to cos in the time embedding.freq_shift (
int, defaults to 0) โ The frequency shift to apply to the time embedding.down_block_types (
tuple[str], defaults to("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")) โ The tuple of downsample blocks to use.only_cross_attention (
Union[bool, Tuple[bool]], defaults toFalse) โblock_out_channels (
tuple[int], defaults to(320, 640, 1280, 1280)) โ The tuple of output channels for each block.layers_per_block (
int, defaults to 2) โ The number of layers per block.downsample_padding (
int, defaults to 1) โ The padding to use for the downsampling convolution.mid_block_scale_factor (
float, defaults to 1) โ The scale factor to use for the mid block.act_fn (
str, 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. If None, normalization and activation layers is skipped in post-processing.norm_eps (
float, defaults to 1e-5) โ The epsilon to use for the normalization.cross_attention_dim (
int, defaults to 1280) โ The dimension of the cross attention features.transformer_layers_per_block (
intorTuple[int], optional, defaults to 1) โ The number of transformer blocks of typeBasicTransformerBlock. Only relevant forCrossAttnDownBlock2D,CrossAttnUpBlock2D,UNetMidBlock2DCrossAttn.encoder_hid_dim (
int, optional, defaults to None) โ Ifencoder_hid_dim_typeis defined,encoder_hidden_stateswill be projected fromencoder_hid_dimdimension tocross_attention_dim.encoder_hid_dim_type (
str, optional, defaults toNone) โ If given, theencoder_hidden_statesand potentially other embeddings are down-projected to text embeddings of dimensioncross_attentionaccording toencoder_hid_dim_type.attention_head_dim (
Union[int, Tuple[int]], defaults to 8) โ The dimension of the attention heads.use_linear_projection (
bool, defaults toFalse) โclass_embed_type (
str, optional, defaults toNone) โ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,"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 fromNoneor โtextโ. โtextโ will use theTextTimeEmbeddinglayer.num_class_embeds (
int, optional, defaults to 0) โ Input dimension of the learnable embedding matrix to be projected totime_embed_dim, when performing class conditioning withclass_embed_typeequal toNone.upcast_attention (
bool, defaults toFalse) โresnet_time_scale_shift (
str, defaults to"default") โ Time scale shift config for ResNet blocks (seeResnetBlock2D). Choose fromdefaultorscale_shift.projection_class_embeddings_input_dim (
int, optional, defaults toNone) โ The dimension of theclass_labelsinput whenclass_embed_type="projection". Required whenclass_embed_type="projection".controlnet_conditioning_channel_order (
str, defaults to"rgb") โ The channel order of conditional image. Will convert torgbif itโsbgr.conditioning_embedding_out_channels (
tuple[int], optional, defaults to(16, 32, 96, 256)) โ The tuple of output channel for each block in theconditioning_embeddinglayer.global_pool_conditions (
bool, defaults toFalse) โ
A ControlNet model.
forward
( sample: FloatTensortimestep: typing.Union[torch.Tensor, float, int]encoder_hidden_states: Tensorcontrolnet_cond: FloatTensorconditioning_scale: float = 1.0class_labels: typing.Optional[torch.Tensor] = Nonetimestep_cond: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneadded_cond_kwargs: typing.Union[typing.Dict[str, torch.Tensor], NoneType] = Nonecross_attention_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = Noneguess_mode: bool = Falsereturn_dict: bool = True ) โ ControlNetOutput or tuple
Parameters
sample (
torch.FloatTensor) โ The noisy input tensor.timestep (
Union[torch.Tensor, float, int]) โ The number of timesteps to denoise an input.encoder_hidden_states (
torch.Tensor) โ The encoder hidden states.controlnet_cond (
torch.FloatTensor) โ The conditional input tensor of shape(batch_size, sequence_length, hidden_size).conditioning_scale (
float, defaults to1.0) โ The scale factor for ControlNet outputs.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) โattention_mask (
torch.Tensor, optional, defaults toNone) โadded_cond_kwargs (
dict) โ Additional conditions for the Stable Diffusion XL UNet.cross_attention_kwargs (
dict[str], optional, defaults toNone) โ A kwargs dictionary that if specified is passed along to theAttnProcessor.guess_mode (
bool, defaults toFalse) โ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if you remove all prompts. Aguidance_scalebetween 3.0 and 5.0 is recommended.return_dict (
bool, defaults toTrue) โ Whether or not to return a ControlNetOutput instead of a plain tuple.
Returns
ControlNetOutput or tuple
If return_dict is True, a ControlNetOutput is returned, otherwise a tuple is returned where the first element is the sample tensor.
The ControlNetModel forward method.
from_unet
( unet: UNet2DConditionModelcontrolnet_conditioning_channel_order: str = 'rgb'conditioning_embedding_out_channels: typing.Optional[typing.Tuple[int]] = (16, 32, 96, 256)load_weights_from_unet: bool = True )
Parameters
unet (
UNet2DConditionModel) โ The UNet model weights to copy to the ControlNetModel. All configuration options are also copied where applicable.
Instantiate a ControlNetModel from UNet2DConditionModel.
set_attention_slice
( slice_size )
Parameters
slice_size (
strorintorlist(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_dimmust 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
( 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.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.LoRAAttnProcessor, diffusers.models.attention_processor.LoRAAttnProcessor2_0, diffusers.models.attention_processor.LoRAXFormersAttnProcessor, diffusers.models.attention_processor.LoRAAttnAddedKVProcessor]]] )
Parameters
processor (
dictofAttentionProcessoror onlyAttentionProcessor) โ The instantiated processor class or a dictionary of processor classes that will be set as the processor for allAttentionlayers.If
processoris 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.
set_default_attn_processor
( )
Disables custom attention processors and sets the default attention implementation.
ControlNetOutput
class diffusers.models.controlnet.ControlNetOutput
( down_block_res_samples: typing.Tuple[torch.Tensor]mid_block_res_sample: Tensor )
Parameters
down_block_res_samples (
tuple[torch.Tensor]) โ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should be of shape(batch_size, channel * resolution, height //resolution, width // resolution). Output can be used to condition the original UNetโs downsampling activations.mid_down_block_re_sample (
torch.Tensor) โ The activation of the midde block (the lowest sample resolution). Each tensor should be of shape(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution). Output can be used to condition the original UNetโs middle block activation.
The output of ControlNetModel.
FlaxControlNetModel
class diffusers.FlaxControlNetModel
( sample_size: int = 32in_channels: int = 4down_block_types: typing.Tuple[str] = ('CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D', 'DownBlock2D')only_cross_attention: typing.Union[bool, typing.Tuple[bool]] = Falseblock_out_channels: typing.Tuple[int] = (320, 640, 1280, 1280)layers_per_block: int = 2attention_head_dim: typing.Union[int, typing.Tuple[int]] = 8num_attention_heads: typing.Union[int, typing.Tuple[int], NoneType] = Nonecross_attention_dim: int = 1280dropout: float = 0.0use_linear_projection: bool = Falsedtype: dtype = <class 'jax.numpy.float32'>flip_sin_to_cos: bool = Truefreq_shift: int = 0controlnet_conditioning_channel_order: str = 'rgb'conditioning_embedding_out_channels: typing.Tuple[int] = (16, 32, 96, 256)parent: typing.Union[typing.Type[flax.linen.module.Module], typing.Type[flax.core.scope.Scope], typing.Type[flax.linen.module._Sentinel], NoneType] = <flax.linen.module._Sentinel object at 0x7f3306dc42e0>name: typing.Optional[str] = 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.down_block_types (
Tuple[str], optional, defaults to("FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxDownBlock2D")) โ The tuple of downsample blocks to use.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 (
intorTuple[int], optional, defaults to 8) โ The dimension of the attention heads.num_attention_heads (
intorTuple[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.controlnet_conditioning_channel_order (
str, optional, defaults torgb) โ The channel order of conditional image. Will convert torgbif itโsbgr.conditioning_embedding_out_channels (
tuple, optional, defaults to(16, 32, 96, 256)) โ The tuple of output channel for each block in theconditioning_embeddinglayer.
A ControlNet model.
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:
FlaxControlNetOutput
class diffusers.models.controlnet_flax.FlaxControlNetOutput
( down_block_res_samples: Arraymid_block_res_sample: Array )
Parameters
down_block_res_samples (
jnp.ndarray) โmid_block_res_sample (
jnp.ndarray) โ
The output of FlaxControlNetModel.
replace
( **updates )
โReturns a new object replacing the specified fields with new values.
Last updated