o
    Me                     @   s  d dl mZ d dlZd dlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZ ddlmZ ddlmZ d dlZdd	lmZ dd
lmZ ddlmZmZmZ d dlmZmZ d dlZg dZdadaG dd de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"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(d d!Z'd"d# Z(d$d% Z)d(d&d'Z*eZ+e Z,e!Z-e"Z.e#Z/e$Z0e%Z1dS ))    )print_functionN   )	framework)core)_non_static_modein_dygraph_mode_in_legacy_dygraphdefault_main_program_current_expected_place)lazy_init_helper)program_guard)VarDesc)unique_name)check_variable_and_dtype
check_typecheck_dtype)_C_ops_legacy_C_ops)ConstantUniformNormalTruncatedNormalXavierBilinearMSRAConstantInitializerUniformInitializerNormalInitializerTruncatedNormalInitializerXavierInitializerBilinearInitializerMSRAInitializerNumpyArrayInitializerset_global_initializerc                   @   sF   e Zd ZdZdd ZdddZdddZdd	d
Zdd Zdd Z	dS )Initializera  Base class for variable initializers

    Defines the common interface of variable initializers.
    They add operations to the init program that are used
    to initialize variables. Users should not use this class
    directly, but need to use one of its implementations.
    c                 C   s   d S N selfr&   r&   HD:\Projects\ConvertPro\env\Lib\site-packages\paddle/fluid/initializer.py__init__3   s   zInitializer.__init__Nc                 C   s    t  js
| ||S | ||S r%   )r   stateforward
_lazy_initr(   paramblockr&   r&   r)   __call__6   s   zInitializer.__call__c                 C   s   t  )zCAdd corresponding initialization operations to the network
        )NotImplementedErrorr.   r&   r&   r)   r,   <   s   zInitializer.forwardc                 C   s>   t  sJ dd }|t| j|| t|| j||_|S )z+
        Apply lazy initialization
        c                 S   sD   |j d|d}t  | || W d    d S 1 sw   Y  d S )NT)r0   )Z_to_static_varr   )r,   r/   r0   Znew_varr&   r&   r)   init_op_creatorG   s   "z/Initializer._lazy_init.<locals>.init_op_creator)r   Zset_init_func	functoolspartialr,   Z_init_op_creator)r(   r/   r0   r3   r&   r&   r)   r-   A   s   
zInitializer._lazy_initc                 C   s   |d u r	t   }|S r%   )r	   Zglobal_block)r(   r0   r&   r&   r)   _check_blockT   s   
zInitializer._check_blockc                 C   s   |j }|rt|dkrd }}||fS t|dkr#|d  }}||fS t|dkr5|d }|d }||fS t|dd }|d | }|d | }||fS )a  Compute the fan_in and the fan_out for layers

        This method computes the fan_in and the fan_out
        for neural network layers, if not specified. It is
        not possible to perfectly estimate fan_in and fan_out.
        This method will estimate it correctly for matrix multiply and
        convolutions.

        Args:
            var: variable for which fan_in and fan_out have to be computed

        Returns:
            tuple of two integers (fan_in, fan_out)
        r   r      N)shapelennpprod)r(   varr8   fan_infan_outZreceptive_field_sizer&   r&   r)   _compute_fansZ   s   
zInitializer._compute_fansr%   )
__name__
__module____qualname____doc__r*   r1   r,   r-   r6   r?   r&   r&   r&   r)   r$   *   s    


r$   c                       s,   e Zd ZdZd	 fdd	Zd
ddZ  ZS )r   a  Implements the constant initializer

    Args:
        value (float32): constant value to initialize the variable 

    Examples:
        .. code-block:: python

            import paddle
            import paddle.fluid as fluid
            paddle.enable_static()
            x = fluid.data(name="data", shape=[8, 32, 32], dtype="float32")
            fc = fluid.layers.fc(
                input=x,
                size=10,
                param_attr=fluid.initializer.Constant(value=2.0))

            Fc                    s*   |d usJ t t|   || _|| _d S r%   )superr   r*   _value
