Ë
    (täiÎ�  ã            	       óv  — d dl mZ d dlmZ d dlZd dlmZ d dlmZ ddl	m
Z
mZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZ ddlmZmZmZmZ ddlmZmZmZmZm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z& ddl'm(Z(  ejR                  e*«      Z+e G d„ de«      «       Z, G d„ dejZ                  «      Z. G d„ de"ee
ee«      Z/d„ Z0y)é    )Ú	dataclass)ÚAnyN)Únn)Ú
functionalé   )ÚConfigMixinÚregister_to_config)ÚPeftAdapterMixin)ÚFromOriginalModelMixin)Ú
BaseOutputÚapply_lora_scaleÚloggingé   )ÚAttentionMixin)ÚADDED_KV_ATTENTION_PROCESSORSÚCROSS_ATTENTION_PROCESSORSÚAttnAddedKVProcessorÚAttnProcessor)ÚTextImageProjectionÚTextImageTimeEmbeddingÚTextTimeEmbeddingÚTimestepEmbeddingÚ	Timesteps)Ú
ModelMixin)ÚUNetMidBlock2DÚUNetMidBlock2DCrossAttnÚget_down_block)ÚUNet2DConditionModelc                   óT   — e Zd ZU dZeej                     ed<   ej                  ed<   y)ÚControlNetOutputa  
    The output of [`ControlNetModel`].

    Args:
        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 middle 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.
    Údown_block_res_samplesÚmid_block_res_sampleN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚtupleÚtorchÚTensorÚ__annotations__© ó    úv/Volumes/fast/ai/experiments/MLX_z-image/.venv/lib/python3.12/site-packages/diffusers/models/controlnets/controlnet.pyr    r    -   s"   … ñð " %§,¡,Ñ/Ó/ØŸ,™,Ô&r,   r    c            	       óF   ‡ — e Zd ZdZ	 	 ddededeedf   fˆ fd„Zd„ Zˆ xZS )	ÚControlNetConditioningEmbeddingu™  
    Quoting from https://huggingface.co/papers/2302.05543: "Stable Diffusion uses a pre-processing method similar to
    VQ-GAN [11] to convert the entire dataset of 512 Ã— 512 images into smaller 64 Ã— 64 â€œlatent imagesâ€� for stabilized
    training. This requires ControlNets to convert image-based conditions to 64 Ã— 64 feature space to match the
    convolution size. We use a tiny network E(Â·) of four convolution layers with 4 Ã— 4 kernels and 2 Ã— 2 strides
    (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
    model) to encode image-space conditions ... into feature maps ..."
    Úconditioning_embedding_channelsÚconditioning_channelsÚblock_out_channels.c           
      ó  •— t         ‰| �  «        t        j                  ||d   dd¬«      | _        t        j
                  g «      | _        t        t        |«      dz
  «      D ]t  }||   }||dz      }| j                  j                  t        j                  ||dd¬«      «       | j                  j                  t        j                  ||ddd¬«      «       Œv t        t        j                  |d   |dd¬«      «      | _        y )Nr   r   é   ©Úkernel_sizeÚpaddingr   )r6   r7   Ústrideéÿÿÿÿ)ÚsuperÚ__init__r   ÚConv2dÚconv_inÚ
