o
    + i8                     @  s   d dl mZ d dlZd dlmZmZ ddlmZmZmZ ddl	m
Z
 ddlmZmZmZ dd	lmZ dd
lmZ g ZG dd deZG dd deZG dd deZG dd deZdS )    )annotationsN)_C_opspir   )core	frameworkunique_name)check_variable_and_dtype)_current_expected_placein_dygraph_modein_pir_mode   )Initializer)lazy_init_helperc                      s4   e Zd ZdZ	dd fddZ	ddddZ  ZS )NormalInitializeraA  Implements the Random Normal(Gaussian) distribution initializer

    Args:
        loc (float|complex, optional): mean of the normal distribution. Default is 0.0.
        scale (float, optional): standard deviation of the normal distribution. Default is 1.0.
        seed (int, optional): random seed. Default is 0.

                  ?r   locfloatscaleseedintreturnNonec                   s   |d usJ |d usJ |d usJ t    || _|| _|| _t| jtrC| jj| jjkr<t	d| jj d| jj | jj| _d S d S )NzVif mean is a complex number, its real part should equal imag part, but got real part: z != imag part: )
super__init___mean_std_dev_seed
isinstancecomplexrealimag
ValueError)selfr   r   r   	__class__ h/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/paddle/nn/initializer/normal.pyr   +   s$   
zNormalInitializer.__init__Nvarpaddle.Tensorblockpir.Block | Nonepaddle.Tensor | Nonec              	   C  s   t |tjr| rJ d| |}t |tjtjfsJ t|dg dd | jdkr1|j	j
| _t rMt }t|j| j| j| j|j|}|| dS t rdt }t|j| j| j| j|j|}|S |jdd|i|j|j| j| j| jddd	}||_|S )
a\  Initialize the input tensor with Normal distribution.

        Args:
            var(Tensor): Tensor that needs to be initialized.
            block(Block|None, optional): The block in which initialization ops
                   should be added. Used in static graph only, default None.

        Returns:
            The initialization op.
        zCCurrently, normal initializer not support lazy init for dist param.Out)Zuint16Zfloat16Zfloat32Zfloat64Z	complex64Z
complex128Zgaussian_randomr   N)shapedtypemeanstdr   TtypeoutputsattrsZstop_gradient)r   r   ZEagerParamBaseZis_dist_check_blockBlockr   r	   r   programrandom_seedr   r
   r   Zgaussianr/   r   r   r0   _share_underline_tensor_tor   	append_opop)r$   r)   r+   Zplaceout_varr=   r'   r'   r(   forward=   sh   




zNormalInitializer.forward)r   r   r   )r   r   r   r   r   r   r   r   Nr)   r*   r+   r,   r   r-   __name__
__module____qualname____doc__r   r?   __classcell__r'   r'   r%   r(   r   !   s    
r   c                      s&   e Zd ZdZ	dd fddZ  ZS )Normalam  The Random Normal (Gaussian) distribution initializer.

    Args:
        mean (float|complex, optional): mean of the normal distribution. Default is 0.0.
        std (float, optional): standard deviation of the normal distribution. Default is 1.0.
        name(str|None, optional): The default value is None. Normally there is no need for user to set this
            property. For more information, please refer to :ref:`api_guide_Name`. Default: None.

    Returns:
        A parameter initialized by Random Normal (Gaussian) distribution.

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> data = paddle.ones(shape=[3, 1, 2], dtype='float32')
            >>> weight_attr = paddle.framework.ParamAttr(
            ...     name="linear_weight",
            ...     initializer=paddle.nn.initializer.Normal(mean=0.0, std=2.0))
            >>> bias_attr = paddle.framework.ParamAttr(
            ...     name="linear_bias",
            ...     initializer=paddle.nn.initializer.Normal(mean=0.0, std=2.0))
            >>> # doctest: +SKIP('name has been used')
            >>> linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr)
            >>> print(linear.weight)
            Parameter containing:
            Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
            [[ 2.1973135 -2.2697184],
             [-1.9104223 -1.0541488]])
            >>> print(linear.bias)
            Parameter containing:
            Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=False,
            [ 0.7885926  -0.74719954])
            >>> res = linear(data)
            >>> print(res)
            Tensor(shape=[3, 1, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
            [[[ 1.0754838 -4.071067 ]],
             [[ 1.0754838 -4.071067 ]],
             [[ 1.0754838 -4.071067 ]]])
    r   r   Nr1   r   r2   name
str | Noner   r   c                   s6   |d usJ d|d usJ dt  j||dd d S )Nmean should not be Nonestd should not be Noner   )r   r   r   r   r   )r$   r1   r2   rI   r%   r'   r(   r      s   zNormal.__init__)r   r   N)r1   r   r2   r   rI   rJ   r   r   rC   rD   rE   rF   r   rG   r'   r'   r%   r(   rH      s    +rH   c                      s<   e Zd ZdZ					dd fddZ	ddddZ  ZS )TruncatedNormalInitializera|  Implements the Random TruncatedNormal(Gaussian) distribution initializer

    Note:
        It is better to set `a <= mean <= b`.
        If `mean < a - 2*std` or `mean > b + 2*std`, the distribution of values may be incorrect.

    Args:
        loc (float, optional): Mean of the normal distribution. Default is :math:`0.0`.
        scale (float, optional): Standard deviation of the normal distribution. Default is :math:`1.0`.
        seed (int, optional): random seed. Default is 0.
        a (float, optional): The minimum cutoff value. Default is -2.0.
        b (float, optional): The maximum cutoff value. Default is 2.0.

    r   r   r                 @r   r   r   r   r   abr   r   c                   sh   |d usJ |d usJ |d usJ |d usJ |d usJ t    || _|| _|| _|| _|| _d S r@   )r   r   r   r   r   _a_b)r$   r   r   r   rR   rS   r%   r'   r(   r      s   