_force_cpu)r(   value	force_cpu	__class__r&   r)   r*      s   
zConstantInitializer.__init__Nc                 C   s   |  |}t|tjst|tjsJ t|tjsJ t r:t }| jr(t	
 }t||jtt| j|j| dS t r[t|dt| jd| jdt|jdtt| jd|j dS |jdd|i|jt|jt| jtt| j| jd	d
d}||_|S )aK  Initialize the input tensor with constant.

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

        Returns:
            The initialization op
        NrH   rI   dtype	str_valuer8   fill_constantOut)r8   rL   rH   rM   rI   Ttypeoutputsattrsstop_gradient)r6   
isinstancer   VariableZEagerParamBaseBlockr   r
   rG   r   ZCPUPlacer   Zfull_r8   strfloatrF   rL   r   r   rN   int	append_opop)r(   r<   r0   placer\   r&   r&   r)   r,      sB   


zConstantInitializer.forward)rD   Fr%   r@   rA   rB   rC   r*   r,   __classcell__r&   r&   rJ   r)   r   ~   s    r   c                       s8   e Zd ZdZ						d
 fdd	Zddd	Z  ZS )r   a  Implements the random uniform distribution initializer

    Args:
        low (float): lower boundary of the uniform distribution
        high (float): upper boundary of the uniform distribution
        seed (int): random seed
        diag_num (int): the number of diagonal elements to initialize.
            If set to 0, diagonal initialization will be not performed.
        diag_step (int): Step size between two diagonal elements,
            which is generally the width of the square matrix.
        diag_val (float): the value of the diagonal element to be initialized,
            default 1.0. It takes effect only if the diag_num is greater than 0.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            x = fluid.data(name='x', shape=[None, 1], dtype='float32')
            fc = fluid.layers.fc(input=x, size=10,
    		param_attr=fluid.initializer.Uniform(low=-0.5, high=0.5))
                ?r   c                    s   |d usJ |d usJ ||ksJ |d usJ |d usJ |d us$J |d us*J |dks2|dkr<|dkr:|dks<J t t|   || _|| _|| _|| _|| _|| _d S Nr   )	rE   r   r*   _low_high_seed	_diag_num
_diag_step	_diag_val)r(   lowhighseeddiag_num	diag_stepdiag_valrJ   r&   r)   r*      s    
zUniformInitializer.__init__Nc                 C   s  |  |}t|tjsJ t|dg dd | jdkr |jj| _|jt	j
jkrCt	j
j}|jtdd|jdg|j|t	j
jdd}n|j}|}t rt r_t|j|| j| j| jt }nt r}td	|jd
| jd| jd| jd|d| jd| jd| j}|jt	j
jkrt rt ||j}nt rt |d|jd|j}|!| dS |!| dS |j"di d|i|j|| j| j| j| j| j| jddd}|jt	j
jkr|j"dd|id|i|j|jdd ||_#|S )aW  Initialize the input tensor with Uniform distribution.

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

        Returns:
            The initialization op
        rO   Zuint16Zfloat16float32Zfloat64uniform_randomr   .tmpFnamer8   rL   rQ   Zpersistabler8   minmaxrk   rL   rl   rm   rn   in_dtype	out_dtypeN)r8   rL   rv   rw   rk   rl   rm   rn   TrQ   inputsrR   rS   rT   castXrx   ry   rQ   r{   rR   rS   )$r6   rU   r   rW   r   re   programrandom_seedrL   r   VarTypeFP16FP32