ModuleListÚblocksÚrangeÚlenÚappendÚzero_moduleÚconv_out)Úselfr0   r1   r2   ÚiÚ
channel_inÚchannel_outÚ	__class__s          €r-   r;   z(ControlNetConditioningEmbedding.__init__K   sá   ø€ ô 	‰ÑÔä—y‘yÐ!6Ð8JÈ1Ñ8MÐ[\ÐfgÔhˆŒä—m‘m BÓ'ˆŒä”sÐ-Ó.°Ñ2Ö3ˆAØ+¨AÑ.ˆJØ,¨Q°©UÑ3ˆKØ�K‰K×ÑœrŸy™y¨°ZÈQÐXYÔZÔ[Ø�K‰K×ÑœrŸy™y¨°[ÈaÐYZÐcdÔeÕfð	 4ô $Ü�I‰IÐ(¨Ñ,Ð.MÐ[\ÐfgÔhó
ˆ�r,   c                 óÐ   — | j                  |«      }t        j                  |«      }| j                  D ]  } ||«      }t        j                  |«      }Œ! | j	                  |«      }|S ©N)r=   ÚFÚsilur?   rD   )rE   ÚconditioningÚ	embeddingÚblocks       r-   Úforwardz'ControlNetConditioningEmbedding.forwarda   sZ   € Ø—L‘L Ó.ˆ	Ü—F‘F˜9Ó%ˆ	à—[”[ˆEÙ˜iÓ(ˆIÜŸ™˜yÓ)‰Ið !ð —M‘M )Ó,ˆ	àÐr,   )r   ©é   é    é`   é   )	r#   r$   r%   r&   Úintr'   r;   rQ   Ú__classcell__©rI   s   @r-   r/   r/   A   s>   ø„ ñð &'Ø.?ñ	
à),ð
ð  #ð
ð " # s (™Oõ	
ö,
r,   r/   c            B       ó|  ‡ — e Zd ZdZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d:dededededee	d	f   d
e	dz  deee   z  deed	f   dedede
de	dedz  de
dedeeed	f   z  dedz  de	dz  deeed	f   z  deeed	f   z  dz  dede	dz  de	dz  dedz  dedz  dede	d edz  d!e	d"eed	f   dz  d#ed$ef@ˆ fd%„«       Ze	 	 	 	 d;d&ed!e	d"eed	f   dz  d'edef
d(„«       Zd)„ Zd*e	ez  ee   z  d+dfd,„Z ed-«      	 	 	 	 	 	 	 	 d<d.ej(                  d/ej(                  e
z  ez  d0ej(                  d1ej(                  d2e
d3ej(                  dz  d4ej(                  dz  d5ej(                  dz  d6ee	ej(                  f   dz  d-ee	ef   dz  d7ed8ed+eeeej(                  d	f   ej(                  f   z  fd9„«       Zˆ xZS )=ÚControlNetModelaœ  
    A ControlNet model.

    Args:
        in_channels (`int`, defaults to 4):
            The number of channels in the input sample.
        flip_sin_to_cos (`bool`, defaults to `True`):
            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 (`bool | tuple[bool]`, defaults to `False`):
        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 (`int` or `tuple[int]`, *optional*, defaults to 1):
            The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
            [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
            [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
        encoder_hid_dim (`int`, *optional*, defaults to None):
            If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
            dimension to `cross_attention_dim`.
        encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
            If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
            embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
        attention_head_dim (`int | tuple[int]`, defaults to 8):
            The dimension of the attention heads.
        use_linear_projection (`bool`, defaults to `False`):
        class_embed_type (`str`, *optional*, defaults to `None`):
            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 to `None`):
            Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
            "text". "text" will use the `TextTimeEmbedding` layer.
        num_class_embeds (`int`, *optional*, defaults to 0):
            Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
            class conditioning with `class_embed_type` equal to `None`.
        upcast_attention (`bool`, defaults to `False`):
        resnet_time_scale_shift (`str`, defaults to `"default"`):
            Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
        projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
            The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
            `class_embed_type="projection"`.
        controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
            The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
        conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
            The tuple of output channel for each block in the `conditioning_embedding` layer.
        global_pool_conditions (`bool`, defaults to `False`):
            TODO(Patrick) - unused parameter.
        addition_embed_type_num_heads (`int`, defaults to 64):
            The number of heads to use for the `TextTimeEmbedding` layer.
    TNÚin_channelsr1   Úflip_sin_to_cosÚ
freq_shiftÚdown_block_types.Úmid_block_typeÚonly_cross_attentionr2   Úlayers_per_blockÚdownsample_paddingÚmid_block_scale_factorÚact_fnÚnorm_num_groupsÚnorm_epsÚcross_attention_dimÚtransformer_layers_per_blockÚencoder_hid_dimÚencoder_hid_dim_typeÚattention_head_dimÚnum_attention_headsÚuse_linear_projectionÚclass_embed_typeÚaddition_embed_typeÚaddition_time_embed_dimÚnum_class_embedsÚupcast_attentionÚresnet_time_scale_shiftÚ%projection_class_embeddings_input_dimÚ%controlnet_conditioning_channel_orderÚ#conditioning_embedding_out_channelsÚglobal_pool_conditionsÚaddition_embed_type_num_headsc!                 ó¢
  •— t         ‰/| �  «        |xs |}t        |«      t        |«      k7  rt        d|› d|› d�«      ‚t	        |t
        «      s)t        |«      t        |«      k7  rt        d|› d|› d�«      ‚t	        |t        «      s)t        |«      t        |«      k7  rt        d|› d|› d�«      ‚t	        |t        «      r|gt        |«      z  }d}!|!dz
  dz  }"t        j                  ||d	   |!|"¬
«      | _	        |d	   dz  }#t        |d	   ||«      | _        |d	   }$t        |$|#|¬«      | _        |€+|�)d}| j                  |¬«       t        j!                  d«       |€|�t        d|› d�«      ‚|dk(  rt        j"                  ||«      | _        n1|dk(  rt'        |||¬«      | _        n|�t        d|› d�«      ‚d | _        |€|�t        j(                  ||#«      | _        nc|dk(  rt        |$|#«      | _        nL|dk(  rt        j,                  |#|#«      | _        n+|dk(  r|€t        d«      ‚t        ||#«      | _        nd | _        |dk(  r|�|}%n|}%t/        |%|#| ¬«      | _        nS|dk(  rt3        |||#¬«      | _        n:|dk(  r$t        |||«      | _        t        ||#«      | _        n|�t        d|› d�«      ‚t7        |d	   ||¬ «      | _        t        j:                  g «      | _        t        j:                  g «      | _        t	        |t
        «      r|gt        |«      z  }t	        |t        «      r|ft        |«      z  }t	        |t        «      r|ft        |«      z  }|d	   }&t        j                  |&|&d¬!«      }'tA        |'«      }'| j>                  jC                  |'«       tE        |«      D �]  \  }(})|&}*||(   }&|(t        |«      dz
  k(  }+tG        |)fi d"|	“d#||(   “d$|*“d%|&“d&|#“d'|+ “d(|“d)|“d*|“d+|“d,||(   “d-||(   �||(   n|&“d.|
