
    biK                     B   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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 dd
lmZmZ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'm(Z(m)Z)  ejT                  e+      Z,e G d de             Z- G d de#ee      Z.y)    )	dataclass)AnyDictListOptionalTupleUnionN   )ConfigMixinregister_to_config)UNet2DConditionLoadersMixin)
BaseOutputlogging   )get_activation)ADDED_KV_ATTENTION_PROCESSORSCROSS_ATTENTION_PROCESSORS	AttentionAttentionProcessorAttnAddedKVProcessorAttnProcessorFusedAttnProcessor2_0)TimestepEmbedding	Timesteps)
ModelMixin)TransformerTemporalModel   )UNetMidBlock3DCrossAttnget_down_blockget_up_blockc                   0    e Zd ZU dZej
                  ed<   y)UNet3DConditionOutputa  
    The output of [`UNet3DConditionModel`].

    Args:
        sample (`torch.Tensor` of shape `(batch_size, num_channels, num_frames, height, width)`):
            The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
    sampleN)__name__
__module____qualname____doc__torchTensor__annotations__     c/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/unets/unet_3d_condition.pyr"   r"   1   s     LLr,   r"   c            $           e Zd ZdZdZddgZe	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d2dee   deded	e	e
d
f   de	e
d
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   f   deeee	e   f      dee   f  fd       Zedee
ef   fd       Zdee
eee   f   ddfdZdeeee
ef   f   fdZd3dee   deddfd Zd! Zd" Zd# Zd$ Zd% Zd& Z	 	 	 	 	 	 	 d4d'ej:                  d(eej:                  eef   d)ej:                  d*eej:                     d+eej:                     d,eej:                     d-eee
ef      d.ee	ej:                        d/eej:                     d0edee e	ej:                     f   fd1Z! xZ"S )5UNet3DConditionModela8	  
    A conditional 3D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
    shaped output.

    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
    for all models (such as downloading or saving).

    Parameters:
        sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
            Height and width of input/output sample.
        in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample.
        out_channels (`int`, *optional*, defaults to 4): The number of channels in the output.
        down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D")`):
            The tuple of downsample blocks to use.
        up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D")`):
            The tuple of upsample blocks to use.
        block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
            The tuple of output channels for each block.
        layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
        downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
        mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
        act_fn (`str`, *optional*, 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`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
        cross_attention_dim (`int`, *optional*, defaults to 1024): The dimension of the cross attention features.
        attention_head_dim (`int`, *optional*, defaults to 64): The dimension of the attention heads.
        num_attention_heads (`int`, *optional*): The number of attention heads.
        time_cond_proj_dim (`int`, *optional*, defaults to `None`):
            The dimension of `cond_proj` layer in the timestep embedding.
    Fnormtime_embeddingNsample_sizein_channelsout_channelsdown_block_types.up_block_typesblock_out_channelslayers_per_blockdownsample_paddingmid_block_scale_factoract_fnnorm_num_groupsnorm_epscross_attention_dimattention_head_dimnum_attention_headstime_cond_proj_dimc                    t         #|           || _        |t        d      |xs |}t	        |      t	        |      k7  rt        d| d| d      t	        |      t	        |      k7  rt        d| d| d      t        |t              s)t	        |      t	        |      k7  rt        d| d| d      d}d}|d	z
  d
z  }t        j                  ||d   ||      | _
        |d   dz  }t        |d   dd      | _        |d   }t        |||
|      | _        t        d||d   d	|      | _        t        j"                  g       | _        t        j"                  g       | _        t        |t              r|ft	        |      z  }|d   }t)        |      D ]T  \  }}|}||   }|t	        |      d	z
  k(  }t+        |||||| ||
||||   |d      }| j$                  j-                  |       V t/        |d   |||
|	||d   |d	      | _        d| _        t5        t7        |            }t5        t7        |            }|d   }t)        |      D ]  \  }}|t	        |      d	z
  k(  }|}||   }|t9        |d	z   t	        |      d	z
           }|sd} | xj2                  d	z  c_        nd} t;        ||d	z   ||||| ||
||||   d|      }!| j&                  j-                  |!       |} |1t        j<                  |d   ||      | _        tA        d      | _!        nd | _        d | _!        |d	z
  d
z  }"t        j                  |d   |||"      | _"        y )Na#  At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.z\Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: z. `up_block_types`: .zbMust provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: z. `down_block_types`: zdMust provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: r
   r   r   r   )kernel_sizepadding   T)r;   cond_proj_dim   )r@   r?   r3   
num_layersr<   F)rI   r3   r4   temb_channelsadd_downsample
resnet_epsresnet_act_fnresnet_groupsr>   r@   r9   dual_cross_attention)	r3   rJ   rL   rM   output_scale_factorr>   r@   rN   rO   )rI   r3   r4   prev_output_channelrJ   add_upsamplerL   rM   rN   r>   r@   rO   resolution_idx)num_channels
num_groupsepssilu)#super__init__r2   NotImplementedErrorlen
ValueError
isinstanceintnnConv2dconv_inr   	time_projr   r1   r   transformer_in
ModuleListdown_blocks	up_blocks	enumerater   appendr   	mid_blocknum_upsamplerslistreversedminr    	GroupNormconv_norm_outr   conv_actconv_out)$selfr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   conv_in_kernelconv_out_kernelconv_in_paddingtime_embed_dimtimestep_input_dimoutput_channelidown_block_typeinput_channelis_final_block
down_blockreversed_block_out_channelsreversed_num_attention_headsup_block_typerR   rS   up_blockconv_out_padding	__class__s$                                      r-   rZ   zUNet3DConditionModel.__init__b   s   < 	&*% v  2G5G  C$77no  oA  AU  Vd  Ue  ef  g  !"c*:&;;t  vH  uI  I_  `p  _q  qr  s  -s3<O8PTWXhTi8iv  xK  wL  Lb  cs  bt  tu  v 
 )A-!3yy+A.NTc

 ,A.2"#5a#8$B/2/,	
 7 !1*1-+
 ==,r*)3/#6"83?O;P"P ,A."+,<"= 	0A*M/2N#&8"9A"==N'+)+,#11#$-$7$7$:#5%*J ##J/)	0. 1*2.(  6 3 3B 7)!&

   '+84F+G&H#'+H5H,I'J$4Q7 ). 9 	1A}#&8"9A"==N"08;N7AE3GYCZ]^C^8_`M "###q(#$#+a/)+$7,)#$-$7$@$C%* H  NN!!(+"0?	1D &!#/2T\"D +62DM!%D DM+a/A5		q!<_Vf
