
    biՕ                        d dl mZ 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 ddlmZmZ ddlmZ dd	lmZmZ d
dlmZmZmZmZmZ d
dlmZmZ d
dlm Z  d
dl!m"Z" d
dl#m$Z$ d
dl%m&Z&m'Z'  ejP                  e)      Z*e G d de             Z+ G d de
jX                        Z- G d de ee      Z.de
jX                  de
jX                  fdZ/y)    )	dataclass)AnyDictListOptionalTupleUnionN)nn)
functional   )ConfigMixinregister_to_config)FromOriginalModelMixin)
BaseOutputlogging   )ADDED_KV_ATTENTION_PROCESSORSCROSS_ATTENTION_PROCESSORSAttentionProcessorAttnAddedKVProcessorAttnProcessor)TimestepEmbedding	Timesteps)
ModelMixin)UNetMidBlock2DCrossAttn)UNet2DConditionModel)CrossAttnDownBlockMotionDownBlockMotionc                   T    e Zd ZU dZeej                     ed<   ej                  ed<   y)SparseControlNetOutputa  
    The output of [`SparseControlNetModel`].

    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__r   torchTensor__annotations__     m/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/controlnets/controlnet_sparsectrl.pyr    r    *   s"     "%,,//,,&r+   r    c            	       t     e Zd Z	 	 d	dededeedf   f fdZdej                  dej                  fdZ xZ	S )
%SparseControlNetConditioningEmbedding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   )r5   r6   stride)super__init__r
   Conv2dconv_in
