
    bi=                        d dl mZmZ d dlZd dlmZ d dlmc mZ ddl	m
Z
 ddlmZ ddlmZ  G d d	ej                        Z G d
 dej                        Z G d dej                        Z G d dej                        Z G d dej                        Z	 	 	 ddej*                  deej*                     dededej*                  f
dZy)    )OptionalTupleN   )	deprecate   )RMSNorm)upfirdn2d_nativec                        e Zd ZdZ	 	 	 	 ddededee   dedef
 fdZde	j                  d	e	j                  fd
Z xZS )Downsample1Da  A 1D downsampling layer with an optional convolution.

    Parameters:
        channels (`int`):
            number of channels in the inputs and outputs.
        use_conv (`bool`, default `False`):
            option to use a convolution.
        out_channels (`int`, optional):
            number of output channels. Defaults to `channels`.
        padding (`int`, default `1`):
            padding for the convolution.
        name (`str`, default `conv`):
            name of the downsampling 1D layer.
    channelsuse_convout_channelspaddingnamec                 N   t         |           || _        |xs || _        || _        || _        d}|| _        |r4t        j                  | j                  | j                  d||      | _	        y | j                  | j                  k(  sJ t        j                  ||      | _	        y )Nr      strider   kernel_sizer   )super__init__r   r   r   r   r   nnConv1dconv	AvgPool1d)selfr   r   r   r   r   r   	__class__s          X/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/models/downsampling.pyr   zDownsample1D.__init__*   s     	 (4H 			$--1B1BAf^efDI==D$5$5555GDI    inputsreturnc                 `    |j                   d   | j                  k(  sJ | j                  |      S )Nr   )shaper   r   )r   r!   s     r   forwardzDownsample1D.forward@   s+    ||A$--///yy  r    )FNr   r   __name__
__module____qualname____doc__intboolr   strr   torchTensorr%   __classcell__r   s   @r   r   r      sp    $ &*HH H sm	H
 H H,!ell !u|| !r    r   c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 ddededee   dedef
 fdZde	j                  d	e	j                  fd
Z xZS )Downsample2Da  A 2D downsampling layer with an optional convolution.

    Parameters:
        channels (`int`):
            number of channels in the inputs and outputs.
        use_conv (`bool`, default `False`):
            option to use a convolution.
        out_channels (`int`, optional):
            number of output channels. Defaults to `channels`.
        padding (`int`, default `1`):
            padding for the convolution.
        name (`str`, default `conv`):
            name of the downsampling 2D layer.
    r   r   r   r   r   c                 0   t         |           || _        |xs || _        || _        || _        d}|| _        |dk(  rt        j                  |||	      | _	        n0|dk(  rt        |||	      | _	        n|d | _	        nt        d|       |r0t        j                  | j                  | j                  ||||
      }n2| j                  | j                  k(  sJ t        j                  ||      }|dk(  r|| _        || _        y |dk(  r|| _        y || _        y )	Nr   ln_normrms_normzunknown norm_type: )r   r   r   biasr   r   Conv2d_0)r   r   r   r   r   r   r   r   	LayerNormnormr   
ValueErrorConv2d	AvgPool2dr8   r   )r   r   r   r   r   r   r   	norm_typeepselementwise_affiner7   r   r   r   s                r   r   zDownsample2D.__init__U   s    	 (4H 		!Xs4FGDI*$#/ABDIDI29+>??99t00kRXbiptD ==D$5$5555<<F6BD 6> DMDIZDIDIr    hidden_statesr"   c                    t        |      dkD  s|j                  dd       d}t        dd|       |j                  d   | j                  k(  sJ | j
                  5| j                  |j                  dddd            j                  dddd      }| j                  r*| j                  dk(  rd}t        j                  ||d	d
      }|j                  d   | j                  k(  sJ | j                  |      }|S )Nr   scalezThe `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`.z1.0.0r   r   r   r   r   r   r   constantmodevalue)lengetr   r$   r   r:   permuter   r   Fpadr   )r   rA   argskwargsdeprecation_messagerM   s         r   r%   zDownsample2D.forward   s    t9q=FJJw5A #Ugw(;<""1%66699  IIm&;&;Aq!Q&GHPPQRTUWXZ[\M==T\\Q.CEE-:QOM""1%666		-0r    )	FNr   r   r   NNNTr&   r1   s   @r   r3   r3   E   sz    $ &*-- - sm	-
 - -^U\\ u|| r    r3   c                       e Zd ZdZ	 	 	 	 ddee   dee   dedeeeeef   f fdZ	 	 	 	 dde	j                  dee	j                     d	ee	j                     d
edede	j                  fdZde	j                  de	j                  fdZ xZS )FirDownsample2Da  A 2D FIR downsampling layer with an optional convolution.

    Parameters:
        channels (`int`):
            number of channels in the inputs and outputs.
        use_conv (`bool`, default `False`):
            option to use a convolution.
        out_channels (`int`, optional):
            number of output channels. Defaults to `channels`.
        fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
            kernel for the FIR filter.
    r   r   r   
fir_kernelc                     t         |           |r|n|}|rt        j                  ||ddd      | _        || _        || _        || _        y )Nr   r   r   r   r   )r   r   r   r<   r8   rS   r   r   )r   r   r   r   rS   r   s        r   r   zFirDownsample2D.__init__   sL     	'3|IIh!TU_`aDM$ (r    rA   weightkernelfactorgainr"   c                    t        |t              r|dk\  sJ |dg|z  }t        j                  |t        j                        }|j
                  dk(  rt        j                  ||      }|t        j                  |      z  }||z  }| j                  r|j                  \  }}}}|j                  d   |z
  |dz
  z   }	||g}
