
    bi                        d dl mZmZmZmZmZmZ d dl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mZmZ dd
lmZmZmZmZ ddlmZ ddlmZmZ ddl m!Z! ddl"m#Z#m$Z$m%Z%  ejL                  e'      Z( G d dejR                        Z* G d dejR                        Z+ G d dejR                        Z, G d dee
e      Z-y)    )AnyDictListOptionalTupleUnionN)nn   )ConfigMixinregister_to_config)FromOriginalModelMixin)logging   )ADDED_KV_ATTENTION_PROCESSORSCROSS_ATTENTION_PROCESSORSAttentionProcessorAttnAddedKVProcessorAttnProcessor)TextImageTimeEmbeddingTextTimeEmbeddingTimestepEmbedding	Timesteps)
ModelMixin)UNetMidBlock2DCrossAttnget_down_block)UNet2DConditionModel   )ControlNetConditioningEmbeddingControlNetOutputzero_modulec                   H    e Zd ZdZdej
                  dej
                  fdZy)	QuickGELUzr
    Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs
    inputreturnc                 8    |t        j                  d|z        z  S )NgZd;?)torchsigmoid)selfr#   s     h/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/controlnets/controlnet_union.pyforwardzQuickGELU.forward/   s    u}}UU]333    N)__name__
__module____qualname____doc__r&   Tensorr*    r+   r)   r"   r"   *   s"    4U\\ 4ell 4r+   r"   c                   D     e Zd Zdef fdZdej                  fdZ xZS )ResidualAttentionMlpd_modelc                     t         |           t        j                  ||dz        | _        t               | _        t        j                  |dz  |      | _        y )N   )super__init__r	   Linearc_fcr"   geluc_proj)r(   r4   	__class__s     r)   r8   zResidualAttentionMlp.__init__4   sC    IIgw{3	K	ii!W5r+   xc                 l    | j                  |      }| j                  |      }| j                  |      }|S N)r:   r;   r<   r(   r>   s     r)   r*   zResidualAttentionMlp.forward:   s.    IIaLIIaLKKNr+   )	r,   r-   r.   intr8   r&   r0   r*   __classcell__r=   s   @r)   r3   r3   3   s    6 6 r+   r3   c                        e Zd Zddededej
                  f fdZdej
                  fdZdej
                  fdZ xZ	S )	ResidualAttentionBlockr4   n_head	attn_maskc                     t         |           t        j                  ||      | _        t        j
                  |      | _        t        |      | _        t        j
                  |      | _	        || _
        y r@   )r7   r8   r	   MultiheadAttentionattn	LayerNormln_1r3   mlpln_2rH   )r(   r4   rG   rH   r=   s       r)   r8   zResidualAttentionBlock.__init__B   sU    ))'6:	LL)	'0LL)	"r+   r>   c                     | j                   1| j                   j                  |j                  |j                        nd | _         | j	                  |||d| j                         d   S )NdtypedeviceF)need_weightsrH   r   )rH   torR   rS   rK   rA   s     r)   	attentionz ResidualAttentionBlock.attentionJ   sT    NRnnNh***JnryyAquyOPQRRr+   c                     || j                  | j                  |            z   }|| j                  | j                  |            z   }|S r@   )rV   rM   rN   rO   rA   s     r)   r*   zResidualAttentionBlock.forwardN   s=    tyy|,,1&&r+   r@   )