ModuleListblocksrangelenappendzero_moduleconv_out)selfr/   r0   r1   i
channel_inchannel_out	__class__s          r,   r:   z.SparseControlNetConditioningEmbedding.__init__?   s     	yy!68J18M[\fghmmB's-.23 	gA+A.J,QU3KKKryyZQXYZ[KKryy[aYZcdef		g $II(,.M[\fgh
r+   conditioningreturnc                     | j                  |      }t        j                  |      }| j                  D ]  } ||      }t        j                  |      }! | j	                  |      }|S N)r<   Fsilur>   rC   )rD   rI   	embeddingblocks       r,   forwardz-SparseControlNetConditioningEmbedding.forwardT   s_    LL.	FF9%	[[ 	*Ei(Iy)I	* MM),	r+   )r          `      )
r#   r$   r%   intr   r:   r'   r(   rQ   __classcell__rH   s   @r,   r.   r.   >   sO     &'.?	
),
  #
 "#s(O	
*	ELL 	U\\ 	r+   r.   c            <       |    e Zd ZdZdZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9d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
eee   f      de
eeed	f   f   de
eeed	f   f   dee
eeed	f   f      dedede	deeed	f      dede	deded ed!ef: fd"       Ze	 	 	 	 d:d#ede	deeed	f      d$eded%d fd&       Zed%ee	ef   fd'       Zd(e
eee	ef   f   fd)Zd* Zd+e
e	eee   f   d%dfd,Z	 	 	 	 	 	 	 d;d-ej4                  d.e
ej4                  eef   d/ej4                  d0ej4                  d1ed2eej4                     d3eej4                     d4eee	ef      d5eej4                     d6ed7ed%e
eeeej4                  d	f   ej4                  f   f   fd8Z xZS )<SparseControlNetModela3  
    A SparseControlNet model as described in [SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion
    Models](https://huggingface.co/papers/2311.16933).

    Args:
        in_channels (`int`, defaults to 4):
            The number of channels in the input sample.
        conditioning_channels (`int`, defaults to 4):
            The number of input channels in the controlnet conditional embedding module. If
            `concat_condition_embedding` is True, the value provided here is incremented by 1.
        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`].
        transformer_layers_per_mid_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
            The number of transformer layers to use in each layer in the middle block.
        attention_head_dim (`int` or `Tuple[int]`, defaults to 8):
            The dimension of the attention heads.
        num_attention_heads (`int` or `Tuple[int]`, *optional*):
            The number of heads to use for multi-head attention.
        use_linear_projection (`bool`, defaults to `False`):
        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`.
        conditioning_embedding_out_channels (`Tuple[int]`, 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
        controlnet_conditioning_channel_order (`str`, defaults to `rgb`):
        motion_max_seq_length (`int`, defaults to `32`):
            The maximum sequence length to use in the motion module.
        motion_num_attention_heads (`int` or `Tuple[int]`, defaults to `8`):
            The number of heads to use in each attention layer of the motion module.
        concat_conditioning_mask (`bool`, defaults to `True`):
        use_simplified_condition_embedding (`bool`, defaults to `True`):
    TNin_channelsr0   flip_sin_to_cos
freq_shiftdown_block_types.only_cross_attentionr1   layers_per_blockdownsample_paddingmid_block_scale_factoract_fnnorm_num_groupsnorm_epscross_attention_dimtransformer_layers_per_block transformer_layers_per_mid_block%temporal_transformer_layers_per_blockattention_head_dimnum_attention_headsuse_linear_projectionupcast_attentionresnet_time_scale_shift#conditioning_embedding_out_channelsglobal_pool_conditions%controlnet_conditioning_channel_ordermotion_max_seq_lengthmotion_num_attention_headsconcat_conditioning_mask"use_simplified_condition_embeddingc                 t	   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  }t        |t              r|gt        |      z  }d}|dz
  dz  }t        j                  ||d	   ||
      | _
        |r|dz   }|| _        |r+t        t        j                  ||d	   dd
            | _        nt        |d	   ||      | _        |d	   dz  } t        |d	   ||      | _        |d	   }!t#        |!| |      | _        t        j&                  g       | _        t        j&                  g       | _        t        |t              r|ft        |      z  }t        |t              r|gt        |      z  }t        |t              r|ft        |      z  }t        |t              r|ft        |      z  }t        |t              r|ft        |      z  }|d	   }"t        j                  |"|"d      }#t        |#      }#| j*                  j-                  |#       t/        |      D ]_  \  }$}%|"}&||$   }"|$t        |      dz
  k(  }'|%dk(  r_t1        d/i d|&d|"d| dd	d|d||$   d|d|d|d|ddd||$   d||$   d|' dd d!|d"||$   d#|d$||$   d%|d&||$   d'd }(n2|%d(k(  r"t3        |&|"| d	|||||d|' ||$   |||$   d )      }(nt	        d*      | j(                  j-                  |(       t5        |      D ]@  })t        j                  |"|"d      }#t        |#      }#| j*                  j-                  |#       B |'r"t        j                  |"|"d      }#t        |#      }#| j*                  j-                  |#       b |d+   }*t        j                  |*|*d      }#t        |#      }#|#| _        |t        |d+   t              r|d+   nd}t9        d/i d|*d| dd	ddd|d|d|d|d|ddd|d+   d,|
d|d+   dd d!|d#|d-d.| _        y )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   r3   r   r   r4   )r/   r1   r0      )rd   )r5   r   r\   out_channelstemb_channelsdropout
num_layersrh   
resnet_epsro   resnet_act_fnresnet_groupsresnet_pre_normTrl   rg   add_downsampledual_cross_attentionFrm   r`   rn   temporal_num_attention_headstemporal_max_seq_lengthrj   temporal_double_self_attentionr   )r\   rz   r{   r|   r}   r~   ro   r   r   r   r   r   r   rj   r   z`Invalid `block_type` encountered. Must be one of `CrossAttnDownBlockMotion` or `DownBlockMotion`r8   output_scale_factorattention_typedefaultr*   )r9   r:   rv   r@   
ValueError
isinstanceboolrW   r
   r;   r<   ru   rB   controlnet_cond_embeddingr.   r   	time_projr   time_embeddingr=   down_blockscontrolnet_down_blocksrA   	enumerater   r   r?   controlnet_mid_blockr   	mid_block),rD   r\   r0   r]   r^   r_   r`   r1   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   conv_in_kernelconv_in_paddingtime_embed_dimtimestep_input_dimoutput_channelcontrolnet_blockrE   down_block_typeinput_channelis_final_block