create_varr   generatejoinru   r8   
LOD_TENSORr   r   r   rq   rc   rd   r
   r   r   rf   rg   rh   r|   _share_underline_tensor_tor[   r\   r(   r<   r0   ry   out_varvar_tmpr\   r&   r&   r)   r,      s   






zUniformInitializer.forward)r`   ra   r   r   r   ra   r%   r^   r&   r&   rJ   r)   r      s    r   c                       ,   e Zd ZdZd
 fdd	Zddd	Z  ZS )r   a  Implements the Random Normal(Gaussian) distribution initializer

    Args:
        loc (float): mean of the normal distribution
        scale (float): standard deviation of the normal distribution
        seed (int): random seed

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            x = fluid.data(name="data", shape=[None, 32, 32], dtype="float32")
            fc = fluid.layers.fc(input=x, size=10,
                param_attr=fluid.initializer.Normal(loc=0.0, scale=2.0))

    rD   ra   r   c                    H   |d usJ |d usJ |d usJ t t|   || _|| _|| _d S r%   )rE   r   r*   _mean_std_devre   r(   locscalerk   rJ   r&   r)   r*   ]     
zNormalInitializer.__init__Nc                 C   s   |  |}t|tjsJ t|dg dd | jdkr |jj| _t r<t	 }t
|j| j| j| j|j|}|| dS t r[td|jd|jd| jd	| jd
| jdd}|| dS |jdd|i|j|j| j| j| jdddd}||_|S )aV  Initialize the input tensor with Normal distribution.

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

        Returns:
            The initialization op
        rO   ro   Zguassian_randomr   Nr8   rL   meanstdrk   
use_mkldnnFgaussian_random)r8   rL   r   r   rk   r   TrP   )r6   rU   r   rW   r   re   r   r   r   r
   r   r   r8   r   r   rL   r   r   r   r[   r\   )r(   r<   r0   r]   r   r\   r&   r&   r)   r,   f  sH   




zNormalInitializer.forwardrD   ra   r   r%   r^   r&   r&   rJ   r)   r   K  s    	r   c                       r   )r   a  Implements the Random TruncatedNormal(Gaussian) distribution initializer

    Args:
        loc (float): mean of the normal distribution
        scale (float): standard deviation of the normal distribution
        seed (int): random seed

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            x = fluid.data(name='x', shape=[None, 1], dtype='float32')
            fc = fluid.layers.fc(input=x, size=10,
                param_attr=fluid.initializer.TruncatedNormal(loc=0.0, scale=2.0))
    rD   ra   r   c                    r   r%   )rE   r   r*   r   r   re   r   rJ   r&   r)   r*     r   z#TruncatedNormalInitializer.__init__Nc                 C   s  |  |}t|tjsJ t|tjsJ | jdkr|jj| _|jt	j
jt	j
jfv rFt	j
j}|jtdd|jdg|j|t	j
jdd}n|j}|}t r}t|j| j| j| j|t }|jt	j
jt	j
jfv rvt||j}|| dS || dS t rtd|jd	|d
| jd| jd| j
}|jt	j
jt	j
jfv rt|d|jd|j}|| dS || dS |jdd|i|j|| j| j| jddd}|jt	j
jt	j
jfv r|jdd|id|i|j|jdd ||_ |S )a_  Initialize the input tensor with TruncatedNormal distribution.

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

        Returns:
            The initialization op
        r   rr   truncated_gaussian_randomrs   Frt   Nr8   rL   r   r   rk   rx   ry   rO   r8   rL   r   r   rk   TrP   r|   r}   r~   r   )!r6   rU   r   rV   rW   re   r   r   rL   r   r   r   BF16r   r   r   r   r   ru   r8   r   r   r   r   r   r   r
   r|   r   r   r   r[   r\   r   r&   r&   r)   r,     sz   







z"TruncatedNormalInitializer.forwardr   r%   r^   r&   r&   rJ   r)   r     s    	r   c                       s,   e Zd ZdZd	 fdd	Zd
ddZ  ZS )r   a  
    This class implements the Xavier weight initializer from the paper
    `Understanding the difficulty of training deep feedforward neural
    networks <http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf>`_
    by Xavier Glorot and Yoshua Bengio.

    This initializer is designed to keep the scale of the gradients
    approximately same in all the layers. In case of Uniform distribution,
    the range is [-x, x], where

    .. math::

        x = \sqrt{\\frac{6.0}{fan\_in + fan\_out}}

    In case of Normal distribution, the mean is 0 and the standard deviation
    is

    .. math::

        \sqrt{\\frac{2.0}{fan\_in + fan\_out}}


    Args:
        uniform (bool,default True): whether to use uniform ,if False use normal distribution
        fan_in (float,default None): fan_in for Xavier initialization. If None, it is
                inferred from the variable.
        fan_out (float,default None): fan_out for Xavier initialization. If None, it is
                 inferred from the variable.
        seed (int): random seed

    Note:
        It is recommended to set fan_in and fan_out to None for most cases.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            queries = fluid.data(name='x', shape=[None,1], dtype='float32')
            fc = fluid.layers.fc(
                input=queries, size=10,
                param_attr=fluid.initializer.Xavier(uniform=False))

    TNr   c                    sB   |d usJ |d usJ t t|   || _|| _|| _|| _d S r%   )rE   r   r*   _uniform_fan_in_fan_outre   )r(   uniformr=   r>   rk   rJ   r&   r)   r*   0  s   
zXavierInitializer.__init__c                 C   s  |  |}t|tjsJ t|dg dd | |\}}| jdu r$|n| j}| jdu r.|n| j}| jdkr;|j	j
| _|jtjjksL|jtjjkrh| jshtjj}|jtdd|jdg|j|tjjdd	}n|j}|}t r| jrtd
t||  }	t rt|j||	 |	| jt  }nCt! rt"d|jd|	 d|	d| jd|
}n.tdt||  }
t rt  }t#|jd|
| j||}nt"#d|jd|ddd|
d| j
}|jtjjks|jtjjkr	| js	t rt$||j}nt! rt"$|d|jd|j}|%| dS |%| dS | jr5td
t||  }	|j&di d|i|j||	 |	| jddd}ntdt||  }
|j&dd|i|j|jd|
| jddd}|jtjjksh|jtjjkrz| jsz|j&dd|id|i|j|jdd  ||_'|S )!aX  Initialize the input tensor with Xavier initialization.

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

        Returns:
            The initialization op
        rO   ro   Zxavier_initNr   rr   rs   Frt   g      @r8   rv   rw   rk   rL          @rD   r   r   rx   ry   rq   r8   rL   rv   rw   rk   Trz   r   r   rP   r|   r}   r~   r   )(r6   rU   r   rW   r   r?   r   r   re   r   r   rL   r   r   r   r   r   r   r   r   r   r   ru   r8   r   r   mathsqrtrY   r   r   rq   r
   r   r   r   r|   r   r[   r\   )r(   r<   r0   f_inf_outr=   r>   ry   r   limitr   r]   r   r\   r&   r&   r)   r,   9  s   










zXavierInitializer.forward)TNNr   r%   r^   r&   r&   rJ   r)   r     s    ,	r   c                       s6   e Zd ZdZ					d
 fdd	Zddd	Z  ZS )r!   a  Implements the MSRA initializer a.k.a. Kaiming Initializer

    This class implements the weight initialization from the paper
    `Delving Deep into Rectifiers: Surpassing Human-Level Performance on
    ImageNet Classification <https://arxiv.org/abs/1502.01852>`_
    by Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun. This is a
    robust initialization method that particularly considers the rectifier
    nonlinearities. In case of Uniform distribution, the range is [-x, x], where

    .. math::

        x = gain \times \sqrt{\frac{3}{fan\_in}}

    In case of Normal distribution, the mean is 0 and the standard deviation
    is

    .. math::

        \frac{gain}{\sqrt{{fan\_in}}}

    Args:
        uniform (bool, optional): whether to use uniform or normal distribution
        fan_in (float32|None, optional): fan_in (in_features) of trainable Tensor, If None, it will be infered automaticly. If you don't want to use in_features of the Tensor, you can set the value of 'fan_in' smartly by yourself. default is None.
        seed (int32, optional): random seed.
        negative_slope (float, optional): negative_slope (only used with leaky_relu). default is 0.0.
        nonlinearity(str, optional): the non-linear function. default is relu.

    Note:
        It is recommended to set fan_in to None for most cases.

    Examples:
        .. code-block:: python

            import paddle
            import paddle.fluid as fluid
            paddle.enable_static()
            x = fluid.data(name="data", shape=[8, 32, 32], dtype="float32")
            fc = fluid.layers.fc(input=x, size=10,
                param_attr=fluid.initializer.MSRA(uniform=False))

    TNr   reluc                    sH   |dusJ |dusJ t t|   || _|| _|| _|| _|| _dS )z(Constructor for MSRAInitializer
        N)rE   r!   r*   r   r   re   _negative_slope_nonlinearity)r(   r   r=   rk   Znegative_slopenonlinearityrJ   r&   r)   r*     s   
