o
    Qe                     @   s   d dl m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	 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Zd	d
lZd	d
lZd	dlmZmZ g ZG dd deZd
S )   )	Optimizer   )core)	framework)Variable_in_legacy_dygraphin_dygraph_mode)layers)unique_name)LayerHelper    N)base)defaultdict)_C_ops_legacy_C_opsc                       s   e Zd ZdZdZdZdZdZ						
	
	
				
d  fdd	Zdd Z	dd Z
dd Zdd Zdd Zejejdd Zdd Zdd Zdd Z  ZS )!Adama  
    The Adam optimizer uses an optimization described at the end
    of section 2 of `Adam paper <https://arxiv.org/abs/1412.6980>`_ ,
    it can dynamically adjusts the learning rate of each parameter using
    the 1st moment estimates and the 2nd moment estimates of the gradient.

    The parameter ``param_out`` update rule with gradient ``grad``:

    .. math::

        t & = t + 1

        moment\_1\_out & = {\beta}_1 * moment\_1 + (1 - {\beta}_1) * grad

        moment\_2\_out & = {\beta}_2 * moment\_2 + (1 - {\beta}_2) * grad * grad

        learning\_rate & = learning\_rate * \
                          \frac{\sqrt{1 - {\beta}_2^t}}{1 - {\beta}_1^t}

        param\_out & = param - learning\_rate * \frac{moment\_1}{\sqrt{moment\_2} + \epsilon}

    Related paper: `Adam: A Method for Stochastic Optimization <https://arxiv.org/abs/1412.6980>`_

    Args:
        learning_rate (float|LRScheduler, optional): The learning rate used to update ``Parameter``.
            It can be a float value or a LRScheduler. The default value is 0.001.
        beta1 (float|Tensor, optional): The exponential decay rate for the 1st moment estimates.
            It should be a float number or a Tensor with shape [1] and data type as float32.
            The default value is 0.9.
        beta2 (float|Tensor, optional): The exponential decay rate for the 2nd moment estimates.
            It should be a float number or a Tensor with shape [1] and data type as float32.
            The default value is 0.999.
        epsilon (float|Tensor, optional): A small float value for numerical stability.
            It should be a float number or a Tensor with shape [1] and data type as float32.
            The default value is 1e-08.
	parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \
	    This parameter is required in dygraph mode. And you can specify different options for \
            different parameter groups such as the learning rate, weight decay, etc, \
            then the parameters are list of dict. Note that the learning_rate in paramter groups \
            represents the scale of base learning_rate. \
	    The default value is None in static mode, at this time all parameters will be updated.
	weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \
	    It canbe a float value as coeff of L2 regularization or \
	    :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`.
	    If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \
	    the regularization setting here in optimizer will be ignored for this parameter. \
	    Otherwise, the regularization setting here in optimizer will take effect. \
	    Default None, meaning there is no regularization.
        grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of
            some derived class of ``GradientClipBase`` . There are three cliping strategies
            ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` ,
            :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping.
        lazy_mode (bool, optional): The official Adam algorithm has two moving-average accumulators.
            The accumulators are updated at every step. Every element of the two moving-average
            is updated in both dense mode and sparse mode. If the size of parameter is very large,
            then the update may be very slow. The lazy mode only update the element that has
            gradient in current mini-batch, so it will be much more faster. But this mode has
            different semantics with the original Adam algorithm and may lead to different result.
            The default value is False.
        multi_precision (bool, optional): Whether to use multi-precision during weight updating. Default is false.
        use_multi_tensor (bool, optional): Whether to use multi-tensor strategy to update all parameters at once . Default is false.
        name (str, optional): Normally there is no need for user to set this property.
            For more information, please refer to :ref:`api_guide_Name`.
            The default value is None.

    Examples:
        .. code-block:: python

            import paddle

            linear = paddle.nn.Linear(10, 10)
            inp = paddle.rand([10,10], dtype="float32")
            out = linear(inp)
            loss = paddle.mean(out)
            adam = paddle.optimizer.Adam(learning_rate=0.1,
                    parameters=linear.parameters())
            out.backward()
            adam.step()
            adam.clear_grad()

        .. code-block:: python

            # Adam with beta1/beta2 as Tensor and weight_decay as float
            import paddle

            linear = paddle.nn.Linear(10, 10)
            inp = paddle.rand([10,10], dtype="float32")
            out = linear(inp)
            loss = paddle.mean(out)

            beta1 = paddle.to_tensor([0.9], dtype="float32")
            beta2 = paddle.to_tensor([0.99], dtype="float32")

            adam = paddle.optimizer.Adam(learning_rate=0.1,
                    parameters=linear.parameters(),
                    beta1=beta1,
                    beta2=beta2,
                    weight_decay=0.01)
            out.backward()
            adam.step()
            adam.clear_grad()

            #Note that the learning_rate of linear_2 is 0.01.
            linear_1 = paddle.nn.Linear(10, 10)
            linear_2 = paddle.nn.Linear(10, 10)
            inp = paddle.uniform(shape=[10, 10], min=-0.1, max=0.1)
            out = linear_1(inp)
            out = linear_2(out)
            loss = paddle.mean(out)
            adam = paddle.optimizer.Adam(
                learning_rate=0.1,
                parameters=[{
                    'params': linear_1.parameters()
                }, {
                    'params': linear_2.parameters(),
                    'weight_decay': 0.001,
                    'learning_rate': 0.1,
                    'beta1': 0.8
                }],
                weight_decay=0.01,
                beta1=0.9)                   
            out.backward()
            adam.step()
            adam.clear_grad()

    moment1moment2beta1_pow_accbeta2_pow_accMbP??+?:0yE>NFc                    sT  |d usJ |d usJ |d usJ |d usJ t |ts/d|  kr*dk s/td tdt |tsFd|  krAdk sFtd tdt |tsSd|ksStdtt| j|||||d d| _|| _|| _|| _	|| _