down_block_mid_block_channelsrH   s,                                              r,   r:   zSparseControlNetModel.__init__   s   L 	2T/ 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(;SA5Z4[^abr^s4s1 )A-!3yy+A.NTc
 $$9A$=!(@% .-8		/1CA1FTU_`a.D* .S0B10E#F&;.D* ,A.2"#5a#8/:V/2/
 ==,&(mmB&7#)3/#6"83?O;P"P*D1$8#9C@P<Q#Q (#."4!6=M9N!N)3/#6"83?O;P"P0#6*D)FM]I^)^& ,A.99^^QRS&'78##**+;<"+,<"= ?	EA*M/2N#&8"9A"==N"<<5  -!/ #1 	
  0 2Na1P  ( -D #) #2 %) )<A(> )<A(> (6#5 */  +@!" *>a)@#$ &6%& 2LA1N'( -B)* ;``a:b+, 49-
0 !$55, -!/"0/',C"("1$('5#51KA1N,A:_`a:b38
$ !v  ##J/+, E#%99^^YZ#[ #./?#@ ++223CDE
 "#%99^^YZ#[ #./?#@ ++223CD?	ED 0399%79KYZ[&'78$4!+34>?[\^?_ad4e,R0kl - 1 
*
(
 
 	

 *J
  
 %<
 !
 *
 !
 !4B 7
 !7
 !4B 7
 "'
 #8
  .!
" %#
r+   unetload_weights_from_unetrJ   c                 p   d|j                   v r|j                   j                  nd}|j                   j                  }t        t	        |            D ]&  }d||   v rd||<   d||   v rd||<   t        d        | di d|j                   j                  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|d|j                   j$                  d|j                   j&                  d|j                   j(                  d|j                   j*                  d|j                   j,                  d|d|}	|r	|	j.                  j1                  |j.                  j3                         d       |	j4                  j1                  |j4                  j3                         d       |	j6                  j1                  |j6                  j3                         d       |	j8                  j1                  |j8                  j3                         d       |	j:                  j1                  |j:                  j3                         d       |	S ) a5  
        Instantiate a [`SparseControlNetModel`] from [`UNet2DConditionModel`].

        Parameters:
            unet (`UNet2DConditionModel`):
                The UNet model weights to copy to the [`SparseControlNetModel`]. All configuration options are also
                copied where applicable.
        rh   r3   	CrossAttnr   Downr   zIInvalid `block_type` encountered. Must be a cross-attention or down blockr\   r0   r]   r^   r_   r`   r1   ra   rb   rc   rd   re   rf   rg   rk   rl   rm   rn   ro   rp   rr   F)strictr*   )configrh   r_   r?   r@   r   r\   r]   r^   r`   r1   ra   rb   rc   rd   re   rf   rg   rk   rl   rm   rn   ro   r<   load_state_dict
state_dictr   r   r   r   )
clsr   rr   rp   r   r0   rh   r_   rE   
controlnets
             r,   	from_unetzSparseControlNetModel.from_unet  s   $ 9WZ^ZeZe8eDKK44kl 	%  ;;77s+,- 	nA.q11&@ #+A..&7 # !lmm	n  