zMSRAInitializer.__init__c                 C   s   |  |}t|tjsJ t|tjsJ | |\}}| jdu r#|n| j}| jdkr0|jj	| _|j
tjjksA|j
tjjkr]| js]tjj}|jtdd|jdg|j|tjjdd}n|j
}|}t r| jrt| j| j}|tdt|  }	t rt !|j||	 |	| jt" }nIt#!d	|jd
|	 d|	d| jdt$|
}n5t| j| j}|tt| }
t rt" }t %|jd|
| j||}nt#%d	|jdt$|ddd|
d| j
}|j
tjjks|j
tjjkr| jst rt &||j
}nt' rt#&|d|j
d|j
}|(| dS |(| dS | jr@t| j| j}|tdt|  }	|j)di d|i|jt$||	 |	| jddd}n%t| j| j}|tt| }
|j)dd|i|jt$|d|
| jddd}|j
tjjksy|j
tjjkr| js|j)dd|id|i|j
|j
dd ||_*|S )aV  Initialize the input tensor with MSRA initialization.

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

        Returns:
            The initialization op
        Nr   rr   Z
masra_initrs   Frt   g      @r8   rv   rw   rk   rL   rD   r   r   rx   ry   rq   rO   r   Trz   r   r   rP   r|   r}   r~   r   )+r6   rU   r   rV   rW   r?   r   re   r   r   rL   r   r   r   r   r   r   r   r   r   r   ru   r8   r   r   calculate_gainr   r   r   r   rY   r   r   rq   r
   r   rZ   r   r|   r   r   r[   r\   )r(   r<   r0   r   r   r=   ry   r   Zgainr   r   r]   r   r\   r&   r&   r)   r,     s   