r,   r-   r.   rB   r&   r0   r8   rV   r*   rC   rD   s   @r)   rF   rF   A   sC    # #S #U\\ #S5<< S r+   rF   c            J           e Zd ZdZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dDdededededee	d	f   d
e
eee   f   deed	f   dededede	dee   dedede
eeed	f   f   dee   dee	   de
eeed	f   f   dee
eeed	f   f      dedee	   dee	   dee   dee   dede	dee   d e	d!eeed	f      d"ed#ed$ed%ed&ed'ed(efH fd)       Ze	 	 	 dEd*ed e	d!eeed	f      d+efd,       Zed-ee	ef   fd.       Zd/e
eee	ef   f   fd0Zd1 Zd2e
e	eee   f   d-dfd3Z	 	 	 	 	 	 	 	 	 dFd4ej4                  d5e
ej4                  eef   d6ej4                  d7eej4                     d8ej4                  d9ee   d:e
eee   f   d;eej4                     d<eej4                     d=eej4                     d>eee	ej4                  f      d?eee	ef      d@edAedBed-e
eeeej4                  d	f   ej4                  f   f   f dCZ xZS )GControlNetUnionModela  
    A ControlNetUnion 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 (`Union[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 (`Union[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 `(48, 96, 192, 384)`):
            The tuple of output channel for each block in the `conditioning_embedding` layer.
        global_pool_conditions (`bool`, defaults to `False`):
    TNin_channelsconditioning_channelsflip_sin_to_cos
freq_shiftdown_block_types.only_cross_attentionblock_out_channels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_headsnum_control_typenum_trans_channelnum_trans_headnum_trans_layernum_proj_channelc%                 
   t         4|           |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        |(|'|      | _        |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t)        |||'      | _        n:|dk(  r$t        |||      | _        t        ||'      | _        n|t        d| d      t-        |d	   ||      | _        |!dz  }*t        j0                  |*t3        j4                  | |!      z        | _        t        j8                  t;        |#      D +cg c]  }+t=        |!|"       c}+      | _        tA        t        jB                  |!|$            | _"        t        |||      | _#        t        || z  |'      | _$        t        j8                  g       | _%        t        j8                  g       | _&        t	        |t
              r|gt        |      z  }t	        |t              r|ft        |      z  }t	        |t              r|ft        |      z  }|d	   },t        j                  |,|,d      }-tA        |-      }-| jL                  jO                  |-       tQ        |      D ]  \  }.}/|,}0||.   },|.t        |      dz
  k(  }1tS        |/fi d|d||.   d|0d |,d!|'d"|1 d#|d$|d%|d&|d'||.   d(||.   ||.   n|,d)|	d*|d+||.   d,|d-|}2| jJ                  jO                  |2       t;        |      D ]@  }+t        j                  |,|,d      }-tA        |-      }-| jL                  jO                  |-       B |1rt        j                  |,|,d      }-tA        |-      }-| jL                  jO                  |-        |d.   }3t        j                  |3|3d      }-tA        |-      }-|-| _*        tW        |d.   |3|'|||
|||d.   |||/      | _,        y c c}+w )0NzbMust 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
   r   r   r   )kernel_sizepaddingr6   )rd   zencoder_hid_dim_type: z must be None.timestepidentity