//
"7
 !KK77
 {{--	

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

2 "..t||/F/F/HQV.W  001J1J1LUZ0[%%55d6I6I6T6T6V_d5e""2243C3C3N3N3PY^2_  001J1J1LUZ0[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
.processorrx   )hasattrr   named_children)r   r   r   sub_namechildfn_recursive_add_processorss        r,   r   zJSparseControlNetModel.attn_processors.<locals>.fn_recursive_add_processors  sd    v/282F2F2H
dV:./#)#8#8#: U%+tfAhZ,@%TU r+   )strr'   r
   Moduler   r   r   )rD   r   r   r   r   s       @r,   attn_processorsz%SparseControlNetModel.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   rx   )r   r   dictr   popr   )r   r   r   r   r   fn_recursive_attn_processors        r,   r   zMSparseControlNetModel.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   )rD   r   countr   r   r   s        @r,   set_attn_processorz(SparseControlNetModel.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rL   )rH   r   .0procs     r,   	<genexpr>zCSparseControlNetModel.set_default_attn_processor.<locals>.<genexpr>  s     i4t~~!>>i   c              3   @   K   | ]  }|j                   t        v   y wrL   )rH   r   r   s     r,   r   zCSparseControlNetModel.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   )rD   r   s     r,   set_default_attn_processorz0SparseControlNetModel.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   rA   sliceable_head_dimchildren)r   r   $fn_recursive_retrieve_sliceable_dimssliceable_head_dimss     r,   r   zWSparseControlNetModel.set_attention_slice.<locals>.fn_recursive_retrieve_sliceable_dims   s@    v45#**6+D+DE* <4U;<r+   autor   maxr3   zYou have provided z, but z has zH different attention layers. Make sure to match `len(slice_size)` to be rx   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   zSSparseControlNetModel.set_attention_slice.<locals>.fn_recursive_set_attention_sliceF  sE    v45**:>>+;<* D0
CDr+   )r'   r
   r   r   r@   r   listr   r   r?   r   rW   reversed)rD   r   r   num_sliceable_layersdimrE   sizereversed_slice_sizer   r   r   s           @@@r,   r   z)SparseControlNetModel.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;sampletimestepencoder_hidden_statescontrolnet_condconditioning_scaletimestep_condattention_maskcross_attention_kwargsconditioning_mask
guess_modereturn_dictc           	      
   |j                   \  }}}}}t        j                  |      }| 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/                  ||      }|j1                  |d|j                   d   |z        }|j                   \  }}}}}|j3                  ddddd      j5                  ||z  |||      }| j7                  |      }|j                   \  }}}}|dddf   j5                  |||||      }| j8                  rt        j:                  ||	gd      }|j                   \  }}}}}|j3                  ddddd      j5                  ||z  |||      }| j=                  |      }|j                   \  }}}}|dddf   j5                  |||||      }||z   }|j                   \  }}}}}|j5                  ||z  |||      }|f}| j>                  D ]?  }tA        |d      r|jB                  r |||||||      \  }} n ||||      \  }} || z  }A | jD                  UtA        | jD                  d      r-| jD                  jB                  r| jE                  |||||      }n| jE                  ||      }d}!tG        || jH                        D ]  \  }"}# |#|"      }"|!|"fz   }! |!}| jK                  |      }$|
