Ë
    •\;jô1  ã                   óV   — d dl Z d dl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é   )Ú	framework)Úin_dygraph_modeé   )Ú	Optimizerc                   óR   ‡ — e Zd ZdZdZdZdZ	 	 	 	 	 	 	 	 d	ˆ fd„	Zd„ Zd„ Z	d„ Z
ˆ xZS )
ÚRMSPropa­  
    Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning
    rate method. The original slides proposed RMSProp: Slide 29 of
    http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf .

    The original equation is as follows:

    ..  math::

        r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2

        w & = w - \frac{\eta} {\sqrt{r(w,t) + \epsilon}} \nabla Q_{i}(w)

    The first equation calculates moving average of the squared gradient for
    each weight. Then dividing the gradient by :math:`sqrt{v(w,t)}`.

    In some cases, adding a momentum term :math: `\\beta` is beneficial.
    In our implementation, Nesterov momentum is used:

    ..  math::

        r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2

        v(w, t) & = \beta v(w, t-1) + \frac{\eta} {\sqrt{r(w,t) +
            \epsilon}} \nabla Q_{i}(w)

        w & = w - v(w, t)

    if centered is True:

    ..  math::

        r(w, t) & = \rho r(w, t-1) + (1 - \rho)(\nabla Q_{i}(w))^2

        g(w, t) & = \rho g(w, t-1) + (1 - \rho)\nabla Q_{i}(w)

        v(w, t) & = \beta v(w, t-1) + \frac{\eta} {\sqrt{r(w,t) - (g(w, t))^2 +
            \epsilon}} \nabla Q_{i}(w)

        w & = w - v(w, t)

    where, :math:`\rho` is a hyperparameter and typical values are 0.9, 0.95
    and so on. :math:`\beta` is the momentum term. :math:`\epsilon` is a
    smoothing term to avoid division by zero, usually set somewhere in range
    from 1e-4 to 1e-8.


    Parameters:
        learning_rate (float|LRScheduler): The learning rate used to update ``Parameter``.
          It can be a float value or a LRScheduler.
        rho(float, optional): rho is :math:`\rho` in equation, default is 0.95.
        epsilon(float, optional): :math:`\epsilon` in equation is smoothing term to
          avoid division by zero, default is 1e-6.
        momentum(float, optional): :math:`\beta` in equation is the momentum term,
          default is 0.0.
        centered(bool, optional): If True, gradients are normalized by the estimated variance of
          the gradient; if False, by the uncentered second moment. Setting this to
          True may help with training, but is slightly more expensive in terms of
          computation and memory. Defaults to False.
        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): This parameter is used by developers to print debugging information.
          For details, please refer to :ref:`api_guide_Name`. Default is None.

    Examples:
            .. code-block:: python

                >>> import paddle

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

                >>> rmsprop = paddle.optimizer.RMSProp(learning_rate=0.1,
                ...                     parameters=linear.parameters(),
                ...                             weight_decay=0.01)
                >>> out.backward()
                >>> rmsprop.step()
                >>> rmsprop.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)
                >>> rmsprop = paddle.optimizer.RMSProp(
                ...     learning_rate=0.1,
                ...     parameters=[{
                ...         'params': linear_1.parameters()
                ...     }, {
                ...         'params': linear_2.parameters(),
                ...         'weight_decay': 0.001,
                ...         'learning_rate': 0.1
                ...     }],
                ...     weight_decay=0.01
                ... )
                >>> out.backward()
                >>> rmsprop.step()
                >>> rmsprop.clear_grad()
    ÚmomentumÚmean_squareÚ	mean_gradc
                 óp  •— |€t        d«      ‚|€t        d«      ‚|€t        d«      ‚|€t        d«      ‚d|k  st        d«      ‚d|k  st        d«      ‚d|k  st        d«      ‚t        ‰