“d/|“d0||(   “d1|“d2|“Ž},| j<                  jC                  |,«       tI        |	«      D ]@  }-t        j                  |&|&d¬!«      }'tA        |'«      }'| j>                  jC                  |'«       ŒB |+rŒÜt        j                  |&|&d¬!«      }'tA        |'«      }'| j>                  jC                  |'«       �Œ |d3   }.t        j                  |.|.d¬!«      }'tA        |'«      }'|'| _%        |d4k(  r#tM        |d3   |.|#||||||d3   |||¬5«      | _'        y |d6k(  rtQ        |d3   |#d	|||||d7¬8«	      | _'        y t        d9|› �«      ‚):NzbMust provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: z. `down_block_types`: Ú.zfMust provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: zdMust provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: r   r4   r   r   r5   é   )re   Ú	text_proj)rk   zMencoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.zJ`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to Útext_image_proj)Útext_embed_dimÚimage_embed_dimrh   zencoder_hid_dim_type: z0 must be None, 'text_proj' or 'text_image_proj'.ÚtimestepÚidentityÚ
projectionzX`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be setÚtext)Ú	num_headsÚ
text_image)r   r€   Útime_embed_dimÚ	text_timezaddition_embed_type: z& must be None, 'text' or 'text_image'.)r0   r2   r1   )r6   Ú
num_layersri   r\   Úout_channelsÚtemb_channelsÚadd_downsampleÚ
resnet_epsÚresnet_act_fnÚresnet_groupsrh   rm   rl   rc   rn   ra   rs   rt   r9   r   )ri   r\   r‹   r�   rŽ   Úoutput_scale_factorrt   rh   rm   r�   rn   rs   r   F)	r\   r‹   r‰   r�   rŽ   r�   r�   rt   Úadd_attentionzunknown mid_block_type : ))r:   r;   rA   Ú
ValueErrorÚ
isinstanceÚboolrW   r   r<   r=   r   Ú	time_projr   Útime_embeddingr	   ÚloggerÚinfoÚLinearÚencoder_hid_projr   Ú	EmbeddingÚclass_embeddingÚIdentityr   Úadd_embeddingr   Úadd_time_projr/   Úcontrolnet_cond_embeddingr>   Údown_blocksÚcontrolnet_down_blocksrC   rB   Ú	enumerater   r@   Úcontrolnet_mid_blockr   Ú	mid_blockr   )0rE   r\   r1   r]   r^   r_   r`   ra   r2   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   Úconv_in_kernelÚconv_in_paddingr‡   Útimestep_input_dimÚtext_time_embedding_from_dimÚoutput_channelÚcontrolnet_blockrF   Údown_block_typeÚinput_channelÚis_final_blockÚ
down_blockÚ_Úmid_block_channelrI   s0                                                  €r-   r;   zControlNetModel.__init__µ   s  ø€ ôR 	‰ÑÔð 2ÒGÐ5GÐô Ð!Ó"¤cÐ*:Ó&;Ò;ÜØtð  vHð  uIð  I_ð  `pð  _qð  qrð  sóð ô Ð.´Ô5¼#Ð>RÓ:SÔWZÐ[kÓWlÒ:lÜØxð  zNð  yOð  Oeð  fvð  ewð  wxð  yóð ô Ð-¬sÔ3¼Ð<OÓ8PÔTWÐXhÓTiÒ8iÜØvð  xKð  wLð  Lbð  csð  btð  tuð  vóð ô Ð2´CÔ8Ø,HÐ+IÌCÐP`ÓLaÑ+aÐ(ð ˆØ)¨AÑ-°!Ñ3ˆÜ—y‘yØÐ+¨AÑ.¸NÐTcô
ˆŒð
 ,¨AÑ.°Ñ2ˆÜ"Ð#5°aÑ#8¸/È:ÓVˆŒØ/°Ñ2ÐÜ/ØØØô
ˆÔð  Ð'¨OÐ,GØ#.Ð Ø×#Ñ#Ð9MÐ#ÔNÜ�K‰KÐgÔhàÐ"Ð';Ð'GÜØ\Ð]qÐ\rÐrsÐtóð ð   ;Ò.Ü$&§I¡I¨oÐ?RÓ$SˆDÕ!Ø!Ð%6Ò6ô %8Ø.Ø 3Ø$7ô%ˆDÕ!ð "Ð-ÜØ(Ð)=Ð(>Ð>nÐoóð ð %)ˆDÔ!ð Ð#Ð(8Ð(DÜ#%§<¡<Ð0@À.Ó#QˆDÕ Ø Ò+Ü#4Ð5GÈÓ#XˆDÕ Ø Ò+Ü#%§;¡;¨~¸~Ó#NˆDÕ Ø Ò-Ø4Ð<Ü Ønóð ô $5Ð5ZÐ\jÓ#kˆDÕ à#'ˆDÔ à &Ò(ØÐ*Ø/>Ñ,à/BÐ,ä!2Ø,¨nÐHeô"ˆDÕð ! LÒ0ô "8Ø2ÐDWÐhvô"ˆDÕð ! KÒ/Ü!*Ð+BÀOÐU_Ó!`ˆDÔÜ!2Ð3XÐZhÓ!iˆDÕà Ð,ÜÐ4Ð5HÐ4IÐIoÐpÓqÐqô *IØ,>¸qÑ,AØBØ"7ô*
ˆÔ&ô Ÿ=™=¨Ó,ˆÔÜ&(§m¡m°BÓ&7ˆÔ#äÐ*¬DÔ1Ø$8Ð#9¼CÐ@PÓ<QÑ#QÐ äÐ(¬#Ô.Ø"4Ð!6¼Ð=MÓ9NÑ!NÐäÐ)¬3Ô/Ø#6Ð"8¼3Ð?OÓ;PÑ"PÐð ,¨AÑ.ˆäŸ9™9 ^°^ÐQRÔSÐÜ&Ð'7Ó8ÐØ×#Ñ#×*Ñ*Ð+;Ô<ä"+Ð,<×"=ÑˆAˆØ*ˆMØ/°Ñ2ˆNØ¤#Ð&8Ó"9¸AÑ"=Ñ=ˆNä'Øòá+ðð .JÈ!Ò-Lðñ *ð	ñ
 ,ðñ -ðð $2Ñ1ðñ $ðñ %ðñ .ðñ %8ðð %8¸Ò$:ðð =OÈqÑ<QÐ<]Ð#5°aÒ#8Ðcqøðñ $6ðñ '<ðð  &:¸!Ò%<ð!ñ" "2ð#ñ$ )@ð%ˆJð( ×Ñ×#Ñ# JÔ/äÐ+Ö,�Ü#%§9¡9¨^¸^ÐYZÔ#[Ð Ü#.Ð/?Ó#@Ð Ø×+Ñ+×2Ñ2Ð3CÕDð -ò
 "Ü#%§9¡9¨^¸^ÐYZÔ#[Ð Ü#.Ð/?Ó#@Ð Ø×+Ñ+×2Ñ2Ð3CÖDðG #>ðL /¨rÑ2ÐäŸ9™9Ð%6Ð8IÐWXÔYÐÜ&Ð'7Ó8ÐØ$4ˆÔ!àÐ6Ò6Ü4Ø-IÈ"Ñ-MØ-Ø,Ø#Ø$Ø$:Ø(?Ø$7Ø$7¸Ñ$;Ø-Ø&;Ø!1ôˆD�Nð Ð/Ò/Ü+Ø.¨rÑ2Ø,ØØ#Ø$Ø$:Ø-Ø(?Ø#ô
ˆD�Nô Ð8¸Ð8HÐIÓJÐJr,   ÚunetÚload_weights_from_unetc                 ó²  — d|j                   v r|j                   j                  nd}d|j                   v r|j                   j                  nd}d|j                   v r|j                   j                  nd}d|j                   v r|j                   j                  nd}	d|j                   v r|j                   j
                  nd}
 | d"i d|“d|“d|	“d|