z#TruncatedNormalInitializer.__init__Nr)   r*   r+   r,   r-   c                 C  s&  |  |}t jrtjtjjjtj	j
f}ntjtjjtjjjf}t||s'J t|tjtjfs2J | jdkr<|jj| _|jtjjjtjjjfv rgtjjj}|jtdd|jdg|j|tjjjdd}n|j}|}t rt |j| j!| j"| j| j#| j$|t% }|jtjjjtjjjfv rt&||j}|'| dS |'| dS t( rt |j| j!| j"| j| j#| j$|t% }|jtjjjtjjjfv rt&||j}|'| |S |j)dd|i|j|| j!| j"| j| j#| j$d	d
d}|jtjjjtjjjfv r|j)dd|id|i|j|jdd ||_*|S )ad  Initialize the input tensor with TruncatedNormal distribution.

        Args:
            var(Tensor): Tensor that needs to be initialized.
            block(Block|None, optional): The block in which initialization ops
                   should be added. Used in static graph only, default None.

        Returns:
            The initialization op
        r   .truncated_gaussian_randomtmpF)rI   r/   r0   r4   ZpersistableNr.   )r/   r0   r1   r2   r   rR   rS   Tr3   castX)Zin_dtype	out_dtype)r4   Zinputsr5   r6   )+r7   r   stater   Variablepaddler   r   ZParameterMetaeagerZTensorValuer   r8   r   r9   r:   r0   ZVarDescZVarTypeZFP16ZBF16ZFP32Z
create_varr   generatejoinrI   r/   ZDENSE_TENSORr   r   rW   r   r   rT   rU   r
   rY   r;   r   r<   r=   )r$   r)   r+   expectedr[   r>   Zvar_tmpr=   r'   r'   r(   r?      s   









	z"TruncatedNormalInitializer.forward)r   r   r   rP   rQ   )r   r   r   r   r   r   rR   r   rS   r   r   r   r@   rA   rB   r'   r'   r%   r(   rO      s    rO   c                      s.   e Zd ZdZ					dd fddZ  ZS )TruncatedNormala  The truncated normal distribution (Gaussian distribution) initializer.

    Note:
        It is better to set `a <= mean <= b`.
        If `mean < a - 2*std` or `mean > b + 2*std`, the distribution of values may be incorrect.

    Args:
        mean (float, optional): Mean of the normal distribution. Default is :math:`0.0`.
        std (float, optional): Standard deviation of the normal distribution. Default is :math:`1.0`.
        a (float, optional): The minimum cutoff value. Default is -2.0.
        b (float, optional): The maximum cutoff value. Default is 2.0.
        name (str|None, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.

    Returns:
        A parameter initialized by truncated normal distribution (Gaussian distribution).

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> data = paddle.ones(shape=[3, 1, 2], dtype='float32')
            >>> weight_attr = paddle.framework.ParamAttr(
            ...     name="linear_weight",
            ...     initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0, std=2.0))
            >>> bias_attr = paddle.framework.ParamAttr(
            ...     name="linear_bias",
            ...     initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0, std=2.0))
            >>> # doctest: +SKIP('name has been used')
            >>> linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr)
            >>> print(linear.weight)
            Parameter containing:
            Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
            [[-1.0981836  1.4140984],
             [ 3.1390522 -2.8266568]])
            >>> print(linear.bias)
            Parameter containing:
            Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=False,
            [ -2.1546738  -1.6570673])
            >>> res = linear(data)
            >>> print(res)
            Tensor(shape=[3, 1, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
            [[[-0.11380529 -3.0696259 ]],
             [[-0.11380529 -3.0696259 ]],
             [[-0.11380529 -3.0696259 ]]])
    r   r   rP   rQ   Nr1   r   r2   rR   rS   rI   rJ   r   r   c                   sZ   |d usJ d|d usJ d|d usJ d|d us J dt  j||d||d d S )NrK   rL   za should not be Nonezb should not be Noner   )r   r   r   rR   rS   rM   )r$   r1   r2   rR   rS   rI   r%   r'   r(   r     s
   zTruncatedNormal.__init__)r   r   rP   rQ   N)r1   r   r2   r   rR   r   rS   r   rI   rJ   r   r   rN   r'   r'   r%   r(   rd   X  s    1rd   )
__future__r   r^   r   r   baser   r   r   Zbase.data_feederr	   Zbase.frameworkr
   r   r   Zinitializerr   Z	lazy_initr   __all__r   rH   rO   rd   r'   r'   r'   r(   <module>   s   i3 