
    ͑iT&                        S SK Jr  S SKrS SKJrJr  S SKJr  S SKJr  SS/r	 " S S	5      r
 " S
 S\
5      r " S S\
5      rg)    )annotationsN)_C_opspir)	framework)in_dynamic_or_pir_modeL1DecayL2Decayc                  >    \ rS rSrSrSS jr      S	S jrS rSrg)
WeightDecayRegularizer   av  Base class for weight decay regularizers

Defines the common interface of weight-decay regularizers.
Weight-decay regularizers are added only during the backward
pass for faster regularization. They add operations to the network
that correspond to gradient of the regularization function.
Users should not use this class directly, but need to use one
of its implementations
c                    g N selfs    R/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/regularizer.py__init__WeightDecayRegularizer.__init__%   s        c                    [         e)z8Add corresponding weight decay operations to the networkNotImplementedError)r   paramgradblocks       r   __call__WeightDecayRegularizer.__call__(   s
     "!r   c                    [         e)zDebug stringr   r   s    r   __str__WeightDecayRegularizer.__str__.   s    !!r   r   N)returnNoner   paddle.Tensorr   r$   r   z	pir.Block)	__name__
__module____qualname____firstlineno____doc__r   r   r   __static_attributes__r   r   r   r   r      s.    """*7"@I""r   r   c                  T   ^  \ rS rSrSrSSU 4S jjjr      S	S jrS
S jrSrU =r	$ )r   3   a	  
Implement the L1 Weight Decay Regularization, which encourages the weights to be sparse.

It can be set in :ref:`api_paddle_ParamAttr` or ``optimizer`` (such as :ref:`api_paddle_optimizer_Momentum` ).
When set in ``ParamAttr`` , it only takes effect for trainable parameters in this layer. When set in
``optimizer`` , it takes effect for all trainable parameters. When set together, ``ParamAttr`` has
higher priority than ``optimizer`` , which means that for a trainable parameter, if regularizer is defined
in its ParamAttr, then the regularizer in Optimizer will be ignored. Otherwise the  regularizer
in Optimizer will be used.

In the implementation, the loss function of L1 Weight Decay Regularization is as follows:

.. math::

    loss = coeff * reduce\_sum(abs(x))

Args:
    coeff(float, optional): regularization coeff. Default:0.0.

Examples:
    .. code-block:: python
        :name: code-example1

        >>> # Example1: set Regularizer in optimizer
        >>> import paddle
        >>> from paddle.regularizer import L1Decay

        >>> linear = paddle.nn.Linear(10, 10)
        >>> inp = paddle.rand(shape=[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")
        >>> momentum = paddle.optimizer.Momentum(
        ...     learning_rate=0.1,
        ...     parameters=linear.parameters(),
        ...     weight_decay=L1Decay(0.0001))
        >>> back = out.backward()
        >>> momentum.step()
        >>> momentum.clear_grad()

    .. code-block:: python
        :name: code-example2

        >>> # Example2: set Regularizer in parameters
        >>> # Set L1 regularization in parameters.
        >>> # Global regularizer does not take effect on my_conv2d for this case.
        >>> from paddle.nn import Conv2D
        >>> from paddle import ParamAttr
        >>> from paddle.regularizer import L1Decay

        >>> my_conv2d = Conv2D(
        ...         in_channels=10,
        ...         out_channels=10,
        ...         kernel_size=1,
        ...         stride=1,
        ...         padding=0,
        ...         weight_attr=ParamAttr(regularizer=L1Decay(coeff=0.01)),
        ...         bias_attr=False)
c                8   > Uc   e[         TU ]  5         Xl        g r   superr   _coeffr   coeff	__class__s     r   r   L1Decay.__init__q          r   c                   [        U[        R                  [        R                  [        R
                  R                  45      (       d   e[        U[        R                  [        R                  45      (       d   e[        5       (       a8  [        R                  " U5      n[        R                  " X@R                  SS5      $ UR                  UR                  UR                  UR                   S9nUR                  UR                  UR                  UR                   S9nUR#                  SSU0SU0S9  UR#                  SSU0SU0SU R                  0S	9  U$ )
a  Add L1 weight decay ops to network

Adds L1 weight decay ops.
L1WeightDecay = reg_coeff * sign(parameter)

Args:
    param: parameter variable for which regularization is applied
    block: block in which variable is to be created

Returns:
    new variable for weight decay
        Tdtypeshape	lod_levelsignXOut)typeinputsoutputsscaler?   r@   rA   attrs)
isinstancer   Variabler   ValuecoreParameterMetaBlockr   r   r<   rB   r0   
create_varr9   r:   r;   	append_op)r   r   r   r   r<   decays         r   r   L1Decay.__call__v   s6   $ I&&		3883I3IJ
 
 	
 
 %)//399!=>>>>!##;;u%D<<kk3==##kk $ D $$kk % E OOS%L5$-  
 OOT{,	   Lr   c                "    SU R                   S 3$ )NzL1Decay, coeff=fr0   r   s    r   r   L1Decay.__str__        Q00r   rQ   r7   r2   floatr!   r"   r#   r!   str
r%   r&   r'   r(   r)   r   r   r   r*   __classcell__r3   s   @r   r   r   3   s?    ;z 
-- - 	-^1 1r   c                  T   ^  \ rS rSrSrSSU 4S jjjr      S	S jrS
S jrSrU =r	$ )r	      a	  
Implement the L2 Weight Decay Regularization, which helps to prevent the model over-fitting.

It can be set in :ref:`api_paddle_ParamAttr` or ``optimizer`` (such as :ref:`api_paddle_optimizer_Momentum` ).
When set in ``ParamAttr`` , it only takes effect for trainable parameters in this layer. When set in
``optimizer`` , it takes effect for all trainable parameters. When set together, ``ParamAttr`` has
higher priority than ``optimizer`` , which means that for a trainable parameter, if regularizer is defined
in its ParamAttr, then the regularizer in Optimizer will be ignored. Otherwise the  regularizer
in Optimizer will be used.

In the implementation, the loss function of L2 Weight Decay Regularization is as follows:

.. math::

    loss = 0.5 * coeff * reduce\_sum(square(x))

Args:
    coeff(float, optional): regularization coeff. Default:0.0

Examples:
    .. code-block:: python
        :name: code-example1

        >>> # Example1: set Regularizer in optimizer
        >>> import paddle
        >>> from paddle.regularizer import L2Decay
        >>> linear = paddle.nn.Linear(10, 10)
        >>> inp = paddle.rand(shape=[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")
        >>> momentum = paddle.optimizer.Momentum(
        ...     learning_rate=0.1,
        ...     parameters=linear.parameters(),
        ...     weight_decay=L2Decay(0.0001))
        >>> back = out.backward()
        >>> momentum.step()
        >>> momentum.clear_grad()

    .. code-block:: python
        :name: code-example2

        >>> # Example2: set Regularizer in parameters
        >>> # Set L2 regularization in parameters.
        >>> # Global regularizer does not take effect on my_conv2d for this case.
        >>> from paddle.nn import Conv2D
        >>> from paddle import ParamAttr
        >>> from paddle.regularizer import L2Decay

        >>> my_conv2d = Conv2D(
        ...         in_channels=10,
        ...         out_channels=10,
        ...         kernel_size=1,
        ...         stride=1,
        ...         padding=0,
        ...         weight_attr=ParamAttr(regularizer=L2Decay(coeff=0.01)),
        ...         bias_attr=False)
c                8   > Uc   e[         TU ]  5         Xl        g r   r.   r1   s     r   r   L2Decay.__init__   r5   r   c                    [        U[        R                  [        R                  [        R
                  R                  45      (       d   e[        U[        R                  [        R                  45      (       d   e[        5       (       a"  [        R                  " XR                  SS5      $ UR                  UR                  UR                  UR                  S9nUR!                  SSU0SU0SU R                  0S9  U$ )a  Add L2 weight decay ops to network

Adds L2 weight decay ops.
L2WeightDecay = reg_coeff * parameter

Args:
    param: parameter variable for which regularization is applied
    block: block in which variable is to be created

Returns:
    new variable for weight decay
r7   Tr8   rB   r=   r>   rC   )rE   r   rF   r   rG   rH   rI   rJ   r   r   rB   r0   rK   r9   r:   r;   rL   )r   r   r   r   rM   s        r   r   L2Decay.__call__   s    $ I&&		3883I3IJ
 
 	
 
 %)//399!=>>>>!##<<{{C>>$$kk % E
 OOU|,	   Lr   c                "    SU R                   S 3$ )NzL2Decay, coeff=rP   rQ   r   s    r   r   L2Decay.__str__  rS   r   rQ   rT   rU   r#   rW   rY   r[   s   @r   r	   r	      s?    :x 
&& & 	&P1 1r   )
__future__r   paddler   r   paddle.baser   paddle.base.frameworkr   __all__r   r   r	   r   r   r   <module>ri      sI     #   ! 8i
 " "2s1$ s1lk1$ k1r   