“d|“d|j                   j                  “d	|j                   j                  “d
|j                   j                  “d|j                   j                  “d|j                   j                  “d|j                   j                  “d|j                   j                  “d|j                   j                  “d|j                   j                  “d|j                   j                  “d|j                   j                   “d|j                   j"                  “d|j                   j$                  “d|j                   j&                  “d|j                   j(                  “d|j                   j*                  “d|j                   j,                  “d|j                   j.                  “d|j                   j0                  “d|j                   j2                  “d|j                   j4                  “d|j                   j6                  “d|“d|“d |“Ž}|�r}|j8                  j;                  |j8                  j=                  «       «       |j>                  j;                  |j>                  j=                  «       «       |j@                  j;                  |j@                  j=                  «       «       |jB                  r3|jB                  j;                  |jB                  j=                  «       «       tE        |d!«      r3|jF                  j;                  |jF                  j=                  «       «       |jH                  j;                  |jH                  j=                  «       «       |jJ                  j;                  |jJ                  j=                  «       «       |S )#a)  
        Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].

        Parameters:
            unet (`UNet2DConditionModel`):
                The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
                where applicable.
        ri   r4   rj   Nrk   rp   rq   r\   r]   r^   r_   ra   r2   rb   rc   rd   re   rf   rg   rh   rl   rm   rn   ro   rr   rs   rt   ru   r`   rv   rw   r1   rž   r+   )&Úconfigri   rj   rk   rp   rq   r\   r]   r^   r_   ra   r2   rb   rc   rd   re   rf   rg   rh   rl   rm   rn   ro   rr   rs   rt   ru   r`   r=   Úload_state_dictÚ
