
    ёi4                        S SK Jr  S SKrS SKJr  S SKJr  S SKJrJ	r	  SSK
Jr  SSKJr  S	S
KJr  \(       a5  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S	SKJr   " S S\5      r/ r " S S\5      rg)    )annotationsN)TYPE_CHECKING)NotRequired)_C_opspir   )	framework)in_dynamic_or_pir_mode   )	Optimizer)Sequence)Tensor)GradientClipBase)LRScheduler)WeightDecayRegularizer)_ParameterConfigc                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   Srg	)
_RMSPropParameterConfig(   zNotRequired[float]epsilonmomentumrhozNotRequired[bool]centered N)__name__
__module____qualname____firstlineno____annotations____static_attributes__r       X/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/optimizer/rmsprop.pyr   r   (   s    ##$$##r!   r   c                     ^  \ rS rSrSrSrSrSr        S                   SU 4S jjjrS r	S r
S	 rS
rU =r$ )RMSProp2   aw  
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|None, 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 (int|float|WeightDecayRegularizer|None, optional): The strategy of regularization.
      It can be a int or 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|None, 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|None, 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

            >>> 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=[{  # type: ignore
            ...         '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()
r   mean_square	mean_gradc
                p  > Uc  [        S5      eUc  [        S5      eUc  [        S5      eUc  [        S5      eSU::  d  [        S5      eSU::  d  [        S5      eSU::  d  [        S5      e[        T
U ]	  UUUUU	S	9  S
U l        X l        X0l        X@l        XPl        SU l        0 U l	        UUUUS.U l
        g )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)r   r   r   r   )
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             r"   r2   RMSProp.__init__   s      899;.//?233344g~MNNhOPPczEFF'!% 	 	
 		!! %!  	
r!   c                   [        U[        R                  [        R                  45      (       d  [	        S5      e[        U[
        5      (       a  UR                  S5      nU GH  nUR                  U R                  ;   a  M   U R                  (       a  U R                  UR                  5      (       a  U R                  U5      nU R                  U R                  U5        U R                  U R                  U5        U R                  U R                   U5        U R                  R#                  UR                  5        M  U R                  UR                  5      (       a'  U R                  (       d  [$        R&                  " S5        U R                  U R                  U5        U R                  U R                  U5        U R                  U R                   U5        U R                  R#                  UR                  5        GM     g )Nblock is not instance of Block.paramszAccumulating with FP16 in optimizer can lead to poor accuracy or slow convergence.Consider using multi_precision=True option of the Lars optimizer.)
isinstancer	   Blockr   	TypeErrordictgetr.   _already_create_accumulatorr8   _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_accumulatorsRMSProp._create_accumulators   sx   %)//399!=>>=>>j$''#1JAvv999$$)D)DQWW)M)M55a8%%d&<&<hG%%d&?&?J%%d&=&=xH0044QVV<++AGG44--X !!$"8"8!<!!$";";Q?!!$"9"91=,,008- r!   c                
   [        U[        R                  [        R                  45      (       d  [	        S5      e[        U[
        5      (       a  U R                  U5      nU R                  U R                  US   5      nU R                  U R                  US   5      nU R                  U R                  US   5      nU R                  =(       a    U R                  US   R                  5      nU(       a  U R                  US   R                     OS n[!        5       (       a_  ["        R$                  " US   UUS   UU R'                  U5      UUU R(                  U R*                  U R,                  U R.                  U5        g US   US   UUUU R'                  U5      S.nUS   UUUS.n	U(       a  XxS'   XyS'   UR1                  U R2                  UU	U R(                  U R*                  U R,                  U R.                  S.S	S
9n
U
$ )Nr?   r   r   )ParamGradMoment
MeanSquareMeanGradLearningRate)ParamOut	MomentOutMeanSquareOutMeanGradOutMasterParamMasterParamOut)r   decayr   r   T)r3   inputsoutputsattrsstop_gradient)rA   r	   rB   r   rC   rD   _update_param_group_get_accumulator_masterrK   rL   rM   r8   rG   rH   r9   r.   r
   r   rmsprop__create_param_lrr5   r4   r6   r7   	append_opr3   )r;   rQ   param_and_gradmomentum_accmean_square_accmean_grad_accfind_mastermaster_weightrd   re   
rmsprop_ops              r"   _append_optimize_opRMSProp._append_optimize_op  s   %)//399!=>>=>>nd++!55nEN33""N1$5
 66%%~a'8
 44##^A%6
 ++ 
0K0K1##1

    !2!7!78 	 "##OOq!q!%%n5		  (*&q)&-) $ 5 5n EF +1-)!0,	G (5}%,9()YY#}}!YY $ $	 # ) J r!   c                H   UR                  SU R                  S   5      U l        UR                  SU R                  S   5      U l        UR                  SU R                  S   5      U l        UR                  SU R                  S   5      U l        UR                  S5      nU$ )Nr   r   r   r   r@   )rE   r:   r5   r4   r6   r7   )r;   r+   s     r"   rh   RMSProp._update_param_groupO  s    "y$2D2DY2OPNN5$*<*<U*CD	#**:6
 $**:6
  ^^H-
r!   )r7   r:   r5   r9   r6   r8   r4   r3   )gffffff?gư>r)   FNNNN)r*   zfloat | LRSchedulerr   floatr   rx   r   rx   r   boolr+   z;Sequence[Tensor] | Sequence[_RMSPropParameterConfig] | Noner,   z%float | WeightDecayRegularizer | Noner-   zGradientClipBase | Noner.   z
str | NonereturnNone)r   r   r   r   __doc__rK   rL   rM   r2   rT   rt   rh   r    __classcell__)r<   s   @r"   r$   r$   2   s    xt #($
  >B-11
*1
 1
 	1

 1
 1
 H1
 <1
 +1
 1
 
1
 1
f9>JX
 
r!   r$   )
__future__r   rO   typingr   typing_extensionsr   paddler   r   baser	   base.frameworkr
   	optimizerr   collections.abcr   r   paddle.nn.clipr   paddle.optimizer.lrr   paddle.regularizerr   r   r   __all__r$   r   r!   r"   <module>r      sY    #    )   3  (-//9+$"2 $ gi gr!   