projectionzX`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be settext)	num_heads
text_image)text_embed_dimimage_embed_dimtime_embed_dim	text_timezaddition_embed_type: z& must be None, 'text' or 'text_image'.)conditioning_embedding_channelsr`   r[   g      ?)r   
num_layersrh   rZ   out_channelstemb_channelsadd_downsample
resnet_epsresnet_act_fnresnet_groupsrg   rl   rk   rb   rm   r_   rr   rs   )rh   rZ   r   r   r   output_scale_factorrs   rg   rl   r   rm   rr   )-r7   r8   len
ValueError
isinstanceboolrB   r	   Conv2dconv_inr   	time_projr   time_embeddingencoder_hid_proj	Embeddingclass_embeddingIdentityr   add_embeddingr   add_time_projr   controlnet_cond_embedding	Parameterr&   randntask_embedding
ModuleListrangerF   transformer_layesr    r9   spatial_ch_projscontrol_type_projcontrol_add_embeddingdown_blockscontrolnet_down_blocksappend	enumerater   controlnet_mid_blockr   	mid_block)5r(   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   conv_in_kernelconv_in_paddingr   timestep_input_dimtext_time_embedding_from_dimtask_scale_factor_output_channelcontrolnet_blockidown_block_typeinput_channelis_final_block
down_blockmid_block_channelr=   s5                                                       r)   r8   zControlNetUnionModel.__init__   s   Z 	 2G5G !"c*:&;;t  vH  uI  I_  `p  _q  qr  s  .5#>R:SWZ[kWl:lx  zN  yO  Oe  fv  ew  wx  y  -s3<O8PTWXhTi8iv  xK  wL  Lb  cs  bt  tu  v  2C8,H+ICP`La+a( )A-!3yy+A.NTc

 ,A.2"#5a#8/:V/2/
  +56J5K>Z[[$(D! #(8(D#%<<0@.#QD +#45G#XD +#%;;~~#ND -4< n  $55Z\j#kD #'D &(*/>,/B,!2,nHe"D !L0 "82DWhv"D !K/!*+BOU_!`D!23XZh!iD ,45H4IIopqq *I,>q,AB"7*
& .s2 ll+<u{{K[]n?o+op!#PUVePfg1#$5~Fg"
 !,BII6GIY,Z [!*+BOU_!`%67NQa7acq%r"==,&(mmB&7#*D1$8#9C@P<Q#Q (#."4!6=M9N!N)3/#6"83?O;P"P ,A.99^^QRS&'78##**+;<"+,<"= #	EA*M/2N#&8"9A"==N'+ .J!-L *	
 , - $21 $ % . %8 %8$: =Oq<Q<]#5a#8cq $6 '<  &:!%<!" "2#$ )@%J( ##J/+, E#%99^^YZ#[ #./?#@ ++223CDE
 "#%99^^YZ#[ #./?#@ ++223CDG#	EL /r299%68IWXY&'78$4!0)Eb)I)(  6$; 3 3B 7)"7-
K hs   &U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|d|}
|rB|
j6                  j9                  |j6                  j;                                |
j<                  j9                  |j<                  j;                                |
j>                  j9                  |j>                  j;                                |
j@                  r3|
j@                  j9                  |j@                  j;                                |
jB                  j9                  |jB                  j;                         d        |
jD                  j9                  |jD                  j;                         d        |
S )"a3  
        Instantiate a [`ControlNetUnionModel`] from [`UNet2DConditionModel`].

        Parameters:
            unet (`UNet2DConditionModel`):
                The UNet model weights to copy to the [`ControlNetUnionModel`]. All configuration options are also
                copied where applicable.
        rh   r   ri   Nrj   ro   rp   rZ   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rk   rl   rm   rn   rq   rr   rs   rt   ru   rv   F)strictr1   )#configrh   ri   rj   ro   rp   rZ   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rk   rl   rm   rn   rq   rr   rs   rt   r   load_state_dict
state_dictr   r   r   r   r   )clsr   ru   rv   r   rh   ri   rj   ro   rp   
controlnets              r)   	from_unetzControlNetUnionModel.from_unet  s   " 9WZ^ZeZe8eDKK44kl 	% :Kdkk9Y$++55_cCY]a]h]hCht{{??nrAVZ^ZeZeAedkk==ko3LPTP[P[3[DKK//ae 	   
+
!5
 !4
 %<	

 *F
 //
 !KK77
 {{--
 "[[99
 "&!A!A
  ${{==
 "[[99
  ${{==
 $(;;#E#E
 ;;%%
  !KK77!
" [[))#
$ !% ? ?%
&  ${{=='
( !% ? ?)
* #'++"C"C+
, "[[99-
. "[[99/
0 "[[991
2 %)KK$G$G3
4 37++2c2c5
6 3X7
8 1T9

> "..t||/F/F/HI  001J1J1LM%%55d6I6I6T6T6VW))**::4;O;O;Z;Z;\]""2243C3C3N3N3PY^2_  001J1J1LUZ0[r+   r$   c                     i }dt         dt        j                  j                  dt        t         t
        f   ffd| j                         D ]  \  }} |||        |S )z
        Returns:
            `dict` of attention processors: A dictionary containing all attention processors used in the model with
            indexed by its weight name.
        namemodule
processorsc                     t        |d      r|j                         ||  d<   |j                         D ]  \  }} |  d| ||        |S )Nget_processor
.processorr   )hasattrr   named_children)r   r   r   sub_namechildfn_recursive_add_processorss        r)   r   zIControlNetUnionModel.attn_processors.<locals>.fn_recursive_add_processors  sd    v/282F2F2H
dV:./#)#8#8#: U%+tfAhZ,@%TU r+   )strr&   r	   Moduler   r   r   )r(   r   r   r   r   s       @r)   attn_processorsz$ControlNetUnionModel.attn_processors  sm     
	c 	588?? 	X\]`bt]tXu 	 !//1 	BLD&'fjA	B r+   	processorc           	      T   t        | j                  j                               }t        |t              r,t        |      |k7  rt        dt        |       d| d| d      dt        dt        j                  j                  ffd| j                         D ]  \  }} |||        y)	a4  
        Sets the attention processor to use to compute attention.

        Parameters:
            processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
                The instantiated processor class or a dictionary of processor classes that will be set as the processor
                for **all** `Attention` 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.

        z>A dict of processors was passed, but the number of processors z0 does not match the number of attention layers: z. Please make sure to pass z processor classes.r   r   c                     t        |d      rEt        |t              s|j                  |       n#|j                  |j	                  |  d             |j                         D ]  \  }} |  d| ||        y )Nset_processorr   r   )r   r   dictr   popr   )r   r   r   r   r   fn_recursive_attn_processors        r)   r   zLControlNetUnionModel.set_attn_processor.<locals>.fn_recursive_attn_processor  sx    v/!)T2((3(($z7J)KL#)#8#8#: T%+tfAhZ,@%STr+   N)r   r   keysr   r   r   r   r&   r	   r   r   )r(   r   countr   r   r   s        @r)   set_attn_processorz'ControlNetUnionModel.set_attn_processor  s     D((--/0i&3y>U+BPQTU^Q_P` a005w6QRWQXXkm 
	Tc 	T588?? 	T !//1 	ALD&'fi@	A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r@   )r=   r   .0procs     r)   	<genexpr>zBControlNetUnionModel.set_default_attn_processor.<locals>.<genexpr>  s     i4t~~!>>i   c              3   @   K   | ]  }|j                   t        v   y wr@   )r=   r   r   s     r)   r   zBControlNetUnionModel.set_default_attn_processor.<locals>.<genexpr>  s     h$#==hr   zOCannot call `set_default_attn_processor` when attention processors are of type N)	allr   valuesr   r   r   nextiterr   )r(   r   s     r)   set_default_attn_processorz/ControlNetUnionModel.set_default_attn_processor  s     i4K_K_KfKfKhii,.Ih$J^J^JeJeJghh%Iabfgklp  mA  mA  mH  mH  mJ  hK  cL  bM  N  		*r+   
slice_sizec                    	
 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`.
        r   c                     t        | d      rj                  | j                         | j                         D ]
  } |        y Nset_attention_slice)r   r   sliceable_head_dimchildren)r   r   $fn_recursive_retrieve_sliceable_dimssliceable_head_dimss     r)   r   zVControlNetUnionModel.set_attention_slice.<locals>.fn_recursive_retrieve_sliceable_dims'  s@    v45#**6+D+DE* <4U;<r+   autor   maxr   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   r   r   )r   r   r    fn_recursive_set_attention_slices      r)   r   zRControlNetUnionModel.set_attention_slice.<locals>.fn_recursive_set_attention_sliceM  sE    v45**:>>+;<* D0
CDr+   )r&   r	   r   r   r   r   listr   r   r   r   rB   reversed)r(   r   r   num_sliceable_layersdimr   sizereversed_slice_sizer   r   r   s           @@@r)   r   z(ControlNetUnionModel.set_attention_slice  s    !	< 	< mmo 	9F08	9  ##67 /BBs#(BJB5 -3J@J:W[@\)ZL8bl
z?c"566$S_$5VDKK=cReNfMg hQQTUhQiPjjkm 
 s:' 	VAa=D%a(CD3J 5.McURS!TUU		V	DUXX__ 	DRVWZR[ 	D #8J#78mmo 	JF,V5HI	J= Cs   E;sampler   encoder_hidden_statescontrolnet_condcontrol_typecontrol_type_idxconditioning_scaleclass_labelstimestep_condattention_maskadded_cond_kwargscross_attention_kwargs
from_multi
guess_modereturn_dictc                 x   t        |t              r|gt        |      z  }| j                  j                  }|dk7  r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                  j.                  dk(  r| j)                  |      }| j-                  |      j                  | j                  
      }||z   }| j                  j0                  "| j                  j0                  dk(  r| j3                  |      }n| j                  j0                  dk(  rd|vrt        | j4                   d      |j7                  d      }d|vrt        | j4                   d      |j7                  d      }| j9                  |j;                               }|j=                  |j$                  d	   df      }t        j>                  ||gd      }|j                  |j                        }| j3                  |      }| jA                  |j;                               }|j=                  |j$                  d	   df      }|j                  |j                        }| jC                  |      }||z   }|||z   n|}| jE                  |      }g }g } tG        |||      D ]  \  }!}"}#| jI                  |!      }$t        jJ                  |$d      }%|%| jL                  |"   z   }%|st        |      dk(  r2|jO                  |%j                  d             | jO                  |$       |jO                  |%j                  d      |#z         | jO                  |$|#z          |}$t        jJ                  |$d      }%|jO                  |%j                  d             | jO                  |$       t        jP                  |d      }&| jR                  D ]
  }' |'|&      }& |dz  }(tG        tU        | dd       |      D ]d  \  \  })}$}#| jW                  |&dd|)f         }*|*j                  d      j                  d      }*|st        |      dk(  r	|(|$|*z   z  }(Z|(|$|*|#z  z   z  }(f ||(z   }|f}+| jX                  D ]=  },t[        |,d      r|,j\                  r |,||||
|      \  }}-n |,||      \  }}-|+|-z  }+? | j^                  | j_                  ||||
|      }d}.tG        |+| j`                        D ]  \  }/}0 |0|/      }/|.|/fz   }. |.}+| jc                  |      }1|r| j                  jd                  sqt        jf                  dd	t        |+      dz   |j                        }2|st        |      dk(  r|2|d	   z  }2tG        |+|2      D #cg c]
  \  }}#||#z   }+}}#|1|2d   z  }1n-|st        |      dk(  r|+D cg c]
  }||d	   z   }+}|1|d	   z  }1| j                  jd                  r=|+D cg c]  }t        jJ                  |dd       }+}t        jJ                  |1dd      }1|s|+|1fS ti        |+|1      S c c}#}w c c}w c c}w ) am  
        The [`ControlNetUnionModel`] forward method.

        Args:
            sample (`torch.Tensor`):
                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 (`List[torch.Tensor]`):
                The conditional input tensors.
            control_type (`torch.Tensor`):
                A tensor of shape `(batch, num_control_type)` with values `0` or `1` depending on whether the control
                type is used.
            control_type_idx (`List[int]`):
                The indices of `control_type`.
            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`.
            from_multi (`bool`, defaults to `False`):
                Use standard scaling when called from `MultiControlNetUnionModel`.
            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.controlnet.ControlNetOutput`] instead of a plain tuple.

        Returns:
            [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
                If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
                returned where the first element is the sample tensor.
        rgbz1unknown `controlnet_conditioning_channel_order`: Nr   g     mpsnpurQ   r   )rR   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`r   )r  )r   r
   g        has_cross_attention)hidden_statestembr  r  r  )r  r  )r  r  r  r1   )rS   T)r  keepdim)down_block_res_samplesmid_block_res_sample)5r   floatr   r   ru   r   rU   rR   	unsqueezer&   	is_tensorrS   typefloat32float64int32int64tensorshapeexpandr   r   r   rn   ro   r   r=   getr   flattenreshapeconcatr   r   r   zipr   meanr   r   catr   r   r   r   r   r  r   r   r   rw   logspacer   )3r(   r  r   r  r  r  r	  r
  r  r  r  r  r  r  r  r  channel_order	timestepsis_mpsis_npurR   t_embembaug_emb	class_embr  r  time_embeds
add_embedscontrol_embedscontrol_embinputscondition_listcondcontrol_idxscale	conditionfeat_seqr>   layercontrolnet_cond_fuseridxalphar  downsample_blockres_samples!controlnet_down_block_res_samplesdown_block_res_sampler   r  scaless3                                                      r)   r*   zControlNetUnionModel.forwardX  s   @ (%0"4!5O8L!L IIE!PQ^P_`aa %."3"3FLL"AAXMN+55a8N 	y) ]]''50F]]''50F(E**0F(.&u{{i[fmmTI!Q&!$**6==9I $$V\\!_5	y)
 v||,!!%7+# !\]]{{++z9#~~l;,,\:==DJJ=OI	/C;;**6{{..&8,,-BC00K? (99$>>*  +  @  033MB%66$>>*  +|  }  -00<"001A1A1CD)11;3D3DQ3G2LM"\\;*D"M