state_dictr•   r–   rœ   Úhasattrrž   r¡   r¥   )Úclsr²   rv   rw   r³   r1   ri   rj   rk   rp   rq   Ú
controlnets               r-   Ú	from_unetzControlNetModel.from_unet»  sÎ  € ð$ 9WÐZ^×ZeÑZeÑ8eˆD�K‰K×4Ò4Ðklð 	%ð :KÈdÏkÉkÑ9Y˜$Ÿ+™+×5Ò5Ð_cˆØCYÐ]a×]hÑ]hÑCh˜tŸ{™{×?Ò?ÐnrÐØAVÐZ^×ZeÑZeÑAe˜dŸk™k×=Ò=ÐkoÐà3LÐPT×P[ÑP[Ñ3[ˆD�K‰K×/Ò/Ðaeð 	 ñ ò 
Ù+ð
á!5ð
ñ !4ð
ñ %<ð	
ñ
 *Fð
ð Ÿ™×/Ò/ð
ð !ŸK™K×7Ò7ð
ð —{‘{×-Ò-ð
ð "Ÿ[™[×9Ò9ð
ð "&§¡×!AÒ!Að
ð  $Ÿ{™{×=Ò=ð
ð "Ÿ[™[×9Ò9ð
ð  $Ÿ{™{×=Ò=ð
ð $(§;¡;×#EÒ#Eð
ð —;‘;×%Ò%ð
ð  !ŸK™K×7Ò7ð!
ð" —[‘[×)Ò)ð#
ð$ !%§¡× ?Ò ?ð%
ð&  $Ÿ{™{×=Ò=ð'
ð( !%§¡× ?Ò ?ð)
ð* #'§+¡+×"CÒ"Cð+
ð, "Ÿ[™[×9Ò9ð-
ð. "Ÿ[™[×9Ò9ð/
ð0 "Ÿ[™[×9Ò9ð1
ð2 %)§K¡K×$GÒ$Gð3
ð4 37·+±+×2cÒ2cð5
ð6  Ÿ;™;×5Ò5ð7
ñ8 3Xð9
ñ: 1Tð;
ñ< #8ð=
ˆ
òB "Ø×Ñ×.Ñ.¨t¯|©|×/FÑ/FÓ/HÔIØ× Ñ ×0Ñ0°·±×1JÑ1JÓ1LÔMØ×%Ñ%×5Ñ5°d×6IÑ6I×6TÑ6TÓ6VÔWà×)Ò)Ø×*Ñ*×:Ñ:¸4×;OÑ;O×;ZÑ;ZÓ;\Ô]ä�z ?Ô3Ø×(Ñ(×8Ñ8¸×9KÑ9K×9VÑ9VÓ9XÔYà×"Ñ"×2Ñ2°4×3CÑ3C×3NÑ3NÓ3PÔQØ× Ñ ×0Ñ0°·±×1JÑ1JÓ1LÔMàÐr,   c           	      ój  — t        d„ | j                  j                  «       D «       «      rt        «       }nmt        d„ | j                  j                  «       D «       «      rt	        «       }n8t        dt        t        | j                  j                  «       «      «      › �«      ‚| j                  |«       y)ze
        Disables custom attention processors and sets the default attention implementation.
        c              3   ó@   K  — | ]  }|j                   t        v –— Œ y ­wrK   )rI   r   ©Ú.0Úprocs     r-   Ú	<genexpr>z=ControlNetModel.set_default_attn_processor.<locals>.<genexpr>  s   è ø€ ÐiÑKhÀ4ˆt�~‰~Ô!>Ô>ÑKhùó   ‚c              3   ó@   K  — | ]  }|j                   t        v –— Œ y ­wrK   )rI   r   r¾   s     r-   rÁ   z=ControlNetModel.set_default_attn_processor.<locals>.<genexpr>  s   è ø€ ÐhÑJgÀ$�—‘Ô#=Ô=ÑJgùrÂ   zOCannot call `set_default_attn_processor` when attention processors are of type N)	ÚallÚattn_processorsÚvaluesr   r   r’   ÚnextÚiterÚset_attn_processor)rE   Ú	processors     r-   Úset_default_attn_processorz*ControlNetModel.set_default_attn_processor  s´   € ô ÑiÈ4×K_ÑK_×KfÑKfÔKhÓiÔiÜ,Ó.‰IÜÑhÈ$×J^ÑJ^×JeÑJeÔJgÓhÔhÜ%›‰IäØaÔbfÔgkÐlp÷  mAñ  mA÷  mHñ  mHó  mJó  hKó  cLð  bMð  Nóð ð 	×Ñ 	Õ*r,   Ú
slice_sizeÚreturnc                 ó   ‡‡	‡
— g Š
dt         j                  j                  fˆˆ
fd„Š| j                  «       D ]
  } ‰|«       Œ t	        ‰
«      }|dk(  r‰
D �cg c]  }|dz  ‘Œ	 }}n|dk(  r|dgz  }t        |t        «      s||gz  n|}t	        |«      t	        ‰
«      k7  r=t        dt	        |«      › d| j                  › d	t	        ‰
«      › d
t	        ‰
«      › d�	«      ‚t        t	        |«      «      D ]&  }||   }‰
|   }|€Œ||kD  sŒt        d|› d|› d�«      ‚ dt         j                  j                  dt        t           fˆ	fd„Š	t        t        |«      «      }| j                  «       D ]  } ‰	||«       Œ yc c}w )a  
        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.

        Args:
            slice_size (`str` or `int` or `list(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 as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
                must be a multiple of `slice_size`.
        Úmodulec                 óŽ   •— t        | d«      r‰j                  | j                  «       | j                  «       D ]
  } ‰|«       Œ y ©NÚset_attention_slice)r¸   rB   Úsliceable_head_dimÚchildren)rÏ   ÚchildÚ$fn_recursive_retrieve_sliceable_dimsÚsliceable_head_dimss     €€r-   rÖ   zQControlNetModel.set_attention_slice.<locals>.fn_recursive_retrieve_sliceable_dims(  s;   ø€ Ü�vÐ4Ô5Ø#×*Ñ*¨6×+DÑ+DÔEàŸ™Ö*�Ù4°UÕ;ñ +r,   Úautor   Úmaxr4   zYou have provided z, but z has zH different attention layers. Make sure to match `len(slice_size)` to be r{   Nzsize z has to be smaller or equal to rÌ   c                 ó˜   •— t        | d«      r| j                  |j                  «       «       | j                  «       D ]  } ‰||«       Œ y rÑ   )r¸   rÒ   ÚpoprÔ   )rÏ   rÌ   rÕ   Ú fn_recursive_set_attention_slices      €r-   rÜ   zMControlNetModel.set_attention_slice.<locals>.fn_recursive_set_attention_sliceN  s>   ø€ Ü�vÐ4Ô5Ø×*Ñ*¨:¯>©>Ó+;Ô<àŸ™Ö*�Ù0°¸
ÕCñ +r,   )r(   r   ÚModulerÔ   rA   r“   Úlistr’   rµ   r@   rW   Úreversed)rE   rÌ   rÏ   Únum_sliceable_layersÚdimrF   ÚsizeÚreversed_slice_sizerÖ   rÜ   r×   s           @@@r-   rÒ   z#ControlNetModel.set_attention_slice  s   ú€ ð !Ðð	<¼¿¹¿¹ö 	<ð —m‘m–oˆFÙ0°Õ8ð &ô  #Ð#6Ó7Ðà˜Òñ /BÓBÑ.A s˜# ›(Ð.AˆJÑBØ˜5Ò à-°°Ñ3ˆJä@JÈ:ÔW[Ô@\Ð)¨Z¨LÒ8Ðblˆ
äˆz‹?œcÐ"5Ó6Ò6ÜØ$¤S¨£_Ð$5°V¸D¿K¹K¸=ÈÌcÐReÓNfÐMgð hQÜQTÐUhÓQiÐPjÐjkðmóð ô
 ”s˜:“Ö'ˆAØ˜a‘=ˆDØ% aÑ(ˆCØÑ D¨3£JÜ  5¨¨Ð.MÈcÈUÐRSÐ!TÓUÐUð	 (ð	D´U·X±X·_±_ð 	DÔRVÔWZÑR[õ 	Dô #¤8¨JÓ#7Ó8ÐØ—m‘m–oˆFÙ,¨VÐ5HÕIñ &ùò= Cs   ÁE;Úcross_attention_kwargsÚsampler�   Úencoder_hidden_statesÚcontrolnet_condÚconditioning_scaleÚclass_labelsÚtimestep_condÚattention_maskÚadded_cond_kwargsÚ
guess_modeÚreturn_dictc                 óP  — | j                   j                  }|dk(  rn,|dk(  rt        j                  |dg¬«      }nt	        d|› �«      ‚|�2d|j                  |j                  «      z
  dz  }|j                  d«      }|}t        j                  |«      s¯|j                  j                  dk(  }|j                  j                  d	k(  }t        |t        «      r%|s|rt        j                  nt        j                  }n$|s|rt        j                  nt        j                   }t        j"                  |g||j                  ¬
«      }n6t%        |j&                  «      dk(  r|d   j                  |j                  «      }|j)                  |j&                  d   «      }| j+                  |«      }|j                  |j                  ¬«      }| j-                  ||«      }d}| j.                  �g|€t	        d«      ‚| j                   j0                  dk(  r| j+                  |«      }| j/                  |«      j                  | j                  ¬«      }||z   }| j                   j2                  ��"| j                   j2                  dk(  r| j5                  |«      }n÷| j                   j2                  dk(  rÞd|	vrt	        | j6                  › d�«      ‚|	j9                  d«      }d|	vrt	        | j6                  › d�«      ‚|	j9                  d«      }| j;                  |j=                  «       «      }|j?                  |j&                  d   df«      }t        j@                  ||gd¬«      }|j                  |j                  «      }| j5                  |«      }|�||z   n|}| jC                  |«      }| jE                  |«      }||z   }|f}| jF                  D ]=  }tI        |d«      r|jJ                  r ||||||
¬«      \  }}n |||¬«      \  }}||z  }Œ? | jL                  �UtI        | jL                  d«      r-| jL                  jJ                  r| jM                  |||||
¬«      }n| jM                  ||«      }d}tO        || jP                  «      D ]  \  }} ||«      }||fz   }Œ |}| jS                  |«      } |rt| j                   jT                  s^t        jV                  ddt%        |«      dz   |j                  ¬«      }!|!|z  }!tO        ||!«      D ��"cg c]
  \  }}"||"z  ‘Œ }}}"| |!d   z  } n|D �cg c]  }||z  ‘Œ	 }}| |z  } | j                   jT                  r=|D �cg c]  }t        jX                  |dd¬«      ‘Œ }}t        jX                  | dd¬«      } |s|| fS t[        || ¬ «      S c c}"}w c c}w c c}w )!a#
  
        The [`ControlNetModel`] forward method.

        Args:
            sample (`torch.Tensor`):
                The noisy input tensor.
            timestep (`torch.Tensor | float | int`):
                The number of timesteps to denoise an input.
            encoder_hidden_states (`torch.Tensor`):
                The encoder hidden states.
            controlnet_cond (`torch.Tensor`):
                The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
            conditioning_scale (`float`, defaults to `1.0`):
                The scale factor for ControlNet outputs.
            class_labels (`torch.Tensor`, *optional*, defaults to `None`):
                Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
            timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
                Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
                timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
                embeddings.
            attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
                An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
                is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
                negative values to the attention scores corresponding to "discard" tokens.
            added_cond_kwargs (`dict`):
                Additional conditions for the Stable Diffusion XL UNet.
            cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
                A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
            guess_mode (`bool`, defaults to `False`):
                In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
                you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
            return_dict (`bool`, defaults to `True`):
                Whether or not to return a [`~models.controlnets.controlnet.ControlNetOutput`] instead of a plain
                tuple.

        Returns:
            [`~models.controlnets.controlnet.ControlNetOutput`] **or** `tuple`:
                If `return_dict` is `True`, a [`~models.controlnets.controlnet.ControlNetOutput`] is returned,
                otherwise a tuple is returned where the first element is the sample tensor.
        ÚrgbÚbgrr4   )Údimsz1unknown `controlnet_conditioning_channel_order`: Ng     ˆÃÀÚmpsÚnpu)ÚdtypeÚdevicer   )rõ   z9class_labels should be provided when num_class_embeds > 0r�   r„   rˆ   Útext_embedsz” has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`Útime_idsz‘ has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`r9   )rá   Úhas_cross_attention)Úhidden_statesÚtembræ   rë   rä   )rú   rû   )ræ   rë   rä   r+   )rö   )r   r   T)rá   Úkeepdim)r!   r"   ).rµ   rv   r(   Úflipr’   Útorõ   Ú	unsqueezeÚ	is_tensorrö   Útyper“   ÚfloatÚfloat32Úfloat64Úint32Úint64ÚtensorrA   ÚshapeÚexpandr•   r–   rœ   ro   rp   rž   rI   ÚgetrŸ   ÚflattenÚreshapeÚconcatr=   r    r¡   r¸   rù   r¥   Úzipr¢   r¤   rx   ÚlogspaceÚmeanr    )#rE   rå   r�   ræ   rç   rè   ré   rê   rë   rì   rä   rí   rî   Úchannel_orderÚ	timestepsÚis_mpsÚis_npurõ   Út_embÚembÚaug_embÚ	class_embr÷   rø   Útime_embedsÚ
add_embedsr!   Údownsample_blockÚres_samplesÚ!controlnet_down_block_res_samplesÚdown_block_res_sampler«   r"   ÚscalesÚscales#                                      r-   rQ   zControlNetModel.forwardY  s¤  € ðr Ÿ™×IÑIˆà˜EÒ!àØ˜eÒ#Ü#Ÿj™j¨À¸sÔC‰OäÐPÐQ^ÐP_Ð`ÓaÐað Ð%Ø .×"3Ñ"3°F·L±LÓ"AÑAÀXÑMˆNØ+×5Ñ5°aÓ8ˆNð ˆ	Ü�‰˜yÔ)ð —]‘]×'Ñ'¨5Ñ0ˆFØ—]‘]×'Ñ'¨5Ñ0ˆFÜ˜(¤EÔ*Ù*0±FœŸšÄÇÁ‘á(.±&œŸš¼u¿{¹{�ÜŸ™ i [¸ÀfÇmÁmÔT‰IÜ�—‘Ó! QÒ&Ø! $™×*Ñ*¨6¯=©=Ó9ˆIð ×$Ñ$ V§\¡\°!¡_Ó5ˆ	à—‘˜yÓ)ˆð
 —‘˜vŸ|™|�Ó,ˆà×!Ñ! %¨Ó7ˆØˆà×ÑÐ+ØÐ#Ü Ð!\Ó]Ð]à�{‰{×+Ñ+¨zÒ9Ø#Ÿ~™~¨lÓ;�à×,Ñ,¨\Ó:×=Ñ=ÀDÇJÁJÐ=ÓOˆIØ˜	‘/ˆCà�;‰;×*Ñ*Ñ6Ø�{‰{×.Ñ.°&Ò8Ø×,Ñ,Ð-BÓC‘à—‘×0Ñ0°KÒ?Ø Ð(9Ñ9Ü$ØŸ>™>Ð*ð  +ð  @óð ð 0×3Ñ3°MÓB�ØÐ%6Ñ6Ü$ØŸ>™>Ð*ð  +|ð  }óð ð -×0Ñ0°Ó<�Ø"×0Ñ0°×1AÑ1AÓ1CÓD�Ø)×1Ñ1°;×3DÑ3DÀQÑ3GÈÐ2LÓM�ä"Ÿ\™\¨;¸Ð*DÈ"ÔM�
Ø'Ÿ]™]¨3¯9©9Ó5�
Ø×,Ñ,¨ZÓ8�à&Ð2ˆc�GŠm¸ˆð —‘˜fÓ%ˆà×8Ñ8¸ÓIˆØ˜/Ñ)ˆð #) ÐØ $× 0Ô 0ÐÜÐ'Ð)>Ô?ÐDT×DhÒDhÙ&6Ø"(ØØ*?Ø#1Ø+Aô'Ñ#�™ñ '7ÀVÐRUÔ&VÑ#�˜à" kÑ1Ñ"ð !1ð �>‰>Ð%Ü�t—~‘~Ð'<Ô=À$Ç.Á.×BdÒBdØŸ™ØØØ*?Ø#1Ø+Að (ó ‘ð Ÿ™¨°Ó4�ð -/Ð)ä7:Ð;QÐSW×SnÑSnÖ7oÑ3Ð!Ð#3Ù$4Ð5JÓ$KÐ!Ø0QÐUjÐTlÑ0lÑ-ð 8pð "CÐà#×8Ñ8¸Ó@Ðñ ˜dŸk™k×@Ò@Ü—^‘^ B¨¬3Ð/EÓ+FÈÑ+JÐSY×S`ÑS`ÔaˆFØÐ0Ñ0ˆFÜJMÐNdÐflÔJmÔ%nÑJm¹¸À f¨u£nÐJmÐ"Ñ%nØ#7¸&À¹*Ñ#DÑ áPfÓ%gÑPfÀf fÐ/AÓ&AÐPfÐ"Ð%gØ#7Ð:LÑ#LÐ à�;‰;×-Ò-áKaó&ÙKaÀ”—
‘
˜6 v°tÖ<ÐKað #ð &ô $)§:¡:Ð.BÈÐX\Ô#]Ð áØ*Ð,@ÐAÐAäØ#9ÐPdô
ð 	
ùó &oùò &hùò&s   Ô VÔVÕV#) r|   r   Tr   )ÚCrossAttnDownBlock2Dr!  r!  ÚDownBlock2Dr   F)i@  i€  é   r#  r   r4   r4   rM   rT   gñhãˆµøä>r#  r4   NNé   NFNNNNFÚdefaultNrð   rR   Fé@   )rð   rR   Tr   )g      ð?NNNNNFT)r#   r$   r%   r&   Ú _supports_gradient_checkpointingr	   rW   r”   r'   Ústrr  r;   Úclassmethodr   r»   rË   rÞ   rÒ   r   r(   r)   Údictr   r    rQ   rX   rY   s   @r-   r[   r[   n   s[  ø„ ñBðH (,Ð$àð Ø%&Ø $Øð-
ð &?Ø38Ø.DØ !Ø"#Ø()ØØ&(ØØ#'Ø>?Ø&*Ø+/Ø45Ø<@Ø&+Ø'+Ø*.Ø.2Ø'+Ø!&Ø'0Ø<@Ø5:ØFWØ',Ø-/ñMCKàðCKð  #ðCKð ð	CKð
 ðCKð    S ™/ðCKð ˜d™