| �	  |||||	¬	«       d
| _        || _        || _        || _        || _        d| _        i | _	        ||||dœ| _
        y )Nzlearning_rate is not set.zrho is not set.zepsilon is not set.zmomentum is not set.ç        z.Invalid value of epsilon, expect epsilon >= 0.z0Invalid value of momentum, expect momentum >= 0.z&Invalid value of rho, expect rho >= 0.)Úlearning_rateÚ
parametersÚweight_decayÚ	grad_clipÚnameÚrmspropF)ÚrhoÚepsilonr   Úcentered)Ú
ValueErrorÚsuperÚ__init__ÚtypeÚ_rhoÚ_epsilonÚ	_momentumÚ	_centeredÚ_multi_precisionÚ_master_weightsÚ_default_dict)Úselfr   r   r   r   r   r   r   r   r   Ú	__class__s             €úaG:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/optimizer/rmsprop.pyr   zRMSProp.__init__–   sð   ø€ ð Ð ÜÐ8Ó9Ð9Øˆ;ÜÐ.Ó/Ð/Øˆ?ÜÐ2Ó3Ð3ØÐÜÐ3Ó4Ð4Ø�gŠ~ÜÐMÓNÐNØ�hŠÜÐOÓPÐPØ�cŠzÜÐEÓFÐFä‰ÑØ'Ø!Ø%ØØð 	ô 	
ð ˆŒ	ØˆŒ	ØˆŒØ!ˆŒØ!ˆŒØ %ˆÔØ!ˆÔàØØ Ø ñ	
ˆÕó    c                 ó¢  — t        |t        j                  «      st        d«      ‚t        |t        «      r|j                  d«      }|D �]ƒ  }|j                  | j                  v rŒ| j                  r¦| j                  |j                  «      r‹| j                  |«      }| j                  | j                  |«       | j                  | j                  |«       | j                  | j                  |«       | j                  j!                  |j                  «       ŒÏ| j                  |j                  «      r!| j                  st#        j$                  d«       | j                  | j                  |«       | j                  | j                  |«       | j                  | j                  |«       | j                  j!                  |j                  «       �Œ† y )Nú)block is not instance of framework.Block.Úparamsz“Accumulating with FP16 in optimizer can lead to poor accuracy or slow convergence.Consider using multi_precision=True option of the Lars optimizer.)Ú
isinstancer   ÚBlockÚ	TypeErrorÚdictÚgetr   Ú_already_create_accumulaterr!   Ú_is_dtype_fp16_or_bf16ÚdtypeÚ_create_master_weightÚ_add_accumulatorÚ_momentum_acc_strÚ_mean_square_acc_strÚ_mean_grad_acc_strÚaddÚwarningsÚwarn)r$   Úblockr   ÚpÚmaster_ps        r&   Ú_create_accumulatorszRMSProp._create_accumulatorsÇ   sc  € Ü˜%¤§¡Ô1ÜÐGÓHÐHä�j¤$Ô'Ø#Ÿ™¨Ó1ˆJäˆAØ�v‰v˜×9Ñ9Ñ9Øà×$Ò$¨×)DÑ)DÀQÇWÁWÔ)MØ×5Ñ5°aÓ8�Ø×%Ñ% d×&<Ñ&<¸hÔGØ×%Ñ% d×&?Ñ&?ÀÔJØ×%Ñ% d×&=Ñ&=¸xÔHØ×0Ñ0×4Ñ4°Q·V±VÔ<Øà×+Ñ+¨A¯G©GÔ4Ø×-Ò-ä—‘ðXôð ×!Ñ! $×"8Ñ"8¸!Ô<Ø×!Ñ! $×";Ñ";¸QÔ?Ø×!Ñ! $×"9Ñ"9¸1Ô=Ø×,Ñ,×0Ñ0°·±Ö8ñ- r'   c                 ó¶  — t        |t        j                  «      st        d«      ‚t        |t        «      r| j                  |«      }| j                  | j                  |d   «      }| j                  | j                  |d   «      }| j                  | j                  |d   «      }| j                  xr | j                  |d   j                  «      }|r| j                  |d   j                     nd }t        «       r^t!        j"                  |d   ||d   || j%                  |«      ||| j&                  | j(                  | j*                  | j,                  |«       y |d   |d   |||| j%                  |«      dœ}|d   |||dœ}	|r
||d<   ||	d<   |j/                  | j0                  ||	| j&                  | j(                  | j*                  | j,                  dœd	¬
«      }
|
S )Nr)   r   r   )ÚParamÚGradÚMomentÚ
MeanSquareÚMeanGradÚLearningRate)ÚParamOutÚ	MomentOutÚMeanSquareOutÚMeanGradOutÚMasterParamÚMasterParamOut)r   Údecayr   r   T)r   ÚinputsÚoutputsÚattrsÚstop_gradient)r+   r   r,   r-   r.   Ú_update_param_groupÚ_get_accumulator_masterr5   r6   r7   r!   r1   r2   r"   r   r   r   Úrmsprop_Ú_create_param_lrr   r   r   r    Ú	append_opr   )r$   r;   Úparam_and_gradÚmomentum_accÚmean_square_accÚmean_grad_accÚfind_masterÚmaster_weightrM   rN   Ú
rmsprop_ops              r&   Ú_append_optimize_opzRMSProp._append_optimize_opæ   s  € Ü˜%¤§¡Ô1ÜÐGÓHÐHä�n¤dÔ+Ø!×5Ñ5°nÓEˆNà×3Ñ3Ø×"Ñ" N°1Ñ$5ó
ˆð ×6Ñ6Ø×%Ñ% ~°aÑ'8ó
ˆð ×4Ñ4Ø×#Ñ# ^°AÑ%6ó
ˆð ×+Ñ+ò 
°×0KÑ0KØ˜1Ñ×#Ñ#ó1
ˆñ
 ð × Ñ  °Ñ!2×!7Ñ!7Ò8àð 	ô ÔÜ�O‰OØ˜qÑ!ØØ˜qÑ!ØØ×%Ñ% nÓ5ØØØ—‘Ø—	‘	Ø—‘Ø—‘Øôð ð (¨Ñ*Ø& qÑ)Ø&Ø-Ø)Ø $× 5Ñ 5°nÓ EñˆFð +¨1Ñ-Ø)Ø!0Ø,ñ	ˆGñ Ø(5��}Ñ%Ø,9�Ð(Ñ)ØŸ™Ø—Y‘YØØà#Ÿ}™}Ø!ŸY™YØ $§¡Ø $§¡ñ	ð #ð )ó ˆJð Ðr'   c                 óH  — |j                  d| j                  d   «      | _        |j                  d| j                  d   «      | _        |j                  d| j                  d   «      | _        |j                  d| j                  d   «      | _        |j                  d«      }|S )Nr   r   r   r   r*   )r/   r#   r   r   r   r    )r$   r   s     r&   rQ   zRMSProp._update_param_group2  s”   € Ø"Ÿ™ y°$×2DÑ2DÀYÑ2OÓPˆŒØ—N‘N 5¨$×*<Ñ*<¸UÑ*CÓDˆŒ	Ø#Ÿ™Ø˜×*Ñ*¨:Ñ6ó
ˆŒð $Ÿ™Ø˜×*Ñ*¨:Ñ6ó
ˆŒð  —^‘^ HÓ-ˆ
ØÐr'   )gffffffî?g�íµ ÷Æ°>r   FNNNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r5   r6   r7   r   r>   r]   rQ   Ú__classcell__)r%   s   @r&   r
   r
      sO   ø„ ñuðn #ÐØ(ÐØ$Ðð
 ØØØØØØØõ/
òb9ò>JöX
r'   r
   )r9   Úpaddler   Úbaser   Úbase.frameworkr   Ú	optimizerr   Ú__all__r
   © r'   r&   Ú<module>rj      s)   ðó å å Ý ,Ý  à
€ôbˆiõ br'   