|	| _i | _||||d| _|
| _| jr|  | _|  | _|  | _|  | _|  | _|  | _d | jd	< d S d S )
Nr   r   z.Invaild value of beta1, expect beta1 in [0,1).z.Invaild value of beta2, expect beta2 in [0,1).z.Invaild value of epsilon, expect epsilon >= 0.)learning_rate
parametersweight_decay	grad_clipnameadam)beta1beta2epsilon	lazy_modeFP32_LODTensor)
isinstancer   
ValueErrorsuperr   __init__type_beta1_beta2_epsilon
_lazy_mode_multi_precision_master_weights_default_dictZ_use_multi_tensorZ_create_multi_tensor_dict_param_dict_moment1_dict_moment2_dict_beta1_pow_acc_dict_beta2_pow_acc_dict_master_weight_dict)selfr   r    r!   r"   r   r   r   r#   multi_precisionZuse_multi_tensorr   	__class__ ED:\Projects\ConvertPro\env\Lib\site-packages\paddle/optimizer/adam.pyr(      sp   









zAdam.__init__c                 C   s   |j | jv r| j|j  }|S t| jtsJ |j d }t|}tj||j	dddd}| jj
 }|jdd|gid|gi|jtjjjd	d
 || j|j < |S )NZ_fp32_masterr   float32T)r   shapevaluedtypeZpersistablecastXZOut)Zin_dtypeZ	out_dtype)r)   inputsoutputsattrs)r   r/   r%   helperr   r
   generater	   Zcreate_global_varr>   startup_programZglobal_block	append_opr@   r   VarDescVarTypeFP32)r7   paramvarvar_nameblockr;   r;   r<   _create_master_weight   s0   

	zAdam._create_master_weightc                 C   s~   | j dur| j d | }| jo|jtjjjk}|r| j|j n|}|j}|| j	vs0|| j	| vr8t
d||| j	| | S )a
  Utility function to fetch an accumulator for a parameter
        Args:
            name: name of the accumulator
            param: parameter variable for which accumulator is to be fetched
        Returns:
            accumulator variable for the parameter
        N_z.Accumulator {} does not exist for parameter {})_namer.   r@   r   rJ   rK   FP16r/   r   Z_accumulators	Exceptionformat)r7   r   rM   find_masterZtarget_paramtarget_namer;   r;   r<   _get_accumulator  s   

zAdam._get_accumulatorc              	   C   s   |j }|tjjjks|tjjjkrtjjj}| j| j||d | j| j	||d | j| j
||t| jtr6dn| jdgtjjjdd | j| j||t| jtrPdn| jdgtjjjdd d S )N)r@   r   r   cpu)r   rM   r@   Z
fill_valuer>   r)   Zdevicer   )r@   r   rJ   rK   rT   ZBF16rL   Z_add_accumulator_moment1_acc_str_moment2_acc_str_beta1_pow_acc_strr%   r*   r   
LOD_TENSOR_beta2_pow_acc_strr+   )r7   pZ	acc_dtyper;   r;   r<   _add_moments_pows  s8   