t        |t        j                  ||j                        |	dz   dz  |	dz  f      }t        j                  |||
d      }|S |j                  d   |z
  }	t        |t        j                  ||j                        ||	dz   dz  |	dz  f      }|S )	a"  Fused `Conv2d()` followed by `downsample_2d()`.
        Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
        efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
        arbitrary order.

        Args:
            hidden_states (`torch.Tensor`):
                Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
            weight (`torch.Tensor`, *optional*):
                Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
                performed by `inChannels = x.shape[0] // numGroups`.
            kernel (`torch.Tensor`, *optional*):
                FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
                corresponds to average pooling.
            factor (`int`, *optional*, default to `2`):
                Integer downsampling factor.
            gain (`float`, *optional*, default to `1.0`):
                Scaling factor for signal magnitude.

        Returns:
            output (`torch.Tensor`):
                Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same
                datatype as `x`.
        r   dtyper   devicer   )rM   r   downrM   )
isinstancer+   r.   tensorfloat32ndimoutersumr   r$   r	   r^   rL   conv2d)r   rA   rV   rW   rX   rY   _convHconvW	pad_valuestride_valueupfirdn_inputoutputs                r   _downsample_2dzFirDownsample2D._downsample_2d   s_   B &#&6Q;66>S6\F fEMM:;;![[0F%))F##$==!'Aq%a61eai@I"F+L,VM,@,@A!m)9>:M
 XXmVLRSTF  Q&0I%VM,@,@A!m)9>:	F r    c                    | j                   r_| j                  || j                  j                  | j                        }|| j                  j
                  j                  dddd      z   }|S | j                  || j                  d      }|S )N)rV   rW   r   r   )rW   rX   )r   ro   r8   rV   rS   r7   reshape)r   rA   downsample_inputs      r   r%   zFirDownsample2D.forward   s    ==#22=I]I]fjfufu2v,t}}/A/A/I/I!RQRTU/VVM  !//doo^_/`Mr    )NNF)r   r   r   r   )NNr   r   )r'   r(   r)   r*   r   r+   r,   r   r   r.   r/   floatro   r%   r0   r1   s   @r   rR   rR      s     #'&*0<)3-) sm) 	)
 #sC,-)$ *.)-@||@ &@ &	@
 @ @ 
@DU\\ ell r    rR   c                   b     e Zd ZdZddef fdZdej                  dej                  fdZ xZ	S )KDownsample2DzA 2D K-downsampling layer.

    Parameters:
        pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
    pad_modec                     t         |           || _        t        j                  g dg      }|j
                  d   dz  dz
  | _        | j                  d|j                  |z  d       y )N)      ?      ?rz   ry   r   r   rW   F)
persistent)	r   r   rw   r.   rb   r$   rM   register_bufferT)r   rw   	kernel_1dr   s      r   r   zKDownsample2D.__init__	  s_     LL">!?@	??1%*Q.Xy{{Y'>5Qr    r!   r"   c                 4   t        j                  || j                  fdz  | j                        }|j                  |j                  d   |j                  d   | j
                  j                  d   | j
                  j                  d   g      }t        j                  |j                  d   |j                        }| j
                  j                  |      d d d f   j                  |j                  d   dd      }||||f<   t        j                  ||d      S )N   r   r   r]   rq   r   )r   )rL   rM   rw   	new_zerosr$   rW   r.   aranger^   toexpandrg   )r   r!   rV   indicesrW   s        r   r%   zKDownsample2D.forward  s    v{Q>!!QQ!!!$!!!$	
 ,,v||Av}}E'a077QRP#)w xxq11r    )reflect)