r,   returnc                     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
.processorrC   )hasattrr   named_children)r   r   r   sub_namechildfn_recursive_add_processorss        r-   r   zIUNet3DConditionModel.attn_processors.<locals>.fn_recursive_add_processors,  sd    v/282F2F2H
dV:./#)#8#8#: U%+tfAhZ,@%TU r,   )strr(   r`   Moduler   r   r   )rs   r   r   r   r   s       @r-   attn_processorsz$UNet3DConditionModel.attn_processors!  sm     
	c 	588?? 	X\]`bt]tXu 	 !//1 	BLD&'fjA	B 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   ri   sliceable_head_dimchildren)r   r   $fn_recursive_retrieve_sliceable_dimssliceable_head_dimss     r-   r   zVUNet3DConditionModel.set_attention_slice.<locals>.fn_recursive_retrieve_sliceable_dimsK  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 rC   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   zRUNet3DConditionModel.set_attention_slice.<locals>.fn_recursive_set_attention_sliceq  sE    v45**:>>+;<* D0
CDr,   )r(   r`   r   r   r\   r^   rl   r]   configranger   r_   rm   )rs   r   r   num_sliceable_layersdimrz   sizereversed_slice_sizer   r   r   s           @@@r-   r   z(UNet3DConditionModel.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;	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   rC   )r   r^   dictr   r   r   )r   r   r   r   r   fn_recursive_attn_processors        r-   r   zLUNet3DConditionModel.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   )rs   r   countr   r   r   s        @r-   set_attn_processorz'UNet3DConditionModel.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,   
chunk_sizer   c                     |dvrt        d|       |xs d}dt        j                  j                  dt        dt        ffd| j                         D ]  } |||        y)	aX  
        Sets the attention processor to use [feed forward
        chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).

        Parameters:
            chunk_size (`int`, *optional*):
                The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
                over each tensor of dim=`dim`.
            dim (`int`, *optional*, defaults to `0`):
                The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
                or dim=1 (sequence length).
        )r   r   z-Make sure to set `dim` to either 0 or 1, not r   r   r   r   c                     t        | d      r| j                  ||       | j                         D ]  } |||        y Nset_chunk_feed_forward)r   r   r   r   r   r   r   r   r   fn_recursive_feed_forwards       r-   r   zOUNet3DConditionModel.enable_forward_chunking.<locals>.fn_recursive_feed_forward  E    v78---M* B)%SABr,   N)r]   r(   r`   r   r_   r   )rs   r   r   r   r   s       @r-   enable_forward_chunkingz,UNet3DConditionModel.enable_forward_chunking  su     fLSERSS  _1
	Behhoo 	B3 	BUX 	B mmo 	?F%fj#>	?r,   c                     dt         j                  j                  dt        dt        ffd| j	                         D ]  } |d d        y )Nr   r   r   c                     t        | d      r| j                  ||       | j                         D ]  } |||        y r   r   r   s       r-   r   zPUNet3DConditionModel.disable_forward_chunking.<locals>.fn_recursive_feed_forward  r   r,   r   )r(   r`   r   r_   r   )rs   r   r   s     @r-   disable_forward_chunkingz-UNet3DConditionModel.disable_forward_chunking  sM    	Behhoo 	B3 	BUX 	B mmo 	7F%fdA6	7r,   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N)r   r   .0procs     r-   	<genexpr>zBUNet3DConditionModel.set_default_attn_processor.<locals>.<genexpr>  s     i4t~~!>>i   c              3   @   K   | ]  }|j                   t        v   y wr   )r   r   r   s     r-   r   zBUNet3DConditionModel.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   )rs   r   s     r-   set_default_attn_processorz/UNet3DConditionModel.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,   c                     t        | j                        D ]9  \  }}t        |d|       t        |d|       t        |d|       t        |d|       ; y)aF  Enables the FreeU mechanism from https://huggingface.co/papers/2309.11497.

        The suffixes after the scaling factors represent the stage blocks where they are being applied.

        Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
        are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.

        Args:
            s1 (`float`):
                Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
                mitigate the "oversmoothing effect" in the enhanced denoising process.
            s2 (`float`):
                Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
                mitigate the "oversmoothing effect" in the enhanced denoising process.
            b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
            b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
        s1s2b1b2N)rh   rg   setattr)rs   r   r   r   r   rz   upsample_blocks          r-   enable_freeuz!UNet3DConditionModel.enable_freeu  sQ    $ "+4>>!: 	.A~ND"-ND"-ND"-ND"-		.r,   c                     h d}t        | j                        D ]3  \  }}|D ])  }t        ||      st        ||d      t	        ||d       + 5 y)zDisables the FreeU mechanism.>   r   r   r   r   N)rh   rg   r   getattrr   )rs   