']]3995
,,Z8//0D0D0FG'//Q0DE'**399500@K&2cGm f%(+O=MOa(b 		9$D+u66t<Izz)8H$"5"5k"BBHS!12a7h0034%%i0h003e;<%%i%&78		9 	::iV4h((+,i(IIf!$++ 	EaA	 !''*9^CR5H+IK]'^ 	C#S)e))!AsF)4EOOB'11"5ES!12a7%U)::%%UU])BB%	C // #) $ 0 0 	2')>?DTDhDh&6"(*?#1+A'# '7VRU&V#"k1"	2 >>%^^&;-'= $ F -/)7:;QSWSnSn7o 	m3!#3$45J$K!0QUjTl0l-	m "C#88@ dkk@@^^B3/E+F+JSYS`S`aFS!12a7"4Q"77JMNdflJm%nfun%n"%n#7&*#D 3/0A5Si%jf/A!/D&D%j"%j#7:LQ:O#O ;;--Ka&AG

6vt<&" & $)::.BX\#] *,@AA#9Pd
 	
 &o &k&s   >^,-^2 ^7)$r6   r
   Tr   )CrossAttnDownBlock2DrN  rN  DownBlock2DF)@  i     rQ  r   r   r   silu    gh㈵>rQ  r   NN   NFNNNNFdefaultNr  )0   `      i  F@      rP  rT  r   rP  )r  )   rS  rW     T)	g      ?NNNNNFFT)r,   r-   r.   r/    _supports_gradient_checkpointingr   rB   r   r   r   r   r  r   r8   classmethodr   r   propertyr   r   r   r   r   r   r   r&   r0   r   r   r*   rC   rD   s   @r)   rY   rY   T   s   ?B (,$ %& $-
 :?.D !"#())+#'DE)-.2:;EI&+*.-115*.!&'0?C5:I[',-/ !!$  #Ui
i
  #i
 	i

 i
  S/i
 $D%+$56i
 "#s(Oi
 i
  i
  !&!i
" #i
$ "#%i
& 'i
( !)i
* ',CsCx,@&A+i
, "#-i
. 'sm/i
0 "#uS#X"671i
2 &eCsCx,@&AB3i
4  $5i
6 #3-7i
8 &c]9i
: "*#;i
< #3-=i
> ?i
@ "%Ai
B 08}Ci
D 03Ei
F .6eCHo-FGi
H !%Ii
J (+Ki
L Mi
N Oi
P Qi
R Si
T Ui
 i
V  6;IZ'+C"C 03C .6eCHo-F	C
 !%C CJ c+=&=!>  0 AE2Dd3PbKbFc2c,d  AF+ ?JeCd3i4G.H ?JT ?JR 9</30415?C;?   !q
q
 eS01q
  %||	q

 ell+q
 llq
 s)q
 "%e"45q
 u||,q
  -q
 !.q
 $Dell):$;<q
 !)c3h 8q
 q
 q
  !q
" 
uU\\3->'?'M!NN	O#q
r+   rY   ).typingr   r   r   r   r   r   r&   r	   configuration_utilsr   r   loaders.single_file_modelr   utilsr   attention_processorr   r   r   r   r   
embeddingsr   r   r   r   modeling_utilsr   unets.unet_2d_blocksr   r   unets.unet_2d_conditionr   r   r   r   r    
get_loggerr,   loggerr   r"   r3   rF   rY   r1   r+   r)   <module>rk     s    ; :   B ?   a ` ' ; V V 
		H	%4		 4299 RYY &u
:{4J u
r+   