r'   r(   r)   r*   r-   r   r.   r/   r%   r0   r1   s   @r   rv   rv     s1    R R2ell 2u|| 2r    rv   c                   ~     e Zd ZdZ	 	 	 	 ddedededededef fdZd	ej                  d
ej                  fdZ	 xZ
S )CogVideoXDownsample3Da  
    A 3D Downsampling layer using in [CogVideoX]() by Tsinghua University & ZhipuAI

    Args:
        in_channels (`int`):
            Number of channels in the input image.
        out_channels (`int`):
            Number of channels produced by the convolution.
        kernel_size (`int`, defaults to `3`):
            Size of the convolving kernel.
        stride (`int`, defaults to `2`):
            Stride of the convolution.
        padding (`int`, defaults to `0`):
            Padding added to all four sides of the input.
        compress_time (`bool`, defaults to `False`):
            Whether or not to compress the time dimension.
    in_channelsr   r   r   r   compress_timec                 n    t         |           t        j                  |||||      | _        || _        y )NrU   )r   r   r   r<   r   r   )r   r   r   r   r   r   r   r   s          r   r   zCogVideoXDownsample3D.__init__4  s2     	IIk<[Y_ipq	*r    xr"   c                    | j                   r*|j                  \  }}}}}|j                  ddddd      j                  ||z  |z  ||      }|j                  d   dz  dk(  r|d   |ddd f   }}|j                  d   dkD  rt	        j
                  |dd	      }t        j                  |d
   |gd      }|j                  |||||j                  d         j                  ddddd      }nMt	        j
                  |dd	      }|j                  |||||j                  d         j                  ddddd      }d}	t	        j                  ||	dd      }|j                  \  }}}}}|j                  ddddd      j                  ||z  |||      }| j                  |      }|j                  |||j                  d   |j                  d   |j                  d         j                  ddddd      }|S )Nr   r   r   r   r   rq   ).r   .r   ).N)dimrD   rE   rF   )
r   r$   rK   rr   rL   
avg_pool1dr.   catrM   r   )
r   r   
batch_sizer   framesheightwidthx_firstx_restrM   s
             r   r%   zCogVideoXDownsample3D.forwardB  s   :;''7J&&% 		!Q1a(00f1Du1LhX^_Awwr{Q!#"#F)QsABwZ<<#a'\\&aJFIIwy16:CIIj&%1772;OWWXY[\^_abdef LL!<IIj&%1772;OWWXY[\^_abdef EE!Sz367gg3
HffeIIaAq!$,,Z&-@(FTYZIIaLIIj&!''!*aggaj!''!*MUUVWYZ\]_`bcdr    )r   r   r   F)r'   r(   r)   r*   r+   r,   r   r.   r/   r%   r0   r1   s   @r   r   r      sp    , #++ + 	+
 + + + %,, r    r   rA   rW   rX   rY   r"   c                    t        |t              r|dk\  sJ |dg|z  }t        j                  |t        j                        }|j
                  dk(  rt        j                  ||      }|t        j                  |      z  }||z  }|j                  d   |z
  }t        | |j                  | j                        ||dz   dz  |dz  f      }|S )aE  Downsample2D a batch of 2D images with the given filter.
    Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
    given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
    specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
    shape is a multiple of the downsampling factor.

    Args:
        hidden_states (`torch.Tensor`)
            Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
        kernel (`torch.Tensor`, *optional*):
            FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
            corresponds to average pooling.
        factor (`int`, *optional*, default to `2`):
            Integer downsampling factor.
        gain (`float`, *optional*, default to `1.0`):
            Scaling factor for signal magnitude.

    Returns:
        output (`torch.Tensor`):
            Tensor of the shape `[N, C, H // factor, W // factor]`
    r   r[   r   r]   r   r_   )ra   r+   r.   rb   rc   rd   re   rf   r$   r	   r   r^   )rA   rW   rX   rY   rk   rn   s         r   downsample_2dr   d  s    8 fc"v{22~v\\&6F{{aVV,
eiiFd]FQ&(I		--	.!m!9>2	F Mr    )Nr   r   )typingr   r   r.   torch.nnr   torch.nn.functional
functionalrL   utilsr   normalizationr   
upsamplingr	   Moduler   r3   rR   rv   r   r/   r+   rt   r    r    r   <module>r      s    #      " ((!299 (!VP299 Pffbii fT2BII 2<ABII AL &*	-<<-U\\"- - 	-
 \\-r    