zMSRAInitializer.forward)TNr   r   r   r%   r^   r&   r&   rJ   r)   r!     s    +r!   c                       *   e Zd ZdZ fddZdddZ  ZS )r    a  
    This initializer can be used in transposed convolution operator to
    act as upsampling. Users can upsample a feature map with shape of
    (B, C, H, W) by any integer factor. The usage is:

    Examples:

        .. code-block:: python

            import math

            import paddle
            import paddle.nn as nn
            from paddle.regularizer import L2Decay

            factor = 2
            C = 2
            B = 8
            H = W = 32
            w_attr = paddle.ParamAttr(learning_rate=0.,
                                      regularizer=L2Decay(0.),
                                      initializer=nn.initializer.Bilinear())
            data = paddle.rand([B, 3, H, W], dtype='float32')
            conv_up = nn.Conv2DTranspose(3,
                                         out_channels=C,
                                         kernel_size=2 * factor - factor % 2,
                                         padding=int(
                                             math.ceil((factor - 1) / 2.)),
                                         stride=factor,
                                         weight_attr=w_attr,
                                         bias_attr=False)
            x = conv_up(data)

    Where, `out_channels=C` and `groups=C` means this is channel-wise transposed
    convolution. The filter shape will be (C, 1, K, K) where K is `kernel_size`,
    This initializer will set a (K, K) interpolation kernel for every channel
    of the filter identically. The resulting shape of the output feature map
    will be (B, C, factor * H, factor * W). Note that the learning rate and the
    weight decay are set to 0 in order to keep coefficient values of bilinear
    interpolation unchanged during training.

    c                    s   t t|   dS )z-Constructor for BilinearInitializer.
        N)rE   r    r*   r'   rJ   r&   r)   r*     s   zBilinearInitializer.__init__Nc              	   C   s  |  |}t|tjstdt|tjstd|j}t|dkr&td|d |d kr2tdtj	t
|jdd	}|d }t|d
 }d| d |d  d