ðCKð # U¨4¡[Ñ0ðCKð " # s (™OðCKð ðCKð   ð!CKð" !&ð#CKð$ ð%CKð& ˜t™ð'CKð( ð)CKð* !ð+CKð, '*¨E°#°s°(©OÑ&;ð-CKð. ˜t™ð/CKð0 " D™jð1CKð2   %¨¨S¨¡/Ñ1ð3CKð4 ! 5¨¨c¨¡?Ñ2°TÑ9ð5CKð6  $ð7CKð8  ™*ð9CKð: ! 4™Zð;CKð< "% t¡ð=CKð>  ™*ð?CKð@ ðACKðB "%ðCCKðD 03°T©zðECKðF 03ðGCKðH .3°3¸°8©_¸tÑ-CðICKðJ !%ðKCKðL (+ôMCKó ðCKðJ ð 6;ØFWØ'+Ø%&ñIà"ðIð 03ðIð .3°3¸°8©_¸tÑ-Cð	Ið
 !%ðIð  #òIó ðIòX+ð ?J¨c°C©i¸$¸s¹)Ñ.Cð ?JÈó ?JñB Ð.Ó/ð %(Ø,0Ø-1Ø.2Ø<@Ø8<Ø Ø ñI
à—‘ðI
ð —,‘, Ñ&¨Ñ,ðI
ð  %Ÿ|™|ð	I
ð
 Ÿ™ðI