zAdam._add_moments_powsc                 C   s   t |tjsJ t |tr| |}|D ]-}| jr,|jtjj	j
kr,| |}| | q|jtjj	j
kr<| js<td | | qd S )NzAccumulating with FP16 in optimizer can lead to poor accuracy or slow convergence.Consider using multi_precision=True option of the Adam optimizer.)r%   r   Blockdict_update_param_groupr.   r@   r   rJ   rK   rT   rQ   ra   warningswarn)r7   rP   r   r`   Zmaster_pr;   r;   r<   _create_accumulators>  s    



zAdam._create_accumulatorsc                 C   s  t |tjsJ t |tr| |}| | j|d }| | j|d }| | j|d }| | j	|d }| j
oB|d jtjjjk}|rM| j|d j nd }| |}	t r| d}
t | jtsf| jn| j d}t | jtsw| jn| j d}t|d |d |	||||||
||| j| jd|d\}}}}}}d S t rt | jts| jn| j d}t | jts| jn| j d}t |d |d |	||||||d |||||d| jd| jddd	|d
|d|\}}}}}}d S |d g|d g|	g|g|g|g|gd}|d g|g|g|g|gd}| jd|d}t | jtr-| j|d< n| j|d	< t | jtr?| j|d< n| j|d
< t | jtrQ| j|d< n| j|d< |ra||d< ||d< |j!| j"|||dd}|S )Nr   	found_infr   i  Fr"   r#   min_row_size_to_use_multithreadr    r!   r8   ParamZGradZLearningRateZMoment1ZMoment2ZBeta1PowZBeta2PowZParamOutZ
Moment1OutZ
Moment2OutZBeta1PowOutZBeta2PowOut)r#   ri   r8   ZBeta1TensorZBeta2TensorZEpsilonTensorMasterParamMasterParamOutTr)   rC   rD   rE   stop_gradient)#r%   r   rb   rc   rd   rY   r[   r\   r]   r_   r.   r@   r   rJ   rK   rT   r/   r   _create_param_lrr   Z_get_auxiliary_varr*   r   numpyitemr+   r   Zadam_r,   r-   r   r   r   rI   r)   )r7   rP   param_and_gradr   r   r   r   rW   master_weightlrrh   r*   r+   rR   rC   rD   rE   Zadam_opr;   r;   r<   _append_optimize_opS  s   















zAdam._append_optimize_opc                 C   s:  t | jd tsXg }| jD ]?}|jrq| durL| }t r3t|dr2| r2| jdur2t	dnt|drE|
 rE| jdurEt	d|||f q| jdd|dd}dS t| jD ]=\}}tdd }|d	 D ]}|jrqqk| dur| }|d	 ||f qk|d
d | D  | jdd||d q]dS )av  
        Execute the optimizer and update parameters once.

        Returns:
            None

        Examples:
            .. code-block:: python

                import paddle

                a = paddle.rand([2,13], dtype="float32")
                linear = paddle.nn.Linear(13, 5)
                # This can be any optimizer supported by dygraph.
                adam = paddle.optimizer.Adam(learning_rate = 0.01,
                                            parameters = linear.parameters())
                out = linear(a)
                out.backward()
                adam.step()
                adam.clear_grad()
        r   Nis_selected_rowszNAdam don't support weight_decay with sparse parameters, please set it to None.
_is_sparse)ZlossrH   params_gradsparam_group_idxc                   S   s   t  S )N)listr;   r;   r;   r<   <lambda>+  s    zAdam.step.<locals>.<lambda>paramsc                 S      i | ]\}}|d kr||qS r~   r;   .0kvr;   r;   r<   
<dictcomp>3  s    zAdam.step.<locals>.<dictcomp>)r%   Z_parameter_listrc   rp   Z
_grad_ivarr   hasattrrx   ZregularizationRuntimeErrorry   appendZ_apply_optimize	enumerateZ_param_groupsr   updateitems)r7   rz   rM   Zgrad_varZoptimize_opsidxZparam_groupr;   r;   r<   step  sh   



z	Adam.stepc           	      C   sj  |  || |D ]}| | j|}| | j|}| | j|}| | j|}|jtjkr_| j	d | 
| | jd | 
| | jd | 
| | jd | 
| | jd | 
| q|jtjkr| j	d | 
| | jd | 
| | jd | 
| | jd | 
| | jd | 
| | jr| jd | 
| j|j  qd| jd< qtddS )a  
        All parameters used for optimizer (such as: parameters, master_weight, velocity_acc for momentum) calculations are grouped into a python list by data type (float16, float32).
        This function will be overridden in the corresponding optimizer file.
        Args:
            target_block: the block in which the loss tensor is present
            parameters: list of parameter tensors for the optimizer
        r$   FP16_LODTensorNzWNow multi_tensor_momentum only support fp32 and fp16 parameters and grad is LOD_TENSOR.)rg   rY   r[   r\   r]   r_   r@   paddler=   r1   r   r2   r3   r4   r5   float16r.   r6   r/   r   r&   )	r7   target_blockr   r{   rM   r   r   r   r   r;   r;   r<   _multi_tensor_init<  sp   
zAdam._multi_tensor_initc                 C   s  t |tjsJ g g d}g g d}t |trz|D ]_}|d du r"q|d jdu rx|d jtjkrQ|d jt	j
jjkrQ|d |d  | |}|d | q|d jtjkrx|d jt	j
jjkrx|d |d  | |}|d | qn||d D ]w}|d du rq~|d jdu rt }||d< |d	d
 | D  | |}|d jtjkr|d jt	j
jjkr|d |d  | |}|d | q~|d jtjkr|d jt	j
jjkr|d |d  | |}|d | q~ddg}	|	D ]S}
t| j|
 | dkrP| jo|
dk}t | jts| jn| j d}t | jts/| jn| j d}t r| j|
 }|durJ|| nd}t rt | j|
 | ||
 ||
 | j!|
 | | j"|
 | | j#|
 | | j$|
 | |||| j%|d\}}}}}}qt&'| j|
 | ||
 ||
 | j!|
 | | j"|
 | | j#|
 | | j$|
 | || j|
 | | j!|
 | | j"|
 | | j#|
 | | j$|
 | |d| j%d|d|d|\}}}}}}q| j|
 | ||
 ||
 | j!|
 | | j"|
 | | j#|
 | | j$|
 | d}| j|
 | | j!|
 | | j"|
 | | j#|
 | | j$|
 | d}| j%||d}|rF| j|
 | |d< | j|
 | |d< ||d< |j(d|||dd qdS )zM
        For Multi Tensor, append optimize merged_operator to block.
        )r$   r   r   Nr   Fr$   r   r~   c                 S   r   r   r;   r   r;   r;   r<   r     s
    z9Adam._append_optimize_multi_tensor_op.<locals>.<dictcomp>r"   r    r!   r8   rj   rl   )r"   r    r!   rm   rn   merged_adamTro   ))r%   r   rb   r|   rp   r@   r   r=   r)   r   rJ   rK   r^   r   rq   r   rc   r   r   rd   lenr1   r.   r*   r   rr   rs   r+   Z_non_static_moder6   r   r   Zmerged_adam_r2   r3   r4   r5   r,   r   r   rI   )r7   r   Zparameters_and_gradsr{   Z	grad_dictZlr_dictrt   rv   Zparam_grad_dictZmulti_tensor_listkeyrW   r*   r+   ru   rR   rC   rD   rE   r;   r;   r<    _append_optimize_multi_tensor_opz  s4  	















z%Adam._append_optimize_multi_tensor_opc                 C   s^   | d| jd | _| d| jd | _| d| jd | _| d| jd | _| d}|S )Nr    r!   r"   r#   r~   )getr0   r*   r+   r,   r-   )r7   r   r;   r;   r<   rd   -  s   

zAdam._update_param_group)r   r   r   r   NNNFFFN)__name__
__module____qualname____doc__r[   r\   r]   r_   r(   rQ   rY   ra   rg   rw   imperative_baseZno_gradr   Zdygraph_onlyr   r   r   rd   __classcell__r;   r;   r9   r<   r   "   s>    ~@  K> 4r   )Z	optimizerr   Zfluidr   r   Zfluid.frameworkr   r   r   r	   r
   Zfluid.layer_helperr   re   Zfluid.dygraphr   r   collectionsr   rr   nptimer   r   r   __all__r   r;   r;   r;   r<   <module>   s    