|  }tt
|D ]"}|| }	|| | }
dt|	| |  dt|
| |   ||< q]t||}|jtjjtjjtjjfv rtjj}|jtdd|jdg|j|tjjdd}n|j}|}|tjjkrd}dd |jD }ntd|jt
|dkrtdt r4t rt !|t"|||t#  nt$ rt%&|dt"|d||| |jtjjtjjtjjfv r-t rt '||j}nt$ r&t%'|d|jd|j}|(| dS |(| dS |j)dd|gid|dt"|||id}|jtjjtjjtjjfv rh|j)dd |id|i|j|jd!d" ||_*|S )#aZ  Initialize the input tensor with Bilinear initialization.

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

        Returns:
            The initialization op
        zvar must be framework.Variable.zblock must be framework.Block.   zthe length of shape must be 4.r7      z#shape[2] must be equal to shape[3].rp   )rL   r   r   rr   Zbilinear_initrs   Frt   fp32_valuesc                 S      g | ]}t |qS r&   rY   .0vr&   r&   r)   
<listcomp>      z/BilinearInitializer.forward.<locals>.<listcomp>Unsupported dtype %si   zThe size of input is too big. r8   rL   rx   ry   Nassign_valuerO   )rQ   rR   rS   r|   r}   r~   r   )+r6   rU   r   rV   
ValueErrorrW   r8   r9   r:   Zzerosr;   ceilrangeabsZreshaperL   r   r   r   r   ZFP64r   r   r   r   r   ru   r   flat	TypeErrorr   r   r   assign_value_listr
   r   r   r   r|   r   r[   r\   )r(   r<   r0   r8   weightsizefcixyry   r   
value_namevaluesr   r\   r&   r&   r)   r,     s   
.



zBilinearInitializer.forwardr%   r^   r&   r&   rJ   r)   r    a  s    +r    c                       r   )r"   a%  Init an parameter with an numpy array
    This op initialize the variable by numpy array.

    Args:
        value (numpy): numpy array to initialize the variable

    Returns:
        A Tensor variable initialized by numpy.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            import numpy
            x = fluid.data(name="x", shape=[2, 1], dtype='float32')
            fc = fluid.layers.fc(input=x, size=10,
                param_attr=fluid.initializer.NumpyArrayInitializer(numpy.array([1,2])))
    c                    s0   dd l }t||jsJ tt|   || _d S rb   )numpyrU   ZndarrayrE   r"   r*   rF   )r(   rH   r   rJ   r&   r)   r*     s   
zNumpyArrayInitializer.__init__Nc           
   	   C   s  |  |}t|tjsJ t|tjsJ |jtjjtjj	fv rBtjj
}| jd}|jtdd|jdg|j|tjjdd}n|}|j}| j}|tjj
kr[d}dd	 |jD }n|tjjkrld
}dd	 |jD }ntd| jj| jjdkr}tdt rt rt|t| jj||t  nt rt |dt| jjd||| |jtjjtjj	fv rt rt!||j}nt rt!|d|jd|j}|"| dS |"| dS |j#dd|id|dt| jj||idd}	|jtjjtjj	fv r
|j#dd|id|i|j|jdd |	|_$|	S )aN  Initialize the input tensor with Numpy array.

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

        Returns:
            The initialization op
        rp   rr   Znumpy_array_initrs   Frt   r   c                 S   r   r&   r   r   r&   r&   r)   r   9  r   z1NumpyArrayInitializer.forward.<locals>.<listcomp>Zint32_valuesc                 S   r   r&   )rZ   r   r&   r&   r)   r   <  r   r   i   @zXThe size of input is too big. Please consider saving it to file and 'load_op' to load itr8   rL   rx   ry   Nr   rO   TrP   r|   r}   r~   r   )%r6   rU   r   rV   rW   rL   r   r   r   r   r   rF   Zastyper   r   r   r   ru   r8   r   r   ZINT32r   r   r   r   r   r   r   r
   r   r   r   r|   r   r[   r\   )