ð "ðI
ð —l‘l TÑ)ðI
ð —|‘| dÑ*ðI
ð Ÿ™ tÑ+ðI
ð    U§\¡\Ð 1Ñ2°TÑ9ðI
ð !% S¨# X¡°Ñ 5ðI
ð ðI
ð ðI
ð 
˜E %¨¯©°cÐ(9Ñ":¸E¿L¹LÐ"HÑIÑ	IòI
ó 0ôI
r,   r[   c                 ón   — | j                  «       D ]!  }t        j                  j                  |«       Œ# | S rK   )Ú
parametersr   ÚinitÚzeros_)rÏ   Úps     r-   rC   rC   &  s*   € Ø×ÑÖ ˆÜ
�‰�‰�qÕð !à€Mr,   )1Údataclassesr   Útypingr   r(   r   Útorch.nnr   rL   Úconfiguration_utilsr   r	   Úloadersr
   Úloaders.single_file_modelr   Úutilsr   r   r   Ú	attentionr   Úattention_processorr   r   r   r   Ú
embeddingsr   r   r   r   r   Úmodeling_utilsr   Úunets.unet_2d_blocksr   r   r   Úunets.unet_2d_conditionr   Ú
get_loggerr#   r—   r    rÝ   r/   r[   rC   r+   r,   r-   Ú<module>r>     s«   ðõ "Ý ã Ý Ý $ç BÝ 'Ý ?ß :Ñ :Ý &÷ó ÷ vÕ uÝ '÷ñ õ
 ;ð 
ˆ×	Ñ	˜HÓ	%€ð ô'�zó 'ó ð'ô&* b§i¡iô *ôZu

�j .°+Ð?UÐWgô u

ópr,   