freeu_keysrz   r   ks        r-   disable_freeuz"UNet3DConditionModel.disable_freeu  sW    -
!*4>>!: 	5A~ 5>1-D1Q1]NAt45	5r,   c                 r   d| _         | j                  j                         D ]1  \  }}dt        |j                  j
                        v s(t        d       | j                  | _         | j                         D ]%  }t        |t              s|j                  d       ' | j                  t                      y)u1  
        Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
        are fused. For cross-attention modules, key and value projection matrices are fused.

        <Tip warning={true}>

        This API is 🧪 experimental.

        </Tip>
        NAddedzQ`fuse_qkv_projections()` is not supported for models having added KV projections.T)fuse)original_attn_processorsr   itemsr   r   r$   r]   modulesr^   r   fuse_projectionsr   r   )rs   _attn_processorr   s       r-   fuse_qkv_projectionsz)UNet3DConditionModel.fuse_qkv_projections  s     )-%!%!5!5!;!;!= 	vA~#n66??@@ !tuu	v )-(<(<%lln 	3F&),''T'2	3 	 5 78r,   c                 T    | j                   | j                  | j                          yy)u   Disables the fused QKV projection if enabled.

        <Tip warning={true}>

        This API is 🧪 experimental.

        </Tip>

        N)r   r   )rs   s    r-   unfuse_qkv_projectionsz+UNet3DConditionModel.unfuse_qkv_projections  s)     ((4##D$A$AB 5r,   r#   timestepencoder_hidden_statesclass_labelstimestep_condattention_maskcross_attention_kwargsdown_block_additional_residualsmid_block_additional_residualreturn_dictc                 	   d| j                   z  d}d}t        fd|j                  dd D              rt        j	                  d       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                  d   }|j)                  |j                  d         }| j+                  |      }|j                  | j                        }| j-                  ||      }|j/                  |d|j                  d   |z        }|j/                  |d|j                  d   |z        }|j1                  ddddd      j3                  |j                  d   |z  df|j                  dd z         }| j5                  |      }| j7                  |||d      d   }|f}| j8                  D ]?  }t;        |d      r|j<                  r |||||||      \  }}n ||||      \  }}||z  }A |#d}t?        ||      D ]  \  }}||z   }||fz  } |}| j@                  | jA                  ||||||      }|	||	z   }tC        | jD                        D ]  \  }}|t'        | jD                        dz
  k(  }|t'        |jF                         d }|dt'        |jF                          }|s|r|d   j                  dd }t;        |d      r|j<                  r |||||||||      } ||||||      } | jH                  r"| jI                  |      }| jK                  |      }| jM                  |      }|dddf   j3                  d|f|j                  dd z         j1                  ddddd      }|