rt| j                  jL                  s^t        jN                  ddt)        |      dz   |j                        }%|%|z  }%tG        ||%      D &cg c]
  \  }}&||&z   }}}&|$|%d   z  }$n|D cg c]  }||z  	 }}|$|z  }$| j                  jL                  r=|D cg c]  }t        jP                  |dd       }}t        jP                  |$dd      }$|s||$fS tS        ||$      S c c}&}w c c}w c c}w )a	  
        The [`SparseControlNetModel`] 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 (`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.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.
        rgbbgrr3   )dimsz1unknown `controlnet_conditioning_channel_order`: Ng     mpsnpu)dtypedevicer   )r   )r   output_sizer   r   ry   )r   has_cross_attention)hidden_statestembr   r   
num_framesr   )r   r   r   )r   r   r   r*   r8   )r   )r   r   T)r   keepdim)r!   r"   )*shaper'   
zeros_liker   rr   flipr   tor   	unsqueeze	is_tensorr   typer   floatfloat32float64int32int64tensorr@   expandr   r   repeat_interleavepermutereshaper<   ru   catr   r   r   r   r   zipr   r   rq   logspacemeanr    )'rD   r   r   r   r   r   r   r   r   r   r   r   sample_batch_sizesample_channelssample_num_framessample_heightsample_widthchannel_order	timestepsis_mpsis_npur   t_embemb
batch_sizechannelsr   heightwidthbatch_framesr!   downsample_blockres_samples!controlnet_down_block_res_samplesdown_block_res_sampler   r"   scalesscales'                                          r,   rQ   zSparseControlNetModel.forwardQ  s   h ^d]i]iZ?,=}l!!&) IIE!e##jjsCO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##$51#))TU,YjJj#k ;A,,7
Hj&%1aA.66zJ7NPXZ`bghf%06-h4(():<MxY_afg((#ii:K(LRSTO:I:O:O7
Hj&%)11!Q1a@HH#Xvu
 88I0?0E0E-h)!T'2:::zS[]cejk/):@,,7
J&% 14E ExQWY^_ #) $ 0 0 	2')>?DTDhDh&6"(*?#1)+A'# '7VRUbl&m#"k1"	2  >>%t~~'<=$..BdBd*?#1+A (  4 -/)7:;QSWSnSn7o 	m3!#3$45J$K!0QUjTl0l-	m "C#88@ dkk@@^^B3/E+F+JSYS`S`aF00FJMNdflJm%nfun%n"%n#7&*#D Pf%gff/A&A%g"%g#7:L#L ;;--Ka&AG

6vt<&" & $)::.BX\#] *,@AA%#9Pd
 	
 &o &h&s   6UUU)ry   ry   Tr   )r   r   r   r   F)i@  i     r*  r   r3   r3   rN   rT   gh㈵>i   r3   Nr3      NFFr   rR   Fr   rT   r+  TT)r   rR   Tr   )g      ?NNNNFT)r#   r$   r%   r&    _supports_gradient_checkpointingr   rW   r   r   r   r	   r  r   r:   classmethodr   r   propertyr   r   r   r   r   r   r   r'   r(   r   r    rQ   rX   rY   s   @r,   r[   r[   `   sB   ;z (,$ %& $-
 :?.D !"#())+#&DEMQMN:;EI&+!&'0IZ',5:%'*+)-37G`
`
  #`
 	`

 `
  S/`
 $D%+$56`
 "#s(O`
 `
  `
  !&!`
" #`
$ "#%`
& '`
( !)`
* ',CsCx,@&A+`
, +35eCj3I*J-`
. 05S%S/5I/J/`
0 "#uS#X"671`
2 &eCsCx,@&AB3`
4  $5`
6 7`
8 "%9`
: .6eCHo-F;`
< !%=`
> 03?`
@  #A`
B %(C`
D #'E`
F -1G`
 `
D  6;IZ'+%&="= 03= .6eCHo-F	=
 !%=  #= 
!= =~ c+=&=!>  0 AE2Dd3PbKbFc2c,d  AF+ ?JeCd3i4G.H ?JT ?JN %(0415;?48  y
y
 eS01y
  %||	y

 y
 "y
  -y
 !.y
 !)c3h 8y
 $ELL1y
 y
 y
 
%uU5<<3D-Eu||-S'TT	Uy
r+   r[   r   rJ   c                 n    | j                         D ]!  }t        j                  j                  |       # | S rL   )
parametersr
   initzeros_)r   ps     r,   rB   rB     s/      
qMr+   )0dataclassesr   typingr   r   r   r   r   r	   r'   r
   torch.nnr   rM   configuration_utilsr   r   loadersr   utilsr   r   attention_processorr   r   r   r   r   
embeddingsr   r   modeling_utilsr   unets.unet_2d_blocksr   unets.unet_2d_conditionr   unets.unet_motion_modelr   r   
get_loggerr#   loggerr    r   r.   r[   rB   r*   r+   r,   <module>rB     s    " : :   $ B - (  6 ' : : O 
		H	% 'Z ' '&BII Dj

J5K j

\		 bii r+   