r(   r<   r0   ry   Znp_valuer   r   r   r   r\   r&   r&   r)   r,     s   



	zNumpyArrayInitializer.forwardr%   r^   r&   r&   rJ   r)   r"     s    r"   c                 C   s8   t | dttdfd | at |dttdfd |adS )a  
    This API is used to set up global model parameter initializer in framework.

    After this API is invoked, the global initializer will takes effect in subsequent code.

    The model parameters include ``weight`` and ``bias`` . In the framework, they correspond 
    to ``paddle.ParamAttr`` , which is inherited from ``paddle.Tensor`` , and is a persistable Variable.
    This API only takes effect for model parameters, not for variables created through apis such as 
    :ref:`api_fluid_layers_create_global_var` , :ref:`api_fluid_layers_create_tensor`.
    
    If the initializer is also set up by ``param_attr`` or ``bias_attr`` when creating a network layer,
    the global initializer setting here will not take effect because it has a lower priority.

    If you want to cancel the global initializer in framework, please set global initializer to ``None`` .

    Args:
        weight_init (Initializer): set the global initializer for ``weight`` of model parameters.
        bias_init (Initializer, optional): set the global initializer for ``bias`` of model parameters. 
            Default: None.

    Returns:
        None

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn as nn

            nn.initializer.set_global_initializer(nn.initializer.Uniform(), nn.initializer.Constant())
            x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.)

            # The weight of conv1 is initialized by Uniform
            # The bias of conv1 is initialized by Constant
            conv1 = nn.Conv2D(4, 6, (3, 3))
            y_var1 = conv1(x_var)

            # If set param_attr/bias_attr too, global initializer will not take effect
            # The weight of conv2 is initialized by Xavier
            # The bias of conv2 is initialized by Normal
            conv2 = nn.Conv2D(4, 6, (3, 3), 
                weight_attr=nn.initializer.XavierUniform(),
                bias_attr=nn.initializer.Normal())
            y_var2 = conv2(x_var)

            # Cancel the global initializer in framework, it will takes effect in subsequent code
            nn.initializer.set_global_initializer(None)
    weight_initNr#   	bias_init)r   r$   rQ   _global_weight_initializer__global_bias_initializer_)r   r   r&   r&   r)   r#   n  s   2r#   c                   C      t S zP
    Return the global weight initializer, The user doesn't need to use it.
    )r   r&   r&   r&   r)   _global_weight_initializer     r   c                   C   r   r   )r   r&   r&   r&   r)   _global_bias_initializer  r   r   c                 C   s   |du rd}nt |tttfsJ t|}dddddddddtdtdd|d   dd}| | v r:||  S td	| )
a  
    Get the recommended ``gain`` value of some nonlinearity function. ``gain`` value can be used in some 
    ``paddle.nn.initializer`` api to adjust the initialization value.

    Args:
        nonlinearity(str): name of nonlinearity activation function. If it is a linear function, such as: 
            `linear/conv1d/conv2d/conv3d/conv1d_transpose/conv2d_transpose/conv3d_transpose` , 1.0 will be returned.
        param(bool|int|float, optional): optional parameter for somme nonlinearity function. Now, it only applies to 
            'leaky_relu'. Default: None, it will be calculated as 0.01 in the formula.

    Returns:
        A float value, which is the recommended gain for this nonlinearity function.

    Examples:
        .. code-block:: python

            import paddle
            gain = paddle.nn.initializer.calculate_gain('tanh') # 5.0 / 3
            gain = paddle.nn.initializer.calculate_gain('leaky_relu', param=1.0) # 1.0 = math.sqrt(2.0 / (1+param^2))
            initializer = paddle.nn.initializer.Orthogonal(gain)

    Ng{Gz?r   g?r   r7   g      ?)ZsigmoidZlinearZconv1dZconv2dZconv3dZconv1d_transposeZconv2d_transposeZconv3d_transposetanhr   Z
leaky_reluZseluz/nonlinearity function {} is not suppported now.)	rU   boolrZ   rY   r   r   keysr   format)r   r/   Zrecommended_gainr&   r&   r)   r     s0   r   r%   )2
__future__r   r   r4    r   r   r   r   r   r	   r
   Z	lazy_initr   r   r   r:   r   r   Zdata_feederr   r   r   Zpaddler   r   __all__r   r   objectr$   r   r   r   r   r   r!   r    r"   r#   r   r   r   r   r   r   r   r   r   r   r&   r&   r&   r)   <module>   sR   TI Ph - 3 
p=
;