s|fS tO        |      S )a
  
        The [`UNet3DConditionModel`] forward method.

        Args:
            sample (`torch.Tensor`):
                The noisy input tensor with the following shape `(batch, num_channels, num_frames, height, width`.
            timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
            encoder_hidden_states (`torch.Tensor`):
                The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
            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`):
                Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
                through the `self.time_embedding` layer to obtain the 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.
            cross_attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
                A tuple of tensors that if specified are added to the residuals of down unet blocks.
            mid_block_additional_residual: (`torch.Tensor`, *optional*):
                A tensor that if specified is added to the residual of the middle unet block.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~models.unets.unet_3d_condition.UNet3DConditionOutput`] instead of a plain
                tuple.
            cross_attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the [`AttnProcessor`].

        Returns:
            [`~models.unets.unet_3d_condition.UNet3DConditionOutput`] or `tuple`:
                If `return_dict` is True, an [`~models.unets.unet_3d_condition.UNet3DConditionOutput`] is returned,
                otherwise a `tuple` is returned where the first element is the sample tensor.
        r   FNc              3   .   K   | ]  }|z  d k7    yw)r   Nr+   )r   sdefault_overall_up_factors     r-   r   z/UNet3DConditionModel.forward.<locals>.<genexpr>]  s     Maq,,1Ms   z9Forward upsample size to force interpolation output size.Tr   g     mpsnpu)dtypedevicer   )r   )r   output_sizer
   rF   rP   )
num_framesr   r   has_cross_attention)hidden_statestembr   r   r   r   )r   r   r   r+   )r   r   r   r   )r   r   res_hidden_states_tupler   upsample_sizer   r   r   )r   r   r   r   r   )r#   )(rk   anyshapeloggerinfotor   	unsqueezer(   	is_tensorr   typer^   floatfloat32float64int32int64tensorr\   expandrc   r1   repeat_interleavepermutereshaperb   rd   rf   r   r   ziprj   rh   rg   resnetsrp   rq   rr   r"   )rs   r#   r   r   r   r   r   r   r   r   r   forward_upsample_sizer   	timestepsis_mpsis_npur   r   t_embembdown_block_res_samplesdownsample_blockres_samplesnew_down_block_res_samplesdown_block_res_sampledown_block_additional_residualrz   r   r}   r   s                                @r-   forwardzUNet3DConditionModel.forward!  s   l %&t':':$:! !&M6<<;LMMKKST$(! %."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)
 tzz*!!%7##JA399Q<R\C\#] 5 G GA+@+F+Fq+IJ+V !H !

 1aA.66Q*8TVX7Y\b\h\hijik\l7lmf%$$!#9	 % 

  #) $ 0 0 	2')>?DTDhDh&6"(*?#1)+A'# '7VRUbl&m#"k1"	2 +6)+&IL&(GJ GE%'E )>@^(^%*/D.FF*	G &@" >>%^^&;-%'= $ F )4;;F "+4>>!: 	A~#dnn"5"99N0#n6L6L2M1M1OPK%;<Zs>CYCY?Z>Z%[" "&; 6r : @ @ D~'<=.BdBd'"(,7*?"/#1)+A	 ("(,7"/)/	@ ''/F]]6*Fv& a(("j)9FLL<L)LMUUVWYZ\]_`bcd9$F33r,   )NrF   rF   )CrossAttnDownBlock3Dr   r   DownBlock3D)	UpBlock3DCrossAttnUpBlock3Dr#  r#  )i@  i     r$  r   r   r   rX       gh㈵>i   @   NN)Nr   )NNNNNNT)#r$   r%   r&   r'    _supports_gradient_checkpointing _skip_layerwise_casting_patternsr   r   r_   r   r   r  r	   rZ   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r(   r)   r   boolr"   r  __classcell__)r   s   @r-   r/   r/   >   s   @ (-$(.0@'A$ &*-
+
 /E !"#())+#'57@D,07|
c]|
 |
 	|

  S/|
 c3h|
" "#s(O#|
$ %|
&  '|
( !&)|
* +|
, "#-|
. /|
0 !1|
2 "#uSz/23|
4 &eCsO&<=5|
6 %SM7|
 |
| c+=&=!>  0?JeCd3i4G.H ?JT ?JD AE2Dd3PbKbFc2c,d  AD?(3- ?S ?Y] ?:	7+ .2594C$ 040415;?IM@D G4G4 eS01G4  %||	G4
 u||,G4  -G4 !.G4 !)c3h 8G4 *2%2E)FG4 (0'=G4 G4 
$eELL&99	:G4r,   r/   )/dataclassesr   typingr   r   r   r   r   r	   r(   torch.nnr`   torch.utils.checkpointconfiguration_utilsr   r   loadersr   utilsr   r   activationsr   attention_processorr   r   r   r   r   r   r   
embeddingsr   r   modeling_utilsr   !transformers.transformer_temporalr   unet_3d_blocksr   r   r    
get_loggerr$   r  r"   r/   r+   r,   r-   <module>r:     s     " : :    B 2 ( (   6 ' H  
		H	% 	J 	 	j
4:{4O j
4r,   