Ë
    •\;j<:  ã                   óf   — d dl Z d dlmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
mZ g Z G d	„ d
e«      Zy)é    N)Ú_C_opsé   )ÚcoreÚ	framework)Úno_grad)Ú
name_scopeé   )Ú	Optimizerc                   ó^   ‡ — e Zd ZdZdZdZdZ	 	 	 	 	 	 	 	 dˆ fd„	Zd„ Zd„ Z	d„ Z
d	„ Zd
„ Zˆ xZS )ÚAdamaxaè  
    The Adamax optimizer is implemented based on the Adamax Optimization
    in Section 7 of `Adam paper <https://arxiv.org/abs/1412.6980>`_.
    The Adamax algorithm is a variant of the Adam algorithm based on the infinite norm,
    which makes the learning rate update algorithm more stable and simple.

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

    .. math::

        t & = t + 1

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

        inf\_norm\_out & = max({\beta}_2 * inf\_norm + \epsilon, |grad|)

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

        param\_out & = param - learning\_rate * \frac{moment\_out}{inf\_norm\_out}

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

    The original paper does not have an ``epsilon`` attribute,
    it is added here for numerical stability to prevent the division by 0 error.

    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, optional): The exponential decay rate for the 1st moment estimates.
            The default value is 0.9.
        beta2 (float, optional): The exponential decay rate for the 2nd moment estimates.
            The default value is 0.999.
        epsilon (float, optional): A small float value for numerical stability.
            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 parameter groups
            represents the scale of base learning_rate.
            The default value is None in static graph mode, at this time all parameters will be updated.
        weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization.
            It can be a float value as coeff of L2 regularization or
            :ref:`api_paddle_regularizer_L1Decay`, :ref:`api_paddle_regularizer_L2Decay`.
            If a parameter has set regularizer using :ref:`api_paddle_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 clipping strategy, it's an instance of
            some derived class of ``GradientClipBase`` . There are three clipping strategies
            ( :ref:`api_paddle_nn_ClipGradByGlobalNorm` , :ref:`api_paddle_nn_ClipGradByNorm` ,
            :ref:`api_paddle_nn_ClipGradByValue` ). Default None, meaning there is no gradient clipping.
        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.

    **Notes**:
        **Currently, Adamax doesn't support sparse parameter optimization.**

    Examples:
        .. code-block:: python

            >>> import paddle

            >>> inp = paddle.uniform([10, 10], dtype="float32", min=-0.1, max=0.1)
            >>> linear = paddle.nn.Linear(10, 10)
            >>> inp = paddle.to_tensor(inp)
            >>> 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.Adamax(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.Adamax(
            ...     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()
    ÚmomentÚinf_normÚbeta1_pow_accc	                 ó`  •— |€J ‚|€J ‚|€J ‚|€J ‚d|cxk  rdk  st        d«      ‚ t        d«      ‚d|cxk  rdk  st        d«      ‚ t        d«      ‚d|k  st        d«      ‚t        ‰	| �	  |||||¬«       d| _        || _        || _        || _        d| _        i | _        |||d	œ| _	        y )
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ÚadamaxF)Úbeta1Úbeta2Úepsilon)
Ú
ValueErrorÚsuperÚ__init__ÚtypeÚ_beta1Ú_beta2Ú_epsilonÚ_multi_precisionÚ_master_weightsÚ_default_dict)
Úselfr   r   r   r   r   r   r   r   Ú	__class__s
            €ú`G:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/optimizer/adamax.pyr   zAdamax.__init__‹   sü   ø€ ð Ð(Ð(Ð(ØÐ Ð Ð ØÐ Ð Ð ØÐ"Ð"Ð"Ø�EŒ~˜AŠ~ÜÐMÓNÐNð ÜÐMÓNÐNØ�EŒ~˜AŠ~ÜÐMÓNÐNð ÜÐMÓNÐNØ�GŠ|ÜÐMÓNÐNÜ‰ÑØ'Ø!Ø%ØØð 	ô 	
ð ˆŒ	ØˆŒØˆŒØˆŒØ %ˆÔØ!ˆÔð ØØñ
ˆÕó    c                 óR  — |j                   }| j                  |«      r$t        j                  j                  j
                  }| j                  | j                  ||¬«       | j                  | j                  ||¬«       | j                  | j                  || j                  dg¬«       y )N)Údtyper	   )r   ÚparamÚ
fill_valueÚshape)r)   Ú_is_dtype_fp16_or_bf16r   ÚVarDescÚVarTypeÚFP32Ú_add_accumulatorÚ_moment_acc_strÚ_inf_norm_acc_strÚ_beta1_pow_acc_strr   )r$   ÚpÚ	acc_dtypes      r&   Ú_add_moments_powszAdamax._add_moments_pows´   s�   € Ø—G‘Gˆ	Ø×&Ñ& yÔ1ÜŸ™×,Ñ,×1Ñ1ˆIà×Ñ˜d×2Ñ2°A¸YÐÔGØ×Ñ˜d×4Ñ4°a¸yÐÔIØ×ÑØ×(Ñ(ØØ—{‘{Ø�#ð	 	õ 	
r'   c                 óH  — t        |t        «      r| j                  |«      }|D ]ü  }|j                  | j                  v rŒ| j
                  rc| j                  |j                  «      rH| j                  |«      }| j                  |«       | j                  j                  |j                  «       Œ‹| j                  |j                  «      r!| j
                  st        j                  d«       | j                  |«       | j                  j                  |j                  «       Œþ y )Nz˜Accumulating with FP16/BF16 in optimizer can lead to poor accuracy or slow convergence.Consider using multi_precision=True option of the Adam optimizer.)Ú
isinstanceÚdictÚ_update_param_groupr   Ú_already_create_accumulaterr!   r-   r)   Ú_create_master_weightr7   ÚaddÚwarningsÚwarn)r$   Úblockr   r5   Úmaster_ps        r&   Ú_create_accumulatorszAdamax._create_accumulatorsÂ   så   € Ü�j¤$Ô'Ø×1Ñ1°*Ó=ˆJó ˆAØ�v‰v˜×9Ñ9Ñ9ØØ×$Ò$¨×)DÑ)DÀQÇWÁWÔ)MØ×5Ñ5°aÓ8�Ø×&Ñ& xÔ0Ø×0Ñ0×4Ñ4°Q·V±VÔ<Øà×+Ñ+¨A¯G©GÔ4Ø×-Ò-ä—‘ðXôð ×"Ñ" 1Ô%Ø×,Ñ,×0Ñ0°·±Õ8ñ# r'   c                 ó�  — t        |t        j                  «      sJ ‚t        |t        «      r| j	                  |«      }| j                  | j                  |d   «      }| j                  | j                  |d   «      }| j                  xr | j                  |d   j                  «      }|r| j                  |d   j                     nd }| j                  | j                  |d   «      }t        j                  «       rSt        j                   |d   |d   | j#                  |«      ||||| j$                  | j&                  | j(                  |«       y |d   |d   | j#                  |«      |||dœ}|d   ||dœ}	|r
||d<   ||	d<   | j$                  | j&                  | j(                  |dœ}
|j+                  | j,                  ||	|
d¬	«      }|S )
Nr   r	   )ÚParamÚGradÚLearningRateÚMomentÚInfNormÚBeta1Pow)ÚParamOutÚ	MomentOutÚ
InfNormOutÚMasterParamÚMasterParamOut)r   r   r   Úmulti_precisionT©r   ÚinputsÚoutputsÚattrsÚstop_gradient)r9   r   ÚBlockr:   r;   Ú_get_accumulator_masterr2   r3   r!   r-   r)   r"   r   r4   Úin_dygraph_moder   Úadamax_Ú_create_param_lrr   r   r    Ú	append_opr   )r$   rA   Úparam_and_gradr   r   Úfind_masterÚmaster_weightr   rR   rS   rT   Ú	adamax_ops               r&   Ú_append_optimize_opzAdamax._append_optimize_opÚ   sõ  € Ü˜%¤§¡Ô1Ð1Ð1Ü�n¤dÔ+Ø!×5Ñ5°nÓEˆNà×-Ñ-Ø× Ñ  .°Ñ"3ó
ˆð ×/Ñ/Ø×"Ñ" N°1Ñ$5ó
ˆð ×+Ñ+ò 
°×0KÑ0KØ˜1Ñ×#Ñ#ó1
ˆñ
 ð × Ñ  °Ñ!2×!7Ñ!7Ò8àð 	ð ×4Ñ4Ø×#Ñ# ^°AÑ%6ó
ˆô ×$Ñ$Ô&Ü�N‰NØ˜qÑ!Ø˜qÑ!Ø×%Ñ% nÓ5ØØØØØ—‘Ø—‘Ø—‘Øõð" (¨Ñ*Ø& qÑ)Ø $× 5Ñ 5°nÓ EØ Ø#Ø)ñˆFð +¨1Ñ-Ø#Ø&ñˆGñ
 Ø(5��}Ñ%Ø,9�Ð(Ñ)àŸ™ØŸ™ØŸ=™=Ø#.ñ	ˆEð Ÿ™Ø—Y‘YØØØØ"ð (ó ˆIð Ðr'   c           
      óü  — t        |t        j                  «      sJ ‚t        |t        «      �r|D �]  \  }}|�|j                  du rŒt        j
                  «       rd| j                  | j                  |«      }t        «       5  t        j                  || j                  dd«      }|j                  |d«       ddd«       Œ�|j                  j                  j                  ||g«      5  t!        d«      5  | j                  | j                  |«      }|j#                  dd|id|id| j                  id¬	«       ddd«       ddd«       �Œ y|d
   D �]]  \  }}|�|j                  du rŒt        j
                  «       rˆ| j                  | j                  |«      }|j%                  d| j&                  d   «      | _        t        «       5  t        j                  || j                  dd«      }|j                  |d«       ddd«       Œ´|j                  j                  j                  ||g«      5  t!        d«      5  | j                  | j                  |«      }|j%                  d| j&                  d   «      | _        |j#                  dd|id|id| j                  id¬	«       ddd«       ddd«       �Œ` y# 1 sw Y   �Œ‹xY w# 1 sw Y   �ŒŠxY w# 1 sw Y   �Œ¥xY w# 1 sw Y   �Œ“xY w# 1 sw Y   ŒIxY w# 1 sw Y   �Œ¬xY w)zUpdate Beta1 Power accumulatorNTg        Fr   ÚscaleÚXÚOutrQ   Úparamsr   )r9   r   rV   ÚlistrU   rX   rW   r4   r   r   rb   r   Úcopy_rA   ÚprogramÚ_optimized_guardr   r[   Úgetr#   )r$   rA   Úparameters_and_gradsr*   Úgradr   Útmps          r&   Ú_finish_updatezAdamax._finish_update#  sÂ  € ä˜%¤§¡Ô1Ð1Ð1ÜÐ*¬DÕ1Ü3‘��tØ�< 5×#6Ñ#6¸$Ñ#>ØÜ×,Ñ,Ô.Ø$(×$@Ñ$@Ø×/Ñ/°ó%�Mô !�Ü$Ÿl™lØ)¨4¯;©;¸¸Tó˜ð &×+Ñ+¨C°Ô7÷	 #˜ð Ÿ™×,Ñ,×=Ñ=Ø ˜õä! (Õ+Ø(,×(DÑ(DØ ×3Ñ3°Uó)˜ð Ÿ™Ø!(Ø$'¨Ð#7Ø%*¨MÐ$:Ø#*¨D¯K©KÐ"8Ø*.ð (ô ÷	 ,÷ñ ñ  4ð6  4°HÕ=‘��tØ�< 5×#6Ñ#6¸$Ñ#>ØÜ×,Ñ,Ô.Ø$(×$@Ñ$@Ø×/Ñ/°ó%�Mð #7×":Ñ":Ø ×!3Ñ!3°GÑ!<ó#�D”Kô !�Ü$Ÿl™lØ)¨4¯;©;¸¸Tó˜ð &×+Ñ+¨C°Ô7÷	 #˜ð Ÿ™×,Ñ,×=Ñ=Ø ˜õä! (Õ+Ø(,×(DÑ(DØ ×3Ñ3°Uó)˜ð ';×&>Ñ&>Ø# T×%7Ñ%7¸Ñ%@ó'˜œð Ÿ™Ø!(Ø$'¨Ð#7Ø%*¨MÐ$:Ø#*¨D¯K©KÐ"8Ø*.ð (ô ÷ ,÷ñ ñ!  >÷) #™ú÷ ,Ñ+ú÷ñ ú÷0 #™ú÷ ,Ð+ú÷ñ úsb   Â5J1Ã'KÃ3AJ>Ä6KÇ5KÈ*K1È6A'K%ÊK1Ê1J;	Ê>KËKËK	ËK"	Ë%K.Ë*K1Ë1K;	c                 ó   — |j                  d| j                  d   «      | _        |j                  d| j                  d   «      | _        |j                  d| j                  d   «      | _        |j                  d«      }|S )Nr   r   r   re   )rj   r#   r   r   r    )r$   r   s     r&   r;   zAdamax._update_param_groupc  sm   € Ø —n‘n W¨d×.@Ñ.@ÀÑ.IÓJˆŒØ —n‘n W¨d×.@Ñ.@ÀÑ.IÓJˆŒØ"Ÿ™ y°$×2DÑ2DÀYÑ2OÓPˆŒØ—^‘^ HÓ-ˆ
ØÐr'   )gü©ñÒMbP?gÍÌÌÌÌÌì?g+‡ÙÎ÷ï?g:Œ0âŽyE>NNNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r2   r3   r4   r   r7   rC   r`   rn   r;   Ú__classcell__)r%   s   @r&   r   r      sY   ø„ ñjðV €OØ"ÐØ(Ðð ØØØØØØØõ'
òR
ò9ò0GòR>ö@r'   r   )r?   Úpaddler   Úbaser   r   Úbase.dygraphr   Úbase.frameworkr   Ú	optimizerr
   Ú__all__r   © r'   r&   Ú<module>r|      s,   ðó å ç "Ý "Ý 'Ý  à
€ôMˆYõ Mr'   